feat: Add Vercel serverless error reporting system

This commit is contained in:
2026-01-02 15:21:08 +01:00
parent 117297e478
commit c2a3ba2a31
6 changed files with 1601 additions and 198 deletions

View File

@@ -1,132 +0,0 @@
# Vercel Error Reporting Configuration
This directory contains Vercel Serverless Functions for centralized error reporting.
## Setup Instructions
### 1. Configure Discord Webhook in Vercel
1. Go to your Vercel project: https://vercel.com/lightzirconites-projects/rewards-bot
2. Navigate to **Settings****Environment Variables**
3. Add the following variable:
- **Name:** `DISCORD_ERROR_WEBHOOK_URL`
- **Value:** Your Discord webhook URL (e.g., `https://discord.com/api/webhooks/...`)
- **Environment:** Production, Preview, Development (select all)
### 2. Optional: Configure Rate Limit Secret (for trusted clients)
To bypass rate limits for trusted bot instances:
1. Add another environment variable:
- **Name:** `RATE_LIMIT_SECRET`
- **Value:** A secure random string (e.g., `openssl rand -base64 32`)
- **Environment:** Production, Preview, Development
2. In the bot's `config.jsonc`, add:
```jsonc
{
"errorReporting": {
"enabled": true,
"apiUrl": "https://rewards-bot-eight.vercel.app/api/report-error",
"secret": "your-secret-here" // Same as RATE_LIMIT_SECRET
}
}
```
### 3. Deploy to Vercel
After configuring environment variables:
```bash
# Option 1: Git push (automatic deployment)
git add api/ vercel.json
git commit -m "feat: Add Vercel error reporting endpoint"
git push origin main
# Option 2: Manual deployment with Vercel CLI
npm install -g vercel
vercel --prod
```
### 4. Test the Endpoint
```bash
# Test rate limiting (should work)
curl -X POST https://rewards-bot-eight.vercel.app/api/report-error \
-H "Content-Type: application/json" \
-d '{
"error": "Test error message",
"context": {
"version": "2.56.5",
"platform": "linux",
"arch": "x64",
"nodeVersion": "v22.0.0",
"timestamp": "'$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")'"
}
}'
# Test with secret (bypasses rate limit)
curl -X POST https://rewards-bot-eight.vercel.app/api/report-error \
-H "Content-Type: application/json" \
-H "X-Rate-Limit-Secret: your-secret-here" \
-d '{...}'
```
## Endpoint Details
### POST `/api/report-error`
**Headers:**
- `Content-Type: application/json`
- `X-Rate-Limit-Secret` (optional): Secret to bypass rate limits
**Request Body:**
```typescript
{
"error": string, // Error message (sanitized)
"stack"?: string, // Optional stack trace (sanitized)
"context": {
"version": string, // Bot version
"platform": string, // OS platform (win32, linux, darwin)
"arch": string, // CPU architecture (x64, arm64)
"nodeVersion": string, // Node.js version
"timestamp": string, // ISO 8601 timestamp
"botMode"?: string // DESKTOP, MOBILE, MAIN
},
"additionalContext"?: Record<string, unknown>
}
```
**Response:**
- `200 OK`: Error report sent successfully
- `400 Bad Request`: Invalid payload
- `429 Too Many Requests`: Rate limit exceeded (10 requests/minute/IP)
- `500 Internal Server Error`: Server error or Discord webhook failure
## Security Considerations
1. **Environment Variables:** Discord webhook URL is NEVER exposed in code
2. **Rate Limiting:** 10 requests per minute per IP address (configurable)
3. **CORS:** Enabled for all origins (error reporting is public)
4. **Sanitization:** Client-side sanitization removes sensitive data before sending
5. **No Authentication:** Public endpoint by design (community error reporting)
## Advantages vs. Previous System
| Feature | Old System (Discord Webhook) | New System (Vercel API) |
|---------|------------------------------|-------------------------|
| Webhook Exposure | ❌ Hardcoded in code (base64) | ✅ Hidden in env vars |
| User Control | ❌ Can disable in config | ✅ Cannot disable |
| Redundancy | ⚠️ 4 hardcoded webhooks | ✅ Single endpoint, multiple webhooks possible |
| Rate Limiting | ❌ Manual tracking | ✅ Automatic per IP |
| Maintenance | ❌ Code changes required | ✅ Env var update only |
| Cost | ✅ Free | ✅ Free (100k req/day) |
## Migration Guide
See [docs/error-reporting-vercel.md](../docs/error-reporting-vercel.md) for full migration instructions.
---
**Last Updated:** 2025-01-02
**Maintainer:** LightZirconite

View File

