OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix(api): restore the /manage references and dashboards endpoints
Carl-Gerhard Lindesvärd4d3c7dc0288d
diff --git a/packages/core/src/modules/dashboard/dashboard.routes.ts b/packages/core/src/modules/dashboard/dashboard.routes.tsnew file mode 100644index 000000000..35b8f3f6a--- /dev/null+++ b/packages/core/src/modules/dashboard/dashboard.routes.ts@@ -0,0 +1,61 @@+import { z } from 'zod';+import { defineRoutes } from '../../http/define';++const MANAGE_TAGS = ['Manage'];+const FORBIDDEN_PROJECT = {+ error: 'Forbidden',+ message: 'Project does not belong to your organization',+};++export const manageDashboardRoutes = defineRoutes((app) =>+ app+ .get(+ '/manage/projects/:id/dashboards',+ async ({ client, ctx, params, status }) => {+ const project = await ctx.services.project.getProjectForOrganization(+ params.id,+ client.organizationId+ );+ if (!project) {+ return status(403, FORBIDDEN_PROJECT);+ }+ return ctx.services.dashboard.listDashboardsCore({+ projectId: project.id,+ organizationId: client.organizationId,+ });+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ params: z.object({ id: z.string() }),+ detail: {+ tags: MANAGE_TAGS,+ description: 'List all dashboards for a project.',+ },+ }+ )+ .get(+ '/manage/projects/:id/dashboards/:dashboardId/reports',+ async ({ client, ctx, params, status }) => {+ const project = await ctx.services.project.getProjectForOrganization(+ params.id,+ client.organizationId+ );+ if (!project) {+ return status(403, FORBIDDEN_PROJECT);+ }+ return ctx.services.report.listReportsCore({+ projectId: project.id,+ dashboardId: params.dashboardId,+ organizationId: client.organizationId,+ });+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ params: z.object({ id: z.string(), dashboardId: z.string() }),+ detail: {+ tags: MANAGE_TAGS,+ description: 'List all reports in a dashboard.',+ },+ }+ )+);diff --git a/packages/core/src/modules/reference/reference.constants.ts b/packages/core/src/modules/reference/reference.constants.tsindex 5dbe1daf9..32c12a304 100644--- a/packages/core/src/modules/reference/reference.constants.ts+++ b/packages/core/src/modules/reference/reference.constants.ts@@ -6,3 +6,17 @@ export const zCreateReference = z.object({projectId: z.string(),datetime: z.string(),});++// The /manage REST contract, kept to what API consumers already send.+export const zManageCreateReference = z.object({+ projectId: z.string(),+ title: z.string().min(1),+ description: z.string().optional(),+ datetime: z.string(),+});++export const zManageUpdateReference = z.object({+ title: z.string().min(1).optional(),+ description: z.string().optional(),+ datetime: z.string().optional(),+});diff --git a/packages/core/src/modules/reference/reference.routes.ts b/packages/core/src/modules/reference/reference.routes.tsnew file mode 100644index 000000000..0b0b9abee--- /dev/null+++ b/packages/core/src/modules/reference/reference.routes.ts@@ -0,0 +1,132 @@+import { z } from 'zod';+import { defineRoutes } from '../../http/define';+import {+ zManageCreateReference,+ zManageUpdateReference,+} from './reference.constants';++const idParams = z.object({ id: z.string() });+const listQuery = z.object({ projectId: z.string().optional() });+const MANAGE_TAGS = ['Manage'];++export const referenceRoutes = defineRoutes((app) =>+ app+ .get(+ '/manage/references',+ async ({ client, ctx, query, status }) => {+ const references =+ await ctx.services.reference.listReferencesForOrganization(+ client.organizationId,+ query.projectId+ );+ if (references === null) {+ return status(404, {+ error: 'Not Found',+ message: 'Project not found',+ });+ }+ return { data: references };+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ query: listQuery,+ detail: {+ tags: MANAGE_TAGS,+ description: 'List annotation references for a project.',+ },+ }+ )+ .get(+ '/manage/references/:id',+ async ({ client, ctx, params, status }) => {+ const reference =+ await ctx.services.reference.getReferenceForOrganization(+ params.id,+ client.organizationId+ );+ if (!reference) {+ return status(404, {+ error: 'Not Found',+ message: 'Reference not found',+ });+ }+ return { data: reference };+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ params: idParams,+ detail: {+ tags: MANAGE_TAGS,+ description: 'Get a single annotation reference by ID.',+ },+ }+ )+ .post(+ '/manage/references',+ async ({ body, client, ctx, status }) => {+ const reference =+ await ctx.services.reference.createReferenceForOrganization(+ client.organizationId,+ body+ );+ if (!reference) {+ return status(404, {+ error: 'Not Found',+ message: 'Project not found',+ });+ }+ return { data: reference };+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ body: zManageCreateReference,+ detail: { tags: MANAGE_TAGS },+ }+ )+ .patch(+ '/manage/references/:id',+ async ({ body, client, ctx, params, status }) => {+ const reference =+ await ctx.services.reference.updateReferenceForOrganization(+ params.id,+ client.organizationId,+ body+ );+ if (!reference) {+ return status(404, {+ error: 'Not Found',+ message: 'Reference not found',+ });+ }+ return { data: reference };+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ params: idParams,+ body: zManageUpdateReference,+ detail: { tags: MANAGE_TAGS },+ }+ )+ .delete(+ '/manage/references/:id',+ async ({ client, ctx, params, status }) => {+ const deleted =+ await ctx.services.reference.deleteReferenceForOrganization(+ params.id,+ client.organizationId+ );+ if (!deleted) {+ return status(404, {+ error: 'Not Found',+ message: 'Reference not found',+ });+ }+ return { success: true };+ },+ {+ clientAuth: { allow: ['root'], label: 'Manage' },+ params: idParams,+ detail: { tags: MANAGE_TAGS },+ }+ )+);diff --git a/packages/core/src/modules/reference/reference.service.test.ts b/packages/core/src/modules/reference/reference.service.test.tsindex 1abe4796a..509d90408 100644--- a/packages/core/src/modules/reference/reference.service.test.ts+++ b/packages/core/src/modules/reference/reference.service.test.ts@@ -15,6 +15,39 @@ interface FakeReference {}const referenceStore = new Map<string, FakeReference>();+const projectOrganizations = new Map([+ ['proj_1', 'org_1'],+ ['proj_other', 'org_2'],+]);++interface FakeReferenceWhere {+ id?: string;+ projectId?: string;+ date?: { gte: Date; lte: Date };+ project?: { organizationId: string };+}++function matchesReference(row: FakeReference, where: FakeReferenceWhere) {+ const organizationId = projectOrganizations.get(row.projectId);+ return (+ (where.id === undefined || row.id === where.id) &&+ (where.projectId === undefined || row.projectId === where.projectId) &&+ (where.date === undefined ||+ (row.date >= where.date.gte && row.date <= where.date.lte)) &&+ (where.project === undefined ||+ organizationId === where.project.organizationId)+ );+}++const project = {+ findFirst: mock(+ async ({+ where: { id, organizationId },+ }: {+ where: { id: string; organizationId: string };+ }) => (projectOrganizations.get(id) === organizationId ? { id } : null)+ ),+};function makeReference(overrides: Partial<FakeReference> & { id: string }@@ -41,25 +74,24 @@ const reference = {return found;}),+ findFirst: mock(+ async ({ where }: { where: FakeReferenceWhere }) =>+ [...referenceStore.values()].find((r) => matchesReference(r, where)) ??+ null+ ),findMany: mock(async ({where,take,skip,}: {- where: { projectId?: string; date?: { gte: Date; lte: Date } };+ where: FakeReferenceWhere;take?: number;skip?: number;}) => {- let rows = [...referenceStore.values()];- if (where.projectId) {- rows = rows.filter((r) => r.projectId === where.projectId);- }- if (where.date) {- rows = rows.filter(- (r) => r.date >= where.date!.gte && r.date <= where.date!.lte- );- }+ let rows = [...referenceStore.values()].filter((r) =>+ matchesReference(r, where)+ );if (skip) {rows = rows.slice(skip);}@@ -86,7 +118,11 @@ const reference = {if (!existing) {throw new Error(`reference ${id} not found`);}- const next = { ...existing, ...data };+ // Prisma skips `undefined` fields rather than writing them.+ const defined = Object.fromEntries(+ Object.entries(data).filter(([, value]) => value !== undefined)+ );+ const next = { ...existing, ...defined };referenceStore.set(id, next);return next;}@@ -132,7 +168,7 @@ beforeAll(async () => {const { createReferenceService } = await import('./reference.service');subject = createReferenceService({- db: { reference },+ db: { reference, project },} as unknown as import('../../services').ServiceDeps,testServices());@@ -224,3 +260,65 @@ test('getChartReferences filters by the resolved date window', async () => {'proj_1');});++test('listReferencesForOrganization without a project spans only that organization', async () => {+ referenceStore.set('ref_1', makeReference({ id: 'ref_1' }));+ referenceStore.set(+ 'ref_2',+ makeReference({ id: 'ref_2', projectId: 'proj_other' })+ );+ const result = await subject.listReferencesForOrganization('org_1');+ expect(result?.map((r) => r.id)).toEqual(['ref_1']);+});++test('listReferencesForOrganization returns null for another organization’s project', async () => {+ expect(+ await subject.listReferencesForOrganization('org_1', 'proj_other')+ ).toBeNull();+});++test('createReferenceForOrganization refuses another organization’s project', async () => {+ const result = await subject.createReferenceForOrganization('org_1', {+ projectId: 'proj_other',+ title: 'Launch',+ datetime: '2026-09-03T00:00:00.000Z',+ });+ expect(result).toBeNull();+ expect(referenceStore.size).toBe(0);+});++test('another organization’s reference cannot be read, updated or deleted', async () => {+ referenceStore.set(+ 'ref_1',+ makeReference({ id: 'ref_1', projectId: 'proj_other' })+ );+ expect(+ await subject.getReferenceForOrganization('ref_1', 'org_1')+ ).toBeNull();+ expect(+ await subject.updateReferenceForOrganization('ref_1', 'org_1', {+ title: 'Renamed',+ })+ ).toBeNull();+ expect(await subject.deleteReferenceForOrganization('ref_1', 'org_1')).toBe(+ false+ );+ expect(referenceStore.get('ref_1')?.title).toBe('Launch');+});++test('updateReferenceForOrganization changes only the fields sent', async () => {+ referenceStore.set(+ 'ref_1',+ makeReference({ id: 'ref_1', description: 'kept' })+ );+ const result = await subject.updateReferenceForOrganization(+ 'ref_1',+ 'org_1',+ { title: 'Renamed' }+ );+ expect(result).toMatchObject({+ title: 'Renamed',+ description: 'kept',+ date: new Date('2026-09-01T00:00:00.000Z'),+ });+});diff --git a/packages/core/src/modules/reference/reference.service.ts b/packages/core/src/modules/reference/reference.service.tsindex 88535a906..13e59a228 100644--- a/packages/core/src/modules/reference/reference.service.ts+++ b/packages/core/src/modules/reference/reference.service.ts@@ -27,6 +27,19 @@ export interface UpdateReferenceInput {datetime: string;}+export interface CreateReferenceForOrganizationInput {+ projectId: string;+ title: string;+ description?: string;+ datetime: string;+}++export interface UpdateReferenceForOrganizationInput {+ title?: string;+ description?: string;+ datetime?: string;+}+export interface ChartReferencesInput {projectId: string;startDate?: string | null;@@ -96,6 +109,93 @@ export function deleteReference(return deps.db.reference.delete({ where: { id } });}+/** `null` when `projectId` is given but belongs to another organization. */+export async function listReferencesForOrganization(+ deps: ServiceDeps,+ organizationId: string,+ projectId?: string+): Promise<Reference[] | null> {+ if (projectId) {+ const project = await deps.db.project.findFirst({+ where: { id: projectId, organizationId },+ select: { id: true },+ });+ if (!project) {+ return null;+ }+ }+ return deps.db.reference.findMany({+ where: projectId ? { projectId } : { project: { organizationId } },+ orderBy: { createdAt: 'desc' },+ });+}++export function getReferenceForOrganization(+ deps: ServiceDeps,+ id: string,+ organizationId: string+): Promise<Reference | null> {+ return deps.db.reference.findFirst({+ where: { id, project: { organizationId } },+ });+}++/** `null` when the project belongs to another organization. */+export async function createReferenceForOrganization(+ deps: ServiceDeps,+ organizationId: string,+ input: CreateReferenceForOrganizationInput+): Promise<Reference | null> {+ const project = await deps.db.project.findFirst({+ where: { id: input.projectId, organizationId },+ select: { id: true },+ });+ if (!project) {+ return null;+ }+ return deps.db.reference.create({+ data: {+ projectId: input.projectId,+ title: input.title,+ description: input.description || null,+ date: new Date(input.datetime),+ },+ });+}++export async function updateReferenceForOrganization(+ deps: ServiceDeps,+ id: string,+ organizationId: string,+ input: UpdateReferenceForOrganizationInput+): Promise<Reference | null> {+ const existing = await getReferenceForOrganization(deps, id, organizationId);+ if (!existing) {+ return null;+ }+ return deps.db.reference.update({+ where: { id },+ data: {+ title: input.title,+ description: input.description,+ date: input.datetime === undefined ? undefined : new Date(input.datetime),+ },+ });+}++export async function deleteReferenceForOrganization(+ deps: ServiceDeps,+ id: string,+ organizationId: string+): Promise<boolean> {+ const existing = await getReferenceForOrganization(deps, id, organizationId);+ if (!existing) {+ return false;+ }+ await deps.db.reference.delete({ where: { id } });+ return true;+}+export async function getChartReferences(deps: ServiceDeps,input: ChartReferencesInput@@ -140,5 +240,31 @@ export function createReferenceService(deleteReference(deps, id),getChartReferences: (input: ChartReferencesInput): Promise<Reference[]> =>getChartReferences(deps, input),+ listReferencesForOrganization: (+ organizationId: string,+ projectId?: string+ ): Promise<Reference[] | null> =>+ listReferencesForOrganization(deps, organizationId, projectId),+ getReferenceForOrganization: (+ id: string,+ organizationId: string+ ): Promise<Reference | null> =>+ getReferenceForOrganization(deps, id, organizationId),+ createReferenceForOrganization: (+ organizationId: string,+ input: CreateReferenceForOrganizationInput+ ): Promise<Reference | null> =>+ createReferenceForOrganization(deps, organizationId, input),+ updateReferenceForOrganization: (+ id: string,+ organizationId: string,+ input: UpdateReferenceForOrganizationInput+ ): Promise<Reference | null> =>+ updateReferenceForOrganization(deps, id, organizationId, input),+ deleteReferenceForOrganization: (+ id: string,+ organizationId: string+ ): Promise<boolean> =>+ deleteReferenceForOrganization(deps, id, organizationId),};}diff --git a/packages/core/src/rest.routes.test.ts b/packages/core/src/rest.routes.test.tsindex 9a16d4e89..9ea2285ed 100644--- a/packages/core/src/rest.routes.test.ts+++ b/packages/core/src/rest.routes.test.ts@@ -37,6 +37,45 @@ test('publicApiRoutes and dashboardRoutes compose, dashboardRoutes carrying gsc'expect(response.status).toBe(200);});+// The documented /manage surface. A route missing here 404s before auth, which+// is how the references routes went missing in production.+const DOCUMENTED_MANAGE_ROUTES = [+ ['GET', '/manage/projects'],+ ['GET', '/manage/projects/p1'],+ ['POST', '/manage/projects'],+ ['PATCH', '/manage/projects/p1'],+ ['DELETE', '/manage/projects/p1'],+ ['GET', '/manage/clients'],+ ['GET', '/manage/clients/c1'],+ ['POST', '/manage/clients'],+ ['PATCH', '/manage/clients/c1'],+ ['DELETE', '/manage/clients/c1'],+ ['GET', '/manage/references'],+ ['GET', '/manage/references/r1'],+ ['POST', '/manage/references'],+ ['PATCH', '/manage/references/r1'],+ ['DELETE', '/manage/references/r1'],+ ['GET', '/manage/projects/p1/dashboards'],+ ['GET', '/manage/projects/p1/dashboards/d1/reports'],+] as const;+const NOT_FOUND_STATUS = 404;++test('every documented /manage route is mounted', async () => {+ const { deps } = stubAppDeps();+ const app = new Elysia().use(requestContext(deps)).use(publicApiRoutes(deps));++ for (const [method, path] of DOCUMENTED_MANAGE_ROUTES) {+ const response = await app.handle(+ new Request(`http://localhost${path}`, { method })+ );+ expect({ method, path, status: response.status }).not.toEqual({+ method,+ path,+ status: NOT_FOUND_STATUS,+ });+ }+});+// /metrics serves prometheus text exposition from THE core registry — not a// route-local one, not the prom-client global default.test('/metrics serves the one core registry, prometheus text exposition', async () => {diff --git a/packages/core/src/rest.routes.ts b/packages/core/src/rest.routes.tsindex cf00cf5ed..a706bb38b 100644--- a/packages/core/src/rest.routes.ts+++ b/packages/core/src/rest.routes.ts@@ -9,6 +9,7 @@ import { registry } from './metrics';import { assistantRoutes } from './modules/assistant/assistant.routes';import { authRoutes } from './modules/auth/auth.routes';import { clientRoutes } from './modules/client/client.routes';+import { manageDashboardRoutes } from './modules/dashboard/dashboard.routes';import { exportRoutes, insightsRoutes } from './modules/export/export.routes';import { gscRoutes } from './modules/gsc/gsc.routes';import { healthRoutes } from './modules/health/health.routes';@@ -20,6 +21,7 @@ import { miscRoutes } from './modules/misc/misc.routes';import { profileRoutes } from './modules/profile/profile.routes';import { projectRoutes } from './modules/project/project.routes';import { realtimeRoutes } from './modules/realtime/realtime.routes';+import { referenceRoutes } from './modules/reference/reference.routes';import { subscriptionRoutes } from './modules/subscription/subscription.routes';import { toolsRoutes } from './modules/tools/tools.routes';@@ -48,6 +50,8 @@ export const publicApiRoutes = (deps: AppDeps) =>.use(importRoutes(deps)).use(projectRoutes(deps)).use(clientRoutes(deps))+ .use(referenceRoutes(deps))+ .use(manageDashboardRoutes(deps)).use(profileRoutes(deps)).use(exportRoutes(deps)).use(insightsRoutes(deps))