Skip to content
Merged

done #788

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
54 changes: 54 additions & 0 deletions backend/src/middleware/__tests__/validation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, expect, it, vi } from 'vitest';
import type { Request, Response } from 'express';
import { z } from 'zod';
import { commonSchemas, validateAndSanitize } from '../validation.js';

function req(overrides: Partial<Request>): Request {
return {
body: {},
query: {},
params: {},
headers: {},
...overrides,
} as Request;
}

describe('validation middleware', () => {
it('sanitizes and validates body, query, and params', () => {
const request = req({
body: { email: ' USER@EXAMPLE.COM ', note: '<script>alert(1)</script>paid' },
query: { page: '2', limit: '10' },
params: { id: 'payment_123' },
});
const next = vi.fn();

validateAndSanitize({
body: z.object({
email: commonSchemas.email,
note: z.string().max(100),
}),
query: commonSchemas.pagination,
params: z.object({ id: commonSchemas.id }),
})(request, {} as Response, next);

expect(next).toHaveBeenCalledWith();
expect(request.body.email).toBe('user@example.com');
expect(request.body.note).not.toContain('<script>');
expect(request.query.page).toBe(2);
expect(request.params.id).toBe('payment_123');
});

it('passes formatted validation errors to error middleware', () => {
const request = req({ body: { amount: '-1' } });
const next = vi.fn();

validateAndSanitize({
body: z.object({ amount: commonSchemas.amount }),
})(request, {} as Response, next);

expect(next).toHaveBeenCalledWith(expect.objectContaining({
statusCode: 400,
code: 'ERR_VALIDATION_FAILED',
}));
});
});
8 changes: 8 additions & 0 deletions backend/src/middleware/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ export { slaTrackingMiddleware } from './slaTracking.js';
export { traceMiddleware, TRACE_ID_HEADER } from './trace.js';
export { cacheControlNoStore, CACHE_NOSTORE_HEADER, VARY_HEADER } from './cache-control.js';
export { validate } from './validate.js';
export {
validateAndSanitize,
validateRequest as validateRequestWithSanitization,
validateBody,
commonSchemas,
type ValidationOptions,
type ValidationSchemas,
} from './validation.js';
export { versionMiddleware } from './versioning.js';
export { verifyWebhook, webhookVerifiers, rawBodyCapture, type WebhookVerificationConfig } from './webhookVerification.js';
export { composeMiddleware, type MiddlewareFunction, type MiddlewareChain } from './compose.js';
Expand Down
2 changes: 1 addition & 1 deletion backend/src/middleware/sanitize.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ var InputSanitizer = /** @class */ (function () {
}
// XSS Protection
if (options.xssProtection) {
sanitized = (0, xss_1.default)(sanitized);
sanitized = (typeof xss_1 === 'function' ? xss_1 : xss_1.default)(sanitized);
}
// HTML Sanitization
if (options.htmlSanitization) {
Expand Down
69 changes: 44 additions & 25 deletions backend/src/middleware/validate.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.validate = void 0;
var zod_1 = require("zod");
/**
* Reusable middleware to validate the request body against a Zod schema.
* Returns a 400 Bad Request with detailed errors if validation fails.
*/
var validate = function (schema) {
return function validateMiddleware(req, res, next) {
try {
schema.parse(req.body);
next();
}
catch (error) {
if (error instanceof zod_1.ZodError) {
return res.status(400).json({
message: 'Validation failed',
errors: error.errors.map(function (err) { return ({
path: err.path.join('.'),
message: err.message,
}); }),
});
}
next(error);
}
};
exports.validate = exports.validateRequest = void 0;

const zod_1 = require("zod");
const errors_js_1 = require("../types/errors.js");

function formatIssues(issues) {
return issues.map((err) => ({
path: err.path.join(".") || "root",
message: err.message,
}));
}

function isZodError(error) {
return error instanceof zod_1.ZodError ||
(typeof error === "object" &&
error !== null &&
error.name === "ZodError" &&
Array.isArray(error.errors));
}

const validateRequest = (targets) => {
return function validateRequestMiddleware(req, _res, next) {
try {
if (targets.body) req.body = targets.body.parse(req.body ?? {});
if (targets.query) req.query = targets.query.parse(req.query ?? {});
if (targets.params) req.params = targets.params.parse(req.params ?? {});
next();
} catch (error) {
if (isZodError(error)) {
return next(new errors_js_1.AppError(
400,
"Request validation failed",
"ERR_VALIDATION_FAILED",
formatIssues(error.errors)
));
}
next(error);
}
};
};

exports.validateRequest = validateRequest;
const validate = (schema) => (0, exports.validateRequest)({ body: schema });
exports.validate = validate;
exports.default = validate;
13 changes: 11 additions & 2 deletions backend/src/middleware/validate.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from 'express';
import { ZodSchema, ZodError, ZodIssue } from 'zod';
import { AppError } from './errorHandler.js';
import { AppError } from '../types/errors.js';

export interface ValidationTargets {
body?: ZodSchema;
Expand All @@ -15,6 +15,15 @@ function formatIssues(issues: ZodIssue[]) {
}));
}

function isZodError(error: unknown): error is ZodError {
return error instanceof ZodError || (
typeof error === 'object' &&
error !== null &&
(error as { name?: string }).name === 'ZodError' &&
Array.isArray((error as { errors?: unknown }).errors)
);
}

/**
* Validate request body, query, and params against Zod schemas.
* Returns generic 400 responses without leaking internal details.
Expand All @@ -33,7 +42,7 @@ export const validateRequest = (targets: ValidationTargets) => {
}
next();
} catch (error) {
if (error instanceof ZodError) {
if (isZodError(error)) {
return next(new AppError(400, 'Request validation failed', 'ERR_VALIDATION_FAILED', formatIssues(error.errors)));
}
next(error);
Expand Down
101 changes: 101 additions & 0 deletions backend/src/middleware/validation.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.validateBody = exports.validateRequest = exports.validateAndSanitize = exports.commonSchemas = void 0;

const zod_1 = require("zod");
const errors_js_1 = require("../types/errors.js");
const sanitize_js_1 = require("./sanitize.js");

exports.commonSchemas = {
uuid: zod_1.z.string().uuid(),
id: zod_1.z.string().trim().min(1).max(128).regex(/^[a-zA-Z0-9._:-]+$/),
email: zod_1.z.string().trim().email().max(255).transform((value) => value.toLowerCase()),
pagination: zod_1.z.object({
page: zod_1.z.coerce.number().int().min(1).max(1000).default(1),
limit: zod_1.z.coerce.number().int().min(1).max(100).default(20),
}),
stellarAddress: zod_1.z.string().regex(/^G[A-Z0-9]{55}$/, "Invalid Stellar address format"),
amount: zod_1.z.coerce.number().positive().finite().max(1_000_000_000),
};

function sanitizeValue(value, options) {
return sanitize_js_1.InputSanitizer.getInstance().sanitize(value, {
sqlEscape: false,
htmlSanitization: false,
escapeHtml: false,
...options,
});
}

function parseSchema(schema, value, stripUnknown) {
if (stripUnknown && schema instanceof zod_1.z.ZodObject) {
return schema.strip().parse(value ?? {});
}
return schema.parse(value ?? {});
}

function formatZodError(error) {
return error.issues.map((issue) => ({
path: issue.path.join(".") || "root",
message: issue.message,
code: issue.code,
}));
}

function isZodError(error) {
return error instanceof zod_1.ZodError ||
(typeof error === "object" &&
error !== null &&
error.name === "ZodError" &&
Array.isArray(error.errors));
}

function validateAndSanitize(schemas, options = {}) {
return function validationMiddleware(req, _res, next) {
try {
const shouldSanitize = options.sanitize ?? true;

if (schemas.body) {
const value = shouldSanitize ? sanitizeValue(req.body ?? {}, options.sanitizer) : req.body;
req.body = parseSchema(schemas.body, value, options.stripUnknown);
}

if (schemas.query) {
const value = shouldSanitize ? sanitizeValue(req.query ?? {}, options.sanitizer) : req.query;
req.query = parseSchema(schemas.query, value, options.stripUnknown);
}

if (schemas.params) {
const value = shouldSanitize ? sanitizeValue(req.params ?? {}, options.sanitizer) : req.params;
req.params = parseSchema(schemas.params, value, options.stripUnknown);
}

if (schemas.headers) {
const headers = Object.fromEntries(
Object.entries(req.headers).map(([key, value]) => [key.toLowerCase(), value])
);
parseSchema(schemas.headers, headers, options.stripUnknown);
}

next();
} catch (error) {
if (isZodError(error)) {
return next(new errors_js_1.AppError(
400,
"Request validation failed",
"ERR_VALIDATION_FAILED",
formatZodError(error)
));
}

next(error);
}
};
}

exports.validateAndSanitize = validateAndSanitize;
exports.validateRequest = validateAndSanitize;
const validateBody = (schema, options) => validateAndSanitize({ body: schema }, options);
exports.validateBody = validateBody;
exports.default = validateAndSanitize;
Loading
Loading