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
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{
"wake.compiler.solc.remappings": []
"wake.compiler.solc.remappings": [],
"git.ignoreLimitWarning": true
}
122 changes: 44 additions & 78 deletions CREATE_PR_LINK.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,87 +4,74 @@

**Click here to create the Pull Request:**

https://github.com/Whiznificent/Harvest-Finance/compare/master...feature/stellar-authentication
https://github.com/mrmoney10010-design/Harvest-Finance/compare/main...feature/platform-circuit-breaker

## 📋 PR Details

**Title:** `feat: Implement Stellar authentication (SEP-10)`
**Title:** `feat: implement platform-wide circuit breaker for deposits and withdrawals`

**Base Branch:** `master`
**Base Branch:** `main`

**Compare Branch:** `feature/stellar-authentication`
**Compare Branch:** `feature/platform-circuit-breaker`

## 🔗 Alternative PR Creation Methods

### Method 1: GitHub Web Interface
1. Visit: https://github.com/Whiznificent/Harvest-Finance
2. Click "Pull requests" tab
1. Visit: https://github.com/mrmoney10010-design/Harvest-Finance
2. Click the "Pull requests" tab
3. Click "New pull request"
4. Select base: `master`
5. Select compare: `feature/stellar-authentication`
4. Select base: `main`
5. Select compare: `feature/platform-circuit-breaker`
6. Click "Create pull request"

### Method 2: GitHub CLI
```bash
gh pr create --base master --head feature/stellar-authentication --title "feat: Implement Stellar authentication (SEP-10)" --body "Implements Stellar authentication with SEP-10 compliance"
### Method 2: Direct URL Parameters
```

### Method 3: Direct URL Parameters
```
https://github.com/Whiznificent/Harvest-Finance/compare/master...feature/stellar-authentication?expand=1
https://github.com/mrmoney10010-design/Harvest-Finance/compare/main...feature/platform-circuit-breaker?expand=1
```

## 📝 PR Description Template

```markdown
## Summary
This PR implements "Sign-in with Stellar" authentication using SEP-10 standard for the Harvest Finance platform, addressing issues #162 and #97.
Adds a platform-wide circuit breaker that allows administrators to instantly halt and resume all deposit and withdrawal operations across all service instances.

## Features Implemented
- ✅ SEP-10 compliant challenge-response authentication
- ✅ Freighter wallet integration
- ✅ Secure signature verification
- ✅ JWT token integration
- ✅ Comprehensive test suite (42 tests, 85%+ coverage)
- ✅ Complete documentation and setup guides
## Purpose / Motivation
To protect user funds and limit platform liability during critical events (e.g. smart contract failures, third-party oracle/RPC failures, or malicious exploits), administrators need a quick, highly reliable way to pause all transactional actions (deposits and withdrawals) across all vault types (Stellar, farm-vaults, and insurance-funds).

## Changes Made
- **Backend**: Stellar strategy, auth endpoints, DTOs, guards
- **Frontend**: StellarAuth component, login page updates, auth store integration
- **Tests**: Unit tests, integration tests, component tests
- **Documentation**: Setup guides, API docs, test reports

## Environment Variables Required
```env
# Backend
STELLAR_SERVER_SECRET=your_server_secret
STELLAR_NETWORK_PASSPHRASE=Test SDF Network ; September 2015

