Compare commits
2 Commits
b2f2274673
...
96ef5b8379
| Author | SHA1 | Date | |
|---|---|---|---|
| 96ef5b8379 | |||
| 0062220d8e |
@@ -18,6 +18,7 @@ export default async function ApiKeysPage() {
|
|||||||
.select({
|
.select({
|
||||||
id: apiKeys.id,
|
id: apiKeys.id,
|
||||||
name: apiKeys.name,
|
name: apiKeys.name,
|
||||||
|
scope: apiKeys.scope,
|
||||||
lastUsedAt: apiKeys.lastUsedAt,
|
lastUsedAt: apiKeys.lastUsedAt,
|
||||||
createdAt: apiKeys.createdAt,
|
createdAt: apiKeys.createdAt,
|
||||||
})
|
})
|
||||||
@@ -45,6 +46,7 @@ export default async function ApiKeysPage() {
|
|||||||
initialKeys={keys.map((k) => ({
|
initialKeys={keys.map((k) => ({
|
||||||
id: k.id,
|
id: k.id,
|
||||||
name: k.name,
|
name: k.name,
|
||||||
|
scope: k.scope,
|
||||||
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
lastUsedAt: k.lastUsedAt ? k.lastUsedAt.toISOString() : null,
|
||||||
createdAt: k.createdAt.toISOString(),
|
createdAt: k.createdAt.toISOString(),
|
||||||
}))}
|
}))}
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { db, chatMessages, eq, and, isNull, desc, asc, ilike } from "@epicure/db";
|
||||||
|
import { requireSession } from "@/lib/api-auth";
|
||||||
|
|
||||||
|
const Schema = z.object({
|
||||||
|
recipeId: z.string().uuid().optional(),
|
||||||
|
// "general" restricts to the homepage cooking assistant (recipeId null);
|
||||||
|
// omit both recipeId and scope to search across everything.
|
||||||
|
scope: z.enum(["general"]).optional(),
|
||||||
|
q: z.string().max(200).optional(),
|
||||||
|
limit: z.coerce.number().int().min(1).max(100).default(30),
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function GET(req: NextRequest) {
|
||||||
|
const { session, response } = await requireSession();
|
||||||
|
if (response) return response;
|
||||||
|
|
||||||
|
const { searchParams } = new URL(req.url);
|
||||||
|
const parsed = Schema.safeParse({
|
||||||
|
recipeId: searchParams.get("recipeId") ?? undefined,
|
||||||
|
scope: searchParams.get("scope") ?? undefined,
|
||||||
|
q: searchParams.get("q") ?? undefined,
|
||||||
|
limit: searchParams.get("limit") ?? undefined,
|
||||||
|
});
|
||||||
|
if (!parsed.success) {
|
||||||
|
return NextResponse.json({ error: "Validation error" }, { status: 400 });
|
||||||
|
}
|
||||||
|
const { recipeId, scope, q, limit } = parsed.data;
|
||||||
|
|
||||||
|
const conditions = [eq(chatMessages.userId, session!.user.id)];
|
||||||
|
if (recipeId) conditions.push(eq(chatMessages.recipeId, recipeId));
|
||||||
|
else if (scope === "general") conditions.push(isNull(chatMessages.recipeId));
|
||||||
|
if (q?.trim()) conditions.push(ilike(chatMessages.content, `%${q.trim()}%`));
|
||||||
|
|
||||||
|
const rows = await db.query.chatMessages.findMany({
|
||||||
|
where: and(...conditions),
|
||||||
|
orderBy: q?.trim() ? [desc(chatMessages.createdAt)] : [asc(chatMessages.createdAt)],
|
||||||
|
limit,
|
||||||
|
with: { recipe: { columns: { id: true, title: true } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
return NextResponse.json({
|
||||||
|
data: rows.map((r) => ({
|
||||||
|
id: r.id,
|
||||||
|
role: r.role,
|
||||||
|
content: r.content,
|
||||||
|
createdAt: r.createdAt.toISOString(),
|
||||||
|
recipeId: r.recipeId,
|
||||||
|
recipeTitle: r.recipe?.title ?? null,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
import { NextRequest, NextResponse } from "next/server";
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { generateText } from "ai";
|
import { generateText } from "ai";
|
||||||
|
import { db, chatMessages } from "@epicure/db";
|
||||||
import { requireSession } from "@/lib/api-auth";
|
import { requireSession } from "@/lib/api-auth";
|
||||||
import { applyRateLimit } from "@/lib/rate-limit";
|
import { applyRateLimit } from "@/lib/rate-limit";
|
||||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||||
@@ -46,5 +47,10 @@ export async function POST(req: NextRequest) {
|
|||||||
);
|
);
|
||||||
if (!result.ok) return result.response;
|
if (!result.ok) return result.response;
|
||||||
|
|
||||||
|
void db.insert(chatMessages).values([
|
||||||
|
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: null, role: "user", content: parsed.data.question },
|
||||||
|
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: null, role: "assistant", content: result.data.text },
|
||||||
|
]).catch((err) => console.error("[cooking-chat] failed to persist chat history", err));
|
||||||
|
|
||||||
return NextResponse.json({ answer: result.data.text });
|
return NextResponse.json({ answer: result.data.text });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import { applyRateLimit } from "@/lib/rate-limit";
|
|||||||
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
import { withAiQuota, resolveAiConfigOrError } from "@/lib/ai/ai-error";
|
||||||
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
import { getModelConfigForUseCase } from "@/lib/ai/resolve-user-key";
|
||||||
import { resolveModel } from "@/lib/ai/factory";
|
import { resolveModel } from "@/lib/ai/factory";
|
||||||
import { db, recipes, eq, and } from "@epicure/db";
|
import { db, recipes, chatMessages, eq, and } from "@epicure/db";
|
||||||
import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
|
import { getUserPrivateBio, buildUserBioContext } from "@/lib/ai/user-bio";
|
||||||
import { hasQuantity } from "@/lib/fractions";
|
import { hasQuantity } from "@/lib/fractions";
|
||||||
|
|
||||||
@@ -84,5 +84,10 @@ ${recipeContext}${bioContext}`,
|
|||||||
);
|
);
|
||||||
if (!result.ok) return result.response;
|
if (!result.ok) return result.response;
|
||||||
|
|
||||||
|
void db.insert(chatMessages).values([
|
||||||
|
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: recipe.id, role: "user", content: parsed.data.question },
|
||||||
|
{ id: crypto.randomUUID(), userId: session!.user.id, recipeId: recipe.id, role: "assistant", content: result.data.text },
|
||||||
|
]).catch((err) => console.error("[recipe-chat] failed to persist chat history", err));
|
||||||
|
|
||||||
return NextResponse.json({ answer: result.data.text });
|
return NextResponse.json({ answer: result.data.text });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { requireSession } from "@/lib/api-auth";
|
|||||||
|
|
||||||
const CreateApiKeyBody = z.object({
|
const CreateApiKeyBody = z.object({
|
||||||
name: z.string().min(1).max(100),
|
name: z.string().min(1).max(100),
|
||||||
|
scope: z.enum(["full", "read"]).default("full"),
|
||||||
});
|
});
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
@@ -16,6 +17,7 @@ export async function GET() {
|
|||||||
.select({
|
.select({
|
||||||
id: apiKeys.id,
|
id: apiKeys.id,
|
||||||
name: apiKeys.name,
|
name: apiKeys.name,
|
||||||
|
scope: apiKeys.scope,
|
||||||
lastUsedAt: apiKeys.lastUsedAt,
|
lastUsedAt: apiKeys.lastUsedAt,
|
||||||
createdAt: apiKeys.createdAt,
|
createdAt: apiKeys.createdAt,
|
||||||
})
|
})
|
||||||
@@ -56,11 +58,12 @@ export async function POST(req: NextRequest) {
|
|||||||
userId: session!.user.id,
|
userId: session!.user.id,
|
||||||
name: parsed.data.name,
|
name: parsed.data.name,
|
||||||
keyHash,
|
keyHash,
|
||||||
|
scope: parsed.data.scope,
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
});
|
});
|
||||||
|
|
||||||
return NextResponse.json(
|
return NextResponse.json(
|
||||||
{ id, name: parsed.data.name, key: rawKey, createdAt: now.toISOString() },
|
{ id, name: parsed.data.name, scope: parsed.data.scope, key: rawKey, createdAt: now.toISOString() },
|
||||||
{ status: 201 }
|
{ status: 201 }
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import { Search, X, Bot, User } from "lucide-react";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
|
type SearchResult = {
|
||||||
|
id: string;
|
||||||
|
role: "user" | "assistant";
|
||||||
|
content: string;
|
||||||
|
createdAt: string;
|
||||||
|
recipeId: string | null;
|
||||||
|
recipeTitle: string | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Search across the user's own AI-chat history. With `recipeId` set, scopes
|
||||||
|
* to that recipe's conversation; omit it to search everything the user has
|
||||||
|
* ever asked (both per-recipe chats and the general cooking assistant).
|
||||||
|
*/
|
||||||
|
export function ChatHistorySearch({ recipeId }: { recipeId?: string }) {
|
||||||
|
const t = useTranslations("chatHistory");
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [results, setResults] = useState<SearchResult[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
function handleClickOutside(e: MouseEvent) {
|
||||||
|
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener("mousedown", handleClickOutside);
|
||||||
|
return () => document.removeEventListener("mousedown", handleClickOutside);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!query.trim()) return;
|
||||||
|
const timeout = setTimeout(() => {
|
||||||
|
setLoading(true);
|
||||||
|
const params = new URLSearchParams({ q: query.trim() });
|
||||||
|
if (recipeId) params.set("recipeId", recipeId);
|
||||||
|
fetch(`/api/v1/ai/chat-history?${params.toString()}`)
|
||||||
|
.then((res) => (res.ok ? res.json() : null))
|
||||||
|
.then((json: { data?: SearchResult[] } | null) => setResults(json?.data ?? []))
|
||||||
|
.catch(() => setResults([]))
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, 300);
|
||||||
|
return () => clearTimeout(timeout);
|
||||||
|
}, [query, recipeId]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={containerRef} className="relative">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen((v) => !v)}
|
||||||
|
className="p-1.5 rounded-md hover:bg-muted transition-colors text-muted-foreground"
|
||||||
|
aria-label={t("searchAriaLabel")}
|
||||||
|
>
|
||||||
|
<Search className="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<div className="absolute right-0 top-full mt-1 w-80 rounded-lg border bg-popover shadow-lg z-50 max-h-96 flex flex-col">
|
||||||
|
<div className="p-2 border-b flex items-center gap-1">
|
||||||
|
<Input
|
||||||
|
autoFocus
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
placeholder={t("searchPlaceholder")}
|
||||||
|
className="h-8 text-sm"
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
className="p-1.5 rounded-md hover:bg-muted text-muted-foreground shrink-0"
|
||||||
|
aria-label={t("close")}
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div className="overflow-y-auto flex-1 p-1">
|
||||||
|
{loading && <p className="text-xs text-muted-foreground text-center py-4">{t("searching")}</p>}
|
||||||
|
{!loading && query.trim() && results.length === 0 && (
|
||||||
|
<p className="text-xs text-muted-foreground text-center py-4">{t("noResults")}</p>
|
||||||
|
)}
|
||||||
|
{!loading && query.trim() && results.map((r) => (
|
||||||
|
<div key={r.id} className="p-2 rounded-md hover:bg-muted/50 text-sm space-y-1">
|
||||||
|
<div className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||||
|
{r.role === "user" ? <User className="h-3 w-3" /> : <Bot className="h-3 w-3" />}
|
||||||
|
<span>{new Date(r.createdAt).toLocaleDateString()}</span>
|
||||||
|
{r.recipeTitle && !recipeId && (
|
||||||
|
<span className="truncate">· {r.recipeTitle}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className={cn("line-clamp-2", r.role === "user" && "font-medium")}>{r.content}</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -8,12 +8,15 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sh
|
|||||||
import { MessageCircle, Send, Bot, User } from "lucide-react";
|
import { MessageCircle, Send, Bot, User } from "lucide-react";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ChatHistorySearch } from "./chat-history-search";
|
||||||
|
|
||||||
type Message = {
|
type Message = {
|
||||||
role: "user" | "assistant";
|
role: "user" | "assistant";
|
||||||
content: string;
|
content: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type HistoryEntry = { role: "user" | "assistant"; content: string };
|
||||||
|
|
||||||
export function CookingAssistantPanel() {
|
export function CookingAssistantPanel() {
|
||||||
const t = useTranslations("cookingChat");
|
const t = useTranslations("cookingChat");
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
@@ -21,6 +24,18 @@ export function CookingAssistantPanel() {
|
|||||||
const [input, setInput] = useState("");
|
const [input, setInput] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const bottomRef = useRef<HTMLDivElement>(null);
|
const bottomRef = useRef<HTMLDivElement>(null);
|
||||||
|
const historyLoadedRef = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || historyLoadedRef.current) return;
|
||||||
|
historyLoadedRef.current = true;
|
||||||
|
fetch("/api/v1/ai/chat-history?scope=general&limit=50")
|
||||||
|
.then((res) => (res.ok ? res.json() : null))
|
||||||
|
.then((json: { data?: HistoryEntry[] } | null) => {
|
||||||
|
if (json?.data?.length) setMessages(json.data.map((m) => ({ role: m.role, content: m.content })));
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, [open]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open && bottomRef.current) {
|
if (open && bottomRef.current) {
|
||||||
@@ -83,10 +98,13 @@ export function CookingAssistantPanel() {
|
|||||||
<Sheet open={open} onOpenChange={setOpen}>
|
<Sheet open={open} onOpenChange={setOpen}>
|
||||||
<SheetContent side="right" className="w-full sm:w-[420px] flex flex-col p-0">
|
<SheetContent side="right" className="w-full sm:w-[420px] flex flex-col p-0">
|
||||||
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
|
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
|
||||||
<SheetTitle className="text-base flex items-center gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<Bot className="h-4 w-4 text-primary" />
|
<SheetTitle className="text-base flex items-center gap-2">
|
||||||
{t("title")}
|
<Bot className="h-4 w-4 text-primary" />
|
||||||
</SheetTitle>
|
{t("title")}
|
||||||
|
</SheetTitle>
|
||||||
|
<ChatHistorySearch />
|
||||||
|
</div>
|
||||||
<p className="text-xs text-muted-foreground text-left">{t("subtitle")}</p>
|
<p className="text-xs text-muted-foreground text-left">{t("subtitle")}</p>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
|
|
||||||
|
|||||||
@@ -8,12 +8,15 @@ import { Sheet, SheetContent, SheetHeader, SheetTitle } from "@/components/ui/sh
|
|||||||
import { MessageCircle, Send, Bot, User } from "lucide-react";
|
import { MessageCircle, Send, Bot, User } from "lucide-react";
|
||||||
import ReactMarkdown from "react-markdown";
|
import ReactMarkdown from "react-markdown";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
import { ChatHistorySearch } from "./chat-history-search";
|
||||||
|
|
||||||
type Message = {
|
type Message = {
|
||||||
role: "user" | "assistant";
|
role: "user" | "assistant";
|
||||||
content: string;
|
content: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type HistoryEntry = { role: "user" | "assistant"; content: string };
|
||||||
|
|
||||||
type Props = {
|
type Props = {
|
||||||
recipeId: string;
|
recipeId: string;
|
||||||
recipeTitle: string;
|
recipeTitle: string;
|
||||||
@@ -26,6 +29,18 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
|
|||||||
const [input, setInput] = useState("");
|
const [input, setInput] = useState("");
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
const bottomRef = useRef<HTMLDivElement>(null);
|
const bottomRef = useRef<HTMLDivElement>(null);
|
||||||
|
const historyLoadedRef = useRef(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || historyLoadedRef.current) return;
|
||||||
|
historyLoadedRef.current = true;
|
||||||
|
fetch(`/api/v1/ai/chat-history?recipeId=${recipeId}&limit=50`)
|
||||||
|
.then((res) => (res.ok ? res.json() : null))
|
||||||
|
.then((json: { data?: HistoryEntry[] } | null) => {
|
||||||
|
if (json?.data?.length) setMessages(json.data.map((m) => ({ role: m.role, content: m.content })));
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
}, [open, recipeId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (open && bottomRef.current) {
|
if (open && bottomRef.current) {
|
||||||
@@ -85,10 +100,13 @@ export function RecipeChatPanel({ recipeId, recipeTitle }: Props) {
|
|||||||
<Sheet open={open} onOpenChange={setOpen}>
|
<Sheet open={open} onOpenChange={setOpen}>
|
||||||
<SheetContent side="right" className="w-full sm:w-[420px] flex flex-col p-0">
|
<SheetContent side="right" className="w-full sm:w-[420px] flex flex-col p-0">
|
||||||
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
|
<SheetHeader className="px-4 py-3 pr-10 border-b shrink-0">
|
||||||
<SheetTitle className="text-base flex items-center gap-2">
|
<div className="flex items-center justify-between gap-2">
|
||||||
<Bot className="h-4 w-4 text-primary" />
|
<SheetTitle className="text-base flex items-center gap-2">
|
||||||
{t("title")}
|
<Bot className="h-4 w-4 text-primary" />
|
||||||
</SheetTitle>
|
{t("title")}
|
||||||
|
</SheetTitle>
|
||||||
|
<ChatHistorySearch recipeId={recipeId} />
|
||||||
|
</div>
|
||||||
<p className="text-xs text-muted-foreground text-left">{recipeTitle}</p>
|
<p className="text-xs text-muted-foreground text-left">{recipeTitle}</p>
|
||||||
</SheetHeader>
|
</SheetHeader>
|
||||||
|
|
||||||
|
|||||||
@@ -7,10 +7,14 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||||
|
|
||||||
|
type ApiKeyScope = "full" | "read";
|
||||||
|
|
||||||
type ApiKey = {
|
type ApiKey = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
scope: ApiKeyScope;
|
||||||
lastUsedAt: string | null;
|
lastUsedAt: string | null;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
};
|
};
|
||||||
@@ -18,6 +22,7 @@ type ApiKey = {
|
|||||||
type CreateApiKeyResponse = {
|
type CreateApiKeyResponse = {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
scope: ApiKeyScope;
|
||||||
key: string;
|
key: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
};
|
};
|
||||||
@@ -34,6 +39,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
|
|||||||
const t = useTranslations("settingsForm");
|
const t = useTranslations("settingsForm");
|
||||||
const [keys, setKeys] = useState<ApiKey[]>(initialKeys);
|
const [keys, setKeys] = useState<ApiKey[]>(initialKeys);
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
|
const [scope, setScope] = useState<ApiKeyScope>("full");
|
||||||
const [creating, setCreating] = useState(false);
|
const [creating, setCreating] = useState(false);
|
||||||
const [newKey, setNewKey] = useState<string | null>(null);
|
const [newKey, setNewKey] = useState<string | null>(null);
|
||||||
const [copied, setCopied] = useState(false);
|
const [copied, setCopied] = useState(false);
|
||||||
@@ -46,7 +52,7 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
|
|||||||
const res = await fetch("/api/v1/api-keys", {
|
const res = await fetch("/api/v1/api-keys", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ name: name.trim() }),
|
body: JSON.stringify({ name: name.trim(), scope }),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const data = await res.json() as { error?: string };
|
const data = await res.json() as { error?: string };
|
||||||
@@ -55,10 +61,11 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
|
|||||||
const data = await res.json() as CreateApiKeyResponse;
|
const data = await res.json() as CreateApiKeyResponse;
|
||||||
setNewKey(data.key);
|
setNewKey(data.key);
|
||||||
setKeys((prev) => [
|
setKeys((prev) => [
|
||||||
{ id: data.id, name: data.name, lastUsedAt: null, createdAt: data.createdAt },
|
{ id: data.id, name: data.name, scope: data.scope, lastUsedAt: null, createdAt: data.createdAt },
|
||||||
...prev,
|
...prev,
|
||||||
]);
|
]);
|
||||||
setName("");
|
setName("");
|
||||||
|
setScope("full");
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.error(err instanceof Error ? err.message : t("apiKeyCreateFailed"));
|
toast.error(err instanceof Error ? err.message : t("apiKeyCreateFailed"));
|
||||||
} finally {
|
} finally {
|
||||||
@@ -105,10 +112,20 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
|
|||||||
maxLength={100}
|
maxLength={100}
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
<Select value={scope} onValueChange={(v) => setScope(v as ApiKeyScope)}>
|
||||||
|
<SelectTrigger className="w-36">
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="full">{t("apiKeyScopeFull")}</SelectItem>
|
||||||
|
<SelectItem value="read">{t("apiKeyScopeRead")}</SelectItem>
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
<Button type="submit" disabled={creating || !name.trim()}>
|
<Button type="submit" disabled={creating || !name.trim()}>
|
||||||
{creating ? t("apiKeyCreating") : t("apiKeyCreate")}
|
{creating ? t("apiKeyCreating") : t("apiKeyCreate")}
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">{t("apiKeyScopeHelp")}</p>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
@@ -146,7 +163,12 @@ export function ApiKeysManager({ initialKeys }: { initialKeys: ApiKey[] }) {
|
|||||||
{keys.map((k) => (
|
{keys.map((k) => (
|
||||||
<div key={k.id} className="flex items-center justify-between px-4 py-3 gap-4">
|
<div key={k.id} className="flex items-center justify-between px-4 py-3 gap-4">
|
||||||
<div className="min-w-0 flex-1 space-y-1">
|
<div className="min-w-0 flex-1 space-y-1">
|
||||||
<p className="text-sm font-medium truncate">{k.name}</p>
|
<div className="flex items-center gap-2">
|
||||||
|
<p className="text-sm font-medium truncate">{k.name}</p>
|
||||||
|
<Badge variant={k.scope === "read" ? "secondary" : "default"} className="text-xs">
|
||||||
|
{k.scope === "read" ? t("apiKeyScopeRead") : t("apiKeyScopeFull")}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
<span>{t("createdOn", { date: formatDate(k.createdAt) })}</span>
|
<span>{t("createdOn", { date: formatDate(k.createdAt) })}</span>
|
||||||
<span>·</span>
|
<span>·</span>
|
||||||
|
|||||||
@@ -57,12 +57,22 @@ export async function requireSessionOrApiKey(
|
|||||||
const keyHash = crypto.createHash("sha256").update(rawKey).digest("hex");
|
const keyHash = crypto.createHash("sha256").update(rawKey).digest("hex");
|
||||||
|
|
||||||
const [keyRow] = await db
|
const [keyRow] = await db
|
||||||
.select({ id: apiKeys.id, userId: apiKeys.userId })
|
.select({ id: apiKeys.id, userId: apiKeys.userId, scope: apiKeys.scope })
|
||||||
.from(apiKeys)
|
.from(apiKeys)
|
||||||
.where(eq(apiKeys.keyHash, keyHash))
|
.where(eq(apiKeys.keyHash, keyHash))
|
||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
if (keyRow) {
|
if (keyRow) {
|
||||||
|
// Read-scoped keys can't make any state-changing request — enforced
|
||||||
|
// once here rather than in every route, since a route can't tell
|
||||||
|
// whether it's being called by a "read" key without this check.
|
||||||
|
if (keyRow.scope === "read" && !["GET", "HEAD", "OPTIONS"].includes(req.method)) {
|
||||||
|
return {
|
||||||
|
session: null,
|
||||||
|
response: NextResponse.json({ error: "This API key is read-only" }, { status: 403 }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Update lastUsedAt asynchronously — don't block response
|
// Update lastUsedAt asynchronously — don't block response
|
||||||
void db
|
void db
|
||||||
.update(apiKeys)
|
.update(apiKeys)
|
||||||
|
|||||||
@@ -86,11 +86,11 @@ export function generateOpenApiSpec(): object {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
const ApiKeyRef = registry.register("ApiKey", z.object({
|
const ApiKeyRef = registry.register("ApiKey", z.object({
|
||||||
id: z.string(), name: z.string(), lastUsedAt: z.string().datetime().nullable(), createdAt: z.string().datetime(),
|
id: z.string(), name: z.string(), scope: z.enum(["full", "read"]), lastUsedAt: z.string().datetime().nullable(), createdAt: z.string().datetime(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const CreateApiKeyResponseRef = registry.register("CreateApiKeyResponse", z.object({
|
const CreateApiKeyResponseRef = registry.register("CreateApiKeyResponse", z.object({
|
||||||
id: z.string(), name: z.string(), key: z.string().describe("Full key — shown once"), createdAt: z.string().datetime(),
|
id: z.string(), name: z.string(), scope: z.enum(["full", "read"]), key: z.string().describe("Full key — shown once"), createdAt: z.string().datetime(),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const AiGeneratedRef = registry.register("AiGeneratedRecipe", z.object({
|
const AiGeneratedRef = registry.register("AiGeneratedRecipe", z.object({
|
||||||
@@ -137,7 +137,7 @@ export function generateOpenApiSpec(): object {
|
|||||||
registry.registerPath({ method: "get", path: "/api/v1/shopping-lists", summary: "List shopping lists", security, request: { query: Pagination }, responses: { 200: { description: "Lists", content: { "application/json": { schema: z.array(ShoppingListRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
registry.registerPath({ method: "get", path: "/api/v1/shopping-lists", summary: "List shopping lists", security, request: { query: Pagination }, responses: { 200: { description: "Lists", content: { "application/json": { schema: z.array(ShoppingListRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||||
registry.registerPath({ method: "post", path: "/api/v1/shopping-lists", summary: "Create shopping list", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1), fromMealPlanWeek: z.string().optional() }) } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: ShoppingListRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
registry.registerPath({ method: "post", path: "/api/v1/shopping-lists", summary: "Create shopping list", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1), fromMealPlanWeek: z.string().optional() }) } }, required: true } }, responses: { 201: { description: "Created", content: { "application/json": { schema: ShoppingListRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||||
registry.registerPath({ method: "get", path: "/api/v1/api-keys", summary: "List API keys", security, responses: { 200: { description: "Keys (hash never returned)", content: { "application/json": { schema: z.array(ApiKeyRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
registry.registerPath({ method: "get", path: "/api/v1/api-keys", summary: "List API keys", security, responses: { 200: { description: "Keys (hash never returned)", content: { "application/json": { schema: z.array(ApiKeyRef) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||||
registry.registerPath({ method: "post", path: "/api/v1/api-keys", summary: "Create API key", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1).max(100) }) } }, required: true } }, responses: { 201: { description: "Key created — shown once", content: { "application/json": { schema: CreateApiKeyResponseRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
registry.registerPath({ method: "post", path: "/api/v1/api-keys", summary: "Create API key", security, request: { body: { content: { "application/json": { schema: z.object({ name: z.string().min(1).max(100), scope: z.enum(["full", "read"]).default("full").describe("read-only keys can only make GET requests") }) } }, required: true } }, responses: { 201: { description: "Key created — shown once", content: { "application/json": { schema: CreateApiKeyResponseRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||||
registry.registerPath({ method: "delete", path: "/api/v1/api-keys/{id}", summary: "Revoke API key", security, request: { params: idParam }, responses: { 204: { description: "Revoked" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
registry.registerPath({ method: "delete", path: "/api/v1/api-keys/{id}", summary: "Revoke API key", security, request: { params: idParam }, responses: { 204: { description: "Revoked" }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 404: { description: "Not found", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||||
|
|
||||||
const generator = new OpenApiGeneratorV31(registry.definitions);
|
const generator = new OpenApiGeneratorV31(registry.definitions);
|
||||||
|
|||||||
@@ -388,6 +388,13 @@
|
|||||||
"inputPlaceholder": "Ask a question…",
|
"inputPlaceholder": "Ask a question…",
|
||||||
"send": "Send message"
|
"send": "Send message"
|
||||||
},
|
},
|
||||||
|
"chatHistory": {
|
||||||
|
"searchAriaLabel": "Search chat history",
|
||||||
|
"searchPlaceholder": "Search past questions…",
|
||||||
|
"searching": "Searching…",
|
||||||
|
"noResults": "No matching messages",
|
||||||
|
"close": "Close"
|
||||||
|
},
|
||||||
"cookingChat": {
|
"cookingChat": {
|
||||||
"sorry": "Sorry, I couldn't answer that.",
|
"sorry": "Sorry, I couldn't answer that.",
|
||||||
"error": "Something went wrong. Please try again.",
|
"error": "Something went wrong. Please try again.",
|
||||||
@@ -1147,6 +1154,9 @@
|
|||||||
"lastUsedOn": "Last used {date}",
|
"lastUsedOn": "Last used {date}",
|
||||||
"neverUsed": "Never used",
|
"neverUsed": "Never used",
|
||||||
"revoke": "Revoke",
|
"revoke": "Revoke",
|
||||||
|
"apiKeyScopeFull": "Full access",
|
||||||
|
"apiKeyScopeRead": "Read-only",
|
||||||
|
"apiKeyScopeHelp": "Read-only keys can only make GET requests — they can't create, edit, or delete anything.",
|
||||||
"webhookUrlPlaceholder": "https://example.com/webhook",
|
"webhookUrlPlaceholder": "https://example.com/webhook",
|
||||||
"webhookAdding": "Adding…",
|
"webhookAdding": "Adding…",
|
||||||
"webhookAddButton": "Add webhook",
|
"webhookAddButton": "Add webhook",
|
||||||
|
|||||||
@@ -388,6 +388,13 @@
|
|||||||
"inputPlaceholder": "Posez une question…",
|
"inputPlaceholder": "Posez une question…",
|
||||||
"send": "Envoyer le message"
|
"send": "Envoyer le message"
|
||||||
},
|
},
|
||||||
|
"chatHistory": {
|
||||||
|
"searchAriaLabel": "Rechercher dans l'historique",
|
||||||
|
"searchPlaceholder": "Rechercher une question passée…",
|
||||||
|
"searching": "Recherche…",
|
||||||
|
"noResults": "Aucun message correspondant",
|
||||||
|
"close": "Fermer"
|
||||||
|
},
|
||||||
"cookingChat": {
|
"cookingChat": {
|
||||||
"sorry": "Désolé, je n'ai pas pu répondre à cela.",
|
"sorry": "Désolé, je n'ai pas pu répondre à cela.",
|
||||||
"error": "Une erreur s'est produite. Veuillez réessayer.",
|
"error": "Une erreur s'est produite. Veuillez réessayer.",
|
||||||
@@ -1153,6 +1160,9 @@
|
|||||||
"lastUsedOn": "Utilisée le {date}",
|
"lastUsedOn": "Utilisée le {date}",
|
||||||
"neverUsed": "Jamais utilisée",
|
"neverUsed": "Jamais utilisée",
|
||||||
"revoke": "Révoquer",
|
"revoke": "Révoquer",
|
||||||
|
"apiKeyScopeFull": "Accès complet",
|
||||||
|
"apiKeyScopeRead": "Lecture seule",
|
||||||
|
"apiKeyScopeHelp": "Les clés en lecture seule ne peuvent faire que des requêtes GET — elles ne peuvent rien créer, modifier ou supprimer.",
|
||||||
"copyFailed": "Échec de la copie dans le presse-papiers",
|
"copyFailed": "Échec de la copie dans le presse-papiers",
|
||||||
"byokSaved": "Clé {provider} enregistrée",
|
"byokSaved": "Clé {provider} enregistrée",
|
||||||
"byokSaveFailed": "Échec de l'enregistrement de la clé",
|
"byokSaveFailed": "Échec de l'enregistrement de la clé",
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
CREATE TYPE "public"."api_key_scope" AS ENUM('full', 'read');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."chat_role" AS ENUM('user', 'assistant');--> statement-breakpoint
|
||||||
|
CREATE TABLE "chat_messages" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"user_id" text NOT NULL,
|
||||||
|
"recipe_id" text,
|
||||||
|
"role" "chat_role" NOT NULL,
|
||||||
|
"content" text NOT NULL,
|
||||||
|
"created_at" timestamp DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "api_keys" ADD COLUMN "scope" "api_key_scope" DEFAULT 'full' NOT NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "chat_messages" ADD CONSTRAINT "chat_messages_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "chat_messages" ADD CONSTRAINT "chat_messages_recipe_id_recipes_id_fk" FOREIGN KEY ("recipe_id") REFERENCES "public"."recipes"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "chat_messages_user_idx" ON "chat_messages" USING btree ("user_id","created_at");--> statement-breakpoint
|
||||||
|
CREATE INDEX "chat_messages_recipe_idx" ON "chat_messages" USING btree ("recipe_id");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -246,6 +246,13 @@
|
|||||||
"when": 1783875228288,
|
"when": 1783875228288,
|
||||||
"tag": "0034_dapper_nocturne",
|
"tag": "0034_dapper_nocturne",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 35,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1783887815564,
|
||||||
|
"tag": "0035_gifted_plazm",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import { pgTable, text, timestamp, pgEnum, index } from "drizzle-orm/pg-core";
|
||||||
|
import { relations } from "drizzle-orm";
|
||||||
|
import { users } from "./users";
|
||||||
|
import { recipes } from "./recipes";
|
||||||
|
|
||||||
|
export const chatRoleEnum = pgEnum("chat_role", ["user", "assistant"]);
|
||||||
|
|
||||||
|
// Persists both the per-recipe chat (recipeId set) and the general cooking
|
||||||
|
// assistant on the recipes homepage (recipeId null) — same table, since a
|
||||||
|
// user searching "their chat history" expects both to show up together.
|
||||||
|
export const chatMessages = pgTable("chat_messages", {
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||||
|
recipeId: text("recipe_id").references(() => recipes.id, { onDelete: "cascade" }),
|
||||||
|
role: chatRoleEnum("role").notNull(),
|
||||||
|
content: text("content").notNull(),
|
||||||
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
|
}, (t) => [
|
||||||
|
index("chat_messages_user_idx").on(t.userId, t.createdAt),
|
||||||
|
index("chat_messages_recipe_idx").on(t.recipeId),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const chatMessagesRelations = relations(chatMessages, ({ one }) => ({
|
||||||
|
user: one(users, { fields: [chatMessages.userId], references: [users.id] }),
|
||||||
|
recipe: one(recipes, { fields: [chatMessages.recipeId], references: [recipes.id] }),
|
||||||
|
}));
|
||||||
@@ -6,3 +6,4 @@ export * from "./tiers";
|
|||||||
export * from "./webhooks";
|
export * from "./webhooks";
|
||||||
export * from "./messaging";
|
export * from "./messaging";
|
||||||
export * from "./billing";
|
export * from "./billing";
|
||||||
|
export * from "./ai-chat";
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { relations } from "drizzle-orm";
|
|||||||
export const userRoleEnum = pgEnum("user_role", ["user", "moderator", "admin"]);
|
export const userRoleEnum = pgEnum("user_role", ["user", "moderator", "admin"]);
|
||||||
export const tierEnum = pgEnum("tier", ["free", "pro"]);
|
export const tierEnum = pgEnum("tier", ["free", "pro"]);
|
||||||
export const unitPrefEnum = pgEnum("unit_pref", ["metric", "imperial"]);
|
export const unitPrefEnum = pgEnum("unit_pref", ["metric", "imperial"]);
|
||||||
|
export const apiKeyScopeEnum = pgEnum("api_key_scope", ["full", "read"]);
|
||||||
|
|
||||||
export const users = pgTable("users", {
|
export const users = pgTable("users", {
|
||||||
id: text("id").primaryKey(),
|
id: text("id").primaryKey(),
|
||||||
@@ -96,6 +97,7 @@ export const apiKeys = pgTable("api_keys", {
|
|||||||
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||||
name: text("name").notNull(),
|
name: text("name").notNull(),
|
||||||
keyHash: text("key_hash").notNull().unique(),
|
keyHash: text("key_hash").notNull().unique(),
|
||||||
|
scope: apiKeyScopeEnum("scope").notNull().default("full"),
|
||||||
lastUsedAt: timestamp("last_used_at"),
|
lastUsedAt: timestamp("last_used_at"),
|
||||||
createdAt: timestamp("created_at").notNull().defaultNow(),
|
createdAt: timestamp("created_at").notNull().defaultNow(),
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user