com.xd.sdk.account 7.9.2 → 7.9.4-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,6 +4,6 @@
4
4
  //
5
5
  // Created by Fattycat on 2023/4/14.
6
6
  //
7
- #define XDGAccount_VERSION @"7.9.0"
8
- #define XDSAccount_VERSION_CODE @"7090000"
9
- // HASH 1e690d3c
7
+ #define XDGAccount_VERSION @"7.9.3"
8
+ #define XDSAccount_VERSION_CODE @"7090300"
9
+ // HASH 717b29cd
@@ -26,16 +26,28 @@ namespace XD.SDK.Account.Internal.Standalone
26
26
  // 刷新 token
27
27
  private readonly static string XDG_COMMON_REFRESH = "api/login/v1/token/refresh";
28
28
 
29
- private static readonly Persistence persistence = new Persistence(Path.Combine(Application.persistentDataPath,
30
- XDGConstants.XD_PERSISTENCE_NAME,
31
- "access_token_v2"));
29
+ private static Persistence persistenceStorage;
30
+ private static Persistence persistence
31
+ {
32
+ get
33
+ {
34
+ if (persistenceStorage == null)
35
+ {
36
+ MigrateLegacy();
37
+ persistenceStorage = new Persistence(Path.Combine(XDStandaloneInstance.DataPath,
38
+ XDGConstants.XD_PERSISTENCE_NAME,
39
+ "access_token_v2"));
40
+ }
41
+ return persistenceStorage;
42
+ }
43
+ }
32
44
 
33
45
  public static XDGAccessToken local;
34
46
 
