@useorbis/db-sdk
Version:
Orbis' Typescript SDK for building open-data experiences.
82 lines (81 loc) • 2.46 kB
JavaScript
import { SupportedChains } from "../index.js";
import { createDIDKey } from "did-session";
import { encodeBase64, uint8ArraytoHex, hexToUint8Array, } from "../util/conversion.js";
import { parseSerializedSession } from "../util/session.js";
// Think about unifying with DIDSession from Ceramic
export class KeyDidSession {
#seed;
#did;
constructor(seed, did) {
this.#seed = typeof seed === "string" ? seed : uint8ArraytoHex(seed);
this.#did = did;
}
get seed() {
return this.#seed;
}
get did() {
return this.#did;
}
static async fromSession(session) {
const sess = await parseSerializedSession(session);
if (sess.sessionType === "key-did") {
return sess.session;
}
throw `[KeyDidSession] Incorrect session type ${sess.sessionType}`;
}
serialize() {
return encodeBase64(JSON.stringify({
sessionType: "key-did",
did: this.#did,
seed: this.#seed,
}));
}
}
export class OrbisKeyDidAuth {
orbisAuthId = "ceramic-did";
chain = SupportedChains.evm;
#did;
#seed;
constructor(did, seed) {
this.#seed = seed;
this.#did = did;
}
static async generateSeed(format = "uint8") {
const buffer = new Uint8Array(32);
const seed = crypto.getRandomValues(buffer);
if (format === "uint8") {
return seed;
}
return uint8ArraytoHex(seed);
}
static async createRandom() {
const seed = await this.generateSeed();
return this.fromSeed(seed);
}
static async fromSession(session) {
const keySession = typeof session === "string"
? await KeyDidSession.fromSession(session)
: session;
return this.fromSeed(keySession.seed);
}
static async fromSeed(seed) {
const parsedSeed = typeof seed === "string" ? hexToUint8Array(seed) : seed;
const did = await createDIDKey(parsedSeed);
return new OrbisKeyDidAuth(did, parsedSeed);
}
async getUserInformation() {
return {
did: this.#did.id,
chain: this.chain,
metadata: {
publicKey: this.#did.id.split(":").pop(),
},
};
}
async authenticateDid() {
return {
did: this.#did,
session: new KeyDidSession(this.#seed, this.#did.id),
};
}
}