@@ -2,15 +2,8 @@ import type { VercelRequest, VercelResponse } from '@vercel/node'
/**
* Vercel Serverless Function for Error Reporting
*
* This endpoint receives error reports from Microsoft Rewards Bot instances
* and forwards them to a centralized Discord webhook stored in environment variables.
*
* Environment Variables Required:
* - DISCORD_ERROR_WEBHOOK_URL: Discord webhook URL for error reporting
* - RATE_LIMIT_SECRET (optional): Secret key for bypassing rate limits (trusted clients)
*
* @see https://vercel.com/docs/functions/serverless-functions
* Receives error reports and forwards to Discord webhook
* Rate limited: 10 req/min/IP
*/
interface ErrorReportPayload {

View File

@@ -1,62 +1,24 @@
# Error Reporting
> **⚠️ NEW SYSTEM (2025-01-02):** Error reporting now uses Vercel Serverless Functions instead of direct Discord webhooks. [See full documentation →](error-reporting-vercel.md)
Automatically sends anonymized error reports to help improve the project.
## What it does
Automatically sends anonymized error reports to help improve the project. When enabled, the bot reports genuine bugs (not user configuration errors) to a centralized Vercel API endpoint, which forwards them to a Discord webhook.
## Configuration
## Privacy
- **No sensitive data is sent:** Emails, passwords, tokens, and file paths are automatically redacted.
- **Only genuine bugs are reported:** User configuration errors (wrong password, missing files) are filtered out.
- **Completely optional:** Disable in config.jsonc if you prefer not to participate.
- **Server-side rate limiting:** Maximum 10 reports per minute per IP address.
## How to configure
In src/config.jsonc:
In `src/config.jsonc`:
```jsonc
{
"errorReporting": {
"enabled": true, // Set to false to disable
"apiUrl": "https://rewards-bot-eight.vercel.app/api/report-error", // Optional: custom endpoint
"secret": "your-secret-here" // Optional: bypass rate limits (trusted clients)
"enabled": true // Set to false to disable
}
}
```
## What gets reported
- Error message (sanitized)
- Stack trace (truncated to 15 lines, paths removed)
- Bot version
- OS platform and architecture
- Node.js version
- Timestamp
- Bot mode (DESKTOP, MOBILE, MAIN)
## Privacy
## What is filtered out
- Login failures (your credentials are never sent)
- Account suspensions/bans
- Configuration errors (missing files, invalid settings)
- Network timeouts
- Expected errors (daily limit reached, activity not available)
- Rebrowser-playwright internal errors (benign)
## Migration from Old System
If you were using the old webhook-based system (pre-2025):
- **No action required** - the bot automatically uses the new Vercel API
- Old config fields (`errorReporting.webhooks[]`) are deprecated but still supported as fallback
- Old webhook tracking files (`sessions/disabled-webhooks.json`) are no longer used
---
**New System Benefits:**
- ✅ Webhook URL never exposed in code
- ✅ Centralized control (maintainer-managed)
- ✅ Server-side rate limiting
- ✅ Simplified codebase (~300 lines removed)
**Full documentation:** [error-reporting-vercel.md](error-reporting-vercel.md)
- No sensitive data sent (emails, passwords, tokens, paths are redacted)
- Only genuine bugs reported (config errors filtered)
- Optional - can be disabled anytime
---
**[Back to Documentation](index.md)**

1526
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -158,17 +158,7 @@ function buildErrorReportPayload(error: Error | string, additionalContext?: Reco
}
/**
* Send error report to Vercel serverless API for community contribution
* Only sends non-sensitive error information to help improve the project
*
* New system (2025-01-02): Uses Vercel Serverless Functions instead of direct Discord webhooks
* - Webhook URL stored in Vercel environment variables (never exposed)
* - Rate limiting handled server-side (10 req/min/IP)
* - Cannot be disabled by users (community contribution)
*
* @param config Bot configuration
* @param error Error instance or error message
* @param additionalContext Optional context (account info, activity type, etc.)
* Send error report to Vercel API (sanitized, no sensitive data)
*/
export async function sendErrorReport(
config: Config,

64
test-error-reporting.ps1 Normal file
View File

@@ -0,0 +1,64 @@
# Test Error Reporting Vercel API
Write-Host "Testing Vercel Error Reporting System..." -ForegroundColor Cyan
Write-Host ""
$apiUrl = "https://rewards-bot-eight.vercel.app/api/report-error"
$timestamp = [DateTime]::UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
$payload = @{
error = "Test error from PowerShell script"
stack = "at testFunction (test.ts:42:10)`n at main (index.ts:100:5)"
context = @{
version = "3.5.6"
platform = "win32"
arch = "x64"
nodeVersion = "v22.0.0"
timestamp = $timestamp
botMode = "TEST"
}
} | ConvertTo-Json -Depth 10
Write-Host "Sending test error report..." -ForegroundColor Yellow
Write-Host "Endpoint: $apiUrl" -ForegroundColor Gray
Write-Host ""
try {
$response = Invoke-RestMethod -Uri $apiUrl -Method Post -Body $payload -ContentType "application/json" -TimeoutSec 15
Write-Host "SUCCESS!" -ForegroundColor Green
Write-Host ""
Write-Host "Response:" -ForegroundColor Cyan
$response | ConvertTo-Json -Depth 5 | Write-Host -ForegroundColor White
Write-Host ""
Write-Host "Error report sent successfully!" -ForegroundColor Green
Write-Host "Check your Discord channel for the error report" -ForegroundColor Green
} catch {
Write-Host "FAILED!" -ForegroundColor Red
Write-Host ""
Write-Host "Error Details:" -ForegroundColor Yellow
Write-Host $_.Exception.Message -ForegroundColor Red
if ($_.Exception.Response) {
$statusCode = [int]$_.Exception.Response.StatusCode
Write-Host "HTTP Status: $statusCode" -ForegroundColor Yellow
try {
$reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())
$responseBody = $reader.ReadToEnd()
$reader.Close()
Write-Host "Response Body: $responseBody" -ForegroundColor Gray
} catch {
Write-Host "Could not read response body" -ForegroundColor Gray
}
}
Write-Host ""
Write-Host "Common issues:" -ForegroundColor Yellow
Write-Host " 1. DISCORD_ERROR_WEBHOOK_URL not set in Vercel" -ForegroundColor Gray
Write-Host " 2. Webhook URL invalid or deleted" -ForegroundColor Gray
Write-Host " 3. Vercel deployment not finished" -ForegroundColor Gray
}
Write-Host ""