35
- static AccessTokenModule()
47
+ private static void MigrateLegacy()
36
48
  {
37
49
  // 迁移旧数据
38
- string v1Path = Path.Combine(Application.persistentDataPath,
50
+ string v1Path = Path.Combine(XDStandaloneInstance.DataPath,
39
51
  XDGConstants.XD_PERSISTENCE_NAME,
40
52
  "access_token");
41
53
  if (File.Exists(v1Path))
@@ -43,7 +55,7 @@ namespace XD.SDK.Account.Internal.Standalone
43
55
  // 迁移
44
56
  try
45
57
  {
46
- string v2Path = Path.Combine(Application.persistentDataPath,
58
+ string v2Path = Path.Combine(XDStandaloneInstance.DataPath,
47
59
  XDGConstants.XD_PERSISTENCE_NAME,
48
60
  "access_token_v2");
49
61
  string encryptedData =
@@ -0,0 +1,54 @@
1
+ #if UNITY_EDITOR || UNITY_STANDALONE
2
+ using System;
3
+ using UnityEngine;
4
+ using XD.SDK.Common;
5
+ using XD.SDK.Common.Internal;
6
+ using XD.SDK.Common.Internal.Standalone;
7
+
8
+ namespace XD.SDK.Account.Internal.Standalone
9
+ {
10
+ internal sealed class AccountRecordLogin
11
+ {
12
+ private readonly AccountRecordStore store;
13
+ private readonly AccountRecordStore.LoginSnapshot snapshot;
14
+
15
+ private AccountRecordLogin(AccountRecordStore store, AccountRecordStore.LoginSnapshot snapshot)
16
+ {
17
+ this.store = store;
18
+ this.snapshot = snapshot;
19
+ }
20
+
21
+ internal static AccountRecordLogin Begin(LoginType loginType)
22
+ {
23
+ #if UNITY_STANDALONE_WIN && !UNITY_EDITOR
24
+ try
25
+ {
26
+ // The current built-in authentication client uses the production CN/global host set.
27
+ var store = new AccountRecordStore(Application.persistentDataPath, ConfigModule.ClientId,
28
+ "prod", ConfigModule.IsGlobal ? "global" : "cn", XDStandaloneInstance.RunId);
29
+ bool interactive = loginType != LoginType.Default && !ConfigModule.UsingTapPC;
30
+ return new AccountRecordLogin(store, store.BeginLogin(interactive));
31
+ }
32
+ catch (Exception e) { Warn(e); }
33
+ #endif
34
+ return null;
35
+ }
36
+
37
+ internal void Complete(XDGUser user)
38
+ {
39
+ try
40
+ {
41
+ store.Remember(snapshot, user.UserId, user.NickName, user.Avatar, user.LoginType);
42
+ }
43
+ catch (Exception e) { Warn(e); }
44
+ }
45
+
46
+ private static void Warn(Exception exception)
47
+ {
48
+ // Do not log record payloads, tokens or exception messages containing user data/paths.
49
+ XDGLogger.Warn("Account memory write skipped (" + exception.GetType().Name + "); login unchanged.",
50
+ XDGLoggerTag.Account);
51
+ }
52
+ }
53
+ }
54
+ #endif
@@ -0,0 +1,11 @@
1
+ fileFormatVersion: 2
2
+ guid: 98d6ef6e42a44a56beec9cd00940a7f0
3
+ MonoImporter:
4
+ externalObjects: {}
5
+ serializedVersion: 2
6
+ defaultReferences: []
7
+ executionOrder: 0
8
+ icon: {instanceID: 0}
9
+ userData:
10
+ assetBundleName:
11
+ assetBundleVariant:
@@ -0,0 +1,221 @@
1
+ #if UNITY_EDITOR || UNITY_STANDALONE
2
+ using System;
3
+ using System.Collections.Generic;
4
+ using System.IO;
5
+ using System.Linq;
6
+ using System.Security.Cryptography;
7
+ using System.Text;
8
+ using System.Threading;
9
+ using Newtonsoft.Json;
10
+
11
+ namespace XD.SDK.Account.Internal.Standalone
12
+ {
13
+ // Account memory only. Never serialize XDGUser (or its Token) into this store.
14
+ internal sealed class AccountRecordStore
15
+ {
16
+ internal const int MaxRecordBytes = 64 * 1024;
17
+ private static readonly UTF8Encoding Utf8 = new UTF8Encoding(false, true);
18
+ private static int publishing;
19
+ private readonly string writerRunId;
20
+ internal string Scope { get; }
21
+ internal string Root { get; }
22
+
23
+ internal AccountRecordStore(string legacyRoot, string clientId, string environmentId,
24
+ string identityDomain, string writerRunId)
25
+ {
26
+ Scope = ScopeKey(clientId, environmentId, identityDomain);
27
+ Root = Path.GetFullPath(Path.Combine(legacyRoot, "xd_instances", "accounts", Scope));
28
+ // Include the temporary suffix, not just the final filename. Do not depend on
29
+ // the game's manifest, machine registry or Unity backend supporting long paths.
30
+ string longestPath = Path.Combine(Root, "records", new string('0', 32) + ".json.tmp");
31
+ if (longestPath.Length >= 260)
32
+ throw new PathTooLongException("Account memory path exceeds the Windows compatibility budget.");
33
+ this.writerRunId = writerRunId;
34
+ if (string.IsNullOrEmpty(writerRunId)) throw new ArgumentException("Missing writer identity.");
35
+ }
36
+
37
+ internal static string ScopeKey(string clientId, string environmentId, string identityDomain)
38
+ {
39
+ return HashFields("xd-account-scope-v1", clientId, environmentId, identityDomain);
40
+ }
41
+
42
+ internal static string AccountKey(string scope, string userId)
43
+ {
44
+ return HashFields("xd-account-key-v1", scope, userId);
45
+ }
46
+
47
+ private static string HashFields(params string[] fields)
48
+ {
49
+ using (var buffer = new MemoryStream())
50
+ {
51
+ foreach (string field in fields)
52
+ {
53
+ if (string.IsNullOrEmpty(field)) throw new ArgumentException("Empty account identity field.");
54
+ byte[] bytes = Utf8.GetBytes(field);
55
+ uint length = (uint)bytes.Length;
56
+ buffer.WriteByte((byte)(length >> 24));
57
+ buffer.WriteByte((byte)((length >> 16) & 0xff));
58
+ buffer.WriteByte((byte)((length >> 8) & 0xff));
59
+ buffer.WriteByte((byte)(length & 0xff));
60
+ buffer.Write(bytes, 0, bytes.Length);
61
+ }
62
+ using (var sha = SHA256.Create())
63
+ return BitConverter.ToString(sha.ComputeHash(buffer.ToArray())).Replace("-", "").ToLowerInvariant();
64
+ }
65
+ }
66
+
67
+ internal sealed class LoginSnapshot
68
+ {
69
+ private readonly string scope;
70
+ private readonly Dictionary<string, string[]> forgotten;
71
+ internal LoginSnapshot(string scope, Dictionary<string, string[]> forgotten)
72
+ {
73
+ this.scope = scope;
74
+ this.forgotten = forgotten;
75
+ }
76
+ internal string[] ForAccount(string expectedScope, string account)
77
+ {
78
+ if (scope != expectedScope) throw new InvalidOperationException("Account scope changed during login.");
79
+ string[] ids;
80
+ return forgotten.TryGetValue(account, out ids) ? (string[])ids.Clone() : new string[0];
81
+ }
82
+ }
83
+
84
+ // Capture BEFORE interactive authentication, when the final XD identity may still be unknown.
85
+ // Automatic login/import observes nothing: it must not resurrect a forgotten account.
86
+ internal LoginSnapshot BeginLogin(bool interactive)
87
+ {
88
+ var records = ReadRecords(); // Fail closed on unreadable/unknown records, including auto login.
89
+ var forgotten = new Dictionary<string, string[]>(StringComparer.Ordinal);
90
+ if (interactive)
91
+ foreach (var group in records.Where(r => r.Kind == "forget").GroupBy(r => r.AccountKey))
92
+ forgotten.Add(group.Key, group.Select(r => r.OperationId).OrderBy(id => id, StringComparer.Ordinal).ToArray());
93
+ return new LoginSnapshot(Scope, forgotten);
94
+ }
95
+
96
+ internal void Remember(LoginSnapshot snapshot, string userId, string nickname, string avatar, int loginType)
97
+ {
98
+ if (snapshot == null) throw new ArgumentNullException(nameof(snapshot));
99
+ string key = AccountKey(Scope, userId);
100
+ Publish(new Record { Kind = "remember", AccountKey = key, UserId = userId,
101
+ Nickname = nickname, Avatar = avatar, LoginType = loginType,
102
+ ObservedForgetIds = snapshot.ForAccount(Scope, key) });
103
+ }
104
+
105
+ // Internal primitive; there is deliberately no public account-list / forget API yet.
106
+ internal void Forget(string userId)
107
+ {
108
+ Publish(new Record { Kind = "forget", AccountKey = AccountKey(Scope, userId) });
109
+ }
110
+
111
+ internal List<Record> ReadAccounts()
112
+ {
113
+ var result = new List<Record>();
114
+ foreach (var group in ReadRecords().GroupBy(r => r.AccountKey))
115
+ {
116
+ var forgets = group.Where(r => r.Kind == "forget").Select(r => r.OperationId).ToArray();
117
+ var latest = group.Where(r => r.Kind == "remember" &&
118
+ forgets.All(id => r.ObservedForgetIds.Contains(id)))
119
+ .OrderByDescending(r => r.OccurredAtUtc).ThenByDescending(r => r.OperationId, StringComparer.Ordinal)
120
+ .FirstOrDefault();
121
+ if (latest != null) result.Add(latest);
122
+ }
123
+ return result;
124
+ }
125
+
126
+ private List<Record> ReadRecords()
127
+ {
128
+ var result = new List<Record>();
129
+ string recordsPath = Path.Combine(Root, "records");
130
+ if (!Directory.Exists(recordsPath)) return result;
131
+ foreach (string path in Directory.EnumerateFiles(recordsPath, "*.json", SearchOption.TopDirectoryOnly))
132
+ {
133
+ // Concurrent publishers can exceed the soft admission count. Existing records
134
+ // must remain readable; only subsequent publication is stopped by CheckBudget.
135
+ if (new FileInfo(path).Length > MaxRecordBytes)
136
+ throw new IOException("Account record read budget exceeded.");
137
+ var record = JsonConvert.DeserializeObject<Record>(File.ReadAllText(path, Utf8));
138
+ if (record == null || record.SchemaVersion != 1 || record.AccountScope != Scope ||
139
+ (record.Kind != "remember" && record.Kind != "forget") ||
140
+ string.IsNullOrEmpty(record.OperationId) || string.IsNullOrEmpty(record.AccountKey) ||
141
+ Path.GetFileNameWithoutExtension(path) != record.OperationId ||
142
+
143
+ (record.Kind == "remember" && (record.ObservedForgetIds == null ||
144
+ AccountKey(Scope, record.UserId) != record.AccountKey)))
145
+ throw new IOException("Unrecognized account record; source retained.");
146
+ result.Add(record);
147
+ }
148
+ return result;
149
+ }
150
+
151
+ private void Publish(Record record)
152
+ {
153
+ // A non-waiting process-local admission gate, not a shared file/OS lock.
154
+ if (Interlocked.CompareExchange(ref publishing, 1, 0) != 0)
155
+ throw new IOException("Account record publisher is busy.");
156
+ string temporary = null;
157
+ try
158
+ {
159
+ ReadRecords(); // Do not append into an unknown format.
160
+ record.SchemaVersion = 1;
161
+ record.AccountScope = Scope;
162
+ record.OperationId = Guid.NewGuid().ToString("N");
163
+ record.WriterRunId = writerRunId;
164
+ record.OccurredAtUtc = DateTime.UtcNow.Ticks;
165
+ byte[] data = Utf8.GetBytes(JsonConvert.SerializeObject(record));
166
+ if (data.Length > MaxRecordBytes) throw new IOException("Account record is too large.");
167
+ CheckBudget(data.Length, record.Kind == "forget");
168
+ // The account key is in the record; avoid a redundant 64-character directory.
169
+ string directory = Path.Combine(Root, "records");
170
+ Directory.CreateDirectory(directory);
171
+ string destination = Path.Combine(directory, record.OperationId + ".json");
172
+ temporary = destination + ".tmp";
173
+ using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None))
174
+ {
175
+ stream.Write(data, 0, data.Length);
176
+ stream.Flush();
177
+ }
178
+ File.Move(temporary, destination); // Unique immutable destination; readers ignore .tmp.
179
+ temporary = null;
180
+ }
181
+ finally
182
+ {
183
+ try { if (temporary != null && File.Exists(temporary)) File.Delete(temporary); }
184
+ finally { Interlocked.Exchange(ref publishing, 0); }
185
+ }
186
+ }
187
+
188
+ private void CheckBudget(int incomingBytes, bool forget)
189
+ {
190
+ long bytes = incomingBytes;
191
+ int operations = 1;
192
+ if (Directory.Exists(Root))
193
+ foreach (string path in Directory.EnumerateFiles(Root, "*", SearchOption.AllDirectories))
194
+ {
195
+ if (path.EndsWith(".tmp", StringComparison.Ordinal)) continue;
196
+ bytes += new FileInfo(path).Length;
197
+ if (path.EndsWith(".json", StringComparison.Ordinal)) operations++;
198
+ }
199
+ if (bytes > (forget ? 17L : 16L) * 1024 * 1024 || operations > (forget ? 4352 : 4096))
200
+ throw new IOException("Account memory budget exceeded; existing records retained.");
201
+ }
202
+
203
+ [JsonObject(MemberSerialization.OptIn)]
204
+ internal sealed class Record
205
+ {
206
+ [JsonProperty("schemaVersion")] public int SchemaVersion;
207
+ [JsonProperty("kind")] public string Kind;
208
+ [JsonProperty("operationId")] public string OperationId;
209
+ [JsonProperty("accountScope")] public string AccountScope;
210
+ [JsonProperty("accountKey")] public string AccountKey;
211
+ [JsonProperty("writerRunId")] public string WriterRunId;
212
+ [JsonProperty("occurredAtUtc")] public long OccurredAtUtc;
213
+ [JsonProperty("userId", NullValueHandling = NullValueHandling.Ignore)] public string UserId;
214
+ [JsonProperty("nickname", NullValueHandling = NullValueHandling.Ignore)] public string Nickname;
215
+ [JsonProperty("avatar", NullValueHandling = NullValueHandling.Ignore)] public string Avatar;
216
+ [JsonProperty("loginType", NullValueHandling = NullValueHandling.Ignore)] public int? LoginType;
217
+ [JsonProperty("observedForgetIds", NullValueHandling = NullValueHandling.Ignore)] public string[] ObservedForgetIds;
218
+ }
219
+ }
220
+ }
221
+ #endif
@@ -0,0 +1,11 @@
1
+ fileFormatVersion: 2
2
+ guid: 4e9bd2c024074ea5b1669e9225b21fbb
3
+ MonoImporter:
4
+ externalObjects: {}
5
+ serializedVersion: 2
6
+ defaultReferences: []
7
+ executionOrder: 0
8
+ icon: {instanceID: 0}
9
+ userData:
10
+ assetBundleName:
11
+ assetBundleVariant:
@@ -44,167 +44,68 @@ namespace XD.SDK.Account.Internal.Standalone
44
44
  }
45
45
 
46
46
  internal static async Task<Dictionary<string, object>> WaitForFirstCallbackAsync(
47
- List<HttpListener> servers,
48
- LoginType loginType,
49
- string state,
50
- Func<Task<Dictionary<string, object>>> httpFallback)
47
+ HttpListener server, LoginType loginType, string state,
48
+ Func<Task<Dictionary<string, object>>> httpFallback, Action openBrowser)
51
49
  {
52
- if (string.IsNullOrEmpty(state))
53
- {
54
- // state 缺失时无法做会话隔离:直接走 http
55
- return httpFallback != null
56
- ? await httpFallback()
57
- : new Dictionary<string, object> { { "type", (int)loginType } };
58
- }
59
-
60
- var deepLinkTcs = new TaskCompletionSource<Dictionary<string, object>>(
50
+ var deepLink = new TaskCompletionSource<Dictionary<string, object>>(
61
51
  TaskCreationOptions.RunContinuationsAsynchronously);
62
- var cleaned = 0;
63
-
64
- void StopAllListeners()
65
- {
66
- try
67
- {
68
- foreach (var svr in servers)
69
- {
70
- svr.Stop();
71
- }
72
- servers.Clear();
73
- }
74
- catch
75
- {
76
- // ignore
77
- }
78
- }
79
-
52
+ var quitting = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
53
+ Action onQuit = () => quitting.TrySetResult(true);
54
+ Task<Dictionary<string, object>> httpTask = null;
80
55
  #if UNITY_STANDALONE_WIN && !UNITY_EDITOR
81
- Action<string> onDeepLink = deepLinkUrl =>
56
+ string redirect = TryGetRedirectScheme();
57
+ Action<string> onDeepLink = url =>
82
58
  {
83
- if (string.IsNullOrEmpty(deepLinkUrl)) return;
84
-
85
- XDGLogger.Debug($"[Auth][DeepLink] url: {RedactAuthUrl(deepLinkUrl)}", XDGLoggerTag.Account);
86
-
87
- // 不用 new Uri(),直接截取 query,避免 Uri 对自定义 scheme 做编码归一化
88
- int qIdx = deepLinkUrl.IndexOf('?');
89
- if (qIdx < 0 || qIdx >= deepLinkUrl.Length - 1) return;
90
-
91
- int fragIdx = deepLinkUrl.IndexOf('#', qIdx);
92
- string query = fragIdx >= 0
93
- ? deepLinkUrl.Substring(qIdx + 1, fragIdx - qIdx - 1)
94
- : deepLinkUrl.Substring(qIdx + 1);
95
-
96
- if (string.IsNullOrEmpty(query)) return;
97
-
98
- var parsed = WebAuth.ParseQueryStringToDict(query);
99
- var authData = new Dictionary<string, object> { { "type", (int)loginType } };
100
- foreach (var kv in parsed) authData[kv.Key] = kv.Value;
101
-
102
- if (!authData.TryGetValue(StateKey, out object st) || (st?.ToString() != state))
59
+ if (string.IsNullOrEmpty(redirect) || string.IsNullOrEmpty(url)
60
+ || !url.StartsWith(redirect + "?", StringComparison.Ordinal)) return;
61
+ int fragment = url.IndexOf('#');
62
+ string query = fragment < 0 ? url.Substring(redirect.Length + 1)
63
+ : url.Substring(redirect.Length + 1, fragment - redirect.Length - 1);
64
+ if (!LocalServerUtils.MatchesState(query, state)) return;
65
+ try
103
66
  {
104
- XDGLogger.Debug($"[Auth][DeepLink] state mismatch, expected: {state}, got: {st}", XDGLoggerTag.Account);
105
- return;
67
+ var data = WebAuth.ParseQueryStringToDict(query);
68
+ data["type"] = (int)loginType;
69
+ deepLink.TrySetResult(data);
106
70
  }
107
- AliyunTrack.LoginAuthorizeSuccess();
108
- deepLinkTcs.TrySetResult(authData);
71
+ catch (UriFormatException) { }
109
72
  };
110
-
111
73
  StandaloneDeepLinkReceiver.OnDeepLinkReceived += onDeepLink;
112
74
  #endif
113
-
114
- var httpTask = httpFallback != null
115
- ? httpFallback()
116
- : Task.FromResult(new Dictionary<string, object> { { "type", (int)loginType } });
117
-
118
- var timeout = Task.Delay(TimeSpan.FromMinutes(2));
119
- var done = await Task.WhenAny(deepLinkTcs.Task, httpTask, timeout);
120
-
121
- try
75
+ Application.quitting += onQuit;
76
+ using (var timeoutCancellation = new CancellationTokenSource())
122
77
  {
123
- if (done == deepLinkTcs.Task)
78
+ try
124
79
  {
125
- XDGLogger.Debug("[Auth] Callback channel: DeepLink", XDGLoggerTag.Account);
126
- XDGLogger.Debug("[Auth] DeepLink auth succeeded (won race)", XDGLoggerTag.Account);
127
- StopAllListeners();
128
- return await deepLinkTcs.Task;
80
+ httpTask = httpFallback();
81
+ var timeout = Task.Delay(TimeSpan.FromMinutes(2), timeoutCancellation.Token);
82
+ openBrowser();
83
+ var done = await Task.WhenAny(deepLink.Task, httpTask, timeout, quitting.Task);
84
+ if (done == quitting.Task) throw new TaskCanceledException();
85
+ if (done == timeout) throw new TimeoutException("OAuth callback timed out.");
86
+ var result = await (done == deepLink.Task ? deepLink.Task : httpTask);
87
+ #if UNITY_STANDALONE_WIN && !UNITY_EDITOR
88
+ if (done == deepLink.Task) StandaloneDeepLinkReceiver.ActivateCurrentWindow();
89
+ #endif
90
+ AliyunTrack.LoginAuthorizeSuccess();
91
+ return result;
129
92
  }
130
-
131
- if (done == httpTask)
132
- {
133
- XDGLogger.Debug("[Auth] Callback channel: HttpListener", XDGLoggerTag.Account);
134
- XDGLogger.Debug("[Auth] HTTP auth succeeded (won race)", XDGLoggerTag.Account);
135
- return await httpTask;
136
- }
137
-
138
- XDGLogger.Debug("[Auth] Auth timeout (2min)", XDGLoggerTag.Account);
139
- StopAllListeners();
140
- return new Dictionary<string, object> { { "type", (int)loginType } };
141
- }
142
- finally
143
- {
144
- if (Interlocked.CompareExchange(ref cleaned, 1, 0) == 0)
93
+ finally
145
94
  {
95
+ timeoutCancellation.Cancel();
96
+ Application.quitting -= onQuit;
146
97
  #if UNITY_STANDALONE_WIN && !UNITY_EDITOR
147
- try
148
- {
149
- StandaloneDeepLinkReceiver.OnDeepLinkReceived -= onDeepLink;
150
- }
151
- catch
98
+ StandaloneDeepLinkReceiver.OnDeepLinkReceived -= onDeepLink;
99
+ #endif
100
+ server.Close();
101
+ // Observe the HTTP loser after closing its listener; never stop another request's server.
102
+ if (httpTask != null)
152
103
  {
153
- // ignore
104
+ try { await httpTask; }
105
+ catch (Exception) { }
154
106
  }
155
- #endif
156
- }
157
- }
158
- }
159
-
160
- private static string RedactAuthUrl(string url)
161
- {
162
- if (string.IsNullOrEmpty(url))
163
- {
164
- return url;
165
- }
166
-
167
- int queryIndex = url.IndexOf('?');
168
- if (queryIndex < 0 || queryIndex >= url.Length - 1)
169
- {
170
- return url;
171
- }
172
-
173
- string prefix = url.Substring(0, queryIndex + 1);
174
- string query = url.Substring(queryIndex + 1);
175
- string[] pairs = query.Split('&');
176
- for (int i = 0; i < pairs.Length; i++)
177
- {
178
- string pair = pairs[i];
179
- int equalIndex = pair.IndexOf('=');
180
- if (equalIndex <= 0)
181
- {
182
- continue;
183
- }
184
-
185
- string key = pair.Substring(0, equalIndex);
186
- if (IsSensitiveQueryKey(key))
187
- {
188
- pairs[i] = $"{key}=<redacted>";
189
107
  }
190
108
  }
191
-
192
- return prefix + string.Join("&", pairs);
193
- }
194
-
195
- private static bool IsSensitiveQueryKey(string key)
196
- {
197
- if (string.IsNullOrEmpty(key))
198
- {
199
- return false;
200
- }
201
-
202
- return key.Equals("code", StringComparison.OrdinalIgnoreCase) ||
203
- key.Equals("token", StringComparison.OrdinalIgnoreCase) ||
204
- key.Equals("access_token", StringComparison.OrdinalIgnoreCase) ||
205
- key.Equals("refresh_token", StringComparison.OrdinalIgnoreCase) ||
206
- key.Equals("id_token", StringComparison.OrdinalIgnoreCase) ||
207
- key.IndexOf("token", StringComparison.OrdinalIgnoreCase) >= 0;
208
109
  }
209
110
  }
