@bounded-sh/client 0.0.34 → 0.0.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -3407,7 +3407,7 @@ const IDB_STORE = 'keys';
3407
3407
  const IDB_KEY = 'ed25519';
3408
3408
  const GUEST_KEY_REQUIREMENT = 'Guest auth requires non-extractable WebCrypto Ed25519 keys persisted in IndexedDB; ' +
3409
3409
  'stored-secret guest credentials are disabled.';
3410
- function toBase64(bytes) {
3410
+ function toBase64$1(bytes) {
3411
3411
  let bin = '';
3412
3412
  for (let i = 0; i < bytes.length; i++)
3413
3413
  bin += String.fromCharCode(bytes[i]);
@@ -3471,7 +3471,7 @@ async function webCryptoKey() {
3471
3471
  async sign(message) {
3472
3472
  const data = new TextEncoder().encode(message);
3473
3473
  const sig = new Uint8Array(await s.sign({ name: 'Ed25519' }, pair.privateKey, data));
3474
- return toBase64(sig);
3474
+ return toBase64$1(sig);
3475
3475
  },
3476
3476
  };
3477
3477
  }
@@ -3574,14 +3574,221 @@ class GuestAuthProvider {
3574
3574
  }
3575
3575
  }
3576
3576
 
3577
+ var bufferExports = requireBuffer();
3578
+
3579
+ // crossmint-signer-bridge.ts — routes embedded-wallet signing through the
3580
+ // Bounded-owned signer popup (auth.bounded.sh/wallet/signer).
3581
+ //
3582
+ // Slice-1 attached a non-custodial Crossmint smart wallet to email logins and
3583
+ // populated `@user.address`. This bridge is the slice-2 counterpart: a user
3584
+ // whose address came from `auth.wallets` can APPROVE transactions with that
3585
+ // wallet from ANY app, non-custodially, by having the Crossmint client SDK run
3586
+ // ONLY on the Bounded signer page (one whitelisted origin) and talking to it via
3587
+ // postMessage.
3588
+ //
3589
+ // SEMANTICS (Crossmint Solana smart wallets): these wallets cannot produce raw
3590
+ // detached signatures — there is no signMessage and no sign-without-submit. The
3591
+ // only honest primitive is EXECUTION (sign + submit) via the wallet's email-OTP
3592
+ // authorization. So this bridge implements `signAndSubmitTransaction` and a
3593
+ // token-send; `signMessage` / `signTransaction` throw a clear unsupported error.
3594
+ const EMBEDDED_WALLET_UNSUPPORTED = 'Unsupported for embedded smart wallets — Crossmint Solana smart wallets sign ' +
3595
+ 'and submit atomically. Use signAndSubmitTransaction() (or bounded.sendWalletToken) ' +
3596
+ 'instead of signMessage/signTransaction.';
3597
+ const NO_EMBEDDED_WALLET = 'This login has no embedded wallet. Enable `"auth": { "wallets": true }` in ' +
3598
+ 'the app policy so email logins get a non-custodial wallet (@user.address), ' +
3599
+ 'then sign from a user gesture.';
3600
+ function hasDOM$1() {
3601
+ return typeof window !== 'undefined' && typeof document !== 'undefined';
3602
+ }
3603
+ function decodeJwt$2(token) {
3604
+ try {
3605
+ let b64 = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/');
3606
+ const pad = b64.length % 4;
3607
+ if (pad === 2)
3608
+ b64 += '==';
3609
+ else if (pad === 3)
3610
+ b64 += '=';
3611
+ return JSON.parse(bufferExports.Buffer.from(b64, 'base64').toString('utf8'));
3612
+ }
3613
+ catch (_a) {
3614
+ return {};
3615
+ }
3616
+ }
3617
+ // Pull the embedded-wallet identity out of the active session's id token.
3618
+ // Returns null when this session has no wallet (so callers can throw the
3619
+ // informative NO_EMBEDDED_WALLET error).
3620
+ function walletClaimsFromSession() {
3621
+ let idToken = null;
3622
+ try {
3623
+ idToken = getActiveSessionManager().getIdToken();
3624
+ }
3625
+ catch (_a) {
3626
+ idToken = null;
3627
+ }
3628
+ if (!idToken)
3629
+ return null;
3630
+ const c = decodeJwt$2(idToken);
3631
+ const address = c['custom:walletAddress'];
3632
+ const email = c['email'];
3633
+ if (typeof address !== 'string' || !address)
3634
+ return null;
3635
+ if (typeof email !== 'string' || !email)
3636
+ return null;
3637
+ const envClaim = c['custom:walletEnvironment'];
3638
+ const environment = envClaim === 'staging' || envClaim === 'production' ? envClaim : undefined;
3639
+ return { email, address, environment };
3640
+ }
3641
+ async function signerPageUrl() {
3642
+ const cfg = await getConfig();
3643
+ const base = (cfg.humanAuthApiUrl || 'https://auth.bounded.sh').replace(/\/$/, '');
3644
+ return { url: `${base}/wallet/signer`, origin: new URL(base).origin };
3645
+ }
3646
+ let requestSeq = 0;
3647
+ /**
3648
+ * Open the Bounded signer popup, send `action` to it, and resolve with the
3649
+ * submitted transaction result. Must be called from a USER GESTURE (click/tap) or
3650
+ * the browser will block the popup — in which case this rejects with a clear
3651
+ * "Popup blocked" error telling the app to call from a user gesture.
3652
+ *
3653
+ * Non-custodial: the popup gates signing behind an email OTP delivered to the
3654
+ * wallet's owner, and validates that the wallet address matches the account.
3655
+ */
3656
+ async function signViaSignerPopup(action) {
3657
+ if (!hasDOM$1()) {
3658
+ throw new Error('Embedded-wallet signing is only available in the browser (popup-based).');
3659
+ }
3660
+ const claims = walletClaimsFromSession();
3661
+ if (!claims)
3662
+ throw new Error(NO_EMBEDDED_WALLET);
3663
+ const { url, origin: signerOrigin } = await signerPageUrl();
3664
+ const requestId = `bsign_${Date.now()}_${++requestSeq}`;
3665
+ // Centered popup, sized for the OTP form (matches the OIDC login popup shape).
3666
+ const w = 420, h = 600;
3667
+ const left = window.screenX + Math.max(0, (window.outerWidth - w) / 2);
3668
+ const top = window.screenY + Math.max(0, (window.outerHeight - h) / 2);
3669
+ const popup = window.open(url, 'bounded-wallet-signer', `width=${w},height=${h},left=${left},top=${top}`);
3670
+ if (!popup) {
3671
+ throw new Error('Popup blocked — call signAndSubmitTransaction() from a user gesture (e.g. a click handler) so the wallet approval window can open.');
3672
+ }
3673
+ const request = {
3674
+ type: 'bounded:sign',
3675
+ requestId,
3676
+ environment: claims.environment, // may be undefined → page auto-detects
3677
+ email: claims.email,
3678
+ address: claims.address,
3679
+ action,
3680
+ };
3681
+ return await new Promise((resolve, reject) => {
3682
+ let settled = false;
3683
+ let closeTimer;
3684
+ let sentRequest = false;
3685
+ const cleanup = () => {
3686
+ settled = true;
3687
+ window.removeEventListener('message', onMsg);
3688
+ if (closeTimer)
3689
+ clearInterval(closeTimer);
3690
+ };
3691
+ const sendRequest = () => {
3692
+ if (sentRequest)
3693
+ return;
3694
+ sentRequest = true;
3695
+ try {
3696
+ popup.postMessage(request, signerOrigin);
3697
+ }
3698
+ catch ( /* popup gone */_a) { /* popup gone */ }
3699
+ };
3700
+ const onMsg = (ev) => {
3701
+ if (ev.origin !== signerOrigin)
3702
+ return; // only trust the signer page origin
3703
+ const d = ev.data;
3704
+ if (!d || typeof d !== 'object')
3705
+ return;
3706
+ if (d.type === 'bounded:signer:ready') {
3707
+ sendRequest();
3708
+ return;
3709
+ }
3710
+ if (d.type === 'bounded:signer:result' && d.requestId === requestId) {
3711
+ cleanup();
3712
+ try {
3713
+ popup.close();
3714
+ }
3715
+ catch ( /* ignore */_a) { /* ignore */ }
3716
+ if (d.ok)
3717
+ resolve({ hash: d.hash, explorerLink: d.explorerLink, transactionId: d.transactionId });
3718
+ else
3719
+ reject(new Error(String(d.error || 'Wallet signing failed')));
3720
+ }
3721
+ };
3722
+ window.addEventListener('message', onMsg);
3723
+ // Fallback: if the ready ping was missed (fast load / focus race), push the
3724
+ // request shortly after opening. The page ignores it until a bounded:sign
3725
+ // arrives and only acts on the first one, so a duplicate is harmless.
3726
+ setTimeout(sendRequest, 1200);
3727
+ // If the user closes the popup before completing, reject (unless a result
3728
+ // just arrived — give any in-flight message a beat to settle first).
3729
+ closeTimer = setInterval(() => {
3730
+ if (popup.closed) {
3731
+ clearInterval(closeTimer);
3732
+ setTimeout(() => { if (!settled) {
3733
+ cleanup();
3734
+ reject(new Error('Wallet approval window was closed before signing completed.'));
3735
+ } }, 400);
3736
+ }
3737
+ }, 500);
3738
+ // Overall safety timeout (OTP + signing). Generous — the user may take a
3739
+ // while to fetch the code from their email.
3740
+ setTimeout(() => { if (!settled) {
3741
+ cleanup();
3742
+ try {
3743
+ popup.close();
3744
+ }
3745
+ catch ( /* ignore */_a) { /* ignore */ }
3746
+ reject(new Error('Wallet approval timed out.'));
3747
+ } }, 5 * 60 * 1000);
3748
+ });
3749
+ }
3750
+ function toBase64(bytes) {
3751
+ return bufferExports.Buffer.from(bytes).toString('base64');
3752
+ }
3753
+ // Serialize a legacy or versioned Solana transaction to base64 for the signer
3754
+ // page. We do NOT require existing signatures (the smart wallet signs on the
3755
+ // page); Crossmint extracts the instructions and wraps them for the smart wallet.
3756
+ function serializeTransaction(transaction) {
3757
+ const isLegacy = 'recentBlockhash' in transaction &&
3758
+ !('message' in transaction && 'staticAccountKeys' in transaction.message);
3759
+ const bytes = isLegacy
3760
+ ? transaction.serialize({ requireAllSignatures: false, verifySignatures: false })
3761
+ : transaction.serialize();
3762
+ return toBase64(bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes));
3763
+ }
3764
+ /**
3765
+ * Whether the active session carries an embedded wallet (so the provider should
3766
+ * route signing through the popup rather than throw "no wallet").
3767
+ */
3768
+ function hasEmbeddedWallet() {
3769
+ return walletClaimsFromSession() != null;
3770
+ }
3771
+ /** signAndSubmitTransaction for embedded wallets: serialize + route through the
3772
+ * signer popup, resolve with the on-chain transaction signature/hash. */
3773
+ async function embeddedSignAndSubmit(transaction) {
3774
+ const serializedTransaction = serializeTransaction(transaction);
3775
+ const result = await signViaSignerPopup({ kind: 'transaction', serializedTransaction });
3776
+ const hash = result.hash || result.transactionId;
3777
+ if (!hash)
3778
+ throw new Error('Signer returned no transaction hash.');
3779
+ return hash;
3780
+ }
3781
+
3577
3782
  // Web uses localStorage (WebSessionManager); React Native uses the configured
