"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAuth = exports.AuthProvider = exports.AuthContext = void 0;
require("@hyperledger/aries-askar-react-native");
require("reflect-metadata");
var _askar = require("@credo-ts/askar");
var _core = require("@credo-ts/core");
var _reactHooks = require("@credo-ts/react-hooks");
var _reactNative = require("@credo-ts/react-native");
var _react = _interopRequireWildcard(require("react"));
var _reactI18next = require("react-i18next");
var _store = require("./reducers/store");
var _store2 = require("./store");
var _keychain = require("../services/keychain");
var _crypto = require("../utils/crypto");
var _migration = require("../utils/migration");
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
// Dont remove the following import line or the pin check will fail when opening askar waller

const AuthContext = exports.AuthContext = /*#__PURE__*/(0, _react.createContext)(null);
const AuthProvider = ({
  children
}) => {
  const [walletSecret, setWalletSecret] = (0, _react.useState)();
  const [store, dispatch] = (0, _store2.useStore)();
  const {
    agent
  } = (0, _reactHooks.useAgent)();
  const {
    t
  } = (0, _reactI18next.useTranslation)();
  const setPIN = (0, _react.useCallback)(async PIN => {
    const secret = await (0, _keychain.secretForPIN)(PIN);
    await (0, _keychain.storeWalletSecret)(secret);
  }, []);
  const getWalletSecret = (0, _react.useCallback)(async () => {
    if (walletSecret) {
      return walletSecret;
    }
    const secret = await (0, _keychain.loadWalletSecret)(t('Biometry.UnlockPromptTitle'), t('Biometry.UnlockPromptDescription'));
    setWalletSecret(secret);
    return secret;
  }, [t, walletSecret]);
  const commitWalletToKeychain = (0, _react.useCallback)(async useBiometry => {
    const secret = await getWalletSecret();
    if (!secret) {
      return false;
    }

    // set did authenticate to true if we can get wallet credentials
    dispatch({
      type: _store.DispatchAction.DID_AUTHENTICATE
    });
    if (useBiometry) {
      await (0, _keychain.storeWalletSecret)(secret, useBiometry);
    } else {
      // erase wallet key if biometrics is disabled
      await (0, _keychain.wipeWalletKey)(useBiometry);
    }
    return true;
  }, [dispatch, getWalletSecret]);
  const checkWalletPIN = (0, _react.useCallback)(async PIN => {
    try {
      const secret = await (0, _keychain.loadWalletSalt)();
      if (!(secret !== null && secret !== void 0 && secret.salt)) {
        return false;
      }
      const hash = await (0, _crypto.hashPIN)(PIN, secret.salt);
      if (!store.migration.didMigrateToAskar) {
        await (0, _migration.migrateToAskar)(secret.id, hash);
        dispatch({
          type: _store.DispatchAction.DID_MIGRATE_TO_ASKAR
        });
      }

      // NOTE: We create an instance of AskarWallet, which is the underlying wallet that powers the app
      // we then open that instance with the provided id and key to verify their integrity
      const askarWallet = new _askar.AskarWallet(new _core.ConsoleLogger(_core.LogLevel.off), new _reactNative.agentDependencies.FileSystem(), new _core.SigningProviderRegistry([]));
      await askarWallet.open({
        id: secret.id,
        key: hash
      });
      await askarWallet.close();
      const fullSecret = await (0, _keychain.secretForPIN)(PIN, secret.salt);
      setWalletSecret(fullSecret);
      return true;
    } catch (e) {
      return false;
    }
  }, [dispatch, store.migration.didMigrateToAskar]);
  const removeSavedWalletSecret = (0, _react.useCallback)(() => {
    setWalletSecret(undefined);
  }, []);
  const disableBiometrics = (0, _react.useCallback)(async () => {
    await (0, _keychain.wipeWalletKey)(true);
  }, []);
  const rekeyWallet = (0, _react.useCallback)(async (oldPin, newPin, useBiometry) => {
    try {
      if (!agent) {
        // no agent set, cannot rekey the wallet
        return false;
      }
      // argon2.hash can sometimes generate an error
      const secret = await (0, _keychain.loadWalletSalt)();
      if (!secret) {
        return false;
      }
      const oldHash = await (0, _crypto.hashPIN)(oldPin, secret.salt);
      const newSecret = await (0, _keychain.secretForPIN)(newPin);
      const newHash = await (0, _crypto.hashPIN)(newPin, newSecret.salt);
      if (!newSecret.key) {
        return false;
      }
      await agent.wallet.close();
      await agent.wallet.rotateKey({
        id: secret.id,
        key: oldHash,
        rekey: newHash
      });
      await agent.wallet.open({
        ...newSecret
      });
      await (0, _keychain.storeWalletSecret)(newSecret, useBiometry);
      setWalletSecret(newSecret);
    } catch {
      return false;
    }
    return true;
  }, [agent]);
  return /*#__PURE__*/_react.default.createElement(AuthContext.Provider, {
    value: {
      checkWalletPIN,
      getWalletSecret,
      removeSavedWalletSecret,
      disableBiometrics,
      commitWalletToKeychain,
      setPIN,
      isBiometricsActive: _keychain.isBiometricsActive,
      rekeyWallet,
      walletSecret
    }
  }, children);
};
exports.AuthProvider = AuthProvider;
const useAuth = () => (0, _react.useContext)(AuthContext);
exports.useAuth = useAuth;
//# sourceMappingURL=auth.js.map