@sparkvault/sdk-js 2.1.0 → 2.1.2

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.
@@ -832,6 +832,35 @@ function base64urlEncode(data) {
832
832
  function arrayBufferToBase64url(buffer) {
833
833
  return base64urlEncode(new Uint8Array(buffer));
834
834
  }
835
+ /**
836
+ * Decode base64url string to Uint8Array
837
+ *
838
+ * @param base64url - Base64url encoded string
839
+ * @returns Decoded bytes as Uint8Array
840
+ */
841
+ function base64urlDecode(base64url) {
842
+ const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
843
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
844
+ const binary = atob(padded);
845
+ const bytes = new Uint8Array(binary.length);
846
+ for (let i = 0; i < binary.length; i++) {
847
+ bytes[i] = binary.charCodeAt(i);
848
+ }
849
+ return bytes;
850
+ }
851
+ /**
852
+ * Decode base64url string to ArrayBuffer
853
+ *
854
+ * @param base64url - Base64url encoded string
855
+ * @returns Decoded ArrayBuffer
856
+ */
857
+ function base64urlToArrayBuffer(base64url) {
858
+ const bytes = base64urlDecode(base64url);
859
+ // Create a new ArrayBuffer with exact copy (avoids TypeScript ArrayBufferLike issue)
860
+ const buffer = new ArrayBuffer(bytes.length);
861
+ new Uint8Array(buffer).set(bytes);
862
+ return buffer;
863
+ }
835
864
  /**
836
865
  * Decode base64url string to UTF-8 string
837
866
  *
@@ -1568,11 +1597,115 @@ class PasskeyHandler {
1568
1597
  return result;
1569
1598
  }
1570
1599
  /**
1571
- * Verify user with existing passkey via popup
1600
+ * Verify user with an existing passkey.
1601
+ *
1602
+ * On the Identity origin (the hosted widget / hosted login) the ceremony runs
1603
+ * inline — same-origin with the RP id, one tap, no popup. On a third-party
1604
+ * origin the rpId would not match the document, so it falls back to the popup
1605
+ * served from the Identity origin. (Verification, unlike registration, is
1606
+ * supported in cross-origin iframes, so the embedded widget uses the inline
1607
+ * path.)
1572
1608
  */
1573
1609
  async verify() {
1610
+ if (this.canRunCeremonyInline()) {
1611
+ return this.verifyInline();
1612
+ }
1574
1613
  return this.openPasskeyPopup('verify');
1575
1614
  }
1615
+ /**
1616
+ * True when the SDK is running ON the Identity origin and the browser exposes
1617
+ * WebAuthn — the only place an inline ceremony's rpId matches the document.
1618
+ */
1619
+ canRunCeremonyInline() {
1620
+ return typeof window !== 'undefined'
1621
+ && typeof navigator !== 'undefined'
1622
+ && !!navigator.credentials
1623
+ && window.location.origin === this.trustedOrigin;
1624
+ }
1625
+ /**
1626
+ * Run the discoverable verification ceremony directly in this document and
1627
+ * map the outcome onto the same PasskeyResult shape the popup produces.
1628
+ */
1629
+ async verifyInline() {
1630
+ try {
1631
+ const challenge = await this.api.startPasskeyVerify(undefined, 'email', this.state.authContext);
1632
+ const credential = await navigator.credentials.get({
1633
+ publicKey: {
1634
+ challenge: base64urlToArrayBuffer(challenge.challenge),
1635
+ rpId: challenge.rpId,
1636
+ timeout: challenge.timeout,
1637
+ userVerification: 'required',
1638
+ },
1639
+ });
1640
+ if (!credential) {
1641
+ return { success: false, error: 'Failed to get passkey', errorType: 'unknown' };
1642
+ }
1643
+ const response = await this.api.completePasskeyVerify({
1644
+ session: challenge.session,
1645
+ credential,
1646
+ authContext: this.state.authContext,
1647
+ });
1648
+ return {
1649
+ success: true,
1650
+ result: {
1651
+ token: response.token,
1652
+ identity: response.identity || this.state.recipient,
1653
+ identityType: response.identity_type || 'email',
1654
+ svid: response.svid,
1655
+ sessionId: response.session_id,
1656
+ refreshToken: response.refresh_token,
1657
+ redirect: response.redirect,
1658
+ },
1659
+ };
1660
+ }
1661
+ catch (error) {
1662
+ return this.mapInlineCeremonyError(error);
1663
+ }
1664
+ }
1665
+ /**
1666
+ * Map a thrown inline-ceremony error onto PasskeyResult, mirroring the
1667
+ * popup's error codes so the widget renders the same dedicated states
1668
+ * (cancelled, identity locked, no passkey → registration).
1669
+ */
1670
+ mapInlineCeremonyError(error) {
1671
+ // User dismissed the system sheet, or no credential was available.
1672
+ if (error instanceof Error && error.name === 'NotAllowedError') {
1673
+ return {
1674
+ success: false,
1675
+ error: 'Authentication was cancelled. Please try again.',
1676
+ errorType: 'cancelled',
1677
+ };
1678
+ }
1679
+ if (error instanceof IdentityApiError) {
1680
+ if (error.code === 'identity_locked') {
1681
+ return {
1682
+ success: false,
1683
+ error: 'This SparkVault Identity is locked. Visit auth.sv to manage it.',
1684
+ errorType: 'unknown',
1685
+ errorCode: 'identity_locked',
1686
+ };
1687
+ }
1688
+ if (error.code === 'passkey_not_registered') {
1689
+ return {
1690
+ success: false,
1691
+ error: 'No passkey found. Create one to continue.',
1692
+ errorType: 'not_found',
1693
+ errorCode: 'passkey_not_registered',
1694
+ };
1695
+ }
1696
+ return {
1697
+ success: false,
1698
+ error: error.message || 'Passkey authentication failed',
1699
+ errorType: 'unknown',
1700
+ errorCode: error.code,
1701
+ };
1702
+ }
1703
+ return {
1704
+ success: false,
1705
+ error: error instanceof Error ? error.message : 'Passkey authentication failed',
1706
+ errorType: 'unknown',
1707
+ };
1708
+ }
1576
1709
  /**
1577
1710
  * Open passkey popup and wait for result
1578
1711
  */
@@ -5609,6 +5742,19 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
5609
5742
  ].join(' '),
