rhythia-api 230.0.0 → 233.0.0

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,7 +4,7 @@ import { supabase } from "./supabase";
4
4
 
5
5
  export async function getUserBySession(session: string): Promise<User | null> {
6
6
  const user = (await supabase.auth.getUser(session)).data.user;
7
-
7
+ console.log("session:", session);
8
8
  if (user) {
9
9
  return user;
10
10
  }
@@ -0,0 +1,277 @@
1
+ import { supabase } from "./supabase";
2
+
3
+ type MapLifecycleEvent = "qualified" | "ranked" | "vetoed";
4
+
5
+ const WEBHOOK_COLORS: Record<MapLifecycleEvent, number> = {
6
+ qualified: 0x3498db,
7
+ ranked: 0x2ecc71,
8
+ vetoed: 0xe74c3c,
9
+ };
10
+
11
+ const WEBHOOK_TITLES: Record<MapLifecycleEvent, string> = {
12
+ qualified: "Map Qualified",
13
+ ranked: "Map Ranked",
14
+ vetoed: "Map Vetoed",
15
+ };
16
+
17
+ const WEBHOOK_MESSAGES: Record<MapLifecycleEvent, string> = {
18
+ qualified: "A fresh map just reached qualification.",
19
+ ranked: "This map cleared qualification and is now ranked.",
20
+ vetoed: "This map was vetoed and sent back for improvements.",
21
+ };
22
+
23
+ function clampText(value: string, maxLength: number) {
24
+ const sanitized = value.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, "");
25
+
26
+ if (sanitized.length <= maxLength) {
27
+ return sanitized;
28
+ }
29
+
30
+ if (maxLength <= 3) {
31
+ return sanitized.slice(0, maxLength);
32
+ }
33
+
34
+ return `${sanitized.slice(0, maxLength - 3)}...`;
35
+ }
36
+
37
+ function getSafeHttpUrl(value: string | null | undefined) {
38
+ if (!value) {
39
+ return null;
40
+ }
41
+
42
+ try {
43
+ const parsed = new URL(value.trim());
44
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
45
+ return null;
46
+ }
47
+ const serialized = parsed.toString();
48
+ if (serialized.length > 2048) {
49
+ return null;
50
+ }
51
+ return serialized;
52
+ } catch {
53
+ return null;
54
+ }
55
+ }
56
+
57
+ function formatLength(milliseconds: number | null | undefined) {
58
+ if (!milliseconds || milliseconds < 0) {
59
+ return "-";
60
+ }
61
+
62
+ const totalSeconds = Math.floor(milliseconds / 1000);
63
+ const minutes = Math.floor(totalSeconds / 60);
64
+ const seconds = totalSeconds % 60;
65
+ return `${minutes.toString().padStart(2, "0")}:${seconds
66
+ .toString()
67
+ .padStart(2, "0")}`;
68
+ }
69
+
70
+ export async function postMapLifecycleWebhook({
71
+ mapId,
72
+ event,
73
+ vetoReason,
74
+ }: {
75
+ mapId: number;
76
+ event: MapLifecycleEvent;
77
+ vetoReason?: string;
78
+ }) {
79
+ const webhookUrl = process.env.WEBHOOK_MSG_DISCORD;
80
+ if (!webhookUrl) {
81
+ return;
82
+ }
83
+
84
+ try {
85
+ const { data: beatmapPage } = await supabase
86
+ .from("beatmapPages")
87
+ .select(
88
+ `
89
+ id,
90
+ owner,
91
+ title,
92
+ tags,
93
+ status,
94
+ qualified,
95
+ qualifiedAt,
96
+ beatmaps (
97
+ title,
98
+ starRating,
99
+ length,
100
+ difficulty,
101
+ noteCount,
102
+ image,
103
+ imageLarge
104
+ ),
105
+ profiles (
106
+ id,
107
+ username,
108
+ avatar_url
109
+ )
110
+ `
111
+ )
112
+ .eq("id", mapId)
113
+ .single();
114
+
115
+ if (!beatmapPage) {
116
+ return;
117
+ }
118
+
119
+ const beatmapData = (beatmapPage as any).beatmaps;
120
+ const profileData = (beatmapPage as any).profiles;
121
+ const mapTitle =
122
+ beatmapData?.title || beatmapPage.title || `Beatmap Page #${mapId}`;
123
+ const creatorName = profileData?.username || "Unknown";
124
+ const creatorId = beatmapPage.owner || profileData?.id || 0;
125
+ const rawImage =
126
+ beatmapData?.imageLarge || beatmapData?.image || "https://www.rhythia.com/unkimg.png";
127
+ const mapImage = rawImage.includes("backfill")
128
+ ? "https://www.rhythia.com/unkimg.png"
129
+ : rawImage;
130
+ const safeMapImageUrl = getSafeHttpUrl(mapImage);
131
+ const safeAvatarUrl = getSafeHttpUrl(profileData?.avatar_url);
132
+
133
+ const fields: Array<{ name: string; value: string; inline?: boolean }> = [
134
+ {
135
+ name: "Map ID",
136
+ value: clampText(`${beatmapPage.id}`, 1024),
137
+ inline: true,
138
+ },
139
+ {
140
+ name: "Creator",
141
+ value: clampText(creatorName, 1024),
142
+ inline: true,
143
+ },
144
+ {
145
+ name: "Stars",
146
+ value: clampText(
147
+ beatmapData?.starRating !== null && beatmapData?.starRating !== undefined
148
+ ? `${Math.round(beatmapData.starRating * 100) / 100}*`
149
+ : "-",
150
+ 1024
151
+ ),
152
+ inline: true,
153
+ },
154
+ {
155
+ name: "Length",
156
+ value: clampText(formatLength(beatmapData?.length), 1024),
157
+ inline: true,
158
+ },
159
+ {
160
+ name: "Notes",
161
+ value: clampText(
162
+ beatmapData?.noteCount !== null && beatmapData?.noteCount !== undefined
163
+ ? `${beatmapData.noteCount}`
164
+ : "-",
165
+ 1024
166
+ ),
167
+ inline: true,
168
+ },
169
+ {
170
+ name: "Tags",
171
+ value: clampText(beatmapPage.tags || "-", 1024),
172
+ inline: false,
173
+ },
174
+ ];
175
+
176
+ if (event === "vetoed") {
177
+ fields.push({
178
+ name: "Veto Reason",
179
+ value: clampText(vetoReason || "No reason provided", 1024),
180
+ inline: false,
181
+ });
182
+ }
183
+
184
+ const embed: Record<string, any> = {
185
+ title: clampText(`${WEBHOOK_TITLES[event]}: ${mapTitle}`, 256),
186
+ url: `https://www.rhythia.com/maps/${beatmapPage.id}`,
187
+ description: clampText(WEBHOOK_MESSAGES[event], 4096),
188
+ color: WEBHOOK_COLORS[event],
189
+ fields: fields.map((field) => ({
190
+ ...field,
191
+ name: clampText(field.name || "-", 256),
192
+ value: clampText(field.value || "-", 1024),
193
+ })),
194
+ author: {
195
+ name: clampText(creatorName, 256),
196
+ url: `https://www.rhythia.com/player/${creatorId}`,
197
+ icon_url: safeAvatarUrl || "https://www.rhythia.com/unkimg.png",
198
+ },
199
+ footer: {
200
+ text: clampText(
201
+ `Status: ${beatmapPage.status || "-"} | ${new Date().toUTCString()}`,
202
+ 2048
203
+ ),
204
+ },
205
+ };
206
+
207
+ if (safeMapImageUrl) {
208
+ embed.thumbnail = {
209
+ url: safeMapImageUrl,
210
+ };
211
+ }
212
+
213
+ const payload = {
214
+ content: clampText(WEBHOOK_MESSAGES[event], 2000),
215
+ embeds: [embed],
216
+ };
217
+
218
+ let response = await fetch(webhookUrl, {
219
+ method: "POST",
220
+ headers: {
221
+ "Content-Type": "application/json",
222
+ },
223
+ body: JSON.stringify(payload),
224
+ });
225
+
226
+ if (
227
+ !response.ok &&
228
+ response.status === 400 &&
229
+ (payload.embeds?.[0]?.image?.url || payload.embeds?.[0]?.thumbnail?.url)
230
+ ) {
231
+ // Most common Discord embed 400 here is a bad media URL. Retry without media.
232
+ const retryPayload = {
233
+ ...payload,
234
+ embeds: payload.embeds.map((embed: any) => {
235
+ const clone = { ...embed };
236
+ delete clone.image;
237
+ delete clone.thumbnail;
238
+ return clone;
239
+ }),
240
+ };
241
+
242
+ response = await fetch(webhookUrl, {
243
+ method: "POST",
244
+ headers: {
245
+ "Content-Type": "application/json",
246
+ },
247
+ body: JSON.stringify(retryPayload),
248
+ });
249
+ }
250
+
251
+ if (!response.ok) {
252
+ const responseBody = await response.text();
253
+ console.log("Discord webhook failed", {
254
+ event,
255
+ mapId,
256
+ status: response.status,
257
+ statusText: response.statusText,
258
+ responseBody: clampText(responseBody || "-", 4000),
259
+ payloadPreview: {
260
+ content: payload.content,
261
+ title: payload.embeds?.[0]?.title,
262
+ fields: payload.embeds?.[0]?.fields?.map((field: any) => ({
263
+ name: field.name,
264
+ value: clampText(field.value || "-", 120),
265
+ })),
266
+ imageUrl: payload.embeds?.[0]?.image?.url || null,
267
+ thumbnailUrl: payload.embeds?.[0]?.thumbnail?.url || null,
268
+ authorIconUrl: payload.embeds?.[0]?.author?.icon_url || null,
269
+ hasImage: Boolean(payload.embeds?.[0]?.image?.url),
270
+ hasThumbnail: Boolean(payload.embeds?.[0]?.thumbnail?.url),
271
+ },
272
+ });
273
+ }
274
+ } catch (error) {
275
+ console.log("Failed to post map lifecycle webhook", error);
276
+ }
277
+ }
@@ -1,88 +1,127 @@
1
- import { NextResponse } from "next/server";
2
- import { set, ZodObject } from "zod";
3
- import { getUserBySession } from "./getUserBySession";
4
- import { supabase } from "./supabase";
5
-
6
- interface Props<
7
- K = (...args: any[]) => Promise<NextResponse<any>>,
8
- T = ZodObject<any>,
9
- > {
10
- request: Request;
11
- schema: { input: T; output: T };
12
- authorization?: Function;
13
- activity: K;
14
- }
15
-
16
- export async function protectedApi({
17
- request,
18
- schema,
19
- authorization,
20
- activity,
21
- }: Props) {
22
- try {
23
- const toParse = await request.json();
24
- const data = schema.input.parse(toParse);
25
-
26
- const dataClone = structuredClone(data);
27
- if (dataClone) {
28
- if (dataClone["token"]) {
29
- dataClone["token"] = "********";
30
- }
31
- Object.keys(dataClone).forEach((key) => {
32
- console.log("KEY: ", key, dataClone[key]);
33
- if (key == "data") {
34
- try {
35
- Object.keys(dataClone[key]).forEach((key2) => {
36
- console.log("KEY2: ", key2, dataClone[key][key2]);
37
- });
38
- } catch (error) {}
39
- }
40
- });
41
- }
42
-
43
- setActivity(data);
44
- if (authorization) {
45
- const authorizationResponse = await authorization(data);
46
- if (authorizationResponse) {
47
- return authorizationResponse;
48
- }
49
- }
50
- return await activity(data, request);
51
- } catch (error) {
52
- console.log(`Couldn't parse`, error.toString());
53
- return NextResponse.json({ error: error.toString() }, { status: 400 });
54
- }
55
- }
56
-
57
- export async function setActivity(data: Record<string, any>) {
58
- if (data.session) {
59
- const user = (await supabase.auth.getUser(data.session)).data.user;
60
- if (user) {
61
- await supabase.from("profileActivities").upsert({
62
- uid: user.id,
63
- last_activity: Date.now(),
64
- });
65
- }
66
- }
67
- }
68
-
69
- export async function validUser(data) {
70
- if (!data.session) {
71
- return NextResponse.json(
72
- {
73
- error: "Session is missing",
74
- },
75
- { status: 501 }
76
- );
77
- }
78
-
79
- const user = await getUserBySession(data.session);
80
- if (!user) {
81
- return NextResponse.json(
82
- {
83
- error: "Invalid user session",
84
- },
85
- { status: 400 }
86
- );
87
- }
88
- }
1
+ import { NextResponse } from "next/server";
2
+ import { ZodObject } from "zod";
3
+ import { getUserBySession } from "./getUserBySession";
4
+ import { supabase } from "./supabase";
5
+
6
+ const SENSITIVE_LOG_KEYS = new Set([
7
+ "session",
8
+ "replayBytes",
9
+ "token",
10
+ "secret",
11
+ "passkey",
12
+ "passKey",
13
+ ]);
14
+ const LONG_LOG_STRING_THRESHOLD = 256;
15
+
16
+ function sanitizeForLog(
17
+ value: unknown,
18
+ key?: string
19
+ ):
20
+ | string
21
+ | number
22
+ | boolean
23
+ | null
24
+ | undefined
25
+ | Record<string, unknown>
26
+ | unknown[] {
27
+ const normalizedKey = (key || "").toLowerCase();
28
+ if (
29
+ SENSITIVE_LOG_KEYS.has(key || "") ||
30
+ SENSITIVE_LOG_KEYS.has(normalizedKey)
31
+ ) {
32
+ if (value === null || value === undefined) {
33
+ return value as null | undefined;
34
+ }
35
+ return "<Long>";
36
+ }
37
+
38
+ if (typeof value === "string") {
39
+ return value.length > LONG_LOG_STRING_THRESHOLD ? "<Long>" : value;
40
+ }
41
+
42
+ if (Array.isArray(value)) {
43
+ return value.map((item) => sanitizeForLog(item));
44
+ }
45
+
46
+ if (value && typeof value === "object") {
47
+ const sanitizedObject: Record<string, unknown> = {};
48
+ Object.entries(value as Record<string, unknown>).forEach(
49
+ ([entryKey, entryValue]) => {
50
+ sanitizedObject[entryKey] = sanitizeForLog(entryValue, entryKey);
51
+ }
52
+ );
53
+ return sanitizedObject;
54
+ }
55
+
56
+ return value as string | number | boolean | null | undefined;
57
+ }
58
+
59
+ interface Props<
60
+ K = (...args: any[]) => Promise<NextResponse<any>>,
61
+ T = ZodObject<any>,
62
+ > {
63
+ request: Request;
64
+ schema: { input: T; output: T };
65
+ authorization?: Function;
66
+ activity: K;
67
+ }
68
+
69
+ export async function protectedApi({
70
+ request,
71
+ schema,
72
+ authorization,
73
+ activity,
74
+ }: Props) {
75
+ try {
76
+ const toParse = await request.json();
77
+ const data = schema.input.parse(toParse);
78
+
79
+ console.log("Request payload:", sanitizeForLog(data));
80
+
81
+ setActivity(data);
82
+ if (authorization) {
83
+ const authorizationResponse = await authorization(data);
84
+ if (authorizationResponse) {
85
+ return authorizationResponse;
86
+ }
87
+ }
88
+ return await activity(data, request);
89
+ } catch (error) {
90
+ console.log(`Couldn't parse`, error.toString());
91
+ return NextResponse.json({ error: error.toString() }, { status: 400 });
92
+ }
93
+ }
94
+
95
+ export async function setActivity(data: Record<string, any>) {
96
+ if (data.session) {
97
+ const user = (await supabase.auth.getUser(data.session)).data.user;
98
+ if (user) {
99
+ await supabase.from("profileActivities").upsert({
100
+ uid: user.id,
101
+ last_activity: Date.now(),
102
+ });
103
+ }
104
+ }
105
+ }
106
+
107
+ export async function validUser(data) {
108
+ if (!data.session) {
109
+ return NextResponse.json(
110
+ {
111
+ error: "Session is missing",
112
+ },
113
+ { status: 501 }
114
+ );
115
+ }
116
+
117
+ const user = await getUserBySession(data.session);
118
+ if (!user) {
119
+ console.log("Invalid user session");
120
+ return NextResponse.json(
121
+ {
122
+ error: "Invalid user session",
123
+ },
124
+ { status: 401 }
125
+ );
126
+ }
127
+ }
@@ -1,82 +0,0 @@
1
- import { NextResponse } from "next/server";
2
- import z from "zod";
3
- import { protectedApi, validUser } from "../utils/requestUtils";
4
- import { supabase } from "../utils/supabase";
5
- import { getUserBySession } from "../utils/getUserBySession";
6
- import { User } from "@supabase/supabase-js";
7
-
8
- export const Schema = {
9
- input: z.strictObject({
10
- session: z.string(),
11
- mapId: z.number(),
12
- }),
13
- output: z.object({
14
- error: z.string().optional(),
15
- }),
16
- };
17
-
18
- export async function POST(request: Request) {
19
- return protectedApi({
20
- request,
21
- schema: Schema,
22
- authorization: validUser,
23
- activity: handler,
24
- });
25
- }
26
-
27
- export async function handler(data: (typeof Schema)["input"]["_type"]) {
28
- const user = (await getUserBySession(data.session)) as User;
29
- let { data: queryUserData, error: userError } = await supabase
30
- .from("profiles")
31
- .select("*")
32
- .eq("uid", user.id)
33
- .single();
34
-
35
- if (!queryUserData) {
36
- return NextResponse.json({ error: "Can't find user" });
37
- }
38
-
39
- const tags = (queryUserData?.badges || []) as string[];
40
-
41
- if (!tags.includes("RCT")) {
42
- return NextResponse.json({ error: "Only RCTs can nominate maps!" });
43
- }
44
-
45
- const { data: mapData, error } = await supabase
46
- .from("beatmapPages")
47
- .select("id,nominations,owner")
48
- .eq("id", data.mapId)
49
- .single();
50
-
51
- if (!mapData) {
52
- return NextResponse.json({ error: "Bad map" });
53
- }
54
-
55
- if (mapData.owner == queryUserData.id) {
56
- return NextResponse.json({ error: "Can't nominate own map" });
57
- }
58
-
59
- if ((mapData.nominations as number[]).includes(queryUserData.id)) {
60
- return NextResponse.json({ error: "Already nominated" });
61
- }
62
-
63
- const newNominations = [
64
- ...(mapData.nominations! as number[]),
65
- queryUserData.id,
66
- ];
67
- if (newNominations.length == 2) {
68
- await supabase.from("beatmapPages").upsert({
69
- id: data.mapId,
70
- nominations: newNominations,
71
- status: "RANKED",
72
- ranked_at: Date.now(),
73
- });
74
- } else {
75
- await supabase.from("beatmapPages").upsert({
76
- id: data.mapId,
77
- nominations: newNominations,
78
- });
79
- }
80
-
81
- return NextResponse.json({});
82
- }