@sparkvault/sdk-js 8.0.1 → 8.1.1

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.
@@ -130,6 +130,7 @@ Object.freeze([
130
130
  SPARKVAULT_ROOT_DOMAIN,
131
131
  'app.sparkvault.com',
132
132
  'api.sparkvault.com',
133
+ 'auth.sparkvault.com',
133
134
  'cdn.sparkvault.com',
134
135
  'forge.sparkvault.com',
135
136
  'img.sparkvault.com',
@@ -431,7 +432,7 @@ class HealthModule {
431
432
  * this; clients of the SDK never see any of it.
432
433
  */
433
434
  /** Default request timeout in milliseconds (30 seconds). */
434
- const DEFAULT_TIMEOUT_MS = 30000;
435
+ const DEFAULT_TIMEOUT_MS$1 = 30000;
435
436
  /**
436
437
  * Combine a fresh timeout with a session close signal into one AbortSignal.
437
438
  *
@@ -464,7 +465,7 @@ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
464
465
  };
465
466
  }
466
467
  class SparkVaultApi {
467
- constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
468
+ constructor(timeoutMs = DEFAULT_TIMEOUT_MS$1) {
468
469
  /**
469
470
  * Abort controller for the current session. Replaced by resetSession()
470
471
  * at the start of every user-facing session — an aborted controller can
@@ -1339,6 +1340,97 @@ class VerificationState {
1339
1340
  }
1340
1341
  }
1341
1342
 
1343
+ /**
1344
+ * Popup Launcher
1345
+ *
1346
+ * Opens a top-level popup on the Identity origin and bridges its result back
1347
+ * over postMessage. Used by both the passkey ceremony (which needs a popup so
1348
+ * WebAuthn runs same-origin with the RP id) and the dialog login flow (which
1349
+ * needs a top-level window on the IdP origin so login's first-party SSO cookie
1350
+ * persists).
1351
+ *
1352
+ * The single transfer path: synchronous `window.open` inside the user gesture
1353
+ * (so the browser never blocks it), strict `event.origin` + `data.type`
1354
+ * validation against the caller-supplied trusted origin, a 60s timeout, and a
1355
+ * `window.closed` poll that surfaces a manual close as a cancellation.
1356
+ */
1357
+ /** Default popup dimensions — a centered login/ceremony window. */
1358
+ const DEFAULT_WIDTH = 480;
1359
+ const DEFAULT_HEIGHT = 640;
1360
+ /** Default timeout for popup operations (60 seconds). */
1361
+ const DEFAULT_TIMEOUT_MS = 60000;
1362
+ /** How often to check whether the user closed the popup manually. */
1363
+ const CLOSED_POLL_INTERVAL_MS = 500;
1364
+ /**
1365
+ * Open a popup and resolve with the first validated result envelope it posts.
1366
+ *
1367
+ * Resolves with the raw `event.data` (the caller inspects its `success`/`error`
1368
+ * fields). Rejects with `PopupBlockedError` when the browser blocked the popup,
1369
+ * `UserCancelledError` when the user closed it manually, and `TimeoutError`
1370
+ * when no result arrived within the timeout.
1371
+ */
1372
+ class PopupLauncher {
1373
+ openPopup(options) {
1374
+ const width = options.width ?? DEFAULT_WIDTH;
1375
+ const height = options.height ?? DEFAULT_HEIGHT;
1376
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1377
+ return new Promise((resolve, reject) => {
1378
+ const left = Math.round((window.screen.width - width) / 2);
1379
+ const top = Math.round((window.screen.height - height) / 2);
1380
+ // Synchronous open inside the caller's user gesture — any await before
1381
+ // this point would let the browser treat the popup as programmatic and
1382
+ // block it.
1383
+ const popup = window.open(options.url, options.windowName, `width=${width},height=${height},left=${left},top=${top},popup=1`);
1384
+ if (!popup) {
1385
+ reject(new PopupBlockedError());
1386
+ return;
1387
+ }
1388
+ options.onOpen?.(popup);
1389
+ let settled = false;
1390
+ const cleanup = () => {
1391
+ window.removeEventListener('message', handleMessage);
1392
+ clearTimeout(timeoutId);
1393
+ clearInterval(pollClosedId);
1394
+ };
1395
+ const handleMessage = (event) => {
1396
+ // Only trust the server-validated Identity origin — never the broader
1397
+ // sparkvault.com family (XSS or subdomain-takeover relay).
1398
+ if (event.origin !== options.trustedOrigin) {
1399
+ return;
1400
+ }
1401
+ const data = event.data;
1402
+ // A "ready" ping confirms the window loaded; notify but don't settle.
1403
+ if (options.readyType && data?.type === options.readyType) {
1404
+ options.onReady?.();
1405
+ return;
1406
+ }
1407
+ if (data?.type !== options.resultType) {
1408
+ return;
1409
+ }
1410
+ settled = true;
1411
+ cleanup();
1412
+ resolve(data);
1413
+ };
1414
+ window.addEventListener('message', handleMessage);
1415
+ const timeoutId = setTimeout(() => {
1416
+ if (settled)
1417
+ return;
1418
+ settled = true;
1419
+ cleanup();
1420
+ popup.close();
1421
+ reject(new TimeoutError('Popup operation timed out. Please try again.'));
1422
+ }, timeoutMs);
1423
+ const pollClosedId = setInterval(() => {
1424
+ if (popup.closed && !settled) {
1425
+ settled = true;
1426
+ cleanup();
1427
+ reject(new UserCancelledError('Authentication was cancelled.'));
1428
+ }
1429
+ }, CLOSED_POLL_INTERVAL_MS);
1430
+ });
1431
+ }
1432
+ }
1433
+
1342
1434
  /**
1343
1435
  * Passkey Handler
1344
1436
  *
@@ -1352,11 +1444,11 @@ class VerificationState {
1352
1444
  * 3. Popup sends result via postMessage
1353
1445
  * 4. SDK receives result and returns to caller
1354
1446
  */
1355
- /** Popup window dimensions */
1447
+ /** Passkey popup window dimensions. */
1356
1448
  const POPUP_WIDTH = 450;
1357
1449
  const POPUP_HEIGHT = 500;
1358
- /** Timeout for popup operations (60 seconds) */
1359
- const POPUP_TIMEOUT_MS = 60000;
1450
+ /** `data.type` the passkey popup posts back. */
1451
+ const PASSKEY_RESULT_TYPE = 'sparkvault-passkey-result';
1360
1452
  /**
1361
1453
  * Handles WebAuthn passkey registration and verification via popup
1362
1454
  */
@@ -1364,6 +1456,7 @@ class PasskeyHandler {
1364
1456
  constructor(api, state) {
1365
1457
  this.api = api;
1366
1458
  this.state = state;
1459
+ this.popupLauncher = new PopupLauncher();
1367
1460
  // Extract base URL and account ID from the API's URL construction
1368
1461
  // The API uses: `${this.config.identityBaseUrl}/${this.config.accountId}`
1369
1462
  // We need to access these values for popup URL construction
@@ -1526,125 +1619,86 @@ class PasskeyHandler {
1526
1619
  };
1527
1620
  }
1528
1621
  /**
1529
- * Open passkey popup and wait for result
1622
+ * Open passkey popup (top-level on the Identity origin, so WebAuthn runs
1623
+ * same-origin with the RP id) and wait for its result.
1530
1624
  */
1531
1625
  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,
1626
+ // Registration carries the freshly verified identifier so the backend can
1627
+ // attach the credential to that SVID. Verification carries it too when
1628
+ // known, to scope the ceremony to that person's passkeys; the credential
1629
+ // userHandle still routes completion to the SVID.
1630
+ const params = new URLSearchParams({
1631
+ mode,
1632
+ origin: window.location.origin,
1633
+ });
1634
+ if (this.state.recipient) {
1635
+ const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
1636
+ params.set(identityParam, this.state.recipient);
1637
+ }
1638
+ // Add auth context for OIDC/simple mode flows
1639
+ const authContext = this.state.authContext;
1640
+ if (authContext?.authRequestId) {
1641
+ params.set('auth_request_id', authContext.authRequestId);
1642
+ }
1643
+ if (authContext?.simpleMode) {
1644
+ params.set('simple_mode', JSON.stringify({
1645
+ success_url: authContext.simpleMode.successUrl,
1646
+ failure_url: authContext.simpleMode.failureUrl,
1647
+ state: authContext.simpleMode.state,
1648
+ session_id: authContext.simpleMode.sessionId,
1649
+ }));
1650
+ }
1651
+ const hash = mode === 'register' && registrationToken
1652
+ ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
1653
+ : '';
1654
+ const popupUrl = `${this.baseUrl}/${this.accountId}/passkey/popup?${params}${hash}`;
1655
+ let message;
1656
+ try {
1657
+ message = await this.popupLauncher.openPopup({
1658
+ url: popupUrl,
1659
+ windowName: 'sparkvault-passkey',
1660
+ width: POPUP_WIDTH,
1661
+ height: POPUP_HEIGHT,
1662
+ resultType: PASSKEY_RESULT_TYPE,
1663
+ trustedOrigin: this.trustedOrigin,
1540
1664
  });
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({
1665
+ }
1666
+ catch (error) {
1667
+ if (error instanceof PopupBlockedError) {
1668
+ return {
1569
1669
  success: false,
1570
- error: 'Popup was blocked. Please allow popups for this site.',
1670
+ error: error.message,
1571
1671
  errorType: 'popup_blocked',
1572
- });
1573
- return;
1672
+ };
1574
1673
  }
1575
- // Set up message listener
1576
- let resolved = false;
1577
- const cleanup = () => {
1578
- window.removeEventListener('message', handleMessage);
1579
- clearTimeout(timeoutId);
1580
- clearInterval(pollClosedId);
1674
+ if (error instanceof UserCancelledError) {
1675
+ return {
1676
+ success: false,
1677
+ error: error.message,
1678
+ errorType: 'cancelled',
1679
+ };
1680
+ }
1681
+ return {
1682
+ success: false,
1683
+ error: error instanceof Error ? error.message : 'Passkey operation failed. Please try again.',
1684
+ errorType: 'unknown',
1581
1685
  };
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
- }
1686
+ }
1687
+ if (message.success && message.data) {
1688
+ return {
1689
+ success: true,
1690
+ result: {
1691
+ token: message.data.token || '',
1692
+ identity: message.data.identity || this.state.recipient,
1693
+ identityType: message.data.identity_type || 'email',
1694
+ svid: message.data.svid,
1695
+ sessionId: message.data.session_id,
1696
+ refreshToken: message.data.refresh_token,
1697
+ redirect: message.data.redirect,
1698
+ },
1611
1699
  };
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;
1700
+ }
1701
+ return this.handlePopupError(message.error, message.message, message.errorCode);
1648
1702
  }
1649
1703
  /**
1650
1704
  * Handle popup error response
@@ -1879,12 +1933,13 @@ const STYLE_ID$1 = 'sparkvault-identity-styles';
1879
1933
  */
1880
1934
  function injectStyles(options) {
1881
1935
  if (document.getElementById(STYLE_ID$1)) {
1882
- updateThemeVariables(options.branding);
1936
+ applyBrandingTheme(options.branding);
1883
1937
  updateBlur(options.backdropBlur);
1884
1938
  return;
1885
1939
  }
1886
1940
  const style = document.createElement('style');
1887
1941
  style.id = STYLE_ID$1;
1942
+ style.dataset.svTheme = resolveTheme(options.branding);
1888
1943
  style.textContent = getStyles(options);
1889
1944
  document.head.appendChild(style);
1890
1945
  }
@@ -1899,8 +1954,26 @@ function updateBlur(enabled) {
1899
1954
  }
1900
1955
  }
1901
1956
  }
1902
- function updateThemeVariables(_branding) {
1903
- // v1 branding doesn't include customizable colors
1957
+ /**
1958
+ * Re-theme the injected stylesheet when the resolved theme (light/dark) changes.
1959
+ *
1960
+ * Styles are first injected with default branding before config loads (so the
1961
+ * UI paints instantly), then `updateBranding` calls this with the tenant's real
1962
+ * `themeMode`. The theme is baked into the generated CSS (not runtime CSS
1963
+ * variables), so a theme switch requires regenerating the stylesheet - a no-op
1964
+ * when the theme is unchanged.
1965
+ */
1966
+ function applyBrandingTheme(branding) {
1967
+ const style = document.getElementById(STYLE_ID$1);
1968
+ if (!style)
1969
+ return;
1970
+ const theme = resolveTheme(branding);
1971
+ if (style.dataset.svTheme === theme)
1972
+ return;
1973
+ style.dataset.svTheme = theme;
1974
+ style.textContent = getStyles({
1975
+ branding: branding ?? { companyName: '', logoLight: null, logoDark: null },
1976
+ });
1904
1977
  }
1905
1978
  function resolveTheme(branding) {
1906
1979
  // Use themeMode from server config, default to light
@@ -1910,12 +1983,20 @@ function getStyles(options) {
1910
1983
  const { branding, backdropBlur } = options;
1911
1984
  const isDark = resolveTheme(branding) === 'dark';
1912
1985
  const enableBlur = backdropBlur !== false;
1913
- // Design tokens
1986
+ // Design tokens.
1987
+ //
1988
+ // The brand accent is driven by the `--sv-primary` / `--sv-primary-hover`
1989
+ // CSS custom properties so a host page (e.g. the SparkVault sign-in page) can
1990
+ // tint the whole flow to the tenant's brand color by setting them on `:root`.
1991
+ // The literals are the fallback - when no host sets the variables the UI is
1992
+ // pixel-identical to before. The focus glow is derived from the same accent
1993
+ // via color-mix so it tracks the brand too.
1994
+ const accent = 'var(--sv-primary, #4F46E5)';
1914
1995
  const tokens = {
1915
1996
  // Colors
1916
- primary: '#4F46E5',
1917
- primaryHover: '#4338CA',
1918
- primaryLight: isDark ? 'rgba(99, 102, 241, 0.15)' : 'rgba(79, 70, 229, 0.08)',
1997
+ primary: accent,
1998
+ primaryHover: 'var(--sv-primary-hover, #4338CA)',
1999
+ primaryLight: `color-mix(in srgb, ${accent} ${isDark ? '20%' : '9%'}, transparent)`,
1919
2000
  error: '#DC2626',
1920
2001
  errorLight: isDark ? 'rgba(220, 38, 38, 0.15)' : '#FEF2F2',
1921
2002
  errorBorder: isDark ? 'rgba(220, 38, 38, 0.3)' : '#FECACA',
@@ -1927,7 +2008,7 @@ function getStyles(options) {
1927
2008
  // Borders
1928
2009
  border: isDark ? '#262626' : '#E5E5E5',
1929
2010
  borderHover: isDark ? '#404040' : '#D4D4D4',
1930
- borderFocus: '#4F46E5',
2011
+ borderFocus: accent,
1931
2012
  // Text
1932
2013
  textPrimary: isDark ? '#FAFAFA' : '#0A0A0A',
1933
2014
  textSecondary: isDark ? '#A3A3A3' : '#525252',
@@ -2025,11 +2106,11 @@ function getStyles(options) {
2025
2106
  display: flex;
2026
2107
  align-items: center;
2027
2108
  justify-content: center;
2028
- background: transparent;
2109
+ background: ${tokens.bgSubtle};
2029
2110
  border: none;
2030
2111
  border-radius: 8px;
2031
2112
  cursor: pointer;
2032
- color: ${tokens.textMuted};
2113
+ color: ${tokens.textSecondary};
2033
2114
  transition: background 0.15s ease, color 0.15s ease;
2034
2115
  }
2035
2116
 
@@ -2078,6 +2159,7 @@ function getStyles(options) {
2078
2159
  color: ${tokens.textSecondary};
2079
2160
  margin: 0 0 16px 0;
2080
2161
  text-align: center;
2162
+ text-wrap: balance;
2081
2163
  }
2082
2164
 
2083
2165
  .sv-subtitle strong {
@@ -3145,6 +3227,130 @@ function getStyles(options) {
3145
3227
  padding-right: 32px;
3146
3228
  }
3147
3229
 
3230
+ /* Bare mode: the host page owns the surface and chrome, so the container
3231
+ is transparent and edge-free and the body hugs its content. */
3232
+ .sv-inline-bare {
3233
+ border: none;
3234
+ border-radius: 0;
3235
+ background: transparent;
3236
+ height: auto;
3237
+ }
3238
+
3239
+ .sv-inline-bare > .sv-inline-body {
3240
+ min-height: 0;
3241
+ padding-left: 0;
3242
+ padding-right: 0;
3243
+ }
3244
+
3245
+ /* ========================================
3246
+ BRIDGE MODAL (host page, while the sign-in popup runs)
3247
+ ======================================== */
3248
+
3249
+ .sv-bridge {
3250
+ text-align: center;
3251
+ padding: 4px 4px 6px;
3252
+ }
3253
+
3254
+ .sv-bridge-dots {
3255
+ display: flex;
3256
+ gap: 6px;
3257
+ align-items: center;
3258
+ justify-content: center;
3259
+ margin-bottom: 20px;
3260
+ }
3261
+
3262
+ .sv-bridge-dots span {
3263
+ width: 7px;
3264
+ height: 7px;
3265
+ border-radius: 50%;
3266
+ background: ${tokens.primary};
3267
+ animation: sv-bridge-pulse 1.3s ease-in-out infinite;
3268
+ }
3269
+
3270
+ .sv-bridge-dots span:nth-child(2) { animation-delay: 0.16s; }
3271
+ .sv-bridge-dots span:nth-child(3) { animation-delay: 0.32s; }
3272
+
3273
+ @keyframes sv-bridge-pulse {
3274
+ 0%, 100% { opacity: 0.28; transform: translateY(0); }
3275
+ 50% { opacity: 1; transform: translateY(-3px); }
3276
+ }
3277
+
3278
+ /* Warning shown under the logo only when the popup can't be confirmed -
3279
+ blocked, closed, or no result after a few seconds. Hidden on the happy
3280
+ path; appears with a gentle fade. */
3281
+ .sv-bridge-alert {
3282
+ display: flex;
3283
+ align-items: flex-start;
3284
+ gap: 10px;
3285
+ text-align: left;
3286
+ margin: 0 0 22px;
3287
+ padding: 11px 13px;
3288
+ border: 1px solid ${tokens.border};
3289
+ border-radius: 10px;
3290
+ background: ${tokens.bgSubtle};
3291
+ font-size: 13px;
3292
+ line-height: 1.45;
3293
+ opacity: 0;
3294
+ max-height: 0;
3295
+ padding-top: 0;
3296
+ padding-bottom: 0;
3297
+ margin-bottom: 0;
3298
+ border-width: 0;
3299
+ overflow: hidden;
3300
+ transition: opacity 0.25s ease;
3301
+ }
3302
+
3303
+ .sv-bridge-alert.sv-shown {
3304
+ opacity: 1;
3305
+ max-height: 120px;
3306
+ padding-top: 11px;
3307
+ padding-bottom: 11px;
3308
+ margin-bottom: 22px;
3309
+ border-width: 1px;
3310
+ }
3311
+
3312
+ .sv-bridge-alert-icon {
3313
+ flex-shrink: 0;
3314
+ width: 17px;
3315
+ height: 17px;
3316
+ margin-top: 1px;
3317
+ color: #d97706;
3318
+ }
3319
+
3320
+ /* Text stacked over the action, so the message keeps the full width and
3321
+ never wraps to a lone word beside a right-aligned button. */
3322
+ .sv-bridge-alert-body {
3323
+ display: flex;
3324
+ flex-direction: column;
3325
+ align-items: flex-start;
3326
+ gap: 7px;
3327
+ flex: 1;
3328
+ min-width: 0;
3329
+ line-height: 1.35;
3330
+ }
3331
+
3332
+ .sv-bridge-alert-text { color: ${tokens.textSecondary}; }
3333
+
3334
+ .sv-bridge-retry {
3335
+ padding: 0;
3336
+ background: none;
3337
+ border: none;
3338
+ font-family: inherit;
3339
+ font-size: 13px;
3340
+ font-weight: 600;
3341
+ color: ${tokens.primary};
3342
+ text-decoration: underline;
3343
+ text-underline-offset: 2px;
3344
+ cursor: pointer;
3345
+ }
3346
+
3347
+ .sv-bridge-retry:hover { color: ${tokens.primaryHover}; }
3348
+ .sv-bridge-retry:focus-visible { outline: 2px solid ${tokens.borderFocus}; outline-offset: 2px; border-radius: 4px; }
3349
+
3350
+ @media (prefers-reduced-motion: reduce) {
3351
+ .sv-bridge-dots span { animation: none; opacity: 0.5; }
3352
+ }
3353
+
3148
3354
  /* ========================================
3149
3355
  RESPONSIVE
3150
3356
  ======================================== */
@@ -3501,7 +3707,7 @@ const MODAL_ID$1 = 'sparkvault-identity-modal';
3501
3707
  * Default branding used for immediate modal display before config loads.
3502
3708
  * Uses neutral styling that works with both light and dark themes.
3503
3709
  */
3504
- const DEFAULT_BRANDING$1 = {
3710
+ const DEFAULT_BRANDING$2 = {
3505
3711
  companyName: '',
3506
3712
  logoLight: null,
3507
3713
  logoDark: null,
@@ -3527,7 +3733,7 @@ class ModalContainer {
3527
3733
  */
3528
3734
  createLoading(options, onClose) {
3529
3735
  return this.create({
3530
- branding: DEFAULT_BRANDING$1,
3736
+ branding: DEFAULT_BRANDING$2,
3531
3737
  backdropBlur: options.backdropBlur,
3532
3738
  }, onClose);
3533
3739
  }
@@ -3539,6 +3745,9 @@ class ModalContainer {
3539
3745
  if (!this.elements)
3540
3746
  return;
3541
3747
  this.effectiveTheme = resolveTheme(branding);
3748
+ // Re-theme the stylesheet if the tenant's themeMode differs from the
3749
+ // default used at first paint.
3750
+ applyBrandingTheme(branding);
3542
3751
  // Update header with real branding
3543
3752
  const newHeader = this.createHeader(branding);
3544
3753
  if (this.headerElement?.parentNode) {
@@ -5744,19 +5953,6 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
5744
5953
  ].join(' '),
5745
5954
  code: 'sparklink_csp_blocked',
5746
5955
  };
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
5956
  class IdentityRenderer {
5761
5957
  constructor(container, api, options, callbacks) {
5762
5958
  // View management
@@ -6471,7 +6667,7 @@ class IdentityRenderer {
6471
6667
  this.close();
6472
6668
  this.safeOnSuccess(result);
6473
6669
  if (typeof result.redirect === 'string' && result.redirect) {
6474
- navigateWith(this.options, result.redirect);
6670
+ window.location.href = result.redirect;
6475
6671
  }
6476
6672
  }
6477
6673
  catch (error) {
@@ -6528,7 +6724,7 @@ class IdentityRenderer {
6528
6724
  this.close();
6529
6725
  this.safeOnSuccess(result.result);
6530
6726
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6531
- navigateWith(this.options, result.result.redirect);
6727
+ window.location.href = result.result.redirect;
6532
6728
  }
6533
6729
  }
6534
6730
  else if (this.renderBlockedInterstitial(result.errorCode)) ;
@@ -6593,19 +6789,12 @@ class IdentityRenderer {
6593
6789
  }
6594
6790
  handleSocialLogin(provider) {
6595
6791
  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
6792
  const state = generateState();
6604
6793
  const redirectUri = window.location.origin + window.location.pathname;
6605
6794
  sessionStorage.setItem('sv_oauth_state', state);
6606
6795
  sessionStorage.setItem('sv_oauth_email', this.recipient);
6607
6796
  const authUrl = this.api.getSocialAuthUrl(provider, redirectUri, state, this.verificationState.authContext);
6608
- navigateWith(this.options, authUrl);
6797
+ window.location.href = authUrl;
6609
6798
  }
6610
6799
  normalizeError(error) {
6611
6800
  if (error instanceof IdentityApiError) {
@@ -6710,7 +6899,7 @@ class IdentityRenderer {
6710
6899
  this.safeOnSuccess(result);
6711
6900
  this.close();
6712
6901
  if (typeof result.redirect === 'string' && result.redirect) {
6713
- navigateWith(this.options, result.redirect);
6902
+ window.location.href = result.redirect;
6714
6903
  }
6715
6904
  }
6716
6905
  /**
@@ -7189,290 +7378,286 @@ class IdentityRenderer {
7189
7378
  }
7190
7379
  }
7191
7380
 
7192
- /* global HTMLIFrameElement requestAnimationFrame */
7193
7381
  /**
7194
- * Widget Embedder
7382
+ * Dialog Launcher
7195
7383
  *
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.
7384
+ * Host-side half of the popup login flow. Dialog-mode `verify()` opens a
7385
+ * TOP-LEVEL popup on the Identity origin **directly inside the triggering user
7386
+ * gesture** and, on the host page, shades it with a small branded **bridge
7387
+ * modal** ("continue in the secure window"). The popup (the `chrome: 'bare'`
7388
+ * sign-in page) collects the identifier and runs the whole flow first-party, so
7389
+ * login's `__Host-authsv_sso` cookie persists. Any `email`/`phone` passed to
7390
+ * `verify()` is forwarded as a prefill.
7203
7391
  *
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.
7392
+ * The popup must open synchronously in the gesture or the browser blocks it as
7393
+ * programmatic. `verify()` reaches `start()` through microtask-only awaits (the
7394
+ * redirect-result check does no I/O; the preloaded config resolves from cache),
7395
+ * so transient activation survives.
7396
+ *
7397
+ * It is one dialog. The happy path is clean: logo, a subtle animation, and
7398
+ * "continue in the secure window". A single warning appears under the logo only
7399
+ * when the popup can't be confirmed: it was blocked, it closed, or it never
7400
+ * posted a "ready" ping within `OPEN_TIMEOUT_MS` (so the open/load failed). Its
7401
+ * "Try again" reopens the popup. The header's close ✕ (or backdrop/Escape)
7402
+ * aborts and closes the popup.
7207
7403
  */
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';
7404
+ /** `data.type` the sign-in popup posts back to the opener. */
7405
+ const LOGIN_RESULT_TYPE = 'sparkvault-login-result';
7406
+ /** `data.type` the sign-in page posts once it has loaded (a liveness ping). */
7407
+ const LOGIN_READY_TYPE = 'sparkvault-login-ready';
7408
+ const DEFAULT_BRANDING$1 = { companyName: '', logoLight: null, logoDark: null };
7216
7409
  /**
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.
7410
+ * How long to wait for the popup's "ready" ping before warning that the open
7411
+ * may have failed. A real window loads the page and pings within ~1-2s, so this
7412
+ * never fires during normal use (however long the person then takes to sign in);
7413
+ * it only fires when the window opened but the page never loaded.
7223
7414
  */
7224
- const FRAME_READY_TIMEOUT_MS = 8000;
7225
- class WidgetEmbedder {
7226
- constructor(config, options, callbacks) {
7415
+ const OPEN_TIMEOUT_MS = 8000;
7416
+ const SVG_NS = 'http://www.w3.org/2000/svg';
7417
+ function el(tag, className, text) {
7418
+ const node = document.createElement(tag);
7419
+ if (className)
7420
+ node.className = className;
7421
+ if (text != null)
7422
+ node.textContent = text;
7423
+ return node;
7424
+ }
7425
+ /** Small inline warning triangle; `currentColor` lets the CSS tint it amber. */
7426
+ function warningIcon() {
7427
+ const svg = document.createElementNS(SVG_NS, 'svg');
7428
+ svg.setAttribute('viewBox', '0 0 20 20');
7429
+ svg.setAttribute('fill', 'none');
7430
+ svg.classList.add('sv-bridge-alert-icon');
7431
+ const path = (d, attrs) => {
7432
+ const p = document.createElementNS(SVG_NS, 'path');
7433
+ p.setAttribute('d', d);
7434
+ for (const [k, v] of Object.entries(attrs))
7435
+ p.setAttribute(k, v);
7436
+ return p;
7437
+ };
7438
+ svg.appendChild(path('M10 2.75 18.25 17.25H1.75L10 2.75Z', {
7439
+ stroke: 'currentColor', 'stroke-width': '1.5', 'stroke-linejoin': 'round',
7440
+ }));
7441
+ svg.appendChild(path('M10 8.25v3.25', {
7442
+ stroke: 'currentColor', 'stroke-width': '1.5', 'stroke-linecap': 'round',
7443
+ }));
7444
+ const dot = document.createElementNS(SVG_NS, 'circle');
7445
+ dot.setAttribute('cx', '10');
7446
+ dot.setAttribute('cy', '14.5');
7447
+ dot.setAttribute('r', '0.95');
7448
+ dot.setAttribute('fill', 'currentColor');
7449
+ svg.appendChild(dot);
7450
+ return svg;
7451
+ }
7452
+ /**
7453
+ * Opens the sign-in popup for dialog-mode `verify()` and bridges its result
7454
+ * back, behind a single branded host-page modal.
7455
+ */
7456
+ class DialogLauncher {
7457
+ constructor(config, api, options, callbacks) {
7227
7458
  this.config = config;
7459
+ this.api = api;
7228
7460
  this.options = options;
7229
7461
  this.callbacks = callbacks;
7230
- this.iframe = null;
7462
+ this.popupLauncher = new PopupLauncher();
7463
+ this.modal = null;
7464
+ this.alertEl = null;
7465
+ this.popupWindow = null;
7466
+ this.openTimer = null;
7231
7467
  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.
7468
+ // Bumped on every open so a superseded popup's late result or ready ping
7469
+ // (e.g. the prior window after "Try again") is ignored.
7470
+ this.generation = 0;
7238
7471
  this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
7239
- this.boundHandleMessage = (event) => this.handleMessage(event);
7240
- this.boundHandleCspViolation = (event) => this.handleCspViolation(event);
7241
7472
  }
7473
+ /** Shade the host with the bridge and open the popup in the caller's gesture. */
7242
7474
  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
- }
7475
+ this.showBridge();
7476
+ this.openPopup();
7477
+ this.loadBranding();
7304
7478
  }
7479
+ /** Tear down the bridge modal and close any popup it opened. */
7305
7480
  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;
7314
- }
7315
- /**
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.
7318
- */
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
- }
7327
- }
7328
- clearReadyTimer() {
7329
- if (this.readyTimer !== null) {
7330
- clearTimeout(this.readyTimer);
7331
- this.readyTimer = null;
7332
- }
7333
- }
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();
7346
- }
7347
- /**
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.
7351
- */
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);
7481
+ this.clearOpenTimer();
7482
+ this.closePopup();
7483
+ this.modal?.destroy();
7484
+ this.modal = null;
7485
+ this.alertEl = null;
7486
+ }
7487
+ openPopup() {
7488
+ const generation = ++this.generation;
7489
+ this.popupLauncher
7490
+ .openPopup({
7491
+ url: this.buildPopupUrl(),
7492
+ windowName: 'sparkvault-login',
7493
+ resultType: LOGIN_RESULT_TYPE,
7494
+ readyType: LOGIN_READY_TYPE,
7495
+ trustedOrigin: this.trustedOrigin,
7496
+ onOpen: (popup) => {
7497
+ if (generation !== this.generation)
7498
+ return;
7499
+ this.popupWindow = popup;
7500
+ this.scheduleOpenWarning();
7501
+ },
7502
+ // The page loaded and pinged back — the open succeeded, so cancel the
7503
+ // open-failure warning no matter how long the person now takes.
7504
+ onReady: () => { if (generation === this.generation)
7505
+ this.clearOpenTimer(); },
7506
+ })
7507
+ .then((message) => { if (generation === this.generation)
7508
+ this.handleResult(message); })
7509
+ .catch((error) => { if (generation === this.generation)
7510
+ this.handleError(error); });
7511
+ }
7512
+ buildPopupUrl() {
7513
+ const params = new URLSearchParams({ origin: window.location.origin });
7514
+ // Identifier prefill - the popup collects it itself when absent.
7515
+ if (this.options.email) {
7516
+ params.set('email', this.options.email);
7517
+ }
7518
+ else if (this.options.phone) {
7519
+ params.set('phone', this.options.phone);
7520
+ }
7521
+ // Auth context, in the query shape the sign-in page reads server-side:
7522
+ // OIDC rides `auth_request`; simple redirect rides `mode=simple` + the
7523
+ // opaque `session` (the page loads success/failure URLs from the session).
7367
7524
  const authContext = this.options.authContext;
7368
7525
  if (authContext?.authRequestId) {
7369
- url.searchParams.set('auth_request_id', authContext.authRequestId);
7526
+ params.set('auth_request', authContext.authRequestId);
7370
7527
  }
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));
7528
+ else if (authContext?.simpleMode?.sessionId) {
7529
+ params.set('mode', 'simple');
7530
+ params.set('session', authContext.simpleMode.sessionId);
7380
7531
  }
7381
- this.close();
7382
- window.location.href = url.toString();
7532
+ return `${this.config.identityBaseUrl}/${this.config.accountId}/signin?${params}`;
7383
7533
  }
7384
- /**
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.
7390
- */
7391
- safeNavigate(url) {
7392
- let resolved;
7393
- try {
7394
- resolved = new URL(url, window.location.href);
7395
- }
7396
- catch {
7534
+ handleResult(message) {
7535
+ if (this.settled)
7397
7536
  return;
7398
- }
7399
- if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
7537
+ if (message.success && message.data) {
7538
+ const result = {
7539
+ token: message.data.token || '',
7540
+ identity: message.data.identity || '',
7541
+ identityType: message.data.identity_type || 'email',
7542
+ svid: message.data.svid,
7543
+ sessionId: message.data.session_id,
7544
+ refreshToken: message.data.refresh_token,
7545
+ redirect: message.data.redirect,
7546
+ };
7547
+ this.finish();
7548
+ this.callbacks.onSuccess(result);
7400
7549
  return;
7401
7550
  }
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');
7413
- const authContext = this.options.authContext;
7414
- if (authContext?.authRequestId) {
7415
- url.searchParams.set('auth_request_id', authContext.authRequestId);
7416
- }
7417
- if (authContext?.simpleMode) {
7418
- url.searchParams.set('simple_mode', JSON.stringify({
7419
- success_url: authContext.simpleMode.successUrl,
7420
- failure_url: authContext.simpleMode.failureUrl,
7421
- state: authContext.simpleMode.state,
7422
- session_id: authContext.simpleMode.sessionId,
7423
- }));
7551
+ if (message.error === 'cancelled') {
7552
+ // The person explicitly backed out inside the popup — end the flow rather
7553
+ // than offer to reopen to the same place.
7554
+ this.finishCancel();
7555
+ return;
7424
7556
  }
7425
- return url.toString();
7557
+ this.finish();
7558
+ this.callbacks.onError(new SparkVaultError(message.message || message.error || 'Verification failed', message.errorCode || message.error || 'verification_failed'));
7426
7559
  }
7427
- handleMessage(event) {
7428
- if (event.origin !== this.trustedOrigin)
7429
- return;
7430
- if (this.iframe && event.source !== this.iframe.contentWindow)
7560
+ handleError(error) {
7561
+ if (this.settled)
7431
7562
  return;
7432
- const data = event.data;
7433
- if (!data || typeof data.type !== 'string')
7434
- 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();
7563
+ // Blocked (never opened) or closed (gone) - the popup can't be confirmed,
7564
+ // so surface the warning so the user can reopen it.
7565
+ if (error instanceof PopupBlockedError || error instanceof UserCancelledError) {
7566
+ this.showAlert();
7441
7567
  return;
7442
7568
  }
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);
7569
+ this.finish();
7570
+ this.callbacks.onError(error instanceof Error ? error : new Error(String(error)));
7571
+ }
7572
+ /** Create the bridge modal (once) and render its single happy-path body. */
7573
+ showBridge() {
7574
+ if (this.settled)
7447
7575
  return;
7576
+ if (!this.modal) {
7577
+ this.modal = new ModalContainer();
7578
+ this.modal.create({ branding: DEFAULT_BRANDING$1, backdropBlur: this.options.backdropBlur }, () => this.abort());
7448
7579
  }
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);
7580
+ const body = this.modal.getBody();
7581
+ if (!body)
7455
7582
  return;
7583
+ clearChildren(body);
7584
+ const wrap = el('div', 'sv-bridge');
7585
+ // Warning under the logo - collapsed until the popup can't be confirmed.
7586
+ const alert = el('div', 'sv-bridge-alert');
7587
+ alert.appendChild(warningIcon());
7588
+ const alertBody = el('div', 'sv-bridge-alert-body');
7589
+ alertBody.appendChild(el('span', 'sv-bridge-alert-text', 'The sign-in window may not have opened.'));
7590
+ const retry = el('button', 'sv-bridge-retry', 'Try again');
7591
+ retry.type = 'button';
7592
+ retry.addEventListener('click', () => this.retry());
7593
+ alertBody.appendChild(retry);
7594
+ alert.appendChild(alertBody);
7595
+ this.alertEl = alert;
7596
+ const dots = el('div', 'sv-bridge-dots');
7597
+ dots.append(el('span'), el('span'), el('span'));
7598
+ wrap.append(alert, dots, el('h3', 'sv-title', 'Continue in the secure window'), el('p', 'sv-subtitle', 'Finish signing in there. This page updates on its own.'));
7599
+ body.appendChild(wrap);
7600
+ }
7601
+ showAlert() {
7602
+ this.clearOpenTimer();
7603
+ this.alertEl?.classList.add('sv-shown');
7604
+ }
7605
+ hideAlert() {
7606
+ this.alertEl?.classList.remove('sv-shown');
7607
+ }
7608
+ scheduleOpenWarning() {
7609
+ this.clearOpenTimer();
7610
+ this.openTimer = setTimeout(() => this.showAlert(), OPEN_TIMEOUT_MS);
7611
+ }
7612
+ clearOpenTimer() {
7613
+ if (this.openTimer) {
7614
+ clearTimeout(this.openTimer);
7615
+ this.openTimer = null;
7616
+ }
7617
+ }
7618
+ /** "Try again": close any current popup and reopen a fresh one. */
7619
+ retry() {
7620
+ this.hideAlert();
7621
+ this.closePopup();
7622
+ this.openPopup();
7623
+ }
7624
+ /** Fetch branding once and drop the tenant logo into the modal header. */
7625
+ loadBranding() {
7626
+ this.api
7627
+ .getConfig()
7628
+ .then((config) => {
7629
+ if (config.branding && this.modal)
7630
+ this.modal.updateBranding(config.branding);
7631
+ })
7632
+ .catch(() => {
7633
+ // Keep the default chrome - the popup itself is fully branded.
7634
+ });
7635
+ }
7636
+ closePopup() {
7637
+ if (this.popupWindow && !this.popupWindow.closed) {
7638
+ try {
7639
+ this.popupWindow.close();
7640
+ }
7641
+ catch {
7642
+ // Cross-origin navigation or already gone - nothing to close.
7643
+ }
7456
7644
  }
7457
- if (data.type !== RESULT_TYPE || this.settled)
7645
+ this.popupWindow = null;
7646
+ }
7647
+ /** Explicit abort (close ✕, backdrop, Escape): close the popup and cancel. */
7648
+ abort() {
7649
+ this.finishCancel();
7650
+ }
7651
+ finish() {
7652
+ this.settled = true;
7653
+ this.close();
7654
+ }
7655
+ finishCancel() {
7656
+ if (this.settled)
7458
7657
  return;
7459
7658
  this.settled = true;
7460
7659
  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
- }
7660
+ this.callbacks.onCancel();
7476
7661
  }
7477
7662
  }
7478
7663
 
@@ -7523,7 +7708,9 @@ class InlineContainer {
7523
7708
  injectStyles(styleOptions);
7524
7709
  // Create main container
7525
7710
  this.container = document.createElement('div');
7526
- this.container.className = 'sv-inline-container';
7711
+ this.container.className = this.containerOptions.bare
7712
+ ? 'sv-inline-container sv-inline-bare'
7713
+ : 'sv-inline-container';
7527
7714
  // Create header if enabled
7528
7715
  if (this.containerOptions.showHeader) {
7529
7716
  this.header = this.createHeader({
@@ -7567,6 +7754,7 @@ class InlineContainer {
7567
7754
  if (!this.container)
7568
7755
  return;
7569
7756
  this.effectiveTheme = resolveTheme(branding);
7757
+ applyBrandingTheme(branding);
7570
7758
  // Update header with real branding
7571
7759
  if (this.containerOptions.showHeader && this.header) {
7572
7760
  const newHeader = this.createHeader(branding);
@@ -7806,7 +7994,7 @@ function isTokenClaims(payload) {
7806
7994
  class IdentityModule {
7807
7995
  constructor(config) {
7808
7996
  this.renderer = null;
7809
- this.embedder = null;
7997
+ this.launcher = null;
7810
7998
  this.config = config;
7811
7999
  this.api = new IdentityApi(config);
7812
8000
  // Preload config in background for instant dialog opening
@@ -7940,9 +8128,9 @@ class IdentityModule {
7940
8128
  options.onSuccess?.(redirectResult);
7941
8129
  return redirectResult;
7942
8130
  }
7943
- if (this.embedder) {
7944
- this.embedder.close();
7945
- this.embedder = null;
8131
+ if (this.launcher) {
8132
+ this.launcher.close();
8133
+ this.launcher = null;
7946
8134
  }
7947
8135
  if (this.renderer) {
7948
8136
  this.renderer.close();
@@ -7958,9 +8146,9 @@ class IdentityModule {
7958
8146
  backdropBlur: options.backdropBlur ?? this.config.backdropBlur,
7959
8147
  };
7960
8148
  // 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).
8149
+ // document. Dialog mode renders a thin launcher and opens a top-level popup
8150
+ // on the Identity origin for the flow (so login's first-party SSO cookie
8151
+ // persists). `renderMode: 'local'` is how the popup itself runs the flow.
7964
8152
  const isInline = !!options.target;
7965
8153
  const useLocal = options.renderMode === 'local' || isInline;
7966
8154
  let resolveRef;
@@ -7988,41 +8176,28 @@ class IdentityModule {
7988
8176
  this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
7989
8177
  this.renderer.start().catch((error) => {
7990
8178
  // 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.
8179
+ // close it silently. Render the error in-dialog instead (consistent with
8180
+ // every in-flow error); the promise settles later via retry/close.
7996
8181
  this.renderer?.showStartupError(error);
7997
8182
  });
7998
8183
  };
7999
8184
  if (!useLocal) {
8000
8185
  // When the preloaded config has already failed *permanently* — this origin
8001
8186
  // 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.
8187
+ // the popup cannot help: the IdP will reject the unverified origin. Render
8188
+ // the error dialog in-page right away instead. Transient failures fall
8189
+ // through to the launcher, which surfaces them in its own dialog.
8006
8190
  if (await this.preloadedConfigPermanentlyFailed()) {
8007
8191
  startLocalRender(new ModalContainer());
8008
8192
  return settledPromise;
8009
8193
  }
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();
8194
+ this.launcher = new DialogLauncher(this.config, this.api, mergedOptions, hostCallbacks);
8195
+ this.launcher.start();
8023
8196
  return settledPromise;
8024
8197
  }
8025
- startLocalRender(isInline ? this.createInlineContainer(options.target) : new ModalContainer());
8198
+ startLocalRender(isInline
8199
+ ? this.createInlineContainer(options.target, options.chrome === 'bare')
8200
+ : new ModalContainer());
8026
8201
  return settledPromise;
8027
8202
  }
8028
8203
  /**
@@ -8184,14 +8359,13 @@ class IdentityModule {
8184
8359
  /**
8185
8360
  * Close the identity dialog/inline UI if open.
8186
8361
  *
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).
8362
+ * Tears down whichever surface is active: the dialog launcher (default dialog
8363
+ * mode) or the local renderer (inline / local mode).
8190
8364
  */
8191
8365
  close() {
8192
- if (this.embedder) {
8193
- this.embedder.close();
8194
- this.embedder = null;
8366
+ if (this.launcher) {
8367
+ this.launcher.close();
8368
+ this.launcher = null;
8195
8369
  }
8196
8370
  if (this.renderer) {
8197
8371
  this.renderer.close();
@@ -8200,12 +8374,12 @@ class IdentityModule {
8200
8374
  }
8201
8375
  /**
8202
8376
  * 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).
8377
+ * the popup can't surface (origin not allowed, or product not configured).
8378
+ * Used to skip the launcher and show the error dialog in-page immediately.
8379
+ * Returns false — proceed to the launcher — when config is not preloaded,
8380
+ * still in flight (raced against a short timeout so the common path is never
8381
+ * delayed), resolved, or failed only transiently (the launcher surfaces a
8382
+ * transient failure in its own dialog).
8209
8383
  */
8210
8384
  async preloadedConfigPermanentlyFailed() {
8211
8385
  if (!this.api.isConfigPreloaded())
@@ -8228,7 +8402,7 @@ class IdentityModule {
8228
8402
  /**
8229
8403
  * Resolve target to an HTMLElement.
8230
8404
  */
8231
- createInlineContainer(target) {
8405
+ createInlineContainer(target, bare = false) {
8232
8406
  let element;
8233
8407
  if (typeof target === 'string') {
8234
8408
  const found = document.querySelector(target);
@@ -8243,7 +8417,9 @@ class IdentityModule {
8243
8417
  else {
8244
8418
  throw new ValidationError('Target must be a CSS selector string or HTMLElement');
8245
8419
  }
8246
- return new InlineContainer(element);
8420
+ // Bare chrome: the host page owns logo + footer + background, so drop the
8421
+ // container's own surface and the SparkVault footer.
8422
+ return new InlineContainer(element, bare ? { bare: true, showFooter: false } : {});
8247
8423
  }
8248
8424
  // Public-API aliases. The documented method names in the customer-facing
8249
8425
  // SDK README and the API docs are pop() and render(); verify() is the