Skip to content

Env configuration #30

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

Merged
merged 2 commits into from
Apr 18, 2025
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
7 changes: 7 additions & 0 deletions eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ export default tseslint.config(
'@typescript-eslint/no-unsafe-assignment': 'off',
'@typescript-eslint/no-unsafe-call': 'off',
'@typescript-eslint/no-unsafe-member-access': 'off',
'no-restricted-syntax': [
'error',
{
selector: "MemberExpression[object.name='process'][property.name='env']",
message: 'Use ENV_CONFIG instead of process.env',
},
],
},
},
);
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
"cors": "^2.8.5",
"csv": "^6.3.11",
"csv-stringify": "^6.5.2",
"dotenv": "^16.5.0",
"jsonwebtoken": "^9.0.2",
"lodash": "^4.17.21",
"reflect-metadata": "^0.2.2",
Expand Down
33 changes: 21 additions & 12 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion src/api/webhooks/trolley/trolley.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ import crypto from 'crypto';
import { Inject, Injectable } from '@nestjs/common';
import { trolley_webhook_log, webhook_status } from '@prisma/client';
import { PrismaService } from 'src/shared/global/prisma.service';
import { ENV_CONFIG } from 'src/config';

enum TrolleyHeaders {
id = 'x-paymentrails-delivery',
signature = 'x-paymentrails-signature',
created = 'x-paymentrails-created',
}

const trolleyWhHmac = process.env.TROLLEY_WH_HMAC;
const trolleyWhHmac = ENV_CONFIG.TROLLEY_WH_HMAC;
if (!trolleyWhHmac) {
throw new Error('TROLLEY_WH_HMAC is not set!');
}
Expand Down
53 changes: 53 additions & 0 deletions src/config/config.env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { IsInt, IsOptional, IsString } from 'class-validator';

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider verifying that changing from IsNumber to IsInt does not affect any existing functionality that relies on non-integer numbers for the PORT variable. If PORT is strictly an integer, this change is appropriate.


export class ConfigEnv {
@IsString()
@IsOptional()
API_BASE = '/v5/finance';

@IsInt()
@IsOptional()
PORT = 3000;

@IsString()
TOPCODER_API_BASE_URL!: string;

@IsString()
AUTH0_M2M_AUDIENCE!: string;

@IsString()
AUTH0_TC_PROXY_URL!: string;

@IsString()
AUTH0_M2M_CLIENT_ID!: string;

@IsString()
AUTH0_M2M_SECRET!: string;

@IsString()
AUTH0_M2M_TOKEN_URL!: string;

@IsString()
AUTH0_M2M_GRANT_TYPE!: string;

@IsString()
AUTH0_CERT!: string;

@IsString()
AUTH0_CLIENT_ID!: string;

@IsString()
DATABASE_URL!: string;

@IsString()
TROLLEY_WIDGET_BASE_URL!: string;

@IsString()
TROLLEY_WH_HMAC!: string;

@IsString()
TROLLEY_ACCESS_KEY!: string;

@IsString()
TROLLEY_SECRET_KEY!: string;
}
45 changes: 45 additions & 0 deletions src/config/config.loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import * as dotenv from 'dotenv';
import { plainToInstance } from 'class-transformer';
import { validateSync } from 'class-validator';
import { Logger } from '@nestjs/common';
import { ConfigEnv } from './config.env';

/**
* Loads and validates environment variables into a `ConfigEnv` instance.
*
* This function uses `plainToInstance` to map environment variables from `process.env`
* into a `ConfigEnv` class instance, enabling implicit conversion and exposing default values.
* It then validates the resulting instance using `validateSync` to ensure all required
* properties are present and conform to the expected constraints.
*
* If validation errors are found, they are logged using a `Logger` instance, and an error
* is thrown to indicate invalid environment variables.
*
* @throws {Error} If any environment variables are invalid or missing.
* @returns {ConfigEnv} A validated instance of the `ConfigEnv` class.
*/
function loadAndValidateEnv(): ConfigEnv {
// eslint-disable-next-line no-restricted-syntax
const env = plainToInstance(ConfigEnv, process.env, {
enableImplicitConversion: true,
exposeDefaultValues: true,
});

const errors = validateSync(env, {
skipMissingProperties: false,
whitelist: true,
});

if (errors.length > 0) {
const logger = new Logger('Config');
for (const err of errors) {
logger.error(JSON.stringify(err.constraints));
}
throw new Error('Invalid environment variables');
}

return env;
}

dotenv.config();
export const ENV_CONFIG = loadAndValidateEnv();
1 change: 1 addition & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './config.loader';
7 changes: 4 additions & 3 deletions src/core/auth/middleware/tokenValidator.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
UnauthorizedException,
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { ENV_CONFIG } from 'src/config';

