@bounded-sh/client 0.0.24 → 0.0.26

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.
Files changed (27) hide show
  1. package/dist/auth/oidc-auth.d.ts +38 -10
  2. package/dist/index.js +168 -70
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +168 -70
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/{index.native-DcetyeOb.js → index.native-BfAzgVuY.js} +171 -73
  7. package/dist/index.native-BfAzgVuY.js.map +1 -0
  8. package/dist/{index.native-D1YQ-LU7.mjs → index.native-DEWlFCQV.mjs} +171 -73
  9. package/dist/index.native-DEWlFCQV.mjs.map +1 -0
  10. package/dist/index.native.js +1 -1
  11. package/dist/index.native.mjs +1 -1
  12. package/dist/{phantom-wallet-provider-DgBk6o3j.js → phantom-wallet-provider-3xKduOOY.js} +2 -2
  13. package/dist/{phantom-wallet-provider-DgBk6o3j.js.map → phantom-wallet-provider-3xKduOOY.js.map} +1 -1
  14. package/dist/{phantom-wallet-provider-3_IulJlh.mjs → phantom-wallet-provider-B3ztJGu2.mjs} +2 -2
  15. package/dist/{phantom-wallet-provider-3_IulJlh.mjs.map → phantom-wallet-provider-B3ztJGu2.mjs.map} +1 -1
  16. package/dist/platform.d.ts +8 -0
  17. package/dist/{privy-wallet-provider-DNvtYCsQ.js → privy-wallet-provider-3LnqlNI-.js} +3 -3
  18. package/dist/{privy-wallet-provider-DNvtYCsQ.js.map → privy-wallet-provider-3LnqlNI-.js.map} +1 -1
  19. package/dist/{privy-wallet-provider-DQtXFGFF.mjs → privy-wallet-provider-D2i_xwYW.mjs} +3 -3
  20. package/dist/{privy-wallet-provider-DQtXFGFF.mjs.map → privy-wallet-provider-D2i_xwYW.mjs.map} +1 -1
  21. package/dist/{solana-mobile-wallet-provider-CcnkDdgZ.js → solana-mobile-wallet-provider-D2nTRj-4.js} +2 -2
  22. package/dist/{solana-mobile-wallet-provider-CcnkDdgZ.js.map → solana-mobile-wallet-provider-D2nTRj-4.js.map} +1 -1
  23. package/dist/{solana-mobile-wallet-provider-DE_zCpKE.mjs → solana-mobile-wallet-provider-dOWiujmo.mjs} +2 -2
  24. package/dist/{solana-mobile-wallet-provider-DE_zCpKE.mjs.map → solana-mobile-wallet-provider-dOWiujmo.mjs.map} +1 -1
  25. package/package.json +10 -2
  26. package/dist/index.native-D1YQ-LU7.mjs.map +0 -1
  27. package/dist/index.native-DcetyeOb.js.map +0 -1
@@ -89,6 +89,17 @@ function createWebPlatform() {
89
89
  const hash = createHash('sha256').update(data).digest();
90
90
  return hash.buffer.slice(hash.byteOffset, hash.byteOffset + hash.byteLength);
91
91
  },
