amplitude/Amplitude-TypeScript

Browser SDK cannot handle url-encoded cookie values

jeremyallison opened this issue · 1 comments

Expected Behavior

  1. Backend sets a cookie value (new format, AMP_xxxxxx). Cookie is returned to browser via a Set-Cookie response header.
  2. Frontend browser SDK parses existing cookie, uses deviceId already set by the backend, and uses it ✅

Current Behavior

  1. Backend sets cookie value (new format, AMP_xxxxxx). Cookie is returned to browser via a Set-Cookie response header.
  2. Frontend browser SDK fails to parse existing cookie, as its value is URL encoded. ❌

Possible Solution

Call decodeURIcomponent on cookie value before atob when parsing Amplitude cookie

Steps to Reproduce

Broken flow:

  1. Manually set an Amplitude cookie in your browser, with an URL encoded value (as my Rails backend would) , for example AMP_1310df2f88=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJkZDU1YjIxNC0yNmY1LTQ5OTAtYjFiZi0zNTkzYTIxOTJlNDIlMjIlN0Q%3D
    (JSON value would equal {"deviceId":"dd55b214-26f5-4990-b1bf-3593a2192e42"})

  2. Initialize browser SDK and let it parse this cookie

  3. Inspect cookie set by browser SDK, decode its value : {"deviceId":"72ac8556-1535-4fb2-bce4-f844bdb1d6cc","sessionId":xxxxx,"optOut":false,"lastEventTime":1234,"lastEventId":5}
    deviceId does not match. The JS SDK has ignored the backend cookie and set its own deviceId

Fixed flow, proves what is broken:

  1. Manually set an Amplitude cookie in your browser, with a value that has not been URL encoded, for example AMP_1310df2f88=JTdCJTIyZGV2aWNlSWQlMjIlM0ElMjJkZDU1YjIxNC0yNmY1LTQ5OTAtYjFiZi0zNTkzYTIxOTJlNDIlMjIlN0Q= <-- ⚠️ notice the = is not encoded into %3D here
    (JSON value would equal {"deviceId":"dd55b214-26f5-4990-b1bf-3593a2192e42"})

  2. Initialize browser SDK and let it parse this cookie

  3. Inspect cookie set by browser SDK, decode its value : {"deviceId":"dd55b214-26f5-4990-b1bf-3593a2192e42","sessionId":xxxxx,"optOut":false,"lastEventTime":1234,"lastEventId":5}
    deviceId is now the proper value we set initially, found at step 1. The JS SDK has taken the initial cookie into account and re-used the existing deviceId

Environment

  • JS SDK Version: 2.4.1
  • Installation Method: yarn
  • Browser and Version: Chrome 121.0.6167.139

Please see #686 (comment) for more details.