@redzone/taunt-logins 0.0.9 → 0.0.10

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(
@@ -633,11 +662,12 @@ class TauntApi {
633
662
  walletAddress,
634
663
  clientNonce
635
664
  });
636
- this.loginWithMagicDid = (did)=>this.post("/v1/auth/login/did", {
637
- did
638
- });
665
+ // loginWithMagicDid = (did: string) => this.post("/v1/auth/login/did", { did })
639
666
  this.loginWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/signature", props);
640
- this.loginExtWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/ext-signature", props);
667
+ this.loginExtWithWeb3WalletSignature = (props)=>{
668
+ props.extNonce = props.extNonce || this.randomTokenString();
669
+ return this.post("/v1/auth/login/ext-signature", props);
670
+ };
641
671
  this.refresh = (refreshToken)=>{
642
672
  const token = refreshToken || this.refreshToken;
643
673
  if (!token) {
@@ -665,6 +695,7 @@ class TauntApi {
665
695
  const data = await this.get("/v1/beamable/inventory/skulls");
666
696
  return data;
667
697
  };
698
+ this.randomTokenString = ()=>crypto.randomUUID().replace(/-/g, "");
668
699
  // Use the cookie stored in the browser to get the user and save user model in state and local storage
669
700
  // This assumes that the user is logged to backend in and has a cookie jwt
670
701
  this.getLoggedInUser = ()=>this.get("/v1/auth/me");
@@ -686,102 +717,67 @@ const getMagic = (magicKey)=>new magicSdk.Magic(magicKey, {
686
717
  new oauth2.OAuthExtension()
687
718
  ]
688
719
  });
689
- function emailOTPWithMagic(magicKey, email) {
690
- const magic = getMagic(magicKey);
720
+ function emailOTPWithMagic(magicKey, email, magic) {
721
+ magic = magic || getMagic(magicKey);
691
722
  return magic.auth.loginWithEmailOTP({
692
723
  email
693
724
  });
694
725
  }
695
- function telegramWithMagic(magicKey) {
696
- const magic = getMagic(magicKey);
726
+ function telegramWithMagic(magicKey, magic) {
727
+ magic = magic || getMagic(magicKey);
697
728
  return magic.oauth2.loginWithPopup({
698
729
  provider: "telegram"
699
730
  });
700
731
  }
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
- }
732
+ function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi, extNonce) {
733
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>telegramWithMagic(magicKey, magic));
718
734
  }
719
- async function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi) {
720
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
735
+ function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi, extNonce) {
736
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>emailOTPWithMagic(magicKey, email, magic));
737
+ }
738
+ async function withLoginTry(endpoint, tauntApi, magicKey, magic, extNonce, fn) {
739
+ tauntApi = tauntApi || new TauntApi(endpoint);
740
+ magic = magic || getMagic(magicKey);
721
741
  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);
742
+ if (!await magic.user.isLoggedIn()) {
743
+ await fn(magic, tauntApi);
744
+ }
745
+ // check if user is logged in
746
+ const isLoggedIn = await magic.user.isLoggedIn();
747
+ if (!isLoggedIn) {
748
+ throw new Error("User is not logged in");
749
+ }
750
+ return tauntApi.withProvider({
751
+ getAddress: ()=>magic.rpcProvider.send("eth_accounts", []).then((accounts)=>accounts[0]),
752
+ personalSign: (message, address)=>magic.rpcProvider.send("personal_sign", [
753
+ message,
754
+ address
755
+ ]).then((sig)=>sig)
756
+ }, extNonce);
728
757
  } catch (err) {
729
758
  console.error("Magic login error:", err);
730
759
  throw err;
731
760
  }
732
761
  }
733
- async function tauntMagicDidLogin(tauntServiceEndpoint, did, tauntApi) {
734
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
735
- return taunt.loginWithMagicDid(did);
736
- }
737
762
 
738
- async function tauntSignWithMetamask(tauntServiceEndpoint, provider, tauntApi) {
763
+ async function tauntMetamaskLogin(tauntServiceEndpoint, provider, tauntApi, extNonce) {
739
764
  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");
765
+ if (!provider) {
766
+ throw new Error("MetaMask provider not found");
769
767
  }
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
768
  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
- });
769
+ return taunt.withProvider({
770
+ getAddress: ()=>provider.request({
771
+ method: "eth_requestAccounts"
772
+ }).then((accounts)=>accounts?.[0]),
773
+ personalSign: (message, address)=>provider.request({
774
+ method: "personal_sign",
775
+ params: [
776
+ message,
777
+ address
778
+ ]
779
+ })
780
+ }, extNonce);
785
781
  }
