about summary refs log tree commit diff
path: root/src/state/models/session.ts
blob: c3653760195882a357cb03becb85cd736bfb7bfc (plain) (blame)
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
import {makeAutoObservable, runInAction} from 'mobx'
import {
  BskyAgent,
  AtpSessionEvent,
  AtpSessionData,
  ComAtprotoServerDescribeServer as DescribeServer,
} from '@atproto/api'
import normalizeUrl from 'normalize-url'
import {isObj, hasProp} from 'lib/type-guards'
import {networkRetry} from 'lib/async/retry'
import {z} from 'zod'
import {RootStoreModel} from './root-store'

export type ServiceDescription = DescribeServer.OutputSchema

export const activeSession = z.object({
  service: z.string(),
  did: z.string(),
})
export type ActiveSession = z.infer<typeof activeSession>

export const accountData = z.object({
  service: z.string(),
  refreshJwt: z.string().optional(),
  accessJwt: z.string().optional(),
  handle: z.string(),
  did: z.string(),
  email: z.string().optional(),
  displayName: z.string().optional(),
  aviUrl: z.string().optional(),
})
export type AccountData = z.infer<typeof accountData>

interface AdditionalAccountData {
  displayName?: string
  aviUrl?: string
}

export class SessionModel {
  // DEBUG
  // emergency log facility to help us track down this logout issue
  // remove when resolved
  // -prf
  _log(message: string, details?: Record<string, any>) {
    details = details || {}
    details.state = {
      data: this.data,
      accounts: this.accounts.map(
        a =>
          `${!!a.accessJwt && !!a.refreshJwt ? '✅' : '❌'} ${a.handle} (${
            a.service
          })`,
      ),
      isResumingSession: this.isResumingSession,
    }
    this.rootStore.log.debug(message, details)
  }

  /**
   * Currently-active session
   */
  data: ActiveSession | null = null
  /**
   * A listing of the currently & previous sessions
   */
  accounts: AccountData[] = []
  /**
   * Flag to indicate if we're doing our initial-load session resumption
   */
  isResumingSession = false

  constructor(public rootStore: RootStoreModel) {
    makeAutoObservable(this, {
      rootStore: false,
      serialize: false,
      hydrate: false,
      hasSession: false,
    })
  }

  get currentSession() {
    if (!this.data) {
      return undefined
    }
    const {did, service} = this.data
    return this.accounts.find(
      account =>
        normalizeUrl(account.service) === normalizeUrl(service) &&
        account.did === did &&
        !!account.accessJwt &&
        !!account.refreshJwt,
    )
  }

  get hasSession() {
    return !!this.currentSession && !!this.rootStore.agent.session
  }

  get hasAccounts() {
    return this.accounts.length >= 1
  }

  get switchableAccounts() {
    return this.accounts.filter(acct => acct.did !== this.data?.did)
  }

  serialize(): unknown {
    return {
      data: this.data,
      accounts: this.accounts,
    }
  }

  hydrate(v: unknown) {
    this.accounts = []
    if (isObj(v)) {
      if (hasProp(v, 'data') && activeSession.safeParse(v.data)) {
        this.data = v.data as ActiveSession
      }
      if (hasProp(v, 'accounts') && Array.isArray(v.accounts)) {
        for (const account of v.accounts) {
          if (accountData.safeParse(account)) {
            this.accounts.push(account as AccountData)
          }
        }
      }
    }
  }

  clear() {
    this.data = null
  }

  /**
   * Attempts to resume the previous session loaded from storage
   */
  async attemptSessionResumption() {
    const sess = this.currentSession
    if (sess) {
      this._log('SessionModel:attemptSessionResumption found stored session')
      this.isResumingSession = true
      try {
        return await this.resumeSession(sess)
      } finally {
        runInAction(() => {
          this.isResumingSession = false
        })
      }
    } else {
      this._log(
        'SessionModel:attemptSessionResumption has no session to resume',
      )
    }
  }

  /**
   * Sets the active session
   */
  async setActiveSession(agent: BskyAgent, did: string) {
    this._log('SessionModel:setActiveSession')
    const hadSession = !!this.data
    this.data = {
      service: agent.service.toString(),
      did,
    }
    await this.rootStore.handleSessionChange(agent, {hadSession})
  }

  /**
   * Upserts a session into the accounts
   */
  persistSession(
    service: string,
    did: string,
    event: AtpSessionEvent,
    session?: AtpSessionData,
    addedInfo?: AdditionalAccountData,
  ) {
    this._log('SessionModel:persistSession', {
      service,
      did,
      event,
      hasSession: !!session,
    })

    const existingAccount = this.accounts.find(
      account => account.service === service && account.did === did,
    )

    // fall back to any pre-existing access tokens
    let refreshJwt = session?.refreshJwt || existingAccount?.refreshJwt
    let accessJwt = session?.accessJwt || existingAccount?.accessJwt
    if (event === 'expired') {
      // only clear the tokens when they're known to have expired
      refreshJwt = undefined
      accessJwt = undefined
    }

    const newAccount = {
      service,
      did,
      refreshJwt,
      accessJwt,

      handle: session?.handle || existingAccount?.handle || '',
      email: session?.email || existingAccount?.email || '',
      displayName: addedInfo
        ? addedInfo.displayName
        : existingAccount?.displayName || '',
      aviUrl: addedInfo ? addedInfo.aviUrl : existingAccount?.aviUrl || '',
    }
    if (!existingAccount) {
      this.accounts.push(newAccount)
    } else {
      this.accounts = [
        newAccount,
        ...this.accounts.filter(
          account => !(account.service === service && account.did === did),
        ),
      ]
    }

    // if the session expired, fire an event to let the user know
    if (event === 'expired') {
      this.rootStore.handleSessionDrop()
    }
  }

