-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetLatestVersion.ts
More file actions
278 lines (238 loc) · 7.28 KB
/
getLatestVersion.ts
File metadata and controls
278 lines (238 loc) · 7.28 KB
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
import { live, xnet } from "@xboxreplay/xboxlive-auth";
import {
IUpdateResponse,
IHistoricalVersions,
InstallType,
Versions,
} from "./types.ts";
import { createHash } from "node:crypto";
const CLIENT_ID = "00000000402b5328";
const SCOPE = "service::user.auth.xboxlive.com::MBI_SSL";
const RELEASE_ID = "7792d9ce-355a-493c-afbd-768f4a77c3b0";
const PREVIEW_ID = "98bd2335-9b01-4e4c-bd05-ccc01614078b";
const VERSIONS_DB = JSON.parse(
await Deno.readTextFile("./historical_versions.json"),
) as IHistoricalVersions;
async function refreshTokens() {
const REFRESH_TOKEN = Deno.env.get("REFRESH_TOKEN");
if (REFRESH_TOKEN === undefined) {
console.log("Refresh token not found! Please generate a new token!");
return;
}
const accessTokenResponse = await live.refreshAccessToken(
REFRESH_TOKEN,
CLIENT_ID,
SCOPE,
);
await Deno.writeTextFile(
".env",
`REFRESH_TOKEN=${accessTokenResponse.refresh_token}`,
);
const authenticationBody = {
RelyingParty: "http://auth.xboxlive.com",
TokenType: "JWT",
Properties: {
AuthMethod: "RPS",
SiteName: "user.auth.xboxlive.com",
RpsTicket: accessTokenResponse.access_token,
},
};
const authenticationURL = new URL(
"user/authenticate",
"https://user.auth.xboxlive.com/",
);
const authenticationResponse = await fetch(authenticationURL.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-xbl-contract-version": "1",
},
body: JSON.stringify(authenticationBody),
});
if (!authenticationResponse.ok) {
return;
}
const userToken = JSON.parse(await authenticationResponse.text()).Token;
const deviceToken = (await xnet.experimental.createDummyWin32DeviceToken())
.Token;
const updateURL = new URL(
"xsts/authorize",
"https://xsts.auth.xboxlive.com/",
);
const updateBody = {
RelyingParty: "http://update.xboxlive.com",
TokenType: "JWT",
Properties: {
UserTokens: [userToken],
SandboxId: "RETAIL",
DeviceToken: deviceToken,
},
};
const updateResponse = await fetch(updateURL.toString(), {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-xbl-contract-version": "1",
},
body: JSON.stringify(updateBody),
});
if (!updateResponse.ok) {
return;
}
const updateResponseJSON = JSON.parse(await updateResponse.text());
const authorizationHeader = `XBL3.0 x=${updateResponseJSON.DisplayClaims.xui[0].uhs};${updateResponseJSON.Token}`;
const releaseURLS = await getVersions(RELEASE_ID, authorizationHeader);
const previewURLS = await getVersions(PREVIEW_ID, authorizationHeader);
if (releaseURLS !== undefined)
await assessAndUpdateHistoricalVersions(
"Release",
"releaseVersions",
releaseURLS,
);
if (previewURLS !== undefined)
await assessAndUpdateHistoricalVersions(
"Preview",
"previewVersions",
previewURLS,
);
}
async function getVersions(releaseType: string, authorizationHeader: string) {
const versionsResponse = await fetch(
`https://packagespc.xboxlive.com/GetBasePackage/${releaseType}`,
{
method: "GET",
headers: {
Authorization: authorizationHeader,
},
},
);
if (!versionsResponse.ok) {
return;
}
const versionsResponseJSON = JSON.parse(
await versionsResponse.text(),
) as IUpdateResponse;
for (const packageFile of versionsResponseJSON.PackageFiles) {
if (!packageFile.FileName.endsWith(".msixvc")) continue;
const versionURLS: string[] = [];
for (let i = 0; i < packageFile.CdnRootPaths.length; i++) {
const versionURL = packageFile.CdnRootPaths[i] + packageFile.RelativeUrl;
versionURLS.push(versionURL);
}
return versionURLS;
}
}
function prettifyVersionNumbers(version: string): string {
const match = version.match(/(\d+)\.(\d+)\.(\d+)\.(\d+)/);
if (match === null) return version;
const a = match[1];
const b = match[2];
const c = match[3];
const cHead = c.length > 2 ? String(parseInt(c.slice(0, -2), 10)) : "0";
const cTail = c.length >= 2 ? c.slice(-2) : c.padStart(2, "0");
return `${a}.${b}.${cHead}.${cTail}`;
}
async function calculateMd5(url: string): Promise<string | null> {
try {
console.log(`Downloading and calculating MD5 for: ${url}`);
const response = await fetch(url);
if (!response.ok || !response.body) {
console.error(`Failed to fetch ${url}: ${response.statusText}`);
return null;
}
const hash = createHash("md5");
for await (const chunk of response.body) {
hash.update(chunk);
}
return hash.digest("hex");
} catch (error) {
console.error(`Error processing ${url}:`, error);
return null;
}
}
async function assessAndUpdateHistoricalVersions(
installType: InstallType,
versions: Versions,
urls: string[],
) {
const versionNameRegex = /[^\/]*.msixvc$/;
const versionNameMatch = urls[0].match(versionNameRegex);
if (versionNameMatch === null) return;
const version = versionNameMatch[0].replace(".msixvc", "");
const versionNumber = prettifyVersionNumbers(version);
const name = `${installType} ${versionNumber}`;
const versionsLength = VERSIONS_DB[versions].length;
let length = 0;
for (const versionEntry of VERSIONS_DB[versions]) {
if (versionEntry.version !== name) length++;
}
const processedUrlSet = new Set(urls);
const extraHostsBySourceHost: Record<string, string[]> = {
"assets1.xboxlive.com": [
"assets1.xboxlive.cn",
"d1.xboxlive.cn",
"d2.xboxlive.cn",
"xvcf1.xboxlive.com",
"xvcf2.xboxlive.com",
"d1.xboxlive.com",
"d2.xboxlive.com",
],
"assets2.xboxlive.com": [
"assets2.xboxlive.cn",
"d1.xboxlive.cn",
"d2.xboxlive.cn",
"xvcf1.xboxlive.com",
"xvcf2.xboxlive.com",
"d1.xboxlive.com",
"d2.xboxlive.com",
],
};
for (const url of urls) {
let parsedUrl: URL;
try {
parsedUrl = new URL(url);
} catch {
continue;
}
const candidateHosts = extraHostsBySourceHost[parsedUrl.host];
if (candidateHosts === undefined) continue;
for (const host of candidateHosts) {
if (host === parsedUrl.host) continue;
const candidateUrl = new URL(url);
candidateUrl.host = host;
processedUrlSet.add(candidateUrl.toString());
}
}
const processedUrls = [...processedUrlSet];
if (versionsLength === length) {
const md5Counts: Record<string, number> = {};
let finalMd5: string | undefined;
console.log(`New version found: ${name}. Verifying MD5...`);
for (const url of processedUrls) {
const md5 = await calculateMd5(url);
if (md5) {
md5Counts[md5] = (md5Counts[md5] || 0) + 1;
}
}
for (const [md5, count] of Object.entries(md5Counts)) {
if (count >= 2) {
finalMd5 = md5;
break;
}
}
if (finalMd5) {
console.log(`MD5 verified: ${finalMd5}`);
} else {
console.log("Could not verify MD5 (less than 2 matches).");
}
VERSIONS_DB[versions].push({
version: name,
urls: processedUrls,
timestamp: Math.floor(Date.now() / 1000),
md5: finalMd5,
});
const jsonContent = JSON.stringify(VERSIONS_DB, null, 4);
await Deno.writeTextFile("./historical_versions.json", jsonContent);
}
}
await refreshTokens();