forked from supabase/stripe-sync-engine
-
Notifications
You must be signed in to change notification settings - Fork 10
Show sync status in the dashboard #133
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
Yostra
wants to merge
1
commit into
main
Choose a base branch
from
dashboard_s
base: main
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.
+253
−10
Open
Changes from all commits
Commits
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 |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| import { NextRequest, NextResponse } from 'next/server' | ||
| import { getSession } from '@/lib/sessions' | ||
|
|
||
| const SYNC_PROGRESS_QUERY = ` | ||
| SELECT json_build_object( | ||
| 'run', ( | ||
| SELECT row_to_json(r) FROM ( | ||
| SELECT account_id, started_at, closed_at, triggered_by, status, | ||
| total_processed, total_objects, complete_count, error_count, | ||
| running_count, pending_count, error_message | ||
| FROM stripe.sync_runs ORDER BY started_at DESC LIMIT 1 | ||
| ) r | ||
| ), | ||
| 'objects', COALESCE(( | ||
| SELECT json_agg(row_to_json(p) ORDER BY p.object) | ||
| FROM stripe.sync_obj_progress p | ||
| ), '[]'::json) | ||
| ) AS result | ||
| ` | ||
|
|
||
| export async function GET(request: NextRequest) { | ||
| try { | ||
| const sessionId = request.nextUrl.searchParams.get('sessionId') | ||
|
|
||
| if (!sessionId) { | ||
| return NextResponse.json({ error: 'Missing sessionId' }, { status: 400 }) | ||
| } | ||
|
|
||
| const session = getSession(sessionId) | ||
| if (!session) { | ||
| return NextResponse.json({ error: 'Session expired' }, { status: 401 }) | ||
| } | ||
|
|
||
| const response = await fetch( | ||
| `https://api.supabase.com/v1/projects/${session.projectRef}/database/query`, | ||
| { | ||
| method: 'POST', | ||
| headers: { | ||
| Authorization: `Bearer ${session.accessToken}`, | ||
| 'Content-Type': 'application/json', | ||
| }, | ||
| body: JSON.stringify({ query: SYNC_PROGRESS_QUERY }), | ||
| } | ||
| ) | ||
|
|
||
| if (!response.ok) { | ||
| const text = await response.text() | ||
| return NextResponse.json({ error: `Database query failed: ${text}` }, { status: 500 }) | ||
| } | ||
|
|
||
| const rows = await response.json() | ||
| const data = rows?.[0]?.result ?? { run: null, objects: [] } | ||
|
|
||
| return NextResponse.json(data) | ||
| } catch (error) { | ||
| return NextResponse.json( | ||
| { error: error instanceof Error ? error.message : 'Unknown error' }, | ||
| { status: 500 } | ||
| ) | ||
| } | ||
| } | ||
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 |
|---|---|---|
| @@ -0,0 +1,176 @@ | ||
| 'use client' | ||
|
|
||
| import { useEffect, useState, useCallback } from 'react' | ||
|
|
||
| interface ObjectProgress { | ||
| object: string | ||
| pct_complete: number | ||
| processed: number | ||
| } | ||
|
|
||
| interface SyncRun { | ||
| account_id: string | ||
| started_at: string | ||
| closed_at: string | null | ||
| status: string | ||
| total_processed: number | ||
| total_objects: number | ||
| complete_count: number | ||
| error_count: number | ||
| running_count: number | ||
| pending_count: number | ||
| } | ||
|
|
||
| interface SyncProgressProps { | ||
| sessionId: string | ||
| } | ||
|
|
||
| function barColor(pct: number): string { | ||
| if (pct >= 100) return '#16a34a' | ||
| if (pct > 0) return '#2563eb' | ||
| return '#9ca3af' | ||
| } | ||
|
|
||
| export function SyncProgress({ sessionId }: SyncProgressProps) { | ||
| const [run, setRun] = useState<SyncRun | null>(null) | ||
| const [objects, setObjects] = useState<ObjectProgress[]>([]) | ||
| const [error, setError] = useState<string | null>(null) | ||
| const [loading, setLoading] = useState(true) | ||
|
|
||
| const fetchData = useCallback(async () => { | ||
| try { | ||
| const res = await fetch(`/api/sync-progress?sessionId=${sessionId}`) | ||
| const data = await res.json() | ||
| if (!res.ok) { | ||
| setError(data.error) | ||
| return | ||
| } | ||
| setRun(data.run) | ||
| setObjects(data.objects ?? []) | ||
| setError(null) | ||
| } catch (err) { | ||
| setError(err instanceof Error ? err.message : 'Failed to fetch') | ||
| } finally { | ||
| setLoading(false) | ||
| } | ||
| }, [sessionId]) | ||
|
|
||
| useEffect(() => { | ||
| fetchData() | ||
| const interval = setInterval(fetchData, 2000) | ||
| return () => clearInterval(interval) | ||
| }, [fetchData]) | ||
|
|
||
| if (loading) return <div style={containerStyle}>Loading...</div> | ||
|
|
||
| if (error) { | ||
| return ( | ||
| <div style={{ ...containerStyle, background: '#fff3cd', color: '#856404' }}> | ||
| <span style={{ fontSize: 20 }}>⚠️</span> {error} | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| if (!run || objects.length === 0) return null | ||
|
|
||
| const totalRows = objects.reduce((sum, o) => sum + Number(o.processed), 0) | ||
|
|
||
| return ( | ||
| <div style={tableWrapStyle}> | ||
| <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}> | ||
| <thead> | ||
| <tr> | ||
| <th style={{ ...thStyle, textAlign: 'left' }}>Table</th> | ||
| <th style={{ ...thStyle, textAlign: 'left', width: '35%' }}>Progress</th> | ||
| <th style={{ ...thStyle, textAlign: 'right' }}>Rows</th> | ||
| </tr> | ||
| </thead> | ||
| <tbody> | ||
| {objects.map((obj) => { | ||
| const pct = Number(obj.pct_complete) | ||
| return ( | ||
| <tr key={obj.object} style={{ borderBottom: '1px solid #eee' }}> | ||
| <td style={tdStyle}> | ||
| <span style={{ fontWeight: 500 }}>{obj.object}</span> | ||
| </td> | ||
| <td style={tdStyle}> | ||
| <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> | ||
| <div style={trackStyle}> | ||
| <div | ||
| style={{ | ||
| height: '100%', | ||
| width: `${pct}%`, | ||
| borderRadius: 3, | ||
| background: barColor(pct), | ||
| transition: 'width 0.5s ease', | ||
| }} | ||
| /> | ||
| </div> | ||
| <span style={{ fontSize: 12, color: '#888', minWidth: 42, textAlign: 'right' }}> | ||
| {pct.toFixed(1)}% | ||
| </span> | ||
| </div> | ||
| </td> | ||
| <td style={{ ...tdStyle, textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}> | ||
| {Number(obj.processed).toLocaleString()} | ||
| </td> | ||
| </tr> | ||
| ) | ||
| })} | ||
| </tbody> | ||
| </table> | ||
| <div style={footerStyle}> | ||
| <span style={{ fontWeight: 600 }}>{totalRows.toLocaleString()} total rows</span> | ||
| </div> | ||
| </div> | ||
| ) | ||
| } | ||
|
|
||
| const containerStyle: React.CSSProperties = { | ||
| display: 'flex', | ||
| alignItems: 'center', | ||
| gap: 10, | ||
| padding: '16px 20px', | ||
| background: '#f9f9f9', | ||
| borderRadius: 8, | ||
| fontSize: 16, | ||
| } | ||
|
|
||
| const tableWrapStyle: React.CSSProperties = { | ||
| border: '1px solid #ddd', | ||
| borderRadius: 8, | ||
| overflow: 'hidden', | ||
| } | ||
|
|
||
| const thStyle: React.CSSProperties = { | ||
| padding: '10px 16px', | ||
| fontSize: 12, | ||
| fontWeight: 500, | ||
| textTransform: 'uppercase', | ||
| letterSpacing: 0.5, | ||
| color: '#888', | ||
| background: '#fafafa', | ||
| borderBottom: '1px solid #ddd', | ||
| } | ||
|
|
||
| const tdStyle: React.CSSProperties = { | ||
| padding: '10px 16px', | ||
| verticalAlign: 'middle', | ||
| } | ||
|
|
||
| const trackStyle: React.CSSProperties = { | ||
| flex: 1, | ||
| height: 6, | ||
| background: '#eee', | ||
| borderRadius: 3, | ||
| overflow: 'hidden', | ||
| } | ||
|
|
||
| const footerStyle: React.CSSProperties = { | ||
| display: 'flex', | ||
| justifyContent: 'space-between', | ||
| padding: '10px 16px', | ||
| background: '#fafafa', | ||
| borderTop: '1px solid #ddd', | ||
| fontSize: 13, | ||
| } |
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.
Check failure
Code scanning / CodeQL
Server-side request forgery Critical
Copilot Autofix
AI 4 days ago
In general, the problem is that
supabaseProjectRef(from the deploy request body) is stored assession.projectRefand later interpolated into a URL path without any validation. To fix this without changing the visible behavior, we should validate and normalize the project reference at the point of intake inpackages/dashboard/src/app/api/deploy/route.ts, rejecting values that are clearly malformed, and store only this sanitized value in the session. That way, by the timesync-progress/route.tsreadssession.projectRef, it is guaranteed to be a safe path segment for the Supabase API URL.The single best fix here is:
deploy/route.ts, add validation logic right after readingsupabaseProjectReffrom the request body:abcd1234.400error.normalizedSupabaseProjectRef) in both:install({ supabaseProjectRef: ... }).createSession(...).sync-progress/route.tsbecause it will now only ever see a validatedprojectRef.This keeps existing functionality (deploying and storing sessions) but prevents arbitrary, potentially dangerous path components from being persisted and later used to build request URLs. No new external dependencies are strictly necessary; we can implement validation with a simple regular expression.
Concretely:
packages/dashboard/src/app/api/deploy/route.ts:supabaseAccessToken, supabaseProjectRef, stripeKey, add validation logic.const normalizedSupabaseProjectRef = supabaseProjectRef.trim();then verify it with a regex like/^[a-z0-9-]{1,64}$/.400with an error message.normalizedSupabaseProjectRefinstead ofsupabaseProjectRefwhen callinginstallandcreateSession.sessions.tsorsync-progress/route.tsbecause they operate on the sanitized value stored in the session.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.
False positive, user provides a projectRef as intended