OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
ingest: key client-secret auth on the verification result, redact URLs in logs
Carl-Gerhard Lindesvärd1f4b8ba79627
diff --git a/apps/public/content/docs/mcp/index.mdx b/apps/public/content/docs/mcp/index.mdxindex fe9a720ce..7e79c8afd 100644--- a/apps/public/content/docs/mcp/index.mdx+++ b/apps/public/content/docs/mcp/index.mdx@@ -13,16 +13,20 @@ https://api.openpanel.dev/mcp## Authentication-The token can be passed as a query parameter or an `Authorization` header — both are equivalent:+Pass the token as an `Authorization` header:```-https://api.openpanel.dev/mcp?token=YOUR_TOKEN+Authorization: Bearer YOUR_TOKEN```+If your client can't set headers, pass it as a query parameter instead:+```-Authorization: Bearer YOUR_TOKEN+https://api.openpanel.dev/mcp?token=YOUR_TOKEN```+Both work. Prefer the header: query strings travel through browser history, shell history and proxy logs, so a token in the URL is easier to leak by accident.+### Token formatThe token is a **base64-encoded** string of your client ID and client secret joined by a colon:@@ -44,7 +48,13 @@ The easiest way to get your MCP token is directly from the dashboard — no termecho -n "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET" | base64```-Then append it to the MCP URL:+Then send it with every request:++```+Authorization: Bearer <base64-encoded-token>+```++Or, for clients that can't set headers, append it to the MCP URL:```https://api.openpanel.dev/mcp?token=<base64-encoded-token>@@ -72,22 +82,27 @@ Add the following to your `claude_desktop_config.json`:"mcpServers": {"openpanel": {"type": "streamable-http",- "url": "https://api.openpanel.dev/mcp?token=YOUR_TOKEN"+ "url": "https://api.openpanel.dev/mcp",+ "headers": {+ "Authorization": "Bearer YOUR_TOKEN"+ }}}}```+If your client doesn't read `headers`, drop that block and put the token in the URL instead: `"url": "https://api.openpanel.dev/mcp?token=YOUR_TOKEN"`.+## Connecting with Claude Code CLI-With the Claude CLI you can use the `--header` flag to pass the token via `Authorization: Bearer` rather than embedding it in the URL:+Use the `--header` flag to pass the token via `Authorization: Bearer`:```bashclaude mcp add --transport http openpanel https://api.openpanel.dev/mcp \--header "Authorization: Bearer YOUR_TOKEN"```-Or with the token in the URL (equivalent):+Or with the token in the URL:```bashclaude mcp add --transport http openpanel "https://api.openpanel.dev/mcp?token=YOUR_TOKEN"@@ -184,7 +199,7 @@ claude mcp add --transport http openpanel "https://api.openpanel.dev/mcp?token=Y### Google Search Console-These tools require GSC to be connected for the project in your dashboard settings.+These tools require GSC to be connected for the project from the project's settings in the dashboard (the "Google Search" tab). On a self-hosted instance the integration must first be [enabled by the operator](/docs/self-hosting/google-search-console).| Tool | Description ||------|-------------|diff --git a/apps/public/content/features/mcp.json b/apps/public/content/features/mcp.jsonindex bef4208d4..39b40d756 100644--- a/apps/public/content/features/mcp.json+++ b/apps/public/content/features/mcp.json@@ -77,7 +77,7 @@},{"title": "Add the URL to your AI client",- "description": "Paste `https://api.openpanel.dev/mcp?token=YOUR_TOKEN` into your AI client's MCP server config. In Claude Desktop that's one JSON block in `claude_desktop_config.json`. In Cursor and Windsurf it's under MCP settings."+ "description": "Paste `https://api.openpanel.dev/mcp` into your AI client's MCP server config and send the token as an `Authorization: Bearer YOUR_TOKEN` header. Clients that can't set headers take it in the URL instead, as `?token=YOUR_TOKEN`. In Claude Desktop that's one JSON block in `claude_desktop_config.json`. In Cursor and Windsurf it's under MCP settings."},{"title": "Start asking questions",@@ -134,7 +134,7 @@},{"question": "How does authentication work?",- "answer": "Your token is `base64(clientId:clientSecret)`. Generate it with `echo -n \"CLIENT_ID:CLIENT_SECRET\" | base64` and append it to the URL as `?token=YOUR_TOKEN`. You can also pass it as an `Authorization: Bearer` header if your client supports that."+ "answer": "Your token is `base64(clientId:clientSecret)`. Generate it with `echo -n \"CLIENT_ID:CLIENT_SECRET\" | base64` and send it as an `Authorization: Bearer YOUR_TOKEN` header. If your client can't set headers, append it to the URL as `?token=YOUR_TOKEN` instead—it works the same, but a token in a URL is easier to leak into history and logs."},{"question": "What's the difference between a read client and a root client?",diff --git a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.mcp.tsx b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.mcp.tsxindex e0789e9cd..6ff5f07e3 100644--- a/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.mcp.tsx+++ b/apps/start/src/routes/_app.$organizationId.$projectId.settings._tabs.mcp.tsx@@ -14,7 +14,7 @@ import { pushModal } from '@/modals';import { cn } from '@/utils/cn';export const Route = createFileRoute(- '/_app/$organizationId/$projectId/settings/_tabs/mcp',+ '/_app/$organizationId/$projectId/settings/_tabs/mcp')({component: Component,});@@ -32,7 +32,10 @@ type AiClient = {};const buildClients = (mcpEndpoint: string): AiClient[] => {- const url = `${mcpEndpoint}?token=${TOKEN_PLACEHOLDER}`;+ const url = mcpEndpoint;+ const headers = { Authorization: `Bearer ${TOKEN_PLACEHOLDER}` };+ // Fallback for clients that can't send headers.+ const urlWithToken = `${mcpEndpoint}?token=${TOKEN_PLACEHOLDER}`;return [{@@ -41,7 +44,8 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {description: (<>Add the following block to <code>claude_desktop_config.json</code>.- You can open it from <strong>Settings → Developer → Edit Config</strong>.+ You can open it from{' '}+ <strong>Settings → Developer → Edit Config</strong>.</>),configFile:@@ -54,11 +58,12 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {openpanel: {type: 'streamable-http',url,+ headers,},},},null,- 2,+ 2),},{@@ -66,20 +71,23 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {name: 'Claude Code (CLI)',description: (<>- Run this once in your terminal. The token can also be passed as a- header via <code>--header "Authorization: Bearer BASE64_TOKEN"</code>.+ Run this once in your terminal. If your setup can't pass headers, use{' '}+ <code>"{urlWithToken}"</code> as the URL instead and drop the{' '}+ <code>--header</code> flag.</>),language: 'bash',- snippet: () => `claude mcp add --transport http openpanel "${url}"`,+ snippet: () =>+ `claude mcp add --transport http openpanel ${url} \\\n --header "Authorization: Bearer ${TOKEN_PLACEHOLDER}"`,},{id: 'cursor',name: 'Cursor',description: (<>- Add the server to your global config at <code>~/.cursor/mcp.json</code>{' '}- or your project config at <code>.cursor/mcp.json</code>.+ Add the server to your global config at{' '}+ <code>~/.cursor/mcp.json</code> or your project config at{' '}+ <code>.cursor/mcp.json</code>.</>),configFile: '~/.cursor/mcp.json',@@ -91,11 +99,12 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {openpanel: {url,transport: 'streamable-http',+ headers,},},},null,- 2,+ 2),},{@@ -115,11 +124,12 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {mcpServers: {openpanel: {serverUrl: url,+ headers,},},},null,- 2,+ 2),},{@@ -140,11 +150,12 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {openpanel: {type: 'http',url,+ headers,},},},null,- 2,+ 2),},{@@ -153,7 +164,8 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {description: (<>Copy the JSON below, then run the <strong>Install Server</strong>{' '}- command in Raycast — it auto-fills the form from your clipboard.+ command in Raycast — it auto-fills the form from your clipboard. The+ install form takes a URL only, so the token goes in the query string.</>),language: 'json',@@ -162,10 +174,10 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {{name: 'openpanel',transport: 'streamable-http',- url,+ url: urlWithToken,},null,- 2,+ 2),},];@@ -174,7 +186,6 @@ const buildClients = (mcpEndpoint: string): AiClient[] => {function Component() {const { apiUrl } = useAppContext();const mcpEndpoint = `${apiUrl}/mcp`;- const fullUrl = `${mcpEndpoint}?token=${TOKEN_PLACEHOLDER}`;const clients = buildClients(mcpEndpoint);return (@@ -189,11 +200,12 @@ function Component() {</div><div className="col gap-2">- <CopyInput label="Endpoint" value={fullUrl} />+ <CopyInput label="Endpoint" value={mcpEndpoint} /><p className="text-muted-foreground text-xs">- Replace <code>{TOKEN_PLACEHOLDER}</code> with{' '}- <code>base64(clientId:clientSecret)</code>. You can also pass it as an{' '}- <code>Authorization: Bearer</code> header instead of a query param.+ Send your token as an <code>Authorization: Bearer</code> header, with{' '}+ <code>base64(clientId:clientSecret)</code> in place of{' '}+ <code>{TOKEN_PLACEHOLDER}</code>. Clients that can't set headers take+ it as a <code>?token=</code> query param instead.</p></div>@@ -201,9 +213,9 @@ function Component() {<div className="col gap-1"><div className="font-medium">Need a token?</div><p className="text-muted-foreground text-sm">- Only <code>read</code> and <code>root</code> clients can authenticate- with MCP. Create one and copy the MCP token from the success screen- — it's only shown once.+ Only <code>read</code> and <code>root</code> clients can+ authenticate with MCP. Create one and copy the MCP token from the+ success screen — it's only shown once.</p></div><div>@@ -217,11 +229,7 @@ function Component() {<div className="font-medium">Configure your AI client</div><Accordion className="rounded-lg border" collapsible type="single">{clients.map((client) => (- <AccordionItem- className="px-4"- key={client.id}- value={client.id}- >+ <AccordionItem className="px-4" key={client.id} value={client.id}><AccordionTrigger>{client.name}</AccordionTrigger><AccordionContent className="col gap-3"><p className="text-muted-foreground text-sm">diff --git a/packages/core/src/http/auth.test.ts b/packages/core/src/http/auth.test.tsindex 2f855c87a..ad7486012 100644--- a/packages/core/src/http/auth.test.ts+++ b/packages/core/src/http/auth.test.ts@@ -15,7 +15,7 @@ const CLIENT: AuthenticatedClient = {projectId: 'proj-1',organizationId: 'org-1',type: 'root',- secretPresented: true,+ secretVerified: true,};const REFUSAL: ClientAuthResult = {@@ -64,7 +64,7 @@ function buildApp() {'/manage/projects',({ client: principal }) => {const typed: AuthenticatedClient = principal;- return { id: typed.id, secretPresented: typed.secretPresented };+ return { id: typed.id, secretVerified: typed.secretVerified };},{ clientAuth: { allow: ['root'], label: 'Manage' } })@@ -87,7 +87,7 @@ test('clientAuth resolves the principal onto the handler', async () => {expect(response.status).toBe(200);expect(await response.json()).toEqual({id: 'client-1',- secretPresented: true,+ secretVerified: true,});expect(authenticateClient).toHaveBeenCalledTimes(1);});diff --git a/packages/core/src/http/client-auth.ts b/packages/core/src/http/client-auth.tsindex 52f1d7fd2..04951a2a6 100644--- a/packages/core/src/http/client-auth.ts+++ b/packages/core/src/http/client-auth.ts@@ -42,12 +42,13 @@ export interface AuthenticatedClient {organizationId: string;type: ClientType;/**- * Whether a client secret was PRESENTED, set before it is verified — V1 sets- * `req.clientSecretAuth` at parse time (utils/auth.ts:62-64) and `isBotHook`- * reads it afterwards as "this is a server-side SDK, never a bot". The- * side-channel survives as a field on the principal (ADR-011 A-i).+ * Whether the supplied client secret VERIFIED against the stored hash.+ * `isBotHook` reads it as "this is a server-side SDK, never a bot", so it+ * follows the verification result, not the presence of a secret string+ * (main #481). The side-channel survives as a field on the principal+ * (ADR-011 A-i).*/- secretPresented: boolean;+ secretVerified: boolean;}/**@@ -72,9 +73,9 @@ export type IngestTierOutcome =organizationId: string;type: ClientType;};- secretPresented: boolean;+ secretVerified: boolean;}- | { ok: false; message: string; secretPresented: boolean };+ | { ok: false; message: string; secretVerified: boolean };/** The ingest tier itself, passed in by the route that wants it. */export type ValidateIngestRequest = (args: {@@ -148,7 +149,7 @@ export async function authenticateClient(projectId: client.projectId,organizationId: client.organizationId,type: client.type,- secretPresented: outcome.secretPresented,+ secretVerified: outcome.secretVerified,},};}@@ -171,7 +172,7 @@ const UNEXPECTED_MESSAGE = 'Unexpected error';* / `validateManageRequest`, which differ only by the accepted `ClientType`* set and by the label their messages carry.*- * `secretPresented` is true on success by construction: this tier verifies the+ * `secretVerified` is true on success by construction: this tier verifies the* secret, so reaching the return means one was presented and matched.*/async function authenticateAllowedClient(@@ -215,7 +216,7 @@ async function authenticateAllowedClient(projectId: client.projectId,organizationId: client.organizationId,type: client.type as ClientType,- secretPresented: true,+ secretVerified: true,},};} catch (error) {diff --git a/packages/core/src/modules/ingest/ingest.routes.ts b/packages/core/src/modules/ingest/ingest.routes.tsindex 225e5580d..51bdc31f7 100644--- a/packages/core/src/modules/ingest/ingest.routes.ts+++ b/packages/core/src/modules/ingest/ingest.routes.ts@@ -10,7 +10,7 @@// `derive -> transform -> macro resolve -> beforeHandle`. So the duplicate// check is a `transform` (V1's `preValidation`), `clientAuth` is the macro,// and the bot check is a `beforeHandle`, which is what lets it read-// `client.secretPresented` the way V1's `isBotHook` reads the+// `client.secretVerified` the way V1's `isBotHook` reads the// `req.clientSecretAuth` side channel `validateSdkRequest` sets.//// Both routes carry the whole chain because V1's `fastify.addHook` calls are@@ -111,13 +111,13 @@ async function botGuard({status,}: {body: unknown;- client: { projectId: string | null; secretPresented: boolean };+ client: { projectId: string | null; secretVerified: boolean };ctx: HttpCtx;status: StatusFn;}) {const bot = await checkIngestBot(ctx, {headers: toIngestHeaders(ctx.headers),- clientSecretAuth: client.secretPresented,+ clientSecretAuth: client.secretVerified,projectId: client.projectId,body,});@@ -183,7 +183,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) => {projectId: client.projectId,clientIp: ctx.ip,headers: toIngestHeaders(ctx.headers),- clientSecretAuth: client.secretPresented,+ clientSecretAuth: client.secretVerified,timestamp,body,},@@ -255,7 +255,7 @@ export const ingestRoutes = defineRoutes((app, deps: AppDeps) => {projectId: client.projectId,clientIp: ctx.ip,headers: toIngestHeaders(ctx.headers),- clientSecretAuth: client.secretPresented,+ clientSecretAuth: client.secretVerified,timestamp,body: body as DeprecatedPostEventPayload | null,},diff --git a/packages/core/src/modules/ingest/src/client-auth.test.ts b/packages/core/src/modules/ingest/src/client-auth.test.tsindex b92ad65af..57df1767a 100644--- a/packages/core/src/modules/ingest/src/client-auth.test.ts+++ b/packages/core/src/modules/ingest/src/client-auth.test.ts@@ -4,8 +4,13 @@** The `mixan-*` case comes from apps/api/src/controllers/event.controller.test.ts:* ADR-015 entry 5 is pending the `/event` usage metric, so the legacy header- * fallback stays. The `secretPresented` assertion is what V1 asserted as- * `request.clientSecretAuth` — the side channel the bot check reads.+ * fallback stays. `secretVerified` is what V1 exposed as+ * `request.clientSecretAuth` — the side channel the bot check reads — and+ * since main #481 it is true only when the secret verified.+ *+ * The `secret verification` block guards main #481: `secretVerified` and+ * revenue ingestion follow whether the secret verified against the stored+ * hash, not whether a secret string was on the request.*/import {@@ -40,6 +45,24 @@ const client = {const getClientByIdCached = mock(async (_deps: unknown, _id: string) => client);+const verifyPassword = mock(async (_secret: string, _hash: string) => false);+const redisGet = mock(async (_key: string): Promise<string | null> => null);+const redisSetex = mock(+ async (_key: string, _ttl: number, _value: string) => 'OK'+);++const realShared = { ...(await import('@openpanel/shared/server')) };+mock.module('@openpanel/shared/server', () => ({+ ...realShared,+ verifyPassword,+}));++const realRedis = { ...(await import('@openpanel/redis')) };+mock.module('@openpanel/redis', () => ({+ ...realRedis,+ getRedisCache: () => ({ get: redisGet, setex: redisSetex }),+}));+// M15-005: client-auth.ts takes the caller's scope and reads// `client.service.ts`'s module-scope `cacheablePerDb` — mocked at that// specifier, spread-actual so the rest of the module (which `services.ts`'s@@ -52,6 +75,8 @@ mock.module('../../client/client.service', () => ({afterAll(() => {mock.module('../../client/client.service', () => realClientService);+ mock.module('@openpanel/shared/server', () => realShared);+ mock.module('@openpanel/redis', () => realRedis);});/** Only `db` is read on this path, and only as the cache's identity. */@@ -65,8 +90,31 @@ beforeAll(async () => {beforeEach(() => {getClientByIdCached.mockClear();+ verifyPassword.mockReset();+ verifyPassword.mockResolvedValue(false);+ redisGet.mockReset();+ redisGet.mockResolvedValue(null);+ redisSetex.mockReset();+ redisSetex.mockResolvedValue('OK');});+const ORIGIN = 'https://app.example.com';++/** A client that has to prove itself: no bypass, one allowed origin. */+const guardedClient = {+ ...client,+ secret: 'stored-hash' as string | null,+ ignoreCorsAndSecret: false,+ project: { ...client.project, cors: [ORIGIN] },+};++const guarded = (overrides: Partial<typeof guardedClient> = {}) => {+ getClientByIdCached.mockResolvedValueOnce({+ ...guardedClient,+ ...overrides,+ } as unknown as typeof client);+};+const body = { name: 'legacy_event', properties: { foo: 'bar' } };describe('validateIngestRequest', () => {@@ -83,7 +131,8 @@ describe('validateIngestRequest', () => {expect(getClientByIdCached).toHaveBeenCalledWith(deps, CLIENT_ID);expect(result.ok && result.client.id).toBe(CLIENT_ID);- expect(result.secretPresented).toBe(true);+ // The fixture stores no secret, so the presented one cannot verify.+ expect(result.secretVerified).toBe(false);});it('accepts the openpanel-* headers and reports no secret when none was sent', async () => {@@ -95,7 +144,7 @@ describe('validateIngestRequest', () => {});expect(result.ok && result.client.id).toBe(CLIENT_ID);- expect(result.secretPresented).toBe(false);+ expect(result.secretVerified).toBe(false);});it('falls back to the credentials carried in the body', async () => {@@ -107,7 +156,7 @@ describe('validateIngestRequest', () => {});expect(result.ok && result.client.id).toBe(CLIENT_ID);- expect(result.secretPresented).toBe(true);+ expect(result.secretVerified).toBe(false);});// A refusal is RETURNED, never thrown: the caller builds the error so its@@ -156,7 +205,7 @@ describe('validateIngestRequest', () => {expect(result.ok === false && result.payload.clientSecret).toBe('abcde...lmnop');- expect(result.secretPresented).toBe(true);+ expect(result.secretVerified).toBe(false);});it('refuses revenue tracking without a client secret', async () => {@@ -196,3 +245,186 @@ describe('validateIngestRequest', () => {});});});++describe('validateIngestRequest — secret verification (main #481)', () => {+ it('does not mark a request authenticated when the secret does not match', async () => {+ guarded();++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'guessed',+ origin: ORIGIN,+ },+ clientIp: '1.2.3.4',+ body,+ });++ expect(verifyPassword).toHaveBeenCalledWith('guessed', 'stored-hash');+ expect(result.ok && result.client.id).toBe(CLIENT_ID);+ expect(result.secretVerified).toBe(false);+ expect(redisSetex).not.toHaveBeenCalled();+ });++ it('rejects revenue from an origin-authorized request with a bad secret', async () => {+ guarded();++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'guessed',+ origin: ORIGIN,+ },+ clientIp: '1.2.3.4',+ body: { ...body, properties: { __revenue: 42 } },+ });++ expect(verifyPassword).toHaveBeenCalled();+ expect(result).toMatchObject({+ ok: false,+ message:+ 'Ingestion: Revenue tracking is not allowed without a client secret',+ secretVerified: false,+ });+ });++ it('rejects a bad secret outright when no origin is allowed', async () => {+ guarded();++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'guessed',+ },+ clientIp: '1.2.3.4',+ body,+ });++ expect(verifyPassword).toHaveBeenCalled();+ expect(result).toMatchObject({+ ok: false,+ message: 'Ingestion: Invalid cors or secret',+ secretVerified: false,+ });+ });++ it('lets ordinary browser traffic through on the origin alone', async () => {+ guarded();++ const result = await validateIngestRequest({+ deps,+ headers: { 'openpanel-client-id': CLIENT_ID, origin: ORIGIN },+ clientIp: '1.2.3.4',+ body,+ });++ expect(result.ok && result.client.id).toBe(CLIENT_ID);+ expect(result.secretVerified).toBe(false);+ expect(verifyPassword).not.toHaveBeenCalled();+ });++ it('authorizes a correct secret without an origin and accepts revenue', async () => {+ guarded();+ verifyPassword.mockResolvedValue(true);++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'correct',+ },+ clientIp: '1.2.3.4',+ body: { ...body, properties: { __revenue: 42 } },+ });++ expect(verifyPassword).toHaveBeenCalledWith('correct', 'stored-hash');+ expect(result.ok && result.client.id).toBe(CLIENT_ID);+ expect(result.secretVerified).toBe(true);+ expect(redisSetex).toHaveBeenCalledWith(+ expect.stringContaining(`client:auth:${CLIENT_ID}:`),+ 300,+ 'true'+ );+ });++ it('trusts a cached successful verification without re-hashing', async () => {+ guarded();+ redisGet.mockResolvedValue('true');++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'correct',+ },+ clientIp: '1.2.3.4',+ body,+ });++ expect(redisGet).toHaveBeenCalled();+ expect(result.ok).toBe(true);+ expect(result.secretVerified).toBe(true);+ expect(verifyPassword).not.toHaveBeenCalled();+ });++ it('does not trust a cached "false" left over from earlier releases', async () => {+ guarded();+ redisGet.mockResolvedValue('false');++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'guessed',+ origin: ORIGIN,+ },+ clientIp: '1.2.3.4',+ body,+ });++ expect(redisGet).toHaveBeenCalled();+ expect(verifyPassword).toHaveBeenCalled();+ expect(result.secretVerified).toBe(false);+ });++ it('skips the cache entirely when the client has no stored secret', async () => {+ guarded({ secret: null });++ const result = await validateIngestRequest({+ deps,+ headers: {+ 'openpanel-client-id': CLIENT_ID,+ 'openpanel-client-secret': 'anything',+ origin: ORIGIN,+ },+ clientIp: '1.2.3.4',+ body,+ });++ expect(getClientByIdCached).toHaveBeenCalled();+ expect(result.secretVerified).toBe(false);+ expect(redisGet).not.toHaveBeenCalled();+ expect(redisSetex).not.toHaveBeenCalled();+ expect(verifyPassword).not.toHaveBeenCalled();+ });++ it('accepts revenue with no secret when allowUnsafeRevenueTracking is on', async () => {+ guarded({+ project: { ...guardedClient.project, allowUnsafeRevenueTracking: true },+ });++ const result = await validateIngestRequest({+ deps,+ headers: { 'openpanel-client-id': CLIENT_ID, origin: ORIGIN },+ clientIp: '1.2.3.4',+ body: { ...body, properties: { __revenue: 42 } },+ });++ expect(getClientByIdCached).toHaveBeenCalled();+ expect(result.ok).toBe(true);+ expect(result.secretVerified).toBe(false);+ });+});diff --git a/packages/core/src/modules/ingest/src/client-auth.ts b/packages/core/src/modules/ingest/src/client-auth.tsindex bb9145e5d..7f289c52e 100644--- a/packages/core/src/modules/ingest/src/client-auth.ts+++ b/packages/core/src/modules/ingest/src/client-auth.ts@@ -13,7 +13,7 @@// cache whose key holds base64(<plaintext secret>) — a recorded finding// ADR-011 leaves to Carl, not to a port.-import { getCache } from '@openpanel/redis';+import { getRedisCache } from '@openpanel/redis';import { verifyPassword } from '@openpanel/shared/server';import { path } from 'ramda';import type { DbScope } from '../../../cacheable-per-deps';@@ -60,18 +60,19 @@ export type IngestAuthOutcome =ok: true;client: IServiceClientWithProject;/**- * Whether a client secret was PRESENTED, set before it is verified. V1- * sets `req.clientSecretAuth` at parse time and the bot hook reads it- * afterwards as "this is a server-side SDK, never a bot" — the side- * channel survives as a field on the outcome (ADR-011 A-i).+ * Whether the supplied client secret VERIFIED against the stored hash+ * (main #481). The bot hook reads it as "this is a server-side SDK,+ * never a bot", so it must not be true for any string a browser+ * happens to send — the side channel survives as a field on the+ * outcome (ADR-011 A-i).*/- secretPresented: boolean;+ secretVerified: boolean;}| {ok: false;message: string;payload: IngestAuthErrorPayload;- secretPresented: boolean;+ secretVerified: boolean;};const cleanDomain = (domain: string) =>@@ -102,6 +103,40 @@ function isOriginAllowed(cors: string[], origin: string | undefined): boolean {return cors.includes('*') && !!origin;}+/**+ * Only successful verifications are cached: the key embeds the caller-supplied+ * secret, so caching a negative would let anyone create entries with keys of+ * their choosing. The read compares against "true" because entries written by+ * earlier releases can hold "false".+ */+async function verifyClientSecret(+ clientId: string,+ clientSecret: string | undefined,+ storedSecret: string | null | undefined+): Promise<boolean> {+ if (!(storedSecret && clientSecret)) {+ return false;+ }++ const cacheKey = `client:auth:${clientId}:${Buffer.from(clientSecret).toString('base64')}`;++ if ((await getRedisCache().get(cacheKey)) === 'true') {+ return true;+ }++ const isVerified = await verifyPassword(clientSecret, storedSecret);++ if (isVerified) {+ getRedisCache()+ .setex(cacheKey, VERIFY_CACHE_SECONDS, 'true')+ .catch(() => {+ // a cache write failure only costs the next request a hash compare+ });+ }++ return isVerified;+}+export async function validateIngestRequest({deps,headers,@@ -125,9 +160,11 @@ export async function validateIngestRequest({const clientSecret =clientSecretNew || clientSecretOld || clientSecretFromBody;const origin = headerValue(headers, 'origin');- const secretPresented = !!clientSecret;- const refuse = (message: string): IngestAuthOutcome => ({+ const refuse = (+ message: string,+ secretVerified = false+ ): IngestAuthOutcome => ({ok: false,message,payload: {@@ -138,7 +175,7 @@ export async function validateIngestRequest({: 'none',origin,},- secretPresented,+ secretVerified,});if (!clientId) {@@ -159,12 +196,23 @@ export async function validateIngestRequest({return refuse('Ingestion: Client has no project');}+ // Everything downstream keys off whether the secret matched, not off its+ // mere presence.+ const secretVerified = await verifyClientSecret(+ clientId,+ clientSecret,+ client.secret+ );+// Filter out blocked IPsconst ipFilter = client.project.filters.filter((filter): filter is IProjectFilterIp => filter.type === 'ip');if (ipFilter.some((filter) => filter.ip === clientIp)) {- return refuse('Ingestion: IP address is blocked by project filter');+ return refuse(+ 'Ingestion: IP address is blocked by project filter',+ secretVerified+ );}// Filter out blocked profile ids@@ -176,44 +224,39 @@ export async function validateIngestRequest({path<string | undefined>(['profileId'], body); // Event handlerif (profileFilter.some((filter) => filter.profileId === profileId)) {- return refuse('Ingestion: Profile id is blocked by project filter');+ return refuse(+ 'Ingestion: Profile id is blocked by project filter',+ secretVerified+ );}const revenue =path(['payload', 'properties', '__revenue'], body) ??path(['properties', '__revenue'], body);- // Only allow revenue tracking if it was sent with a client secret+ // Only allow revenue tracking if it was sent with a verified client secret// or if the project has allowUnsafeRevenueTracking enabledif (- !(client.project.allowUnsafeRevenueTracking || clientSecret) &&+ !(client.project.allowUnsafeRevenueTracking || secretVerified) &&typeof revenue !== 'undefined') {return refuse(- 'Ingestion: Revenue tracking is not allowed without a client secret'+ 'Ingestion: Revenue tracking is not allowed without a client secret',+ secretVerified);}if (client.ignoreCorsAndSecret) {- return { ok: true, client, secretPresented };+ return { ok: true, client, secretVerified };}if (client.project.cors && isOriginAllowed(client.project.cors, origin)) {- return { ok: true, client, secretPresented };+ return { ok: true, client, secretVerified };}- const secret = client.secret;- if (secret && clientSecret) {- const isVerified = await getCache(- `client:auth:${clientId}:${Buffer.from(clientSecret).toString('base64')}`,- VERIFY_CACHE_SECONDS,- async () => await verifyPassword(clientSecret, secret),- true- );- if (isVerified) {- return { ok: true, client, secretPresented };- }+ if (secretVerified) {+ return { ok: true, client, secretVerified };}- return refuse('Ingestion: Invalid cors or secret');+ return refuse('Ingestion: Invalid cors or secret', secretVerified);}diff --git a/packages/core/src/modules/profile/profile.routes.test.ts b/packages/core/src/modules/profile/profile.routes.test.tsindex bfb67116d..0dad98665 100644--- a/packages/core/src/modules/profile/profile.routes.test.ts+++ b/packages/core/src/modules/profile/profile.routes.test.ts@@ -25,7 +25,7 @@ const CLIENT: AuthenticatedClient = {projectId: 'proj-1',organizationId: 'org-1',type: 'write',- secretPresented: true,+ secretVerified: true,};const GEO = { country: 'SE', city: 'Stockholm' };diff --git a/packages/core/src/pino-logger.test.ts b/packages/core/src/pino-logger.test.tsnew file mode 100644index 000000000..7910afd9c--- /dev/null+++ b/packages/core/src/pino-logger.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'bun:test';+import { redactSensitive } from './pino-logger';++describe('redactSensitive', () => {+ it('filters the query of a string url value', () => {+ expect(redactSensitive({ url: '/x?token=abc&foo=1' })).toEqual({+ url: '/x?token=[REDACTED]&foo=1',+ });+ });++ it('covers keys that merely contain url', () => {+ expect(redactSensitive({ requestUrl: '/x?apikey=abc' })).toEqual({+ requestUrl: '/x?apikey=[REDACTED]',+ });+ });++ it('leaves a non-string url value to the existing recursion', () => {+ expect(redactSensitive({ url: { path: '/x', token: 'abc' } })).toEqual({+ url: { path: '/x', token: '[REDACTED]' },+ });+ });++ it('still redacts sensitive keys by name', () => {+ expect(redactSensitive({ authorization: 'Bearer abc', page: 2 })).toEqual({+ authorization: '[REDACTED]',+ page: 2,+ });+ });+});diff --git a/packages/core/src/pino-logger.ts b/packages/core/src/pino-logger.tsindex 665938019..d7acdc934 100644--- a/packages/core/src/pino-logger.ts+++ b/packages/core/src/pino-logger.ts@@ -10,6 +10,11 @@import * as HyperDX from '@hyperdx/node-opentelemetry';import pino, { type Logger as PinoLogger } from 'pino';import type { CoreConfig } from './config';+import {+ isSensitiveKey,+ REDACTED,+ sanitizeUrlQuery,+} from './shared/sanitize-url';export type ILogger = PinoLogger;@@ -19,34 +24,9 @@ export type ILogger = PinoLogger;export const rawStdoutWrite = process.stdout.write.bind(process.stdout);export const rawStderrWrite = process.stderr.write.bind(process.stderr);-// Substring match (lowercased). Catches camelCase, snake_case, prefixed and-// suffixed variants in one entry — e.g. 'token' covers accessToken,-// refresh_token, jwtToken, etc.-const SENSITIVE_KEY_PATTERNS = [- 'password',- 'passwd',- 'pwd',- 'token',- 'secret',- 'authorization',- 'apikey',- 'accesskey',- 'privatekey',- 'cookie',- 'bearer',- 'credential',- 'salt',- 'signature',- 'ip',- 'email',- 'firstname',- 'lastname',- 'surname',-];-const MAX_REDACT_DEPTH = 5;-function redactSensitive(value: unknown, depth = 0): unknown {+export function redactSensitive(value: unknown, depth = 0): unknown {if (value instanceof Error) {return {...value,@@ -71,9 +51,12 @@ function redactSensitive(value: unknown, depth = 0): unknown {const result: Record<string, unknown> = {};for (const [key, val] of Object.entries(value as Record<string, unknown>)) {- const lowered = key.toLowerCase();- if (SENSITIVE_KEY_PATTERNS.some((k) => lowered.includes(k))) {- result[key] = '[REDACTED]';+ if (isSensitiveKey(key)) {+ result[key] = REDACTED;+ } else if (key.toLowerCase().includes('url') && typeof val === 'string') {+ // Backstop for anything that logs a raw URL: the credentials sit in the+ // query, not the key.+ result[key] = sanitizeUrlQuery(val);} else {result[key] = redactSensitive(val, depth + 1);}diff --git a/packages/core/src/shared/parser-user-agent.test.ts b/packages/core/src/shared/parser-user-agent.test.tsindex e4bf3c2ce..90d7f9e88 100644--- a/packages/core/src/shared/parser-user-agent.test.ts+++ b/packages/core/src/shared/parser-user-agent.test.ts@@ -133,6 +133,43 @@ describe('parseUserAgent', () => {model: 'Custom Model',});});++ it('applies overrides on a non-browser sdk user agent', () => {+ // A native SDK sends a plain name/version UA, which the server heuristic+ // matches, but it also states what the device is. The overrides win.+ const ua = 'my-sdk/1.0.0';+ const overrides = {+ __os: 'Android',+ __osVersion: '13',+ __device: 'mobile',+ __brand: 'Acme',+ __model: 'A105',+ };++ expect(parseUserAgent(ua, overrides)).toEqual({+ isServer: false,+ device: 'mobile',+ os: 'Android',+ osVersion: '13',+ browser: undefined,+ browserVersion: undefined,+ brand: 'Acme',+ model: 'A105',+ });+ });++ it('is still a server when a non-browser user agent sends no device overrides', () => {+ expect(parseUserAgent('my-sdk/1.0.0', { __ip: '1.2.3.4' })).toEqual({+ isServer: true,+ device: 'server',+ os: '',+ osVersion: '',+ browser: '',+ browserVersion: '',+ brand: '',+ model: '',+ });+ });});describe('getDevice', () => {diff --git a/packages/core/src/shared/sanitize-url.test.ts b/packages/core/src/shared/sanitize-url.test.tsnew file mode 100644index 000000000..55dbc4fed--- /dev/null+++ b/packages/core/src/shared/sanitize-url.test.ts@@ -0,0 +1,60 @@+import { describe, expect, it } from 'bun:test';+import { sanitizeUrlQuery } from './sanitize-url';++describe('sanitizeUrlQuery', () => {+ it('replaces a token value and keeps the path', () => {+ expect(sanitizeUrlQuery('/mcp?token=abc123')).toBe('/mcp?token=[REDACTED]');+ });++ it('keeps parameters that are not sensitive', () => {+ expect(sanitizeUrlQuery('/mcp?token=abc123&projectId=proj-1')).toBe(+ '/mcp?token=[REDACTED]&projectId=proj-1'+ );+ });++ it('matches parameter names case-insensitively', () => {+ expect(sanitizeUrlQuery('/mcp?TOKEN=abc&Token=def&accessToken=ghi')).toBe(+ '/mcp?TOKEN=[REDACTED]&Token=[REDACTED]&accessToken=[REDACTED]'+ );+ });++ it('replaces every occurrence of a repeated parameter', () => {+ expect(sanitizeUrlQuery('/mcp?token=abc&token=def')).toBe(+ '/mcp?token=[REDACTED]&token=[REDACTED]'+ );+ });++ it('replaces several sensitive parameters in one URL', () => {+ expect(+ sanitizeUrlQuery('/x?token=abc&client_secret=shh&apikey=k&page=2')+ ).toBe(+ '/x?token=[REDACTED]&client_secret=[REDACTED]&apikey=[REDACTED]&page=2'+ );+ });++ it('leaves a URL without a query string untouched', () => {+ expect(sanitizeUrlQuery('/mcp')).toBe('/mcp');+ });++ it('leaves an empty query string untouched', () => {+ expect(sanitizeUrlQuery('/mcp?')).toBe('/mcp?');+ });++ it('does not throw on a malformed query string', () => {+ expect(sanitizeUrlQuery('/x?%zz=1&&=&token')).toBe(+ '/x?%zz=1&&=&token=[REDACTED]'+ );+ });++ it('keeps the encoding of values it does not touch', () => {+ expect(sanitizeUrlQuery('/x?path=%2Fhome%3Fa%3Db&token=abc')).toBe(+ '/x?path=%2Fhome%3Fa%3Db&token=[REDACTED]'+ );+ });++ it('works on absolute URLs too', () => {+ expect(sanitizeUrlQuery('https://api.openpanel.dev/mcp?token=abc')).toBe(+ 'https://api.openpanel.dev/mcp?token=[REDACTED]'+ );+ });+});diff --git a/packages/core/src/shared/sanitize-url.ts b/packages/core/src/shared/sanitize-url.tsnew file mode 100644index 000000000..fd78323df--- /dev/null+++ b/packages/core/src/shared/sanitize-url.ts@@ -0,0 +1,73 @@+// Request URLs are logged as plain strings, so key-based redaction never+// looks inside them. Some routes take credentials in the query string (the+// MCP endpoint accepts `?token=`), which would otherwise land verbatim in+// log lines. The sensitive-key list lives here so the logger's redaction and+// the URL filter match the same names (main #484).++// Substring match (lowercased). Catches camelCase, snake_case, prefixed and+// suffixed variants in one entry — e.g. 'token' covers accessToken,+// refresh_token, jwtToken, etc.+export const SENSITIVE_KEY_PATTERNS = [+ 'password',+ 'passwd',+ 'pwd',+ 'token',+ 'secret',+ 'authorization',+ 'apikey',+ 'accesskey',+ 'privatekey',+ 'cookie',+ 'bearer',+ 'credential',+ 'salt',+ 'signature',+ 'ip',+ 'email',+ 'firstname',+ 'lastname',+ 'surname',+] as const;++export const REDACTED = '[REDACTED]';++const PLUS_AS_SPACE = /\+/g;++export function isSensitiveKey(key: string): boolean {+ const lowered = key.toLowerCase();+ return SENSITIVE_KEY_PATTERNS.some((pattern) => lowered.includes(pattern));+}++/**+ * Replaces the values of sensitive query parameters, keeping the path and+ * every other parameter intact. The query is rebuilt from the raw text rather+ * than through URLSearchParams so untouched values keep their encoding.+ */+export function sanitizeUrlQuery(url: string): string {+ const queryIndex = url.indexOf('?');+ if (queryIndex === -1) {+ return url;+ }++ const query = url.slice(queryIndex + 1);+ if (query === '') {+ return url;+ }++ const sanitized = query+ .split('&')+ .map((param) => {+ const equalsIndex = param.indexOf('=');+ const rawName = equalsIndex === -1 ? param : param.slice(0, equalsIndex);+ let name = rawName;+ try {+ name = decodeURIComponent(rawName.replace(PLUS_AS_SPACE, ' '));+ } catch {+ // Malformed percent-encoding — match on the raw name instead.+ }+ return isSensitiveKey(name) ? `${rawName}=${REDACTED}` : param;+ })+ .join('&');++ return `${url.slice(0, queryIndex)}?${sanitized}`;+}diff --git a/packages/shared/src/server/parser-user-agent.ts b/packages/shared/src/server/parser-user-agent.tsindex 7b2671f93..c2b4aee0f 100644--- a/packages/shared/src/server/parser-user-agent.ts+++ b/packages/shared/src/server/parser-user-agent.ts@@ -251,7 +251,10 @@ export function parseUserAgent(}const res = parse(ua);- if (isServer(res)) {+ // A native SDK sends a plain name/version UA, which the server heuristic+ // matches, but it also states what device it is running on. Trust that over+ // the heuristic, otherwise the overrides are silently dropped.+ if (isServer(res) && !hasDeviceOverrides(overrides)) {return parsedServerUa;}@@ -291,6 +294,22 @@ export function parseUserAgent(} as const;}+const DEVICE_OVERRIDE_KEYS = [+ '__os',+ '__device',+ '__brand',+ '__model',+] as const;++function hasDeviceOverrides(overrides?: Record<string, unknown>): boolean {+ if (!overrides) {+ return false;+ }+ return DEVICE_OVERRIDE_KEYS.some(+ (key) => typeof overrides[key] === 'string' && overrides[key] !== ''+ );+}+function isServer(res: UAParser.IResult) {// Matches user agents like "Go-http-client/1.0" or "Go Http Client/1.0"// It should just match the first name (with optional spaces) and version