Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions app/subs/otel/[tenant]/DailyChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
"use client";

import {
Bar,
BarChart,
CartesianGrid,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
import type { DailyRow } from "@/app/subs/otel/lib/queries";

const BLUE = "var(--proofer-blue)";

export default function DailyChart({
data,
metric,
label,
format,
}: {
data: DailyRow[];
metric: "cost_usd" | "prompts" | "requests" | "users";
label: string;
format?: "usd";
}) {
const fmt = (v: number) =>
format === "usd" ? `$${v.toFixed(2)}` : v.toLocaleString("ko-KR");
return (
<div className="h-56 w-full">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: 0 }}>
<CartesianGrid vertical={false} stroke="var(--proofer-line)" />
<XAxis
dataKey="day"
tickLine={false}
axisLine={false}
fontSize={11}
minTickGap={16}
/>
<YAxis
tickLine={false}
axisLine={false}
fontSize={11}
width={48}
tickFormatter={fmt}
/>
<Tooltip
cursor={{ fill: "var(--proofer-blue-soft)" }}
formatter={(v: number) => [fmt(v), label]}
/>
<Bar dataKey={metric} fill={BLUE} radius={[3, 3, 0, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
);
}
83 changes: 83 additions & 0 deletions app/subs/otel/[tenant]/auth/callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { NextRequest, NextResponse } from "next/server";
import {
findTenant,
publicOrigin,
tenantPath,
} from "@/app/subs/otel/lib/tenant";
import {
SESSION_TTL_SEC,
cookieOptions,
oauthCookie,
sessionCookie,
sign,
verify,
type OAuthState,
} from "@/app/subs/otel/auth/session";
import {
clientSecret,
exchangeCode,
verifyIdToken,
} from "@/app/subs/otel/auth/vercel";

// Vercel 앱의 Sign-In Access 가 "Members of the team" 이면 팀 멤버가 아닌 사용자는
// 여기까지 오지 못하고 error=access_denied 로 돌아온다.
export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ tenant: string }> },
) {
const { tenant: slug } = await params;
const origin = publicOrigin(req.nextUrl.origin);
const home = origin + tenantPath(slug);
const fail = (reason: string) => {
const res = NextResponse.redirect(`${home}?error=${reason}`);
res.cookies.delete(oauthCookie(slug));
return res;
};

const tenant = await findTenant(slug);
const saved = verify<OAuthState>(req.cookies.get(oauthCookie(slug))?.value);
const q = req.nextUrl.searchParams;

if (q.get("error"))
return fail(q.get("error") === "access_denied" ? "denied" : "oauth");
if (!tenant?.vercel_client_id || !saved) return fail("state");
if (saved.clientId !== tenant.vercel_client_id) return fail("state");
if (!q.get("code") || q.get("state") !== saved.state) return fail("state");

const secret = clientSecret(tenant.vercel_client_id);
if (!secret) return fail("config");

try {
const tokens = await exchangeCode({
clientId: tenant.vercel_client_id,
clientSecret: secret,
code: q.get("code")!,
verifier: saved.verifier,
redirectUri: origin + tenantPath(slug, "/auth/callback"),
});
const claims = await verifyIdToken(tokens.id_token, {
clientId: tenant.vercel_client_id,
nonce: saved.nonce,
});

const res = NextResponse.redirect(home);
res.cookies.delete(oauthCookie(slug));
res.cookies.set(
sessionCookie(slug),
sign({
tenantId: tenant.id,
tenantSlug: tenant.slug,
tenantName: tenant.name,
sub: claims.sub,
email: claims.email ?? null,
name: claims.name ?? claims.preferred_username ?? null,
exp: Math.floor(Date.now() / 1000) + SESSION_TTL_SEC,
}),
cookieOptions(SESSION_TTL_SEC),
);
return res;
} catch (error) {
console.error("otel login failed", error);
return fail("token");
}
}
58 changes: 58 additions & 0 deletions app/subs/otel/[tenant]/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from "next/server";
import {
findTenant,
publicOrigin,
tenantPath,
} from "@/app/subs/otel/lib/tenant";
import {
OAUTH_TTL_SEC,
cookieOptions,
oauthCookie,
sign,
} from "@/app/subs/otel/auth/session";
import {
authorizeUrl,
clientSecret,
randomToken,
} from "@/app/subs/otel/auth/vercel";

