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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,21 @@ export function useCurrentDocument(): CurrentDocument {
const urlParams = new URLSearchParams(window.location.search);
let docId = urlParams.get('documentId');

const STORAGE_KEY = 'velt-demo-document-id';

if (docId) {
// Use document ID from URL (shareable link)
setDocumentId(docId);
localStorage.setItem('velt-demo-document-id', docId);
localStorage.setItem(STORAGE_KEY, docId);
} else {
// 2. Check localStorage for existing document
const stored = localStorage.getItem('velt-inline-comments-demo-doc-id');
const stored = localStorage.getItem(STORAGE_KEY);
if (stored) {
docId = stored;
} else {
// 3. Generate new document ID
docId = `doc-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
localStorage.setItem('velt-inline-comments-demo-doc-id', docId);
localStorage.setItem(STORAGE_KEY, docId);
}

// Update URL with document ID for shareability
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ const saveCommentsToDB = async (request: {
body: JSON.stringify(request)
});
if (!response.ok) {
console.warn('[Velt Self-Host] SAVE endpoint returned', response.status);
return { success: true, statusCode: 200 }; // Graceful fallback
console.error('[Velt Self-Host] SAVE endpoint returned', response.status);
return { success: false, statusCode: response.status };
}
await response.json();
return { success: true, statusCode: 200 };
} catch (error) {
console.error('[Velt Self-Host] Error saving comments:', error);
return { success: true, statusCode: 200 }; // Graceful fallback
return { success: false, statusCode: 500 };
}
};

Expand All @@ -82,14 +82,14 @@ const deleteCommentsFromDB = async (request: {
body: JSON.stringify(request)
});
if (!response.ok) {
console.warn('[Velt Self-Host] DELETE endpoint returned', response.status);
return { success: true, statusCode: 200 }; // Graceful fallback
console.error('[Velt Self-Host] DELETE endpoint returned', response.status);
return { success: false, statusCode: response.status };
}
await response.json();
return { success: true, statusCode: 200 };
} catch (error) {
console.error('[Velt Self-Host] Error deleting comments:', error);
return { success: true, statusCode: 200 }; // Graceful fallback
return { success: false, statusCode: 500 };
}
};

Expand Down
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
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 });
}
}
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 });
}
}
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 });
}
}
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();
}
}
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";

Copy link
Copy Markdown

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_TOKEN secret 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. The DATABASE_URL in store.ts correctly uses process.env, but these Velt credentials do not. This exposes the token to anyone with repository access and will persist in git history.

Fix in Cursor Fix in Web


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 });
}
}
Loading
Loading