diff --git a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs index 777ae0f..fe23c07 100644 --- a/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs +++ b/Assets/Plugins/Web3AuthSDK/Api/Web3AuthApi.cs @@ -1,16 +1,14 @@ using System.Collections; -using System.Collections.Generic; -using UnityEngine; -using System.Net.Http; using System; using Newtonsoft.Json.Linq; using Newtonsoft.Json; -using System.Text; +using UnityEngine.Networking; +using UnityEngine; public class Web3AuthApi { static Web3AuthApi instance; - static Uri baseAddress = new Uri("https://broadcast-server.tor.us"); + static string baseAddress = "https://broadcast-server.tor.us"; public static Web3AuthApi getInstance() { @@ -19,36 +17,37 @@ public static Web3AuthApi getInstance() return instance; } - public StoreApiResponse? authorizeSession(string key) + public IEnumerator authorizeSession(string key, Action callback) { - using (var client = new HttpClient()) - { - client.BaseAddress = baseAddress; - HttpResponseMessage response = client.GetAsync("/store/get?key=" + key).Result; + var request = UnityWebRequest.Get($"{baseAddress}/store/get?key={key}"); + yield return request.SendWebRequest(); - if (response.IsSuccessStatusCode) - { - string result = response.Content.ReadAsStringAsync().Result; - return Newtonsoft.Json.JsonConvert.DeserializeObject(result); - } - return null; + if (request.result == UnityWebRequest.Result.Success) + { + string result = request.downloadHandler.text; + callback(Newtonsoft.Json.JsonConvert.DeserializeObject(result)); } + else + callback(null); } - public JObject logout(LogoutApiRequest logoutApiRequest) + public IEnumerator logout(LogoutApiRequest logoutApiRequest, Action callback) { - using (var client = new HttpClient()) - { - client.BaseAddress = baseAddress; - var content = new StringContent(JsonConvert.SerializeObject(logoutApiRequest), Encoding.UTF8, "application/json"); - HttpResponseMessage response = client.PostAsync("/store/set", content).Result; + WWWForm data = new WWWForm(); + data.AddField("key", logoutApiRequest.key); + data.AddField("data", logoutApiRequest.data); + data.AddField("signature", logoutApiRequest.signature); + data.AddField("timeout", logoutApiRequest.timeout.ToString()); + + var request = UnityWebRequest.Post($"{baseAddress}/store/set", data); + yield return request.SendWebRequest(); - if (response.IsSuccessStatusCode) - { - string result = response.Content.ReadAsStringAsync().Result; - return Newtonsoft.Json.JsonConvert.DeserializeObject(result); - } - return null; + if (request.result == UnityWebRequest.Result.Success) + { + string result = request.downloadHandler.text; + callback(Newtonsoft.Json.JsonConvert.DeserializeObject(result)); } + else + callback(null); } } diff --git a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs index 2987f05..20cf345 100644 --- a/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs +++ b/Assets/Plugins/Web3AuthSDK/Keystore/KeyStoreManagerUtils.cs @@ -27,13 +27,20 @@ public class KeyStoreManagerUtils public static string getPubKey(string sessionId) { - var domain = SecNamedCurves.GetByName("secp256k1"); - var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.H); - - var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters); - var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q; - - return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false)); + try + { + var domain = SecNamedCurves.GetByName("secp256k1"); + var parameters = new ECDomainParameters(domain.Curve, domain.G, domain.H); + + var key = new ECPrivateKeyParameters(new BigInteger(sessionId, 16), parameters); + var q = new ECPublicKeyParameters("EC", domain.G.Multiply(key.D), parameters).Q; + + return Hex.ToHexString(domain.Curve.CreatePoint(q.XCoord.ToBigInteger(), q.YCoord.ToBigInteger()).GetEncoded(false)); + } catch (System.Exception ex) + { + UnityEngine.Debug.Log(ex); + return ""; + } } static KeyStoreManagerUtils() diff --git a/Assets/Plugins/Web3AuthSDK/Utils.cs b/Assets/Plugins/Web3AuthSDK/Utils.cs index 501ddb4..94039ba 100644 --- a/Assets/Plugins/Web3AuthSDK/Utils.cs +++ b/Assets/Plugins/Web3AuthSDK/Utils.cs @@ -8,11 +8,22 @@ public static class Utils { -#if UNITY_IOS +#if !UNITY_EDITOR && UNITY_IOS [DllImport("__Internal")] extern static void web3auth_launch(string url, string redirectUri, string objectName); #endif +#if !UNITY_EDITOR && UNITY_WEBGL + [DllImport("__Internal")] + public extern static string GetCurrentURL(); + + [DllImport("__Internal")] + extern static void OpenURL(string url); + + [DllImport("__Internal")] + public extern static void RemoveAuthCodeFromURL(); +#endif + public static void LaunchUrl(string url, string redirectUri = null, string objectName = null) { @@ -29,6 +40,8 @@ public static void LaunchUrl(string url, string redirectUri = null, string objec #elif UNITY_IOS var uri = new Uri(redirectUri); web3auth_launch(url, uri.Scheme, objectName); +#elif UNITY_WEBGL + OpenURL(url); #endif } diff --git a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs index cb0144b..912bcba 100644 --- a/Assets/Plugins/Web3AuthSDK/Web3Auth.cs +++ b/Assets/Plugins/Web3AuthSDK/Web3Auth.cs @@ -54,6 +54,15 @@ public void Awake() { this.setResultUrl(url); }; + +//#elif UNITY_WEBGL +// var code = Utils.GetAuthCode(); +// Debug.Log("code is " + code); +// if (Utils.GetAuthCode() != "") +// { +// Debug.Log("I am here"); +// this.setResultUrl(new Uri($"http://localhost#{code}")); +// } #endif authorizeSession(); @@ -194,6 +203,8 @@ private void request(string path, LoginParams loginParams = null, Dictionary paramMap = new Dictionary(); paramMap["init"] = this.initParams; @@ -221,9 +232,13 @@ private void request(string path, LoginParams loginParams = null, Dictionary queryParameters = Utils.ParseQuery(uri.Query); @@ -249,6 +264,13 @@ public void setResultUrl(Uri uri) web3AuthResponse.userInfo?.verifier, web3AuthResponse.userInfo?.dappShare ); } + +#if !UNITY_EDITOR && UNITY_WEBGL + if (this.web3AuthResponse != null) + { + Utils.RemoveAuthCodeFromURL(); + } +#endif } public void login(LoginParams loginParams) @@ -270,7 +292,6 @@ public void login(LoginParams loginParams) public void logout(Dictionary extraParams) { sessionTimeOutAPI(); - request("logout", extraParams: extraParams); } public void logout(Uri redirectUrl = null, string appState = null) @@ -291,54 +312,41 @@ private void authorizeSession() if (!string.IsNullOrEmpty(sessionId)) { var pubKey = KeyStoreManagerUtils.getPubKey(sessionId); - var response = Web3AuthApi.getInstance().authorizeSession(pubKey); - - if (response != null) + StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, (response => { - var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject(response.message); - - KeyStoreManagerUtils.savePreferenceData( - KeyStoreManagerUtils.EPHEM_PUBLIC_Key, - shareMetadata.ephemPublicKey - ); - - KeyStoreManagerUtils.savePreferenceData( - KeyStoreManagerUtils.IV_KEY, - shareMetadata.iv - ); - - KeyStoreManagerUtils.savePreferenceData( - KeyStoreManagerUtils.MAC, - shareMetadata.mac - ); - - var aes256cbc = new AES256CBC( - sessionId, - shareMetadata.ephemPublicKey, - shareMetadata.iv - ); - - var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16)); - var share = aes256cbc.decrypt(encryptedShareBytes); - var tempJson = JsonConvert.DeserializeObject(share); - tempJson.Add("userInfo", tempJson["store"]); - tempJson.Remove("store"); - - this.web3AuthResponse = JsonConvert.DeserializeObject(tempJson.ToString()); - - if (this.web3AuthResponse != null) + if (response != null) { - if (this.web3AuthResponse.error != null) + var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject(response.message); + + var aes256cbc = new AES256CBC( + sessionId, + shareMetadata.ephemPublicKey, + shareMetadata.iv + ); + + var encryptedShareBytes = AES256CBC.toByteArray(new BigInteger(shareMetadata.ciphertext, 16)); + var share = aes256cbc.decrypt(encryptedShareBytes); + var tempJson = JsonConvert.DeserializeObject(share); + tempJson.Add("userInfo", tempJson["store"]); + tempJson.Remove("store"); + + this.web3AuthResponse = JsonConvert.DeserializeObject(tempJson.ToString()); + + if (this.web3AuthResponse != null) { - throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong"); + if (this.web3AuthResponse.error != null) + { + throw new UnKnownException(this.web3AuthResponse.error ?? "Something went wrong"); + } + + if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0'))) + this.Enqueue(() => this.onLogout?.Invoke()); + else + this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse)); } - - if (string.IsNullOrEmpty(this.web3AuthResponse.privKey) || string.IsNullOrEmpty(this.web3AuthResponse.privKey.Trim('0'))) - this.Enqueue(() => this.onLogout?.Invoke()); - else - this.Enqueue(() => this.onLogin?.Invoke(this.web3AuthResponse)); } - } + + }))); } } @@ -347,58 +355,59 @@ private void sessionTimeOutAPI() string sessionId = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.SESSION_ID); if (!string.IsNullOrEmpty(sessionId)) { - var ephemKey = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.EPHEM_PUBLIC_Key); - var ivKey = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.IV_KEY); - var mac = KeyStoreManagerUtils.getPreferencesData(KeyStoreManagerUtils.MAC); - - if (string.IsNullOrEmpty(ephemKey) == true && string.IsNullOrEmpty(ivKey) == true) return; - - var aes256cbc = new AES256CBC( - sessionId, - ephemKey, - ivKey - ); - - - var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes("")); - var encryptedMetadata = new ShareMetadata() + var pubKey = KeyStoreManagerUtils.getPubKey(sessionId); + StartCoroutine(Web3AuthApi.getInstance().authorizeSession(pubKey, (response => { - iv = ivKey, - ephemPublicKey = ephemKey, - ciphertext = encryptedData, - mac = mac - }; - var jsonData = JsonConvert.SerializeObject(encryptedMetadata); - - var result = Web3AuthApi.getInstance().logout( - new LogoutApiRequest() + if (response != null) { - key = KeyStoreManagerUtils.getPubKey(sessionId), - data = jsonData, - signature = KeyStoreManagerUtils.getECDSASignature( - sessionId, - jsonData - ), - timeout = 1 - } - ); + var shareMetadata = Newtonsoft.Json.JsonConvert.DeserializeObject(response.message); + var aes256cbc = new AES256CBC( + sessionId, + shareMetadata.ephemPublicKey, + shareMetadata.iv + ); - if (result != null) - { - try - { - KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.EPHEM_PUBLIC_Key); - KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.IV_KEY); - KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.MAC); - KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); - KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier); - } - catch (Exception ex) - { - Debug.LogError(ex.Message); + var encryptedData = aes256cbc.encrypt(System.Text.Encoding.UTF8.GetBytes("")); + var encryptedMetadata = new ShareMetadata() + { + iv = shareMetadata.iv, + ephemPublicKey = shareMetadata.ephemPublicKey, + ciphertext = encryptedData, + mac = shareMetadata.mac + }; + var jsonData = JsonConvert.SerializeObject(encryptedMetadata); + + StartCoroutine(Web3AuthApi.getInstance().logout( + new LogoutApiRequest() + { + key = KeyStoreManagerUtils.getPubKey(sessionId), + data = jsonData, + signature = KeyStoreManagerUtils.getECDSASignature( + sessionId, + jsonData + ), + timeout = 1 + }, result => + { + if (result != null) + { + try + { + KeyStoreManagerUtils.deletePreferencesData(KeyStoreManagerUtils.SESSION_ID); + KeyStoreManagerUtils.deletePreferencesData(web3AuthOptions.loginConfig?.Values.First()?.verifier); + + this.Enqueue(() => this.onLogout?.Invoke()); + } + catch (Exception ex) + { + Debug.LogError(ex.Message); + } + } + } + )); } - } + }))); } } diff --git a/Assets/Plugins/Web3AuthSDK/WebGL.meta b/Assets/Plugins/Web3AuthSDK/WebGL.meta new file mode 100644 index 0000000..1aa8438 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/WebGL.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 328ee4ce554c3fd4990e69ee78b2ad6e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/Web3AuthSDK/WebGL/Web3AuthSDK.jslib b/Assets/Plugins/Web3AuthSDK/WebGL/Web3AuthSDK.jslib new file mode 100644 index 0000000..fc7e952 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/WebGL/Web3AuthSDK.jslib @@ -0,0 +1,20 @@ +mergeInto(LibraryManager.library, { + GetCurrentURL: function() { + var url = window.location.href; + + var bufferSize = lengthBytesUTF8(url) + 1; + var buffer = _malloc(bufferSize); + stringToUTF8(url, buffer, bufferSize); + return buffer; + }, + + OpenURL: function (url) { + url = UTF8ToString(url); + window.location.href = url; + }, + + RemoveAuthCodeFromURL: function() { + window.history.replaceState(null, null, ' '); + }, + +}); \ No newline at end of file diff --git a/Assets/Plugins/Web3AuthSDK/WebGL/Web3AuthSDK.jslib.meta b/Assets/Plugins/Web3AuthSDK/WebGL/Web3AuthSDK.jslib.meta new file mode 100644 index 0000000..2ae3f64 --- /dev/null +++ b/Assets/Plugins/Web3AuthSDK/WebGL/Web3AuthSDK.jslib.meta @@ -0,0 +1,32 @@ +fileFormatVersion: 2 +guid: def6b5837a58d224897ccd570ad72fb2 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 0 + settings: + DefaultValueInitialized: true + - first: + WebGL: WebGL + second: + enabled: 1 + settings: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/StreamingAssets.meta b/Assets/StreamingAssets.meta new file mode 100644 index 0000000..1027d5c --- /dev/null +++ b/Assets/StreamingAssets.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ba3919a3133e4884aa5119162f6d9c84 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: