Repository navigation
π‘οΈ Sentinel: [MEDIUM] CSV μμ μ£Όμ μ·¨μ½μ μμ #792
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
seonghobae
wants to merge
2
commits into
developmental
Choose a base branch
from
jules-3241748385914271158-ab065637
base: developmental
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,18 @@ | ||
| import { NextRequest, NextResponse } from 'next/server' | ||
| import type { PaginatedResult, SessionItem } from '@argos/shared' | ||
| import { Prisma } from '@prisma/client' | ||
| import { db } from '@/lib/server/db' | ||
| import { requireAuth } from '@/lib/server/auth-helper' | ||
| import { handleRouteError } from '@/lib/server/error-helper' | ||
| import { parseDateRange, parsePagination } from '@/lib/server/dashboard' | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import type { PaginatedResult, SessionItem } from "@argos/shared"; | ||
| import { Prisma } from "@prisma/client"; | ||
| import { db } from "@/lib/server/db"; | ||
| import { requireAuth } from "@/lib/server/auth-helper"; | ||
| import { handleRouteError } from "@/lib/server/error-helper"; | ||
| import { parseDateRange, parsePagination } from "@/lib/server/dashboard"; | ||
| import { | ||
| assertOrgAccessBySlugOrResponse, | ||
| resolveOrgScopedProjectIds, | ||
| } from '@/lib/server/dashboard-route-helper' | ||
| import { canAccessIndividualData, forbiddenByRole } from '@/lib/server/rbac' | ||
| } from "@/lib/server/dashboard-route-helper"; | ||
| import { canAccessIndividualData, forbiddenByRole } from "@/lib/server/rbac"; | ||
|
|
||
| export const runtime = 'nodejs' | ||
| export const dynamic = 'force-dynamic' | ||
| export const runtime = "nodejs"; | ||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| const sessionInclude = { | ||
| user: { select: { id: true, name: true } }, | ||
|
|
@@ -22,34 +22,37 @@ const sessionInclude = { | |
| }, | ||
| // Title fallback β μ μ₯λ titleμ΄ μλ μΈμ μ©μΌλ‘ 첫 HUMAN λ©μμ§ 1κ±΄λ§ λ‘λ© | ||
| messages: { | ||
| where: { role: 'HUMAN' as const }, | ||
| orderBy: [{ timestamp: 'asc' as const }, { sequence: 'asc' as const }], | ||
| where: { role: "HUMAN" as const }, | ||
| orderBy: [{ timestamp: "asc" as const }, { sequence: "asc" as const }], | ||
| take: 1, | ||
| select: { content: true }, | ||
| }, | ||
| _count: { select: { events: true } }, | ||
| } satisfies Prisma.ClaudeSessionInclude | ||
| } satisfies Prisma.ClaudeSessionInclude; | ||
|
|
||
| type SessionWithInclude = Prisma.ClaudeSessionGetPayload<{ include: typeof sessionInclude }> | ||
| type SessionWithInclude = Prisma.ClaudeSessionGetPayload<{ | ||
| include: typeof sessionInclude; | ||
| }>; | ||
|
|
||
| function getSessionTotals(session: SessionWithInclude) { | ||
| let inputTokens = 0 | ||
| let outputTokens = 0 | ||
| let estimatedCostUsd = 0 | ||
| let inputTokens = 0; | ||
| let outputTokens = 0; | ||
| let estimatedCostUsd = 0; | ||
|
|
||
| for (const r of session.usageRecords) { | ||
| inputTokens += r.inputTokens | ||
| outputTokens += r.outputTokens | ||
| estimatedCostUsd += r.estimatedCostUsd ?? 0 | ||
| inputTokens += r.inputTokens; | ||
| outputTokens += r.outputTokens; | ||
| estimatedCostUsd += r.estimatedCostUsd ?? 0; | ||
| } | ||
|
|
||
| return { inputTokens, outputTokens, estimatedCostUsd } | ||
| return { inputTokens, outputTokens, estimatedCostUsd }; | ||
| } | ||
|
|
||
| function mapSessionItem(session: SessionWithInclude): SessionItem { | ||
| const totals = getSessionTotals(session) | ||
| const fallbackTitle = session.messages[0]?.content.slice(0, 200).trim() || null | ||
| const title = session.title?.trim() || fallbackTitle | ||
| const totals = getSessionTotals(session); | ||
| const fallbackTitle = | ||
| session.messages[0]?.content.slice(0, 200).trim() || null; | ||
| const title = session.title?.trim() || fallbackTitle; | ||
|
|
||
| return { | ||
| id: session.id, | ||
|
|
@@ -68,113 +71,136 @@ function mapSessionItem(session: SessionWithInclude): SessionItem { | |
| slug: session.project.slug, | ||
| name: session.project.name, | ||
| }, | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| function csvField(value: string | number | null | undefined) { | ||
| if (value === null || value === undefined) return '' | ||
| const text = String(value) | ||
| return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text | ||
| if (value === null || value === undefined) return ""; | ||
| let text = String(value); | ||
|
|
||
| // Prevent CSV Formula Injection (Spreadsheet Macro Injection) | ||
| if (typeof value !== "number") { | ||
| if (/^\s*[=+\-@\t\r\nοΌοΌοΌοΌ ]/.test(text)) { | ||
| text = "'" + text; | ||
| } | ||
| } | ||
|
|
||
| return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text; | ||
|
Comment on lines
+82
to
+88
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| } | ||
|
|
||
| function buildSessionsCsv(sessions: SessionWithInclude[]) { | ||
| const headers = [ | ||
| 'Session ID', | ||
| 'User', | ||
| 'Project', | ||
| 'Title', | ||
| 'First Prompt', | ||
| 'Input Tokens', | ||
| 'Output Tokens', | ||
| 'Estimated Cost USD', | ||
| 'Event Count', | ||
| 'Started At', | ||
| 'Ended At', | ||
| ] | ||
| "Session ID", | ||
| "User", | ||
| "Project", | ||
| "Title", | ||
| "First Prompt", | ||
| "Input Tokens", | ||
| "Output Tokens", | ||
| "Estimated Cost USD", | ||
| "Event Count", | ||
| "Started At", | ||
| "Ended At", | ||
| ]; | ||
|
|
||
| const rows = sessions.map((session) => { | ||
| const totals = getSessionTotals(session) | ||
| const title = session.title?.trim() || session.messages[0]?.content.slice(0, 200).trim() || '' | ||
| const totals = getSessionTotals(session); | ||
| const title = | ||
| session.title?.trim() || | ||
| session.messages[0]?.content.slice(0, 200).trim() || | ||
| ""; | ||
|
|
||
| return [ | ||
| session.id, | ||
| session.user.name, | ||
| session.project.name, | ||
| title, | ||
| session.messages[0]?.content ?? '', | ||
| session.messages[0]?.content ?? "", | ||
| totals.inputTokens, | ||
| totals.outputTokens, | ||
| totals.estimatedCostUsd, | ||
| session._count.events, | ||
| session.startedAt.toISOString(), | ||
| session.endedAt?.toISOString() ?? '', | ||
| ].map(csvField).join(',') | ||
| }) | ||
| session.endedAt?.toISOString() ?? "", | ||
| ] | ||
| .map(csvField) | ||
| .join(","); | ||
| }); | ||
|
|
||
| return `\uFEFF${[headers.join(','), ...rows].join('\r\n')}` | ||
| return `\uFEFF${[headers.join(","), ...rows].join("\r\n")}`; | ||
| } | ||
|
|
||
| // GET /api/orgs/:orgSlug/dashboard/sessions?from=&to=&projectId=&page=&pageSize=&sort=recent|cost | ||
| export async function GET( | ||
| req: NextRequest, | ||
| { params }: { params: Promise<{ orgSlug: string }> } | ||
| { params }: { params: Promise<{ orgSlug: string }> }, | ||
| ) { | ||
| try { | ||
| const auth = await requireAuth(req) | ||
| if (auth instanceof NextResponse) return auth | ||
| const { userId } = auth | ||
| const { orgSlug } = await params | ||
| const auth = await requireAuth(req); | ||
| if (auth instanceof NextResponse) return auth; | ||
| const { userId } = auth; | ||
| const { orgSlug } = await params; | ||
|
|
||
| const access = await assertOrgAccessBySlugOrResponse(orgSlug, userId) | ||
| if (access instanceof NextResponse) return access | ||
| const access = await assertOrgAccessBySlugOrResponse(orgSlug, userId); | ||
| if (access instanceof NextResponse) return access; | ||
|
|
||
| // Viewer μ°¨λ¨: μΈμ λͺ©λ‘μ titleμ HUMAN ν둬ννΈ μλ¬Έ(PII κ°λ₯)μ΄ ν¬ν¨λλ―λ‘ μ 체 κΈμ§. | ||
| if (!canAccessIndividualData(access.role)) { | ||
| return forbiddenByRole(access.role, 'MEMBER μ΄μ') | ||
| return forbiddenByRole(access.role, "MEMBER μ΄μ"); | ||
| } | ||
|
|
||
| const projectIdParam = req.nextUrl.searchParams.get('projectId') | ||
| const projectIds = await resolveOrgScopedProjectIds(access.org.id, userId, access.role, projectIdParam) | ||
| if (projectIds instanceof NextResponse) return projectIds | ||
| const projectIdParam = req.nextUrl.searchParams.get("projectId"); | ||
| const projectIds = await resolveOrgScopedProjectIds( | ||
| access.org.id, | ||
| userId, | ||
| access.role, | ||
| projectIdParam, | ||
| ); | ||
| if (projectIds instanceof NextResponse) return projectIds; | ||
|
|
||
| const fromQuery = req.nextUrl.searchParams.get('from') ?? undefined | ||
| const toQuery = req.nextUrl.searchParams.get('to') ?? undefined | ||
| const { from, to } = parseDateRange(fromQuery, toQuery) | ||
| const fromQuery = req.nextUrl.searchParams.get("from") ?? undefined; | ||
| const toQuery = req.nextUrl.searchParams.get("to") ?? undefined; | ||
| const { from, to } = parseDateRange(fromQuery, toQuery); | ||
|
|
||
| const { page, pageSize, skip, take } = parsePagination( | ||
| req.nextUrl.searchParams.get('page'), | ||
| req.nextUrl.searchParams.get('pageSize'), | ||
| ) | ||
| req.nextUrl.searchParams.get("page"), | ||
| req.nextUrl.searchParams.get("pageSize"), | ||
| ); | ||
|
|
||
| const sortBy: 'cost' | 'recent' = | ||
| req.nextUrl.searchParams.get('sort') === 'cost' ? 'cost' : 'recent' | ||
| const wantsCsv = req.nextUrl.searchParams.get('format') === 'csv' | ||
| const sortBy: "cost" | "recent" = | ||
| req.nextUrl.searchParams.get("sort") === "cost" ? "cost" : "recent"; | ||
| const wantsCsv = req.nextUrl.searchParams.get("format") === "csv"; | ||
|
|
||
| const filenameFrom = from.toISOString().slice(0, 10) | ||
| const filenameTo = to.toISOString().slice(0, 10) | ||
| const filenameFrom = from.toISOString().slice(0, 10); | ||
| const filenameTo = to.toISOString().slice(0, 10); | ||
| const csvHeaders = { | ||
| 'Content-Type': 'text/csv; charset=utf-8', | ||
| 'Content-Disposition': `attachment; filename="sessions-${orgSlug}-${filenameFrom}-to-${filenameTo}.csv"`, | ||
| } | ||
| "Content-Type": "text/csv; charset=utf-8", | ||
| "Content-Disposition": `attachment; filename="sessions-${orgSlug}-${filenameFrom}-to-${filenameTo}.csv"`, | ||
| }; | ||
|
|
||
| // projectIds κ° λΉμμΌλ©΄ (org μ project κ° νλλ μμ) μ¦μ λΉ κ²°κ³Ό λ°ν | ||
| if (projectIds.length === 0) { | ||
| if (wantsCsv) { | ||
| return new NextResponse(buildSessionsCsv([]), { headers: csvHeaders }) | ||
| return new NextResponse(buildSessionsCsv([]), { headers: csvHeaders }); | ||
| } | ||
| const body: PaginatedResult<SessionItem> = { items: [], total: 0, page, pageSize } | ||
| return NextResponse.json(body) | ||
| const body: PaginatedResult<SessionItem> = { | ||
| items: [], | ||
| total: 0, | ||
| page, | ||
| pageSize, | ||
| }; | ||
| return NextResponse.json(body); | ||
| } | ||
|
|
||
| const where = { | ||
| projectId: { in: projectIds }, | ||
| startedAt: { gte: from, lte: to }, | ||
| } | ||
| }; | ||
|
|
||
| if (wantsCsv) { | ||
| let csvSessions: SessionWithInclude[] | ||
| let csvSessions: SessionWithInclude[]; | ||
|
|
||
| if (sortBy === 'cost') { | ||
| if (sortBy === "cost") { | ||
| const rankedRows = await db.$queryRaw<Array<{ id: string }>>` | ||
| SELECT cs.id | ||
| FROM claude_sessions cs | ||
|
|
@@ -186,35 +212,37 @@ export async function GET( | |
| ORDER BY COALESCE(SUM(ur.estimated_cost_usd), 0) DESC, | ||
| cs.started_at DESC, | ||
| cs.id ASC | ||
| ` | ||
| const ids = rankedRows.map((r) => r.id) | ||
| `; | ||
| const ids = rankedRows.map((r) => r.id); | ||
| if (ids.length === 0) { | ||
| csvSessions = [] | ||
| csvSessions = []; | ||
| } else { | ||
| const rows = await db.claudeSession.findMany({ | ||
| where: { id: { in: ids } }, | ||
| include: sessionInclude, | ||
| }) | ||
| const byId = new Map(rows.map((s) => [s.id, s])) | ||
| }); | ||
| const byId = new Map(rows.map((s) => [s.id, s])); | ||
| csvSessions = ids | ||
| .map((id) => byId.get(id)) | ||
| .filter((s): s is SessionWithInclude => !!s) | ||
| .filter((s): s is SessionWithInclude => !!s); | ||
| } | ||
| } else { | ||
| csvSessions = await db.claudeSession.findMany({ | ||
| where, | ||
| include: sessionInclude, | ||
| orderBy: { startedAt: 'desc' }, | ||
| }) | ||
| orderBy: { startedAt: "desc" }, | ||
| }); | ||
| } | ||
|
|
||
| return new NextResponse(buildSessionsCsv(csvSessions), { headers: csvHeaders }) | ||
| return new NextResponse(buildSessionsCsv(csvSessions), { | ||
| headers: csvHeaders, | ||
| }); | ||
| } | ||
|
|
||
| let sessions: SessionWithInclude[] | ||
| let total: number | ||
| let sessions: SessionWithInclude[]; | ||
| let total: number; | ||
|
|
||
| if (sortBy === 'cost') { | ||
| if (sortBy === "cost") { | ||
| // 1) SUM(estimated_cost_usd) κΈ°μ€μΌλ‘ ν΄λΉ νμ΄μ§μ session idλ§ λ¨Όμ λ½λλ€. | ||
| // tie-breaker: started_at desc β id asc λ‘ νμ΄μ§ κ²½κ³λ₯Ό μμ ν. | ||
| const [rankedRows, countResult] = await Promise.all([ | ||
|
|
@@ -232,43 +260,43 @@ export async function GET( | |
| LIMIT ${take} OFFSET ${skip} | ||
| `, | ||
| db.claudeSession.count({ where }), | ||
| ]) | ||
| total = countResult | ||
| ]); | ||
| total = countResult; | ||
|
|
||
| const ids = rankedRows.map((r) => r.id) | ||
| const ids = rankedRows.map((r) => r.id); | ||
| if (ids.length === 0) { | ||
| sessions = [] | ||
| sessions = []; | ||
| } else { | ||
| // 2) ν΄λΉ idλ€λ§ κΈ°μ‘΄ include κ΅¬μ‘°λ‘ νμ΄λλ μ΄μ ν rank μμ 볡μ. | ||
| const rows = await db.claudeSession.findMany({ | ||
| where: { id: { in: ids } }, | ||
| include: sessionInclude, | ||
| }) | ||
| const byId = new Map(rows.map((s) => [s.id, s])) | ||
| }); | ||
| const byId = new Map(rows.map((s) => [s.id, s])); | ||
| sessions = ids | ||
| .map((id) => byId.get(id)) | ||
| .filter((s): s is SessionWithInclude => !!s) | ||
| .filter((s): s is SessionWithInclude => !!s); | ||
| } | ||
| } else { | ||
| const [rows, countResult] = await Promise.all([ | ||
| db.claudeSession.findMany({ | ||
| where, | ||
| include: sessionInclude, | ||
| orderBy: { startedAt: 'desc' }, | ||
| orderBy: { startedAt: "desc" }, | ||
| skip, | ||
| take, | ||
| }), | ||
| db.claudeSession.count({ where }), | ||
| ]) | ||
| sessions = rows | ||
| total = countResult | ||
| ]); | ||
| sessions = rows; | ||
| total = countResult; | ||
| } | ||
|
|
||
| const items: SessionItem[] = sessions.map(mapSessionItem) | ||
| const items: SessionItem[] = sessions.map(mapSessionItem); | ||
|
|
||
| const body: PaginatedResult<SessionItem> = { items, total, page, pageSize } | ||
| return NextResponse.json(body) | ||
| const body: PaginatedResult<SessionItem> = { items, total, page, pageSize }; | ||
| return NextResponse.json(body); | ||
| } catch (err) { | ||
| return handleRouteError(err) | ||
| return handleRouteError(err); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
π Formatting churn obscures CSV change
The route-wide quote and semicolon rewrite hides the small CSV change in a 240-line diff. Keeping the existing formatting makes the change easier to review and merge.
Was this helpful? React with π or π to provide feedback.