210
111
  }
@@ -40,7 +40,7 @@ namespace XD.SDK.Account.Internal.Standalone
40
40
  LoginType loginType,
41
41
  Dictionary<string, object> queryParams)
42
42
  {
43
- string redirectUri = $"http://{IPAddress.Loopback}:{LocalServerUtils.GetRandomUnusedPort()}";
43
+ string redirectUri;
44
44
  string gameName = ConfigModule.GameName;
45
45
  string lang = XDLocalization.GetLanguageKey();
46
46
 
@@ -49,7 +49,6 @@ namespace XD.SDK.Account.Internal.Standalone
49
49
  string urlSchemeRedirect = UrlSchemeAuth.TryGetRedirectScheme();
50
50
  Dictionary<string, object> queryParameters = new Dictionary<string, object>
51
51
  {
52
- { "redirect_uri", redirectUri },
53
52
  { "game_name", gameName },
54
53
  { "lang", lang },
55
54
 
@@ -88,100 +87,43 @@ namespace XD.SDK.Account.Internal.Standalone
88
87
  queryParameters[UrlSchemeAuth.RedirectSchemeKey] = urlSchemeRedirect;
89
88
  }
90
89
 
91
- // 注意:redirect_scheme 的值包含 ://,必须单独对 query 做编码,否则 authRequest 会被破坏
92
- string authRequest = $"{url}?{XDUrlUtils.ToQueryString(queryParameters)}";
93
-
94
- // 弹出授权页
95
- XDGLogger.Debug($"[Auth] url: {url}", XDGLoggerTag.Account);
96
- XDGLogger.Debug($"[Auth] state: {state}", XDGLoggerTag.Account);
97
- XDGLogger.Debug($"[Auth] urlSchemeRedirect: {urlSchemeRedirect}", XDGLoggerTag.Account);
98
- XDGLogger.Debug($"[Auth] redirectUri(http): {redirectUri}", XDGLoggerTag.Account);
99
- XDGLogger.Debug($"[Auth] authRequest: {authRequest}", XDGLoggerTag.Account);
100
- AliyunTrack.LoginAuthorize();
101
- // authRequest 的 query 已经过 XDUrlUtils.ToQueryString 编码,避免二次转义导致参数异常
102
- Application.OpenURL(authRequest);
103
-
104
- // 启动监听
105
- HttpListener server = new HttpListener();
106
- server.Prefixes.Add($"{redirectUri}/");
107
- server.Start();
108
-
90
+ if (string.IsNullOrEmpty(state)) throw new ArgumentException("OAuth state is required.");
91
+ var server = LocalServerUtils.StartLoopbackListener(out redirectUri);
109
92
  servers.Add(server);
110
-
111
- // UrlScheme 竞速需要同时满足:平台支持 + scheme 可用 + state 存在(用于会话隔离)
112
- // state 为空时直接走 HttpListener 兜底(UrlSchemeAuth 内部也会检查并回退)
113
- Task<Dictionary<string, object>> HttpFallback()
93
+ try
114
94
  {
115
- return WaitForHttpCallbackAsync(servers, server, loginType);
95
+ queryParameters["redirect_uri"] = redirectUri;
96
+ string authRequest = $"{url}?{XDUrlUtils.ToQueryString(queryParameters)}";
97
+ AliyunTrack.LoginAuthorize();
98
+ // Install both callbacks before opening the browser, including synchronous redirects.
99
+ return await UrlSchemeAuth.WaitForFirstCallbackAsync(server, loginType, state,
100
+ () => WaitForHttpCallbackAsync(server, loginType, state),
101
+ () => Application.OpenURL(authRequest));
102
+ }
103
+ finally
104
+ {
105
+ server.Close();
106
+ servers.Remove(server);
116
107
  }
117
-
118
- return await UrlSchemeAuth.WaitForFirstCallbackAsync(
119
- servers,
120
- loginType,
121
- state,
122
- HttpFallback);
123
108
  }