786
782
 
787
783
  exports.BadGatewayError = BadGatewayError;
@@ -827,9 +823,7 @@ exports.UnsupportedMediaTypeError = UnsupportedMediaTypeError;
827
823
  exports.UpgradeRequiredError = UpgradeRequiredError;
828
824
  exports.VariantAlsoNegotiatesError = VariantAlsoNegotiatesError;
829
825
  exports.emailOTPWithMagic = emailOTPWithMagic;
830
- exports.tauntMagicDidLogin = tauntMagicDidLogin;
831
826
  exports.tauntMagicEmailOTPLogin = tauntMagicEmailOTPLogin;
832
827
  exports.tauntMagicTelegramLogin = tauntMagicTelegramLogin;
833
828
  exports.tauntMetamaskLogin = tauntMetamaskLogin;
834
- exports.tauntSignWithMetamask = tauntSignWithMetamask;
835
829
  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,7 @@ type TauntSigProps = {
291
293
  signature: string;
292
294
  };
293
295
  type TauntExtSigProps = TauntSigProps & {
294
- extNonce: string;
296
+ extNonce?: string;
295
297
  };
296
298
  type TauntRespType = {
297
299
  accessToken: string;
@@ -328,18 +330,24 @@ declare class TauntApi {
328
330
  post<T = TauntRespType>(url: string, body?: {}, headers?: {}): Promise<T>;
329
331
  get<T = TauntRespType>(url: string, headers?: {}): Promise<T>;
330
332
  nonceLogin: (walletAddress: string, clientNonce: string) => Promise<string>;
331
- loginWithMagicDid: (did: string) => Promise<TauntRespType>;
332
333
  loginWithWeb3WalletSignature: (props: TauntSigProps) => Promise<TauntRespType>;
333
334
  loginExtWithWeb3WalletSignature: (props: TauntExtSigProps) => Promise<TauntRespType>;
334
335
  refresh: (refreshToken?: string) => Promise<TauntRespType>;
335
336
  logout: () => Promise<void>;
336
337
  getClaimrToken: () => Promise<string>;
337
338
  getClaimrData: () => Promise<ClaimrCampaignData>;
339
+ randomTokenString: () => string;
340
+ withProvider(provider: {
341
+ getAddress: () => Promise<string | undefined | null>;
342
+ personalSign: (message: string, address: string) => Promise<string | undefined | null>;
343
+ }, extNonce?: string): Promise<TauntRespType>;
338
344
  getLoggedInUser: () => Promise<TauntUser>;
339
345
  writePlayerEvent(eventName: string, eventData?: unknown, retryIfLoginNeeded?: boolean): Promise<void>;
340
346
  }
341
347
 
342
- declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.PromiEvent<string | null, {
348
+ declare const getMagic: (magicKey: string) => _magic_sdk_provider.InstanceWithExtensions<_magic_sdk_provider.SDKBase, OAuthExtension[]>;
349
+ type MagicType = ReturnType<typeof getMagic>;
350
+ declare function emailOTPWithMagic(magicKey: string, email: string, magic?: MagicType): magic_sdk.PromiEvent<string | null, {
343
351
  "email-otp-sent": () => void;
344
352
  "login-throttled": () => void;
345
353
  "invalid-email-otp": () => void;
@@ -368,23 +376,18 @@ declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.P
368
376
  settled: () => void;
369
377
  "closed-by-user": () => void;
370
378
  }>;
371
- declare function telegramWithMagic(magicKey: string): magic_sdk.PromiEvent<OAuthRedirectResult | OAuthRedirectError, {
372
- done: (result: OAuthRedirectResult | OAuthRedirectError) => void;
379
+ declare function telegramWithMagic(magicKey: string, magic?: MagicType): magic_sdk.PromiEvent<_magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError, {
380
+ done: (result: _magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError) => void;
373
381
  error: (reason: any) => void;
374
382
  settled: () => void;
375
383
  "closed-by-user": () => void;
376
384
  }>;
377
- declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi): Promise<{
385
+ declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
378
386
  accessToken: string;
379
387
  refreshToken: string;
380
388
  isNewUser: string;
381
389
  }>;
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<{
390
+ declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
388
391
  accessToken: string;
389
392
  refreshToken: string;
390
393
  isNewUser: string;
@@ -395,16 +398,11 @@ declare global {
395
398
  ethereum?: BaseProvider;
396
399
  }
397
400
  }
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<{
401
+ declare function tauntMetamaskLogin(tauntServiceEndpoint: string, provider?: BaseProvider, tauntApi?: TauntApi, extNonce?: string): Promise<{
404
402
  accessToken: string;
405
403
  refreshToken: string;
406
404
  isNewUser: string;
407
405
  }>;
408
406
 
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 };
407
+ 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 };
410
408
  export type { ClaimrCampaignData, 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,7 @@ type TauntSigProps = {
291
293
  signature: string;
292
294
  };
293
295
  type TauntExtSigProps = TauntSigProps & {
294
- extNonce: string;
296
+ extNonce?: string;
295
297
  };
296
298
  type TauntRespType = {
297
299
  accessToken: string;
@@ -328,18 +330,24 @@ declare class TauntApi {
328
330
  post<T = TauntRespType>(url: string, body?: {}, headers?: {}): Promise<T>;
329
331
  get<T = TauntRespType>(url: string, headers?: {}): Promise<T>;
330
332
  nonceLogin: (walletAddress: string, clientNonce: string) => Promise<string>;
331
- loginWithMagicDid: (did: string) => Promise<TauntRespType>;
332
333
  loginWithWeb3WalletSignature: (props: TauntSigProps) => Promise<TauntRespType>;
333
334
  loginExtWithWeb3WalletSignature: (props: TauntExtSigProps) => Promise<TauntRespType>;
334
335
  refresh: (refreshToken?: string) => Promise<TauntRespType>;
335
336
  logout: () => Promise<void>;
336
337
  getClaimrToken: () => Promise<string>;
337
338
  getClaimrData: () => Promise<ClaimrCampaignData>;
339
+ randomTokenString: () => string;
340
+ withProvider(provider: {
341
+ getAddress: () => Promise<string | undefined | null>;
342
+ personalSign: (message: string, address: string) => Promise<string | undefined | null>;
343
+ }, extNonce?: string): Promise<TauntRespType>;
338
344
  getLoggedInUser: () => Promise<TauntUser>;
339
345
  writePlayerEvent(eventName: string, eventData?: unknown, retryIfLoginNeeded?: boolean): Promise<void>;
340
346
  }
341
347
 
342
- declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.PromiEvent<string | null, {
348
+ declare const getMagic: (magicKey: string) => _magic_sdk_provider.InstanceWithExtensions<_magic_sdk_provider.SDKBase, OAuthExtension[]>;
349
+ type MagicType = ReturnType<typeof getMagic>;
350
+ declare function emailOTPWithMagic(magicKey: string, email: string, magic?: MagicType): magic_sdk.PromiEvent<string | null, {
343
351
  "email-otp-sent": () => void;
344
352
  "login-throttled": () => void;
345
353
  "invalid-email-otp": () => void;
@@ -368,23 +376,18 @@ declare function emailOTPWithMagic(magicKey: string, email: string): magic_sdk.P
368
376
  settled: () => void;
369
377
  "closed-by-user": () => void;
370
378
  }>;
371
- declare function telegramWithMagic(magicKey: string): magic_sdk.PromiEvent<OAuthRedirectResult | OAuthRedirectError, {
372
- done: (result: OAuthRedirectResult | OAuthRedirectError) => void;
379
+ declare function telegramWithMagic(magicKey: string, magic?: MagicType): magic_sdk.PromiEvent<_magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError, {
380
+ done: (result: _magic_ext_oauth2.OAuthRedirectResult | _magic_ext_oauth2.OAuthRedirectError) => void;
373
381
  error: (reason: any) => void;
374
382
  settled: () => void;
375
383
  "closed-by-user": () => void;
376
384
  }>;
377
- declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi): Promise<{
385
+ declare function tauntMagicTelegramLogin(tauntServiceEndpoint: string, magicKey: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
378
386
  accessToken: string;
379
387
  refreshToken: string;
380
388
  isNewUser: string;
381
389
  }>;
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<{
390
+ declare function tauntMagicEmailOTPLogin(tauntServiceEndpoint: string, magicKey: string, email: string, tauntApi?: TauntApi, extNonce?: string): Promise<{
388
391
  accessToken: string;
389
392
  refreshToken: string;
390
393
  isNewUser: string;
@@ -395,16 +398,11 @@ declare global {
395
398
  ethereum?: BaseProvider;
396
399
  }
397
400
  }
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<{
401
+ declare function tauntMetamaskLogin(tauntServiceEndpoint: string, provider?: BaseProvider, tauntApi?: TauntApi, extNonce?: string): Promise<{
404
402
  accessToken: string;
405
403
  refreshToken: string;
406
404
  isNewUser: string;
407
405
  }>;
408
406
 
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 };
407
+ 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 };
410
408
  export type { ClaimrCampaignData, 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(
@@ -627,11 +656,12 @@ class TauntApi {
627
656
  walletAddress,
628
657
  clientNonce
629
658
  });
630
- this.loginWithMagicDid = (did)=>this.post("/v1/auth/login/did", {
631
- did
632
- });
659
+ // loginWithMagicDid = (did: string) => this.post("/v1/auth/login/did", { did })
633
660
  this.loginWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/signature", props);
634
- this.loginExtWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/ext-signature", props);
661
+ this.loginExtWithWeb3WalletSignature = (props)=>{
662
+ props.extNonce = props.extNonce || this.randomTokenString();
663
+ return this.post("/v1/auth/login/ext-signature", props);
664
+ };
635
665
  this.refresh = (refreshToken)=>{
636
666
  const token = refreshToken || this.refreshToken;
637
667
  if (!token) {
@@ -659,6 +689,7 @@ class TauntApi {
659
689
  const data = await this.get("/v1/beamable/inventory/skulls");
660
690
  return data;
661
691
  };
692
+ this.randomTokenString = ()=>crypto.randomUUID().replace(/-/g, "");
662
693
  // Use the cookie stored in the browser to get the user and save user model in state and local storage
663
694
  // This assumes that the user is logged to backend in and has a cookie jwt
664
695
  this.getLoggedInUser = ()=>this.get("/v1/auth/me");
@@ -680,102 +711,67 @@ const getMagic = (magicKey)=>new Magic(magicKey, {
680
711
  new OAuthExtension()
681
712
  ]
682
713
  });
683
- function emailOTPWithMagic(magicKey, email) {
684
- const magic = getMagic(magicKey);
714
+ function emailOTPWithMagic(magicKey, email, magic) {
715
+ magic = magic || getMagic(magicKey);
685
716
  return magic.auth.loginWithEmailOTP({
686
717
  email
687
718
  });
688
719
  }
689
- function telegramWithMagic(magicKey) {
690
- const magic = getMagic(magicKey);
720
+ function telegramWithMagic(magicKey, magic) {
721
+ magic = magic || getMagic(magicKey);
691
722
  return magic.oauth2.loginWithPopup({
692
723
  provider: "telegram"
693
724
  });
694
725
  }
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
- }
726
+ function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi, extNonce) {
727
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>telegramWithMagic(magicKey, magic));
712
728
  }
713
- async function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi) {
714
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
729
+ function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi, extNonce) {
730
+ return withLoginTry(tauntServiceEndpoint, tauntApi, magicKey, undefined, extNonce, (magic)=>emailOTPWithMagic(magicKey, email, magic));
731
+ }
732
+ async function withLoginTry(endpoint, tauntApi, magicKey, magic, extNonce, fn) {
733
+ tauntApi = tauntApi || new TauntApi(endpoint);
734
+ magic = magic || getMagic(magicKey);
715
735
  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);
736
+ if (!await magic.user.isLoggedIn()) {
737
+ await fn(magic, tauntApi);
738
+ }
739
+ // check if user is logged in
740
+ const isLoggedIn = await magic.user.isLoggedIn();
741
+ if (!isLoggedIn) {
742
+ throw new Error("User is not logged in");
743
+ }
744
+ return tauntApi.withProvider({
745
+ getAddress: ()=>magic.rpcProvider.send("eth_accounts", []).then((accounts)=>accounts[0]),
746
+ personalSign: (message, address)=>magic.rpcProvider.send("personal_sign", [
747
+ message,
748
+ address
749
+ ]).then((sig)=>sig)
750
+ }, extNonce);
722
751
  } catch (err) {
723
752
  console.error("Magic login error:", err);
724
753
  throw err;
725
754
  }
726
755
  }
727
- async function tauntMagicDidLogin(tauntServiceEndpoint, did, tauntApi) {
728
- const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
729
- return taunt.loginWithMagicDid(did);
730
- }
731
756
 
732
- async function tauntSignWithMetamask(tauntServiceEndpoint, provider, tauntApi) {
757
+ async function tauntMetamaskLogin(tauntServiceEndpoint, provider, tauntApi, extNonce) {
733
758
  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");
759
+ if (!provider) {
760
+ throw new Error("MetaMask provider not found");
763
761
  }
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
762
  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
- });
763
+ return taunt.withProvider({
764
+ getAddress: ()=>provider.request({
765
+ method: "eth_requestAccounts"
766
+ }).then((accounts)=>accounts?.[0]),
767
+ personalSign: (message, address)=>provider.request({
768
+ method: "personal_sign",
769
+ params: [
770
+ message,
771
+ address
772
+ ]
773
+ })
774
+ }, extNonce);
779
775
  }
780
776
 
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 };
777
+ 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.10",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "files": [