Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: fixed

Consent log: send a REST nonce for logged-in visitors so the consent row records the real user ID instead of 0.
19 changes: 15 additions & 4 deletions projects/packages/cookie-consent/src/class-cookie-consent.php
Original file line number Diff line number Diff line change
Expand Up @@ -1105,15 +1105,26 @@ public static function enqueue_assets() {
// Resolve the configured Tracks event prefix once so it can be shared below.
$config = self::get_config();

$config_data = array(
'apiUrl' => rest_url( 'jetpack/v4/cookie-consent/consent-log' ),
'eventPrefix' => $config['event_prefix'],
);

// Only expose a REST nonce to logged-in visitors, so the consent logger can
// authenticate and record the real user_id. Anonymous visitors deliberately get
// none: their pages are full-page-cached, a cached nonce would go stale and make
// core reject the request (rest_cookie_invalid_nonce). Without a nonce core treats
// the request as anonymous and stores user_id = 0, which is correct for them.
if ( is_user_logged_in() ) {
$config_data['nonce'] = wp_create_nonce( 'wp_rest' );
}

// Pass REST API URL and Tracks event prefix to the module via global config.
wp_print_inline_script_tag(
sprintf(
'window.jetpackCookieConsentConfig = %s;',
wp_json_encode(
array(
'apiUrl' => rest_url( 'jetpack/v4/cookie-consent/consent-log' ),
'eventPrefix' => $config['event_prefix'],
),
$config_data,
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
)
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,20 @@ async function logConsentEvent(
return;
}

const headers: Record< string, string > = {
'Content-Type': 'application/json',
};
// Send the REST nonce when present (logged-in visitors only) so the request
// authenticates and the consent row records the real user_id instead of 0.
const nonce = window.jetpackCookieConsentConfig?.nonce;
if ( nonce ) {
headers[ 'X-WP-Nonce' ] = nonce;
}

try {
const response = await fetch( apiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
headers,
body: JSON.stringify( {
event_type: eventType,
url: window.location.href,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ declare global {
jetpackCookieConsentConfig?: {
apiUrl: string;
eventPrefix?: string;
nonce?: string;
};
wp_set_consent?: ( category: string, value: 'allow' | 'deny' ) => void;
wp_consent_type?: ConsentType;
Expand Down
Loading