@sparkvault/sdk-js 8.0.1 → 8.1.0

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.
@@ -431,7 +431,7 @@ class HealthModule {
431
431
  * this; clients of the SDK never see any of it.
432
432
  */
433
433
  /** Default request timeout in milliseconds (30 seconds). */
434
- const DEFAULT_TIMEOUT_MS = 30000;
434
+ const DEFAULT_TIMEOUT_MS$1 = 30000;
435
435
  /**
436
436
  * Combine a fresh timeout with a session close signal into one AbortSignal.
437
437
  *
@@ -464,7 +464,7 @@ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
464
464
  };
465
465
  }
466
466
  class SparkVaultApi {
467
- constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
467
+ constructor(timeoutMs = DEFAULT_TIMEOUT_MS$1) {
468
468
  /**
469
469
  * Abort controller for the current session. Replaced by resetSession()
470
470
  * at the start of every user-facing session — an aborted controller can
@@ -1339,6 +1339,91 @@ class VerificationState {
1339
1339
  }
1340
1340
  }
1341
1341
 
1342
+ /**
1343
+ * Popup Launcher
1344
+ *
1345
+ * Opens a top-level popup on the Identity origin and bridges its result back
1346
+ * over postMessage. Used by both the passkey ceremony (which needs a popup so
1347
+ * WebAuthn runs same-origin with the RP id) and the dialog login flow (which
1348
+ * needs a top-level window on the IdP origin so login's first-party SSO cookie
1349
+ * persists).
1350
+ *
1351
+ * The single transfer path: synchronous `window.open` inside the user gesture
1352
+ * (so the browser never blocks it), strict `event.origin` + `data.type`
1353
+ * validation against the caller-supplied trusted origin, a 60s timeout, and a
1354
+ * `window.closed` poll that surfaces a manual close as a cancellation.
1355
+ */
1356
+ /** Default popup dimensions — a centered login/ceremony window. */
1357
+ const DEFAULT_WIDTH = 480;
1358
+ const DEFAULT_HEIGHT = 640;
1359
+ /** Default timeout for popup operations (60 seconds). */
1360
+ const DEFAULT_TIMEOUT_MS = 60000;
1361
+ /** How often to check whether the user closed the popup manually. */
1362
+ const CLOSED_POLL_INTERVAL_MS = 500;
1363
+ /**
1364
+ * Open a popup and resolve with the first validated result envelope it posts.
1365
+ *
1366
+ * Resolves with the raw `event.data` (the caller inspects its `success`/`error`
1367
+ * fields). Rejects with `PopupBlockedError` when the browser blocked the popup,
1368
+ * `UserCancelledError` when the user closed it manually, and `TimeoutError`
1369
+ * when no result arrived within the timeout.
1370
+ */
1371
+ class PopupLauncher {
1372
+ openPopup(options) {
1373
+ const width = options.width ?? DEFAULT_WIDTH;
1374
+ const height = options.height ?? DEFAULT_HEIGHT;
1375
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1376
+ return new Promise((resolve, reject) => {
1377
+ const left = Math.round((window.screen.width - width) / 2);
1378
+ const top = Math.round((window.screen.height - height) / 2);
1379
+ // Synchronous open inside the caller's user gesture — any await before
1380
+ // this point would let the browser treat the popup as programmatic and
1381
+ // block it.
1382
+ const popup = window.open(options.url, options.windowName, `width=${width},height=${height},left=${left},top=${top},popup=1`);
1383
+ if (!popup) {
1384
+ reject(new PopupBlockedError());
1385
+ return;
1386
+ }
1387
+ let settled = false;
1388
+ const cleanup = () => {
1389
+ window.removeEventListener('message', handleMessage);
1390
+ clearTimeout(timeoutId);
1391
+ clearInterval(pollClosedId);
1392
+ };
1393
+ const handleMessage = (event) => {
1394
+ // Only trust the server-validated Identity origin — never the broader
1395
+ // sparkvault.com family (XSS or subdomain-takeover relay).
1396
+ if (event.origin !== options.trustedOrigin) {
1397
+ return;
1398
+ }
1399
+ const data = event.data;
1400
+ if (data?.type !== options.resultType) {
1401
+ return;
1402
+ }
1403
+ settled = true;
1404
+ cleanup();
1405
+ resolve(data);
1406
+ };
1407
+ window.addEventListener('message', handleMessage);
1408
+ const timeoutId = setTimeout(() => {
1409
+ if (settled)
1410
+ return;
1411
+ settled = true;
1412
+ cleanup();
1413
+ popup.close();
1414
+ reject(new TimeoutError('Popup operation timed out. Please try again.'));
1415
+ }, timeoutMs);
1416
+ const pollClosedId = setInterval(() => {
1417
+ if (popup.closed && !settled) {
1418
+ settled = true;
1419
+ cleanup();
1420
+ reject(new UserCancelledError('Authentication was cancelled.'));
1421
+ }
1422
+ }, CLOSED_POLL_INTERVAL_MS);
1423
+ });
1424
+ }
1425
+ }
1426
+
1342
1427
  /**
1343
1428
  * Passkey Handler
1344
1429
  *
@@ -1352,11 +1437,11 @@ class VerificationState {
1352
1437
  * 3. Popup sends result via postMessage
1353
1438
  * 4. SDK receives result and returns to caller
1354
1439
  */
1355
- /** Popup window dimensions */
1440
+ /** Passkey popup window dimensions. */
1356
1441
  const POPUP_WIDTH = 450;
1357
1442
  const POPUP_HEIGHT = 500;
1358
- /** Timeout for popup operations (60 seconds) */
1359
- const POPUP_TIMEOUT_MS = 60000;
1443
+ /** `data.type` the passkey popup posts back. */
1444
+ const PASSKEY_RESULT_TYPE = 'sparkvault-passkey-result';
1360
1445
  /**
1361
1446
  * Handles WebAuthn passkey registration and verification via popup
1362
1447
  */
@@ -1364,6 +1449,7 @@ class PasskeyHandler {
1364
1449
  constructor(api, state) {
1365
1450
  this.api = api;
1366
1451
  this.state = state;
1452
+ this.popupLauncher = new PopupLauncher();
1367
1453
  // Extract base URL and account ID from the API's URL construction
1368
1454
  // The API uses: `${this.config.identityBaseUrl}/${this.config.accountId}`
1369
1455
  // We need to access these values for popup URL construction
@@ -1526,125 +1612,86 @@ class PasskeyHandler {
1526
1612
  };
1527
1613
  }
1528
1614
  /**
1529
- * Open passkey popup and wait for result
1615
+ * Open passkey popup (top-level on the Identity origin, so WebAuthn runs
1616
+ * same-origin with the RP id) and wait for its result.
1530
1617
  */
1531
1618
  async openPasskeyPopup(mode, registrationToken) {
1532
- return new Promise((resolve) => {
1533
- // Registration carries the freshly verified identifier so the backend can
1534
- // attach the credential to that SVID. Verification carries it too when
1535
- // known, to scope the ceremony to that person's passkeys; the credential
1536
- // userHandle still routes completion to the SVID.
1537
- const params = new URLSearchParams({
1538
- mode,
1539
- origin: window.location.origin,
1619
+ // Registration carries the freshly verified identifier so the backend can
1620
+ // attach the credential to that SVID. Verification carries it too when
1621
+ // known, to scope the ceremony to that person's passkeys; the credential
1622
+ // userHandle still routes completion to the SVID.
1623
+ const params = new URLSearchParams({
1624
+ mode,
1625
+ origin: window.location.origin,
1626
+ });
1627
+ if (this.state.recipient) {
1628
+ const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
1629
+ params.set(identityParam, this.state.recipient);
1630
+ }
1631
+ // Add auth context for OIDC/simple mode flows
1632
+ const authContext = this.state.authContext;
1633
+ if (authContext?.authRequestId) {
1634
+ params.set('auth_request_id', authContext.authRequestId);
1635
+ }
1636
+ if (authContext?.simpleMode) {
1637
+ params.set('simple_mode', JSON.stringify({
1638
+ success_url: authContext.simpleMode.successUrl,
1639
+ failure_url: authContext.simpleMode.failureUrl,
1640
+ state: authContext.simpleMode.state,
1641
+ session_id: authContext.simpleMode.sessionId,
1642
+ }));
1643
+ }
1644
+ const hash = mode === 'register' && registrationToken
1645
+ ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
1646
+ : '';
1647
+ const popupUrl = `${this.baseUrl}/${this.accountId}/passkey/popup?${params}${hash}`;
1648
+ let message;
1649
+ try {
1650
+ message = await this.popupLauncher.openPopup({
1651
+ url: popupUrl,
1652
+ windowName: 'sparkvault-passkey',
1653
+ width: POPUP_WIDTH,
1654
+ height: POPUP_HEIGHT,
1655
+ resultType: PASSKEY_RESULT_TYPE,
1656
+ trustedOrigin: this.trustedOrigin,
1540
1657
  });
1541
- if (this.state.recipient) {
1542
- const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
1543
- params.set(identityParam, this.state.recipient);
1544
- }
1545
- // Add auth context for OIDC/simple mode flows
1546
- const authContext = this.state.authContext;
1547
- if (authContext?.authRequestId) {
1548
- params.set('auth_request_id', authContext.authRequestId);
1549
- }
1550
- if (authContext?.simpleMode) {
1551
- params.set('simple_mode', JSON.stringify({
1552
- success_url: authContext.simpleMode.successUrl,
1553
- failure_url: authContext.simpleMode.failureUrl,
1554
- state: authContext.simpleMode.state,
1555
- session_id: authContext.simpleMode.sessionId,
1556
- }));
1557
- }
1558
- const hash = mode === 'register' && registrationToken
1559
- ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
1560
- : '';
1561
- const popupUrl = `${this.baseUrl}/${this.accountId}/passkey/popup?${params}${hash}`;
1562
- // Calculate popup position (centered)
1563
- const left = Math.round((window.screen.width - POPUP_WIDTH) / 2);
1564
- const top = Math.round((window.screen.height - POPUP_HEIGHT) / 2);
1565
- // Open popup
1566
- const popup = window.open(popupUrl, 'sparkvault-passkey', `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=1`);
1567
- if (!popup) {
1568
- resolve({
1658
+ }
1659
+ catch (error) {
1660
+ if (error instanceof PopupBlockedError) {
1661
+ return {
1569
1662
  success: false,
1570
- error: 'Popup was blocked. Please allow popups for this site.',
1663
+ error: error.message,
1571
1664
  errorType: 'popup_blocked',
1572
- });
1573
- return;
1665
+ };
1574
1666
  }
1575
- // Set up message listener
1576
- let resolved = false;
1577
- const cleanup = () => {
1578
- window.removeEventListener('message', handleMessage);
1579
- clearTimeout(timeoutId);
1580
- clearInterval(pollClosedId);
1667
+ if (error instanceof UserCancelledError) {
1668
+ return {
1669
+ success: false,
1670
+ error: error.message,
1671
+ errorType: 'cancelled',
1672
+ };
1673
+ }
1674
+ return {
1675
+ success: false,
1676
+ error: error instanceof Error ? error.message : 'Passkey operation failed. Please try again.',
1677
+ errorType: 'unknown',
1581
1678
  };
1582
- const handleMessage = (event) => {
1583
- // Validate origin - must be from sparkvault.com
1584
- if (!this.isValidMessageOrigin(event.origin)) {
1585
- return;
1586
- }
1587
- const data = event.data;
1588
- // Verify message type
1589
- if (data?.type !== 'sparkvault-passkey-result') {
1590
- return;
1591
- }
1592
- resolved = true;
1593
- cleanup();
1594
- if (data.success && data.data) {
1595
- resolve({
1596
- success: true,
1597
- result: {
1598
- token: data.data.token || '',
1599
- identity: data.data.identity || this.state.recipient,
1600
- identityType: data.data.identity_type || 'email',
1601
- svid: data.data.svid,
1602
- sessionId: data.data.session_id,
1603
- refreshToken: data.data.refresh_token,
1604
- redirect: data.data.redirect,
1605
- },
1606
- });
1607
- }
1608
- else {
1609
- resolve(this.handlePopupError(data.error, data.message, data.errorCode));
1610
- }
1679
+ }
1680
+ if (message.success && message.data) {
1681
+ return {
1682
+ success: true,
1683
+ result: {
1684
+ token: message.data.token || '',
1685
+ identity: message.data.identity || this.state.recipient,
1686
+ identityType: message.data.identity_type || 'email',
1687
+ svid: message.data.svid,
1688
+ sessionId: message.data.session_id,
1689
+ refreshToken: message.data.refresh_token,
1690
+ redirect: message.data.redirect,
1691
+ },
1611
1692
  };
1612
- window.addEventListener('message', handleMessage);
1613
- // Timeout after 60 seconds
1614
- const timeoutId = setTimeout(() => {
1615
- if (!resolved) {
1616
- resolved = true;
1617
- cleanup();
1618
- popup.close();
1619
- resolve({
1620
- success: false,
1621
- error: 'Passkey operation timed out. Please try again.',
1622
- errorType: 'unknown',
1623
- });
1624
- }
1625
- }, POPUP_TIMEOUT_MS);
1626
- // Poll for popup being closed manually
1627
- const pollClosedId = setInterval(() => {
1628
- if (popup.closed && !resolved) {
1629
- resolved = true;
1630
- cleanup();
1631
- resolve({
1632
- success: false,
1633
- error: 'Authentication was cancelled.',
1634
- errorType: 'cancelled',
1635
- });
1636
- }
1637
- }, 500);
1638
- });
1639
- }
1640
- /**
1641
- * Validate that a postMessage came from the identity service's own
1642
- * origin. We do not accept the broader sparkvault.com family - a popup
1643
- * is only opened against `this.baseUrl`, so any other origin is
1644
- * either an unrelated tab or a forgery attempt.
1645
- */
1646
- isValidMessageOrigin(origin) {
1647
- return origin === this.trustedOrigin;
1693
+ }
1694
+ return this.handlePopupError(message.error, message.message, message.errorCode);
1648
1695
  }
1649
1696
  /**
1650
1697
  * Handle popup error response
@@ -5744,19 +5791,6 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
5744
5791
  ].join(' '),
5745
5792
  code: 'sparklink_csp_blocked',
5746
5793
  };
5747
- /**
5748
- * Navigate the browser. When the flow runs inside the embed iframe, the host
5749
- * injects `onNavigate` (via VerifyOptions) so redirects move the customer's
5750
- * top window rather than the iframe — providers refuse to be framed anyway.
5751
- * Outside the iframe this falls back to a normal same-window navigation.
5752
- */
5753
- function navigateWith(options, url) {
5754
- if (options.onNavigate) {
5755
- options.onNavigate(url);
5756
- return;
5757
- }
5758
- window.location.href = url;
5759
- }
5760
5794
  class IdentityRenderer {
5761
5795
  constructor(container, api, options, callbacks) {
5762
5796
  // View management
@@ -6471,7 +6505,7 @@ class IdentityRenderer {
6471
6505
  this.close();
6472
6506
  this.safeOnSuccess(result);
6473
6507
  if (typeof result.redirect === 'string' && result.redirect) {
6474
- navigateWith(this.options, result.redirect);
6508
+ window.location.href = result.redirect;
6475
6509
  }
6476
6510
  }
6477
6511
  catch (error) {
@@ -6528,7 +6562,7 @@ class IdentityRenderer {
6528
6562
  this.close();
6529
6563
  this.safeOnSuccess(result.result);
6530
6564
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6531
- navigateWith(this.options, result.result.redirect);
6565
+ window.location.href = result.result.redirect;
6532
6566
  }
6533
6567
  }
6534
6568
  else if (this.renderBlockedInterstitial(result.errorCode)) ;
@@ -6593,19 +6627,12 @@ class IdentityRenderer {
6593
6627
  }
6594
6628
  handleSocialLogin(provider) {
6595
6629
  this.setState({ view: 'oauth-pending', provider });
6596
- // When embedded, social must originate from the host: the OAuth state and
6597
- // redirect_uri belong to the customer's top origin, not this iframe (whose
6598
- // sessionStorage and URL the return would never match). Hand it up.
6599
- if (this.options.onSocial) {
6600
- this.options.onSocial(provider);
6601
- return;
6602
- }
6603
6630
  const state = generateState();
6604
6631
  const redirectUri = window.location.origin + window.location.pathname;
6605
6632
  sessionStorage.setItem('sv_oauth_state', state);
6606
6633
  sessionStorage.setItem('sv_oauth_email', this.recipient);
6607
6634
  const authUrl = this.api.getSocialAuthUrl(provider, redirectUri, state, this.verificationState.authContext);
6608
- navigateWith(this.options, authUrl);
6635
+ window.location.href = authUrl;
6609
6636
  }
6610
6637
  normalizeError(error) {
6611
6638
  if (error instanceof IdentityApiError) {
@@ -6710,7 +6737,7 @@ class IdentityRenderer {
6710
6737
  this.safeOnSuccess(result);
6711
6738
  this.close();
6712
6739
  if (typeof result.redirect === 'string' && result.redirect) {
6713
- navigateWith(this.options, result.redirect);
6740
+ window.location.href = result.redirect;
6714
6741
  }
6715
6742
  }
6716
6743
  /**
@@ -7189,290 +7216,204 @@ class IdentityRenderer {
7189
7216
  }
7190
7217
  }
7191
7218
 
7192
- /* global HTMLIFrameElement requestAnimationFrame */
7193
7219
  /**
7194
- * Widget Embedder
7220
+ * Dialog Launcher
7195
7221
  *
7196
- * Host-side half of the iframe architecture. For dialog (modal) verification,
7197
- * the SDK injects a borderless, transparent, full-viewport iframe pointing at
7198
- * the SparkVault-hosted widget page and bridges the result back over
7199
- * postMessage. Running the flow on the SparkVault origin lets passkey login
7200
- * complete in a single tap on every platform — the WebAuthn ceremony is
7201
- * same-origin with the RP id and the user's tap lives in the iframe document —
7202
- * without a popup.
7222
+ * Host-side half of the popup login flow. Dialog (modal) verification renders a
7223
+ * thin email/phone launcher in the SDK's own ModalContainer, then — inside the
7224
+ * user's submit gesture — opens a TOP-LEVEL popup on the Identity origin that
7225
+ * runs the full login flow. Because the popup is top-level on api.sparkvault.com,
7226
+ * login completion's first-party `__Host-authsv_sso` cookie persists.
7203
7227
  *
7204
- * The widget renders the SDK's own modal (overlay, backdrop, chrome) inside the
7205
- * iframe, so the page sees only a transparent full-viewport frame: no border,
7206
- * no seam, visually identical to the in-page modal.
7228
+ * The launcher only collects an identifier and bridges the popup result back;
7229
+ * the flow UI itself lives in the popup (the renderMode:'local' renderer).
7207
7230
  */
7208
- /** Result envelope posted by the widget page. */
7209
- const RESULT_TYPE = 'sparkvault-identity-result';
7210
- /** Top-window navigation request posted by the widget (OIDC / generic). */
7211
- const REDIRECT_TYPE = 'sparkvault-identity-redirect';
7212
- /** Social-login start request posted by the widget. */
7213
- const SOCIAL_TYPE = 'sparkvault-identity-social';
7214
- /** Sent by the widget once its modal has mounted — proof the frame is alive. */
7215
- const READY_TYPE = 'sparkvault-identity-ready';
7231
+ /** `data.type` the login popup posts back to the opener. */
7232
+ const LOGIN_RESULT_TYPE = 'sparkvault-login-result';
7216
7233
  /**
7217
- * How long to wait for the widget frame to signal it has mounted before giving
7218
- * up and recovering in-page. The frame paints its own backdrop + spinner the
7219
- * instant it loads and posts `ready` the moment its modal mounts; a frame that
7220
- * is blocked from framing, 404s, or whose SDK never loads will never post — so
7221
- * this bounds the "scroll locked, nothing on screen" failure to a few seconds
7222
- * instead of leaving the host stuck until a manual refresh.
7234
+ * Renders the email/phone launcher modal and opens the login popup on submit.
7223
7235
  */
7224
- const FRAME_READY_TIMEOUT_MS = 8000;
7225
- class WidgetEmbedder {
7226
- constructor(config, options, callbacks) {
7236
+ class DialogLauncher {
7237
+ constructor(config, api, options, callbacks) {
7227
7238
  this.config = config;
7239
+ this.api = api;
7228
7240
  this.options = options;
7229
7241
  this.callbacks = callbacks;
7230
- this.iframe = null;
7242
+ this.modal = new ModalContainer();
7243
+ this.popupLauncher = new PopupLauncher();
7244
+ this.currentView = null;
7231
7245
  this.settled = false;
7232
- this.ready = false;
7233
- this.failed = false;
7234
- this.readyTimer = null;
7235
- this.previousBodyOverflow = '';
7236
- // Only ever trust messages from the Identity origin the SDK is configured
7237
- // against — never the broader sparkvault.com family.
7246
+ this.allowedTypes = ['email'];
7238
7247
  this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
7239
- this.boundHandleMessage = (event) => this.handleMessage(event);
7240
- this.boundHandleCspViolation = (event) => this.handleCspViolation(event);
7241
7248
  }
7249
+ /**
7250
+ * Mount the modal, then load config to render the identifier input (or a
7251
+ * terminal error view when config fails).
7252
+ */
7242
7253
  start() {
7243
- const iframe = document.createElement('iframe');
7244
- iframe.src = this.buildUrl();
7245
- iframe.title = 'Sign in';
7246
- // Delegate WebAuthn into the cross-origin widget document so the ceremony
7247
- // runs there. The widget response also opts in via Permissions-Policy.
7248
- iframe.setAttribute('allow', 'publickey-credentials-get; publickey-credentials-create');
7249
- iframe.style.cssText = [
7250
- 'position:fixed',
7251
- 'inset:0',
7252
- 'width:100%',
7253
- 'height:100%',
7254
- 'border:0',
7255
- 'margin:0',
7256
- 'padding:0',
7257
- 'background:transparent',
7258
- 'z-index:2147483647',
7259
- ].join(';');
7260
- // Promote to its own compositing layer up front. iOS Safari can otherwise
7261
- // leave a freshly-inserted fixed, full-viewport iframe loaded but UNPAINTED
7262
- // until the next composite (a scroll, resize, or app foreground) — the
7263
- // frame even runs, but the dialog only appears after an app switch.
7264
- iframe.style.transform = 'translateZ(0)';
7265
- iframe.style.willChange = 'transform';
7266
- // A network-level load failure (DNS, connection reset) fires onerror; an
7267
- // HTTP error body or a frame blocked from framing does not, which is what
7268
- // the readiness timeout below covers.
7269
- iframe.onerror = () => this.handleFrameUnavailable();
7270
- this.iframe = iframe;
7271
- // Lock host scroll while the modal (rendered inside the iframe) is open.
7272
- this.previousBodyOverflow = document.body.style.overflow;
7273
- document.body.style.overflow = 'hidden';
7274
- window.addEventListener('message', this.boundHandleMessage);
7275
- // A host-page CSP whose frame-src/child-src omits the Identity origin blocks
7276
- // the iframe before it can load and fires no `onerror`. Catch the violation
7277
- // so we fail over to the in-page flow at once instead of after the timeout.
7278
- document.addEventListener('securitypolicyviolation', this.boundHandleCspViolation);
7279
- document.body.appendChild(iframe);
7280
- // Force the composite the iframe insertion may not have triggered on iOS,
7281
- // so the dialog paints on the click rather than only after an app switch.
7282
- this.forceComposite(iframe);
7283
- this.readyTimer = setTimeout(() => this.handleFrameUnavailable(), FRAME_READY_TIMEOUT_MS);
7284
- }
7285
- /**
7286
- * Nudge the browser to paint the just-inserted iframe on the next frame.
7287
- * Reading layout forces a reflow; toggling a transform forces the compositor
7288
- * to flush the new layer — the workaround for iOS Safari leaving a fixed
7289
- * full-viewport iframe invisible until an unrelated repaint.
7290
- */
7291
- forceComposite(iframe) {
7292
- const paint = () => {
7293
- if (!this.iframe)
7294
- return;
7295
- void iframe.offsetHeight;
7296
- iframe.style.transform = 'translateZ(0) scale(1)';
7297
- };
7298
- if (typeof requestAnimationFrame === 'function') {
7299
- requestAnimationFrame(paint);
7300
- }
7301
- else {
7302
- setTimeout(paint, 16);
7303
- }
7304
- }
7305
- close() {
7306
- this.clearReadyTimer();
7307
- if (this.iframe?.parentNode) {
7308
- this.iframe.parentNode.removeChild(this.iframe);
7309
- }
7310
- this.iframe = null;
7311
- window.removeEventListener('message', this.boundHandleMessage);
7312
- document.removeEventListener('securitypolicyviolation', this.boundHandleCspViolation);
7313
- document.body.style.overflow = this.previousBodyOverflow;
7254
+ this.modal.createLoading({ backdropBlur: this.options.backdropBlur }, () => this.handleClose());
7255
+ this.api
7256
+ .getConfig()
7257
+ .then((config) => this.renderInput(config))
7258
+ .catch((error) => this.renderConfigError(error));
7314
7259
  }
7315
7260
  /**
7316
- * Host CSP blocked the widget iframe (frame-src/child-src). The frame can
7317
- * never load, so fail over to the in-page flow immediately.
7261
+ * Close the launcher and tear everything down. Cancels in-flight config
7262
+ * requests so a late resolution can't render into a destroyed modal.
7318
7263
  */
7319
- handleCspViolation(event) {
7320
- const directive = event.effectiveDirective || event.violatedDirective;
7321
- if (directive !== 'frame-src' && directive !== 'child-src')
7322
- return;
7323
- // blockedURI is the framed URL (sometimes just its origin); match either.
7324
- if (typeof event.blockedURI === 'string' && event.blockedURI.startsWith(this.trustedOrigin)) {
7325
- this.handleFrameUnavailable();
7326
- }
7264
+ close() {
7265
+ this.api.abort();
7266
+ this.currentView?.destroy?.();
7267
+ this.currentView = null;
7268
+ this.modal.destroy();
7327
7269
  }
7328
- clearReadyTimer() {
7329
- if (this.readyTimer !== null) {
7330
- clearTimeout(this.readyTimer);
7331
- this.readyTimer = null;
7270
+ handleClose() {
7271
+ this.close();
7272
+ if (!this.settled) {
7273
+ this.settled = true;
7274
+ this.callbacks.onCancel();
7332
7275
  }
7333
7276
  }
7334
- /**
7335
- * The widget frame never became interactive. Tear down, release the host
7336
- * scroll lock, and hand control back so the flow can run in-page. Guarded so
7337
- * a late onerror or timeout firing after a real result (or after the frame
7338
- * has proven itself with `ready`) is a no-op.
7339
- */
7340
- handleFrameUnavailable() {
7341
- if (this.settled || this.failed || this.ready)
7342
- return;
7343
- this.failed = true;
7344
- this.close();
7345
- this.callbacks.onFrameUnavailable();
7277
+ renderInput(config) {
7278
+ if (config.branding) {
7279
+ this.modal.updateBranding(config.branding);
7280
+ }
7281
+ const resolvedBackdropBlur = this.options.backdropBlur !== undefined
7282
+ ? this.options.backdropBlur
7283
+ : config.branding?.backdrop_blur ?? true;
7284
+ this.modal.updateBackdropBlur(resolvedBackdropBlur);
7285
+ this.allowedTypes = (config.allowedIdentityTypes ?? ['email']);
7286
+ this.mountInput(undefined);
7346
7287
  }
7347
7288
  /**
7348
- * Begin a social-login redirect from the host. State and redirect_uri are
7349
- * the customer's top origin so `consumeRedirectResult` validates them on
7350
- * return. Mirrors the SDK's getSocialAuthUrl.
7289
+ * Render the identifier input. The submit handler runs synchronously inside
7290
+ * the user gesture, so the popup open is never treated as programmatic (and
7291
+ * never blocked).
7351
7292
  */
7352
- startSocial(provider) {
7353
- // Provider comes from the trusted widget origin, but never build a URL from
7354
- // an unexpected value.
7355
- if (!/^[a-z0-9_]+$/i.test(provider))
7356
- return;
7357
- const state = generateState();
7358
- try {
7359
- sessionStorage.setItem('sv_oauth_state', state);
7360
- }
7361
- catch {
7362
- // Storage disabled (private mode): proceed; the backend still binds state.
7363
- }
7364
- const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/social/${provider}`);
7365
- url.searchParams.set('redirect_uri', window.location.origin + window.location.pathname);
7366
- url.searchParams.set('state', state);
7367
- const authContext = this.options.authContext;
7368
- if (authContext?.authRequestId) {
7369
- url.searchParams.set('auth_request_id', authContext.authRequestId);
7370
- }
7371
- if (authContext?.simpleMode) {
7372
- const simpleMode = authContext.simpleMode.sessionId
7373
- ? { session_id: authContext.simpleMode.sessionId }
7374
- : {
7375
- success_url: authContext.simpleMode.successUrl,
7376
- failure_url: authContext.simpleMode.failureUrl,
7377
- state: authContext.simpleMode.state,
7378
- };
7379
- url.searchParams.set('simple_mode', JSON.stringify(simpleMode));
7380
- }
7381
- this.close();
7382
- window.location.href = url.toString();
7293
+ mountInput(error) {
7294
+ this.mountView(new IdentityInputView({
7295
+ allowedTypes: this.allowedTypes,
7296
+ initialValue: this.options.email ?? this.options.phone,
7297
+ error,
7298
+ onSubmit: (result) => this.handleIdentitySubmit(result),
7299
+ }));
7383
7300
  }
7384
7301
  /**
7385
- * Navigate the host top window to a widget-supplied URL — only when it
7386
- * resolves to http(s). The sender is already constrained to the trusted
7387
- * widget origin, but defense-in-depth across the SparkVault->customer
7388
- * boundary: compromised widget-origin code must never escalate into script
7389
- * execution on the embedding page via a javascript:/data: navigation.
7302
+ * Open the login popup for the submitted identifier. SYNCHRONOUS: no await
7303
+ * precedes window.open, so the browser keeps the user-gesture grant.
7390
7304
  */
7391
- safeNavigate(url) {
7392
- let resolved;
7393
- try {
7394
- resolved = new URL(url, window.location.href);
7395
- }
7396
- catch {
7397
- return;
7398
- }
7399
- if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
7400
- return;
7401
- }
7402
- window.location.href = resolved.href;
7403
- }
7404
- buildUrl() {
7405
- const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7406
- url.searchParams.set('origin', window.location.origin);
7407
- if (this.options.email)
7408
- url.searchParams.set('email', this.options.email);
7409
- if (this.options.phone)
7410
- url.searchParams.set('phone', this.options.phone);
7411
- if (this.options.backdropBlur === false)
7412
- url.searchParams.set('backdrop_blur', 'false');
7305
+ handleIdentitySubmit(result) {
7306
+ this.popupLauncher
7307
+ .openPopup({
7308
+ url: this.buildPopupUrl(result),
7309
+ windowName: 'sparkvault-login',
7310
+ resultType: LOGIN_RESULT_TYPE,
7311
+ trustedOrigin: this.trustedOrigin,
7312
+ })
7313
+ .then((message) => this.handlePopupResult(message))
7314
+ .catch((error) => this.handlePopupError(error));
7315
+ }
7316
+ buildPopupUrl(result) {
7317
+ const params = new URLSearchParams({ origin: window.location.origin });
7318
+ params.set(result.type, result.value);
7413
7319
  const authContext = this.options.authContext;
7414
7320
  if (authContext?.authRequestId) {
7415
- url.searchParams.set('auth_request_id', authContext.authRequestId);
7321
+ params.set('auth_request_id', authContext.authRequestId);
7416
7322
  }
7417
7323
  if (authContext?.simpleMode) {
7418
- url.searchParams.set('simple_mode', JSON.stringify({
7324
+ params.set('simple_mode', JSON.stringify({
7419
7325
  success_url: authContext.simpleMode.successUrl,
7420
7326
  failure_url: authContext.simpleMode.failureUrl,
7421
7327
  state: authContext.simpleMode.state,
7422
7328
  session_id: authContext.simpleMode.sessionId,
7423
7329
  }));
7424
7330
  }
7425
- return url.toString();
7331
+ return `${this.config.identityBaseUrl}/${this.config.accountId}/popup?${params}`;
7426
7332
  }
7427
- handleMessage(event) {
7428
- if (event.origin !== this.trustedOrigin)
7429
- return;
7430
- if (this.iframe && event.source !== this.iframe.contentWindow)
7333
+ handlePopupResult(message) {
7334
+ if (message.success && message.data) {
7335
+ const result = {
7336
+ token: message.data.token || '',
7337
+ identity: message.data.identity || '',
7338
+ identityType: message.data.identity_type || 'email',
7339
+ svid: message.data.svid,
7340
+ sessionId: message.data.session_id,
7341
+ refreshToken: message.data.refresh_token,
7342
+ redirect: message.data.redirect,
7343
+ };
7344
+ this.finish();
7345
+ this.callbacks.onSuccess(result);
7431
7346
  return;
7432
- const data = event.data;
7433
- if (!data || typeof data.type !== 'string')
7347
+ }
7348
+ if (message.error === 'cancelled') {
7349
+ // User backed out inside the popup — re-render the input so they can
7350
+ // retry from the still-open launcher.
7351
+ this.reEnableInput(undefined);
7434
7352
  return;
7435
- // The frame mounted its modal — it is alive and owns the interaction now.
7436
- // Cancel the readiness timeout so a slow-but-working frame is never torn
7437
- // down and recovered in-page.
7438
- if (data.type === READY_TYPE) {
7439
- this.ready = true;
7440
- this.clearReadyTimer();
7353
+ }
7354
+ this.finish();
7355
+ this.callbacks.onError(new SparkVaultError(message.message || message.error || 'Verification failed', message.errorCode || message.error || 'verification_failed'));
7356
+ }
7357
+ handlePopupError(error) {
7358
+ if (error instanceof UserCancelledError) {
7359
+ // Manual popup close — let the user retry from the still-open launcher.
7360
+ this.reEnableInput(undefined);
7441
7361
  return;
7442
7362
  }
7443
- // Social login: start it from the host so the OAuth state and redirect_uri
7444
- // live on the customer's top origin (where the return is consumed).
7445
- if (data.type === SOCIAL_TYPE && typeof data.provider === 'string') {
7446
- this.startSocial(data.provider);
7363
+ if (error instanceof PopupBlockedError) {
7364
+ // Same inline "allow popups" surface the passkey path shows.
7365
+ this.reEnableInput(error.message);
7447
7366
  return;
7448
7367
  }
7449
- // OIDC / generic redirect: the widget cannot navigate the top window from a
7450
- // cross-origin frame, so it asks us to. Navigating away tears down the
7451
- // iframe; on return the host SDK consumes the redirect token.
7452
- if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7453
- this.clearReadyTimer();
7454
- this.safeNavigate(data.url);
7368
+ this.finish();
7369
+ this.callbacks.onError(error instanceof Error ? error : new Error(String(error)));
7370
+ }
7371
+ /**
7372
+ * Re-render the input (its Continue button is disabled to "Please wait…" on
7373
+ * submit) so it is interactive again after a cancelled or blocked popup.
7374
+ */
7375
+ reEnableInput(error) {
7376
+ if (this.settled || !this.modal.isOpen())
7455
7377
  return;
7378
+ this.mountInput(error);
7379
+ }
7380
+ renderConfigError(error) {
7381
+ this.mountView(this.viewForConfigError(error));
7382
+ }
7383
+ viewForConfigError(error) {
7384
+ if (error instanceof IdentityApiError) {
7385
+ if (error.code === 'product_not_configured') {
7386
+ return new ProductNotConfiguredView({ onClose: () => this.handleClose() });
7387
+ }
7388
+ if (error.code === 'ORIGIN_NOT_ALLOWED') {
7389
+ const origin = typeof error.details?.origin === 'string' ? error.details.origin : undefined;
7390
+ return new OriginNotAllowedView({ origin, onClose: () => this.handleClose() });
7391
+ }
7456
7392
  }
7457
- if (data.type !== RESULT_TYPE || this.settled)
7393
+ return new ServiceUnavailableView({
7394
+ onRetry: () => this.retryConfig(),
7395
+ onClose: () => this.handleClose(),
7396
+ });
7397
+ }
7398
+ retryConfig() {
7399
+ this.mountView(new LoadingView({ message: 'Loading...' }));
7400
+ this.api
7401
+ .getConfig()
7402
+ .then((config) => this.renderInput(config))
7403
+ .catch((err) => this.renderConfigError(err));
7404
+ }
7405
+ mountView(view) {
7406
+ const body = this.modal.getBody();
7407
+ if (!body)
7458
7408
  return;
7409
+ this.currentView?.destroy?.();
7410
+ clearChildren(body);
7411
+ this.currentView = view;
7412
+ body.appendChild(view.render());
7413
+ }
7414
+ finish() {
7459
7415
  this.settled = true;
7460
7416
  this.close();
7461
- if (data.success && data.result) {
7462
- const result = data.result;
7463
- this.callbacks.onSuccess(result);
7464
- // Mirror the renderer's belt-and-suspenders: complete a server-issued
7465
- // redirect from the host's own top window if the customer didn't.
7466
- if (typeof result.redirect === 'string' && result.redirect) {
7467
- this.safeNavigate(result.redirect);
7468
- }
7469
- }
7470
- else if (data.cancelled) {
7471
- this.callbacks.onCancel();
7472
- }
7473
- else {
7474
- this.callbacks.onError(new Error(data.error || 'Verification failed'));
7475
- }
7476
7417
  }
7477
7418
  }
7478
7419
 
@@ -7806,7 +7747,7 @@ function isTokenClaims(payload) {
7806
7747
  class IdentityModule {
7807
7748
  constructor(config) {
7808
7749
  this.renderer = null;
7809
- this.embedder = null;
7750
+ this.launcher = null;
7810
7751
  this.config = config;
7811
7752
  this.api = new IdentityApi(config);
7812
7753
  // Preload config in background for instant dialog opening
@@ -7940,9 +7881,9 @@ class IdentityModule {
7940
7881
  options.onSuccess?.(redirectResult);
7941
7882
  return redirectResult;
7942
7883
  }
7943
- if (this.embedder) {
7944
- this.embedder.close();
7945
- this.embedder = null;
7884
+ if (this.launcher) {
7885
+ this.launcher.close();
7886
+ this.launcher = null;
7946
7887
  }
7947
7888
  if (this.renderer) {
7948
7889
  this.renderer.close();
@@ -7958,9 +7899,9 @@ class IdentityModule {
7958
7899
  backdropBlur: options.backdropBlur ?? this.config.backdropBlur,
7959
7900
  };
7960
7901
  // Inline rendering (target) and explicit local mode run the flow in this
7961
- // document. Dialog mode embeds the SparkVault-hosted widget in an iframe so
7962
- // passkey login completes in one tap with no popup. `renderMode: 'local'`
7963
- // is how the hosted widget itself runs the flow (and avoids re-embedding).
7902
+ // document. Dialog mode renders a thin launcher and opens a top-level popup
7903
+ // on the Identity origin for the flow (so login's first-party SSO cookie
7904
+ // persists). `renderMode: 'local'` is how the popup itself runs the flow.
7964
7905
  const isInline = !!options.target;
7965
7906
  const useLocal = options.renderMode === 'local' || isInline;
7966
7907
  let resolveRef;
@@ -7988,38 +7929,23 @@ class IdentityModule {
7988
7929
  this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
7989
7930
  this.renderer.start().catch((error) => {
7990
7931
  // A startup failure must surface inside the SparkVault dialog, never
7991
- // close it silently. Rejecting here would, in the default embedded
7992
- // mode, run the host's onError and let the embedding page remove the
7993
- // iframe — leaving the user with a vanished dialog and no error. Render
7994
- // the error in-dialog instead (consistent with every in-flow error);
7995
- // the promise settles later via the user's retry/close.
7932
+ // close it silently. Render the error in-dialog instead (consistent with
7933
+ // every in-flow error); the promise settles later via retry/close.
7996
7934
  this.renderer?.showStartupError(error);
7997
7935
  });
7998
7936
  };
7999
7937
  if (!useLocal) {
8000
7938
  // When the preloaded config has already failed *permanently* — this origin
8001
7939
  // is not a verified domain, or the account hasn't configured Identity —
8002
- // the hosted widget cannot help: it never frames an unverified origin, so
8003
- // embedding it would only hang until the readiness timeout. Render the
8004
- // error dialog in-page right away instead. Transient failures fall through
8005
- // to the iframe so one-tap passkey login is preserved.
7940
+ // the popup cannot help: the IdP will reject the unverified origin. Render
7941
+ // the error dialog in-page right away instead. Transient failures fall
7942
+ // through to the launcher, which surfaces them in its own dialog.
8006
7943
  if (await this.preloadedConfigPermanentlyFailed()) {
8007
7944
  startLocalRender(new ModalContainer());
8008
7945
  return settledPromise;
8009
7946
  }
8010
- this.embedder = new WidgetEmbedder(this.config, mergedOptions, {
8011
- ...hostCallbacks,
8012
- onFrameUnavailable: () => {
8013
- // The hosted widget iframe could not load or mount (blocked from
8014
- // framing, network failure, blank render, or its in-frame SDK never
8015
- // loaded). Recover by running the verification flow in this document
8016
- // — the same local path inline rendering uses — so login still works
8017
- // and the host scroll lock the embedder set has already been released.
8018
- this.embedder = null;
8019
- startLocalRender(new ModalContainer());
8020
- },
8021
- });
8022
- this.embedder.start();
7947
+ this.launcher = new DialogLauncher(this.config, this.api, mergedOptions, hostCallbacks);
7948
+ this.launcher.start();
8023
7949
  return settledPromise;
8024
7950
  }
8025
7951
  startLocalRender(isInline ? this.createInlineContainer(options.target) : new ModalContainer());
@@ -8184,14 +8110,13 @@ class IdentityModule {
8184
8110
  /**
8185
8111
  * Close the identity dialog/inline UI if open.
8186
8112
  *
8187
- * Tears down whichever surface is active: the hosted-widget iframe
8188
- * (default dialog mode — also releases the embedder's host scroll lock)
8189
- * or the local renderer (inline / local mode).
8113
+ * Tears down whichever surface is active: the dialog launcher (default dialog
8114
+ * mode) or the local renderer (inline / local mode).
8190
8115
  */
8191
8116
  close() {
8192
- if (this.embedder) {
8193
- this.embedder.close();
8194
- this.embedder = null;
8117
+ if (this.launcher) {
8118
+ this.launcher.close();
8119
+ this.launcher = null;
8195
8120
  }
8196
8121
  if (this.renderer) {
8197
8122
  this.renderer.close();
@@ -8200,12 +8125,12 @@ class IdentityModule {
8200
8125
  }
8201
8126
  /**
8202
8127
  * Whether the preloaded config has already settled as a *permanent* failure
8203
- * the hosted widget can't surface (origin not allowed, or product not
8204
- * configured). Used to skip the iframe and show the error dialog in-page
8205
- * immediately. Returns false — proceed to embed — when config is not
8206
- * preloaded, still in flight (raced against a short timeout so the common
8207
- * path is never delayed), resolved, or failed only transiently (so one-tap
8208
- * passkey login via the frame is preserved).
8128
+ * the popup can't surface (origin not allowed, or product not configured).
8129
+ * Used to skip the launcher and show the error dialog in-page immediately.
8130
+ * Returns false — proceed to the launcher — when config is not preloaded,
8131
+ * still in flight (raced against a short timeout so the common path is never
8132
+ * delayed), resolved, or failed only transiently (the launcher surfaces a
8133
+ * transient failure in its own dialog).
8209
8134
  */
8210
8135
  async preloadedConfigPermanentlyFailed() {
8211
8136
  if (!this.api.isConfigPreloaded())