Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

fix: handle no access/no permissions better

Carl-Gerhard Lindesvärd09afab85518e
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index c5081e910..ddd7adafc 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -370,7 +370,11 @@ export async function buildApp(
);
});
- const SKIP_LOG_ERRORS = ['UNAUTHORIZED', 'FST_ERR_CTP_INVALID_MEDIA_TYPE'];
+ const SKIP_LOG_ERRORS = [
+ 'UNAUTHORIZED',
+ 'FORBIDDEN',
+ 'FST_ERR_CTP_INVALID_MEDIA_TYPE',
+ ];
fastify.setErrorHandler((error, request, reply) => {
const { status, code, message, errorName } = normalizeError(error);
diff --git a/apps/start/src/router.tsx b/apps/start/src/router.tsx
index 780d292a6..86ac130ac 100644
--- a/apps/start/src/router.tsx
+++ b/apps/start/src/router.tsx
@@ -1,5 +1,7 @@
import { createRouter as createTanstackRouter } from '@tanstack/react-router';
import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query';
+import { FullPageEmptyState } from '@/components/full-page-empty-state';
+import { LinkButton } from '@/components/ui/button';
import * as TanstackQuery from './integrations/tanstack-query/root-provider';
import { routeTree } from './routeTree.gen';
import { getServerEnvs } from './server/get-envs';
@@ -21,6 +23,15 @@ export const getRouter = async () => {
},
},
defaultPreload: 'intent',
+ defaultNotFoundComponent: () => (
+ <FullPageEmptyState
+ title="Page not found"
+ description="The page you're looking for doesn't exist or has moved."
+ className="min-h-screen"
+ >
+ <LinkButton href="/">Go to home</LinkButton>
+ </FullPageEmptyState>
+ ),
Wrap: (props: { children: React.ReactNode }) => {
return (
<TanstackQuery.Provider {...rqContext} apiUrl={envs.apiUrl}>
diff --git a/apps/start/src/routes/__root.tsx b/apps/start/src/routes/__root.tsx
index 4f2b5ace3..716025f5b 100644
--- a/apps/start/src/routes/__root.tsx
+++ b/apps/start/src/routes/__root.tsx
@@ -10,9 +10,12 @@ import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';
import type { AppRouter } from '@openpanel/trpc';
import type { QueryClient } from '@tanstack/react-query';
+import { TRPCClientError } from '@trpc/client';
import type { TRPCOptionsProxy } from '@trpc/tanstack-react-query';
+import { LockIcon } from 'lucide-react';
import appCss from '../styles.css?url';
import type { ConfigResonse } from './api/config';
+import { FullPageEmptyState } from '@/components/full-page-empty-state';
import { FullPageErrorState } from '@/components/full-page-error-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
import { Providers } from '@/components/providers';
@@ -63,14 +66,30 @@ export const Route = createRootRouteWithContext<MyRouterContext>()({
],
}),
shellComponent: RootDocument,
- errorComponent: ({ error }) => (
- <FullPageErrorState
- description={error.message}
- title={'Something went wrong'}
- >
- <LinkButton href="/">Go back to home</LinkButton>
- </FullPageErrorState>
- ),
+ errorComponent: ({ error }) => {
+ // Authorization failures (403) surface as a friendly "no access" page
+ // instead of a scary error. 401s never reach here — handleUnauthorized
+ // hard-redirects them to /login.
+ if (error instanceof TRPCClientError && error.data?.httpStatus === 403) {
+ return (
+ <FullPageEmptyState
+ description={error.message}
+ icon={LockIcon}
+ title="No access"
+ >
+ <LinkButton href="/">Go back to home</LinkButton>
+ </FullPageEmptyState>
+ );
+ }
+ return (
+ <FullPageErrorState
+ description={error.message}
+ title={'Something went wrong'}
+ >
+ <LinkButton href="/">Go back to home</LinkButton>
+ </FullPageErrorState>
+ );
+ },
pendingComponent: FullPageLoadingState,
});
diff --git a/apps/start/src/routes/_app.$organizationId.tsx b/apps/start/src/routes/_app.$organizationId.tsx
index 18ae66946..4afd1c77c 100644
--- a/apps/start/src/routes/_app.$organizationId.tsx
+++ b/apps/start/src/routes/_app.$organizationId.tsx
@@ -1,3 +1,4 @@
+import { FullPageEmptyState } from '@/components/full-page-empty-state';
import FullPageLoadingState from '@/components/full-page-loading-state';
import FeedbackPrompt from '@/components/organization/feedback-prompt';
import SupporterPrompt from '@/components/organization/supporter-prompt';
@@ -12,6 +13,7 @@ import {
useLocation,
} from '@tanstack/react-router';
import { format } from 'date-fns';
+import { Building2Icon } from 'lucide-react';
const IGNORE_ORGANIZATION_IDS = ['.well-known', 'onboarding', 'assets'];
@@ -43,22 +45,39 @@ export const Route = createFileRoute('/_app/$organizationId')({
if (isStaticFile(params.organizationId)) {
throw notFound();
}
+ // Single source of truth for "can this user see this org?". myAccess is
+ // membership-exempt and returns null for non-members (and non-existent
+ // orgs), which we surface as a not-found page. Real errors (network/500)
+ // reject and fall through to the errorComponent. Runs before child routes,
+ // so it short-circuits settings/index/billing/members/project.
+ const access = await context.queryClient.fetchQuery(
+ context.trpc.organization.myAccess.queryOptions({
+ organizationId: params.organizationId,
+ }),
+ );
+ if (access === null) {
+ throw notFound();
+ }
},
loader: async ({ context, params }) => {
- await Promise.all([
- context.queryClient.prefetchQuery(
- context.trpc.organization.get.queryOptions({
- organizationId: params.organizationId,
- }),
- ),
- context.queryClient.prefetchQuery(
- context.trpc.organization.myAccess.queryOptions({
- organizationId: params.organizationId,
- }),
- ),
- ]);
+ // myAccess is already warmed in beforeLoad; only organization.get remains.
+ await context.queryClient.prefetchQuery(
+ context.trpc.organization.get.queryOptions({
+ organizationId: params.organizationId,
+ }),
+ );
},
pendingComponent: FullPageLoadingState,
+ notFoundComponent: () => (
+ <FullPageEmptyState
+ title="Workspace not found"
+ description="This workspace doesn't exist or you don't have access to it."
+ icon={Building2Icon}
+ className="min-h-[calc(100vh-4rem)]"
+ >
+ <LinkButton href="/">Go to home</LinkButton>
+ </FullPageEmptyState>
+ ),
});
function Alert({
diff --git a/packages/trpc/src/errors.ts b/packages/trpc/src/errors.ts
index e99527edb..785b12ca5 100644
--- a/packages/trpc/src/errors.ts
+++ b/packages/trpc/src/errors.ts
@@ -1,25 +1,31 @@
import { TRPCError } from '@trpc/server';
-export const TRPCAccessError = (message: string) =>
- new TRPCError({
- code: 'UNAUTHORIZED',
- message,
- });
+export class TRPCAccessError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'UNAUTHORIZED', message });
+ }
+}
-export const TRPCNotFoundError = (message: string) =>
- new TRPCError({
- code: 'NOT_FOUND',
- message,
- });
+export class TRPCNotFoundError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'NOT_FOUND', message });
+ }
+}
-export const TRPCInternalServerError = (message: string) =>
- new TRPCError({
- code: 'INTERNAL_SERVER_ERROR',
- message,
- });
+export class TRPCForbiddenError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'FORBIDDEN', message });
+ }
+}
-export const TRPCBadRequestError = (message: string) =>
- new TRPCError({
- code: 'BAD_REQUEST',
- message,
- });
+export class TRPCInternalServerError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'INTERNAL_SERVER_ERROR', message });
+ }
+}
+
+export class TRPCBadRequestError extends TRPCError {
+ constructor(message: string) {
+ super({ code: 'BAD_REQUEST', message });
+ }
+}
diff --git a/packages/trpc/src/routers/auth.ts b/packages/trpc/src/routers/auth.ts
index 8d83bdf4f..bfd983c4a 100644
--- a/packages/trpc/src/routers/auth.ts
+++ b/packages/trpc/src/routers/auth.ts
@@ -100,7 +100,7 @@ export const authRouter = createTRPCRouter({
);
if (!isRegistrationAllowed) {
- throw TRPCAccessError('Registrations are not allowed');
+ throw new TRPCAccessError('Registrations are not allowed');
}
const { provider } = input;
@@ -156,7 +156,7 @@ export const authRouter = createTRPCRouter({
);
if (!isRegistrationAllowed) {
- throw TRPCAccessError('Registrations are not allowed');
+ throw new TRPCAccessError('Registrations are not allowed');
}
const provider = 'email';
@@ -166,7 +166,7 @@ export const authRouter = createTRPCRouter({
});
if (user) {
- throw TRPCNotFoundError('User already exists');
+ throw new TRPCNotFoundError('User already exists');
}
const createdUser = await db.user.create({
@@ -215,7 +215,7 @@ export const authRouter = createTRPCRouter({
});
if (!user) {
- throw TRPCNotFoundError('User does not exists');
+ throw new TRPCNotFoundError('User does not exists');
}
if (provider === 'email') {
@@ -229,10 +229,10 @@ export const authRouter = createTRPCRouter({
);
if (!validPassword) {
- throw TRPCAccessError('Incorrect email or password');
+ throw new TRPCAccessError('Incorrect email or password');
}
} else {
- throw TRPCAccessError(
+ throw new TRPCAccessError(
'Reset your password, old password has expired'
);
}
@@ -278,7 +278,7 @@ export const authRouter = createTRPCRouter({
.mutation(async ({ input, ctx }) => {
const challengeId = ctx.cookies[TWO_FACTOR_COOKIE];
if (!challengeId) {
- throw TRPCAccessError('No active two-factor challenge');
+ throw new TRPCAccessError('No active two-factor challenge');
}
const challenge = await db.twoFactorChallenge.findUnique({
@@ -290,7 +290,7 @@ export const authRouter = createTRPCRouter({
await db.twoFactorChallenge.delete({ where: { id: challenge.id } });
}
ctx.setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
- throw TRPCAccessError('Two-factor challenge has expired');
+ throw new TRPCAccessError('Two-factor challenge has expired');
}
const totp = await db.userTotp.findUnique({
@@ -299,7 +299,7 @@ export const authRouter = createTRPCRouter({
if (!totp?.enabledAt) {
await db.twoFactorChallenge.delete({ where: { id: challenge.id } });
ctx.setCookie(TWO_FACTOR_COOKIE, '', { maxAge: 0 });
- throw TRPCAccessError('Two-factor is not enabled');
+ throw new TRPCAccessError('Two-factor is not enabled');
}
const secret = decrypt(totp.secret);
@@ -323,7 +323,7 @@ export const authRouter = createTRPCRouter({
}
if (!valid) {
- throw TRPCAccessError('Invalid code');
+ throw new TRPCAccessError('Invalid code');
}
await db.twoFactorChallenge.delete({ where: { id: challenge.id } });
@@ -360,13 +360,13 @@ export const authRouter = createTRPCRouter({
select: { id: true },
});
if (!emailAccount) {
- throw TRPCAccessError(
+ throw new TRPCAccessError(
'Two-factor authentication is only available for email/password sign-ins. Your account uses a social provider, which handles 2FA on its end.'
);
}
const existing = await db.userTotp.findUnique({ where: { userId } });
if (existing?.enabledAt) {
- throw TRPCAccessError(
+ throw new TRPCAccessError(
'Two-factor is already enabled. Disable it first to re-configure.'
);
}
@@ -407,15 +407,15 @@ export const authRouter = createTRPCRouter({
const userId = ctx.session.userId!;
const totp = await db.userTotp.findUnique({ where: { userId } });
if (!totp) {
- throw TRPCNotFoundError('Start two-factor setup first');
+ throw new TRPCNotFoundError('Start two-factor setup first');
}
if (totp.enabledAt) {
- throw TRPCAccessError('Two-factor is already enabled');
+ throw new TRPCAccessError('Two-factor is already enabled');
}
const secret = decrypt(totp.secret);
if (!verifyTotpCode(secret, input.code)) {
- throw TRPCAccessError('Invalid code');
+ throw new TRPCAccessError('Invalid code');
}
const recoveryCodes = generateRecoveryCodes();
@@ -439,7 +439,7 @@ export const authRouter = createTRPCRouter({
const userId = ctx.session.userId!;
const totp = await db.userTotp.findUnique({ where: { userId } });
if (!totp?.enabledAt) {
- throw TRPCAccessError('Two-factor is not enabled');
+ throw new TRPCAccessError('Two-factor is not enabled');
}
const secret = decrypt(totp.secret);
@@ -454,7 +454,7 @@ export const authRouter = createTRPCRouter({
).valid;
if (!valid) {
- throw TRPCAccessError('Invalid code');
+ throw new TRPCAccessError('Invalid code');
}
await db.userTotp.delete({ where: { userId } });
@@ -469,11 +469,11 @@ export const authRouter = createTRPCRouter({
const userId = ctx.session.userId!;
const totp = await db.userTotp.findUnique({ where: { userId } });
if (!totp?.enabledAt) {
- throw TRPCAccessError('Two-factor is not enabled');
+ throw new TRPCAccessError('Two-factor is not enabled');
}
const secret = decrypt(totp.secret);
if (!verifyTotpCode(secret, input.code)) {
- throw TRPCAccessError('Invalid code');
+ throw new TRPCAccessError('Invalid code');
}
const recoveryCodes = generateRecoveryCodes();
const hashed = await hashRecoveryCodes(recoveryCodes);
@@ -502,11 +502,11 @@ export const authRouter = createTRPCRouter({
});
if (!resetPassword) {
- throw TRPCNotFoundError('Reset password not found');
+ throw new TRPCNotFoundError('Reset password not found');
}
if (resetPassword.expiresAt < new Date()) {
- throw TRPCNotFoundError('Reset password expired');
+ throw new TRPCNotFoundError('Reset password expired');
}
await db.account.update({
@@ -623,21 +623,21 @@ export const authRouter = createTRPCRouter({
}
if (!share) {
- throw TRPCNotFoundError('Share not found');
+ throw new TRPCNotFoundError('Share not found');
}
if (!share.public) {
- throw TRPCNotFoundError('Share is not public');
+ throw new TRPCNotFoundError('Share is not public');
}
if (!share.password) {
- throw TRPCNotFoundError('Share is not password protected');
+ throw new TRPCNotFoundError('Share is not password protected');
}
const validPassword = await verifyPasswordHash(share.password, password);
if (!validPassword) {
- throw TRPCAccessError('Incorrect password');
+ throw new TRPCAccessError('Incorrect password');
}
ctx.setCookie(cookieName, '1', {
diff --git a/packages/trpc/src/routers/chart.ts b/packages/trpc/src/routers/chart.ts
index 2a7e3a417..70219b7c9 100644
--- a/packages/trpc/src/routers/chart.ts
+++ b/packages/trpc/src/routers/chart.ts
@@ -45,7 +45,7 @@ import { flatten, map, pipe, prop, range, sort, uniq } from 'ramda';
import sqlstring from 'sqlstring';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCAccessError, TRPCForbiddenError } from '../errors';
import {
cacheMiddleware,
createTRPCRouter,
@@ -88,13 +88,13 @@ const chartProcedure = publicProcedure.use(
}
);
if (!shareValidation.isValid) {
- throw TRPCAccessError('You do not have access to this share');
+ throw new TRPCForbiddenError('You do not have access to this share');
}
// Fetch report
const report = await getReportById(rawInput.id);
if (!report) {
- throw TRPCAccessError('Report not found');
+ throw new TRPCAccessError('Report not found');
}
return next({
@@ -106,14 +106,14 @@ const chartProcedure = publicProcedure.use(
// Regular member access check
if (!ctx.session?.userId) {
- throw TRPCAccessError('Authentication required');
+ throw new TRPCAccessError('Authentication required');
}
const access = await getProjectAccess({
projectId: rawInput.projectId,
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return next({
diff --git a/packages/trpc/src/routers/client.ts b/packages/trpc/src/routers/client.ts
index 7cb443d9f..5c09b47ef 100644
--- a/packages/trpc/src/routers/client.ts
+++ b/packages/trpc/src/routers/client.ts
@@ -6,7 +6,7 @@ import { db } from '@openpanel/db';
import { hashPassword } from '@openpanel/common/server';
import { getClientAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const clientRouter = createTRPCRouter({
@@ -37,7 +37,7 @@ export const clientRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this client');
+ throw new TRPCForbiddenError('You do not have access to this client');
}
return db.client.update({
@@ -88,7 +88,7 @@ export const clientRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this client');
+ throw new TRPCForbiddenError('You do not have access to this client');
}
await db.client.delete({
diff --git a/packages/trpc/src/routers/cohort.ts b/packages/trpc/src/routers/cohort.ts
index 48eecfa2f..f8bf73d0b 100644
--- a/packages/trpc/src/routers/cohort.ts
+++ b/packages/trpc/src/routers/cohort.ts
@@ -21,7 +21,7 @@ import {
} from '@openpanel/validation';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCNotFoundError } from '../errors';
+import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const cohortRouter = createTRPCRouter({
@@ -56,7 +56,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!cohort) {
- throw TRPCNotFoundError('Cohort not found');
+ throw new TRPCNotFoundError('Cohort not found');
}
const access = await getProjectAccess({
@@ -65,7 +65,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this cohort');
+ throw new TRPCForbiddenError('You do not have access to this cohort');
}
return cohort;
@@ -95,7 +95,7 @@ export const cohortRouter = createTRPCRouter({
const existingCohort = await db.cohort.findUnique({ where: { id } });
if (!existingCohort) {
- throw TRPCNotFoundError('Cohort not found');
+ throw new TRPCNotFoundError('Cohort not found');
}
const access = await getProjectAccess({
@@ -104,7 +104,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this cohort');
+ throw new TRPCForbiddenError('You do not have access to this cohort');
}
const cohort = await db.cohort.update({
@@ -136,7 +136,7 @@ export const cohortRouter = createTRPCRouter({
const cohort = await db.cohort.findUnique({ where: { id: input.id } });
if (!cohort) {
- throw TRPCNotFoundError('Cohort not found');
+ throw new TRPCNotFoundError('Cohort not found');
}
const access = await getProjectAccess({
@@ -145,7 +145,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this cohort');
+ throw new TRPCForbiddenError('You do not have access to this cohort');
}
await db.cohort.delete({ where: { id: input.id } });
@@ -202,7 +202,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!cohort) {
- throw TRPCNotFoundError('Cohort not found');
+ throw new TRPCNotFoundError('Cohort not found');
}
const access = await getProjectAccess({
@@ -211,7 +211,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this cohort');
+ throw new TRPCForbiddenError('You do not have access to this cohort');
}
const count = await getCohortCount(input.cohortId, cohort.projectId);
@@ -250,7 +250,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!cohort) {
- throw TRPCNotFoundError('Cohort not found');
+ throw new TRPCNotFoundError('Cohort not found');
}
const access = await getProjectAccess({
@@ -259,7 +259,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this cohort');
+ throw new TRPCForbiddenError('You do not have access to this cohort');
}
const result = await getCohortMembers(input.cohortId, cohort.projectId, {
@@ -282,7 +282,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!cohort) {
- throw TRPCNotFoundError('Cohort not found');
+ throw new TRPCNotFoundError('Cohort not found');
}
const access = await getProjectAccess({
@@ -291,7 +291,7 @@ export const cohortRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this cohort');
+ throw new TRPCForbiddenError('You do not have access to this cohort');
}
if (cohort.isStatic) {
diff --git a/packages/trpc/src/routers/conversation.ts b/packages/trpc/src/routers/conversation.ts
index 6a1c40d82..984d48942 100644
--- a/packages/trpc/src/routers/conversation.ts
+++ b/packages/trpc/src/routers/conversation.ts
@@ -10,7 +10,7 @@ import {
} from '@openpanel/db';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
/**
@@ -35,7 +35,7 @@ export const conversationRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return listConversations({
projectId: input.projectId,
@@ -87,7 +87,7 @@ export const conversationRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
}
// Derive organizationId from the project — we never trust a
diff --git a/packages/trpc/src/routers/dashboard.ts b/packages/trpc/src/routers/dashboard.ts
index 1decfe99c..259db5587 100644
--- a/packages/trpc/src/routers/dashboard.ts
+++ b/packages/trpc/src/routers/dashboard.ts
@@ -11,7 +11,7 @@ import {
import type { Prisma } from '@openpanel/db';
import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCNotFoundError } from '../errors';
+import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const dashboardRouter = createTRPCRouter({
@@ -38,13 +38,13 @@ export const dashboardRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const dashboard = await getDashboardById(input.id, input.projectId);
if (!dashboard) {
- throw TRPCNotFoundError('Dashboard not found');
+ throw new TRPCNotFoundError('Dashboard not found');
}
return dashboard;
@@ -63,13 +63,13 @@ export const dashboardRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const project = await getProjectById(input.projectId);
if (!project) {
- throw TRPCNotFoundError('Project not found');
+ throw new TRPCNotFoundError('Project not found');
}
return db.dashboard.create({
@@ -101,7 +101,7 @@ export const dashboardRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this dashboard');
+ throw new TRPCForbiddenError('You do not have access to this dashboard');
}
return db.dashboard.update({
@@ -133,7 +133,7 @@ export const dashboardRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this dashboard');
+ throw new TRPCForbiddenError('You do not have access to this dashboard');
}
try {
diff --git a/packages/trpc/src/routers/email.ts b/packages/trpc/src/routers/email.ts
index d912cb0a5..0c37d3e48 100644
--- a/packages/trpc/src/routers/email.ts
+++ b/packages/trpc/src/routers/email.ts
@@ -19,7 +19,7 @@ export const emailRouter = createTRPCRouter({
// Verify token
if (!verifyUnsubscribeToken(email, category, token)) {
- throw TRPCBadRequestError('Invalid unsubscribe link');
+ throw new TRPCBadRequestError('Invalid unsubscribe link');
}
// Upsert the unsubscribe record
diff --git a/packages/trpc/src/routers/event.ts b/packages/trpc/src/routers/event.ts
index 976798586..018b8aaf4 100644
--- a/packages/trpc/src/routers/event.ts
+++ b/packages/trpc/src/routers/event.ts
@@ -26,7 +26,7 @@ import {
import { clone } from 'ramda';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
export const eventRouter = createTRPCRouter({
@@ -287,7 +287,7 @@ export const eventRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
} else {
const share = await db.shareOverview.findFirst({
@@ -297,7 +297,7 @@ export const eventRouter = createTRPCRouter({
});
if (!share) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
}
diff --git a/packages/trpc/src/routers/gsc.ts b/packages/trpc/src/routers/gsc.ts
index 743340c43..6bc8df8f3 100644
--- a/packages/trpc/src/routers/gsc.ts
+++ b/packages/trpc/src/routers/gsc.ts
@@ -17,7 +17,7 @@ import { gscQueue } from '@openpanel/queue';
import { zRange, zTimeInterval } from '@openpanel/validation';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCNotFoundError } from '../errors';
+import { TRPCForbiddenError, TRPCNotFoundError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
const zGscDateInput = z.object({
@@ -56,7 +56,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.gscConnection.findUnique({
where: { projectId: input.projectId },
@@ -81,7 +81,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const state = Arctic.generateState();
@@ -108,7 +108,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return listGscSites(input.projectId);
}),
@@ -121,14 +121,14 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const conn = await db.gscConnection.findUnique({
where: { projectId: input.projectId },
});
if (!conn) {
- throw TRPCNotFoundError('GSC connection not found');
+ throw new TRPCNotFoundError('GSC connection not found');
}
await db.gscConnection.update({
@@ -155,7 +155,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
await db.gscConnection.deleteMany({
@@ -173,7 +173,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
const interval = ['day', 'week', 'month'].includes(input.interval)
@@ -194,7 +194,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
return getGscPages(input.projectId, startDate, endDate, input.limit);
@@ -208,7 +208,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
return getGscPageDetails(input.projectId, input.page, startDate, endDate);
@@ -222,7 +222,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
return getGscQueryDetails(
@@ -245,7 +245,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
return getGscQueries(input.projectId, startDate, endDate, input.limit);
@@ -259,7 +259,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
@@ -308,7 +308,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
@@ -376,7 +376,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
@@ -408,7 +408,7 @@ export const gscRouter = createTRPCRouter({
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const { startDate, endDate } = await resolveDates(input.projectId, input);
return getGscCannibalization(input.projectId, startDate, endDate);
diff --git a/packages/trpc/src/routers/import.ts b/packages/trpc/src/routers/import.ts
index a3e7e2538..24450a94b 100644
--- a/packages/trpc/src/routers/import.ts
+++ b/packages/trpc/src/routers/import.ts
@@ -6,7 +6,7 @@ import { zCreateImport } from '@openpanel/validation';
import { getProjectAccess } from '../access';
import {
- TRPCAccessError,
+ TRPCForbiddenError,
TRPCBadRequestError,
TRPCNotFoundError,
} from '../errors';
@@ -22,7 +22,7 @@ export const importRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.import.findMany({
@@ -53,7 +53,7 @@ export const importRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this import');
+ throw new TRPCForbiddenError('You do not have access to this import');
}
return importRecord;
@@ -68,7 +68,7 @@ export const importRouter = createTRPCRouter({
});
if (!access || (typeof access !== 'boolean' && access.level === 'read')) {
- throw TRPCAccessError(
+ throw new TRPCForbiddenError(
'You do not have permission to create imports for this project',
);
}
@@ -84,13 +84,13 @@ export const importRouter = createTRPCRouter({
});
if (!organization) {
- throw TRPCNotFoundError(
+ throw new TRPCNotFoundError(
'Could not start import, organization not found',
);
}
if (!organization.isActive) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
'You cannot start an import without an active subscription!',
);
}
@@ -139,7 +139,7 @@ export const importRouter = createTRPCRouter({
});
if (!access || (typeof access !== 'boolean' && access.level === 'read')) {
- throw TRPCAccessError(
+ throw new TRPCForbiddenError(
'You do not have permission to delete imports for this project',
);
}
@@ -173,7 +173,7 @@ export const importRouter = createTRPCRouter({
});
if (!access || (typeof access !== 'boolean' && access.level === 'read')) {
- throw TRPCAccessError(
+ throw new TRPCForbiddenError(
'You do not have permission to retry imports for this project',
);
}
diff --git a/packages/trpc/src/routers/insight.ts b/packages/trpc/src/routers/insight.ts
index 02343d267..428cb3049 100644
--- a/packages/trpc/src/routers/insight.ts
+++ b/packages/trpc/src/routers/insight.ts
@@ -1,7 +1,7 @@
import { db } from '@openpanel/db';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const insightRouter = createTRPCRouter({
@@ -19,7 +19,7 @@ export const insightRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
// Fetch more insights than needed to account for deduplication
@@ -80,7 +80,7 @@ export const insightRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const insights = await db.projectInsight.findMany({
diff --git a/packages/trpc/src/routers/integration.ts b/packages/trpc/src/routers/integration.ts
index 0c454c011..3efbd063b 100644
--- a/packages/trpc/src/routers/integration.ts
+++ b/packages/trpc/src/routers/integration.ts
@@ -10,7 +10,7 @@ import {
zCreateWebhookIntegration,
} from '@openpanel/validation';
import { getOrganizationAccess } from '../access';
-import { TRPCAccessError, TRPCBadRequestError } from '../errors';
+import { TRPCForbiddenError, TRPCBadRequestError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
import { validate as validateJavaScriptTemplate } from '@openpanel/js-runtime';
@@ -30,7 +30,7 @@ export const integrationRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return integration;
@@ -104,7 +104,7 @@ export const integrationRouter = createTRPCRouter({
input.config.javascriptTemplate,
);
if (!validation.valid) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
`Invalid JavaScript template: ${validation.error}`,
);
}
@@ -145,7 +145,7 @@ export const integrationRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.integration.delete({
diff --git a/packages/trpc/src/routers/notification.ts b/packages/trpc/src/routers/notification.ts
index 04fce5850..144d50043 100644
--- a/packages/trpc/src/routers/notification.ts
+++ b/packages/trpc/src/routers/notification.ts
@@ -11,7 +11,7 @@ import {
import { zCreateNotificationRule } from '@openpanel/validation';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const notificationRouter = createTRPCRouter({
@@ -140,7 +140,7 @@ export const notificationRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.notificationRule.delete({
diff --git a/packages/trpc/src/routers/organization.ts b/packages/trpc/src/routers/organization.ts
index 68a53ca98..e81a0333b 100644
--- a/packages/trpc/src/routers/organization.ts
+++ b/packages/trpc/src/routers/organization.ts
@@ -15,10 +15,11 @@ import { generateSecureId } from '@openpanel/common/server';
import { sendEmail } from '@openpanel/email';
import { addDays, addHours } from 'date-fns';
import { getOrganizationAccess } from '../access';
-import { TRPCAccessError, TRPCBadRequestError } from '../errors';
+import { TRPCForbiddenError, TRPCBadRequestError } from '../errors';
import {
createTRPCRouter,
protectedProcedure,
+ protectedProcedureWithoutAccess,
publicProcedure,
rateLimitMiddleware,
} from '../trpc';
@@ -34,7 +35,10 @@ export const organizationRouter = createTRPCRouter({
return getOrganizations(ctx.session.userId);
}),
- myAccess: protectedProcedure
+ // Membership-exempt on purpose: any logged-in user may ask whether they have
+ // access to a given org. Returns null when they're not a member (instead of
+ // throwing), which the org-layout guard uses to render a not-found page.
+ myAccess: protectedProcedureWithoutAccess
.input(z.object({ organizationId: z.string() }))
.query(async ({ input, ctx }) => {
const access = await getOrganizationAccess({
@@ -54,7 +58,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.organization.update({
@@ -77,7 +81,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this organization');
+ throw new TRPCForbiddenError('You do not have access to this organization');
}
const organization = await getOrganizationById(input.organizationId);
@@ -86,7 +90,7 @@ export const organizationRouter = createTRPCRouter({
// organization that still has a live paid subscription. Once the user has
// cancelled (the subscription is scheduled to end), deletion is allowed.
if (organization.hasSubscription && !organization.isWillBeCanceled) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
'Please cancel your subscription before deleting this organization.',
);
}
@@ -127,7 +131,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this organization');
+ throw new TRPCForbiddenError('You do not have access to this organization');
}
await db.$transaction([
@@ -161,7 +165,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const email = input.email.toLowerCase();
@@ -182,7 +186,7 @@ export const organizationRouter = createTRPCRouter({
});
if (alreadyMember && userExists) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
'User is already a member of the organization',
);
}
@@ -195,7 +199,7 @@ export const organizationRouter = createTRPCRouter({
});
if (alreadyInvited) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
'User is already invited to the organization',
);
}
@@ -263,7 +267,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.invite.delete({
@@ -299,7 +303,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
await db.$transaction([
@@ -329,7 +333,7 @@ export const organizationRouter = createTRPCRouter({
)
.mutation(async ({ input, ctx }) => {
if (input.userId === ctx.session.userId) {
- throw TRPCAccessError('You cannot update your own access');
+ throw new TRPCForbiddenError('You cannot update your own access');
}
const access = await getOrganizationAccess({
@@ -338,7 +342,7 @@ export const organizationRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.$transaction([
@@ -367,7 +371,7 @@ export const organizationRouter = createTRPCRouter({
organizationId: input.organizationId,
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return getMembers(input.organizationId);
}),
@@ -380,7 +384,7 @@ export const organizationRouter = createTRPCRouter({
organizationId: input.organizationId,
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return getInvites(input.organizationId);
}),
@@ -395,7 +399,7 @@ export const organizationRouter = createTRPCRouter({
.input(z.object({ inviteId: z.string().optional() }))
.query(async ({ input }) => {
if (!input.inviteId) {
- throw TRPCBadRequestError('Invite ID is required');
+ throw new TRPCBadRequestError('Invite ID is required');
}
return getInviteById(input.inviteId);
}),
diff --git a/packages/trpc/src/routers/overview.ts b/packages/trpc/src/routers/overview.ts
index 422ff366d..350c5fb84 100644
--- a/packages/trpc/src/routers/overview.ts
+++ b/packages/trpc/src/routers/overview.ts
@@ -1,5 +1,4 @@
import {
- TABLE_NAMES,
ch,
clix,
eventBuffer,
@@ -10,6 +9,7 @@ import {
getReferrerSpikes,
getSettingsForProject,
overviewService,
+ TABLE_NAMES,
validateOverviewShareAccess,
zGetMapDataInput,
zGetMetricsInput,
@@ -20,12 +20,16 @@ import {
zGetTopPagesInput,
zGetUserJourneyInput,
} from '@openpanel/db';
-import { pageContextSchema, type IChartRange, zRange } from '@openpanel/validation';
+import {
+ type IChartRange,
+ pageContextSchema,
+ zRange,
+} from '@openpanel/validation';
import { format } from 'date-fns';
import { z } from 'zod';
import { getProjectAccess } from '../access';
import { runFilterCommand } from '../agents/filter-command';
-import { TRPCAccessError } from '../errors';
+import { TRPCAccessError, TRPCForbiddenError } from '../errors';
import {
cacheMiddleware,
createTRPCRouter,
@@ -66,19 +70,19 @@ const overviewProcedure = publicProcedure.use(
});
} else {
if (!ctx.session?.userId) {
- throw TRPCAccessError('Authentication required');
+ throw new TRPCAccessError('Authentication required');
}
const access = await getProjectAccess({
projectId: rawInput.projectId,
userId: ctx.session.userId,
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
}
return next();
- },
+ }
);
function getCurrentAndPrevious<
@@ -93,14 +97,14 @@ function getCurrentAndPrevious<
const previous = getChartPrevStartEndDate(current);
return async <R>(
- fn: (input: T & { startDate: string; endDate: string }) => Promise<R>,
+ fn: (input: T & { startDate: string; endDate: string }) => Promise<R>
): Promise<{
current: R;
previous: R | null;
}> => {
const endDate = await getOrganizationSubscriptionChartEndDate(
input.projectId,
- current.endDate,
+ current.endDate
);
if (endDate) {
current.endDate = endDate;
@@ -172,7 +176,7 @@ export const overviewRouter = createTRPCRouter({
.fill(
clix.exp('toStartOfMinute(now() - INTERVAL 30 MINUTE)'),
clix.exp('toStartOfMinute(now())'),
- clix.exp('INTERVAL 1 MINUTE'),
+ clix.exp('INTERVAL 1 MINUTE')
);
// Get referrers per minute for the last 30 minutes
@@ -259,7 +263,7 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -267,7 +271,7 @@ export const overviewRouter = createTRPCRouter({
const { current, previous } = await getCurrentAndPrevious(
{ ...input, timezone },
true,
- timezone,
+ timezone
)(overviewService.getMetrics.bind(overviewService));
return {
metrics: {
@@ -305,7 +309,7 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -322,8 +326,7 @@ export const overviewRouter = createTRPCRouter({
// Reformat every spike date (and the cluster's anchor) to match
// overview.stats' series date format, so markers x-align with the
// chart's data points (xScale matches by Date identity).
- const fmt = (iso: string) =>
- format(new Date(iso), 'yyyy-MM-dd HH:mm:ss');
+ const fmt = (iso: string) => format(new Date(iso), 'yyyy-MM-dd HH:mm:ss');
return clusters.map((cluster) => ({
anchorDate: fmt(cluster.anchorDate),
spikes: cluster.spikes.map((spike) => ({
@@ -341,7 +344,7 @@ export const overviewRouter = createTRPCRouter({
range: zRange,
mode: z.enum(['page', 'entry', 'exit', 'bot']),
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -349,7 +352,7 @@ export const overviewRouter = createTRPCRouter({
const { current } = await getCurrentAndPrevious(
{ ...input },
false,
- timezone,
+ timezone
)(async (input) => {
if (input.mode === 'page') {
return overviewService.getTopPages({ ...input, timezone });
@@ -376,17 +379,15 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
- console.log('input', input);
-
const { timezone } = await getSettingsForProject(input.projectId);
const { current } = await getCurrentAndPrevious(
{ ...input, timezone },
false,
- timezone,
+ timezone
)(overviewService.getTopGeneric.bind(overviewService));
return current;
@@ -401,7 +402,7 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -409,7 +410,7 @@ export const overviewRouter = createTRPCRouter({
const { current } = await getCurrentAndPrevious(
{ ...input, timezone },
false,
- timezone,
+ timezone
)(overviewService.getTopGenericSeries.bind(overviewService));
return current;
@@ -423,7 +424,7 @@ export const overviewRouter = createTRPCRouter({
range: zRange,
steps: z.number().min(2).max(10).default(5).optional(),
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -431,7 +432,7 @@ export const overviewRouter = createTRPCRouter({
const { current } = await getCurrentAndPrevious(
{ ...input, timezone },
false,
- timezone,
+ timezone
)(async (input) => {
return overviewService.getUserJourney({
...input,
@@ -450,7 +451,7 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -458,7 +459,7 @@ export const overviewRouter = createTRPCRouter({
const { current } = await getCurrentAndPrevious(
{ ...input, timezone },
false,
- timezone,
+ timezone
)(overviewService.getTopEvents.bind(overviewService));
return current;
@@ -469,7 +470,7 @@ export const overviewRouter = createTRPCRouter({
z.object({
projectId: z.string(),
shareId: z.string().optional(),
- }),
+ })
)
.query(async ({ input }) => {
return getConversionEventNames(input.projectId);
@@ -482,7 +483,7 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -490,7 +491,7 @@ export const overviewRouter = createTRPCRouter({
const { current } = await getCurrentAndPrevious(
{ ...input, timezone },
false,
- timezone,
+ timezone
)(overviewService.getTopLinkOut.bind(overviewService));
return current;
@@ -506,7 +507,7 @@ export const overviewRouter = createTRPCRouter({
projectId: z.string(),
query: z.string().min(1).max(500),
pageContext: pageContextSchema.optional(),
- }),
+ })
)
.mutation(async ({ input }) => {
const { timezone } = await getSettingsForProject(input.projectId);
@@ -525,7 +526,7 @@ export const overviewRouter = createTRPCRouter({
endDate: z.string().nullish(),
range: zRange,
shareId: z.string().optional(),
- }),
+ })
)
.use(cacher)
.query(async ({ input }) => {
@@ -533,7 +534,7 @@ export const overviewRouter = createTRPCRouter({
const { current } = await getCurrentAndPrevious(
{ ...input, timezone },
false,
- timezone,
+ timezone
)(overviewService.getMapData.bind(overviewService));
return current;
diff --git a/packages/trpc/src/routers/project.ts b/packages/trpc/src/routers/project.ts
index a10c9a2fe..34819c733 100644
--- a/packages/trpc/src/routers/project.ts
+++ b/packages/trpc/src/routers/project.ts
@@ -15,7 +15,7 @@ import { zOnboardingProject, zProjectUpdate } from '@openpanel/validation';
import { addHours } from 'date-fns';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCBadRequestError } from '../errors';
+import { TRPCForbiddenError, TRPCBadRequestError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const projectRouter = createTRPCRouter({
@@ -32,7 +32,7 @@ export const projectRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return getProjectWithClients(projectId);
@@ -63,7 +63,7 @@ export const projectRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const res = await db.project.update({
@@ -105,7 +105,7 @@ export const projectRouter = createTRPCRouter({
.input(zOnboardingProject)
.mutation(async ({ input, ctx }) => {
if (!input.organizationId) {
- throw TRPCBadRequestError('Organization is required');
+ throw new TRPCBadRequestError('Organization is required');
}
const access = await getOrganizationAccess({
@@ -114,7 +114,7 @@ export const projectRouter = createTRPCRouter({
});
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('Only organization admins can create projects');
+ throw new TRPCForbiddenError('Only organization admins can create projects');
}
const secret = `sec_${crypto.randomBytes(10).toString('hex')}`;
@@ -170,7 +170,7 @@ export const projectRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
await db.project.update({
@@ -197,7 +197,7 @@ export const projectRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const project = await db.project.findUnique({
@@ -217,7 +217,7 @@ export const projectRouter = createTRPCRouter({
// deletion is part of it and can only be cancelled at the organization
// level. Cancelling it here would leave the organization unable to delete.
if (project?.organization?.deleteAt) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
'This organization is scheduled for deletion. Cancel the deletion from the organization settings.',
);
}
diff --git a/packages/trpc/src/routers/reference.ts b/packages/trpc/src/routers/reference.ts
index 16578bf8c..7a7d121a6 100644
--- a/packages/trpc/src/routers/reference.ts
+++ b/packages/trpc/src/routers/reference.ts
@@ -4,7 +4,7 @@ import { db, getChartStartEndDate, getSettingsForProject } from '@openpanel/db';
import { zCreateReference, zRange } from '@openpanel/validation';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
export const referenceRouter = createTRPCRouter({
@@ -22,7 +22,7 @@ export const referenceRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.reference.findMany({
@@ -68,7 +68,7 @@ export const referenceRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.reference.update({
@@ -95,7 +95,7 @@ export const referenceRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.reference.delete({
diff --git a/packages/trpc/src/routers/report.ts b/packages/trpc/src/routers/report.ts
index bd9f91f83..8db706b60 100644
--- a/packages/trpc/src/routers/report.ts
+++ b/packages/trpc/src/routers/report.ts
@@ -4,7 +4,7 @@ import { db, getReportById, getReportsByDashboardId } from '@openpanel/db';
import { zReport } from '@openpanel/validation';
import { getProjectAccess } from '../access';
-import { TRPCAccessError } from '../errors';
+import { TRPCForbiddenError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
export const reportRouter = createTRPCRouter({
@@ -38,7 +38,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.report.create({
@@ -83,7 +83,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.report.update({
@@ -128,7 +128,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.report.delete({
@@ -156,7 +156,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.report.create({
@@ -219,7 +219,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
// Upsert the layout (create if doesn't exist, update if it does)
@@ -264,7 +264,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
return db.reportLayout.findMany({
@@ -292,7 +292,7 @@ export const reportRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
// Delete all layout data for reports in this dashboard
diff --git a/packages/trpc/src/routers/share.ts b/packages/trpc/src/routers/share.ts
index 92dc9b1b3..58ee3f630 100644
--- a/packages/trpc/src/routers/share.ts
+++ b/packages/trpc/src/routers/share.ts
@@ -17,7 +17,11 @@ import {
import { hashPassword } from '@openpanel/auth';
import { z } from 'zod';
import { getProjectAccess } from '../access';
-import { TRPCAccessError, TRPCNotFoundError } from '../errors';
+import {
+ TRPCAccessError,
+ TRPCForbiddenError,
+ TRPCNotFoundError,
+} from '../errors';
import { createTRPCRouter, protectedProcedure, publicProcedure } from '../trpc';
const uid = new ShortUniqueId({ length: 6 });
@@ -62,7 +66,7 @@ export const shareRouter = createTRPCRouter({
if (!share) {
// Throw error if shareId is provided, otherwise return null
if ('shareId' in input) {
- throw TRPCNotFoundError('Share not found');
+ throw new TRPCNotFoundError('Share not found');
}
return null;
@@ -142,7 +146,7 @@ export const shareRouter = createTRPCRouter({
if (!share) {
if ('shareId' in input) {
- throw TRPCNotFoundError('Dashboard share not found');
+ throw new TRPCNotFoundError('Dashboard share not found');
}
return null;
}
@@ -162,7 +166,7 @@ export const shareRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const passwordHash = input.password
@@ -198,13 +202,13 @@ export const shareRouter = createTRPCRouter({
const share = await getShareDashboardById(input.shareId);
if (!share || !share.public) {
- throw TRPCNotFoundError('Dashboard share not found');
+ throw new TRPCNotFoundError('Dashboard share not found');
}
// Check password access
const hasAccess = !!ctx.cookies[`shared-dashboard-${share.id}`];
if (share.password && !hasAccess) {
- throw TRPCAccessError('Password required');
+ throw new TRPCAccessError('Password required');
}
return getReportsByDashboardId(share.dashboardId);
@@ -250,7 +254,7 @@ export const shareRouter = createTRPCRouter({
if (!share) {
if ('shareId' in input) {
- throw TRPCNotFoundError('Report share not found');
+ throw new TRPCNotFoundError('Report share not found');
}
return null;
}
@@ -271,7 +275,7 @@ export const shareRouter = createTRPCRouter({
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
const passwordHash = input.password
diff --git a/packages/trpc/src/routers/subscription.ts b/packages/trpc/src/routers/subscription.ts
index 22d88d713..6186013f7 100644
--- a/packages/trpc/src/routers/subscription.ts
+++ b/packages/trpc/src/routers/subscription.ts
@@ -18,13 +18,13 @@ import { zCheckout } from '@openpanel/validation';
import { getCache } from '@openpanel/redis';
import { subDays } from 'date-fns';
import { z } from 'zod';
-import { TRPCAccessError, TRPCBadRequestError } from '../errors';
+import { TRPCForbiddenError, TRPCBadRequestError } from '../errors';
import { createTRPCRouter, protectedProcedure } from '../trpc';
async function requireAdmin(userId: string, organizationId: string) {
const access = await getOrganizationAccess({ userId, organizationId });
if (access?.role !== 'org:admin') {
- throw TRPCAccessError('Only organization admins can manage billing');
+ throw new TRPCForbiddenError('Only organization admins can manage billing');
}
}
@@ -161,7 +161,7 @@ export const subscriptionRouter = createTRPCRouter({
await requireAdmin(ctx.session.userId, input.organizationId);
const organization = await getOrganizationById(input.organizationId);
if (!organization.subscriptionId) {
- throw TRPCBadRequestError('Organization has no subscription');
+ throw new TRPCBadRequestError('Organization has no subscription');
}
const res = await cancelSubscription(organization.subscriptionId);
@@ -175,7 +175,7 @@ export const subscriptionRouter = createTRPCRouter({
await requireAdmin(ctx.session.userId, input.organizationId);
const organization = await getOrganizationById(input.organizationId);
if (!organization.subscriptionCustomerId) {
- throw TRPCBadRequestError('Organization has no subscription');
+ throw new TRPCBadRequestError('Organization has no subscription');
}
const portal = await createPortal({
diff --git a/packages/trpc/src/routers/user.ts b/packages/trpc/src/routers/user.ts
index 93465f85b..cc15fb900 100644
--- a/packages/trpc/src/routers/user.ts
+++ b/packages/trpc/src/routers/user.ts
@@ -35,7 +35,7 @@ export const userRouter = createTRPCRouter({
);
if (blocking.length > 0) {
- throw TRPCBadRequestError(
+ throw new TRPCBadRequestError(
`Please cancel the subscription for ${blocking
.map((organization) => organization.name)
.join(', ')} before deleting your account.`,
diff --git a/packages/trpc/src/routers/widget.ts b/packages/trpc/src/routers/widget.ts
index acfbbfb3a..56ba74bb7 100644
--- a/packages/trpc/src/routers/widget.ts
+++ b/packages/trpc/src/routers/widget.ts
@@ -125,11 +125,11 @@ export const widgetRouter = createTRPCRouter({
});
if (!(widget && widget.public)) {
- throw TRPCNotFoundError('Widget not found');
+ throw new TRPCNotFoundError('Widget not found');
}
if (widget.options.type !== 'counter') {
- throw TRPCNotFoundError('Invalid widget type');
+ throw new TRPCNotFoundError('Invalid widget type');
}
return {
@@ -148,11 +148,11 @@ export const widgetRouter = createTRPCRouter({
});
if (!(widget && widget.public)) {
- throw TRPCNotFoundError('Widget not found');
+ throw new TRPCNotFoundError('Widget not found');
}
if (widget.options.type !== 'counter') {
- throw TRPCNotFoundError('Invalid widget type');
+ throw new TRPCNotFoundError('Invalid widget type');
}
const { projectId } = widget;
@@ -200,13 +200,13 @@ export const widgetRouter = createTRPCRouter({
});
if (!(widget && widget.public)) {
- throw TRPCNotFoundError('Widget not found');
+ throw new TRPCNotFoundError('Widget not found');
}
const { projectId, options } = widget;
if (options.type !== 'realtime') {
- throw TRPCNotFoundError('Invalid widget type');
+ throw new TRPCNotFoundError('Invalid widget type');
}
const { timezone } = await getSettingsForProject(projectId);
diff --git a/packages/trpc/src/trpc.ts b/packages/trpc/src/trpc.ts
index 5d34ad54d..b32340e6c 100644
--- a/packages/trpc/src/trpc.ts
+++ b/packages/trpc/src/trpc.ts
@@ -13,7 +13,7 @@ import {
defaultFingerPrint,
} from '@trpc-limiter/redis';
import { getOrganizationAccess, getProjectAccess } from './access';
-import { TRPCAccessError } from './errors';
+import { TRPCForbiddenError } from './errors';
export const rateLimitMiddleware = ({
max,
@@ -100,10 +100,7 @@ const enforceAccess = t.middleware(async ({ ctx, next, type, getRawInput }) => {
return runWithAlsSession(sessionId, async () => {
const rawInput = await getRawInput();
if (type === 'mutation' && process.env.DEMO_USER_ID) {
- throw new TRPCError({
- code: 'UNAUTHORIZED',
- message: 'You are not allowed to do this in demo mode',
- });
+ throw new TRPCForbiddenError('You are not allowed to do this in demo mode');
}
if (has('projectId', rawInput)) {
@@ -113,7 +110,7 @@ const enforceAccess = t.middleware(async ({ ctx, next, type, getRawInput }) => {
});
if (!access) {
- throw TRPCAccessError('You do not have access to this project');
+ throw new TRPCForbiddenError('You do not have access to this project');
}
}
@@ -124,7 +121,7 @@ const enforceAccess = t.middleware(async ({ ctx, next, type, getRawInput }) => {
});
if (!access) {
- throw TRPCAccessError('You do not have access to this organization');
+ throw new TRPCForbiddenError('You do not have access to this organization');
}
}
@@ -174,6 +171,13 @@ export const protectedProcedure = t.procedure
.use(enforceAccess)
.use(loggerMiddleware)
.use(sessionScopeMiddleware);
+// Authenticated but WITHOUT the org/project membership check. Use for endpoints
+// that must answer for any logged-in user (e.g. checking your own access to an
+// org you may not belong to) and return null instead of throwing.
+export const protectedProcedureWithoutAccess = t.procedure
+ .use(enforceUserIsAuthed)
+ .use(loggerMiddleware)
+ .use(sessionScopeMiddleware);
const middlewareMarker = 'middlewareMarker' as 'middlewareMarker' & {
__brand: 'middlewareMarker';