Clear sessionStorage on 403 and retry with fresh visitor
When SECRET_ANALYTICS changes (deploy), old uid/hash become invalid. On 403, clear session and auto-retry with a new visitor creation. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -34,6 +34,11 @@ async function decrypt(b64) {
|
||||
}
|
||||
}
|
||||
|
||||
function clearSession() {
|
||||
sessionStorage.removeItem(SK_UID)
|
||||
sessionStorage.removeItem(SK_HASH)
|
||||
}
|
||||
|
||||
async function send(data, expectResponse = false) {
|
||||
const d = await encrypt(data)
|
||||
if (!d) return null
|
||||
@@ -48,6 +53,10 @@ async function send(data, expectResponse = false) {
|
||||
body: JSON.stringify({ d }),
|
||||
keepalive: true,
|
||||
})
|
||||
if (res.status === 403) {
|
||||
clearSession()
|
||||
return null
|
||||
}
|
||||
if (!res.ok || res.status === 204) return null
|
||||
const json = await res.json()
|
||||
return json.d ? await decrypt(json.d) : null
|
||||
@@ -96,11 +105,18 @@ export async function initAnalytics() {
|
||||
return
|
||||
}
|
||||
|
||||
const visitor = await getOrCreateVisitor()
|
||||
let visitor = await getOrCreateVisitor()
|
||||
if (!visitor) return
|
||||
|
||||
await trackPageView(visitor)
|
||||
|
||||
// If trackPageView got 403 (stale session), retry with fresh visitor
|
||||
if (!sessionStorage.getItem(SK_UID)) {
|
||||
visitor = await getOrCreateVisitor()
|
||||
if (!visitor) return
|
||||
await trackPageView(visitor)
|
||||
}
|
||||
|
||||
const authUserId = document.body.dataset.uid
|
||||
if (authUserId) {
|
||||
await setAuth(parseInt(authUserId, 10))
|
||||
|
||||
Reference in New Issue
Block a user