3578
3783
  // ReactNativeSessionManager. getActiveSessionManager() picks the right one by
3579
3784
  // whether the RN manager was configured (NOT `typeof window`, which is truthy on
3580
3785
  // RN too and would wrongly route to localStorage). Same selector the core
3581
3786
  // request path uses, so hosted Bounded Auth sessions persist + authenticate on BOTH.
3582
3787
  const sessionManager$1 = getActiveSessionManager;
3583
- const NO_WALLET = 'Email login is offchain — it has no Solana wallet and cannot sign/submit ' +
3584
- 'transactions. Use a wallet provider for onchain actions, or link a wallet later.';
3788
+ const NO_WALLET = 'Email login has no embedded wallet. Enable `"auth": { "wallets": true }` in ' +
3789
+ 'the app policy so email logins get a non-custodial Crossmint wallet ' +
3790
+ '(@user.address), then sign from a user gesture. Otherwise use a wallet ' +
3791
+ 'provider (e.g. Phantom) for onchain actions.';
3585
3792
  // ---------------------------------------------------------------------------
3586
3793
  // token / session helpers
3587
3794
  // ---------------------------------------------------------------------------
@@ -3631,10 +3838,23 @@ class EmailAuthProvider {
3631
3838
  sessionManager$1().clearSession();
3632
3839
  setCurrentUser(null);
3633
3840
  }
