From 4bb20b3e883912fc5468fe2492d9070cec9e367f Mon Sep 17 00:00:00 2001 From: Treeki Date: Thu, 30 Jun 2016 04:00:55 +0200 Subject: initial commit --- .gitignore | 253 +++++++++++++++++++ App.config | 6 + ArchBreaker.csproj | 113 +++++++++ ArchBreaker.sln | 22 ++ ArchSecurity.cs | 130 ++++++++++ ArchSession.cs | 527 ++++++++++++++++++++++++++++++++++++++ IntroForm.Designer.cs | 532 +++++++++++++++++++++++++++++++++++++++ IntroForm.cs | 236 +++++++++++++++++ IntroForm.resx | 126 ++++++++++ Program.cs | 22 ++ Properties/AssemblyInfo.cs | 36 +++ Properties/Resources.Designer.cs | 71 ++++++ Properties/Resources.resx | 117 +++++++++ Properties/Settings.Designer.cs | 30 +++ Properties/Settings.settings | 7 + packages.config | 8 + 16 files changed, 2236 insertions(+) create mode 100644 .gitignore create mode 100755 App.config create mode 100755 ArchBreaker.csproj create mode 100755 ArchBreaker.sln create mode 100755 ArchSecurity.cs create mode 100755 ArchSession.cs create mode 100755 IntroForm.Designer.cs create mode 100755 IntroForm.cs create mode 100755 IntroForm.resx create mode 100755 Program.cs create mode 100755 Properties/AssemblyInfo.cs create mode 100755 Properties/Resources.Designer.cs create mode 100755 Properties/Resources.resx create mode 100755 Properties/Settings.Designer.cs create mode 100755 Properties/Settings.settings create mode 100755 packages.config diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..67acbf4 --- /dev/null +++ b/.gitignore @@ -0,0 +1,253 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# DNX +project.lock.json +project.fragment.lock.json +artifacts/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignoreable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.pfx +*.publishsettings +node_modules/ +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml diff --git a/App.config b/App.config new file mode 100755 index 0000000..d740e88 --- /dev/null +++ b/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/ArchBreaker.csproj b/ArchBreaker.csproj new file mode 100755 index 0000000..db6e57d --- /dev/null +++ b/ArchBreaker.csproj @@ -0,0 +1,113 @@ + + + + + Debug + AnyCPU + {1961BA9D-8BDF-4DEC-A7E5-F60469411E94} + WinExe + Properties + ArchBreaker + ArchBreaker + v4.5.2 + 512 + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + packages\Base32.1.0.0.26\lib\portable-net40+sl40+win+wp80\Base32.dll + True + + + packages\jose-jwt.1.9.2\lib\4.0\jose-jwt.dll + True + + + packages\LZ4PCL.1.0.0\lib\portable-net4+netcore45+wpa81+MonoAndroid1+MonoTouch1\LZ4PCL.dll + True + + + packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll + True + + + packages\OtpSharp.1.3.0.4\lib\net40\OtpSharp.dll + True + + + + + + + + + + + + + + + + + + Form + + + IntroForm.cs + + + + + IntroForm.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + \ No newline at end of file diff --git a/ArchBreaker.sln b/ArchBreaker.sln new file mode 100755 index 0000000..4d30e5c --- /dev/null +++ b/ArchBreaker.sln @@ -0,0 +1,22 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.25123.0 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArchBreaker", "ArchBreaker.csproj", "{1961BA9D-8BDF-4DEC-A7E5-F60469411E94}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {1961BA9D-8BDF-4DEC-A7E5-F60469411E94}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1961BA9D-8BDF-4DEC-A7E5-F60469411E94}.Debug|Any CPU.Build.0 = Debug|Any CPU + {1961BA9D-8BDF-4DEC-A7E5-F60469411E94}.Release|Any CPU.ActiveCfg = Release|Any CPU + {1961BA9D-8BDF-4DEC-A7E5-F60469411E94}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/ArchSecurity.cs b/ArchSecurity.cs new file mode 100755 index 0000000..60f7047 --- /dev/null +++ b/ArchSecurity.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using OtpSharp; + +namespace ArchBreaker +{ + static class ArchSecurity + { + public static string GenerateAssertion(string issuer) + { + var totpObj = new Totp(Encoding.UTF8.GetBytes(issuer), step: 600, totpSize: 8); + var totp = totpObj.ComputeTotp(); + + var payload = new Dictionary() + { + {"aud", Constants.BaasBaseURL}, + {"iss", issuer} + }; + + return Jose.JWT.Encode(payload, Encoding.UTF8.GetBytes(totp), Jose.JwsAlgorithm.HS256); + } + + + public static byte[] ComputeKey(string commonKey, string sessionID) + { + var commonBytes = Encoding.ASCII.GetBytes(commonKey); + var sessionBytes = Encoding.ASCII.GetBytes(sessionID); + var result = new byte[commonBytes.Length + sessionBytes.Length]; + + for (int i = 0; i < commonBytes.Length; i++) + result[i] = (byte)(0x9E - commonBytes[i]); + Array.Copy(sessionBytes, 0, result, commonBytes.Length, sessionBytes.Length); + + return result; + } + + + public static void TransformPacket(byte[] packet, byte[] key, bool encrypt) + { + for (int i = 0; i < packet.Length; i++) + { + int keyOffset = (i + 1) % key.Length; + int rot = key[keyOffset] & 7; + if (rot == 0) + packet[i] ^= key[keyOffset]; + else + { + if (encrypt) + rot = 8 - rot; + packet[i] = (byte)((packet[i] >> (8 - rot)) | (packet[i] << rot)); + } + } + } + + + public static byte[] DecompressPacket(byte[] input) + { + var hdr = ReadLZ4Header(input); + int destSize = hdr.Item1, offset = hdr.Item2; + + var output = new byte[destSize]; + LZ4PCL.LZ4Codec.Decode( + input, offset, input.Length - offset, + output, 0, destSize, + true); + return output; + } + public static byte[] CompressPacket(byte[] input) + { + var buf = new byte[LZ4PCL.LZ4Codec.MaximumOutputLength(input.Length)]; + + int realSize = LZ4PCL.LZ4Codec.Encode( + input, 0, input.Length, + buf, 0, buf.Length); + + // Pack the header for ruby-lz4 compat + var header = new byte[5]; + int headerSize = 0; + int inputSize = input.Length; + do + { + byte b = (byte)(inputSize & 0x7F); + inputSize >>= 7; + + if (inputSize == 0) + header[headerSize++] = b; + else + header[headerSize++] = (byte)(b | 0x80); + } while (inputSize != 0); + + // Combine header + output into one final array + var output = new byte[headerSize + realSize]; + Array.Copy(header, 0, output, 0, headerSize); + Array.Copy(buf, 0, output, headerSize, realSize); + return output; + } + + + private static Tuple ReadLZ4Header(byte[] buffer) + { + int destSize = 0; + for (int i = 0; i < 5; i++) + { + int v = buffer[i]; + destSize |= ((v & 0x7F) << (7 * i)); + + if ((v & 0x80) == 0) + return new Tuple(destSize, i + 1); + } + return new Tuple(-1, -1); + } + + + private static readonly Random _prng = new Random(); + + public static string RandomString(int size) + { + const string pool = "abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPRSTUVWXYZ0123456789"; + + var result = new char[size]; + for (int i = 0; i < size; i++) + result[i] = pool[_prng.Next(pool.Length)]; + + return new string(result); + } + } +} diff --git a/ArchSession.cs b/ArchSession.cs new file mode 100755 index 0000000..d080558 --- /dev/null +++ b/ArchSession.cs @@ -0,0 +1,527 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Net; +using Newtonsoft.Json.Linq; +using System.IO; +using System.Security.Cryptography; + +namespace ArchBreaker +{ + static class Constants + { + public const string ClientID = "2c44652b8960c92e"; + public const string RedirectURI = "npf" + ClientID + "://auth"; + public const string OAuthURL = "https://accounts.nintendo.com/connect/1.0.0/authorize"; + + public const string BaasBaseURL = "https://a01202e031d911e58fa2efb70468ccd2.baas.nintendo.com"; + public const string MiitomoBaseURL = "https://api.miitomo.com"; + public const string AccountsBaseURL = "https://accounts.nintendo.com"; + public const string ApiAccountsBaseURL = "https://api.accounts.nintendo.com"; + + public const string LoginURL = BaasBaseURL + "/1.0.0/gateway/sdk/login"; + public const string TokenURL = ApiAccountsBaseURL + "/1.0.0/gateway/sdk/token"; + public const string SessionTokenURL = AccountsBaseURL + "/connect/1.0.0/api/session_token"; + public const string FederationURL = BaasBaseURL + "/1.0.0/gateway/sdk/federation"; + + public const string MiiSessionURL = MiitomoBaseURL + "/v1/session"; + public const string MiiPlayerURL = MiitomoBaseURL + "/v1/player"; + } + + class ArchSession + { + public class ConfigParam + { + public string Key { get; } + public string Value { get; set; } + + public ConfigParam(string key, string value) + { + Key = key; + Value = value; + } + } + + private List _config = new List(); + public IEnumerable Config { get { return _config; } } + private WebProxy _proxy; + + private readonly string[] iOSDevices = { + "iPhone5,1", "iPhone5,2", "iPhone5,3", "iPhone5,4", + "iPhone6,1", "iPhone6,2", "iPhone7,1", "iPhone7,2", + "iPhone8,1", "iPhone8,2", "iPhone8,3", + "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4", + "iPad2,5", "iPad2,6", "iPad2,7", + "iPad3,1", "iPad3,2", "iPad3,3", "iPad3,4", "iPad3,5", "iPad3,6", + "iPad4,1", "iPad4,2", "iPad4,3", "iPad4,4", "iPad4,5", + "iPad4,6", "iPad4,7", "iPad4,8", "iPad4,9", + "iPad5,1", "iPad5,2", "iPad5,3", "iPad5,4", + "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8", + "iPod5,1", "iPod7,1" + }; + private readonly string[] iOSVersions = + { + "9.0", "9.0.1", "9.0.2", "9.1", "9.2", "9.2.1", + "9.3", "9.3.1", "9.3.2", "9.3.3" + }; + + public ArchSession() + { + var random = new Random(); + + _config.Add(new ConfigParam("NPFDeviceAccount", "")); + _config.Add(new ConfigParam("NPFDevicePassword", "")); + _config.Add(new ConfigParam("MiitomoSessionID", "")); + _config.Add(new ConfigParam("AdvertisingID", Guid.NewGuid().ToString().ToUpper())); + _config.Add(new ConfigParam("CommonKey", "")); + _config.Add(new ConfigParam("TokenIssuer", "")); + _config.Add(new ConfigParam("Manufacturer", "Apple")); + _config.Add(new ConfigParam("DeviceName", iOSDevices[random.Next(iOSDevices.Length)])); + _config.Add(new ConfigParam("OSType", "iOS")); + _config.Add(new ConfigParam("OSVersion", iOSVersions[random.Next(iOSVersions.Length)])); + _config.Add(new ConfigParam("TimeZoneOffset", "7200000")); + _config.Add(new ConfigParam("TimeZone", "Europe/Madrid")); + _config.Add(new ConfigParam("Locale", "en-GB")); + _config.Add(new ConfigParam("Country", "GB")); + _config.Add(new ConfigParam("NetworkType", "wifi")); + _config.Add(new ConfigParam("MiitomoVersion", "1.2.3")); + _config.Add(new ConfigParam("NPFSDKVersion", "1.0.6-1d50eaf")); + _config.Add(new ConfigParam("SakashoSDKVersion", "3.2.0")); + + _proxy = new WebProxy("http://192.168.1.70:8888"); + } + + public ConfigParam GetParam(string key) + { + return _config.First(p => p.Key == key); + } + + + public class LogEventArgs : EventArgs + { + public string Message; + } + public event EventHandler OnLog; + private void Log(string message) + { + OnLog?.Invoke(this, new LogEventArgs { Message = message }); + } + + + public async Task CallMiitomoAPIAsync(string endpoint, string method, JObject payload, string sessionId = null) + { + var key = ArchSecurity.ComputeKey( + GetParam("CommonKey").Value, + sessionId ?? GetParam("MiitomoSessionID").Value); + + string url = Constants.MiitomoBaseURL; + url += (endpoint.StartsWith("/") ? endpoint : ("/" + endpoint)); + + var request = CreateRequest(url, method) as HttpWebRequest; + + request.CookieContainer = new CookieContainer(1); + request.CookieContainer.Add(new Cookie( + "player_session_id", + sessionId ?? GetParam("MiitomoSessionID").Value, + "/", "api.miitomo.com")); + + if ((method == "POST" || method == "PUT") && payload != null) + { + var jsonBytes = Encoding.UTF8.GetBytes(payload.ToString()); + var compBytes = ArchSecurity.CompressPacket(jsonBytes); + ArchSecurity.TransformPacket(compBytes, key, true); + + request.ContentLength = compBytes.Length; + request.ContentType = "application/json"; + + var reqstream = await request.GetRequestStreamAsync(); + reqstream.Write(compBytes, 0, compBytes.Length); + reqstream.Close(); + } + + HttpWebResponse response; + try + { + response = await request.GetResponseAsync() as HttpWebResponse; + } + catch (WebException ex) + { + Log(ex.ToString()); + return null; + } + + // We've got something + var stream = response.GetResponseStream(); + var reader = new BinaryReader(stream); + var blob = reader.ReadBytes((int) response.ContentLength); + + ArchSecurity.TransformPacket(blob, key, false); + blob = ArchSecurity.DecompressPacket(blob); + + return JObject.Parse(Encoding.UTF8.GetString(blob)); + } + + + public class NewAccountResult + { + public string OriginalUserID, OriginalIDToken; + public string DeviceAccount, DevicePassword; + public string NPFSessionID, MiitomoSessionID; + public string OAuthURL, Verifier; + } + public async Task CreateNewAccountAsync() + { + // Step 1: Create an account + Log("-----\r\n[1] Creating a new device account."); + + var loginReq = await CreateLoginRequestAsync(null, null); + var loginResp = await loginReq.GetResponseAsync(); + var login = await HandleJSONResponseAsync(loginResp); + + var devAccInfo = login["createdDeviceAccount"]; + var devAccount = devAccInfo["id"].ToObject(); + var devPassword = devAccInfo["password"].ToObject(); + var accessToken = login["accessToken"].ToObject(); + var idToken = login["idToken"].ToObject(); + var userId = login["user"]["id"].ToObject(); + var sessionId = login["sessionId"].ToObject(); + + Log(string.Format("Account created ({0} :: {1})", devAccount, devPassword)); + + // Step 2: Create a Miitomo player + Log("-----\r\n[2] Creating a Miitomo player"); + + var playerReq = await CreateMiiPlayerRequestAsync(idToken); + var playerResp = await playerReq.GetResponseAsync(); + var player = await HandleJSONResponseAsync(playerResp); + var playerId = player["player_id"].ToObject(); + + // Step 3: Create a Miitomo session + Log("-----\r\n[3] Logging into Miitomo"); + + var miiSessionId = await AuthToMiitomoAsync(idToken); + Log("Session ID obtained: " + miiSessionId); + + // Step 4: OAuth! + var state = ArchSecurity.RandomString(50); + var verifier = ArchSecurity.RandomString(50); + var verifierHash = SHA256.Create().ComputeHash(Encoding.ASCII.GetBytes(verifier)); + + var oauthUrl = string.Format( + "{0}?state={1}&redirect_uri={2}&client_id={3}&lang={4}" + + "&scope={5}&response_type={6}&profile_source={7}" + + "&session_token_code_challenge={8}" + + "&session_token_code_challenge_method={9}", + + Constants.OAuthURL, state, + Uri.EscapeDataString(Constants.RedirectURI), Constants.ClientID, + Uri.EscapeDataString(GetParam("Locale").Value.Replace('-', '_')), + Uri.EscapeDataString("userinfo.birthday userinfo.mii openid offline userinfo.profile mission missionStatus missionCompletion members:authenticate userGift:receive"), + "session_token_code", + Uri.EscapeDataString("{\"country\":\"" + GetParam("Country").Value + "\"}"), + Uri.EscapeDataString(Jose.Base64Url.Encode(verifierHash)), + "S256"); + + Log("-----\r\n[4] Link your Nintendo Account"); + + return new NewAccountResult + { + OriginalIDToken = idToken, + OriginalUserID = userId, + NPFSessionID = sessionId, + DeviceAccount = devAccount, + DevicePassword = devPassword, + MiitomoSessionID = miiSessionId, + OAuthURL = oauthUrl, + Verifier = verifier + }; + } + + public class SessionTokenResult + { + public string SessionToken, Code; + } + public async Task HandleAuthURLAsync(string authUrl, NewAccountResult acctInfo) + { + // Extract bits from the url + int codePos = authUrl.IndexOf("&session_token_code="); + if (codePos == -1) + { + Log("No session_token_code? Welp, that's weird"); + return null; + } + + codePos += 20; + int codeEndPos = authUrl.IndexOf('&', codePos); + if (codeEndPos == -1) + codeEndPos = authUrl.Length; // just in case it's at the end! + + var sessionTokenCode = authUrl.Substring(codePos, codeEndPos - codePos); + var request = await CreateSessionTokenRequestAsync(sessionTokenCode, acctInfo.Verifier); + var response = await request.GetResponseAsync(); + var result = await HandleJSONResponseAsync(response); + + Log("-----\r\nObtained session_token and code"); + + return new SessionTokenResult + { + SessionToken = result["session_token"].ToObject(), + Code = result["code"].ToObject() + }; + } + + public class AccountTokenResult + { + public string UserID, IDToken; + } + public async Task GetAccountTokenAsync(string sessionToken) + { + Log(string.Format("-----\r\nLinking session token {0} ...", sessionToken)); + + var request = await CreateAccountTokenRequestAsync(sessionToken); + var response = await request.GetResponseAsync(); + var result = await HandleJSONResponseAsync(response); + + Log(result.ToString()); + return new AccountTokenResult + { + UserID = result["user"]["id"].ToObject(), + IDToken = result["idToken"].ToObject() + }; + } + + + public async Task DoFederationAsync(string idToken, string sessionId, string previousUserId, string deviceAccount, string devicePassword) + { + var payload = CreateBaseLoginParameters(deviceAccount, devicePassword); + payload["sessionId"] = sessionId; + payload["previousUserId"] = previousUserId; + payload["idpAccount"] = new JObject + { + { "idToken", idToken }, + { "idp", "nintendoAccount" } + }; + + var request = await CreateJSONRequestAsync(Constants.FederationURL, "POST", payload); + var response = await request.GetResponseAsync(); + var result = await HandleJSONResponseAsync(response); + + return result["idToken"].ToObject(); + } + + + public async Task NPFLoginAsync(string account, string password) + { + Log(string.Format("Logging in (device creds {0} :: {1})", account, password)); + + var loginReq = await CreateLoginRequestAsync(account, password); + WebResponse loginResp; + try + { + loginResp = await loginReq.GetResponseAsync(); + } + catch (WebException e) + { + Log("Login failed:\r\n" + e.ToString()); + return null; + } + + var loginBlob = await HandleJSONResponseAsync(loginResp); + return loginBlob["idToken"].ToObject(); + } + + public async Task AuthToMiitomoAsync(string idToken) + { + var sessionReq = await CreateMiiSessionRequestAsync(idToken); + WebResponse sessionResp; + try + { + sessionResp = await sessionReq.GetResponseAsync(); + } + catch (WebException e) + { + Log("Session creation failed:\r\n" + e.ToString()); + return null; + } + + // .NET won't let me read the cookie directly because it's HTTP- + // only, so I have to parse the Set-Cookie header + var cookieHeader = sessionResp.Headers[HttpResponseHeader.SetCookie]; + sessionResp.Close(); + + int psidPos = cookieHeader.IndexOf("player_session_id="); + if (psidPos >= 0) + { + int psidEndPos = cookieHeader.IndexOf(';', psidPos); + + psidPos += 18; + return cookieHeader.Substring(psidPos, psidEndPos - psidPos); + } + else + { + Log("Login failed; could not find player_session_id in cookie!\r\n" + cookieHeader); + return null; + } + } + + + private JObject CreateBaseLoginParameters(string deviceAccount = null, string devicePassword = null) + { + var root = new JObject + { + {"timeZoneOffset", int.Parse(GetParam("TimeZoneOffset").Value)}, + {"advertisingId", GetParam("AdvertisingID").Value}, + {"osVersion", GetParam("OSVersion").Value}, + {"networkType", GetParam("NetworkType").Value}, + {"locale", GetParam("Locale").Value}, + {"osType", GetParam("OSType").Value}, + {"deviceName", GetParam("DeviceName").Value}, + {"timeZone", GetParam("TimeZone").Value}, + {"manufacturer", GetParam("Manufacturer").Value}, + {"assertion", ArchSecurity.GenerateAssertion(GetParam("TokenIssuer").Value)}, + {"appVersion", GetParam("MiitomoVersion").Value}, + {"sdkVersion", GetParam("NPFSDKVersion").Value}, + //{"carrier", GetParam("Carrier").Value} -- this is optional! + }; + + if (deviceAccount != null && devicePassword != null) + { + root["deviceAccount"] = new JObject + { + {"id", deviceAccount}, + {"password", devicePassword} + }; + } + + return root; + } + + + private async Task CreateLoginRequestAsync(string deviceAccount, string devicePassword) + { + var root = CreateBaseLoginParameters(deviceAccount, devicePassword); + return await CreateJSONRequestAsync(Constants.LoginURL, "POST", root); + } + + private async Task CreateMiiPlayerRequestAsync(string idToken) + { + var root = new JObject { { "id_token", idToken } }; + return await CreateJSONRequestAsync(Constants.MiiPlayerURL, "POST", root); + } + + private async Task CreateMiiSessionRequestAsync(string idToken) + { + var root = new JObject { { "id_token", idToken } }; + return await CreateJSONRequestAsync(Constants.MiiSessionURL, "POST", root); + } + + private async Task CreateSessionTokenRequestAsync(string tokenCode, string verifier) + { + var request = CreateRequest(Constants.SessionTokenURL, "POST"); + + var payload = string.Format( + "client_id={0}&session_token_code={1}&session_token_code_verifier={2}", + Uri.EscapeDataString(Constants.ClientID), + Uri.EscapeDataString(tokenCode), + Uri.EscapeDataString(verifier)); + var payloadBytes = Encoding.ASCII.GetBytes(payload); + + request.ContentType = "application/x-www-form-urlencoded"; + request.ContentLength = payloadBytes.Length; + + var stream = await request.GetRequestStreamAsync(); + stream.Write(payloadBytes, 0, payloadBytes.Length); + stream.Close(); + + return request; + } + + private async Task CreateAccountTokenRequestAsync(string sessionToken) + { + var root = new JObject { + { "client_id", Constants.ClientID }, + { "session_token", sessionToken } + }; + return await CreateJSONRequestAsync(Constants.TokenURL, "POST", root); + } + + public WebRequest CreateRequest(string URI, string method) + { + var req = WebRequest.CreateHttp(URI); + req.Method = method; + //req.Proxy = _proxy; + req.Accept = "*/*"; + if (URI.StartsWith(Constants.MiitomoBaseURL)) + { + req.UserAgent = SakashoUserAgent; + req.Headers["X-Arch-Device-Language"] = GetParam("Locale").Value; + req.Headers["X-Arch-Device-Timezone"] = GetParam("TimeZone").Value; + req.Headers["X-Sakasho-Gameid"] = "1"; + } + else + { + req.UserAgent = NintendoUserAgent; + } + return req; + } + + private async Task CreateJSONRequestAsync(string URI, string method, JObject root) + { + var req = CreateRequest(URI, method); + + var json = root.ToString(Newtonsoft.Json.Formatting.None); + var blob = Encoding.UTF8.GetBytes(json); + + req.ContentType = "application/json"; + req.ContentLength = blob.Length; + + var stream = await req.GetRequestStreamAsync(); + stream.Write(blob, 0, blob.Length); + stream.Close(); + + return req; + } + + private async Task HandleJSONResponseAsync(WebResponse resp) + { + var stream = resp.GetResponseStream(); + var reader = new StreamReader(stream); + var blob = await reader.ReadToEndAsync(); + reader.Close(); + resp.Close(); + + return JObject.Parse(blob); + } + + + private string NintendoUserAgent + { + get + { + var appVer = GetParam("MiitomoVersion").Value; + var device = GetParam("DeviceName").Value; + var osVer = GetParam("OSVersion").Value; + var sdkVer = GetParam("NPFSDKVersion").Value; + return string.Format( + "com.nintendo.zaaa/{0} {1}/{2} NPFSDK/{3}", + appVer, device, osVer, sdkVer); + } + } + private string SakashoUserAgent + { + get + { + var appVer = GetParam("MiitomoVersion").Value; + var device = GetParam("DeviceName").Value; + var osType = GetParam("OSType").Value; + var osVer = GetParam("OSVersion").Value; + var sdkVer = GetParam("SakashoSDKVersion").Value; + return string.Format( + "SakashoClient/{0}-Native/SDK:{1}/Client:{2}/OS:{3}/Model:{4}", + osType, sdkVer, appVer, osVer, device); + } + } + } +} diff --git a/IntroForm.Designer.cs b/IntroForm.Designer.cs new file mode 100755 index 0000000..dc3bc9c --- /dev/null +++ b/IntroForm.Designer.cs @@ -0,0 +1,532 @@ +namespace ArchBreaker +{ + partial class IntroForm + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.configDataGrid = new System.Windows.Forms.DataGridView(); + this.logInButton = new System.Windows.Forms.Button(); + this.logBox = new System.Windows.Forms.TextBox(); + this.tabs = new System.Windows.Forms.TabControl(); + this.controlTab = new System.Windows.Forms.TabPage(); + this.newAccountButton = new System.Windows.Forms.Button(); + this.splitContainer2 = new System.Windows.Forms.SplitContainer(); + this.sandboxTab = new System.Windows.Forms.TabPage(); + this.sandboxSend = new System.Windows.Forms.Button(); + this.label1 = new System.Windows.Forms.Label(); + this.sandboxURL = new System.Windows.Forms.TextBox(); + this.splitContainer1 = new System.Windows.Forms.SplitContainer(); + this.sandboxInput = new System.Windows.Forms.TextBox(); + this.sandboxOutput = new System.Windows.Forms.TextBox(); + this.deleteRadioButton = new System.Windows.Forms.RadioButton(); + this.putRadioButton = new System.Windows.Forms.RadioButton(); + this.postRadioButton = new System.Windows.Forms.RadioButton(); + this.getRadioButton = new System.Windows.Forms.RadioButton(); + this.newAccountPanel = new System.Windows.Forms.Panel(); + this.authURLInput = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.newAccountFinishButton = new System.Windows.Forms.Button(); + this.saveSettingsButton = new System.Windows.Forms.Button(); + this.loadSettingsButton = new System.Windows.Forms.Button(); + this.inventoryTab = new System.Windows.Forms.TabPage(); + this.downloadInventoryButton = new System.Windows.Forms.Button(); + this.uploadInventoryButton = new System.Windows.Forms.Button(); + this.loadSettingsDialog = new System.Windows.Forms.OpenFileDialog(); + this.saveSettingsDialog = new System.Windows.Forms.SaveFileDialog(); + this.label3 = new System.Windows.Forms.Label(); + this.sweetCounter = new System.Windows.Forms.NumericUpDown(); + this.ticketCounter = new System.Windows.Forms.NumericUpDown(); + this.label4 = new System.Windows.Forms.Label(); + this.inventoryStatsLabel = new System.Windows.Forms.Label(); + ((System.ComponentModel.ISupportInitialize)(this.configDataGrid)).BeginInit(); + this.tabs.SuspendLayout(); + this.controlTab.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit(); + this.splitContainer2.Panel1.SuspendLayout(); + this.splitContainer2.Panel2.SuspendLayout(); + this.splitContainer2.SuspendLayout(); + this.sandboxTab.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); + this.splitContainer1.Panel1.SuspendLayout(); + this.splitContainer1.Panel2.SuspendLayout(); + this.splitContainer1.SuspendLayout(); + this.newAccountPanel.SuspendLayout(); + this.inventoryTab.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.sweetCounter)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.ticketCounter)).BeginInit(); + this.SuspendLayout(); + // + // configDataGrid + // + this.configDataGrid.AllowUserToAddRows = false; + this.configDataGrid.AllowUserToDeleteRows = false; + this.configDataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.configDataGrid.Dock = System.Windows.Forms.DockStyle.Fill; + this.configDataGrid.Location = new System.Drawing.Point(0, 0); + this.configDataGrid.Name = "configDataGrid"; + this.configDataGrid.Size = new System.Drawing.Size(522, 210); + this.configDataGrid.TabIndex = 0; + // + // logInButton + // + this.logInButton.Location = new System.Drawing.Point(101, 6); + this.logInButton.Name = "logInButton"; + this.logInButton.Size = new System.Drawing.Size(50, 23); + this.logInButton.TabIndex = 1; + this.logInButton.Text = "Log In"; + this.logInButton.UseVisualStyleBackColor = true; + this.logInButton.Click += new System.EventHandler(this.logInButton_Click); + // + // logBox + // + this.logBox.Dock = System.Windows.Forms.DockStyle.Fill; + this.logBox.Location = new System.Drawing.Point(0, 0); + this.logBox.MaxLength = 1000000; + this.logBox.Multiline = true; + this.logBox.Name = "logBox"; + this.logBox.ReadOnly = true; + this.logBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.logBox.Size = new System.Drawing.Size(522, 207); + this.logBox.TabIndex = 0; + // + // tabs + // + this.tabs.Controls.Add(this.controlTab); + this.tabs.Controls.Add(this.sandboxTab); + this.tabs.Controls.Add(this.inventoryTab); + this.tabs.Dock = System.Windows.Forms.DockStyle.Fill; + this.tabs.Location = new System.Drawing.Point(0, 0); + this.tabs.Name = "tabs"; + this.tabs.SelectedIndex = 0; + this.tabs.Size = new System.Drawing.Size(542, 488); + this.tabs.TabIndex = 3; + // + // controlTab + // + this.controlTab.Controls.Add(this.loadSettingsButton); + this.controlTab.Controls.Add(this.saveSettingsButton); + this.controlTab.Controls.Add(this.newAccountPanel); + this.controlTab.Controls.Add(this.newAccountButton); + this.controlTab.Controls.Add(this.splitContainer2); + this.controlTab.Controls.Add(this.logInButton); + this.controlTab.Location = new System.Drawing.Point(4, 22); + this.controlTab.Name = "controlTab"; + this.controlTab.Padding = new System.Windows.Forms.Padding(3); + this.controlTab.Size = new System.Drawing.Size(534, 462); + this.controlTab.TabIndex = 0; + this.controlTab.Text = "Control Panel"; + this.controlTab.UseVisualStyleBackColor = true; + // + // newAccountButton + // + this.newAccountButton.Location = new System.Drawing.Point(6, 6); + this.newAccountButton.Name = "newAccountButton"; + this.newAccountButton.Size = new System.Drawing.Size(89, 23); + this.newAccountButton.TabIndex = 4; + this.newAccountButton.Text = "New Account"; + this.newAccountButton.UseVisualStyleBackColor = true; + this.newAccountButton.Click += new System.EventHandler(this.newAccountButton_Click); + // + // splitContainer2 + // + this.splitContainer2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.splitContainer2.Location = new System.Drawing.Point(6, 35); + this.splitContainer2.Name = "splitContainer2"; + this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // splitContainer2.Panel1 + // + this.splitContainer2.Panel1.Controls.Add(this.configDataGrid); + // + // splitContainer2.Panel2 + // + this.splitContainer2.Panel2.Controls.Add(this.logBox); + this.splitContainer2.Size = new System.Drawing.Size(522, 421); + this.splitContainer2.SplitterDistance = 210; + this.splitContainer2.TabIndex = 3; + // + // sandboxTab + // + this.sandboxTab.Controls.Add(this.sandboxSend); + this.sandboxTab.Controls.Add(this.label1); + this.sandboxTab.Controls.Add(this.sandboxURL); + this.sandboxTab.Controls.Add(this.splitContainer1); + this.sandboxTab.Controls.Add(this.deleteRadioButton); + this.sandboxTab.Controls.Add(this.putRadioButton); + this.sandboxTab.Controls.Add(this.postRadioButton); + this.sandboxTab.Controls.Add(this.getRadioButton); + this.sandboxTab.Location = new System.Drawing.Point(4, 22); + this.sandboxTab.Name = "sandboxTab"; + this.sandboxTab.Padding = new System.Windows.Forms.Padding(3); + this.sandboxTab.Size = new System.Drawing.Size(534, 462); + this.sandboxTab.TabIndex = 1; + this.sandboxTab.Text = "Miitomo API Sandbox"; + this.sandboxTab.UseVisualStyleBackColor = true; + // + // sandboxSend + // + this.sandboxSend.Location = new System.Drawing.Point(480, 25); + this.sandboxSend.Name = "sandboxSend"; + this.sandboxSend.Size = new System.Drawing.Size(48, 22); + this.sandboxSend.TabIndex = 7; + this.sandboxSend.Text = "Send"; + this.sandboxSend.UseVisualStyleBackColor = true; + this.sandboxSend.Click += new System.EventHandler(this.sandboxSend_Click); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(129, 8); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(52, 13); + this.label1.TabIndex = 6; + this.label1.Text = "Endpoint:"; + // + // sandboxURL + // + this.sandboxURL.Location = new System.Drawing.Point(132, 26); + this.sandboxURL.Name = "sandboxURL"; + this.sandboxURL.Size = new System.Drawing.Size(342, 20); + this.sandboxURL.TabIndex = 5; + // + // splitContainer1 + // + this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.splitContainer1.Location = new System.Drawing.Point(6, 52); + this.splitContainer1.Name = "splitContainer1"; + this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // splitContainer1.Panel1 + // + this.splitContainer1.Panel1.Controls.Add(this.sandboxInput); + // + // splitContainer1.Panel2 + // + this.splitContainer1.Panel2.Controls.Add(this.sandboxOutput); + this.splitContainer1.Size = new System.Drawing.Size(522, 404); + this.splitContainer1.SplitterDistance = 202; + this.splitContainer1.TabIndex = 4; + // + // sandboxInput + // + this.sandboxInput.Dock = System.Windows.Forms.DockStyle.Fill; + this.sandboxInput.Location = new System.Drawing.Point(0, 0); + this.sandboxInput.Multiline = true; + this.sandboxInput.Name = "sandboxInput"; + this.sandboxInput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.sandboxInput.Size = new System.Drawing.Size(522, 202); + this.sandboxInput.TabIndex = 0; + // + // sandboxOutput + // + this.sandboxOutput.Dock = System.Windows.Forms.DockStyle.Fill; + this.sandboxOutput.Location = new System.Drawing.Point(0, 0); + this.sandboxOutput.Multiline = true; + this.sandboxOutput.Name = "sandboxOutput"; + this.sandboxOutput.ReadOnly = true; + this.sandboxOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.sandboxOutput.Size = new System.Drawing.Size(522, 198); + this.sandboxOutput.TabIndex = 0; + // + // deleteRadioButton + // + this.deleteRadioButton.AutoSize = true; + this.deleteRadioButton.Location = new System.Drawing.Point(59, 29); + this.deleteRadioButton.Name = "deleteRadioButton"; + this.deleteRadioButton.Size = new System.Drawing.Size(67, 17); + this.deleteRadioButton.TabIndex = 3; + this.deleteRadioButton.Text = "DELETE"; + this.deleteRadioButton.UseVisualStyleBackColor = true; + // + // putRadioButton + // + this.putRadioButton.AutoSize = true; + this.putRadioButton.Location = new System.Drawing.Point(6, 29); + this.putRadioButton.Name = "putRadioButton"; + this.putRadioButton.Size = new System.Drawing.Size(47, 17); + this.putRadioButton.TabIndex = 2; + this.putRadioButton.Text = "PUT"; + this.putRadioButton.UseVisualStyleBackColor = true; + // + // postRadioButton + // + this.postRadioButton.AutoSize = true; + this.postRadioButton.Location = new System.Drawing.Point(59, 6); + this.postRadioButton.Name = "postRadioButton"; + this.postRadioButton.Size = new System.Drawing.Size(54, 17); + this.postRadioButton.TabIndex = 1; + this.postRadioButton.Text = "POST"; + this.postRadioButton.UseVisualStyleBackColor = true; + // + // getRadioButton + // + this.getRadioButton.AutoSize = true; + this.getRadioButton.Checked = true; + this.getRadioButton.Location = new System.Drawing.Point(6, 6); + this.getRadioButton.Name = "getRadioButton"; + this.getRadioButton.Size = new System.Drawing.Size(47, 17); + this.getRadioButton.TabIndex = 0; + this.getRadioButton.TabStop = true; + this.getRadioButton.Text = "GET"; + this.getRadioButton.UseVisualStyleBackColor = true; + // + // newAccountPanel + // + this.newAccountPanel.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; + this.newAccountPanel.Controls.Add(this.newAccountFinishButton); + this.newAccountPanel.Controls.Add(this.label2); + this.newAccountPanel.Controls.Add(this.authURLInput); + this.newAccountPanel.Location = new System.Drawing.Point(16, 45); + this.newAccountPanel.Name = "newAccountPanel"; + this.newAccountPanel.Size = new System.Drawing.Size(334, 47); + this.newAccountPanel.TabIndex = 5; + this.newAccountPanel.Visible = false; + // + // authURLInput + // + this.authURLInput.Location = new System.Drawing.Point(3, 20); + this.authURLInput.Name = "authURLInput"; + this.authURLInput.Size = new System.Drawing.Size(243, 20); + this.authURLInput.TabIndex = 0; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(4, 4); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(151, 13); + this.label2.TabIndex = 1; + this.label2.Text = "Paste \"OK\" Button Link Below"; + // + // newAccountFinishButton + // + this.newAccountFinishButton.Location = new System.Drawing.Point(252, 19); + this.newAccountFinishButton.Name = "newAccountFinishButton"; + this.newAccountFinishButton.Size = new System.Drawing.Size(75, 22); + this.newAccountFinishButton.TabIndex = 2; + this.newAccountFinishButton.Text = "Finish >>"; + this.newAccountFinishButton.UseVisualStyleBackColor = true; + this.newAccountFinishButton.Click += new System.EventHandler(this.newAccountFinishButton_Click); + // + // saveSettingsButton + // + this.saveSettingsButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.saveSettingsButton.Location = new System.Drawing.Point(432, 6); + this.saveSettingsButton.Name = "saveSettingsButton"; + this.saveSettingsButton.Size = new System.Drawing.Size(94, 23); + this.saveSettingsButton.TabIndex = 6; + this.saveSettingsButton.Text = "Save Settings"; + this.saveSettingsButton.UseVisualStyleBackColor = true; + this.saveSettingsButton.Click += new System.EventHandler(this.saveSettingsButton_Click); + // + // loadSettingsButton + // + this.loadSettingsButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.loadSettingsButton.Location = new System.Drawing.Point(332, 6); + this.loadSettingsButton.Name = "loadSettingsButton"; + this.loadSettingsButton.Size = new System.Drawing.Size(94, 23); + this.loadSettingsButton.TabIndex = 7; + this.loadSettingsButton.Text = "Load Settings"; + this.loadSettingsButton.UseVisualStyleBackColor = true; + this.loadSettingsButton.Click += new System.EventHandler(this.loadSettingsButton_Click); + // + // inventoryTab + // + this.inventoryTab.Controls.Add(this.inventoryStatsLabel); + this.inventoryTab.Controls.Add(this.label4); + this.inventoryTab.Controls.Add(this.ticketCounter); + this.inventoryTab.Controls.Add(this.sweetCounter); + this.inventoryTab.Controls.Add(this.label3); + this.inventoryTab.Controls.Add(this.uploadInventoryButton); + this.inventoryTab.Controls.Add(this.downloadInventoryButton); + this.inventoryTab.Location = new System.Drawing.Point(4, 22); + this.inventoryTab.Name = "inventoryTab"; + this.inventoryTab.Padding = new System.Windows.Forms.Padding(3); + this.inventoryTab.Size = new System.Drawing.Size(534, 462); + this.inventoryTab.TabIndex = 2; + this.inventoryTab.Text = "Inventory Editor"; + this.inventoryTab.UseVisualStyleBackColor = true; + // + // downloadInventoryButton + // + this.downloadInventoryButton.Location = new System.Drawing.Point(6, 6); + this.downloadInventoryButton.Name = "downloadInventoryButton"; + this.downloadInventoryButton.Size = new System.Drawing.Size(97, 23); + this.downloadInventoryButton.TabIndex = 0; + this.downloadInventoryButton.Text = "Download Data"; + this.downloadInventoryButton.UseVisualStyleBackColor = true; + this.downloadInventoryButton.Click += new System.EventHandler(this.downloadInventoryButton_Click); + // + // uploadInventoryButton + // + this.uploadInventoryButton.Enabled = false; + this.uploadInventoryButton.Location = new System.Drawing.Point(6, 35); + this.uploadInventoryButton.Name = "uploadInventoryButton"; + this.uploadInventoryButton.Size = new System.Drawing.Size(97, 23); + this.uploadInventoryButton.TabIndex = 1; + this.uploadInventoryButton.Text = "Upload Data"; + this.uploadInventoryButton.UseVisualStyleBackColor = true; + this.uploadInventoryButton.Click += new System.EventHandler(this.uploadInventoryButton_Click); + // + // loadSettingsDialog + // + this.loadSettingsDialog.Filter = "JSON files (*.json)|*.json|All files|*.*"; + this.loadSettingsDialog.Title = "Load ArchBreaker Settings"; + // + // saveSettingsDialog + // + this.saveSettingsDialog.Filter = "JSON files (*.json)|*.json|All files|*.*"; + this.saveSettingsDialog.Title = "Save ArchBreaker Settings"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(109, 11); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(45, 13); + this.label3.TabIndex = 2; + this.label3.Text = "Sweets:"; + // + // sweetCounter + // + this.sweetCounter.Location = new System.Drawing.Point(160, 9); + this.sweetCounter.Maximum = new decimal(new int[] { + 1000, + 0, + 0, + 0}); + this.sweetCounter.Name = "sweetCounter"; + this.sweetCounter.Size = new System.Drawing.Size(55, 20); + this.sweetCounter.TabIndex = 3; + // + // ticketCounter + // + this.ticketCounter.Location = new System.Drawing.Point(160, 38); + this.ticketCounter.Maximum = new decimal(new int[] { + 99, + 0, + 0, + 0}); + this.ticketCounter.Name = "ticketCounter"; + this.ticketCounter.Size = new System.Drawing.Size(55, 20); + this.ticketCounter.TabIndex = 4; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(109, 40); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(45, 13); + this.label4.TabIndex = 5; + this.label4.Text = "Tickets:"; + // + // inventoryStatsLabel + // + this.inventoryStatsLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.inventoryStatsLabel.Location = new System.Drawing.Point(230, 9); + this.inventoryStatsLabel.Name = "inventoryStatsLabel"; + this.inventoryStatsLabel.Size = new System.Drawing.Size(296, 49); + this.inventoryStatsLabel.TabIndex = 6; + this.inventoryStatsLabel.Text = "---"; + // + // IntroForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(542, 488); + this.Controls.Add(this.tabs); + this.Name = "IntroForm"; + this.Text = "ArchBreaker"; + ((System.ComponentModel.ISupportInitialize)(this.configDataGrid)).EndInit(); + this.tabs.ResumeLayout(false); + this.controlTab.ResumeLayout(false); + this.splitContainer2.Panel1.ResumeLayout(false); + this.splitContainer2.Panel2.ResumeLayout(false); + this.splitContainer2.Panel2.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit(); + this.splitContainer2.ResumeLayout(false); + this.sandboxTab.ResumeLayout(false); + this.sandboxTab.PerformLayout(); + this.splitContainer1.Panel1.ResumeLayout(false); + this.splitContainer1.Panel1.PerformLayout(); + this.splitContainer1.Panel2.ResumeLayout(false); + this.splitContainer1.Panel2.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); + this.splitContainer1.ResumeLayout(false); + this.newAccountPanel.ResumeLayout(false); + this.newAccountPanel.PerformLayout(); + this.inventoryTab.ResumeLayout(false); + this.inventoryTab.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.sweetCounter)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.ticketCounter)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + private System.Windows.Forms.DataGridView configDataGrid; + private System.Windows.Forms.Button logInButton; + private System.Windows.Forms.TextBox logBox; + private System.Windows.Forms.TabPage controlTab; + private System.Windows.Forms.TabPage sandboxTab; + private System.Windows.Forms.Button sandboxSend; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.TextBox sandboxURL; + private System.Windows.Forms.SplitContainer splitContainer1; + private System.Windows.Forms.TextBox sandboxInput; + private System.Windows.Forms.TextBox sandboxOutput; + private System.Windows.Forms.RadioButton deleteRadioButton; + private System.Windows.Forms.RadioButton putRadioButton; + private System.Windows.Forms.RadioButton postRadioButton; + private System.Windows.Forms.RadioButton getRadioButton; + private System.Windows.Forms.SplitContainer splitContainer2; + private System.Windows.Forms.Button newAccountButton; + private System.Windows.Forms.Panel newAccountPanel; + private System.Windows.Forms.Button newAccountFinishButton; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.TextBox authURLInput; + private System.Windows.Forms.Button loadSettingsButton; + private System.Windows.Forms.Button saveSettingsButton; + private System.Windows.Forms.TabPage inventoryTab; + private System.Windows.Forms.Button uploadInventoryButton; + private System.Windows.Forms.Button downloadInventoryButton; + private System.Windows.Forms.TabControl tabs; + private System.Windows.Forms.OpenFileDialog loadSettingsDialog; + private System.Windows.Forms.SaveFileDialog saveSettingsDialog; + private System.Windows.Forms.Label inventoryStatsLabel; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.NumericUpDown ticketCounter; + private System.Windows.Forms.NumericUpDown sweetCounter; + private System.Windows.Forms.Label label3; + } +} + diff --git a/IntroForm.cs b/IntroForm.cs new file mode 100755 index 0000000..a9d35e4 --- /dev/null +++ b/IntroForm.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Data; +using System.Drawing; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Forms; +using System.IO; +using System.Net; +using Newtonsoft.Json.Linq; + +namespace ArchBreaker +{ + public partial class IntroForm : Form + { + private ArchSession _session; + + public IntroForm() + { + InitializeComponent(); + + _session = new ArchSession(); + + _session.OnLog += (o, e) => + { + Log(e.Message); + }; + + configDataGrid.DataSource = _session.Config; + configDataGrid.Columns[0].Width = 140; + configDataGrid.Columns[1].Width = 300; + } + + private void Log(string text) + { + logBox.AppendText("\r\n" + text); + } + + private async void logInButton_Click(object sender, EventArgs e) + { + // Step 1: Log in with our account + var devAccount = _session.GetParam("NPFDeviceAccount").Value; + var devPassword = _session.GetParam("NPFDevicePassword").Value; + if (devAccount.Length == 0 || devPassword.Length == 0) + { + MessageBox.Show("No device account! You must create one first"); + return; + } + + var idToken = await _session.NPFLoginAsync(devAccount, devPassword); + Log(string.Format("Received ID Token: {0}[...]", idToken.Substring(0, 30))); + + var sessionId = await _session.AuthToMiitomoAsync(idToken); + Log("Login complete! Session ID obtained: " + sessionId); + + _session.GetParam("MiitomoSessionID").Value = sessionId; + } + + private async void sandboxSend_Click(object sender, EventArgs e) + { + string method = "GET"; + if (postRadioButton.Checked) + method = "POST"; + else if (putRadioButton.Checked) + method = "PUT"; + else if (deleteRadioButton.Checked) + method = "DELETE"; + + if (_session.GetParam("MiitomoSessionID").Value.Length == 0) + { + sandboxOutput.Text = "No cookie!"; + return; + } + + JObject payload = null; + if ((method == "POST" || method == "PUT") && sandboxInput.Text.Length > 0) + { + try + { + payload = JObject.Parse(sandboxInput.Text); + } catch (Exception ex) + { + sandboxOutput.Text = "Could not parse JSON:\r\n" + ex.ToString(); + return; + } + } + var result = await _session.CallMiitomoAPIAsync(sandboxURL.Text, method, payload); + if (result != null) + sandboxOutput.Text = result.ToString(); + } + + + private ArchSession.NewAccountResult _newAccountState = null; + private async void newAccountButton_Click(object sender, EventArgs e) + { + _newAccountState = await _session.CreateNewAccountAsync(); + Log("Open the following URL: " + _newAccountState.OAuthURL); + Log("\r\nWhen you see \"The above account will be linked, and Miitomo will begin. Select OK to proceed.\", right click on the OK button, copy the link it leads to, and paste it into the box above."); + + authURLInput.Text = ""; + newAccountPanel.Visible = true; + } + + private async void newAccountFinishButton_Click(object sender, EventArgs e) + { + var url = authURLInput.Text; + if (!url.StartsWith(Constants.RedirectURI)) + { + MessageBox.Show("That doesn't look right; the address should begin with " + Constants.RedirectURI); + return; + } + newAccountPanel.Visible = false; + + var authURLResult = await _session.HandleAuthURLAsync(url, _newAccountState); + if (authURLResult == null) + return; + + var accountToken = await _session.GetAccountTokenAsync(authURLResult.SessionToken); + Log(string.Format("Obtained target account info - id {0}", + accountToken.UserID)); + + await _session.CallMiitomoAPIAsync( + string.Format("/v1/platform_accounts/{0}/authorization_code", accountToken.UserID), + "POST", + new JObject { { "authorization_code", authURLResult.Code } }, + _newAccountState.MiitomoSessionID); + + Log("Miitomo platform account authorised successfully, doing federation now"); + + var newIdToken = await _session.DoFederationAsync( + accountToken.IDToken, + _newAccountState.NPFSessionID, + _newAccountState.OriginalUserID, + _newAccountState.DeviceAccount, + _newAccountState.DevicePassword); + + Log("Federation completed, new ID token obtained, getting new Miitomo session ID"); + + var newMiiSession = await _session.AuthToMiitomoAsync(newIdToken); + + Log("All done! Remember to save your settings so you don't lose them."); + + _session.GetParam("NPFDeviceAccount").Value = _newAccountState.DeviceAccount; + _session.GetParam("NPFDevicePassword").Value = _newAccountState.DevicePassword; + _session.GetParam("MiitomoSessionID").Value = newMiiSession; + configDataGrid.Refresh(); + } + + + + private void saveSettingsButton_Click(object sender, EventArgs e) + { + if (saveSettingsDialog.ShowDialog() != DialogResult.OK) + return; + + var jsonRoot = new JObject(); + foreach (var param in _session.Config) + jsonRoot[param.Key] = param.Value; + + File.WriteAllText(saveSettingsDialog.FileName, jsonRoot.ToString()); + } + + private void loadSettingsButton_Click(object sender, EventArgs e) + { + if (loadSettingsDialog.ShowDialog() != DialogResult.OK) + return; + + var jsonRoot = JObject.Parse(File.ReadAllText(loadSettingsDialog.FileName)); + foreach (var param in _session.Config) { + JToken value; + if (jsonRoot.TryGetValue(param.Key, out value)) + param.Value = value.ToObject(); + } + + configDataGrid.Refresh(); + } + + + + private JObject _stockItem; + + private async void downloadInventoryButton_Click(object sender, EventArgs e) + { + uploadInventoryButton.Enabled = false; + + _stockItem = await _session.CallMiitomoAPIAsync( + "/v1/player/stock_item", + "GET", null); + if (_stockItem == null) + { + MessageBox.Show("Error! You might need to log in again."); + return; + } + + var si = _stockItem["player"]["stock_item"]; + sweetCounter.Value = si["snack"].ToObject(); + ticketCounter.Value = si["game_ticket"].ToObject(); + + inventoryStatsLabel.Text = string.Format( + "JSON Version: {0}\r\n" + + "Levels: Popularity {1} / Style {2}\r\n" + + "{3} clothing item(s), {4} template(s), {5} background(s)", + + si["json_version"].ToObject(), + si["level_progress_popularity"].ToObject(), + si["level_progress_fashionability"].ToObject(), + (si["wears"] as JArray).Count, + (si["templates"] as JArray).Count, + (si["backgrounds"] as JArray).Count + ); + + uploadInventoryButton.Enabled = true; + } + + private async void uploadInventoryButton_Click(object sender, EventArgs e) + { + var root = _stockItem["player"] as JObject; + var si = root["stock_item"]; + + si["snack"] = (int)sweetCounter.Value; + si["game_ticket"] = (int)ticketCounter.Value; + + uploadInventoryButton.Enabled = false; + + var result = await _session.CallMiitomoAPIAsync( + "/v1/player/stock_item", + "PUT", root); + if (result == null) + MessageBox.Show("Error!"); + + uploadInventoryButton.Enabled = true; + } + } +} diff --git a/IntroForm.resx b/IntroForm.resx new file mode 100755 index 0000000..d367475 --- /dev/null +++ b/IntroForm.resx @@ -0,0 +1,126 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + 157, 17 + + \ No newline at end of file diff --git a/Program.cs b/Program.cs new file mode 100755 index 0000000..5896013 --- /dev/null +++ b/Program.cs @@ -0,0 +1,22 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace ArchBreaker +{ + static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new IntroForm()); + } + } +} diff --git a/Properties/AssemblyInfo.cs b/Properties/AssemblyInfo.cs new file mode 100755 index 0000000..b898805 --- /dev/null +++ b/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("ArchBreaker")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("ArchBreaker")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1961ba9d-8bdf-4dec-a7e5-f60469411e94")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/Properties/Resources.Designer.cs b/Properties/Resources.Designer.cs new file mode 100755 index 0000000..99f04ed --- /dev/null +++ b/Properties/Resources.Designer.cs @@ -0,0 +1,71 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ArchBreaker.Properties +{ + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources + { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() + { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager + { + get + { + if ((resourceMan == null)) + { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ArchBreaker.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture + { + get + { + return resourceCulture; + } + set + { + resourceCulture = value; + } + } + } +} diff --git a/Properties/Resources.resx b/Properties/Resources.resx new file mode 100755 index 0000000..ffecec8 --- /dev/null +++ b/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/Properties/Settings.Designer.cs b/Properties/Settings.Designer.cs new file mode 100755 index 0000000..b571869 --- /dev/null +++ b/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace ArchBreaker.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/Properties/Settings.settings b/Properties/Settings.settings new file mode 100755 index 0000000..abf36c5 --- /dev/null +++ b/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/packages.config b/packages.config new file mode 100755 index 0000000..15a8e56 --- /dev/null +++ b/packages.config @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file -- cgit v1.2.3