aboutsummaryrefslogtreecommitdiff
path: root/apps/proxy/src/index.js
blob: e6ed8690059377a3c7a502367df82df8e5dfc6f5 (plain) (blame)
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
import { bootstrapManga, syncMangadexIndex } from "./mangadex.js";
import { fetchRawkumaChapterCounts } from "./rawkuma.js";
import {
	deleteMangadexFailureRows,
	getMangadexFailureRowsByAniListIds,
	getMangadexRowsByAniListIds,
	hasSupabaseConfig,
	upsertMangadexFailureRows,
	upsertMangadexRows,
} from "./supabase.js";

const DEFAULT_ALLOWED_ORIGIN = "https://due.moe";
const DEFAULT_BOOTSTRAP_RETRY_MINUTES = 360;
const DEFAULT_PENDING_RETRY_MS = 750;
const bootstrapInFlight = new Map();

const isPrivateHostname = (hostname) =>
	hostname === "localhost" ||
	hostname === "127.0.0.1" ||
	hostname.endsWith(".local") ||
	hostname.endsWith(".localhost") ||
	/^10\./.test(hostname) ||
	/^192\.168\./.test(hostname) ||
	/^172\.(1[6-9]|2\d|3[0-1])\./.test(hostname);

const accessControlOrigin = (request) => {
	const origin = request.headers.get("Origin");

	if (!origin) return DEFAULT_ALLOWED_ORIGIN;

	try {
		const url = new URL(origin);

		if (
			url.hostname === "due.moe" ||
			url.hostname.endsWith(".due.moe") ||
			isPrivateHostname(url.hostname)
		)
			return origin;
	} catch {}

	return DEFAULT_ALLOWED_ORIGIN;
};

const appendCorsHeaders = (request, headers = new Headers()) => {
	headers.set("Access-Control-Allow-Origin", accessControlOrigin(request));
	headers.set("Access-Control-Allow-Methods", "GET, HEAD, POST, OPTIONS");
	headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
	headers.append("Vary", "Origin");

	return headers;
};

const jsonResponse = (request, body, init = {}) => {
	const headers = appendCorsHeaders(request, new Headers(init.headers));

	headers.set("Content-Type", "application/json");

	return new Response(JSON.stringify(body), {
		...init,
		headers,
	});
};

const textResponse = (request, body, init = {}) =>
	new Response(body, {
		...init,
		headers: appendCorsHeaders(request, new Headers(init.headers)),
	});

const decodeProxyTarget = (url) => {
	if (url.search.includes("?q=")) return url.search.split("?q=")[1];
	if (url.search.includes("?d=")) return atob(url.search.split("?d=")[1]);
	if (url.search.includes("?d2=")) {
		const fullEncodedUrl = url.search.split("?d2=")[1];
		const key = Number.parseInt(fullEncodedUrl.slice(-2), 10);

		return atob(fullEncodedUrl.slice(0, -2))
			.split(":")
			.map((char) => String.fromCharCode(Number(char) - key))
			.join("");
	}

	return null;
};

const forwardProxyRequest = async (request) => {
	const url = new URL(request.url);
	const dropHeaders = url.search.includes("&dh");

	if (dropHeaders) url.search = url.search.replace("&dh", "");

	const target = decodeProxyTarget(url);

	if (!target)
		return textResponse(request, null, {
			status: 400,
			statusText: "Bad Request",
		});

	const targetUrl = new URL(target);
	const proxiedRequest = new Request(target, request);

	proxiedRequest.headers.set("Host", targetUrl.hostname);
	proxiedRequest.headers.set("Referrer", targetUrl.toString());
	proxiedRequest.headers.set("Origin", targetUrl.origin);
	proxiedRequest.headers.delete("X-Content-Type-Options");

	let response = await fetch(proxiedRequest);

	response = new Response(response.body, response);

	if (dropHeaders)
		for (const key of [...response.headers.keys()])
			response.headers.delete(key);

	appendCorsHeaders(request, response.headers);
	response.headers.set("Cache-Control", "max-age=300");

	return response;
};

const handleOptions = (request) =>
	new Response(null, {
		headers: appendCorsHeaders(request),
	});

const isMangadexIdConstraintConflict = (error) =>
	error instanceof Error &&
	error.message.includes("mangadex_manga_index_mangadex_id_key");

