Skip to content

Commit

Permalink
chore: added prettier and format all existing files (#220)
Browse files Browse the repository at this point in the history
Co-authored-by: Agustina <agusaldasoro@users.noreply.github.com>
Co-authored-by: Agustina Aldasoro <agusaldasoro@gmail.com>
  • Loading branch information
3 people authored Dec 3, 2020
1 parent 2b0fabe commit 89fb48b
Show file tree
Hide file tree
Showing 267 changed files with 17,998 additions and 15,204 deletions.
16 changes: 8 additions & 8 deletions .ci/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { env, envTLD } from "dcl-ops-lib/domain";
import { buildStatic } from "dcl-ops-lib/buildStatic";
import { globalConfig } from "dcl-ops-lib/values";
import { env, envTLD } from 'dcl-ops-lib/domain'
import { buildStatic } from 'dcl-ops-lib/buildStatic'
import { globalConfig } from 'dcl-ops-lib/values'

const { defaultSecurityGroupName } = globalConfig[env]

async function main() {
const builder = buildStatic({
domain: `catalysts.decentraland.${envTLD}`,
});
domain: `catalysts.decentraland.${envTLD}`
})

return {
cloudfrontDistribution: builder.cloudfrontDistribution,
bucketName: builder.contentBucket,
};
bucketName: builder.contentBucket
}
}
export = main;
export = main
5 changes: 5 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
dist
bazel-out
tmpbin
linked-peer-package
**/*.json
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
"dist/**/*": true
},
"typescript.tsdk": "node_modules/typescript/lib",
"editor.formatOnSave": true,
"cSpell.words": [
"Ethereum"
]
],
"editor.rulers": [120]
}
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ A Catalyst is a server that runs different services. These services currently wo

