feat: add api key validation endpoint and update comic generation model

This commit is contained in:
Riccardo Giorato
2026-06-17 10:09:40 +02:00
parent 624a729b24
commit fbdf84fca7
6 changed files with 250 additions and 54 deletions
+3
View File
@@ -27,4 +27,7 @@ next-env.d.ts
/.clerk/ /.clerk/
.DS_Store .DS_Store
IDEAS.md IDEAS.md
.claude/launch.json
+1 -1
View File
@@ -31,7 +31,7 @@ const FIXED_DIMENSIONS = NEW_MODEL
? { width: 896, height: 1200 } ? { width: 896, height: 1200 }
: { width: 864, height: 1184 }; : { width: 864, height: 1184 };
const TEXT_MODEL = "Qwen/Qwen3-Next-80B-A3B-Instruct"; const TEXT_MODEL = "Qwen/Qwen3.5-9B";
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
+45
View File
@@ -0,0 +1,45 @@
import { type NextRequest, NextResponse } from "next/server";
import Together from "together-ai";
export async function POST(request: NextRequest) {
try {
const { apiKey } = await request.json();
if (!apiKey || typeof apiKey !== "string") {
return NextResponse.json(
{ valid: false, error: "API key is required" },
{ status: 400 },
);
}
// Dynamically fetch the fastest available model
const routerRes = await fetch("https://whichllm.together.ai/router/fast", {
next: { revalidate: 60 },
});
const { model } = await routerRes.json();
// Fire a minimal completion — 1 output token to keep cost/latency negligible
const client = new Together({ apiKey });
await client.chat.completions.create({
model,
messages: [{ role: "user", content: "hi" }],
max_tokens: 1,
});
return NextResponse.json({ valid: true });
} catch (error: unknown) {
const status =
typeof error === "object" && error !== null && "status" in error
? (error as { status: number }).status
: undefined;
if (status === 401 || status === 403) {
return NextResponse.json({ valid: false, error: "Invalid API key" });
}
return NextResponse.json(
{ valid: false, error: "Validation failed" },
{ status: 500 },
);
}
}
+140 -53
View File
@@ -2,7 +2,8 @@
import type React from "react" import type React from "react"
import { useState, useEffect } from "react" import { useState, useEffect } from "react"
import { Key, ExternalLink, ArrowRight, X } from "lucide-react" import { Key, ExternalLink, ArrowRight, X, Check } from "lucide-react"
import { motion, AnimatePresence } from "motion/react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input" import { Input } from "@/components/ui/input"
import { import {
@@ -24,10 +25,15 @@ interface ApiKeyModalProps {
export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) { export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
const [apiKeyInput, setApiKeyInput] = useState("") const [apiKeyInput, setApiKeyInput] = useState("")
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [shakeKey, setShakeKey] = useState(0)
const [success, setSuccess] = useState(false)
const [existingKey, setApiKey] = useApiKey() const [existingKey, setApiKey] = useApiKey()
useEffect(() => { useEffect(() => {
if (isOpen) { if (isOpen) {
setSuccess(false)
setError(null)
setApiKeyInput((current) => { setApiKeyInput((current) => {
if (existingKey && current === "") { if (existingKey && current === "") {
return existingKey return existingKey
@@ -42,98 +48,179 @@ export function ApiKeyModal({ isOpen, onClose, onSubmit }: ApiKeyModalProps) {
if (!apiKeyInput.trim()) return if (!apiKeyInput.trim()) return
setIsLoading(true) setIsLoading(true)
await new Promise((resolve) => setTimeout(resolve, 500)) setError(null)
try {
const res = await fetch("/api/validate-api-key", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ apiKey: apiKeyInput.trim() }),
})
const data = await res.json()
if (!data.valid) {
setError("Invalid API key. Please check and try again.")
setShakeKey((k) => k + 1)
setIsLoading(false)
return
}
} catch {
setError("Could not validate key. Please try again.")
setShakeKey((k) => k + 1)
setIsLoading(false)
return
}
setIsLoading(false) setIsLoading(false)
setSuccess(true)
onSubmit(apiKeyInput.trim()) onSubmit(apiKeyInput.trim())
setApiKeyInput("") setTimeout(() => {
setSuccess(false)
setApiKeyInput("")
}, 1400)
} }
const handleDelete = () => { const handleDelete = () => {
setApiKey(null) setApiKey(null)
setApiKeyInput("") setApiKeyInput("")
setError(null)
onClose() onClose()
} }
return ( return (
<Dialog open={isOpen} onOpenChange={onClose}> <Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="border border-border/50 rounded-lg bg-background max-w-md"> <DialogContent className="border border-border/50 rounded-xl bg-background max-w-sm p-6 overflow-hidden">
<DialogHeader className="text-center"> <AnimatePresence>
<div className="mx-auto mb-4"> {success && (
<div className="w-14 h-14 glass-panel rounded-full flex items-center justify-center"> <motion.div
<Key className="w-6 h-6 text-indigo" /> key="success"
</div> initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.2 }}
className="absolute inset-0 z-10 flex flex-col items-center justify-center gap-3 bg-background rounded-xl"
>
<motion.div
initial={{ scale: 0.5, opacity: 0 }}
animate={{ scale: 1, opacity: 1 }}
transition={{ type: "spring", stiffness: 300, damping: 20, delay: 0.05 }}
className="w-14 h-14 rounded-full bg-emerald-500/15 border border-emerald-500/30 flex items-center justify-center"
>
<Check className="w-7 h-7 text-emerald-400" strokeWidth={2.5} />
</motion.div>
<motion.p
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.15, duration: 0.2 }}
className="text-sm font-medium text-white"
>
API key saved
</motion.p>
<motion.p
initial={{ opacity: 0, y: 4 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.2, duration: 0.2 }}
className="text-xs text-muted-foreground"
>
You're all set for unlimited generation
</motion.p>
</motion.div>
)}
</AnimatePresence>
<DialogHeader className="mb-4">
<div className="flex items-center gap-2 mb-1">
<Key className="w-4 h-4 text-muted-foreground flex-shrink-0" />
<DialogTitle className="text-base font-semibold text-white leading-none">
{existingKey ? "Your API key" : "Add your API key"}
</DialogTitle>
</div> </div>
<DialogDescription className="text-sm text-muted-foreground leading-snug pl-6">
<DialogTitle className="text-xl text-center text-white">
{existingKey {existingKey
? "Update your API key" ? "Update or remove your Together AI key."
: "Add your API key to continue"} : "You've used all your free credits. Add your key for unlimited use."}
</DialogTitle>
<DialogDescription className="text-center text-muted-foreground">
{existingKey
? "Update your Together API key or add a new one. You can also delete your existing key."
: "You've used all your weekly credits! Add your Together API key for unlimited generation."}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-4"> <form onSubmit={handleSubmit} className="space-y-3">
<div className="relative"> <div className="relative">
<Input <AnimatePresence>
type="password" {error && (
value={apiKeyInput} <motion.p
onChange={(e) => setApiKeyInput(e.target.value)} key="error"
placeholder={ initial={{ opacity: 0, y: 4 }}
existingKey ? "Your current API key" : "Enter your API key..." animate={{ opacity: 1, y: 0 }}
} exit={{ opacity: 0, y: 4 }}
className="bg-secondary border-border/50 text-white placeholder-muted-foreground py-5 pr-10" transition={{ duration: 0.18, ease: "easeOut" }}
/> className="absolute bottom-full left-0 mb-1.5 text-xs text-red-400 flex items-center gap-1.5 pointer-events-none"
{apiKeyInput && ( >
<button <span className="inline-block w-1 h-1 rounded-full bg-red-400 flex-shrink-0" />
type="button" {error}
onClick={() => setApiKeyInput("")} </motion.p>
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-white transition-colors" )}
> </AnimatePresence>
<X className="w-4 h-4" />
</button> <motion.div
)} key={shakeKey}
className="relative"
animate={shakeKey > 0 ? { x: [0, -8, 8, -6, 6, -3, 3, 0] } : {}}
transition={{ duration: 0.45, ease: "easeInOut" }}
>
<Input
type="password"
value={apiKeyInput}
onChange={(e) => { setApiKeyInput(e.target.value); setError(null) }}
placeholder="sk-"
className={`bg-secondary border-border/50 text-white placeholder-muted-foreground/40 py-5 pr-10 font-mono text-sm transition-colors duration-200 ${error ? "border-red-500/60 focus-visible:ring-red-500/20" : ""}`}
/>
{apiKeyInput && (
<button
type="button"
onClick={() => setApiKeyInput("")}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-white transition-colors"
>
<X className="w-4 h-4" />
</button>
)}
</motion.div>
</div> </div>
<a <a
href={TOGETHER_LINK} href={TOGETHER_LINK}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
className="text-sm text-indigo hover:text-indigo-light flex items-center gap-1.5 transition-colors" className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-white transition-colors"
> >
Get your Together API key Get a free Together AI key
<ExternalLink className="h-3.5 w-3.5" /> <ExternalLink className="h-3 w-3" />
</a> </a>
<div className="flex gap-3 pt-2"> <div className="flex gap-2 pt-1">
<Button <Button
type="button" type="button"
variant="ghost" variant="outline"
onClick={existingKey ? handleDelete : onClose} onClick={existingKey ? handleDelete : onClose}
className="flex-1 text-muted-foreground hover:text-white hover:bg-secondary" className={`flex-1 border-border/50 hover:border-border transition-colors ${
existingKey
? "text-red-400 border-red-500/30 hover:bg-red-500/10 hover:border-red-500/50 hover:text-red-300"
: "text-muted-foreground hover:text-white hover:bg-secondary"
}`}
> >
{existingKey ? "Delete API Key" : "Maybe Later"} {existingKey ? "Delete" : "Later"}
</Button> </Button>
<Button <Button
type="submit" type="submit"
disabled={!apiKeyInput.trim() || isLoading} disabled={!apiKeyInput.trim() || isLoading}
className="flex-1 gap-2 bg-white hover:bg-neutral-200 text-black" className="flex-[2] gap-2 bg-white hover:bg-neutral-200 text-black font-medium"
> >
{isLoading ? "Validating..." : "Continue"} {isLoading ? "Checking" : "Save key"}
<ArrowRight className="w-4 h-4" /> {!isLoading && <ArrowRight className="w-4 h-4" />}
</Button> </Button>
</div> </div>
</form>
<div className="mt-4 p-3 glass-panel rounded-lg"> <p className="text-xs text-muted-foreground/50 text-center pt-1">
<p className="text-xs text-muted-foreground text-center"> Stored locally · never sent to our servers
Your API key is stored locally and never stored on our servers.
</p> </p>
</div> </form>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
) )
+1
View File
@@ -54,6 +54,7 @@
"input-otp": "1.4.2", "input-otp": "1.4.2",
"jspdf": "^4.2.1", "jspdf": "^4.2.1",
"lucide-react": "^1.20.0", "lucide-react": "^1.20.0",
"motion": "^12.40.0",
"next": "16.2.9", "next": "16.2.9",
"next-plausible": "^4.0.0", "next-plausible": "^4.0.0",
"next-s3-upload": "^0.3.4", "next-s3-upload": "^0.3.4",
+60
View File
@@ -149,6 +149,9 @@ importers:
lucide-react: lucide-react:
specifier: ^1.20.0 specifier: ^1.20.0
version: 1.20.0(react@19.2.7) version: 1.20.0(react@19.2.7)
motion:
specifier: ^12.40.0
version: 12.40.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
next: next:
specifier: 16.2.9 specifier: 16.2.9
version: 16.2.9(react-dom@19.2.7(react@19.2.7))(react@19.2.7) version: 16.2.9(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
@@ -2888,6 +2891,20 @@ packages:
fraction.js@5.3.4: fraction.js@5.3.4:
resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==} resolution: {integrity: sha512-1X1NTtiJphryn/uLQz3whtY6jK3fTqoE3ohKs0tT+Ujr1W59oopxmoEh7Lu5p6vBaPbgoM0bzveAW4Qi5RyWDQ==}
framer-motion@12.40.0:
resolution: {integrity: sha512-uaBd3qC1v3KQqBEjwTUd183K6PbS+j0yR9w9VmEOLWA/tnUcSn8Xa3uck7t4dgpDoUss8xQTcj8W2L07lrnLFg==}
peerDependencies:
'@emotion/is-prop-valid': '*'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@emotion/is-prop-valid':
optional: true
react:
optional: true
react-dom:
optional: true
fsevents@2.3.3: fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -3028,6 +3045,26 @@ packages:
magic-string@0.30.21: magic-string@0.30.21:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
motion-dom@12.40.0:
resolution: {integrity: sha512-HxU3ZaBwNPVQUBQf1xxgq+7JrPNZvjLVxgbpEZL7RrWJnsxOf0/OM+yrHG9ogLQ31Do/r57Oz2gQWPK+6q62mg==}
motion-utils@12.39.0:
resolution: {integrity: sha512-8nadJAJjTtqRkmRF36FoJTrywK9nnFmnPwnSMyxaOCU7GDjN9RTMJIxx9De8ErM+vpPhMccr/6fo5WciyQLnMQ==}
motion@12.40.0:
resolution: {integrity: sha512-yjrHUrBFW6kQvjJwRsoiPSAhC5tRwRqNGJWmiJ4CrGnbKp0V88AdzkhBmDoqIsIPfarOe0Uddd37Xq43/gIocA==}
peerDependencies:
'@emotion/is-prop-valid': '*'
react: ^18.0.0 || ^19.0.0
react-dom: ^18.0.0 || ^19.0.0
peerDependenciesMeta:
'@emotion/is-prop-valid':
optional: true
react:
optional: true
react-dom:
optional: true
nanoid@3.3.12: nanoid@3.3.12:
resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==} resolution: {integrity: sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
@@ -6481,6 +6518,15 @@ snapshots:
fraction.js@5.3.4: {} fraction.js@5.3.4: {}
framer-motion@12.40.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
dependencies:
motion-dom: 12.40.0
motion-utils: 12.39.0
tslib: 2.8.1
optionalDependencies:
react: 19.2.7
react-dom: 19.2.7(react@19.2.7)
fsevents@2.3.3: fsevents@2.3.3:
optional: true optional: true
@@ -6589,6 +6635,20 @@ snapshots:
dependencies: dependencies:
'@jridgewell/sourcemap-codec': 1.5.5 '@jridgewell/sourcemap-codec': 1.5.5
motion-dom@12.40.0:
dependencies:
motion-utils: 12.39.0
motion-utils@12.39.0: {}
motion@12.40.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7):
dependencies:
framer-motion: 12.40.0(react-dom@19.2.7(react@19.2.7))(react@19.2.7)
tslib: 2.8.1
optionalDependencies:
react: 19.2.7
react-dom: 19.2.7(react@19.2.7)
nanoid@3.3.12: {} nanoid@3.3.12: {}
next-plausible@4.0.0(next@16.2.9(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7): next-plausible@4.0.0(next@16.2.9(react-dom@19.2.7(react@19.2.7))(react@19.2.7))(react-dom@19.2.7(react@19.2.7))(react@19.2.7):