Skip to content
Open
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
4 changes: 0 additions & 4 deletions fix.py

This file was deleted.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@
"@types/node": "^20.14.0",
"@types/nodemailer": "^6.4.15",
"@types/passport-jwt":"^4.0.1",
"@types/supertest": "^7.2.0",
"jest": "^29.7.0",
"prisma": "^5.15.0",
"supertest": "^7.2.2",
"ts-jest": "^29.1.5",
"ts-node": "^10.9.2",
"typescript": "^5.4.5"
Expand Down
2 changes: 2 additions & 0 deletions src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { MembersModule } from "./modules/members/members.module";
import { LoansModule } from "./modules/loans/loans.module";
import { GovernanceModule } from "./modules/governance/governance.module";
import { NotificationsModule } from "./modules/notifications/notifications.module";
import { AuthModule } from "./modules/auth/auth.module";
import { PrismaService } from "./common/prisma.service";
import { StellarService } from "./common/stellar.service";
import { StellarIndexerService } from "./common/stellar-indexer.service";
Expand All @@ -19,6 +20,7 @@ import { StellarIndexerService } from "./common/stellar-indexer.service";
LoansModule,
GovernanceModule,
NotificationsModule,
AuthModule,
],
providers: [PrismaService, StellarService, StellarIndexerService],
})
Expand Down
4 changes: 2 additions & 2 deletions src/common/stellar.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,9 @@ export class StellarService {
async getBalance(address: string, assetContractId?: string): Promise<string> {
try {
if (!assetContractId) {
const account = await this.server.getAccount(address);
const account: any = await this.server.getAccount(address);
return account.balances
.find((b) => b.asset_type === "native")
?.find((b: any) => b.asset_type === "native")
?.balance ?? "0";
}
// USDC or other token contract balance
Expand Down
33 changes: 33 additions & 0 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Controller, Get, Post, Body, Query, UnauthorizedException, BadRequestException } from '@nestjs/common';
import { ApiTags, ApiOperation } from '@nestjs/swagger';
import { AuthService } from './auth.service';

class VerifyDto {
address: string;
signedNonce: string;
}

@ApiTags('auth')
@Controller('api/auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}

@Get('nonce')
@ApiOperation({ summary: 'Get a random nonce for signing' })
getNonce(@Query('address') address: string) {
if (!address) {
throw new BadRequestException('Address is required');
}
const nonce = this.authService.generateNonce(address);
return { nonce };
}

@Post('verify')
@ApiOperation({ summary: 'Verify signature and issue JWT' })
verify(@Body() body: VerifyDto) {
if (!body.address || !body.signedNonce) {
throw new BadRequestException('Address and signedNonce are required');
}
return this.authService.verifySignature(body.address, body.signedNonce);
}
}
25 changes: 25 additions & 0 deletions src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Module } from '@nestjs/common';
import { JwtModule } from '@nestjs/jwt';
import { PassportModule } from '@nestjs/passport';
import { AuthService } from './auth.service';
import { AuthController } from './auth.controller';
import { JwtStrategy } from './jwt.strategy';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
imports: [
PassportModule,
JwtModule.registerAsync({
imports: [ConfigModule],
useFactory: async (configService: ConfigService) => ({
secret: configService.get<string>('JWT_SECRET') || 'fallback_secret',
signOptions: { expiresIn: '60m' },
}),
inject: [ConfigService],
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
48 changes: 48 additions & 0 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Keypair } from '@stellar/stellar-sdk';
import * as crypto from 'crypto';

@Injectable()
export class AuthService {
private nonceMap = new Map<string, { nonce: string; expiresAt: number }>();

constructor(private jwtService: JwtService) {}

generateNonce(address: string): string {
const nonce = crypto.randomBytes(32).toString('hex');
// 5 minutes TTL
const expiresAt = Date.now() + 5 * 60 * 1000;
this.nonceMap.set(address, { nonce, expiresAt });
return nonce;
}

verifySignature(address: string, signedNonce: string): { accessToken: string } {
const stored = this.nonceMap.get(address);
if (!stored) {
throw new UnauthorizedException('Nonce not found or expired');
}

if (Date.now() > stored.expiresAt) {
this.nonceMap.delete(address);
throw new UnauthorizedException('Nonce expired');
}

try {
const keypair = Keypair.fromPublicKey(address);
const isValid = keypair.verify(Buffer.from(stored.nonce), Buffer.from(signedNonce, 'base64'));
if (!isValid) {
throw new UnauthorizedException('Invalid signature');
}
} catch (e) {
throw new UnauthorizedException('Invalid signature or address');
}

this.nonceMap.delete(address);

const payload = { sub: address, address };
return {
accessToken: this.jwtService.sign(payload),
};
}
}
5 changes: 5 additions & 0 deletions src/modules/auth/jwt-auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {}
18 changes: 18 additions & 0 deletions src/modules/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable } from '@nestjs/common';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET || 'fallback_secret',
});
}