5610
5743
  code: 'sparklink_csp_blocked',
5611
5744
  };
5745
+ /**
5746
+ * Navigate the browser. When the flow runs inside the embed iframe, the host
5747
+ * injects `onNavigate` (via VerifyOptions) so redirects move the customer's
5748
+ * top window rather than the iframe — providers refuse to be framed anyway.
5749
+ * Outside the iframe this falls back to a normal same-window navigation.
5750
+ */
5751
+ function navigateWith(options, url) {
5752
+ if (options.onNavigate) {
5753
+ options.onNavigate(url);
5754
+ return;
5755
+ }
5756
+ window.location.href = url;
5757
+ }
5612
5758
  class IdentityRenderer {
5613
5759
  constructor(container, api, options, callbacks) {
5614
5760
  // View management
@@ -6185,7 +6331,7 @@ class IdentityRenderer {
6185
6331
  // page-level handler can act before we navigate away.
6186
6332
  this.safeOnSuccess(result.result);
6187
6333
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6188
- window.location.href = result.result.redirect;
6334
+ navigateWith(this.options, result.result.redirect);
6189
6335
  }
6190
6336
  }
6191
6337
  else if (result.errorCode === 'identity_locked') {
@@ -6252,7 +6398,7 @@ class IdentityRenderer {
6252
6398
  this.close();
6253
6399
  this.safeOnSuccess(result);
6254
6400
  if (typeof result.redirect === 'string' && result.redirect) {
6255
- window.location.href = result.redirect;
6401
+ navigateWith(this.options, result.redirect);
6256
6402
  }
6257
6403
  }
6258
6404
  catch (error) {
@@ -6307,7 +6453,7 @@ class IdentityRenderer {
6307
6453
  this.close();
6308
6454
  this.safeOnSuccess(result.result);
6309
6455
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6310
- window.location.href = result.result.redirect;
6456
+ navigateWith(this.options, result.result.redirect);
6311
6457
  }
6312
6458
  }
6313
6459
  else if (result.errorCode === 'identity_locked') {
@@ -6370,18 +6516,25 @@ class IdentityRenderer {
6370
6516
  this.close();
6371
6517
  this.safeOnSuccess(pendingResult);
6372
6518
  if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6373
- window.location.href = pendingResult.redirect;
6519
+ navigateWith(this.options, pendingResult.redirect);
6374
6520
  }
6375
6521
  }
6376
6522
  }
6377
6523
  handleSocialLogin(provider) {
6378
6524
  this.setState({ view: 'oauth-pending', provider });
6525
+ // When embedded, social must originate from the host: the OAuth state and
6526
+ // redirect_uri belong to the customer's top origin, not this iframe (whose
6527
+ // sessionStorage and URL the return would never match). Hand it up.
6528
+ if (this.options.onSocial) {
6529
+ this.options.onSocial(provider);
6530
+ return;
6531
+ }
6379
6532
  const state = generateState();
6380
6533
  const redirectUri = window.location.origin + window.location.pathname;
6381
6534
  sessionStorage.setItem('sv_oauth_state', state);
6382
6535
  sessionStorage.setItem('sv_oauth_email', this.recipient);
6383
6536
  const authUrl = this.api.getSocialAuthUrl(provider, redirectUri, state, this.verificationState.authContext);
6384
- window.location.href = authUrl;
6537
+ navigateWith(this.options, authUrl);
6385
6538
  }
6386
6539
  normalizeError(error) {
6387
6540
  if (error instanceof IdentityApiError) {
@@ -6457,7 +6610,7 @@ class IdentityRenderer {
6457
6610
  this.close();
6458
6611
  this.safeOnSuccess(result.result);
6459
6612
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6460
- window.location.href = result.result.redirect;
6613
+ navigateWith(this.options, result.result.redirect);
6461
6614
  }
6462
6615
  }
6463
6616
  else if (result.errorType === 'cancelled') {
@@ -6489,7 +6642,7 @@ class IdentityRenderer {
6489
6642
  this.close();
6490
6643
  this.safeOnSuccess(pendingResult);
6491
6644
  if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6492
- window.location.href = pendingResult.redirect;
6645
+ navigateWith(this.options, pendingResult.redirect);
6493
6646
  }
6494
6647
  }
6495
6648
  /**
@@ -6661,7 +6814,7 @@ class IdentityRenderer {
6661
6814
  // a no-op (the document is already unloading); if not, this rescues
6662
6815
  // simple-mode flows whose host forgot to act on result.redirect.
6663
6816
  if (typeof result.redirect === 'string' && result.redirect) {
6664
- window.location.href = result.redirect;
6817
+ navigateWith(this.options, result.redirect);
6665
6818
  }
6666
6819
  }
6667
6820
  /**
@@ -6740,6 +6893,177 @@ class IdentityRenderer {
6740
6893
  }
6741
6894
  }
6742
6895
 
6896
+ /* global HTMLIFrameElement */
6897
+ /**
6898
+ * Widget Embedder
6899
+ *
6900
+ * Host-side half of the iframe architecture. For dialog (modal) verification,
6901
+ * the SDK injects a borderless, transparent, full-viewport iframe pointing at
6902
+ * the SparkVault-hosted widget page and bridges the result back over
6903
+ * postMessage. Running the flow on the SparkVault origin lets passkey login
6904
+ * complete in a single tap on every platform — the WebAuthn ceremony is
6905
+ * same-origin with the RP id and the user's tap lives in the iframe document —
6906
+ * without a popup.
6907
+ *
6908
+ * The widget renders the SDK's own modal (overlay, backdrop, chrome) inside the
6909
+ * iframe, so the page sees only a transparent full-viewport frame: no border,
6910
+ * no seam, visually identical to the in-page modal.
6911
+ */
6912
+ /** Result envelope posted by the widget page. */
6913
+ const RESULT_TYPE = 'sparkvault-identity-result';
6914
+ /** Top-window navigation request posted by the widget (OIDC / generic). */
6915
+ const REDIRECT_TYPE = 'sparkvault-identity-redirect';
6916
+ /** Social-login start request posted by the widget. */
6917
+ const SOCIAL_TYPE = 'sparkvault-identity-social';
6918
+ class WidgetEmbedder {
6919
+ constructor(config, options, callbacks) {
6920
+ this.config = config;
6921
+ this.options = options;
6922
+ this.callbacks = callbacks;
6923
+ this.iframe = null;
6924
+ this.settled = false;
6925
+ this.previousBodyOverflow = '';
6926
+ // Only ever trust messages from the Identity origin the SDK is configured
6927
+ // against — never the broader sparkvault.com family.
6928
+ this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
6929
+ this.boundHandleMessage = (event) => this.handleMessage(event);
6930
+ }
6931
+ start() {
6932
+ const iframe = document.createElement('iframe');
6933
+ iframe.src = this.buildUrl();
6934
+ iframe.title = 'Sign in';
6935
+ // Delegate WebAuthn into the cross-origin widget document so the ceremony
6936
+ // runs there. The widget response also opts in via Permissions-Policy.
6937
+ iframe.setAttribute('allow', 'publickey-credentials-get; publickey-credentials-create');
6938
+ iframe.style.cssText = [
6939
+ 'position:fixed',
6940
+ 'inset:0',
6941
+ 'width:100%',
6942
+ 'height:100%',
6943
+ 'border:0',
6944
+ 'margin:0',
6945
+ 'padding:0',
6946
+ 'background:transparent',
6947
+ 'z-index:2147483647',
6948
+ ].join(';');
6949
+ this.iframe = iframe;
6950
+ // Lock host scroll while the modal (rendered inside the iframe) is open.
6951
+ this.previousBodyOverflow = document.body.style.overflow;
6952
+ document.body.style.overflow = 'hidden';
6953
+ window.addEventListener('message', this.boundHandleMessage);
6954
+ document.body.appendChild(iframe);
6955
+ }
6956
+ close() {
6957
+ if (this.iframe?.parentNode) {
6958
+ this.iframe.parentNode.removeChild(this.iframe);
6959
+ }
6960
+ this.iframe = null;
6961
+ window.removeEventListener('message', this.boundHandleMessage);
6962
+ document.body.style.overflow = this.previousBodyOverflow;
6963
+ }
6964
+ /**
6965
+ * Begin a social-login redirect from the host. State and redirect_uri are
6966
+ * the customer's top origin so `consumeRedirectResult` validates them on
6967
+ * return. Mirrors the SDK's getSocialAuthUrl.
6968
+ */
6969
+ startSocial(provider) {
6970
+ // Provider comes from the trusted widget origin, but never build a URL from
6971
+ // an unexpected value.
6972
+ if (!/^[a-z0-9_]+$/i.test(provider))
6973
+ return;
6974
+ const state = generateState();
6975
+ try {
6976
+ sessionStorage.setItem('sv_oauth_state', state);
6977
+ }
6978
+ catch {
6979
+ // Storage disabled (private mode): proceed; the backend still binds state.
6980
+ }
6981
+ const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/social/${provider}`);
6982
+ url.searchParams.set('redirect_uri', window.location.origin + window.location.pathname);
6983
+ url.searchParams.set('state', state);
6984
+ const authContext = this.options.authContext;
6985
+ if (authContext?.authRequestId) {
6986
+ url.searchParams.set('auth_request_id', authContext.authRequestId);
6987
+ }
6988
+ if (authContext?.simpleMode) {
6989
+ const simpleMode = authContext.simpleMode.sessionId
6990
+ ? { session_id: authContext.simpleMode.sessionId }
6991
+ : {
6992
+ success_url: authContext.simpleMode.successUrl,
6993
+ failure_url: authContext.simpleMode.failureUrl,
6994
+ state: authContext.simpleMode.state,
6995
+ };
6996
+ url.searchParams.set('simple_mode', JSON.stringify(simpleMode));
6997
+ }
6998
+ this.close();
6999
+ window.location.href = url.toString();
7000
+ }
7001
+ buildUrl() {
7002
+ const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7003
+ url.searchParams.set('origin', window.location.origin);
7004
+ if (this.options.email)
7005
+ url.searchParams.set('email', this.options.email);
7006
+ if (this.options.phone)
7007
+ url.searchParams.set('phone', this.options.phone);
7008
+ if (this.options.backdropBlur === false)
7009
+ url.searchParams.set('backdrop_blur', 'false');
7010
+ const authContext = this.options.authContext;
7011
+ if (authContext?.authRequestId) {
7012
+ url.searchParams.set('auth_request_id', authContext.authRequestId);
7013
+ }
7014
+ if (authContext?.simpleMode) {
7015
+ url.searchParams.set('simple_mode', JSON.stringify({
7016
+ success_url: authContext.simpleMode.successUrl,
7017
+ failure_url: authContext.simpleMode.failureUrl,
7018
+ state: authContext.simpleMode.state,
7019
+ session_id: authContext.simpleMode.sessionId,
7020
+ }));
7021
+ }
7022
+ return url.toString();
7023
+ }
7024
+ handleMessage(event) {
7025
+ if (event.origin !== this.trustedOrigin)
7026
+ return;
7027
+ if (this.iframe && event.source !== this.iframe.contentWindow)
7028
+ return;
7029
+ const data = event.data;
7030
+ if (!data || typeof data.type !== 'string')
7031
+ return;
7032
+ // Social login: start it from the host so the OAuth state and redirect_uri
7033
+ // live on the customer's top origin (where the return is consumed).
7034
+ if (data.type === SOCIAL_TYPE && typeof data.provider === 'string') {
7035
+ this.startSocial(data.provider);
7036
+ return;
7037
+ }
7038
+ // OIDC / generic redirect: the widget cannot navigate the top window from a
7039
+ // cross-origin frame, so it asks us to. Navigating away tears down the
7040
+ // iframe; on return the host SDK consumes the redirect token.
7041
+ if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7042
+ window.location.href = data.url;
7043
+ return;
7044
+ }
7045
+ if (data.type !== RESULT_TYPE || this.settled)
7046
+ return;
7047
+ this.settled = true;
7048
+ this.close();
7049
+ if (data.success && data.result) {
7050
+ const result = data.result;
7051
+ this.callbacks.onSuccess(result);
7052
+ // Mirror the renderer's belt-and-suspenders: complete a server-issued
7053
+ // redirect from the host's own top window if the customer didn't.
7054
+ if (typeof result.redirect === 'string' && result.redirect) {
7055
+ window.location.href = result.redirect;
7056
+ }
7057
+ }
7058
+ else if (data.cancelled) {
7059
+ this.callbacks.onCancel();
7060
+ }
7061
+ else {
7062
+ this.callbacks.onError(new Error(data.error || 'Verification failed'));
7063
+ }
7064
+ }
7065
+ }
7066
+
6743
7067
  /**
6744
7068
  * Inline Container
6745
7069
  *
@@ -7014,6 +7338,7 @@ function isTokenClaims(payload) {
7014
7338
  class IdentityModule {
7015
7339
  constructor(config) {
7016
7340
  this.renderer = null;
7341
+ this.embedder = null;
7017
7342
  this.attachedElements = new Map();
7018
7343
  this.config = config;
7019
7344
  this.api = new IdentityApi(config);
@@ -7044,6 +7369,10 @@ class IdentityModule {
7044
7369
  options.onSuccess?.(redirectResult);
7045
7370
  return redirectResult;
7046
7371
  }
7372
+ if (this.embedder) {
7373
+ this.embedder.close();
7374
+ this.embedder = null;
7375
+ }
7047
7376
  if (this.renderer) {
7048
7377
  this.renderer.close();
7049
7378
  }
@@ -7051,37 +7380,53 @@ class IdentityModule {
7051
7380
  // AbortController aborted on close() would short-circuit the next
7052
7381
  // session's first request as "Request cancelled".
7053
7382
  this.api.resetSession();
7054
- const isInline = !!options.target;
7055
- const container = isInline
7056
- ? this.createInlineContainer(options.target)
7057
- : new ModalContainer();
7058
7383
  // Merge global config defaults with per-call options
7059
7384
  const mergedOptions = {
7060
7385
  ...options,
7061
7386
  // Use global backdropBlur unless explicitly overridden per-call
7062
7387
  backdropBlur: options.backdropBlur ?? this.config.backdropBlur,
7063
7388
  };
7064
- return new Promise((resolve, reject) => {
7065
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, {
7066
- onSuccess: (result) => {
7067
- options.onSuccess?.(result);
7068
- resolve(result);
7069
- },
7070
- onError: (error) => {
7071
- options.onError?.(error);
7072
- reject(error);
7073
- },
7074
- onCancel: () => {
7075
- const error = new UserCancelledError();
7076
- options.onCancel?.();
7077
- reject(error);
7078
- },
7079
- });
7080
- this.renderer.start().catch((error) => {
7389
+ // Inline rendering (target) and explicit local mode run the flow in this
7390
+ // document. Dialog mode embeds the SparkVault-hosted widget in an iframe so
7391
+ // passkey login completes in one tap with no popup. `renderMode: 'local'`
7392
+ // is how the hosted widget itself runs the flow (and avoids re-embedding).
7393
+ const isInline = !!options.target;
7394
+ const useLocal = options.renderMode === 'local' || isInline;
7395
+ let resolveRef;
7396
+ let rejectRef;
7397
+ const settledPromise = new Promise((resolve, reject) => {
7398
+ resolveRef = resolve;
7399
+ rejectRef = reject;
7400
+ });
7401
+ const hostCallbacks = {
7402
+ onSuccess: (result) => {
7403
+ options.onSuccess?.(result);
7404
+ resolveRef(result);
7405
+ },
7406
+ onError: (error) => {
7081
7407
  options.onError?.(error);
7082
- reject(error);
7083
- });
7408
+ rejectRef(error);
7409
+ },
7410
+ onCancel: () => {
7411
+ const error = new UserCancelledError();
7412
+ options.onCancel?.();
7413
+ rejectRef(error);
7414
+ },
7415
+ };
7416
+ if (!useLocal) {
7417
+ this.embedder = new WidgetEmbedder(this.config, mergedOptions, hostCallbacks);
7418
+ this.embedder.start();
7419
+ return settledPromise;
7420
+ }
7421
+ const container = isInline
7422
+ ? this.createInlineContainer(options.target)
7423
+ : new ModalContainer();
7424
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
7425
+ this.renderer.start().catch((error) => {
7426
+ options.onError?.(error);
7427
+ rejectRef(error);
7084
7428
  });
7429
+ return settledPromise;
7085
7430
  }
7086
7431
  /**
7087
7432
  * Attach identity verification to element clicks.