const parseMangaPayload = async (request) => {
	const body = await request.json().catch(() => null);
	const manga = Array.isArray(body?.manga) ? body.manga : [];

	return manga
		.map((entry) => ({
			anilistId: Number(entry?.anilistId),
			progress: entry?.progress ? Number(entry.progress) : 0,
			status: String(entry?.status || ""),
			startYear: entry?.startYear ? Number(entry.startYear) : null,
			nativeTitle: entry?.nativeTitle || null,
			englishTitle: entry?.englishTitle || null,
			romajiTitle: entry?.romajiTitle || null,
		}))
		.filter((entry) => Number.isFinite(entry.anilistId));
};

const bootstrapRetryMinutes = (env) => {
	const minutes = Number.parseInt(
		env.MANGADEX_BOOTSTRAP_RETRY_MINUTES || "",
		10,
	);

	return Number.isFinite(minutes) && minutes > 0
		? minutes
		: DEFAULT_BOOTSTRAP_RETRY_MINUTES;
};

const pendingRetryMs = (env) => {
	const milliseconds = Number.parseInt(
		env.MANGA_CHAPTER_COUNTS_RETRY_MS || "",
		10,
	);

	return Number.isFinite(milliseconds) && milliseconds > 0
		? milliseconds
		: DEFAULT_PENDING_RETRY_MS;
};

const isRecentFailure = (row, retryMinutes) =>
	Date.now() - new Date(row.last_attempted_at || row.updated_at).getTime() <
	retryMinutes * 60 * 1000;

const queueBootstrap = (env, manga) =>
	manga
		.map((entry) => {
			const existing = bootstrapInFlight.get(entry.anilistId);

			if (existing) return existing;

			const promise = (async () => {
				const row = await bootstrapManga(env, entry);

				if (row) {
					try {
						await upsertMangadexRows(env, [row]);
					} catch (error) {
						if (!isMangadexIdConstraintConflict(error)) throw error;
					}

					await deleteMangadexFailureRows(env, [row.anilist_id]);

					return;
				}

				await upsertMangadexFailureRows(env, [entry.anilistId]);
			})().finally(() => {
				bootstrapInFlight.delete(entry.anilistId);
			});

			bootstrapInFlight.set(entry.anilistId, promise);

			return promise;
		})
		.filter(Boolean);

const parseOptionalNumber = (value) => {
	if (value === null || value === undefined || value === "") return null;

	const number = Number.parseFloat(String(value));

	return Number.isFinite(number) ? number : null;
};

const recommendedVolumeText = (volumeChapterBoundaries, progress) => {
	if (!volumeChapterBoundaries || !Number.isFinite(progress) || progress <= 0)
		return null;

	let recommended = null;
	let recommendedNumber = null;

	for (const [volumeText, chapterBoundary] of Object.entries(
		volumeChapterBoundaries,
	)) {
		const volumeNumber = parseOptionalNumber(volumeText);
		const boundaryNumber = parseOptionalNumber(chapterBoundary);

		if (
			volumeNumber === null ||
			boundaryNumber === null ||
			boundaryNumber > progress
		)
			continue;

		if (recommendedNumber === null || volumeNumber > recommendedNumber) {
			recommended = String(volumeNumber);
			recommendedNumber = volumeNumber;
		}
	}

	return recommended;
};

