Skip to content

Commit 920bc91

Browse files
committed
Update: Key-Pair auth data check
1 parent 3325fad commit 920bc91

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

src/server/middleware/auth.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
getToken as getJWT,
66
} from "@thirdweb-dev/auth/fastify";
77
import { AsyncWallet } from "@thirdweb-dev/wallets/evm/wallets/async";
8+
import { createHash } from "crypto";
89
import { FastifyInstance } from "fastify";
910
import { FastifyRequest } from "fastify/types/request";
1011
import jsonwebtoken from "jsonwebtoken";
@@ -153,6 +154,7 @@ export const onRequest = async ({
153154
const jwt = getJWT(req);
154155
if (jwt) {
155156
const payload = jsonwebtoken.decode(jwt, { json: true });
157+
const data = payload?.data;
156158

157159
// The `iss` field determines the auth type.
158160
if (payload?.iss) {
@@ -162,7 +164,7 @@ export const onRequest = async ({
162164
} else if (payload.iss === THIRDWEB_DASHBOARD_ISSUER) {
163165
return await handleDashboardAuth(jwt);
164166
} else {
165-
return await handleKeypairAuth(jwt, payload.iss);
167+
return await handleKeypairAuth(jwt, payload.iss, req, payload.data);
166168
}
167169
}
168170
}
@@ -264,6 +266,8 @@ const handleWebsocketAuth = async (
264266
const handleKeypairAuth = async (
265267
jwt: string,
266268
iss: string,
269+
req: FastifyRequest,
270+
data: string | null,
267271
): Promise<AuthResponse> => {
268272
// The keypair auth feature must be explicitly enabled.
269273
if (!env.ENABLE_KEYPAIR_AUTH) {
@@ -278,6 +282,11 @@ const handleKeypairAuth = async (
278282
throw error;
279283
}
280284

285+
if (data && req.method === "POST" && data !== hashRequestBody(req)) {
286+
error = "The request body has been tampered with.";
287+
throw error;
288+
}
289+
281290
// The JWT is valid if `verify` did not throw.
282291
jsonwebtoken.verify(jwt, keypair.publicKey, {
283292
algorithms: [keypair.algorithm as jsonwebtoken.Algorithm],
@@ -421,3 +430,9 @@ const handleAuthWebhooks = async (
421430

422431
return { isAuthed: false };
423432
};
433+
434+
const hashRequestBody = (req: FastifyRequest): string => {
435+
return createHash("sha256")
436+
.update(JSON.stringify(req.body), "utf8")
437+
.digest("hex");
438+
};

0 commit comments

Comments
 (0)