92
+ getRandomBytes(length) {
93
+ const out = new Uint8Array(length);
94
+ const g = typeof globalThis !== 'undefined' ? globalThis : undefined;
95
+ if (g && g.crypto && typeof g.crypto.getRandomValues === 'function') {
96
+ g.crypto.getRandomValues(out);
97
+ return out;
98
+ }
99
+ throw new Error('No secure random source available for PKCE. On React Native, either import ' +
100
+ "'react-native-get-random-values' once at your app entry, or pass getRandomBytes " +
101
+ 'via setPlatform({ getRandomBytes }) (e.g. expo-crypto getRandomBytes).');
102
+ },
92
103
  getUserAgent() {
93
104
  if (hasWindow && typeof navigator !== 'undefined')
94
105
  return navigator.userAgent;
@@ -4256,24 +4267,27 @@ async function issuerBase() {
4256
4267
  const cfg = await core.getConfig();
4257
4268
  return (cfg.humanAuthApiUrl || 'https://auth.bounded.sh').replace(/\/$/, '');
4258
4269
  }
4270
+ // Base64url-encode raw bytes via the platform abstraction (web: window.btoa;
4271
+ // RN/Node: the polyfilled/Buffer btoa supplied by getPlatform()). On web this is
4272
+ // byte-identical to the previous direct `btoa(...)` call.
4259
4273
  function b64url(buf) {
4260
4274
  let s = '';
4261
- const bytes = new Uint8Array(buf);
4275
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
4262
4276
  for (let i = 0; i < bytes.length; i++)
4263
4277
  s += String.fromCharCode(bytes[i]);
4264
- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
4278
+ return getPlatform().btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
4265
4279
  }
4280
+ // PKCE verifier + S256 challenge, fully platform-neutral: random bytes and the
4281
+ // SHA-256 digest both come from getPlatform() (web → WebCrypto, RN → polyfill/
4282
+ // expo-crypto). Web output is identical to the previous raw-crypto path.
4266
4283
  async function makePkce() {
4267
- const rnd = new Uint8Array(32);
4268
- crypto.getRandomValues(rnd);
4269
- const verifier = b64url(rnd.buffer);
4270
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
4284
+ const rnd = getPlatform().getRandomBytes(32);
4285
+ const verifier = b64url(rnd);
4286
+ const digest = await getPlatform().sha256(getPlatform().textEncode(verifier));
4271
4287
  return { verifier, challenge: b64url(digest) };
4272
4288
  }
4273
4289
  function randomState() {
4274
- const rnd = new Uint8Array(16);
4275
- crypto.getRandomValues(rnd);
4276
- return b64url(rnd.buffer);
4290
+ return b64url(getPlatform().getRandomBytes(16));
4277
4291
  }
4278
4292
  function normalizeMethod(value) {
4279
4293
  const normalized = String(value || '').trim().toLowerCase();
@@ -4289,84 +4303,171 @@ function appendHostedLoginHints(params, opts) {
4289
4303
  const provider = normalizeMethod(opts.provider);
4290
4304
  if (provider)
4291
4305
  params.set('bounded_provider', provider);
4306
+ // Standard OIDC prompt (e.g. 'login' to force a fresh sign-in / account choice).
4307
+ const prompt = normalizeMethod(opts.prompt);
4308
+ if (prompt)
4309
+ params.set('prompt', prompt);
4292
4310
  }
4293
- async function buildAuthorizeUrl(opts) {
4311
+ // Build the authorize URL + the PKCE state that pairs with it. PURE: no storage,
4312
+ // no navigation — so it's shared verbatim by the web redirect/popup paths and the
4313
+ // native (expo-web-browser) path. The caller decides where the PkceState lives
4314
+ // (web → sessionStorage across the full-page redirect; native → in-memory across
4315
+ // the awaited browser session).
4316
+ async function buildAuthorize(opts, guestHint) {
4294
4317
  const cfg = await core.getConfig();
4295
4318
  if (!cfg.appId)
4296
4319
  throw new Error('appId is not configured (init the SDK with your appId)');
4297
4320
  const redirectUri = opts.redirectUri;
4298
4321
  const { verifier, challenge } = await makePkce();
4299
4322
  const state = randomState();
4300
- // Stash the verifier + state so the redirect_uri page can finish the exchange. sessionStorage
4301
- // is per-tab and cleared on close — appropriate for a short-lived auth handshake.
4302
- sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify({ verifier, state, redirectUri }));
4303
4323
  const base = await issuerBase();
4304
4324
  const params = new URLSearchParams({
4305
4325
  client_id: cfg.appId, redirect_uri: redirectUri, response_type: 'code', scope: 'openid profile email',
4306
4326
  code_challenge: challenge, code_challenge_method: 'S256', state,
4307
4327
  });
4308
4328
  appendHostedLoginHints(params, opts);
4309
- return `${base}/api/auth/oauth2/authorize?${params.toString()}`;
4329
+ // Anonymous→real UPGRADE (linkWithRedirect): carry the guest's signed id-token THROUGH
4330
+ // the authorize request as a hint. The issuer signature-verifies it and binds it to this
4331
+ // request's PKCE code_challenge, so the link is completed single-use during the normal
4332
+ // code→token exchange — no retired /link/social, and the appId stays bound to client_id.
4333
+ if (guestHint)
4334
+ params.set('bounded_guest_hint', guestHint);
4335
+ return { url: `${base}/api/auth/oauth2/authorize?${params.toString()}`, pkce: { verifier, state, redirectUri } };
4336
+ }
4337
+ // Are we on React Native (no DOM)? OIDC dispatch uses this to choose the native
4338
+ // expo-web-browser driver vs. the web full-page-redirect/popup driver.
4339
+ function isNative() {
4340
+ return !getPlatform().hasDOM;
4341
+ }
4342
+ // ---------------------------------------------------------------------------
4343
+ // Native (React Native / Expo) redirect driver
4344
+ // ---------------------------------------------------------------------------
4345
+ // Lazily load expo-web-browser. It's an OPTIONAL peer dep — imported dynamically
4346
+ // so the web/Node bundle never requires it. Throws an actionable error if a native
4347
+ // app calls hosted login without installing it.
4348
+ async function loadExpoWebBrowser() {
4349
+ try {
4350
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
4351
+ return await import('expo-web-browser');
4352
+ }
4353
+ catch (_a) {
4354
+ throw new Error('React Native hosted login requires the optional peer dependency "expo-web-browser". ' +
4355
+ 'Install it with `npx expo install expo-web-browser` (and `expo-crypto`), then retry.');
4356
+ }
4310
4357
  }
4311
- /** Start login: navigate the whole page to the hosted Bounded login. Returns after redirect
4312
- * to `redirectUri?code=...`, where you call completeLoginFromRedirect(). Web only. */
4358
+ // Parse code/state out of the universal-link callback URL. Hand-rolled (no `new URL()`)
4359
+ // because React Native's URL implementation is non-spec-compliant for query parsing.
4360
+ function parseCallbackParams(callbackUrl) {
4361
+ var _a, _b;
4362
+ const qIndex = callbackUrl.indexOf('?');
4363
+ if (qIndex < 0)
4364
+ return { code: null, state: null };
4365
+ const query = callbackUrl.slice(qIndex + 1).split('#')[0];
4366
+ const out = {};
4367
+ for (const part of query.split('&')) {
4368
+ if (!part)
4369
+ continue;
4370
+ const eq = part.indexOf('=');
4371
+ const k = eq < 0 ? part : part.slice(0, eq);
4372
+ const v = eq < 0 ? '' : part.slice(eq + 1);
4373
+ try {
4374
+ out[decodeURIComponent(k)] = decodeURIComponent(v.replace(/\+/g, ' '));
4375
+ }
4376
+ catch (_c) {
4377
+ out[k] = v;
4378
+ }
4379
+ }
4380
+ return { code: (_a = out['code']) !== null && _a !== void 0 ? _a : null, state: (_b = out['state']) !== null && _b !== void 0 ? _b : null };
4381
+ }
4382
+ // Full native login: open the hosted page in the system auth session, await the
4383
+ // universal-link callback, verify state, and run the SAME PKCE code→token exchange
4384
+ // as web. Returns the signed-in User (native completes inline — there's no separate
4385
+ // completeLoginFromRedirect() round-trip the way the web full-page redirect needs).
4386
+ async function runNativeLogin(opts, guestHint) {
4387
+ var _a, _b;
4388
+ const { url, pkce } = await buildAuthorize(opts, guestHint);
4389
+ const WebBrowser = await loadExpoWebBrowser();
4390
+ const openAuthSession = WebBrowser.openAuthSessionAsync || ((_a = WebBrowser.default) === null || _a === void 0 ? void 0 : _a.openAuthSessionAsync);
4391
+ if (typeof openAuthSession !== 'function') {
4392
+ throw new Error('expo-web-browser.openAuthSessionAsync is unavailable — update expo-web-browser.');
4393
+ }
4394
+ setAuthLoading(true);
4395
+ try {
4396
+ // openAuthSessionAsync keeps JS alive while the system browser is shown, then
4397
+ // resolves with the callback URL once the universal link fires — so `pkce`
4398
+ // stays in scope and never needs to be persisted.
4399
+ const result = await openAuthSession(url, opts.redirectUri);
4400
+ if (!result || result.type === 'cancel' || result.type === 'dismiss') {
4401
+ throw new Error('Login cancelled');
4402
+ }
4403
+ if (result.type !== 'success' || typeof result.url !== 'string') {
4404
+ throw new Error(`Hosted login did not complete (result: ${(_b = result === null || result === void 0 ? void 0 : result.type) !== null && _b !== void 0 ? _b : 'unknown'})`);
4405
+ }
4406
+ const { code, state: returnedState } = parseCallbackParams(result.url);
4407
+ if (!code)
4408
+ throw new Error('No authorization code in the callback URL');
4409
+ if (!returnedState || returnedState !== pkce.state) {
4410
+ throw new Error('OAuth state mismatch — possible CSRF; aborting');
4411
+ }
4412
+ return await exchangeCode(code, pkce.verifier, pkce.redirectUri);
4413
+ }
4414
+ finally {
4415
+ setAuthLoading(false);
4416
+ }
4417
+ }
4418
+ /** Start hosted login (Google / Apple / email / hosted phone). Works on WEB and REACT NATIVE.
4419
+ *
4420
+ * WEB: navigates the whole page to the hosted Bounded login and resolves (void) as the page
4421
+ * unloads; on return to `redirectUri?code=...` you call completeLoginFromRedirect().
4422
+ *
4423
+ * REACT NATIVE: opens the hosted page via expo-web-browser, awaits the https universal-link
4424
+ * callback, runs the PKCE exchange INLINE, and resolves with the signed-in User. No
4425
+ * completeLoginFromRedirect() call is needed on native. Requires `redirectUri` to be an
4426
+ * https UNIVERSAL LINK whose origin the app owner registered in the app's allowedOrigins
4427
+ * (custom `myapp://` schemes are rejected by the issuer). Needs the optional peer deps
4428
+ * expo-web-browser + (expo-crypto or react-native-get-random-values). */
4313
4429
  async function loginWithRedirect(opts) {
4430
+ if (isNative())
4431
+ return runNativeLogin(opts);
4314
4432
  if (!hasDOM())
4315
- throw new Error('loginWithRedirect is web-only');
4316
- const url = await buildAuthorizeUrl(opts);
4433
+ throw new Error('loginWithRedirect requires a browser or a configured React Native platform');
4434
+ const { url, pkce } = await buildAuthorize(opts);
4435
+ // Stash the verifier + state so the redirect_uri page can finish the exchange. sessionStorage
4436
+ // is per-tab and cleared on close — appropriate for a short-lived auth handshake.
4437
+ sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify(pkce));
4317
4438
  window.location.href = url;
4318
4439
  }
4319
- const LINK_GUEST_KEY = 'bounded.link.guest';
4320
4440
  /** UPGRADE the current anonymous (guest) session by linking a SOCIAL/redirect login
4321
- * (e.g. Google) — Firebase `linkWithPopup`/redirect parity. Stashes the guest token,
4322
- * then runs the normal redirect login; `completeLoginFromRedirect()` on the callback
4323
- * page finishes the link automatically (if the social account is brand-new the guest's
4324
- * `@user.id` is preserved, else it stays separate). Requires an active guest session. */
4441
+ * (e.g. Google) — Firebase `linkWithPopup`/redirect parity. Carries the guest's signed
4442
+ * id-token THROUGH the OIDC authorize request (as a single-use hint bound to the PKCE
4443
+ * challenge), then runs the normal redirect login. The issuer completes the link during
4444
+ * the standard code→token exchange: if the chosen account is brand-new the guest's
4445
+ * `@user.id` is preserved (the returned id_token is minted under it), else the account
4446
+ * stays separate (guest id discarded). Requires an active guest session.
4447
+ *
4448
+ * Works on WEB (navigates, finish with completeLoginFromRedirect) and REACT NATIVE
4449
+ * (opens expo-web-browser and resolves with the upgraded User inline). */
4325
4450
  async function linkWithRedirect(opts) {
4326
- if (!hasDOM())
4327
- throw new Error('linkWithRedirect is web-only');
4328
4451
  const guestToken = sessionManager().getIdToken();
4329
4452
  if (!guestToken)
4330
4453
  throw new Error('linkWithRedirect requires an active anonymous session — call signInAnonymously() first.');
4331
- sessionStorage.setItem(LINK_GUEST_KEY, guestToken);
4332
- const url = await buildAuthorizeUrl(opts);
4333
- window.location.href = url;
4334
- }
4335
- // If a guest-link is pending (linkWithRedirect stashed a guest token before this
4336
- // redirect), exchange it + the fresh social token for an UPGRADED token via
4337
- // /link/social and replace the session. Returns the upgraded user, or null if no
4338
- // link was pending / the link failed (in which case the plain social login stands).
4339
- async function finishGuestLinkIfPending(socialIdToken) {
4454
+ if (isNative())
4455
+ return runNativeLogin(opts, guestToken);
4340
4456
  if (!hasDOM())
4341
- return null;
4342
- const guestToken = sessionStorage.getItem(LINK_GUEST_KEY);
4343
- if (!guestToken)
4344
- return null;
4345
- sessionStorage.removeItem(LINK_GUEST_KEY);
4346
- try {
4347
- const cfg = await core.getConfig();
4348
- const base = await issuerBase();
4349
- const res = await fetch(`${base}/link/social`, {
4350
- method: 'POST', headers: { 'content-type': 'application/json' },
4351
- body: JSON.stringify({ appId: cfg.appId, guestToken, socialToken: socialIdToken }),
4352
- });
4353
- const data = await res.json().catch(() => null);
4354
- const idToken = tokenField(data, 'id_token', 'idToken');
4355
- if (!res.ok || !idToken)
4356
- return null; // link failed -> keep the plain social session
4357
- const upgraded = userFromIdToken(idToken);
4358
- const accessToken = tokenField(data, 'access_token', 'accessToken') || idToken;
4359
- const refreshToken = boundedRefreshTokenField(data);
4360
- await sessionManager().storeSession(String(upgraded.address || ''), accessToken, idToken, refreshToken, base);
4361
- setCurrentUser(upgraded);
4362
- return upgraded;
4363
- }
4364
- catch (_a) {
4365
- return null;
4366
- }
4457
+ throw new Error('linkWithRedirect requires a browser or a configured React Native platform');
4458
+ const { url, pkce } = await buildAuthorize(opts, guestToken);
4459
+ sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify(pkce));
4460
+ window.location.href = url;
4367
4461
  }
