@@ -2,6 +2,10 @@ import { createHash } from "node:crypto";
22import { privateKeyToAccount } from "viem/accounts" ;
33import type { RequestSignerConfig } from "../core/types.js" ;
44
5+ const EMPTY_BODY_HASH =
6+ "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ;
7+ type BodyHashFormat = NonNullable < RequestSignerConfig [ "bodyHashFormat" ] > ;
8+
59function base64urlEncode ( input : string ) : string {
610 return Buffer . from ( input , "utf-8" )
711 . toString ( "base64" )
@@ -21,14 +25,18 @@ function canonicalizeJson(obj: unknown): unknown {
2125 return sorted ;
2226}
2327
24- function computeBodyHash ( body ?: string ) : string {
28+ function computeBodyHash (
29+ body : string | undefined ,
30+ format : BodyHashFormat ,
31+ ) : string {
2532 if ( ! body || body . length === 0 ) {
26- return "" ;
33+ return format === "prefixed" ? EMPTY_BODY_HASH : "" ;
2734 }
2835 const parsed = JSON . parse ( body ) ;
2936 const canonical = canonicalizeJson ( parsed ) ;
3037 const canonicalStr = JSON . stringify ( canonical ) ;
31- return createHash ( "sha256" ) . update ( canonicalStr ) . digest ( "hex" ) ;
38+ const hash = createHash ( "sha256" ) . update ( canonicalStr ) . digest ( "hex" ) ;
39+ return format === "prefixed" ? `sha256:${ hash } ` : hash ;
3240}
3341
3442/**
@@ -64,6 +72,7 @@ export function createRequestSigner(
6472 config : RequestSignerConfig ,
6573) : RequestSigner {
6674 const account = privateKeyToAccount ( config . privateKey ) ;
75+ const bodyHashFormat = config . bodyHashFormat ?? "legacy" ;
6776
6877 return {
6978 address : account . address ,
@@ -73,7 +82,7 @@ export function createRequestSigner(
7382
7483 const payload : Record < string , unknown > = {
7584 aud : params . aud ,
76- bodyHash : computeBodyHash ( params . body ) ,
85+ bodyHash : computeBodyHash ( params . body , bodyHashFormat ) ,
7786 exp : now + 300 ,
7887 iat : now ,
7988 method : params . method ,
0 commit comments