# SiliconPin API Documentation This document describes the comprehensive API endpoints available in the SiliconPin platform. ## Base URL - Development: `http://localhost:4024` - Production: `https://siliconpin.com` ## Authentication This API uses JWT (JSON Web Tokens) for authentication. Tokens are stored in HTTP-only cookies for security. ### Authentication Flow 1. Register or login to receive access and refresh tokens 2. Access token is valid for 15 minutes 3. Refresh token is valid for 7 days 4. When access token expires, use refresh endpoint to get new tokens 5. All protected routes require valid access token in cookies ## API Endpoints ### Authentication Endpoints #### POST /api/auth/register Register a new user account. **Request Body:** ```json { "name": "John Doe", "email": "john@example.com", "password": "securePassword123" } ``` **Validation:** - `name`: Required, minimum 2 characters - `email`: Required, valid email format - `password`: Required, minimum 6 characters **Response (201 Created):** ```json { "success": true, "data": { "user": { "id": "64f5a2b4c8d9e1f2a3b4c5d6", "name": "John Doe", "email": "john@example.com", "createdAt": "2024-01-15T10:30:00.000Z" } }, "message": "User registered successfully" } ``` **Error Responses:** ```json // 400 Bad Request - Validation Error { "success": false, "error": "Validation failed", "details": [ { "field": "email", "message": "Invalid email format" } ] } // 409 Conflict - User Already Exists { "success": false, "error": "User with this email already exists" } ``` #### POST /api/auth/login Sign in an existing user. **Request Body:** ```json { "email": "john@example.com", "password": "securePassword123" } ``` **Response (200 OK):** ```json { "success": true, "data": { "user": { "id": "64f5a2b4c8d9e1f2a3b4c5d6", "name": "John Doe", "email": "john@example.com" } }, "message": "Login successful" } ``` **Sets Cookies:** - `accessToken`: HTTP-only, expires in 15 minutes - `refreshToken`: HTTP-only, expires in 7 days **Error Responses:** ```json // 401 Unauthorized - Invalid Credentials { "success": false, "error": "Invalid email or password" } ``` #### POST /api/auth/logout Sign out the current user. **Authorization:** Required (access token in cookies) **Response (200 OK):** ```json { "success": true, "message": "Logout successful" } ``` **Effect:** Clears authentication cookies #### POST /api/auth/refresh Refresh the access token using refresh token. **Authorization:** Required (refresh token in cookies) **Response (200 OK):** ```json { "success": true, "message": "Token refreshed successfully" } ``` **Sets Cookies:** - New `accessToken`: HTTP-only, expires in 15 minutes - New `refreshToken`: HTTP-only, expires in 7 days **Error Responses:** ```json // 401 Unauthorized - Invalid Refresh Token { "success": false, "error": "Invalid or expired refresh token" } ``` #### GET /api/auth/me Get current user information. **Authorization:** Required (access token in cookies) **Response (200 OK):** ```json { "success": true, "data": { "user": { "id": "64f5a2b4c8d9e1f2a3b4c5d6", "name": "John Doe", "email": "john@example.com", "createdAt": "2024-01-15T10:30:00.000Z", "updatedAt": "2024-01-15T10:30:00.000Z" } } } ``` **Error Responses:** ```json // 401 Unauthorized - No Token or Invalid Token { "success": false, "error": "Authentication required" } ``` ## Error Handling All API endpoints follow a consistent error response format: ### Standard Error Response ```json { "success": false, "error": "Error message", "details": [] // Optional array of detailed errors } ``` ### HTTP Status Codes - `200` - Success - `201` - Created (successful registration) - `400` - Bad Request (validation errors) - `401` - Unauthorized (authentication required/failed) - `403` - Forbidden (access denied) - `404` - Not Found - `409` - Conflict (resource already exists) - `500` - Internal Server Error ### Validation Errors When validation fails, the API returns detailed error information: ```json { "success": false, "error": "Validation failed", "details": [ { "field": "email", "message": "Invalid email format" }, { "field": "password", "message": "Password must be at least 6 characters" } ] } ``` ## Rate Limiting Currently, no rate limiting is implemented. For production deployment, consider adding rate limiting to prevent abuse: - Login attempts: 5 per minute per IP - Registration: 3 per minute per IP - General API: 100 per minute per IP ## CORS Configuration CORS is configured to allow requests from your frontend domain. In development, all origins are allowed. ## Security Headers The API includes security headers: - `Content-Security-Policy` - `X-Content-Type-Options: nosniff` - `X-Frame-Options: DENY` - `X-XSS-Protection: 1; mode=block` ## Frontend Integration ### Using with fetch API ```javascript // Login example const login = async (email, password) => { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email, password }), credentials: 'include', // Important: include cookies }) const data = await response.json() if (!data.success) { throw new Error(data.error) } return data } // Protected API call example const getUserProfile = async () => { const response = await fetch('/api/auth/me', { method: 'GET', credentials: 'include', // Important: include cookies }) const data = await response.json() if (!data.success) { if (response.status === 401) { // Token expired, try to refresh await refreshToken() // Retry the original request return getUserProfile() } throw new Error(data.error) } return data } ``` ### Using with Axios ```javascript import axios from 'axios' // Configure axios to include cookies axios.defaults.withCredentials = true // Request interceptor for automatic token refresh axios.interceptors.response.use( (response) => response, async (error) => { if (error.response?.status === 401) { try { await axios.post('/api/auth/refresh') // Retry the original request return axios.request(error.config) } catch (refreshError) { // Refresh failed, redirect to login window.location.href = '/auth' } } return Promise.reject(error) } ) ``` ## Testing the API ### Using curl ```bash # Register a new user curl -X POST http://localhost:4024/api/auth/register \ -H "Content-Type: application/json" \ -d '{"name":"Test User","email":"test@example.com","password":"password123"}' \ -c cookies.txt # Login curl -X POST http://localhost:4024/api/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"test@example.com","password":"password123"}' \ -c cookies.txt # Get user profile (protected route) curl -X GET http://localhost:4024/api/auth/me \ -b cookies.txt # Logout curl -X POST http://localhost:4024/api/auth/logout \ -b cookies.txt ``` ### Using Postman 1. Set up environment variables for base URL 2. Use "Send and download cookies" option in requests 3. Test the authentication flow step by step 4. Save cookies between requests for protected routes ## Extending the API ### Adding New Protected Routes ```typescript // app/api/example/route.ts import { authMiddleware } from '@/lib/auth-middleware' export async function GET(request: Request) { // Authenticate the request const user = await authMiddleware(request) if (!user) { return Response.json({ success: false, error: 'Authentication required' }, { status: 401 }) } // Your protected logic here return Response.json({ success: true, data: { message: 'Protected data', user: user.id }, }) } ``` ### Adding Request Validation ```typescript import { z } from 'zod' const CreatePostSchema = z.object({ title: z.string().min(1, 'Title is required'), content: z.string().min(10, 'Content must be at least 10 characters'), }) export async function POST(request: Request) { try { const body = await request.json() const validatedData = CreatePostSchema.parse(body) // Process validated data } catch (error) { if (error instanceof z.ZodError) { return Response.json( { success: false, error: 'Validation failed', details: error.errors.map((err) => ({ field: err.path.join('.'), message: err.message, })), }, { status: 400 } ) } return Response.json({ success: false, error: 'Internal server error' }, { status: 500 }) } } ``` ## Additional API Endpoints SiliconPin includes extensive API coverage beyond authentication: ### Topics API - `GET /api/topics` - List all topics with search and filtering - `POST /api/topics` - Create new topic (protected) - `GET /api/topics/[slug]` - Get specific topic - `PUT /api/topic/[id]` - Update topic (protected, owner only) - `DELETE /api/topic/[id]` - Delete topic (protected, owner only) - `GET /api/topics/[slug]/related` - Get related topics - `POST /api/topics/[slug]/view` - Track topic views ### Admin API (Protected, Admin Only) - `GET /api/admin/dashboard` - Admin dashboard statistics - `GET /api/admin/users` - User management - `GET /api/admin/billing` - Billing management - `GET /api/admin/reports` - Generate reports - `GET /api/admin/services` - Service management - `GET /api/admin/settings` - System settings ### Services API - `POST /api/services/deploy-kubernetes` - Deploy K8s service - `POST /api/services/deploy-vpn` - Deploy VPN service - `POST /api/services/deploy-cloude` - Deploy cloud instance - `POST /api/services/hire-developer` - Developer hiring request - `GET /api/services/active` - Get active services ### Payment & Billing API - `POST /api/balance/add` - Add balance to account - `POST /api/balance/deduct` - Deduct balance - `GET /api/user/balance` - Get user balance - `POST /api/payments/initiate` - Initiate payment - `GET /api/billing` - Get billing history - `GET /api/billing/stats` - Billing statistics - `GET /api/transactions` - Transaction history ### Tools API - `POST /api/tools/openai-chat` - OpenAI chat integration ### Upload & File Management - `POST /api/upload` - Upload files to MinIO - `POST /api/upload/confirm` - Confirm file upload - `POST /api/topic-content-image` - Upload topic images ### Utility API - `GET /api/health` - Health check endpoint - `POST /api/contact` - Contact form submission - `POST /api/feedback` - Submit feedback - `GET /api/tags` - Get all available tags - `GET /api/startup-test` - System startup validation This comprehensive API documentation covers the complete SiliconPin platform, providing authentication, content management, admin capabilities, web services, payment processing, and utility endpoints.