@@ -32,42 +32,43 @@ function getKeyData() {
3232}
3333
3434function canonicalize ( url : URL ) : string {
35- const params = new URLSearchParams ( url . searchParams ) ;
35+ const sigParams = url . searchParams . get ( 'sig_params' ) ;
3636
37- const canonicalParams = new URLSearchParams ( ) ;
37+ let params ;
38+ if ( sigParams ) {
39+ const allowedParams = sigParams . split ( ',' ) ;
40+ params = new URLSearchParams ( ) ;
3841
39- // If sig_params is present, only include the
40- // parameters listed in it for sig verification
41- if ( params . has ( 'sig_params' ) ) {
42- const stringifiedSigParams = params . get ( 'sig_params' ) || '' ;
43-
44- // Filter to only valid, existing params with non-null values
45- stringifiedSigParams . split ( ',' ) . forEach ( ( paramName ) => {
46- if ( ! paramName ) return ; // Skip empty strings
47-
48- const value = params . get ( paramName ) ; // can be string or null
49- if ( value !== null ) {
50- // remove null
51- canonicalParams . set ( paramName , value ) ;
42+ for ( const allowedParam of allowedParams ) {
43+ const values = url . searchParams . getAll ( allowedParam ) ;
44+ for ( const value of values ) {
45+ params . append ( allowedParam , value ) ;
5246 }
53- } ) ;
54-
55- canonicalParams . set ( 'sig_params' , stringifiedSigParams ) ;
56- canonicalParams . sort ( ) ;
47+ }
5748
58- const queryString = canonicalParams . toString ( ) ;
59- return url . origin + url . pathname + ( queryString ? `?${ queryString } ` : '' ) ;
49+ params . append ( 'sig_params' , sigParams ) ;
50+ } else {
51+ params = new URLSearchParams ( url . searchParams ) ;
52+ params . delete ( 'sig' ) ;
6053 }
6154
62- // Fallback to old behavior for URLs without sig_params
63- params . delete ( 'sig' ) ;
64- params . sort ( ) ;
65-
66- const queryString = params . toString ( ) ;
67- const fullUrl =
55+ const paramsArray = Array . from ( params . entries ( ) ) ;
56+ paramsArray . sort ( ( a , b ) => {
57+ if ( a [ 0 ] < b [ 0 ] ) return - 1 ;
58+ if ( a [ 0 ] > b [ 0 ] ) return 1 ;
59+ return 0 ;
60+ } ) ;
61+
62+ const queryString = paramsArray
63+ . map (
64+ ( [ key , value ] ) =>
65+ `${ encodeURIComponent ( key ) } =${ encodeURIComponent ( value ) } ` ,
66+ )
67+ . join ( '&' ) ;
68+
69+ const result =
6870 url . origin + url . pathname + ( queryString ? `?${ queryString } ` : '' ) ;
69-
70- return fullUrl ;
71+ return result ;
7172}
7273
7374export const MISSING = 'MISSING' as const ;
0 commit comments