Skip to content

Commit abcba2f

Browse files
committed
fix(server): using zod v4 and fastify were expecting different specification versions for json schemas
1 parent f4693f4 commit abcba2f

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

packages/server/package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@
4242
"@fastify/websocket": "^7.1.3",
4343
"@socialgouv/e2esdk-api": "workspace:^",
4444
"@socialgouv/e2esdk-crypto": "workspace:^",
45+
"ajv": "^8.17.1",
46+
"ajv-formats": "^3.0.1",
4547
"dotenv": "^16.0.3",
48+
"fast-uri": "^3.1.0",
4649
"fastify": "^4.15.0",
4750
"fastify-micro": "4.0.0-beta.4",
4851
"fastify-plugin": "^4.5.0",

packages/server/src/server.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import addFormats from 'ajv-formats'
2+
import Ajv2020 from 'ajv/dist/2020.js'
3+
import fastUri from 'fast-uri'
14
import { createServer as createFastifyServer } from 'fastify-micro'
25
import path from 'node:path'
36
import { fileURLToPath } from 'node:url'
@@ -150,6 +153,27 @@ export function createServer() {
150153
},
151154
})
152155

156+
// By default Fastify is using the JSON schema specification "draft 7" whereas new librairies like Zod v4
157+
// by default generates schemas for the specification "2020-12", so make sure the AJV instance is for this specification
158+
// (otherwise the schema parsing would not work)
159+
const ajv = new Ajv2020({
160+
// We reuse the initial Fastify parameters they pass to be "safe"
161+
// Ref: https://fastify.dev/docs/v4.29.x/Reference/Validation-and-Serialization/#validator-compiler
162+
coerceTypes: 'array',
163+
useDefaults: true,
164+
removeAdditional: true,
165+
uriResolver: fastUri,
166+
addUsedSchema: false,
167+
allErrors: false, // Explicitly set allErrors to `false`. When set to `true`, a DoS attack is possible.
168+
})
169+
170+
// Native formats like "uuid" are not supported by default, so adding them
171+
addFormats(ajv)
172+
173+
app.setValidatorCompiler(({ schema, method, url, httpPart }) => {
174+
return ajv.compile(schema)
175+
})
176+
153177
app.ready(() => {
154178
app.log.debug({
155179
msg: 'Plugins loaded',

pnpm-lock.yaml

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)