124
109
 
125
110
  private static async Task<Dictionary<string, object>> WaitForHttpCallbackAsync(
126
- List<HttpListener> servers,
127
- HttpListener server,
128
- LoginType loginType)
111
+ HttpListener server, LoginType loginType, string state)
129
112
  {
130
- Dictionary<string, object> authData = new Dictionary<string, object>
131
- {
132
- { "type", (int)loginType }
133
- };
134
-
135
113
  while (true)
136
114
  {
137
- try
138
- {
139
- HttpListenerContext context = await server.GetContextAsync();
140
-
141
- XDGLogger.Debug($"Request url: {context.Request.RawUrl}", XDGLoggerTag.Account);
142
- XDGLogger.Debug($"Request method: {context.Request.HttpMethod}", XDGLoggerTag.Account);
143
-
144
- context.Response.StatusCode = 200;
145
- context.Response.Close();
146
-
147
- if (context.Request.HttpMethod == "OPTIONS")
148
- {
149
- continue;
150
- }
151
-
152
- foreach (HttpListener svr in servers)
153
- {
154
- svr.Stop();
155
- }
156
-
157
- servers.Clear();
158
-
159
- string[] urlSegments = context.Request.RawUrl.Split('?');
160
- if (urlSegments.Length < 2)
161
- {
162
- return authData;
163
- }
164
-
165
- var dict = ParseQueryStringToDict(urlSegments[1]);
166
- foreach (var kv in dict)
167
- {
168
- authData[kv.Key] = kv.Value;
169
- }
170
-
171
- AliyunTrack.LoginAuthorizeSuccess();
172
- return authData;
173
- }
174
- catch (Exception e)
175
- {
176
- XDGLogger.Debug(e.Message, XDGLoggerTag.Account);
177
- // 异常结果则一直 pending(保持原行为)
178
- AliyunTrack.LoginAuthorizeFail(e.Message);
179
- TaskCompletionSource<Dictionary<string, object>> pending_tcs =
180
- new TaskCompletionSource<Dictionary<string, object>>();
181
- return await pending_tcs.Task;
182
- }
115
+ var context = await server.GetContextAsync();
116
+ bool valid = context.Request.HttpMethod == "GET"
117
+ && context.Request.Url.AbsolutePath == "/"
118
+ && LocalServerUtils.MatchesState(context.Request.Url.Query, state);
119
+ context.Response.StatusCode = valid || context.Request.HttpMethod == "OPTIONS" ? 200 : 400;
120
+ context.Response.Close();
121
+ if (!valid) continue;
122
+ var authData = ParseQueryStringToDict(context.Request.Url.Query.TrimStart('?'));
123
+ authData["type"] = (int)loginType;
124
+ return authData;
183
125
  }
184
126
  }
