5
5
getToken as getJWT ,
6
6
} from "@thirdweb-dev/auth/fastify" ;
7
7
import { AsyncWallet } from "@thirdweb-dev/wallets/evm/wallets/async" ;
8
+ import { createHash } from "crypto" ;
8
9
import { FastifyInstance } from "fastify" ;
9
10
import { FastifyRequest } from "fastify/types/request" ;
10
11
import jsonwebtoken from "jsonwebtoken" ;
@@ -153,6 +154,7 @@ export const onRequest = async ({
153
154
const jwt = getJWT ( req ) ;
154
155
if ( jwt ) {
155
156
const payload = jsonwebtoken . decode ( jwt , { json : true } ) ;
157
+ const data = payload ?. data ;
156
158
157
159
// The `iss` field determines the auth type.
158
160
if ( payload ?. iss ) {
@@ -162,7 +164,7 @@ export const onRequest = async ({
162
164
} else if ( payload . iss === THIRDWEB_DASHBOARD_ISSUER ) {
163
165
return await handleDashboardAuth ( jwt ) ;
164
166
} else {
165
- return await handleKeypairAuth ( jwt , payload . iss ) ;
167
+ return await handleKeypairAuth ( jwt , payload . iss , req , payload . data ) ;
166
168
}
167
169
}
168
170
}
@@ -264,6 +266,8 @@ const handleWebsocketAuth = async (
264
266
const handleKeypairAuth = async (
265
267
jwt : string ,
266
268
iss : string ,
269
+ req : FastifyRequest ,
270
+ data : string | null ,
267
271
) : Promise < AuthResponse > => {
268
272
// The keypair auth feature must be explicitly enabled.
269
273
if ( ! env . ENABLE_KEYPAIR_AUTH ) {
@@ -278,6 +282,11 @@ const handleKeypairAuth = async (
278
282
throw error ;
279
283
}
280
284
285
+ if ( data && req . method === "POST" && data !== hashRequestBody ( req ) ) {
286
+ error = "The request body has been tampered with." ;
287
+ throw error ;
288
+ }
289
+
281
290
// The JWT is valid if `verify` did not throw.
282
291
jsonwebtoken . verify ( jwt , keypair . publicKey , {
283
292
algorithms : [ keypair . algorithm as jsonwebtoken . Algorithm ] ,
@@ -421,3 +430,9 @@ const handleAuthWebhooks = async (
421
430
422
431
return { isAuthed : false } ;
423
432
} ;
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