UNPKG

@baqhub/sdk-react

Version:

The official React SDK for the BAQ federated app platform.

100 lines (99 loc) 3.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.AuthenticationStorage = exports.Storage = exports.StorageAdapterType = void 0; const sdk_1 = require("@baqhub/sdk"); var StorageAdapterType; (function (StorageAdapterType) { StorageAdapterType["STANDARD"] = "standard"; StorageAdapterType["SECURE"] = "secure"; })(StorageAdapterType || (exports.StorageAdapterType = StorageAdapterType = {})); // // API. // exports.Storage = { async read(provider, model, key) { try { const stringValue = await provider.getString(key); if (!stringValue) { return undefined; } const jsonValue = JSON.parse(stringValue); return sdk_1.IO.decode(model, jsonValue); } catch (err) { console.log("Error while reading storage value:", key, err); return undefined; } }, write(provider, model, key, value) { const jsonValue = model.encode(value); const stringValue = JSON.stringify(jsonValue); return provider.setString(key, stringValue); }, }; // // Authentication state API. // const stateKey = "auth_state"; const stateSecretKey = "auth_state_secret"; class AuthenticationStorage { adapter; secureAdapter; constructor(adapter, secureAdapter) { this.adapter = adapter; this.secureAdapter = secureAdapter; } async read() { const authenticationStatePromise = exports.Storage.read(this.adapter, sdk_1.RAuthenticationState, stateKey); if (!this.secureAdapter) { return authenticationStatePromise; } // If secure storage is available, read the private key separately. const [authenticationState, authenticationSecret] = await Promise.all([ authenticationStatePromise, exports.Storage.read(this.secureAdapter, sdk_1.IO.base64Bytes, stateSecretKey), ]); if (!authenticationState || !authenticationSecret) { return undefined; } return { ...authenticationState, credentialsRecord: { ...authenticationState.credentialsRecord, content: { ...authenticationState.credentialsRecord.content, privateKey: authenticationSecret, }, }, }; } async write(state) { // If no state was provided, clear the storage. if (!state) { return Promise.all([ this.adapter.removeString(stateKey), this.secureAdapter?.removeString(stateSecretKey), ].filter(sdk_1.isDefined)); } if (!this.secureAdapter) { return exports.Storage.write(this.adapter, sdk_1.RAuthenticationState, stateKey, state); } // If secure storage is available, store the private key separately. const authenticationState = { ...state, credentialsRecord: { ...state.credentialsRecord, content: { ...state.credentialsRecord.content, privateKey: new Uint8Array(0), }, }, }; const authenticationSecret = state.credentialsRecord.content.privateKey; return Promise.all([ exports.Storage.write(this.adapter, sdk_1.RAuthenticationState, stateKey, authenticationState), exports.Storage.write(this.secureAdapter, sdk_1.IO.base64Bytes, stateSecretKey, authenticationSecret), ]); } } exports.AuthenticationStorage = AuthenticationStorage;