async validate(payload: any) {
return { address: payload.address };
}
}
7 changes: 5 additions & 2 deletions src/modules/groups/groups.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Controller, Get, Post, Param, Body } from "@nestjs/common";
import { ApiTags, ApiOperation } from "@nestjs/swagger";
import { Controller, Get, Post, Param, Body, UseGuards } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiBearerAuth } from "@nestjs/swagger";
import { GroupsService, CreateGroupDto } from "./groups.service";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";

@ApiTags("groups")
@Controller("groups")
Expand All @@ -20,6 +21,8 @@ export class GroupsController {
}

@Post()
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: "Register a new group after contract deployment" })
create(@Body() dto: CreateGroupDto) {
return this.groupsService.create(dto);
Expand Down
9 changes: 7 additions & 2 deletions src/modules/loans/loans.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Controller, Get, Post, Patch, Param, Body, Query } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiQuery } from "@nestjs/swagger";
import { Controller, Get, Post, Patch, Param, Body, Query, UseGuards } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiQuery, ApiBearerAuth } from "@nestjs/swagger";
import { LoansService, CreateLoanDto } from "./loans.service";
import { JwtAuthGuard } from "../auth/jwt-auth.guard";

@ApiTags("loans")
@Controller("loans")
Expand All @@ -21,12 +22,16 @@ export class LoansController {
}

@Post()
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: "Register a loan request after on-chain submission" })
create(@Body() dto: CreateLoanDto) {
return this.loansService.create(dto);
}

@Patch(":id/status")
@UseGuards(JwtAuthGuard)
@ApiBearerAuth()
@ApiOperation({ summary: "Update loan status (after on-chain approval/repayment)" })
updateStatus(@Param("id") id: string, @Body("status") status: string) {
return this.loansService.updateStatus(id, status);
Expand Down
2 changes: 1 addition & 1 deletion src/modules/notifications/notifications.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class NotificationsService {
metadata?: Record<string, unknown>
) {
return this.prisma.notification.create({
data: { recipient, type, title, body, metadata },
data: { recipient, type, title, body, metadata: metadata as any },
});
}

Expand Down
72 changes: 72 additions & 0 deletions test/auth.e2e-spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { Test, TestingModule } from '@nestjs/testing';
import { INestApplication } from '@nestjs/common';
import * as request from 'supertest';
import { AppModule } from './../src/app.module';
import { PrismaService } from './../src/common/prisma.service';
import { Keypair } from '@stellar/stellar-sdk';

describe('AuthController (e2e)', () => {
let app: INestApplication;
const keypair = Keypair.random();

beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider(PrismaService)
.useValue({
$connect: jest.fn(),
$disconnect: jest.fn(),
})
.compile();

app = moduleFixture.createNestApplication();
await app.init();
});

afterAll(async () => {
await app.close();
});

it('/api/auth/nonce (GET)', async () => {
const address = keypair.publicKey();
const res = await request(app.getHttpServer())
.get(`/api/auth/nonce?address=${address}`)
.expect(200);

expect(res.body.nonce).toBeDefined();
});

it('/api/auth/verify (POST)', async () => {
const address = keypair.publicKey();

// Get nonce
const nonceRes = await request(app.getHttpServer())
.get(`/api/auth/nonce?address=${address}`)
.expect(200);

const nonce = nonceRes.body.nonce;

// Sign nonce
const signature = keypair.sign(Buffer.from(nonce)).toString('base64');

// Verify
const verifyRes = await request(app.getHttpServer())
.post('/api/auth/verify')
.send({ address, signedNonce: signature })
.expect(201);

expect(verifyRes.body.accessToken).toBeDefined();

// Verify token can be used on protected route
await request(app.getHttpServer())
.post('/groups')
.set('Authorization', `Bearer ${verifyRes.body.accessToken}`)
.send({})
.expect((res: any) => {
if (res.status === 401) {
throw new Error('Expected authenticated response, got 401');
}
});
});
});
9 changes: 9 additions & 0 deletions test/jest-e2e.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": ".",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
}
}