@fourt/sdk 1.1.7 → 1.2.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.
package/dist/index.cjs CHANGED
@@ -39,14 +39,13 @@ var import_zustand = require("zustand");
39
39
  var import_middleware = require("zustand/middleware");
40
40
  var SessionStore = class {
41
41
  _store;
42
- /**
43
- * Initializes a new instance of the `SessionStore` class by creating a new `zustand`store with the initial state.
44
- */
45
42
  constructor() {
46
43
  this._store = (0, import_zustand.createStore)()(
47
44
  (0, import_middleware.persist)(this._getInitialState, {
48
- name: "fourt.io-signer-session",
49
- storage: (0, import_middleware.createJSONStorage)(() => localStorage)
45
+ name: "fourt-session",
46
+ storage: (0, import_middleware.createJSONStorage)(() => localStorage),
47
+ // keep only these keys in persisted storage
48
+ partialize: (state) => ({ bundle: state.bundle, type: state.type })
50
49
  })
51
50
  );
52
51
  }
@@ -82,6 +81,22 @@ var SessionStore = class {
82
81
  set token(token) {
83
82
  this._store.setState({ token });
84
83
  }
84
+ /**
85
+ * Gets the CSRF token from the session state.
86
+ *
87
+ * @returns {string | undefined} the CSRF token.
88
+ */
89
+ get csrfToken() {
90
+ return this._store.getState().csrfToken;
91
+ }
92
+ /**
93
+ * Sets the CSRF token in the session state.
94
+ *
95
+ * @param {string} csrfToken the CSRF token to set.
96
+ */
97
+ set csrfToken(csrfToken) {
98
+ this._store.setState({ csrfToken });
99
+ }
85
100
  /**
86
101
  * Gets the bundle from the session state.
87
102
  *
@@ -402,26 +417,29 @@ var UserModule = class {
402
417
  this._webSignerClient = _webSignerClient;
403
418
  }
404
419
  /**
405
- * Gets the user information.
406
- *
407
- * @returns {User | undefined} user information.
420
+ * Retrieves information for the authenticated user.
421
+ * Assumes a user is already logged in, otherwise it will throw an error.
408
422
  */
409
- get info() {
410
- return this._webSignerClient.user;
423
+ async getInfo() {
424
+ return this._webSignerClient.getUser();
411
425
  }
412
- /** Gets the user token.
413
- *
414
- * @returns {string | undefined} user token.
426
+ /**
427
+ * Checks if a user is currently logged in to the fourt.io SDK.
415
428
  */
416
- get token() {
429
+ async isLoggedIn() {
430
+ return this._webSignerClient.isLoggedIn();
431
+ }
432
+ /**
433
+ * Generates an access token with a lifespan of 15 minutes.
434
+ * Assumes a user is already logged in, otherwise it will throw an error.
435
+ */
436
+ async getToken() {
417
437
  return this._webSignerClient.getToken();
418
438
  }
419
439
  /**
420
440
  * Logs out the user.
421
- *
422
- * @returns {void}
423
441
  */
424
- logout() {
442
+ async logout() {
425
443
  return this._webSignerClient.logout();
426
444
  }
427
445
  };
@@ -488,14 +506,18 @@ var UnauthenticatedError = class _UnauthenticatedError extends SDKError {
488
506
  }
489
507
  };
490
508
 
491
- // src/types/Routes.ts
509
+ // src/types/routes.ts
492
510
  var ROUTE_METHOD_MAP = {
493
511
  "/v1/signup": "POST",
494
512
  "/v1/email-auth": "POST",
495
513
  "/v1/lookup": "POST",
496
514
  "/v1/signin": "POST",
497
515
  "/v1/sign": "POST",
498
- "v1/oauth/init": "POST"
516
+ "/v1/oauth/init": "POST",
517
+ "/v1/refresh": "POST",
518
+ "/v1/csrf-token": "GET",
519
+ "/v1/logout": "POST",
520
+ "/v1/me": "GET"
499
521
  };
500
522
 
501
523
  // src/signer/index.ts
@@ -505,7 +527,8 @@ var SignerClient = class {
505
527
  _turnkeyClient;
506
528
  _configuration;
507
529
  _sessionStore;
508
- _user;
530
+ _refreshPromise;
531
+ _refreshTimer;
509
532
  constructor({
510
533
  stamper,
511
534
  configuration: { apiUrl, paymasterRpcUrl, ...requiredConfiguration }
@@ -521,54 +544,97 @@ var SignerClient = class {
521
544
  };
522
545
  this._sessionStore = new SessionStore();
523
546
  }
524
- logout() {
525
- this._user = void 0;
526
- this.sessionStore.clearAll();
527
- }
528
547
  get configuration() {
529
548
  return this._configuration;
530
549
  }
531
- get user() {
532
- if (this._user) return this._user;
533
- if (!this.sessionStore.token) {
534
- this.sessionStore.clearAll();
535
- return void 0;
536
- }
537
- const decodedToken = (0, import_jwt_decode.jwtDecode)(this.sessionStore.token);
538
- if (decodedToken.exp && (0, import_date_fns.isPast)(new Date((0, import_date_fns.secondsToMilliseconds)(decodedToken.exp)))) {
539
- this.sessionStore.clearAll();
540
- return void 0;
550
+ async getUser() {
551
+ if (this._sessionStore.user) return this._sessionStore.user;
552
+ try {
553
+ const user = await this.request("/v1/me");
554
+ this._sessionStore.user = user;
555
+ return user;
556
+ } catch (error) {
557
+ if (error instanceof UnauthorizedError) {
558
+ try {
559
+ await this._refreshToken();
560
+ const user = await this.request("/v1/me");
561
+ this._sessionStore.user = user;
562
+ return user;
563
+ } catch (error2) {
564
+ throw error2;
565
+ }
566
+ }
567
+ throw error;
541
568
  }
542
- if (this.sessionStore.user) this._user = this.sessionStore.user;
543
- return this._user;
544
569
  }
545
- set user(value) {
546
- this._user = value;
570
+ async isLoggedIn() {
571
+ const token = this._sessionStore.token;
572
+ if (token && !this._isTokenExpired(token)) return true;
573
+ try {
574
+ await this._refreshToken();
575
+ return !!this._sessionStore.token;
576
+ } catch {
577
+ return false;
578
+ }
547
579
  }
548
- set stamper(stamper) {
549
- this._turnkeyClient.stamper = stamper;
580
+ async getToken() {
581
+ if (!this._sessionStore.token) {
582
+ try {
583
+ await this._refreshToken();
584
+ } catch {
585
+ throw new UnauthorizedError({
586
+ message: "No token found, user might not be logged in"
587
+ });
588
+ }
589
+ } else if (this._isTokenExpired(this._sessionStore.token)) {
590
+ try {
591
+ await this._refreshToken();
592
+ } catch {
593
+ throw new UnauthorizedError({
594
+ message: "Token expired and refresh failed"
595
+ });
596
+ }
597
+ }
598
+ const token = this._sessionStore.token;
599
+ if (!token) {
600
+ throw new UnauthorizedError({
601
+ message: "No token found, user might not be logged in"
602
+ });
603
+ }
604
+ return token;
550
605
  }
551
- get stamper() {
552
- return this._turnkeyClient.stamper;
606
+ _isTokenExpired(token) {
607
+ try {
608
+ const decoded = (0, import_jwt_decode.jwtDecode)(token);
609
+ if (decoded.exp) {
610
+ return decoded.exp * 1e3 <= Date.now();
611
+ }
612
+ return true;
613
+ } catch {
614
+ return true;
615
+ }
553
616
  }
554
- get sessionStore() {
555
- return this._sessionStore;
617
+ async logout() {
618
+ if (this._refreshTimer) clearTimeout(this._refreshTimer);
619
+ this._refreshTimer = void 0;
620
+ await this.request("/v1/logout");
621
+ this._sessionStore.clearAll();
556
622
  }
557
623
  async signRawMessage(msg) {
558
- if (!this._user) {
624
+ if (!this._sessionStore.token || !this._sessionStore.user) {
559
625
  throw new UnauthorizedError({
560
626
  message: "SignerClient must be authenticated to sign a message"
561
627
  });
562
628
  }
563
629
  const stampedRequest = await this._turnkeyClient.stampSignRawPayload({
564
- organizationId: this._user.subOrgId,
630
+ organizationId: this._sessionStore.user.subOrgId,
565
631
  type: "ACTIVITY_TYPE_SIGN_RAW_PAYLOAD_V2",
566
632
  timestampMs: Date.now().toString(),
567
633
  parameters: {
568
634
  encoding: "PAYLOAD_ENCODING_HEXADECIMAL",
569
635
  hashFunction: "HASH_FUNCTION_NO_OP",
570
636
  payload: msg,
571
- signWith: this._user.walletAddress
637
+ signWith: this._sessionStore.user.walletAddress
572
638
  }
573
639
  });
574
640
  const { signature } = await this.request("/v1/sign", {
@@ -576,8 +642,11 @@ var SignerClient = class {
576
642
  });
577
643
  return signature;
578
644
  }
579
- getToken() {
580
- return this._sessionStore.token;
645
+ set stamper(stamper) {
646
+ this._turnkeyClient.stamper = stamper;
647
+ }
648
+ get stamper() {
649
+ return this._turnkeyClient.stamper;
581
650
  }
582
651
  async lookUpUser(email) {
583
652
  try {
@@ -597,12 +666,12 @@ var SignerClient = class {
597
666
  }
598
667
  }
599
668
  async whoAmI(subOrgId) {
600
- const orgId = subOrgId || this._user?.subOrgId;
669
+ const orgId = subOrgId || this._sessionStore.user?.subOrgId;
601
670
  if (!orgId) throw new BadRequestError({ message: "No orgId provided" });
602
671
  const stampedRequest = await this._turnkeyClient.stampGetWhoami({
603
672
  organizationId: orgId
604
673
  });
605
- const { user, token } = await this.request("/v1/signin", {
674
+ const { user, token, csrfToken } = await this.request("/v1/signin", {
606
675
  stampedRequest
607
676
  });
608
677
  const credentialId = (() => {
@@ -612,16 +681,18 @@ var SignerClient = class {
612
681
  return void 0;
613
682
  }
614
683
  })();
615
- this._user = {
684
+ this._sessionStore.user = {
616
685
  ...user,
617
686
  credentialId
618
687
  };
619
- this.sessionStore.user = this.user;
620
- this.sessionStore.token = token;
688
+ this._sessionStore.token = token;
689
+ this._sessionStore.csrfToken = csrfToken;
690
+ this._scheduleRefresh(token);
621
691
  }
622
692
  async request(route, body) {
623
693
  const url = new URL(`${route}`, this._configuration.apiUrl);
624
- const token = this.sessionStore.token;
694
+ const token = this._sessionStore.token;
695
+ const csrfToken = this._sessionStore.csrfToken;
625
696
  const headers = {
626
697
  "Content-Type": "application/json",
627
698
  "X-FOURT-KEY": this._configuration.apiKey
@@ -629,6 +700,9 @@ var SignerClient = class {
629
700
  if (token) {
630
701
  headers["Authorization"] = `Bearer ${token}`;
631
702
  }
703
+ if (csrfToken) {
704
+ headers["X-CSRF-Token"] = csrfToken;
705
+ }
632
706
  const response = await fetch(url, {
633
707
  method: ROUTE_METHOD_MAP[route],
634
708
  body: JSON.stringify(body),
@@ -639,7 +713,6 @@ var SignerClient = class {
639
713
  if (error) {
640
714
  switch (error.kind) {
641
715
  case "UnauthorizedError": {
642
- this.logout();
643
716
  throw new UnauthorizedError({ message: error.message });
644
717
  }
645
718
  case "NotFoundError": {
@@ -655,6 +728,80 @@ var SignerClient = class {
655
728
  }
656
729
  return { ...data };
657
730
  }
731
+ _scheduleRefresh(token) {
732
+ try {
733
+ const decoded = (0, import_jwt_decode.jwtDecode)(token);
734
+ if (!decoded.exp) return;
735
+ const expiryDate = new Date(decoded.exp * 1e3);
736
+ const refreshDate = (0, import_date_fns.subMinutes)(expiryDate, 2);
737
+ const delay = (0, import_date_fns.isBefore)(refreshDate, /* @__PURE__ */ new Date()) ? 0 : (0, import_date_fns.differenceInMilliseconds)(refreshDate, /* @__PURE__ */ new Date());
738
+ if (this._refreshTimer) clearTimeout(this._refreshTimer);
739
+ this._refreshTimer = setTimeout(() => {
740
+ this._refreshTimer = void 0;
741
+ this._refreshToken();
742
+ }, delay);
743
+ } catch {
744
+ }
745
+ }
746
+ async _refreshToken() {
747
+ if (this._refreshPromise) return this._refreshPromise;
748
+ this._refreshPromise = (async () => {
749
+ const TIMEOUT_MS = 1e4;
750
+ const RETRY_DELAY_MS = 5e3;
751
+ try {
752
+ if (!this._sessionStore.csrfToken) {
753
+ const { csrfToken } = await this.request("/v1/csrf-token");
754
+ this._sessionStore.csrfToken = csrfToken;
755
+ }
756
+ const refreshPromise = this.request("/v1/refresh");
757
+ const data = await Promise.race([
758
+ refreshPromise,
759
+ new Promise(
760
+ (_, reject) => setTimeout(() => reject(new Error("Refresh timeout")), TIMEOUT_MS)
761
+ )
762
+ ]);
763
+ if (!data || !data.token) {
764
+ throw new UnauthorizedError({
765
+ message: "Refresh did not return a token"
766
+ });
767
+ }
768
+ this._sessionStore.token = data.token;
769
+ this._scheduleRefresh(data.token);
770
+ } catch (error) {
771
+ if (error instanceof UnauthorizedError) {
772
+ try {
773
+ this._sessionStore.clearAll();
774
+ } catch {
775
+ }
776
+ throw error;
777
+ }
778
+ if (this._refreshTimer) clearTimeout(this._refreshTimer);
779
+ const MAX_RETRIES = 5;
780
+ let retryCount = 0;
781
+ this._refreshTimer = setTimeout(() => {
782
+ this._refreshTimer = void 0;
783
+ void this._refreshToken().catch(() => {
784
+ retryCount++;
785
+ if (retryCount <= MAX_RETRIES) {
786
+ const nextDelay = Math.min(
787
+ RETRY_DELAY_MS * 2 ** (retryCount - 1),
788
+ 6e4
789
+ );
790
+ this._refreshTimer = setTimeout(() => {
791
+ this._refreshTimer = void 0;
792
+ void this._refreshToken().catch(() => {
793
+ });
794
+ }, nextDelay);
795
+ }
796
+ });
797
+ }, RETRY_DELAY_MS);
798
+ throw error;
799
+ } finally {
800
+ this._refreshPromise = void 0;
801
+ }
802
+ })();
803
+ return this._refreshPromise;
804
+ }
658
805
  };
659
806
 
660
807
  // src/signer/web.ts
@@ -697,10 +844,6 @@ var WebSignerClient = class extends SignerClient {
697
844
  this.webauthnStamper = new import_webauthn_stamper.WebauthnStamper({ rpId: webauthn.rpId });
698
845
  this.oauthConfiguration = oauth;
699
846
  }
700
- async signRawMessage(msg) {
701
- await this.updateStamper();
702
- return super.signRawMessage(msg);
703
- }
704
847
  async logout() {
705
848
  super.logout();
706
849
  this.iframeStamper.clear();
@@ -714,23 +857,20 @@ var WebSignerClient = class extends SignerClient {
714
857
  this.iframeStamper = stamper;
715
858
  await this._initIframeStamper();
716
859
  }
860
+ async signRawMessage(msg) {
861
+ await this._updateStamper();
862
+ return super.signRawMessage(msg);
863
+ }
717
864
  /**
718
- * Checks for an existing session and if exists, updates the stamper accordingly.
865
+ * Get the pre-filled URL for initiating oauth with a specific provider.
719
866
  *
867
+ * @param {string} provider provider for which we are getting the URL, currently google or apple
720
868
  */
721
- async updateStamper() {
722
- if (this._sessionStore.type === void 0 && (this._sessionStore.bundle === void 0 || this._sessionStore.token === void 0))
723
- return;
724
- if (this._sessionStore.type === "passkeys" /* Passkeys */) {
725
- this.stamper = this.webauthnStamper;
726
- } else {
727
- this.stamper = this.iframeStamper;
728
- await this.completeAuthWithBundle({
729
- bundle: this._sessionStore.bundle,
730
- subOrgId: this.user?.subOrgId,
731
- sessionType: this._sessionStore.type
732
- });
733
- }
869
+ async getOAuthInitUrl(provider) {
870
+ const { url } = await this.request("/v1/oauth/init", {
871
+ provider
872
+ });
873
+ return url;
734
874
  }
735
875
  /**
736
876
  * Signs in a user with webauthn.
@@ -745,12 +885,12 @@ var WebSignerClient = class extends SignerClient {
745
885
  this.stamper = this.webauthnStamper;
746
886
  await this.whoAmI(existingUserSubOrgId);
747
887
  this._sessionStore.type = "passkeys" /* Passkeys */;
748
- if (!this.user || !this.user.credentialId) {
888
+ if (!this._sessionStore.user || !this._sessionStore.user.credentialId) {
749
889
  return;
750
890
  }
751
891
  this.webauthnStamper.allowCredentials = [
752
892
  {
753
- id: LibBase64.toBuffer(this.user.credentialId),
893
+ id: LibBase64.toBuffer(this._sessionStore.user.credentialId),
754
894
  type: "public-key",
755
895
  transports: ["internal", "usb"]
756
896
  }
@@ -773,23 +913,6 @@ var WebSignerClient = class extends SignerClient {
773
913
  async getIframePublicKey() {
774
914
  return await this._initIframeStamper();
775
915
  }
776
- /**
777
- * Signs in a user with email.
778
- *
779
- * @param {EmailInitializeAuthParams} params params for the sign in
780
- */
781
- async _signInWithEmail({
782
- email,
783
- expirationSeconds,
784
- redirectUrl
785
- }) {
786
- return this.request("/v1/email-auth", {
787
- email,
788
- targetPublicKey: await this.getIframePublicKey(),
789
- expirationSeconds,
790
- redirectUrl: redirectUrl.toString()
791
- });
792
- }
793
916
  /**
794
917
  * Completes the authentication process with a credential bundle.
795
918
  *
@@ -809,6 +932,40 @@ var WebSignerClient = class extends SignerClient {
809
932
  this._sessionStore.type = sessionType;
810
933
  this._sessionStore.bundle = bundle;
811
934
  }
935
+ /**
936
+ * Checks for an existing session and if exists, updates the stamper accordingly.
937
+ */
938
+ async _updateStamper() {
939
+ if (this._sessionStore.type === void 0 && (this._sessionStore.bundle === void 0 || this._sessionStore.token === void 0))
940
+ return;
941
+ if (this._sessionStore.type === "passkeys" /* Passkeys */) {
942
+ this.stamper = this.webauthnStamper;
943
+ } else {
944
+ this.stamper = this.iframeStamper;
945
+ await this.completeAuthWithBundle({
946
+ bundle: this._sessionStore.bundle,
947
+ subOrgId: this._sessionStore.user?.subOrgId,
948
+ sessionType: this._sessionStore.type
949
+ });
950
+ }
951
+ }
952
+ /**
953
+ * Signs in a user with email.
954
+ *
955
+ * @param {EmailInitializeAuthParams} params params for the sign in
956
+ */
957
+ async _signInWithEmail({
958
+ email,
959
+ expirationSeconds,
960
+ redirectUrl
961
+ }) {
962
+ return this.request("/v1/email-auth", {
963
+ email,
964
+ targetPublicKey: await this.getIframePublicKey(),
965
+ expirationSeconds,
966
+ redirectUrl: redirectUrl.toString()
967
+ });
968
+ }
812
969
  /**
813
970
  * Creates a passkey account using the webauthn stamper.
814
971
  *
@@ -818,28 +975,21 @@ var WebSignerClient = class extends SignerClient {
818
975
  const { challenge, attestation } = await this._webauthnGenerateAttestation(
819
976
  params.email
820
977
  );
821
- const {
822
- token,
823
- user: { id, email, subOrgId, walletAddress, salt, smartAccountAddress }
824
- } = await this.request("/v1/signup", {
978
+ const { user, token, csrfToken } = await this.request("/v1/signup", {
825
979
  passkey: {
826
980
  challenge: LibBase64.fromBuffer(challenge),
827
981
  attestation
828
982
  },
829
983
  email: params.email
830
984
  });
831
- this.user = {
832
- id,
833
- email,
834
- subOrgId,
835
- walletAddress,
836
- salt,
837
- smartAccountAddress,
985
+ this._sessionStore.user = {
986
+ ...user,
838
987
  credentialId: attestation.credentialId
839
988
  };
840
- this._sessionStore.user = this.user;
841
989
  this._sessionStore.type = "passkeys" /* Passkeys */;
842
990
  this._sessionStore.token = token;
991
+ this._sessionStore.csrfToken = csrfToken;
992
+ this._scheduleRefresh(token);
843
993
  }
844
994
  /**
845
995
  * Creates an email account using the iframe stamper.
@@ -916,17 +1066,6 @@ var WebSignerClient = class extends SignerClient {
916
1066
  this.stamper = this.iframeStamper;
917
1067
  return this.iframeStamper.publicKey();
918
1068
  }
919
- /**
920
- * Get the pre-filled URL for initiating oauth with a specific provider.
921
- *
922
- * @param {string} provider provider for which we are getting the URL, currently google or apple
923
- */
924
- async getOAuthInitUrl(provider) {
925
- const { url } = await this.request("v1/oauth/init", {
926
- provider
927
- });
928
- return url;
929
- }
930
1069
  };
931
1070
 
932
1071
  // src/third-party/viem.ts
@@ -939,13 +1078,13 @@ var ViemModule = class {
939
1078
  this._signerClient = _signerClient;
940
1079
  }
941
1080
  async toLocalAccount() {
942
- const user = this._signerClient.user;
1081
+ const user = await this._signerClient.getUser();
943
1082
  if (!user) {
944
1083
  throw new UnauthenticatedError({ message: "Signer not authenticated" });
945
1084
  }
946
1085
  return (0, import_accounts.toAccount)({
947
1086
  address: user.walletAddress,
948
- signMessage: (msg) => this.signMessage(msg.message),
1087
+ signMessage: ({ message }) => this.signMessage(message),
949
1088
  signTypedData: (typedDataDefinition) => this.signTypedData(typedDataDefinition),
950
1089
  signTransaction: this.signTransaction
951
1090
  });
@@ -954,7 +1093,7 @@ var ViemModule = class {
954
1093
  client,
955
1094
  owner
956
1095
  }) {
957
- const user = this._signerClient.user;
1096
+ const user = await this._signerClient.getUser();
958
1097
  if (!user) {
959
1098
  throw new UnauthenticatedError({ message: "Signer not authenticated" });
960
1099
  }
@@ -990,7 +1129,7 @@ var ViemModule = class {
990
1129
  }
991
1130
  async signTransaction(transaction, options) {
992
1131
  const serializeFn = options?.serializer ?? import_viem.serializeTransaction;
993
- const serializedTx = serializeFn(transaction);
1132
+ const serializedTx = await serializeFn(transaction);
994
1133
  const signatureHex = await this._signerClient.signRawMessage(
995
1134
  (0, import_viem.keccak256)(serializedTx)
996
1135
  );