diff options
author | Paul Frazee <pfrazee@gmail.com> | 2022-06-10 11:55:09 -0500 |
---|---|---|
committer | Paul Frazee <pfrazee@gmail.com> | 2022-06-10 11:55:09 -0500 |
commit | faddda83f04b46bcdaab5c225cab696fc7a820cd (patch) | |
tree | 8a7cacb04f0a480d90a8e5dc9f9daae00f27c802 /src/api/index.ts | |
parent | 967f9fc474f2903dd2c12ef4f662ead1592ea26c (diff) | |
download | voidsky-faddda83f04b46bcdaab5c225cab696fc7a820cd.tar.zst |
(WIP) Add initial API client
Diffstat (limited to 'src/api/index.ts')
-rw-r--r-- | src/api/index.ts | 97 |
1 files changed, 97 insertions, 0 deletions
diff --git a/src/api/index.ts b/src/api/index.ts new file mode 100644 index 000000000..f83e65411 --- /dev/null +++ b/src/api/index.ts @@ -0,0 +1,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]) + } + } +} |