@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.
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Widget Embedder
3
+ *
4
+ * Host-side half of the iframe architecture. For dialog (modal) verification,
5
+ * the SDK injects a borderless, transparent, full-viewport iframe pointing at
6
+ * the SparkVault-hosted widget page and bridges the result back over
7
+ * postMessage. Running the flow on the SparkVault origin lets passkey login
8
+ * complete in a single tap on every platform — the WebAuthn ceremony is
9
+ * same-origin with the RP id and the user's tap lives in the iframe document —
10
+ * without a popup.
11
+ *
12
+ * The widget renders the SDK's own modal (overlay, backdrop, chrome) inside the
13
+ * iframe, so the page sees only a transparent full-viewport frame: no border,
14
+ * no seam, visually identical to the in-page modal.
15
+ */
16
+ import type { ResolvedConfig } from '../config';
17
+ import type { VerifyOptions, VerifyResult } from './types';
18
+ interface EmbedderCallbacks {
19
+ onSuccess: (result: VerifyResult) => void;
20
+ onError: (error: Error) => void;
21
+ onCancel: () => void;
22
+ }
23
+ export declare class WidgetEmbedder {
24
+ private readonly config;
25
+ private readonly options;
26
+ private readonly callbacks;
27
+ private iframe;
28
+ private settled;
29
+ private previousBodyOverflow;
30
+ private readonly trustedOrigin;
31
+ private readonly boundHandleMessage;
32
+ constructor(config: ResolvedConfig, options: VerifyOptions, callbacks: EmbedderCallbacks);
33
+ start(): void;
34
+ close(): void;
35
+ /**
36
+ * Begin a social-login redirect from the host. State and redirect_uri are
37
+ * the customer's top origin so `consumeRedirectResult` validates them on
38
+ * return. Mirrors the SDK's getSocialAuthUrl.
39
+ */
40
+ private startSocial;
41
+ private buildUrl;
42
+ private handleMessage;
43
+ }
44
+ export {};
@@ -60,9 +60,32 @@ export declare class PasskeyHandler {
60
60
  */
61
61
  register(registrationToken?: string): Promise<PasskeyResult>;
62
62
  /**
63
- * Verify user with existing passkey via popup
63
+ * Verify user with an existing passkey.
64
+ *
65
+ * On the Identity origin (the hosted widget / hosted login) the ceremony runs
66
+ * inline — same-origin with the RP id, one tap, no popup. On a third-party
67
+ * origin the rpId would not match the document, so it falls back to the popup
68
+ * served from the Identity origin. (Verification, unlike registration, is
69
+ * supported in cross-origin iframes, so the embedded widget uses the inline
70
+ * path.)
64
71
  */
65
72
  verify(): Promise<PasskeyResult>;
73
+ /**
74
+ * True when the SDK is running ON the Identity origin and the browser exposes
75
+ * WebAuthn — the only place an inline ceremony's rpId matches the document.
76
+ */
77
+ private canRunCeremonyInline;
78
+ /**
79
+ * Run the discoverable verification ceremony directly in this document and
80
+ * map the outcome onto the same PasskeyResult shape the popup produces.
81
+ */
82
+ private verifyInline;
83
+ /**
84
+ * Map a thrown inline-ceremony error onto PasskeyResult, mirroring the
85
+ * popup's error codes so the widget renders the same dedicated states
86
+ * (cancelled, identity locked, no passkey → registration).
87
+ */
88
+ private mapInlineCeremonyError;
66
89
  /**
67
90
  * Open passkey popup and wait for result
68
91
  */
@@ -19,6 +19,7 @@ export declare class IdentityModule {
19
19
  private readonly config;
20
20
  private readonly api;
21
21
  private renderer;
22
+ private embedder;
22
23
  private attachedElements;
23
24
  constructor(config: ResolvedConfig);
24
25
  /**
@@ -36,6 +36,27 @@ export interface VerifyOptions {
36
36
  backdropBlur?: boolean;
37
37
  /** Auth context for OIDC/simple mode flows (used by hosted login) */
38
38
  authContext?: AuthContext;
39
+ /**
40
+ * Rendering strategy (internal).
41
+ * - `'embed'` (default for dialog mode): inject a cross-origin iframe to the
42
+ * SparkVault-hosted widget and bridge the result. Lets passkey login
43
+ * complete in one tap with no popup.
44
+ * - `'local'`: render the flow directly in this document. Used inside the
45
+ * hosted widget itself, and forced for inline (`target`) rendering.
46
+ */
47
+ renderMode?: 'embed' | 'local';
48
+ /**
49
+ * Navigation override (internal). When the flow runs inside the embed
50
+ * iframe, redirects (social, OIDC) are handed to the host's top window via
51
+ * this hook instead of navigating the iframe. Omitted outside the iframe.
52
+ */
53
+ onNavigate?: (url: string) => void;
54
+ /**
55
+ * Social-login override (internal). When embedded, social must be started
56
+ * from the host so its OAuth state and redirect_uri live on the customer's
57
+ * top origin. The renderer hands the provider up instead of redirecting.
58
+ */
59
+ onSocial?: (provider: string) => void;
39
60
  /** Called when user cancels (if omitted, uses server-configured redirect) */
40
61
  onCancel?: () => void;
41
62
  /** Called when verification completes (if omitted, uses server-configured redirect) */
package/dist/index.d.ts CHANGED
@@ -101,6 +101,27 @@ interface VerifyOptions {
101
101
  backdropBlur?: boolean;
102
102
  /** Auth context for OIDC/simple mode flows (used by hosted login) */
103
103
  authContext?: AuthContext;
104
+ /**
105
+ * Rendering strategy (internal).
106
+ * - `'embed'` (default for dialog mode): inject a cross-origin iframe to the
107
+ * SparkVault-hosted widget and bridge the result. Lets passkey login
108
+ * complete in one tap with no popup.
109
+ * - `'local'`: render the flow directly in this document. Used inside the
110
+ * hosted widget itself, and forced for inline (`target`) rendering.
111
+ */
112
+ renderMode?: 'embed' | 'local';
113
+ /**
114
+ * Navigation override (internal). When the flow runs inside the embed
115
+ * iframe, redirects (social, OIDC) are handed to the host's top window via
116
+ * this hook instead of navigating the iframe. Omitted outside the iframe.
117
+ */
118
+ onNavigate?: (url: string) => void;
119
+ /**
120
+ * Social-login override (internal). When embedded, social must be started
121
+ * from the host so its OAuth state and redirect_uri live on the customer's
122
+ * top origin. The renderer hands the provider up instead of redirecting.
123
+ */
124
+ onSocial?: (provider: string) => void;
104
125
  /** Called when user cancels (if omitted, uses server-configured redirect) */
105
126
  onCancel?: () => void;
106
127
  /** Called when verification completes (if omitted, uses server-configured redirect) */
@@ -217,6 +238,7 @@ declare class IdentityModule {
217
238
  private readonly config;
218
239
  private readonly api;
219
240
  private renderer;
241
+ private embedder;
220
242
  private attachedElements;
221
243
  constructor(config: ResolvedConfig);
222
244
  /**
@@ -836,6 +836,35 @@ function base64urlEncode(data) {
836
836
  function arrayBufferToBase64url(buffer) {
837
837
  return base64urlEncode(new Uint8Array(buffer));
838
838
  }
839
+ /**
840
+ * Decode base64url string to Uint8Array
841
+ *
842
+ * @param base64url - Base64url encoded string
843
+ * @returns Decoded bytes as Uint8Array
844
+ */
845
+ function base64urlDecode(base64url) {
846
+ const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
847
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
848
+ const binary = atob(padded);
849
+ const bytes = new Uint8Array(binary.length);
850
+ for (let i = 0; i < binary.length; i++) {
851
+ bytes[i] = binary.charCodeAt(i);
852
+ }
853
+ return bytes;
854
+ }
855
+ /**
856
+ * Decode base64url string to ArrayBuffer
857
+ *
858
+ * @param base64url - Base64url encoded string
859
+ * @returns Decoded ArrayBuffer
860
+ */
861
+ function base64urlToArrayBuffer(base64url) {
862
+ const bytes = base64urlDecode(base64url);
863
+ // Create a new ArrayBuffer with exact copy (avoids TypeScript ArrayBufferLike issue)
864
+ const buffer = new ArrayBuffer(bytes.length);
865
+ new Uint8Array(buffer).set(bytes);
866
+ return buffer;
867
+ }
839
868
  /**
840
869
  * Decode base64url string to UTF-8 string
841
870
  *
@@ -1572,11 +1601,115 @@ class PasskeyHandler {
1572
1601
  return result;
1573
1602
  }
1574
1603
  /**
1575
- * Verify user with existing passkey via popup
1604
+ * Verify user with an existing passkey.
1605
+ *
1606
+ * On the Identity origin (the hosted widget / hosted login) the ceremony runs
1607
+ * inline — same-origin with the RP id, one tap, no popup. On a third-party
1608
+ * origin the rpId would not match the document, so it falls back to the popup
1609
+ * served from the Identity origin. (Verification, unlike registration, is
1610
+ * supported in cross-origin iframes, so the embedded widget uses the inline
1611
+ * path.)
1576
1612
  */
1577
1613
  async verify() {
1614
+ if (this.canRunCeremonyInline()) {
1615
+ return this.verifyInline();
1616
+ }
1578
1617
  return this.openPasskeyPopup('verify');
1579
1618
  }
1619
+ /**
1620
+ * True when the SDK is running ON the Identity origin and the browser exposes
1621
+ * WebAuthn — the only place an inline ceremony's rpId matches the document.
1622
+ */
1623
+ canRunCeremonyInline() {
1624
+ return typeof window !== 'undefined'
1625
+ && typeof navigator !== 'undefined'
1626
+ && !!navigator.credentials
1627
+ && window.location.origin === this.trustedOrigin;
1628
+ }
1629
+ /**
1630
+ * Run the discoverable verification ceremony directly in this document and
1631
+ * map the outcome onto the same PasskeyResult shape the popup produces.
1632
+ */
1633
+ async verifyInline() {
1634
+ try {
1635
+ const challenge = await this.api.startPasskeyVerify(undefined, 'email', this.state.authContext);
1636
+ const credential = await navigator.credentials.get({
1637
+ publicKey: {
1638
+ challenge: base64urlToArrayBuffer(challenge.challenge),
1639
+ rpId: challenge.rpId,
1640
+ timeout: challenge.timeout,
1641
+ userVerification: 'required',
1642
+ },
1643
+ });
1644
+ if (!credential) {
1645
+ return { success: false, error: 'Failed to get passkey', errorType: 'unknown' };
1646
+ }
1647
+ const response = await this.api.completePasskeyVerify({
1648
+ session: challenge.session,
1649
+ credential,
1650
+ authContext: this.state.authContext,
1651
+ });
1652
+ return {
1653
+ success: true,
1654
+ result: {
1655
+ token: response.token,
1656
+ identity: response.identity || this.state.recipient,
1657
+ identityType: response.identity_type || 'email',
1658
+ svid: response.svid,
1659
+ sessionId: response.session_id,
1660
+ refreshToken: response.refresh_token,
1661
+ redirect: response.redirect,
1662
+ },
1663
+ };
1664
+ }
1665
+ catch (error) {
1666
+ return this.mapInlineCeremonyError(error);
1667
+ }
1668
+ }
1669
+ /**
1670
+ * Map a thrown inline-ceremony error onto PasskeyResult, mirroring the
1671
+ * popup's error codes so the widget renders the same dedicated states
1672
+ * (cancelled, identity locked, no passkey → registration).
1673
+ */
1674
+ mapInlineCeremonyError(error) {
1675
+ // User dismissed the system sheet, or no credential was available.
1676
+ if (error instanceof Error && error.name === 'NotAllowedError') {
1677
+ return {
1678
+ success: false,
1679
+ error: 'Authentication was cancelled. Please try again.',
1680
+ errorType: 'cancelled',
1681
+ };
1682
+ }
1683
+ if (error instanceof IdentityApiError) {
1684
+ if (error.code === 'identity_locked') {
1685
+ return {
1686
+ success: false,
1687
+ error: 'This SparkVault Identity is locked. Visit auth.sv to manage it.',
1688
+ errorType: 'unknown',
1689
+ errorCode: 'identity_locked',
1690
+ };
1691
+ }
1692
+ if (error.code === 'passkey_not_registered') {
1693
+ return {
1694
+ success: false,
1695
+ error: 'No passkey found. Create one to continue.',
1696
+ errorType: 'not_found',
1697
+ errorCode: 'passkey_not_registered',
1698
+ };
1699
+ }
1700
+ return {
1701
+ success: false,
1702
+ error: error.message || 'Passkey authentication failed',
1703
+ errorType: 'unknown',
1704
+ errorCode: error.code,
1705
+ };
1706
+ }
1707
+ return {
1708
+ success: false,
1709
+ error: error instanceof Error ? error.message : 'Passkey authentication failed',
1710
+ errorType: 'unknown',
1711
+ };
1712
+ }
1580
1713
  /**
1581
1714
  * Open passkey popup and wait for result
1582
1715
  */
@@ -5613,6 +5746,19 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
5613
5746
  ].join(' '),
5614
5747
  code: 'sparklink_csp_blocked',
5615
5748
  };
5749
+ /**
5750
+ * Navigate the browser. When the flow runs inside the embed iframe, the host
5751
+ * injects `onNavigate` (via VerifyOptions) so redirects move the customer's
5752
+ * top window rather than the iframe — providers refuse to be framed anyway.
5753
+ * Outside the iframe this falls back to a normal same-window navigation.
5754
+ */
5755
+ function navigateWith(options, url) {
5756
+ if (options.onNavigate) {
5757
+ options.onNavigate(url);
5758
+ return;
5759
+ }
5760
+ window.location.href = url;
5761
+ }
5616
5762
  class IdentityRenderer {
5617
5763
  constructor(container, api, options, callbacks) {
5618
5764
  // View management
@@ -6189,7 +6335,7 @@ class IdentityRenderer {
6189
6335
  // page-level handler can act before we navigate away.
6190
6336
  this.safeOnSuccess(result.result);
6191
6337
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6192
- window.location.href = result.result.redirect;
6338
+ navigateWith(this.options, result.result.redirect);
6193
6339
  }
6194
6340
  }
6195
6341
  else if (result.errorCode === 'identity_locked') {
@@ -6256,7 +6402,7 @@ class IdentityRenderer {
6256
6402
  this.close();
6257
6403
  this.safeOnSuccess(result);
6258
6404
  if (typeof result.redirect === 'string' && result.redirect) {
6259
- window.location.href = result.redirect;
6405
+ navigateWith(this.options, result.redirect);
6260
6406
  }
6261
6407
  }
6262
6408
  catch (error) {
@@ -6311,7 +6457,7 @@ class IdentityRenderer {
6311
6457
  this.close();
6312
6458
  this.safeOnSuccess(result.result);
6313
6459
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6314
- window.location.href = result.result.redirect;
6460
+ navigateWith(this.options, result.result.redirect);
6315
6461
  }
6316
6462
  }
6317
6463
  else if (result.errorCode === 'identity_locked') {
@@ -6374,18 +6520,25 @@ class IdentityRenderer {
6374
6520
  this.close();
6375
6521
  this.safeOnSuccess(pendingResult);
6376
6522
  if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6377
- window.location.href = pendingResult.redirect;
6523
+ navigateWith(this.options, pendingResult.redirect);
6378
6524
  }
6379
6525
  }
6380
6526
  }
6381
6527
  handleSocialLogin(provider) {
6382
6528
  this.setState({ view: 'oauth-pending', provider });
6529
+ // When embedded, social must originate from the host: the OAuth state and
6530
+ // redirect_uri belong to the customer's top origin, not this iframe (whose
6531
+ // sessionStorage and URL the return would never match). Hand it up.
6532
+ if (this.options.onSocial) {
6533
+ this.options.onSocial(provider);
6534
+ return;
6535
+ }
6383
6536
  const state = generateState();
6384
6537
  const redirectUri = window.location.origin + window.location.pathname;
6385
6538
  sessionStorage.setItem('sv_oauth_state', state);
6386
6539
  sessionStorage.setItem('sv_oauth_email', this.recipient);
6387
6540
  const authUrl = this.api.getSocialAuthUrl(provider, redirectUri, state, this.verificationState.authContext);
6388
- window.location.href = authUrl;
6541
+ navigateWith(this.options, authUrl);
6389
6542
  }
6390
6543
  normalizeError(error) {
6391
6544
  if (error instanceof IdentityApiError) {
@@ -6461,7 +6614,7 @@ class IdentityRenderer {
6461
6614
  this.close();
6462
6615
  this.safeOnSuccess(result.result);
6463
6616
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6464
- window.location.href = result.result.redirect;
6617
+ navigateWith(this.options, result.result.redirect);
6465
6618
  }
6466
6619
  }
6467
6620
  else if (result.errorType === 'cancelled') {
@@ -6493,7 +6646,7 @@ class IdentityRenderer {
6493
6646
  this.close();
6494
6647
  this.safeOnSuccess(pendingResult);
6495
6648
  if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6496
- window.location.href = pendingResult.redirect;
6649
+ navigateWith(this.options, pendingResult.redirect);
6497
6650
  }
6498
6651
  }
6499
6652
  /**
@@ -6665,7 +6818,7 @@ class IdentityRenderer {
6665
6818
  // a no-op (the document is already unloading); if not, this rescues
6666
6819
  // simple-mode flows whose host forgot to act on result.redirect.
6667
6820
  if (typeof result.redirect === 'string' && result.redirect) {
6668
- window.location.href = result.redirect;
6821
+ navigateWith(this.options, result.redirect);
6669
6822
  }
6670
6823
  }
6671
6824
  /**
@@ -6744,6 +6897,177 @@ class IdentityRenderer {
6744
6897
  }
6745
6898
  }
6746
6899
 
6900
+ /* global HTMLIFrameElement */
6901
+ /**
6902
+ * Widget Embedder
6903
+ *
6904
+ * Host-side half of the iframe architecture. For dialog (modal) verification,
6905
+ * the SDK injects a borderless, transparent, full-viewport iframe pointing at
6906
+ * the SparkVault-hosted widget page and bridges the result back over
6907
+ * postMessage. Running the flow on the SparkVault origin lets passkey login
6908
+ * complete in a single tap on every platform — the WebAuthn ceremony is
6909
+ * same-origin with the RP id and the user's tap lives in the iframe document —
6910
+ * without a popup.
6911
+ *
6912
+ * The widget renders the SDK's own modal (overlay, backdrop, chrome) inside the
6913
+ * iframe, so the page sees only a transparent full-viewport frame: no border,
6914
+ * no seam, visually identical to the in-page modal.
6915
+ */
6916
+ /** Result envelope posted by the widget page. */
6917
+ const RESULT_TYPE = 'sparkvault-identity-result';
6918
+ /** Top-window navigation request posted by the widget (OIDC / generic). */
6919
+ const REDIRECT_TYPE = 'sparkvault-identity-redirect';
6920
+ /** Social-login start request posted by the widget. */
6921
+ const SOCIAL_TYPE = 'sparkvault-identity-social';
6922
+ class WidgetEmbedder {
6923
+ constructor(config, options, callbacks) {
6924
+ this.config = config;
6925
+ this.options = options;
6926
+ this.callbacks = callbacks;
6927
+ this.iframe = null;
6928
+ this.settled = false;
6929
+ this.previousBodyOverflow = '';
6930
+ // Only ever trust messages from the Identity origin the SDK is configured
6931
+ // against — never the broader sparkvault.com family.
6932
+ this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
6933
+ this.boundHandleMessage = (event) => this.handleMessage(event);
6934
+ }
6935
+ start() {
6936
+ const iframe = document.createElement('iframe');
6937
+ iframe.src = this.buildUrl();
6938
+ iframe.title = 'Sign in';
6939
+ // Delegate WebAuthn into the cross-origin widget document so the ceremony
6940
+ // runs there. The widget response also opts in via Permissions-Policy.
6941
+ iframe.setAttribute('allow', 'publickey-credentials-get; publickey-credentials-create');
6942
+ iframe.style.cssText = [
6943
+ 'position:fixed',
6944
+ 'inset:0',
6945
+ 'width:100%',
6946
+ 'height:100%',
6947
+ 'border:0',
6948
+ 'margin:0',
6949
+ 'padding:0',
6950
+ 'background:transparent',
6951
+ 'z-index:2147483647',
6952
+ ].join(';');
6953
+ this.iframe = iframe;
6954
+ // Lock host scroll while the modal (rendered inside the iframe) is open.
6955
+ this.previousBodyOverflow = document.body.style.overflow;
6956
+ document.body.style.overflow = 'hidden';
6957
+ window.addEventListener('message', this.boundHandleMessage);
6958
+ document.body.appendChild(iframe);
6959
+ }
6960
+ close() {
6961
+ if (this.iframe?.parentNode) {
6962
+ this.iframe.parentNode.removeChild(this.iframe);
6963
+ }
6964
+ this.iframe = null;
6965
+ window.removeEventListener('message', this.boundHandleMessage);
6966
+ document.body.style.overflow = this.previousBodyOverflow;
6967
+ }
6968
+ /**
6969
+ * Begin a social-login redirect from the host. State and redirect_uri are
6970
+ * the customer's top origin so `consumeRedirectResult` validates them on
6971
+ * return. Mirrors the SDK's getSocialAuthUrl.
6972
+ */
6973
+ startSocial(provider) {
6974
+ // Provider comes from the trusted widget origin, but never build a URL from
6975
+ // an unexpected value.
6976
+ if (!/^[a-z0-9_]+$/i.test(provider))
6977
+ return;
6978
+ const state = generateState();
6979
+ try {
6980
+ sessionStorage.setItem('sv_oauth_state', state);
6981
+ }
6982
+ catch {
6983
+ // Storage disabled (private mode): proceed; the backend still binds state.
6984
+ }
6985
+ const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/social/${provider}`);
6986
+ url.searchParams.set('redirect_uri', window.location.origin + window.location.pathname);
6987
+ url.searchParams.set('state', state);
6988
+ const authContext = this.options.authContext;
6989
+ if (authContext?.authRequestId) {
6990
+ url.searchParams.set('auth_request_id', authContext.authRequestId);
6991
+ }
6992
+ if (authContext?.simpleMode) {
6993
+ const simpleMode = authContext.simpleMode.sessionId
6994
+ ? { session_id: authContext.simpleMode.sessionId }
6995
+ : {
6996
+ success_url: authContext.simpleMode.successUrl,
6997
+ failure_url: authContext.simpleMode.failureUrl,
6998
+ state: authContext.simpleMode.state,
6999
+ };
7000
+ url.searchParams.set('simple_mode', JSON.stringify(simpleMode));
7001
+ }
7002
+ this.close();
7003
+ window.location.href = url.toString();
7004
+ }
7005
+ buildUrl() {
7006
+ const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7007
+ url.searchParams.set('origin', window.location.origin);
7008
+ if (this.options.email)
7009
+ url.searchParams.set('email', this.options.email);
7010
+ if (this.options.phone)
7011
+ url.searchParams.set('phone', this.options.phone);
7012
+ if (this.options.backdropBlur === false)
7013
+ url.searchParams.set('backdrop_blur', 'false');
7014
+ const authContext = this.options.authContext;
7015
+ if (authContext?.authRequestId) {
7016
+ url.searchParams.set('auth_request_id', authContext.authRequestId);
7017
+ }
7018
+ if (authContext?.simpleMode) {
7019
+ url.searchParams.set('simple_mode', JSON.stringify({
7020
+ success_url: authContext.simpleMode.successUrl,
7021
+ failure_url: authContext.simpleMode.failureUrl,
7022
+ state: authContext.simpleMode.state,
7023
+ session_id: authContext.simpleMode.sessionId,
7024
+ }));
7025
+ }
7026
+ return url.toString();
7027
+ }
7028
+ handleMessage(event) {
7029
+ if (event.origin !== this.trustedOrigin)
7030
+ return;
7031
+ if (this.iframe && event.source !== this.iframe.contentWindow)
7032
+ return;
7033
+ const data = event.data;
7034
+ if (!data || typeof data.type !== 'string')
7035
+ return;
7036
+ // Social login: start it from the host so the OAuth state and redirect_uri
7037
+ // live on the customer's top origin (where the return is consumed).
7038
+ if (data.type === SOCIAL_TYPE && typeof data.provider === 'string') {
7039
+ this.startSocial(data.provider);
7040
+ return;
7041
+ }
7042
+ // OIDC / generic redirect: the widget cannot navigate the top window from a
7043
+ // cross-origin frame, so it asks us to. Navigating away tears down the
7044
+ // iframe; on return the host SDK consumes the redirect token.
7045
+ if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7046
+ window.location.href = data.url;
7047
+ return;
7048
+ }
7049
+ if (data.type !== RESULT_TYPE || this.settled)
7050
+ return;
7051
+ this.settled = true;
7052
+ this.close();
7053
+ if (data.success && data.result) {
7054
+ const result = data.result;
7055
+ this.callbacks.onSuccess(result);
7056
+ // Mirror the renderer's belt-and-suspenders: complete a server-issued
7057
+ // redirect from the host's own top window if the customer didn't.
7058
+ if (typeof result.redirect === 'string' && result.redirect) {
7059
+ window.location.href = result.redirect;
7060
+ }
7061
+ }
7062
+ else if (data.cancelled) {
7063
+ this.callbacks.onCancel();
7064
+ }
7065
+ else {
7066
+ this.callbacks.onError(new Error(data.error || 'Verification failed'));
7067
+ }
7068
+ }
7069
+ }
7070
+
6747
7071
  /**
6748
7072
  * Inline Container
6749
7073
  *
@@ -7018,6 +7342,7 @@ function isTokenClaims(payload) {
7018
7342
  class IdentityModule {
7019
7343
  constructor(config) {
7020
7344
  this.renderer = null;
7345
+ this.embedder = null;
7021
7346
  this.attachedElements = new Map();
7022
7347
  this.config = config;
7023
7348
  this.api = new IdentityApi(config);
@@ -7048,6 +7373,10 @@ class IdentityModule {
7048
7373
  options.onSuccess?.(redirectResult);
7049
7374
  return redirectResult;
7050
7375
  }
7376
+ if (this.embedder) {
7377
+ this.embedder.close();
7378
+ this.embedder = null;
7379
+ }
7051
7380
  if (this.renderer) {
7052
7381
  this.renderer.close();
7053
7382
  }
@@ -7055,37 +7384,53 @@ class IdentityModule {
7055
7384
  // AbortController aborted on close() would short-circuit the next
7056
7385
  // session's first request as "Request cancelled".
7057
7386
  this.api.resetSession();
7058
- const isInline = !!options.target;
7059
- const container = isInline
7060
- ? this.createInlineContainer(options.target)
7061
- : new ModalContainer();
7062
7387
  // Merge global config defaults with per-call options
7063
7388
  const mergedOptions = {
7064
7389
  ...options,
7065
7390
  // Use global backdropBlur unless explicitly overridden per-call
7066
7391
  backdropBlur: options.backdropBlur ?? this.config.backdropBlur,
7067
7392
  };
7068
- return new Promise((resolve, reject) => {
7069
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, {
7070
- onSuccess: (result) => {
7071
- options.onSuccess?.(result);
7072
- resolve(result);
7073
- },
7074
- onError: (error) => {
7075
- options.onError?.(error);
7076
- reject(error);
7077
- },
7078
- onCancel: () => {
7079
- const error = new UserCancelledError();
7080
- options.onCancel?.();
7081
- reject(error);
7082
- },
7083
- });
7084
- this.renderer.start().catch((error) => {
7393
+ // Inline rendering (target) and explicit local mode run the flow in this
7394
+ // document. Dialog mode embeds the SparkVault-hosted widget in an iframe so
7395
+ // passkey login completes in one tap with no popup. `renderMode: 'local'`
7396
+ // is how the hosted widget itself runs the flow (and avoids re-embedding).
7397
+ const isInline = !!options.target;
7398
+ const useLocal = options.renderMode === 'local' || isInline;
7399
+ let resolveRef;
7400
+ let rejectRef;
7401
+ const settledPromise = new Promise((resolve, reject) => {
7402
+ resolveRef = resolve;
7403
+ rejectRef = reject;
7404
+ });
7405
+ const hostCallbacks = {
7406
+ onSuccess: (result) => {
7407
+ options.onSuccess?.(result);
7408
+ resolveRef(result);
7409
+ },
7410
+ onError: (error) => {
7085
7411
  options.onError?.(error);
7086
- reject(error);
7087
- });
7412
+ rejectRef(error);
7413
+ },
7414
+ onCancel: () => {
7415
+ const error = new UserCancelledError();
7416
+ options.onCancel?.();
7417
+ rejectRef(error);
7418
+ },
7419
+ };
7420
+ if (!useLocal) {
7421
+ this.embedder = new WidgetEmbedder(this.config, mergedOptions, hostCallbacks);
7422
+ this.embedder.start();
7423
+ return settledPromise;
7424
+ }
7425
+ const container = isInline
7426
+ ? this.createInlineContainer(options.target)
7427
+ : new ModalContainer();
7428
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
7429
+ this.renderer.start().catch((error) => {
7430
+ options.onError?.(error);
7431
+ rejectRef(error);
7088
7432
  });
7433
+ return settledPromise;
7089
7434
  }
7090
7435
  /**
7091
7436
  * Attach identity verification to element clicks.