@redzone/taunt-logins 0.0.9 → 0.0.11

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.
@@ -502,6 +502,35 @@ class TauntApi {
502
502
  async get(url, headers = {}) {
503
503
  return this._api("GET", url, undefined, headers);
504
504
  }
505
+ async withProvider(provider, extNonce) {
506
+ const walletAddress = await provider.getAddress();
507
+ if (!walletAddress) {
508
+ throw new Error("No wallet address found");
509
+ }
510
+ const cryptoValuesArray = new Uint32Array(3);
511
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString();
512
+ const serverNonce = await this.nonceLogin(walletAddress, clientNonce);
513
+ const payload = JSON.stringify({
514
+ clientNonce,
515
+ serverNonce
516
+ });
517
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`;
518
+ let signature;
519
+ try {
520
+ signature = await provider.personalSign(message, walletAddress);
521
+ } catch (err) {
522
+ throw new Error("User denied message signature");
523
+ }
524
+ if (!signature) {
525
+ throw new Error("No signature returned");
526
+ }
527
+ return this.loginExtWithWeb3WalletSignature({
528
+ walletAddress,
529
+ message,
530
+ signature,
531
+ extNonce
532
+ });
533
+ }
505
534
  // this.user = data
506
535
  // localStorage.setItem("user", JSON.stringify(data))
507
536
  // localStorage.setItem(
@@ -629,15 +658,32 @@ class TauntApi {
629
658
  }
630
659
  return Promise.reject(ErrorFromResponse(error.response));
631
660
  };
661
+ this.setLoginDetails = async (props, checkGet = true)=>{
662
+ this.accessToken = props.accessToken;
663
+ this.refreshToken = props.refreshToken;
664
+ if (checkGet) {
665
+ const user = await this.getLoggedInUser();
666
+ if (!user) {
667
+ this.accessToken = null;
668
+ this.refreshToken = null;
669
+ return null;
670
+ }
671
+ }
672
+ return {
673
+ accessToken: this.accessToken,
674
+ refreshToken: this.refreshToken
675
+ };
676
+ };
632
677
  this.nonceLogin = (walletAddress, clientNonce)=>this.post("/v1/auth/nonce/login", {
633
678
  walletAddress,
634
679
  clientNonce
635
680
  });
636
- this.loginWithMagicDid = (did)=>this.post("/v1/auth/login/did", {
637
- did
638
- });
681
+ // loginWithMagicDid = (did: string) => this.post("/v1/auth/login/did", { did })
639
682
  this.loginWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/signature", props);
640
- this.loginExtWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/ext-signature", props);
683
+ this.loginExtWithWeb3WalletSignature = (props)=>{
684
+ props.extNonce = props.extNonce || this.randomTokenString();
685
+ return this.post("/v1/auth/login/ext-signature", props);
686
+ };
641
687
  this.refresh = (refreshToken)=>{
642
688
  const token = refreshToken || this.refreshToken;
643
689
  if (!token) {
@@ -665,6 +711,7 @@ class TauntApi {
665
711
  const data = await this.get("/v1/beamable/inventory/skulls");
666
712
  return data;
667
713
  };
714
+ this.randomTokenString = ()=>crypto.randomUUID().replace(/-/g, "");
668
715
  // Use the cookie stored in the browser to get the user and save user model in state and local storage
669
716
  // This assumes that the user is logged to backend in and has a cookie jwt
670
717
  this.getLoggedInUser = ()=>this.get("/v1/auth/me");
@@ -686,102 +733,67 @@ const getMagic = (magicKey)=>new magicSdk.Magic(magicKey, {
686
733
  new oauth2.OAuthExtension()
687
734
  ]
688
735
  });
689
- function emailOTPWithMagic(magicKey, email) {
690
- const magic = getMagic(magicKey);
736
+ function emailOTPWithMagic(magicKey, email, magic) {
737
+ magic = magic || getMagic(magicKey);
691
738
  return magic.auth.loginWithEmailOTP({
692
739
  email
693
740
  });
694
741
  }
695
- function telegramWithMagic(magicKey) {
696
- const magic = getMagic(magicKey);
742
+ function telegramWithMagic(magicKey, magic) {
743
+ magic = magic || getMagic(magicKey);
697
744
  return magic.oauth2.loginWithPopup({
698
745
  provider: "telegram"
699
746
  });
700
747
  }
701
- async function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi) {
702
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
703
- try {
704
- let result = await telegramWithMagic(magicKey);
705
- const errResult = result;
706
- if (errResult.error) {
707
- throw new Error(`No ID token returned ${errResult.error}`);
708
- }
709
- result = result;
710
- console.log("Magic telegram login", {
711
- result
712
- });
713
- return taunt.loginWithMagicDid(result.magic.idToken);
714
- } catch (err) {
715
- console.error("Magic login error:", err);
716
- throw err;
717
- }
748
+ function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi, extNonce) {
749
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>telegramWithMagic(magicKey, magic));
718
750
  }
719
- async function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi) {
720
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
751
+ function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi, extNonce) {
752
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>emailOTPWithMagic(magicKey, email, magic));
753
+ }
754
+ async function withLoginTry(endpoint, tauntApi, magicKey, magic, extNonce, fn) {
755
+ tauntApi = tauntApi || new TauntApi(endpoint);
756
+ magic = magic || getMagic(magicKey);
721
757
  try {
722
- const did = await emailOTPWithMagic(magicKey, email);
723
- if (!did) throw new Error("No DID returned");
724
- console.log("Magic email OTP login", {
725
- did
726
- });
727
- return taunt.loginWithMagicDid(did);
758
+ if (!await magic.user.isLoggedIn()) {
759
+ await fn(magic, tauntApi);
760
+ }
761
+ // check if user is logged in
762
+ const isLoggedIn = await magic.user.isLoggedIn();
763
+ if (!isLoggedIn) {
764
+ throw new Error("User is not logged in");
765
+ }
766
+ return tauntApi.withProvider({
767
+ getAddress: ()=>magic.rpcProvider.send("eth_accounts", []).then((accounts)=>accounts[0]),
768
+ personalSign: (message, address)=>magic.rpcProvider.send("personal_sign", [
769
+ message,
770
+ address
771
+ ]).then((sig)=>sig)
772
+ }, extNonce);
728
773
  } catch (err) {
729
774
  console.error("Magic login error:", err);
730
775
  throw err;
731
776
  }
732
777
  }
733
- async function tauntMagicDidLogin(tauntServiceEndpoint, did, tauntApi) {
734
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
735
- return taunt.loginWithMagicDid(did);
736
- }
737
778
 
738
- async function tauntSignWithMetamask(tauntServiceEndpoint, provider, tauntApi) {
779
+ async function tauntMetamaskLogin(tauntServiceEndpoint, provider, tauntApi, extNonce) {
739
780
  provider = provider || window.ethereum;
740
- if (!provider) throw new Error("MetaMask provider not found");
741
- const accounts = await provider.request({
742
- method: "eth_requestAccounts"
743
- });
744
- if (!accounts.length) throw new Error("No accounts returned");
745
- console.log("MetaMask", {
746
- accounts
747
- });
748
- const walletAddress = accounts[0];
749
- const cryptoValuesArray = new Uint32Array(3);
750
- const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString();
751
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
752
- const serverNonce = await taunt.nonceLogin(walletAddress, clientNonce);
753
- const payload = JSON.stringify({
754
- clientNonce,
755
- serverNonce
756
- });
757
- const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`;
758
- let signature;
759
- try {
760
- signature = await provider.request({
761
- method: "personal_sign",
762
- params: [
763
- message,
764
- walletAddress
765
- ]
766
- });
767
- } catch (err) {
768
- throw new Error("User denied message signature");
781
+ if (!provider) {
782
+ throw new Error("MetaMask provider not found");
769
783
  }
770
- if (!signature) throw new Error("No signature returned");
771
- return {
772
- walletAddress,
773
- message,
774
- signature
775
- };
776
- }
777
- async function tauntMetamaskLogin(tauntServiceEndpoint, providerParam, tauntApi) {
778
784
  const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
779
- const { walletAddress, message, signature } = await tauntSignWithMetamask(tauntServiceEndpoint, providerParam, tauntApi);
780
- return taunt.loginWithWeb3WalletSignature({
781
- walletAddress,
782
- message,
783
- signature
784
- });
785
+ return taunt.withProvider({
786
+ getAddress: ()=>provider.request({
787
+ method: "eth_requestAccounts"
788
+ }).then((accounts)=>accounts?.[0]),
789
+ personalSign: (message, address)=>provider.request({
790
+ method: "personal_sign",
791
+ params: [
792
+ message,
793
+ address
794
+ ]
795
+ })
796
+ }, extNonce);
785
797
  }
786
798
 
787
799
  exports.BadGatewayError = BadGatewayError;
@@ -827,9 +839,7 @@ exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError;
827
839
  exports.UpgradeRequiredError = UpgradeRequiredError;
828
840
  exports.VariantAlsoNegotiatesError = VariantAlsoNegotiatesError;
829
841
  exports.emailOTPWithMagic = emailOTPWithMagic;
830
- exports.tauntMagicDidLogin = tauntMagicDidLogin;
831
842
  exports.tauntMagicEmailOTPLogin = tauntMagicEmailOTPLogin;
832
843
  exports.tauntMagicTelegramLogin = tauntMagicTelegramLogin;
833
844
  exports.tauntMetamaskLogin = tauntMetamaskLogin;
834
- exports.tauntSignWithMetamask = tauntSignWithMetamask;
835
845
  exports.telegramWithMagic = telegramWithMagic;
@@ -1,6 +1,8 @@
1
1
  import { AxiosResponse, AxiosRequestConfig } from 'axios';
2
+ import * as _magic_ext_oauth2 from '@magic-ext/oauth2';
3
+ import { OAuthExtension } from '@magic-ext/oauth2';
2
4
  import * as magic_sdk from 'magic-sdk';
3
- import { OAuthRedirectResult, OAuthRedirectError } from '@magic-ext/oauth2';
5
+ import * as _magic_sdk_provider from '@magic-sdk/provider';
4
6
  import { BaseProvider } from '@metamask/providers';
5
7
 
6
8
  declare class ErrorResponse {
@@ -291,7 +293,11 @@ type TauntSigProps = {
291
293
  signature: string;
292
294
  };
293
295
  type TauntExtSigProps = TauntSigProps & {
294
- extNonce: string;
296
+ extNonce?: string;
297
+ };
298
+ type TauntAccessDetails = {
299
+ accessToken: string;
300
+ refreshToken: string;
295
301
  };
296
302
  type TauntRespType = {
297
303
  accessToken: string;
@@ -325,21 +331,31 @@ declare class TauntApi {
325
331
  response: AxiosResponse;
326
332
  }) => Promise<AxiosResponse<any, any, {}>>;
327
333
  private _api;
334
+ setLoginDetails: (props: TauntAccessDetails, checkGet?: boolean) => Promise<{
335
+ accessToken: string;
336
+ refreshToken: string;
337
+ } | null>;
328
338
  post<T = TauntRespType>(url: string, body?: {}, headers?: {}): Promise<T>;
329
339
  get<T = TauntRespType>(url: string, headers?: {}): Promise<T>;
330
340
  nonceLogin: (walletAddress: string, clientNonce: string) => Promise<string>;
331
- loginWithMagicDid: (did: string) => Promise<TauntRespType>;
332
341
  loginWithWeb3WalletSignature: (props: TauntSigProps) => Promise<TauntRespType>;
333
342
  loginExtWithWeb3WalletSignature: (props: TauntExtSigProps) => Promise<TauntRespType>;
334
343
  refresh: (refreshToken?: string) => Promise<TauntRespType>;
335
344
  logout: () => Promise<void>;
336
345
  getClaimrToken: () => Promise<string>;
337
346
  getClaimrData: () => Promise<ClaimrCampaignData>;
347
+ randomTokenString: () => string;
348
+ withProvider(provider: {
349
+ getAddress: () => Promise<string | undefined | null>;
350
+ personalSign: (message: string, address: string) => Promise<string | undefined | null>;
351
+ }, extNonce?: string): Promise<TauntRespType>;
338
352
  getLoggedInUser: () => Promise<TauntUser>;
339
353
  writePlayerEvent(eventName: string, eventData?: unknown, retryIfLoginNeeded?: boolean): Promise<void>;
340
354
  }
341
355
 
342
- declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.PromiEvent<string | null, {
356
+ declare const getMagic: (magicKey: string) => _magic_sdk_provider.InstanceWithExtensions<_magic_sdk_provider.SDKBase, OAuthExtension[]>;
357
+ type MagicType = ReturnType<typeof getMagic>;
358
+ declare function emailOTPWithMagic(magicKey: string, email: string, magic?: MagicType): magic_sdk.PromiEvent<string | null, {
343
359
  "email-otp-sent": () => void;
344
360
  "login-throttled": () => void;
345
361
  "invalid-email-otp": () => void;
@@ -368,23 +384,18 @@ declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.P
368
384
  settled: () => void;
369
385
  "closed-by-user": () => void;
370
386
  }>;
371
- declare function telegramWithMagic(magicKey: string): magic_sdk.PromiEvent<OAuthRedirectResult | OAuthRedirectError, {
372
- done: (result: OAuthRedirectResult | OAuthRedirectError) => void;
387
+ declare function telegramWithMagic(magicKey: string, magic?: MagicType): magic_sdk.PromiEvent<_magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError, {
388
+ done: (result: _magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError) => void;
373
389
  error: (reason: any) => void;
374
390
  settled: () => void;
375
391
  "closed-by-user": () => void;
376
392
  }>;
377
- declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi): Promise<{
393
+ declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
378
394
  accessToken: string;
379
395
  refreshToken: string;
380
396
  isNewUser: string;
381
397
  }>;
382
- declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string, tauntApi?: TauntApi): Promise<{
383
- accessToken: string;
384
- refreshToken: string;
385
- isNewUser: string;
386
- }>;
387
- declare function tauntMagicDidLogin(tauntServiceEndpoint: string, did: string, tauntApi?: TauntApi): Promise<{
398
+ declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
388
399
  accessToken: string;
389
400
  refreshToken: string;
390
401
  isNewUser: string;
@@ -395,16 +406,11 @@ declare global {
395
406
  ethereum?: BaseProvider;
396
407
  }
397
408
  }
398
- declare function tauntSignWithMetamask(tauntServiceEndpoint: string, provider?: BaseProvider, tauntApi?: TauntApi): Promise<{
399
- walletAddress: string;
400
- message: string;
401
- signature: string;
402
- }>;
403
- declare function tauntMetamaskLogin(tauntServiceEndpoint: string, providerParam?: BaseProvider, tauntApi?: TauntApi): Promise<{
409
+ declare function tauntMetamaskLogin(tauntServiceEndpoint: string, provider?: BaseProvider, tauntApi?: TauntApi, extNonce?: string): Promise<{
404
410
  accessToken: string;
405
411
  refreshToken: string;
406
412
  isNewUser: string;
407
413
  }>;
408
414
 
409
- export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicDidLogin, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, tauntSignWithMetamask, telegramWithMagic };
410
- export type { ClaimrCampaignData, TauntExtSigProps, TauntSigProps, TauntUser };
415
+ export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, telegramWithMagic };
416
+ export type { ClaimrCampaignData, TauntAccessDetails, TauntExtSigProps, TauntSigProps, TauntUser };
@@ -1,6 +1,8 @@
1
1
  import { AxiosResponse, AxiosRequestConfig } from 'axios';
2
+ import * as _magic_ext_oauth2 from '@magic-ext/oauth2';
3
+ import { OAuthExtension } from '@magic-ext/oauth2';
2
4
  import * as magic_sdk from 'magic-sdk';
3
- import { OAuthRedirectResult, OAuthRedirectError } from '@magic-ext/oauth2';
5
+ import * as _magic_sdk_provider from '@magic-sdk/provider';
4
6
  import { BaseProvider } from '@metamask/providers';
5
7
 
6
8
  declare class ErrorResponse {
@@ -291,7 +293,11 @@ type TauntSigProps = {
291
293
  signature: string;
292
294
  };
293
295
  type TauntExtSigProps = TauntSigProps & {
294
- extNonce: string;
296
+ extNonce?: string;
297
+ };
298
+ type TauntAccessDetails = {
299
+ accessToken: string;
300
+ refreshToken: string;
295
301
  };
296
302
  type TauntRespType = {
297
303
  accessToken: string;
@@ -325,21 +331,31 @@ declare class TauntApi {
325
331
  response: AxiosResponse;
326
332
  }) => Promise<AxiosResponse<any, any, {}>>;
327
333
  private _api;
334
+ setLoginDetails: (props: TauntAccessDetails, checkGet?: boolean) => Promise<{
335
+ accessToken: string;
336
+ refreshToken: string;
337
+ } | null>;
328
338
  post<T = TauntRespType>(url: string, body?: {}, headers?: {}): Promise<T>;
329
339
  get<T = TauntRespType>(url: string, headers?: {}): Promise<T>;
330
340
  nonceLogin: (walletAddress: string, clientNonce: string) => Promise<string>;
331
- loginWithMagicDid: (did: string) => Promise<TauntRespType>;
332
341
  loginWithWeb3WalletSignature: (props: TauntSigProps) => Promise<TauntRespType>;
333
342
  loginExtWithWeb3WalletSignature: (props: TauntExtSigProps) => Promise<TauntRespType>;
334
343
  refresh: (refreshToken?: string) => Promise<TauntRespType>;
335
344
  logout: () => Promise<void>;
336
345
  getClaimrToken: () => Promise<string>;
337
346
  getClaimrData: () => Promise<ClaimrCampaignData>;
347
+ randomTokenString: () => string;
348
+ withProvider(provider: {
349
+ getAddress: () => Promise<string | undefined | null>;
350
+ personalSign: (message: string, address: string) => Promise<string | undefined | null>;
351
+ }, extNonce?: string): Promise<TauntRespType>;
338
352
  getLoggedInUser: () => Promise<TauntUser>;
339
353
  writePlayerEvent(eventName: string, eventData?: unknown, retryIfLoginNeeded?: boolean): Promise<void>;
340
354
  }
341
355
 
342
- declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.PromiEvent<string | null, {
356
+ declare const getMagic: (magicKey: string) => _magic_sdk_provider.InstanceWithExtensions<_magic_sdk_provider.SDKBase, OAuthExtension[]>;
357
+ type MagicType = ReturnType<typeof getMagic>;
358
+ declare function emailOTPWithMagic(magicKey: string, email: string, magic?: MagicType): magic_sdk.PromiEvent<string | null, {
343
359
  "email-otp-sent": () => void;
344
360
  "login-throttled": () => void;
345
361
  "invalid-email-otp": () => void;
@@ -368,23 +384,18 @@ declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.P
368
384
  settled: () => void;
369
385
  "closed-by-user": () => void;
370
386
  }>;
371
- declare function telegramWithMagic(magicKey: string): magic_sdk.PromiEvent<OAuthRedirectResult | OAuthRedirectError, {
372
- done: (result: OAuthRedirectResult | OAuthRedirectError) => void;
387
+ declare function telegramWithMagic(magicKey: string, magic?: MagicType): magic_sdk.PromiEvent<_magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError, {
388
+ done: (result: _magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError) => void;
373
389
  error: (reason: any) => void;
374
390
  settled: () => void;
375
391
  "closed-by-user": () => void;
376
392
  }>;
377
- declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi): Promise<{
393
+ declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
378
394
  accessToken: string;
379
395
  refreshToken: string;
380
396
  isNewUser: string;
381
397
  }>;
382
- declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string, tauntApi?: TauntApi): Promise<{
383
- accessToken: string;
384
- refreshToken: string;
385
- isNewUser: string;
386
- }>;
387
- declare function tauntMagicDidLogin(tauntServiceEndpoint: string, did: string, tauntApi?: TauntApi): Promise<{
398
+ declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
388
399
  accessToken: string;
389
400
  refreshToken: string;
390
401
  isNewUser: string;
@@ -395,16 +406,11 @@ declare global {
395
406
  ethereum?: BaseProvider;
396
407
  }
397
408
  }
398
- declare function tauntSignWithMetamask(tauntServiceEndpoint: string, provider?: BaseProvider, tauntApi?: TauntApi): Promise<{
399
- walletAddress: string;
400
- message: string;
401
- signature: string;
402
- }>;
403
- declare function tauntMetamaskLogin(tauntServiceEndpoint: string, providerParam?: BaseProvider, tauntApi?: TauntApi): Promise<{
409
+ declare function tauntMetamaskLogin(tauntServiceEndpoint: string, provider?: BaseProvider, tauntApi?: TauntApi, extNonce?: string): Promise<{
404
410
  accessToken: string;
405
411
  refreshToken: string;
406
412
  isNewUser: string;
407
413
  }>;
408
414
 
409
- export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicDidLogin, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, tauntSignWithMetamask, telegramWithMagic };
410
- export type { ClaimrCampaignData, TauntExtSigProps, TauntSigProps, TauntUser };
415
+ export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, telegramWithMagic };
416
+ export type { ClaimrCampaignData, TauntAccessDetails, TauntExtSigProps, TauntSigProps, TauntUser };
package/dist/es/index.js CHANGED
@@ -496,6 +496,35 @@ class TauntApi {
496
496
  async get(url, headers = {}) {
497
497
  return this._api("GET", url, undefined, headers);
498
498
  }
499
+ async withProvider(provider, extNonce) {
500
+ const walletAddress = await provider.getAddress();
501
+ if (!walletAddress) {
502
+ throw new Error("No wallet address found");
503
+ }
504
+ const cryptoValuesArray = new Uint32Array(3);
505
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString();
506
+ const serverNonce = await this.nonceLogin(walletAddress, clientNonce);
507
+ const payload = JSON.stringify({
508
+ clientNonce,
509
+ serverNonce
510
+ });
511
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`;
512
+ let signature;
513
+ try {
514
+ signature = await provider.personalSign(message, walletAddress);
515
+ } catch (err) {
516
+ throw new Error("User denied message signature");
517
+ }
518
+ if (!signature) {
519
+ throw new Error("No signature returned");
520
+ }
521
+ return this.loginExtWithWeb3WalletSignature({
522
+ walletAddress,
523
+ message,
524
+ signature,
525
+ extNonce
526
+ });
527
+ }
499
528
  // this.user = data
500
529
  // localStorage.setItem("user", JSON.stringify(data))
501
530
  // localStorage.setItem(
@@ -623,15 +652,32 @@ class TauntApi {
623
652
  }
624
653
  return Promise.reject(ErrorFromResponse(error.response));
625
654
  };
655
+ this.setLoginDetails = async (props, checkGet = true)=>{
656
+ this.accessToken = props.accessToken;
657
+ this.refreshToken = props.refreshToken;
658
+ if (checkGet) {
659
+ const user = await this.getLoggedInUser();
660
+ if (!user) {
661
+ this.accessToken = null;
662
+ this.refreshToken = null;
663
+ return null;
664
+ }
665
+ }
666
+ return {
667
+ accessToken: this.accessToken,
668
+ refreshToken: this.refreshToken
669
+ };
670
+ };
626
671
  this.nonceLogin = (walletAddress, clientNonce)=>this.post("/v1/auth/nonce/login", {
627
672
  walletAddress,
628
673
  clientNonce
629
674
  });
630
- this.loginWithMagicDid = (did)=>this.post("/v1/auth/login/did", {
631
- did
632
- });
675
+ // loginWithMagicDid = (did: string) => this.post("/v1/auth/login/did", { did })
633
676
  this.loginWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/signature", props);
634
- this.loginExtWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/ext-signature", props);
677
+ this.loginExtWithWeb3WalletSignature = (props)=>{
678
+ props.extNonce = props.extNonce || this.randomTokenString();
679
+ return this.post("/v1/auth/login/ext-signature", props);
680
+ };
635
681
  this.refresh = (refreshToken)=>{
636
682
  const token = refreshToken || this.refreshToken;
637
683
  if (!token) {
@@ -659,6 +705,7 @@ class TauntApi {
659
705
  const data = await this.get("/v1/beamable/inventory/skulls");
660
706
  return data;
661
707
  };
708
+ this.randomTokenString = ()=>crypto.randomUUID().replace(/-/g, "");
662
709
  // Use the cookie stored in the browser to get the user and save user model in state and local storage
663
710
  // This assumes that the user is logged to backend in and has a cookie jwt
664
711
  this.getLoggedInUser = ()=>this.get("/v1/auth/me");
@@ -680,102 +727,67 @@ const getMagic = (magicKey)=>new Magic(magicKey, {
680
727
  new OAuthExtension()
681
728
  ]
682
729
  });
683
- function emailOTPWithMagic(magicKey, email) {
684
- const magic = getMagic(magicKey);
730
+ function emailOTPWithMagic(magicKey, email, magic) {
731
+ magic = magic || getMagic(magicKey);
685
732
  return magic.auth.loginWithEmailOTP({
686
733
  email
687
734
  });
688
735
  }
689
- function telegramWithMagic(magicKey) {
690
- const magic = getMagic(magicKey);
736
+ function telegramWithMagic(magicKey, magic) {
737
+ magic = magic || getMagic(magicKey);
691
738
  return magic.oauth2.loginWithPopup({
692
739
  provider: "telegram"
693
740
  });
694
741
  }
695
- async function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi) {
696
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
697
- try {
698
- let result = await telegramWithMagic(magicKey);
699
- const errResult = result;
700
- if (errResult.error) {
701
- throw new Error(`No ID token returned ${errResult.error}`);
702
- }
703
- result = result;
704
- console.log("Magic telegram login", {
705
- result
706
- });
707
- return taunt.loginWithMagicDid(result.magic.idToken);
708
- } catch (err) {
709
- console.error("Magic login error:", err);
710
- throw err;
711
- }
742
+ function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi, extNonce) {
743
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>telegramWithMagic(magicKey, magic));
712
744
  }
713
- async function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi) {
714
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
745
+ function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi, extNonce) {
746
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>emailOTPWithMagic(magicKey, email, magic));
747
+ }
748
+ async function withLoginTry(endpoint, tauntApi, magicKey, magic, extNonce, fn) {
749
+ tauntApi = tauntApi || new TauntApi(endpoint);
750
+ magic = magic || getMagic(magicKey);
715
751
  try {
716
- const did = await emailOTPWithMagic(magicKey, email);
717
- if (!did) throw new Error("No DID returned");
718
- console.log("Magic email OTP login", {
719
- did
720
- });
721
- return taunt.loginWithMagicDid(did);
752
+ if (!await magic.user.isLoggedIn()) {
753
+ await fn(magic, tauntApi);
754
+ }
755
+ // check if user is logged in
756
+ const isLoggedIn = await magic.user.isLoggedIn();
757
+ if (!isLoggedIn) {
758
+ throw new Error("User is not logged in");
759
+ }
760
+ return tauntApi.withProvider({
761
+ getAddress: ()=>magic.rpcProvider.send("eth_accounts", []).then((accounts)=>accounts[0]),
762
+ personalSign: (message, address)=>magic.rpcProvider.send("personal_sign", [
763
+ message,
764
+ address
765
+ ]).then((sig)=>sig)
766
+ }, extNonce);
722
767
  } catch (err) {
723
768
  console.error("Magic login error:", err);
724
769
  throw err;
725
770
  }
726
771
  }
727
- async function tauntMagicDidLogin(tauntServiceEndpoint, did, tauntApi) {
728
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
729
- return taunt.loginWithMagicDid(did);
730
- }
731
772
 
732
- async function tauntSignWithMetamask(tauntServiceEndpoint, provider, tauntApi) {
773
+ async function tauntMetamaskLogin(tauntServiceEndpoint, provider, tauntApi, extNonce) {
733
774
  provider = provider || window.ethereum;
734
- if (!provider) throw new Error("MetaMask provider not found");
735
- const accounts = await provider.request({
736
- method: "eth_requestAccounts"
737
- });
738
- if (!accounts.length) throw new Error("No accounts returned");
739
- console.log("MetaMask", {
740
- accounts
741
- });
742
- const walletAddress = accounts[0];
743
- const cryptoValuesArray = new Uint32Array(3);
744
- const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString();
745
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
746
- const serverNonce = await taunt.nonceLogin(walletAddress, clientNonce);
747
- const payload = JSON.stringify({
748
- clientNonce,
749
- serverNonce
750
- });
751
- const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`;
752
- let signature;
753
- try {
754
- signature = await provider.request({
755
- method: "personal_sign",
756
- params: [
757
- message,
758
- walletAddress
759
- ]
760
- });
761
- } catch (err) {
762
- throw new Error("User denied message signature");
775
+ if (!provider) {
776
+ throw new Error("MetaMask provider not found");
763
777
  }
764
- if (!signature) throw new Error("No signature returned");
765
- return {
766
- walletAddress,
767
- message,
768
- signature
769
- };
770
- }
771
- async function tauntMetamaskLogin(tauntServiceEndpoint, providerParam, tauntApi) {
772
778
  const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
773
- const { walletAddress, message, signature } = await tauntSignWithMetamask(tauntServiceEndpoint, providerParam, tauntApi);
774
- return taunt.loginWithWeb3WalletSignature({
775
- walletAddress,
776
- message,
777
- signature
778
- });
779
+ return taunt.withProvider({
780
+ getAddress: ()=>provider.request({
781
+ method: "eth_requestAccounts"
782
+ }).then((accounts)=>accounts?.[0]),
783
+ personalSign: (message, address)=>provider.request({
784
+ method: "personal_sign",
785
+ params: [
786
+ message,
787
+ address
788
+ ]
789
+ })
790
+ }, extNonce);
779
791
  }
780
792
 
781
- export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicDidLogin, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, tauntSignWithMetamask, telegramWithMagic };
793
+ export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, telegramWithMagic };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@redzone/taunt-logins",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [