Skip to content
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
8 changes: 5 additions & 3 deletions packages/apps/human-app/server/jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
process.env['GIT_HASH'] = 'test_value_hardcoded_in_jest_config';

import { createDefaultPreset } from 'ts-jest';

const jestTsPreset = createDefaultPreset({});

module.exports = {
...jestTsPreset,
coverageDirectory: '../coverage',
collectCoverageFrom: ['**/*.(t|j)s'],
moduleFileExtensions: ['js', 'json', 'ts'],
rootDir: 'src',
testEnvironment: 'node',
testRegex: '.*\\.spec\\.ts$',
transform: {
'^.+\\.(t|j)s$': 'ts-jest',
},
moduleNameMapper: {
'^uuid$': require.resolve('uuid'),
},
Expand Down
1 change: 0 additions & 1 deletion packages/apps/human-app/server/scripts/generate-env-doc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ function processConfigFiles() {
'common-config.module.ts',
'gateway-config.service.ts',
'gateway-config.types.ts',
'params-decorators.ts',
'spec',
].includes(file),
);
Expand Down
2 changes: 2 additions & 0 deletions packages/apps/human-app/server/src/app.controller.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { Controller, Get, Redirect } from '@nestjs/common';
import { ApiExcludeEndpoint } from '@nestjs/swagger';
import { Public } from './common/decorators';

