Skip to content

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

ui, mcp, export: the low-hanging batch

Carl-Gerhard Lindesvärdaa245fc48007
diff --git a/apps/start/src/components/overview/overview-top-geo.tsx b/apps/start/src/components/overview/overview-top-geo.tsx
index ae6723323..c18b0b74c 100644
--- a/apps/start/src/components/overview/overview-top-geo.tsx
+++ b/apps/start/src/components/overview/overview-top-geo.tsx
@@ -201,7 +201,7 @@ export default function OverviewTopGeo({
Geo data provided by{' '}
<a
className="hover:underline"
- href="https://ipdata.co"
+ href="https://www.maxmind.com"
rel="noopener noreferrer nofollow"
target="_blank"
>
diff --git a/apps/start/src/components/pages/table/columns.tsx b/apps/start/src/components/pages/table/columns.tsx
index 72dca1572..dfc8217b8 100644
--- a/apps/start/src/components/pages/table/columns.tsx
+++ b/apps/start/src/components/pages/table/columns.tsx
@@ -40,15 +40,22 @@ export function useColumns({
const page = row.original;
return (
<div className="flex min-w-0 items-center gap-3">
- <img
- alt=""
- className="size-4 shrink-0 rounded-sm"
- loading="lazy"
- onError={(e) => {
- (e.target as HTMLImageElement).style.display = 'none';
- }}
- src={`${apiUrl}/misc/favicon?url=${page.origin}`}
- />
+ {/* No origin means no favicon to fetch; the request used to go
+ out anyway as `?url=` and answer 404 on every render. The
+ value is also user data, so it is encoded. */}
+ {page.origin ? (
+ <img
+ alt=""
+ className="size-4 shrink-0 rounded-sm"
+ loading="lazy"
+ onError={(e) => {
+ (e.target as HTMLImageElement).style.display = 'none';
+ }}
+ src={`${apiUrl}/misc/favicon?url=${encodeURIComponent(page.origin)}`}
+ />
+ ) : (
+ <div className="size-4 shrink-0" />
+ )}
<div className="min-w-0">
{page.title && (
<div className="truncate font-medium text-sm leading-tight">
diff --git a/apps/start/src/components/profiles/popular-routes.tsx b/apps/start/src/components/profiles/popular-routes.tsx
index 1edff4765..e3418fa36 100644
--- a/apps/start/src/components/profiles/popular-routes.tsx
+++ b/apps/start/src/components/profiles/popular-routes.tsx
@@ -11,7 +11,7 @@ export const PopularRoutes = ({ data }: Props) => {
return (
<Widget className="w-full">
<WidgetHead>
- <WidgetTitle>Most visted pages</WidgetTitle>
+ <WidgetTitle>Most visited pages</WidgetTitle>
</WidgetHead>
{data.length === 0 ? (
<WidgetEmptyState icon={RouteIcon} text="No pages visited yet" />
diff --git a/apps/start/src/components/report-chart/common/empty.tsx b/apps/start/src/components/report-chart/common/empty.tsx
index 758097c0c..9983c5dc8 100644
--- a/apps/start/src/components/report-chart/common/empty.tsx
+++ b/apps/start/src/components/report-chart/common/empty.tsx
@@ -32,7 +32,7 @@ export function ReportChartEmpty({
Ready when you're
</div>
<div className="mt-2 text-muted-foreground">
- Pick atleast one event to start visualize
+ Pick at least one event to start visualising
</div>
</div>
);
diff --git a/apps/start/src/components/ui/combobox-advanced.tsx b/apps/start/src/components/ui/combobox-advanced.tsx
index 1ebe9ca21..238328a75 100644
--- a/apps/start/src/components/ui/combobox-advanced.tsx
+++ b/apps/start/src/components/ui/combobox-advanced.tsx
@@ -120,7 +120,12 @@ export function ComboboxAdvanced({
<Popover onOpenChange={setOpen} open={open}>
<PopoverTrigger asChild>{trigger}</PopoverTrigger>
<PopoverPortal>
- <PopoverContent align="start" className="w-full max-w-md p-0">
+ {/* `w-full` resolved against the PORTAL, not the trigger, so the
+ popover opened at an unrelated width and position. */}
+ <PopoverContent
+ align="start"
+ className="w-[--radix-popover-trigger-width] max-w-md p-0"
+ >
<Command shouldFilter={false}>
<CommandInput
onValueChange={setInputValue}
diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx
index 6db19d755..5e34d7e1a 100644
--- a/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx
+++ b/apps/start/src/routes/_app.$organizationId.$projectId.events._tabs.stats.tsx
@@ -65,7 +65,7 @@ function Component() {
</Widget>
<Widget className="w-full">
<WidgetHead>
- <span className="title">Event distribution</span>
+ <span className="title">Share of events</span>
</WidgetHead>
<WidgetBody>
<ReportChartShortcut
@@ -109,7 +109,7 @@ function Component() {
</Widget>
<Widget className="w-full">
<WidgetHead>
- <span className="title">Event distribution</span>
+ <span className="title">Events by name</span>
</WidgetHead>
<WidgetBody>
<ReportChartShortcut
@@ -153,7 +153,7 @@ function Component() {
</Widget>
<Widget className="w-full">
<WidgetHead>
- <span className="title">Event distribution</span>
+ <span className="title">Events over time</span>
</WidgetHead>
<WidgetBody>
<ReportChartShortcut
diff --git a/packages/core/src/http/errors.ts b/packages/core/src/http/errors.ts
index 2dbd691f4..e7f01740f 100644
--- a/packages/core/src/http/errors.ts
+++ b/packages/core/src/http/errors.ts
@@ -26,6 +26,9 @@ const SKIP_LOG_ERROR_CODES = [
'UNAUTHORIZED',
'FORBIDDEN',
'FST_ERR_CTP_INVALID_MEDIA_TYPE',
+ // Every request for a route that does not exist logged a warning with a
+ // stack trace. A 404 is the caller's business, not an incident.
+ 'NOT_FOUND',
];
const VALIDATION_STATUS = 400;
diff --git a/packages/core/src/modules/event/event.service.ts b/packages/core/src/modules/event/event.service.ts
index a21ec1856..44c79e6e4 100644
--- a/packages/core/src/modules/event/event.service.ts
+++ b/packages/core/src/modules/event/event.service.ts
@@ -35,6 +35,7 @@ import { clone, mergeDeepRight, uniq } from 'ramda';
import { cacheablePerDeps } from '../../cacheable-per-deps';
import { chQuery } from '../../ch-query';
import type { ServiceDeps, Services } from '../../services';
+import { stripFixedStringPadding } from '../../shared/ch-fixed-string';
import { getEventFiltersWhereClause } from '../chart/src/filter-where';
import { buildFilterWhere } from '../chart/src/table-filter-where';
import {
@@ -331,7 +332,7 @@ export function transformEvent(event: IClickhouseEvent): IServiceEvent {
sessionId: event.session_id,
properties: event.properties,
createdAt: convertClickhouseDateToJs(event.created_at),
- country: event.country,
+ country: stripFixedStringPadding(event.country),
city: event.city,
region: event.region,
longitude: event.longitude,
diff --git a/packages/core/src/modules/mcp/mcp.routes.ts b/packages/core/src/modules/mcp/mcp.routes.ts
index 6e3270690..b6cb044cb 100644
--- a/packages/core/src/modules/mcp/mcp.routes.ts
+++ b/packages/core/src/modules/mcp/mcp.routes.ts
@@ -19,16 +19,42 @@
import { defineRoutes } from '../../http/define';
+const METHOD_NOT_ALLOWED = 405;
+const JSONRPC_METHOD_NOT_FOUND = -32_601;
+
+/**
+ * A stateless MCP server speaks POST only. Without these the other methods
+ * fell through to the framework's 404, which tells a client the endpoint does
+ * not exist rather than that it used the wrong method. The MCP spec asks for
+ * 405 with an `Allow` header.
+ */
+const methodNotAllowedBody = {
+ jsonrpc: '2.0',
+ error: { code: JSONRPC_METHOD_NOT_FOUND, message: 'Method Not Allowed' },
+ id: null,
+};
+
export const mcpRoutes = defineRoutes((app) =>
- app.post('/mcp', async ({ body, ctx, query, request, set }) => {
- const token = ctx.services.mcp.extractToken(
- query as Record<string, string>,
- request.headers.get('authorization') ?? undefined
- );
+ app
+ .get('/mcp', ({ set }) => {
+ set.status = METHOD_NOT_ALLOWED;
+ set.headers.allow = 'POST';
+ return methodNotAllowedBody;
+ })
+ .delete('/mcp', ({ set }) => {
+ set.status = METHOD_NOT_ALLOWED;
+ set.headers.allow = 'POST';
+ return methodNotAllowedBody;
+ })
+ .post('/mcp', async ({ body, ctx, query, request, set }) => {
+ const token = ctx.services.mcp.extractToken(
+ query as Record<string, string>,
+ request.headers.get('authorization') ?? undefined
+ );
- const { status, body: responseBody } =
- await ctx.services.mcp.handleStatelessMcpRequest(token, body);
- set.status = status;
- return responseBody;
- })
+ const { status, body: responseBody } =
+ await ctx.services.mcp.handleStatelessMcpRequest(token, body);
+ set.status = status;
+ return responseBody;
+ })
);
diff --git a/packages/core/src/modules/mcp/src/auth.ts b/packages/core/src/modules/mcp/src/auth.ts
index 7d4bae851..37ca97e92 100644
--- a/packages/core/src/modules/mcp/src/auth.ts
+++ b/packages/core/src/modules/mcp/src/auth.ts
@@ -144,8 +144,12 @@ export function extractToken(
if (typeof query['token'] === 'string') {
return query['token'];
}
- if (authHeader?.startsWith('Bearer ')) {
- return authHeader.slice(7);
+ // RFC 7235: the auth scheme is case-insensitive, so `bearer` is as valid as
+ // `Bearer`. Refusing it was non-conformant, and accepting it can only let
+ // more clients through.
+ const [scheme, value] = (authHeader ?? '').split(' ');
+ if (scheme?.toLowerCase() === 'bearer' && value) {
+ return value;
}
return undefined;
}
diff --git a/packages/core/src/modules/mcp/src/tools/dashboard-links.ts b/packages/core/src/modules/mcp/src/tools/dashboard-links.ts
index 12fca986e..768e9a24b 100644
--- a/packages/core/src/modules/mcp/src/tools/dashboard-links.ts
+++ b/packages/core/src/modules/mcp/src/tools/dashboard-links.ts
@@ -71,7 +71,11 @@ export function registerDashboardLinkTools(
}) =>
withErrorHandling(deps, async () => {
const projectId = await resolveProjectId(deps, context, inputProjectId);
- const base = `${dashboardBaseUrl(deps.config)}/${context.organizationId}/${projectId}`;
+ // Every segment below is caller data — a project or profile id can
+ // contain `/`, `?` or `#` and would otherwise change what the URL
+ // points at.
+ const segment = encodeURIComponent;
+ const base = `${dashboardBaseUrl(deps.config)}/${segment(context.organizationId)}/${segment(projectId)}`;
const urls: Record<string, string> = {
overview: base,
@@ -86,16 +90,16 @@ export function registerDashboardLinkTools(
};
if (profileId) {
- urls.profile = `${base}/profiles/${profileId}`;
+ urls.profile = `${base}/profiles/${segment(profileId)}`;
}
if (sessionId) {
- urls.session = `${base}/sessions/${sessionId}`;
+ urls.session = `${base}/sessions/${segment(sessionId)}`;
}
if (dashboardId) {
- urls.dashboard = `${base}/dashboards/${dashboardId}`;
+ urls.dashboard = `${base}/dashboards/${segment(dashboardId)}`;
}
if (reportId) {
- urls.report = `${base}/reports/${reportId}`;
+ urls.report = `${base}/reports/${segment(reportId)}`;
}
return urls;
diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.ts
index 565e3e2de..d199d87c0 100644
--- a/packages/core/src/modules/organization/organization.service.ts
+++ b/packages/core/src/modules/organization/organization.service.ts
@@ -53,7 +53,7 @@ import {
getProjectAccess,
} from '../../shared/access-lookups';
import { formatClickhouseDate } from '../../shared/ch-dates';
-import { TABLE_NAMES } from '../../shared/ch-tables';
+import { replicatedTarget, TABLE_NAMES } from '../../shared/ch-tables';
import { DEFAULT_TIMEZONE, isValidTimezone } from './organization.constants';
export type IServiceOrganization = Awaited<
@@ -565,12 +565,7 @@ export async function deleteFromClickhouse(
];
for (const table of tables) {
- // `getReplicatedTableName` appends `ON CLUSTER '{cluster}'` in clustered
- // mode, which is a clause rather than an identifier — so the table name
- // goes through `sql.id` and the clause stays literal template text.
- const target = deps.config.clickhouseClustered
- ? sql`${sql.id(`${table}_replicated`)} ON CLUSTER '{cluster}'`
- : sql.id(table);
+ const target = replicatedTarget(deps.config.clickhouseClustered, table);
// If materialized view, use ALTER TABLE since DELETE is not supported
const statement = table.endsWith('_mv')
? sql`ALTER TABLE ${target} DELETE WHERE ${where};`
diff --git a/packages/core/src/shared/ch-fixed-string.ts b/packages/core/src/shared/ch-fixed-string.ts
new file mode 100644
index 000000000..b72756e4c
--- /dev/null
+++ b/packages/core/src/shared/ch-fixed-string.ts
@@ -0,0 +1,9 @@
+// ClickHouse `FixedString(N)` pads short values with NUL bytes, so a row with
+// no geo comes back as "\u0000\u0000" rather than an empty string. That text
+// reached /export/events, the dashboard, the MCP tools and the charts
+// (ISSUES.md, API nits).
+
+export function stripFixedStringPadding(value: string): string {
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the padding IS a control character
+ return value.replace(/\u0000+$/, '');
+}