  /**
   * Clears any session tokens from the accounts; used on logout.
   */
  clearSessionTokens() {
    this._log('SessionModel:clearSessionTokens')
    this.accounts = this.accounts.map(acct => ({
      service: acct.service,
      handle: acct.handle,
      did: acct.did,
      displayName: acct.displayName,
      aviUrl: acct.aviUrl,
    }))
  }

  /**
   * Fetches additional information about an account on load.
   */
  async loadAccountInfo(agent: BskyAgent, did: string) {
    const res = await agent.getProfile({actor: did}).catch(_e => undefined)
    if (res) {
      return {
        dispayName: res.data.displayName,
        aviUrl: res.data.avatar,
      }
    }
  }

  /**
   * Helper to fetch the accounts config settings from an account.
   */
  async describeService(service: string): Promise<ServiceDescription> {
    const agent = new BskyAgent({service})
    const res = await agent.com.atproto.server.describeServer({})
    return res.data
  }

  /**
   * Attempt to resume a session that we still have access tokens for.
   */
  async resumeSession(account: AccountData): Promise<boolean> {
    this._log('SessionModel:resumeSession')
    if (!(account.accessJwt && account.refreshJwt && account.service)) {
      this._log(
        'SessionModel:resumeSession aborted due to lack of access tokens',
      )
      return false
    }

    const agent = new BskyAgent({
      service: account.service,
      persistSession: (evt: AtpSessionEvent, sess?: AtpSessionData) => {
        this.persistSession(account.service, account.did, evt, sess)
      },
    })

    try {
      await networkRetry(3, () =>
        agent.resumeSession({
          accessJwt: account.accessJwt || '',
          refreshJwt: account.refreshJwt || '',
          did: account.did,
          handle: account.handle,
        }),
      )
      const addedInfo = await this.loadAccountInfo(agent, account.did)
      this.persistSession(
        account.service,
        account.did,
        'create',
        agent.session,
        addedInfo,
      )
      this._log('SessionModel:resumeSession succeeded')
    } catch (e: any) {
      this._log('SessionModel:resumeSession failed', {
        error: e.toString(),
      })
      return false
    }

    await this.setActiveSession(agent, account.did)
    return true
  }

  /**
   * Create a new session.
   */
  async login({
    service,
    identifier,
    password,
  }: {
    service: string
    identifier: string
    password: string
  }) {
    this._log('SessionModel:login')
    const agent = new BskyAgent({service})
    await agent.login({identifier, password})
    if (!agent.session) {
      throw new Error('Failed to establish session')
    }

    const did = agent.session.did
    const addedInfo = await this.loadAccountInfo(agent, did)

    this.persistSession(service, did, 'create', agent.session, addedInfo)
    agent.setPersistSessionHandler(
      (evt: AtpSessionEvent, sess?: AtpSessionData) => {
        this.persistSession(service, did, evt, sess)
      },
    )

    await this.setActiveSession(agent, did)
    this._log('SessionModel:login succeeded')
  }

  async createAccount({
    service,
    email,
    password,
    handle,
    inviteCode,
  }: {
    service: string
    email: string
    password: string
    handle: string
    inviteCode?: string
  }) {
    this._log('SessionModel:createAccount')
    const agent = new BskyAgent({service})
    await agent.createAccount({
      handle,
      password,
      email,
      inviteCode,
    })
    if (!agent.session) {
      throw new Error('Failed to establish session')
    }

    const did = agent.session.did
    const addedInfo = await this.loadAccountInfo(agent, did)

    this.persistSession(service, did, 'create', agent.session, addedInfo)
    agent.setPersistSessionHandler(
      (evt: AtpSessionEvent, sess?: AtpSessionData) => {
        this.persistSession(service, did, evt, sess)
      },
    )

    await this.setActiveSession(agent, did)
    this._log('SessionModel:createAccount succeeded')
  }

  /**
   * Close all sessions across all accounts.
   */
  async logout() {
    this._log('SessionModel:logout')
    // TODO
    // need to evaluate why deleting the session has caused errors at times
    // -prf
    /*if (this.hasSession) {
      this.rootStore.agent.com.atproto.session.delete().catch((e: any) => {
        this.rootStore.log.warn(
          '(Minor issue) Failed to delete session on the server',
          e,
        )
      })
    }*/
    this.clearSessionTokens()
    this.rootStore.clearAllSessionState()
  }

  /**
   * Removes an account from the list of stored accounts.
   */
  removeAccount(handle: string) {
    this.accounts = this.accounts.filter(acc => acc.handle !== handle)
  }

  /**
   * Reloads the session from the server. Useful when account details change, like the handle.
   */
  async reloadFromServer() {
    const sess = this.currentSession
    if (!sess) {
      return
    }
    const res = await this.rootStore.agent
      .getProfile({actor: sess.did})
      .catch(_e => undefined)
    if (res?.success) {
      const updated = {
        ...sess,
        handle: res.data.handle,
        displayName: res.data.displayName,
        aviUrl: res.data.avatar,
      }
      runInAction(() => {
        this.accounts = [
          updated,
          ...this.accounts.filter(
            account =>
              !(
                account.service === updated.service &&
                account.did === updated.did
              ),
          ),
        ]
      })
      await this.rootStore.me.load()
    }
  }
}