Skip to content

Commit

Permalink
feat: externalize env (#153)
Browse files Browse the repository at this point in the history
Signed-off-by: KulkarniShashank <[email protected]>
  • Loading branch information
GHkrishna authored and KulkarniShashank committed Sep 13, 2024
1 parent 32cf432 commit c710479
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 32 deletions.
49 changes: 36 additions & 13 deletions src/utils/util.ts → .env.sample

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"axios": "^1.4.0",
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.18.1",
"express-rate-limit": "^7.1.5",
"joi": "^17.12.3",
Expand Down
6 changes: 3 additions & 3 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,9 @@ export async function runCliServer() {
type: parsed['wallet-type'],
config: {
host: parsed['wallet-url'],
connectTimeout: 10,
maxConnections: 1000,
idleTimeout: 30000,
connectTimeout: Number(process.env.CONNECT_TIMEOUT),
maxConnections: Number(process.env.MAX_CONNECTIONS),
idleTimeout: Number(process.env.IDLE_TIMEOUT),
},
credentials: {
account: parsed['wallet-account'],
Expand Down
26 changes: 15 additions & 11 deletions src/cliAgent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ import jwt from 'jsonwebtoken'

import { setupServer } from './server'
import { TsLogger } from './utils/logger'
import { BCOVRIN_TEST_GENESIS } from './utils/util'

export type Transports = 'ws' | 'http'
export type InboundTransport = {
Expand Down Expand Up @@ -114,6 +113,12 @@ export type RestMultiTenantAgentModules = Awaited<ReturnType<typeof getWithTenan
export type RestAgentModules = Awaited<ReturnType<typeof getModules>>

const getModules = (networkConfig: [IndyVdrPoolConfig, ...IndyVdrPoolConfig[]]) => {
const didContractAddress = process.env.DID_CONTRACT_ADDRESS as string
const schemaManagerContractAddress = process.env.SCHEMA_MANAGER_CONTRACT_ADDRESS as string
const fileServerToken = process.env.FILE_SERVER_TOKEN
const rpcUrl = process.env.RPC_URL
const serverUrl = process.env.SERVER_URL

const legacyIndyCredentialFormat = new LegacyIndyCredentialFormatService()
const legacyIndyProofFormat = new LegacyIndyProofFormatService()
const jsonLdCredentialFormatService = new JsonLdCredentialFormatService()
Expand Down Expand Up @@ -172,17 +177,16 @@ const getModules = (networkConfig: [IndyVdrPoolConfig, ...IndyVdrPoolConfig[]])
}),
w3cCredentials: new W3cCredentialsModule(),
cache: new CacheModule({
cache: new InMemoryLruCache({ limit: Infinity }),
cache: new InMemoryLruCache({ limit: Number(process.env.INMEMORY_LRU_CACHE_LIMIT) }),
}),

questionAnswer: new QuestionAnswerModule(),
polygon: new PolygonModule({
didContractAddress: '0x1adeA199dCf07E17232415Cb232442BE52517Add',
schemaManagerContractAddress: '0x289c7Bd4C7d38cC54bff370d6f9f01b74Df51b11',
fileServerToken:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJBeWFuV29ya3MiLCJpZCI6ImNhZDI3ZjhjLTMyNWYtNDRmZC04ZmZkLWExNGNhZTY3NTMyMSJ9.I3IR7abjWbfStnxzn1BhxhV0OEzt1x3mULjDdUcgWHk',
rpcUrl: 'https://rpc-amoy.polygon.technology',
serverUrl: 'https://schema.credebl.id',
didContractAddress: didContractAddress,
schemaManagerContractAddress: schemaManagerContractAddress,
fileServerToken: fileServerToken,
rpcUrl: rpcUrl,
serverUrl: serverUrl,
}),
}
}
Expand All @@ -191,8 +195,8 @@ const getWithTenantModules = (networkConfig: [IndyVdrPoolConfig, ...IndyVdrPoolC
const modules = getModules(networkConfig)
return {
tenants: new TenantsModule<typeof modules>({
sessionAcquireTimeout: Infinity,
sessionLimit: Infinity,
sessionAcquireTimeout: Number(process.env.SESSION_ACQUIRE_TIMEOUT),
sessionLimit: Number(process.env.SESSION_LIMIT),
}),
...modules,
}
Expand Down Expand Up @@ -291,7 +295,7 @@ export async function runRestAgent(restConfig: AriesRestConfig) {
} else {
networkConfig = [
{
genesisTransactions: BCOVRIN_TEST_GENESIS,
genesisTransactions: process.env.BCOVRIN_TEST_GENESIS as string,
indyNamespace: 'bcovrin:testnet',
isProduction: false,
connectOnStartup: true,
Expand Down
3 changes: 2 additions & 1 deletion src/controllers/did/DidController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import axios from 'axios'
import { injectable } from 'tsyringe'

import { DidMethod, Network, Role } from '../../enums/enum'
import { BCOVRIN_REGISTER_URL, INDICIO_NYM_URL } from '../../utils/util'
import { Did, DidRecordExample } from '../examples'
import { DidCreate } from '../types'

Expand Down Expand Up @@ -163,6 +162,7 @@ export class DidController extends Controller {
didDocument: didDocument,
}
} else {
const BCOVRIN_REGISTER_URL = process.env.BCOVRIN_REGISTER_URL as string
const res = await axios.post(BCOVRIN_REGISTER_URL, {
role: 'ENDORSER',
alias: 'Alias',
Expand Down Expand Up @@ -216,6 +216,7 @@ export class DidController extends Controller {
}
} else {
const key = await this.createIndicioKey(createDidOptions)
const INDICIO_NYM_URL = process.env.INDICIO_NYM_URL as string
const res = await axios.post(INDICIO_NYM_URL, key)
if (res.data.statusCode === 200) {
await this.importDid(didMethod, key.did, createDidOptions.seed)
Expand Down
3 changes: 2 additions & 1 deletion src/controllers/multi-tenancy/MultiTenancyController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ import axios from 'axios'
import * as fs from 'fs'

import { CredentialEnum, DidMethod, Network, Role } from '../../enums/enum'
import { BCOVRIN_REGISTER_URL, INDICIO_NYM_URL } from '../../utils/util'
import { SchemaId, CredentialDefinitionId, RecordId, ProofRecordExample, ConnectionRecordExample } from '../examples'
import {
RequestProofOptions,
Expand Down Expand Up @@ -254,6 +253,7 @@ export class MultiTenancyController extends Controller {
seed: createDidOptions.seed,
}

const BCOVRIN_REGISTER_URL = process.env.BCOVRIN_REGISTER_URL as string
const res = await axios.post(BCOVRIN_REGISTER_URL, body)
if (res) {
const { did } = res?.data || {}
Expand Down Expand Up @@ -353,6 +353,7 @@ export class MultiTenancyController extends Controller {
verkey: TypedArrayEncoder.toBase58(buffer),
}
}
const INDICIO_NYM_URL = process.env.INDICIO_NYM_URL as string
const res = await axios.post(INDICIO_NYM_URL, body)
if (res.data.statusCode === 200) {
await this.importDid(didMethod, did, createDidOptions.seed, tenantAgent)
Expand Down
6 changes: 5 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { Response as ExResponse, Request as ExRequest, NextFunction } from
import { Agent } from '@credo-ts/core'
import bodyParser from 'body-parser'
import cors from 'cors'
import dotenv from 'dotenv'
import express from 'express'
import { rateLimit } from 'express-rate-limit'
import * as fs from 'fs'
Expand All @@ -19,10 +20,11 @@ import { proofEvents } from './events/ProofEvents'
import { questionAnswerEvents } from './events/QuestionAnswerEvents'
import { RegisterRoutes } from './routes/routes'
import { SecurityMiddleware } from './securityMiddleware'
import { maxRateLimit, windowMs } from './utils/util'

import { ValidateError, type Exception } from 'tsoa'

dotenv.config()

export const setupServer = async (agent: Agent, config: ServerConfig, apiKey?: string) => {
container.registerInstance(Agent, agent)
fs.writeFileSync('config.json', JSON.stringify(config, null, 2))
Expand Down Expand Up @@ -51,6 +53,8 @@ export const setupServer = async (agent: Agent, config: ServerConfig, apiKey?: s
return res.send(generateHTML(await import('./routes/swagger.json')))
})

const windowMs = Number(process.env.windowMs)
const maxRateLimit = Number(process.env.maxRateLimit)
const limiter = rateLimit({
windowMs, // 1 second
max: maxRateLimit, // max 800 requests per second
Expand Down
3 changes: 1 addition & 2 deletions src/utils/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ import { ariesAskar } from '@hyperledger/aries-askar-nodejs'
import { indyVdr } from '@hyperledger/indy-vdr-nodejs'

import { TsLogger } from './logger'
import { BCOVRIN_TEST_GENESIS } from './util'

export const setupAgent = async ({ name, endpoints, port }: { name: string; endpoints: string[]; port: number }) => {
const logger = new TsLogger(LogLevel.debug)
Expand All @@ -62,7 +61,7 @@ export const setupAgent = async ({ name, endpoints, port }: { name: string; endp
{
isProduction: false,
indyNamespace: 'bcovrin:test',
genesisTransactions: BCOVRIN_TEST_GENESIS,
genesisTransactions: process.env.BCOVRIN_TEST_GENESIS as string,
connectOnStartup: true,
},
],
Expand Down

0 comments on commit c710479

Please sign in to comment.