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AAC7B,EAAA,IAAI,CAAC,IAAA,EAAM,MAAM,IAAI,MAAM,yBAAyB,CAAA;AACpD,EAAA,MAAM,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,GAAG,CAAC,CAAA;AAC5D,EAAA,OAAO,IAAA,CAAK,MAAM,IAAI,CAAA;AACxB","file":"chunk-B7V3XD5F.mjs","sourcesContent":["/** Characters in the sign-in code the enclave mails. */\nexport const EMAIL_CODE_LENGTH = 9;\n\n/**\n * A code as the enclave compares it: lower-case, with whitespace and hyphens\n * removed, so a pasted `QPZ-RY9 X8G` is the code that was sent.\n */\nexport function normalizeEmailCode(raw: string): string {\n  return raw.toLowerCase().replace(/[\\s-]/g, \"\");\n}\n","import type { AuthProvider, Identity } from \"./AuthProvider\";\nimport {\n  createSocialRecoveryCredential,\n  ENCLAVE_EMAIL_ISSUER,\n  ENCLAVE_GITHUB_ISSUER,\n  ENCLAVE_TELEGRAM_ISSUER,\n  isSocialRecoveryIssuer,\n  type SocialRecoveryCredential,\n} from \"../recovery/SocialRecoveryCredential\";\nimport type { AttestationPolicy } from \"../recovery/SocialRecoveryClient\";\nimport { DEFAULT_SOCIAL_RECOVERY_ATTESTATION } from \"../recovery/attestationDefaults\";\nimport { fetchEnclaveRelease, runEnclaveJob, verifiedChannelKey } from \"../recovery/enclaveChannel\";\nimport { secureRandomBytes } from \"../crypto/encoding\";\nimport { normalizeEmailCode } from \"./emailCode\";\nimport {\n  assertLoginBinding,\n  loginNonce,\n  loginSecretFrom,\n  requiresLoginBinding,\n} from \"./loginBinding\";\n\nexport interface CavosAuthOptions {\n  /** Cavos backend base URL. Defaults to the hosted service (same as @cavos/react). */\n  backendUrl?: string;\n  /** App identifier registered with Cavos (the `appId` from the dashboard). */\n  appId?: string;\n  /**\n   * `false` keeps the signed-in identity in `sessionStorage`: it survives a\n   * reload and the OAuth redirect, and ends when the tab closes. Any identity\n   * already in `localStorage` is removed. Defaults to `true` (`localStorage`,\n   * signed in across tabs and restarts).\n   */\n  persistSession?: boolean;\n  /**\n   * The enclave measurements email login verifies before it sends a code to\n   * the enclave. Defaults to the enclave shipped with this package.\n   */\n  attestation?: AttestationPolicy;\n}\n\n/**\n * Hosted login (Privy-like) backed by the Cavos backend — same endpoints\n * `@cavos/react` uses for Google / Apple OAuth, plus an email code the recovery\n * enclave generates and verifies itself, and GitHub, which has no id_token of\n * its own: the enclave verifies the GitHub grant and signs one, as it does\n * for Telegram. Login only resolves a stable `userId` (the OAuth `sub` claim);\n * it never touches signing.\n * Feed the returned `Identity` to `Cavos.connect`.\n *\n *   const auth = new CavosAuth({ appId });\n *   // social: open the returned URL; user returns, then:\n *   const identity = await auth.handleCallback(window.location.search);\n *   // GitHub: the same, from getGitHubOAuthUrl; Telegram: from getTelegramOAuthUrl\n *   // or email OTP:\n *   await auth.sendOtp(email); const identity = await auth.verifyOtp(email, code);\n *   const cavos = await Cavos.connect({ network, appSalt, identity, paymasterApiKey });\n *\n * Device-signer model note: the backend issues a Cavos JWT (the same one react\n * uses for on-chain RSA verification). Here we only need the stable `sub` claim\n * from it — the RSA/JWKS/nonce machinery react relies on is dead weight for the\n * device model, because the device key (not the JWT) authorizes on-chain calls.\n * The provider token is kept in `sessionStorage` so a reconnect can still\n * authenticate to the wallet registry. The separate social-recovery credential\n * is NOT: it stays in memory, its SHA-256 fingerprint reserves exactly one\n * enclave session, and the token itself travels only through the attested\n * encrypted channel.\n */\nexport class CavosAuth implements AuthProvider {\n  private readonly backendUrl: string;\n  private readonly identityStorageKey: string;\n  private readonly authTokenKey: string;\n  private readonly loginSecretKey: string;\n  private readonly pkceKey: string;\n  /** The login secret, for a callback this same instance handles. */\n  private loginSecret: string | null = null;\n  /** The PKCE verifier of the GitHub or Telegram login in flight, for a callback this same instance handles. */\n  private pkceVerifier: string | null = null;\n  private last: Identity | null = null;\n  /** Fresh OIDC proof retained only in memory for an immediate TEE recovery.\n   * Never persisted to localStorage and never sent to the Cavos control plane\n   * outside the attested encrypted channel. */\n  private recoveryCredential: SocialRecoveryCredential | null = null;\n  /**\n   * The raw provider token from this session's login.\n   *\n   * Held in `sessionStorage`, not memory alone. The wallet registry\n   * authenticates with it, and `resolveAddress` fails closed rather than mint a\n   * second wallet for a user who already has one — so a token that does not\n   * survive a reload takes every reconnect down with it, and a device with no\n   * cached address can never connect at all.\n   *\n   * `sessionStorage` and not `localStorage`: it dies with the tab, is not shared\n   * across tabs, and never reaches another origin. The token is already inside\n   * this page's JavaScript either way; what changes is that it now outlives a\n   * navigation, which is exactly what the reconnect needs.\n   */\n  private authTokenValue: string | null = null;\n\n  constructor(private readonly opts: CavosAuthOptions = {}) {\n    this.backendUrl = opts.backendUrl ?? \"https://cavos.xyz\";\n    this.identityStorageKey = `cavos-kit:identity:${opts.appId ?? \"default\"}`;\n    this.authTokenKey = `cavos-kit:token:${opts.appId ?? \"default\"}`;\n    this.loginSecretKey = `cavos-kit:login-secret:${opts.appId ?? \"default\"}`;\n    this.pkceKey = `cavos-kit:pkce:${opts.appId ?? \"default\"}`;\n    if (opts.persistSession === false && typeof window !== \"undefined\") {\n      // An identity saved before the app turned persistence off would\n      // otherwise keep this browser signed in for good.\n      try {\n        window.localStorage.removeItem(this.identityStorageKey);\n      } catch {\n        /* nothing was stored if storage is unavailable */\n      }\n    }\n  }\n\n  /**\n   * Where the identity lives. Resolved on use, not in the constructor, because\n   * the provider also builds this during SSR, where there is no `window`.\n   */\n  private identityStorage(): Storage {\n    return this.opts.persistSession === false ? window.sessionStorage : window.localStorage;\n  }\n\n  /**\n   * Restore the last confirmed identity for this app on this browser. This is\n   * deliberately only public profile data — never an OAuth token or private\n   * key. The device signer remains protected in IndexedDB/WebCrypto.\n   */\n  restoreIdentity(): Identity | null {\n    if (typeof window === \"undefined\") return null;\n    try {\n      const value = this.identityStorage().getItem(this.identityStorageKey);\n      if (!value) return null;\n      const identity = JSON.parse(value) as Identity;\n      if (!identity.userId || typeof identity.userId !== \"string\") return null;\n      this.last = identity;\n      return identity;\n    } catch {\n      return null;\n    }\n  }\n\n  /** Clear the persisted identity on an explicit user logout. */\n  clearStoredIdentity(): void {\n    this.last = null;\n    this.recoveryCredential = null;\n    this.setAuthToken(null);\n    if (typeof window !== \"undefined\") {\n      try {\n        this.identityStorage().removeItem(this.identityStorageKey);\n      } catch {\n        /* nothing was stored if storage is unavailable */\n      }\n    }\n  }\n\n  /** Redirect URL for Google login (open it; user returns to your redirectUri). */\n  async getGoogleOAuthUrl(redirectUri?: string): Promise<string> {\n    return this.oauthUrl(\"google\", redirectUri);\n  }\n\n  /** Redirect URL for Apple login. */\n  async getAppleOAuthUrl(redirectUri?: string): Promise<string> {\n    return this.oauthUrl(\"apple\", redirectUri);\n  }\n\n  /**\n   * Redirect URL for GitHub login.\n   *\n   * GitHub issues no id_token, so the enclave verifies the sign-in and signs\n   * one itself. The URL is built by the backend, and a code issued without our\n   * PKCE challenge could be redeemed without this browser, so a URL that does\n   * not carry the challenge this login made is refused here.\n   */\n  async getGitHubOAuthUrl(redirectUri?: string): Promise<string> {\n    if (typeof window === \"undefined\") throw new Error(\"kit/auth: OAuth requires a browser\");\n    const appId = this.requireAppId();\n    this.startLogin();\n    const verifier = this.startPkce();\n    const challenge = loginNonce(verifier);\n    const params = new URLSearchParams({\n      code_challenge: challenge,\n      redirect_uri: redirectUri ?? window.location.href,\n      app_id: appId,\n    });\n    const { url } = await this.get(`/api/oauth/v2/github?${params}`);\n    if (!isGitHubAuthorizeUrl(url, challenge)) {\n      throw new Error(\"kit/auth: the GitHub sign-in URL is not the one this login asked for\");\n    }\n    return url;\n  }\n\n  /**\n   * Redirect URL for Telegram login.\n   *\n   * Telegram issues an id_token the enclave re-signs after verifying the\n   * sign-in. The backend builds the URL, and the challenge, nonce and scope are\n   * what bind the code to this browser and app, so a URL that does not carry\n   * exactly what this login asked for is refused here.\n   */\n  async getTelegramOAuthUrl(redirectUri?: string): Promise<string> {\n    if (typeof window === \"undefined\") throw new Error(\"kit/auth: OAuth requires a browser\");\n    const appId = this.requireAppId();\n    const clientNonce = this.startLogin();\n    const verifier = this.startPkce();\n    const challenge = loginNonce(verifier);\n    const params = new URLSearchParams({\n      code_challenge: challenge,\n      redirect_uri: redirectUri ?? window.location.href,\n      app_id: appId,\n      nonce: clientNonce,\n    });\n    const { url } = await this.get(`/api/oauth/v2/telegram?${params}`);\n    if (!isTelegramAuthorizeUrl(url, challenge, `${appId}.${clientNonce}`)) {\n      throw new Error(\"kit/auth: the Telegram sign-in URL is not the one this login asked for\");\n    }\n    return url;\n  }\n\n  private async oauthUrl(provider: \"google\" | \"apple\", redirectUri?: string): Promise<string> {\n    if (typeof window === \"undefined\") throw new Error(\"kit/auth: OAuth requires a browser\");\n    const params = new URLSearchParams({\n      nonce: this.startLogin(),\n      redirect_uri: redirectUri ?? window.location.href,\n      ...(this.opts.appId ? { app_id: this.opts.appId } : {}),\n    });\n    const { url } = await this.get(`/api/oauth/v2/${provider}?${params}`);\n    return url;\n  }\n\n  /**\n   * Resolve identity from an OAuth callback. Current callbacks carry only a\n   * short-lived one-time code; legacy raw auth data remains readable so apps can\n   * roll forward without losing an already-open callback.\n   */\n  async handleCallback(authDataOrSearch: string, redirectUri?: string): Promise<Identity> {\n    const callbackCode = extractCallbackCode(authDataOrSearch);\n    if (callbackCode) {\n      const callbackRedirectUri = redirectUri ?? currentCleanCallbackUrl();\n      if (!callbackRedirectUri) throw new Error(\"kit/auth: callback redirect URI is required\");\n      const result = await this.post(\"/api/oauth/callback/exchange\", {\n        code: callbackCode,\n        app_id: this.opts.appId,\n        redirect_uri: callbackRedirectUri,\n      });\n      if (typeof result.github_grant === \"string\") {\n        return this.githubIdentity(result.github_grant);\n      }\n      if (typeof result.telegram_grant === \"string\") {\n        return this.telegramIdentity(result.telegram_grant);\n      }\n      return this.identityFromAuthData(JSON.stringify(result), \"oauth\");\n    }\n    const authData = extractAuthData(authDataOrSearch);\n    return this.identityFromAuthData(authData, \"oauth\");\n  }\n\n  /**\n   * Email a 9-character sign-in code. The code is generated and mailed by the\n   * recovery enclave, so the Cavos control plane never sees it.\n   */\n  async sendOtp(email: string): Promise<void> {\n    await this.enclavePost(\"/api/oauth/email/code\", {\n      app_id: this.requireAppId(),\n      email: normalizeEmail(email),\n    });\n  }\n\n  /**\n   * Verify the emailed code inside the attested enclave and resolve the\n   * identity. The enclave answers with its own signed token, bound to a secret\n   * created here, and that token is used exactly like a Google id_token.\n   */\n  async verifyOtp(email: string, code: string): Promise<Identity> {\n    const address = normalizeEmail(email);\n    const secret = loginSecretFrom(secureRandomBytes(32));\n    const idToken = await this.enclaveLogin(\n      {\n        action: \"verify_email\",\n        email: address,\n        code: normalizeEmailCode(code),\n        client_nonce: loginNonce(secret),\n      },\n      \"/api/oauth/email/verify\",\n      {},\n      \"email_verified\",\n      \"kit/auth: the enclave did not verify this email\",\n    );\n    if (parseJwt(idToken).iss !== ENCLAVE_EMAIL_ISSUER) {\n      throw new Error(\"kit/auth: the email token was not issued by the enclave\");\n    }\n    return this.identityFromAuthData(idToken, \"email\", address, secret);\n  }\n\n  /**\n   * Redeem a GitHub grant inside the attested enclave. The grant is only\n   * useful with the PKCE verifier and login secret this browser kept, and the\n   * token the enclave signs is bound to that secret exactly like a Google one.\n   */\n  private async githubIdentity(githubGrant: string): Promise<Identity> {\n    const secret = this.takeLoginSecret();\n    const verifier = this.takePkceVerifier();\n    if (!secret || !verifier) {\n      throw new Error(\n        \"kit/auth: this sign-in did not start here, or the browser could not keep its state. Sign in again.\",\n      );\n    }\n    const idToken = await this.enclaveLogin(\n      { action: \"verify_github\", code_verifier: verifier, client_nonce: loginNonce(secret) },\n      \"/api/oauth/github/verify\",\n      { github_grant: githubGrant },\n      \"github_verified\",\n      \"kit/auth: the enclave did not verify this GitHub sign-in\",\n    );\n    if (parseJwt(idToken).iss !== ENCLAVE_GITHUB_ISSUER) {\n      throw new Error(\"kit/auth: the GitHub token was not issued by the enclave\");\n    }\n    return this.identityFromAuthData(idToken, \"github\", undefined, secret);\n  }\n\n  /**\n   * Redeem a Telegram grant inside the attested enclave. Unlike GitHub, the\n   * enclave is given the login secret itself and derives the nonce from it, so\n   * a stolen code is useless without the secret this browser kept.\n   */\n  private async telegramIdentity(telegramGrant: string): Promise<Identity> {\n    const secret = this.takeLoginSecret();\n    const verifier = this.takePkceVerifier();\n    if (!secret || !verifier) {\n      throw new Error(\n        \"kit/auth: this sign-in did not start here, or the browser could not keep its state. Sign in again.\",\n      );\n    }\n    const idToken = await this.enclaveLogin(\n      { action: \"verify_telegram\", code_verifier: verifier, login_secret: secret },\n      \"/api/oauth/telegram/verify\",\n      { telegram_grant: telegramGrant },\n      \"telegram_verified\",\n      \"kit/auth: the enclave did not verify this Telegram sign-in\",\n    );\n    if (parseJwt(idToken).iss !== ENCLAVE_TELEGRAM_ISSUER) {\n      throw new Error(\"kit/auth: the Telegram token was not issued by the enclave\");\n    }\n    return this.identityFromAuthData(idToken, \"telegram\", undefined, secret);\n  }\n\n  /**\n   * Open an attested enclave session, run one encrypted login job through it\n   * and return the id_token the enclave signed.\n   */\n  private async enclaveLogin(\n    job: Record<string, unknown>,\n    verifyPath: string,\n    extraBody: Record<string, unknown>,\n    expectedResult: string,\n    failure: string,\n  ): Promise<string> {\n    const session = await this.enclavePost(\"/api/oauth/email/session\", { app_id: this.requireAppId() });\n    const sessionId: unknown = session?.session_id;\n    if (typeof sessionId !== \"string\") {\n      throw new Error(\"kit/auth: the enclave session carried no id\");\n    }\n    const channelKey = await verifiedChannelKey(\n      sessionId,\n      session.attestation_document_b64,\n      this.opts.attestation ?? DEFAULT_SOCIAL_RECOVERY_ATTESTATION,\n      (pcr0Hex) => fetchEnclaveRelease(`${this.backendUrl}/api/enclave/releases/${pcr0Hex}`),\n    );\n    const result = await runEnclaveJob<{ result?: string; id_token?: unknown }>(\n      sessionId,\n      channelKey,\n      job,\n      (sealed) => this.enclavePost(verifyPath, { session_id: sessionId, job: sealed, ...extraBody }),\n    );\n    if (result.result !== expectedResult || typeof result.id_token !== \"string\") {\n      throw new Error(failure);\n    }\n    return result.id_token;\n  }\n\n  /** AuthProvider: returns the identity resolved by the last login step. */\n  async authenticate(): Promise<Identity> {\n    if (!this.last) throw new Error(\"kit/auth: no identity yet — complete a login first\");\n    return this.last;\n  }\n\n  /**\n   * Return the fresh social credential the recovery enclave requires.\n   * Callers should use it immediately; it is intentionally not restorable\n   * after a refresh. A new social login is required for each recovery attempt.\n   */\n  getSocialRecoveryCredential(): SocialRecoveryCredential {\n    if (!this.recoveryCredential) {\n      throw new Error(\"kit/auth: complete a fresh social login before recovery\");\n    }\n    return this.recoveryCredential;\n  }\n\n  /**\n   * Take the fresh social credential exactly once. A provider token is bound to\n   * one enclave session, so retaining it after recovery only permits accidental\n   * replay attempts during the wallet's post-recovery reconnect.\n   */\n  /**\n   * Whether a login proof is available without taking it.\n   *\n   * The UI has to choose how a device gets authorized before anything runs, and\n   * that choice depends on whether the enclave can be used at all. Asking with\n   * `consume` would spend the proof to find out.\n   */\n  hasSocialRecoveryCredential(): boolean {\n    return this.recoveryCredential !== null;\n  }\n\n  consumeSocialRecoveryCredential(): SocialRecoveryCredential {\n    // Kept for the session rather than dropped on first use. A session holds a\n    // wallet on every configured chain and each needs its own enrolment, so\n    // spending the credential on the first one left the rest unprotected —\n    // with no error, because there was simply nothing left to try with.\n    //\n    // Replay is the control plane's to refuse, and it does: one session per\n    // credential per wallet. It cannot be reused against a wallet it has\n    // already enrolled.\n    return this.getSocialRecoveryCredential();\n  }\n\n  /**\n   * Accept a provider id_token obtained by the host's own authentication.\n   *\n   * Apps that sign users in themselves already hold a Google or Apple token;\n   * this lets social recovery use it instead of sending the user through a\n   * second sign-in. Nothing here grants trust: the token is checked inside the\n   * enclave against the issuer and audience sealed for the app, and only Google\n   * or Apple can produce a token that passes.\n   *\n   * Rejected up front if it was not issued by a provider the enclave accepts,\n   * so a mistake surfaces here rather than as an opaque enclave failure.\n   *\n   * The token must be recent — the enclave requires the authentication to be\n   * within five minutes — so pass one straight from a sign-in, not a stored one.\n   */\n  useExternalSocialRecoveryToken(idToken: string): void {\n    const claims = parseJwt(idToken);\n    if (!isSocialRecoveryIssuer(claims?.iss)) {\n      throw new Error(\n        `kit/auth: id_token issuer ${JSON.stringify(claims?.iss ?? null)} cannot be used for social recovery. ` +\n          \"Pass the raw Google or Apple id_token from your login, not your own session JWT.\",\n      );\n    }\n    this.recoveryCredential = createSocialRecoveryCredential(idToken);\n  }\n\n  // ── internals ──────────────────────────────────────────────────────────────\n\n  /**\n   * Build an `Identity` from whatever the backend returned. The Cavos backend\n   * wraps the user id in a JWT (its `sub` claim); for the device model we only\n   * need that stable id — the signature is never checked on-chain.\n   */\n  private async identityFromAuthData(\n    authData: string,\n    provider: string,\n    emailOverride?: string,\n    presentedSecret?: string,\n  ): Promise<Identity> {\n    let token = authData;\n    try {\n      const parsed = JSON.parse(authData);\n      token = parsed.id_token ?? parsed.jwt ?? parsed.token ?? authData;\n    } catch {\n      // raw JWT\n    }\n    const claims = parseJwt(token);\n    let loginSecret: string | undefined;\n    if (requiresLoginBinding(claims.iss)) {\n      const kept = presentedSecret ?? this.takeLoginSecret();\n      assertLoginBinding(claims.nonce, kept);\n      loginSecret = kept;\n    }\n    this.setAuthToken(token);\n    this.recoveryCredential = isSocialRecoveryIssuer(claims.iss)\n      ? createSocialRecoveryCredential(token, loginSecret)\n      : null;\n    return this.remember({\n      userId: String(claims.sub ?? claims.user_id ?? claims.uid),\n      email: claims.email ?? emailOverride,\n      name: claims.name,\n      provider: providerFromClaims(claims, provider),\n    });\n  }\n\n  /**\n   * The provider id_token from this session's login, for the wallet registry.\n   * Null on a page reload that restored the identity from storage but not\n   * the token — the address cache covers that device; a brand-new device has\n   * just logged in and therefore has one.\n   */\n  getAuthToken(): string | null {\n    if (this.authTokenValue) return this.authTokenValue;\n    try {\n      this.authTokenValue = window.sessionStorage.getItem(this.authTokenKey);\n    } catch {\n      // No session storage (private mode, blocked): memory only, as before.\n    }\n    return this.authTokenValue;\n  }\n\n  private setAuthToken(token: string | null): void {\n    this.authTokenValue = token;\n    if (typeof window === \"undefined\") return;\n    try {\n      if (token) window.sessionStorage.setItem(this.authTokenKey, token);\n      else window.sessionStorage.removeItem(this.authTokenKey);\n    } catch {\n      /* memory-only fallback; a reconnect will 401 as it did before */\n    }\n  }\n\n  /**\n   * Begin a Google or Apple login: keep a fresh secret for the trip to the\n   * provider and back, and return the nonce that commits to it.\n   *\n   * `sessionStorage` because the login navigates away and the secret has to be\n   * here when the callback lands; it is removed as soon as it is read. Where\n   * storage is unavailable only this instance remembers it, so a login that\n   * reloads the page is refused at the callback — the safe outcome.\n   */\n  private startLogin(): string {\n    const secret = loginSecretFrom(secureRandomBytes(32));\n    this.loginSecret = secret;\n    try {\n      window.sessionStorage.setItem(this.loginSecretKey, secret);\n    } catch {\n      /* memory only */\n    }\n    return loginNonce(secret);\n  }\n\n  /** Begin the PKCE half of a GitHub or Telegram login: keep a fresh verifier and return it. */\n  private startPkce(): string {\n    const verifier = loginSecretFrom(secureRandomBytes(32));\n    try {\n      window.sessionStorage.setItem(this.pkceKey, verifier);\n    } catch {\n      this.pkceVerifier = verifier;\n    }\n    return verifier;\n  }\n\n  /** The PKCE verifier of the login in flight, taken exactly once. */\n  private takePkceVerifier(): string | null {\n    const kept = this.pkceVerifier;\n    this.pkceVerifier = null;\n    try {\n      const stored = window.sessionStorage.getItem(this.pkceKey);\n      window.sessionStorage.removeItem(this.pkceKey);\n      return stored ?? kept;\n    } catch {\n      return kept;\n    }\n  }\n\n  /** The secret of the login in flight, taken exactly once. */\n  private takeLoginSecret(): string | null {\n    let secret = this.loginSecret;\n    this.loginSecret = null;\n    try {\n      secret = window.sessionStorage.getItem(this.loginSecretKey) ?? secret;\n      window.sessionStorage.removeItem(this.loginSecretKey);\n    } catch {\n      /* memory only */\n    }\n    return secret;\n  }\n\n  private remember(id: Identity): Identity {\n    this.last = id;\n    if (typeof window !== \"undefined\") {\n      try {\n        this.identityStorage().setItem(this.identityStorageKey, JSON.stringify(id));\n      } catch {\n        // Private mode and blocked site data throw here. This store only saves\n        // a returning user from signing in again; an unwritable one must not\n        // take down the login that just succeeded.\n      }\n    }\n    return id;\n  }\n\n  private async get(path: string): Promise<any> {\n    const r = await fetch(`${this.backendUrl}${path}`);\n    if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);\n    return r.json();\n  }\n\n  private requireAppId(): string {\n    if (!this.opts.appId) throw new Error(\"kit/auth: this sign-in needs an appId\");\n    return this.opts.appId;\n  }\n\n  private async enclavePost(path: string, body: unknown): Promise<any> {\n    const r = await fetch(`${this.backendUrl}${path}`, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify(body),\n    });\n    if (r.ok) return r.json();\n    const text = await r.text().catch(() => \"\");\n    let code: unknown;\n    try {\n      code = JSON.parse(text)?.error;\n    } catch {\n      code = undefined;\n    }\n    const known = typeof code === \"string\" ? ENCLAVE_LOGIN_ERRORS[code] : undefined;\n    throw new Error(known ?? `kit/auth: ${path} -> ${r.status} ${text}`);\n  }\n\n  private async post(path: string, body: unknown): Promise<any> {\n    const r = await fetch(`${this.backendUrl}${path}`, {\n      method: \"POST\",\n      headers: { \"Content-Type\": \"application/json\" },\n      body: JSON.stringify(body),\n    });\n    if (!r.ok) throw new Error(`kit/auth: ${path} -> ${r.status} ${await r.text()}`);\n    return r.json();\n  }\n}\n\nconst ENCLAVE_LOGIN_ERRORS: Record<string, string> = {\n  invalid_request: \"Enter a valid email address.\",\n  app_not_found: \"kit/auth: this app is not registered with Cavos.\",\n  email_undeliverable: \"This email provider is not supported yet.\",\n  code_cooldown: \"A code was just sent to this address. Wait a minute before requesting another.\",\n  rate_limited: \"Too many attempts. Try again in a few minutes.\",\n  email_unavailable: \"Email sign-in is unavailable right now. Try again later.\",\n  enclave_unavailable: \"Sign-in is unavailable right now. Try again later.\",\n  code_rejected: \"That code is wrong or has expired. Request a new one.\",\n  github_rejected: \"GitHub did not accept this sign-in. Try again.\",\n  telegram_rejected: \"Telegram did not accept this sign-in. Try again.\",\n  invalid_grant: \"This sign-in expired. Sign in again.\",\n};\n\n/** Whether `url` is GitHub's authorize page, asked for with exactly this PKCE challenge. */\nfunction isGitHubAuthorizeUrl(url: unknown, challenge: string): boolean {\n  if (typeof url !== \"string\") return false;\n  try {\n    const parsed = new URL(url);\n    return (\n      parsed.protocol === \"https:\" &&\n      parsed.host === \"github.com\" &&\n      parsed.pathname === \"/login/oauth/authorize\" &&\n      parsed.searchParams.get(\"code_challenge\") === challenge &&\n      parsed.searchParams.get(\"code_challenge_method\") === \"S256\"\n    );\n  } catch {\n    return false;\n  }\n}\n\n/** Whether `url` is Telegram's authorize page, asked for with exactly this challenge, nonce and scope. */\nfunction isTelegramAuthorizeUrl(url: unknown, challenge: string, expectedNonce: string): boolean {\n  if (typeof url !== \"string\") return false;\n  try {\n    const parsed = new URL(url);\n    return (\n      parsed.protocol === \"https:\" &&\n      parsed.host === \"oauth.telegram.org\" &&\n      parsed.pathname === \"/auth\" &&\n      parsed.searchParams.get(\"response_type\") === \"code\" &&\n      parsed.searchParams.get(\"code_challenge\") === challenge &&\n      parsed.searchParams.get(\"code_challenge_method\") === \"S256\" &&\n      parsed.searchParams.get(\"nonce\") === expectedNonce &&\n      parsed.searchParams.get(\"scope\") === \"openid profile\"\n    );\n  } catch {\n    return false;\n  }\n}\n\nfunction normalizeEmail(email: string): string {\n  return email.trim().toLowerCase();\n}\n\n/** Pull the `auth_data` / `zk_auth_data` value out of a callback string. */\nfunction extractAuthData(input: string): string {\n  if (input.includes(\"auth_data=\") || input.includes(\"zk_auth_data=\")) {\n    const params = new URLSearchParams(input.startsWith(\"?\") ? input : `?${input}`);\n    return params.get(\"auth_data\") ?? params.get(\"zk_auth_data\") ?? input;\n  }\n  return input;\n}\n\nfunction extractCallbackCode(input: string): string | null {\n  if (/^[A-Za-z0-9_-]{43}$/.test(input)) return input;\n  try {\n    const params = input.includes('://')\n      ? new URL(input).searchParams\n      : new URLSearchParams(input.startsWith('?') ? input : `?${input}`);\n    return params.get('cavos_auth_code');\n  } catch {\n    return null;\n  }\n}\n\nfunction currentCleanCallbackUrl(): string | null {\n  if (typeof window === 'undefined') return null;\n  const url = new URL(window.location.href);\n  url.searchParams.delete('cavos_auth_code');\n  url.searchParams.delete('auth_data');\n  url.searchParams.delete('zk_auth_data');\n  return url.toString();\n}\n\n/** Decode a JWT payload (no verification — the backend already validated it). */\n/**\n * Which provider actually signed this token.\n *\n * A raw Google or Apple id_token carries no `provider` claim, so the OAuth\n * path would fall through to the literal \"oauth\" — true, and useless to\n * anything that wants to name the provider back to the user. The issuer is the\n * authoritative answer and is always there.\n */\nfunction providerFromClaims(claims: any, fallback: string): string {\n  switch (claims?.iss) {\n    case \"https://accounts.google.com\":\n      return \"google\";\n    case \"https://appleid.apple.com\":\n      return \"apple\";\n    case ENCLAVE_EMAIL_ISSUER:\n      return \"email\";\n    case ENCLAVE_GITHUB_ISSUER:\n      return \"github\";\n    case ENCLAVE_TELEGRAM_ISSUER:\n      return \"telegram\";\n    default:\n      return claims?.provider ?? fallback;\n  }\n}\n\nfunction parseJwt(jwt: string): any {\n  const part = jwt.split(\".\")[1];\n  if (!part) throw new Error(\"kit/auth: malformed JWT\");\n  const json = atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n  return JSON.parse(json);\n}\n"]}