📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Better access control
Blue Mousecbb63606abb2
diff --git a/backend/apps/cloud/src/ai/ai-chat.service.ts b/backend/apps/cloud/src/ai/ai-chat.service.tsindex f2253bbbd..e24d67fb2 100644--- a/backend/apps/cloud/src/ai/ai-chat.service.ts+++ b/backend/apps/cloud/src/ai/ai-chat.service.ts@@ -176,6 +176,15 @@ export class AiChatService {id: chatId,project: { id: projectId },},+ relations: ['user'],})}++ /**+ * Check if the user is the owner of a chat.+ */+ isOwner(chat: AiChat, userId: string | null): boolean {+ if (!userId) return false+ return chat.user?.id === userId+ }}diff --git a/backend/apps/cloud/src/ai/ai.controller.ts b/backend/apps/cloud/src/ai/ai.controller.tsindex 276b935c6..73c1e30d8 100644--- a/backend/apps/cloud/src/ai/ai.controller.ts+++ b/backend/apps/cloud/src/ai/ai.controller.ts@@ -464,28 +464,23 @@ export class AiController {this.projectService.allowedToView(project, uid)- let chat-- if (project.public) {- if (!uid) {- chat = await this.aiChatService.verifyPublicChatAccess(chatId, pid)- } else {- chat = await this.aiChatService.verifyAccess(chatId, pid, uid)- }- } else {- chat = await this.aiChatService.verifyOwnerAccess(chatId, pid, uid)- }+ // Anyone who can view the project can view any chat via direct link+ const chat = await this.aiChatService.verifyProjectAccess(chatId, pid)if (!chat) {throw new NotFoundException('Chat not found')}+ // Check if the current user is the owner of this chat+ const isOwner = uid && chat.user?.id === uid+return {id: chat.id,name: chat.name,messages: chat.messages,created: chat.created,updated: chat.updated,+ isOwner,}}@@ -540,7 +535,7 @@ export class AiController {@Post(':pid/chats/:chatId')@Auth(false, true) // Allow optional auth for public projects@ApiOperation({ summary: 'Update an AI chat' })- @ApiResponse({ status: 200, description: 'Chat updated' })+ @ApiResponse({ status: 200, description: 'Chat updated or branched' })async updateChat(@Param('pid') pid: string,@Param('chatId') chatId: string,@@ -560,31 +555,60 @@ export class AiController {this.projectService.allowedToView(project, uid)- const existingChat = await this.aiChatService.verifyOwnerAccess(+ // Check if the chat exists and belongs to this project+ const existingChat = await this.aiChatService.verifyProjectAccess(chatId,pid,- uid,)if (!existingChat) {throw new NotFoundException('Chat not found')}- const chat = await this.aiChatService.update(chatId, {- messages: updateChatDto.messages,+ // Check if the current user owns this chat+ const isOwner = this.aiChatService.isOwner(existingChat, uid)++ if (isOwner) {+ // User owns the chat - update it directly+ const chat = await this.aiChatService.update(chatId, {+ messages: updateChatDto.messages,+ name: updateChatDto.name,+ })++ if (!chat) {+ throw new NotFoundException('Chat not found')+ }++ return {+ id: chat.id,+ name: chat.name,+ messages: chat.messages,+ created: chat.created,+ updated: chat.updated,+ branched: false,+ }+ }++ // User doesn't own the chat - create a new branched chat with the messages+ const branchedChat = await this.aiChatService.create({+ projectId: pid,+ userId: uid,+ messages: updateChatDto.messages || existingChat.messages,name: updateChatDto.name,})- if (!chat) {- throw new NotFoundException('Chat not found')- }+ this.logger.log(+ { uid, pid, originalChatId: chatId, newChatId: branchedChat.id },+ 'Chat branched for non-owner',+ )return {- id: chat.id,- name: chat.name,- messages: chat.messages,- created: chat.created,- updated: chat.updated,+ id: branchedChat.id,+ name: branchedChat.name,+ messages: branchedChat.messages,+ created: branchedChat.created,+ updated: branchedChat.updated,+ branched: true,}}diff --git a/backend/apps/cloud/src/experiment/experiment.controller.ts b/backend/apps/cloud/src/experiment/experiment.controller.tsindex e176f738e..1a133344b 100644--- a/backend/apps/cloud/src/experiment/experiment.controller.ts+++ b/backend/apps/cloud/src/experiment/experiment.controller.ts@@ -89,7 +89,7 @@ export class ExperimentController {@ApiBearerAuth()@Get('/project/:projectId')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: [ExperimentDto] })@ApiOperation({ summary: 'Get all experiments for a project' })async getProjectExperiments(@@ -141,7 +141,7 @@ export class ExperimentController {@ApiBearerAuth()@Get('/:id')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: ExperimentDto })@ApiOperation({ summary: 'Get an experiment by ID' })async getExperiment(@@ -846,7 +846,7 @@ export class ExperimentController {@ApiBearerAuth()@Get('/:id/results')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: ExperimentResultsDto })@ApiOperation({ summary: 'Get experiment results with Bayesian statistics' })async getExperimentResults(diff --git a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts b/backend/apps/cloud/src/feature-flag/feature-flag.controller.tsindex 3826fb0e9..7e77e8118 100644--- a/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/cloud/src/feature-flag/feature-flag.controller.ts@@ -77,7 +77,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/project/:projectId')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: [FeatureFlagDto] })@ApiOperation({ summary: 'Get all feature flags for a project' })async getProjectFeatureFlags(@@ -124,7 +124,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/:flagId')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: FeatureFlagDto })@ApiOperation({ summary: 'Get a feature flag by ID' })async getFeatureFlag(@@ -546,7 +546,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/:id/stats')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: FeatureFlagStatsDto })@ApiOperation({ summary: 'Get statistics for a feature flag' })async getFeatureFlagStats(@@ -648,7 +648,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/:id/profiles')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: FeatureFlagProfilesResponseDto })@ApiOperation({summary: 'Get profiles who have evaluated a feature flag',diff --git a/backend/apps/cloud/src/goal/goal.controller.ts b/backend/apps/cloud/src/goal/goal.controller.tsindex 5a172a1e8..1230051c1 100644--- a/backend/apps/cloud/src/goal/goal.controller.ts+++ b/backend/apps/cloud/src/goal/goal.controller.ts@@ -89,7 +89,7 @@ export class GoalController {@ApiBearerAuth()@Get('/:goalId')- @Auth()+ @Auth(true, true)@ApiResponse({ status: 200, type: Goal })async getGoal(@CurrentUserId() userId: string,@@ -118,7 +118,7 @@ export class GoalController {@ApiBearerAuth()@Get('/project/:projectId')- @Auth()+ @Auth(true, true)@ApiResponse({ status: 200, type: [GoalDto] })async getProjectGoals(@CurrentUserId() userId: string,@@ -393,7 +393,7 @@ export class GoalController {@ApiBearerAuth()@Get('/:id/stats')- @Auth()+ @Auth(true, true)@ApiResponse({ status: 200, type: GoalStatsDto })async getGoalStats(@CurrentUserId() userId: string,@@ -601,7 +601,7 @@ export class GoalController {@ApiBearerAuth()@Get('/:id/chart')- @Auth()+ @Auth(true, true)async getGoalChart(@CurrentUserId() userId: string,@Param('id') id: string,diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex 90c78409f..c6144d915 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -730,7 +730,7 @@ export class ProjectController {@Get('/annotations/:pid')@ApiResponse({ status: 200 })- @Auth(true)+ @Auth(true, true)async getAnnotations(@Param('pid') pid: string,@CurrentUserId() userId: string,@@ -738,11 +738,7 @@ export class ProjectController {): Promise<any> {this.logger.log({ pid, userId }, 'GET /project/annotations')- if (!userId) {- throw new UnauthorizedException('Please auth first')- }-- const project = await this.projectService.getFullProject(pid, userId)+ const project = await this.projectService.getFullProject(pid)if (!project) {throw new NotFoundException('Project not found.')diff --git a/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.ts b/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.tsindex dce481f59..c55167741 100644--- a/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.ts+++ b/backend/apps/cloud/src/revenue/dto/revenue-stats.dto.ts@@ -89,26 +89,6 @@ export class RevenueBreakdownItemDto {count: number}-export class RevenueBreakdownDto {- @ApiProperty({- description: 'Revenue by source/referrer',- type: [RevenueBreakdownItemDto],- })- bySource: RevenueBreakdownItemDto[]-- @ApiProperty({- description: 'Revenue by country',- type: [RevenueBreakdownItemDto],- })- byCountry: RevenueBreakdownItemDto[]-- @ApiProperty({- description: 'Revenue by product',- type: [RevenueBreakdownItemDto],- })- byProduct: RevenueBreakdownItemDto[]-}-export class RevenueStatusDto {@ApiProperty({ description: 'Whether Paddle is connected' })connected: booleandiff --git a/backend/apps/cloud/src/revenue/revenue.controller.ts b/backend/apps/cloud/src/revenue/revenue.controller.tsindex 82c27632c..fe9721c3c 100644--- a/backend/apps/cloud/src/revenue/revenue.controller.ts+++ b/backend/apps/cloud/src/revenue/revenue.controller.ts@@ -32,7 +32,6 @@ import {RevenueStatsDto,RevenueChartDto,RevenueTransactionDto,- RevenueBreakdownDto,RevenueStatusDto,} from './dto/revenue-stats.dto'import { STRIPE_REQUIRED_PERMISSIONS } from './interfaces/revenue.interface'@@ -47,13 +46,12 @@ export class RevenueController {private readonly paddleAdapter: PaddleAdapter,private readonly stripeAdapter: StripeAdapter,private readonly projectService: ProjectService,- private readonly analyticsService: AnalyticsService,private readonly logger: AppLoggerService,) {}@ApiBearerAuth()@Get('/:pid/revenue/status')- @Auth()+ @Auth(true, true)@ApiResponse({ status: 200, type: RevenueStatusDto })async getRevenueStatus(@CurrentUserId() userId: string,@@ -268,7 +266,7 @@ export class RevenueAnalyticsController {@ApiBearerAuth()@Get('/')- @Auth()+ @Auth(true, true)@ApiResponse({ status: 200 })async getRevenueStats(@CurrentUserId() userId: string,@@ -380,46 +378,4 @@ export class RevenueAnalyticsController {dto.status,)}-- @ApiBearerAuth()- @Get('/breakdown')- @Auth()- @ApiResponse({ status: 200, type: RevenueBreakdownDto })- async getRevenueBreakdown(- @CurrentUserId() userId: string,- @Query() dto: GetRevenueDto,- ): Promise<RevenueBreakdownDto> {- this.logger.log({ userId, ...dto }, 'GET /log/revenue/breakdown')-- const project = await this.projectService.getFullProject(dto.pid)-- if (_isEmpty(project)) {- throw new NotFoundException('Project not found')- }-- this.projectService.allowedToView(project, userId)-- if (!project.paddleApiKeyEnc && !project.stripeApiKeyEnc) {- throw new BadRequestException(- 'Revenue tracking is not configured for this project',- )- }-- const safeTimezone = this.analyticsService.getSafeTimezone(dto.timezone)- const timeBucket = getLowestPossibleTimeBucket(dto.period, dto.from, dto.to)-- const { groupFromUTC, groupToUTC } = this.analyticsService.getGroupFromTo(- dto.from,- dto.to,- timeBucket,- dto.period,- safeTimezone,- )-- return this.revenueService.getRevenueBreakdown(- dto.pid,- groupFromUTC,- groupToUTC,- )- }}diff --git a/backend/apps/cloud/src/revenue/revenue.service.ts b/backend/apps/cloud/src/revenue/revenue.service.tsindex 838649f02..cfb242ab9 100644--- a/backend/apps/cloud/src/revenue/revenue.service.ts+++ b/backend/apps/cloud/src/revenue/revenue.service.ts@@ -16,7 +16,6 @@ import {RevenueStatsDto,RevenueChartDto,RevenueTransactionDto,- RevenueBreakdownDto,} from './dto/revenue-stats.dto'import { deriveKey } from '../common/utils'@@ -518,140 +517,6 @@ export class RevenueService {}}- async getRevenueBreakdown(- projectId: string,- groupFromUTC: string,- groupToUTC: string,- ): Promise<RevenueBreakdownDto> {- const params = {- pid: projectId,- groupFrom: groupFromUTC,- groupTo: groupToUTC,- }-- // By product- const byProductQuery = `- SELECT- COALESCE(product_name, 'Unknown') as name,- sum(CASE WHEN type = 'sale' THEN amount ELSE 0 END) as revenue,- count(CASE WHEN type = 'sale' THEN 1 ELSE NULL END) as count- FROM (- SELECT- pid,- transaction_id,- argMax(product_name, synced_at) as product_name,- argMax(type, synced_at) as type,- argMax(amount, synced_at) as amount,- argMax(created, synced_at) as created_at- FROM revenue- WHERE pid = {pid:FixedString(12)}- AND revenue.created BETWEEN {groupFrom:String} AND {groupTo:String}- GROUP BY pid, transaction_id- ) AS latest- GROUP BY name- ORDER BY revenue DESC- LIMIT 10- `-- const { data: byProductData } = await clickhouse- .query({ query: byProductQuery, query_params: params })- .then(resultSet =>- resultSet.json<{ name: string; revenue: number; count: number }>(),- )-- // By source- const bySourceQuery = `- SELECT- COALESCE(a.so, 'Direct') as name,- sum(r.amount) as revenue,- count(r.amount) as count- FROM (- SELECT- session_id,- argMax(amount, synced_at) as amount- FROM revenue- WHERE pid = {pid:FixedString(12)}- AND created BETWEEN {groupFrom:String} AND {groupTo:String}- AND type = 'sale'- AND session_id IS NOT NULL- GROUP BY session_id, transaction_id- ) AS r- JOIN (- SELECT- psid,- argMin(so, created) as so- FROM analytics- WHERE pid = {pid:FixedString(12)}- AND psid IS NOT NULL- GROUP BY psid- ) AS a ON r.session_id = toString(a.psid)- GROUP BY name- ORDER BY revenue DESC- LIMIT 10- `-- const { data: bySourceData } = await clickhouse- .query({ query: bySourceQuery, query_params: params })- .then(resultSet =>- resultSet.json<{ name: string; revenue: number; count: number }>(),- )-- // By country- const byCountryQuery = `- SELECT- COALESCE(a.cc, 'Unknown') as name,- sum(r.amount) as revenue,- count(r.amount) as count- FROM (- SELECT- session_id,- argMax(amount, synced_at) as amount- FROM revenue- WHERE pid = {pid:FixedString(12)}- AND created BETWEEN {groupFrom:String} AND {groupTo:String}- AND type = 'sale'- AND session_id IS NOT NULL- GROUP BY session_id, transaction_id- ) AS r- JOIN (- SELECT- psid,- argMin(cc, created) as cc- FROM analytics- WHERE pid = {pid:FixedString(12)}- AND psid IS NOT NULL- GROUP BY psid- ) AS a ON r.session_id = toString(a.psid)- GROUP BY name- ORDER BY revenue DESC- LIMIT 10- `-- const { data: byCountryData } = await clickhouse- .query({ query: byCountryQuery, query_params: params })- .then(resultSet =>- resultSet.json<{ name: string; revenue: number; count: number }>(),- )-- return {- bySource: bySourceData.map(row => ({- name: row.name,- revenue: _round(row.revenue, 2),- count: row.count,- })),- byCountry: byCountryData.map(row => ({- name: row.name,- revenue: _round(row.revenue, 2),- count: row.count,- })),- byProduct: byProductData.map(row => ({- name: row.name,- revenue: _round(row.revenue, 2),- count: row.count,- })),- }- }-async insertTransaction(transaction: RevenueTransaction): Promise<void> {// Format date for ClickHouse DateTime (YYYY-MM-DD HH:mm:ss)const formatDateForCH = (date: Date): string => {diff --git a/backend/apps/community/src/feature-flag/feature-flag.controller.ts b/backend/apps/community/src/feature-flag/feature-flag.controller.tsindex 59629c739..a2ac4e062 100644--- a/backend/apps/community/src/feature-flag/feature-flag.controller.ts+++ b/backend/apps/community/src/feature-flag/feature-flag.controller.ts@@ -65,7 +65,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/project/:projectId')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: [FeatureFlagDto] })@ApiOperation({ summary: 'Get all feature flags for a project' })async getProjectFeatureFlags(@@ -111,7 +111,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/:flagId')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: FeatureFlagDto })@ApiOperation({ summary: 'Get a feature flag by ID' })async getFeatureFlag(@@ -415,7 +415,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/:id/stats')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: FeatureFlagStatsDto })@ApiOperation({ summary: 'Get statistics for a feature flag' })async getFeatureFlagStats(@@ -517,7 +517,7 @@ export class FeatureFlagController {@ApiBearerAuth()@Get('/:id/profiles')- @Auth()+ @Auth(false, true)@ApiResponse({ status: 200, type: FeatureFlagProfilesResponseDto })@ApiOperation({summary: 'Get profiles who have evaluated a feature flag',diff --git a/backend/apps/community/src/project/project.controller.ts b/backend/apps/community/src/project/project.controller.tsindex 0bc143244..c24d5e9ad 100644--- a/backend/apps/community/src/project/project.controller.ts+++ b/backend/apps/community/src/project/project.controller.ts@@ -821,7 +821,7 @@ export class ProjectController {@Get('/annotations/:pid')@ApiResponse({ status: 200 })- @Auth(true)+ @Auth(true, true)async getAnnotations(@Param('pid') pid: string,@CurrentUserId() userId: string,@@ -829,10 +829,6 @@ export class ProjectController {): Promise<any> {this.logger.log({ pid, userId }, 'GET /project/annotations')- if (!userId) {- throw new UnauthorizedException('Please auth first')- }-const project = await this.projectService.getFullProject(pid)if (_isEmpty(project)) {diff --git a/web/app/api/index.ts b/web/app/api/index.tsindex 10bc9f8a8..0321f2872 100644--- a/web/app/api/index.ts+++ b/web/app/api/index.ts@@ -2299,6 +2299,8 @@ export interface AIChatSummary {interface AIChat extends AIChatSummary {messages: AIChatMessage[]+ isOwner?: boolean+ branched?: boolean}export const getRecentAIChats = async (pid: string, limit: number = 5): Promise<AIChatSummary[]> => {diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsxindex 75bc2dde0..f285f941a 100644--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx@@ -487,6 +487,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {const abortControllerRef = useRef<AbortController | null>(null)const [currentChatId, setCurrentChatId] = useState<string | null>(null)+ const [isCurrentChatOwner, setIsCurrentChatOwner] = useState(true)const [recentChats, setRecentChats] = useState<AIChatSummary[]>([])const [allChats, setAllChats] = useState<AIChatSummary[]>([])const [allChatsTotal, setAllChatsTotal] = useState(0)@@ -549,6 +550,8 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {})),)setCurrentChatId(chatId)+ // Track if the current user owns this chat (defaults to true for new chats)+ setIsCurrentChatOwner(chat.isOwner !== false)} catch (err) {console.error('Failed to load chat:', err)const newParams = new URLSearchParams(searchParams)@@ -572,10 +575,20 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {try {if (currentChatId) {- await updateAIChat(projectId, currentChatId, { messages: apiMessages })+ const result = await updateAIChat(projectId, currentChatId, { messages: apiMessages })++ // If the chat was branched (user didn't own the original), update to the new chat ID+ if (result.branched) {+ setCurrentChatId(result.id)+ setIsCurrentChatOwner(true) // User now owns the branched chat+ const newParams = new URLSearchParams(searchParams)+ newParams.set('chat', result.id)+ setSearchParams(newParams, { replace: true })+ }} else {const chat = await createAIChat(projectId, apiMessages)setCurrentChatId(chat.id)+ setIsCurrentChatOwner(true)const newParams = new URLSearchParams(searchParams)newParams.set('chat', chat.id)setSearchParams(newParams, { replace: true })@@ -602,6 +615,7 @@ const AskAIView = ({ projectId }: AskAIViewProps) => {const handleNewChat = () => {setMessages([])setCurrentChatId(null)+ setIsCurrentChatOwner(true)setStreamingMessage(null)setError(null)const newParams = new URLSearchParams(searchParams)diff --git a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx b/web/app/pages/Project/tabs/Errors/ErrorsView.tsxindex b24b1d39d..f13a8eb64 100644--- a/web/app/pages/Project/tabs/Errors/ErrorsView.tsx+++ b/web/app/pages/Project/tabs/Errors/ErrorsView.tsx@@ -334,7 +334,7 @@ const ErrorItem = ({ error }: ErrorItemProps) => {<Tooltiptext={error.message}tooltipNode={- <Text as='p' size='sm' colour='muted' className='mt-1 flex leading-5'>+ <Text as='p' size='sm' colour='muted' className='mt-1 flex text-left leading-5'>{displayMessage}</Text>}