If you just want to run a Catalyst server, please check the [Catalyst Owner](https://github.com/decentraland/catalyst-owner) repository. This repository is mostly used for developing.


## Services

- [Content Server](content)
Expand All @@ -17,3 +16,7 @@ If you just want to run a Catalyst server, please check the [Catalyst Owner](htt
## Monitoring

For monitoring see [the following doc](docs/MONITORING.md)

## Contributions

If using Visual Studio, please download the `prettier` plugin: https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
21 changes: 10 additions & 11 deletions commons/servers/DAOClient.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { ServerMetadata } from "./ServerMetadata";
import { DAOContract, CatalystId, CatalystData } from "decentraland-katalyst-contracts/DAOContract";
import { ServerMetadata } from './ServerMetadata'
import { DAOContract, CatalystId, CatalystData } from 'decentraland-katalyst-contracts/DAOContract'

export interface DAOClient {
getAllContentServers(): Promise<Set<ServerMetadata>>;
getAllServers(): Promise<Set<ServerMetadata>>;
getAllContentServers(): Promise<Set<ServerMetadata>>
getAllServers(): Promise<Set<ServerMetadata>>
}

export class DAOContractClient {
Expand All @@ -16,7 +16,7 @@ export class DAOContractClient {

async getAllContentServers(): Promise<Set<ServerMetadata>> {
const servers: Set<ServerMetadata> = await this.getAllServers()
return new Set(Array.from(servers.values()).map(server => ({ ...server, address: server.address + '/content' })))
return new Set(Array.from(servers.values()).map((server) => ({ ...server, address: server.address + '/content' })))
}

async getAllServers(): Promise<Set<ServerMetadata>> {
Expand Down Expand Up @@ -58,16 +58,15 @@ export class DAOContractClient {

let address = domain.trim()

if (address.startsWith("http://")) {
console.warn(`Catalyst node domain using http protocol, skipping ${address}`);
if (address.startsWith('http://')) {
console.warn(`Catalyst node domain using http protocol, skipping ${address}`)
return undefined
}

if (!address.startsWith("https://")) {
address = "https://" + address;
if (!address.startsWith('https://')) {
address = 'https://' + address
}

return { address, owner, id };
return { address, owner, id }
}

}
10 changes: 5 additions & 5 deletions commons/servers/ServerMetadata.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { EthAddress } from "dcl-crypto";
import { EthAddress } from 'dcl-crypto'
export type ServerMetadata = {
address: string;
owner: EthAddress;
id: string;
};
address: string
owner: EthAddress
id: string
}
4 changes: 2 additions & 2 deletions commons/servers/addresses.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { EthAddress } from "dcl-crypto";
import { EthAddress } from 'dcl-crypto'

export const DECENTRALAND_ADDRESS: EthAddress = "0x1337e0507eb4ab47e08a179573ed4533d9e22a7b";
export const DECENTRALAND_ADDRESS: EthAddress = '0x1337e0507eb4ab47e08a179573ed4533d9e22a7b'
18 changes: 9 additions & 9 deletions commons/servers/fsutils.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
import fs from "fs";
import fs from 'fs'

export async function existPath(path: string): Promise<boolean> {
try {
await fs.promises.access(path, fs.constants.F_OK | fs.constants.W_OK);
return true;
await fs.promises.access(path, fs.constants.F_OK | fs.constants.W_OK)
return true
} catch (error) {
return false;
return false
}
}

export async function ensureDirectoryExists(directory: string): Promise<void> {
const alreadyExist = await existPath(directory)
if (!alreadyExist) {
try {
await fs.promises.mkdir(directory, { recursive: true });
} catch (error) {
// Ignore these errors
}
try {
await fs.promises.mkdir(directory, { recursive: true })
} catch (error) {
// Ignore these errors
}
}
}
16 changes: 8 additions & 8 deletions commons/servers/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Request, Response, NextFunction, RequestHandler } from "express-serve-static-core";
import { EthAddress, Authenticator } from "dcl-crypto";
import { EthereumProvider } from "web3x/providers";
import { SignerData, SignatureValidator, validateSignature } from "./signatures";
import { Request, Response, NextFunction, RequestHandler } from 'express-serve-static-core'
import { EthAddress, Authenticator } from 'dcl-crypto'
import { EthereumProvider } from 'web3x/providers'
import { SignerData, SignatureValidator, validateSignature } from './signatures'

/**
* @param messageToSignBuilder Function to build the signature payload to test against. Keep in mind that the timestamp will be appended to the result.
Expand All @@ -17,16 +17,16 @@ export function validateSignatureHandler(
signatureValidator: SignatureValidator = Authenticator.validateSignature
): RequestHandler {
return async (req: Request, res: Response, next: NextFunction) => {
const signerData = signerDataBuilder(req.body);
const signerData = signerDataBuilder(req.body)

await validateSignature(
signerData,
`${messageToSignBuilder(req.body)}${signerData.timestamp}`,
next,
(message) => res.status(401).send({ status: "unauthorized", message }),
(message) => res.status(401).send({ status: 'unauthorized', message }),
(signer) => authorizedSignerPredicate(signer, req.body),
networkOrProvider,
signatureValidator
);
};
)
}
}
92 changes: 46 additions & 46 deletions commons/servers/metrics.ts
Original file line number Diff line number Diff line change
@@ -1,56 +1,56 @@
import express from 'express';
import ResponseTime from 'response-time';
import { register as Register, Counter, Summary, collectDefaultMetrics } from 'prom-client';
import express from 'express'
import ResponseTime from 'response-time'
import { register as Register, Counter, Summary, collectDefaultMetrics } from 'prom-client'

const pathsTaken = new Counter({
name: 'paths_taken',
help: 'Paths taken in the app',
labelNames: ['path']
});
name: 'paths_taken',
help: 'Paths taken in the app',
labelNames: ['path']
})

const responses = new Summary({
name: 'http_responses',
help: 'Response time in milliseconds',
labelNames: ['method', 'path', 'status']
});
name: 'http_responses',
help: 'Response time in milliseconds',
labelNames: ['method', 'path', 'status']
})

const numRequests = new Counter({
name: 'num_requests',
help: 'Number of requests made',
labelNames: ['method']
});
name: 'num_requests',
help: 'Number of requests made',
labelNames: ['method']
})

const port = parseInt(process.env.METRICS_PORT ?? "9090");
const port = parseInt(process.env.METRICS_PORT ?? '9090')

export class Metrics {
static initialize(app: express.Express) {
const metricsServer = express();
app.use(Metrics.requestCounters);
app.use(Metrics.responseCounters);
this.injectMetricsRoute(metricsServer);
this.startCollection(metricsServer);
}

static requestCounters = function (req, res, next) {
numRequests.inc({ method: req.method });
pathsTaken.inc({ path: req.path });
next();
}

static responseCounters = ResponseTime(function (req, res, time) {
responses.labels(req.method, req.url, res.statusCode).observe(time);
static initialize(app: express.Express) {
const metricsServer = express()
app.use(Metrics.requestCounters)
app.use(Metrics.responseCounters)
this.injectMetricsRoute(metricsServer)
this.startCollection(metricsServer)
}

static requestCounters = function (req, res, next) {
numRequests.inc({ method: req.method })
pathsTaken.inc({ path: req.path })
next()
}

static responseCounters = ResponseTime(function (req, res, time) {
responses.labels(req.method, req.url, res.statusCode).observe(time)
})

static injectMetricsRoute(app: express.Express) {
app.get('/metrics', (req, res) => {
res.set('Content-Type', Register.contentType)
res.end(Register.metrics())
})

static injectMetricsRoute(app: express.Express) {
app.get('/metrics', (req, res) => {
res.set('Content-Type', Register.contentType);
res.end(Register.metrics());
});
};

static startCollection(app: express.Express) {
console.log(`Starting the collection of metrics, the metrics are available on :${port}/metrics`);
collectDefaultMetrics();
app.listen(port);
};
}
}

static startCollection(app: express.Express) {
console.log(`Starting the collection of metrics, the metrics are available on :${port}/metrics`)
collectDefaultMetrics()
app.listen(port)
}
}
60 changes: 35 additions & 25 deletions commons/servers/signatures.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,45 @@
import { EthAddress, Signature, AuthChain, Authenticator, ValidationResult } from "dcl-crypto";
import { EthereumProvider } from "web3x/providers";
import { httpProviderForNetwork } from "decentraland-katalyst-contracts/utils";
import { EthAddress, Signature, AuthChain, Authenticator, ValidationResult } from 'dcl-crypto'
import { EthereumProvider } from 'web3x/providers'
import { httpProviderForNetwork } from 'decentraland-katalyst-contracts/utils'

// We want all signatures to be "current". We consider "current" to be the current time,
// with a 10 minute tolerance to account for network delays and possibly unsynched clocks
export const VALID_SIGNATURE_TOLERANCE_INTERVAL_MS = 10 * 1000 * 60;
export const VALID_SIGNATURE_TOLERANCE_INTERVAL_MS = 10 * 1000 * 60

export type SimpleSignature = {
signer: EthAddress;
signature: Signature;
};
signer: EthAddress
signature: Signature
}

export type SignerData = {
authChain?: AuthChain;
simpleSignature?: SimpleSignature;
timestamp: number;
};
authChain?: AuthChain
simpleSignature?: SimpleSignature
timestamp: number
}

function getSigner(signerData: SignerData) {
if (signerData.authChain) {
const ownerAddress = Authenticator.ownerAddress(signerData.authChain);
return ownerAddress === "Invalid-Owner-Address" ? undefined : ownerAddress;
const ownerAddress = Authenticator.ownerAddress(signerData.authChain)
return ownerAddress === 'Invalid-Owner-Address' ? undefined : ownerAddress
} else {
return signerData.simpleSignature?.signer;
return signerData.simpleSignature?.signer
}
}

function validSignatureInterval(timestamp: number) {
const currentTime = Date.now();
return timestamp > currentTime - VALID_SIGNATURE_TOLERANCE_INTERVAL_MS && timestamp < currentTime + VALID_SIGNATURE_TOLERANCE_INTERVAL_MS;
const currentTime = Date.now()
return (
timestamp > currentTime - VALID_SIGNATURE_TOLERANCE_INTERVAL_MS &&
timestamp < currentTime + VALID_SIGNATURE_TOLERANCE_INTERVAL_MS
)
}

export type SignatureValidator = (
expectedFinalAuthority: string,
authChain: AuthChain,
provider: EthereumProvider,
dateToValidateExpirationInMillis?: number
) => Promise<ValidationResult>;
) => Promise<ValidationResult>

export async function validateSignature(
signerData: SignerData,
Expand All @@ -48,20 +51,27 @@ export async function validateSignature(
validator: SignatureValidator = Authenticator.validateSignature
) {
if (!signerData.authChain && !signerData.simpleSignature) {
onNotAuthorized("This operation requires a signed payload");
onNotAuthorized('This operation requires a signed payload')
} else if (!validSignatureInterval(signerData.timestamp)) {
onNotAuthorized("The signature is too old or too far in the future");
onNotAuthorized('The signature is too old or too far in the future')
} else if (!signerIsAuthorizedPredicate(getSigner(signerData))) {
onNotAuthorized("The signer is not authorized to perform this operation");
onNotAuthorized('The signer is not authorized to perform this operation')
} else {
const authChain = signerData.authChain ?? Authenticator.createSimpleAuthChain(expectedPayload, signerData.simpleSignature!.signer, signerData.simpleSignature!.signature);
const provider = typeof networkOrProvider === "string" ? httpProviderForNetwork(networkOrProvider) : networkOrProvider;
const valid = await validator(expectedPayload, authChain, provider, Date.now());
const authChain =
signerData.authChain ??
Authenticator.createSimpleAuthChain(
expectedPayload,
signerData.simpleSignature!.signer,
signerData.simpleSignature!.signature
)
const provider =
typeof networkOrProvider === 'string' ? httpProviderForNetwork(networkOrProvider) : networkOrProvider
const valid = await validator(expectedPayload, authChain, provider, Date.now())

if (!valid.ok) {
onNotAuthorized("Invalid signature: " + valid.message);
onNotAuthorized('Invalid signature: ' + valid.message)
} else {
onAuthorized();
onAuthorized()
}
}
}
Loading

0 comments on commit 89fb48b

Please sign in to comment.