# Frontend
NEXT_PUBLIC_API_URL=http://localhost:5000/api/v1
```
- **PlatformCircuitBreakerService**: Implements breaker state validation, activation (`open`), and deactivation (`close`) with state persistence in Redis cache.
- **PlatformCircuitBreakerGuard**: Throws a `503 Service Unavailable` with a clear message `Maintenance Mode` when the circuit breaker is active.
- **Admin Endpoints**: Adds `POST /api/v1/admin/platform/circuit-breaker/open` and `/api/v1/admin/platform/circuit-breaker/close` with proper admin role checking and audit trail logging.
- **Controller Protections**: Applied `@UseGuards(PlatformCircuitBreakerGuard)` to deposit and withdrawal endpoints in:
- `VaultsController`
- `FarmVaultsController`
- `InsuranceFundController`
- **Unit and Integration Tests**:
- `platform-circuit-breaker.service.spec.ts`
- `platform-circuit-breaker.guard.spec.ts`
- `circuit-breaker.controller.spec.ts`
- `circuit-breaker.e2e-spec.ts` (End-to-end verification of endpoint blocking, propagation via Redis, and rapid toggles)

## How to Test
1. Install Freighter wallet extension
2. Set up environment variables
3. Run backend and frontend servers
4. Navigate to login page and select "Stellar" auth method
5. Connect wallet and authenticate

## Security Features
- SEP-10 compliance
- Challenge expiration (5 minutes)
- Server and client signature verification
- Replay attack prevention
- Network validation

## Test Coverage
- 42 total tests
- 85%+ code coverage
- All security scenarios covered
- Performance benchmarks met

Fixes #162 #97
1. Set up env variables and ensure Redis is running.
2. Run backend E2E tests:
```bash
npm run test:e2e test/circuit-breaker.e2e-spec.ts
```
3. Test manually by authenticating as admin:
- Open circuit breaker: `POST /api/v1/admin/platform/circuit-breaker/open`
- Attempt deposit or withdraw; confirm it fails with `503 Service Unavailable (Maintenance Mode)`.
- Close circuit breaker: `POST /api/v1/admin/platform/circuit-breaker/close`
- Attempt deposit or withdraw; confirm it succeeds.

## Related Issues
Implements the platform-wide circuit breaker specification.

## Checklist
- [x] Code builds successfully
- [x] Tests added/updated
- [x] No console errors
- [x] Documentation updated
```

## 🎯 Quick Actions
Expand All @@ -94,27 +81,6 @@ Fixes #162 #97
3. **Fill in the PR description** using the template above
4. **Create the pull request** for review

## 📊 Implementation Status

- ✅ All code implemented and tested
- ✅ Documentation complete
- ✅ Ready for review and merge
- ✅ Addresses all requirements from issues #162 and #97

---

