@sparkvault/sdk-js 2.1.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -832,6 +832,35 @@ function base64urlEncode(data) {
832
832
  function arrayBufferToBase64url(buffer) {
833
833
  return base64urlEncode(new Uint8Array(buffer));
834
834
  }
835
+ /**
836
+ * Decode base64url string to Uint8Array
837
+ *
838
+ * @param base64url - Base64url encoded string
839
+ * @returns Decoded bytes as Uint8Array
840
+ */
841
+ function base64urlDecode(base64url) {
842
+ const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/');
843
+ const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
844
+ const binary = atob(padded);
845
+ const bytes = new Uint8Array(binary.length);
846
+ for (let i = 0; i < binary.length; i++) {
847
+ bytes[i] = binary.charCodeAt(i);
848
+ }
849
+ return bytes;
850
+ }
851
+ /**
852
+ * Decode base64url string to ArrayBuffer
853
+ *
854
+ * @param base64url - Base64url encoded string
855
+ * @returns Decoded ArrayBuffer
856
+ */
857
+ function base64urlToArrayBuffer(base64url) {
858
+ const bytes = base64urlDecode(base64url);
859
+ // Create a new ArrayBuffer with exact copy (avoids TypeScript ArrayBufferLike issue)
860
+ const buffer = new ArrayBuffer(bytes.length);
861
+ new Uint8Array(buffer).set(bytes);
862
+ return buffer;
863
+ }
835
864
  /**
836
865
  * Decode base64url string to UTF-8 string
837
866
  *
@@ -1568,11 +1597,115 @@ class PasskeyHandler {
1568
1597
  return result;
1569
1598
  }
1570
1599
  /**
1571
- * Verify user with existing passkey via popup
1600
+ * Verify user with an existing passkey.
1601
+ *
1602
+ * On the Identity origin (the hosted widget / hosted login) the ceremony runs
1603
+ * inline — same-origin with the RP id, one tap, no popup. On a third-party
1604
+ * origin the rpId would not match the document, so it falls back to the popup
1605
+ * served from the Identity origin. (Verification, unlike registration, is
1606
+ * supported in cross-origin iframes, so the embedded widget uses the inline
1607
+ * path.)
1572
1608
  */
1573
1609
  async verify() {
1610
+ if (this.canRunCeremonyInline()) {
1611
+ return this.verifyInline();
1612
+ }
1574
1613
  return this.openPasskeyPopup('verify');
1575
1614
  }
1615
+ /**
1616
+ * True when the SDK is running ON the Identity origin and the browser exposes
1617
+ * WebAuthn — the only place an inline ceremony's rpId matches the document.
1618
+ */
1619
+ canRunCeremonyInline() {
1620
+ return typeof window !== 'undefined'
1621
+ && typeof navigator !== 'undefined'
1622
+ && !!navigator.credentials
1623
+ && window.location.origin === this.trustedOrigin;
1624
+ }
1625
+ /**
1626
+ * Run the discoverable verification ceremony directly in this document and
1627
+ * map the outcome onto the same PasskeyResult shape the popup produces.
1628
+ */
1629
+ async verifyInline() {
1630
+ try {
1631
+ const challenge = await this.api.startPasskeyVerify(undefined, 'email', this.state.authContext);
1632
+ const credential = await navigator.credentials.get({
1633
+ publicKey: {
1634
+ challenge: base64urlToArrayBuffer(challenge.challenge),
1635
+ rpId: challenge.rpId,
1636
+ timeout: challenge.timeout,
1637
+ userVerification: 'required',
1638
+ },
1639
+ });
1640
+ if (!credential) {
1641
+ return { success: false, error: 'Failed to get passkey', errorType: 'unknown' };
1642
+ }
1643
+ const response = await this.api.completePasskeyVerify({
1644
+ session: challenge.session,
1645
+ credential,
1646
+ authContext: this.state.authContext,
1647
+ });
1648
+ return {
1649
+ success: true,
1650
+ result: {
1651
+ token: response.token,
1652
+ identity: response.identity || this.state.recipient,
1653
+ identityType: response.identity_type || 'email',
1654
+ svid: response.svid,
1655
+ sessionId: response.session_id,
1656
+ refreshToken: response.refresh_token,
1657
+ redirect: response.redirect,
1658
+ },
1659
+ };
1660
+ }
1661
+ catch (error) {
1662
+ return this.mapInlineCeremonyError(error);
1663
+ }
1664
+ }
1665
+ /**
1666
+ * Map a thrown inline-ceremony error onto PasskeyResult, mirroring the
1667
+ * popup's error codes so the widget renders the same dedicated states
1668
+ * (cancelled, identity locked, no passkey → registration).
1669
+ */
1670
+ mapInlineCeremonyError(error) {
1671
+ // User dismissed the system sheet, or no credential was available.
1672
+ if (error instanceof Error && error.name === 'NotAllowedError') {
1673
+ return {
1674
+ success: false,
1675
+ error: 'Authentication was cancelled. Please try again.',
1676
+ errorType: 'cancelled',
1677
+ };
1678
+ }
1679
+ if (error instanceof IdentityApiError) {
1680
+ if (error.code === 'identity_locked') {
1681
+ return {
1682
+ success: false,
1683
+ error: 'This SparkVault Identity is locked. Visit auth.sv to manage it.',
1684
+ errorType: 'unknown',
1685
+ errorCode: 'identity_locked',
1686
+ };
1687
+ }
1688
+ if (error.code === 'passkey_not_registered') {
1689
+ return {
1690
+ success: false,
1691
+ error: 'No passkey found. Create one to continue.',
1692
+ errorType: 'not_found',
1693
+ errorCode: 'passkey_not_registered',
1694
+ };
1695
+ }
1696
+ return {
1697
+ success: false,
1698
+ error: error.message || 'Passkey authentication failed',
1699
+ errorType: 'unknown',
1700
+ errorCode: error.code,
1701
+ };
1702
+ }
1703
+ return {
1704
+ success: false,
1705
+ error: error instanceof Error ? error.message : 'Passkey authentication failed',
1706
+ errorType: 'unknown',
1707
+ };
1708
+ }
1576
1709
  /**
1577
1710
  * Open passkey popup and wait for result
1578
1711
  */
@@ -5609,6 +5742,19 @@ const SPARKLINK_CSP_BLOCKED_ERROR = {
5609
5742
  ].join(' '),
5610
5743
  code: 'sparklink_csp_blocked',
5611
5744
  };
