diff --git a/app/subs/otel/[tenant]/DailyChart.tsx b/app/subs/otel/[tenant]/DailyChart.tsx new file mode 100644 index 0000000..c2913eb --- /dev/null +++ b/app/subs/otel/[tenant]/DailyChart.tsx @@ -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 ( +
+ + + + + + [fmt(v), label]} + /> + + + +
+ ); +} diff --git a/app/subs/otel/[tenant]/auth/callback/route.ts b/app/subs/otel/[tenant]/auth/callback/route.ts new file mode 100644 index 0000000..ea68ace --- /dev/null +++ b/app/subs/otel/[tenant]/auth/callback/route.ts @@ -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(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"); + } +} diff --git a/app/subs/otel/[tenant]/auth/login/route.ts b/app/subs/otel/[tenant]/auth/login/route.ts new file mode 100644 index 0000000..8ee78c5 --- /dev/null +++ b/app/subs/otel/[tenant]/auth/login/route.ts @@ -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; +} diff --git a/app/subs/otel/[tenant]/auth/logout/route.ts b/app/subs/otel/[tenant]/auth/logout/route.ts new file mode 100644 index 0000000..ab78d80 --- /dev/null +++ b/app/subs/otel/[tenant]/auth/logout/route.ts @@ -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; +} diff --git a/app/subs/otel/[tenant]/p/[promptId]/page.tsx b/app/subs/otel/[tenant]/p/[promptId]/page.tsx new file mode 100644 index 0000000..f89f0e9 --- /dev/null +++ b/app/subs/otel/[tenant]/p/[promptId]/page.tsx @@ -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 ( + <> +
+
+ + 대시보드로 + +

+ 프롬프트 {promptId} +

+

+ {events[0].user_email} / 세션 {events[0].session_id} / 이벤트{" "} + {events.length}건 +

+ {events.map((e) => ( + +
+ {e.event_name} + {kst(e.at)} +
+
+              {JSON.stringify(e.attributes, null, 2)}
+            
+
+ ))} +
+ + ); +} diff --git a/app/subs/otel/[tenant]/page.tsx b/app/subs/otel/[tenant]/page.tsx new file mode 100644 index 0000000..edafff8 --- /dev/null +++ b/app/subs/otel/[tenant]/page.tsx @@ -0,0 +1,214 @@ +import Link from "next/link"; +import { notFound } from "next/navigation"; +import { findTenant, getSession, tenantPath } from "@/app/subs/otel/lib/tenant"; +import { + RANGES, + byModel, + bySource, + byTool, + byUser, + daily, + kpis, + parseRange, + recentPrompts, +} from "@/app/subs/otel/lib/queries"; +import DailyChart from "./DailyChart"; +import { Card, Header, Stat, Table, compact, kst, n, usd } from "./ui"; + +export const dynamic = "force-dynamic"; + +const ERRORS: Record = { + denied: "이 팀의 Vercel 멤버만 들어올 수 있습니다.", + state: "로그인 요청이 만료됐습니다. 다시 시도해 주세요.", + token: "Vercel 인증을 확인하지 못했습니다. 다시 시도해 주세요.", + oauth: "Vercel 로그인이 취소되었거나 실패했습니다.", + config: "이 팀의 로그인 설정이 끝나지 않았습니다.", +}; + +type Props = { + params: Promise<{ tenant: string }>; + searchParams: Promise<{ days?: string; error?: string }>; +}; + +export default async function TenantDashboard({ params, searchParams }: Props) { + const { tenant: slug } = await params; + const { days: daysParam, error } = await searchParams; + const tenant = await findTenant(slug); + if (!tenant) notFound(); + + const session = await getSession(tenant); + if (!session) { + return ( +
+

{tenant.name} OTel

+

+ Claude Cowork 와 Office Agents 활동 대시보드입니다. {tenant.name} 팀의 + Vercel 계정으로 로그인하세요. +

+ {error && ( +

+ {ERRORS[error] ?? ERRORS.oauth} +

+ )} + {tenant.vercel_client_id ? ( + + Vercel 로 로그인 + + ) : ( +

{ERRORS.config}

+ )} +
+ ); + } + + const days = parseRange(daysParam); + const [k, d, users, tools, models, sources, prompts] = await Promise.all([ + kpis(tenant.id, days), + daily(tenant.id, days), + byUser(tenant.id, days), + byTool(tenant.id, days), + byModel(tenant.id, days), + bySource(tenant.id, days), + recentPrompts(tenant.id), + ]); + const failRate = k.tool_calls ? (k.tool_failures / k.tool_calls) * 100 : 0; + + return ( + <> +
+
+
+

최근 {days}일

+ +
+ +
+ + + + + + +
+ +
+ + + + + + +
+ +
+ + [ + u.user_email ?? "(없음)", + n(u.prompts), + n(u.sessions), + usd(u.cost_usd), + kst(u.last_seen), + ])} + /> + + +
[ + m.model, + n(m.requests), + usd(m.cost_usd), + `${(m.avg_ms / 1000).toFixed(1)}s`, + ])} + /> + + + + +
[ + + {t.tool_name} + , + n(t.calls), + n(t.failures), + n(t.rejects), + `${Math.round(t.avg_ms)}ms`, + ])} + /> + + + +
[ + + {kst(p.at)} + , + p.user_email ?? "", + p.service_name ?? "", + p.prompt_id ? ( + + {p.prompt ?? `(본문 미수집, ${p.prompt_length ?? "?"}자)`} + + ) : ( + (p.prompt ?? `(본문 미수집, ${p.prompt_length ?? "?"}자)`) + ), + ])} + /> + + + +
[ + s.service_name, + s.event_name, + n(s.count), + ])} + /> + + + + ); +} diff --git a/app/subs/otel/[tenant]/ui.tsx b/app/subs/otel/[tenant]/ui.tsx new file mode 100644 index 0000000..a959714 --- /dev/null +++ b/app/subs/otel/[tenant]/ui.tsx @@ -0,0 +1,122 @@ +import React from "react"; +import Link from "next/link"; +import { tenantPath } from "@/app/subs/otel/lib/tenant"; +import type { Session } from "@/app/subs/otel/auth/session"; + +export const usd = (v: number) => + `$${v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; +export const n = (v: number) => v.toLocaleString("ko-KR"); +export const compact = (v: number) => + Intl.NumberFormat("ko-KR", { notation: "compact" }).format(v); +export const kst = (v: string | Date) => + new Date(v).toLocaleString("ko-KR", { + timeZone: "Asia/Seoul", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + }); + +export function Card({ + title, + children, + className = "", +}: { + title?: string; + children: React.ReactNode; + className?: string; +}) { + return ( +
+ {title &&

{title}

} + {children} +
+ ); +} + +export function Stat({ + label, + value, + sub, +}: { + label: string; + value: string; + sub?: string; +}) { + return ( +
+
{label}
+
{value}
+ {sub &&
{sub}
} +
+ ); +} + +export function Table({ + head, + rows, + align, +}: { + head: string[]; + rows: React.ReactNode[][]; + align?: ("left" | "right")[]; +}) { + if (rows.length === 0) { + return

아직 데이터가 없습니다.

; + } + return ( +
+
+ + + {head.map((h, i) => ( + + ))} + + + + {rows.map((r, i) => ( + + {r.map((c, j) => ( + + ))} + + ))} + +
+ {h} +
+ {c} +
+
+ ); +} + +export function Header({ session }: { session: Session }) { + return ( +
+
+ + {session.tenantName} OTel + +
+ {session.email ?? session.name} +
+ +
+
+
+
+ ); +} diff --git a/app/subs/otel/[tenant]/v1/logs/route.ts b/app/subs/otel/[tenant]/v1/logs/route.ts new file mode 100644 index 0000000..2f5f78e --- /dev/null +++ b/app/subs/otel/[tenant]/v1/logs/route.ts @@ -0,0 +1,13 @@ +import { NextRequest } from "next/server"; +import { ingest } from "@/app/subs/otel/ingest"; + +export const runtime = "nodejs"; + +// otel.proofer.tech/{tenant}/v1/logs. 토큰이 이 테넌트 것이 아니면 401. +export async function POST( + req: NextRequest, + { params }: { params: Promise<{ tenant: string }> }, +) { + const { tenant } = await params; + return ingest(req, "logs", tenant); +} diff --git a/app/subs/otel/[tenant]/v1/metrics/route.ts b/app/subs/otel/[tenant]/v1/metrics/route.ts new file mode 100644 index 0000000..d408f09 --- /dev/null +++ b/app/subs/otel/[tenant]/v1/metrics/route.ts @@ -0,0 +1,13 @@ +import { NextRequest } from "next/server"; +import { ingest } from "@/app/subs/otel/ingest"; + +export const runtime = "nodejs"; + +// otel.proofer.tech/{tenant}/v1/metrics. 토큰이 이 테넌트 것이 아니면 401. +export async function POST( + req: NextRequest, + { params }: { params: Promise<{ tenant: string }> }, +) { + const { tenant } = await params; + return ingest(req, "metrics", tenant); +} diff --git a/app/subs/otel/[tenant]/v1/traces/route.ts b/app/subs/otel/[tenant]/v1/traces/route.ts new file mode 100644 index 0000000..16b2084 --- /dev/null +++ b/app/subs/otel/[tenant]/v1/traces/route.ts @@ -0,0 +1,13 @@ +import { NextRequest } from "next/server"; +import { ingest } from "@/app/subs/otel/ingest"; + +export const runtime = "nodejs"; + +// otel.proofer.tech/{tenant}/v1/traces. 토큰이 이 테넌트 것이 아니면 401. +export async function POST( + req: NextRequest, + { params }: { params: Promise<{ tenant: string }> }, +) { + const { tenant } = await params; + return ingest(req, "traces", tenant); +} diff --git a/app/subs/otel/auth/session.test.ts b/app/subs/otel/auth/session.test.ts new file mode 100644 index 0000000..a02d2e4 --- /dev/null +++ b/app/subs/otel/auth/session.test.ts @@ -0,0 +1,35 @@ +/** + * @jest-environment node + */ +import { sign, verify } from "./session"; + +const KEY = "k".repeat(40); + +describe("session", () => { + it("서명한 값은 그대로 돌아온다", () => { + const v = sign({ tenantId: 1, exp: 2000 }, KEY); + expect(verify<{ tenantId: number; exp: number }>(v, KEY, 1000)).toEqual({ + tenantId: 1, + exp: 2000, + }); + }); + + it("내용을 바꾸면 거부한다", () => { + const [, sig] = sign({ tenantId: 1, exp: 2000 }, KEY).split("."); + const forged = + Buffer.from(JSON.stringify({ tenantId: 2, exp: 2000 })).toString( + "base64url", + ) + + "." + + sig; + expect(verify(forged, KEY, 1000)).toBeNull(); + }); + + it("다른 키로 서명한 값은 거부한다", () => { + expect(verify(sign({ exp: 2000 }, "x".repeat(40)), KEY, 1000)).toBeNull(); + }); + + it("만료된 값은 거부한다", () => { + expect(verify(sign({ exp: 999 }, KEY), KEY, 1000)).toBeNull(); + }); +}); diff --git a/app/subs/otel/auth/session.ts b/app/subs/otel/auth/session.ts new file mode 100644 index 0000000..1665c38 --- /dev/null +++ b/app/subs/otel/auth/session.ts @@ -0,0 +1,76 @@ +import { createHmac, timingSafeEqual } from "node:crypto"; + +// 서명한 쿠키 값. 내용은 base64url(JSON) 이고 HMAC-SHA256 으로 위조를 막는다. +// 비밀값은 OTEL_SESSION_SECRET (32바이트 이상 임의 문자열). + +// 테넌트마다 쿠키를 따로 둔다. 두 팀에 다 속한 사람은 두 대시보드에 동시에 로그인해 있을 수 있다. +export const sessionCookie = (slug: string) => `otel_session_${slug}`; +export const oauthCookie = (slug: string) => `otel_oauth_${slug}`; +export const SESSION_TTL_SEC = 60 * 60 * 12; +export const OAUTH_TTL_SEC = 60 * 10; + +export type Session = { + tenantId: number; + tenantSlug: string; + tenantName: string; + sub: string; + email: string | null; + name: string | null; + exp: number; +}; + +export type OAuthState = { + state: string; + verifier: string; + nonce: string; + clientId: string; + exp: number; +}; + +function secret(): string { + const s = process.env.OTEL_SESSION_SECRET; + if (!s || s.length < 32) { + throw new Error("OTEL_SESSION_SECRET must be at least 32 characters"); + } + return s; +} + +function mac(data: string, key: string): string { + return createHmac("sha256", key).update(data).digest("base64url"); +} + +export function sign(payload: object, key: string = secret()): string { + const data = Buffer.from(JSON.stringify(payload)).toString("base64url"); + return `${data}.${mac(data, key)}`; +} + +export function verify( + value: string | undefined, + key: string = secret(), + now: number = Date.now() / 1000, +): T | null { + if (!value) return null; + const [data, sig] = value.split("."); + if (!data || !sig) return null; + const expected = Buffer.from(mac(data, key)); + const given = Buffer.from(sig); + if (expected.length !== given.length || !timingSafeEqual(expected, given)) { + return null; + } + try { + const payload = JSON.parse(Buffer.from(data, "base64url").toString()) as T; + return typeof payload.exp === "number" && payload.exp > now + ? payload + : null; + } catch { + return null; + } +} + +export const cookieOptions = (maxAge: number) => ({ + httpOnly: true, + secure: process.env.NODE_ENV === "production", + sameSite: "lax" as const, + path: "/", + maxAge, +}); diff --git a/app/subs/otel/auth/vercel.test.ts b/app/subs/otel/auth/vercel.test.ts new file mode 100644 index 0000000..7525dea --- /dev/null +++ b/app/subs/otel/auth/vercel.test.ts @@ -0,0 +1,72 @@ +/** + * @jest-environment node + */ +import { generateKeyPairSync, sign as cryptoSign } from "node:crypto"; +import { resetJwksCache, verifyIdToken } from "./vercel"; + +const { privateKey, publicKey } = generateKeyPairSync("rsa", { + modulusLength: 2048, +}); +const jwk = { ...publicKey.export({ format: "jwk" }), kid: "k1" }; +const fetchImpl = (async () => + new Response(JSON.stringify({ keys: [jwk] }))) as typeof fetch; + +function token(claims: object, kid = "k1") { + const h = Buffer.from(JSON.stringify({ alg: "RS256", kid })).toString( + "base64url", + ); + const b = Buffer.from(JSON.stringify(claims)).toString("base64url"); + const s = cryptoSign("sha256", Buffer.from(`${h}.${b}`), privateKey).toString( + "base64url", + ); + return `${h}.${b}.${s}`; +} + +const base = { + iss: "https://vercel.com", + sub: "u1", + aud: "cl_proofer", + exp: 2000, + nonce: "n1", + email: "a@b.c", +}; +const opts = { clientId: "cl_proofer", nonce: "n1", fetchImpl, now: 1000 }; + +describe("verifyIdToken", () => { + beforeEach(() => resetJwksCache()); + + it("올바른 토큰은 claims 를 돌려준다", async () => { + await expect(verifyIdToken(token(base), opts)).resolves.toMatchObject({ + sub: "u1", + email: "a@b.c", + }); + }); + + it("다른 앱(aud)의 토큰은 거부한다", async () => { + await expect( + verifyIdToken(token({ ...base, aud: "cl_hsol" }), opts), + ).rejects.toThrow("bad aud"); + }); + + it("nonce 가 다르면 거부한다", async () => { + await expect( + verifyIdToken(token({ ...base, nonce: "x" }), opts), + ).rejects.toThrow("bad nonce"); + }); + + it("만료된 토큰은 거부한다", async () => { + await expect( + verifyIdToken(token({ ...base, exp: 900 }), opts), + ).rejects.toThrow("expired"); + }); + + it("서명이 틀리면 거부한다", async () => { + const [h, , s] = token(base).split("."); + const b = Buffer.from(JSON.stringify({ ...base, sub: "u2" })).toString( + "base64url", + ); + await expect(verifyIdToken(`${h}.${b}.${s}`, opts)).rejects.toThrow( + "bad signature", + ); + }); +}); diff --git a/app/subs/otel/auth/vercel.ts b/app/subs/otel/auth/vercel.ts new file mode 100644 index 0000000..10de350 --- /dev/null +++ b/app/subs/otel/auth/vercel.ts @@ -0,0 +1,154 @@ +import { + createHash, + createPublicKey, + randomBytes, + verify as cryptoVerify, + type JsonWebKey, +} from "node:crypto"; + +// Sign in with Vercel (OAuth 2.0 + OIDC). +// https://vercel.com/docs/sign-in-with-vercel/authorization-server-api +export const AUTHORIZE_URL = "https://vercel.com/oauth/authorize"; +export const TOKEN_URL = "https://api.vercel.com/login/oauth/token"; +export const JWKS_URL = "https://vercel.com/.well-known/jwks"; +export const ISSUER = "https://vercel.com"; + +// 테넌트 앱의 client secret. client id 를 키로 하는 JSON 이다. +// OTEL_VERCEL_APPS='{"cl_abc":"secret1","cl_def":"secret2"}' +export function clientSecret(clientId: string): string | null { + try { + const apps = JSON.parse(process.env.OTEL_VERCEL_APPS ?? "{}"); + return typeof apps[clientId] === "string" ? apps[clientId] : null; + } catch { + return null; + } +} + +export const randomToken = () => randomBytes(32).toString("base64url"); + +export function pkceChallenge(verifier: string): string { + return createHash("sha256").update(verifier).digest("base64url"); +} + +export function authorizeUrl(p: { + clientId: string; + redirectUri: string; + state: string; + nonce: string; + verifier: string; +}): string { + const q = new URLSearchParams({ + client_id: p.clientId, + redirect_uri: p.redirectUri, + response_type: "code", + scope: "openid email profile", + state: p.state, + nonce: p.nonce, + code_challenge: pkceChallenge(p.verifier), + code_challenge_method: "S256", + }); + return `${AUTHORIZE_URL}?${q}`; +} + +export async function exchangeCode(p: { + clientId: string; + clientSecret: string; + code: string; + verifier: string; + redirectUri: string; + fetchImpl?: typeof fetch; +}): Promise<{ id_token: string; access_token: string }> { + const res = await (p.fetchImpl ?? fetch)(TOKEN_URL, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + client_id: p.clientId, + client_secret: p.clientSecret, + code: p.code, + code_verifier: p.verifier, + redirect_uri: p.redirectUri, + }), + }); + if (!res.ok) throw new Error(`token endpoint ${res.status}`); + return res.json(); +} + +type Jwk = JsonWebKey & { kid?: string }; +let jwksCache: { at: number; keys: Jwk[] } | null = null; + +async function jwks(fetchImpl: typeof fetch, force = false): Promise { + if (!force && jwksCache && Date.now() - jwksCache.at < 60 * 60 * 1000) { + return jwksCache.keys; + } + const res = await fetchImpl(JWKS_URL); + if (!res.ok) throw new Error(`jwks ${res.status}`); + const { keys } = (await res.json()) as { keys: Jwk[] }; + jwksCache = { at: Date.now(), keys }; + return keys; +} + +export function resetJwksCache() { + jwksCache = null; +} + +export type IdClaims = { + sub: string; + aud: string | string[]; + email?: string; + name?: string; + preferred_username?: string; + nonce?: string; +}; + +// ID 토큰 서명(RS256/ES256)과 iss, aud, exp, nbf, nonce 를 검사한다. +export async function verifyIdToken( + idToken: string, + p: { + clientId: string; + nonce: string; + fetchImpl?: typeof fetch; + now?: number; + }, +): Promise { + const [h, b, s] = idToken.split("."); + if (!h || !b || !s) throw new Error("malformed id_token"); + const header = JSON.parse(Buffer.from(h, "base64url").toString()); + const claims = JSON.parse(Buffer.from(b, "base64url").toString()); + + const fetchImpl = p.fetchImpl ?? fetch; + let keys = await jwks(fetchImpl); + let jwk = keys.find((k) => k.kid === header.kid); + if (!jwk) { + keys = await jwks(fetchImpl, true); + jwk = keys.find((k) => k.kid === header.kid); + } + if (!jwk) throw new Error("unknown kid"); + + const key = createPublicKey({ key: jwk, format: "jwk" }); + const data = Buffer.from(`${h}.${b}`); + const sig = Buffer.from(s, "base64url"); + if (header.alg !== "RS256" && header.alg !== "ES256") { + throw new Error(`unsupported alg ${header.alg}`); + } + const ok = + header.alg === "RS256" + ? cryptoVerify("sha256", data, key, sig) + : cryptoVerify("sha256", data, { key, dsaEncoding: "ieee-p1363" }, sig); + if (!ok) throw new Error("bad signature"); + + const now = p.now ?? Date.now() / 1000; + const skew = 60; + const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud]; + if (claims.iss !== ISSUER) throw new Error("bad iss"); + if (!aud.includes(p.clientId)) throw new Error("bad aud"); + if (typeof claims.exp !== "number" || claims.exp + skew < now) { + throw new Error("expired"); + } + if (typeof claims.nbf === "number" && claims.nbf - skew > now) { + throw new Error("not yet valid"); + } + if (claims.nonce !== p.nonce) throw new Error("bad nonce"); + if (typeof claims.sub !== "string") throw new Error("no sub"); + return claims as IdClaims; +} diff --git a/app/subs/otel/ingest.ts b/app/subs/otel/ingest.ts index cd5ca37..0ecbe83 100644 --- a/app/subs/otel/ingest.ts +++ b/app/subs/otel/ingest.ts @@ -28,7 +28,7 @@ export function bearerToken(req: Request): string | null { async function findTenant(token: string) { const [tenant] = await dz - .select({ id: OtelTenant.id }) + .select({ id: OtelTenant.id, slug: OtelTenant.slug }) .from(OtelTenant) .where( and( @@ -51,9 +51,11 @@ async function readJson(req: NextRequest): Promise { // OTLP/HTTP 응답 규약: 성공은 200 + Export*ServiceResponse(JSON 빈 객체 허용), // 503 은 익스포터가 재시도한다. 400/401/413/415 는 재시도하지 않는다. +// expectedSlug 가 있으면(/{tenant}/v1/...) 토큰의 테넌트와 경로의 테넌트가 같아야 한다. export async function ingest( req: NextRequest, signal: Signal, + expectedSlug?: string, ): Promise { const token = bearerToken(req); if (!token) return new NextResponse(null, { status: 401 }); @@ -72,6 +74,9 @@ export async function ingest( return new NextResponse(null, { status: 503 }); } if (!tenant) return new NextResponse(null, { status: 401 }); + if (expectedSlug && tenant.slug !== expectedSlug) { + return new NextResponse(null, { status: 401 }); + } let payload: unknown; try { diff --git a/app/subs/otel/layout.tsx b/app/subs/otel/layout.tsx new file mode 100644 index 0000000..8f600a2 --- /dev/null +++ b/app/subs/otel/layout.tsx @@ -0,0 +1,19 @@ +import React from "react"; +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "프루퍼 OTel", + robots: { index: false, follow: false }, +}; + +export default function OtelLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( +
+ {children} +
+ ); +} diff --git a/app/subs/otel/lib/queries.ts b/app/subs/otel/lib/queries.ts new file mode 100644 index 0000000..0592360 --- /dev/null +++ b/app/subs/otel/lib/queries.ts @@ -0,0 +1,256 @@ +import { sql } from "drizzle-orm"; +import { dz } from "@/database/engine"; + +// 모든 쿼리는 tenant_id 로 먼저 거른다. 시각은 observed_at, 없으면 received_at. +const TS = sql.raw("coalesce(observed_at, received_at)"); + +export const RANGES = [7, 30, 90] as const; +export type Range = (typeof RANGES)[number]; +export const parseRange = (v: string | undefined): Range => + (RANGES as readonly number[]).includes(Number(v)) ? (Number(v) as Range) : 30; + +async function rows(q: ReturnType): Promise { + const res = await dz.execute(q); + return res.rows as T[]; +} + +const since = (days: number) => + sql`${TS} >= now() - make_interval(days => ${days})`; +const num = (key: string) => + sql.raw(`coalesce((attributes->>'${key}')::numeric, 0)`); + +export type Kpis = { + prompts: number; + sessions: number; + users: number; + requests: number; + cost_usd: number; + input_tokens: number; + output_tokens: number; + cache_read_tokens: number; + tool_calls: number; + tool_failures: number; + api_errors: number; +}; + +export async function kpis(tenantId: number, days: number): Promise { + const [r] = await rows>(sql` + select + count(*) filter (where event_name = 'user_prompt') as prompts, + count(distinct session_id) as sessions, + count(distinct user_email) as users, + count(*) filter (where event_name = 'api_request') as requests, + coalesce(sum(${num("cost_usd")}) filter (where event_name = 'api_request'), 0) as cost_usd, + coalesce(sum(${num("input_tokens")}) filter (where event_name = 'api_request'), 0) as input_tokens, + coalesce(sum(${num("output_tokens")}) filter (where event_name = 'api_request'), 0) as output_tokens, + coalesce(sum(${num("cache_read_tokens")}) filter (where event_name = 'api_request'), 0) as cache_read_tokens, + count(*) filter (where event_name = 'tool_result') as tool_calls, + count(*) filter (where event_name = 'tool_result' and attributes->>'success' = 'false') as tool_failures, + count(*) filter (where event_name = 'api_error') as api_errors + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} + `); + return Object.fromEntries( + Object.entries(r).map(([k, v]) => [k, Number(v)]), + ) as Kpis; +} + +export type DailyRow = { + day: string; + prompts: number; + requests: number; + cost_usd: number; + users: number; +}; + +export async function daily( + tenantId: number, + days: number, +): Promise { + const r = await rows>(sql` + with d as ( + select generate_series( + (now() at time zone 'Asia/Seoul')::date - (${days} - 1), + (now() at time zone 'Asia/Seoul')::date, + interval '1 day' + )::date as day + ), e as ( + select (${TS} at time zone 'Asia/Seoul')::date as day, * + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} + ) + select to_char(d.day, 'MM-DD') as day, + count(e.*) filter (where e.event_name = 'user_prompt') as prompts, + count(e.*) filter (where e.event_name = 'api_request') as requests, + coalesce(sum(coalesce((e.attributes->>'cost_usd')::numeric, 0)) filter (where e.event_name = 'api_request'), 0) as cost_usd, + count(distinct e.user_email) as users + from d left join e on e.day = d.day + group by d.day order by d.day + `); + return r.map((x) => ({ + day: x.day, + prompts: Number(x.prompts), + requests: Number(x.requests), + cost_usd: Number(x.cost_usd), + users: Number(x.users), + })); +} + +export type UserRow = { + user_email: string | null; + prompts: number; + sessions: number; + cost_usd: number; + last_seen: string; +}; + +export async function byUser( + tenantId: number, + days: number, +): Promise { + const r = await rows>(sql` + select user_email, + count(*) filter (where event_name = 'user_prompt') as prompts, + count(distinct session_id) as sessions, + coalesce(sum(${num("cost_usd")}) filter (where event_name = 'api_request'), 0) as cost_usd, + max(${TS}) as last_seen + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} + group by user_email order by cost_usd desc limit 50 + `); + return r.map((x) => ({ + user_email: x.user_email, + prompts: Number(x.prompts), + sessions: Number(x.sessions), + cost_usd: Number(x.cost_usd), + last_seen: String(x.last_seen), + })); +} + +export type ToolRow = { + tool_name: string; + calls: number; + failures: number; + avg_ms: number; + rejects: number; +}; + +export async function byTool( + tenantId: number, + days: number, +): Promise { + const r = await rows>(sql` + select coalesce(attributes->>'tool_name', '(unknown)') as tool_name, + count(*) as calls, + count(*) filter (where attributes->>'success' = 'false') as failures, + coalesce(avg(${num("duration_ms")}), 0) as avg_ms, + count(*) filter (where attributes->>'decision_type' = 'reject') as rejects + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} and event_name = 'tool_result' + group by 1 order by calls desc limit 30 + `); + return r.map((x) => ({ + tool_name: x.tool_name, + calls: Number(x.calls), + failures: Number(x.failures), + avg_ms: Number(x.avg_ms), + rejects: Number(x.rejects), + })); +} + +export type ModelRow = { + model: string; + requests: number; + cost_usd: number; + avg_ms: number; +}; + +export async function byModel( + tenantId: number, + days: number, +): Promise { + const r = await rows>(sql` + select coalesce(attributes->>'model', '(unknown)') as model, + count(*) as requests, + coalesce(sum(${num("cost_usd")}), 0) as cost_usd, + coalesce(avg(${num("duration_ms")}), 0) as avg_ms + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} and event_name = 'api_request' + group by 1 order by cost_usd desc + `); + return r.map((x) => ({ + model: x.model, + requests: Number(x.requests), + cost_usd: Number(x.cost_usd), + avg_ms: Number(x.avg_ms), + })); +} + +export type SourceRow = { + service_name: string; + event_name: string; + count: number; +}; + +// Office Agents 처럼 이벤트 이름을 미리 모르는 출처도 보이도록 전체 분포를 같이 낸다. +export async function bySource( + tenantId: number, + days: number, +): Promise { + const r = await rows>(sql` + select coalesce(service_name, '(unknown)') as service_name, + coalesce(event_name, '(none)') as event_name, + count(*) as count + from otel_log_record + where tenant_id = ${tenantId} and ${since(days)} + group by 1, 2 order by 1, count desc + `); + return r.map((x) => ({ ...x, count: Number(x.count) })); +} + +export type PromptRow = { + prompt_id: string | null; + at: string; + user_email: string | null; + service_name: string | null; + prompt: string | null; + prompt_length: number | null; +}; + +export async function recentPrompts( + tenantId: number, + limit = 30, +): Promise { + const r = await rows(sql` + select prompt_id, ${TS} as at, user_email, service_name, + left(attributes->>'prompt', 300) as prompt, + (attributes->>'prompt_length')::int as prompt_length + from otel_log_record + where tenant_id = ${tenantId} and event_name = 'user_prompt' + order by ${TS} desc limit ${limit} + `); + return r; +} + +export type EventRow = { + id: number; + at: string; + event_name: string | null; + service_name: string | null; + user_email: string | null; + session_id: string | null; + attributes: Record; +}; + +export async function promptEvents( + tenantId: number, + promptId: string, +): Promise { + return rows(sql` + select id, ${TS} as at, event_name, service_name, user_email, session_id, attributes + from otel_log_record + where tenant_id = ${tenantId} and prompt_id = ${promptId} + order by coalesce((attributes->>'event.sequence')::bigint, 0), ${TS}, id + limit 500 + `); +} diff --git a/app/subs/otel/lib/tenant.ts b/app/subs/otel/lib/tenant.ts new file mode 100644 index 0000000..5f5006f --- /dev/null +++ b/app/subs/otel/lib/tenant.ts @@ -0,0 +1,48 @@ +import { cookies } from "next/headers"; +import { and, eq, isNull } from "drizzle-orm"; +import { dz } from "@/database/engine"; +import { OtelTenant } from "@/database/schemas/otel"; +import { generateSubdomainPath } from "@/src/path"; +import { SUB_DOMAIN } from "@/src/constants"; +import { + sessionCookie, + verify, + type Session, +} from "@/app/subs/otel/auth/session"; + +// otel.proofer.tech/{tenant}/{path}. tenant 는 otel_tenant.slug 다. +// "v1" 은 테넌트 없는 수신 경로(/v1/logs)라 slug 로 쓸 수 없다. +export const RESERVED_SLUGS = new Set(["v1", "auth", "api", "health"]); + +export async function findTenant(slug: string) { + if (RESERVED_SLUGS.has(slug)) return null; + const [tenant] = await dz + .select({ + id: OtelTenant.id, + slug: OtelTenant.slug, + name: OtelTenant.name, + vercel_client_id: OtelTenant.vercel_client_id, + }) + .from(OtelTenant) + .where(and(eq(OtelTenant.slug, slug), isNull(OtelTenant.disabled_at))) + .limit(1); + return tenant ?? null; +} + +export const tenantPath = (slug: string, path = "") => + generateSubdomainPath(`/${slug}${path}`, SUB_DOMAIN.otel); + +export function publicOrigin(fallback: string): string { + return process.env.OTEL_PUBLIC_ORIGIN || fallback; +} + +// 세션이 이 테넌트 것인지까지 확인한다. 다른 테넌트 세션은 null. +export async function getSession(tenant: { + id: number; + slug: string; +}): Promise { + const store = await cookies(); + const session = verify(store.get(sessionCookie(tenant.slug))?.value); + if (!session || session.tenantId !== tenant.id) return null; + return session; +} diff --git a/app/subs/otel/page.tsx b/app/subs/otel/page.tsx new file mode 100644 index 0000000..e415b03 --- /dev/null +++ b/app/subs/otel/page.tsx @@ -0,0 +1,11 @@ +// 테넌트 목록은 공개하지 않는다. 각 팀은 자기 주소(otel.proofer.tech/{tenant})로 들어온다. +export default function OtelRoot() { + return ( +
+

프루퍼 OTel

+

+ 팀에 안내받은 주소(otel.proofer.tech/팀이름)로 접속해 주세요. +

+
+ ); +} diff --git a/database/migrations/0029_otel_tenant_vercel.sql b/database/migrations/0029_otel_tenant_vercel.sql new file mode 100644 index 0000000..fd51541 --- /dev/null +++ b/database/migrations/0029_otel_tenant_vercel.sql @@ -0,0 +1,3 @@ +ALTER TABLE "otel_tenant" ADD COLUMN "vercel_client_id" varchar(128);--> statement-breakpoint +ALTER TABLE "otel_tenant" ADD COLUMN "vercel_team_id" varchar(64);--> statement-breakpoint +ALTER TABLE "otel_tenant" ADD CONSTRAINT "otel_tenant_vercel_client_id_unique" UNIQUE("vercel_client_id"); \ No newline at end of file diff --git a/database/migrations/meta/0029_snapshot.json b/database/migrations/meta/0029_snapshot.json new file mode 100644 index 0000000..80a1ace --- /dev/null +++ b/database/migrations/meta/0029_snapshot.json @@ -0,0 +1,1061 @@ +{ + "id": "d39d0f1f-93e4-40f5-833b-0932eff89c3b", + "prevId": "81ba07c9-18d4-4485-b9b1-79e08f69be1d", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.article": { + "name": "article", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(256)", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar(256)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "varchar(80)", + "primaryKey": false, + "notNull": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "contents": { + "name": "contents", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "origin": { + "name": "origin", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false + }, + "author": { + "name": "author", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "default": "'프루퍼'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "is_published": { + "name": "is_published", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "subtitle": { + "name": "subtitle", + "type": "varchar(160)", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "body_md": { + "name": "body_md", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "source_html": { + "name": "source_html", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "article_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "author_id": { + "name": "author_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "canonical_url": { + "name": "canonical_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "source": { + "name": "source", + "type": "article_source", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'native'" + }, + "medium_post_id": { + "name": "medium_post_id", + "type": "varchar(16)", + "primaryKey": false, + "notNull": false + }, + "medium_url": { + "name": "medium_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cover_asset_id": { + "name": "cover_asset_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "reading_minutes": { + "name": "reading_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "word_count": { + "name": "word_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "keywords": { + "name": "keywords", + "type": "text[]", + "primaryKey": false, + "notNull": false + }, + "content_hash": { + "name": "content_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true, + "default": "''" + }, + "link_cards": { + "name": "link_cards", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "article_idx_created_at": { + "name": "article_idx_created_at", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "article_idx_title": { + "name": "article_idx_title", + "columns": [ + { + "expression": "title", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "article_idx_is_published": { + "name": "article_idx_is_published", + "columns": [ + { + "expression": "is_published", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "article_author_id_author_id_fk": { + "name": "article_author_id_author_id_fk", + "tableFrom": "article", + "tableTo": "author", + "columnsFrom": ["author_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + }, + "article_cover_asset_id_asset_id_fk": { + "name": "article_cover_asset_id_asset_id_fk", + "tableFrom": "article", + "tableTo": "asset", + "columnsFrom": ["cover_asset_id"], + "columnsTo": ["id"], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "article_uidx_slug": { + "name": "article_uidx_slug", + "nullsNotDistinct": false, + "columns": ["slug"] + }, + "article_uidx_medium_post_id": { + "name": "article_uidx_medium_post_id", + "nullsNotDistinct": false, + "columns": ["medium_post_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.article_redirect": { + "name": "article_redirect", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "from_path": { + "name": "from_path", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true + }, + "article_id": { + "name": "article_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "article_redirect_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "article_redirect_article_id_article_id_fk": { + "name": "article_redirect_article_id_article_id_fk", + "tableFrom": "article_redirect", + "tableTo": "article", + "columnsFrom": ["article_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "article_redirect_uidx_from_path": { + "name": "article_redirect_uidx_from_path", + "nullsNotDistinct": false, + "columns": ["from_path"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.article_revision": { + "name": "article_revision", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "article_id": { + "name": "article_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "body_md": { + "name": "body_md", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_hash": { + "name": "content_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "article_revision_article_id_article_id_fk": { + "name": "article_revision_article_id_article_id_fk", + "tableFrom": "article_revision", + "tableTo": "article", + "columnsFrom": ["article_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.article_to_tag": { + "name": "article_to_tag", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "article_id": { + "name": "article_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "article_to_tag_article_id_article_id_fk": { + "name": "article_to_tag_article_id_article_id_fk", + "tableFrom": "article_to_tag", + "tableTo": "article", + "columnsFrom": ["article_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "article_to_tag_name_tag_name_fk": { + "name": "article_to_tag_name_tag_name_fk", + "tableFrom": "article_to_tag", + "tableTo": "tag", + "columnsFrom": ["name"], + "columnsTo": ["name"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "article_to_tag_uidx_article_name": { + "name": "article_to_tag_uidx_article_name", + "nullsNotDistinct": false, + "columns": ["article_id", "name"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.asset": { + "name": "asset", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "article_id": { + "name": "article_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "original_url": { + "name": "original_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "width": { + "name": "width", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "height": { + "name": "height", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "alt": { + "name": "alt", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "caption": { + "name": "caption", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "asset_article_id_article_id_fk": { + "name": "asset_article_id_article_id_fk", + "tableFrom": "asset", + "tableTo": "article", + "columnsFrom": ["article_id"], + "columnsTo": ["id"], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.author": { + "name": "author", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "author_kind", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'person'" + }, + "display_name": { + "name": "display_name", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "bio": { + "name": "bio", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "medium_username": { + "name": "medium_username", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "medium_url": { + "name": "medium_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "website_url": { + "name": "website_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "same_as": { + "name": "same_as", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "is_default": { + "name": "is_default", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "author_uidx_slug": { + "name": "author_uidx_slug", + "nullsNotDistinct": false, + "columns": ["slug"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tag": { + "name": "tag", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tag_uidx_name": { + "name": "tag_uidx_name", + "nullsNotDistinct": false, + "columns": ["name"] + }, + "tag_uidx_slug": { + "name": "tag_uidx_slug", + "nullsNotDistinct": false, + "columns": ["slug"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.otel_log_record": { + "name": "otel_log_record", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "observed_at": { + "name": "observed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "service_name": { + "name": "service_name", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "event_name": { + "name": "event_name", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "session_id": { + "name": "session_id", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "prompt_id": { + "name": "prompt_id", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "user_email": { + "name": "user_email", + "type": "varchar(320)", + "primaryKey": false, + "notNull": false + }, + "severity": { + "name": "severity", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "attributes": { + "name": "attributes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "resource": { + "name": "resource", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "scope": { + "name": "scope", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "otel_log_record_tenant_time_idx": { + "name": "otel_log_record_tenant_time_idx", + "columns": [ + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "observed_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "otel_log_record_tenant_event_idx": { + "name": "otel_log_record_tenant_event_idx", + "columns": [ + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "event_name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "otel_log_record_session_idx": { + "name": "otel_log_record_session_idx", + "columns": [ + { + "expression": "session_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "otel_log_record_prompt_idx": { + "name": "otel_log_record_prompt_idx", + "columns": [ + { + "expression": "prompt_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "otel_log_record_tenant_id_otel_tenant_id_fk": { + "name": "otel_log_record_tenant_id_otel_tenant_id_fk", + "tableFrom": "otel_log_record", + "tableTo": "otel_tenant", + "columnsFrom": ["tenant_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.otel_raw_batch": { + "name": "otel_raw_batch", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "tenant_id": { + "name": "tenant_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "signal": { + "name": "signal", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "otel_raw_batch_tenant_idx": { + "name": "otel_raw_batch_tenant_idx", + "columns": [ + { + "expression": "tenant_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "otel_raw_batch_tenant_id_otel_tenant_id_fk": { + "name": "otel_raw_batch_tenant_id_otel_tenant_id_fk", + "tableFrom": "otel_raw_batch", + "tableTo": "otel_tenant", + "columnsFrom": ["tenant_id"], + "columnsTo": ["id"], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.otel_tenant": { + "name": "otel_tenant", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "vercel_client_id": { + "name": "vercel_client_id", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "vercel_team_id": { + "name": "vercel_team_id", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "disabled_at": { + "name": "disabled_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "otel_tenant_slug_unique": { + "name": "otel_tenant_slug_unique", + "nullsNotDistinct": false, + "columns": ["slug"] + }, + "otel_tenant_token_hash_unique": { + "name": "otel_tenant_token_hash_unique", + "nullsNotDistinct": false, + "columns": ["token_hash"] + }, + "otel_tenant_vercel_client_id_unique": { + "name": "otel_tenant_vercel_client_id_unique", + "nullsNotDistinct": false, + "columns": ["vercel_client_id"] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.payapp_callback": { + "name": "payapp_callback", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "raw_body": { + "name": "raw_body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parsed": { + "name": "parsed", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "mul_no": { + "name": "mul_no", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false + }, + "pay_state": { + "name": "pay_state", + "type": "varchar(8)", + "primaryKey": false, + "notNull": false + }, + "received_at": { + "name": "received_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.article_source": { + "name": "article_source", + "schema": "public", + "values": ["native", "medium_publication", "medium_personal"] + }, + "public.article_status": { + "name": "article_status", + "schema": "public", + "values": ["draft", "published", "unlisted"] + }, + "public.author_kind": { + "name": "author_kind", + "schema": "public", + "values": ["org", "person"] + }, + "public.article_redirect_kind": { + "name": "article_redirect_kind", + "schema": "public", + "values": ["medium", "legacy_blog", "slug_change"] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} diff --git a/database/migrations/meta/_journal.json b/database/migrations/meta/_journal.json index 1e0a6ff..7e746b3 100644 --- a/database/migrations/meta/_journal.json +++ b/database/migrations/meta/_journal.json @@ -204,6 +204,13 @@ "when": 1794667414345, "tag": "0028_otel_ingest", "breakpoints": true + }, + { + "idx": 29, + "version": "7", + "when": 1794667967792, + "tag": "0029_otel_tenant_vercel", + "breakpoints": true } ] -} \ No newline at end of file +} diff --git a/database/schemas/otel.ts b/database/schemas/otel.ts index 1731017..8f6de55 100644 --- a/database/schemas/otel.ts +++ b/database/schemas/otel.ts @@ -17,6 +17,11 @@ export const OtelTenant = schema.table("otel_tenant", { slug: varchar("slug", { length: 64 }).notNull().unique(), name: text("name").notNull(), token_hash: varchar("token_hash", { length: 64 }).notNull().unique(), + // 대시보드 로그인. 테넌트의 Vercel 팀이 소유한 Sign in with Vercel 앱의 client id 다. + // 앱의 Sign-In Access 를 팀 멤버로 제한해 두면, 이 앱으로 로그인했다는 것이 곧 팀 멤버라는 뜻이다. + vercel_client_id: varchar("vercel_client_id", { length: 128 }).unique(), + // 팀 권한(private beta)이 열리면 앱 하나로 합칠 때 쓴다. + vercel_team_id: varchar("vercel_team_id", { length: 64 }), created_at: timestamp("created_at").defaultNow().notNull(), disabled_at: timestamp("disabled_at"), }); diff --git a/database/scripts/otel-tenant.ts b/database/scripts/otel-tenant.ts index dd4efa4..19fd274 100644 --- a/database/scripts/otel-tenant.ts +++ b/database/scripts/otel-tenant.ts @@ -1,6 +1,10 @@ // OTLP 수신 테넌트를 만들거나 토큰을 재발급한다. 토큰 원문은 이 출력에서 한 번만 보인다. // pnpm tsx database/scripts/otel-tenant.ts [name] // 이미 있는 slug 면 토큰만 새로 발급하고 이전 토큰은 즉시 무효가 된다. +// +// 대시보드 로그인용 Vercel 앱을 연결할 때는 토큰을 건드리지 않는다: +// pnpm tsx database/scripts/otel-tenant.ts --vercel-client-id cl_xxx [--vercel-team-id team_xxx] +// client secret 은 DB 가 아니라 OTEL_VERCEL_APPS 환경변수에 넣는다. import "dotenv/config"; import { randomBytes } from "node:crypto"; import { eq } from "drizzle-orm"; @@ -8,12 +12,42 @@ import { dz } from "../engine.js"; import { OtelTenant } from "../schemas/otel"; import { hashToken } from "../../app/subs/otel/ingest"; +// app/subs/otel/lib/tenant.ts 의 RESERVED_SLUGS 와 같다. 그 모듈은 next/headers 를 써서 스크립트에서 못 부른다. +const RESERVED_SLUGS = new Set(["v1", "auth", "api", "health"]); + +function flag(args: string[], name: string): string | undefined { + const i = args.indexOf(name); + return i >= 0 ? args[i + 1] : undefined; +} + async function main() { - const [slug, name] = process.argv.slice(2); - if (!slug || !/^[a-z0-9-]{2,64}$/.test(slug)) { + const args = process.argv.slice(2); + const [slug, name] = args.filter( + (a, i) => !a.startsWith("--") && !args[i - 1]?.startsWith("--"), + ); + const vercelClientId = flag(args, "--vercel-client-id"); + const vercelTeamId = flag(args, "--vercel-team-id"); + if (!slug || !/^[a-z0-9-]{2,64}$/.test(slug) || RESERVED_SLUGS.has(slug)) { console.error("usage: otel-tenant.ts [name]"); process.exit(1); } + if (vercelClientId) { + const updated = await dz + .update(OtelTenant) + .set({ + vercel_client_id: vercelClientId, + vercel_team_id: vercelTeamId ?? null, + }) + .where(eq(OtelTenant.slug, slug)) + .returning({ id: OtelTenant.id }); + if (updated.length === 0) { + console.error(`tenant "${slug}" not found. create it first`); + process.exit(1); + } + console.log(`linked Vercel app ${vercelClientId} to tenant "${slug}"`); + process.exit(0); + } + const token = `otel_${slug}_${randomBytes(24).toString("base64url")}`; const token_hash = hashToken(token);