Skip to content

Commit

Permalink
cross origin refresh session
Browse files Browse the repository at this point in the history
  • Loading branch information
a-type committed Mar 26, 2024
1 parent 7d12126 commit bd032ec
Show file tree
Hide file tree
Showing 4 changed files with 79 additions and 15 deletions.
42 changes: 41 additions & 1 deletion packages/client/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const refreshTokenStorage = {

export async function refreshSession(apiOrigin: string) {
const refreshToken = refreshTokenStorage.get();
if (!refreshToken) return false;
if (!refreshToken) return refreshSessionViaIframe();
try {
const response = await fetch(`${apiOrigin}/auth/refresh`, {
method: 'POST',
Expand All @@ -77,6 +77,46 @@ export async function refreshSession(apiOrigin: string) {
}
}

async function refreshSessionViaIframe() {
let iframe: HTMLIFrameElement | null = null;
try {
return await new Promise<void>((resolve, reject) => {
const iframeUrl = `${import.meta.env.VITE_HOME_ORIGIN}/refresh-session`;
// go ahead and subscribe to postMessage events
window.addEventListener('message', (event) => {
if (event.data.type === 'refresh-session') {
if (event.data.success) {
console.debug('refreshed session via iframe');
// store the new refresh token
refreshTokenStorage.set(event.data.success.refreshToken);
resolve();
}
}
});
iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = iframeUrl;
iframe.addEventListener('load', () => {
console.debug('iframe loaded');
});
iframe.addEventListener('error', (ev) => {
console.error('iframe failed to load', ev.error);
reject(ev.error);
});
document.body.appendChild(iframe);

// failure case: if the iframe doesn't load, reject
setTimeout(() => {
reject(new Error('iframe-based session refresh timed out'));
}, 5000);
});
} finally {
if (iframe) {
document.body.removeChild(iframe);
}
}
}

async function peekAtResponseBody(response: Response): Promise<{
body: any;
clone: Response;
Expand Down
26 changes: 12 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions web/src/pages/RefreshSessionPage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useMe } from '@biscuits/client';
import { useEffect } from 'react';

/**
* A stub page that just calls an API request. This will automatically trigger session
* refresh if the user is logged in. This page is rendered in an iframe by other apps
* on other origins to transparently keep the session alive without having to know
* the refresh token, which is stored in this app's origin localStorage.
*/
export function RefreshSessionPage() {
const [data] = useMe();
const success = data.data?.me;
useEffect(() => {
if (window.top) {
window.top.postMessage({ type: 'refresh-session', success }, '*');
}
}, [success]);
return null;
}

export default RefreshSessionPage;
5 changes: 5 additions & 0 deletions web/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { TopLoader } from '@/components/nav/TopLoader.jsx';
import { Outlet, Router, makeRoutes } from '@verdant-web/react-router';
import { Suspense, lazy } from 'react';
import LoginPage from './LoginPage.jsx';
import RefreshSessionPage from './RefreshSessionPage.jsx';
const HomePage = lazy(() => import('./HomePage.js'));

const routes = makeRoutes([
Expand Down Expand Up @@ -30,6 +31,10 @@ const routes = makeRoutes([
path: '/invite/:code',
component: lazy(() => import('./ClaimInvitePage.js')),
},
{
path: '/refresh-session',
component: RefreshSessionPage,
},
]);

export function Pages() {
Expand Down

0 comments on commit bd032ec

Please sign in to comment.