File size: 8,613 Bytes
6778ee0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/** @typedef {import('../test/support/types').VerifierArgs} VerifierArgs */
/** @typedef {import('../test/support/types').VerifierResult} VerifierResult */
import { initializeCookieConsentEngine } from './autoconsent-to-cookies'
import { checkDisallowedByCSP } from './check-disallowed-by-csp'

/**
 * Function that verifies if Plausible is installed correctly.
 * @param {VerifierArgs}
 * @returns {Promise<VerifierResult>}
 */

const DEFAULT_TRACKER_SCRIPT_SELECTOR = 'script[src^="https://plausible.io/js"]'

async function verifyPlausibleInstallation(options) {
  const {
    timeoutMs,
    responseHeaders,
    debug,
    cspHostToCheck,
    trackerScriptSelector
  } = {
    trackerScriptSelector: DEFAULT_TRACKER_SCRIPT_SELECTOR,
    ...options
  }

  function log(message) {
    if (debug) console.log('[VERIFICATION]', message)
  }

  const disallowedByCsp = checkDisallowedByCSP(responseHeaders, cspHostToCheck)

  forceIgnoreWebdriverCondition()
  const { stopRecording, getInterceptedFetch } = startRecordingEventFetchCalls()

  const {
    plausibleIsInitialized,
    plausibleIsOnWindow,
    plausibleVersion,
    plausibleVariant,
    testEvent,
    cookiesConsentResult,
    error: testPlausibleFunctionError
  } = await testPlausibleFunction({
    timeoutMs,
    debug
  })
  const trackerIsInHtml = isInHtml(trackerScriptSelector)

  if (testPlausibleFunctionError) {
    log(
      `There was an error testing plausible function: ${testPlausibleFunctionError}`
    )
  }

  stopRecording()

  let interceptedTestEvent = getInterceptedFetch('verification-agent-test')

  if (!interceptedTestEvent) {
    log(`No test event request was among intercepted requests`)
  }

  // this can be removed once most sites have migrated to v2 and WP plugin is migrated to v2
  if (
    !interceptedTestEvent &&
    [200, 202].includes(testEvent.callbackResult?.status)
  ) {
    log(
      `The callback result indicates a successful request, assuming legacy .compat installation that uses XMLHttpRequest`
    )
    const firstLegacySnippet = document.querySelector(
      'script[data-domain][src]'
    )
    if (firstLegacySnippet) {
      // legacy installations may list multiple domains in a comma-separated list
      const domainString = firstLegacySnippet.getAttribute('data-domain')
      const firstDomain = domainString && domainString.split(',').shift()

      interceptedTestEvent = {
        request: {
          normalizedBody: {
            __legacyCompatInstallation: true,
            domain: firstDomain
          }
        },
        response: { status: testEvent.callbackResult.status }
      }
    }
  }

  const diagnostics = {
    disallowedByCsp,
    trackerIsInHtml,
    plausibleIsOnWindow,
    plausibleIsInitialized,
    plausibleVersion,
    plausibleVariant,
    testEvent: {
      ...testEvent, // callbackResult
      testPlausibleFunctionError,
      requestUrl: interceptedTestEvent?.request?.url,
      normalizedBody: interceptedTestEvent?.request?.normalizedBody,
      responseStatus: interceptedTestEvent?.response?.status,
      error: interceptedTestEvent?.error
    },
    cookiesConsentResult
  }

  log({
    diagnostics
  })

  return {
    data: {
      completed: true,
      ...diagnostics
    }
  }
}

function getNormalizedPlausibleEventBody(fetchOptions) {
  try {
    const body = JSON.parse(fetchOptions.body ?? '{}')

    let name = null
    let domain = null
    let version = null

    if (
      fetchOptions.method === 'POST' &&
      (typeof body?.n === 'string' || typeof body?.name === 'string') &&
      (typeof body?.d === 'string' || typeof body?.domain === 'string')
    ) {
      name = body?.n || body?.name
      domain = body?.d || body?.domain
      version = body?.v || body?.version
    }
    return name && domain ? { name, domain, version } : null
  } catch (_error) {
    // ignore error
  }
}

