summaryrefslogtreecommitdiff
path: root/archived/projt-launcher/launcher/minecraft/auth/steps/DeviceCodeAuthStep.cpp
blob: 48433e81f6704d85ec40e3a4fa6933075a64e314 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: 2026 Project Tick
// SPDX-FileContributor: Project Tick Team
/*
 *  ProjT Launcher - Minecraft Launcher
 *  Copyright (C) 2026 Project Tick
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, version 3.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, write to the Free Software Foundation,
 *  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */

#include "DeviceCodeAuthStep.hpp"

#include <QDateTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonParseError>
#include <QUrlQuery>

#include "Application.h"
#include "Json.h"
#include "net/RawHeaderProxy.h"

namespace projt::minecraft::auth
{

	namespace
	{

		// Device authorization endpoints
		constexpr auto kDeviceCodeUrl = "https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode";
		constexpr auto kTokenUrl	  = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token";

		/**
		 * Parse device code response from Microsoft.
		 */
		struct DeviceCodeResponse
		{
			QString deviceCode;
			QString userCode;
			QString verificationUri;
			int expiresIn = 0;
			int interval  = 5;
			QString error;
			QString errorDescription;

			[[nodiscard]] bool isValid() const noexcept
			{
				return !deviceCode.isEmpty() && !userCode.isEmpty() && !verificationUri.isEmpty() && expiresIn > 0;
			}
		};

		[[nodiscard]] DeviceCodeResponse parseDeviceCodeResponse(const QByteArray& data)
		{
			QJsonParseError err;
			const auto doc = QJsonDocument::fromJson(data, &err);
			if (err.error != QJsonParseError::NoError || !doc.isObject())
			{
				qWarning() << "Failed to parse device code response:" << err.errorString();
				return {};
			}

			const auto obj = doc.object();
			return { Json::ensureString(obj, "device_code"),	  Json::ensureString(obj, "user_code"),
					 Json::ensureString(obj, "verification_uri"), Json::ensureInteger(obj, "expires_in"),
					 Json::ensureInteger(obj, "interval", 5),	  Json::ensureString(obj, "error"),
					 Json::ensureString(obj, "error_description") };
		}

		/**
		 * Parse token response from Microsoft.
		 */
		struct TokenResponse
		{
			QString accessToken;
			QString tokenType;
			QString refreshToken;
			int expiresIn = 0;
			QString error;
			QString errorDescription;
			QVariantMap metadata;

			[[nodiscard]] bool isSuccess() const noexcept
			{
				return !accessToken.isEmpty();
			}
			[[nodiscard]] bool isPending() const noexcept
			{
				return error == QStringLiteral("authorization_pending");
			}
			[[nodiscard]] bool needsSlowDown() const noexcept
			{
				return error == QStringLiteral("slow_down");
			}
		};

		[[nodiscard]] TokenResponse parseTokenResponse(const QByteArray& data)
		{
			QJsonParseError err;
			const auto doc = QJsonDocument::fromJson(data, &err);
			if (err.error != QJsonParseError::NoError || !doc.isObject())
			{
				qWarning() << "Failed to parse token response:" << err.errorString();
				return {};
			}

			const auto obj = doc.object();
			return { Json::ensureString(obj, "access_token"),
					 Json::ensureString(obj, "token_type"),
					 Json::ensureString(obj, "refresh_token"),
					 Json::ensureInteger(obj, "expires_in"),
					 Json::ensureString(obj, "error"),
					 Json::ensureString(obj, "error_description"),
					 obj.toVariantMap() };
		}

	} // namespace

	DeviceCodeAuthStep::DeviceCodeAuthStep(Credentials& credentials) noexcept
		: Step(credentials),
		  m_clientId(APPLICATION->getMSAClientID())
	{
		m_pollTimer.setTimerType(Qt::VeryCoarseTimer);
		m_pollTimer.setSingleShot(true);
		m_expirationTimer.setTimerType(Qt::VeryCoarseTimer);
		m_expirationTimer.setSingleShot(true);

		connect(&m_expirationTimer, &QTimer::timeout, this, &DeviceCodeAuthStep::cancel);
		connect(&m_pollTimer, &QTimer::timeout, this, &DeviceCodeAuthStep::pollForCompletion);
	}

	QString DeviceCodeAuthStep::description() const
	{
		return tr("Logging in with Microsoft account (device code).");
	}

