@bounded-sh/client 0.0.23 → 0.0.25

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 +31 -10
  2. package/dist/index.js +163 -69
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +163 -69
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/{index.native-D1YQ-LU7.mjs → index.native-CcpKp_mg.mjs} +167 -73
  7. package/dist/index.native-CcpKp_mg.mjs.map +1 -0
  8. package/dist/{index.native-DcetyeOb.js → index.native-DIw0cB5C.js} +167 -73
  9. package/dist/index.native-DIw0cB5C.js.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-Cagl3roP.js} +2 -2
  13. package/dist/{phantom-wallet-provider-DgBk6o3j.js.map → phantom-wallet-provider-Cagl3roP.js.map} +1 -1
  14. package/dist/{phantom-wallet-provider-3_IulJlh.mjs → phantom-wallet-provider-CyMav6HM.mjs} +2 -2
  15. package/dist/{phantom-wallet-provider-3_IulJlh.mjs.map → phantom-wallet-provider-CyMav6HM.mjs.map} +1 -1
  16. package/dist/platform.d.ts +8 -0
  17. package/dist/{privy-wallet-provider-DNvtYCsQ.js → privy-wallet-provider-Cb1GUmOi.js} +3 -3
  18. package/dist/{privy-wallet-provider-DNvtYCsQ.js.map → privy-wallet-provider-Cb1GUmOi.js.map} +1 -1
  19. package/dist/{privy-wallet-provider-DQtXFGFF.mjs → privy-wallet-provider-YR9Eisgl.mjs} +3 -3
  20. package/dist/{privy-wallet-provider-DQtXFGFF.mjs.map → privy-wallet-provider-YR9Eisgl.mjs.map} +1 -1
  21. package/dist/{solana-mobile-wallet-provider-CcnkDdgZ.js → solana-mobile-wallet-provider-BEpjk4Sz.js} +2 -2
  22. package/dist/{solana-mobile-wallet-provider-CcnkDdgZ.js.map → solana-mobile-wallet-provider-BEpjk4Sz.js.map} +1 -1
  23. package/dist/{solana-mobile-wallet-provider-DE_zCpKE.mjs → solana-mobile-wallet-provider-DOSBGM8C.mjs} +2 -2
  24. package/dist/{solana-mobile-wallet-provider-DE_zCpKE.mjs.map → solana-mobile-wallet-provider-DOSBGM8C.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
package/dist/index.mjs CHANGED
@@ -70,6 +70,17 @@ function createWebPlatform() {
70
70
  const hash = createHash('sha256').update(data).digest();
71
71
  return hash.buffer.slice(hash.byteOffset, hash.byteOffset + hash.byteLength);
72
72
  },
73
+ getRandomBytes(length) {
74
+ const out = new Uint8Array(length);
75
+ const g = typeof globalThis !== 'undefined' ? globalThis : undefined;
76
+ if (g && g.crypto && typeof g.crypto.getRandomValues === 'function') {
77
+ g.crypto.getRandomValues(out);
78
+ return out;
79
+ }
80
+ throw new Error('No secure random source available for PKCE. On React Native, either import ' +
81
+ "'react-native-get-random-values' once at your app entry, or pass getRandomBytes " +
82
+ 'via setPlatform({ getRandomBytes }) (e.g. expo-crypto getRandomBytes).');
83
+ },
73
84
  getUserAgent() {
74
85
  if (hasWindow && typeof navigator !== 'undefined')
75
86
  return navigator.userAgent;
@@ -4237,24 +4248,27 @@ async function issuerBase() {
4237
4248
  const cfg = await getConfig();
4238
4249
  return (cfg.humanAuthApiUrl || 'https://auth.bounded.sh').replace(/\/$/, '');
4239
4250
  }
4251
+ // Base64url-encode raw bytes via the platform abstraction (web: window.btoa;
4252
+ // RN/Node: the polyfilled/Buffer btoa supplied by getPlatform()). On web this is
4253
+ // byte-identical to the previous direct `btoa(...)` call.
4240
4254
  function b64url(buf) {
4241
4255
  let s = '';
4242
- const bytes = new Uint8Array(buf);
4256
+ const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
4243
4257
  for (let i = 0; i < bytes.length; i++)
4244
4258
  s += String.fromCharCode(bytes[i]);
4245
- return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
4259
+ return getPlatform().btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
4246
4260
  }
4261
+ // PKCE verifier + S256 challenge, fully platform-neutral: random bytes and the
4262
+ // SHA-256 digest both come from getPlatform() (web → WebCrypto, RN → polyfill/
4263
+ // expo-crypto). Web output is identical to the previous raw-crypto path.
4247
4264
  async function makePkce() {
4248
- const rnd = new Uint8Array(32);
4249
- crypto.getRandomValues(rnd);
4250
- const verifier = b64url(rnd.buffer);
4251
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
4265
+ const rnd = getPlatform().getRandomBytes(32);
4266
+ const verifier = b64url(rnd);
4267
+ const digest = await getPlatform().sha256(getPlatform().textEncode(verifier));
4252
4268
  return { verifier, challenge: b64url(digest) };
4253
4269
  }
4254
4270
  function randomState() {
4255
- const rnd = new Uint8Array(16);
4256
- crypto.getRandomValues(rnd);
4257
- return b64url(rnd.buffer);
4271
+ return b64url(getPlatform().getRandomBytes(16));
4258
4272
  }
4259
4273
  function normalizeMethod(value) {
4260
4274
  const normalized = String(value || '').trim().toLowerCase();
@@ -4271,83 +4285,166 @@ function appendHostedLoginHints(params, opts) {
4271
4285
  if (provider)
4272
4286
  params.set('bounded_provider', provider);
4273
4287
  }
4274
- async function buildAuthorizeUrl(opts) {
4288
+ // Build the authorize URL + the PKCE state that pairs with it. PURE: no storage,
4289
+ // no navigation — so it's shared verbatim by the web redirect/popup paths and the
4290
+ // native (expo-web-browser) path. The caller decides where the PkceState lives
4291
+ // (web → sessionStorage across the full-page redirect; native → in-memory across
4292
+ // the awaited browser session).
4293
+ async function buildAuthorize(opts, guestHint) {
4275
4294
  const cfg = await getConfig();
4276
4295
  if (!cfg.appId)
4277
4296
  throw new Error('appId is not configured (init the SDK with your appId)');
4278
4297
  const redirectUri = opts.redirectUri;
4279
4298
  const { verifier, challenge } = await makePkce();
4280
4299
  const state = randomState();
4281
- // Stash the verifier + state so the redirect_uri page can finish the exchange. sessionStorage
4282
- // is per-tab and cleared on close — appropriate for a short-lived auth handshake.
4283
- sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify({ verifier, state, redirectUri }));
4284
4300
  const base = await issuerBase();
4285
4301
  const params = new URLSearchParams({
4286
4302
  client_id: cfg.appId, redirect_uri: redirectUri, response_type: 'code', scope: 'openid profile email',
4287
4303
  code_challenge: challenge, code_challenge_method: 'S256', state,
4288
4304
  });
4289
4305
  appendHostedLoginHints(params, opts);
4290
- return `${base}/api/auth/oauth2/authorize?${params.toString()}`;
4306
+ // Anonymous→real UPGRADE (linkWithRedirect): carry the guest's signed id-token THROUGH
4307
+ // the authorize request as a hint. The issuer signature-verifies it and binds it to this
4308
+ // request's PKCE code_challenge, so the link is completed single-use during the normal
4309
+ // code→token exchange — no retired /link/social, and the appId stays bound to client_id.
4310
+ if (guestHint)
4311
+ params.set('bounded_guest_hint', guestHint);
4312
+ return { url: `${base}/api/auth/oauth2/authorize?${params.toString()}`, pkce: { verifier, state, redirectUri } };
4313
+ }
4314
+ // Are we on React Native (no DOM)? OIDC dispatch uses this to choose the native
4315
+ // expo-web-browser driver vs. the web full-page-redirect/popup driver.
4316
+ function isNative() {
4317
+ return !getPlatform().hasDOM;
4318
+ }
4319
+ // ---------------------------------------------------------------------------
4320
+ // Native (React Native / Expo) redirect driver
4321
+ // ---------------------------------------------------------------------------
4322
+ // Lazily load expo-web-browser. It's an OPTIONAL peer dep — imported dynamically
4323
+ // so the web/Node bundle never requires it. Throws an actionable error if a native
4324
+ // app calls hosted login without installing it.
4325
+ async function loadExpoWebBrowser() {
4326
+ try {
4327
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
4328
+ return await import('expo-web-browser');
4329
+ }
4330
+ catch (_a) {
4331
+ throw new Error('React Native hosted login requires the optional peer dependency "expo-web-browser". ' +
4332
+ 'Install it with `npx expo install expo-web-browser` (and `expo-crypto`), then retry.');
4333
+ }
4334
+ }
4335
+ // Parse code/state out of the universal-link callback URL. Hand-rolled (no `new URL()`)
4336
+ // because React Native's URL implementation is non-spec-compliant for query parsing.
4337
+ function parseCallbackParams(callbackUrl) {
4338
+ var _a, _b;
4339
+ const qIndex = callbackUrl.indexOf('?');
4340
+ if (qIndex < 0)
4341
+ return { code: null, state: null };
4342
+ const query = callbackUrl.slice(qIndex + 1).split('#')[0];
4343
+ const out = {};
4344
+ for (const part of query.split('&')) {
4345
+ if (!part)
4346
+ continue;
4347
+ const eq = part.indexOf('=');
4348
+ const k = eq < 0 ? part : part.slice(0, eq);
4349
+ const v = eq < 0 ? '' : part.slice(eq + 1);
4350
+ try {
4351
+ out[decodeURIComponent(k)] = decodeURIComponent(v.replace(/\+/g, ' '));
4352
+ }
4353
+ catch (_c) {
4354
+ out[k] = v;
4355
+ }
4356
+ }
4357
+ return { code: (_a = out['code']) !== null && _a !== void 0 ? _a : null, state: (_b = out['state']) !== null && _b !== void 0 ? _b : null };
4291
4358
  }
4292
- /** Start login: navigate the whole page to the hosted Bounded login. Returns after redirect
4293
- * to `redirectUri?code=...`, where you call completeLoginFromRedirect(). Web only. */
4359
+ // Full native login: open the hosted page in the system auth session, await the
4360
+ // universal-link callback, verify state, and run the SAME PKCE code→token exchange
4361
+ // as web. Returns the signed-in User (native completes inline — there's no separate
4362
+ // completeLoginFromRedirect() round-trip the way the web full-page redirect needs).
4363
+ async function runNativeLogin(opts, guestHint) {
4364
+ var _a, _b;
4365
+ const { url, pkce } = await buildAuthorize(opts, guestHint);
4366
+ const WebBrowser = await loadExpoWebBrowser();
4367
+ const openAuthSession = WebBrowser.openAuthSessionAsync || ((_a = WebBrowser.default) === null || _a === void 0 ? void 0 : _a.openAuthSessionAsync);
4368
+ if (typeof openAuthSession !== 'function') {
4369
+ throw new Error('expo-web-browser.openAuthSessionAsync is unavailable — update expo-web-browser.');
4370
+ }
4371
+ setAuthLoading(true);
4372
+ try {
4373
+ // openAuthSessionAsync keeps JS alive while the system browser is shown, then
4374
+ // resolves with the callback URL once the universal link fires — so `pkce`
4375
+ // stays in scope and never needs to be persisted.
4376
+ const result = await openAuthSession(url, opts.redirectUri);
4377
+ if (!result || result.type === 'cancel' || result.type === 'dismiss') {
4378
+ throw new Error('Login cancelled');
4379
+ }
4380
+ if (result.type !== 'success' || typeof result.url !== 'string') {
4381
+ 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'})`);
4382
+ }
4383
+ const { code, state: returnedState } = parseCallbackParams(result.url);
4384
+ if (!code)
4385
+ throw new Error('No authorization code in the callback URL');
4386
+ if (!returnedState || returnedState !== pkce.state) {
4387
+ throw new Error('OAuth state mismatch — possible CSRF; aborting');
4388
+ }
4389
+ return await exchangeCode(code, pkce.verifier, pkce.redirectUri);
4390
+ }
4391
+ finally {
4392
+ setAuthLoading(false);
4393
+ }
4394
+ }
4395
+ /** Start hosted login (Google / Apple / email / hosted phone). Works on WEB and REACT NATIVE.
4396
+ *
4397
+ * WEB: navigates the whole page to the hosted Bounded login and resolves (void) as the page
4398
+ * unloads; on return to `redirectUri?code=...` you call completeLoginFromRedirect().
4399
+ *
4400
+ * REACT NATIVE: opens the hosted page via expo-web-browser, awaits the https universal-link
4401
+ * callback, runs the PKCE exchange INLINE, and resolves with the signed-in User. No
4402
+ * completeLoginFromRedirect() call is needed on native. Requires `redirectUri` to be an
4403
+ * https UNIVERSAL LINK whose origin the app owner registered in the app's allowedOrigins
4404
+ * (custom `myapp://` schemes are rejected by the issuer). Needs the optional peer deps
4405
+ * expo-web-browser + (expo-crypto or react-native-get-random-values). */
4294
4406
  async function loginWithRedirect(opts) {
4407
+ if (isNative())
4408
+ return runNativeLogin(opts);
4295
4409
  if (!hasDOM())
4296
- throw new Error('loginWithRedirect is web-only');
4297
- const url = await buildAuthorizeUrl(opts);
4410
+ throw new Error('loginWithRedirect requires a browser or a configured React Native platform');
4411
+ const { url, pkce } = await buildAuthorize(opts);
4412
+ // Stash the verifier + state so the redirect_uri page can finish the exchange. sessionStorage
4413
+ // is per-tab and cleared on close — appropriate for a short-lived auth handshake.
4414
+ sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify(pkce));
4298
4415
  window.location.href = url;
4299
4416
  }
4300
- const LINK_GUEST_KEY = 'bounded.link.guest';
4301
4417
  /** UPGRADE the current anonymous (guest) session by linking a SOCIAL/redirect login
4302
- * (e.g. Google) — Firebase `linkWithPopup`/redirect parity. Stashes the guest token,
4303
- * then runs the normal redirect login; `completeLoginFromRedirect()` on the callback
4304
- * page finishes the link automatically (if the social account is brand-new the guest's
4305
- * `@user.id` is preserved, else it stays separate). Requires an active guest session. */
4418
+ * (e.g. Google) — Firebase `linkWithPopup`/redirect parity. Carries the guest's signed
4419
+ * id-token THROUGH the OIDC authorize request (as a single-use hint bound to the PKCE
4420
+ * challenge), then runs the normal redirect login. The issuer completes the link during
4421
+ * the standard code→token exchange: if the chosen account is brand-new the guest's
4422
+ * `@user.id` is preserved (the returned id_token is minted under it), else the account
4423
+ * stays separate (guest id discarded). Requires an active guest session.
4424
+ *
4425
+ * Works on WEB (navigates, finish with completeLoginFromRedirect) and REACT NATIVE
4426
+ * (opens expo-web-browser and resolves with the upgraded User inline). */
4306
4427
  async function linkWithRedirect(opts) {
4307
- if (!hasDOM())
4308
- throw new Error('linkWithRedirect is web-only');
4309
4428
  const guestToken = sessionManager().getIdToken();
4310
4429
  if (!guestToken)
4311
4430
  throw new Error('linkWithRedirect requires an active anonymous session — call signInAnonymously() first.');
4312
- sessionStorage.setItem(LINK_GUEST_KEY, guestToken);
4313
- const url = await buildAuthorizeUrl(opts);
4314
- window.location.href = url;
4315
- }
4316
- // If a guest-link is pending (linkWithRedirect stashed a guest token before this
4317
- // redirect), exchange it + the fresh social token for an UPGRADED token via
4318
- // /link/social and replace the session. Returns the upgraded user, or null if no
4319
- // link was pending / the link failed (in which case the plain social login stands).
4320
- async function finishGuestLinkIfPending(socialIdToken) {
4431
+ if (isNative())
4432
+ return runNativeLogin(opts, guestToken);
4321
4433
  if (!hasDOM())
4322
- return null;
4323
- const guestToken = sessionStorage.getItem(LINK_GUEST_KEY);
4324
- if (!guestToken)
4325
- return null;
4326
- sessionStorage.removeItem(LINK_GUEST_KEY);
4327
- try {
4328
- const cfg = await getConfig();
4329
- const base = await issuerBase();
4330
- const res = await fetch(`${base}/link/social`, {
4331
- method: 'POST', headers: { 'content-type': 'application/json' },
4332
- body: JSON.stringify({ appId: cfg.appId, guestToken, socialToken: socialIdToken }),
4333
- });
4334
- const data = await res.json().catch(() => null);
4335
- const idToken = tokenField(data, 'id_token', 'idToken');
4336
- if (!res.ok || !idToken)
4337
- return null; // link failed -> keep the plain social session
4338
- const upgraded = userFromIdToken(idToken);
4339
- const accessToken = tokenField(data, 'access_token', 'accessToken') || idToken;
4340
- const refreshToken = boundedRefreshTokenField(data);
4341
- await sessionManager().storeSession(String(upgraded.address || ''), accessToken, idToken, refreshToken, base);
4342
- setCurrentUser(upgraded);
4343
- return upgraded;
4344
- }
4345
- catch (_a) {
4346
- return null;
4347
- }
4434
+ throw new Error('linkWithRedirect requires a browser or a configured React Native platform');
4435
+ const { url, pkce } = await buildAuthorize(opts, guestToken);
4436
+ sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify(pkce));
4437
+ window.location.href = url;
4348
4438
  }
4349
- /** Finish login on the redirect_uri page: exchange ?code= for a token (PKCE-verified), store
4350
- * the session, and return the User. Idempotent: returns null if there's no ?code= in the URL. */
4439
+ /** Finish login on the redirect_uri page (WEB ONLY): exchange ?code= for a token (PKCE-verified),
4440
+ * store the session, and return the User. Idempotent: returns null if there's no ?code= in the URL.
4441
+ * When the redirect was a guest UPGRADE (linkWithRedirect) and the issuer adopted the guest
4442
+ * id, the exchanged id_token already carries the preserved `@user.id`, so the returned User
4443
+ * reflects it automatically (no extra round-trip).
4444
+ *
4445
+ * On REACT NATIVE this returns null and is a no-op: native login completes INLINE inside
4446
+ * loginWithRedirect()/linkWithRedirect() (which resolve with the User), so there is no
4447
+ * separate redirect page to finish from. Calling it on RN is harmless. */
4351
4448
  async function completeLoginFromRedirect() {
4352
4449
  if (!hasDOM())
4353
4450
  return null;
@@ -4366,15 +4463,11 @@ async function completeLoginFromRedirect() {
4366
4463
  throw new Error('OAuth state mismatch — possible CSRF; aborting');
4367
4464
  const user = await exchangeCode(code, pkce.verifier, pkce.redirectUri);
4368
4465
  sessionStorage.removeItem(PKCE_STORE_KEY);
4369
- // If this redirect was a guest UPGRADE (linkWithRedirect), finish the link now:
4370
- // swap the fresh social session for one minted under the guest's preserved id.
4371
- const socialIdToken = sessionManager().getIdToken();
4372
- const upgraded = socialIdToken ? await finishGuestLinkIfPending(socialIdToken) : null;
4373
4466
  // Strip code/state from the URL so a reload doesn't re-exchange (codes are single-use anyway).
4374
4467
  url.searchParams.delete('code');
4375
4468
  url.searchParams.delete('state');
4376
4469
  window.history.replaceState({}, document.title, url.pathname + url.search + url.hash);
4377
- return upgraded !== null && upgraded !== void 0 ? upgraded : user;
4470
+ return user;
4378
4471
  }
4379
4472
  finally {
4380
4473
  setAuthLoading(false);
@@ -4384,8 +4477,9 @@ async function completeLoginFromRedirect() {
4384
4477
  * redirect_uri page posts the code back. The redirect_uri page must call completeLoginInPopup(). */
4385
4478
  async function loginWithPopup(opts) {
4386
4479
  if (!hasDOM())
4387
- throw new Error('loginWithPopup is web-only');
4388
- const url = await buildAuthorizeUrl(opts);
4480
+ throw new Error('loginWithPopup is web-only — on React Native use loginWithRedirect()');
4481
+ const { url, pkce } = await buildAuthorize(opts);
4482
+ sessionStorage.setItem(PKCE_STORE_KEY, JSON.stringify(pkce));
4389
4483
  const w = opts.width || 480, h = opts.height || 720;
4390
4484
  const left = window.screenX + (window.outerWidth - w) / 2;
4391
4485
  const top = window.screenY + (window.outerHeight - h) / 2;