@sparkvault/sdk-js 8.0.0 → 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
@@ -880,20 +880,20 @@ class IdentityApi extends SparkVaultApi {
880
880
  return params;
881
881
  }
882
882
  /**
883
- * Send TOTP code to email or phone
883
+ * Send OTP code to email or phone
884
884
  */
885
- async sendTotp(params) {
886
- return this.request('POST', '/totp/send', {
885
+ async sendOtp(params) {
886
+ return this.request('POST', '/otp/send', {
887
887
  recipient: params.recipient,
888
888
  method: params.method,
889
889
  ...this.buildAuthContextParams(params.authContext),
890
890
  });
891
891
  }
892
892
  /**
893
- * Verify TOTP code
893
+ * Verify OTP code
894
894
  */
895
- async verifyTotp(params) {
896
- return this.request('POST', '/totp/verify', {
895
+ async verifyOtp(params) {
896
+ return this.request('POST', '/otp/verify', {
897
897
  kindling: params.kindling,
898
898
  pin: params.pin,
899
899
  recipient: params.recipient,
@@ -1129,25 +1129,25 @@ class IdentityApiError extends SparkVaultError {
1129
1129
  */
1130
1130
  const METHOD_REGISTRY = {
1131
1131
  // Core methods
1132
- totp_email: {
1133
- id: 'totp_email',
1134
- type: 'totp',
1132
+ otp_email: {
1133
+ id: 'otp_email',
1134
+ type: 'otp',
1135
1135
  identityType: 'email',
1136
1136
  name: 'Email code',
1137
1137
  description: 'Get a one-time code via email',
1138
1138
  icon: 'email',
1139
1139
  },
1140
- totp_sms: {
1141
- id: 'totp_sms',
1142
- type: 'totp',
1140
+ otp_sms: {
1141
+ id: 'otp_sms',
1142
+ type: 'otp',
1143
1143
  identityType: 'phone',
1144
1144
  name: 'Text message',
1145
1145
  description: 'Get a one-time code via SMS',
1146
1146
  icon: 'sms',
1147
1147
  },
1148
- totp_voice: {
1149
- id: 'totp_voice',
1150
- type: 'totp',
1148
+ otp_voice: {
1149
+ id: 'otp_voice',
1150
+ type: 'otp',
1151
1151
  identityType: 'phone',
1152
1152
  name: 'Voice call',
1153
1153
  description: 'Get a one-time code via phone call',
@@ -1263,8 +1263,8 @@ class VerificationState {
1263
1263
  isFallbackMode: false,
1264
1264
  pendingResult: null,
1265
1265
  };
1266
- // TOTP state
1267
- this._totp = {
1266
+ // OTP state
1267
+ this._otp = {
1268
1268
  kindling: '',
1269
1269
  method: null,
1270
1270
  };
@@ -1323,15 +1323,100 @@ class VerificationState {
1323
1323
  setPendingResult(result) {
1324
1324
  this._passkey.pendingResult = result;
1325
1325
  }
1326
- // --- TOTP State ---
1327
- get totp() {
1328
- return this._totp;
1326
+ // --- OTP State ---
1327
+ get otp() {
1328
+ return this._otp;
1329
1329
  }
1330
1330
  setKindling(kindling) {
1331
- this._totp.kindling = kindling;
1331
+ this._otp.kindling = kindling;
1332
1332
  }
1333
- setTotpMethod(method) {
1334
- this._totp.method = method;
1333
+ setOtpMethod(method) {
1334
+ this._otp.method = method;
1335
+ }
1336
+ }
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
+ });
1335
1420
  }
1336
1421
  }
1337
1422
 
@@ -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
@@ -1678,32 +1725,32 @@ class PasskeyHandler {
1678
1725
  }
1679
1726
 
1680
1727
  /**
1681
- * TOTP Handler
1728
+ * OTP Handler
1682
1729
  *
1683
- * Single responsibility: TOTP code sending and verification.
1684
- * Extracts TOTP logic from IdentityRenderer for better separation of concerns.
1730
+ * Single responsibility: OTP code sending and verification.
1731
+ * Extracts OTP logic from IdentityRenderer for better separation of concerns.
1685
1732
  */
1686
1733
  /**
1687
- * Handles TOTP code sending and verification
1734
+ * Handles OTP code sending and verification
1688
1735
  */
1689
- class TotpHandler {
1736
+ class OtpHandler {
1690
1737
  constructor(api, state) {
1691
1738
  this.api = api;
1692
1739
  this.state = state;
1693
1740
  }
1694
1741
  /**
1695
- * Send TOTP code via email, SMS, or voice
1742
+ * Send OTP code via email, SMS, or voice
1696
1743
  */
1697
1744
  async send(method) {
1698
1745
  try {
1699
- const response = await this.api.sendTotp({
1746
+ const response = await this.api.sendOtp({
1700
1747
  recipient: this.state.recipient,
1701
1748
  method,
1702
1749
  authContext: this.state.authContext,
1703
1750
  });
1704
1751
  // Update state with kindling
1705
1752
  this.state.setKindling(response.kindling);
1706
- this.state.setTotpMethod(method);
1753
+ this.state.setOtpMethod(method);
1707
1754
  return {
1708
1755
  success: true,
1709
1756
  kindling: response.kindling,
@@ -1721,18 +1768,18 @@ class TotpHandler {
1721
1768
  }
1722
1769
  }
1723
1770
  /**
1724
- * Resend TOTP code
1771
+ * Resend OTP code
1725
1772
  */
1726
1773
  async resend() {
1727
- const method = this.state.totp.method;
1774
+ const method = this.state.otp.method;
1728
1775
  if (!method) {
1729
1776
  return {
1730
1777
  success: false,
1731
- error: 'No TOTP method set',
1778
+ error: 'No OTP method set',
1732
1779
  };
1733
1780
  }
1734
1781
  try {
1735
- const response = await this.api.sendTotp({
1782
+ const response = await this.api.sendOtp({
1736
1783
  recipient: this.state.recipient,
1737
1784
  method,
1738
1785
  authContext: this.state.authContext,
@@ -1756,10 +1803,10 @@ class TotpHandler {
1756
1803
  }
1757
1804
  }
1758
1805
  /**
1759
- * Verify TOTP code
1806
+ * Verify OTP code
1760
1807
  */
1761
1808
  async verify(code) {
1762
- const kindling = this.state.totp.kindling;
1809
+ const kindling = this.state.otp.kindling;
1763
1810
  if (!kindling) {
1764
1811
  return {
1765
1812
  success: false,
@@ -1767,7 +1814,7 @@ class TotpHandler {
1767
1814
  };
1768
1815
  }
1769
1816
  try {
1770
- const response = await this.api.verifyTotp({
1817
+ const response = await this.api.verifyOtp({
1771
1818
  kindling,
1772
1819
  pin: code,
1773
1820
  recipient: this.state.recipient,
@@ -2302,17 +2349,17 @@ function getStyles(options) {
2302
2349
  }
2303
2350
 
2304
2351
  /* ========================================
2305
- TOTP INPUT
2352
+ OTP INPUT
2306
2353
  ======================================== */
2307
2354
 
2308
- .sv-totp-input-group {
2355
+ .sv-otp-input-group {
2309
2356
  display: flex;
2310
2357
  gap: 8px;
2311
2358
  justify-content: center;
2312
2359
  margin-bottom: 16px;
2313
2360
  }
2314
2361
 
2315
- .sv-totp-digit {
2362
+ .sv-otp-digit {
2316
2363
  width: 44px;
2317
2364
  height: 52px;
2318
2365
  text-align: center;
@@ -2327,17 +2374,17 @@ function getStyles(options) {
2327
2374
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
2328
2375
  }
2329
2376
 
2330
- .sv-totp-digit:hover:not(:focus):not(:disabled) {
2377
+ .sv-otp-digit:hover:not(:focus):not(:disabled) {
2331
2378
  border-color: ${tokens.borderHover};
2332
2379
  }
2333
2380
 
2334
- .sv-totp-digit:focus {
2381
+ .sv-otp-digit:focus {
2335
2382
  outline: none;
2336
2383
  border-color: ${tokens.borderFocus};
2337
2384
  box-shadow: 0 0 0 3px ${tokens.primaryLight};
2338
2385
  }
2339
2386
 
2340
- .sv-totp-digit:disabled {
2387
+ .sv-otp-digit:disabled {
2341
2388
  opacity: 0.5;
2342
2389
  cursor: not-allowed;
2343
2390
  }
@@ -2847,7 +2894,7 @@ function getStyles(options) {
2847
2894
  }
2848
2895
 
2849
2896
  /* ========================================
2850
- TOTP VIEW
2897
+ OTP VIEW
2851
2898
  ======================================== */
2852
2899
 
2853
2900
  .sv-resend-container {
@@ -3160,7 +3207,7 @@ function getStyles(options) {
3160
3207
  padding: 24px 28px;
3161
3208
  }
3162
3209
 
3163
- .sv-totp-digit {
3210
+ .sv-otp-digit {
3164
3211
  width: 40px;
3165
3212
  height: 48px;
3166
3213
  font-size: 18px;
@@ -3172,11 +3219,11 @@ function getStyles(options) {
3172
3219
  }
3173
3220
 
3174
3221
  @media (max-width: 360px) {
3175
- .sv-totp-input-group {
3222
+ .sv-otp-input-group {
3176
3223
  gap: 6px;
3177
3224
  }
3178
3225
 
3179
- .sv-totp-digit {
3226
+ .sv-otp-digit {
3180
3227
  width: 36px;
3181
3228
  height: 44px;
3182
3229
  font-size: 16px;
@@ -3860,10 +3907,10 @@ function looksLikePhone(input) {
3860
3907
  return /^[+(\d]/.test(trimmed) && !/[@.]/.test(trimmed);
3861
3908
  }
3862
3909
  /**
3863
- * Validate TOTP code format.
3910
+ * Validate OTP code format.
3864
3911
  * Returns sanitized code or null if invalid.
3865
3912
  */
3866
- function validateTotpCode(code) {
3913
+ function validateOtpCode(code) {
3867
3914
  const digits = code.replace(/\D/g, '');
3868
3915
  if (digits.length === 6) {
3869
3916
  return digits;
@@ -4219,12 +4266,12 @@ class MethodSelectView {
4219
4266
  }
4220
4267
 
4221
4268
  /**
4222
- * TOTP Verification View
4269
+ * OTP Verification View
4223
4270
  *
4224
- * Collects and validates the 6-digit TOTP code sent via email, SMS, or voice.
4271
+ * Collects and validates the 6-digit OTP code sent via email, SMS, or voice.
4225
4272
  */
4226
4273
  const CODE_LENGTH = 6;
4227
- class TotpVerifyView {
4274
+ class OtpVerifyView {
4228
4275
  constructor(props) {
4229
4276
  this.inputElements = [];
4230
4277
  this.submitButton = null;
@@ -4301,14 +4348,14 @@ class TotpVerifyView {
4301
4348
  return link;
4302
4349
  }
4303
4350
  createInputGroup() {
4304
- const group = div('sv-totp-input-group');
4351
+ const group = div('sv-otp-input-group');
4305
4352
  for (let i = 0; i < CODE_LENGTH; i++) {
4306
4353
  const input = document.createElement('input');
4307
4354
  input.type = 'text';
4308
4355
  input.inputMode = 'numeric';
4309
4356
  input.pattern = '[0-9]*';
4310
4357
  input.maxLength = 1;
4311
- input.className = 'sv-totp-digit';
4358
+ input.className = 'sv-otp-digit';
4312
4359
  input.autocomplete = 'one-time-code';
4313
4360
  input.setAttribute('aria-label', `Digit ${i + 1} of ${CODE_LENGTH}`);
4314
4361
  // Create and store handlers for proper cleanup
@@ -4415,7 +4462,7 @@ class TotpVerifyView {
4415
4462
  return;
4416
4463
  }
4417
4464
  const code = this.getCode();
4418
- const validCode = validateTotpCode(code);
4465
+ const validCode = validateOtpCode(code);
4419
4466
  if (!validCode) {
4420
4467
  this.showError('Please enter the complete 6-digit code');
4421
4468
  return;
@@ -5723,7 +5770,7 @@ class OriginNotAllowedView {
5723
5770
  * Identity View Renderer
5724
5771
  *
5725
5772
  * Orchestrates view state and rendering for identity verification flows.
5726
- * Uses extracted handlers for TOTP and Passkey operations.
5773
+ * Uses extracted handlers for OTP and Passkey operations.
5727
5774
  */
5728
5775
  /**
5729
5776
  * End-user copy for a blocked Identity. Intentionally generic — it never names
@@ -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
@@ -5779,7 +5813,7 @@ class IdentityRenderer {
5779
5813
  this.verificationState = new VerificationState();
5780
5814
  // Initialize handlers with shared state
5781
5815
  this.passkeyHandler = new PasskeyHandler(api, this.verificationState);
5782
- this.totpHandler = new TotpHandler(api, this.verificationState);
5816
+ this.otpHandler = new OtpHandler(api, this.verificationState);
5783
5817
  this.sparkLinkHandler = new SparkLinkHandler(api, this.verificationState);
5784
5818
  // Set initial identity from options
5785
5819
  if (options.email) {
@@ -6046,14 +6080,14 @@ class IdentityRenderer {
6046
6080
  onSelectMethod: (method) => this.handleMethodSelect(method, true),
6047
6081
  onBack: state.email ? () => this.showIdentityInput() : undefined,
6048
6082
  });
6049
- case 'totp-verify':
6050
- return new TotpVerifyView({
6083
+ case 'otp-verify':
6084
+ return new OtpVerifyView({
6051
6085
  email: state.email,
6052
6086
  method: state.method,
6053
6087
  error: state.error,
6054
6088
  backoffExpires: state.backoffExpires,
6055
- onSubmit: (code) => this.handleTotpSubmit(code),
6056
- onResend: () => this.handleTotpResend(),
6089
+ onSubmit: (code) => this.handleOtpSubmit(code),
6090
+ onResend: () => this.handleOtpResend(),
6057
6091
  onBack: () => this.showMethodSelect(),
6058
6092
  });
6059
6093
  case 'two-factor':
@@ -6104,7 +6138,7 @@ class IdentityRenderer {
6104
6138
  onSkip: () => this.handleBackupSkip(),
6105
6139
  });
6106
6140
  case 'backup-code':
6107
- return new TotpVerifyView({
6141
+ return new OtpVerifyView({
6108
6142
  email: state.value,
6109
6143
  method: state.method,
6110
6144
  error: state.error,
@@ -6256,29 +6290,29 @@ class IdentityRenderer {
6256
6290
  async handleMethodSelect(method, userInitiated = false) {
6257
6291
  try {
6258
6292
  switch (method.type) {
6259
- case 'totp': {
6260
- const totpMethod = method.id === 'totp_sms'
6293
+ case 'otp': {
6294
+ const otpMethod = method.id === 'otp_sms'
6261
6295
  ? 'sms'
6262
- : method.id === 'totp_voice'
6296
+ : method.id === 'otp_voice'
6263
6297
  ? 'voice'
6264
6298
  : 'email';
6265
6299
  this.setState({ view: 'loading' });
6266
- const result = await this.totpHandler.send(totpMethod);
6300
+ const result = await this.otpHandler.send(otpMethod);
6267
6301
  if (!result.success) {
6268
6302
  if (this.renderBlockedInterstitial(result.errorCode))
6269
6303
  return;
6270
6304
  this.setState({
6271
6305
  view: 'error',
6272
6306
  message: result.error ?? 'Failed to send code',
6273
- code: 'totp_send_failed',
6307
+ code: 'otp_send_failed',
6274
6308
  });
6275
6309
  return;
6276
6310
  }
6277
6311
  this.setState({
6278
- view: 'totp-verify',
6312
+ view: 'otp-verify',
6279
6313
  email: this.recipient,
6280
- method: totpMethod,
6281
- kindling: this.verificationState.totp.kindling,
6314
+ method: otpMethod,
6315
+ kindling: this.verificationState.otp.kindling,
6282
6316
  });
6283
6317
  break;
6284
6318
  }
@@ -6328,7 +6362,7 @@ class IdentityRenderer {
6328
6362
  // A blocked Identity (trial exhausted/expired, paid capacity) is
6329
6363
  // terminal — show the "sign-in unavailable" interstitial, not a
6330
6364
  // retryable "Try Again" that invites retrying a permanently-blocked
6331
- // login. Mirrors the totp send path.
6365
+ // login. Mirrors the otp send path.
6332
6366
  if (this.renderBlockedInterstitial(result.errorCode))
6333
6367
  return;
6334
6368
  this.setState({
@@ -6386,11 +6420,11 @@ class IdentityRenderer {
6386
6420
  });
6387
6421
  return true;
6388
6422
  }
6389
- async handleTotpSubmit(code) {
6390
- if (this.viewState.view !== 'totp-verify')
6423
+ async handleOtpSubmit(code) {
6424
+ if (this.viewState.view !== 'otp-verify')
6391
6425
  return;
6392
- const currentMethod = this.verificationState.totp.method ?? 'email';
6393
- const result = await this.totpHandler.verify(code);
6426
+ const currentMethod = this.verificationState.otp.method ?? 'email';
6427
+ const result = await this.otpHandler.verify(code);
6394
6428
  if (result.secondFactor) {
6395
6429
  this.setState({
6396
6430
  view: 'two-factor',
@@ -6417,33 +6451,33 @@ class IdentityRenderer {
6417
6451
  const errorMsg = result.error?.toLowerCase() ?? '';
6418
6452
  if (errorMsg.includes('expired')) {
6419
6453
  // Auto-resend a new code
6420
- const resendResult = await this.totpHandler.resend();
6454
+ const resendResult = await this.otpHandler.resend();
6421
6455
  if (resendResult.success) {
6422
6456
  this.setState({
6423
- view: 'totp-verify',
6457
+ view: 'otp-verify',
6424
6458
  email: this.recipient,
6425
6459
  method: currentMethod,
6426
- kindling: this.verificationState.totp.kindling,
6460
+ kindling: this.verificationState.otp.kindling,
6427
6461
  error: 'Code expired. We\'ve sent a new one.',
6428
6462
  });
6429
6463
  return;
6430
6464
  }
6431
6465
  // Resend failed - show error
6432
6466
  this.setState({
6433
- view: 'totp-verify',
6467
+ view: 'otp-verify',
6434
6468
  email: this.recipient,
6435
6469
  method: currentMethod,
6436
- kindling: this.verificationState.totp.kindling,
6470
+ kindling: this.verificationState.otp.kindling,
6437
6471
  error: resendResult.error ?? 'Code expired and failed to resend.',
6438
6472
  });
6439
6473
  return;
6440
6474
  }
6441
6475
  // Other verification failure
6442
6476
  this.setState({
6443
- view: 'totp-verify',
6477
+ view: 'otp-verify',
6444
6478
  email: this.recipient,
6445
6479
  method: currentMethod,
6446
- kindling: this.verificationState.totp.kindling,
6480
+ kindling: this.verificationState.otp.kindling,
6447
6481
  error: result.error ?? 'Invalid code. Please try again.',
6448
6482
  backoffExpires: result.backoffExpires,
6449
6483
  });
@@ -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) {
@@ -6477,19 +6511,19 @@ class IdentityRenderer {
6477
6511
  this.setState({ view: 'two-factor', ticket, methods, error: message });
6478
6512
  }
6479
6513
  }
6480
- async handleTotpResend() {
6481
- if (this.viewState.view !== 'totp-verify')
6514
+ async handleOtpResend() {
6515
+ if (this.viewState.view !== 'otp-verify')
6482
6516
  return;
6483
- const currentMethod = this.verificationState.totp.method ?? 'email';
6484
- const result = await this.totpHandler.resend();
6517
+ const currentMethod = this.verificationState.otp.method ?? 'email';
6518
+ const result = await this.otpHandler.resend();
6485
6519
  if (!result.success) {
6486
6520
  if (this.renderBlockedInterstitial(result.errorCode))
6487
6521
  return;
6488
6522
  this.setState({
6489
- view: 'totp-verify',
6523
+ view: 'otp-verify',
6490
6524
  email: this.recipient,
6491
6525
  method: currentMethod,
6492
- kindling: this.verificationState.totp.kindling,
6526
+ kindling: this.verificationState.otp.kindling,
6493
6527
  error: result.error ?? 'Failed to resend code',
6494
6528
  });
6495
6529
  }
@@ -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
  /**
@@ -7160,315 +7187,229 @@ class IdentityRenderer {
7160
7187
  }
7161
7188
  }
7162
7189
  /**
7163
- * Handle fallback from SparkLink to TOTP verification code.
7190
+ * Handle fallback from SparkLink to OTP verification code.
7164
7191
  */
7165
7192
  async handleSparkLinkFallback() {
7166
7193
  this.cleanupSparkLink();
7167
7194
  this.setState({ view: 'loading' });
7168
- const result = await this.totpHandler.send('email');
7195
+ const result = await this.otpHandler.send('email');
7169
7196
  if (!result.success) {
7170
7197
  if (this.renderBlockedInterstitial(result.errorCode))
7171
7198
  return;
7172
7199
  this.setState({
7173
7200
  view: 'error',
7174
7201
  message: result.error ?? 'Failed to send code',
7175
- code: 'totp_send_failed',
7202
+ code: 'otp_send_failed',
7176
7203
  });
7177
7204
  return;
7178
7205
  }
7179
7206
  this.setState({
7180
- view: 'totp-verify',
7207
+ view: 'otp-verify',
7181
7208
  email: this.recipient,
7182
7209
  method: 'email',
7183
- kindling: this.verificationState.totp.kindling,
7210
+ kindling: this.verificationState.otp.kindling,
7184
7211
  });
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
 
@@ -7772,7 +7713,7 @@ function attachClickHandler(selector, onClick) {
7772
7713
  * Identity Module
7773
7714
  *
7774
7715
  * Provides identity verification through dialog or inline UI.
7775
- * Supports passkey, TOTP, SparkLink, and social authentication.
7716
+ * Supports passkey, OTP, SparkLink, and social authentication.
7776
7717
  *
7777
7718
  * @example Dialog mode (immediate)
7778
7719
  * const result = await sv.products.identity.verify();
@@ -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())