forked from codechefPesuecc/CodeChef-PESUECC-Chapter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathroute.ts
More file actions
235 lines (215 loc) · 7.99 KB
/
Copy pathroute.ts
File metadata and controls
235 lines (215 loc) · 7.99 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
import crypto from "node:crypto";
import { NextResponse } from "next/server";
import { and, eq } from "drizzle-orm";
import { getDb } from "@/server/db";
import { submissions, attempts } from "@/server/db/schema";
import { getCurrentUser } from "@/server/auth/session";
import { getDailyChallenge } from "@/lib/challenges";
import { judge } from "@/server/judge";
import { hasSolvedRanked } from "@/server/solves";
import { rateLimit, clientIp } from "@/server/rateLimit";
import { verifyTurnstile } from "@/server/turnstile";
import { PISTON_LANGUAGE } from "@/lib/piston";
import {
bodyTooLarge,
tooLong,
MAX_CODE_CHARS,
MAX_FLAGS_BREAKDOWN_CHARS,
} from "@/server/limits";
export const dynamic = "force-dynamic";
// Read per-request, not at import: on Workers env vars/secrets are only reliably
// in process.env within a request scope (see auth/token.ts).
function requireVerified(): boolean {
return process.env.REQUIRE_EMAIL_VERIFICATION === "true";
}
// Per-user submission cap — the FIFO judge queue bounds throughput, this bounds
// spam per account before it ever reaches the queue.
const SUBMIT_LIMIT = 20;
const SUBMIT_WINDOW_MS = 60_000;
/**
* Graded submission: requires login, runs the code against the hidden tests, and
* records the result server-side (which is what makes the leaderboard real and
* the solve time unspoofable). Hidden test data never leaves the server.
*/
export async function POST(req: Request) {
const user = await getCurrentUser();
if (!user) {
return NextResponse.json(
{ ok: false, error: "Log in to submit.", needsAuth: true },
{ status: 401 },
);
}
if (requireVerified() && !user.emailVerified) {
return NextResponse.json(
{ ok: false, error: "Verify your email before submitting.", needsVerify: true },
{ status: 403 },
);
}
const limit = await rateLimit(`submit:user:${user.id}`, SUBMIT_LIMIT, SUBMIT_WINDOW_MS);
if (!limit.ok) {
return NextResponse.json(
{
ok: false,
error: `Too many submissions — try again in ${Math.ceil(limit.retryAfterMs / 1000)}s.`,
rateLimited: true,
},
{ status: 429, headers: { "Retry-After": String(Math.ceil(limit.retryAfterMs / 1000)) } },
);
}
const oversize = bodyTooLarge(req);
if (oversize) return oversize;
let body: {
slug?: string;
language?: string;
code?: string;
elapsedSeconds?: number;
flags?: number;
flagsBreakdown?: unknown;
turnstileToken?: string;
};
try {
body = await req.json();
} catch {
return NextResponse.json({ ok: false, error: "Invalid JSON body." }, { status: 400 });
}
const { slug, language, code } = body;
if (!slug || !language || typeof code !== "string") {
return NextResponse.json(
{ ok: false, error: "slug, language and code are required." },
{ status: 400 },
);
}
const codeTooLong = tooLong(code, MAX_CODE_CHARS, "Code");
if (codeTooLong) return codeTooLong;
if (!PISTON_LANGUAGE[language]) {
return NextResponse.json(
{ ok: false, error: `Unsupported language: ${language}.` },
{ status: 400 },
);
}
// Bot check (no-op unless TURNSTILE_SECRET_KEY is configured).
const turnstile = await verifyTurnstile(body.turnstileToken, clientIp(req));
if (!turnstile.ok) {
return NextResponse.json(
{ ok: false, error: turnstile.error, needsTurnstile: true },
{ status: 403 },
);
}
// Only the current Problem of the Day is ranked (speed-bounty by finish order).
// A past problem is practice: an accepted solve earns the flat base score, but
// it never mints speed-bounty points or shifts the live board.
const daily = await getDailyChallenge();
const ranked = daily?.slug === slug;
// Hide-after-solve, enforced server-side: once a user has a live AC for today's
// problem, the solve page stops serving it AND a crafted re-submit is rejected.
// This also guarantees exactly one ranked award per (user, problem).
if (ranked) {
try {
if (await hasSolvedRanked(user.id, slug)) {
return NextResponse.json(
{ ok: false, alreadySolved: true, error: "You've already solved today's problem." },
{ status: 409 },
);
}
} catch (error) {
console.error("[submit] failed to check for an existing solve:", error);
}
}
const result = await judge({ slug, language, code });
if (result.verdict === "ERR") {
return NextResponse.json({ ok: false, error: result.message ?? "Judge error." }, { status: 503 });
}
// The official solve time is server-authoritative: the submit time minus the
// first-open time recorded in `attempts` — never the client's stopwatch.
const submittedAt = Date.now();
let elapsedSeconds: number | null = null;
// Record every ranked judged submission (audit trail + leaderboard source).
let persistFailed = false;
if (ranked) {
const db = getDb();
try {
const startRows = await db
.select({ startedAt: attempts.startedAt })
.from(attempts)
.where(and(eq(attempts.userId, user.id), eq(attempts.challengeSlug, slug)))
.limit(1);
const startedAt = startRows[0]?.startedAt;
if (typeof startedAt === "number") {
elapsedSeconds = Math.max(0, Math.round((submittedAt - startedAt) / 1000));
}
} catch (error) {
console.error("[submit] failed to read attempt start:", error);
}
// Client-supplied integrity detail is diagnostic only; drop it if it's
// oversized rather than storing an unbounded blob.
const rawBreakdown =
body.flagsBreakdown != null ? JSON.stringify(body.flagsBreakdown) : null;
const flagsBreakdown =
rawBreakdown && rawBreakdown.length <= MAX_FLAGS_BREAKDOWN_CHARS
? rawBreakdown
: null;
try {
await db.insert(submissions).values({
id: crypto.randomUUID(),
challengeSlug: slug,
userId: user.id,
language,
code,
status: result.verdict,
elapsedSeconds,
flags: typeof body.flags === "number" ? Math.max(0, Math.round(body.flags)) : 0,
flagsBreakdown,
ranked: true,
createdAt: submittedAt,
});
} catch (error) {
console.error("[submit] failed to record submission:", error);
persistFailed = true;
}
// For a ranked AC whose insert succeeded, read back the user's authoritative
// rank/points from the DB state that just recorded the submission — the
// client can use this directly instead of relying on a potentially-stale
// board re-fetch (D1 read-after-write lag).
if (result.verdict === "AC" && !persistFailed) {
try {
const { todayLeaderboard } = await import("@/server/leaderboard");
const board = await todayLeaderboard();
const me = board.find((r) => r.display === (user.srn ?? user.prn));
return NextResponse.json({
ok: true,
practice: false,
...result,
elapsedSeconds,
persistFailed,
rank: me?.rank ?? null,
points: me?.points ?? null,
flagged: me?.flagged ?? false,
});
} catch (error) {
console.error("[submit] failed to compute post-AC standings:", error);
// Fall through to the generic response — client will use board fetch.
}
}
} else if (result.verdict === "AC") {
// Past-problem practice: record the accepted solve so it earns the flat base
// score on the aggregate boards. No attempt clock and no proctoring flags.
try {
await getDb().insert(submissions).values({
id: crypto.randomUUID(),
challengeSlug: slug,
userId: user.id,
language,
code,
status: result.verdict,
elapsedSeconds: null,
flags: 0,
flagsBreakdown: null,
ranked: false,
createdAt: submittedAt,
});
} catch (error) {
console.error("[submit] failed to record practice solve:", error);
}
}
return NextResponse.json({ ok: true, practice: !ranked, ...result, elapsedSeconds, ...(ranked ? { persistFailed } : {}) });
}