export async function GET(
req: NextRequest,
{ params }: { params: Promise<{ tenant: string }> },
) {
const { tenant: slug } = await params;
const tenant = await findTenant(slug);
if (!tenant?.vercel_client_id || !clientSecret(tenant.vercel_client_id)) {
return new NextResponse("login is not configured for this tenant", {
status: 404,
});
}

const state = randomToken();
const nonce = randomToken();
const verifier = randomToken();
const redirectUri =
publicOrigin(req.nextUrl.origin) + tenantPath(slug, "/auth/callback");

const res = NextResponse.redirect(
authorizeUrl({
clientId: tenant.vercel_client_id,
redirectUri,
state,
nonce,
verifier,
}),
);
res.cookies.set(
oauthCookie(slug),
sign({
state,
nonce,
verifier,
clientId: tenant.vercel_client_id,
exp: Math.floor(Date.now() / 1000) + OAUTH_TTL_SEC,
}),
cookieOptions(OAUTH_TTL_SEC),
);
return res;
}
16 changes: 16 additions & 0 deletions app/subs/otel/[tenant]/auth/logout/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { NextRequest, NextResponse } from "next/server";
import { publicOrigin, tenantPath } from "@/app/subs/otel/lib/tenant";
import { sessionCookie } from "@/app/subs/otel/auth/session";

export async function POST(
req: NextRequest,
{ params }: { params: Promise<{ tenant: string }> },
) {
const { tenant: slug } = await params;
const res = NextResponse.redirect(
publicOrigin(req.nextUrl.origin) + tenantPath(slug),
303,
);
res.cookies.delete(sessionCookie(slug));
return res;
}
52 changes: 52 additions & 0 deletions app/subs/otel/[tenant]/p/[promptId]/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import Link from "next/link";
import { notFound, redirect } from "next/navigation";
import { findTenant, getSession, tenantPath } from "@/app/subs/otel/lib/tenant";
import { promptEvents } from "@/app/subs/otel/lib/queries";
import { Card, Header, kst } from "../../ui";

export const dynamic = "force-dynamic";

// 프롬프트 하나가 일으킨 이벤트(API 호출, 툴 실행, 응답)를 순서대로 보여준다.
export default async function PromptTimeline({
params,
}: {
params: Promise<{ tenant: string; promptId: string }>;
}) {
const { tenant: slug, promptId } = await params;
const tenant = await findTenant(slug);
if (!tenant) notFound();
const session = await getSession(tenant);
if (!session) redirect(tenantPath(slug));

const events = await promptEvents(tenant.id, promptId);
if (events.length === 0) notFound();

return (
<>
<Header session={session} />
<main className="mx-auto max-w-[1160px] space-y-4 px-6 py-8">
<Link href={tenantPath(slug)} className="text-sm text-proofer-gray">
대시보드로
</Link>
<h1 className="text-xl font-bold">
프롬프트 <code className="text-base">{promptId}</code>
</h1>
<p className="text-sm text-proofer-gray">
{events[0].user_email} / 세션 {events[0].session_id} / 이벤트{" "}
{events.length}건
</p>
{events.map((e) => (
<Card key={e.id}>
<div className="mb-2 flex items-center justify-between text-sm">
<span className="font-bold">{e.event_name}</span>
<span className="text-proofer-gray">{kst(e.at)}</span>
</div>
<pre className="max-h-96 overflow-auto whitespace-pre-wrap break-all rounded-proofer-xs bg-proofer-bg-alt p-3 text-xs">
{JSON.stringify(e.attributes, null, 2)}
</pre>
</Card>
))}
</main>
</>
);
}
Loading
Loading