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
9,219 changes: 9,219 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

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 = await this.server.getAccount(address) as any;
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, HttpCode, HttpStatus } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiQuery, ApiBody } from "@nestjs/swagger";
import { AuthService } from "./auth.service";

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

@Get("nonce")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Get a nonce for Stellar signature" })
@ApiQuery({ name: "address", type: String, required: true })
async getNonce(@Query("address") address: string) {
return this.authService.generateNonce(address);
}

@Post("verify")
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: "Verify Stellar signature and receive JWT" })
@ApiBody({
schema: {
type: "object",
properties: {
address: { type: "string" },
signedNonce: { type: "string" },
},
},
})
async verify(@Body() body: { address: string; signedNonce: string }) {
return this.authService.verifySignature(body.address, body.signedNonce);
}
}
20 changes: 20 additions & 0 deletions src/modules/auth/auth.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Module } from "@nestjs/common";
import { JwtModule } from "@nestjs/jwt";
import { PassportModule } from "@nestjs/passport";
import { AuthController } from "./auth.controller";
import { AuthService } from "./auth.service";
import { JwtStrategy } from "./jwt.strategy";

@Module({
imports: [
PassportModule,
JwtModule.register({
secret: process.env.JWT_SECRET || "change-me",
signOptions: { expiresIn: "7d" },
}),
],
controllers: [AuthController],
providers: [AuthService, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
45 changes: 45 additions & 0 deletions src/modules/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { Injectable, Logger } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Keypair } from "@stellar/stellar-sdk";

const NONCE_STORE = new Map<string, { nonce: string; expiresAt: number }>();

@Injectable()
export class AuthService {
private readonly logger = new Logger(AuthService.name);

constructor(private jwtService: JwtService) {}

async generateNonce(address: string) {
const nonce = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
const expiresAt = Date.now() + 5 * 60 * 1000;
NONCE_STORE.set(address.toLowerCase(), { nonce, expiresAt });
return { nonce };
}

async verifySignature(address: string, signedNonce: string) {
const stored = NONCE_STORE.get(address.toLowerCase());
if (!stored) throw new Error("Nonce not found or expired");

if (Date.now() > stored.expiresAt) {
NONCE_STORE.delete(address.toLowerCase());
throw new Error("Nonce expired");
}

let signatureBuffer: Buffer;
try {
signatureBuffer = Buffer.from(signedNonce, "base64");
} catch {
signatureBuffer = Buffer.from(signedNonce, "hex");
}

const keypair = Keypair.fromPublicKey(address);
const valid = keypair.verify(Buffer.from(stored.nonce), signatureBuffer);
if (!valid) throw new Error("Invalid signature");

NONCE_STORE.delete(address.toLowerCase());

const token = this.jwtService.sign({ address: address.toLowerCase() });
return { access_token: token };
}
}
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 { Injectable } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";

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

validate(payload: { address: string }) {
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,5 +1,6 @@
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 { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { GroupsService, CreateGroupDto } from "./groups.service";

@ApiTags("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,5 +1,6 @@
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 { JwtAuthGuard } from "../auth/jwt-auth.guard";
import { LoansService, CreateLoanDto } from "./loans.service";

@ApiTags("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