-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.ts
205 lines (156 loc) · 4.83 KB
/
index.ts
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
import { ClientHttp2Session, connect, constants } from "node:http2";
import { createServer } from "node:http";
import { Browser, CookieParam, Page, Protocol, launch } from "puppeteer";
import fs from "fs/promises";
const COOKIE_PATH = "./cookies.json";
async function saveCookies(cookies: Protocol.Network.Cookie[]) {
console.log("Saving cookies");
await fs.writeFile(
COOKIE_PATH,
JSON.stringify(
cookies.map((cookie) => {
const { session, partitionKey, size, ...rest } = cookie;
return rest;
}),
null,
2
)
);
}
async function loadCookies(): Promise<CookieParam[]> {
console.log("Loading cookies");
try {
return JSON.parse(await fs.readFile(COOKIE_PATH, "utf-8"));
} catch (error) {
return [];
}
}
async function loginToStrava(): Promise<
(CookieParam | Protocol.Network.Cookie)[]
> {
let browser: Browser | undefined;
try {
browser = await launch({
headless: true,
devtools: false,
timeout: 0,
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--disable-blink-features=AutomationControlled",
],
});
const page: Page = await browser.newPage();
await page.setUserAgent(
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
);
await page.setViewport({ width: 1280, height: 800 });
const cookies = await loadCookies();
await page.setCookie(...cookies);
async function tryTile() {
console.log("Trying the tile...");
const response = await page.goto(
"https://heatmap-external-c.strava.com/tiles-auth/all/blue/15/18319/11293.png",
{ waitUntil: "networkidle2" }
);
const ok = response?.headers()["content-type"].startsWith("image/");
console.log("Tile: " + (ok ? "OK" : "FAIL"));
return ok;
}
if (await tryTile()) {
return cookies;
}
console.log("Trying the onboarding...");
await page.goto("https://www.strava.com/onboarding", {
waitUntil: "networkidle2",
});
if (page.url() === "https://www.strava.com/login") {
console.log("Redirected to log-in page");
await page.type("#desktop-email", process.env.SP_EMAIL!);
await page.type("#desktop-current-password", process.env.SP_PASSWORD!);
await Promise.all([
page.click("#desktop-login-button"),
page.waitForNavigation({ waitUntil: "networkidle2" }),
]);
} else {
console.log("Onboarding: OK");
}
if (await tryTile()) {
return cookies;
}
await page.goto("https://www.strava.com/maps/global-heatmap", {
waitUntil: "networkidle2",
});
await page.waitForResponse((response) =>
response.url().includes("heatmap-external")
);
const client = await page.createCDPSession();
await saveCookies((await client.send("Network.getAllCookies")).cookies);
return cookies;
} finally {
if (browser) {
await browser.close();
}
}
}
const cookies = await loginToStrava();
let client2: Record<string, ClientHttp2Session> = {};
function getClient2(key: string) {
return client2[key] && !client2[key].destroyed
? client2[key]
: connect(`https://heatmap-external-${key}.strava.com`);
}
function ensureSingle<T>(header: T | T[] | undefined) {
return Array.isArray(header) ? header[0] : header;
}
const keys = ["a", "b", "c"];
let keyIndex = 0;
createServer((req, res) => {
keyIndex = (keyIndex + 1) % keys.length;
const clientStream = getClient2(keys[keyIndex]).request({
[constants.HTTP2_HEADER_METHOD]: constants.HTTP2_METHOD_GET,
[constants.HTTP2_HEADER_PATH]: "/tiles-auth" + req.url,
[constants.HTTP2_HEADER_COOKIE]: cookies
.map((cookie) => `${cookie.name}=${cookie.value}`)
.join("; "),
});
clientStream.on("response", (headers) => {
const status = Number(ensureSingle(headers[constants.HTTP2_HEADER_STATUS]));
console.log(
status +
": " +
req.headers["x-forwarded-for"] +
" | " +
req.headers["referer"] +
" | " +
req.headers["user-agent"]
);
const ct = ensureSingle(headers[constants.HTTP2_HEADER_CONTENT_TYPE]);
if (status === 200 && ct && ct?.startsWith("image/")) {
res.setHeader("Content-Type", ct);
} else if (status === 404) {
res.writeHead(404).end();
} else {
console.warn(
Object.entries(headers)
.map(([k, v]) => `${k}: ${v}`)
.join("|")
);
res.writeHead(500).end();
}
});
clientStream.on("error", (err) => {
console.error(err);
if (!res.headersSent) {
res.writeHead(500);
}
res.end();
});
clientStream.on("data", (chunk) => {
res.write(chunk);
});
clientStream.on("end", () => {
res.end();
});
clientStream.end();
}).listen(Number(process.env.SP_PORT || "8080"));