Skip to content
Draft
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
2 changes: 2 additions & 0 deletions api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
"@types/swagger-ui-express": "^4.1.8",
"cors": "^2.8.5",
"express": "^4.21.2",
"express-rate-limit": "^8.2.1",
"helmet": "^8.1.0",
"sqlite3": "^5.1.7",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1"
Expand Down
27 changes: 27 additions & 0 deletions api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import express from 'express';
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import cors from 'cors';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import deliveryRoutes from './routes/delivery';
import orderDetailDeliveryRoutes from './routes/orderDetailDelivery';
import productRoutes from './routes/product';
Expand All @@ -16,6 +18,31 @@ import { errorHandler } from './utils/errors';
const app = express();
const port = process.env.PORT || 3000;

// Security: Add Helmet middleware for security headers
app.use(
helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
scriptSrc: ["'self'"],
imgSrc: ["'self'", 'data:', 'https:'],
},
},
crossOriginEmbedderPolicy: false, // Allow embedding for Swagger UI
}),
);

// Security: Add rate limiting to prevent DoS attacks
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // Limit each IP to 100 requests per windowMs
message: 'Too many requests from this IP, please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
app.use('/api', limiter);

// Parse CORS origins from environment variable if available
const corsOrigins = process.env.API_CORS_ORIGINS
? process.env.API_CORS_ORIGINS.split(',')
Expand Down
6 changes: 4 additions & 2 deletions api/src/repositories/branchesRepo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { getDatabase, DatabaseConnection } from '../db/sqlite';
import { Branch } from '../models/branch';
import { handleDatabaseError, NotFoundError } from '../utils/errors';
import { buildInsertSQL, buildUpdateSQL, objectToCamelCase } from '../utils/sql';
import { sanitizeSearchQuery } from '../utils/validation';

