File tree Expand file tree Collapse file tree
projects/packages/cookie-consent Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ Significance: patch
2+ Type: fixed
3+
4+ Consent log: send a REST nonce for logged-in visitors so the consent row records the real user ID instead of 0.
Original file line number Diff line number Diff line change @@ -1228,15 +1228,26 @@ public static function enqueue_assets() {
12281228 // Resolve the configured Tracks event prefix once so it can be shared below.
12291229 $ config = self ::get_config ();
12301230
1231+ $ config_data = array (
1232+ 'apiUrl ' => rest_url ( 'jetpack/v4/cookie-consent/consent-log ' ),
1233+ 'eventPrefix ' => $ config ['event_prefix ' ],
1234+ );
1235+
1236+ // Only expose a REST nonce to logged-in visitors, so the consent logger can
1237+ // authenticate and record the real user_id. Anonymous visitors deliberately get
1238+ // none: their pages are full-page-cached, a cached nonce would go stale and make
1239+ // core reject the request (rest_cookie_invalid_nonce). Without a nonce core treats
1240+ // the request as anonymous and stores user_id = 0, which is correct for them.
1241+ if ( is_user_logged_in () ) {
1242+ $ config_data ['nonce ' ] = wp_create_nonce ( 'wp_rest ' );
1243+ }
1244+
12311245 // Pass REST API URL and Tracks event prefix to the module via global config.
12321246 wp_print_inline_script_tag (
12331247 sprintf (
12341248 'window.jetpackCookieConsentConfig = %s; ' ,
12351249 wp_json_encode (
1236- array (
1237- 'apiUrl ' => rest_url ( 'jetpack/v4/cookie-consent/consent-log ' ),
1238- 'eventPrefix ' => $ config ['event_prefix ' ],
1239- ),
1250+ $ config_data ,
12401251 JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
12411252 )
12421253 ),
Original file line number Diff line number Diff line change @@ -24,12 +24,20 @@ async function logConsentEvent(
2424 return ;
2525 }
2626
27+ const headers : Record < string , string > = {
28+ 'Content-Type' : 'application/json' ,
29+ } ;
30+ // Send the REST nonce when present (logged-in visitors only) so the request
31+ // authenticates and the consent row records the real user_id instead of 0.
32+ const nonce = window . jetpackCookieConsentConfig ?. nonce ;
33+ if ( nonce ) {
34+ headers [ 'X-WP-Nonce' ] = nonce ;
35+ }
36+
2737 try {
2838 const response = await fetch ( apiUrl , {
2939 method : 'POST' ,
30- headers : {
31- 'Content-Type' : 'application/json' ,
32- } ,
40+ headers,
3341 body : JSON . stringify ( {
3442 event_type : eventType ,
3543 url : window . location . href ,
Original file line number Diff line number Diff line change @@ -41,6 +41,7 @@ declare global {
4141 jetpackCookieConsentConfig ?: {
4242 apiUrl : string ;
4343 eventPrefix ?: string ;
44+ nonce ?: string ;
4445 } ;
4546 wp_set_consent ?: ( category : string , value : 'allow' | 'deny' ) => void ;
4647 wp_consent_type ?: ConsentType ;
You can’t perform that action at this time.
0 commit comments