|
| 1 | +import { pollDeviceToken } from "@/lib/spectrum"; |
| 2 | +import { cookies } from "next/headers"; |
| 3 | +import { NextResponse } from "next/server"; |
| 4 | + |
| 5 | +export const runtime = "nodejs"; |
| 6 | +export const dynamic = "force-dynamic"; |
| 7 | + |
| 8 | +export async function POST() { |
| 9 | + const jar = await cookies(); |
| 10 | + const deviceCode = jar.get("device_code")?.value; |
| 11 | + if (!deviceCode) { |
| 12 | + return NextResponse.json( |
| 13 | + { status: "error", reason: "no device flow in progress" }, |
| 14 | + { status: 400 }, |
| 15 | + ); |
| 16 | + } |
| 17 | + |
| 18 | + let result: Awaited<ReturnType<typeof pollDeviceToken>>; |
| 19 | + try { |
| 20 | + result = await pollDeviceToken(deviceCode); |
| 21 | + } catch (err) { |
| 22 | + console.error("[oauth/device/poll] failed:", err); |
| 23 | + const host = process.env.SPECTRUM_API_HOST ?? "<unset>"; |
| 24 | + return NextResponse.json( |
| 25 | + { status: "error", reason: `Couldn't reach Spectrum at ${host}` }, |
| 26 | + { status: 502 }, |
| 27 | + ); |
| 28 | + } |
| 29 | + |
| 30 | + if (result.ok) { |
| 31 | + jar.set("bearer", result.token.access_token, { |
| 32 | + httpOnly: true, |
| 33 | + sameSite: "lax", |
| 34 | + secure: process.env.NODE_ENV === "production", |
| 35 | + path: "/", |
| 36 | + maxAge: result.token.expires_in ?? 60 * 60 * 24 * 7, |
| 37 | + }); |
| 38 | + jar.delete("device_code"); |
| 39 | + return NextResponse.json({ status: "ok" }); |
| 40 | + } |
| 41 | + |
| 42 | + switch (result.error) { |
| 43 | + case "authorization_pending": |
| 44 | + return NextResponse.json({ status: "pending" }); |
| 45 | + case "slow_down": |
| 46 | + return NextResponse.json({ status: "slow_down" }); |
| 47 | + case "access_denied": |
| 48 | + jar.delete("device_code"); |
| 49 | + return NextResponse.json({ status: "denied" }); |
| 50 | + case "expired_token": |
| 51 | + jar.delete("device_code"); |
| 52 | + return NextResponse.json({ status: "expired" }); |
| 53 | + default: |
| 54 | + return NextResponse.json({ status: "error", reason: result.error }); |
| 55 | + } |
| 56 | +} |
0 commit comments