**Ready for Review!** 🚀
```

## 🚀 Direct PR Creation Link

**Click here to create your Pull Request:**

### https://github.com/Whiznificent/Harvest-Finance/compare/master...feature/stellar-authentication

This link will take you directly to GitHub where you can:
1. Review all the changes between branches
2. See the file comparisons
3. Create the pull request with a single click

The PR will include all the Stellar authentication implementation with 42 tests, 85%+ coverage, and complete documentation addressing issues #162 and #97.
40 changes: 40 additions & 0 deletions PR_DESCRIPTION_CIRCUIT_BREAKER.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
## Summary
Adds a platform-wide circuit breaker that allows administrators to instantly halt and resume all deposit and withdrawal operations across all service instances.

## Purpose / Motivation
To protect user funds and limit platform liability during critical events (e.g. smart contract failures, third-party oracle/RPC failures, or malicious exploits), administrators need a quick, highly reliable way to pause all transactional actions (deposits and withdrawals) across all vault types (Stellar, farm-vaults, and insurance-funds).

## Changes Made
- **PlatformCircuitBreakerService**: Implements breaker state validation, activation (`open`), and deactivation (`close`) with state persistence in Redis cache.
- **PlatformCircuitBreakerGuard**: Throws a `503 Service Unavailable` with a clear message `Maintenance Mode` when the circuit breaker is active.
- **Admin Endpoints**: Adds `POST /api/v1/admin/platform/circuit-breaker/open` and `/api/v1/admin/platform/circuit-breaker/close` with proper admin role checking and audit trail logging.
- **Controller Protections**: Applied `@UseGuards(PlatformCircuitBreakerGuard)` to deposit and withdrawal endpoints in:
- `VaultsController`
- `FarmVaultsController`
- `InsuranceFundController`
- **Unit and Integration Tests**:
- `platform-circuit-breaker.service.spec.ts`
- `platform-circuit-breaker.guard.spec.ts`
- `circuit-breaker.controller.spec.ts`
- `circuit-breaker.e2e-spec.ts` (End-to-end verification of endpoint blocking, propagation via Redis, and rapid toggles)

## How to Test
1. Set up env variables and ensure Redis is running.
2. Run backend E2E tests:
```bash
npm run test:e2e test/circuit-breaker.e2e-spec.ts
```
3. Test manually by authenticating as admin:
- Open circuit breaker: `POST /api/v1/admin/platform/circuit-breaker/open`
- Attempt deposit or withdraw; confirm it fails with `503 Service Unavailable (Maintenance Mode)`.
- Close circuit breaker: `POST /api/v1/admin/platform/circuit-breaker/close`
- Attempt deposit or withdraw; confirm it succeeds.

## Related Issues
Implements the platform-wide circuit breaker specification.

## Checklist
- [x] Code builds successfully
- [x] Tests added/updated
- [x] No console errors
- [x] Documentation updated
Binary file added harvest-finance/backend/dump.rdb
Binary file not shown.
14 changes: 14 additions & 0 deletions harvest-finance/backend/package-lock.json

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

1 change: 1 addition & 0 deletions harvest-finance/backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
},
"dependencies": {
"@apollo/server": "^5.5.1",
"@as-integrations/express5": "^1.1.2",
"@aws-sdk/client-secrets-manager": "^3.1037.0",
"@hookform/resolvers": "^5.2.2",
"@nestjs/apollo": "^13.4.2",
Expand Down
31 changes: 30 additions & 1 deletion harvest-finance/backend/src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { DashboardStatsDto } from './dto/dashboard-stats.dto';
import { PlatformAnalyticsDto } from './dto/analytics.dto';
import { CreateVaultDto, UpdateVaultDto } from './dto/vault-crud.dto';
import { UpdateUserStatusDto } from './dto/user-status.dto';
import { CircuitBreakerActionDto } from './dto/circuit-breaker.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator';
Expand Down Expand Up @@ -136,6 +137,34 @@ export class AdminController {
return this.adminService.getUserActivity();
}

@Post('platform/circuit-breaker/open')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary:
'Activate platform circuit breaker to halt all deposits and withdrawals',
})
@ApiResponse({ status: 200, description: 'Circuit breaker activated' })
async openCircuitBreaker(
@Request() req: any,
@Body() body?: CircuitBreakerActionDto,
): Promise<{ active: boolean }> {
return this.adminService.openCircuitBreaker(req.user.id, body?.reason);
}

@Post('platform/circuit-breaker/close')
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary:
'Deactivate platform circuit breaker to resume all deposits and withdrawals',
})
@ApiResponse({ status: 200, description: 'Circuit breaker deactivated' })
async closeCircuitBreaker(
@Request() req: any,
@Body() body?: CircuitBreakerActionDto,
): Promise<{ active: boolean }> {
return this.adminService.closeCircuitBreaker(req.user.id, body?.reason);
}

@Get('email-preview/:templateName')
@ApiOperation({ summary: 'Preview email template in browser' })
@ApiParam({
Expand All @@ -152,4 +181,4 @@ export class AdminController {
templateName as any,
);
}
}
}
2 changes: 2 additions & 0 deletions harvest-finance/backend/src/admin/admin.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,11 @@ import { Deposit } from '../database/entities/deposit.entity';
import { User } from '../database/entities/user.entity';
import { Reward } from '../database/entities/reward.entity';
import { Withdrawal } from '../database/entities/withdrawal.entity';
import { CommonModule } from '../common/common.module';

@Module({
imports: [
CommonModule,
TypeOrmModule.forFeature([Vault, Deposit, User, Reward, Withdrawal]),
],
controllers: [AdminController],
Expand Down
17 changes: 17 additions & 0 deletions harvest-finance/backend/src/admin/admin.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
Injectable,
NotFoundException,
ForbiddenException,
InternalServerErrorException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource } from 'typeorm';
Expand All @@ -16,6 +17,7 @@ import {
import { DashboardStatsDto } from './dto/dashboard-stats.dto';
import { CreateVaultDto, UpdateVaultDto } from './dto/vault-crud.dto';
import { PlatformAnalyticsDto } from './dto/analytics.dto';
import { PlatformCircuitBreakerService } from '../common/circuit-breaker/platform-circuit-breaker.service';

@Injectable()
export class AdminService {
Expand All @@ -31,6 +33,7 @@ export class AdminService {
@InjectRepository(Withdrawal)
private withdrawalRepository: Repository<Withdrawal>,
private dataSource: DataSource,
private circuitBreakerService: PlatformCircuitBreakerService,
) {}

/**
Expand Down Expand Up @@ -283,4 +286,18 @@ export class AdminService {
totalWithdrawals: parseFloat(totalWithdrawalsResult?.total || '0'),
};
}

async openCircuitBreaker(
adminId: string,
reason?: string,
): Promise<{ active: boolean }> {
return this.circuitBreakerService.activate(adminId, reason);
}

async closeCircuitBreaker(
adminId: string,
reason?: string,
): Promise<{ active: boolean }> {
return this.circuitBreakerService.deactivate(adminId, reason);
}
}
Loading