function startRecordingEventFetchCalls() {
  const interceptions = new Map()

  const originalFetch = window.fetch
  window.fetch = function (url, options = {}) {
    let identifier = null

    const normalizedEventBody = getNormalizedPlausibleEventBody(options)
    if (normalizedEventBody) {
      identifier = normalizedEventBody.name
      interceptions.set(identifier, {
        request: { url, normalizedBody: normalizedEventBody }
      })
    }

    return originalFetch
      .apply(this, arguments)
      .then(async (response) => {
        const eventRequest = interceptions.get(identifier)
        if (eventRequest) {
          const responseClone = response.clone()
          const body = await responseClone.text()
          eventRequest.response = { status: response.status, body }
        }
        return response
      })
      .catch((error) => {
        const eventRequest = interceptions.get(identifier)
        if (eventRequest) {
          eventRequest.error = {
            message: error?.message || 'Unknown error during fetch'
          }
        }
        throw error
      })
  }
  return {
    getInterceptedFetch: (identifier) => interceptions.get(identifier),
    stopRecording: () => {
      window.fetch = originalFetch
    }
  }
}

function isInHtml(selector) {
  return document.querySelector(selector) !== null
}

function isPlausibleOnWindow() {
  return !!window.plausible
}

function isPlausibleInitialized() {
  return window.plausible?.l
}

function getPlausibleVersion() {
  return window.plausible?.v
}

function getPlausibleVariant() {
  return window.plausible?.s
}

async function testPlausibleFunction({ timeoutMs, debug }) {
  return new Promise((_resolve) => {
    let plausibleIsOnWindow = isPlausibleOnWindow()
    let plausibleIsInitialized = isPlausibleInitialized()
    let plausibleVersion = getPlausibleVersion()
    let plausibleVariant = getPlausibleVariant()
    let testEvent = {}
    let cookiesConsentResult = {
      handled: null,
      engineLifecycle: 'not-started'
    }
    let timeout = null
    let plausibleOnWindowPollInterval = null
    let plausibleInitializedPollInterval = null
    let testEventPollInterval = null

    let resolved = false

    const resolve = (overrides) => {
      clearTimeout(timeout)
      clearInterval(plausibleOnWindowPollInterval)
      clearInterval(plausibleInitializedPollInterval)
      clearInterval(testEventPollInterval)
      if (resolved) {
        return
      }

      resolved = true
      _resolve({
        plausibleIsOnWindow,
        plausibleIsInitialized,
        plausibleVersion,
        plausibleVariant,
        testEvent,
        cookiesConsentResult,
        ...overrides
      })
    }

    timeout = setTimeout(() => {
      resolve({
        error: 'Test Plausible function timeout exceeded'
      })
    }, timeoutMs)

    plausibleOnWindowPollInterval = setInterval(
      () =>
        plausibleIsOnWindow
          ? clearInterval(plausibleOnWindowPollInterval)
          : (plausibleIsOnWindow = isPlausibleOnWindow()),
      10
    )

    plausibleInitializedPollInterval = setInterval(() => {
      if (plausibleIsInitialized) {
        plausibleVersion = getPlausibleVersion()
        plausibleVariant = getPlausibleVariant()
        clearInterval(plausibleInitializedPollInterval)
      } else {
        plausibleIsInitialized = isPlausibleInitialized()
      }
    }, 10)

    testEventPollInterval = setInterval(() => {
      if (plausibleIsOnWindow && plausibleIsInitialized) {
        window.plausible('verification-agent-test', {
          callback: (testEventCallbackResult) => {
            resolve({
              testEvent: {
                callbackResult: testEventCallbackResult ?? 'undefined or null'
              }
            })
          }
        })
        clearInterval(testEventPollInterval)
      }
    }, 10)

    cookiesConsentResult = initializeCookieConsentEngine({
      debug,
      onConsentDone: (cmp) => {
        if (resolved) return
        cookiesConsentResult = { handled: true, cmp }
      },
      onConsentError: (err) => {
        if (resolved) return
        cookiesConsentResult = { handled: false, error: err }
      },
      onLifecycleUpdate: (lifecycle) => {
        if (resolved) return
        // skips messages that might override consent success or error
        if (cookiesConsentResult.handled !== null) return
        if (lifecycle === 'done') {
          cookiesConsentResult = { handled: true }
        } else {
          cookiesConsentResult.engineLifecycle = lifecycle
        }
      }
    })
  })
}

function forceIgnoreWebdriverCondition() {
  window.__plausible = true
}

window.verifyPlausibleInstallation = verifyPlausibleInstallation