Repository navigation
Postgres Self-hosting Dashboard Demo #26
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
Merged
Merged
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
35 changes: 35 additions & 0 deletions
35
apps/react/comments/dashboard/self-hosting/dashboard-postgres-demo/.gitignore
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,35 @@ | ||
| # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. | ||
|
|
||
| # dependencies | ||
| /node_modules | ||
| /.pnp | ||
| .pnp.js | ||
|
|
||
| # testing | ||
| /coverage | ||
|
|
||
| # next.js | ||
| /.next/ | ||
| /out/ | ||
|
|
||
| # production | ||
| /build | ||
|
|
||
| # misc | ||
| .DS_Store | ||
| *.pem | ||
|
|
||
| # debug | ||
| npm-debug.log* | ||
| yarn-debug.log* | ||
| yarn-error.log* | ||
|
|
||
| # local env files | ||
| .env*.local | ||
|
|
||
| # vercel | ||
| .vercel | ||
|
|
||
| # typescript | ||
| *.tsbuildinfo | ||
| next-env.d.ts |
20 changes: 20 additions & 0 deletions
20
...ents/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/delete/route.ts
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,20 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import { deleteComment } from '../store'; | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const body = await request.json(); | ||
| const { commentAnnotationId } = body; | ||
|
|
||
| console.log('[Velt API] DELETE comment:', commentAnnotationId); | ||
|
|
||
| if (commentAnnotationId) { | ||
| await deleteComment(commentAnnotationId); | ||
| } | ||
|
|
||
| return NextResponse.json({ success: true }); | ||
| } catch (error) { | ||
| console.error('[Velt API] Error deleting comment:', error); | ||
| return NextResponse.json({ success: false, error: 'Failed to delete' }, { status: 500 }); | ||
| } | ||
| } |
22 changes: 22 additions & 0 deletions
22
...omments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/get/route.ts
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,22 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import { getComments } from '../store'; | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const body = await request.json(); | ||
| const { organizationId, commentAnnotationIds, documentIds } = body; | ||
|
|
||
| console.log('[Velt API] GET comments:', { organizationId, commentAnnotationIds, documentIds }); | ||
|
|
||
| const result = await getComments({ | ||
| organizationId, | ||
| commentAnnotationIds, | ||
| documentIds, | ||
| }); | ||
|
|
||
| return NextResponse.json({ result, success: true }); | ||
| } catch (error) { | ||
| console.error('[Velt API] Error getting comments:', error); | ||
| return NextResponse.json({ result: {}, success: true }, { status: 200 }); | ||
| } | ||
| } |
23 changes: 23 additions & 0 deletions
23
...mments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/save/route.ts
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,23 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
| import { saveComments } from '../store'; | ||
|
|
||
| export async function POST(request: NextRequest) { | ||
| try { | ||
| const body = await request.json(); | ||
| const { commentAnnotation, metadata } = body; | ||
|
|
||
| console.log('[Velt API] SAVE comments:', { commentAnnotation, metadata }); | ||
|
|
||
| if (commentAnnotation) { | ||
| // Extract documentId and organizationId from metadata | ||
| const documentId = metadata?.documentId; | ||
| const organizationId = metadata?.organizationId; | ||
| await saveComments(commentAnnotation, { documentId, organizationId }); | ||
| } | ||
|
|
||
| return NextResponse.json({ success: true }); | ||
| } catch (error) { | ||
| console.error('[Velt API] Error saving comments:', error); | ||
| return NextResponse.json({ success: false, error: 'Failed to save' }, { status: 500 }); | ||
| } | ||
| } |
179 changes: 179 additions & 0 deletions
179
...ct/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/comments/store.ts
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,179 @@ | ||
| // PostgreSQL store for Velt comments | ||
| // Docs: https://docs.velt.dev/self-host-data/comments | ||
|
|
||
| import { Pool } from 'pg'; | ||
|
|
||
| export type CommentAnnotation = { | ||
| annotationId: string; | ||
| documentId?: string; | ||
| organizationId?: string; | ||
| metadata?: unknown; | ||
| comments: Record<string, { commentId: string | number; commentHtml?: string; commentText?: string }>; | ||
| }; | ||
|
|
||
| // PostgreSQL connection string | ||
| const DATABASE_URL = process.env.DATABASE_URL; | ||
|
|
||
| if (!DATABASE_URL && process.env.NODE_ENV === 'production') { | ||
| console.warn('[PostgreSQL] WARNING: DATABASE_URL not set. Database operations will fail.'); | ||
| } | ||
|
|
||
| const TABLE_NAME = 'comment_annotations'; | ||
|
|
||
| // Create a connection pool for serverless environments | ||
| let pool: Pool | null = null; | ||
| let initPromise: Promise<void> | null = null; | ||
|
|
||
| function getPool(): Pool { | ||
| if (!pool) { | ||
| pool = new Pool({ | ||
| connectionString: DATABASE_URL, | ||
| ssl: DATABASE_URL?.includes('sslmode=require') ? { rejectUnauthorized: false } : false, | ||
| max: 10, | ||
| idleTimeoutMillis: 30000, | ||
| connectionTimeoutMillis: 10000, | ||
| }); | ||
| } | ||
| return pool; | ||
| } | ||
|
|
||
| async function ensureInitialized(): Promise<void> { | ||
| if (!initPromise) { | ||
| initPromise = initializeTable(); | ||
| } | ||
| return initPromise; | ||
| } | ||
|
|
||
| async function initializeTable(): Promise<void> { | ||
| const client = await getPool().connect(); | ||
| try { | ||
| await client.query(` | ||
| CREATE TABLE IF NOT EXISTS ${TABLE_NAME} ( | ||
| annotation_id TEXT PRIMARY KEY, | ||
| document_id TEXT, | ||
| organization_id TEXT, | ||
| data JSONB NOT NULL, | ||
| created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(), | ||
| updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() | ||
| ) | ||
| `); | ||
|
|
||
| // Create indexes for faster queries | ||
| await client.query(` | ||
| CREATE INDEX IF NOT EXISTS idx_${TABLE_NAME}_document_id ON ${TABLE_NAME}(document_id) | ||
| `); | ||
| await client.query(` | ||
| CREATE INDEX IF NOT EXISTS idx_${TABLE_NAME}_organization_id ON ${TABLE_NAME}(organization_id) | ||
| `); | ||
|
|
||
| console.log('[PostgreSQL] Table initialized:', TABLE_NAME); | ||
| } finally { | ||
| client.release(); | ||
| } | ||
| } | ||
|
|
||
| export async function getComments(filters: { | ||
| organizationId?: string; | ||
| commentAnnotationIds?: string[]; | ||
| documentIds?: string[]; | ||
| }): Promise<Record<string, CommentAnnotation>> { | ||
| await ensureInitialized(); | ||
| const client = await getPool().connect(); | ||
| try { | ||
| const conditions: string[] = []; | ||
| const values: unknown[] = []; | ||
| let paramIndex = 1; | ||
|
|
||
| if (filters.commentAnnotationIds?.length) { | ||
| conditions.push(`annotation_id = ANY($${paramIndex})`); | ||
| values.push(filters.commentAnnotationIds); | ||
| paramIndex++; | ||
| } | ||
| if (filters.documentIds?.length) { | ||
| conditions.push(`document_id = ANY($${paramIndex})`); | ||
| values.push(filters.documentIds); | ||
| paramIndex++; | ||
| } | ||
| if (filters.organizationId) { | ||
| conditions.push(`organization_id = $${paramIndex}`); | ||
| values.push(filters.organizationId); | ||
| paramIndex++; | ||
| } | ||
|
|
||
| const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : ''; | ||
| const query = `SELECT annotation_id, data FROM ${TABLE_NAME} ${whereClause}`; | ||
|
|
||
| const result = await client.query(query, values); | ||
|
|
||
| // Convert to Record format expected by Velt | ||
| const annotations: Record<string, CommentAnnotation> = {}; | ||
| for (const row of result.rows) { | ||
| const annotation = row.data as CommentAnnotation; | ||
| annotations[row.annotation_id] = annotation; | ||
| } | ||
|
|
||
| return annotations; | ||
| } finally { | ||
| client.release(); | ||
| } | ||
| } | ||
|
|
||
| export async function saveComments( | ||
| annotations: Record<string, CommentAnnotation>, | ||
| context?: { documentId?: string; organizationId?: string } | ||
| ): Promise<void> { | ||
| if (Object.keys(annotations).length === 0) return; | ||
|
|
||
| await ensureInitialized(); | ||
| const client = await getPool().connect(); | ||
| try { | ||
| // Use a transaction for batch upserts | ||
| await client.query('BEGIN'); | ||
|
|
||
| for (const [id, annotation] of Object.entries(annotations)) { | ||
| const documentId = context?.documentId || annotation.documentId || null; | ||
| const organizationId = context?.organizationId || annotation.organizationId || null; | ||
|
|
||
| // Store the full annotation with annotationId included | ||
| const data = { | ||
| ...annotation, | ||
| annotationId: id, | ||
| documentId, | ||
| organizationId, | ||
| }; | ||
|
|
||
| await client.query( | ||
| `INSERT INTO ${TABLE_NAME} (annotation_id, document_id, organization_id, data, updated_at) | ||
| VALUES ($1, $2, $3, $4, NOW()) | ||
| ON CONFLICT (annotation_id) | ||
| DO UPDATE SET | ||
| document_id = EXCLUDED.document_id, | ||
| organization_id = EXCLUDED.organization_id, | ||
| data = EXCLUDED.data, | ||
| updated_at = NOW()`, | ||
| [id, documentId, organizationId, JSON.stringify(data)] | ||
| ); | ||
| } | ||
|
|
||
| await client.query('COMMIT'); | ||
| } catch (error) { | ||
| await client.query('ROLLBACK'); | ||
| throw error; | ||
| } finally { | ||
| client.release(); | ||
| } | ||
| } | ||
|
|
||
| export async function deleteComment(annotationId: string): Promise<boolean> { | ||
| await ensureInitialized(); | ||
| const client = await getPool().connect(); | ||
| try { | ||
| const result = await client.query( | ||
| `DELETE FROM ${TABLE_NAME} WHERE annotation_id = $1`, | ||
| [annotationId] | ||
| ); | ||
| return (result.rowCount ?? 0) > 0; | ||
| } finally { | ||
| client.release(); | ||
| } | ||
| } |
40 changes: 40 additions & 0 deletions
40
...react/comments/dashboard/self-hosting/dashboard-postgres-demo/app/api/velt/token/route.ts
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,40 @@ | ||
| import { NextRequest, NextResponse } from 'next/server'; | ||
|
|
||
| // [Velt] API key and auth token from environment variables | ||
| const NEXT_PUBLIC_VELT_API_KEY = "6xTcUFtlYAlCdh11zrKB"; | ||
| const VELT_AUTH_TOKEN = "bd4d5226050470b6c658054fcdf1092a"; | ||
|
|
||
| export async function POST(req: NextRequest) { | ||
| try { | ||
| const { userId, organizationId, email, isAdmin } = await req.json(); | ||
| if (!userId || !organizationId) { | ||
| return NextResponse.json({ error: 'Missing userId or organizationId' }, { status: 400 }); | ||
| } | ||
| if (!VELT_AUTH_TOKEN) { | ||
| return NextResponse.json({ error: 'Server configuration error: missing VELT_AUTH_TOKEN' }, { status: 500 }); | ||
| } | ||
| const body = { | ||
| data: { | ||
| userId, | ||
| userProperties: { | ||
| organizationId, | ||
| ...(typeof isAdmin === 'boolean' ? { isAdmin } : {}), | ||
| ...(email ? { email } : {}), | ||
| }, | ||
| }, | ||
| }; | ||
| const res = await fetch('https://api.velt.dev/v2/auth/token/get', { | ||
| method: 'POST', | ||
| headers: { 'Content-Type': 'application/json', 'x-velt-api-key': NEXT_PUBLIC_VELT_API_KEY, 'x-velt-auth-token': VELT_AUTH_TOKEN }, | ||
| body: JSON.stringify(body), | ||
| }); | ||
| const json = await res.json(); | ||
| const token = json?.result?.data?.token; | ||
| if (!res.ok || !token) { | ||
| return NextResponse.json({ error: json?.error?.message || 'Failed to generate token' }, { status: 500 }); | ||
| } | ||
| return NextResponse.json({ token }); | ||
| } catch { | ||
| return NextResponse.json({ error: 'Internal error' }, { status: 500 }); | ||
| } | ||
| } | ||
Oops, something went wrong.
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.
Bug: Hardcoded authentication token exposed in source code
The
VELT_AUTH_TOKENsecret is hardcoded directly in the source code despite the comment claiming these values come from environment variables. This authentication token grants access to the Velt API and should never be committed to version control. TheDATABASE_URLinstore.tscorrectly usesprocess.env, but these Velt credentials do not. This exposes the token to anyone with repository access and will persist in git history.