3634
- async signMessage(_message) { throw new Error(NO_WALLET); }
3841
+ // Crossmint Solana smart wallets sign+submit atomically and cannot produce a
3842
+ // raw signature — signMessage/signTransaction are structurally unsupported
3843
+ // (throw the clear "use signAndSubmitTransaction" error when a wallet exists;
3844
+ // the no-wallet error otherwise). signAndSubmitTransaction routes through the
3845
+ // Bounded signer popup for wallets-enabled email logins.
3846
+ async signMessage(_message) {
3847
+ throw new Error(hasEmbeddedWallet() ? EMBEDDED_WALLET_UNSUPPORTED : NO_WALLET);
3848
+ }
3635
3849
  async runTransaction(_evm, _sol, _options) { throw new Error(NO_WALLET); }
3636
- async signTransaction(_t) { throw new Error(NO_WALLET); }
3637
- async signAndSubmitTransaction() { throw new Error(NO_WALLET); }
3850
+ async signTransaction(_t) {
3851
+ throw new Error(hasEmbeddedWallet() ? EMBEDDED_WALLET_UNSUPPORTED : NO_WALLET);
3852
+ }
3853
+ async signAndSubmitTransaction(transaction, _feePayer) {
3854
+ if (!hasEmbeddedWallet())
3855
+ throw new Error(NO_WALLET);
3856
+ return embeddedSignAndSubmit(transaction);
3857
+ }
3638
3858
  async getNativeMethods() { return {}; }
