From 9c85e2684984f7b36150e70acab473c48957a004 Mon Sep 17 00:00:00 2001 From: Aaron Date: Mon, 30 Oct 2023 18:03:25 +0100 Subject: [PATCH 1/2] move to prettier 3 remove some custom rules replace pretty-quick (EOL) with lint-staged --- .husky/pre-commit | 2 +- .lintstagedrc.json | 4 + .prettierrc.js | 2 - apps/combiner/src/common/combine.ts | 18 +- .../crypto-clients/bls-crypto-client.ts | 10 +- .../common/crypto-clients/crypto-client.ts | 4 +- apps/combiner/src/common/error.ts | 8 +- apps/combiner/src/common/handlers.ts | 28 +- apps/combiner/src/common/io.ts | 8 +- apps/combiner/src/common/web3/contracts.ts | 4 +- apps/combiner/src/config.ts | 2 +- .../src/domain/endpoints/disable/action.ts | 8 +- .../src/domain/endpoints/quota/action.ts | 4 +- .../src/domain/endpoints/sign/action.ts | 8 +- .../src/domain/services/log-responses.ts | 2 +- .../src/domain/services/threshold-state.ts | 6 +- .../src/pnp/endpoints/quota/action.ts | 4 +- .../combiner/src/pnp/endpoints/sign/action.ts | 10 +- .../src/pnp/services/account-services.ts | 5 +- .../src/pnp/services/log-responses.ts | 6 +- .../src/pnp/services/threshold-state.ts | 8 +- apps/combiner/src/server.ts | 25 +- apps/combiner/src/tracing.ts | 2 +- apps/combiner/test/end-to-end/domain.test.ts | 32 +- apps/combiner/test/end-to-end/pnp.test.ts | 86 ++--- apps/combiner/test/integration/domain.test.ts | 58 ++-- apps/combiner/test/integration/pnp.test.ts | 68 ++-- apps/combiner/test/unit/bls-signature.test.ts | 8 +- .../test/unit/domain-response-logger.test.ts | 4 +- .../test/unit/domain-threshold-state.test.ts | 2 +- .../test/unit/pnp-response-logger.test.ts | 2 +- .../test/unit/pnp-threshold-state.test.ts | 6 +- apps/monitor/src/query.ts | 8 +- apps/monitor/src/scripts/run-load-test.ts | 4 +- apps/monitor/src/test.ts | 18 +- .../src/common/bls/bls-cryptography-client.ts | 2 +- .../common/database/models/domain-request.ts | 2 +- .../common/database/models/domain-state.ts | 4 +- .../src/common/database/models/request.ts | 2 +- apps/signer/src/common/database/utils.ts | 4 +- .../src/common/database/wrappers/account.ts | 10 +- .../database/wrappers/domain-request.ts | 12 +- .../common/database/wrappers/domain-state.ts | 16 +- .../src/common/database/wrappers/request.ts | 10 +- apps/signer/src/common/error.ts | 8 +- apps/signer/src/common/handler.ts | 26 +- .../key-management/google-key-provider.ts | 2 +- .../src/common/key-management/key-provider.ts | 2 +- apps/signer/src/common/web3/contracts.ts | 10 +- .../src/domain/endpoints/disable/action.ts | 4 +- .../src/domain/endpoints/quota/action.ts | 2 +- .../src/domain/endpoints/sign/action.ts | 16 +- apps/signer/src/domain/services/quota.ts | 6 +- apps/signer/src/pnp/endpoints/quota/action.ts | 4 +- apps/signer/src/pnp/endpoints/sign/action.ts | 12 +- .../src/pnp/services/account-service.ts | 14 +- .../src/pnp/services/request-service.ts | 26 +- apps/signer/src/server.ts | 28 +- apps/signer/src/tracing.ts | 2 +- .../test/end-to-end/disabled-apis.test.ts | 6 +- apps/signer/test/end-to-end/domain.test.ts | 40 +-- apps/signer/test/end-to-end/pnp.test.ts | 38 +-- apps/signer/test/integration/domain.test.ts | 54 +-- apps/signer/test/integration/pnp.test.ts | 118 +++---- .../signer/test/signing/bls-signature.test.ts | 14 +- docs/examples/blinding/webBlindingClient.ts | 4 +- docs/examples/contractKit.ts | 10 +- docs/examples/ethers.ts | 18 +- docs/examples/web3.ts | 12 +- package.json | 4 +- .../common/src/domains/sequential-delay.ts | 4 +- packages/common/src/interfaces/requests.ts | 34 +- packages/common/src/interfaces/responses.ts | 6 +- packages/common/src/poprf.ts | 8 +- packages/common/src/test/utils.ts | 12 +- packages/common/src/utils/authentication.ts | 14 +- packages/common/src/utils/key-version.ts | 10 +- packages/common/src/utils/logger.ts | 2 +- packages/common/src/utils/responses.utils.ts | 2 +- packages/common/test/poprf.test.ts | 18 +- .../common/test/utils/key-version.test.ts | 4 +- packages/encrypted-backup/src/backup.ts | 26 +- packages/encrypted-backup/src/errors.ts | 20 +- packages/encrypted-backup/src/odis.mock.ts | 8 +- packages/encrypted-backup/src/odis.ts | 36 +- packages/encrypted-backup/src/schema.ts | 12 +- packages/encrypted-backup/src/utils.ts | 6 +- .../identity/src/odis/bls-blinding-client.ts | 4 +- .../identity/src/odis/circuit-breaker.mock.ts | 6 +- .../identity/src/odis/circuit-breaker.test.ts | 2 +- packages/identity/src/odis/circuit-breaker.ts | 11 +- ...identifier-backwards-compatibility.test.ts | 14 +- packages/identity/src/odis/identifier.test.ts | 22 +- packages/identity/src/odis/identifier.ts | 18 +- .../src/odis/phone-number-identifier.test.ts | 12 +- .../src/odis/phone-number-identifier.ts | 16 +- packages/identity/src/odis/query.ts | 12 +- packages/identity/src/odis/quota.test.ts | 2 +- packages/identity/src/odis/quota.ts | 4 +- .../src/offchain-data-wrapper.test.ts | 12 +- .../identity/src/offchain-data-wrapper.ts | 20 +- .../offchain/accessors/authorized-signer.ts | 8 +- .../identity/src/offchain/accessors/binary.ts | 12 +- .../identity/src/offchain/accessors/simple.ts | 6 +- .../identity/src/offchain/storage-writers.ts | 16 +- packages/identity/src/offchain/utils.ts | 36 +- .../identity/src/test-utils/setup.global.ts | 2 +- .../odis-identifiers/src/identifier.test.ts | 2 +- packages/odis-identifiers/src/identifier.ts | 4 +- yarn.lock | 316 ++++++++++++------ 110 files changed, 991 insertions(+), 804 deletions(-) create mode 100644 .lintstagedrc.json diff --git a/.husky/pre-commit b/.husky/pre-commit index 2f9c57182..a17368849 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,6 +1,6 @@ #!/usr/bin/env bash . "$(dirname -- "$0")/_/husky.sh" -yarn pretty-quick --staged --pattern '**/*.+(ts|js)' +yarn lint-staged bash scripts/prereleasecheck.sh diff --git a/.lintstagedrc.json b/.lintstagedrc.json new file mode 100644 index 000000000..908c2f978 --- /dev/null +++ b/.lintstagedrc.json @@ -0,0 +1,4 @@ +{ + "apps/**/*.ts": "prettier --list-different", + "packages/**/*.ts": "prettier --list-different" +} \ No newline at end of file diff --git a/.prettierrc.js b/.prettierrc.js index 7f3a4d2de..abb7445ea 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,8 +1,6 @@ module.exports = { semi: false, singleQuote: true, - trailingComma: 'es5', - arrowParens: 'always', printWidth: 100, tabWidth: 2, bracketSpacing: true, diff --git a/apps/combiner/src/common/combine.ts b/apps/combiner/src/common/combine.ts index 51bc340f7..3bae4f0f6 100644 --- a/apps/combiner/src/common/combine.ts +++ b/apps/combiner/src/common/combine.ts @@ -32,7 +32,7 @@ export interface ThresholdCallToSignersOptions { export async function thresholdCallToSigners( ctx: Context, options: ThresholdCallToSignersOptions, - processResult: (res: OdisResponse) => Promise = (_) => Promise.resolve(false) + processResult: (res: OdisResponse) => Promise = (_) => Promise.resolve(false), ): Promise<{ signerResponses: Array>; maxErrorCode?: number }> { const { signers, @@ -72,8 +72,8 @@ export async function thresholdCallToSigners( request, logger, // @ts-ignore - abortSignal - ) + abortSignal, + ), ) Counters.sigResponses @@ -100,7 +100,7 @@ export async function thresholdCallToSigners( errorCount++ errorCodes.set( signerFetchResult.status, - (errorCodes.get(signerFetchResult.status) ?? 0) + 1 + (errorCodes.get(signerFetchResult.status) ?? 0) + 1, ) if (signers.length - errorCount < requiredThreshold) { @@ -121,14 +121,14 @@ export async function thresholdCallToSigners( const data: any = await signerFetchResult.json() logger.info( { signer, res: data, status: signerFetchResult.status }, - `received 'OK' response from signer` + `received 'OK' response from signer`, ) const odisResponse: OdisResponse = parseSchema(responseSchema, data, logger) if (!odisResponse.success) { logger.error( { err: odisResponse.error, signer: signer.url }, - `Signer request to failed with 'OK' status` + `Signer request to failed with 'OK' status`, ) throw new Error(ErrorMessage.SIGNER_RESPONSE_FAILED_WITH_OK_STATUS) } @@ -161,7 +161,7 @@ export async function thresholdCallToSigners( } } } - }) + }), ) if (errorCodes.size > 0) { @@ -169,7 +169,7 @@ export async function thresholdCallToSigners( Counters.sigInconsistenciesErrors.labels(request.url).inc() logger.error( { errorCodes: JSON.stringify([...errorCodes]) }, - ErrorMessage.INCONSISTENT_SIGNER_RESPONSES + ErrorMessage.INCONSISTENT_SIGNER_RESPONSES, ) } @@ -227,7 +227,7 @@ function abortSignalAny(signals: AbortSignal[]): AbortSignal { (e) => { ac.abort(e) }, - { once: true } + { once: true }, ) } return ac.signal diff --git a/apps/combiner/src/common/crypto-clients/bls-crypto-client.ts b/apps/combiner/src/common/crypto-clients/bls-crypto-client.ts index f340ded98..96cf04dc7 100644 --- a/apps/combiner/src/common/crypto-clients/bls-crypto-client.ts +++ b/apps/combiner/src/common/crypto-clients/bls-crypto-client.ts @@ -50,7 +50,7 @@ export class BLSCryptographyClient extends CryptoClient { private verifyCombinedSignature( blindedMessage: string, combinedSignature: Uint8Array, - logger: Logger + logger: Logger, ) { try { // TODO: Address bad documentation in threshold-bls lib. @@ -59,7 +59,7 @@ export class BLSCryptographyClient extends CryptoClient { threshold_bls.verifyBlindSignature( Buffer.from(this.keyVersionInfo.pubKey, 'base64'), Buffer.from(blindedMessage, 'base64'), - combinedSignature + combinedSignature, ) } catch (error) { logger.error('Combined signature verification failed') @@ -70,7 +70,7 @@ export class BLSCryptographyClient extends CryptoClient { private verifyPartialSignature( blindedMessage: string, unverifiedSignature: ServicePartialSignature, - ctx: Context + ctx: Context, ) { const sigBuffer = Buffer.from(unverifiedSignature.signature, 'base64') if (this.isValidPartialSignature(sigBuffer, blindedMessage)) { @@ -81,7 +81,7 @@ export class BLSCryptographyClient extends CryptoClient { Counters.blsComputeErrors.labels(ctx.url, unverifiedSignature.url).inc() ctx.logger.error( { url: unverifiedSignature.url }, - ErrorMessage.VERIFY_PARTIAL_SIGNATURE_ERROR + ErrorMessage.VERIFY_PARTIAL_SIGNATURE_ERROR, ) } } @@ -95,7 +95,7 @@ export class BLSCryptographyClient extends CryptoClient { threshold_bls.partialVerifyBlindSignature( Buffer.from(this.keyVersionInfo.polynomial, 'hex'), Buffer.from(blindedMessage, 'base64'), - signature + signature, ) return true } catch { diff --git a/apps/combiner/src/common/crypto-clients/crypto-client.ts b/apps/combiner/src/common/crypto-clients/crypto-client.ts index a34705939..00d2a8464 100644 --- a/apps/combiner/src/common/crypto-clients/crypto-client.ts +++ b/apps/combiner/src/common/crypto-clients/crypto-client.ts @@ -38,10 +38,10 @@ export abstract class CryptoClient { const { threshold } = this.keyVersionInfo ctx.logger.error( { signatures: this.allSignaturesLength, required: threshold }, - ErrorMessage.NOT_ENOUGH_PARTIAL_SIGNATURES + ErrorMessage.NOT_ENOUGH_PARTIAL_SIGNATURES, ) throw new Error( - `${ErrorMessage.NOT_ENOUGH_PARTIAL_SIGNATURES} ${this.allSignaturesLength}/${threshold}` + `${ErrorMessage.NOT_ENOUGH_PARTIAL_SIGNATURES} ${this.allSignaturesLength}/${threshold}`, ) } diff --git a/apps/combiner/src/common/error.ts b/apps/combiner/src/common/error.ts index 91060f236..712331f56 100644 --- a/apps/combiner/src/common/error.ts +++ b/apps/combiner/src/common/error.ts @@ -1,7 +1,11 @@ import { ErrorType } from '@celo/phone-number-privacy-common' export class OdisError extends Error { - constructor(readonly code: ErrorType, readonly parent?: Error, readonly status: number = 500) { + constructor( + readonly code: ErrorType, + readonly parent?: Error, + readonly status: number = 500, + ) { // This is necessary when extending Error Classes super(code) // 'Error' breaks prototype chain here Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain @@ -11,7 +15,7 @@ export class OdisError extends Error { export function wrapError( valueOrError: Promise, code: ErrorType, - status: number = 500 + status: number = 500, ): Promise { return valueOrError.catch((parentErr) => { throw new OdisError(code, parentErr, status) diff --git a/apps/combiner/src/common/handlers.ts b/apps/combiner/src/common/handlers.ts index 9b24323dc..aff14def8 100644 --- a/apps/combiner/src/common/handlers.ts +++ b/apps/combiner/src/common/handlers.ts @@ -25,11 +25,11 @@ export interface Locals { export type PromiseHandler = ( request: Request<{}, {}, R>, - res: Response, Locals> + res: Response, Locals>, ) => Promise export function catchErrorHandler( - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { try { @@ -56,7 +56,7 @@ export function catchErrorHandler( } export function tracingHandler( - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { return tracer.startActiveSpan( @@ -83,19 +83,19 @@ export function tracingHandler( } finally { span.end() } - } + }, ) } } export function meteringHandler( histogram: client.Histogram, - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => newMeter( histogram, - req.url + req.url, )(async () => { const logger: Logger = res.locals.logger logger.info({ req: req.body }, 'Request received') @@ -116,7 +116,7 @@ export function meteringHandler( export function timeoutHandler( timeoutMs: number, - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { const timeoutSignal = (AbortSignal as any).timeout(timeoutMs) @@ -127,7 +127,7 @@ export function timeoutHandler( sendFailure(ErrorMessage.TIMEOUT_FROM_SIGNER, 500, res, req.url) } }, - { once: true } + { once: true }, ) await handler(req, res) @@ -136,7 +136,7 @@ export function timeoutHandler( export async function disabledHandler( req: Request<{}, {}, R>, - response: Response, Locals> + response: Response, Locals>, ): Promise { Counters.warnings.labels(req.url, WarningMessage.API_UNAVAILABLE).inc() sendFailure(WarningMessage.API_UNAVAILABLE, 503, response, req.url) @@ -147,7 +147,7 @@ export function sendFailure( status: number, response: Response, _endpoint: string, - body?: Record // TODO remove any + body?: Record, // TODO remove any ) { send( response, @@ -158,7 +158,7 @@ export function sendFailure( ...body, }, status, - response.locals.logger + response.locals.logger, ) } @@ -169,11 +169,11 @@ export interface Result { export type ResultHandler = ( request: Request<{}, {}, R>, - res: Response, Locals> + res: Response, Locals>, ) => Promise> export function resultHandler( - resHandler: ResultHandler + resHandler: ResultHandler, ): PromiseHandler { return async (req, res) => { const result = await resHandler(req, res) @@ -184,7 +184,7 @@ export function resultHandler( export function errorResult( status: number, error: string, - quotaStatus?: PnpQuotaStatus | { status: SequentialDelayDomainState } + quotaStatus?: PnpQuotaStatus | { status: SequentialDelayDomainState }, ): Result { // TODO remove any return { diff --git a/apps/combiner/src/common/io.ts b/apps/combiner/src/common/io.ts index f3598d0d0..df9463f41 100644 --- a/apps/combiner/src/common/io.ts +++ b/apps/combiner/src/common/io.ts @@ -26,7 +26,7 @@ export type SignerResponse = { export function requestHasSupportedKeyVersion( request: Request<{}, {}, OdisRequest>, config: OdisConfig, - logger: Logger + logger: Logger, ): boolean { try { getKeyVersionInfo(request, config, logger) @@ -41,7 +41,7 @@ export function requestHasSupportedKeyVersion( export function getKeyVersionInfo( request: Request<{}, {}, OdisRequest>, config: OdisConfig, - logger: Logger + logger: Logger, ): KeyVersionInfo { // If an invalid key version is present, we don't want this function to throw but // to instead replace the key version with the default @@ -53,7 +53,7 @@ export function getKeyVersionInfo( const keyVersion = requestKeyVersion ?? config.keys.currentVersion const supportedVersions: KeyVersionInfo[] = JSON.parse(config.keys.versions) // TODO add io-ts checks for this and signer array const filteredSupportedVersions: KeyVersionInfo[] = supportedVersions.filter( - (v) => v.keyVersion === keyVersion + (v) => v.keyVersion === keyVersion, ) if (!filteredSupportedVersions.length) { throw new Error(`key version ${keyVersion} not supported`) @@ -67,7 +67,7 @@ export async function fetchSignerResponseWithFallback( keyVersion: number, request: Request<{}, {}, R>, logger: Logger, - abortSignal: AbortSignal + abortSignal: AbortSignal, ): Promise { async function fetchSignerResponse(url: string): Promise { // prettier-ignore diff --git a/apps/combiner/src/common/web3/contracts.ts b/apps/combiner/src/common/web3/contracts.ts index aaacf8792..d8fbacd1b 100644 --- a/apps/combiner/src/common/web3/contracts.ts +++ b/apps/combiner/src/common/web3/contracts.ts @@ -13,12 +13,12 @@ export async function getDEK(kit: ContractKit, logger: Logger, account: string): logger, config.phoneNumberPrivacy.fullNodeTimeoutMs, config.phoneNumberPrivacy.fullNodeRetryCount, - config.phoneNumberPrivacy.fullNodeRetryDelayMs + config.phoneNumberPrivacy.fullNodeRetryDelayMs, ).catch((err) => { logger.error({ err, account }, 'failed to get on-chain DEK for account') Counters.errors.labels('NA', ErrorMessage.FULL_NODE_ERROR).inc() Counters.blockchainErrors.labels('NA', ErrorMessage.FAILURE_TO_GET_DEK).inc() throw err - }) + }), ) } diff --git a/apps/combiner/src/config.ts b/apps/combiner/src/config.ts index b3d794521..315418f8f 100644 --- a/apps/combiner/src/config.ts +++ b/apps/combiner/src/config.ts @@ -56,7 +56,7 @@ export let config: CombinerConfig const defaultServiceName = 'odis-combiner' const defaultMockDEK = ensureLeading0x( - 'bf8a2b73baf8402f8fe906ad3f42b560bf14b39f7df7797ece9e293d6f162188' + 'bf8a2b73baf8402f8fe906ad3f42b560bf14b39f7df7797ece9e293d6f162188', ) if (DEV_MODE) { diff --git a/apps/combiner/src/domain/endpoints/disable/action.ts b/apps/combiner/src/domain/endpoints/disable/action.ts index 63c507775..af3151600 100644 --- a/apps/combiner/src/domain/endpoints/disable/action.ts +++ b/apps/combiner/src/domain/endpoints/disable/action.ts @@ -20,7 +20,7 @@ import { findThresholdDomainState } from '../../services/threshold-state' export function disableDomain( signers: Signer[], - config: OdisConfig + config: OdisConfig, ): ResultHandler { return async (request, response) => { if (!disableDomainRequestSchema(DomainSchema).is(request.body)) { @@ -46,7 +46,7 @@ export function disableDomain( requestTimeoutMS: config.odisServices.timeoutMilliSeconds, responseSchema: disableDomainResponseSchema(SequentialDelayDomainStateSchema), shouldCheckKeyVersion: false, - } + }, ) logDomainResponseDiscrepancies(response.locals.logger, signerResponses) @@ -54,7 +54,7 @@ export function disableDomain( const disableDomainStatus = findThresholdDomainState( keyVersionInfo, signerResponses, - signers.length + signers.length, ) if (disableDomainStatus.disabled) { return { @@ -69,7 +69,7 @@ export function disableDomain( } catch (err) { response.locals.logger.error( { err }, - 'Error combining signer disable domain status responses' + 'Error combining signer disable domain status responses', ) } diff --git a/apps/combiner/src/domain/endpoints/quota/action.ts b/apps/combiner/src/domain/endpoints/quota/action.ts index a569c9f7c..e3dcaa1e7 100644 --- a/apps/combiner/src/domain/endpoints/quota/action.ts +++ b/apps/combiner/src/domain/endpoints/quota/action.ts @@ -20,7 +20,7 @@ import { findThresholdDomainState } from '../../services/threshold-state' export function domainQuota( signers: Signer[], - config: OdisConfig + config: OdisConfig, ): ResultHandler { return async (request, response) => { if (!domainQuotaStatusRequestSchema(DomainSchema).is(request.body)) { @@ -46,7 +46,7 @@ export function domainQuota( requestTimeoutMS: config.odisServices.timeoutMilliSeconds, responseSchema: domainQuotaStatusResponseSchema(SequentialDelayDomainStateSchema), shouldCheckKeyVersion: false, - } + }, ) logDomainResponseDiscrepancies(response.locals.logger, signerResponses) diff --git a/apps/combiner/src/domain/endpoints/sign/action.ts b/apps/combiner/src/domain/endpoints/sign/action.ts index 776416d9c..a33438eb7 100644 --- a/apps/combiner/src/domain/endpoints/sign/action.ts +++ b/apps/combiner/src/domain/endpoints/sign/action.ts @@ -25,7 +25,7 @@ import { findThresholdDomainState } from '../../services/threshold-state' export function domainSign( signers: Signer[], - config: OdisConfig + config: OdisConfig, ): ResultHandler { return async (request, response) => { const { logger } = response.locals @@ -53,7 +53,7 @@ export function domainSign( const crypto = new DomainCryptoClient(keyVersionInfo) const processResult = async ( - res: OdisResponse + res: OdisResponse, ): Promise => { assert(res.success) // TODO remove the need to pass url here @@ -87,7 +87,7 @@ export function domainSign( responseSchema: domainRestrictedSignatureResponseSchema(SequentialDelayDomainStateSchema), shouldCheckKeyVersion: true, }, - processResult + processResult, ) logDomainResponseDiscrepancies(response.locals.logger, signerResponses) @@ -96,7 +96,7 @@ export function domainSign( try { const combinedSignature = crypto.combineBlindedSignatureShares( request.body.blindedMessage, - ctx + ctx, ) return { diff --git a/apps/combiner/src/domain/services/log-responses.ts b/apps/combiner/src/domain/services/log-responses.ts index 1c3f9e21d..f4a089079 100644 --- a/apps/combiner/src/domain/services/log-responses.ts +++ b/apps/combiner/src/domain/services/log-responses.ts @@ -6,7 +6,7 @@ import { Counters } from '../../common/metrics' export function logDomainResponseDiscrepancies( logger: Logger, - responses: Array> + responses: Array>, ) { const parsedResponses: Array<{ signerUrl: string diff --git a/apps/combiner/src/domain/services/threshold-state.ts b/apps/combiner/src/domain/services/threshold-state.ts index 31b8a3032..11d63fab9 100644 --- a/apps/combiner/src/domain/services/threshold-state.ts +++ b/apps/combiner/src/domain/services/threshold-state.ts @@ -4,7 +4,7 @@ import { SignerResponse } from '../../common/io' export function findThresholdDomainState( keyVersionInfo: KeyVersionInfo, rawSignerResponses: Array>, - totalSigners: number + totalSigners: number, ): DomainState { const { threshold } = keyVersionInfo // Get the domain status from the responses, filtering out responses that don't have the status. @@ -45,11 +45,11 @@ export function findThresholdDomainState( // Client should submit requests with nonce === thresholdCounter const domainStatesWithThresholdCounter = domainStatesEnabled.filter( - (ds) => ds.counter <= thresholdCounter + (ds) => ds.counter <= thresholdCounter, ) const domainStatesAscendingByTimestampRestrictiveness = domainStatesWithThresholdCounter.sort( - (a, b) => a.timer - a.now - (b.timer - b.now) + (a, b) => a.timer - a.now - (b.timer - b.now), /** * Please see '@celo/phone-number-privacy-common/src/domains/sequential-delay.ts' * and https://github.com/celo-org/celo-proposals/blob/master/CIPs/CIP-0040/sequentialDelayDomain.md diff --git a/apps/combiner/src/pnp/endpoints/quota/action.ts b/apps/combiner/src/pnp/endpoints/quota/action.ts index 972e1e747..5967395ae 100644 --- a/apps/combiner/src/pnp/endpoints/quota/action.ts +++ b/apps/combiner/src/pnp/endpoints/quota/action.ts @@ -27,7 +27,7 @@ export function pnpQuota( signers: Signer[], config: OdisConfig, accountService: AccountService, - noQuotaCache: NoQuotaCache + noQuotaCache: NoQuotaCache, ): ResultHandler { return async (request, response) => { const logger = response.locals.logger @@ -111,7 +111,7 @@ export function pnpQuota( } function isValidRequest( - request: Request<{}, {}, unknown> + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, PnpQuotaRequest> { return ( PnpQuotaRequestSchema.is(request.body) && diff --git a/apps/combiner/src/pnp/endpoints/sign/action.ts b/apps/combiner/src/pnp/endpoints/sign/action.ts index 59b180bfa..4b1971eb0 100644 --- a/apps/combiner/src/pnp/endpoints/sign/action.ts +++ b/apps/combiner/src/pnp/endpoints/sign/action.ts @@ -31,7 +31,7 @@ export function pnpSign( signers: Signer[], config: OdisConfig, accountService: AccountService, - noQuotaCache: NoQuotaCache + noQuotaCache: NoQuotaCache, ): ResultHandler { return async (request, response) => { const logger = response.locals.logger @@ -103,7 +103,7 @@ export function pnpSign( responseSchema: SignMessageResponseSchema, shouldCheckKeyVersion: true, }, - processResult + processResult, ) warnings.push(...logPnpSignerResponseDiscrepancies(logger, signerResponses)) @@ -112,7 +112,7 @@ export function pnpSign( try { const combinedSignature = crypto.combineBlindedSignatureShares( request.body.blindedQueryPhoneNumber, - ctx + ctx, ) return { @@ -136,7 +136,7 @@ export function pnpSign( // If the error is 403 it means that we don't have quota for the signer if (errorCode === 403) { const exceededResponse = signerResponses.find( - (e) => !e.res.success && e.res.error === WarningMessage.EXCEEDED_QUOTA + (e) => !e.res.success && e.res.error === WarningMessage.EXCEEDED_QUOTA, ) if (exceededResponse && exceededResponse.res.totalQuota !== undefined) { noQuotaCache.setNoMoreQuota(account, exceededResponse.res.totalQuota) @@ -154,7 +154,7 @@ export function pnpSign( } function isValidRequest( - request: Request<{}, {}, unknown> + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, SignMessageRequest> { return ( SignMessageRequestSchema.is(request.body) && diff --git a/apps/combiner/src/pnp/services/account-services.ts b/apps/combiner/src/pnp/services/account-services.ts index 6a4b8f518..b3015d1f5 100644 --- a/apps/combiner/src/pnp/services/account-services.ts +++ b/apps/combiner/src/pnp/services/account-services.ts @@ -45,7 +45,10 @@ export class CachingAccountService implements AccountService { // tslint:disable-next-line:max-classes-per-file export class ContractKitAccountService implements AccountService { - constructor(private readonly logger: Logger, private readonly kit: ContractKit) {} + constructor( + private readonly logger: Logger, + private readonly kit: ContractKit, + ) {} async getAccount(address: string): Promise { return traceAsyncFunction('ContractKitAccountService - getAccount', async () => { diff --git a/apps/combiner/src/pnp/services/log-responses.ts b/apps/combiner/src/pnp/services/log-responses.ts index ca0163b7e..02076aa12 100644 --- a/apps/combiner/src/pnp/services/log-responses.ts +++ b/apps/combiner/src/pnp/services/log-responses.ts @@ -15,7 +15,7 @@ import { export function logPnpSignerResponseDiscrepancies( logger: Logger, - responses: Array> + responses: Array>, ): ErrorType[] { const warnings: ErrorType[] = [] @@ -58,7 +58,7 @@ export function logPnpSignerResponseDiscrepancies( // totalQuota const sortedByTotalQuota = parsedResponses.sort( - (a, b) => a.values.totalQuota - b.values.totalQuota + (a, b) => a.values.totalQuota - b.values.totalQuota, ) if ( sortedByTotalQuota[sortedByTotalQuota.length - 1].values.totalQuota - @@ -74,7 +74,7 @@ export function logPnpSignerResponseDiscrepancies( // performedQueryCount const sortedByQueryCount = parsedResponses.sort( - (a, b) => a.values.performedQueryCount - b.values.performedQueryCount + (a, b) => a.values.performedQueryCount - b.values.performedQueryCount, ) if ( sortedByQueryCount[sortedByQueryCount.length - 1].values.performedQueryCount - diff --git a/apps/combiner/src/pnp/services/threshold-state.ts b/apps/combiner/src/pnp/services/threshold-state.ts index dd6e5236a..ad47f71cd 100644 --- a/apps/combiner/src/pnp/services/threshold-state.ts +++ b/apps/combiner/src/pnp/services/threshold-state.ts @@ -12,21 +12,21 @@ import { MAX_TOTAL_QUOTA_DISCREPANCY_THRESHOLD } from '../../config' export function findCombinerQuotaState( keyVersionInfo: KeyVersionInfo, rawSignerResponses: Array>, - warnings: string[] + warnings: string[], ): PnpQuotaStatus { const { threshold } = keyVersionInfo const signerResponses = rawSignerResponses .map((signerResponse) => signerResponse.res) .filter((res) => res.success) as PnpQuotaStatus[] const sortedResponses = signerResponses.sort( - (a, b) => b.totalQuota - b.performedQueryCount - (a.totalQuota - a.performedQueryCount) + (a, b) => b.totalQuota - b.performedQueryCount - (a.totalQuota - a.performedQueryCount), ) const totalQuotaAvg = sortedResponses.map((r) => r.totalQuota).reduce((a, b) => a + b) / sortedResponses.length const totalQuotaStDev = Math.sqrt( sortedResponses.map((r) => (r.totalQuota - totalQuotaAvg) ** 2).reduce((a, b) => a + b) / - sortedResponses.length + sortedResponses.length, ) if (totalQuotaStDev > MAX_TOTAL_QUOTA_DISCREPANCY_THRESHOLD) { // TODO(2.0.0): add alerting for this @@ -37,7 +37,7 @@ export function findCombinerQuotaState( .inc() warnings.push( WarningMessage.INCONSISTENT_SIGNER_QUOTA_MEASUREMENTS + - ', using threshold signer as best guess' + ', using threshold signer as best guess', ) } diff --git a/apps/combiner/src/server.ts b/apps/combiner/src/server.ts index 6c276a35f..b902cc9ad 100644 --- a/apps/combiner/src/server.ts +++ b/apps/combiner/src/server.ts @@ -58,7 +58,7 @@ export function startCombiner(config: CombinerConfig, kit?: ContractKit) { res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') res.header( 'Access-Control-Allow-Headers', - `Origin, X-Requested-With, Content-Type, Accept, Authorization, ${KEY_VERSION_HEADER}` + `Origin, X-Requested-With, Content-Type, Accept, Authorization, ${KEY_VERSION_HEADER}`, ) next() }) @@ -85,27 +85,27 @@ export function startCombiner(config: CombinerConfig, kit?: ContractKit) { CombinerEndpoint.PNP_QUOTA, createHandler( phoneNumberPrivacy.enabled, - pnpQuota(pnpSigners, config.phoneNumberPrivacy, accountService, noQuotaCache) - ) + pnpQuota(pnpSigners, config.phoneNumberPrivacy, accountService, noQuotaCache), + ), ) app.post( CombinerEndpoint.PNP_SIGN, createHandler( phoneNumberPrivacy.enabled, - pnpSign(pnpSigners, config.phoneNumberPrivacy, accountService, noQuotaCache) - ) + pnpSign(pnpSigners, config.phoneNumberPrivacy, accountService, noQuotaCache), + ), ) app.post( CombinerEndpoint.DOMAIN_QUOTA_STATUS, - createHandler(domains.enabled, domainQuota(domainSigners, config.domains)) + createHandler(domains.enabled, domainQuota(domainSigners, config.domains)), ) app.post( CombinerEndpoint.DOMAIN_SIGN, - createHandler(domains.enabled, domainSign(domainSigners, domains)) + createHandler(domains.enabled, domainSign(domainSigners, domains)), ) app.post( CombinerEndpoint.DISABLE_DOMAIN, - createHandler(domains.enabled, disableDomain(domainSigners, domains)) + createHandler(domains.enabled, disableDomain(domainSigners, domains)), ) app.get(CombinerEndpoint.METRICS, (_req, res) => { res.send(register.metrics()) @@ -140,11 +140,14 @@ function getSslOptions(config: CombinerConfig) { function createHandler( enabled: boolean, - action: ResultHandler + action: ResultHandler, ): RequestHandler<{}, {}, R, {}, Locals> { return catchErrorHandler( tracingHandler( - meteringHandler(Histograms.responseLatency, enabled ? resultHandler(action) : disabledHandler) - ) + meteringHandler( + Histograms.responseLatency, + enabled ? resultHandler(action) : disabledHandler, + ), + ), ) } diff --git a/apps/combiner/src/tracing.ts b/apps/combiner/src/tracing.ts index 3d3f699da..9dc9e743a 100644 --- a/apps/combiner/src/tracing.ts +++ b/apps/combiner/src/tracing.ts @@ -36,7 +36,7 @@ const resource = Resource.default().merge( new Resource({ [SemanticResourceAttributes.SERVICE_NAME]: process.env.TRACING_SERVICE_NAME, [SemanticResourceAttributes.SERVICE_VERSION]: '0.1.0', - }) + }), ) const provider = new NodeTracerProvider({ diff --git a/apps/combiner/test/end-to-end/domain.test.ts b/apps/combiner/test/end-to-end/domain.test.ts index 57ad88bb4..1275126c0 100644 --- a/apps/combiner/test/end-to-end/domain.test.ts +++ b/apps/combiner/test/end-to-end/domain.test.ts @@ -66,7 +66,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi domain, SERVICE_CONTEXT, genSessionID(), - authorizer.wallet + authorizer.wallet, ) expect(res.ok).toBe(true) @@ -100,7 +100,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi Buffer.from('password'), domain, SERVICE_CONTEXT, - authorizer.wallet + authorizer.wallet, ) // odisHardenKey verifies the signature against the service public key expect(res.ok).toBe(true) @@ -118,12 +118,12 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const signatureRequest = async ( keyVersion: number, nonce: number, - _domain: SequentialDelayDomain = domain + _domain: SequentialDelayDomain = domain, ): Promise<[DomainRestrictedSignatureRequest, PoprfClient]> => { const poprfClient = new PoprfClient( Buffer.from(TestUtils.Values.DOMAINS_THRESHOLD_DEV_PUBKEYS[keyVersion - 1], 'base64'), domainHash(_domain), - Buffer.from('test message', 'utf8') + Buffer.from('test message', 'utf8'), ) const req: DomainRestrictedSignatureRequest = { @@ -139,8 +139,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi req.options.signature = defined( await authorizer.wallet.signTypedData( authorizer.address, - domainRestrictedSignatureRequestEIP712(req) - ) + domainRestrictedSignatureRequestEIP712(req), + ), ) return [req, poprfClient] } @@ -151,7 +151,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi domain, SERVICE_CONTEXT, genSessionID(), - authorizer.wallet + authorizer.wallet, ) let nonce = 0 @@ -180,7 +180,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi domainRestrictedSignatureResponseSchema(SequentialDelayDomainStateSchema), { [KEY_VERSION_HEADER]: keyVersion.toString(), - } + }, ) expect(res.success).toBe(true) @@ -205,7 +205,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi domain, SERVICE_CONTEXT, genSessionID(), - authorizer.wallet + authorizer.wallet, ) let nonce = 0 @@ -238,8 +238,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi domainRestrictedSignatureResponseSchema(SequentialDelayDomainStateSchema), { [KEY_VERSION_HEADER]: keyVersion.toString(), - } - ) + }, + ), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) @@ -249,7 +249,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi Buffer.from('password'), noQuotaDomain, SERVICE_CONTEXT, - authorizer.wallet + authorizer.wallet, ) expect(res.ok).toBe(false) if (!res.ok) { @@ -262,7 +262,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const domainForDisabling = buildOdisDomain( E2E_TESTING_ALFAJORES_CONFIG.odis!, authorizer.address, - 'e2e testing, okay to disable ' + crypto.randomBytes(16).toString('base64') + 'e2e testing, okay to disable ' + crypto.randomBytes(16).toString('base64'), ) const disableRequest = async (): Promise> => { const req: DisableDomainRequest = { @@ -275,7 +275,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi sessionID: defined(genSessionID()), } req.options.signature = defined( - await authorizer.wallet.signTypedData(authorizer.address, disableDomainRequestEIP712(req)) + await authorizer.wallet.signTypedData(authorizer.address, disableDomainRequestEIP712(req)), ) return req } @@ -285,7 +285,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi domainForDisabling, SERVICE_CONTEXT, genSessionID(), - authorizer.wallet + authorizer.wallet, ) expect(quotaRes.ok).toBe(true) if (quotaRes.ok) { @@ -307,7 +307,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi await disableRequest(), SERVICE_CONTEXT, CombinerEndpoint.DISABLE_DOMAIN, - disableDomainResponseSchema(SequentialDelayDomainStateSchema) + disableDomainResponseSchema(SequentialDelayDomainStateSchema), ) expect(res.success).toBe(true) diff --git a/apps/combiner/test/end-to-end/pnp.test.ts b/apps/combiner/test/end-to-end/pnp.test.ts index bf52a5499..a0ce34fb6 100644 --- a/apps/combiner/test/end-to-end/pnp.test.ts +++ b/apps/combiner/test/end-to-end/pnp.test.ts @@ -64,7 +64,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const res = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, walletAuthSigner, - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(res).toStrictEqual({ version: expectedVersion, @@ -79,7 +79,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const res = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(res).toStrictEqual({ version: expectedVersion, @@ -94,7 +94,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const res1 = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) const expectedRes: PnpClientQuotaStatus = { version: expectedVersion, @@ -107,14 +107,14 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const res2 = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(res2).toStrictEqual(expectedRes) }) it(`Should reject to throw ${ErrorMessages.ODIS_INPUT_ERROR} with invalid address`, async () => { await expect( - OdisUtils.Quota.getPnpQuotaStatus('not an address', dekAuthSigner(0), SERVICE_CONTEXT) + OdisUtils.Quota.getPnpQuotaStatus('not an address', dekAuthSigner(0), SERVICE_CONTEXT), ).rejects.toThrow(ErrorMessages.ODIS_INPUT_ERROR) }) @@ -132,10 +132,10 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi { Authorization: await walletAuthSigner.contractKit.connection.sign( JSON.stringify(req), - ACCOUNT_ADDRESS_NO_QUOTA + ACCOUNT_ADDRESS_NO_QUOTA, ), - } - ) + }, + ), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) @@ -144,8 +144,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(1), // DEK auth signer doesn't match the registered DEK for ACCOUNT_ADDRESS - SERVICE_CONTEXT - ) + SERVICE_CONTEXT, + ), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) }) @@ -160,7 +160,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi .times(numQueriesToReplenish) .toString() const stableToken = await walletAuthSigner.contractKit.contracts.getStableToken( - StableToken.cUSD + StableToken.cUSD, ) const odisPayments = await walletAuthSigner.contractKit.contracts.getOdisPayments() await stableToken @@ -183,7 +183,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const res = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) startingPerformedQueryCount = res.performedQueryCount startingTotalQuota = res.totalQuota @@ -198,12 +198,12 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi IdentifierPrefix.PHONE_NUMBER, ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) const quotaRes = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(quotaRes).toStrictEqual({ version: expectedVersion, @@ -224,12 +224,12 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi ACCOUNT_ADDRESS, walletAuthSigner, SERVICE_CONTEXT, - Buffer.from(randomBytes(32)).toString('base64') + Buffer.from(randomBytes(32)).toString('base64'), ) const quotaRes = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, walletAuthSigner, - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(quotaRes).toStrictEqual({ version: expectedVersion, @@ -246,7 +246,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi describe('replayed requests', () => { const replayedBlindingFactor = Buffer.from('test string for blinding factor').toString( - 'base64' + 'base64', ) beforeAll(async () => { // Ensure that these are each called at least once for the first test runs @@ -256,14 +256,14 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi ACCOUNT_ADDRESS, walletAuthSigner, SERVICE_CONTEXT, - replayedBlindingFactor + replayedBlindingFactor, ) await OdisUtils.Identifier.getObfuscatedIdentifier( PHONE_NUMBER, IdentifierPrefix.PHONE_NUMBER, ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) }) @@ -275,7 +275,7 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi const res = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) startingPerformedQueryCount = res.performedQueryCount startingTotalQuota = res.totalQuota @@ -288,17 +288,17 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi ACCOUNT_ADDRESS, walletAuthSigner, SERVICE_CONTEXT, - replayedBlindingFactor + replayedBlindingFactor, ) threshold_bls.verify( Buffer.from(SERVICE_CONTEXT.odisPubKey, 'base64'), Buffer.from(PHONE_NUMBER), - Buffer.from(res.unblindedSignature!, 'base64') + Buffer.from(res.unblindedSignature!, 'base64'), ) const quotaRes = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, walletAuthSigner, - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(quotaRes.performedQueryCount).toEqual(startingPerformedQueryCount) expect(quotaRes.totalQuota).toEqual(startingTotalQuota) @@ -310,17 +310,17 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi IdentifierPrefix.PHONE_NUMBER, ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) threshold_bls.verify( Buffer.from(SERVICE_CONTEXT.odisPubKey, 'base64'), Buffer.from(PHONE_NUMBER), - Buffer.from(res.unblindedSignature!, 'base64') + Buffer.from(res.unblindedSignature!, 'base64'), ) const quotaRes = await OdisUtils.Quota.getPnpQuotaStatus( ACCOUNT_ADDRESS, dekAuthSigner(0), - SERVICE_CONTEXT + SERVICE_CONTEXT, ) expect(quotaRes.performedQueryCount).toEqual(startingPerformedQueryCount) expect(quotaRes.totalQuota).toEqual(startingTotalQuota) @@ -340,12 +340,12 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi undefined, undefined, undefined, - i + i, ) threshold_bls.verify( Buffer.from(SERVICE_CONTEXT.odisPubKey, 'base64'), Buffer.from(PHONE_NUMBER), - Buffer.from(res.unblindedSignature!, 'base64') + Buffer.from(res.unblindedSignature!, 'base64'), ) }) } @@ -361,12 +361,12 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi undefined, undefined, undefined, - 1.5 + 1.5, ) threshold_bls.verify( Buffer.from(SERVICE_CONTEXT.odisPubKey, 'base64'), Buffer.from(PHONE_NUMBER), - Buffer.from(res.unblindedSignature!, 'base64') + Buffer.from(res.unblindedSignature!, 'base64'), ) }) @@ -382,8 +382,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi undefined, undefined, undefined, - 10 - ) + 10, + ), ).rejects.toThrow(ErrorMessages.ODIS_INPUT_ERROR) }) @@ -399,8 +399,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi undefined, undefined, undefined, - 1 - ) + 1, + ), ).rejects.toThrow(ErrorMessages.ODIS_INPUT_ERROR) }) @@ -416,8 +416,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi undefined, undefined, undefined, - 1 - ) + 1, + ), ).rejects.toThrow('Invalid phone number: 12345') }) @@ -436,10 +436,10 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi { Authorization: await walletAuthSigner.contractKit.connection.sign( JSON.stringify(req), - ACCOUNT_ADDRESS_NO_QUOTA + ACCOUNT_ADDRESS_NO_QUOTA, ), - } - ) + }, + ), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) @@ -450,8 +450,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi IdentifierPrefix.PHONE_NUMBER, ACCOUNT_ADDRESS, dekAuthSigner(1), // DEK auth signer doesn't match the registered DEK for ACCOUNT_ADDRESS - SERVICE_CONTEXT - ) + SERVICE_CONTEXT, + ), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) @@ -462,8 +462,8 @@ describe(`Running against service deployed at ${combinerUrl} w/ blockchain provi IdentifierPrefix.PHONE_NUMBER, ACCOUNT_ADDRESS_NO_QUOTA, dekAuthSigner(0), - SERVICE_CONTEXT - ) + SERVICE_CONTEXT, + ), ).rejects.toThrow(ErrorMessages.ODIS_QUOTA_ERROR) }) }) diff --git a/apps/combiner/test/integration/domain.test.ts b/apps/combiner/test/integration/domain.test.ts index 54ae19bc7..472eb99d7 100644 --- a/apps/combiner/test/integration/domain.test.ts +++ b/apps/combiner/test/integration/domain.test.ts @@ -162,13 +162,13 @@ describe('domainService', () => { const signatureRequest = async ( _domain?: SequentialDelayDomain, _nonce?: number, - _pubKey: string = DEFAULT_PUB_KEY + _pubKey: string = DEFAULT_PUB_KEY, ): Promise<[DomainRestrictedSignatureRequest, PoprfClient]> => { const domain = _domain ?? authenticatedDomain() const poprfClient = new PoprfClient( Buffer.from(_pubKey, 'base64'), domainHash(domain), - Buffer.from('test message', 'utf8') + Buffer.from('test message', 'utf8'), ) const req: DomainRestrictedSignatureRequest = { @@ -182,7 +182,7 @@ describe('domainService', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)), ) return [req, poprfClient] } @@ -198,14 +198,14 @@ describe('domainService', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainQuotaStatusRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainQuotaStatusRequestEIP712(req)), ) return req } // Build and sign an example disable domain request. const disableRequest = async ( - _domain?: SequentialDelayDomain + _domain?: SequentialDelayDomain, ): Promise> => { const req: DisableDomainRequest = { type: DomainRequestTypeTag.DISABLE, @@ -217,7 +217,7 @@ describe('domainService', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, disableDomainRequestEIP712(req)) + await wallet.signTypedData(walletAddress, disableDomainRequestEIP712(req)), ) return req } @@ -249,21 +249,21 @@ describe('domainService', () => { [`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_1_V1], [`${DefaultKeyName.DOMAINS}-2`, DOMAINS_THRESHOLD_DEV_PK_SHARE_1_V2], [`${DefaultKeyName.DOMAINS}-3`, DOMAINS_THRESHOLD_DEV_PK_SHARE_1_V3], - ]) + ]), ) keyProvider2 = new MockKeyProvider( new Map([ [`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_2_V1], [`${DefaultKeyName.DOMAINS}-2`, DOMAINS_THRESHOLD_DEV_PK_SHARE_2_V2], [`${DefaultKeyName.DOMAINS}-3`, DOMAINS_THRESHOLD_DEV_PK_SHARE_2_V3], - ]) + ]), ) keyProvider3 = new MockKeyProvider( new Map([ [`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_3_V1], [`${DefaultKeyName.DOMAINS}-2`, DOMAINS_THRESHOLD_DEV_PK_SHARE_3_V2], [`${DefaultKeyName.DOMAINS}-3`, DOMAINS_THRESHOLD_DEV_PK_SHARE_3_V3], - ]) + ]), ) app = startCombiner(combinerConfig, getContractKitWithAgent(combinerConfig.blockchain)) @@ -409,12 +409,12 @@ describe('domainService', () => { it('Should respond with 503 on disabled api', async () => { const configWithApiDisabled: typeof combinerConfig = JSON.parse( - JSON.stringify(combinerConfig) + JSON.stringify(combinerConfig), ) configWithApiDisabled.domains.enabled = false const appWithApiDisabled = startCombiner( configWithApiDisabled, - getContractKitWithAgent(configWithApiDisabled.blockchain) + getContractKitWithAgent(configWithApiDisabled.blockchain), ) const req = await disableRequest() @@ -558,12 +558,12 @@ describe('domainService', () => { it('Should respond with 503 on disabled api', async () => { const configWithApiDisabled: typeof combinerConfig = JSON.parse( - JSON.stringify(combinerConfig) + JSON.stringify(combinerConfig), ) configWithApiDisabled.domains.enabled = false const appWithApiDisabled = startCombiner( configWithApiDisabled, - getContractKitWithAgent(configWithApiDisabled.blockchain) + getContractKitWithAgent(configWithApiDisabled.blockchain), ) const req = await quotaRequest() @@ -607,7 +607,7 @@ describe('domainService', () => { const [req, poprfClient] = await signatureRequest( undefined, undefined, - TestUtils.Values.DOMAINS_THRESHOLD_DEV_PUBKEYS[i - 1] + TestUtils.Values.DOMAINS_THRESHOLD_DEV_PUBKEYS[i - 1], ) const res = await request(app) @@ -628,7 +628,7 @@ describe('domainService', () => { }, }) const evaluation = poprfClient.unblindResponse( - Buffer.from(res.body.signature, 'base64') + Buffer.from(res.body.signature, 'base64'), ) expect(evaluation.toString('base64')).toEqual(expectedEvals[i - 1]) }) @@ -678,7 +678,7 @@ describe('domainService', () => { req1.options.nonce = defined(1) req1.options.signature = noString req1.options.signature = defined( - await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req1)) + await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req1)), ) const res2 = await request(app).post(CombinerEndpoint.DOMAIN_SIGN).send(req1) @@ -888,12 +888,12 @@ describe('domainService', () => { it('Should respond with 503 on disabled api', async () => { const configWithApiDisabled: typeof combinerConfig = JSON.parse( - JSON.stringify(combinerConfig) + JSON.stringify(combinerConfig), ) configWithApiDisabled.domains.enabled = false const appWithApiDisabled = startCombiner( configWithApiDisabled, - getContractKitWithAgent(configWithApiDisabled.blockchain) + getContractKitWithAgent(configWithApiDisabled.blockchain), ) const [req, _] = await signatureRequest() @@ -919,10 +919,10 @@ describe('domainService', () => { beforeEach(async () => { // Signer 1 & 2's v1 keys are misconfigured to point to the v3 share const badKeyProvider1 = new MockKeyProvider( - new Map([[`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_1_V3]]) + new Map([[`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_1_V3]]), ) const badKeyProvider2 = new MockKeyProvider( - new Map([[`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_2_V3]]) + new Map([[`${DefaultKeyName.DOMAINS}-1`, DOMAINS_THRESHOLD_DEV_PK_SHARE_2_V3]]), ) signer1 = startSigner(signerConfig, signerDB1, badKeyProvider1).listen(3001) signer2 = startSigner(signerConfig, signerDB2, badKeyProvider2).listen(3002) @@ -935,7 +935,7 @@ describe('domainService', () => { const [req, poprfClient] = await signatureRequest( undefined, undefined, - TestUtils.Values.DOMAINS_THRESHOLD_DEV_PUBKEY_V1 + TestUtils.Values.DOMAINS_THRESHOLD_DEV_PUBKEY_V1, ) const res = await request(app).post(CombinerEndpoint.DOMAIN_SIGN).send(req) @@ -952,7 +952,7 @@ describe('domainService', () => { }, }) expect(() => - poprfClient.unblindResponse(Buffer.from(res.body.signature, 'base64')) + poprfClient.unblindResponse(Buffer.from(res.body.signature, 'base64')), ).toThrow(/verification failed/) }) }) @@ -1064,7 +1064,7 @@ describe('domainService', () => { }, }) const evaluation = poprfClient.unblindResponse( - Buffer.from(res.body.signature, 'base64') + Buffer.from(res.body.signature, 'base64'), ) expect(evaluation.toString('base64')).toEqual(expectedEval) }) @@ -1180,7 +1180,7 @@ describe('domainService', () => { `${DefaultKeyName.DOMAINS}-1`, '01000000fa9f3c7a0ed050b3b4ab9df241e3e3e2069e36c96369b2bf378d7edd66e37a0e', ], - ]) + ]), ) keyProvider2 = new MockKeyProvider( new Map([ @@ -1188,7 +1188,7 @@ describe('domainService', () => { `${DefaultKeyName.DOMAINS}-1`, '02000000b03e8d5203edb8b27a9c56185df0ee94e8be45f0c91e116beac68c851cc4ba10', ], - ]) + ]), ) keyProvider3 = new MockKeyProvider( new Map([ @@ -1196,7 +1196,7 @@ describe('domainService', () => { `${DefaultKeyName.DOMAINS}-1`, '03000000bad95bc039a5418bd57e7f5bad4bf6c19ff85e523462925e226e6ac0a6770005', ], - ]) + ]), ) keyProvider4 = new MockKeyProvider( new Map([ @@ -1204,7 +1204,7 @@ describe('domainService', () => { `${DefaultKeyName.DOMAINS}-1`, '040000002ffdcc94fd5322e4f3e0d7ba00b591c38f77e584b61b59dd6e62cc6cfed5fd06', ], - ]) + ]), ) keyProvider5 = new MockKeyProvider( new Map([ @@ -1212,11 +1212,11 @@ describe('domainService', () => { `${DefaultKeyName.DOMAINS}-1`, '05000000243505a19a546f5002511f9527fe03401908cd6427991f69b2380e355fec0d0d', ], - ]) + ]), ) app = startCombiner( combinerConfigLargerN, - getContractKitWithAgent(combinerConfigLargerN.blockchain) + getContractKitWithAgent(combinerConfigLargerN.blockchain), ) }) diff --git a/apps/combiner/test/integration/pnp.test.ts b/apps/combiner/test/integration/pnp.test.ts index 282e416b7..c5aaadd94 100644 --- a/apps/combiner/test/integration/pnp.test.ts +++ b/apps/combiner/test/integration/pnp.test.ts @@ -155,7 +155,7 @@ const mockGetDataEncryptionKey = jest.fn() const mockContractKit = createMockContractKit({ [ContractRetrieval.getAccounts]: createMockAccounts( mockGetWalletAddress, - mockGetDataEncryptionKey + mockGetDataEncryptionKey, ), [ContractRetrieval.getOdisPayments]: createMockOdisPayments(mockOdisPaymentsTotalPaidCUSD), }) @@ -198,7 +198,7 @@ describe('pnpService', () => { req: SignMessageRequest, authorization: string, app: any, - keyVersionHeader?: string + keyVersionHeader?: string, ) => { let reqWithHeaders = request(app) .post(CombinerEndpoint.PNP_SIGN) @@ -237,7 +237,7 @@ describe('pnpService', () => { const getCombinerQuotaResponse = async ( req: PnpQuotaRequest, authorization: string, - _app: any = app + _app: any = app, ) => { const res = await request(_app) .post(CombinerEndpoint.PNP_QUOTA) @@ -268,21 +268,21 @@ describe('pnpService', () => { [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, PNP_THRESHOLD_DEV_PK_SHARE_1_V1], [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-2`, PNP_THRESHOLD_DEV_PK_SHARE_1_V2], [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-3`, PNP_THRESHOLD_DEV_PK_SHARE_1_V3], - ]) + ]), ) keyProvider2 = new MockKeyProvider( new Map([ [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, PNP_THRESHOLD_DEV_PK_SHARE_2_V1], [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-2`, PNP_THRESHOLD_DEV_PK_SHARE_2_V2], [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-3`, PNP_THRESHOLD_DEV_PK_SHARE_2_V3], - ]) + ]), ) keyProvider3 = new MockKeyProvider( new Map([ [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, PNP_THRESHOLD_DEV_PK_SHARE_3_V1], [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-2`, PNP_THRESHOLD_DEV_PK_SHARE_3_V2], [`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-3`, PNP_THRESHOLD_DEV_PK_SHARE_3_V3], - ]) + ]), ) app = startCombiner(combinerConfig, mockKit) }) @@ -324,7 +324,7 @@ describe('pnpService', () => { const weiTocusd = new BigNumber(1e18) beforeAll(async () => { mockOdisPaymentsTotalPaidCUSD.mockReturnValue( - weiTocusd.multipliedBy(totalQuota).multipliedBy(signerConfig.quota.queryPriceInCUSD) + weiTocusd.multipliedBy(totalQuota).multipliedBy(signerConfig.quota.queryPriceInCUSD), ) }) @@ -454,7 +454,9 @@ describe('pnpService', () => { it('Should respond with a warning when there are slight discrepancies in total quota', async () => { mockOdisPaymentsTotalPaidCUSD.mockReturnValueOnce( - weiTocusd.multipliedBy(totalQuota + 1).multipliedBy(signerConfig.quota.queryPriceInCUSD) + weiTocusd + .multipliedBy(totalQuota + 1) + .multipliedBy(signerConfig.quota.queryPriceInCUSD), ) const req = { account: ACCOUNT_ADDRESS1, @@ -575,7 +577,7 @@ describe('pnpService', () => { it('Should respond with 503 on disabled api', async () => { const configWithApiDisabled: typeof combinerConfig = JSON.parse( - JSON.stringify(combinerConfig) + JSON.stringify(combinerConfig), ) configWithApiDisabled.phoneNumberPrivacy.enabled = false const appWithApiDisabled = startCombiner(configWithApiDisabled, mockKit) @@ -620,7 +622,7 @@ describe('pnpService', () => { }) const unblindedSig = threshold_bls.unblind( Buffer.from(res.body.signature, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) expect(Buffer.from(unblindedSig).toString('base64')).toEqual(expectedUnblindedSig) @@ -644,11 +646,11 @@ describe('pnpService', () => { const unblindedSig = threshold_bls.unblind( Buffer.from(res.body.signature, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) expect(Buffer.from(unblindedSig).toString('base64')).toEqual( - expectedUnblindedSigs[i - 1] + expectedUnblindedSigs[i - 1], ) }) } @@ -788,11 +790,11 @@ describe('pnpService', () => { expect(res2.status).toBe(200) const unblindedSig1 = threshold_bls.unblind( Buffer.from(res1.body.signature, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) const unblindedSig2 = threshold_bls.unblind( Buffer.from(res2.body.signature, 'base64'), - blindedMsgResult2.blindingFactor + blindedMsgResult2.blindingFactor, ) expect(Buffer.from(unblindedSig1).toString('base64')).toEqual(expectedUnblindedSig) expect(unblindedSig1).toEqual(unblindedSig2) @@ -866,7 +868,7 @@ describe('pnpService', () => { it('Should respond with 503 on disabled api', async () => { const configWithApiDisabled: typeof combinerConfig = JSON.parse( - JSON.stringify(combinerConfig) + JSON.stringify(combinerConfig), ) configWithApiDisabled.phoneNumberPrivacy.enabled = false const appWithApiDisabled = startCombiner(configWithApiDisabled, mockKit) @@ -892,11 +894,11 @@ describe('pnpService', () => { const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const combinerConfigWithFailOpenDisabled: typeof combinerConfig = JSON.parse( - JSON.stringify(combinerConfig) + JSON.stringify(combinerConfig), ) const appWithFailOpenDisabled = startCombiner( combinerConfigWithFailOpenDisabled, - mockKit + mockKit, ) const res = await sendPnpSignRequest(req, authorization, appWithFailOpenDisabled) @@ -923,7 +925,7 @@ describe('pnpService', () => { '000000002e50aa714ef6b865b5de89c56969ef9f8f27b6b0a6d157c9cc01c574ac9df604' const badKeyProvider1 = new MockKeyProvider( - new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare1]]) + new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare1]]), ) signer1 = startSigner(signerConfig, signerDB1, badKeyProvider1, mockKit).listen(3001) signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockKit).listen(3002) @@ -948,7 +950,7 @@ describe('pnpService', () => { }) const unblindedSig = threshold_bls.unblind( Buffer.from(res.body.signature, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) expect(Buffer.from(unblindedSig).toString('base64')).toEqual(expectedUnblindedSig) }) @@ -963,11 +965,11 @@ describe('pnpService', () => { '01000000b8f0ef841dcf8d7bd1da5e8025e47d729eb67f513335784183b8fa227a0b9a0b' const badKeyProvider1 = new MockKeyProvider( - new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare1]]) + new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare1]]), ) const badKeyProvider2 = new MockKeyProvider( - new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare2]]) + new Map([[`${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, badBlsShare2]]), ) signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001) @@ -997,10 +999,10 @@ describe('pnpService', () => { configWithApiDisabled.api.phoneNumberPrivacy.enabled = false signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001) signer2 = startSigner(configWithApiDisabled, signerDB2, keyProvider2, mockKit).listen( - 3002 + 3002, ) signer3 = startSigner(configWithApiDisabled, signerDB3, keyProvider3, mockKit).listen( - 3003 + 3003, ) }) @@ -1043,7 +1045,7 @@ describe('pnpService', () => { signer1 = startSigner(signerConfig, signerDB1, keyProvider1, mockKit).listen(3001) signer2 = startSigner(signerConfig, signerDB2, keyProvider2, mockKit).listen(3002) signer3 = startSigner(configWithApiDisabled, signerDB3, keyProvider3, mockKit).listen( - 3003 + 3003, ) }) @@ -1093,13 +1095,13 @@ describe('pnpService', () => { configWithShortTimeout.timeout = testTimeoutMS // Test this with all signers timing out to decrease possibility of race conditions signer1 = startSigner(configWithShortTimeout, signerDB1, keyProvider1, mockKit).listen( - 3001 + 3001, ) signer2 = startSigner(configWithShortTimeout, signerDB2, keyProvider2, mockKit).listen( - 3002 + 3002, ) signer3 = startSigner(configWithShortTimeout, signerDB3, keyProvider3, mockKit).listen( - 3003 + 3003, ) }) @@ -1187,7 +1189,7 @@ describe('pnpService', () => { `${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, '00000000a49c8a293839ccb24bbcc7b833b0d57fe2f6087d33271750e7d6cf40897f520c', ], - ]) + ]), ) keyProvider2 = new MockKeyProvider( new Map([ @@ -1195,7 +1197,7 @@ describe('pnpService', () => { `${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, '01000000c0866754b43a0e7c6f86c6732c1bc1bc1900f71a0ccab81fcd4048c5ff2edb02', ], - ]) + ]), ) keyProvider3 = new MockKeyProvider( new Map([ @@ -1203,7 +1205,7 @@ describe('pnpService', () => { `${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, '02000000c24271a9dd0827e2939e5afbd5cd1c6705fa40d6e962fb288bbc7201921efa10', ], - ]) + ]), ) keyProvider4 = new MockKeyProvider( new Map([ @@ -1211,7 +1213,7 @@ describe('pnpService', () => { `${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, '030000006320e2a99d4ce6a491a6354feda06051966a056dffbb0e7c8431b246d863ac09', ], - ]) + ]), ) keyProvider5 = new MockKeyProvider( new Map([ @@ -1219,7 +1221,7 @@ describe('pnpService', () => { `${DefaultKeyName.PHONE_NUMBER_PRIVACY}-1`, '04000000606ff4d6ddae61ac454009af2a49aeb4c297410ef9d3f3ab751c1c4fe5a99c0a', ], - ]) + ]), ) app = startCombiner(combinerConfigLargerN, mockKit) }) @@ -1278,7 +1280,7 @@ describe('pnpService', () => { }) threshold_bls.unblind( Buffer.from(res.body.signature, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) }) diff --git a/apps/combiner/test/unit/bls-signature.test.ts b/apps/combiner/test/unit/bls-signature.test.ts index 559660dcb..2f77a9811 100644 --- a/apps/combiner/test/unit/bls-signature.test.ts +++ b/apps/combiner/test/unit/bls-signature.test.ts @@ -79,7 +79,7 @@ describe(`BLS service computes signature`, () => { const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) @@ -125,7 +125,7 @@ describe(`BLS service computes signature`, () => { const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) @@ -229,7 +229,7 @@ describe(`BLS service computes signature`, () => { const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) @@ -291,7 +291,7 @@ describe(`BLS service computes signature`, () => { const unblindedSignedMessage = threshold_bls.unblind( Buffer.from(actual, 'base64'), - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) const publicKey = Buffer.from(PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) diff --git a/apps/combiner/test/unit/domain-response-logger.test.ts b/apps/combiner/test/unit/domain-response-logger.test.ts index 7041d1c36..a4448bb55 100644 --- a/apps/combiner/test/unit/domain-response-logger.test.ts +++ b/apps/combiner/test/unit/domain-response-logger.test.ts @@ -310,12 +310,12 @@ describe('domain response logger', () => { } logDomainResponseDiscrepancies( logger, - testCase.responses.map((res) => ({ url, res })) + testCase.responses.map((res) => ({ url, res })), ) testCase.expectedLogs.forEach((log) => { expect(logSpys[log.level].spy).toHaveBeenNthCalledWith( ++logSpys[log.level].callCount, - ...log.params + ...log.params, ) }) Object.values(logSpys).forEach((level) => { diff --git a/apps/combiner/test/unit/domain-threshold-state.test.ts b/apps/combiner/test/unit/domain-threshold-state.test.ts index c66c4d478..c65ca1569 100644 --- a/apps/combiner/test/unit/domain-threshold-state.test.ts +++ b/apps/combiner/test/unit/domain-threshold-state.test.ts @@ -155,7 +155,7 @@ describe('domain threshold state', () => { }) expect(() => findThresholdDomainState(keyVersionInfo, responses, totalSigners)).toThrow( - 'Insufficient number of signer responses. Domain may be disabled' + 'Insufficient number of signer responses. Domain may be disabled', ) }) }) diff --git a/apps/combiner/test/unit/pnp-response-logger.test.ts b/apps/combiner/test/unit/pnp-response-logger.test.ts index 85512f04a..5ae8a5176 100644 --- a/apps/combiner/test/unit/pnp-response-logger.test.ts +++ b/apps/combiner/test/unit/pnp-response-logger.test.ts @@ -437,7 +437,7 @@ describe('pnp response logger', () => { testCase.expectedLogs.forEach((log) => { expect(logSpys[log.level].spy).toHaveBeenNthCalledWith( ++logSpys[log.level].callCount, - ...log.params + ...log.params, ) }) Object.values(logSpys).forEach((level) => { diff --git a/apps/combiner/test/unit/pnp-threshold-state.test.ts b/apps/combiner/test/unit/pnp-threshold-state.test.ts index cbbe1908c..fabc7d948 100644 --- a/apps/combiner/test/unit/pnp-threshold-state.test.ts +++ b/apps/combiner/test/unit/pnp-threshold-state.test.ts @@ -148,7 +148,7 @@ describe('pnp threshold state', () => { if (warning) { expect(warnings).toContain( WarningMessage.INCONSISTENT_SIGNER_QUOTA_MEASUREMENTS + - ', using threshold signer as best guess' + ', using threshold signer as best guess', ) } }) @@ -201,7 +201,7 @@ describe('pnp threshold state', () => { if (warning) { expect(warnings).toContain( WarningMessage.INCONSISTENT_SIGNER_QUOTA_MEASUREMENTS + - ', using threshold signer as best guess' + ', using threshold signer as best guess', ) } }) @@ -228,7 +228,7 @@ describe('pnp threshold state', () => { const warnings: string[] = [] expect(() => findCombinerQuotaState(keyVersionInfo, responses, warnings)).toThrow( - WarningMessage.INCONSISTENT_SIGNER_QUOTA_MEASUREMENTS + WarningMessage.INCONSISTENT_SIGNER_QUOTA_MEASUREMENTS, ) }) }) diff --git a/apps/monitor/src/query.ts b/apps/monitor/src/query.ts index 95b9d5944..28a6dc044 100644 --- a/apps/monitor/src/query.ts +++ b/apps/monitor/src/query.ts @@ -34,7 +34,7 @@ export const queryOdisForSalt = async ( bypassQuota: boolean = false, useDEK: boolean = false, privateKey?: string, - privateKeyPercentage: number = 100 + privateKeyPercentage: number = 100, ) => { let authSigner: AuthSigner let accountAddress: string @@ -83,7 +83,7 @@ export const queryOdisForSalt = async ( undefined, bypassQuota ? testSessionId : genSessionID(), undefined, - abortController + abortController, ) clearTimeout(timeout) @@ -99,7 +99,7 @@ export const queryOdisForQuota = async ( contextName: OdisContextName, timeoutMs: number = 10000, privateKey?: string, - privateKeyPercentage: number = 100 + privateKeyPercentage: number = 100, ) => { console.log(`contextName: ${contextName}`) // tslint:disable-line:no-console console.log(`blockchain provider: ${blockchainProvider}`) // tslint:disable-line:no-console @@ -131,7 +131,7 @@ export const queryOdisForQuota = async ( serviceContext, undefined, undefined, - abortController + abortController, ) clearTimeout(timeout) diff --git a/apps/monitor/src/scripts/run-load-test.ts b/apps/monitor/src/scripts/run-load-test.ts index d6a2d9a3b..f825bf3d3 100644 --- a/apps/monitor/src/scripts/run-load-test.ts +++ b/apps/monitor/src/scripts/run-load-test.ts @@ -92,7 +92,7 @@ yargs args.useDEK, args.movingAvgRequests, args.privateKey, - args.privateKeyPercentage + args.privateKeyPercentage, ) - } + }, ).argv diff --git a/apps/monitor/src/test.ts b/apps/monitor/src/test.ts index cd9264153..038a1fb23 100644 --- a/apps/monitor/src/test.ts +++ b/apps/monitor/src/test.ts @@ -17,7 +17,7 @@ export async function testPNPSignQuery( bypassQuota?: boolean, useDEK?: boolean, privateKey?: string, - privateKeyPercentage: number = 100 + privateKeyPercentage: number = 100, ) { try { const odisResponse: IdentifierHashDetails = await queryOdisForSalt( @@ -27,14 +27,14 @@ export async function testPNPSignQuery( bypassQuota, useDEK, privateKey, - privateKeyPercentage + privateKeyPercentage, ) logger.debug({ odisResponse }, 'ODIS salt request successful. System is healthy.') } catch (err) { if ((err as Error).message === ErrorMessages.ODIS_QUOTA_ERROR) { logger.warn( { error: err }, - 'ODIS salt request out of quota. This is expected. System is healthy.' + 'ODIS salt request out of quota. This is expected. System is healthy.', ) } else { logger.error('ODIS salt request failed.') @@ -49,7 +49,7 @@ export async function testPNPQuotaQuery( contextName: OdisContextName, timeoutMs?: number, privateKey?: string, - privateKeyPercentage: number = 100 + privateKeyPercentage: number = 100, ) { logger.info(`Performing test PNP query for ${CombinerEndpointPNP.PNP_QUOTA}`) try { @@ -58,7 +58,7 @@ export async function testPNPQuotaQuery( contextName, timeoutMs, privateKey, - privateKeyPercentage + privateKeyPercentage, ) logger.info({ odisResponse }, 'ODIS quota request successful. System is healthy.') } catch (err) { @@ -98,7 +98,7 @@ export async function concurrentRPSLoadTest( useDEK: boolean = false, movingAverageRequests: number = 50, privateKey?: string, - privateKeyPercentage: number = 100 + privateKeyPercentage: number = 100, ) { const latencyQueue: number[] = [] let movingAvgLatencySum = 0 @@ -145,14 +145,14 @@ export async function concurrentRPSLoadTest( bypassQuota, useDEK, privateKey, - privateKeyPercentage + privateKeyPercentage, ) : testPNPQuotaQuery( blockchainProvider, contextName, undefined, privateKey, - privateKeyPercentage + privateKeyPercentage, )) } catch (_) { logger.error('load test request failed') @@ -165,7 +165,7 @@ export async function concurrentRPSLoadTest( async function doRPSTest( testFn: () => Promise, rps: number, - duration: number = 0 + duration: number = 0, ): Promise { const inFlightRequests: Array> = [] let shouldRun = true diff --git a/apps/signer/src/common/bls/bls-cryptography-client.ts b/apps/signer/src/common/bls/bls-cryptography-client.ts index 8949df8a5..f67cf4521 100644 --- a/apps/signer/src/common/bls/bls-cryptography-client.ts +++ b/apps/signer/src/common/bls/bls-cryptography-client.ts @@ -9,7 +9,7 @@ import { Counters } from '../metrics' export function computeBlindedSignature( base64BlindedMessage: string, privateKey: string, - logger: Logger + logger: Logger, ) { try { const keyBuffer = Buffer.from(privateKey, 'hex') diff --git a/apps/signer/src/common/database/models/domain-request.ts b/apps/signer/src/common/database/models/domain-request.ts index 84a3a6fd9..aba36cf9e 100644 --- a/apps/signer/src/common/database/models/domain-request.ts +++ b/apps/signer/src/common/database/models/domain-request.ts @@ -15,7 +15,7 @@ export interface DomainRequestRecord { export function toDomainRequestRecord( domain: D, - blindedMessage: string + blindedMessage: string, ): DomainRequestRecord { return { [DOMAIN_REQUESTS_COLUMNS.domainHash]: domainHash(domain).toString('hex'), diff --git a/apps/signer/src/common/database/models/domain-state.ts b/apps/signer/src/common/database/models/domain-state.ts index ae1a964ec..ee0b0186a 100644 --- a/apps/signer/src/common/database/models/domain-state.ts +++ b/apps/signer/src/common/database/models/domain-state.ts @@ -22,7 +22,7 @@ export interface DomainStateRecord { export function toDomainStateRecord( domain: D, - domainState: DomainState + domainState: DomainState, ): DomainStateRecord { return { [DOMAIN_STATE_COLUMNS.domainHash]: domainHash(domain).toString('hex'), @@ -34,7 +34,7 @@ export function toDomainStateRecord( export function toSequentialDelayDomainState( record: DomainStateRecord, - attemptTime?: number + attemptTime?: number, ): SequentialDelayDomainState { return { disabled: record[DOMAIN_STATE_COLUMNS.disabled], diff --git a/apps/signer/src/common/database/models/request.ts b/apps/signer/src/common/database/models/request.ts index 2cc9aba49..5e96b66ba 100644 --- a/apps/signer/src/common/database/models/request.ts +++ b/apps/signer/src/common/database/models/request.ts @@ -17,7 +17,7 @@ export interface PnpSignRequestRecord { export function toPnpSignRequestRecord( account: string, blindedQuery: string, - signature: string + signature: string, ): PnpSignRequestRecord { return { [REQUESTS_COLUMNS.address]: account, diff --git a/apps/signer/src/common/database/utils.ts b/apps/signer/src/common/database/utils.ts index 70f7ade52..640c6e932 100644 --- a/apps/signer/src/common/database/utils.ts +++ b/apps/signer/src/common/database/utils.ts @@ -12,7 +12,7 @@ export type DatabaseErrorMessage = export function countAndThrowDBError( err: any, logger: Logger, - errorMsg: DatabaseErrorMessage + errorMsg: DatabaseErrorMessage, ): never { let label: Labels switch (errorMsg) { @@ -41,7 +41,7 @@ export function doMeteredSql( sqlLabel: string, errorMsg: DatabaseErrorMessage, logger: Logger, - fn: () => Promise + fn: () => Promise, ): Promise { const meter = newMeter(Histograms.dbOpsInstrumentation, sqlLabel) diff --git a/apps/signer/src/common/database/wrappers/account.ts b/apps/signer/src/common/database/wrappers/account.ts index 264f89466..b673c38df 100644 --- a/apps/signer/src/common/database/wrappers/account.ts +++ b/apps/signer/src/common/database/wrappers/account.ts @@ -11,7 +11,7 @@ import { doMeteredSql } from '../utils' export async function getPerformedQueryCount( db: Knex, account: string, - logger: Logger + logger: Logger, ): Promise { logger.debug({ account }, 'Getting performed query count') return doMeteredSql( @@ -25,7 +25,7 @@ export async function getPerformedQueryCount( .first() .timeout(config.db.timeout) return queryCounts === undefined ? 0 : queryCounts[ACCOUNTS_COLUMNS.numLookups] - } + }, ) } @@ -33,7 +33,7 @@ async function getAccountExists( db: Knex, account: string, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { return doMeteredSql('getAccountExists', ErrorMessage.DATABASE_GET_FAILURE, logger, async () => { const sql = db(ACCOUNTS_TABLE) @@ -53,7 +53,7 @@ export async function incrementQueryCount( db: Knex, account: string, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { logger.debug({ account }, 'Incrementing query count') return doMeteredSql( @@ -73,6 +73,6 @@ export async function incrementQueryCount( .timeout(config.db.timeout) await (trx != null ? sql.transacting(trx) : sql) } - } + }, ) } diff --git a/apps/signer/src/common/database/wrappers/domain-request.ts b/apps/signer/src/common/database/wrappers/domain-request.ts index ef7506d75..a0b51a41a 100644 --- a/apps/signer/src/common/database/wrappers/domain-request.ts +++ b/apps/signer/src/common/database/wrappers/domain-request.ts @@ -18,7 +18,7 @@ export async function getDomainRequestRecordExists( domain: D, blindedMessage: string, trx: Knex.Transaction, - logger: Logger + logger: Logger, ): Promise { const hash = domainHash(domain).toString('hex') logger.debug({ domain, blindedMessage, hash }, 'Checking if domain request exists') @@ -36,7 +36,7 @@ export async function getDomainRequestRecordExists( .first() .timeout(config.db.timeout) return !!existingRequest - } + }, ) } @@ -45,7 +45,7 @@ export async function storeDomainRequestRecord( domain: D, blindedMessage: string, trx: Knex.Transaction, - logger: Logger + logger: Logger, ) { logger.debug({ domain, blindedMessage }, 'Storing domain restricted signature request') return doMeteredSql( @@ -57,7 +57,7 @@ export async function storeDomainRequestRecord( .transacting(trx) .insert(toDomainRequestRecord(domain, blindedMessage)) .timeout(config.db.timeout) - } + }, ) } @@ -65,7 +65,7 @@ export async function deleteDomainRequestsOlderThan( db: Knex, date: Date, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { logger.debug(`Removing request older than: ${date}`) if (date > new Date()) { @@ -81,6 +81,6 @@ export async function deleteDomainRequestsOlderThan( .where(DOMAIN_REQUESTS_COLUMNS.timestamp, '<=', date) .del() return trx != null ? sql.transacting(trx) : sql - } + }, ) } diff --git a/apps/signer/src/common/database/wrappers/domain-state.ts b/apps/signer/src/common/database/wrappers/domain-state.ts index 8cebb8625..85d2d24ed 100644 --- a/apps/signer/src/common/database/wrappers/domain-state.ts +++ b/apps/signer/src/common/database/wrappers/domain-state.ts @@ -15,7 +15,7 @@ export async function setDomainDisabled( db: Knex, domain: D, trx: Knex.Transaction, - logger: Logger + logger: Logger, ): Promise { const hash = domainHash(domain).toString('hex') logger.debug({ hash, domain }, 'Disabling domain') @@ -32,7 +32,7 @@ export async function getDomainStateRecordOrEmpty( db: Knex, domain: Domain, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { return ( (await getDomainStateRecord(db, domain, logger, trx)) ?? createEmptyDomainStateRecord(domain) @@ -52,7 +52,7 @@ export async function getDomainStateRecord( db: Knex, domain: D, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { const hash = domainHash(domain).toString('hex') logger.debug({ hash, domain }, 'Getting domain state from db') @@ -73,7 +73,7 @@ export async function getDomainStateRecord( } return result ?? null - } + }, ) } @@ -82,7 +82,7 @@ export async function updateDomainStateRecord( domain: D, domainState: DomainStateRecord, trx: Knex.Transaction, - logger: Logger + logger: Logger, ): Promise { const hash = domainHash(domain).toString('hex') logger.debug({ hash, domain, domainState }, 'Update domain state') @@ -106,7 +106,7 @@ export async function updateDomainStateRecord( .update(domainState) .timeout(config.db.timeout) } - } + }, ) } @@ -114,7 +114,7 @@ export async function insertDomainStateRecord( db: Knex, domainState: DomainStateRecord, trx: Knex.Transaction, - logger: Logger + logger: Logger, ): Promise { logger.debug({ domainState }, 'Insert domain state') return doMeteredSql( @@ -127,6 +127,6 @@ export async function insertDomainStateRecord( .insert(domainState) .timeout(config.db.timeout) return domainState - } + }, ) } diff --git a/apps/signer/src/common/database/wrappers/request.ts b/apps/signer/src/common/database/wrappers/request.ts index 9e843fa93..6e1ccd436 100644 --- a/apps/signer/src/common/database/wrappers/request.ts +++ b/apps/signer/src/common/database/wrappers/request.ts @@ -14,7 +14,7 @@ export async function getRequestIfExists( db: Knex, account: string, blindedQuery: string, - logger: Logger + logger: Logger, ): Promise { logger.debug(`Checking if request exists for account: ${account}, blindedQuery: ${blindedQuery}`) return doMeteredSql('getRequestIfExists', ErrorMessage.DATABASE_GET_FAILURE, logger, async () => { @@ -35,10 +35,10 @@ export async function insertRequest( blindedQuery: string, signature: string, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { logger.debug( - `Storing salt request for: ${account}, blindedQuery: ${blindedQuery}, signature: ${signature}` + `Storing salt request for: ${account}, blindedQuery: ${blindedQuery}, signature: ${signature}`, ) return doMeteredSql('insertRequest', ErrorMessage.DATABASE_INSERT_FAILURE, logger, async () => { const sql = db(REQUESTS_TABLE) @@ -51,7 +51,7 @@ export async function insertRequest( export async function deleteRequestsOlderThan( db: Knex, since: Date, - logger: Logger + logger: Logger, ): Promise { logger.debug(`Removing request older than: ${since}`) if (since > new Date(Date.now())) { @@ -67,6 +67,6 @@ export async function deleteRequestsOlderThan( .where(REQUESTS_COLUMNS.timestamp, '<=', since) .del() return sql - } + }, ) } diff --git a/apps/signer/src/common/error.ts b/apps/signer/src/common/error.ts index 91060f236..712331f56 100644 --- a/apps/signer/src/common/error.ts +++ b/apps/signer/src/common/error.ts @@ -1,7 +1,11 @@ import { ErrorType } from '@celo/phone-number-privacy-common' export class OdisError extends Error { - constructor(readonly code: ErrorType, readonly parent?: Error, readonly status: number = 500) { + constructor( + readonly code: ErrorType, + readonly parent?: Error, + readonly status: number = 500, + ) { // This is necessary when extending Error Classes super(code) // 'Error' breaks prototype chain here Object.setPrototypeOf(this, new.target.prototype) // restore prototype chain @@ -11,7 +15,7 @@ export class OdisError extends Error { export function wrapError( valueOrError: Promise, code: ErrorType, - status: number = 500 + status: number = 500, ): Promise { return valueOrError.catch((parentErr) => { throw new OdisError(code, parentErr, status) diff --git a/apps/signer/src/common/handler.ts b/apps/signer/src/common/handler.ts index 4efad1e38..b26ffac47 100644 --- a/apps/signer/src/common/handler.ts +++ b/apps/signer/src/common/handler.ts @@ -25,11 +25,11 @@ export interface Locals { export type PromiseHandler = ( request: Request<{}, {}, R>, - res: Response, Locals> + res: Response, Locals>, ) => Promise export function catchErrorHandler( - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { try { @@ -59,7 +59,7 @@ export function catchErrorHandler( } export function tracingHandler( - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { return tracer.startActiveSpan( @@ -86,21 +86,21 @@ export function tracingHandler( } finally { span.end() } - } + }, ) } } export function meteringHandler( histogram: client.Histogram, - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return (req, res) => newMeter(histogram, req.url)(async () => handler(req, res)) } export function timeoutHandler( timeoutMs: number, - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { const timeoutId = setTimeout(() => { @@ -120,7 +120,7 @@ export function timeoutHandler( } export function connectionClosedHandler( - handler: PromiseHandler + handler: PromiseHandler, ): PromiseHandler { return async (req, res) => { req.on('close', () => { @@ -137,7 +137,7 @@ export function connectionClosedHandler( export async function disabledHandler( req: Request<{}, {}, R>, - response: Response, Locals> + response: Response, Locals>, ): Promise { sendFailure(WarningMessage.API_UNAVAILABLE, 503, response, req.url) } @@ -149,11 +149,11 @@ export interface Result { export type ResultHandler = ( request: Request<{}, {}, R>, - res: Response, Locals> + res: Response, Locals>, ) => Promise> export function resultHandler( - resHandler: ResultHandler + resHandler: ResultHandler, ): PromiseHandler { return async (req, res) => { const result = await resHandler(req, res) @@ -168,7 +168,7 @@ export function resultHandler( export function errorResult( status: number, error: string, - quotaStatus?: PnpQuotaStatus | { status: SequentialDelayDomainState } + quotaStatus?: PnpQuotaStatus | { status: SequentialDelayDomainState }, ): Result { // TODO remove any return { @@ -187,7 +187,7 @@ function sendFailure( status: number, response: Response, endpoint: string, - body?: Record // TODO remove any + body?: Record, // TODO remove any ) { // Check if the response was ended if (!response.writableEnded) { @@ -200,7 +200,7 @@ function sendFailure( ...body, }, status, - response.locals.logger + response.locals.logger, ) Counters.responses.labels(endpoint, status.toString()).inc() } diff --git a/apps/signer/src/common/key-management/google-key-provider.ts b/apps/signer/src/common/key-management/google-key-provider.ts index 0d3c7f9fa..5ef422056 100644 --- a/apps/signer/src/common/key-management/google-key-provider.ts +++ b/apps/signer/src/common/key-management/google-key-provider.ts @@ -26,7 +26,7 @@ export class GoogleKeyProvider extends KeyProviderBase { client: SecretManagerServiceClient, projectId: string, secretName: string, - secretVersion: string + secretVersion: string, ) { // check for empty strings from undefined env vars if (!(projectId && secretName && secretVersion)) { diff --git a/apps/signer/src/common/key-management/key-provider.ts b/apps/signer/src/common/key-management/key-provider.ts index 6e6e9a384..05fef0aa9 100644 --- a/apps/signer/src/common/key-management/key-provider.ts +++ b/apps/signer/src/common/key-management/key-provider.ts @@ -44,7 +44,7 @@ export async function initKeyProvider(config: SignerConfig): Promise { const _meter = newMeter(Histograms.fullNodeLatency, 'getOnChainOdisPayments') return _meter(() => @@ -19,12 +19,12 @@ export async function getOnChainOdisPayments( [], config.fullNodeRetryDelayMs, undefined, - config.fullNodeTimeoutMs + config.fullNodeTimeoutMs, ).catch((err: any) => { logger.error({ err, account }, 'failed to get on-chain odis balance for account') Counters.blockchainErrors.inc() throw err - }) + }), ) } @@ -37,11 +37,11 @@ export async function getDEK(kit: ContractKit, logger: Logger, account: string): logger, config.fullNodeTimeoutMs, config.fullNodeRetryCount, - config.fullNodeRetryDelayMs + config.fullNodeRetryDelayMs, ).catch((err) => { logger.error({ err, account }, 'failed to get on-chain DEK for account') Counters.blockchainErrors.inc() throw err - }) + }), ) } diff --git a/apps/signer/src/domain/endpoints/disable/action.ts b/apps/signer/src/domain/endpoints/disable/action.ts index 1cf71fb0d..ee0ed4517 100644 --- a/apps/signer/src/domain/endpoints/disable/action.ts +++ b/apps/signer/src/domain/endpoints/disable/action.ts @@ -37,7 +37,7 @@ export function domainDisable(db: Knex): ResultHandler { version: domain.version, hash: domainHash(domain).toString('hex'), }, - 'Processing request to disable domain' + 'Processing request to disable domain', ) const res = await db.transaction(async (trx) => { @@ -70,7 +70,7 @@ export function domainDisable(db: Knex): ResultHandler { } function isValidRequest( - request: Request<{}, {}, unknown> + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, DisableDomainRequest> { return disableDomainRequestSchema(DomainSchema).is(request.body) } diff --git a/apps/signer/src/domain/endpoints/quota/action.ts b/apps/signer/src/domain/endpoints/quota/action.ts index e397b2a05..fe31f1b40 100644 --- a/apps/signer/src/domain/endpoints/quota/action.ts +++ b/apps/signer/src/domain/endpoints/quota/action.ts @@ -44,7 +44,7 @@ export function domainQuota(quota: DomainQuotaService): ResultHandler + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, DomainQuotaStatusRequest> { return domainQuotaStatusRequestSchema(DomainSchema).is(request.body) } diff --git a/apps/signer/src/domain/endpoints/sign/action.ts b/apps/signer/src/domain/endpoints/sign/action.ts index 7cc0ec853..091929e0e 100644 --- a/apps/signer/src/domain/endpoints/sign/action.ts +++ b/apps/signer/src/domain/endpoints/sign/action.ts @@ -45,7 +45,7 @@ export function domainSign( db: Knex, config: SignerConfig, quota: DomainQuotaService, - keyProvider: KeyProvider + keyProvider: KeyProvider, ): ResultHandler { return async (request, response) => { const { logger } = response.locals @@ -68,7 +68,7 @@ export function domainSign( version: domain.version, hash: domainHash(domain).toString('hex'), }, - 'Processing request to get domain signature ' + 'Processing request to get domain signature ', ) const res: TrxResult = await db.transaction(async (trx) => { // Get the current domain state record, or use an empty record if one does not exist. @@ -92,7 +92,7 @@ export function domainSign( domainStateRecord, request.body.domain, trx, - logger + logger, ) if (!quotaStatus.sufficient) { @@ -102,7 +102,7 @@ export function domainSign( version: domain.version, hash: domainHash(domain), }, - `Exceeded quota` + `Exceeded quota`, ) return { success: false, @@ -123,7 +123,7 @@ export function domainSign( request.body.blindedMessage, key, logger, - keyProvider + keyProvider, ) return { @@ -155,7 +155,7 @@ export function domainSign( } function isValidRequest( - request: Request<{}, {}, unknown> + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, DomainRestrictedSignatureRequest> { return domainRestrictedSignatureRequestSchema(DomainSchema).is(request.body) } @@ -163,7 +163,7 @@ function isValidRequest( function nonceCheck( domainStateRecord: DomainStateRecord, body: DomainRestrictedSignatureRequest, - logger: Logger + logger: Logger, ): boolean { const nonce: EIP712Optional = body.options.nonce if (!nonce.defined) { @@ -178,7 +178,7 @@ async function sign( blindedMessage: string, key: Key, logger: Logger, - keyProvider: KeyProvider + keyProvider: KeyProvider, ): Promise { let privateKey: string try { diff --git a/apps/signer/src/domain/services/quota.ts b/apps/signer/src/domain/services/quota.ts index 4a05475cf..42d5a9779 100644 --- a/apps/signer/src/domain/services/quota.ts +++ b/apps/signer/src/domain/services/quota.ts @@ -31,7 +31,7 @@ export class DomainQuotaService { domain: SequentialDelayDomain, trx: Knex.Transaction, logger: Logger, - attemptTime?: number + attemptTime?: number, ): Promise> { // Timestamp precision is lowered to seconds to reduce the chance of effective timing attacks. attemptTime = attemptTime ?? Math.floor(Date.now() / 1000) @@ -39,7 +39,7 @@ export class DomainQuotaService { const result = checkSequentialDelayRateLimit( domain, attemptTime, - toSequentialDelayDomainState(state, attemptTime) + toSequentialDelayDomainState(state, attemptTime), ) if (result.accepted) { const newState = toDomainStateRecord(domain, result.state) @@ -58,7 +58,7 @@ export class DomainQuotaService { async getQuotaStatus( domain: SequentialDelayDomain, logger: Logger, - trx?: Knex.Transaction + trx?: Knex.Transaction, ): Promise { return getDomainStateRecordOrEmpty(this.db, domain, logger, trx) } diff --git a/apps/signer/src/pnp/endpoints/quota/action.ts b/apps/signer/src/pnp/endpoints/quota/action.ts index fb9ffa180..afdc36447 100644 --- a/apps/signer/src/pnp/endpoints/quota/action.ts +++ b/apps/signer/src/pnp/endpoints/quota/action.ts @@ -17,7 +17,7 @@ import { PnpRequestService } from '../../services/request-service' export function pnpQuota( requestService: PnpRequestService, - accountService: AccountService + accountService: AccountService, ): ResultHandler { return async (request, response) => { const logger = response.locals.logger @@ -59,7 +59,7 @@ export function pnpQuota( } function isValidRequest( - request: Request<{}, {}, unknown> + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, PnpQuotaRequest> { return ( PnpQuotaRequestSchema.is(request.body) && diff --git a/apps/signer/src/pnp/endpoints/sign/action.ts b/apps/signer/src/pnp/endpoints/sign/action.ts index 6db2a2548..3e9ca0206 100644 --- a/apps/signer/src/pnp/endpoints/sign/action.ts +++ b/apps/signer/src/pnp/endpoints/sign/action.ts @@ -28,7 +28,7 @@ export function pnpSign( config: SignerConfig, requestService: PnpRequestService, accountService: AccountService, - keyProvider: KeyProvider + keyProvider: KeyProvider, ): ResultHandler { return async (request, response) => { const logger = response.locals.logger @@ -63,7 +63,7 @@ export function pnpSign( const duplicateRequest = await requestService.getDuplicateRequest( request.body.account, request.body.blindedQueryPhoneNumber, - ctx + ctx, ) Histograms.userRemainingQuotaAtRequest @@ -111,7 +111,7 @@ export function pnpSign( account.address, request.body.blindedQueryPhoneNumber, signature, - ctx + ctx, ) if (!bypassQuotaForE2ETesting(config.test_quota_bypass_percentage, request.body)) { usedQuota++ @@ -142,7 +142,7 @@ async function sign( blindedMessage: string, key: Key, keyProvider: KeyProvider, - logger: Logger + logger: Logger, ): Promise { let privateKey: string return traceAsyncFunction('pnpSign', async () => { @@ -158,7 +158,7 @@ async function sign( } function isValidRequest( - request: Request<{}, {}, unknown> + request: Request<{}, {}, unknown>, ): request is Request<{}, {}, SignMessageRequest> { return ( SignMessageRequestSchema.is(request.body) && @@ -170,7 +170,7 @@ function isValidRequest( function bypassQuotaForE2ETesting( bypassQuotaPercentage: number, - requestBody: SignMessageRequest + requestBody: SignMessageRequest, ): boolean { const sessionID = Number(requestBody.sessionID) // TODO revisit whether to remove sessionID return !Number.isNaN(sessionID) && sessionID % 100 < bypassQuotaPercentage diff --git a/apps/signer/src/pnp/services/account-service.ts b/apps/signer/src/pnp/services/account-service.ts index c57b50a49..442ea7447 100644 --- a/apps/signer/src/pnp/services/account-service.ts +++ b/apps/signer/src/pnp/services/account-service.ts @@ -54,19 +54,22 @@ export class CachingAccountService implements AccountService { } export class ContractKitAccountService implements AccountService { - constructor(private readonly logger: Logger, private readonly kit: ContractKit) {} + constructor( + private readonly logger: Logger, + private readonly kit: ContractKit, + ) {} async getAccount(address: string): Promise { return traceAsyncFunction('ContractKitAccountService - getAccount', async () => { const dek = await wrapError( getDEK(this.kit, this.logger, address), - ErrorMessage.FAILURE_TO_GET_DEK + ErrorMessage.FAILURE_TO_GET_DEK, ) const { queryPriceInCUSD } = config.quota const totalPaidInWei = await wrapError( getOnChainOdisPayments(this.kit, this.logger, address), - ErrorMessage.FAILURE_TO_GET_TOTAL_QUOTA + ErrorMessage.FAILURE_TO_GET_TOTAL_QUOTA, ) const totalQuotaBN = totalPaidInWei .div(queryPriceInCUSD.times(new BigNumber(1e18))) @@ -86,7 +89,10 @@ export class ContractKitAccountService implements AccountService { } export class MockAccountService implements AccountService { - constructor(private readonly mockDek: string, private readonly mockTotalQuota: number) {} + constructor( + private readonly mockDek: string, + private readonly mockTotalQuota: number, + ) {} async getAccount(address: string): Promise { return { diff --git a/apps/signer/src/pnp/services/request-service.ts b/apps/signer/src/pnp/services/request-service.ts index c3c74f375..c5961dffa 100644 --- a/apps/signer/src/pnp/services/request-service.ts +++ b/apps/signer/src/pnp/services/request-service.ts @@ -16,13 +16,13 @@ export interface PnpRequestService { address: string, blindedQuery: string, signature: string, - ctx: Context + ctx: Context, ): Promise getUsedQuotaForAccount(address: string, ctx: Context): Promise getDuplicateRequest( address: string, blindedQuery: string, - ctx: Context + ctx: Context, ): Promise removeOldRequests(daysToKeep: number, ctx: Context): Promise } @@ -34,13 +34,13 @@ export class DefaultPnpRequestService implements PnpRequestService { account: string, blindedQueryPhoneNumber: string, signature: string, - ctx: Context + ctx: Context, ): Promise { return traceAsyncFunction('DefaultPnpRequestService - recordRequest', () => this.db.transaction(async (trx) => { await insertRequest(this.db, account, blindedQueryPhoneNumber, signature, ctx.logger, trx) await incrementQueryCount(this.db, account, ctx.logger, trx) - }) + }), ) } @@ -48,15 +48,15 @@ export class DefaultPnpRequestService implements PnpRequestService { return traceAsyncFunction('DefaultPnpRequestService - getUsedQuotaForAccount', () => wrapError( getPerformedQueryCount(this.db, account, ctx.logger), - ErrorMessage.FAILURE_TO_GET_PERFORMED_QUERY_COUNT - ) + ErrorMessage.FAILURE_TO_GET_PERFORMED_QUERY_COUNT, + ), ) } public async getDuplicateRequest( account: string, blindedQueryPhoneNumber: string, - ctx: Context + ctx: Context, ): Promise { try { const res = await getRequestIfExists(this.db, account, blindedQueryPhoneNumber, ctx.logger) @@ -71,13 +71,13 @@ export class DefaultPnpRequestService implements PnpRequestService { if (daysToKeep < 0) { ctx.logger.error( { daysToKeep }, - 'RemoveOldRequests - DaysToKeep should be bigger than or equal to zero' + 'RemoveOldRequests - DaysToKeep should be bigger than or equal to zero', ) return 0 } const since: Date = new Date(Date.now() - daysToKeep * 24 * 60 * 60 * 1000) return traceAsyncFunction('DefaultPnpRequestService - removeOldRequests', () => - deleteRequestsOlderThan(this.db, since, ctx.logger) + deleteRequestsOlderThan(this.db, since, ctx.logger), ) } } @@ -87,11 +87,11 @@ export class MockPnpRequestService implements PnpRequestService { account: string, blindedQueryPhoneNumber: string, signature: string, - ctx: Context + ctx: Context, ): Promise { ctx.logger.info( { account, blindedQueryPhoneNumber, signature }, - 'MockPnpRequestService - recordRequest' + 'MockPnpRequestService - recordRequest', ) return } @@ -104,11 +104,11 @@ export class MockPnpRequestService implements PnpRequestService { public async getDuplicateRequest( account: string, blindedQueryPhoneNumber: string, - ctx: Context + ctx: Context, ): Promise { ctx.logger.info( { account, blindedQueryPhoneNumber }, - 'MockPnpRequestService - isDuplicateRequest' + 'MockPnpRequestService - isDuplicateRequest', ) return undefined } diff --git a/apps/signer/src/server.ts b/apps/signer/src/server.ts index 2933cf7c2..01e0b84c0 100644 --- a/apps/signer/src/server.ts +++ b/apps/signer/src/server.ts @@ -45,7 +45,7 @@ export function startSigner( config: SignerConfig, db: Knex, keyProvider: KeyProvider, - kit?: ContractKit + kit?: ContractKit, ): Express | https.Server { const logger = rootLogger(config.serviceName) @@ -88,24 +88,28 @@ export function startSigner( createHandler( timeout, phoneNumberPrivacy.enabled, - pnpSign(config, pnpRequestService, accountService, keyProvider) - ) + pnpSign(config, pnpRequestService, accountService, keyProvider), + ), ) app.post( SignerEndpoint.PNP_QUOTA, - createHandler(timeout, phoneNumberPrivacy.enabled, pnpQuota(pnpRequestService, accountService)) + createHandler(timeout, phoneNumberPrivacy.enabled, pnpQuota(pnpRequestService, accountService)), ) app.post( SignerEndpoint.DOMAIN_QUOTA_STATUS, - createHandler(timeout, domains.enabled, domainQuota(domainQuotaService)) + createHandler(timeout, domains.enabled, domainQuota(domainQuotaService)), ) app.post( SignerEndpoint.DOMAIN_SIGN, - createHandler(timeout, domains.enabled, domainSign(db, config, domainQuotaService, keyProvider)) + createHandler( + timeout, + domains.enabled, + domainSign(db, config, domainQuotaService, keyProvider), + ), ) app.post( SignerEndpoint.DISABLE_DOMAIN, - createHandler(timeout, domains.enabled, domainDisable(db)) + createHandler(timeout, domains.enabled, domainDisable(db)), ) const sslOptions = getSslOptions(config) @@ -139,7 +143,7 @@ function getSslOptions(config: SignerConfig) { function createHandler( timeoutMs: number, enabled: boolean, - action: ResultHandler + action: ResultHandler, ): RequestHandler<{}, {}, R, {}, Locals> { return catchErrorHandler( tracingHandler( @@ -147,9 +151,9 @@ function createHandler( Histograms.responseLatency, timeoutHandler( timeoutMs, - enabled ? connectionClosedHandler(resultHandler(action)) : disabledHandler - ) - ) - ) + enabled ? connectionClosedHandler(resultHandler(action)) : disabledHandler, + ), + ), + ), ) } diff --git a/apps/signer/src/tracing.ts b/apps/signer/src/tracing.ts index 6bdcd64d3..9b4500b61 100644 --- a/apps/signer/src/tracing.ts +++ b/apps/signer/src/tracing.ts @@ -67,7 +67,7 @@ const resource = Resource.default().merge( [SemanticResourceAttributes.SERVICE_NAME]: process.env.TRACING_SERVICE_NAME, // 'testing-signer-tracing', [SemanticResourceAttributes.SERVICE_VERSION]: '0.1.0', // should be the same as package.json version? - }) + }), ) const provider = new NodeTracerProvider({ diff --git a/apps/signer/test/end-to-end/disabled-apis.test.ts b/apps/signer/test/end-to-end/disabled-apis.test.ts index 594c6888a..b2ac32098 100644 --- a/apps/signer/test/end-to-end/disabled-apis.test.ts +++ b/apps/signer/test/end-to-end/disabled-apis.test.ts @@ -71,7 +71,7 @@ describe('Running against a deployed service with disabled APIs', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, disableDomainRequestEIP712(req)) + await wallet.signTypedData(walletAddress, disableDomainRequestEIP712(req)), ) const body = JSON.stringify(req) const response = await fetch(ODIS_SIGNER + SignerEndpoint.DISABLE_DOMAIN, { @@ -102,7 +102,7 @@ describe('Running against a deployed service with disabled APIs', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainQuotaStatusRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainQuotaStatusRequestEIP712(req)), ) const body = JSON.stringify(req) const response = await fetch(ODIS_SIGNER + SignerEndpoint.DOMAIN_QUOTA_STATUS, { @@ -135,7 +135,7 @@ describe('Running against a deployed service with disabled APIs', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)), ) const body = JSON.stringify(req) const response = await fetch(ODIS_SIGNER + SignerEndpoint.DOMAIN_SIGN, { diff --git a/apps/signer/test/end-to-end/domain.test.ts b/apps/signer/test/end-to-end/domain.test.ts index 019da1422..94a8e0b91 100644 --- a/apps/signer/test/end-to-end/domain.test.ts +++ b/apps/signer/test/end-to-end/domain.test.ts @@ -260,7 +260,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { expect(res.headers.get(KEY_VERSION_HEADER)).toEqual(contextSpecificParams.domainsKeyVersion) poprf.unblindPartialResponse( // throws if verification fails - Buffer.from(resBody.signature, 'base64') + Buffer.from(resBody.signature, 'base64'), ) }) @@ -287,7 +287,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { req.options.nonce = defined(1) req.options.signature = noString req.options.signature = defined( - await wallet.signTypedData(ACCOUNT_ADDRESS1, domainRestrictedSignatureRequestEIP712(req)) + await wallet.signTypedData(ACCOUNT_ADDRESS1, domainRestrictedSignatureRequestEIP712(req)), ) // TODO(ODIS 2.0.0 e2e fix) clean up this duplicated logic @@ -323,7 +323,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { ACCOUNT_ADDRESS1, `${signSalt}-${Date.now()}`, undefined, - 5 + 5, ) const res = await queryDomainEndpoint(newReq, SignerEndpoint.DOMAIN_SIGN) expect(res.status).toBe(200) @@ -346,12 +346,12 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const [newReq, _poprf] = await signatureRequest( wallet, ACCOUNT_ADDRESS1, - `${signSalt}-${Date.now() + 1}` + `${signSalt}-${Date.now() + 1}`, ) const res = await queryDomainEndpoint( newReq, SignerEndpoint.DOMAIN_SIGN, - contextSpecificParams.domainsKeyVersion + contextSpecificParams.domainsKeyVersion, ) expect(res.status).toBe(200) const resBody: DomainRestrictedSignatureResponseSuccess = await res.json() @@ -374,7 +374,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const [badRequest, _] = await signatureRequest( wallet, ACCOUNT_ADDRESS1, - `${signSalt}-${Date.now()}` + `${signSalt}-${Date.now()}`, ) // @ts-ignore Intentionally deleting required field delete badRequest.domain.version @@ -392,7 +392,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const [badRequest, _] = await signatureRequest( wallet, ACCOUNT_ADDRESS1, - `${signSalt}-${Date.now()}` + `${signSalt}-${Date.now()}`, ) // @ts-ignore UnknownDomain is (intentionally) not a valid domain identifier. badRequest.domain.name = 'UnknownDomain' @@ -410,7 +410,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const [badRequest, _] = await signatureRequest( wallet, ACCOUNT_ADDRESS1, - `${signSalt}-${Date.now()}` + `${signSalt}-${Date.now()}`, ) // @ts-ignore Intentionally not JSON badRequest.domain = 'Freddy' @@ -428,7 +428,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const [badRequest, _] = await signatureRequest( wallet, ACCOUNT_ADDRESS1, - `${signSalt}-${Date.now()}` + `${signSalt}-${Date.now()}`, ) const res = await queryDomainEndpoint(badRequest, SignerEndpoint.DOMAIN_SIGN, 'a') expect(res.status).toBe(400) @@ -444,7 +444,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const [badRequest, _] = await signatureRequest( wallet, ACCOUNT_ADDRESS1, - `${signSalt}-${Date.now()}` + `${signSalt}-${Date.now()}`, ) badRequest.domain.salt = defined('badSalt') const res = await queryDomainEndpoint(badRequest, SignerEndpoint.DOMAIN_SIGN) @@ -487,7 +487,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { wallet, ACCOUNT_ADDRESS1, `${signSalt}-${Date.now()}`, - disableReq.domain + disableReq.domain, ) const res = await queryDomainEndpoint(signReq, SignerEndpoint.DOMAIN_SIGN) expect(res.status).toBe(429) @@ -510,7 +510,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { async function queryDomainEndpoint( req: DomainRequest, endpoint: DomainEndpoint, - keyVersion?: string + keyVersion?: string, ): Promise { const body = JSON.stringify(req) const headers: any = { @@ -539,7 +539,7 @@ const domainStages = (): SequentialDelayStage[] => [ const authenticatedDomain = ( address: string, salt: string, - _stages?: SequentialDelayStage[] + _stages?: SequentialDelayStage[], ): SequentialDelayDomain => ({ name: DomainIdentifiers.SequentialDelay, version: '1', @@ -551,7 +551,7 @@ const authenticatedDomain = ( const quotaRequest = async ( wallet: LocalWallet, address: string, - salt: string + salt: string, ): Promise> => { const req: DomainQuotaStatusRequest = { type: DomainRequestTypeTag.QUOTA, @@ -563,7 +563,7 @@ const quotaRequest = async ( sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(address, domainQuotaStatusRequestEIP712(req)) + await wallet.signTypedData(address, domainQuotaStatusRequestEIP712(req)), ) return req } @@ -571,7 +571,7 @@ const quotaRequest = async ( const disableRequest = async ( wallet: LocalWallet, address: string, - salt: string + salt: string, ): Promise> => { const req: DisableDomainRequest = { type: DomainRequestTypeTag.DISABLE, @@ -583,7 +583,7 @@ const disableRequest = async ( sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(address, disableDomainRequestEIP712(req)) + await wallet.signTypedData(address, disableDomainRequestEIP712(req)), ) return req } @@ -593,14 +593,14 @@ const signatureRequest = async ( address: string, salt: string, _domain?: SequentialDelayDomain, - _nonce?: number + _nonce?: number, ): Promise<[DomainRestrictedSignatureRequest, ThresholdPoprfClient]> => { const domain = _domain ?? authenticatedDomain(address, salt) const thresholdPoprfClient = new ThresholdPoprfClient( Buffer.from(contextSpecificParams.domainsPubKey, 'base64'), Buffer.from(contextSpecificParams.domainsPolynomial, 'hex'), domainHash(domain), - Buffer.from('test message', 'utf8') + Buffer.from('test message', 'utf8'), ) const req: DomainRestrictedSignatureRequest = { @@ -614,7 +614,7 @@ const signatureRequest = async ( sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(address, domainRestrictedSignatureRequestEIP712(req)) + await wallet.signTypedData(address, domainRestrictedSignatureRequestEIP712(req)), ) return [req, thresholdPoprfClient] } diff --git a/apps/signer/test/end-to-end/pnp.test.ts b/apps/signer/test/end-to-end/pnp.test.ts index 8be4b6f10..b7222cab5 100644 --- a/apps/signer/test/end-to-end/pnp.test.ts +++ b/apps/signer/test/end-to-end/pnp.test.ts @@ -207,7 +207,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) await sendCUSDToOdisPayments(singleQueryCost, ACCOUNT_ADDRESS2, ACCOUNT_ADDRESS2) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY2) @@ -227,8 +227,8 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { threshold_bls.partialVerifyBlindSignature( Buffer.from(contextSpecificParams.pnpPolynomial, 'hex'), Buffer.from(blindedMessage, 'base64'), - Buffer.from(resBody.signature, 'base64') - ) + Buffer.from(resBody.signature, 'base64'), + ), ) }) @@ -241,7 +241,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) await sendCUSDToOdisPayments(singleQueryCost, ACCOUNT_ADDRESS2, ACCOUNT_ADDRESS2) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY2) @@ -261,8 +261,8 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { threshold_bls.partialVerifyBlindSignature( Buffer.from(contextSpecificParams.pnpPolynomial, 'hex'), Buffer.from(blindedMessage, 'base64'), - Buffer.from(resBody.signature, 'base64') - ) + Buffer.from(resBody.signature, 'base64'), + ), ) }) @@ -272,7 +272,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY2) const res = await queryPnpSignEndpoint(req, authorization) @@ -291,8 +291,8 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { threshold_bls.partialVerifyBlindSignature( Buffer.from(contextSpecificParams.pnpPolynomial, 'hex'), Buffer.from(blindedMessage, 'base64'), - Buffer.from(resBody.signature, 'base64') - ) + Buffer.from(resBody.signature, 'base64'), + ), ) await sleep(5 * 1000) // sleep for cache ttl @@ -318,7 +318,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) // @ts-ignore Intentionally deleting required field delete badRequest.blindedQueryPhoneNumber @@ -337,7 +337,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await queryPnpSignEndpoint(badRequest, authorization, 'asd') @@ -354,7 +354,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS2, PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await queryPnpSignEndpoint(badRequest, authorization) @@ -371,7 +371,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( '0xnotanaddress', blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await queryPnpSignEndpoint(badRequest, authorization) @@ -388,7 +388,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await queryPnpSignEndpoint(badRequest, authorization) @@ -406,7 +406,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS2, blindedMessage, - AuthenticationMethod.ENCRYPTION_KEY + AuthenticationMethod.ENCRYPTION_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY2) const res = await queryPnpSignEndpoint(badRequest, authorization) @@ -423,7 +423,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, blindedMessage, - AuthenticationMethod.ENCRYPTION_KEY + AuthenticationMethod.ENCRYPTION_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await queryPnpSignEndpoint(badRequest, authorization) @@ -464,7 +464,7 @@ describe(`Running against service deployed at ${ODIS_SIGNER_URL}`, () => { async function queryPnpQuotaEndpoint( req: PnpQuotaRequest, - authorization: string + authorization: string, ): Promise { const body = JSON.stringify(req) return fetch(ODIS_SIGNER_URL + SignerEndpoint.PNP_QUOTA, { @@ -481,7 +481,7 @@ async function queryPnpQuotaEndpoint( async function queryPnpSignEndpoint( req: SignMessageRequest, authorization: string, - keyVersion?: string + keyVersion?: string, ): Promise { const body = JSON.stringify(req) const headers: any = { @@ -503,7 +503,7 @@ async function queryPnpSignEndpoint( async function sendCUSDToOdisPayments( amountInWei: string | number, recipient: string, - sender: string + sender: string, ) { const stableToken = await kit.contracts.getStableToken(StableToken.cUSD) const odisPayments = await kit.contracts.getOdisPayments() diff --git a/apps/signer/test/integration/domain.test.ts b/apps/signer/test/integration/domain.test.ts index b9141f14f..e6941eacb 100644 --- a/apps/signer/test/integration/domain.test.ts +++ b/apps/signer/test/integration/domain.test.ts @@ -62,14 +62,14 @@ describe('domain', () => { const signatureRequest = async ( _domain?: SequentialDelayDomain, _nonce?: number, - keyVersion: number = config.keystore.keys.domains.latest + keyVersion: number = config.keystore.keys.domains.latest, ): Promise<[DomainRestrictedSignatureRequest, ThresholdPoprfClient]> => { const domain = _domain ?? authenticatedDomain() const thresholdPoprfClient = new ThresholdPoprfClient( Buffer.from(TestUtils.Values.DOMAINS_THRESHOLD_DEV_PUBKEYS[keyVersion - 1], 'base64'), Buffer.from(TestUtils.Values.DOMAINS_THRESHOLD_DEV_POLYNOMIALS[keyVersion - 1], 'hex'), domainHash(domain), - Buffer.from('test message', 'utf8') + Buffer.from('test message', 'utf8'), ) const req: DomainRestrictedSignatureRequest = { @@ -83,7 +83,7 @@ describe('domain', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)), ) return [req, thresholdPoprfClient] } @@ -99,7 +99,7 @@ describe('domain', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainQuotaStatusRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainQuotaStatusRequestEIP712(req)), ) return req } @@ -116,7 +116,7 @@ describe('domain', () => { sessionID: defined(genSessionID()), } req.options.signature = defined( - await wallet.signTypedData(walletAddress, disableDomainRequestEIP712(req)) + await wallet.signTypedData(walletAddress, disableDomainRequestEIP712(req)), ) return req } @@ -313,14 +313,14 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'insertDomainStateRecord' + 'insertDomainStateRecord', ) .mockImplementationOnce(() => { // Handle errors in the same way as in insertDomainStateRecord countAndThrowDBError( new Error(), rootLogger(_config.serviceName), - ErrorMessage.DATABASE_INSERT_FAILURE + ErrorMessage.DATABASE_INSERT_FAILURE, ) }) const res = await request(app).post(SignerEndpoint.DISABLE_DOMAIN).send(req) @@ -332,7 +332,7 @@ describe('domain', () => { error: ErrorMessage.DATABASE_INSERT_FAILURE, }) expect(await getDomainStateRecord(db, req.domain, rootLogger(_config.serviceName))).toBe( - null + null, ) }) @@ -348,7 +348,7 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'getDomainStateRecord' + 'getDomainStateRecord', ) .mockImplementationOnce(async () => { await new Promise((resolve) => setTimeout(resolve, testTimeoutMS + delay)) @@ -520,13 +520,13 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'getDomainStateRecordOrEmpty' + 'getDomainStateRecordOrEmpty', ) .mockImplementationOnce(() => { countAndThrowDBError( new Error(), rootLogger(_config.serviceName), - ErrorMessage.DATABASE_GET_FAILURE + ErrorMessage.DATABASE_GET_FAILURE, ) }) const res = await request(app).post(SignerEndpoint.DOMAIN_QUOTA_STATUS).send(req) @@ -538,7 +538,7 @@ describe('domain', () => { error: ErrorMessage.DATABASE_GET_FAILURE, }) expect(await getDomainStateRecord(db, req.domain, rootLogger(_config.serviceName))).toBe( - null + null, ) }) }) @@ -555,7 +555,7 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'getDomainStateRecordOrEmpty' + 'getDomainStateRecordOrEmpty', ) .mockImplementationOnce(async () => { await new Promise((resolve) => setTimeout(resolve, testTimeoutMS + delay)) @@ -605,7 +605,7 @@ describe('domain', () => { }, }) const evaluation = thresholdPoprfClient.unblindPartialResponse( - Buffer.from(res.body.signature, 'base64') + Buffer.from(res.body.signature, 'base64'), ) expect(evaluation.toString('base64')).toEqual(expectedEval) expect(res.get(KEY_VERSION_HEADER)).toEqual(_config.keystore.keys.domains.latest.toString()) @@ -633,7 +633,7 @@ describe('domain', () => { }, }) const evaluation = thresholdPoprfClient.unblindPartialResponse( - Buffer.from(res.body.signature, 'base64') + Buffer.from(res.body.signature, 'base64'), ) expect(evaluation.toString('base64')).toEqual(expectedEvals[i - 1]) expect(res.get(KEY_VERSION_HEADER)).toEqual(i.toString()) @@ -658,7 +658,7 @@ describe('domain', () => { }, }) const eval1 = thresholdPoprfClient.unblindPartialResponse( - Buffer.from(res1.body.signature, 'base64') + Buffer.from(res1.body.signature, 'base64'), ) expect(eval1.toString('base64')).toEqual(expectedEval) @@ -667,7 +667,7 @@ describe('domain', () => { // This is how req.options.signature = noString req.options.signature = defined( - await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)) + await wallet.signTypedData(walletAddress, domainRestrictedSignatureRequestEIP712(req)), ) const res2 = await request(app).post(SignerEndpoint.DOMAIN_SIGN).send(req) expect(res2.status).toBe(200) @@ -683,7 +683,7 @@ describe('domain', () => { }, }) const eval2 = thresholdPoprfClient.unblindPartialResponse( - Buffer.from(res2.body.signature, 'base64') + Buffer.from(res2.body.signature, 'base64'), ) expect(eval2).toEqual(eval1) }) @@ -704,7 +704,7 @@ describe('domain', () => { }, }) const evaluation = thresholdPoprfClient.unblindPartialResponse( - Buffer.from(res.body.signature, 'base64') + Buffer.from(res.body.signature, 'base64'), ) expect(evaluation.toString('base64')).toEqual(expectedEval) }) @@ -729,7 +729,7 @@ describe('domain', () => { }, }) const evaluation = thresholdPoprfClient.unblindPartialResponse( - Buffer.from(res.body.signature, 'base64') + Buffer.from(res.body.signature, 'base64'), ) expect(evaluation.toString('base64')).toEqual(expectedEval) }) @@ -948,13 +948,13 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'getDomainStateRecordOrEmpty' + 'getDomainStateRecordOrEmpty', ) .mockImplementationOnce(() => { countAndThrowDBError( new Error(), rootLogger(_config.serviceName), - ErrorMessage.DATABASE_GET_FAILURE + ErrorMessage.DATABASE_GET_FAILURE, ) }) const res = await request(app).post(SignerEndpoint.DOMAIN_SIGN).send(req) @@ -966,7 +966,7 @@ describe('domain', () => { error: ErrorMessage.DATABASE_GET_FAILURE, }) expect(await getDomainStateRecord(db, req.domain, rootLogger(_config.serviceName))).toBe( - null + null, ) }) @@ -978,13 +978,13 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'updateDomainStateRecord' + 'updateDomainStateRecord', ) .mockImplementationOnce(() => { countAndThrowDBError( new Error(), rootLogger(_config.serviceName), - ErrorMessage.DATABASE_UPDATE_FAILURE + ErrorMessage.DATABASE_UPDATE_FAILURE, ) }) const res = await request(app).post(SignerEndpoint.DOMAIN_SIGN).send(req) @@ -996,7 +996,7 @@ describe('domain', () => { error: ErrorMessage.DATABASE_UPDATE_FAILURE, }) expect(await getDomainStateRecord(db, req.domain, rootLogger(_config.serviceName))).toBe( - null + null, ) }) @@ -1008,7 +1008,7 @@ describe('domain', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/domain-state'), - 'getDomainStateRecordOrEmpty' + 'getDomainStateRecordOrEmpty', ) .mockImplementationOnce(async () => { await new Promise((resolve) => setTimeout(resolve, testTimeoutMS + delay)) diff --git a/apps/signer/test/integration/pnp.test.ts b/apps/signer/test/integration/pnp.test.ts index 87b7b15d4..ae8dfd121 100644 --- a/apps/signer/test/integration/pnp.test.ts +++ b/apps/signer/test/integration/pnp.test.ts @@ -52,7 +52,7 @@ const mockGetDataEncryptionKey = jest.fn() const mockContractKit = createMockContractKit({ [ContractRetrieval.getAccounts]: createMockAccounts( mockGetWalletAddress, - mockGetDataEncryptionKey + mockGetDataEncryptionKey, ), [ContractRetrieval.getOdisPayments]: createMockOdisPayments(mockOdisPaymentsTotalPaidCUSD), }) @@ -118,7 +118,7 @@ describe('pnp', () => { authorization: string, endpoint: SignerEndpoint, keyVersionHeader?: string, - signerApp: any = app + signerApp: any = app, ) => { const _req = request(signerApp).post(endpoint).set('Authorization', authorization) @@ -320,7 +320,7 @@ describe('pnp', () => { configWithApiDisabled, db, keyProvider, - newKit('dummyKit') + newKit('dummyKit'), ) const req = getPnpQuotaRequest(ACCOUNT_ADDRESS1) @@ -330,7 +330,7 @@ describe('pnp', () => { authorization, SignerEndpoint.PNP_QUOTA, undefined, - appWithApiDisabled + appWithApiDisabled, ) expect(res.status).toBe(503) expect(res.body).toStrictEqual({ @@ -345,7 +345,7 @@ describe('pnp', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/account'), - 'getPerformedQueryCount' + 'getPerformedQueryCount', ) .mockRejectedValueOnce(new Error()) @@ -385,7 +385,7 @@ describe('pnp', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/account'), - 'getPerformedQueryCount' + 'getPerformedQueryCount', ) .mockImplementation(async () => { await new Promise((resolve) => setTimeout(resolve, testTimeoutMS + delay)) @@ -398,7 +398,7 @@ describe('pnp', () => { configWithShortTimeout, db, keyProvider, - newKit('dummyKit') + newKit('dummyKit'), ) const req = getPnpQuotaRequest(ACCOUNT_ADDRESS1) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) @@ -407,7 +407,7 @@ describe('pnp', () => { authorization, SignerEndpoint.PNP_QUOTA, undefined, - appWithShortTimeout + appWithShortTimeout, ) // Ensure that this is restored before test can fail on assertions // to prevent failures in other tests @@ -435,7 +435,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -483,7 +483,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -497,7 +497,7 @@ describe('pnp', () => { warnings: [], }) expect(res.get(KEY_VERSION_HEADER)).toEqual( - _config.keystore.keys.phoneNumberPrivacy.latest.toString() + _config.keystore.keys.phoneNumberPrivacy.latest.toString(), ) }) @@ -505,7 +505,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.ENCRYPTION_KEY + AuthenticationMethod.ENCRYPTION_KEY, ) const authorization = getPnpRequestAuthorization(req, DEK_PRIVATE_KEY) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -525,7 +525,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN, i.toString()) @@ -547,7 +547,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res1 = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -565,7 +565,7 @@ describe('pnp', () => { db, req.account, req.blindedQueryPhoneNumber, - logger + logger, ) expect(requestDbRecord).toEqual({ blinded_query: req.blindedQueryPhoneNumber, @@ -584,7 +584,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) // @ts-ignore Intentionally adding an extra field to the request type req.extraField = 'dummyString' @@ -605,7 +605,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) // @ts-ignore Intentionally deleting required field delete badRequest.account @@ -623,7 +623,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await sendRequest(badRequest, authorization, SignerEndpoint.PNP_SIGN, 'a') @@ -639,7 +639,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, '+1234567890', - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await sendRequest(badRequest, authorization, SignerEndpoint.PNP_SIGN) @@ -655,7 +655,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( '0xnotanaddress', BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await sendRequest(badRequest, authorization, SignerEndpoint.PNP_SIGN) @@ -671,7 +671,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const differentPk = '0x00000000000000000000000000000000000000000000000000000000ddddbbbb' const authorization = getPnpRequestAuthorization(badRequest, differentPk) @@ -688,7 +688,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.ENCRYPTION_KEY + AuthenticationMethod.ENCRYPTION_KEY, ) const differentPk = '0x00000000000000000000000000000000000000000000000000000000ddddbbbb' const authorization = getPnpRequestAuthorization(badRequest, differentPk) @@ -712,7 +712,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -731,14 +731,14 @@ describe('pnp', () => { const spy = jest // for convenience so we don't have to refactor or reset the db just for this test .spyOn( jest.requireActual('../../src/common/database/wrappers/account'), - 'getPerformedQueryCount' + 'getPerformedQueryCount', ) .mockResolvedValueOnce(0) const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -765,7 +765,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -783,7 +783,7 @@ describe('pnp', () => { const badRequest = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(badRequest, PRIVATE_KEY1) const res = await sendRequest(badRequest, authorization, SignerEndpoint.PNP_SIGN, '4') @@ -804,13 +804,13 @@ describe('pnp', () => { configWithApiDisabled, db, keyProvider, - newKit('dummyKit') + newKit('dummyKit'), ) const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest( @@ -818,7 +818,7 @@ describe('pnp', () => { authorization, SignerEndpoint.PNP_SIGN, '1', - appWithApiDisabled + appWithApiDisabled, ) expect(res.status).toBe(503) expect(res.body).toStrictEqual({ @@ -839,26 +839,26 @@ describe('pnp', () => { ACCOUNT_ADDRESS1, rootLogger(_config.serviceName), - trx + trx, ) } }) // sanity check expect( - await getPerformedQueryCount(db, ACCOUNT_ADDRESS1, rootLogger(_config.serviceName)) + await getPerformedQueryCount(db, ACCOUNT_ADDRESS1, rootLogger(_config.serviceName)), ).toBe(expectedQuota) const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/account'), - 'getPerformedQueryCount' + 'getPerformedQueryCount', ) .mockRejectedValueOnce(new Error()) const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -879,7 +879,7 @@ describe('pnp', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/account'), - 'getPerformedQueryCount' + 'getPerformedQueryCount', ) .mockImplementationOnce(async () => { await new Promise((resolve) => setTimeout(resolve, testTimeoutMS + delay)) @@ -892,13 +892,13 @@ describe('pnp', () => { configWithShortTimeout, db, keyProvider, - newKit('dummyKit') + newKit('dummyKit'), ) const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest( @@ -906,7 +906,7 @@ describe('pnp', () => { authorization, SignerEndpoint.PNP_SIGN, undefined, - appWithShortTimeout + appWithShortTimeout, ) expect(res.status).toBe(500) @@ -926,7 +926,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const configWithFailOpenDisabled: typeof _config = JSON.parse(JSON.stringify(_config)) @@ -934,7 +934,7 @@ describe('pnp', () => { configWithFailOpenDisabled, db, keyProvider, - newKit('dummyKit') + newKit('dummyKit'), ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) @@ -943,7 +943,7 @@ describe('pnp', () => { authorization, SignerEndpoint.PNP_SIGN, '1', - appWithFailOpenDisabled + appWithFailOpenDisabled, ) expect(res.status).toBe(500) @@ -959,7 +959,7 @@ describe('pnp', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/account'), - 'incrementQueryCount' + 'incrementQueryCount', ) .mockImplementationOnce(() => { countAndThrowDBError(new Error(), logger, ErrorMessage.DATABASE_UPDATE_FAILURE) @@ -968,7 +968,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -984,10 +984,10 @@ describe('pnp', () => { // check DB state: performedQueryCount was not incremented and request was not stored expect(await getPerformedQueryCount(db, ACCOUNT_ADDRESS1, logger)).toBe( - performedQueryCount + performedQueryCount, ) expect( - await getRequestIfExists(db, req.account, req.blindedQueryPhoneNumber, logger) + await getRequestIfExists(db, req.account, req.blindedQueryPhoneNumber, logger), ).toBe(undefined) }) @@ -996,7 +996,7 @@ describe('pnp', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/database/wrappers/request'), - 'insertRequest' + 'insertRequest', ) .mockImplementationOnce(() => { countAndThrowDBError(new Error(), logger, ErrorMessage.DATABASE_INSERT_FAILURE) @@ -1005,7 +1005,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -1020,10 +1020,10 @@ describe('pnp', () => { // check DB state: performedQueryCount was not incremented and request was not stored expect(await getPerformedQueryCount(db, ACCOUNT_ADDRESS1, logger)).toBe( - performedQueryCount + performedQueryCount, ) expect( - await getRequestIfExists(db, req.account, req.blindedQueryPhoneNumber, logger) + await getRequestIfExists(db, req.account, req.blindedQueryPhoneNumber, logger), ).toBe(undefined) }) @@ -1037,7 +1037,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -1059,16 +1059,16 @@ describe('pnp', () => { db, ACCOUNT_ADDRESS1, - rootLogger(_config.serviceName) - ) + rootLogger(_config.serviceName), + ), ).toBe(performedQueryCount) expect( await getRequestIfExists( db, req.account, req.blindedQueryPhoneNumber, - rootLogger(_config.serviceName) - ) + rootLogger(_config.serviceName), + ), ).toBe(undefined) }) @@ -1076,7 +1076,7 @@ describe('pnp', () => { const spy = jest .spyOn( jest.requireActual('../../src/common/bls/bls-cryptography-client'), - 'computeBlindedSignature' + 'computeBlindedSignature', ) .mockImplementationOnce(() => { // Trigger a generic error in .sign to trigger the default error returned. @@ -1086,7 +1086,7 @@ describe('pnp', () => { const req = getPnpSignRequest( ACCOUNT_ADDRESS1, BLINDED_PHONE_NUMBER, - AuthenticationMethod.WALLET_KEY + AuthenticationMethod.WALLET_KEY, ) const authorization = getPnpRequestAuthorization(req, PRIVATE_KEY1) const res = await sendRequest(req, authorization, SignerEndpoint.PNP_SIGN) @@ -1104,7 +1104,7 @@ describe('pnp', () => { // check DB state: performedQueryCount was not incremented and request was not stored expect( - await getPerformedQueryCount(db, ACCOUNT_ADDRESS1, rootLogger(config.serviceName)) + await getPerformedQueryCount(db, ACCOUNT_ADDRESS1, rootLogger(config.serviceName)), ).toBe(performedQueryCount) expect( await getRequestIfExists( @@ -1112,8 +1112,8 @@ describe('pnp', () => { req.account, req.blindedQueryPhoneNumber, - rootLogger(config.serviceName) - ) + rootLogger(config.serviceName), + ), ).toBe(undefined) }) }) diff --git a/apps/signer/test/signing/bls-signature.test.ts b/apps/signer/test/signing/bls-signature.test.ts index 779fbd635..6e5030ffe 100644 --- a/apps/signer/test/signing/bls-signature.test.ts +++ b/apps/signer/test/signing/bls-signature.test.ts @@ -17,24 +17,24 @@ describe(`BLS service computes signature`, () => { const actual = computeBlindedSignature( blindedMsg, TestUtils.Values.PNP_DEV_SIGNER_PRIVATE_KEY, - rootLogger(config.serviceName) + rootLogger(config.serviceName), ) expect(actual).toEqual( - 'MAAAAAAAAADDilSaA/xvbtE4NV3agMzHIf8PGPQ83Cu8gQy5E2mRWyUIges8bjE4EBe1L7pcY4AAAAAA' + 'MAAAAAAAAADDilSaA/xvbtE4NV3agMzHIf8PGPQ83Cu8gQy5E2mRWyUIges8bjE4EBe1L7pcY4AAAAAA', ) expect( threshold_bls.partialVerifyBlindSignature( Buffer.from(TestUtils.Values.PNP_DEV_ODIS_POLYNOMIAL, 'hex'), blindedMsgResult.message, - Buffer.from(actual, 'base64') - ) + Buffer.from(actual, 'base64'), + ), ) const combinedSignature = threshold_bls.combine(1, Buffer.from(actual, 'base64')) const unblindedSignedMessage = threshold_bls.unblind( combinedSignature, - blindedMsgResult.blindingFactor + blindedMsgResult.blindingFactor, ) const publicKey = Buffer.from(TestUtils.Values.PNP_DEV_ODIS_PUBLIC_KEY, 'base64') expect(threshold_bls.verify(publicKey, message, unblindedSignedMessage)) @@ -48,8 +48,8 @@ describe(`BLS service computes signature`, () => { computeBlindedSignature( blindedMsg, TestUtils.Values.PNP_DEV_SIGNER_PRIVATE_KEY, - rootLogger(config.serviceName) - ) + rootLogger(config.serviceName), + ), ).toThrow() }) }) diff --git a/docs/examples/blinding/webBlindingClient.ts b/docs/examples/blinding/webBlindingClient.ts index 83d463dc5..d1de49083 100644 --- a/docs/examples/blinding/webBlindingClient.ts +++ b/docs/examples/blinding/webBlindingClient.ts @@ -26,7 +26,7 @@ export class WebBlsBlindingClient implements BlsBlindingClient { const userSeed = seed ?? randomBytes(32) if (!seed) { console.warn( - 'Warning: Use a private deterministic seed (e.g. DEK private key) to preserve user quota when requests are replayed.' + 'Warning: Use a private deterministic seed (e.g. DEK private key) to preserve user quota when requests are replayed.', ) } this.rawMessage = Buffer.from(base64PhoneNumber, 'base64') @@ -43,7 +43,7 @@ export class WebBlsBlindingClient implements BlsBlindingClient { const blindedSignature = Buffer.from(base64BlindSig, 'base64') const unblindMessage = await thresholdBls.unblind( blindedSignature, - this.blindedValue.blindingFactor + this.blindedValue.blindingFactor, ) // this throws on error await thresholdBls.verify(this.odisPubKey, this.rawMessage, unblindMessage) diff --git a/docs/examples/contractKit.ts b/docs/examples/contractKit.ts index 4cb870d3a..90840a290 100644 --- a/docs/examples/contractKit.ts +++ b/docs/examples/contractKit.ts @@ -32,7 +32,7 @@ class ASv2 { OdisUtils.Identifier.IdentifierPrefix.PHONE_NUMBER, this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) const federatedAttestationsContract = await this.kit.contracts.getFederatedAttestations() @@ -50,7 +50,7 @@ class ASv2 { OdisUtils.Identifier.IdentifierPrefix.PHONE_NUMBER, this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) const federatedAttestationsContract = await this.kit.contracts.getFederatedAttestations() @@ -58,7 +58,7 @@ class ASv2 { // query on-chain mappings const attestations = await federatedAttestationsContract.lookupAttestations( obfuscatedIdentifier, - [this.issuer.address] + [this.issuer.address], ) return attestations.accounts @@ -69,7 +69,7 @@ class ASv2 { const { remainingQuota } = await OdisUtils.Quota.getPnpQuotaStatus( this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) console.log('remaining ODIS quota', remainingQuota) @@ -80,7 +80,7 @@ class ASv2 { // give odis payment contract permission to use cUSD const currentAllowance = await stableTokenContract.allowance( this.issuer.address, - odisPaymentsContract.address + odisPaymentsContract.address, ) console.log('current allowance:', currentAllowance.toString()) let enoughAllowance: boolean = false diff --git a/docs/examples/ethers.ts b/docs/examples/ethers.ts index 515bf1d72..5bcef3cc1 100644 --- a/docs/examples/ethers.ts +++ b/docs/examples/ethers.ts @@ -38,17 +38,17 @@ class ASv2 { federatedAttestationsContract = new ethers.Contract( FA_PROXY_ADDRESS, FA_CONTRACT.abi, - this.issuer + this.issuer, ) odisPaymentsContract = new ethers.Contract( ODIS_PAYMENTS_PROXY_ADDRESS, ODIS_PAYMENTS_CONTRACT.abi, - this.issuer + this.issuer, ) stableTokenContract = new ethers.Contract( ALFAJORES_CUSD_ADDRESS, STABLE_TOKEN_CONTRACT.abi, - this.issuer + this.issuer, ) constructor() { @@ -65,7 +65,7 @@ class ASv2 { OdisUtils.Identifier.IdentifierPrefix.PHONE_NUMBER, this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) ).obfuscatedIdentifier @@ -73,7 +73,7 @@ class ASv2 { await this.federatedAttestationsContract.registerAttestationAsIssuer( obfuscatedIdentifier, account, - NOW_TIMESTAMP + NOW_TIMESTAMP, ) } @@ -85,14 +85,14 @@ class ASv2 { OdisUtils.Identifier.IdentifierPrefix.PHONE_NUMBER, this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) ).obfuscatedIdentifier // query onchain mappings const attestations = await this.federatedAttestationsContract.lookupAttestations( obfuscatedIdentifier, - [this.issuer.address] + [this.issuer.address], ) return attestations.accounts @@ -103,7 +103,7 @@ class ASv2 { const { remainingQuota } = await OdisUtils.Quota.getPnpQuotaStatus( this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) console.log('remaining ODIS quota', remainingQuota) @@ -111,7 +111,7 @@ class ASv2 { // give odis payment contract permission to use cUSD const currentAllowance = await this.stableTokenContract.allowance( this.issuer.address, - this.odisPaymentsContract.address + this.odisPaymentsContract.address, ) console.log('current allowance:', currentAllowance.toString()) let enoughAllowance: boolean = false diff --git a/docs/examples/web3.ts b/docs/examples/web3.ts index ef282dbe2..023fbb39d 100644 --- a/docs/examples/web3.ts +++ b/docs/examples/web3.ts @@ -32,11 +32,11 @@ class ASv2 { federatedAttestationsContract = new this.web3.eth.Contract(FA_CONTRACT.abi, FA_PROXY_ADDRESS) odisPaymentsContract = new this.web3.eth.Contract( ODIS_PAYMENTS_CONTRACT.abi, - ODIS_PAYMENTS_PROXY_ADDRESS + ODIS_PAYMENTS_PROXY_ADDRESS, ) stableTokenContract = new this.web3.eth.Contract( STABLE_TOKEN_CONTRACT.abi, - ALFAJORES_CUSD_ADDRESS + ALFAJORES_CUSD_ADDRESS, ) constructor() { @@ -57,7 +57,7 @@ class ASv2 { OdisUtils.Identifier.IdentifierPrefix.PHONE_NUMBER, this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) ).obfuscatedIdentifier @@ -75,7 +75,7 @@ class ASv2 { OdisUtils.Identifier.IdentifierPrefix.PHONE_NUMBER, this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) ).obfuscatedIdentifier @@ -92,7 +92,7 @@ class ASv2 { const { remainingQuota } = await OdisUtils.Quota.getPnpQuotaStatus( this.issuer.address, this.authSigner, - this.serviceContext + this.serviceContext, ) console.log('remaining ODIS quota', remainingQuota) @@ -100,7 +100,7 @@ class ASv2 { // give odis payment contract permission to use cUSD const currentAllowance = await this.stableTokenContract.methods.allowance( this.issuer.address, - this.odisPaymentsContract.options.address + this.odisPaymentsContract.options.address, ) console.log('current allowance:', currentAllowance.toString()) let enoughAllowance: boolean = false diff --git a/package.json b/package.json index 2be05c0bb..64633a894 100644 --- a/package.json +++ b/package.json @@ -56,10 +56,10 @@ "jest-circus": "^29.7.0", "jest-junit": "^14.0.1", "jest-snapshot": "^29.7.0", + "lint-staged": "^15.0.2", "patch-package": "^6.2.2", - "prettier": "^2.7.1", + "prettier": "^3.0.3", "prettier-plugin-java": "^1.6.2", - "pretty-quick": "^2.0.1", "prompt": "1.3.0", "semver": "7.5.4", "solc": "0.8.22", diff --git a/packages/common/src/domains/sequential-delay.ts b/packages/common/src/domains/sequential-delay.ts index a6d75af3a..4e44e38bd 100644 --- a/packages/common/src/domains/sequential-delay.ts +++ b/packages/common/src/domains/sequential-delay.ts @@ -196,7 +196,7 @@ interface IndexedSequentialDelayStage extends SequentialDelayStage { export const checkSequentialDelayRateLimit = ( domain: SequentialDelayDomain, attemptTime: number, - state: SequentialDelayDomainState = INITIAL_SEQUENTIAL_DELAY_DOMAIN_STATE + state: SequentialDelayDomainState = INITIAL_SEQUENTIAL_DELAY_DOMAIN_STATE, ): SequentialDelayResult => { // If the domain has been disabled, all queries are to be rejected. if (state.disabled) { @@ -239,7 +239,7 @@ export const checkSequentialDelayRateLimit = ( */ const getIndexedStage = ( domain: SequentialDelayDomain, - counter: number + counter: number, ): IndexedSequentialDelayStage | undefined => { // The attempt index marking the beginning of the current stage let start = 0 diff --git a/packages/common/src/interfaces/requests.ts b/packages/common/src/interfaces/requests.ts index da7611319..c95dc49ea 100644 --- a/packages/common/src/interfaces/requests.ts +++ b/packages/common/src/interfaces/requests.ts @@ -161,7 +161,7 @@ export type OdisRequest = DomainRequest | PhoneNum /** Parameterized schema for checking unknown input against DomainRestrictedSignatureRequest */ export function domainRestrictedSignatureRequestSchema( - domain: t.Type + domain: t.Type, ): t.Type> { // The schema defined here does most of the work, but does not guarantee consistency between the // domain and options fields. We wrap the schema below to add a consistency check. @@ -175,7 +175,7 @@ export function domainRestrictedSignatureRequestSchema> => pipe( schema.validate(unk, ctx), @@ -194,20 +194,20 @@ export function domainRestrictedSignatureRequestSchema x canary(value.domain) throw new Error('Implementation error: validated domain is not of any known type') - }) + }), ) return new t.Type, DomainRestrictedSignatureRequest>( `DomainRestrictedSignatureRequestSchema<${domain.name}>`, (unk: unknown): unk is DomainRestrictedSignatureRequest => isRight(validation(unk, [])), validation, - (req: DomainRestrictedSignatureRequest) => req + (req: DomainRestrictedSignatureRequest) => req, ) } /** Parameterized schema for checking unknown input against DomainQuotaStatusRequest */ export function domainQuotaStatusRequestSchema( - domain: t.Type + domain: t.Type, ): t.Type> { // The schema defined here does most of the work, but does not guarantee consistency between the // domain and options fields. We wrap the schema below to add a consistency check. @@ -236,20 +236,20 @@ export function domainQuotaStatusRequestSchema( const canary = (x: never) => x canary(value.domain) throw new Error('Implementation error: validated domain is not of any known type') - }) + }), ) return new t.Type, DomainQuotaStatusRequest>( `DomainQuotaStatusRequestSchema<${domain.name}>`, (unk: unknown): unk is DomainQuotaStatusRequest => isRight(validation(unk, [])), validation, - (req: DomainQuotaStatusRequest) => req + (req: DomainQuotaStatusRequest) => req, ) } /** Parameterized schema for checking unknown input against DisableDomainRequest */ export function disableDomainRequestSchema( - domain: t.Type + domain: t.Type, ): t.Type> { // The schema defined here does most of the work, but does not guarantee consistency between the // domain and options fields. We wrap the schema below to add a consistency check. @@ -278,20 +278,20 @@ export function disableDomainRequestSchema( const canary = (x: never) => x canary(value.domain) throw new Error('Implementation error: validated domain is not of any known type') - }) + }), ) return new t.Type, DisableDomainRequest>( `DisableDomainRequestSchema<${domain.name}>`, (unk: unknown): unk is DisableDomainRequest => isRight(validation(unk, [])), validation, - (req: DisableDomainRequest) => req + (req: DisableDomainRequest) => req, ) } /** Wraps the signature request as an EIP-712 typed data structure for hashing and signing */ export function domainRestrictedSignatureRequestEIP712( - request: DomainRestrictedSignatureRequest + request: DomainRestrictedSignatureRequest, ): EIP712TypedData { const domainTypes = domainEIP712Types(request.domain) const optionsTypes = domainOptionsEIP712Types(request.domain) @@ -323,7 +323,7 @@ export function domainRestrictedSignatureRequestEIP712( /** Wraps the domain quota request as an EIP-712 typed data structure for hashing and signing */ export function domainQuotaStatusRequestEIP712( - request: DomainQuotaStatusRequest + request: DomainQuotaStatusRequest, ): EIP712TypedData { const domainTypes = domainEIP712Types(request.domain) const optionsTypes = domainOptionsEIP712Types(request.domain) @@ -354,7 +354,7 @@ export function domainQuotaStatusRequestEIP712( /** Wraps the disable domain request as an EIP-712 typed data structure for hashing and signing */ export function disableDomainRequestEIP712( - request: DisableDomainRequest + request: DisableDomainRequest, ): EIP712TypedData { const domainTypes = domainEIP712Types(request.domain) const optionsTypes = domainOptionsEIP712Types(request.domain) @@ -395,7 +395,7 @@ export function disableDomainRequestEIP712( */ function verifyRequestSignature>( typedDataBuilder: (request: R) => EIP712TypedData, - request: R + request: R, ): boolean { // If the address field is undefined, then this domain is unauthenticated. // Return false as the signature cannot be checked. @@ -435,7 +435,7 @@ function verifyRequestSignature>( * to the undefined value for type EIP712Optional). */ export function verifyDomainRestrictedSignatureRequestAuthenticity( - request: DomainRestrictedSignatureRequest + request: DomainRestrictedSignatureRequest, ): boolean { return verifyRequestSignature(domainRestrictedSignatureRequestEIP712, request) } @@ -449,7 +449,7 @@ export function verifyDomainRestrictedSignatureRequestAuthenticity( * to the undefined value for type EIP712Optional). */ export function verifyDomainQuotaStatusRequestAuthenticity( - request: DomainQuotaStatusRequest + request: DomainQuotaStatusRequest, ): boolean { return verifyRequestSignature(domainQuotaStatusRequestEIP712, request) } @@ -463,7 +463,7 @@ export function verifyDomainQuotaStatusRequestAuthenticity( * to the undefined value for type EIP712Optional). */ export function verifyDisableDomainRequestAuthenticity( - request: DisableDomainRequest + request: DisableDomainRequest, ): boolean { return verifyRequestSignature(disableDomainRequestEIP712, request) } diff --git a/packages/common/src/interfaces/responses.ts b/packages/common/src/interfaces/responses.ts index 8c9c7d2b5..2e1594e59 100644 --- a/packages/common/src/interfaces/responses.ts +++ b/packages/common/src/interfaces/responses.ts @@ -170,7 +170,7 @@ export type DomainResponse< | R extends DisableDomainRequest ? DisableDomainResponse : never export function domainRestrictedSignatureResponseSchema( - state: t.Type> + state: t.Type>, ): t.Type> { return t.union([ t.type({ @@ -193,7 +193,7 @@ export function domainRestrictedSignatureResponseSchema( } export function domainQuotaStatusResponseSchema( - state: t.Type> + state: t.Type>, ): t.Type> { return t.union([ t.type({ @@ -210,7 +210,7 @@ export function domainQuotaStatusResponseSchema( } export function disableDomainResponseSchema( - state: t.Type> + state: t.Type>, ): t.Type> { return t.union([ t.type({ diff --git a/packages/common/src/poprf.ts b/packages/common/src/poprf.ts index 1988f5f8b..7540ffce2 100644 --- a/packages/common/src/poprf.ts +++ b/packages/common/src/poprf.ts @@ -70,7 +70,7 @@ export class PoprfClient { readonly publicKey: Uint8Array, readonly tag: Uint8Array, readonly message: Uint8Array, - readonly seed?: Uint8Array + readonly seed?: Uint8Array, ) { const blinded = poprf().blindMsg(message, seed ?? randomBytes(32)) @@ -131,7 +131,7 @@ export class PoprfCombiner { } return Buffer.from( - poprf().blindAggregate(this.threshold, Buffer.concat(blindedResponses.map(Buffer.from))) + poprf().blindAggregate(this.threshold, Buffer.concat(blindedResponses.map(Buffer.from))), ) } @@ -180,7 +180,7 @@ export class ThresholdPoprfClient extends PoprfClient { readonly polynomial: Uint8Array, readonly tag: Uint8Array, readonly message: Uint8Array, - readonly seed?: Uint8Array + readonly seed?: Uint8Array, ) { super(publicKey, tag, message, seed) } @@ -196,7 +196,7 @@ export class ThresholdPoprfClient extends PoprfClient { */ public unblindPartialResponse(response: Uint8Array): Buffer { return Buffer.from( - poprf().unblindPartialResp(this.polynomial, this.blindingFactor, this.tag, response) + poprf().unblindPartialResp(this.polynomial, this.blindingFactor, this.tag, response), ) } } diff --git a/packages/common/src/test/utils.ts b/packages/common/src/test/utils.ts index eea6164b7..02da7fd4e 100644 --- a/packages/common/src/test/utils.ts +++ b/packages/common/src/test/utils.ts @@ -31,7 +31,7 @@ export function createMockToken(balanceOf: jest.Mock) { export function createMockAccounts( getWalletAddress: jest.Mock, - getDataEncryptionKey: jest.Mock + getDataEncryptionKey: jest.Mock, ) { return { getWalletAddress, @@ -49,7 +49,7 @@ export function createMockOdisPayments(totalPaidCUSDFunc: jest.Mock getDataEncryptionKey( @@ -32,7 +32,7 @@ export function newContractKitFetcher( logger, fullNodeTimeoutMs, fullNodeRetryCount, - fullNodeRetryDelayMs + fullNodeRetryDelayMs, ) } @@ -44,7 +44,7 @@ export async function authenticateUser( request: Request<{}, {}, R>, logger: Logger, fetchDEK: DataEncryptionKeyFetcher, - warnings: ErrorType[] = [] + warnings: ErrorType[] = [], ): Promise { logger.debug('Authenticating user') @@ -86,7 +86,7 @@ export async function authenticateUser( // Fallback to previous signing pattern logger.info( { account: signer, message, messageSignature }, - 'Message was not authenticated with DEK, attempting to authenticate using wallet key' + 'Message was not authenticated with DEK, attempting to authenticate using wallet key', ) // TODO This uses signature utils, why doesn't DEK authentication? // (https://github.com/celo-org/celo-monorepo/issues/9803) @@ -116,7 +116,7 @@ export function verifyDEKSignature( message: string, messageSignature: string, registeredEncryptionKey: string, - logger?: Logger + logger?: Logger, ) { logger = logger ?? rootLogger(fetchEnv('SERVICE_NAME')) try { @@ -145,7 +145,7 @@ export async function getDataEncryptionKey( logger: Logger, fullNodeTimeoutMs: number, fullNodeRetryCount: number, - fullNodeRetryDelayMs: number + fullNodeRetryDelayMs: number, ): Promise { try { const res = await retryAsyncWithBackOffAndTimeout( @@ -157,7 +157,7 @@ export async function getDataEncryptionKey( [], fullNodeRetryDelayMs, 1.5, - fullNodeTimeoutMs + fullNodeTimeoutMs, ) return res } catch (error) { diff --git a/packages/common/src/utils/key-version.ts b/packages/common/src/utils/key-version.ts index de87277d4..a4666248e 100644 --- a/packages/common/src/utils/key-version.ts +++ b/packages/common/src/utils/key-version.ts @@ -12,7 +12,7 @@ export interface KeyVersionInfo { export function requestHasValidKeyVersion( request: Request<{}, {}, OdisRequest>, - logger: Logger + logger: Logger, ): boolean { try { getRequestKeyVersion(request, logger) @@ -26,7 +26,7 @@ export function requestHasValidKeyVersion( export function getRequestKeyVersion( request: Request<{}, {}, OdisRequest>, - logger: Logger + logger: Logger, ): number | undefined { const keyVersionHeader = request.headers[KEY_VERSION_HEADER] const keyVersion = parseKeyVersionFromHeader(keyVersionHeader) @@ -46,7 +46,7 @@ export function getRequestKeyVersion( export function responseHasExpectedKeyVersion( response: FetchResponse, expectedKeyVersion: number, - logger: Logger + logger: Logger, ): boolean { let responseKeyVersion try { @@ -60,7 +60,7 @@ export function responseHasExpectedKeyVersion( if (responseKeyVersion !== expectedKeyVersion) { logger.error( { expectedKeyVersion, responseKeyVersion }, - ErrorMessage.INVALID_KEY_VERSION_RESPONSE + ErrorMessage.INVALID_KEY_VERSION_RESPONSE, ) return false } @@ -85,7 +85,7 @@ export function getResponseKeyVersion(response: FetchResponse, logger: Logger): } function parseKeyVersionFromHeader( - keyVersionHeader: string | string[] | undefined | null + keyVersionHeader: string | string[] | undefined | null, ): number | undefined { if (keyVersionHeader === undefined || keyVersionHeader === null) { return undefined diff --git a/packages/common/src/utils/logger.ts b/packages/common/src/utils/logger.ts index 0114aebb6..e40d52056 100644 --- a/packages/common/src/utils/logger.ts +++ b/packages/common/src/utils/logger.ts @@ -37,7 +37,7 @@ export function rootLogger(serviceName: string): Logger { } export function loggerMiddleware( - serviceName: string + serviceName: string, ): (req: Request, res: Response, next?: NextFunction) => Logger { return (req, res, next) => { const requestLogger = rootLogger(serviceName).child({ diff --git a/packages/common/src/utils/responses.utils.ts b/packages/common/src/utils/responses.utils.ts index fffe55a18..970d6d471 100644 --- a/packages/common/src/utils/responses.utils.ts +++ b/packages/common/src/utils/responses.utils.ts @@ -4,7 +4,7 @@ import { OdisRequest, OdisResponse, WarningMessage } from '..' export function send< I extends OdisRequest = OdisRequest, - O extends OdisResponse = OdisResponse + O extends OdisResponse = OdisResponse, >(response: Response, body: O, status: number, logger: Logger) { if (!response.headersSent) { if (!body.success) { diff --git a/packages/common/test/poprf.test.ts b/packages/common/test/poprf.test.ts index 474d324c8..aa003c56e 100644 --- a/packages/common/test/poprf.test.ts +++ b/packages/common/test/poprf.test.ts @@ -13,7 +13,7 @@ const TEST_THRESHOLD_T = 2 const TEST_THRESHOLD_POPRF_KEYS = poprf.thresholdKeygen( TEST_THRESHOLD_N, TEST_THRESHOLD_T, - Buffer.from('TEST THRESHOLD POPRF KEYPAIR SEED') + Buffer.from('TEST THRESHOLD POPRF KEYPAIR SEED'), ) const TEST_MESSAGE_A = Buffer.from('TEST MESSAGE A') @@ -34,13 +34,13 @@ describe('PoprfClient', () => { TEST_POPRF_KEYPAIR.publicKey, TEST_TAG_A, TEST_MESSAGE_A, - TEST_BLINDING_SEED + TEST_BLINDING_SEED, ) const clientB = new PoprfClient( TEST_POPRF_KEYPAIR.publicKey, TEST_TAG_A, TEST_MESSAGE_A, - TEST_BLINDING_SEED + TEST_BLINDING_SEED, ) expect(clientA.blindedMessage).toEqual(clientB.blindedMessage) }) @@ -89,17 +89,17 @@ describe('end-to-end', () => { it('successfully completes client-server exchange with combiner', () => { const servers = [...Array(TEST_THRESHOLD_N).keys()].map( - (i) => new ThresholdPoprfServer(TEST_THRESHOLD_POPRF_KEYS.getShare(i)) + (i) => new ThresholdPoprfServer(TEST_THRESHOLD_POPRF_KEYS.getShare(i)), ) const combiner = new PoprfCombiner(TEST_THRESHOLD_T) const client = new PoprfClient( TEST_THRESHOLD_POPRF_KEYS.thresholdPublicKey, TEST_TAG_A, - TEST_MESSAGE_A + TEST_MESSAGE_A, ) const blindedPartials = servers.map((s) => - s.blindPartialEval(client.tag, client.blindedMessage) + s.blindPartialEval(client.tag, client.blindedMessage), ) const response = combiner.blindAggregate(blindedPartials) expect(response).toBeDefined() @@ -115,17 +115,17 @@ describe('end-to-end', () => { it('successfully completes client-server exchange with threshold client and server', () => { const servers = [...Array(TEST_THRESHOLD_N).keys()].map( - (i) => new ThresholdPoprfServer(TEST_THRESHOLD_POPRF_KEYS.getShare(i)) + (i) => new ThresholdPoprfServer(TEST_THRESHOLD_POPRF_KEYS.getShare(i)), ) const client = new ThresholdPoprfClient( TEST_THRESHOLD_POPRF_KEYS.thresholdPublicKey, TEST_THRESHOLD_POPRF_KEYS.polynomial, TEST_TAG_A, - TEST_MESSAGE_A + TEST_MESSAGE_A, ) const blindedPartials = servers.map((s) => - s.blindPartialEval(client.tag, client.blindedMessage) + s.blindPartialEval(client.tag, client.blindedMessage), ) const partials = blindedPartials.map((r) => client.unblindPartialResponse(r)) expect(partials.map((p) => p.toString('base64'))).toEqual([ diff --git a/packages/common/test/utils/key-version.test.ts b/packages/common/test/utils/key-version.test.ts index 46db29d71..fa5c79732 100644 --- a/packages/common/test/utils/key-version.test.ts +++ b/packages/common/test/utils/key-version.test.ts @@ -80,7 +80,7 @@ describe('key version test suite', () => { it(`Should throw for invalid key version ${kv}`, () => { request.headers[KEY_VERSION_HEADER] = kv.toString() expect(() => getRequestKeyVersion(request, logger)).toThrow( - WarningMessage.INVALID_KEY_VERSION_REQUEST + WarningMessage.INVALID_KEY_VERSION_REQUEST, ) }) }) @@ -172,7 +172,7 @@ describe('key version test suite', () => { it(`Should throw for invalid key version ${kv}`, () => { response.headers.set(KEY_VERSION_HEADER, kv.toString()) expect(() => getResponseKeyVersion(response, logger)).toThrow( - ErrorMessage.INVALID_KEY_VERSION_RESPONSE + ErrorMessage.INVALID_KEY_VERSION_RESPONSE, ) }) }) diff --git a/packages/encrypted-backup/src/backup.ts b/packages/encrypted-backup/src/backup.ts index 7ee6f445e..b68aa6ece 100644 --- a/packages/encrypted-backup/src/backup.ts +++ b/packages/encrypted-backup/src/backup.ts @@ -256,7 +256,7 @@ export async function createBackup({ // Safety measure to prevent users from accidentally using this API without any hardening. if (hardening.odis === undefined && hardening.computational === undefined) { return Err( - new UsageError(new Error('createBackup cannot be used with a empty hardening config')) + new UsageError(new Error('createBackup cannot be used with a empty hardening config')), ) } @@ -326,7 +326,7 @@ export async function createBackup({ updatedKey, domain, hardening.odis.environment, - authorizer.wallet + authorizer.wallet, ) if (!odisHardening.ok) { return Err(odisHardening.error) @@ -410,15 +410,17 @@ export async function openBackup({ if (backup.environment?.circuitBreaker === undefined) { return Err( new InvalidBackupError( - new Error('encrypted fuse key is provided but no circuit breaker environment is provided') - ) + new Error( + 'encrypted fuse key is provided but no circuit breaker environment is provided', + ), + ), ) } const circuitBreakerClient = new CircuitBreakerClient(backup.environment.circuitBreaker) debug( 'requesting the circuit breaker service unwrap the encrypted circuit breaker key', - backup.environment.circuitBreaker + backup.environment.circuitBreaker, ) const unwrap = await circuitBreakerClient.unwrapKey(backup.encryptedFuseKey) if (!unwrap.ok) { @@ -446,16 +448,16 @@ export async function openBackup({ return Err( new InvalidBackupError( new Error( - 'domain query authorizer address is provided but is not derived from the backup nonce' - ) - ) + 'domain query authorizer address is provided but is not derived from the backup nonce', + ), + ), ) } if (backup.environment?.odis === undefined) { return Err( new InvalidBackupError( - new Error('ODIS domain is provided by no ODIS environment information') - ) + new Error('ODIS domain is provided by no ODIS environment information'), + ), ) } @@ -464,7 +466,7 @@ export async function openBackup({ updatedKey, domain, backup.environment.odis, - authorizer.wallet + authorizer.wallet, ) if (!odisHardening.ok) { return Err(odisHardening.error) @@ -479,7 +481,7 @@ export async function openBackup({ debug('hardening user key with computational function', backup.computationalHardening) const computationalHardening = await computationalHardenKey( updatedKey, - backup.computationalHardening + backup.computationalHardening, ) if (!computationalHardening.ok) { return Err(computationalHardening.error) diff --git a/packages/encrypted-backup/src/errors.ts b/packages/encrypted-backup/src/errors.ts index 9a348e92f..a36bcfbcf 100644 --- a/packages/encrypted-backup/src/errors.ts +++ b/packages/encrypted-backup/src/errors.ts @@ -54,13 +54,19 @@ export class InvalidBackupError extends RootError { - constructor(readonly error?: Error, readonly version?: string) { + constructor( + readonly error?: Error, + readonly version?: string, + ) { super(BackupErrorTypes.ODIS_SERVICE_ERROR) } } export class OdisRateLimitingError extends RootError { - constructor(readonly notBefore?: number, readonly error?: Error) { + constructor( + readonly notBefore?: number, + readonly error?: Error, + ) { super(BackupErrorTypes.ODIS_RATE_LIMITING_ERROR) } } @@ -72,13 +78,19 @@ export class OdisVerificationError extends RootError { - constructor(readonly iterations: number, readonly error?: Error) { + constructor( + readonly iterations: number, + readonly error?: Error, + ) { super(BackupErrorTypes.PBKDF_ERROR) } } export class ScryptError extends RootError { - constructor(readonly options: ScryptOptions, readonly error?: Error) { + constructor( + readonly options: ScryptOptions, + readonly error?: Error, + ) { super(BackupErrorTypes.SCRYPT_ERROR) } } diff --git a/packages/encrypted-backup/src/odis.mock.ts b/packages/encrypted-backup/src/odis.mock.ts index 141644918..4f969c24f 100644 --- a/packages/encrypted-backup/src/odis.mock.ts +++ b/packages/encrypted-backup/src/odis.mock.ts @@ -152,11 +152,11 @@ export class MockOdis { override ?? ((url: string, req: { body: string }) => { const res = this.quota( - JSON.parse(req.body) as DomainQuotaStatusRequest + JSON.parse(req.body) as DomainQuotaStatusRequest, ) debug('Mocking request', JSON.stringify({ url, req, res })) return res - }) + }), ) } @@ -169,11 +169,11 @@ export class MockOdis { override ?? ((url: string, req: { body: string }) => { const res = this.sign( - JSON.parse(req.body) as DomainRestrictedSignatureRequest + JSON.parse(req.body) as DomainRestrictedSignatureRequest, ) debug('Mocking request', JSON.stringify({ url, req, res })) return res - }) + }), ) } diff --git a/packages/encrypted-backup/src/odis.ts b/packages/encrypted-backup/src/odis.ts index e7630ebf7..5fead1759 100644 --- a/packages/encrypted-backup/src/odis.ts +++ b/packages/encrypted-backup/src/odis.ts @@ -50,7 +50,7 @@ import { deriveKey, EIP712Wallet, KDFInfo } from './utils' export function buildOdisDomain( config: OdisHardeningConfig, authorizer: Address, - salt?: string + salt?: string, ): SequentialDelayDomain { return { name: DomainIdentifiers.SequentialDelay, @@ -75,7 +75,7 @@ export async function odisHardenKey( key: Buffer, domain: SequentialDelayDomain, environment: OdisServiceContext, - wallet?: EIP712Wallet + wallet?: EIP712Wallet, ): Promise> { // Session ID for logging requests. const sessionID = genSessionID() @@ -95,14 +95,14 @@ export async function odisHardenKey( domain, // Use the local clock as a fallback. Divide by 1000 to get seconds from ms. quotaState.now ?? Date.now() / 1000, - quotaState + quotaState, ) if (!quotaResult.accepted) { return Err( new OdisRateLimitingError( quotaResult.notBefore, - new Error('client does not currently have quota based on status response.') - ) + new Error('client does not currently have quota based on status response.'), + ), ) } @@ -114,7 +114,7 @@ export async function odisHardenKey( Buffer.from(environment.odisPubKey, 'base64'), domainHash(domain), key, - blindingSeed + blindingSeed, ) // Request the partial oblivious signature from ODIS. @@ -125,7 +125,7 @@ export async function odisHardenKey( domain, environment, sessionID, - wallet + wallet, ) if (!signatureResp.ok) { return signatureResp @@ -135,7 +135,7 @@ export async function odisHardenKey( let odisOutput: Buffer try { odisOutput = await poprfClient.unblindResponse( - Buffer.from(signatureResp.result.signature, 'base64') + Buffer.from(signatureResp.result.signature, 'base64'), ) } catch (error) { return Err(new OdisVerificationError(error as Error)) @@ -180,7 +180,7 @@ export async function requestOdisDomainQuotaStatus( domain: SequentialDelayDomain, environment: OdisServiceContext, sessionID: string, - wallet?: EIP712Wallet + wallet?: EIP712Wallet, ): Promise> { const quotaStatusReq: DomainQuotaStatusRequest = { type: DomainRequestTypeTag.QUOTA, @@ -198,12 +198,12 @@ export async function requestOdisDomainQuotaStatus( if (wallet === undefined || !wallet.hasAccount(authorizer)) { return Err( new AuthorizationError( - new Error('key for signing ODIS quota status request is unavailable') - ) + new Error('key for signing ODIS quota status request is unavailable'), + ), ) } quotaStatusReq.options.signature = defined( - await wallet.signTypedData(authorizer, domainQuotaStatusRequestEIP712(quotaStatusReq)) + await wallet.signTypedData(authorizer, domainQuotaStatusRequestEIP712(quotaStatusReq)), ) } else if (wallet !== undefined) { return Err(new UsageError(new Error('wallet provided but the domain is unauthenticated'))) @@ -215,7 +215,7 @@ export async function requestOdisDomainQuotaStatus( quotaStatusReq, environment, DomainEndpoint.DOMAIN_QUOTA_STATUS, - domainQuotaStatusResponseSchema(SequentialDelayDomainStateSchema) + domainQuotaStatusResponseSchema(SequentialDelayDomainStateSchema), ) } catch (error) { if ((error as Error).message?.includes(ErrorMessages.ODIS_FETCH_ERROR)) { @@ -236,7 +236,7 @@ async function requestOdisDomainSignature( domain: SequentialDelayDomain, environment: OdisServiceContext, sessionID: string, - wallet?: EIP712Wallet + wallet?: EIP712Wallet, ): Promise> { const signatureReq: DomainRestrictedSignatureRequest = { type: DomainRequestTypeTag.SIGN, @@ -255,12 +255,12 @@ async function requestOdisDomainSignature( if (wallet === undefined || !wallet.hasAccount(authorizer)) { return Err( new AuthorizationError( - new Error('key for signing ODIS domain signature request is unavailable') - ) + new Error('key for signing ODIS domain signature request is unavailable'), + ), ) } signatureReq.options.signature = defined( - await wallet.signTypedData(authorizer, domainRestrictedSignatureRequestEIP712(signatureReq)) + await wallet.signTypedData(authorizer, domainRestrictedSignatureRequestEIP712(signatureReq)), ) } else if (wallet !== undefined) { return Err(new UsageError(new Error('wallet provided but the domain is unauthenticated'))) @@ -272,7 +272,7 @@ async function requestOdisDomainSignature( signatureReq, environment, DomainEndpoint.DOMAIN_SIGN, - domainRestrictedSignatureResponseSchema(SequentialDelayDomainStateSchema) + domainRestrictedSignatureResponseSchema(SequentialDelayDomainStateSchema), ) } catch (error) { if ((error as Error).message?.includes(ErrorMessages.ODIS_FETCH_ERROR)) { diff --git a/packages/encrypted-backup/src/schema.ts b/packages/encrypted-backup/src/schema.ts index fa8f04f68..50b6f9665 100644 --- a/packages/encrypted-backup/src/schema.ts +++ b/packages/encrypted-backup/src/schema.ts @@ -23,9 +23,9 @@ export const BufferFromBase64 = new t.Type( return t.failure(unk, context, 'provided string is not base64') } return t.success(Buffer.from(str, 'base64')) - }) + }), ), - (buffer: Buffer) => buffer.toString('base64') + (buffer: Buffer) => buffer.toString('base64'), ) /** io-ts codec used to encode and decode backups from JSON objects */ @@ -85,8 +85,8 @@ export function deserializeBackup(data: string): Result { if (isLeft(decoding)) { return Err( new DecodeError( - new Error(`error in validating backup object: ${JSON.stringify(decoding.left)}`) - ) + new Error(`error in validating backup object: ${JSON.stringify(decoding.left)}`), + ), ) } const backup = decoding.right @@ -94,8 +94,8 @@ export function deserializeBackup(data: string): Result { if (backup.nonce.length !== 32) { return Err( new DecodeError( - new Error(`expected backup nonce to be 32 bytes but got ${backup.nonce.length}`) - ) + new Error(`expected backup nonce to be 32 bytes but got ${backup.nonce.length}`), + ), ) } diff --git a/packages/encrypted-backup/src/utils.ts b/packages/encrypted-backup/src/utils.ts index 0637ec4e8..62383197a 100644 --- a/packages/encrypted-backup/src/utils.ts +++ b/packages/encrypted-backup/src/utils.ts @@ -68,8 +68,8 @@ export function decrypt(key: Buffer, ciphertext: Buffer): Result> { switch (config.function) { case ComputationalHardeningFunction.PBKDF: diff --git a/packages/identity/src/odis/bls-blinding-client.ts b/packages/identity/src/odis/bls-blinding-client.ts index d69171c3c..2a4c1f9d6 100644 --- a/packages/identity/src/odis/bls-blinding-client.ts +++ b/packages/identity/src/odis/bls-blinding-client.ts @@ -42,7 +42,7 @@ export class WasmBlsBlindingClient implements BlsBlindingClient { const userSeed = seed ?? randomBytes(32) if (!seed) { console.warn( - 'Warning: Use a private deterministic seed (e.g. DEK private key) to preserve user quota when requests are replayed.' + 'Warning: Use a private deterministic seed (e.g. DEK private key) to preserve user quota when requests are replayed.', ) } this.rawMessage = Buffer.from(base64PhoneNumber, 'base64') @@ -59,7 +59,7 @@ export class WasmBlsBlindingClient implements BlsBlindingClient { const blindedSignature = Buffer.from(base64BlindSig, 'base64') const unblindMessage = await this.thresholdBls.unblind( blindedSignature, - this.blindedValue.blindingFactor + this.blindedValue.blindingFactor, ) // this throws on error await this.thresholdBls.verify(this.odisPubKey, this.rawMessage, unblindMessage) diff --git a/packages/identity/src/odis/circuit-breaker.mock.ts b/packages/identity/src/odis/circuit-breaker.mock.ts index cc08051b7..ef5a5c967 100644 --- a/packages/identity/src/odis/circuit-breaker.mock.ts +++ b/packages/identity/src/odis/circuit-breaker.mock.ts @@ -89,7 +89,7 @@ export class MockCircuitBreaker { plaintext = crypto.privateDecrypt( // @ts-ignore support for OAEP hash option, was added in Node 12.9.0. { key: MOCK_CIRCUIT_BREAKER_PRIVATE_KEY, oaepHash: 'sha256' }, - Buffer.from(ciphertext, 'base64') + Buffer.from(ciphertext, 'base64'), ) } catch (error) { return { @@ -114,7 +114,7 @@ export class MockCircuitBreaker { ((url: string, req: unknown) => { debug('Mocking request', { url, req }) return this.status() - }) + }), ) } @@ -128,7 +128,7 @@ export class MockCircuitBreaker { ((url: string, req: { body: string }) => { debug('Mocking request', { url, req }) return this.unwrapKey(JSON.parse(req.body) as CircuitBreakerUnwrapKeyRequest) - }) + }), ) } diff --git a/packages/identity/src/odis/circuit-breaker.test.ts b/packages/identity/src/odis/circuit-breaker.test.ts index 11ef00efd..1190725f1 100644 --- a/packages/identity/src/odis/circuit-breaker.test.ts +++ b/packages/identity/src/odis/circuit-breaker.test.ts @@ -93,7 +93,7 @@ describe('CircuitBreakerClient', () => { const plaintext = crypto.privateDecrypt( //@ts-ignore support for OAEP hash option, was added in Node 12.9.0. { key: MockCircuitBreaker.privateKey, oaepHash: 'sha256' }, - ciphertext.result + ciphertext.result, ) expect(plaintext.toString('utf8')).toEqual(testData) }) diff --git a/packages/identity/src/odis/circuit-breaker.ts b/packages/identity/src/odis/circuit-breaker.ts index c1950b73a..fd9b21fe7 100644 --- a/packages/identity/src/odis/circuit-breaker.ts +++ b/packages/identity/src/odis/circuit-breaker.ts @@ -82,7 +82,10 @@ export enum CircuitBreakerErrorTypes { } export class CircuitBreakerServiceError extends RootError { - constructor(readonly status: number, readonly error?: Error) { + constructor( + readonly status: number, + readonly error?: Error, + ) { super(CircuitBreakerErrorTypes.SERVICE_ERROR) } } @@ -176,8 +179,8 @@ export class CircuitBreakerClient { return Err( new CircuitBreakerServiceError( response.status, - new Error(`circuit breaker service returned unexpected response: ${obj.status}`) - ) + new Error(`circuit breaker service returned unexpected response: ${obj.status}`), + ), ) } @@ -198,7 +201,7 @@ export class CircuitBreakerClient { key: this.environment.publicKey, oaepHash: 'sha256', }, - plaintext + plaintext, ) } catch (error) { return Err(new EncryptionError(error as Error)) diff --git a/packages/identity/src/odis/identifier-backwards-compatibility.test.ts b/packages/identity/src/odis/identifier-backwards-compatibility.test.ts index 5e7d4f455..8aef4e4bc 100644 --- a/packages/identity/src/odis/identifier-backwards-compatibility.test.ts +++ b/packages/identity/src/odis/identifier-backwards-compatibility.test.ts @@ -39,7 +39,7 @@ describe('backwards compatibility of phone number identifiers', () => { mockE164Number, mockAccount, authSigner, - oldServiceContext + oldServiceContext, ) const currRes = await getObfuscatedIdentifier( @@ -47,7 +47,7 @@ describe('backwards compatibility of phone number identifiers', () => { IdentifierPrefix.PHONE_NUMBER, mockAccount, authSigner, - currentServiceContext + currentServiceContext, ) expect(oldRes.e164Number).toEqual(currRes.plaintextIdentifier) @@ -61,18 +61,18 @@ describe('backwards compatibility of phone number identifiers', () => { const blsBlindingClient = new WasmBlsBlindingClient('') const seed = Buffer.from( '44714c0a2b2bacec757a67822a4fbbdfe043cca8c6ae936545ef992f246df1a9', - 'hex' + 'hex', ) const oldRes = await OdisUtilsOld.PhoneNumberIdentifier.getBlindedPhoneNumber( mockE164Number, blsBlindingClient, - seed + seed, ) const currentRes = await getBlindedIdentifier( mockE164Number, IdentifierPrefix.PHONE_NUMBER, blsBlindingClient, - seed + seed, ) const expectedBlindedIdentifier = @@ -97,7 +97,7 @@ describe('backwards compatibility of phone number identifiers', () => { mockE164Number, mockAccount, authSigner, - oldServiceContext + oldServiceContext, ) const currRes = await getObfuscatedIdentifier( @@ -105,7 +105,7 @@ describe('backwards compatibility of phone number identifiers', () => { '' as typeof IdentifierPrefix.PHONE_NUMBER, mockAccount, authSigner, - currentServiceContext + currentServiceContext, ) expect(oldRes.e164Number).toEqual(currRes.plaintextIdentifier) diff --git a/packages/identity/src/odis/identifier.test.ts b/packages/identity/src/odis/identifier.test.ts index ae97ca73b..6df3bb106 100644 --- a/packages/identity/src/odis/identifier.test.ts +++ b/packages/identity/src/odis/identifier.test.ts @@ -58,13 +58,13 @@ describe(getObfuscatedIdentifier, () => { const base64BlindedMessage = await getBlindedIdentifier( mockOffchainIdentifier, IdentifierPrefix.TWITTER, - blsBlindingClient + blsBlindingClient, ) const base64BlindSig = await getBlindedIdentifierSignature( mockAccount, authSigner, serviceContext, - base64BlindedMessage + base64BlindedMessage, ) const base64UnblindedSig = await blsBlindingClient.unblindAndVerifyMessage(base64BlindSig) @@ -74,8 +74,8 @@ describe(getObfuscatedIdentifier, () => { IdentifierPrefix.TWITTER, mockAccount, authSigner, - serviceContext - ) + serviceContext, + ), ).resolves.toMatchObject({ plaintextIdentifier: mockOffchainIdentifier, pepper: expectedPepper, @@ -97,21 +97,21 @@ describe(getObfuscatedIdentifier, () => { const base64BlindedMessage = await getBlindedIdentifier( mockOffchainIdentifier, IdentifierPrefix.TWITTER, - blsBlindingClient + blsBlindingClient, ) const base64BlindSig = await getBlindedIdentifierSignature( mockAccount, authSigner, serviceContext, - base64BlindedMessage + base64BlindedMessage, ) const obfuscatedIdentifierDetails = await getObfuscatedIdentifierFromSignature( mockOffchainIdentifier, IdentifierPrefix.TWITTER, base64BlindSig, - blsBlindingClient + blsBlindingClient, ) expect(obfuscatedIdentifierDetails.obfuscatedIdentifier).toEqual(expectedIdentifierHash) @@ -128,8 +128,8 @@ describe(getObfuscatedIdentifier, () => { IdentifierPrefix.TWITTER, mockAccount, authSigner, - serviceContext - ) + serviceContext, + ), ).rejects.toThrow(ErrorMessages.ODIS_QUOTA_ERROR) }) @@ -141,8 +141,8 @@ describe(getObfuscatedIdentifier, () => { IdentifierPrefix.TWITTER, mockAccount, authSigner, - serviceContext - ) + serviceContext, + ), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) }) diff --git a/packages/identity/src/odis/identifier.ts b/packages/identity/src/odis/identifier.ts index 71cb0e9ce..afc486f41 100644 --- a/packages/identity/src/odis/identifier.ts +++ b/packages/identity/src/odis/identifier.ts @@ -113,7 +113,7 @@ export async function getObfuscatedIdentifier( blsBlindingClient?: BlsBlindingClient, sessionID?: string, keyVersion?: number, - abortController?: AbortController + abortController?: AbortController, ): Promise { debug('Getting identifier pepper') @@ -134,7 +134,7 @@ export async function getObfuscatedIdentifier( plaintextIdentifier, identifierPrefix, blsBlindingClient, - seed + seed, ) const base64BlindSig = await getBlindedIdentifierSignature( @@ -145,14 +145,14 @@ export async function getObfuscatedIdentifier( clientVersion, sessionID, keyVersion, - abortController + abortController, ) return getObfuscatedIdentifierFromSignature( plaintextIdentifier, identifierPrefix, base64BlindSig, - blsBlindingClient + blsBlindingClient, ) } @@ -170,7 +170,7 @@ export async function getBlindedIdentifier( plaintextIdentifier: string, identifierPrefix: IdentifierPrefix, blsBlindingClient: BlsBlindingClient, - seed?: Buffer + seed?: Buffer, ): Promise { debug('Retrieving blinded message') // phone number identifiers don't have prefixes in the blinding stage @@ -209,7 +209,7 @@ export async function getBlindedIdentifierSignature( clientVersion?: string, sessionID?: string, keyVersion?: number, - abortControlller?: AbortController + abortControlller?: AbortController, ): Promise { const body: SignMessageRequest = { account, @@ -228,7 +228,7 @@ export async function getBlindedIdentifierSignature( [KEY_VERSION_HEADER]: keyVersion?.toString(), Authorization: await getOdisPnpRequestAuth(body, signer), }, - abortControlller + abortControlller, ) if (!response.success) { @@ -250,7 +250,7 @@ export async function getObfuscatedIdentifierFromSignature( plaintextIdentifier: string, identifierPrefix: IdentifierPrefix, base64BlindedSignature: string, - blsBlindingClient: BlsBlindingClient + blsBlindingClient: BlsBlindingClient, ): Promise { debug('Retrieving unblinded signature') const base64UnblindedSig = await blsBlindingClient.unblindAndVerifyMessage(base64BlindedSignature) @@ -281,7 +281,7 @@ export async function getObfuscatedIdentifierFromSignature( export const getIdentifierHash = ( plaintextIdentifier: string, identifierPrefix: IdentifierPrefix, - pepper: string + pepper: string, ): string => { return baseGetIdentifierHash(sha3, plaintextIdentifier, identifierPrefix, pepper) } diff --git a/packages/identity/src/odis/phone-number-identifier.test.ts b/packages/identity/src/odis/phone-number-identifier.test.ts index f0f85ec47..545e163af 100644 --- a/packages/identity/src/odis/phone-number-identifier.test.ts +++ b/packages/identity/src/odis/phone-number-identifier.test.ts @@ -67,12 +67,12 @@ describe(getPhoneNumberIdentifier, () => { mockAccount, authSigner, serviceContext, - base64BlindedMessage + base64BlindedMessage, ) const base64UnblindedSig = await blsBlindingClient.unblindAndVerifyMessage(base64BlindSig) await expect( - getPhoneNumberIdentifier(mockE164Number, mockAccount, authSigner, serviceContext) + getPhoneNumberIdentifier(mockE164Number, mockAccount, authSigner, serviceContext), ).resolves.toMatchObject({ e164Number: mockE164Number, pepper: expectedPepper, @@ -97,13 +97,13 @@ describe(getPhoneNumberIdentifier, () => { mockAccount, authSigner, serviceContext, - base64BlindedMessage + base64BlindedMessage, ) const phoneNumberHashDetails = await getPhoneNumberIdentifierFromSignature( mockE164Number, base64BlindSig, - blsBlindingClient + blsBlindingClient, ) expect(phoneNumberHashDetails.phoneHash).toEqual(expectedPhoneHash) @@ -115,14 +115,14 @@ describe(getPhoneNumberIdentifier, () => { fetchMock.mock(endpoint, 403) await expect( - getPhoneNumberIdentifier(mockE164Number, mockAccount, authSigner, serviceContext) + getPhoneNumberIdentifier(mockE164Number, mockAccount, authSigner, serviceContext), ).rejects.toThrow(ErrorMessages.ODIS_QUOTA_ERROR) }) it('Throws auth error', async () => { fetchMock.mock(endpoint, 401) await expect( - getPhoneNumberIdentifier(mockE164Number, mockAccount, authSigner, serviceContext) + getPhoneNumberIdentifier(mockE164Number, mockAccount, authSigner, serviceContext), ).rejects.toThrow(ErrorMessages.ODIS_AUTH_ERROR) }) }) diff --git a/packages/identity/src/odis/phone-number-identifier.ts b/packages/identity/src/odis/phone-number-identifier.ts index 97b32d82a..d9c92cd11 100644 --- a/packages/identity/src/odis/phone-number-identifier.ts +++ b/packages/identity/src/odis/phone-number-identifier.ts @@ -38,7 +38,7 @@ export async function getPhoneNumberIdentifier( clientVersion?: string, blsBlindingClient?: BlsBlindingClient, sessionID?: string, - keyVersion?: number + keyVersion?: number, ): Promise { debug('Getting phone number pepper') @@ -53,7 +53,7 @@ export async function getPhoneNumberIdentifier( clientVersion, blsBlindingClient, sessionID, - keyVersion + keyVersion, ) return { e164Number: plaintextIdentifier, @@ -71,7 +71,7 @@ export async function getPhoneNumberIdentifier( export async function getBlindedPhoneNumber( e164Number: string, blsBlindingClient: BlsBlindingClient, - seed?: Buffer + seed?: Buffer, ): Promise { return getBlindedIdentifier(e164Number, IdentifierPrefix.PHONE_NUMBER, blsBlindingClient, seed) } @@ -89,7 +89,7 @@ export async function getBlindedPhoneNumberSignature( base64BlindedMessage: string, clientVersion?: string, sessionID?: string, - keyVersion?: number + keyVersion?: number, ): Promise { return getBlindedIdentifierSignature( account, @@ -98,7 +98,7 @@ export async function getBlindedPhoneNumberSignature( base64BlindedMessage, clientVersion, sessionID, - keyVersion + keyVersion, ) } @@ -109,14 +109,14 @@ export async function getBlindedPhoneNumberSignature( export async function getPhoneNumberIdentifierFromSignature( e164Number: string, base64BlindedSignature: string, - blsBlindingClient: BlsBlindingClient + blsBlindingClient: BlsBlindingClient, ): Promise { const { plaintextIdentifier, obfuscatedIdentifier, pepper, unblindedSignature } = await getObfuscatedIdentifierFromSignature( e164Number, IdentifierPrefix.PHONE_NUMBER, base64BlindedSignature, - blsBlindingClient + blsBlindingClient, ) return { e164Number: plaintextIdentifier, @@ -132,7 +132,7 @@ export async function getPhoneNumberIdentifierFromSignature( */ export function isBalanceSufficientForSigRetrieval( dollarBalance: BigNumber.Value, - celoBalance: BigNumber.Value + celoBalance: BigNumber.Value, ) { return ( new BigNumber(dollarBalance).isGreaterThanOrEqualTo(ODIS_MINIMUM_DOLLAR_BALANCE) || diff --git a/packages/identity/src/odis/query.ts b/packages/identity/src/odis/query.ts index 772b6c8a9..2be905257 100644 --- a/packages/identity/src/odis/query.ts +++ b/packages/identity/src/odis/query.ts @@ -94,7 +94,7 @@ export enum OdisContextName { export function getServiceContext( contextName: OdisContextName = OdisContextName.MAINNET, - api: OdisAPI = OdisAPI.PNP + api: OdisAPI = OdisAPI.PNP, ) { switch (contextName) { case OdisContextName.ALFAJORES: @@ -124,7 +124,7 @@ export function signWithDEK(msg: string, signer: EncryptionKeySigner) { export async function getOdisPnpRequestAuth( body: PhoneNumberPrivacyRequest, - signer: AuthSigner + signer: AuthSigner, ): Promise { // Sign payload using provided account and authentication method. const bodyString = JSON.stringify(body) @@ -152,7 +152,7 @@ export async function queryOdis( endpoint: CombinerEndpoint, responseSchema: t.Type, OdisResponse, unknown>, headers: OdisRequestHeader, - abortController?: AbortController + abortController?: AbortController, ): Promise> { debug(`Posting to ${endpoint}`) @@ -215,7 +215,7 @@ export async function queryOdis( }, 3, dontRetry, - [] + [], ) } @@ -233,13 +233,13 @@ export async function sendOdisDomainRequest( context: ServiceContext, endpoint: DomainEndpoint, responseSchema: t.Type>, - headers?: DomainRequestHeader + headers?: DomainRequestHeader, ): Promise> { return queryOdis( body, context, endpoint, responseSchema, - headers as OdisRequestHeader + headers as OdisRequestHeader, ) as Promise> } diff --git a/packages/identity/src/odis/quota.test.ts b/packages/identity/src/odis/quota.test.ts index 5c2e34efb..3eb196326 100644 --- a/packages/identity/src/odis/quota.test.ts +++ b/packages/identity/src/odis/quota.test.ts @@ -33,7 +33,7 @@ describe(getPnpQuotaStatus, () => { }) await expect( - getPnpQuotaStatus(mockAccount, authSigner, serviceContext) + getPnpQuotaStatus(mockAccount, authSigner, serviceContext), ).resolves.toStrictEqual({ performedQueryCount, totalQuota, diff --git a/packages/identity/src/odis/quota.ts b/packages/identity/src/odis/quota.ts index 8d866b9ce..3d41b1072 100644 --- a/packages/identity/src/odis/quota.ts +++ b/packages/identity/src/odis/quota.ts @@ -31,7 +31,7 @@ export async function getPnpQuotaStatus( context: ServiceContext, clientVersion?: string, sessionID?: string, - abortController?: AbortController + abortController?: AbortController, ): Promise { const body: PnpQuotaRequest = { account, @@ -48,7 +48,7 @@ export async function getPnpQuotaStatus( { Authorization: await getOdisPnpRequestAuth(body, signer), }, - abortController + abortController, ) if (response.success) { diff --git a/packages/identity/src/offchain-data-wrapper.test.ts b/packages/identity/src/offchain-data-wrapper.test.ts index c5a2657d8..291b6e0a2 100644 --- a/packages/identity/src/offchain-data-wrapper.test.ts +++ b/packages/identity/src/offchain-data-wrapper.test.ts @@ -57,7 +57,7 @@ testWithGanache('Offchain Data', (web3) => { async function setupAccount( privateKey: string, dek?: string, - compressedDEK = false + compressedDEK = false, ): Promise { const publicKey = privateKeyToPublicKey(privateKey) const address = publicKeyToAddress(publicKey) @@ -73,7 +73,7 @@ testWithGanache('Offchain Data', (web3) => { .setAccountDataEncryptionKey( compressedDEK ? ensureLeading0x(ensureCompressed(privateKeyToPublicKey(dek))) - : privateKeyToPublicKey(dek) + : privateKeyToPublicKey(dek), ) .sendAndWaitForReceipt({ from: address }) kit.connection.addAccount(dek) @@ -173,14 +173,14 @@ testWithGanache('Offchain Data', (web3) => { // Mock the 404 fetchMock.mock( writer.storageRoot + `/account/authorizedSigners/${toChecksumAddress(signer.address)}`, - 404 + 404, ) const wrapper = new BasicDataWrapper(signer.address, kit) wrapper.storageWriter = new MockStorageWriter( writer.localStorageRoot, writer.storageRoot, - fetchMock + fetchMock, ) const nameAccessor = new PublicNameAccessor(wrapper) await nameAccessor.write(testPayload) @@ -190,7 +190,7 @@ testWithGanache('Offchain Data', (web3) => { const authorizedSignerAccessor = new AuthorizedSignerAccessor(writer.wrapper) const authorization = await authorizedSignerAccessor.readAsResult( writer.address, - signer.address + signer.address, ) expect(authorization.ok).toEqual(false) }) @@ -206,7 +206,7 @@ testWithGanache('Offchain Data', (web3) => { const authorizedSignerAccessor = new AuthorizedSignerAccessor(reader.wrapper) const authorization = await authorizedSignerAccessor.readAsResult( writer.address, - signer.address + signer.address, ) expect(authorization).toBeDefined() }) diff --git a/packages/identity/src/offchain-data-wrapper.ts b/packages/identity/src/offchain-data-wrapper.ts index 5eb1a4498..3dd867d3d 100644 --- a/packages/identity/src/offchain-data-wrapper.ts +++ b/packages/identity/src/offchain-data-wrapper.ts @@ -66,7 +66,7 @@ export interface OffchainDataWrapper { account: Address, dataPath: string, checkOffchainSigners: boolean, - type?: t.Type + type?: t.Type, ): Promise> } @@ -74,7 +74,11 @@ export class BasicDataWrapper implements OffchainDataWrapper { storageWriter: StorageWriter | undefined signer: string - constructor(readonly self: string, readonly kit: ContractKit, signer?: string) { + constructor( + readonly self: string, + readonly kit: ContractKit, + signer?: string, + ) { this.signer = signer || self } @@ -82,7 +86,7 @@ export class BasicDataWrapper implements OffchainDataWrapper { account: Address, dataPath: string, checkOffchainSigners: boolean, - type?: t.Type + type?: t.Type, ): Promise> { const accounts = await this.kit.contracts.getAccounts() const metadataURL = await accounts.getMetadataURL(account) @@ -98,7 +102,7 @@ export class BasicDataWrapper implements OffchainDataWrapper { } const results = await Promise.all( - storageRoots.map(async (s) => s.readAndVerifySignature(dataPath, checkOffchainSigners, type)) + storageRoots.map(async (s) => s.readAndVerifySignature(dataPath, checkOffchainSigners, type)), ) const item = results.find((s) => s.ok) @@ -114,7 +118,7 @@ export class BasicDataWrapper implements OffchainDataWrapper { async writeDataTo( data: Buffer, signature: Buffer, - dataPath: string + dataPath: string, ): Promise { if (this.storageWriter === undefined) { return new NoStorageProvider() @@ -135,13 +139,13 @@ class StorageRoot { constructor( readonly wrapper: OffchainDataWrapper, readonly account: Address, - readonly root: string + readonly root: string, ) {} async readAndVerifySignature( dataPath: string, checkOffchainSigners: boolean, - type?: t.Type + type?: t.Type, ): Promise> { let dataResponse, signatureResponse @@ -202,7 +206,7 @@ class StorageRoot { const authorizedSignerAccessor = new AuthorizedSignerAccessor(this.wrapper) const authorizedSigner = await authorizedSignerAccessor.readAsResult( this.account, - guessedSigner + guessedSigner, ) if (authorizedSigner.ok) { return Ok(body) diff --git a/packages/identity/src/offchain/accessors/authorized-signer.ts b/packages/identity/src/offchain/accessors/authorized-signer.ts index 366480b80..625c071ed 100644 --- a/packages/identity/src/offchain/accessors/authorized-signer.ts +++ b/packages/identity/src/offchain/accessors/authorized-signer.ts @@ -23,7 +23,7 @@ export class AuthorizedSignerAccessor { account, dataPath, false, - AuthorizedSignerSchema + AuthorizedSignerSchema, ) if (!rawData.ok) { return Err(new OffchainError(rawData.error)) @@ -37,7 +37,7 @@ export class AuthorizedSignerAccessor { async write( signer: Address, proofOfPossession: string, - filteredDataPaths: string + filteredDataPaths: string, ): Promise { const payload = { address: toChecksumAddress(signer), @@ -49,7 +49,7 @@ export class AuthorizedSignerAccessor { this.wrapper, dataPath, payload, - AuthorizedSignerSchema + AuthorizedSignerSchema, ) const signature = await this.wrapper.kit .getWallet()! @@ -57,7 +57,7 @@ export class AuthorizedSignerAccessor { return this.wrapper.writeDataTo( Buffer.from(JSON.stringify(payload)), Buffer.from(trimLeading0x(signature), 'hex'), - dataPath + dataPath, ) } } diff --git a/packages/identity/src/offchain/accessors/binary.ts b/packages/identity/src/offchain/accessors/binary.ts index 71cfb41e0..d2f13239c 100644 --- a/packages/identity/src/offchain/accessors/binary.ts +++ b/packages/identity/src/offchain/accessors/binary.ts @@ -9,14 +9,17 @@ import { PrivateAccessor, PublicAccessor } from './interfaces' * Schema for writing any generic binary data */ export class PublicBinaryAccessor implements PublicAccessor { - constructor(readonly wrapper: OffchainDataWrapper, readonly dataPath: string) {} + constructor( + readonly wrapper: OffchainDataWrapper, + readonly dataPath: string, + ) {} async write(data: Buffer) { const signature = await signBuffer(this.wrapper, this.dataPath, data) const error = await this.wrapper.writeDataTo( data, Buffer.from(trimLeading0x(signature), 'hex'), - this.dataPath + this.dataPath, ) if (error) { return new OffchainError(error) @@ -39,7 +42,10 @@ export class PublicBinaryAccessor implements PublicAccessor { * Schema for writing any encrypted binary data. */ export class PrivateBinaryAccessor implements PrivateAccessor { - constructor(readonly wrapper: OffchainDataWrapper, readonly dataPath: string) {} + constructor( + readonly wrapper: OffchainDataWrapper, + readonly dataPath: string, + ) {} async write(data: Buffer, toAddresses: Address[], symmetricKey?: Buffer) { return writeEncrypted(this.wrapper, this.dataPath, data, toAddresses, symmetricKey) diff --git a/packages/identity/src/offchain/accessors/simple.ts b/packages/identity/src/offchain/accessors/simple.ts index 4089900c1..959d4efba 100644 --- a/packages/identity/src/offchain/accessors/simple.ts +++ b/packages/identity/src/offchain/accessors/simple.ts @@ -24,7 +24,7 @@ export class PublicSimpleAccessor implements PublicAccessor constructor( readonly wrapper: OffchainDataWrapper, readonly type: t.Type, - readonly dataPath: string + readonly dataPath: string, ) {} private async sign(data: DataType) { @@ -42,7 +42,7 @@ export class PublicSimpleAccessor implements PublicAccessor const error = await this.wrapper.writeDataTo( serialize(data), Buffer.from(trimLeading0x(signature), 'hex'), - this.dataPath + this.dataPath, ) if (error) { return new OffchainError(error) @@ -75,7 +75,7 @@ export class PrivateSimpleAccessor implements PrivateAccessor, - readonly dataPath: string + readonly dataPath: string, ) {} write(data: DataType, toAddresses: Address[], symmetricKey?: Buffer) { diff --git a/packages/identity/src/offchain/storage-writers.ts b/packages/identity/src/offchain/storage-writers.ts index 3b6fc8bbe..97446d1b1 100644 --- a/packages/identity/src/offchain/storage-writers.ts +++ b/packages/identity/src/offchain/storage-writers.ts @@ -36,7 +36,10 @@ export class GitStorageWriter extends LocalStorageWriter { export class GoogleStorageWriter extends LocalStorageWriter { private readonly bucket: string - constructor(readonly local: string, bucket: string) { + constructor( + readonly local: string, + bucket: string, + ) { super(local) this.bucket = bucket } @@ -52,7 +55,10 @@ export class GoogleStorageWriter extends LocalStorageWriter { export class AwsStorageWriter extends LocalStorageWriter { private readonly bucket: string - constructor(readonly local: string, bucket: string) { + constructor( + readonly local: string, + bucket: string, + ) { super(local) this.bucket = bucket } @@ -66,7 +72,11 @@ export class AwsStorageWriter extends LocalStorageWriter { } export class MockStorageWriter extends LocalStorageWriter { - constructor(readonly root: string, readonly mockedStorageRoot: string, readonly fetchMock: any) { + constructor( + readonly root: string, + readonly mockedStorageRoot: string, + readonly fetchMock: any, + ) { super(root) } async write(data: Buffer, dataPath: string): Promise { diff --git a/packages/identity/src/offchain/utils.ts b/packages/identity/src/offchain/utils.ts index af8674bbd..c9e0a2948 100644 --- a/packages/identity/src/offchain/utils.ts +++ b/packages/identity/src/offchain/utils.ts @@ -27,7 +27,7 @@ function getCiphertextLabel( path: string, sharedSecret: Buffer, senderPublicKey: string, - receiverPublicKey: string + receiverPublicKey: string, ) { const senderPublicKeyBuffer = Buffer.from(ensureCompressed(senderPublicKey), 'hex') const receiverPublicKeyBuffer = Buffer.from(ensureCompressed(receiverPublicKey), 'hex') @@ -54,7 +54,7 @@ const distributeSymmetricKey = async ( wrapper: OffchainDataWrapper, dataPath: string, key: Buffer, - toAddress: Address + toAddress: Address, ): Promise => { const accounts = await wrapper.kit.contracts.getAccounts() const [fromPubKey, toPubKey] = await Promise.all([ @@ -74,14 +74,14 @@ const distributeSymmetricKey = async ( const computedDataPath = getCiphertextLabel(`${dataPath}.key`, sharedSecret, fromPubKey, toPubKey) const encryptedData = Encrypt( Buffer.from(trimUncompressedPrefix(ensureUncompressed(toPubKey)), 'hex'), - key + key, ) const signature = await signBuffer(wrapper, computedDataPath, encryptedData) const writeError = await wrapper.writeDataTo( encryptedData, Buffer.from(trimLeading0x(signature), 'hex'), - computedDataPath + computedDataPath, ) if (writeError) { return new OffchainError(writeError) @@ -101,7 +101,7 @@ const distributeSymmetricKey = async ( async function fetchOrGenerateKey( wrapper: OffchainDataWrapper, dataPath: string, - symmetricKey?: Buffer + symmetricKey?: Buffer, ) { if (symmetricKey) { return Ok(symmetricKey) @@ -138,7 +138,7 @@ export const writeEncrypted = async ( dataPath: string, data: Buffer, toAddresses: Address[], - symmetricKey?: Buffer + symmetricKey?: Buffer, ): Promise => { const fetchKey = await fetchOrGenerateKey(wrapper, dataPath, symmetricKey) if (!fetchKey.ok) { @@ -152,7 +152,7 @@ export const writeEncrypted = async ( const writeError = await wrapper.writeDataTo( payload, Buffer.from(trimLeading0x(signature), 'hex'), - `${dataPath}.enc` + `${dataPath}.enc`, ) if (writeError) { return new OffchainError(writeError) @@ -162,8 +162,8 @@ export const writeEncrypted = async ( await Promise.all( // here we encrypt the key to ourselves so we can retrieve it later [wrapper.self, ...toAddresses].map(async (toAddress) => - distributeSymmetricKey(wrapper, dataPath, fetchKey.result, toAddress) - ) + distributeSymmetricKey(wrapper, dataPath, fetchKey.result, toAddress), + ), ) ).find(Boolean) return firstWriteError @@ -173,7 +173,7 @@ export const writeSymmetricKeys = async ( wrapper: OffchainDataWrapper, dataPath: string, toAddresses: Address[], - symmetricKey?: Buffer + symmetricKey?: Buffer, ): Promise => { const fetchKey = await fetchOrGenerateKey(wrapper, dataPath, symmetricKey) if (!fetchKey.ok) { @@ -183,8 +183,8 @@ export const writeSymmetricKeys = async ( const firstWriteError = ( await Promise.all( toAddresses.map(async (toAddress) => - distributeSymmetricKey(wrapper, dataPath, fetchKey.result, toAddress) - ) + distributeSymmetricKey(wrapper, dataPath, fetchKey.result, toAddress), + ), ) ).find(Boolean) return firstWriteError @@ -201,7 +201,7 @@ export const writeSymmetricKeys = async ( const readSymmetricKey = async ( wrapper: OffchainDataWrapper, dataPath: string, - senderAddress: Address + senderAddress: Address, ): Promise> => { const accounts = await wrapper.kit.contracts.getAccounts() const wallet = wrapper.kit.getWallet()! @@ -227,7 +227,7 @@ const readSymmetricKey = async ( `${dataPath}.key`, sharedSecret, senderPubKey, - readerPubKey + readerPubKey, ) const encryptedPayload = await wrapper.readDataFromAsResult(senderAddress, computedDataPath, true) @@ -250,7 +250,7 @@ const readSymmetricKey = async ( export const readEncrypted = async ( wrapper: OffchainDataWrapper, dataPath: string, - senderAddress: Address + senderAddress: Address, ): Promise> => { const encryptedPayloadPath = `${dataPath}.enc` const [payload, key] = await Promise.all([ @@ -273,13 +273,13 @@ export const readEncrypted = async ( } return Ok( - AES128Decrypt(key.result, payload.result.slice(0, IV_LENGTH), payload.result.slice(IV_LENGTH)) + AES128Decrypt(key.result, payload.result.slice(0, IV_LENGTH), payload.result.slice(IV_LENGTH)), ) } export const deserialize = ( type: t.Type, - buf: Buffer + buf: Buffer, ): Result => { const dataAsJson = parseJsonAsResult(buf.toString()) if (!dataAsJson.ok) { @@ -298,7 +298,7 @@ export const buildEIP712TypedData = async ( wrapper: OffchainDataWrapper, path: string, data: DataType | Buffer, - type?: t.Type + type?: t.Type, ): Promise => { const chainId = await wrapper.kit.connection.chainId() const EIP712Domain = [ diff --git a/packages/identity/src/test-utils/setup.global.ts b/packages/identity/src/test-utils/setup.global.ts index 5670525c1..e21e54735 100644 --- a/packages/identity/src/test-utils/setup.global.ts +++ b/packages/identity/src/test-utils/setup.global.ts @@ -14,7 +14,7 @@ export default async function globalSetup() { console.log('\nstarting ganache... set NO_GANACHE=true to disable') const chainDataPath = path.join( path.dirname(require.resolve('@celo/celo-devchain')), - '../chains' + '../chains', ) await baseSetup(path.resolve(chainDataPath), 'v10.tar.gz', { from_targz: true, diff --git a/packages/odis-identifiers/src/identifier.test.ts b/packages/odis-identifiers/src/identifier.test.ts index 7c72b0bde..464985a2e 100644 --- a/packages/odis-identifiers/src/identifier.test.ts +++ b/packages/odis-identifiers/src/identifier.test.ts @@ -26,7 +26,7 @@ describe('Identifier hashing', () => { it(`with IdentifierPrefix: ${prefix}`, () => { const expectedHash = EXPECTED_HASH_FOR_PREFIX[prefix] expect(getIdentifierHash(sha3, TEST_PLAINTEXT_IDENTIFIER, prefix, TEST_SALT)).toBe( - expectedHash + expectedHash, ) }) }) diff --git a/packages/odis-identifiers/src/identifier.ts b/packages/odis-identifiers/src/identifier.ts index 00b2844a0..d4b760a58 100644 --- a/packages/odis-identifiers/src/identifier.ts +++ b/packages/odis-identifiers/src/identifier.ts @@ -50,7 +50,7 @@ export enum IdentifierPrefix { */ export const getPrefixedIdentifier = ( plaintextIdentifier: string, - identifierPrefix: IdentifierPrefix + identifierPrefix: IdentifierPrefix, ): string => identifierPrefix + '://' + plaintextIdentifier /** @@ -70,7 +70,7 @@ export const getIdentifierHash = ( sha3: (a: string) => string | null, plaintextIdentifier: string, identifierPrefix: IdentifierPrefix, - pepper: string + pepper: string, ): string => { // hashing the identifier before appending the pepper to avoid domain collisions where the // identifier may contain underscores diff --git a/yarn.lock b/yarn.lock index d307c6a10..d8519adb6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7091,13 +7091,6 @@ __metadata: languageName: node linkType: hard -"@types/minimatch@npm:^3.0.3": - version: 3.0.5 - resolution: "@types/minimatch@npm:3.0.5" - checksum: c41d136f67231c3131cf1d4ca0b06687f4a322918a3a5adddc87ce90ed9dbd175a3610adee36b106ae68c0b92c637c35e02b58c8a56c424f71d30993ea220b92 - languageName: node - linkType: hard - "@types/minimist@npm:^1.2.0": version: 1.2.2 resolution: "@types/minimist@npm:1.2.2" @@ -7845,6 +7838,15 @@ __metadata: languageName: node linkType: hard +"ansi-escapes@npm:^5.0.0": + version: 5.0.0 + resolution: "ansi-escapes@npm:5.0.0" + dependencies: + type-fest: "npm:^1.0.2" + checksum: cbfb95f9f6d8a1ffc89f50fcda3313effae2d9ac2f357f89f626815b4d95fdc3f10f74e0887614ff850d01f805b7505eb1e7ebfdd26144bbfc26c5de08e19195 + languageName: node + linkType: hard + "ansi-fragments@npm:^0.2.1": version: 0.2.1 resolution: "ansi-fragments@npm:0.2.1" @@ -7923,7 +7925,7 @@ __metadata: languageName: node linkType: hard -"ansi-styles@npm:^6.1.0": +"ansi-styles@npm:^6.0.0, ansi-styles@npm:^6.1.0": version: 6.2.1 resolution: "ansi-styles@npm:6.2.1" checksum: 70fdf883b704d17a5dfc9cde206e698c16bcd74e7f196ab821511651aee4f9f76c9514bdfa6ca3a27b5e49138b89cb222a28caf3afe4567570139577f991df32 @@ -8072,13 +8074,6 @@ __metadata: languageName: node linkType: hard -"array-differ@npm:^3.0.0": - version: 3.0.0 - resolution: "array-differ@npm:3.0.0" - checksum: 117edd9df5c1530bd116c6e8eea891d4bd02850fd89b1b36e532b6540e47ca620a373b81feca1c62d1395d9ae601516ba538abe5e8172d41091da2c546b05fb7 - languageName: node - linkType: hard - "array-flatten@npm:1.1.1, array-flatten@npm:^1.0.0": version: 1.1.1 resolution: "array-flatten@npm:1.1.1" @@ -8160,7 +8155,7 @@ __metadata: languageName: node linkType: hard -"arrify@npm:^2.0.0, arrify@npm:^2.0.1": +"arrify@npm:^2.0.0": version: 2.0.1 resolution: "arrify@npm:2.0.1" checksum: 067c4c1afd182806a82e4c1cb8acee16ab8b5284fbca1ce29408e6e91281c36bb5b612f6ddfbd40a0f7a7e0c75bf2696eb94c027f6e328d6e9c52465c98e4209 @@ -9534,6 +9529,13 @@ __metadata: languageName: node linkType: hard +"chalk@npm:5.3.0": + version: 5.3.0 + resolution: "chalk@npm:5.3.0" + checksum: 6373caaab21bd64c405bfc4bd9672b145647fc9482657b5ea1d549b3b2765054e9d3d928870cdf764fb4aad67555f5061538ff247b8310f110c5c888d92397ea + languageName: node + linkType: hard + "chalk@npm:^1.1.3": version: 1.1.3 resolution: "chalk@npm:1.1.3" @@ -9754,6 +9756,15 @@ __metadata: languageName: node linkType: hard +"cli-cursor@npm:^4.0.0": + version: 4.0.0 + resolution: "cli-cursor@npm:4.0.0" + dependencies: + restore-cursor: "npm:^4.0.0" + checksum: ab3f3ea2076e2176a1da29f9d64f72ec3efad51c0960898b56c8a17671365c26e67b735920530eaf7328d61f8bd41c27f46b9cf6e4e10fe2fa44b5e8c0e392cc + languageName: node + linkType: hard + "cli-spinners@npm:^2.0.0": version: 2.8.0 resolution: "cli-spinners@npm:2.8.0" @@ -9777,6 +9788,16 @@ __metadata: languageName: node linkType: hard +"cli-truncate@npm:^3.1.0": + version: 3.1.0 + resolution: "cli-truncate@npm:3.1.0" + dependencies: + slice-ansi: "npm:^5.0.0" + string-width: "npm:^5.0.0" + checksum: c3243e41974445691c63f8b405df1d5a24049dc33d324fe448dc572e561a7b772ae982692900b1a5960901cc4fc7def25a629b9c69a4208ee89d12ab3332617a + languageName: node + linkType: hard + "cli-width@npm:^2.0.0": version: 2.2.1 resolution: "cli-width@npm:2.2.1" @@ -9959,6 +9980,13 @@ __metadata: languageName: node linkType: hard +"colorette@npm:^2.0.20": + version: 2.0.20 + resolution: "colorette@npm:2.0.20" + checksum: 0b8de48bfa5d10afc160b8eaa2b9938f34a892530b2f7d7897e0458d9535a066e3998b49da9d21161c78225b272df19ae3a64d6df28b4c9734c0e55bbd02406f + languageName: node + linkType: hard + "colors@npm:1.0.3, colors@npm:1.0.x": version: 1.0.3 resolution: "colors@npm:1.0.3" @@ -9999,6 +10027,13 @@ __metadata: languageName: node linkType: hard +"commander@npm:11.1.0": + version: 11.1.0 + resolution: "commander@npm:11.1.0" + checksum: 66bd2d8a0547f6cb1d34022efb25f348e433b0e04ad76a65279b1b09da108f59a4d3001ca539c60a7a46ea38bcf399fc17d91adad76a8cf43845d8dcbaf5cda1 + languageName: node + linkType: hard + "commander@npm:^10.0.0": version: 10.0.1 resolution: "commander@npm:10.0.1" @@ -11907,6 +11942,13 @@ __metadata: languageName: node linkType: hard +"eventemitter3@npm:^5.0.1": + version: 5.0.1 + resolution: "eventemitter3@npm:5.0.1" + checksum: ac6423ec31124629c84c7077eed1e6987f6d66c31cf43c6fcbf6c87791d56317ce808d9ead483652436df171b526fc7220eccdc9f3225df334e81582c3cf7dd5 + languageName: node + linkType: hard + "events-listener@npm:^1.1.0": version: 1.1.0 resolution: "events-listener@npm:1.1.0" @@ -11948,20 +11990,20 @@ __metadata: languageName: node linkType: hard -"execa@npm:^2.1.0": - version: 2.1.0 - resolution: "execa@npm:2.1.0" +"execa@npm:8.0.1": + version: 8.0.1 + resolution: "execa@npm:8.0.1" dependencies: - cross-spawn: "npm:^7.0.0" - get-stream: "npm:^5.0.0" - is-stream: "npm:^2.0.0" + cross-spawn: "npm:^7.0.3" + get-stream: "npm:^8.0.1" + human-signals: "npm:^5.0.0" + is-stream: "npm:^3.0.0" merge-stream: "npm:^2.0.0" - npm-run-path: "npm:^3.0.0" - onetime: "npm:^5.1.0" - p-finally: "npm:^2.0.0" - signal-exit: "npm:^3.0.2" - strip-final-newline: "npm:^2.0.0" - checksum: e1280d17f95f18860bb3e6e2c4a096c847d4fbe06d7a49f4c6d2e3832cb66e84cdf5c302d8c63ffd110f870b8cad4927bd3ea596a69b130a5919de21afcd087a + npm-run-path: "npm:^5.1.0" + onetime: "npm:^6.0.0" + signal-exit: "npm:^4.1.0" + strip-final-newline: "npm:^3.0.0" + checksum: d2ab5fe1e2bb92b9788864d0713f1fce9a07c4594e272c0c97bc18c90569897ab262e4ea58d27a694d288227a2e24f16f5e2575b44224ad9983b799dc7f1098d languageName: node linkType: hard @@ -13138,7 +13180,7 @@ __metadata: languageName: node linkType: hard -"get-stream@npm:^5.0.0, get-stream@npm:^5.1.0": +"get-stream@npm:^5.1.0": version: 5.2.0 resolution: "get-stream@npm:5.2.0" dependencies: @@ -13154,6 +13196,13 @@ __metadata: languageName: node linkType: hard +"get-stream@npm:^8.0.1": + version: 8.0.1 + resolution: "get-stream@npm:8.0.1" + checksum: dde5511e2e65a48e9af80fea64aff11b4921b14b6e874c6f8294c50975095af08f41bfb0b680c887f28b566dd6ec2cb2f960f9d36a323359be324ce98b766e9e + languageName: node + linkType: hard + "get-symbol-description@npm:^1.0.0": version: 1.0.0 resolution: "get-symbol-description@npm:1.0.0" @@ -13928,6 +13977,13 @@ __metadata: languageName: node linkType: hard +"human-signals@npm:^5.0.0": + version: 5.0.0 + resolution: "human-signals@npm:5.0.0" + checksum: 30f8870d831cdcd2d6ec0486a7d35d49384996742052cee792854273fa9dd9e7d5db06bb7985d4953e337e10714e994e0302e90dc6848069171b05ec836d65b0 + languageName: node + linkType: hard + "humanize-ms@npm:^1.2.1": version: 1.2.1 resolution: "humanize-ms@npm:1.2.1" @@ -14005,7 +14061,7 @@ __metadata: languageName: node linkType: hard -"ignore@npm:^5.1.4, ignore@npm:^5.2.0, ignore@npm:^5.2.4": +"ignore@npm:^5.2.0, ignore@npm:^5.2.4": version: 5.2.4 resolution: "ignore@npm:5.2.4" checksum: 4f7caf5d2005da21a382d4bd1d2aa741a3bed51de185c8562dd7f899a81a620ac4fd0619b06f7029a38ae79e4e4c134399db3bd0192c703c3ef54bb82df3086c @@ -14410,6 +14466,13 @@ __metadata: languageName: node linkType: hard +"is-fullwidth-code-point@npm:^4.0.0": + version: 4.0.0 + resolution: "is-fullwidth-code-point@npm:4.0.0" + checksum: 8ae89bf5057bdf4f57b346fb6c55e9c3dd2549983d54191d722d5c739397a903012cc41a04ee3403fd872e811243ef91a7c5196da7b5841dc6b6aae31a264a8d + languageName: node + linkType: hard + "is-function@npm:^1.0.1": version: 1.0.2 resolution: "is-function@npm:1.0.2" @@ -16050,6 +16113,13 @@ __metadata: languageName: node linkType: hard +"lilconfig@npm:2.1.0": + version: 2.1.0 + resolution: "lilconfig@npm:2.1.0" + checksum: b1314a2e55319013d5e7d7d08be39015829d2764a1eaee130129545d40388499d81b1c31b0f9b3417d4db12775a88008b72ec33dd06e0184cf7503b32ca7cc0b + languageName: node + linkType: hard + "limiter@npm:^1.1.5": version: 1.1.5 resolution: "limiter@npm:1.1.5" @@ -16064,6 +16134,26 @@ __metadata: languageName: node linkType: hard +"lint-staged@npm:^15.0.2": + version: 15.0.2 + resolution: "lint-staged@npm:15.0.2" + dependencies: + chalk: "npm:5.3.0" + commander: "npm:11.1.0" + debug: "npm:4.3.4" + execa: "npm:8.0.1" + lilconfig: "npm:2.1.0" + listr2: "npm:7.0.2" + micromatch: "npm:4.0.5" + pidtree: "npm:0.6.0" + string-argv: "npm:0.3.2" + yaml: "npm:2.3.3" + bin: + lint-staged: bin/lint-staged.js + checksum: 79c6487405dff2670bcf7e4721f06705bd33b4fef88d77988565fb9cb2f62608231cbbc706da0ae150b49d0fab447be083c4561164670ec7f407fd183ce27615 + languageName: node + linkType: hard + "listenercount@npm:~1.0.1": version: 1.0.1 resolution: "listenercount@npm:1.0.1" @@ -16071,6 +16161,20 @@ __metadata: languageName: node linkType: hard +"listr2@npm:7.0.2": + version: 7.0.2 + resolution: "listr2@npm:7.0.2" + dependencies: + cli-truncate: "npm:^3.1.0" + colorette: "npm:^2.0.20" + eventemitter3: "npm:^5.0.1" + log-update: "npm:^5.0.1" + rfdc: "npm:^1.3.0" + wrap-ansi: "npm:^8.1.0" + checksum: 42cda5764906f9d298e3b0b0a684e71a3737533b2aef66f361265a3b938c4bc8f49bcea91536a8daa956833658d14108469b00c565c8e93ce4079795f6a06e07 + languageName: node + linkType: hard + "load-yaml-file@npm:^0.2.0": version: 0.2.0 resolution: "load-yaml-file@npm:0.2.0" @@ -16357,6 +16461,19 @@ __metadata: languageName: node linkType: hard +"log-update@npm:^5.0.1": + version: 5.0.1 + resolution: "log-update@npm:5.0.1" + dependencies: + ansi-escapes: "npm:^5.0.0" + cli-cursor: "npm:^4.0.0" + slice-ansi: "npm:^5.0.0" + strip-ansi: "npm:^7.0.1" + wrap-ansi: "npm:^8.0.1" + checksum: 0e154e46744125b6d20c30289e90091794d58b83c2f01d7676da2afa2411c6ec2c3ee2c99753b9c6b896b9ee496a9a403a563330a2d5914a3bdb30e836f17cfb + languageName: node + linkType: hard + "logform@npm:^2.3.2, logform@npm:^2.4.0": version: 2.5.1 resolution: "logform@npm:2.5.1" @@ -17061,7 +17178,7 @@ __metadata: languageName: node linkType: hard -"micromatch@npm:^4.0.2, micromatch@npm:^4.0.4": +"micromatch@npm:4.0.5, micromatch@npm:^4.0.2, micromatch@npm:^4.0.4": version: 4.0.5 resolution: "micromatch@npm:4.0.5" dependencies: @@ -17501,13 +17618,6 @@ __metadata: languageName: node linkType: hard -"mri@npm:^1.1.4": - version: 1.2.0 - resolution: "mri@npm:1.2.0" - checksum: 6775a1d2228bb9d191ead4efc220bd6be64f943ad3afd4dcb3b3ac8fc7b87034443f666e38805df38e8d047b29f910c3cc7810da0109af83e42c82c73bd3f6bc - languageName: node - linkType: hard - "ms@npm:2.0.0": version: 2.0.0 resolution: "ms@npm:2.0.0" @@ -17608,19 +17718,6 @@ __metadata: languageName: node linkType: hard -"multimatch@npm:^4.0.0": - version: 4.0.0 - resolution: "multimatch@npm:4.0.0" - dependencies: - "@types/minimatch": "npm:^3.0.3" - array-differ: "npm:^3.0.0" - array-union: "npm:^2.1.0" - arrify: "npm:^2.0.1" - minimatch: "npm:^3.0.4" - checksum: bdb6a98dad4e919d9a1a2a0db872f44fa2337315f2fd5827d91ae005cf22f4425782bdfa97c10b80d567f0cb3c226c31f4e85f8f6a4a4be4facf9af0de1bb0c2 - languageName: node - linkType: hard - "mute-stream@npm:0.0.7": version: 0.0.7 resolution: "mute-stream@npm:0.0.7" @@ -18092,15 +18189,6 @@ __metadata: languageName: node linkType: hard -"npm-run-path@npm:^3.0.0": - version: 3.1.0 - resolution: "npm-run-path@npm:3.1.0" - dependencies: - path-key: "npm:^3.0.0" - checksum: 141e0b8f0e3b137347a2896572c9a84701754dda0670d3ceb8c56a87702ee03c26227e4517ab93f2904acfc836547315e740b8289bb24ca0cd8ba2b198043b0f - languageName: node - linkType: hard - "npm-run-path@npm:^4.0.1": version: 4.0.1 resolution: "npm-run-path@npm:4.0.1" @@ -18305,10 +18393,10 @@ __metadata: jest-circus: "npm:^29.7.0" jest-junit: "npm:^14.0.1" jest-snapshot: "npm:^29.7.0" + lint-staged: "npm:^15.0.2" patch-package: "npm:^6.2.2" - prettier: "npm:^2.7.1" + prettier: "npm:^3.0.3" prettier-plugin-java: "npm:^1.6.2" - pretty-quick: "npm:^2.0.1" prompt: "npm:1.3.0" semver: "npm:7.5.4" solc: "npm:0.8.22" @@ -18566,13 +18654,6 @@ __metadata: languageName: node linkType: hard -"p-finally@npm:^2.0.0": - version: 2.0.1 - resolution: "p-finally@npm:2.0.1" - checksum: 6306a2851c3b28f8b603624f395ae84dce76970498fed8aa6aae2d930595053746edf1e4ee0c4b78a97410d84aa4504d63179f5310d555511ecd226f53ed1e8e - languageName: node - linkType: hard - "p-limit@npm:^2.0.0, p-limit@npm:^2.2.0": version: 2.3.0 resolution: "p-limit@npm:2.3.0" @@ -19012,6 +19093,15 @@ __metadata: languageName: node linkType: hard +"pidtree@npm:0.6.0": + version: 0.6.0 + resolution: "pidtree@npm:0.6.0" + bin: + pidtree: bin/pidtree.js + checksum: ea67fb3159e170fd069020e0108ba7712df9f0fd13c8db9b2286762856ddce414fb33932e08df4bfe36e91fe860b51852aee49a6f56eb4714b69634343add5df + languageName: node + linkType: hard + "pify@npm:^4.0.1": version: 4.0.1 resolution: "pify@npm:4.0.1" @@ -19231,6 +19321,15 @@ __metadata: languageName: node linkType: hard +"prettier@npm:^3.0.3": + version: 3.0.3 + resolution: "prettier@npm:3.0.3" + bin: + prettier: bin/prettier.cjs + checksum: ccf1ead9794b017be6b42d0873f459070beef2069eb393c8b4c0d11aa3430acefc54f6d5f44a5b7ce9af05ad8daf694b912f0aa2808d1c22dfa86e61e9d563f8 + languageName: node + linkType: hard + "pretty-format@npm:^26.5.2, pretty-format@npm:^26.6.2": version: 26.6.2 resolution: "pretty-format@npm:26.6.2" @@ -19254,24 +19353,6 @@ __metadata: languageName: node linkType: hard -"pretty-quick@npm:^2.0.1": - version: 2.0.2 - resolution: "pretty-quick@npm:2.0.2" - dependencies: - chalk: "npm:^2.4.2" - execa: "npm:^2.1.0" - find-up: "npm:^4.1.0" - ignore: "npm:^5.1.4" - mri: "npm:^1.1.4" - multimatch: "npm:^4.0.0" - peerDependencies: - prettier: ">=1.8.0" - bin: - pretty-quick: bin/pretty-quick.js - checksum: 34aa6ec1f1c54dba0f87d3d4ecfb4c3e0b5744113d5e0a4d6d0d4ba67ac32f0ac44c3c425e1b23255d193696c75df8ad889a010ea200e389b5fab3db81cd8046 - languageName: node - linkType: hard - "process-nextick-args@npm:~1.0.6": version: 1.0.7 resolution: "process-nextick-args@npm:1.0.7" @@ -20420,6 +20501,16 @@ __metadata: languageName: node linkType: hard +"restore-cursor@npm:^4.0.0": + version: 4.0.0 + resolution: "restore-cursor@npm:4.0.0" + dependencies: + onetime: "npm:^5.1.0" + signal-exit: "npm:^3.0.2" + checksum: 5b675c5a59763bf26e604289eab35711525f11388d77f409453904e1e69c0d37ae5889295706b2c81d23bd780165084d040f9b68fffc32cc921519031c4fa4af + languageName: node + linkType: hard + "retry-request@npm:^4.0.0, retry-request@npm:^4.2.2": version: 4.2.2 resolution: "retry-request@npm:4.2.2" @@ -20458,6 +20549,13 @@ __metadata: languageName: node linkType: hard +"rfdc@npm:^1.3.0": + version: 1.3.0 + resolution: "rfdc@npm:1.3.0" + checksum: 76dedd9700cdf132947fde7ce1a8838c9cbb7f3e8f9188af0aaf97194cce745f42094dd2cf547426934cc83252ee2c0e432b2e0222a4415ab0db32de82665c69 + languageName: node + linkType: hard + "rimraf@npm:2, rimraf@npm:^2.6.3": version: 2.7.1 resolution: "rimraf@npm:2.7.1" @@ -20934,7 +21032,7 @@ __metadata: languageName: node linkType: hard -"signal-exit@npm:^4.0.1": +"signal-exit@npm:^4.0.1, signal-exit@npm:^4.1.0": version: 4.1.0 resolution: "signal-exit@npm:4.1.0" checksum: c9fa63bbbd7431066174a48ba2dd9986dfd930c3a8b59de9c29d7b6854ec1c12a80d15310869ea5166d413b99f041bfa3dd80a7947bcd44ea8e6eb3ffeabfa1f @@ -21011,6 +21109,16 @@ __metadata: languageName: node linkType: hard +"slice-ansi@npm:^5.0.0": + version: 5.0.0 + resolution: "slice-ansi@npm:5.0.0" + dependencies: + ansi-styles: "npm:^6.0.0" + is-fullwidth-code-point: "npm:^4.0.0" + checksum: 7e600a2a55e333a21ef5214b987c8358fe28bfb03c2867ff2cbf919d62143d1812ac27b4297a077fdaf27a03da3678e49551c93e35f9498a3d90221908a1180e + languageName: node + linkType: hard + "smart-buffer@npm:^4.2.0": version: 4.2.0 resolution: "smart-buffer@npm:4.2.0" @@ -21367,6 +21475,13 @@ __metadata: languageName: node linkType: hard +"string-argv@npm:0.3.2": + version: 0.3.2 + resolution: "string-argv@npm:0.3.2" + checksum: f9d3addf887026b4b5f997a271149e93bf71efc8692e7dc0816e8807f960b18bcb9787b45beedf0f97ff459575ee389af3f189d8b649834cac602f2e857e75af + languageName: node + linkType: hard + "string-length@npm:^1.0.0": version: 1.0.1 resolution: "string-length@npm:1.0.1" @@ -21425,7 +21540,7 @@ __metadata: languageName: node linkType: hard -"string-width@npm:^5.0.1, string-width@npm:^5.1.2": +"string-width@npm:^5.0.0, string-width@npm:^5.0.1, string-width@npm:^5.1.2": version: 5.1.2 resolution: "string-width@npm:5.1.2" dependencies: @@ -22499,6 +22614,13 @@ __metadata: languageName: node linkType: hard +"type-fest@npm:^1.0.2": + version: 1.4.0 + resolution: "type-fest@npm:1.4.0" + checksum: 89875c247564601c2650bacad5ff80b859007fbdb6c9e43713ae3ffa3f584552eea60f33711dd762e16496a1ab4debd409822627be14097d9a17e39c49db591a + languageName: node + linkType: hard + "type-is@npm:~1.6.18": version: 1.6.18 resolution: "type-is@npm:1.6.18" @@ -24249,7 +24371,7 @@ __metadata: languageName: node linkType: hard -"wrap-ansi@npm:^8.1.0": +"wrap-ansi@npm:^8.0.1, wrap-ansi@npm:^8.1.0": version: 8.1.0 resolution: "wrap-ansi@npm:8.1.0" dependencies: @@ -24511,6 +24633,13 @@ __metadata: languageName: node linkType: hard +"yaml@npm:2.3.3, yaml@npm:^2.2.1": + version: 2.3.3 + resolution: "yaml@npm:2.3.3" + checksum: 3b1a974b9d3672c671d47099a41c0de77b7ff978d0849aa55a095587486e82cd072321d19f2b4c791a367f766310b5a82dff098839b0f4ddcbbbe477f82dfb07 + languageName: node + linkType: hard + "yaml@npm:^1.10.2": version: 1.10.2 resolution: "yaml@npm:1.10.2" @@ -24518,13 +24647,6 @@ __metadata: languageName: node linkType: hard -"yaml@npm:^2.2.1": - version: 2.3.3 - resolution: "yaml@npm:2.3.3" - checksum: 3b1a974b9d3672c671d47099a41c0de77b7ff978d0849aa55a095587486e82cd072321d19f2b4c791a367f766310b5a82dff098839b0f4ddcbbbe477f82dfb07 - languageName: node - linkType: hard - "yargs-parser@npm:13.1.2, yargs-parser@npm:^13.1.2": version: 13.1.2 resolution: "yargs-parser@npm:13.1.2" From 0445136a8279d27ec621a5effd4d0c163219fff2 Mon Sep 17 00:00:00 2001 From: Aaron Date: Tue, 31 Oct 2023 11:15:52 +0100 Subject: [PATCH 2/2] no changeset needed for formatter upgrade --- .changeset/gold-insects-tease.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .changeset/gold-insects-tease.md diff --git a/.changeset/gold-insects-tease.md b/.changeset/gold-insects-tease.md new file mode 100644 index 000000000..a845151cc --- /dev/null +++ b/.changeset/gold-insects-tease.md @@ -0,0 +1,2 @@ +--- +---