5745
+ /**
5746
+ * Navigate the browser. When the flow runs inside the embed iframe, the host
5747
+ * injects `onNavigate` (via VerifyOptions) so redirects move the customer's
5748
+ * top window rather than the iframe — providers refuse to be framed anyway.
5749
+ * Outside the iframe this falls back to a normal same-window navigation.
5750
+ */
5751
+ function navigateWith(options, url) {
5752
+ if (options.onNavigate) {
5753
+ options.onNavigate(url);
5754
+ return;
5755
+ }
5756
+ window.location.href = url;
5757
+ }
5612
5758
  class IdentityRenderer {
5613
5759
  constructor(container, api, options, callbacks) {
5614
5760
  // View management
@@ -6185,7 +6331,7 @@ class IdentityRenderer {
6185
6331
  // page-level handler can act before we navigate away.
6186
6332
  this.safeOnSuccess(result.result);
6187
6333
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6188
- window.location.href = result.result.redirect;
6334
+ navigateWith(this.options, result.result.redirect);
6189
6335
  }
6190
6336
  }
6191
6337
  else if (result.errorCode === 'identity_locked') {
@@ -6252,7 +6398,7 @@ class IdentityRenderer {
6252
6398
  this.close();
6253
6399
  this.safeOnSuccess(result);
6254
6400
  if (typeof result.redirect === 'string' && result.redirect) {
6255
- window.location.href = result.redirect;
6401
+ navigateWith(this.options, result.redirect);
6256
6402
  }
6257
6403
  }
6258
6404
  catch (error) {
@@ -6307,7 +6453,7 @@ class IdentityRenderer {
6307
6453
  this.close();
6308
6454
  this.safeOnSuccess(result.result);
6309
6455
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6310
- window.location.href = result.result.redirect;
6456
+ navigateWith(this.options, result.result.redirect);
6311
6457
  }
6312
6458
  }
6313
6459
  else if (result.errorCode === 'identity_locked') {
@@ -6370,7 +6516,7 @@ class IdentityRenderer {
6370
6516
  this.close();
6371
6517
  this.safeOnSuccess(pendingResult);
6372
6518
  if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6373
- window.location.href = pendingResult.redirect;
6519
+ navigateWith(this.options, pendingResult.redirect);
6374
6520
  }
6375
6521
  }
6376
6522
  }
@@ -6381,7 +6527,7 @@ class IdentityRenderer {
6381
6527
  sessionStorage.setItem('sv_oauth_state', state);
6382
6528
  sessionStorage.setItem('sv_oauth_email', this.recipient);
6383
6529
  const authUrl = this.api.getSocialAuthUrl(provider, redirectUri, state, this.verificationState.authContext);
6384
- window.location.href = authUrl;
6530
+ navigateWith(this.options, authUrl);
6385
6531
  }
6386
6532
  normalizeError(error) {
6387
6533
  if (error instanceof IdentityApiError) {
@@ -6457,7 +6603,7 @@ class IdentityRenderer {
6457
6603
  this.close();
6458
6604
  this.safeOnSuccess(result.result);
6459
6605
  if (typeof result.result.redirect === 'string' && result.result.redirect) {
6460
- window.location.href = result.result.redirect;
6606
+ navigateWith(this.options, result.result.redirect);
6461
6607
  }
6462
6608
  }
6463
6609
  else if (result.errorType === 'cancelled') {
@@ -6489,7 +6635,7 @@ class IdentityRenderer {
6489
6635
  this.close();
6490
6636
  this.safeOnSuccess(pendingResult);
6491
6637
  if (typeof pendingResult.redirect === 'string' && pendingResult.redirect) {
6492
- window.location.href = pendingResult.redirect;
6638
+ navigateWith(this.options, pendingResult.redirect);
6493
6639
  }
6494
6640
  }
6495
6641
  /**
@@ -6661,7 +6807,7 @@ class IdentityRenderer {
6661
6807
  // a no-op (the document is already unloading); if not, this rescues
6662
6808
  // simple-mode flows whose host forgot to act on result.redirect.
6663
6809
  if (typeof result.redirect === 'string' && result.redirect) {
6664
- window.location.href = result.redirect;
6810
+ navigateWith(this.options, result.redirect);
6665
6811
  }
6666
6812
  }
6667
6813
  /**
@@ -6740,6 +6886,132 @@ class IdentityRenderer {
6740
6886
  }
6741
6887
  }
6742
6888
 
6889
+ /* global HTMLIFrameElement */
6890
+ /**
6891
+ * Widget Embedder
6892
+ *
6893
+ * Host-side half of the iframe architecture. For dialog (modal) verification,
6894
+ * the SDK injects a borderless, transparent, full-viewport iframe pointing at
6895
+ * the SparkVault-hosted widget page and bridges the result back over
6896
+ * postMessage. Running the flow on the SparkVault origin lets passkey login
6897
+ * complete in a single tap on every platform — the WebAuthn ceremony is
6898
+ * same-origin with the RP id and the user's tap lives in the iframe document —
6899
+ * without a popup.
6900
+ *
6901
+ * The widget renders the SDK's own modal (overlay, backdrop, chrome) inside the
6902
+ * iframe, so the page sees only a transparent full-viewport frame: no border,
6903
+ * no seam, visually identical to the in-page modal.
6904
+ */
6905
+ /** Result envelope posted by the widget page. */
6906
+ const RESULT_TYPE = 'sparkvault-identity-result';
6907
+ /** Top-window navigation request posted by the widget (social / OIDC). */
6908
+ const REDIRECT_TYPE = 'sparkvault-identity-redirect';
6909
+ class WidgetEmbedder {
6910
+ constructor(config, options, callbacks) {
6911
+ this.config = config;
6912
+ this.options = options;
6913
+ this.callbacks = callbacks;
6914
+ this.iframe = null;
6915
+ this.settled = false;
6916
+ this.previousBodyOverflow = '';
6917
+ // Only ever trust messages from the Identity origin the SDK is configured
6918
+ // against — never the broader sparkvault.com family.
6919
+ this.trustedOrigin = new URL(this.config.identityBaseUrl).origin;
6920
+ this.boundHandleMessage = (event) => this.handleMessage(event);
6921
+ }
6922
+ start() {
6923
+ const iframe = document.createElement('iframe');
6924
+ iframe.src = this.buildUrl();
6925
+ iframe.title = 'Sign in';
6926
+ // Delegate WebAuthn into the cross-origin widget document so the ceremony
6927
+ // runs there. The widget response also opts in via Permissions-Policy.
6928
+ iframe.setAttribute('allow', 'publickey-credentials-get; publickey-credentials-create');
6929
+ iframe.style.cssText = [
6930
+ 'position:fixed',
6931
+ 'inset:0',
6932
+ 'width:100%',
6933
+ 'height:100%',
6934
+ 'border:0',
6935
+ 'margin:0',
6936
+ 'padding:0',
6937
+ 'background:transparent',
6938
+ 'z-index:2147483647',
6939
+ ].join(';');
6940
+ this.iframe = iframe;
6941
+ // Lock host scroll while the modal (rendered inside the iframe) is open.
6942
+ this.previousBodyOverflow = document.body.style.overflow;
6943
+ document.body.style.overflow = 'hidden';
6944
+ window.addEventListener('message', this.boundHandleMessage);
6945
+ document.body.appendChild(iframe);
6946
+ }
6947
+ close() {
6948
+ if (this.iframe?.parentNode) {
6949
+ this.iframe.parentNode.removeChild(this.iframe);
6950
+ }
6951
+ this.iframe = null;
6952
+ window.removeEventListener('message', this.boundHandleMessage);
6953
+ document.body.style.overflow = this.previousBodyOverflow;
6954
+ }
6955
+ buildUrl() {
6956
+ const url = new URL(`${this.config.identityBaseUrl}/${this.config.accountId}/widget`);
6957
+ url.searchParams.set('origin', window.location.origin);
6958
+ if (this.options.email)
6959
+ url.searchParams.set('email', this.options.email);
6960
+ if (this.options.phone)
6961
+ url.searchParams.set('phone', this.options.phone);
6962
+ if (this.options.backdropBlur === false)
6963
+ url.searchParams.set('backdrop_blur', 'false');
6964
+ const authContext = this.options.authContext;
6965
+ if (authContext?.authRequestId) {
6966
+ url.searchParams.set('auth_request_id', authContext.authRequestId);
6967
+ }
6968
+ if (authContext?.simpleMode) {
6969
+ url.searchParams.set('simple_mode', JSON.stringify({
6970
+ success_url: authContext.simpleMode.successUrl,
6971
+ failure_url: authContext.simpleMode.failureUrl,
6972
+ state: authContext.simpleMode.state,
6973
+ session_id: authContext.simpleMode.sessionId,
6974
+ }));
6975
+ }
6976
+ return url.toString();
6977
+ }
6978
+ handleMessage(event) {
6979
+ if (event.origin !== this.trustedOrigin)
6980
+ return;
6981
+ if (this.iframe && event.source !== this.iframe.contentWindow)
6982
+ return;
6983
+ const data = event.data;
6984
+ if (!data || typeof data.type !== 'string')
6985
+ return;
6986
+ // Social / OIDC redirect: the widget cannot navigate the top window from a
6987
+ // cross-origin frame, so it asks us to. Navigating away tears down the
6988
+ // iframe; on return the host SDK consumes the redirect token.
6989
+ if (data.type === REDIRECT_TYPE && typeof data.url === 'string') {
6990
+ window.location.href = data.url;
6991
+ return;
6992
+ }
6993
+ if (data.type !== RESULT_TYPE || this.settled)
6994
+ return;
6995
+ this.settled = true;
6996
+ this.close();
6997
+ if (data.success && data.result) {
6998
+ const result = data.result;
6999
+ this.callbacks.onSuccess(result);
7000
+ // Mirror the renderer's belt-and-suspenders: complete a server-issued
7001
+ // redirect from the host's own top window if the customer didn't.
7002
+ if (typeof result.redirect === 'string' && result.redirect) {
7003
+ window.location.href = result.redirect;
7004
+ }
7005
+ }
7006
+ else if (data.cancelled) {
7007
+ this.callbacks.onCancel();
7008
+ }
7009
+ else {
7010
+ this.callbacks.onError(new Error(data.error || 'Verification failed'));
7011
+ }
7012
+ }
7013
+ }
7014
+
6743
7015
  /**
6744
7016
  * Inline Container
6745
7017
  *
@@ -7014,6 +7286,7 @@ function isTokenClaims(payload) {
7014
7286
  class IdentityModule {
7015
7287
  constructor(config) {
7016
7288
  this.renderer = null;
7289
+ this.embedder = null;
7017
7290
  this.attachedElements = new Map();
7018
7291
  this.config = config;
7019
7292
  this.api = new IdentityApi(config);
@@ -7044,6 +7317,10 @@ class IdentityModule {
7044
7317
  options.onSuccess?.(redirectResult);
7045
7318
  return redirectResult;
7046
7319
  }
7320
+ if (this.embedder) {
7321
+ this.embedder.close();
7322
+ this.embedder = null;
7323
+ }
7047
7324
  if (this.renderer) {
7048
7325
  this.renderer.close();
7049
7326
  }
@@ -7051,37 +7328,53 @@ class IdentityModule {
7051
7328
  // AbortController aborted on close() would short-circuit the next
7052
7329
  // session's first request as "Request cancelled".
7053
7330
  this.api.resetSession();
7054
- const isInline = !!options.target;
7055
- const container = isInline
7056
- ? this.createInlineContainer(options.target)
7057
- : new ModalContainer();
7058
7331
  // Merge global config defaults with per-call options
7059
7332
  const mergedOptions = {
7060
7333
  ...options,
7061
7334
  // Use global backdropBlur unless explicitly overridden per-call
7062
7335
  backdropBlur: options.backdropBlur ?? this.config.backdropBlur,
7063
7336
  };
7064
- return new Promise((resolve, reject) => {
7065
- this.renderer = new IdentityRenderer(container, this.api, mergedOptions, {
7066
- onSuccess: (result) => {
7067
- options.onSuccess?.(result);
7068
- resolve(result);
7069
- },
7070
- onError: (error) => {
7071
- options.onError?.(error);
7072
- reject(error);
7073
- },
7074
- onCancel: () => {
7075
- const error = new UserCancelledError();
7076
- options.onCancel?.();
7077
- reject(error);
7078
- },
7079
- });
7080
- this.renderer.start().catch((error) => {
7337
+ // Inline rendering (target) and explicit local mode run the flow in this
7338
+ // document. Dialog mode embeds the SparkVault-hosted widget in an iframe so
7339
+ // passkey login completes in one tap with no popup. `renderMode: 'local'`
7340
+ // is how the hosted widget itself runs the flow (and avoids re-embedding).
7341
+ const isInline = !!options.target;
7342
+ const useLocal = options.renderMode === 'local' || isInline;
7343
+ let resolveRef;
7344
+ let rejectRef;
7345
+ const settledPromise = new Promise((resolve, reject) => {
7346
+ resolveRef = resolve;
7347
+ rejectRef = reject;
7348
+ });
7349
+ const hostCallbacks = {
7350
+ onSuccess: (result) => {
7351
+ options.onSuccess?.(result);
7352
+ resolveRef(result);
7353
+ },
7354
+ onError: (error) => {
7081
7355
  options.onError?.(error);
7082
- reject(error);
7083
- });
7356
+ rejectRef(error);
7357
+ },
7358
+ onCancel: () => {
7359
+ const error = new UserCancelledError();
7360
+ options.onCancel?.();
7361
+ rejectRef(error);
7362
+ },
7363
+ };
7364
+ if (!useLocal) {
7365
+ this.embedder = new WidgetEmbedder(this.config, mergedOptions, hostCallbacks);
7366
+ this.embedder.start();
7367
+ return settledPromise;
7368
+ }
7369
+ const container = isInline
7370
+ ? this.createInlineContainer(options.target)
7371
+ : new ModalContainer();
7372
+ this.renderer = new IdentityRenderer(container, this.api, mergedOptions, hostCallbacks);
7373
+ this.renderer.start().catch((error) => {
7374
+ options.onError?.(error);
7375
+ rejectRef(error);
7084
7376
  });
7377
+ return settledPromise;
7085
7378
  }
7086
7379
  /**
7087
7380
  * Attach identity verification to element clicks.