59 lines
2.7 KiB
TypeScript
59 lines
2.7 KiB
TypeScript
import { and, eq } from "drizzle-orm";
|
|
import * as z from "zod";
|
|
import { getDb } from "@/db";
|
|
import { commissionPushSubscriptions } from "@/db/schema";
|
|
import { pushPublicKey, validPushEndpoint } from "@/lib/commission/push";
|
|
import { requireCommissionUser } from "@/lib/commission/server";
|
|
import { errorResponse, HttpError, readJson, requireSameOrigin } from "@/lib/security/http";
|
|
import { limitRequest } from "@/lib/security/rate-limit";
|
|
|
|
const subscriptionSchema = z.object({
|
|
endpoint: z.string().max(2048),
|
|
keys: z.object({ p256dh: z.string().regex(/^[A-Za-z0-9_-]{50,200}$/),
|
|
auth: z.string().regex(/^[A-Za-z0-9_-]{10,100}$/) }),
|
|
scope: z.enum(["customer", "admin"]),
|
|
});
|
|
|
|
export async function GET() {
|
|
try {
|
|
const user = await requireCommissionUser();
|
|
const publicKey = pushPublicKey();
|
|
if (!publicKey) throw new HttpError(503, "push-not-configured");
|
|
return Response.json({ publicKey, canAdmin: user.role === "admin" && user.emailVerified },
|
|
{ headers: { "Cache-Control": "no-store" } });
|
|
} catch (cause) { return errorResponse(cause); }
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
requireSameOrigin(request);
|
|
const user = await requireCommissionUser();
|
|
if (!pushPublicKey()) throw new HttpError(503, "push-not-configured");
|
|
await limitRequest("commission-push-subscription", user.id, 60);
|
|
const parsed = subscriptionSchema.safeParse(await readJson(request, 4096));
|
|
if (!parsed.success || !validPushEndpoint(parsed.data.endpoint))
|
|
throw new HttpError(400, "invalid-push-subscription");
|
|
const { endpoint, keys, scope } = parsed.data;
|
|
if (scope === "admin" && (user.role !== "admin" || !user.emailVerified))
|
|
throw new HttpError(403, "forbidden");
|
|
await getDb().insert(commissionPushSubscriptions).values({
|
|
endpoint, userId: user.id, scope, p256dh: keys.p256dh, auth: keys.auth,
|
|
}).onConflictDoUpdate({ target: commissionPushSubscriptions.endpoint,
|
|
set: { userId: user.id, scope, p256dh: keys.p256dh, auth: keys.auth } });
|
|
return new Response(null, { status: 204 });
|
|
} catch (cause) { return errorResponse(cause); }
|
|
}
|
|
|
|
export async function DELETE(request: Request) {
|
|
try {
|
|
requireSameOrigin(request);
|
|
const user = await requireCommissionUser();
|
|
const parsed = z.object({ endpoint: z.string().max(2048) }).safeParse(await readJson(request, 4096));
|
|
if (!parsed.success) throw new HttpError(400, "invalid-push-subscription");
|
|
await getDb().delete(commissionPushSubscriptions).where(and(
|
|
eq(commissionPushSubscriptions.endpoint, parsed.data.endpoint),
|
|
eq(commissionPushSubscriptions.userId, user.id)));
|
|
return new Response(null, { status: 204 });
|
|
} catch (cause) { return errorResponse(cause); }
|
|
}
|