3639
3859
  }
3640
3860
  const emailProviderSingleton = new EmailAuthProvider();
@@ -3665,6 +3885,11 @@ function resolveSolanaRpcUrl(explicitRpcUrl, network, context) {
3665
3885
  throw new Error(`${context} requires an explicit Solana RPC URL. Pass config.rpcUrl before signing or submitting onchain transactions.`);
3666
3886
  }
3667
3887
 
3888
+ // Same message the email provider uses when a hosted (OIDC) login has no
3889
+ // embedded wallet — enable `auth.wallets` in policy to get one.
3890
+ const OIDC_NO_WALLET = 'This login has no embedded wallet. Enable `"auth": { "wallets": true }` in ' +
3891
+ 'the app policy so logins get a non-custodial Crossmint wallet (@user.address), ' +
3892
+ 'then sign from a user gesture.';
3668
3893
  const PKCE_STORE_KEY = 'bounded.oidc.pkce';
3669
3894
  const STORED_AUTH_METHOD_KEY$1 = 'bounded_last_auth_method';
3670
3895
  // Active session store (Web on web, RN on React Native) — selected by config,
@@ -3689,6 +3914,10 @@ function decodeJwt(token) {
3689
3914
  }
3690
3915
  }
3691
3916
  // A minimal AuthProvider so getSession()/logout() work for OIDC sessions, mirroring email.
3917
+ // Signing surface (slice 2): a hosted login on a wallets-enabled app carries an
3918
+ // embedded Crossmint wallet (@user.address). signAndSubmitTransaction routes
3919
+ // through the Bounded signer popup; signMessage/signTransaction are structurally
3920
+ // unsupported for Crossmint smart wallets (sign+submit atomically, no raw sig).
3692
3921
  const oidcProviderSingleton = {
3693
3922
  async login() {
3694
3923
  const idToken = sessionManager().getIdToken();
@@ -3699,6 +3928,17 @@ const oidcProviderSingleton = {
3699
3928
  return idToken ? userFromIdToken(idToken) : null;
3700
3929
  },
3701
3930
  async logout() { sessionManager().clearSession(); },
3931
+ async signMessage(_message) {
3932
+ throw new Error(hasEmbeddedWallet() ? EMBEDDED_WALLET_UNSUPPORTED : OIDC_NO_WALLET);
3933
+ },
3934
+ async signTransaction(_t) {
3935
+ throw new Error(hasEmbeddedWallet() ? EMBEDDED_WALLET_UNSUPPORTED : OIDC_NO_WALLET);
3936
+ },
3937
+ async signAndSubmitTransaction(transaction, _feePayer) {
3938
+ if (!hasEmbeddedWallet())
3939
+ throw new Error(OIDC_NO_WALLET);
3940
+ return embeddedSignAndSubmit(transaction);
3941
+ },
3702
3942
  };
3703
3943
  function userFromIdToken(idToken) {
3704
3944
  const c = decodeJwt(idToken);
@@ -4739,8 +4979,6 @@ async function getIdToken() {
4739
4979
  return getIdToken$1(false);
4740
4980
  }
4741
4981
 
4742
- var bufferExports = requireBuffer();
4743
-
4744
4982
  /**
4745
4983
  * Extracts a human-readable error message from Solana transaction logs.
4746
4984
  */