about summary refs log tree commit diff
path: root/src/api/index.ts
blob: f83e65411dd5b023185d41f5eab37ea1f563ce6e (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
import {MicroblogDelegator, MicroblogReader, auth} from '@adx/common'
import * as ucan from 'ucans'

export class API {
  userCfg?: UserConfig
  reader?: MicroblogReader
  writer?: MicroblogDelegator

  setUserCfg(cfg: UserConfig) {
    this.userCfg = cfg
    this.createReader()
    this.createWriter()
  }

  private createReader() {
    if (!this.userCfg?.serverUrl) {
      this.reader = undefined
    } else {
      this.reader = new MicroblogReader(
        this.userCfg.serverUrl,
        this.userCfg.did,
      )
    }
  }

  private createWriter() {
    if (
      this.userCfg?.serverUrl &&
      this.userCfg?.did &&
      this.userCfg?.keypair &&
      this.userCfg?.ucanStore
    ) {
      this.writer = new MicroblogDelegator(
        this.userCfg.serverUrl,
        this.userCfg.did,
        this.userCfg.keypair,
        this.userCfg.ucanStore,
      )
    } else {
      this.writer = undefined
    }
  }
}

export interface SerializedUserConfig {
  serverUrl?: string
  secretKeyStr?: string
  rootAuthToken?: string
}

export class UserConfig {
  serverUrl?: string
  did?: string
  keypair?: ucan.EdKeypair
  rootAuthToken?: string
  ucanStore?: ucan.Store

  get hasWriteCaps() {
    return Boolean(this.did && this.keypair && this.ucanStore)
  }

  static async createTest(serverUrl: string) {
    const cfg = new UserConfig()
    cfg.serverUrl = serverUrl
    cfg.keypair = await ucan.EdKeypair.create()
    cfg.did = cfg.keypair.did()
    cfg.rootAuthToken = (await auth.claimFull(cfg.did, cfg.keypair)).encoded()
    cfg.ucanStore = await ucan.Store.fromTokens([cfg.rootAuthToken])
    return cfg
  }

  static async hydrate(state: SerializedUserConfig) {
    const cfg = new UserConfig()
    await cfg.hydrate(state)
    return cfg
  }

  async serialize(): Promise<SerializedUserConfig> {
    return {
      serverUrl: this.serverUrl,
      secretKeyStr: this.keypair
        ? await this.keypair.export('base64')
        : undefined,
      rootAuthToken: this.rootAuthToken,
    }
  }

  async hydrate(state: SerializedUserConfig) {
    this.serverUrl = state.serverUrl
    if (state.secretKeyStr && state.rootAuthToken) {
      this.keypair = ucan.EdKeypair.fromSecretKey(state.secretKeyStr)
      this.did = this.keypair.did()
      this.rootAuthToken = state.rootAuthToken
      this.ucanStore = await ucan.Store.fromTokens([this.rootAuthToken])
    }
  }
}