const handleMangaChapterCounts = async (request, env, executionContext) => {
	if (!hasSupabaseConfig(env))
		return jsonResponse(
			request,
			{ error: "Supabase is not configured for the proxy worker." },
			{ status: 500 },
		);

	const manga = await parseMangaPayload(request);

	if (!manga.length) return jsonResponse(request, { data: {} });

	const mangaById = new Map(manga.map((entry) => [entry.anilistId, entry]));
	const anilistIds = manga.map((entry) => entry.anilistId);
	const [existingRows, failureRows] = await Promise.all([
		getMangadexRowsByAniListIds(env, anilistIds),
		getMangadexFailureRowsByAniListIds(env, anilistIds),
	]);
	const existingRowsById = new Map(
		existingRows.map((row) => [row.anilist_id, row]),
	);
	const recentFailures = new Set(
		failureRows
			.filter((row) => isRecentFailure(row, bootstrapRetryMinutes(env)))
			.map((row) => row.anilist_id),
	);
	const rowsMissingFromIndex = manga.filter((entry) => {
		const row = existingRowsById.get(entry.anilistId);

		if (!row) return !recentFailures.has(entry.anilistId);
		return false;
	});
	const rowsNeedingVolumeBackfill = manga.filter((entry) => {
		const row = existingRowsById.get(entry.anilistId);

		if (!row) return false;

		return (
			entry.progress > 0 &&
			row.volume_chapter_boundaries === null &&
			!recentFailures.has(entry.anilistId)
		);
	});
	const rowsNeedingBackfill = [
		...rowsMissingFromIndex,
		...rowsNeedingVolumeBackfill,
	];
	const pendingRows = rowsMissingFromIndex.filter((entry) =>
		bootstrapInFlight.has(entry.anilistId),
	);
	const queueableRows = rowsNeedingBackfill.filter(
		(entry) => !bootstrapInFlight.has(entry.anilistId),
	);
	const queueablePendingRows = rowsMissingFromIndex.filter(
		(entry) => !bootstrapInFlight.has(entry.anilistId),
	);

	if (queueableRows.length)
		executionContext.waitUntil(
			Promise.all(queueBootstrap(env, queueableRows)).catch((error) => {
				if (!isMangadexIdConstraintConflict(error)) throw error;
			}),
		);

	const data = Object.fromEntries(
		existingRows.map((row) => {
			const entry = mangaById.get(row.anilist_id);
			const volumeText = recommendedVolumeText(
				row.volume_chapter_boundaries,
				entry?.progress || 0,
			);

			return [
				String(row.anilist_id),
				{
					chapter: row.latest_en_chapter_number,
					...(volumeText === null ? {} : { volumeText }),
				},
			];
		}),
	);
	const pending = [
		...new Set(
			[...pendingRows, ...queueablePendingRows].map((entry) => entry.anilistId),
		),
	];

	return jsonResponse(request, {
		data,
		...(pending.length
			? {
					pending,
					retryAfterMs: pendingRetryMs(env),
				}
			: {}),
	});
};

const handleMangaNativeChapterCounts = async (request, env) => {
	const manga = await parseMangaPayload(request);

	if (!manga.length) return jsonResponse(request, { data: {} });

	return jsonResponse(request, {
		data: await fetchRawkumaChapterCounts(env, request.headers, manga),
	});
};

const isAuthorisedSyncRequest = (request, env) => {
	const token = env.MANGADEX_SYNC_TOKEN;

	if (!token) return isPrivateHostname(new URL(request.url).hostname);

	return request.headers.get("Authorization") === `Bearer ${token}`;
};

const handleMangaSync = async (request, env) => {
	if (!hasSupabaseConfig(env))
		return jsonResponse(
			request,
			{ error: "Supabase is not configured for the proxy worker." },
			{ status: 500 },
		);

	if (!isAuthorisedSyncRequest(request, env))
		return jsonResponse(request, { error: "Forbidden" }, { status: 403 });

	const result = await syncMangadexIndex(env);

	return jsonResponse(request, { data: result });
};

export default {
	async fetch(request, env, executionContext) {
		try {
			const url = new URL(request.url);

			if (request.method === "OPTIONS") return handleOptions(request);

			if (url.pathname === "/manga/chapter-counts" && request.method === "POST")
				return handleMangaChapterCounts(request, env, executionContext);

			if (
				url.pathname === "/manga/native-chapter-counts" &&
				request.method === "POST"
			)
				return handleMangaNativeChapterCounts(request, env);

			if (url.pathname === "/manga/sync" && request.method === "POST")
				return handleMangaSync(request, env);

			if (["GET", "HEAD", "POST"].includes(request.method))
				return forwardProxyRequest(request);

			return textResponse(request, null, {
				status: 405,
				statusText: "Method Not Allowed",
			});
		} catch (error) {
			return jsonResponse(
				request,
				{ error: error instanceof Error ? error.message : "Bad Request" },
				{ status: 400 },
			);
		}
	},

	async scheduled(_controller, env, executionContext) {
		if (!hasSupabaseConfig(env)) return;

		executionContext.waitUntil(syncMangadexIndex(env));
	},
};