Skip to content
Merged
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
136 changes: 106 additions & 30 deletions docs/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,19 @@
"application/json": {
"schema": {
"$ref": "#/components/schemas/BillingDeductRequest"
},
"examples": {
"deductRequest": {
"summary": "Deduct billing request",
"value": {
"requestId": "req-123e4567-e89b-12d3-a456-426614174000",
"apiId": "api-123",
"endpointId": "endpoint-456",
"apiKeyId": "key-789",
"amountUsdc": "0.01",
"idempotencyKey": "idem-abc123"
}
}
}
}
}
Expand All @@ -75,6 +88,26 @@
"application/json": {
"schema": {
"$ref": "#/components/schemas/BillingDeductResponse"
},
"examples": {
"success": {
"summary": "Successful deduction",
"value": {
"success": true,
"usageEventId": "evt-123e4567-e89b-12d3-a456-426614174000",
"stellarTxHash": "abc123def456...",
"alreadyProcessed": false
}
},
"alreadyProcessed": {
"summary": "Already processed (idempotent)",
"value": {
"success": true,
"usageEventId": "evt-123e4567-e89b-12d3-a456-426614174000",
"stellarTxHash": "abc123def456...",
"alreadyProcessed": true
}
}
}
}
}
Expand All @@ -85,6 +118,16 @@
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"invalidAmount": {
"summary": "Invalid amount format",
"value": {
"code": "BAD_REQUEST",
"message": "amountUsdc must be a positive number with at most 7 decimal places",
"requestId": "req-abc123"
}
}
}
}
}
Expand All @@ -95,6 +138,16 @@
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"unauthorized": {
"summary": "Missing or invalid authentication",
"value": {
"code": "UNAUTHORIZED",
"message": "Authentication required",
"requestId": "req-abc123"
}
}
}
}
}
Expand All @@ -105,54 +158,77 @@
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"insufficientBalance": {
"summary": "Insufficient balance",
"value": {
"code": "INSUFFICIENT_BALANCE",
"message": "Vault balance too low for deduction",
"requestId": "req-abc123"
}
}
}
}
}
},
"500": {
"description": "Internal server error",
"409": {
"description": "Idempotency conflict",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"idempotencyConflict": {
"summary": "Idempotency key already used with different parameters",
"value": {
"code": "IDEMPOTENCY_CONFLICT",
"message": "Idempotency key conflict: different request parameters",
"requestId": "req-abc123"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Success"
},
"400": {
"description": "Bad Request"
},
"401": {
"description": "Unauthorized"
},
"402": {
"description": "Payment Required"
},
"409": {
"description": "Idempotency conflict",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
"429": {
"description": "Rate limit exceeded",
"headers": {
"Retry-After": {
"schema": {
"type": "integer",
"description": "Seconds until the rate limit expires"
}
}
},
"429": {
"description": "Rate limit exceeded",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
},
"examples": {
"rateLimited": {
"summary": "Too many requests",
"value": {
"code": "TOO_MANY_REQUESTS",
"message": "Too Many Requests",
"requestId": "req-abc123"
}
}
}
}
},
"500": {}
}
},
"500": {
"description": "Internal server error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,15 @@ export const envSchema = z
WEBHOOK_RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive().optional(),
WEBHOOK_RATE_LIMIT_MAX_REQUESTS: z.coerce.number().int().positive().optional(),
WEBHOOK_SECRET_ROTATION_GRACE_MS: z.coerce.number().int().positive().default(24 * 60 * 60 * 1000),
// Generic rate limiter (optional legacy config)
RATE_LIMIT_MAX_REQUESTS: z.coerce.number().int().positive().optional(),
RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive().optional(),
RATE_LIMIT_STORE: z.string().optional(),
RATE_LIMIT_PG_TABLE: z.string().optional(),

// Login rate limiting (IP-based throttling for auth attempts)
LOGIN_RATE_LIMIT_MAX_REQUESTS: z.coerce.number().int().positive().default(5),
LOGIN_RATE_LIMIT_WINDOW_MS: z.coerce.number().int().positive().default(60_000), // 1 minute sliding window

// CORS
CORS_ALLOWED_ORIGINS: z.string().default("http://localhost:5173"),

Expand Down
5 changes: 5 additions & 0 deletions src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,11 @@ export const config = {
secretRotationGraceMs: env.WEBHOOK_SECRET_ROTATION_GRACE_MS,
},

loginRateLimit: {
windowMs: env.LOGIN_RATE_LIMIT_WINDOW_MS,
maxRequests: env.LOGIN_RATE_LIMIT_MAX_REQUESTS,
},

rateLimiter: {
maxRequests: env.RATE_LIMIT_MAX_REQUESTS,
windowMs: env.RATE_LIMIT_WINDOW_MS,
Expand Down
39 changes: 38 additions & 1 deletion src/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { RefreshTokenService } from '../services/refreshTokenService.js';
import type { RefreshTokenRepository } from '../repositories/refreshTokenRepository.js';
import { logger } from '../logger.js';
import { UnauthorizedError } from '../errors/index.js';
import { getClientIp, DEFAULT_PROXY_HEADERS } from '../lib/clientIp.js';

export interface AuthControllerOptions {
refreshTokenService: RefreshTokenService;
Expand All @@ -19,7 +20,43 @@ export class AuthController {
}

/**
* Refresh access token using a valid refresh token.
* Wallet-based login with IP-based rate limiting applied at the route level.
* Returns JWT on successful signature verification.
*
* POST /auth/wallet
* Rate limited to 5 requests per minute per IP by loginThrottle middleware.
*/
async walletLogin(req: Request, res: Response, next: NextFunction): Promise<void> {
try {
const { walletAddress, signature, message } = req.body;

if (!walletAddress || !signature || !message) {
next(new UnauthorizedError('Missing required fields', 'MISSING_AUTH_FIELDS'));
return;
}

// Extract client IP for structured logging
const clientIp = getClientIp(req, process.env.TRUST_PROXY_HEADERS === 'true', DEFAULT_PROXY_HEADERS);

logger.info('[AuthController] Wallet login attempt', {
walletAddress,
clientIp,
});

// TODO: Implement actual Stellar signature verification
// This would typically call a service to verify the wallet signature
// against the message and derive a user ID for JWT generation

next(new UnauthorizedError('Wallet login not fully implemented', 'AUTH_NOT_IMPLEMENTED'));

} catch (error) {
logger.error('[AuthController] Error during wallet login', { error });
next(new UnauthorizedError('Login failed', 'REFRESH_FAILED'));
}
}

/**
* Refresh access token using a valid refresh token.
*
* On success the consumed refresh token is revoked and a fresh token pair
* (access + refresh) is returned. Single-use enforcement means a reused
Expand Down
Loading