Skip to content
This repository has been archived by the owner on Aug 30, 2023. It is now read-only.

Commit

Permalink
fix: Session storage access throws when disabled (#318)
Browse files Browse the repository at this point in the history
sessionStorage access can throw when it (or cookies) are
disabled. Ensure that all API accesses to Session Storage
are doneso safely.

Fixes #316
  • Loading branch information
billyvg authored Nov 17, 2022
1 parent be72954 commit 76d1df3
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 8 deletions.
21 changes: 20 additions & 1 deletion src/session/fetchSession.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import { afterEach, beforeAll, expect, it } from '@jest/globals';
import { afterEach, beforeAll, expect, it, jest } from '@jest/globals';

import { REPLAY_SESSION_KEY } from './constants';
import { fetchSession } from './fetchSession';

const oldSessionStorage = window.sessionStorage;

beforeAll(() => {
window.sessionStorage.clear();
});

afterEach(() => {
Object.defineProperty(window, 'sessionStorage', {
writable: true,
value: oldSessionStorage,
});
window.sessionStorage.clear();
});

Expand Down Expand Up @@ -43,3 +49,16 @@ it('fetches an invalid session', function () {

expect(fetchSession(SAMPLE_RATES)).toBe(null);
});

it('safely attempts to fetch session when Session Storage is disabled', function () {
Object.defineProperty(window, 'sessionStorage', {
writable: true,
value: {
getItem: () => {
throw new Error('No Session Storage for you');
},
},
});

expect(fetchSession(SAMPLE_RATES)).toEqual(null);
});
13 changes: 7 additions & 6 deletions src/session/fetchSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ export function fetchSession({
return null;
}

const sessionStringFromStorage =
window.sessionStorage.getItem(REPLAY_SESSION_KEY);
try {
// This can throw if cookies are disabled
const sessionStringFromStorage =
window.sessionStorage.getItem(REPLAY_SESSION_KEY);

if (!sessionStringFromStorage) {
return null;
}
if (!sessionStringFromStorage) {
return null;
}

try {
const sessionObj = JSON.parse(sessionStringFromStorage);

return new Session(
Expand Down
2 changes: 1 addition & 1 deletion src/session/saveSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ export function saveSession(session: Session) {
try {
window.sessionStorage.setItem(REPLAY_SESSION_KEY, JSON.stringify(session));
} catch {
// this shouldn't happen
// Ignore potential SecurityError exceptions
}
}

0 comments on commit 76d1df3

Please sign in to comment.