Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: externalize env #153

Merged
merged 10 commits into from
Jul 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 { 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 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 @@
}),
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 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 @@
} else {
networkConfig = [
{
genesisTransactions: BCOVRIN_TEST_GENESIS,
genesisTransactions: process.env.BCOVRIN_TEST_GENESIS as string,
indyNamespace: 'bcovrin:testnet',
isProduction: false,
connectOnStartup: true,
Expand Down Expand Up @@ -348,7 +352,7 @@
// instead use the existin JWT token
// if JWT token is not found, create/generate a new token and save in genericRecords
// next time, the same token should be used - instead of creating a new token on every restart event of the agent
token = jwt.sign({ agentInfo: 'agentInfo' }, secretKeyInfo)

Check warning on line 355 in src/cliAgent.ts

View workflow job for this annotation

GitHub Actions / Validate

Caution: `jwt` also has a named export `sign`. Check if you meant to write `import {sign} from 'jsonwebtoken'` instead
await agent.genericRecords.save({
content: {
secretKey: secretKeyInfo,
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 { 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 @@
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 @@
}
} 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 Expand Up @@ -347,7 +348,7 @@
}

public async handleWeb(didOptions: DidCreate) {
let didDocument: any

Check warning on line 351 in src/controllers/did/DidController.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type
if (!didOptions.domain) {
throw Error('domain is required')
}
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 * 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 @@
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 @@
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 Expand Up @@ -389,7 +390,7 @@
private async handleKey(createDidOptions: DidCreate, tenantId: string) {
let didResponse
let did: string
let didDocument: any

Check warning on line 393 in src/controllers/multi-tenancy/MultiTenancyController.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type

await this.agent.modules.tenants.withTenantAgent({ tenantId }, async (tenantAgent) => {
if (!createDidOptions.seed) {
Expand Down Expand Up @@ -444,7 +445,7 @@

private async handleDidPeer(createDidOptions: DidCreate, tenantId: string) {
let didResponse
let did: any

Check warning on line 448 in src/controllers/multi-tenancy/MultiTenancyController.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type

if (!createDidOptions.keyType) {
throw Error('keyType is required')
Expand Down Expand Up @@ -478,7 +479,7 @@

private async handleWeb(createDidOptions: DidCreate, tenantId: string) {
let did
let didDocument: any

Check warning on line 482 in src/controllers/multi-tenancy/MultiTenancyController.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type

if (!createDidOptions.domain) {
throw Error('For web method domain is required')
Expand Down Expand Up @@ -833,7 +834,7 @@
outOfBandRecords = await tenantAgent.oob.getAll()

if (invitationId)
outOfBandRecords = outOfBandRecords.filter((o: any) => o.outOfBandInvitation.id === invitationId)

Check warning on line 837 in src/controllers/multi-tenancy/MultiTenancyController.ts

View workflow job for this annotation

GitHub Actions / Validate

Unexpected any. Specify a different type
outOfBandRecordsRes = outOfBandRecords.map((c: any) => c.toJSON())
})

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
Loading