	void DeviceCodeAuthStep::execute()
	{
		QUrlQuery query;
		query.addQueryItem(QStringLiteral("client_id"), m_clientId);
		query.addQueryItem(QStringLiteral("scope"), QStringLiteral("XboxLive.SignIn XboxLive.offline_access"));

		const auto payload = query.query(QUrl::FullyEncoded).toUtf8();
		const QUrl url(QString::fromLatin1(kDeviceCodeUrl));

		const auto headers = QList<Net::HeaderPair>{ { "Content-Type", "application/x-www-form-urlencoded" },
													 { "Accept", "application/json" } };

		m_response = std::make_shared<QByteArray>();
		m_request  = Net::Upload::makeByteArray(url, m_response, payload);
		m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));

		m_task = NetJob::Ptr::create(QStringLiteral("DeviceCodeRequest"), APPLICATION->network());
		m_task->setAskRetry(false);
		m_task->addNetAction(m_request);

		connect(m_task.get(), &Task::finished, this, &DeviceCodeAuthStep::onDeviceCodeReceived);
		m_task->start();
	}

	void DeviceCodeAuthStep::cancel() noexcept
	{
		m_cancelled = true;
		m_expirationTimer.stop();
		m_pollTimer.stop();

		if (m_request)
		{
			m_request->abort();
		}

		emit completed(StepResult::HardFailure, tr("Authentication cancelled or timed out."));
	}

	void DeviceCodeAuthStep::onDeviceCodeReceived()
	{
		const auto rsp = parseDeviceCodeResponse(*m_response);

		if (!rsp.error.isEmpty())
		{
			const QString msg = rsp.errorDescription.isEmpty() ? rsp.error : rsp.errorDescription;
			emit completed(StepResult::HardFailure, tr("Device authorization failed: %1").arg(msg));
			return;
		}

		if (!m_request->wasSuccessful() || m_request->error() != QNetworkReply::NoError)
		{
			emit completed(StepResult::HardFailure, tr("Failed to request device authorization."));
			return;
		}

		if (!rsp.isValid())
		{
			emit completed(StepResult::HardFailure, tr("Invalid device authorization response."));
			return;
		}

		m_deviceCode   = rsp.deviceCode;
		m_pollInterval = rsp.interval > 0 ? rsp.interval : 5;

		// Notify UI to display code
		emit deviceCodeReady(rsp.verificationUri, rsp.userCode, rsp.expiresIn);

		// Start polling
		startPolling(m_pollInterval, rsp.expiresIn);
	}

	void DeviceCodeAuthStep::startPolling(int intervalSecs, int expiresInSecs)
	{
		if (m_cancelled)
		{
			return;
		}

		m_expirationTimer.setInterval(expiresInSecs * 1000);
		m_expirationTimer.start();

		m_pollTimer.setInterval(intervalSecs * 1000);
		m_pollTimer.start();
	}

	void DeviceCodeAuthStep::pollForCompletion()
	{
		if (m_cancelled)
		{
			return;
		}

		QUrlQuery query;
		query.addQueryItem(QStringLiteral("client_id"), m_clientId);
		query.addQueryItem(QStringLiteral("grant_type"),
						   QStringLiteral("urn:ietf:params:oauth:grant-type:device_code"));
		query.addQueryItem(QStringLiteral("device_code"), m_deviceCode);

		const auto payload = query.query(QUrl::FullyEncoded).toUtf8();
		const QUrl url(QString::fromLatin1(kTokenUrl));

		const auto headers = QList<Net::HeaderPair>{ { "Content-Type", "application/x-www-form-urlencoded" },
													 { "Accept", "application/json" } };

		m_response = std::make_shared<QByteArray>();
		m_request  = Net::Upload::makeByteArray(url, m_response, payload);
		m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
		m_request->setNetwork(APPLICATION->network());

		connect(m_request.get(), &Task::finished, this, &DeviceCodeAuthStep::onPollResponse);
		m_request->start();
	}

	void DeviceCodeAuthStep::onPollResponse()
	{
		if (m_cancelled)
		{
			return;
		}

		// Handle timeout - exponential backoff per RFC 8628
		if (m_request->error() == QNetworkReply::TimeoutError)
		{
			m_pollInterval *= 2;
			m_pollTimer.setInterval(m_pollInterval * 1000);
			m_pollTimer.start();
			return;
		}

		const auto rsp = parseTokenResponse(*m_response);

		// Handle slow_down - increase interval by 5 seconds per RFC 8628
		if (rsp.needsSlowDown())
		{
			m_pollInterval += 5;
			m_pollTimer.setInterval(m_pollInterval * 1000);
			m_pollTimer.start();
			return;
		}

		// Authorization still pending - keep polling
		if (rsp.isPending())
		{
			m_pollTimer.start();
			return;
		}

		// Check for other errors
		if (!rsp.error.isEmpty())
		{
			const QString msg = rsp.errorDescription.isEmpty() ? rsp.error : rsp.errorDescription;
			emit completed(StepResult::HardFailure, tr("Device authentication failed: %1").arg(msg));
			return;
		}

		// Network error - retry
		if (!m_request->wasSuccessful() || m_request->error() != QNetworkReply::NoError)
		{
			m_pollTimer.start();
			return;
		}

		// Success!
		m_expirationTimer.stop();

		m_credentials.msaClientId			= m_clientId;
		m_credentials.msaToken.issuedAt		= QDateTime::currentDateTimeUtc();
		m_credentials.msaToken.expiresAt	= QDateTime::currentDateTimeUtc().addSecs(rsp.expiresIn);
		m_credentials.msaToken.metadata		= rsp.metadata;
		m_credentials.msaToken.refreshToken = rsp.refreshToken;
		m_credentials.msaToken.accessToken	= rsp.accessToken;
		m_credentials.msaToken.validity		= TokenValidity::Certain;

		emit completed(StepResult::Continue, tr("Microsoft authentication successful."));
	}

} // namespace projt::minecraft::auth