diff --git a/services/web/app/src/infrastructure/Validation.js b/services/web/app/src/infrastructure/Validation.js index 427cede539..72629ae64a 100644 --- a/services/web/app/src/infrastructure/Validation.js +++ b/services/web/app/src/infrastructure/Validation.js @@ -3,12 +3,12 @@ const { Joi: CelebrateJoi, celebrate, errors } = require('celebrate') const { ObjectId } = require('mongodb-legacy') const { NotFoundError } = require('../Features/Errors/Errors') -const { z } = require('zod') - -/** - * @import { ZodType } from 'zod' - * @import { Request } from 'express' - */ +const { + validateReq, + z, + zz, + ParamsError, +} = require('@overleaf/validation-tools') const objectIdValidator = { type: 'objectId', @@ -40,35 +40,23 @@ function validate(schema) { return celebrate(schema, { allowUnknown: true }) } -const zz = { - objectId: () => - z.string().refine(ObjectId.isValid, { message: 'invalid Mongo ObjectId' }), - coercedObjectId: () => - z - .string() - .refine(ObjectId.isValid, { message: 'invalid Mongo ObjectId' }) - .transform(val => new ObjectId(val)), - hex: () => z.string().regex(/^[0-9a-f]*$/), -} - -/** - * Validate a request against a zod schema - * - * @template T - * @param {Request} req - * @param {ZodType} schema - * @return {T} - */ -function validateReq(req, schema) { - const parsed = schema.safeParse(req) - if (parsed.success) { - return parsed.data - } else if (parsed.error.issues.some(issue => issue.path[0] === 'params')) { - // Parts of the URL path failed to validate; throw a 404 rather than a 400 - throw new NotFoundError('Not found').withCause(parsed.error) - } else { - throw parsed.error +const validateReqWeb = (req, schema) => { + try { + return validateReq(req, schema) + } catch (err) { + if (err instanceof ParamsError) { + // convert into a NotFoundError that web understands + throw new NotFoundError('Not found').withCause(err) + } + throw err } } -module.exports = { Joi, validate, errorMiddleware, validateReq, z, zz } +module.exports = { + Joi, + validate, + errorMiddleware, + validateReq: validateReqWeb, + z, + zz, +} diff --git a/services/web/package.json b/services/web/package.json index be150b9fab..4c0ffdd2ed 100644 --- a/services/web/package.json +++ b/services/web/package.json @@ -94,6 +94,7 @@ "@overleaf/redis-wrapper": "*", "@overleaf/settings": "*", "@overleaf/stream-utils": "*", + "@overleaf/validation-tools": "*", "@phosphor-icons/react": "^2.1.7", "@slack/webhook": "^7.0.2", "@stripe/react-stripe-js": "^3.9.0",