@Controller()
export class AppController {
@Get('/')
@Public()
@Redirect('/swagger', 301)
@ApiExcludeEndpoint()
public swagger(): string {
Expand Down
86 changes: 48 additions & 38 deletions packages/apps/human-app/server/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,51 +1,54 @@
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { AppController } from './app.controller';
import { ConfigModule } from '@nestjs/config';
import { HttpModule } from '@nestjs/axios';
import { WorkerModule } from './modules/user-worker/worker.module';
import { ReputationOracleModule } from './integrations/reputation-oracle/reputation-oracle.module';
import { AutomapperModule } from '@automapper/nestjs';
import { classes } from '@automapper/classes';
import { OperatorModule } from './modules/user-operator/operator.module';
import { OperatorController } from './modules/user-operator/operator.controller';
import { WorkerController } from './modules/user-worker/worker.controller';
import { CommonConfigModule } from './common/config/common-config.module';
import { CacheFactoryConfig } from './common/config/cache-factory.config';
import { AutomapperModule } from '@automapper/nestjs';
import { ChainId } from '@human-protocol/sdk';
import { HttpModule } from '@nestjs/axios';
import { CacheModule } from '@nestjs/cache-manager';
import { OracleDiscoveryController } from './modules/oracle-discovery/oracle-discovery.controller';
import { OracleDiscoveryModule } from './modules/oracle-discovery/oracle-discovery.module';
import { JobsDiscoveryModule } from './modules/jobs-discovery/jobs-discovery.module';
import { JobsDiscoveryController } from './modules/jobs-discovery/jobs-discovery.controller';
import { JobAssignmentController } from './modules/job-assignment/job-assignment.controller';
import { JobAssignmentModule } from './modules/job-assignment/job-assignment.module';
import { StatisticsModule } from './modules/statistics/statistics.module';
import { StatisticsController } from './modules/statistics/statistics.controller';
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core';
import Joi from 'joi';
import { AppController } from './app.controller';
import { CacheFactoryConfig } from './common/config/cache-factory.config';
import { CommonConfigModule } from './common/config/common-config.module';
import { EnvironmentConfigService } from './common/config/environment-config.service';
import { JwtAuthGuard } from './common/guards/jwt.auth';
import { JwtHttpStrategy } from './common/guards/strategy';
import { InterceptorModule } from './common/interceptors/interceptor.module';
import { ForbidUnauthorizedHostMiddleware } from './common/middleware/host-check.middleware';
import { EscrowUtilsModule } from './integrations/escrow/escrow-utils.module';
import { ExchangeOracleModule } from './integrations/exchange-oracle/exchange-oracle.module';
import { HCaptchaLabelingModule } from './integrations/h-captcha-labeling/h-captcha-labeling.module';
import { KvStoreModule } from './integrations/kv-store/kv-store.module';
import { ReputationOracleModule } from './integrations/reputation-oracle/reputation-oracle.module';
import { AbuseController } from './modules/abuse/abuse.controller';
import { AbuseModule } from './modules/abuse/abuse.module';
import { CronJobModule } from './modules/cron-job/cron-job.module';
import { EmailConfirmationModule } from './modules/email-confirmation/email-confirmation.module';
import { PasswordResetModule } from './modules/password-reset/password-reset.module';
import { HCaptchaController } from './modules/h-captcha/h-captcha.controller';
import { HCaptchaModule } from './modules/h-captcha/h-captcha.module';
import { HealthModule } from './modules/health/health.module';
import { JobAssignmentController } from './modules/job-assignment/job-assignment.controller';
import { JobAssignmentModule } from './modules/job-assignment/job-assignment.module';
import { JobsDiscoveryController } from './modules/jobs-discovery/jobs-discovery.controller';
import { JobsDiscoveryModule } from './modules/jobs-discovery/jobs-discovery.module';
import { KycProcedureModule } from './modules/kyc-procedure/kyc-procedure.module';
import { NDAController } from './modules/nda/nda.controller';
import { NDAModule } from './modules/nda/nda.module';
import { OracleDiscoveryController } from './modules/oracle-discovery/oracle-discovery.controller';
import { OracleDiscoveryModule } from './modules/oracle-discovery/oracle-discovery.module';
import { PasswordResetModule } from './modules/password-reset/password-reset.module';
import { PrepareSignatureModule } from './modules/prepare-signature/prepare-signature.module';
import { HCaptchaModule } from './modules/h-captcha/h-captcha.module';
import { HCaptchaLabelingModule } from './integrations/h-captcha-labeling/h-captcha-labeling.module';
import { HCaptchaController } from './modules/h-captcha/h-captcha.controller';
import { EscrowUtilsModule } from './integrations/escrow/escrow-utils.module';
import Joi from 'joi';
import { ChainId } from '@human-protocol/sdk';
import { RegisterAddressController } from './modules/register-address/register-address.controller';
import { RegisterAddressModule } from './modules/register-address/register-address.module';
import { InterceptorModule } from './common/interceptors/interceptor.module';
import { TokenRefreshModule } from './modules/token-refresh/token-refresh.module';
import { StatisticsController } from './modules/statistics/statistics.controller';
import { StatisticsModule } from './modules/statistics/statistics.module';
import { TokenRefreshController } from './modules/token-refresh/token-refresh.controller';
import { CronJobModule } from './modules/cron-job/cron-job.module';
import { EnvironmentConfigService } from './common/config/environment-config.service';
import { ForbidUnauthorizedHostMiddleware } from './common/middleware/host-check.middleware';
import { HealthModule } from './modules/health/health.module';
import { TokenRefreshModule } from './modules/token-refresh/token-refresh.module';
import { UiConfigurationModule } from './modules/ui-configuration/ui-configuration.module';
import { NDAModule } from './modules/nda/nda.module';
import { NDAController } from './modules/nda/nda.controller';
import { AbuseController } from './modules/abuse/abuse.controller';
import { AbuseModule } from './modules/abuse/abuse.module';
import { OperatorController } from './modules/user-operator/operator.controller';
import { OperatorModule } from './modules/user-operator/operator.module';
import { WorkerController } from './modules/user-worker/worker.controller';
import { WorkerModule } from './modules/user-worker/worker.module';

const JOI_BOOLEAN_STRING_SCHEMA = Joi.string().valid('true', 'false');

Expand Down Expand Up @@ -146,7 +149,14 @@ const JOI_BOOLEAN_STRING_SCHEMA = Joi.string().valid('true', 'false');
AbuseController,
],
exports: [HttpModule],
providers: [EnvironmentConfigService],
providers: [
EnvironmentConfigService,
JwtHttpStrategy,
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ export const ORACLE_URL_CACHE_KEY = 'oracle:url';
export const DAILY_HMT_SPENT_CACHE_KEY = 'daily:hmt-spent';
export const ORACLE_STATISTICS_CACHE_KEY = 'statistics:oracle';
export const WORKER_STATISTICS_CACHE_KEY = 'statistics:worker';
export const REPUTATION_ORACLE_PUBLIC_KEY = 'reputation:pubkey';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const JWT_KVSTORE_KEY = 'jwt_public_key';
11 changes: 11 additions & 0 deletions packages/apps/human-app/server/src/common/decorators/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,12 @@
import { Reflector } from '@nestjs/core';

export * from './enums';

/**
* Decorator for HTTP endpoints to bypass JWT auth guard
* where JWT auth not needed
*/
export const Public = Reflector.createDecorator<boolean>({
key: 'isPublic',
transform: () => true,
});
40 changes: 40 additions & 0 deletions packages/apps/human-app/server/src/common/guards/jwt.auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import {
CanActivate,
ExecutionContext,
Injectable,
UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { AuthGuard } from '@nestjs/passport';
import { JwtUserData } from '../utils/jwt-token.model';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt-http') implements CanActivate {
constructor(private readonly reflector: Reflector) {
super();
}

public async canActivate(context: ExecutionContext): Promise<boolean> {
// Check for public routes first
const isPublic = this.reflector.getAllAndOverride<boolean>('isPublic', [
Comment thread
dnechay marked this conversation as resolved.
context.getHandler(),
context.getClass(),
]);

if (isPublic) {
return true;
}

// Try to authenticate with JWT
await super.canActivate(context);

const request = context.switchToHttp().getRequest();
const user = request.user as JwtUserData;
if (!user) {
throw new UnauthorizedException('User not found in request');
}
request.token = request.headers['authorization'];

return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './jwt.http';
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { Injectable, Req, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import * as jwt from 'jsonwebtoken';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { EnvironmentConfigService } from '../../../common/config/environment-config.service';
import { JwtUserData } from '../../../common/utils/jwt-token.model';
import { KvStoreGateway } from '../../../integrations/kv-store/kv-store.gateway';

@Injectable()
export class JwtHttpStrategy extends PassportStrategy(Strategy, 'jwt-http') {
constructor(
private readonly configService: EnvironmentConfigService,
private readonly kvStoreGateway: KvStoreGateway,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKeyProvider: async (
_request: any,
rawJwtToken: any,
done: any,
) => {
try {
const payload = jwt.decode(rawJwtToken);
const chainId = this.configService.chainIdsEnabled[0];
const address = (payload as any).reputation_network;
const pubKey = await this.kvStoreGateway.getReputationOraclePublicKey(
chainId,
address,
);
done(null, pubKey);
} catch (error) {
console.error(error);
done(error);
}
},
passReqToCallback: true,
});
}

public async validate(
@Req() _request: any,
payload: {
user_id: string;
status: string;
wallet_address: string;
reputation_network: string;
qualifications?: string[];
site_key?: string;
email?: string;
},
): Promise<JwtUserData> {
if (!payload.user_id) {
throw new UnauthorizedException('Invalid token: missing user id');
}

return {
Comment thread
dnechay marked this conversation as resolved.
user_id: payload.user_id,
wallet_address: payload.wallet_address,
status: payload.status,
reputation_network: payload.reputation_network,
qualifications: payload.qualifications,
site_key: payload.site_key,
email: payload.email,
};
}
}
6 changes: 6 additions & 0 deletions packages/apps/human-app/server/src/common/interfaces/jwt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { JwtUserData } from '../utils/jwt-token.model';

export interface RequestWithUser extends Request {
user: JwtUserData;
token: string;
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,13 @@ export class JwtUserData {
@AutoMap()
wallet_address: string;
@AutoMap()
email: string;
@AutoMap()
kyc_status: 'approved' | 'none';
status: string;
@AutoMap()
reputation_network: string;
@AutoMap()
qualifications: string[];
@AutoMap()
site_key: string;
email?: string;
@AutoMap()
iat: number;
qualifications?: string[];
@AutoMap()
exp: number;
site_key?: string;
}
Loading