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