1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
|
import React from 'react'
import {AtpSessionEvent, BskyAgent} from '@atproto/api'
import {track} from '#/lib/analytics/analytics'
import {networkRetry} from '#/lib/async/retry'
import {PUBLIC_BSKY_SERVICE} from '#/lib/constants'
import {logEvent, tryFetchGates} from '#/lib/statsig/statsig'
import {isWeb} from '#/platform/detection'
import * as persisted from '#/state/persisted'
import {useCloseAllActiveElements} from '#/state/util'
import {useGlobalDialogsControlContext} from '#/components/dialogs/Context'
import {IS_DEV} from '#/env'
import {emitSessionDropped} from '../events'
import {
agentToSessionAccount,
configureModerationForAccount,
configureModerationForGuest,
createAgentAndCreateAccount,
createAgentAndLogin,
isSessionDeactivated,
isSessionExpired,
} from './util'
export type {SessionAccount} from '#/state/session/types'
import {
SessionAccount,
SessionApiContext,
SessionStateContext,
} from '#/state/session/types'
export {isSessionDeactivated}
const StateContext = React.createContext<SessionStateContext>({
accounts: [],
currentAccount: undefined,
hasSession: false,
})
const AgentContext = React.createContext<BskyAgent | null>(null)
const ApiContext = React.createContext<SessionApiContext>({
createAccount: async () => {},
login: async () => {},
logout: async () => {},
initSession: async () => {},
removeAccount: () => {},
updateCurrentAccount: () => {},
})
type AgentState = {
readonly agent: BskyAgent
readonly did: string | undefined
}
type State = {
accounts: SessionStateContext['accounts']
currentAgentState: AgentState
needsPersist: boolean
}
type Action =
| {
type: 'received-agent-event'
agent: BskyAgent
accountDid: string
refreshedAccount: SessionAccount | undefined
sessionEvent: AtpSessionEvent
}
| {
type: 'switched-to-account'
newAgent: BskyAgent
newAccount: SessionAccount
}
| {
type: 'updated-current-account'
updatedFields: Partial<
Pick<
SessionAccount,
'handle' | 'email' | 'emailConfirmed' | 'emailAuthFactor'
>
>
}
| {
type: 'removed-account'
accountDid: string
}
| {
type: 'logged-out'
}
| {
type: 'synced-accounts'
syncedAccounts: SessionAccount[]
syncedCurrentDid: string | undefined
}
function createPublicAgentState() {
configureModerationForGuest() // Side effect but only relevant for tests
return {
agent: new BskyAgent({service: PUBLIC_BSKY_SERVICE}),
did: undefined,
}
}
function getInitialState(): State {
return {
accounts: persisted.get('session').accounts,
currentAgentState: createPublicAgentState(),
needsPersist: false,
}
}
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'received-agent-event': {
const {agent, accountDid, refreshedAccount, sessionEvent} = action
if (agent !== state.currentAgentState.agent) {
// Only consider events from the active agent.
return state
}
if (sessionEvent === 'network-error') {
// Don't change stored accounts but kick to the choose account screen.
return {
accounts: state.accounts,
currentAgentState: createPublicAgentState(),
needsPersist: true,
}
}
const existingAccount = state.accounts.find(a => a.did === accountDid)
if (
!existingAccount ||
JSON.stringify(existingAccount) === JSON.stringify(refreshedAccount)
) {
// Fast path without a state update.
return state
}
return {
accounts: state.accounts.map(a => {
if (a.did === accountDid) {
if (refreshedAccount) {
return refreshedAccount
} else {
return {
...a,
// If we didn't receive a refreshed account, clear out the tokens.
accessJwt: undefined,
refreshJwt: undefined,
}
}
} else {
return a
}
}),
currentAgentState: refreshedAccount
? state.currentAgentState
: createPublicAgentState(), // Log out if expired.
needsPersist: true,
}
}
case 'switched-to-account': {
const {newAccount, newAgent} = action
return {
accounts: [
newAccount,
...state.accounts.filter(a => a.did !== newAccount.did),
],
currentAgentState: {
did: newAccount.did,
agent: newAgent,
},
needsPersist: true,
}
}
case 'updated-current-account': {
const {updatedFields} = action
return {
accounts: state.accounts.map(a => {
if (a.did === state.currentAgentState.did) {
return {
...a,
...updatedFields,
}
} else {
return a
}
}),
currentAgentState: state.currentAgentState,
needsPersist: true,
}
}
case 'removed-account': {
const {accountDid} = action
return {
accounts: state.accounts.filter(a => a.did !== accountDid),
currentAgentState:
state.currentAgentState.did === accountDid
? createPublicAgentState() // Log out if removing the current one.
: state.currentAgentState,
needsPersist: true,
}
}
case 'logged-out': {
return {
accounts: state.accounts.map(a => ({
...a,
// Clear tokens for *every* account (this is a hard logout).
refreshJwt: undefined,
accessJwt: undefined,
})),
currentAgentState: createPublicAgentState(),
needsPersist: true,
}
}
case 'synced-accounts': {
const {syncedAccounts, syncedCurrentDid} = action
return {
accounts: syncedAccounts,
currentAgentState:
syncedCurrentDid === state.currentAgentState.did
? state.currentAgentState
: createPublicAgentState(), // Log out if different user.
needsPersist: false, // Synced from another tab. Don't persist to avoid cycles.
}
}
}
}
export function Provider({children}: React.PropsWithChildren<{}>) {
const [state, dispatch] = React.useReducer(reducer, null, getInitialState)
const onAgentSessionChange = React.useCallback(
(agent: BskyAgent, accountDid: string, sessionEvent: AtpSessionEvent) => {
const refreshedAccount = agentToSessionAccount(agent) // Mutable, so snapshot it right away.
if (sessionEvent === 'expired' || sessionEvent === 'create-failed') {
emitSessionDropped()
}
dispatch({
type: 'received-agent-event',
agent,
refreshedAccount,
accountDid,
sessionEvent,
})
},
[],
)
const createAccount = React.useCallback<SessionApiContext['createAccount']>(
async ({
service,
email,
password,
handle,
birthDate,
inviteCode,
verificationPhone,
verificationCode,
}) => {
track('Try Create Account')
logEvent('account:create:begin', {})
const {agent, account, fetchingGates} = await createAgentAndCreateAccount(
{
service,
email,
password,
handle,
birthDate,
inviteCode,
verificationPhone,
verificationCode,
},
)
agent.setPersistSessionHandler(event => {
onAgentSessionChange(agent, account.did, event)
})
await fetchingGates
dispatch({
type: 'switched-to-account',
newAgent: agent,
newAccount: account,
})
track('Create Account')
logEvent('account:create:success', {})
},
[onAgentSessionChange],
)
const login = React.useCallback<SessionApiContext['login']>(
async ({service, identifier, password, authFactorToken}, logContext) => {
const {agent, account, fetchingGates} = await createAgentAndLogin({
service,
identifier,
password,
authFactorToken,
})
agent.setPersistSessionHandler(event => {
onAgentSessionChange(agent, account.did, event)
})
await fetchingGates
dispatch({
type: 'switched-to-account',
newAgent: agent,
newAccount: account,
})
track('Sign In', {resumedSession: false})
logEvent('account:loggedIn', {logContext, withPassword: true})
},
[onAgentSessionChange],
)
const logout = React.useCallback<SessionApiContext['logout']>(
async logContext => {
dispatch({
type: 'logged-out',
})
logEvent('account:loggedOut', {logContext})
},
[],
)
const initSession = React.useCallback<SessionApiContext['initSession']>(
async account => {
const fetchingGates = tryFetchGates(account.did, 'prefer-low-latency')
const agent = new BskyAgent({service: account.service})
// restore the correct PDS URL if available
if (account.pdsUrl) {
agent.pdsUrl = agent.api.xrpc.uri = new URL(account.pdsUrl)
}
agent.setPersistSessionHandler(event => {
onAgentSessionChange(agent, account.did, event)
})
await configureModerationForAccount(agent, account)
const prevSession = {
accessJwt: account.accessJwt ?? '',
refreshJwt: account.refreshJwt ?? '',
did: account.did,
handle: account.handle,
}
if (isSessionExpired(account)) {
const freshAccount = await resumeSessionWithFreshAccount()
await fetchingGates
dispatch({
type: 'switched-to-account',
newAgent: agent,
newAccount: freshAccount,
})
} else {
agent.session = prevSession
await fetchingGates
dispatch({
type: 'switched-to-account',
newAgent: agent,
newAccount: account,
})
if (isSessionDeactivated(account.accessJwt) || account.deactivated) {
// don't attempt to resume
// use will be taken to the deactivated screen
return
}
// Intentionally not awaited to unblock the UI:
resumeSessionWithFreshAccount()
}
async function resumeSessionWithFreshAccount(): Promise<SessionAccount> {
await networkRetry(1, () => agent.resumeSession(prevSession))
const sessionAccount = agentToSessionAccount(agent)
/*
* If `agent.resumeSession` fails above, it'll throw. This is just to
* make TypeScript happy.
*/
if (!sessionAccount) {
throw new Error(`session: initSession failed to establish a session`)
}
return sessionAccount
}
},
[onAgentSessionChange],
)
const removeAccount = React.useCallback<SessionApiContext['removeAccount']>(
account => {
dispatch({
type: 'removed-account',
accountDid: account.did,
})
},
[],
)
const updateCurrentAccount = React.useCallback<
SessionApiContext['updateCurrentAccount']
>(account => {
dispatch({
type: 'updated-current-account',
updatedFields: account,
})
}, [])
React.useEffect(() => {
if (state.needsPersist) {
state.needsPersist = false
persisted.write('session', {
accounts: state.accounts,
currentAccount: state.accounts.find(
a => a.did === state.currentAgentState.did,
),
})
}
}, [state])
React.useEffect(() => {
return persisted.onUpdate(() => {
const synced = persisted.get('session')
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) {
initSession(syncedAccount)
} else {
// @ts-ignore we checked for `refreshJwt` above
state.currentAgentState.agent.session = syncedAccount
}
}
})
}, [state, initSession])
const stateContext = React.useMemo(
() => ({
accounts: state.accounts,
currentAccount: state.accounts.find(
a => a.did === state.currentAgentState.did,
),
hasSession: !!state.currentAgentState.did,
}),
[state],
)
const api = React.useMemo(
() => ({
createAccount,
login,
logout,
initSession,
removeAccount,
updateCurrentAccount,
}),
[
createAccount,
login,
logout,
initSession,
removeAccount,
updateCurrentAccount,
],
)
// @ts-ignore
if (IS_DEV && isWeb) window.agent = state.currentAgentState.agent
return (
<AgentContext.Provider value={state.currentAgentState.agent}>
<StateContext.Provider value={stateContext}>
<ApiContext.Provider value={api}>{children}</ApiContext.Provider>
</StateContext.Provider>
</AgentContext.Provider>
)
}
export function useSession() {
return React.useContext(StateContext)
}
export function useSessionApi() {
return React.useContext(ApiContext)
}
export function useRequireAuth() {
const {hasSession} = useSession()
const closeAll = useCloseAllActiveElements()
const {signinDialogControl} = useGlobalDialogsControlContext()
return React.useCallback(
(fn: () => void) => {
if (hasSession) {
fn()
} else {
closeAll()
signinDialogControl.open()
}
},
[hasSession, signinDialogControl, closeAll],
)
}
export function useAgent(): {getAgent: () => BskyAgent} {
const agent = React.useContext(AgentContext)
if (!agent) {
throw Error('useAgent() must be below <SessionProvider>.')
}
return React.useMemo(
() => ({
getAgent() {
return agent
},
}),
[agent],
)
}
|