@Injectable()
export class TokenValidatorMiddleware implements NestMiddleware {
Expand All @@ -16,7 +17,7 @@ export class TokenValidatorMiddleware implements NestMiddleware {

let decoded: any;
try {
decoded = jwt.verify(idToken, process.env.AUTH0_CERT);
decoded = jwt.verify(idToken, ENV_CONFIG.AUTH0_CERT);
} catch (error) {
console.error('Error verifying JWT', error);
throw new UnauthorizedException('Invalid or expired JWT!');
Expand All @@ -29,8 +30,8 @@ export class TokenValidatorMiddleware implements NestMiddleware {

req.isM2M = !!decoded.scope;
const aud = req.isM2M
? process.env.AUTH0_M2M_AUDIENCE
: process.env.AUTH0_CLIENT_ID;
? ENV_CONFIG.AUTH0_M2M_AUDIENCE
: ENV_CONFIG.AUTH0_CLIENT_ID;

if (decoded.aud !== aud) {
req.idTokenVerified = false;
Expand Down
7 changes: 4 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import { ApiModule } from './api/api.module';
import { AppModule } from './app.module';
import { PaymentProvidersModule } from './api/payment-providers/payment-providers.module';
import { WebhooksModule } from './api/webhooks/webhooks.module';
import { ENV_CONFIG } from './config';

async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule, {
rawBody: true,
});

// Global prefix for all routes is configured as `/v5/finance`
app.setGlobalPrefix(process.env.API_BASE ?? '/v5/finance');
// Global prefix for all routes
app.setGlobalPrefix(ENV_CONFIG.API_BASE);

// CORS related settings
const corsConfig: cors.CorsOptions = {
Expand Down Expand Up @@ -67,7 +68,7 @@ async function bootstrap() {
);
});

await app.listen(process.env.PORT ?? 3000);
await app.listen(ENV_CONFIG.PORT ?? 3000);
}

void bootstrap();
7 changes: 5 additions & 2 deletions src/shared/global/trolley.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import url from 'url';
import crypto from 'crypto';
import trolley from 'trolleyhq';
import { Injectable } from '@nestjs/common';
import { ENV_CONFIG } from 'src/config';

const { TROLLEY_ACCESS_KEY, TROLLEY_SECRET_KEY, TROLLEY_WIDGET_BASE_URL } =
process.env;

const TROLLEY_ACCESS_KEY = ENV_CONFIG.TROLLEY_ACCESS_KEY;
const TROLLEY_SECRET_KEY = ENV_CONFIG.TROLLEY_SECRET_KEY;
const TROLLEY_WIDGET_BASE_URL = ENV_CONFIG.TROLLEY_WIDGET_BASE_URL;

const client = trolley({
key: TROLLEY_ACCESS_KEY as string,
Expand Down
7 changes: 5 additions & 2 deletions src/shared/topcoder/members.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import { chunk } from 'lodash';
import { Injectable } from '@nestjs/common';
import { MEMBER_FIELDS } from './member.types';
import { TopcoderM2MService } from './topcoder-m2m.service';
import { ENV_CONFIG } from 'src/config';

const { TOPCODER_API_BASE_URL } = ENV_CONFIG;

@Injectable()
export class TopcoderMembersService {
Expand All @@ -21,7 +24,7 @@ export class TopcoderMembersService {

// Split the unique user IDs into chunks of 100 to comply with API request limits
const requests = chunk(uniqUserIds, 30).map((chunk) => {
const requestUrl = `${process.env.TOPCODER_API_BASE_URL}/members?${chunk.map((id) => `userIds[]=${id}`).join('&')}&fields=handle,userId`;
const requestUrl = `${TOPCODER_API_BASE_URL}/members?${chunk.map((id) => `userIds[]=${id}`).join('&')}&fields=handle,userId`;
return fetch(requestUrl).then(
async (response) =>
(await response.json()) as { handle: string; userId: string },
Expand Down Expand Up @@ -67,7 +70,7 @@ export class TopcoderMembersService {
e.message ?? e,
);
}
const requestUrl = `${process.env.TOPCODER_API_BASE_URL}/members/${handle}${fields ? `?fields=${fields.join(',')}` : ''}`;
const requestUrl = `${TOPCODER_API_BASE_URL}/members/${handle}${fields ? `?fields=${fields.join(',')}` : ''}`;

try {
const response: { [key: string]: string } = await fetch(requestUrl, {
Expand Down
13 changes: 7 additions & 6 deletions src/shared/topcoder/topcoder-m2m.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { ENV_CONFIG } from 'src/config';

@Injectable()
export class TopcoderM2MService {
Expand All @@ -18,17 +19,17 @@ export class TopcoderM2MService {
* - `AUTH0_M2M_GRANT_TYPE`: The grant type for the M2M token request.
*/
async getToken(): Promise<string | undefined> {
const tokenURL = `${process.env.AUTH0_TC_PROXY_URL}/token`;
const tokenURL = `${ENV_CONFIG.AUTH0_TC_PROXY_URL}/token`;
try {
const response = await fetch(tokenURL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
auth0_url: `${process.env.AUTH0_M2M_TOKEN_URL}/oauth/token`,
client_id: process.env.AUTH0_M2M_CLIENT_ID,
client_secret: process.env.AUTH0_M2M_SECRET,
audience: process.env.AUTH0_M2M_AUDIENCE,
grant_type: process.env.AUTH0_M2M_GRANT_TYPE,
auth0_url: `${ENV_CONFIG.AUTH0_M2M_TOKEN_URL}/oauth/token`,
client_id: ENV_CONFIG.AUTH0_M2M_CLIENT_ID,
client_secret: ENV_CONFIG.AUTH0_M2M_SECRET,
audience: ENV_CONFIG.AUTH0_M2M_AUDIENCE,
grant_type: ENV_CONFIG.AUTH0_M2M_GRANT_TYPE,
}),
});

Expand Down