export class BranchesRepository {
private db: DatabaseConnection;
Expand Down Expand Up @@ -130,9 +131,10 @@ export class BranchesRepository {
*/
async findByName(name: string): Promise<Branch[]> {
try {
const sanitizedName = sanitizeSearchQuery(name);
const rows = await this.db.all<any>(
'SELECT * FROM branches WHERE name LIKE ? ORDER BY name',
[`%${name}%`],
"SELECT * FROM branches WHERE name LIKE ? ESCAPE '\\' ORDER BY name",
[`%${sanitizedName}%`],
);
return rows.map((row) => objectToCamelCase(row) as Branch);
} catch (error) {
Expand Down
10 changes: 7 additions & 3 deletions api/src/routes/order.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ import express from 'express';
import { Order } from '../models/order';
import { getOrdersRepository } from '../repositories/ordersRepo';
import { handleDatabaseError, NotFoundError } from '../utils/errors';
import { validatePositiveInteger } from '../utils/validation';

const router = express.Router();

Expand Down Expand Up @@ -131,8 +132,9 @@ router.get('/', async (req, res, next) => {
// Get an order by ID
router.get('/:id', async (req, res, next) => {
try {
const id = validatePositiveInteger(req.params.id, 'Order ID');
const repo = await getOrdersRepository();
const order = await repo.findById(parseInt(req.params.id));
const order = await repo.findById(id);
if (order) {
res.json(order);
} else {
Expand All @@ -146,8 +148,9 @@ router.get('/:id', async (req, res, next) => {
// Update an order by ID
router.put('/:id', async (req, res, next) => {
try {
const id = validatePositiveInteger(req.params.id, 'Order ID');
const repo = await getOrdersRepository();
const updatedOrder = await repo.update(parseInt(req.params.id), req.body);
const updatedOrder = await repo.update(id, req.body);
res.json(updatedOrder);
} catch (error) {
if (error instanceof NotFoundError) {
Expand All @@ -161,8 +164,9 @@ router.put('/:id', async (req, res, next) => {
// Delete an order by ID
router.delete('/:id', async (req, res, next) => {
try {
const id = validatePositiveInteger(req.params.id, 'Order ID');
const repo = await getOrdersRepository();
await repo.delete(parseInt(req.params.id));
await repo.delete(id);
res.status(204).send();
} catch (error) {
if (error instanceof NotFoundError) {
Expand Down
7 changes: 6 additions & 1 deletion api/src/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ export function handleDatabaseError(error: any, entity?: string, id?: string | n
* Express error handler middleware for database errors
*/
export function errorHandler(error: any, req: any, res: any, next: any) {
// Log error for debugging (in production, use proper logging service)
console.error('Error:', error.message);

if (error instanceof DatabaseError) {
return res.status(error.statusCode).json({
error: {
Expand All @@ -82,11 +85,13 @@ export function errorHandler(error: any, req: any, res: any, next: any) {
});
}

// Default error handling
// Default error handling - don't leak internal error details in production
const isDevelopment = process.env.NODE_ENV !== 'production';
return res.status(500).json({
error: {
code: 'INTERNAL_ERROR',
message: 'An unexpected error occurred',
...(isDevelopment && { details: error.message }), // Only show details in development
},
});
}
115 changes: 115 additions & 0 deletions api/src/utils/validation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Input validation and sanitization utilities
*/

import { ValidationError } from './errors';

/**
* Validate that a value is a positive integer
*/
export function validatePositiveInteger(value: any, fieldName: string): number {
const num = parseInt(value, 10);
if (isNaN(num) || num <= 0) {
throw new ValidationError(`${fieldName} must be a positive integer`);
}
return num;
}

/**
* Validate that a value is a non-negative integer
*/
export function validateNonNegativeInteger(value: any, fieldName: string): number {
const num = parseInt(value, 10);
if (isNaN(num) || num < 0) {
throw new ValidationError(`${fieldName} must be a non-negative integer`);
}
return num;
}

/**
* Validate and sanitize string input
*/
export function validateString(
value: any,
fieldName: string,
options: { required?: boolean; maxLength?: number; minLength?: number } = {},
): string {
const { required = true, maxLength, minLength } = options;

if (value === undefined || value === null || value === '') {
if (required) {
throw new ValidationError(`${fieldName} is required`);
}
return '';
}

const str = String(value).trim();

if (minLength && str.length < minLength) {
throw new ValidationError(`${fieldName} must be at least ${minLength} characters`);
}

if (maxLength && str.length > maxLength) {
throw new ValidationError(`${fieldName} must not exceed ${maxLength} characters`);
}

return str;
}

/**
* Validate email format
*/
export function validateEmail(email: string, fieldName: string = 'Email'): string {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const sanitized = validateString(email, fieldName, { maxLength: 255 });

if (!emailRegex.test(sanitized)) {
throw new ValidationError(`${fieldName} must be a valid email address`);
}

return sanitized;
}

/**
* Validate date format (ISO 8601)
*/
export function validateDate(date: string, fieldName: string): string {
const sanitized = validateString(date, fieldName);
const parsed = new Date(sanitized);

if (isNaN(parsed.getTime())) {
throw new ValidationError(`${fieldName} must be a valid ISO 8601 date`);
}

return sanitized;
}

/**
* Validate enum value
*/
export function validateEnum<T extends string>(
value: any,
allowedValues: readonly T[],
fieldName: string,
): T {
const sanitized = validateString(value, fieldName);

if (!allowedValues.includes(sanitized as T)) {
throw new ValidationError(
`${fieldName} must be one of: ${allowedValues.join(', ')}`,
);
}

return sanitized as T;
}

/**
* Sanitize search query to prevent SQL injection in LIKE clauses
* Note: This should ONLY be used with parameterized queries.
* The parameterized query prevents SQL injection, this just escapes wildcards
* to prevent unintended LIKE pattern matching.
*/
export function sanitizeSearchQuery(query: string): string {
// Escape SQL LIKE wildcards (% and _) using backslash
return query.replace(/[%_\\]/g, '\\$&').trim();
}
Loading