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

fix: Session storage access throws when disabled #318

Merged
merged 2 commits into from
Nov 17, 2022
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
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
}
}