@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.
@@ -431,7 +431,7 @@ class HealthModule {
431
431
  * this; clients of the SDK never see any of it.
432
432
  */
433
433
  /** Default request timeout in milliseconds (30 seconds). */
434
- const DEFAULT_TIMEOUT_MS = 30000;
434
+ const DEFAULT_TIMEOUT_MS$1 = 30000;
435
435
  /**
436
436
  * Combine a fresh timeout with a session close signal into one AbortSignal.
437
437
  *
@@ -464,7 +464,7 @@ function combineTimeoutAndCloseSignals(timeoutMs, closeSignal) {
464
464
  };
465
465
  }
466
466
  class SparkVaultApi {
467
- constructor(timeoutMs = DEFAULT_TIMEOUT_MS) {
467
+ constructor(timeoutMs = DEFAULT_TIMEOUT_MS$1) {
468
468
  /**
469
469
  * Abort controller for the current session. Replaced by resetSession()
470
470
  * at the start of every user-facing session — an aborted controller can
@@ -884,20 +884,20 @@ class IdentityApi extends SparkVaultApi {
884
884
  return params;
885
885
  }
886
886
  /**
887
- * Send TOTP code to email or phone
887
+ * Send OTP code to email or phone
888
888
  */
889
- async sendTotp(params) {
890
- return this.request('POST', '/totp/send', {
889
+ async sendOtp(params) {
890
+ return this.request('POST', '/otp/send', {
891
891
  recipient: params.recipient,
892
892
  method: params.method,
893
893
  ...this.buildAuthContextParams(params.authContext),
894
894
  });
895
895
  }
896
896
  /**
897
- * Verify TOTP code
897
+ * Verify OTP code
898
898
  */
899
- async verifyTotp(params) {
900
- return this.request('POST', '/totp/verify', {
899
+ async verifyOtp(params) {
900
+ return this.request('POST', '/otp/verify', {
901
901
  kindling: params.kindling,
902
902
  pin: params.pin,
903
903
  recipient: params.recipient,
@@ -1133,25 +1133,25 @@ class IdentityApiError extends SparkVaultError {
1133
1133
  */
1134
1134
  const METHOD_REGISTRY = {
1135
1135
  // Core methods
1136
- totp_email: {
1137
- id: 'totp_email',
1138
- type: 'totp',
1136
+ otp_email: {
1137
+ id: 'otp_email',
1138
+ type: 'otp',
1139
1139
  identityType: 'email',
1140
1140
  name: 'Email code',
1141
1141
  description: 'Get a one-time code via email',
1142
1142
  icon: 'email',
1143
1143
  },
1144
- totp_sms: {
1145
- id: 'totp_sms',
1146
- type: 'totp',
1144
+ otp_sms: {
1145
+ id: 'otp_sms',
1146
+ type: 'otp',
1147
1147
  identityType: 'phone',
1148
1148
  name: 'Text message',
1149
1149
  description: 'Get a one-time code via SMS',
1150
1150
  icon: 'sms',
1151
1151
  },
1152
- totp_voice: {
1153
- id: 'totp_voice',
1154
- type: 'totp',
1152
+ otp_voice: {
1153
+ id: 'otp_voice',
1154
+ type: 'otp',
1155
1155
  identityType: 'phone',
1156
1156
  name: 'Voice call',
1157
1157
  description: 'Get a one-time code via phone call',
@@ -1267,8 +1267,8 @@ class VerificationState {
1267
1267
  isFallbackMode: false,
1268
1268
  pendingResult: null,
1269
1269
  };
1270
- // TOTP state
1271
- this._totp = {
1270
+ // OTP state
1271
+ this._otp = {
1272
1272
  kindling: '',
1273
1273
  method: null,
1274
1274
  };
@@ -1327,15 +1327,100 @@ class VerificationState {
1327
1327
  setPendingResult(result) {
1328
1328
  this._passkey.pendingResult = result;
1329
1329
  }
1330
- // --- TOTP State ---
1331
- get totp() {
1332
- return this._totp;
1330
+ // --- OTP State ---
1331
+ get otp() {
1332
+ return this._otp;
1333
1333
  }
1334
1334
  setKindling(kindling) {
1335
- this._totp.kindling = kindling;
1335
+ this._otp.kindling = kindling;
1336
1336
  }
1337
- setTotpMethod(method) {
1338
- this._totp.method = method;
1337
+ setOtpMethod(method) {
1338
+ this._otp.method = method;
1339
+ }
1340
+ }
1341
+
1342
+ /**
1343
+ * Popup Launcher
1344
+ *
1345
+ * Opens a top-level popup on the Identity origin and bridges its result back
1346
+ * over postMessage. Used by both the passkey ceremony (which needs a popup so
1347
+ * WebAuthn runs same-origin with the RP id) and the dialog login flow (which
1348
+ * needs a top-level window on the IdP origin so login's first-party SSO cookie
1349
+ * persists).
1350
+ *
1351
+ * The single transfer path: synchronous `window.open` inside the user gesture
1352
+ * (so the browser never blocks it), strict `event.origin` + `data.type`
1353
+ * validation against the caller-supplied trusted origin, a 60s timeout, and a
1354
+ * `window.closed` poll that surfaces a manual close as a cancellation.
1355
+ */
1356
+ /** Default popup dimensions — a centered login/ceremony window. */
1357
+ const DEFAULT_WIDTH = 480;
1358
+ const DEFAULT_HEIGHT = 640;
1359
+ /** Default timeout for popup operations (60 seconds). */
1360
+ const DEFAULT_TIMEOUT_MS = 60000;
1361
+ /** How often to check whether the user closed the popup manually. */
1362
+ const CLOSED_POLL_INTERVAL_MS = 500;
1363
+ /**
1364
+ * Open a popup and resolve with the first validated result envelope it posts.
1365
+ *
1366
+ * Resolves with the raw `event.data` (the caller inspects its `success`/`error`
1367
+ * fields). Rejects with `PopupBlockedError` when the browser blocked the popup,
1368
+ * `UserCancelledError` when the user closed it manually, and `TimeoutError`
1369
+ * when no result arrived within the timeout.
1370
+ */
1371
+ class PopupLauncher {
1372
+ openPopup(options) {
1373
+ const width = options.width ?? DEFAULT_WIDTH;
1374
+ const height = options.height ?? DEFAULT_HEIGHT;
1375
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
1376
+ return new Promise((resolve, reject) => {
1377
+ const left = Math.round((window.screen.width - width) / 2);
1378
+ const top = Math.round((window.screen.height - height) / 2);
1379
+ // Synchronous open inside the caller's user gesture — any await before
1380
+ // this point would let the browser treat the popup as programmatic and
1381
+ // block it.
1382
+ const popup = window.open(options.url, options.windowName, `width=${width},height=${height},left=${left},top=${top},popup=1`);
1383
+ if (!popup) {
1384
+ reject(new PopupBlockedError());
1385
+ return;
1386
+ }
1387
+ let settled = false;
1388
+ const cleanup = () => {
1389
+ window.removeEventListener('message', handleMessage);
1390
+ clearTimeout(timeoutId);
1391
+ clearInterval(pollClosedId);
1392
+ };
1393
+ const handleMessage = (event) => {
1394
+ // Only trust the server-validated Identity origin — never the broader
1395
+ // sparkvault.com family (XSS or subdomain-takeover relay).
1396
+ if (event.origin !== options.trustedOrigin) {
1397
+ return;
1398
+ }
1399
+ const data = event.data;
1400
+ if (data?.type !== options.resultType) {
1401
+ return;
1402
+ }
1403
+ settled = true;
1404
+ cleanup();
1405
+ resolve(data);
1406
+ };
1407
+ window.addEventListener('message', handleMessage);
1408
+ const timeoutId = setTimeout(() => {
1409
+ if (settled)
1410
+ return;
1411
+ settled = true;
1412
+ cleanup();
1413
+ popup.close();
1414
+ reject(new TimeoutError('Popup operation timed out. Please try again.'));
1415
+ }, timeoutMs);
1416
+ const pollClosedId = setInterval(() => {
1417
+ if (popup.closed && !settled) {
1418
+ settled = true;
1419
+ cleanup();
1420
+ reject(new UserCancelledError('Authentication was cancelled.'));
1421
+ }
1422
+ }, CLOSED_POLL_INTERVAL_MS);
1423
+ });
1339
1424
  }
1340
1425
  }
1341
1426
 
@@ -1352,11 +1437,11 @@ class VerificationState {
1352
1437
  * 3. Popup sends result via postMessage
1353
1438
  * 4. SDK receives result and returns to caller
1354
1439
  */
1355
- /** Popup window dimensions */
1440
+ /** Passkey popup window dimensions. */
1356
1441
  const POPUP_WIDTH = 450;
1357
1442
  const POPUP_HEIGHT = 500;
1358
- /** Timeout for popup operations (60 seconds) */
1359
- const POPUP_TIMEOUT_MS = 60000;
1443
+ /** `data.type` the passkey popup posts back. */
1444
+ const PASSKEY_RESULT_TYPE = 'sparkvault-passkey-result';
1360
1445
  /**
1361
1446
  * Handles WebAuthn passkey registration and verification via popup
1362
1447
  */
@@ -1364,6 +1449,7 @@ class PasskeyHandler {
1364
1449
  constructor(api, state) {
1365
1450
  this.api = api;
1366
1451
  this.state = state;
1452
+ this.popupLauncher = new PopupLauncher();
1367
1453
  // Extract base URL and account ID from the API's URL construction
1368
1454
  // The API uses: `${this.config.identityBaseUrl}/${this.config.accountId}`
1369
1455
  // We need to access these values for popup URL construction
@@ -1526,125 +1612,86 @@ class PasskeyHandler {
1526
1612
  };
1527
1613
  }
1528
1614
  /**
1529
- * Open passkey popup and wait for result
1615
+ * Open passkey popup (top-level on the Identity origin, so WebAuthn runs
1616
+ * same-origin with the RP id) and wait for its result.
1530
1617
  */
1531
1618
  async openPasskeyPopup(mode, registrationToken) {
1532
- return new Promise((resolve) => {
1533
- // Registration carries the freshly verified identifier so the backend can
1534
- // attach the credential to that SVID. Verification carries it too when
1535
- // known, to scope the ceremony to that person's passkeys; the credential
1536
- // userHandle still routes completion to the SVID.
1537
- const params = new URLSearchParams({
1538
- mode,
1539
- origin: window.location.origin,
1619
+ // Registration carries the freshly verified identifier so the backend can
1620
+ // attach the credential to that SVID. Verification carries it too when
1621
+ // known, to scope the ceremony to that person's passkeys; the credential
1622
+ // userHandle still routes completion to the SVID.
1623
+ const params = new URLSearchParams({
1624
+ mode,
1625
+ origin: window.location.origin,
1626
+ });
1627
+ if (this.state.recipient) {
1628
+ const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
1629
+ params.set(identityParam, this.state.recipient);
1630
+ }
1631
+ // Add auth context for OIDC/simple mode flows
1632
+ const authContext = this.state.authContext;
1633
+ if (authContext?.authRequestId) {
1634
+ params.set('auth_request_id', authContext.authRequestId);
1635
+ }
1636
+ if (authContext?.simpleMode) {
1637
+ params.set('simple_mode', JSON.stringify({
1638
+ success_url: authContext.simpleMode.successUrl,
1639
+ failure_url: authContext.simpleMode.failureUrl,
1640
+ state: authContext.simpleMode.state,
1641
+ session_id: authContext.simpleMode.sessionId,
1642
+ }));
1643
+ }
1644
+ const hash = mode === 'register' && registrationToken
1645
+ ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
1646
+ : '';
1647
+ const popupUrl = `${this.baseUrl}/${this.accountId}/passkey/popup?${params}${hash}`;
1648
+ let message;
1649
+ try {
1650
+ message = await this.popupLauncher.openPopup({
1651
+ url: popupUrl,
1652
+ windowName: 'sparkvault-passkey',
1653
+ width: POPUP_WIDTH,
1654
+ height: POPUP_HEIGHT,
1655
+ resultType: PASSKEY_RESULT_TYPE,
1656
+ trustedOrigin: this.trustedOrigin,
1540
1657
  });
1541
- if (this.state.recipient) {
1542
- const identityParam = this.state.identityType === 'phone' ? 'phone' : 'email';
1543
- params.set(identityParam, this.state.recipient);
1544
- }
1545
- // Add auth context for OIDC/simple mode flows
1546
- const authContext = this.state.authContext;
1547
- if (authContext?.authRequestId) {
1548
- params.set('auth_request_id', authContext.authRequestId);
1549
- }
1550
- if (authContext?.simpleMode) {
1551
- params.set('simple_mode', JSON.stringify({
1552
- success_url: authContext.simpleMode.successUrl,
1553
- failure_url: authContext.simpleMode.failureUrl,
1554
- state: authContext.simpleMode.state,
1555
- session_id: authContext.simpleMode.sessionId,
1556
- }));
1557
- }
1558
- const hash = mode === 'register' && registrationToken
1559
- ? `#${new URLSearchParams({ registration_token: registrationToken }).toString()}`
1560
- : '';
1561
- const popupUrl = `${this.baseUrl}/${this.accountId}/passkey/popup?${params}${hash}`;
1562
- // Calculate popup position (centered)
1563
- const left = Math.round((window.screen.width - POPUP_WIDTH) / 2);
1564
- const top = Math.round((window.screen.height - POPUP_HEIGHT) / 2);
1565
- // Open popup
1566
- const popup = window.open(popupUrl, 'sparkvault-passkey', `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},popup=1`);
1567
- if (!popup) {
1568
- resolve({
1658
+ }
1659
+ catch (error) {
1660
+ if (error instanceof PopupBlockedError) {
1661
+ return {
1569
1662
  success: false,
1570
- error: 'Popup was blocked. Please allow popups for this site.',
1663
+ error: error.message,
1571
1664
  errorType: 'popup_blocked',
1572
- });
1573
- return;
1665
+ };
1574
1666
  }
1575
- // Set up message listener
1576
- let resolved = false;
1577
- const cleanup = () => {
1578
- window.removeEventListener('message', handleMessage);
1579
- clearTimeout(timeoutId);
1580
- clearInterval(pollClosedId);
1667
+ if (error instanceof UserCancelledError) {
1668
+ return {
1669
+ success: false,
1670
+ error: error.message,
1671
+ errorType: 'cancelled',
1672
+ };
1673
+ }
1674
+ return {
1675
+ success: false,
1676
+ error: error instanceof Error ? error.message : 'Passkey operation failed. Please try again.',
1677
+ errorType: 'unknown',
1581
1678
  };
1582
- const handleMessage = (event) => {
1583
- // Validate origin - must be from sparkvault.com
1584
- if (!this.isValidMessageOrigin(event.origin)) {
1585
- return;
1586
- }
1587
- const data = event.data;
1588
- // Verify message type
1589
- if (data?.type !== 'sparkvault-passkey-result') {
1590
- return;
1591
- }
1592
- resolved = true;
1593
- cleanup();
1594
- if (data.success && data.data) {
1595
- resolve({
1596
- success: true,
1597
- result: {
1598
- token: data.data.token || '',
1599
- identity: data.data.identity || this.state.recipient,
1600
- identityType: data.data.identity_type || 'email',
1601
- svid: data.data.svid,
1602
- sessionId: data.data.session_id,
1603
- refreshToken: data.data.refresh_token,
1604
- redirect: data.data.redirect,
1605
- },
1606
- });
1607
- }
1608
- else {
1609
- resolve(this.handlePopupError(data.error, data.message, data.errorCode));
1610
- }
1679
+ }
1680
+ if (message.success && message.data) {
1681
+ return {
1682
+ success: true,
1683
+ result: {
1684
+ token: message.data.token || '',
1685
+ identity: message.data.identity || this.state.recipient,
1686
+ identityType: message.data.identity_type || 'email',
1687
+ svid: message.data.svid,
1688
+ sessionId: message.data.session_id,
1689
+ refreshToken: message.data.refresh_token,
1690
+ redirect: message.data.redirect,
1691
+ },
1611
1692
  };
1612
- window.addEventListener('message', handleMessage);
1613
- // Timeout after 60 seconds
1614
- const timeoutId = setTimeout(() => {
1615
- if (!resolved) {
1616
- resolved = true;
1617
- cleanup();
1618
- popup.close();
1619
- resolve({
1620
- success: false,
1621
- error: 'Passkey operation timed out. Please try again.',
1622
- errorType: 'unknown',
1623
- });
1624
- }
1625
- }, POPUP_TIMEOUT_MS);
1626
- // Poll for popup being closed manually
1627
- const pollClosedId = setInterval(() => {
1628
- if (popup.closed && !resolved) {
1629
- resolved = true;
1630
- cleanup();
1631
- resolve({
1632
- success: false,
1633
- error: 'Authentication was cancelled.',
1634
- errorType: 'cancelled',
1635
- });
1636
- }
1637
- }, 500);
1638
- });
1639
- }
1640
- /**
1641
- * Validate that a postMessage came from the identity service's own
1642
- * origin. We do not accept the broader sparkvault.com family - a popup
1643
- * is only opened against `this.baseUrl`, so any other origin is
1644
- * either an unrelated tab or a forgery attempt.
1645
- */
1646
- isValidMessageOrigin(origin) {
1647
- return origin === this.trustedOrigin;
1693
+ }
1694
+ return this.handlePopupError(message.error, message.message, message.errorCode);
1648
1695
  }
1649
1696
  /**
1650
1697
  * Handle popup error response
@@ -1682,32 +1729,32 @@ class PasskeyHandler {
1682
1729
  }
1683
1730
 
1684
1731
  /**
1685
- * TOTP Handler
1732
+ * OTP Handler
1686
1733
  *
1687
- * Single responsibility: TOTP code sending and verification.
1688
- * Extracts TOTP logic from IdentityRenderer for better separation of concerns.
1734
+ * Single responsibility: OTP code sending and verification.
1735
+ * Extracts OTP logic from IdentityRenderer for better separation of concerns.
1689
1736
  */
1690
1737
  /**
1691
- * Handles TOTP code sending and verification
1738
+ * Handles OTP code sending and verification
1692
1739
  */
1693
- class TotpHandler {
1740
+ class OtpHandler {
1694
1741
  constructor(api, state) {
1695
1742
  this.api = api;
1696
1743
  this.state = state;
1697
1744
  }
1698
1745
  /**
1699
- * Send TOTP code via email, SMS, or voice
1746
+ * Send OTP code via email, SMS, or voice
1700
1747
  */
1701
1748
  async send(method) {
1702
1749
  try {
1703
- const response = await this.api.sendTotp({
1750
+ const response = await this.api.sendOtp({
1704
1751
  recipient: this.state.recipient,
1705
1752
  method,
1706
1753
  authContext: this.state.authContext,
1707
1754
  });
1708
1755
  // Update state with kindling
1709
1756
  this.state.setKindling(response.kindling);
1710
- this.state.setTotpMethod(method);
1757
+ this.state.setOtpMethod(method);
1711
1758
  return {
1712
1759
  success: true,
1713
1760
  kindling: response.kindling,
@@ -1725,18 +1772,18 @@ class TotpHandler {
1725
1772
  }
1726
1773
  }
1727
1774
  /**
1728
- * Resend TOTP code
1775
+ * Resend OTP code
1729
1776
  */
1730
1777
  async resend() {
1731
- const method = this.state.totp.method;
1778
+ const method = this.state.otp.method;
1732
1779
  if (!method) {
1733
1780
  return {
1734
1781
  success: false,
1735
- error: 'No TOTP method set',
1782
+ error: 'No OTP method set',
1736
1783
  };
1737
1784
  }
1738
1785
  try {
1739
- const response = await this.api.sendTotp({
1786
+ const response = await this.api.sendOtp({
1740
1787
  recipient: this.state.recipient,
1741
1788
  method,
1742
1789
  authContext: this.state.authContext,
@@ -1760,10 +1807,10 @@ class TotpHandler {
1760
1807
  }
1761
1808
  }
1762
1809
  /**
1763
- * Verify TOTP code
1810
+ * Verify OTP code
1764
1811
  */
1765
1812
  async verify(code) {
1766
- const kindling = this.state.totp.kindling;
1813
+ const kindling = this.state.otp.kindling;
1767
1814
  if (!kindling) {
1768
1815
  return {
1769
1816
  success: false,
@@ -1771,7 +1818,7 @@ class TotpHandler {
1771
1818
  };
1772
1819
  }
1773
1820
  try {
1774
- const response = await this.api.verifyTotp({
1821
+ const response = await this.api.verifyOtp({
1775
1822
  kindling,
1776
1823
  pin: code,
1777
1824
  recipient: this.state.recipient,
@@ -2306,17 +2353,17 @@ function getStyles(options) {
2306
2353
  }
2307
2354
 
2308
2355
  /* ========================================
2309
- TOTP INPUT
2356
+ OTP INPUT
2310
2357
  ======================================== */
2311
2358
 
2312
- .sv-totp-input-group {
2359
+ .sv-otp-input-group {
2313
2360
  display: flex;
2314
2361
  gap: 8px;
2315
2362
  justify-content: center;
2316
2363
  margin-bottom: 16px;
2317
2364
  }
2318
2365
 
2319
- .sv-totp-digit {
2366
+ .sv-otp-digit {
2320
2367
  width: 44px;
2321
2368
  height: 52px;
2322
2369
  text-align: center;
@@ -2331,17 +2378,17 @@ function getStyles(options) {
2331
2378
  transition: border-color 0.15s ease, box-shadow 0.15s ease;
2332
2379
  }
2333
2380
 
2334
- .sv-totp-digit:hover:not(:focus):not(:disabled) {
2381
+ .sv-otp-digit:hover:not(:focus):not(:disabled) {
2335
2382
  border-color: ${tokens.borderHover};
2336
2383
  }
2337
2384
 
2338
- .sv-totp-digit:focus {
2385
+ .sv-otp-digit:focus {
2339
2386
  outline: none;
2340
2387
  border-color: ${tokens.borderFocus};
2341
2388
  box-shadow: 0 0 0 3px ${tokens.primaryLight};
2342
2389
  }
2343
2390
 
2344
- .sv-totp-digit:disabled {
2391
+ .sv-otp-digit:disabled {
2345
2392
  opacity: 0.5;
2346
2393
  cursor: not-allowed;
2347
2394
  }
@@ -2851,7 +2898,7 @@ function getStyles(options) {
2851
2898
  }
2852
2899
 
2853
2900
  /* ========================================
2854
- TOTP VIEW
2901
+ OTP VIEW
2855
2902
  ======================================== */
2856
2903
 
2857
2904
  .sv-resend-container {
@@ -3164,7 +3211,7 @@ function getStyles(options) {
3164
3211
  padding: 24px 28px;
3165
3212
  }
3166
3213
 
3167
- .sv-totp-digit {
3214
+ .sv-otp-digit {
3168
3215
  width: 40px;
3169
3216
  height: 48px;
3170
3217
  font-size: 18px;
@@ -3176,11 +3223,11 @@ function getStyles(options) {
3176
3223
  }
3177
3224
 
3178
3225
  @media (max-width: 360px) {
3179
- .sv-totp-input-group {
3226
+ .sv-otp-input-group {
3180
3227
  gap: 6px;
3181
3228
  }
3182
3229
 
3183
- .sv-totp-digit {
3230
+ .sv-otp-digit {
3184
3231
  width: 36px;
3185
3232
  height: 44px;
3186
3233
  font-size: 16px;
@@ -3864,10 +3911,10 @@ function looksLikePhone(input) {
3864
3911
  return /^[+(\d]/.test(trimmed) && !/[@.]/.test(trimmed);
3865
3912
  }
3866
3913
  /**
3867
- * Validate TOTP code format.
3914
+ * Validate OTP code format.
3868
3915
  * Returns sanitized code or null if invalid.
3869
3916
  */
3870
- function validateTotpCode(code) {
3917
+ function validateOtpCode(code) {
3871
3918
  const digits = code.replace(/\D/g, '');
3872
3919
  if (digits.length === 6) {
3873
3920
  return digits;
@@ -4223,12 +4270,12 @@ class MethodSelectView {
4223
4270
  }
4224
4271
 
4225
4272
  /**
4226
- * TOTP Verification View
4273
+ * OTP Verification View
4227
4274
  *
4228
- * Collects and validates the 6-digit TOTP code sent via email, SMS, or voice.
4275
+ * Collects and validates the 6-digit OTP code sent via email, SMS, or voice.
4229
4276
  */
4230
4277
  const CODE_LENGTH = 6;
4231
- class TotpVerifyView {
4278
+ class OtpVerifyView {
4232
4279
  constructor(props) {
4233
4280
  this.inputElements = [];
4234
4281
  this.submitButton = null;
@@ -4305,14 +4352,14 @@ class TotpVerifyView {
4305
4352
  return link;
4306
4353
  }
4307
4354
  createInputGroup() {
4308
- const group = div('sv-totp-input-group');
4355
+ const group = div('sv-otp-input-group');
4309
4356
  for (let i = 0; i < CODE_LENGTH; i++) {
4310
4357
  const input = document.createElement('input');
4311
4358
  input.type = 'text';
4312
4359
  input.inputMode = 'numeric';
4313
4360
  input.pattern = '[0-9]*';
4314
4361
  input.maxLength = 1;
4315
- input.className = 'sv-totp-digit';
4362
+ input.className = 'sv-otp-digit';
4316
4363
  input.autocomplete = 'one-time-code';
4317
4364
  input.setAttribute('aria-label', `Digit ${i + 1} of ${CODE_LENGTH}`);
4318
4365
  // Create and store handlers for proper cleanup
@@ -4419,7 +4466,7 @@ class TotpVerifyView {
4419
4466
  return;
4420
4467
  }
4421
4468
  const code = this.getCode();
4422
- const validCode = validateTotpCode(code);
4469
+ const validCode = validateOtpCode(code);
4423
4470
  if (!validCode) {
4424
4471
  this.showError('Please enter the complete 6-digit code');
4425
4472
  return;
@@ -5727,7 +5774,7 @@ class OriginNotAllowedView {
5727
5774
  * Identity View Renderer
5728
5775
  *
5729
5776
  * Orchestrates view state and rendering for identity verification flows.
5730
- * Uses extracted handlers for TOTP and Passkey operations.
5777
+ * Uses extracted handlers for OTP and Passkey operations.
5731
5778
  */
5732
5779
  /**
5733
5780
  * End-user copy for a blocked Identity. Intentionally generic — it never names
@@ -5744,19 +5791,6 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
5744
5791
  ].join(' '),
5745
5792
  code: 'sparklink_csp_blocked',
5746
5793
  };
5747
- /**
5748
- * Navigate the browser. When the flow runs inside the embed iframe, the host
5749
- * injects `onNavigate` (via VerifyOptions) so redirects move the customer's
5750
- * top window rather than the iframe — providers refuse to be framed anyway.
5751
- * Outside the iframe this falls back to a normal same-window navigation.
5752
- */
5753
- function navigateWith(options, url) {
5754
- if (options.onNavigate) {
5755
- options.onNavigate(url);
5756
- return;
5757
- }
5758
- window.location.href = url;
5759
- }
5760
5794
  class IdentityRenderer {
5761
5795
  constructor(container, api, options, callbacks) {
5762
5796
  // View management
@@ -5783,7 +5817,7 @@ class IdentityRenderer {
5783
5817
  this.verificationState = new VerificationState();
5784
5818
  // Initialize handlers with shared state
5785
5819
  this.passkeyHandler = new PasskeyHandler(api, this.verificationState);
5786
- this.totpHandler = new TotpHandler(api, this.verificationState);
5820
+ this.otpHandler = new OtpHandler(api, this.verificationState);
5787
5821
  this.sparkLinkHandler = new SparkLinkHandler(api, this.verificationState);
5788
5822
  // Set initial identity from options
5789
5823
  if (options.email) {
@@ -6050,14 +6084,14 @@ class IdentityRenderer {
6050
6084
  onSelectMethod: (method) => this.handleMethodSelect(method, true),
6051
6085
  onBack: state.email ? () => this.showIdentityInput() : undefined,
6052
6086
  });
6053
- case 'totp-verify':
6054
- return new TotpVerifyView({
6087
+ case 'otp-verify':
6088
+ return new OtpVerifyView({
6055
6089
  email: state.email,
6056
6090
  method: state.method,
6057
6091
  error: state.error,
6058
6092
  backoffExpires: state.backoffExpires,
6059
- onSubmit: (code) => this.handleTotpSubmit(code),
6060
- onResend: () => this.handleTotpResend(),
6093
+ onSubmit: (code) => this.handleOtpSubmit(code),
6094
+ onResend: () => this.handleOtpResend(),
6061
6095
  onBack: () => this.showMethodSelect(),
6062
6096
  });
6063
6097
  case 'two-factor':
@@ -6108,7 +6142,7 @@ class IdentityRenderer {
6108
6142
  onSkip: () => this.handleBackupSkip(),
6109
6143
  });
6110
6144
  case 'backup-code':
6111
- return new TotpVerifyView({
6145
+ return new OtpVerifyView({
6112
6146
  email: state.value,
6113
6147
  method: state.method,
6114
6148
  error: state.error,
@@ -6260,29 +6294,29 @@ class IdentityRenderer {
6260
6294
  async handleMethodSelect(method, userInitiated = false) {
6261
6295
  try {
6262
6296
  switch (method.type) {
6263
- case 'totp': {
6264
- const totpMethod = method.id === 'totp_sms'
6297
+ case 'otp': {
6298
+ const otpMethod = method.id === 'otp_sms'
6265
6299
  ? 'sms'
6266
- : method.id === 'totp_voice'
6300
+ : method.id === 'otp_voice'
6267
6301
  ? 'voice'
6268
6302
  : 'email';
6269
6303
  this.setState({ view: 'loading' });
6270
- const result = await this.totpHandler.send(totpMethod);
6304
+ const result = await this.otpHandler.send(otpMethod);
6271
6305
  if (!result.success) {
6272
6306
  if (this.renderBlockedInterstitial(result.errorCode))
6273
6307
  return;
6274
6308
  this.setState({
6275
6309
  view: 'error',
6276
6310
  message: result.error ?? 'Failed to send code',
6277
- code: 'totp_send_failed',
6311
+ code: 'otp_send_failed',
6278
6312
  });
6279
6313
  return;
6280
6314
  }
6281
6315
  this.setState({
6282
- view: 'totp-verify',
6316
+ view: 'otp-verify',
6283
6317
  email: this.recipient,
6284
- method: totpMethod,
6285
- kindling: this.verificationState.totp.kindling,
6318
+ method: otpMethod,
6319
+ kindling: this.verificationState.otp.kindling,
6286
6320
  });
6287
6321
  break;
6288
6322
  }
@@ -6332,7 +6366,7 @@ class IdentityRenderer {
6332
6366
  // A blocked Identity (trial exhausted/expired, paid capacity) is
6333
6367
  // terminal — show the "sign-in unavailable" interstitial, not a
6334
6368
  // retryable "Try Again" that invites retrying a permanently-blocked
6335
- // login. Mirrors the totp send path.
6369
+ // login. Mirrors the otp send path.
6336
6370
  if (this.renderBlockedInterstitial(result.errorCode))
6337
6371
  return;
6338
6372
  this.setState({
@@ -6390,11 +6424,11 @@ class IdentityRenderer {
6390
6424
  });
6391
6425
  return true;
6392
6426
  }
6393
- async handleTotpSubmit(code) {
6394
- if (this.viewState.view !== 'totp-verify')
6427
+ async handleOtpSubmit(code) {
6428
+ if (this.viewState.view !== 'otp-verify')
6395
6429
  return;
6396
- const currentMethod = this.verificationState.totp.method ?? 'email';
6397
- const result = await this.totpHandler.verify(code);
6430
+ const currentMethod = this.verificationState.otp.method ?? 'email';
6431
+ const result = await this.otpHandler.verify(code);
6398
6432
  if (result.secondFactor) {
6399
6433
  this.setState({
6400
6434
  view: 'two-factor',
@@ -6421,33 +6455,33 @@ class IdentityRenderer {
6421
6455
  const errorMsg = result.error?.toLowerCase() ?? '';
6422
6456
  if (errorMsg.includes('expired')) {
6423
6457
  // Auto-resend a new code
6424
- const resendResult = await this.totpHandler.resend();
6458
+ const resendResult = await this.otpHandler.resend();
6425
6459
  if (resendResult.success) {
6426
6460
  this.setState({
6427
- view: 'totp-verify',
6461
+ view: 'otp-verify',
6428
6462
  email: this.recipient,
6429
6463
  method: currentMethod,
6430
- kindling: this.verificationState.totp.kindling,
6464
+ kindling: this.verificationState.otp.kindling,
6431
6465
  error: 'Code expired. We\'ve sent a new one.',
6432
6466
  });
6433
6467
  return;
6434
6468
  }
6435
6469
  // Resend failed - show error
6436
6470
  this.setState({
6437
- view: 'totp-verify',
6471
+ view: 'otp-verify',
6438
6472
  email: this.recipient,
6439
6473
  method: currentMethod,
6440
- kindling: this.verificationState.totp.kindling,
6474
+ kindling: this.verificationState.otp.kindling,
6441
6475
  error: resendResult.error ?? 'Code expired and failed to resend.',
6442
6476
  });
6443
6477
  return;
6444
6478
  }
6445
6479
  // Other verification failure
6446
6480
  this.setState({
6447
- view: 'totp-verify',
6481
+ view: 'otp-verify',
6448
6482
  email: this.recipient,
6449
6483
  method: currentMethod,
6450
- kindling: this.verificationState.totp.kindling,
6484
+ kindling: this.verificationState.otp.kindling,
6451
6485
  error: result.error ?? 'Invalid code. Please try again.',
6452
6486
  backoffExpires: result.backoffExpires,
6453
6487
  });
@@ -6471,7 +6505,7 @@ class IdentityRenderer {
6471
6505
  this.close();
6472
6506
  this.safeOnSuccess(result);
6473
6507
  if (typeof result.redirect === 'string' && result.redirect) {
6474
- navigateWith(this.options, result.redirect);
6508
+ window.location.href = result.redirect;
6475
6509
  }
6476
6510
  }
6477
6511
  catch (error) {
@@ -6481,19 +6515,19 @@ class IdentityRenderer {
6481
6515
  this.setState({ view: 'two-factor', ticket, methods, error: message });
6482
6516
  }
6483
6517
  }
6484
- async handleTotpResend() {
6485
- if (this.viewState.view !== 'totp-verify')
6518
+ async handleOtpResend() {
6519
+ if (this.viewState.view !== 'otp-verify')
6486
6520
  return;
6487
- const currentMethod = this.verificationState.totp.method ?? 'email';
6488
- const result = await this.totpHandler.resend();
6521
+ const currentMethod = this.verificationState.otp.method ?? 'email';
6522
+ const result = await this.otpHandler.resend();
6489
6523
  if (!result.success) {
6490
6524
  if (this.renderBlockedInterstitial(result.errorCode))
6491
6525
  return;
6492
6526
  this.setState({
6493
- view: 'totp-verify',
6527
+ view: 'otp-verify',
6494
6528
  email: this.recipient,
6495
6529
  method: currentMethod,
6496
- kindling: this.verificationState.totp.kindling,
6530
+ kindling: this.verificationState.otp.kindling,
6497
6531
  error: result.error ?? 'Failed to resend code',
6498
6532
  });
6499
6533
  }
@@ -6528,7 +6562,7 @@ class IdentityRenderer {
6528
6562
  this.close();
6529
6563
  this.safeOnSuccess(result.result);
6530
6564
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6531
- navigateWith(this.options, result.result.redirect);
6565
+ window.location.href = result.result.redirect;
6532
6566
  }
6533
6567
  }
6534
6568
  else if (this.renderBlockedInterstitial(result.errorCode)) ;
@@ -6593,19 +6627,12 @@ class IdentityRenderer {
6593
6627
  }
6594
6628
  handleSocialLogin(provider) {
6595
6629
  this.setState({ view: 'oauth-pending', provider });
6596
- // When embedded, social must originate from the host: the OAuth state and
6597
- // redirect_uri belong to the customer's top origin, not this iframe (whose
6598
- // sessionStorage and URL the return would never match). Hand it up.
6599
- if (this.options.onSocial) {
6600
- this.options.onSocial(provider);
6601
- return;
6602
- }
6603
6630
  const state = generateState();
6604
6631
  const redirectUri = window.location.origin + window.location.pathname;
6605
6632
  sessionStorage.setItem('sv_oauth_state', state);
6606
6633
  sessionStorage.setItem('sv_oauth_email', this.recipient);
6607
6634
  const authUrl = this.api.getSocialAuthUrl(provider, redirectUri, state, this.verificationState.authContext);
6608
- navigateWith(this.options, authUrl);
6635
+ window.location.href = authUrl;
6609
6636
  }
6610
6637
  normalizeError(error) {
6611
6638
  if (error instanceof IdentityApiError) {
@@ -6710,7 +6737,7 @@ class IdentityRenderer {
6710
6737
  this.safeOnSuccess(result);
6711
6738
  this.close();
6712
6739
  if (typeof result.redirect === 'string' && result.redirect) {
6713
- navigateWith(this.options, result.redirect);
6740
+ window.location.href = result.redirect;
6714
6741
  }
6715
6742
  }
6716
6743
  /**
@@ -7164,315 +7191,229 @@ class IdentityRenderer {
7164
7191
  }
7165
7192
  }
7166
7193
  /**
7167
- * Handle fallback from SparkLink to TOTP verification code.
7194
+ * Handle fallback from SparkLink to OTP verification code.
7168
7195
  */
7169
7196
  async handleSparkLinkFallback() {
7170
7197
  this.cleanupSparkLink();
7171
7198
  this.setState({ view: 'loading' });
7172
- const result = await this.totpHandler.send('email');
7199
+ const result = await this.otpHandler.send('email');
7173
7200
  if (!result.success) {
7174
7201
  if (this.renderBlockedInterstitial(result.errorCode))
7175
7202
  return;
7176
7203
  this.setState({
7177
7204
  view: 'error',
7178
7205
  message: result.error ?? 'Failed to send code',
7179
- code: 'totp_send_failed',
7206
+ code: 'otp_send_failed',
7180
7207
  });
7181
7208
  return;
7182
7209
  }
7183
7210
  this.setState({
7184
- view: 'totp-verify',
7211
+ view: 'otp-verify',
7185
7212
  email: this.recipient,
7186
7213
  method: 'email',
7187
- kindling: this.verificationState.totp.kindling,
7214
+ kindling: this.verificationState.otp.kindling,
7188
7215
  });
7189
7216
  }
7190
7217
  }
7191
7218
 
7192
- /* global HTMLIFrameElement requestAnimationFrame */
7193
7219
  /**
7194
- * Widget Embedder
7220
+ * Dialog Launcher
7195
7221
  *
7196
- * Host-side half of the iframe architecture. For dialog (modal) verification,
7197
- * the SDK injects a borderless, transparent, full-viewport iframe pointing at
7198
- * the SparkVault-hosted widget page and bridges the result back over
7199
- * postMessage. Running the flow on the SparkVault origin lets passkey login
7200
- * complete in a single tap on every platform — the WebAuthn ceremony is
7201
- * same-origin with the RP id and the user's tap lives in the iframe document —
7202
- * without a popup.
7222
+ * Host-side half of the popup login flow. Dialog (modal) verification renders a
7223
+ * thin email/phone launcher in the SDK's own ModalContainer, then — inside the
7224
+ * user's submit gesture — opens a TOP-LEVEL popup on the Identity origin that
7225
+ * runs the full login flow. Because the popup is top-level on api.sparkvault.com,
7226
+ * login completion's first-party `__Host-authsv_sso` cookie persists.
7203
7227
  *
7204
- * The widget renders the SDK's own modal (overlay, backdrop, chrome) inside the
7205
- * iframe, so the page sees only a transparent full-viewport frame: no border,
7206
- * no seam, visually identical to the in-page modal.
7228
+ * The launcher only collects an identifier and bridges the popup result back;
7229
+ * the flow UI itself lives in the popup (the renderMode:'local' renderer).
7207
7230
  */
7208
- /** Result envelope posted by the widget page. */
7209
- const RESULT_TYPE = 'sparkvault-identity-result';
7210
- /** Top-window navigation request posted by the widget (OIDC / generic). */
7211
- const REDIRECT_TYPE = 'sparkvault-identity-redirect';
7212
- /** Social-login start request posted by the widget. */
7213
- const SOCIAL_TYPE = 'sparkvault-identity-social';
7214
- /** Sent by the widget once its modal has mounted — proof the frame is alive. */
7215
- const READY_TYPE = 'sparkvault-identity-ready';
7231
+ /** `data.type` the login popup posts back to the opener. */
7232
+ const LOGIN_RESULT_TYPE = 'sparkvault-login-result';
7216
7233
  /**
7217
- * How long to wait for the widget frame to signal it has mounted before giving
7218
- * up and recovering in-page. The frame paints its own backdrop + spinner the
7219
- * instant it loads and posts `ready` the moment its modal mounts; a frame that
7220
- * is blocked from framing, 404s, or whose SDK never loads will never post — so
7221
- * this bounds the "scroll locked, nothing on screen" failure to a few seconds
7222
- * instead of leaving the host stuck until a manual refresh.
7234
+ * Renders the email/phone launcher modal and opens the login popup on submit.
7223
7235
  */
7224
- const FRAME_READY_TIMEOUT_MS = 8000;
7225
- class WidgetEmbedder {
7226
- constructor(config, options, callbacks) {
7236
+ class DialogLauncher {
7237
+ constructor(config, api, options, callbacks) {
7227
7238
  this.config = config;
7239
+ this.api = api;
7228
7240
  this.options = options;
7229
7241
  this.callbacks = callbacks;
7230
- this.iframe = null;
7242
+ this.modal = new ModalContainer();
7243
+ this.popupLauncher = new PopupLauncher();
7244
+ this.currentView = null;
7231
7245
  this.settled = false;
7232
- this.ready = false;
7233
- this.failed = false;
7234
- this.readyTimer = null;
7235
- this.previousBodyOverflow = '';
7236
- // Only ever trust messages from the Identity origin the SDK is configured
7237
- // against — never the broader sparkvault.com family.
7246
+ this.allowedTypes = ['email'];
7238
7247
  this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
7239
- this.boundHandleMessage = (event) => this.handleMessage(event);
7240
- this.boundHandleCspViolation = (event) => this.handleCspViolation(event);
7241
7248
  }
7249
+ /**
7250
+ * Mount the modal, then load config to render the identifier input (or a
7251
+ * terminal error view when config fails).
7252
+ */
7242
7253
  start() {
7243
- const iframe = document.createElement('iframe');
7244
- iframe.src = this.buildUrl();
7245
- iframe.title = 'Sign in';
7246
- // Delegate WebAuthn into the cross-origin widget document so the ceremony
7247
- // runs there. The widget response also opts in via Permissions-Policy.
7248
- iframe.setAttribute('allow', 'publickey-credentials-get; publickey-credentials-create');
7249
- iframe.style.cssText = [
7250
- 'position:fixed',
7251
- 'inset:0',
7252
- 'width:100%',
7253
- 'height:100%',
7254
- 'border:0',
7255
- 'margin:0',
7256
- 'padding:0',
7257
- 'background:transparent',
7258
- 'z-index:2147483647',
7259
- ].join(';');
7260
- // Promote to its own compositing layer up front. iOS Safari can otherwise
7261
- // leave a freshly-inserted fixed, full-viewport iframe loaded but UNPAINTED
7262
- // until the next composite (a scroll, resize, or app foreground) — the
7263
- // frame even runs, but the dialog only appears after an app switch.
7264
- iframe.style.transform = 'translateZ(0)';
7265
- iframe.style.willChange = 'transform';
7266
- // A network-level load failure (DNS, connection reset) fires onerror; an
7267
- // HTTP error body or a frame blocked from framing does not, which is what
7268
- // the readiness timeout below covers.
7269
- iframe.onerror = () => this.handleFrameUnavailable();
7270
- this.iframe = iframe;
7271
- // Lock host scroll while the modal (rendered inside the iframe) is open.
7272
- this.previousBodyOverflow = document.body.style.overflow;
7273
- document.body.style.overflow = 'hidden';
7274
- window.addEventListener('message', this.boundHandleMessage);
7275
- // A host-page CSP whose frame-src/child-src omits the Identity origin blocks
7276
- // the iframe before it can load and fires no `onerror`. Catch the violation
7277
- // so we fail over to the in-page flow at once instead of after the timeout.
7278
- document.addEventListener('securitypolicyviolation', this.boundHandleCspViolation);
7279
- document.body.appendChild(iframe);
7280
- // Force the composite the iframe insertion may not have triggered on iOS,
7281
- // so the dialog paints on the click rather than only after an app switch.
7282
- this.forceComposite(iframe);
7283
- this.readyTimer = setTimeout(() => this.handleFrameUnavailable(), FRAME_READY_TIMEOUT_MS);
7284
- }
7285
- /**
7286
- * Nudge the browser to paint the just-inserted iframe on the next frame.
7287
- * Reading layout forces a reflow; toggling a transform forces the compositor
7288
- * to flush the new layer — the workaround for iOS Safari leaving a fixed
7289
- * full-viewport iframe invisible until an unrelated repaint.
7290
- */
7291
- forceComposite(iframe) {
7292
- const paint = () => {
7293
- if (!this.iframe)
7294
- return;
7295
- void iframe.offsetHeight;
7296
- iframe.style.transform = 'translateZ(0) scale(1)';
7297
- };
7298
- if (typeof requestAnimationFrame === 'function') {
7299
- requestAnimationFrame(paint);
7300
- }
7301
- else {
7302
- setTimeout(paint, 16);
7303
- }
7304
- }
7305
- close() {
7306
- this.clearReadyTimer();
7307
- if (this.iframe?.parentNode) {
7308
- this.iframe.parentNode.removeChild(this.iframe);
7309
- }
7310
- this.iframe = null;
7311
- window.removeEventListener('message', this.boundHandleMessage);
7312
- document.removeEventListener('securitypolicyviolation', this.boundHandleCspViolation);
7313
- document.body.style.overflow = this.previousBodyOverflow;
7254
+ this.modal.createLoading({ backdropBlur: this.options.backdropBlur }, () => this.handleClose());
7255
+ this.api
7256
+ .getConfig()
7257
+ .then((config) => this.renderInput(config))
7258
+ .catch((error) => this.renderConfigError(error));
7314
7259
  }
7315
7260
  /**
7316
- * Host CSP blocked the widget iframe (frame-src/child-src). The frame can
7317
- * never load, so fail over to the in-page flow immediately.
7261
+ * Close the launcher and tear everything down. Cancels in-flight config
7262
+ * requests so a late resolution can't render into a destroyed modal.
7318
7263
  */
7319
- handleCspViolation(event) {
7320
- const directive = event.effectiveDirective || event.violatedDirective;
7321
- if (directive !== 'frame-src' && directive !== 'child-src')
7322
- return;
7323
- // blockedURI is the framed URL (sometimes just its origin); match either.
7324
- if (typeof event.blockedURI === 'string' && event.blockedURI.startsWith(this.trustedOrigin)) {
7325
- this.handleFrameUnavailable();
7326
- }
7264
+ close() {
7265
+ this.api.abort();
7266
+ this.currentView?.destroy?.();
7267
+ this.currentView = null;
7268
+ this.modal.destroy();
7327
7269
  }
7328
- clearReadyTimer() {
7329
- if (this.readyTimer !== null) {
7330
- clearTimeout(this.readyTimer);
7331
- this.readyTimer = null;
7270
+ handleClose() {
7271
+ this.close();
7272
+ if (!this.settled) {
7273
+ this.settled = true;
7274
+ this.callbacks.onCancel();
7332
7275
  }
7333
7276
  }
7334
- /**
7335
- * The widget frame never became interactive. Tear down, release the host
7336
- * scroll lock, and hand control back so the flow can run in-page. Guarded so
7337
- * a late onerror or timeout firing after a real result (or after the frame
7338
- * has proven itself with `ready`) is a no-op.
7339
- */
7340
- handleFrameUnavailable() {
7341
- if (this.settled || this.failed || this.ready)
7342
- return;
7343
- this.failed = true;
7344
- this.close();
7345
- this.callbacks.onFrameUnavailable();
7277
+ renderInput(config) {
7278
+ if (config.branding) {
7279
+ this.modal.updateBranding(config.branding);
7280
+ }
7281
+ const resolvedBackdropBlur = this.options.backdropBlur !== undefined
7282
+ ? this.options.backdropBlur
7283
+ : config.branding?.backdrop_blur ?? true;
7284
+ this.modal.updateBackdropBlur(resolvedBackdropBlur);
7285
+ this.allowedTypes = (config.allowedIdentityTypes ?? ['email']);
7286
+ this.mountInput(undefined);
7346
7287
  }
7347
7288
  /**
7348
- * Begin a social-login redirect from the host. State and redirect_uri are
7349
- * the customer's top origin so `consumeRedirectResult` validates them on
7350
- * return. Mirrors the SDK's getSocialAuthUrl.
7289
+ * Render the identifier input. The submit handler runs synchronously inside
7290
+ * the user gesture, so the popup open is never treated as programmatic (and
7291
+ * never blocked).
7351
7292
  */
7352
- startSocial(provider) {
7353
- // Provider comes from the trusted widget origin, but never build a URL from
7354
- // an unexpected value.
7355
- if (!/^[a-z0-9_]+$/i.test(provider))
7356
- return;
7357
- const state = generateState();
7358
- try {
7359
- sessionStorage.setItem('sv_oauth_state', state);
7360
- }
7361
- catch {
7362
- // Storage disabled (private mode): proceed; the backend still binds state.
7363
- }
7364
- const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/social/${provider}`);
7365
- url.searchParams.set('redirect_uri', window.location.origin + window.location.pathname);
7366
- url.searchParams.set('state', state);
7367
- const authContext = this.options.authContext;
7368
- if (authContext?.authRequestId) {
7369
- url.searchParams.set('auth_request_id', authContext.authRequestId);
7370
- }
7371
- if (authContext?.simpleMode) {
7372
- const simpleMode = authContext.simpleMode.sessionId
7373
- ? { session_id: authContext.simpleMode.sessionId }
7374
- : {
7375
- success_url: authContext.simpleMode.successUrl,
7376
- failure_url: authContext.simpleMode.failureUrl,
7377
- state: authContext.simpleMode.state,
7378
- };
7379
- url.searchParams.set('simple_mode', JSON.stringify(simpleMode));
7380
- }
7381
- this.close();
7382
- window.location.href = url.toString();
7293
+ mountInput(error) {
7294
+ this.mountView(new IdentityInputView({
7295
+ allowedTypes: this.allowedTypes,
7296
+ initialValue: this.options.email ?? this.options.phone,
7297
+ error,
7298
+ onSubmit: (result) => this.handleIdentitySubmit(result),
7299
+ }));
7383
7300
  }
7384
7301
  /**
7385
- * Navigate the host top window to a widget-supplied URL — only when it
7386
- * resolves to http(s). The sender is already constrained to the trusted
7387
- * widget origin, but defense-in-depth across the SparkVault->customer
7388
- * boundary: compromised widget-origin code must never escalate into script
7389
- * execution on the embedding page via a javascript:/data: navigation.
7302
+ * Open the login popup for the submitted identifier. SYNCHRONOUS: no await
7303
+ * precedes window.open, so the browser keeps the user-gesture grant.
7390
7304
  */
7391
- safeNavigate(url) {
7392
- let resolved;
7393
- try {
7394
- resolved = new URL(url, window.location.href);
7395
- }
7396
- catch {
7397
- return;
7398
- }
7399
- if (resolved.protocol !== 'http:' && resolved.protocol !== 'https:') {
7400
- return;
7401
- }
7402
- window.location.href = resolved.href;
7403
- }
7404
- buildUrl() {
7405
- const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
7406
- url.searchParams.set('origin', window.location.origin);
7407
- if (this.options.email)
7408
- url.searchParams.set('email', this.options.email);
7409
- if (this.options.phone)
7410
- url.searchParams.set('phone', this.options.phone);
7411
- if (this.options.backdropBlur === false)
7412
- url.searchParams.set('backdrop_blur', 'false');
7305
+ handleIdentitySubmit(result) {
7306
+ this.popupLauncher
7307
+ .openPopup({
7308
+ url: this.buildPopupUrl(result),
7309
+ windowName: 'sparkvault-login',
7310
+ resultType: LOGIN_RESULT_TYPE,
7311
+ trustedOrigin: this.trustedOrigin,
7312
+ })
7313
+ .then((message) => this.handlePopupResult(message))
7314
+ .catch((error) => this.handlePopupError(error));
7315
+ }
7316
+ buildPopupUrl(result) {
7317
+ const params = new URLSearchParams({ origin: window.location.origin });
7318
+ params.set(result.type, result.value);
7413
7319
  const authContext = this.options.authContext;
7414
7320
  if (authContext?.authRequestId) {
7415
- url.searchParams.set('auth_request_id', authContext.authRequestId);
7321
+ params.set('auth_request_id', authContext.authRequestId);
7416
7322
  }
7417
7323
  if (authContext?.simpleMode) {
7418
- url.searchParams.set('simple_mode', JSON.stringify({
7324
+ params.set('simple_mode', JSON.stringify({
7419
7325
  success_url: authContext.simpleMode.successUrl,
7420
7326
  failure_url: authContext.simpleMode.failureUrl,
7421
7327
  state: authContext.simpleMode.state,
7422
7328
  session_id: authContext.simpleMode.sessionId,
7423
7329
  }));
7424
7330
  }
7425
- return url.toString();
7331
+ return `${this.config.identityBaseUrl}/${this.config.accountId}/popup?${params}`;
7426
7332
  }
7427
- handleMessage(event) {
7428
- if (event.origin !== this.trustedOrigin)
7429
- return;
7430
- if (this.iframe && event.source !== this.iframe.contentWindow)
7333
+ handlePopupResult(message) {
7334
+ if (message.success && message.data) {
7335
+ const result = {
7336
+ token: message.data.token || '',
7337
+ identity: message.data.identity || '',
7338
+ identityType: message.data.identity_type || 'email',
7339
+ svid: message.data.svid,
7340
+ sessionId: message.data.session_id,
7341
+ refreshToken: message.data.refresh_token,
7342
+ redirect: message.data.redirect,
7343
+ };
7344
+ this.finish();
7345
+ this.callbacks.onSuccess(result);
7431
7346
  return;
7432
- const data = event.data;
7433
- if (!data || typeof data.type !== 'string')
7347
+ }
7348
+ if (message.error === 'cancelled') {
7349
+ // User backed out inside the popup — re-render the input so they can
7350
+ // retry from the still-open launcher.
7351
+ this.reEnableInput(undefined);
7434
7352
  return;
7435
- // The frame mounted its modal — it is alive and owns the interaction now.
7436
- // Cancel the readiness timeout so a slow-but-working frame is never torn
7437
- // down and recovered in-page.
7438
- if (data.type === READY_TYPE) {
7439
- this.ready = true;
7440
- this.clearReadyTimer();
7353
+ }
7354
+ this.finish();
7355
+ this.callbacks.onError(new SparkVaultError(message.message || message.error || 'Verification failed', message.errorCode || message.error || 'verification_failed'));
7356
+ }
7357
+ handlePopupError(error) {
7358
+ if (error instanceof UserCancelledError) {
7359
+ // Manual popup close — let the user retry from the still-open launcher.
7360
+ this.reEnableInput(undefined);
7441
7361
  return;
7442
7362
  }
7443
- // Social login: start it from the host so the OAuth state and redirect_uri
7444
- // live on the customer's top origin (where the return is consumed).
7445
- if (data.type === SOCIAL_TYPE && typeof data.provider === 'string') {
7446
- this.startSocial(data.provider);
7363
+ if (error instanceof PopupBlockedError) {
7364
+ // Same inline "allow popups" surface the passkey path shows.
7365
+ this.reEnableInput(error.message);
7447
7366
  return;
7448
7367
  }
7449
- // OIDC / generic redirect: the widget cannot navigate the top window from a
7450
- // cross-origin frame, so it asks us to. Navigating away tears down the
7451
- // iframe; on return the host SDK consumes the redirect token.
7452
- if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
7453
- this.clearReadyTimer();
7454
- this.safeNavigate(data.url);
7368
+ this.finish();
7369
+ this.callbacks.onError(error instanceof Error ? error : new Error(String(error)));
7370
+ }
7371
+ /**
7372
+ * Re-render the input (its Continue button is disabled to "Please wait…" on
7373
+ * submit) so it is interactive again after a cancelled or blocked popup.
7374
+ */
7375
+ reEnableInput(error) {
7376
+ if (this.settled || !this.modal.isOpen())
7455
7377
  return;
7378
+ this.mountInput(error);
7379
+ }
7380
+ renderConfigError(error) {
7381
+ this.mountView(this.viewForConfigError(error));
7382
+ }
7383
+ viewForConfigError(error) {
7384
+ if (error instanceof IdentityApiError) {
7385
+ if (error.code === 'product_not_configured') {
7386
+ return new ProductNotConfiguredView({ onClose: () => this.handleClose() });
7387
+ }
7388
+ if (error.code === 'ORIGIN_NOT_ALLOWED') {
7389
+ const origin = typeof error.details?.origin === 'string' ? error.details.origin : undefined;
7390
+ return new OriginNotAllowedView({ origin, onClose: () => this.handleClose() });
7391
+ }
7456
7392
  }
7457
- if (data.type !== RESULT_TYPE || this.settled)
7393
+ return new ServiceUnavailableView({
7394
+ onRetry: () => this.retryConfig(),
7395
+ onClose: () => this.handleClose(),
7396
+ });
7397
+ }
7398
+ retryConfig() {
7399
+ this.mountView(new LoadingView({ message: 'Loading...' }));
7400
+ this.api
7401
+ .getConfig()
7402
+ .then((config) => this.renderInput(config))
7403
+ .catch((err) => this.renderConfigError(err));
7404
+ }
7405
+ mountView(view) {
7406
+ const body = this.modal.getBody();
7407
+ if (!body)
7458
7408
  return;
7409
+ this.currentView?.destroy?.();
7410
+ clearChildren(body);
7411
+ this.currentView = view;
7412
+ body.appendChild(view.render());
7413
+ }
7414
+ finish() {
7459
7415
  this.settled = true;
7460
7416
  this.close();
7461
- if (data.success && data.result) {
7462
- const result = data.result;
7463
- this.callbacks.onSuccess(result);
7464
- // Mirror the renderer's belt-and-suspenders: complete a server-issued
7465
- // redirect from the host's own top window if the customer didn't.
7466
- if (typeof result.redirect === 'string' && result.redirect) {
7467
- this.safeNavigate(result.redirect);
7468
- }
7469
- }
7470
- else if (data.cancelled) {
7471
- this.callbacks.onCancel();
7472
- }
7473
- else {
7474
- this.callbacks.onError(new Error(data.error || 'Verification failed'));
7475
- }
7476
7417
  }
7477
7418
  }
7478
7419
 
@@ -7776,7 +7717,7 @@ function attachClickHandler(selector, onClick) {
7776
7717
  * Identity Module
7777
7718
  *
7778
7719
  * Provides identity verification through dialog or inline UI.
7779
- * Supports passkey, TOTP, SparkLink, and social authentication.
7720
+ * Supports passkey, OTP, SparkLink, and social authentication.
7780
7721
  *
7781
7722
  * @example Dialog mode (immediate)
7782
7723
  * const result = await sv.products.identity.verify();
@@ -7806,7 +7747,7 @@ function isTokenClaims(payload) {
7806
7747
  class IdentityModule {
7807
7748
  constructor(config) {
7808
7749
  this.renderer = null;
7809
- this.embedder = null;
7750
+ this.launcher = null;
7810
7751
  this.config = config;
7811
7752
  this.api = new IdentityApi(config);
7812
7753
  // Preload config in background for instant dialog opening
@@ -7940,9 +7881,9 @@ class IdentityModule {
7940
7881
  options.onSuccess?.(redirectResult);
7941
7882
  return redirectResult;
7942
7883
  }
7943
- if (this.embedder) {
7944
- this.embedder.close();
7945
- this.embedder = null;
7884
+ if (this.launcher) {
7885
+ this.launcher.close();
7886
+ this.launcher = null;
7946
7887
  }
7947
7888
  if (this.renderer) {
7948
7889
  this.renderer.close();
@@ -7958,9 +7899,9 @@ class IdentityModule {
7958
7899
  backdropBlur: options.backdropBlur ?? this.config.backdropBlur,
7959
7900
  };
7960
7901
  // Inline rendering (target) and explicit local mode run the flow in this
7961
- // document. Dialog mode embeds the SparkVault-hosted widget in an iframe so
7962
- // passkey login completes in one tap with no popup. `renderMode: 'local'`
7963
- // is how the hosted widget itself runs the flow (and avoids re-embedding).
7902
+ // document. Dialog mode renders a thin launcher and opens a top-level popup
7903
+ // on the Identity origin for the flow (so login's first-party SSO cookie
7904
+ // persists). `renderMode: 'local'` is how the popup itself runs the flow.
7964
7905
  const isInline = !!options.target;
7965
7906
  const useLocal = options.renderMode === 'local' || isInline;
7966
7907
  let resolveRef;
@@ -7988,38 +7929,23 @@ class IdentityModule {
7988
7929
  this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
7989
7930
  this.renderer.start().catch((error) => {
7990
7931
  // A startup failure must surface inside the SparkVault dialog, never
7991
- // close it silently. Rejecting here would, in the default embedded
7992
- // mode, run the host's onError and let the embedding page remove the
7993
- // iframe — leaving the user with a vanished dialog and no error. Render
7994
- // the error in-dialog instead (consistent with every in-flow error);
7995
- // the promise settles later via the user's retry/close.
7932
+ // close it silently. Render the error in-dialog instead (consistent with
7933
+ // every in-flow error); the promise settles later via retry/close.
7996
7934
  this.renderer?.showStartupError(error);
7997
7935
  });
7998
7936
  };
7999
7937
  if (!useLocal) {
8000
7938
  // When the preloaded config has already failed *permanently* — this origin
8001
7939
  // is not a verified domain, or the account hasn't configured Identity —
8002
- // the hosted widget cannot help: it never frames an unverified origin, so
8003
- // embedding it would only hang until the readiness timeout. Render the
8004
- // error dialog in-page right away instead. Transient failures fall through
8005
- // to the iframe so one-tap passkey login is preserved.
7940
+ // the popup cannot help: the IdP will reject the unverified origin. Render
7941
+ // the error dialog in-page right away instead. Transient failures fall
7942
+ // through to the launcher, which surfaces them in its own dialog.
8006
7943
  if (await this.preloadedConfigPermanentlyFailed()) {
8007
7944
  startLocalRender(new ModalContainer());
8008
7945
  return settledPromise;
8009
7946
  }
8010
- this.embedder = new WidgetEmbedder(this.config, mergedOptions, {
8011
- ...hostCallbacks,
8012
- onFrameUnavailable: () => {
8013
- // The hosted widget iframe could not load or mount (blocked from
8014
- // framing, network failure, blank render, or its in-frame SDK never
8015
- // loaded). Recover by running the verification flow in this document
8016
- // — the same local path inline rendering uses — so login still works
8017
- // and the host scroll lock the embedder set has already been released.
8018
- this.embedder = null;
8019
- startLocalRender(new ModalContainer());
8020
- },
8021
- });
8022
- this.embedder.start();
7947
+ this.launcher = new DialogLauncher(this.config, this.api, mergedOptions, hostCallbacks);
7948
+ this.launcher.start();
8023
7949
  return settledPromise;
8024
7950
  }
8025
7951
  startLocalRender(isInline ? this.createInlineContainer(options.target) : new ModalContainer());
@@ -8184,14 +8110,13 @@ class IdentityModule {
8184
8110
  /**
8185
8111
  * Close the identity dialog/inline UI if open.
8186
8112
  *
8187
- * Tears down whichever surface is active: the hosted-widget iframe
8188
- * (default dialog mode — also releases the embedder's host scroll lock)
8189
- * or the local renderer (inline / local mode).
8113
+ * Tears down whichever surface is active: the dialog launcher (default dialog
8114
+ * mode) or the local renderer (inline / local mode).
8190
8115
  */
8191
8116
  close() {
8192
- if (this.embedder) {
8193
- this.embedder.close();
8194
- this.embedder = null;
8117
+ if (this.launcher) {
8118
+ this.launcher.close();
8119
+ this.launcher = null;
8195
8120
  }
8196
8121
  if (this.renderer) {
8197
8122
  this.renderer.close();
@@ -8200,12 +8125,12 @@ class IdentityModule {
8200
8125
  }
8201
8126
  /**
8202
8127
  * Whether the preloaded config has already settled as a *permanent* failure
8203
- * the hosted widget can't surface (origin not allowed, or product not
8204
- * configured). Used to skip the iframe and show the error dialog in-page
8205
- * immediately. Returns false — proceed to embed — when config is not
8206
- * preloaded, still in flight (raced against a short timeout so the common
8207
- * path is never delayed), resolved, or failed only transiently (so one-tap
8208
- * passkey login via the frame is preserved).
8128
+ * the popup can't surface (origin not allowed, or product not configured).
8129
+ * Used to skip the launcher and show the error dialog in-page immediately.
8130
+ * Returns false — proceed to the launcher — when config is not preloaded,
8131
+ * still in flight (raced against a short timeout so the common path is never
8132
+ * delayed), resolved, or failed only transiently (the launcher surfaces a
8133
+ * transient failure in its own dialog).
8209
8134
  */
8210
8135
  async preloadedConfigPermanentlyFailed() {
8211
8136
  if (!this.api.isConfigPreloaded())