Skip to content

Commit

Permalink
Merge branch 'develop' of github.com:mission-apprentissage/tjp-pilota…
Browse files Browse the repository at this point in the history
…ge into feat/campagneRegion
  • Loading branch information
LucasDetre committed Feb 18, 2025
2 parents 2611147 + 1cd16a8 commit 31679b1
Showing 1 changed file with 48 additions and 6 deletions.
54 changes: 48 additions & 6 deletions server/src/server/middlewares/errorMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,60 @@ export function formatResponseError(rawError: FastifyError | Boom<unknown> | Err
return result;
}

const withoutSensibleFields = (obj: unknown, seen: Set<unknown>): unknown => {
if (obj == null) return obj;

if (typeof obj === "object") {
if (seen.has(obj)) {
return "(ref)";
}

seen.add(obj);

if (Array.isArray(obj)) {
return obj.map((v) => withoutSensibleFields(v, seen));
}

if (obj instanceof Set) {
return Array.from(obj).map((v) => withoutSensibleFields(v, seen));
}

if (obj instanceof Map) {
return withoutSensibleFields(Object.fromEntries(obj.entries()), seen);
}

return Object.fromEntries(
Object.entries(obj).map(([key, value]) => {
const lower = key.toLowerCase();
if (
lower.indexOf("token") !== -1 ||
["authorization", "password", "pwd"].includes(lower)
) {
return [key, "*****"];
}

return [key, withoutSensibleFields(value, seen)];
})
);
}

if (typeof obj === "string") {
// max 2Ko
return obj.length > 2000 ? obj.substring(0, 2_000) + "..." : obj;
}

return obj;
};

export function errorMiddleware(server: Server) {
server.setErrorHandler<FastifyError | Boom<unknown> | Error | ZodError, { Reply: IResError }>(
(rawError, _request, reply) => {
const logGenericInfo = {
req: {
url: _request.url,
params: _request.params,
body: _request.body,
user: _request.user ? {
email: _request.user.email,
id: _request.user.id
} : undefined
params: withoutSensibleFields(_request.params, new Set([])),
body: withoutSensibleFields(_request.body, new Set()),
user: _request.user ? withoutSensibleFields(_request.user, new Set([])) : undefined
},
res: {
statusCode: reply.statusCode
Expand Down

0 comments on commit 31679b1

Please sign in to comment.