Skip to content

Commit

Permalink
app: move session provider, reset websocket on auth changes for security
Browse files Browse the repository at this point in the history
  • Loading branch information
kahkeng committed Jul 14, 2023
1 parent 8092384 commit e168a67
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 18 deletions.
24 changes: 20 additions & 4 deletions src/contexts/ChatContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import useWebSocket, { ReadyState } from 'react-use-websocket';
import { JsonValue } from 'react-use-websocket/dist/lib/types';
import { useRouter } from 'next/router';
import { getBackendWebsocketUrl } from '@/utils/backend';
import { useSession } from 'next-auth/react';

export type Message = {
messageId: string;
Expand Down Expand Up @@ -75,10 +76,15 @@ export const ChatContextProvider = ({ children }: { children: ReactNode }) => {

const [connectionStatus, setConnectionStatus] = useState<ReadyState>(ReadyState.UNINSTANTIATED);
const [lastInitSessionId, setLastInitSessionId] = useState<string | null>(null);
const [lastAuthStatus, setLastAuthStatus] = useState<string | null>(null);

const queryClient = useQueryClient();

const shouldConnect = true; // allow logged out to view public sessions
const { status } = useSession();
// shouldConnect allows logged out to view public sessions, but we want to
// enforce a disconnect and reconnect when the auth status changes, so
// we use the latest cookie state
const shouldConnect = status == lastAuthStatus;
const backendUrl = getBackendWebsocketUrl();
const {
sendJsonMessage: wsSendMessage,
Expand All @@ -104,18 +110,28 @@ export const ChatContextProvider = ({ children }: { children: ReactNode }) => {

useEffect(() => {
// re-initialize on change
if (status === "loading") {
return;
}
let needsReset = false;
if (status != lastAuthStatus) {
setLastAuthStatus(status);
needsReset = true;
}
if (sessionId != lastInitSessionId) {
// need to clear the messages when we switch chats
setLastInitSessionId(sessionId);
needsReset = true;
}
if (needsReset) {
setMessages([]);
setResumeFromMessageId(null);
setInsertBeforeMessageId(null);
wsSendMessage({ actor: 'system', type: 'clear', payload: {} });
if (sessionId) {
wsSendMessage({ actor: 'system', type: 'init', payload: { sessionId } });
}
setLastInitSessionId(sessionId);
}
}, [sessionId, wsSendMessage]); // note: don't add lastInitSessionId here
}, [status, sessionId, wsSendMessage]); // note: don't add lastAuthStatus, lastInitSessionId here

const onOpen = () => {
console.log(`Connected to backend: ${backendUrl}`);
Expand Down
6 changes: 1 addition & 5 deletions src/contexts/ConnectionWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import {
lightTheme,
} from '@rainbow-me/rainbowkit';
import axios from 'axios';
import { Session } from 'next-auth';
import { SessionProvider } from 'next-auth/react';
import { Chain, WagmiConfig, configureChains, createClient, useEnsAvatar } from 'wagmi';
import { goerli, zkSyncTestnet } from 'wagmi/chains';
import { jsonRpcProvider } from 'wagmi/providers/jsonRpc';
Expand All @@ -20,7 +18,7 @@ import { getBackendApiUrl } from '@/utils/backend';
import { GetSiweMessageOptions, RainbowKitSiweNextAuthProvider } from '@/utils/rainbowSIWEmod';
import SettingsContext from './SettingsContext';

const ConnectionWrapper = ({ children, pageProps, useSiwe = true }: any) => {
const ConnectionWrapper = ({ children, useSiwe = true }: any) => {
/* Use a fork url cached in the browser localStorage, else use the .env value */
const [forkUrl] = useCachedState(
'forkUrl',
Expand Down Expand Up @@ -110,7 +108,6 @@ const ConnectionWrapper = ({ children, pageProps, useSiwe = true }: any) => {

return (
<WagmiConfig client={wagmiClient}>
<SessionProvider refetchInterval={0} session={pageProps?.session}>
{useSiwe && (
<RainbowKitSiweNextAuthProvider
getCustomNonce={getCustomNonce}
Expand Down Expand Up @@ -146,7 +143,6 @@ const ConnectionWrapper = ({ children, pageProps, useSiwe = true }: any) => {
{children}
</RainbowKitProvider>
)}
</SessionProvider>
</WagmiConfig>
);
};
Expand Down
21 changes: 12 additions & 9 deletions src/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { CenterProvider } from '@center-inc/react';
import '@rainbow-me/rainbowkit/styles.css';
import { Session } from 'next-auth';
import Layout from '@/components/experimental_/layout/Layout';
import { SessionProvider } from 'next-auth/react';

/*
// disabled dynamic because this causes the query.id useEffect hook to fire twice
Expand Down Expand Up @@ -46,15 +47,17 @@ export default function App({
theme="light"
/>
<QueryClientProvider client={queryClient}>
<ChatContext>
<ConnectionWrapperDynamic session={session}>
<CenterProvider apiKey={process.env.NEXT_PUBLIC_CENTER_APP_KEY}>
<Layout>
<Component {...pageProps} />
</Layout>
</CenterProvider>
</ConnectionWrapperDynamic>
</ChatContext>
<SessionProvider refetchInterval={0} session={session}>
<ChatContext>
<ConnectionWrapperDynamic>
<CenterProvider apiKey={process.env.NEXT_PUBLIC_CENTER_APP_KEY}>
<Layout>
<Component {...pageProps} />
</Layout>
</CenterProvider>
</ConnectionWrapperDynamic>
</ChatContext>
</SessionProvider>
</QueryClientProvider>
</SettingsProvider>
);
Expand Down

0 comments on commit e168a67

Please sign in to comment.