4368
- /** Finish login on the redirect_uri page: exchange ?code= for a token (PKCE-verified), store
4369
- * the session, and return the User. Idempotent: returns null if there's no ?code= in the URL. */
4462
+ /** Finish login on the redirect_uri page (WEB ONLY): exchange ?code= for a token (PKCE-verified),
4463
+ * store the session, and return the User. Idempotent: returns null if there's no ?code= in the URL.
4464
+ * When the redirect was a guest UPGRADE (linkWithRedirect) and the issuer adopted the guest
4465
+ * id, the exchanged id_token already carries the preserved `@user.id`, so the returned User
4466
+ * reflects it automatically (no extra round-trip).
4467
+ *
4468
+ * On REACT NATIVE this returns null and is a no-op: native login completes INLINE inside
4469
+ * loginWithRedirect()/linkWithRedirect() (which resolve with the User), so there is no
4470
+ * separate redirect page to finish from. Calling it on RN is harmless. */
4370
4471
  async function completeLoginFromRedirect() {
4371
4472
  if (!hasDOM())
4372
4473
  return null;
@@ -4385,15 +4486,11 @@ async function completeLoginFromRedirect() {
4385
4486
  throw new Error('OAuth state mismatch — possible CSRF; aborting');
4386
4487
  const user = await exchangeCode(code, pkce.verifier, pkce.redirectUri);
4387
4488
  sessionStorage.removeItem(PKCE_STORE_KEY);
4388
- // If this redirect was a guest UPGRADE (linkWithRedirect), finish the link now:
4389
- // swap the fresh social session for one minted under the guest's preserved id.
4390
- const socialIdToken = sessionManager().getIdToken();
4391
- const upgraded = socialIdToken ? await finishGuestLinkIfPending(socialIdToken) : null;
4392
4489
  // Strip code/state from the URL so a reload doesn't re-exchange (codes are single-use anyway).
4393
4490
  url.searchParams.delete('code');
4394
4491
  url.searchParams.delete('state');
4395
4492
  window.history.replaceState({}, document.title, url.pathname + url.search + url.hash);
4396
- return upgraded !== null && upgraded !== void 0 ? upgraded : user;
4493
+ return user;
4397
4494
  }
4398
4495
  finally {
4399
4496
  setAuthLoading(false);
@@ -4403,8 +4500,9 @@ async function completeLoginFromRedirect() {
4403
4500
  * redirect_uri page posts the code back. The redirect_uri page must call completeLoginInPopup(). */
4404
4501
  async function loginWithPopup(opts) {
4405
4502
  if (!hasDOM())
4406
- throw new Error('loginWithPopup is web-only');
4407
- const url = await buildAuthorizeUrl(opts);
4503
+ throw new Error('loginWithPopup is web-only — on React Native use loginWithRedirect()');
4504
+ const { url, pkce } = await buildAuthorize(opts);
4505
+ sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify(pkce));
4408
4506
  const w = opts.width || 480, h = opts.height || 720;
4409
4507
  const left = window.screenX + (window.outerWidth - w) / 2;
4410
4508
  const top = window.screenY + (window.outerHeight - h) / 2;
@@ -4611,17 +4709,17 @@ function clearIncompatibleSession() {
4611
4709
  // Lazy loaders for web-only providers.
4612
4710
  // Using dynamic import() ensures Metro (RN) never resolves these modules.
4613
4711
  async function loadPhantomWalletProvider() {
4614
- const mod = await Promise.resolve().then(function () { return require('./phantom-wallet-provider-DgBk6o3j.js'); });
4712
+ const mod = await Promise.resolve().then(function () { return require('./phantom-wallet-provider-3xKduOOY.js'); });
4615
4713
  return { PhantomWalletProvider: mod.PhantomWalletProvider };
4616
4714
  }
4617
4715
  // Web Privy provider (depends on react-dom + @privy-io/react-auth). Lazy so Metro
4618
4716
  // never bundles it into the RN build — RN uses the @privy-io/expo provider instead.
4619
4717
  async function loadPrivyWalletProvider() {
4620
- const mod = await Promise.resolve().then(function () { return require('./privy-wallet-provider-DNvtYCsQ.js'); });
4718
+ const mod = await Promise.resolve().then(function () { return require('./privy-wallet-provider-3LnqlNI-.js'); });
4621
4719
  return mod.PrivyWalletProvider;
4622
4720
  }
4623
4721
  async function loadSolanaMobileWalletProvider() {
4624
- const mod = await Promise.resolve().then(function () { return require('./solana-mobile-wallet-provider-CcnkDdgZ.js'); });
4722
+ const mod = await Promise.resolve().then(function () { return require('./solana-mobile-wallet-provider-D2nTRj-4.js'); });
4625
4723
  return mod.SolanaMobileWalletProvider;
4626
4724
  }
4627
4725
  function requireWebPrivyConfig(config) {
@@ -5701,4 +5799,4 @@ exports.signInAnonymously = signInAnonymously;
5701
5799
  exports.useAuth = useAuth;
5702
5800
  exports.verifyEmailOtp = verifyEmailOtp;
5703
5801
  exports.verifyTextOtp = verifyTextOtp;
5704
- //# sourceMappingURL=index.native-DcetyeOb.js.map
5802
+ //# sourceMappingURL=index.native-BfAzgVuY.js.map