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S,KAEVnB,EAAQ,SACV,GAAI,CACF,OAAO,QAAQ,UAAU,CAAA,EAAI,GAAIA,EAAQ,QAAQ,OACvC,CACV,OAAO,SAAS,KAAOA,EAAQ,SAGrC,GAGF,eAAe0B,EAAezB,EAA0B,CACtD,MAAMA,EAAQ,OAAOO,CAAe,EACpC,MAAMP,EAAQ,OAAOY,CAAsB,EAC3C,MAAMZ,EAAQ,OAAO6C,CAAU,CACjC","names":["AnonymousIdentity","Delegation","DelegationChain","isDelegationValid","DelegationIdentity","Ed25519KeyIdentity","ECDSAKeyIdentity","PartialDelegationIdentity","events","IdleManager","options","onIdle","idleTimeout","_resetTimer","name","debounce","func","wait","timeout","args","context","later","scroll","_a","callback","cb","exit","openDB","AUTH_DB_NAME","OBJECT_STORE_NAME","_openDbStore","dbName","storeName","version","isBrowser","KEY_STORAGE_DELEGATION","KEY_STORAGE_KEY","openDB","database","_getValue","db","key","_setValue","value","_removeValue","IdbKeyVal","_IdbKeyVal","_db","_storeName","options","DB_VERSION","_a","KEY_STORAGE_KEY","KEY_STORAGE_DELEGATION","KEY_VECTOR","DB_VERSION","isBrowser","LocalStorage","prefix","_localStorage","key","value","ls","IdbStorage","options","_IdbStorage_options","__classPrivateFieldSet","resolve","IdbKeyVal","__classPrivateFieldGet","db","IDENTITY_PROVIDER_DEFAULT","IDENTITY_PROVIDER_ENDPOINT","ECDSA_KEY_LABEL","ED25519_KEY_LABEL","INTERRUPT_CHECK_INTERVAL","ERROR_USER_INTERRUPT","AuthClient","_identity","_key","_chain","_storage","idleManager","_createOptions","_idpWindow","_eventHandler","options","storage","_a","IdbStorage","keyType","_b","key","maybeIdentityStorage","KEY_STORAGE_KEY","isBrowser","fallbackLocalStorage","LocalStorage","localChain","KEY_STORAGE_DELEGATION","localKey","error","Ed25519KeyIdentity","ECDSAKeyIdentity","identity","AnonymousIdentity","chain","chainStorage","DelegationChain","isDelegationValid","PartialDelegationIdentity","DelegationIdentity","_deleteStorage","e","_c","IdleManager","idleOptions","message","onSuccess","delegations","signedDelegation","Delegation","delegationChain","defaultTimeToLive","identityProviderUrl","_d","checkInterruption","event","request","err","errorMessage","onError","KEY_VECTOR"],"sources":["../esm/npm/@dfinity/auth-client@1.4.0/node_modules/@dfinity/auth-client/src/index.ts","../esm/npm/@dfinity/auth-client@1.4.0/node_modules/@dfinity/auth-client/src/idleManager.ts","../esm/npm/@dfinity/auth-client@1.4.0/node_modules/@dfinity/auth-client/src/db.ts","../esm/npm/@dfinity/auth-client@1.4.0/node_modules/@dfinity/auth-client/src/storage.ts"],"sourcesContent":["/** @module AuthClient */\nimport {\n  AnonymousIdentity,\n  DerEncodedPublicKey,\n  Identity,\n  Signature,\n  SignIdentity,\n} from '@dfinity/agent';\nimport {\n  Delegation,\n  DelegationChain,\n  isDelegationValid,\n  DelegationIdentity,\n  Ed25519KeyIdentity,\n  ECDSAKeyIdentity,\n  PartialDelegationIdentity,\n} from '@dfinity/identity';\nimport { Principal } from '@dfinity/principal';\nimport { IdleManager, IdleManagerOptions } from './idleManager';\nimport {\n  AuthClientStorage,\n  IdbStorage,\n  isBrowser,\n  KEY_STORAGE_DELEGATION,\n  KEY_STORAGE_KEY,\n  KEY_VECTOR,\n  LocalStorage,\n} from './storage';\nimport { PartialIdentity } from '@dfinity/identity/lib/cjs/identity/partial';\n\nexport { AuthClientStorage, IdbStorage, LocalStorage, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\nexport { IdbKeyVal, DBCreateOptions } from './db';\n\nconst IDENTITY_PROVIDER_DEFAULT = 'https://identity.ic0.app';\nconst IDENTITY_PROVIDER_ENDPOINT = '#authorize';\n\nconst ECDSA_KEY_LABEL = 'ECDSA';\nconst ED25519_KEY_LABEL = 'Ed25519';\ntype BaseKeyType = typeof ECDSA_KEY_LABEL | typeof ED25519_KEY_LABEL;\n\nconst INTERRUPT_CHECK_INTERVAL = 500;\n\nexport const ERROR_USER_INTERRUPT = 'UserInterrupt';\n\n/**\n * List of options for creating an {@link AuthClient}.\n */\nexport interface AuthClientCreateOptions {\n  /**\n   * An identity to use as the base\n   */\n  identity?: SignIdentity | PartialIdentity;\n  /**\n   * Optional storage with get, set, and remove. Uses {@link IdbStorage} by default\n   */\n  storage?: AuthClientStorage;\n  /**\n   * type to use for the base key\n   * @default 'ECDSA'\n   * If you are using a custom storage provider that does not support CryptoKey storage,\n   * you should use 'Ed25519' as the key type, as it can serialize to a string\n   */\n  keyType?: BaseKeyType;\n\n  /**\n   * Options to handle idle timeouts\n   * @default after 30 minutes, invalidates the identity\n   */\n  idleOptions?: IdleOptions;\n}\n\nexport interface IdleOptions extends IdleManagerOptions {\n  /**\n   * Disables idle functionality for {@link IdleManager}\n   * @default false\n   */\n  disableIdle?: boolean;\n\n  /**\n   * Disables default idle behavior - call logout \u0026 reload window\n   * @default false\n   */\n  disableDefaultIdleCallback?: boolean;\n}\n\nexport * from './idleManager';\n\nexport type OnSuccessFunc =\n  | (() =\u003e void | Promise\u003cvoid\u003e)\n  | ((message: InternetIdentityAuthResponseSuccess) =\u003e void | Promise\u003cvoid\u003e);\n\nexport type OnErrorFunc = (error?: string) =\u003e void | Promise\u003cvoid\u003e;\n\nexport interface AuthClientLoginOptions {\n  /**\n   * Identity provider\n   * @default \"https://identity.ic0.app\"\n   */\n  identityProvider?: string | URL;\n  /**\n   * Expiration of the authentication in nanoseconds\n   * @default  BigInt(8) hours * BigInt(3_600_000_000_000) nanoseconds\n   */\n  maxTimeToLive?: bigint;\n  /**\n   * If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n   */\n  allowPinAuthentication?: boolean;\n  /**\n   * Origin for Identity Provider to use while generating the delegated identity. For II, the derivation origin must authorize this origin by setting a record at `\u003cderivation-origin\u003e/.well-known/ii-alternative-origins`.\n   * @see https://github.com/dfinity/internet-identity/blob/main/docs/internet-identity-spec.adoc\n   */\n  derivationOrigin?: string | URL;\n  /**\n   * Auth Window feature config string\n   * @example \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\"\n   */\n  windowOpenerFeatures?: string;\n  /**\n   * Callback once login has completed\n   */\n  onSuccess?: OnSuccessFunc;\n  /**\n   * Callback in case authentication fails\n   */\n  onError?: OnErrorFunc;\n  /**\n   * Extra values to be passed in the login request during the authorize-ready phase\n   */\n  customValues?: Record\u003cstring, unknown\u003e;\n}\n\ninterface InternetIdentityAuthRequest {\n  kind: 'authorize-client';\n  sessionPublicKey: Uint8Array;\n  maxTimeToLive?: bigint;\n  allowPinAuthentication?: boolean;\n  derivationOrigin?: string;\n}\n\nexport interface InternetIdentityAuthResponseSuccess {\n  kind: 'authorize-client-success';\n  delegations: {\n    delegation: {\n      pubkey: Uint8Array;\n      expiration: bigint;\n      targets?: Principal[];\n    };\n    signature: Uint8Array;\n  }[];\n  userPublicKey: Uint8Array;\n  authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthReadyMessage {\n  kind: 'authorize-ready';\n}\n\ninterface AuthResponseSuccess {\n  kind: 'authorize-client-success';\n  delegations: {\n    delegation: {\n      pubkey: Uint8Array;\n      expiration: bigint;\n      targets?: Principal[];\n    };\n    signature: Uint8Array;\n  }[];\n  userPublicKey: Uint8Array;\n  authnMethod: 'passkey' | 'pin' | 'recovery';\n}\n\ninterface AuthResponseFailure {\n  kind: 'authorize-client-failure';\n  text: string;\n}\n\ntype IdentityServiceResponseMessage = AuthReadyMessage | AuthResponse;\ntype AuthResponse = AuthResponseSuccess | AuthResponseFailure;\n\n/**\n * Tool to manage authentication and identity\n * @see {@link AuthClient}\n */\nexport class AuthClient {\n  /**\n   * Create an AuthClient to manage authentication and identity\n   * @constructs\n   * @param {AuthClientCreateOptions} options - Options for creating an {@link AuthClient}\n   * @see {@link AuthClientCreateOptions}\n   * @param options.identity Optional Identity to use as the base\n   * @see {@link SignIdentity}\n   * @param options.storage Storage mechanism for delegration credentials\n   * @see {@link AuthClientStorage}\n   * @param options.keyType Type of key to use for the base key\n   * @param {IdleOptions} options.idleOptions Configures an {@link IdleManager}\n   * @see {@link IdleOptions}\n   * Default behavior is to clear stored identity and reload the page when a user goes idle, unless you set the disableDefaultIdleCallback flag or pass in a custom idle callback.\n   * @example\n   * const authClient = await AuthClient.create({\n   *   idleOptions: {\n   *     disableIdle: true\n   *   }\n   * })\n   */\n  public static async create(\n    options: {\n      /**\n       * An {@link SignIdentity} or {@link PartialIdentity} to authenticate via delegation.\n       */\n      identity?: SignIdentity | PartialIdentity;\n      /**\n       * {@link AuthClientStorage}\n       * @description Optional storage with get, set, and remove. Uses {@link IdbStorage} by default\n       */\n      storage?: AuthClientStorage;\n      /**\n       * type to use for the base key\n       * @default 'ECDSA'\n       * If you are using a custom storage provider that does not support CryptoKey storage,\n       * you should use 'Ed25519' as the key type, as it can serialize to a string\n       */\n      keyType?: BaseKeyType;\n      /**\n       * Options to handle idle timeouts\n       * @default after 10 minutes, invalidates the identity\n       */\n      idleOptions?: IdleOptions;\n    } = {},\n  ): Promise\u003cAuthClient\u003e {\n    const storage = options.storage ?? new IdbStorage();\n    const keyType = options.keyType ?? ECDSA_KEY_LABEL;\n\n    let key: null | SignIdentity | PartialIdentity = null;\n    if (options.identity) {\n      key = options.identity;\n    } else {\n      let maybeIdentityStorage = await storage.get(KEY_STORAGE_KEY);\n      if (!maybeIdentityStorage \u0026\u0026 isBrowser) {\n        // Attempt to migrate from localstorage\n        try {\n          const fallbackLocalStorage = new LocalStorage();\n          const localChain = await fallbackLocalStorage.get(KEY_STORAGE_DELEGATION);\n          const localKey = await fallbackLocalStorage.get(KEY_STORAGE_KEY);\n          // not relevant for Ed25519\n          if (localChain \u0026\u0026 localKey \u0026\u0026 keyType === ECDSA_KEY_LABEL) {\n            console.log('Discovered an identity stored in localstorage. Migrating to IndexedDB');\n            await storage.set(KEY_STORAGE_DELEGATION, localChain);\n            await storage.set(KEY_STORAGE_KEY, localKey);\n\n            maybeIdentityStorage = localChain;\n            // clean up\n            await fallbackLocalStorage.remove(KEY_STORAGE_DELEGATION);\n            await fallbackLocalStorage.remove(KEY_STORAGE_KEY);\n          }\n        } catch (error) {\n          console.error('error while attempting to recover localstorage: ' + error);\n        }\n      }\n      if (maybeIdentityStorage) {\n        try {\n          if (typeof maybeIdentityStorage === 'object') {\n            if (keyType === ED25519_KEY_LABEL \u0026\u0026 typeof maybeIdentityStorage === 'string') {\n              key = await Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n            } else {\n              key = await ECDSAKeyIdentity.fromKeyPair(maybeIdentityStorage);\n            }\n          } else if (typeof maybeIdentityStorage === 'string') {\n            // This is a legacy identity, which is a serialized Ed25519KeyIdentity.\n            key = Ed25519KeyIdentity.fromJSON(maybeIdentityStorage);\n          }\n        } catch (e) {\n          // Ignore this, this means that the localStorage value isn't a valid Ed25519KeyIdentity or ECDSAKeyIdentity\n          // serialization.\n        }\n      }\n    }\n\n    let identity: SignIdentity | PartialIdentity = new AnonymousIdentity() as PartialIdentity;\n    let chain: null | DelegationChain = null;\n    if (key) {\n      try {\n        const chainStorage = await storage.get(KEY_STORAGE_DELEGATION);\n        if (typeof chainStorage === 'object' \u0026\u0026 chainStorage !== null) {\n          throw new Error(\n            'Delegation chain is incorrectly stored. A delegation chain should be stored as a string.',\n          );\n        }\n\n        if (options.identity) {\n          identity = options.identity;\n        } else if (chainStorage) {\n          chain = DelegationChain.fromJSON(chainStorage);\n\n          // Verify that the delegation isn't expired.\n          if (!isDelegationValid(chain)) {\n            await _deleteStorage(storage);\n            key = null;\n          } else {\n            // If the key is a public key, then we create a PartialDelegationIdentity.\n            if ('toDer' in key) {\n              identity = PartialDelegationIdentity.fromDelegation(key, chain);\n              // otherwise, we create a DelegationIdentity.\n            } else {\n              identity = DelegationIdentity.fromDelegation(key, chain);\n            }\n          }\n        }\n      } catch (e) {\n        console.error(e);\n        // If there was a problem loading the chain, delete the key.\n        await _deleteStorage(storage);\n        key = null;\n      }\n    }\n    let idleManager: IdleManager | undefined = undefined;\n    if (options.idleOptions?.disableIdle) {\n      idleManager = undefined;\n    }\n    // if there is a delegation chain or provided identity, setup idleManager\n    else if (chain || options.identity) {\n      idleManager = IdleManager.create(options.idleOptions);\n    }\n\n    if (!key) {\n      // Create a new key (whether or not one was in storage).\n      if (keyType === ED25519_KEY_LABEL) {\n        key = await Ed25519KeyIdentity.generate();\n        await storage.set(KEY_STORAGE_KEY, JSON.stringify((key as Ed25519KeyIdentity).toJSON()));\n      } else {\n        if (options.storage \u0026\u0026 keyType === ECDSA_KEY_LABEL) {\n          console.warn(\n            `You are using a custom storage provider that may not support CryptoKey storage. If you are using a custom storage provider that does not support CryptoKey storage, you should use '${ED25519_KEY_LABEL}' as the key type, as it can serialize to a string`,\n          );\n        }\n        key = await ECDSAKeyIdentity.generate();\n        await storage.set(KEY_STORAGE_KEY, (key as ECDSAKeyIdentity).getKeyPair());\n      }\n    }\n\n    return new this(identity, key, chain, storage, idleManager, options);\n  }\n\n  protected constructor(\n    private _identity: Identity | PartialIdentity,\n    private _key: SignIdentity | PartialIdentity,\n    private _chain: DelegationChain | null,\n    private _storage: AuthClientStorage,\n    public idleManager: IdleManager | undefined,\n    private _createOptions: AuthClientCreateOptions | undefined,\n    // A handle on the IdP window.\n    private _idpWindow?: Window,\n    // The event handler for processing events from the IdP.\n    private _eventHandler?: (event: MessageEvent) =\u003e void,\n  ) {\n    this._registerDefaultIdleCallback();\n  }\n\n  private _registerDefaultIdleCallback() {\n    const idleOptions = this._createOptions?.idleOptions;\n    /**\n     * Default behavior is to clear stored identity and reload the page.\n     * By either setting the disableDefaultIdleCallback flag or passing in a custom idle callback, we will ignore this config\n     */\n    if (!idleOptions?.onIdle \u0026\u0026 !idleOptions?.disableDefaultIdleCallback) {\n      this.idleManager?.registerCallback(() =\u003e {\n        this.logout();\n        location.reload();\n      });\n    }\n  }\n\n  private async _handleSuccess(\n    message: InternetIdentityAuthResponseSuccess,\n    onSuccess?: OnSuccessFunc,\n  ) {\n    const delegations = message.delegations.map(signedDelegation =\u003e {\n      return {\n        delegation: new Delegation(\n          signedDelegation.delegation.pubkey,\n          signedDelegation.delegation.expiration,\n          signedDelegation.delegation.targets,\n        ),\n        signature: signedDelegation.signature.buffer as Signature,\n      };\n    });\n\n    const delegationChain = DelegationChain.fromDelegations(\n      delegations,\n      message.userPublicKey.buffer as DerEncodedPublicKey,\n    );\n\n    const key = this._key;\n    if (!key) {\n      return;\n    }\n\n    this._chain = delegationChain;\n\n    if ('toDer' in key) {\n      this._identity = PartialDelegationIdentity.fromDelegation(key, this._chain);\n    } else {\n      this._identity = DelegationIdentity.fromDelegation(key, this._chain);\n    }\n\n    this._idpWindow?.close();\n    const idleOptions = this._createOptions?.idleOptions;\n    // create the idle manager on a successful login if we haven't disabled it\n    // and it doesn't already exist.\n    if (!this.idleManager \u0026\u0026 !idleOptions?.disableIdle) {\n      this.idleManager = IdleManager.create(idleOptions);\n      this._registerDefaultIdleCallback();\n    }\n\n    this._removeEventListener();\n    delete this._idpWindow;\n\n    if (this._chain) {\n      await this._storage.set(KEY_STORAGE_DELEGATION, JSON.stringify(this._chain.toJSON()));\n    }\n\n    // onSuccess should be the last thing to do to avoid consumers\n    // interfering by navigating or refreshing the page\n    onSuccess?.(message);\n  }\n\n  public getIdentity(): Identity {\n    return this._identity;\n  }\n\n  public async isAuthenticated(): Promise\u003cboolean\u003e {\n    return !this.getIdentity().getPrincipal().isAnonymous() \u0026\u0026 this._chain !== null;\n  }\n\n  /**\n   * AuthClient Login -\n   * Opens up a new window to authenticate with Internet Identity\n   * @param {AuthClientLoginOptions} options - Options for logging in\n   * @param options.identityProvider Identity provider\n   * @param options.maxTimeToLive Expiration of the authentication in nanoseconds\n   * @param options.allowPinAuthentication If present, indicates whether or not the Identity Provider should allow the user to authenticate and/or register using a temporary key/PIN identity. Authenticating dapps may want to prevent users from using Temporary keys/PIN identities because Temporary keys/PIN identities are less secure than Passkeys (webauthn credentials) and because Temporary keys/PIN identities generally only live in a browser database (which may get cleared by the browser/OS).\n   * @param options.derivationOrigin Origin for Identity Provider to use while generating the delegated identity\n   * @param options.windowOpenerFeatures Configures the opened authentication window\n   * @param options.onSuccess Callback once login has completed\n   * @param options.onError Callback in case authentication fails\n   * @example\n   * const authClient = await AuthClient.create();\n   * authClient.login({\n   *  identityProvider: 'http://\u003ccanisterID\u003e.127.0.0.1:8000',\n   *  maxTimeToLive: BigInt (7) * BigInt(24) * BigInt(3_600_000_000_000), // 1 week\n   *  windowOpenerFeatures: \"toolbar=0,location=0,menubar=0,width=500,height=500,left=100,top=100\",\n   *  onSuccess: () =\u003e {\n   *    console.log('Login Successful!');\n   *  },\n   *  onError: (error) =\u003e {\n   *    console.error('Login Failed: ', error);\n   *  }\n   * });\n   */\n  public async login(options?: AuthClientLoginOptions): Promise\u003cvoid\u003e {\n    // Set default maxTimeToLive to 8 hours\n    const defaultTimeToLive = /* hours */ BigInt(8) * /* nanoseconds */ BigInt(3_600_000_000_000);\n\n    // Create the URL of the IDP. (e.g. https://XXXX/#authorize)\n    const identityProviderUrl = new URL(\n      options?.identityProvider?.toString() || IDENTITY_PROVIDER_DEFAULT,\n    );\n    // Set the correct hash if it isn't already set.\n    identityProviderUrl.hash = IDENTITY_PROVIDER_ENDPOINT;\n\n    // If `login` has been called previously, then close/remove any previous windows\n    // and event listeners.\n    this._idpWindow?.close();\n    this._removeEventListener();\n\n    // Add an event listener to handle responses.\n    this._eventHandler = this._getEventHandler(identityProviderUrl, {\n      maxTimeToLive: options?.maxTimeToLive ?? defaultTimeToLive,\n      ...options,\n    });\n    window.addEventListener('message', this._eventHandler);\n\n    // Open a new window with the IDP provider.\n    this._idpWindow =\n      window.open(identityProviderUrl.toString(), 'idpWindow', options?.windowOpenerFeatures) ??\n      undefined;\n\n    // Check if the _idpWindow is closed by user.\n    const checkInterruption = (): void =\u003e {\n      // The _idpWindow is opened and not yet closed by the client\n      if (this._idpWindow) {\n        if (this._idpWindow.closed) {\n          this._handleFailure(ERROR_USER_INTERRUPT, options?.onError);\n        } else {\n          setTimeout(checkInterruption, INTERRUPT_CHECK_INTERVAL);\n        }\n      }\n    };\n    checkInterruption();\n  }\n\n  private _getEventHandler(identityProviderUrl: URL, options?: AuthClientLoginOptions) {\n    return async (event: MessageEvent) =\u003e {\n      if (event.origin !== identityProviderUrl.origin) {\n        console.warn(\n          `WARNING: expected origin '${identityProviderUrl.origin}', got '${event.origin}' (ignoring)`,\n        );\n        return;\n      }\n\n      const message = event.data as IdentityServiceResponseMessage;\n\n      switch (message.kind) {\n        case 'authorize-ready': {\n          // IDP is ready. Send a message to request authorization.\n          const request: InternetIdentityAuthRequest = {\n            kind: 'authorize-client',\n            sessionPublicKey: new Uint8Array(this._key?.getPublicKey().toDer() as ArrayBuffer),\n            maxTimeToLive: options?.maxTimeToLive,\n            allowPinAuthentication: options?.allowPinAuthentication,\n            derivationOrigin: options?.derivationOrigin?.toString(),\n            // Pass any custom values to the IDP.\n            ...options?.customValues,\n          };\n          this._idpWindow?.postMessage(request, identityProviderUrl.origin);\n          break;\n        }\n        case 'authorize-client-success':\n          // Create the delegation chain and store it.\n          try {\n            await this._handleSuccess(message, options?.onSuccess);\n          } catch (err) {\n            this._handleFailure((err as Error).message, options?.onError);\n          }\n          break;\n        case 'authorize-client-failure':\n          this._handleFailure(message.text, options?.onError);\n          break;\n        default:\n          break;\n      }\n    };\n  }\n\n  private _handleFailure(errorMessage?: string, onError?: (error?: string) =\u003e void): void {\n    this._idpWindow?.close();\n    onError?.(errorMessage);\n    this._removeEventListener();\n    delete this._idpWindow;\n  }\n\n  private _removeEventListener() {\n    if (this._eventHandler) {\n      window.removeEventListener('message', this._eventHandler);\n    }\n    this._eventHandler = undefined;\n  }\n\n  public async logout(options: { returnTo?: string } = {}): Promise\u003cvoid\u003e {\n    await _deleteStorage(this._storage);\n\n    // Reset this auth client to a non-authenticated state.\n    this._identity = new AnonymousIdentity();\n    this._chain = null;\n\n    if (options.returnTo) {\n      try {\n        window.history.pushState({}, '', options.returnTo);\n      } catch (e) {\n        window.location.href = options.returnTo;\n      }\n    }\n  }\n}\n\nasync function _deleteStorage(storage: AuthClientStorage) {\n  await storage.remove(KEY_STORAGE_KEY);\n  await storage.remove(KEY_STORAGE_DELEGATION);\n  await storage.remove(KEY_VECTOR);\n}\n","/** @module IdleManager */\ntype IdleCB = () =\u003e unknown;\nexport type IdleManagerOptions = {\n  /**\n   * Callback after the user has gone idle\n   */\n  onIdle?: IdleCB;\n  /**\n   * timeout in ms\n   * @default 30 minutes [600_000]\n   */\n  idleTimeout?: number;\n  /**\n   * capture scroll events\n   * @default false\n   */\n  captureScroll?: boolean;\n  /**\n   * scroll debounce time in ms\n   * @default 100\n   */\n  scrollDebounce?: number;\n};\n\nconst events = ['mousedown', 'mousemove', 'keydown', 'touchstart', 'wheel'];\n\n/**\n * Detects if the user has been idle for a duration of `idleTimeout` ms, and calls `onIdle` and registered callbacks.\n * By default, the IdleManager will log a user out after 10 minutes of inactivity.\n * To override these defaults, you can pass an `onIdle` callback, or configure a custom `idleTimeout` in milliseconds\n */\nexport class IdleManager {\n  callbacks: IdleCB[] = [];\n  idleTimeout: IdleManagerOptions['idleTimeout'] = 10 * 60 * 1000;\n  timeoutID?: number = undefined;\n\n  /**\n   * Creates an {@link IdleManager}\n   * @param {IdleManagerOptions} options Optional configuration\n   * @see {@link IdleManagerOptions}\n   * @param options.onIdle Callback once user has been idle. Use to prompt for fresh login, and use `Actor.agentOf(your_actor).invalidateIdentity()` to protect the user\n   * @param options.idleTimeout timeout in ms\n   * @param options.captureScroll capture scroll events\n   * @param options.scrollDebounce scroll debounce time in ms\n   */\n  public static create(\n    options: {\n      /**\n       * Callback after the user has gone idle\n       * @see {@link IdleCB}\n       */\n      onIdle?: () =\u003e unknown;\n      /**\n       * timeout in ms\n       * @default 10 minutes [600_000]\n       */\n      idleTimeout?: number;\n      /**\n       * capture scroll events\n       * @default false\n       */\n      captureScroll?: boolean;\n      /**\n       * scroll debounce time in ms\n       * @default 100\n       */\n      scrollDebounce?: number;\n    } = {},\n  ): IdleManager {\n    return new this(options);\n  }\n\n  /**\n   * @protected\n   * @param options {@link IdleManagerOptions}\n   */\n  protected constructor(options: IdleManagerOptions = {}) {\n    const { onIdle, idleTimeout = 10 * 60 * 1000 } = options || {};\n\n    this.callbacks = onIdle ? [onIdle] : [];\n    this.idleTimeout = idleTimeout;\n\n    const _resetTimer = this._resetTimer.bind(this);\n\n    window.addEventListener('load', _resetTimer, true);\n\n    events.forEach(function (name) {\n      document.addEventListener(name, _resetTimer, true);\n    });\n\n    // eslint-disable-next-line @typescript-eslint/ban-types\n    const debounce = (func: Function, wait: number) =\u003e {\n      let timeout: number | undefined;\n      return (...args: unknown[]) =\u003e {\n        // eslint-disable-next-line @typescript-eslint/no-this-alias\n        const context = this;\n        const later = function () {\n          timeout = undefined;\n          func.apply(context, args);\n        };\n        clearTimeout(timeout);\n        timeout = window.setTimeout(later, wait);\n      };\n    };\n\n    if (options?.captureScroll) {\n      // debounce scroll events\n      const scroll = debounce(_resetTimer, options?.scrollDebounce ?? 100);\n      window.addEventListener('scroll', scroll, true);\n    }\n\n    _resetTimer();\n  }\n\n  /**\n   * @param {IdleCB} callback function to be called when user goes idle\n   */\n  public registerCallback(callback: IdleCB): void {\n    this.callbacks.push(callback);\n  }\n\n  /**\n   * Cleans up the idle manager and its listeners\n   */\n  public exit(): void {\n    clearTimeout(this.timeoutID);\n    window.removeEventListener('load', this._resetTimer, true);\n\n    const _resetTimer = this._resetTimer.bind(this);\n    events.forEach(function (name) {\n      document.removeEventListener(name, _resetTimer, true);\n    });\n    this.callbacks.forEach(cb =\u003e cb());\n  }\n\n  /**\n   * Resets the timeouts during cleanup\n   */\n  _resetTimer(): void {\n    const exit = this.exit.bind(this);\n    window.clearTimeout(this.timeoutID);\n    this.timeoutID = window.setTimeout(exit, this.idleTimeout);\n  }\n}\n","import { openDB, IDBPDatabase } from 'idb';\nimport { DB_VERSION, isBrowser, KEY_STORAGE_DELEGATION, KEY_STORAGE_KEY } from './storage';\n\ntype Database = IDBPDatabase\u003cunknown\u003e;\ntype IDBValidKey = string | number | Date | BufferSource | IDBValidKey[];\nconst AUTH_DB_NAME = 'auth-client-db';\nconst OBJECT_STORE_NAME = 'ic-keyval';\n\nconst _openDbStore = async (\n  dbName = AUTH_DB_NAME,\n  storeName = OBJECT_STORE_NAME,\n  version: number,\n) =\u003e {\n  // Clear legacy stored delegations\n  if (isBrowser \u0026\u0026 localStorage?.getItem(KEY_STORAGE_DELEGATION)) {\n    localStorage.removeItem(KEY_STORAGE_DELEGATION);\n    localStorage.removeItem(KEY_STORAGE_KEY);\n  }\n  return await openDB(dbName, version, {\n    upgrade: database =\u003e {\n      database.objectStoreNames;\n      if (database.objectStoreNames.contains(storeName)) {\n        database.clear(storeName);\n      }\n      database.createObjectStore(storeName);\n    },\n  });\n};\n\nasync function _getValue\u003cT\u003e(\n  db: Database,\n  storeName: string,\n  key: IDBValidKey,\n): Promise\u003cT | undefined\u003e {\n  return await db.get(storeName, key);\n}\n\nasync function _setValue\u003cT\u003e(\n  db: Database,\n  storeName: string,\n  key: IDBValidKey,\n  value: T,\n): Promise\u003cIDBValidKey\u003e {\n  return await db.put(storeName, value, key);\n}\n\nasync function _removeValue(db: Database, storeName: string, key: IDBValidKey): Promise\u003cvoid\u003e {\n  return await db.delete(storeName, key);\n}\n\nexport type DBCreateOptions = {\n  dbName?: string;\n  storeName?: string;\n  version?: number;\n};\n\n/**\n * Simple Key Value store\n * Defaults to `'auth-client-db'` with an object store of `'ic-keyval'`\n */\nexport class IdbKeyVal {\n  /**\n   * @param {DBCreateOptions} options - DBCreateOptions\n   * @param {DBCreateOptions['dbName']} options.dbName name for the indexeddb database\n   * @default\n   * @param {DBCreateOptions['storeName']} options.storeName name for the indexeddb Data Store\n   * @default\n   * @param {DBCreateOptions['version']} options.version version of the database. Increment to safely upgrade\n   * @constructs an {@link IdbKeyVal}\n   */\n  public static async create(options?: DBCreateOptions): Promise\u003cIdbKeyVal\u003e {\n    const { dbName = AUTH_DB_NAME, storeName = OBJECT_STORE_NAME, version = DB_VERSION } = options ?? {};\n    const db = await _openDbStore(dbName, storeName, version);\n    return new IdbKeyVal(db, storeName);\n  }\n\n  // Do not use - instead prefer create\n  private constructor(private _db: Database, private _storeName: string) {}\n\n  /**\n   * Basic setter\n   * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n   * @param value value to set\n   * @returns void\n   */\n  public async set\u003cT\u003e(key: IDBValidKey, value: T) {\n    return await _setValue\u003cT\u003e(this._db, this._storeName, key, value);\n  }\n  /**\n   * Basic getter\n   * Pass in a type T for type safety if you know the type the value will have if it is found\n   * @param {IDBValidKey} key string | number | Date | BufferSource | IDBValidKey[]\n   * @returns `Promise\u003cT | null\u003e`\n   * @example\n   * await get\u003cstring\u003e('exampleKey') -\u003e 'exampleValue'\n   */\n  public async get\u003cT\u003e(key: IDBValidKey): Promise\u003cT | null\u003e {\n    return (await _getValue\u003cT\u003e(this._db, this._storeName, key)) ?? null;\n  }\n\n  /**\n   * Remove a key\n   * @param key {@link IDBValidKey}\n   * @returns void\n   */\n  public async remove(key: IDBValidKey) {\n    return await _removeValue(this._db, this._storeName, key);\n  }\n}\n","import { DBCreateOptions, IdbKeyVal } from './db';\n\nexport const KEY_STORAGE_KEY = 'identity';\nexport const KEY_STORAGE_DELEGATION = 'delegation';\nexport const KEY_VECTOR = 'iv';\n// Increment if any fields are modified\nexport const DB_VERSION = 1;\n\nexport const isBrowser = typeof window !== 'undefined';\n\nexport type StoredKey = string | CryptoKeyPair;\n\n/**\n * Interface for persisting user authentication data\n */\nexport interface AuthClientStorage {\n  get(key: string): Promise\u003cStoredKey | null\u003e;\n\n  set(key: string, value: StoredKey): Promise\u003cvoid\u003e;\n\n  remove(key: string): Promise\u003cvoid\u003e;\n}\n\n/**\n * Legacy implementation of AuthClientStorage, for use where IndexedDb is not available\n */\nexport class LocalStorage implements AuthClientStorage {\n  constructor(public readonly prefix = 'ic-', private readonly _localStorage?: Storage) {}\n\n  public get(key: string): Promise\u003cstring | null\u003e {\n    return Promise.resolve(this._getLocalStorage().getItem(this.prefix + key));\n  }\n\n  public set(key: string, value: string): Promise\u003cvoid\u003e {\n    this._getLocalStorage().setItem(this.prefix + key, value);\n    return Promise.resolve();\n  }\n\n  public remove(key: string): Promise\u003cvoid\u003e {\n    this._getLocalStorage().removeItem(this.prefix + key);\n    return Promise.resolve();\n  }\n\n  private _getLocalStorage() {\n    if (this._localStorage) {\n      return this._localStorage;\n    }\n\n    const ls =\n      typeof window === 'undefined'\n        ? typeof global === 'undefined'\n          ? typeof self === 'undefined'\n            ? undefined\n            : self.localStorage\n          : global.localStorage\n        : window.localStorage;\n\n    if (!ls) {\n      throw new Error('Could not find local storage.');\n    }\n\n    return ls;\n  }\n}\n\n/**\n * IdbStorage is an interface for simple storage of string key-value pairs built on {@link IdbKeyVal}\n *\n * It replaces {@link LocalStorage}\n * @see implements {@link AuthClientStorage}\n */\nexport class IdbStorage implements AuthClientStorage {\n  #options: DBCreateOptions;\n\n  /**\n   * @param options - DBCreateOptions\n   * @param options.dbName - name for the indexeddb database\n   * @param options.storeName - name for the indexeddb Data Store\n   * @param options.version - version of the database. Increment to safely upgrade\n   * @constructs an {@link IdbStorage}\n   * @example\n   * ```typescript\n   * const storage = new IdbStorage({ dbName: 'my-db', storeName: 'my-store', version: 2 });\n   * ```\n   */\n  constructor(options?: DBCreateOptions) {\n    this.#options = options ?? {};\n  }\n\n  // Initializes a KeyVal on first request\n  private initializedDb: IdbKeyVal | undefined;\n  get _db(): Promise\u003cIdbKeyVal\u003e {\n    return new Promise(resolve =\u003e {\n      if (this.initializedDb) {\n        resolve(this.initializedDb);\n        return;\n      }\n      IdbKeyVal.create(this.#options).then(db =\u003e {\n        this.initializedDb = db;\n        resolve(db);\n      });\n    });\n  }\n\n  public async get\u003cT = string\u003e(key: string): Promise\u003cT | null\u003e {\n    const db = await this._db;\n    return await db.get\u003cT\u003e(key);\n    // return (await db.get\u003cstring\u003e(key)) ?? null;\n  }\n\n  public async set\u003cT = string\u003e(key: string, value: T): Promise\u003cvoid\u003e {\n    const db = await this._db;\n    await db.set(key, value);\n  }\n\n  public async remove(key: string): Promise\u003cvoid\u003e {\n    const db = await this._db;\n    await db.remove(key);\n  }\n}\n"],"version":3}