185
127
  }
186
128
  }
187
- #endif
129
+ #endif
@@ -62,16 +62,28 @@ namespace XD.SDK.Account.Internal.Standalone
62
62
  // 个人信息页
63
63
  public static readonly string XDG_PERSONAL_INFO = "/personal-info";
64
64
 
65
- private static readonly Persistence persistence = new Persistence(Path.Combine(Application.persistentDataPath,
66
- XDGConstants.XD_PERSISTENCE_NAME,
67
- "user_v2"));
65
+ private static Persistence persistenceStorage;
66
+ private static Persistence persistence
67
+ {
68
+ get
69
+ {
70
+ if (persistenceStorage == null)
71
+ {
72
+ MigrateLegacy();
73
+ persistenceStorage = new Persistence(Path.Combine(XDStandaloneInstance.DataPath,
74
+ XDGConstants.XD_PERSISTENCE_NAME,
75
+ "user_v2"));
76
+ }
77
+ return persistenceStorage;
78
+ }
79
+ }
68
80
 
69
81
  public static XDGUser current = null;
70
82
 
71
- static UserModule()
83
+ private static void MigrateLegacy()
72
84
  {
73
85
  // 迁移旧数据
74
- string v1Path = Path.Combine(Application.persistentDataPath,
86
+ string v1Path = Path.Combine(XDStandaloneInstance.DataPath,
75
87
  XDGConstants.XD_PERSISTENCE_NAME,
76
88
  "user");
77
89
  if (File.Exists(v1Path))
@@ -79,7 +91,7 @@ namespace XD.SDK.Account.Internal.Standalone
79
91
  // 迁移
80
92
  try
81
93
  {
82
- string v2Path = Path.Combine(Application.persistentDataPath,
94
+ string v2Path = Path.Combine(XDStandaloneInstance.DataPath,
83
95
  XDGConstants.XD_PERSISTENCE_NAME,
84
96
  "user_v2");
85
97
  string encryptedData = EncryptionUtils.Encrypt(File.ReadAllText(v1Path), SystemInfo.deviceUniqueIdentifier);
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "com.xd.sdk.account",
3
3
  "displayName": "XDGSDK Account",
4
- "version": "7.9.2",
4
+ "version": "7.9.4-beta.1",
5
5
  "description": "XDGSDK",
6
6
  "unity": "2019.3",
7
7
  "license": "MIT",
8
8
  "dependencies": {
9
- "com.xd.sdk.common": "7.9.2"
9
+ "com.xd.sdk.common": "7.9.4-beta.1"
10
10
  }
11
11
  }