Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, useSyncExternalStore,} from 'react'import {type AtpAgent, type AtpSessionEvent} from '@atproto/api'
import * as persisted from '#/state/persisted'import {useCloseAllActiveElements} from '#/state/util'import {useGlobalDialogsControlContext} from '#/components/dialogs/Context'import {AnalyticsContext, useAnalyticsBase, utils} from '#/analytics'import {IS_WEB} from '#/env'import {emitSessionDropped} from '../events'import { agentToSessionAccount, type BskyAppAgent, createAgentAndCreateAccount, createAgentAndLogin, createAgentAndResume, sessionAccountToSession,} from './agent'import { type OauthBskyAppAgent, oauthCreateAgent, oauthResumeSession,} from './oauth-agent'import {categorizeOauthError, setOauthTelemetrySink} from './oauth-telemetry'import {type Action, getInitialState, reducer, type State} from './reducer'export {isSignupQueued} from './util'import {addSessionDebugLog} from './logging'export type {SessionAccount} from '#/state/session/types'
import {clearPersistedQueryStorage} from '#/lib/persisted-query-storage'import { type SessionApiContext, type SessionStateContext,} from '#/state/session/types'import {useOnboardingDispatch} from '#/state/shell/onboarding'
const StateContext = createContext<SessionStateContext>({ accounts: [], currentAccount: undefined, hasSession: false,})StateContext.displayName = 'SessionStateContext'
const AgentContext = createContext<AtpAgent | null>(null)AgentContext.displayName = 'SessionAgentContext'
const ApiContext = createContext<SessionApiContext>({ createAccount: async () => {}, login: async () => {}, logoutCurrentAccount: () => {}, logoutEveryAccount: () => {}, resumeSession: async () => {}, removeAccount: () => {}, partialRefreshSession: async () => {},})ApiContext.displayName = 'SessionApiContext'
class SessionStore { private state: State private listeners = new Set<() => void>()
constructor() { // Careful: By the time this runs, `persisted` needs to already be filled. const initialState = getInitialState(persisted.get('session').accounts) addSessionDebugLog({type: 'reducer:init', state: initialState}) this.state = initialState }
getState = (): State => { return this.state }
subscribe = (listener: () => void) => { this.listeners.add(listener) return () => { this.listeners.delete(listener) } }
dispatch = (action: Action) => { const nextState = reducer(this.state, action) this.state = nextState // Persist synchronously without waiting for the React render cycle. if (nextState.needsPersist) { nextState.needsPersist = false const persistedData = { accounts: nextState.accounts, currentAccount: nextState.accounts.find( a => a.did === nextState.currentAgentState.did, ), } addSessionDebugLog({type: 'persisted:broadcast', data: persistedData}) void persisted.write('session', persistedData) } this.listeners.forEach(listener => listener()) }}
export function Provider({children}: React.PropsWithChildren<{}>) { const ax = useAnalyticsBase() const cancelPendingTask = useOneTaskAtATime() // eslint-disable-next-line react/hook-use-state const [store] = useState(() => new SessionStore()) const state = useSyncExternalStore(store.subscribe, store.getState) const onboardingDispatch = useOnboardingDispatch()
const onAgentSessionChange = useCallback( (agent: AtpAgent, accountDid: string, sessionEvent: AtpSessionEvent) => { const refreshedAccount = agentToSessionAccount(agent) // Mutable, so snapshot it right away. if (sessionEvent === 'expired' || sessionEvent === 'create-failed') { emitSessionDropped() } store.dispatch({ type: 'received-agent-event', agent, refreshedAccount, accountDid, sessionEvent, }) }, [store], )
const createAccount = useCallback<SessionApiContext['createAccount']>( async (params, metrics) => { addSessionDebugLog({type: 'method:start', method: 'createAccount'}) const signal = cancelPendingTask() ax.metric('account:create:begin', {}) const {agent, account} = await createAgentAndCreateAccount( params, onAgentSessionChange, )
// Remember which community this account was created in so the client can // resolve its brand deterministically (incl. communities sharing a PDS). if (params.communitySlug) { account.communitySlug = params.communitySlug }
if (signal.aborted) { return } store.dispatch({ type: 'switched-to-account', newAgent: agent, newAccount: account, }) ax.metric('account:create:success', metrics, { session: utils.accountToSessionMetadata(account), }) addSessionDebugLog({type: 'method:end', method: 'createAccount', account}) }, [ax, store, onAgentSessionChange, cancelPendingTask], )
const login = useCallback<SessionApiContext['login']>( async (params, logContext) => { addSessionDebugLog({type: 'method:start', method: 'login'}) const signal = cancelPendingTask()
let agentAccount: { agent: BskyAppAgent | OauthBskyAppAgent account: persisted.PersistedAccount } if (params.oauthSession) { agentAccount = await oauthCreateAgent(params.oauthSession) } else { agentAccount = await createAgentAndLogin(params, onAgentSessionChange) } const {agent, account} = agentAccount
if (signal.aborted) { return } store.dispatch({ type: 'switched-to-account', newAgent: agent, newAccount: account, }) ax.metric( 'account:loggedIn', {logContext, withPassword: !params.oauthSession}, {session: utils.accountToSessionMetadata(account)}, ) addSessionDebugLog({type: 'method:end', method: 'login', account}) }, [ax, store, onAgentSessionChange, cancelPendingTask], )
const logoutCurrentAccount = useCallback< SessionApiContext['logoutCurrentAccount'] >( logContext => { addSessionDebugLog({type: 'method:start', method: 'logout'}) cancelPendingTask() const prevState = store.getState() store.dispatch({ type: 'logged-out-current-account', }) ax.metric( 'account:loggedOut', {logContext, scope: 'current'}, { session: utils.accountToSessionMetadata( prevState.accounts.find( a => a.did === prevState.currentAgentState.did, ), ), }, ) addSessionDebugLog({type: 'method:end', method: 'logout'}) if (prevState.currentAgentState.did) { void clearPersistedQueryStorage(prevState.currentAgentState.did) } // reset onboarding flow on logout onboardingDispatch({type: 'skip'}) }, [ax, store, cancelPendingTask, onboardingDispatch], )
const logoutEveryAccount = useCallback< SessionApiContext['logoutEveryAccount'] >( logContext => { addSessionDebugLog({type: 'method:start', method: 'logout'}) cancelPendingTask() const prevState = store.getState() store.dispatch({ type: 'logged-out-every-account', }) ax.metric( 'account:loggedOut', {logContext, scope: 'every'}, { session: utils.accountToSessionMetadata( prevState.accounts.find( a => a.did === prevState.currentAgentState.did, ), ), }, ) addSessionDebugLog({type: 'method:end', method: 'logout'}) for (const account of prevState.accounts) { void clearPersistedQueryStorage(account.did) } // reset onboarding flow on logout onboardingDispatch({type: 'skip'}) }, [store, cancelPendingTask, onboardingDispatch, ax], )
const resumeSession = useCallback<SessionApiContext['resumeSession']>( async (storedAccount, isSwitchingAccounts = false) => { addSessionDebugLog({ type: 'method:start', method: 'resumeSession', account: storedAccount, }) const signal = cancelPendingTask()
let agentAccount: { agent: BskyAppAgent | OauthBskyAppAgent account: persisted.PersistedAccount } if (storedAccount.isOauthSession) { try { agentAccount = await oauthResumeSession(storedAccount) } catch (e) { ax.metric('oauth:sessionResumeFailed', { logContext: isSwitchingAccounts ? 'SwitchAccount' : 'AppBoot', errorCategory: categorizeOauthError(e), message: (e instanceof Error ? e.message : String(e)).slice(0, 200), }) throw e } } else { agentAccount = await createAgentAndResume( storedAccount, onAgentSessionChange, ) } const {agent, account} = agentAccount
if (signal.aborted) { return } store.dispatch({ type: 'switched-to-account', newAgent: agent, newAccount: account, }) addSessionDebugLog({type: 'method:end', method: 'resumeSession', account}) if (isSwitchingAccounts) { // reset onboarding flow on switch account onboardingDispatch({type: 'skip'}) } }, [store, onAgentSessionChange, cancelPendingTask, onboardingDispatch], )
const partialRefreshSession = useCallback< SessionApiContext['partialRefreshSession'] >(async () => { const agent = state.currentAgentState.agent as BskyAppAgent const signal = cancelPendingTask() const {data} = await agent.com.atproto.server.getSession() if (signal.aborted) return store.dispatch({ type: 'partial-refresh-session', accountDid: agent.session!.did, patch: { emailConfirmed: data.emailConfirmed, emailAuthFactor: data.emailAuthFactor, active: data.active, status: data.status, }, }) }, [store, state, cancelPendingTask])
const removeAccount = useCallback<SessionApiContext['removeAccount']>( account => { addSessionDebugLog({ type: 'method:start', method: 'removeAccount', account, }) cancelPendingTask() store.dispatch({ type: 'removed-account', accountDid: account.did, }) addSessionDebugLog({type: 'method:end', method: 'removeAccount', account}) }, [store, cancelPendingTask], ) useEffect(() => { setOauthTelemetrySink(event => { ax.metric(event.type, event.payload) }) return () => setOauthTelemetrySink(null) }, [ax])
useEffect(() => { return persisted.onUpdate('session', nextSession => { const synced = nextSession addSessionDebugLog({type: 'persisted:receive', data: synced}) store.dispatch({ type: 'synced-accounts', syncedAccounts: synced.accounts, syncedCurrentDid: synced.currentAccount?.did, }) const syncedAccount = synced.accounts.find( a => a.did === synced.currentAccount?.did, ) if (syncedAccount && syncedAccount.refreshJwt) { if (syncedAccount.did !== state.currentAgentState.did) { /* * Web handling: if leader tab has switched to a diff account that is * stale, it will refresh the session before triggering the update to * follower tabs. Follower tabs will therefore receive the fresh * session. See APP-1960, or ask Eric. */ void resumeSession(syncedAccount) } else { const agent = state.currentAgentState.agent as AtpAgent const prevSession = agent.session // eslint-disable-next-line react-compiler/react-compiler agent.sessionManager.session = sessionAccountToSession(syncedAccount) addSessionDebugLog({ type: 'agent:patch', agent, prevSession, nextSession: agent.session, }) } } }) }, [store, state, resumeSession])
const stateContext = useMemo( () => ({ accounts: state.accounts, currentAccount: state.accounts.find( a => a.did === state.currentAgentState.did, ), hasSession: !!state.currentAgentState.did, }), [state], )
const api = useMemo( () => ({ createAccount, login, logoutCurrentAccount, logoutEveryAccount, resumeSession, removeAccount, partialRefreshSession, }), [ createAccount, login, logoutCurrentAccount, logoutEveryAccount, resumeSession, removeAccount, partialRefreshSession, ], )
// @ts-expect-error window type is not declared, debug only // eslint-disable-next-line react-hooks/immutability if (__DEV__ && IS_WEB) window.agent = state.currentAgentState.agent
const agent = state.currentAgentState.agent as BskyAppAgent const currentAgentRef = useRef(agent) useEffect(() => { if (currentAgentRef.current !== agent) { // Read the previous value and immediately advance the pointer. const prevAgent = currentAgentRef.current currentAgentRef.current = agent addSessionDebugLog({type: 'agent:switch', prevAgent, nextAgent: agent}) // We never reuse agents so let's fully neutralize the previous one. // This ensures it won't try to consume any refresh tokens. prevAgent.dispose() } }, [agent])
return ( <AgentContext.Provider value={agent}> <StateContext.Provider value={stateContext}> <ApiContext.Provider value={api}> <AnalyticsContext metadata={utils.useMeta({ session: utils.accountToSessionMetadata( stateContext.currentAccount, ), })}> {children} </AnalyticsContext> </ApiContext.Provider> </StateContext.Provider> </AgentContext.Provider> )}
function useOneTaskAtATime() { const abortController = useRef<AbortController | null>(null) const cancelPendingTask = useCallback(() => { if (abortController.current) { abortController.current.abort() } abortController.current = new AbortController() return abortController.current.signal }, []) return cancelPendingTask}
export function useSession() { return useContext(StateContext)}
export function useSessionApi() { return useContext(ApiContext)}
export function useRequireAuth() { const {hasSession} = useSession() const closeAll = useCloseAllActiveElements() const {signinDialogControl} = useGlobalDialogsControlContext()
return useCallback( (fn: () => unknown) => { if (hasSession) { fn() } else { closeAll() signinDialogControl.open() } }, [hasSession, signinDialogControl, closeAll], )}
export function useAgent(): AtpAgent { const agent = useContext(AgentContext) if (!agent) { throw Error('useAgent() must be below <SessionProvider>.') } return agent}