OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
feat(dashboard): one-click dev login when DEV_LOGIN is set (#571)
Carl-Gerhard Lindesvärdec76a9609d22
diff --git a/.env.example b/.env.exampleindex bfd92108a..64a4ffb11 100644--- a/.env.example+++ b/.env.example@@ -28,6 +28,11 @@ NEXT_PUBLIC_API_URL="http://localhost:3333"WORKER_PORT=9999API_PORT=3333+# DEV LOGIN (local only). Puts a one-click "Dev login" button on the sign-in+# page that signs in as this account; the API refuses to boot with it under+# NODE_ENV=production. The seed creates exactly this user.+# DEV_LOGIN="[email protected]/openpanel"+# SOCIAL LOGIN (optional). Docs: https://openpanel.dev/docs/self-hosting/social-login# The redirect URIs must match what you register at the provider exactly.# GOOGLE_CLIENT_ID=""diff --git a/apps/api/src/config/env.test.ts b/apps/api/src/config/env.test.tsindex 0a030cf30..3e404bb34 100644--- a/apps/api/src/config/env.test.ts+++ b/apps/api/src/config/env.test.ts@@ -214,6 +214,29 @@ describe('derived values, computed once in the transform', () => {);});+ it('devLogin is DEV_LOGIN split at the first slash, so the password keeps its own', () => {+ expect(loadConfig(base).core.auth.devLogin).toBeUndefined();+ expect(+ loadConfig({ ...base, DEV_LOGIN: '[email protected]/openpanel' }).core+ .auth.devLogin+ ).toEqual({ email: '[email protected]', password: 'openpanel' });+ expect(+ loadConfig({ ...base, DEV_LOGIN: '[email protected]/a/b' }).core.auth+ .devLogin+ ).toEqual({ email: '[email protected]', password: 'a/b' });+ for (const malformed of ['[email protected]', '/pw', '[email protected]/']) {+ let message = '';+ try {+ loadConfig({ ...base, DEV_LOGIN: malformed });+ } catch (error) {+ message = (error as Error).message;+ }+ expect(message).toContain('DEV_LOGIN must be "email/password"');+ // The value is a credential; the boot error must not echo it.+ expect(message).not.toContain(malformed);+ }+ });+it('clickhouseClustered is CLICKHOUSE_CLUSTER alone, the rule the migrations use', () => {expect(loadConfig(base).core.clickhouseClustered).toBe(false);expect(@@ -384,6 +407,17 @@ describe('cross-field invariants, checked before the transform', () => {).not.toThrow();});+ it('refuses DEV_LOGIN under NODE_ENV=production', () => {+ const devLogin = { ...base, DEV_LOGIN: '[email protected]/openpanel' };+ expect(() => loadConfig({ ...devLogin, NODE_ENV: 'production' })).toThrow(+ /DEV_LOGIN is set while NODE_ENV=production/+ );+ expect(() =>+ loadConfig({ ...devLogin, NODE_ENV: 'development' })+ ).not.toThrow();+ expect(() => loadConfig(devLogin)).not.toThrow();+ });+it('refuses LOG_EXPORTER=otlp without a HyperDX key', () => {expect(() => loadConfig({ ...base, LOG_EXPORTER: 'otlp' })).toThrow(/LOG_EXPORTER=otlp requires HYPERDX_API_KEY/diff --git a/apps/api/src/config/env.ts b/apps/api/src/config/env.tsindex 8e8eb2e3c..13695d358 100644--- a/apps/api/src/config/env.ts+++ b/apps/api/src/config/env.ts@@ -3,7 +3,11 @@// contradiction fails at boot. A blank `KEY=` counts as unset. Every issue is reported at once:// boot-critical values (roles, queues, Kafka wiring) fail, tuning knobs fall back to the module's default.-import type { CoreConfig, KafkaSaslMechanism } from '@openpanel/core';+import type {+ CoreConfig,+ DevLoginConfig,+ KafkaSaslMechanism,+} from '@openpanel/core';import { KAFKA_SASL_MECHANISMS, queues } from '@openpanel/core';import { z } from 'zod';@@ -64,6 +68,8 @@ const DEFAULT_INGEST_DEAD_LETTER_MAX_ENTRIES = 1000;const DEFAULT_KAFKA_HANDLER_RETRY_INITIAL_MS = 100;const DEFAULT_KAFKA_HANDLER_RETRY_MAX_MS = 1000;const DEFAULT_KAFKA_SASL_MECHANISM: KafkaSaslMechanism = 'scram-sha-512';+/** `DEV_LOGIN=email/password`; the password may itself contain the separator. */+const DEV_LOGIN_SEPARATOR = '/';/** The Kafka events consumer's token. The old `events_kafka` spelling gets its own error (`RENAMED_QUEUE_TOKENS`), not an alias. */export const KAFKA_QUEUE_TOKEN = 'events';@@ -224,6 +230,43 @@ const positiveIntWithDefault = (fallback: number) =>z.coerce.number().int().positive().default(fallback));+/**+ * `email/password`, split at the first separator. A value with no separator+ * or an empty half fails boot: a dev login that cannot sign in is a typo.+ */+const devLoginSchema = z.preprocess(+ blankToUndefined,+ z+ .string()+ .optional()+ .superRefine((value, ctx) => {+ if (value === undefined || parseDevLogin(value) !== undefined) {+ return;+ }+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ // The value is a credential, so it stays out of the boot error.+ message: `DEV_LOGIN must be "email${DEV_LOGIN_SEPARATOR}password", with neither half empty`,+ });+ })+ .transform((value) =>+ value === undefined ? undefined : parseDevLogin(value)+ )+);++function parseDevLogin(value: string): DevLoginConfig | undefined {+ const separatorAt = value.indexOf(DEV_LOGIN_SEPARATOR);+ if (separatorAt === -1) {+ return undefined;+ }+ const email = value.slice(0, separatorAt).trim();+ const password = value.slice(separatorAt + DEV_LOGIN_SEPARATOR.length);+ if (email === '' || password === '') {+ return undefined;+ }+ return { email, password };+}+/** Comma-separated list; `undefined` when unset so the caller's order stands. */const optionalTokenList = z.preprocess(blankToUndefined,@@ -388,6 +431,8 @@ const rawSchema = z.object({ALLOW_REGISTRATION: optionalString,ALLOW_INVITATION: optionalString,+ /** A one-click sign-in on the login page; refused under NODE_ENV=production. */+ DEV_LOGIN: devLoginSchema,GITHUB_CLIENT_ID: stringWithDefault(''),GITHUB_CLIENT_SECRET: stringWithDefault(''),GITHUB_REDIRECT_URI: stringWithDefault(''),@@ -624,6 +669,18 @@ function checkKafkaSaslIsComplete(raw: RawEnv, ctx: z.RefinementCtx): void {}}+/** A password-free sign-in button has no place on a production deployment. */+function checkDevLoginIsNotProduction(raw: RawEnv, ctx: z.RefinementCtx): void {+ if (raw.DEV_LOGIN === undefined || raw.NODE_ENV !== PRODUCTION) {+ return;+ }+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message:+ 'DEV_LOGIN is set while NODE_ENV=production — it puts a one-click sign-in on the login page, so unset it here.',+ });+}+/** A CA or a verification switch on a plaintext connection does nothing. */function checkKafkaTlsOptionsHaveTls(raw: RawEnv, ctx: z.RefinementCtx): void {const hasTlsOptions =@@ -800,6 +857,7 @@ function deriveCoreConfig(raw: RawEnv): CoreConfig {},google: { ...googleClient, redirectUri: raw.GOOGLE_REDIRECT_URI },googleGsc: { ...googleClient, redirectUri: raw.GSC_GOOGLE_REDIRECT_URI },+ devLogin: raw.DEV_LOGIN,},cookies: {secret: raw.COOKIE_SECRET,@@ -941,6 +999,7 @@ const envSchema = rawSchemacheckKafkaHeartbeatFitsSession(raw, ctx);checkKafkaSaslIsComplete(raw, ctx);checkAdminAuthIsComplete(raw, ctx);+ checkDevLoginIsNotProduction(raw, ctx);checkKafkaTlsOptionsHaveTls(raw, ctx);checkReaperDeadmanOutlivesSession(raw, ctx);checkVacuumOutlivesReaper(raw, ctx);diff --git a/apps/start/e2e/auth-login.spec.ts b/apps/start/e2e/auth-login.spec.tsindex 2d683ee34..be8694061 100644--- a/apps/start/e2e/auth-login.spec.ts+++ b/apps/start/e2e/auth-login.spec.ts@@ -2,6 +2,7 @@// shared auth state and signs in by itself, so the shared session is never touched.import {+ apiUrl,FRESH_CONTEXT,gotoHydrated,hasHorizontalOverflow,@@ -19,6 +20,7 @@ test.describe.configure({ timeout: 120_000 });const MOBILE_VIEWPORT = { width: 390, height: 844 };const SIGN_IN_REQUEST = '/trpc/auth.signInEmail';+const DEV_SIGN_IN_REQUEST = '/trpc/auth.signInDev';test('signed-out visitors are sent to /login from every protected route', async ({page,@@ -217,3 +219,31 @@ test('a submit before hydration never puts the password in the URL', async ({await page.waitForLoadState('load');expect(page.url()).not.toContain('super-secret-password');});++test('the dev login button signs in with one click when DEV_LOGIN is set', async ({+ page,+ context,+ seed,+ request,+}) => {+ const providers = await request.get(`${apiUrl()}/trpc/auth.providers`);+ const configured = (await providers.json()).result.data.json.devLogin;+ test.skip(!configured, 'DEV_LOGIN is not set on this API');++ const issues = watchIssues(page);+ await gotoHydrated(page, '/login');+ await page.screenshot({ path: `${SHOTS_DIR}/login-dev-button.png` });++ const signedIn = page.waitForResponse((response) =>+ response.url().includes(DEV_SIGN_IN_REQUEST)+ );+ await page.getByRole('button', { name: 'Dev login' }).click();+ expect((await signedIn).status()).toBe(200);+ await expect(page).toHaveURL(new RegExp(`/${seed.organizationId}$`), {+ timeout: 20_000,+ });+ expect((await context.cookies()).map((cookie) => cookie.name)).toContain(+ 'session'+ );+ expect(issues.unexpected()).toEqual([]);+});diff --git a/apps/start/src/components/auth/sign-in-dev.tsx b/apps/start/src/components/auth/sign-in-dev.tsxnew file mode 100644index 000000000..f7b9fae9d--- /dev/null+++ b/apps/start/src/components/auth/sign-in-dev.tsx@@ -0,0 +1,36 @@+import { useMutation } from '@tanstack/react-query';+import { TerminalIcon } from 'lucide-react';+import { toast } from 'sonner';+import { Button } from '../ui/button';+import { useTRPC } from '@/integrations/trpc/react';++/** Only rendered when the API reports `DEV_LOGIN`, which production refuses. */+export function SignInDev({ inviteId }: { inviteId?: string }) {+ const trpc = useTRPC();+ const mutation = useMutation(+ trpc.auth.signInDev.mutationOptions({+ onSuccess(data) {+ if (data.type === 'totp_required') {+ window.location.href = '/verify';+ return;+ }+ window.location.href = '/';+ },+ onError(error) {+ toast.error(error.message);+ },+ })+ );+ return (+ <Button+ className="w-full"+ loading={mutation.isPending}+ onClick={() => mutation.mutate({ inviteId })}+ size="lg"+ variant="outline"+ >+ <TerminalIcon className="mr-2 size-4" />+ Dev login+ </Button>+ );+}diff --git a/apps/start/src/routes/_login.login.tsx b/apps/start/src/routes/_login.login.tsxindex c3d65dfba..065fb01b1 100644--- a/apps/start/src/routes/_login.login.tsx+++ b/apps/start/src/routes/_login.login.tsx@@ -3,6 +3,7 @@ import { createFileRoute } from '@tanstack/react-router';import { AlertCircle } from 'lucide-react';import { z } from 'zod';import { Or } from '@/components/auth/or';+import { SignInDev } from '@/components/auth/sign-in-dev';import { SignInEmailForm } from '@/components/auth/sign-in-email-form';import { SignInGithub } from '@/components/auth/sign-in-github';import { SignInGoogle } from '@/components/auth/sign-in-google';@@ -109,6 +110,12 @@ function LoginPage() {inviteId={inviteId}isLastUsed={lastProvider === 'email'}/>+ {providers.devLogin && (+ <>+ <Or />+ <SignInDev inviteId={inviteId} />+ </>+ )}</div>);}diff --git a/hub.config.ts b/hub.config.tsindex 7477828d8..bbb093d1f 100644--- a/hub.config.ts+++ b/hub.config.ts@@ -1,22 +1,42 @@import { readFileSync } from 'node:fs';import { join } from 'node:path';+/** The parts of `.seed.json` this file reads; the seed writes the rest for agents and tests. */+interface SeedManifest {+ user?: { email?: unknown; password?: unknown };+ mcp?: { token?: unknown };+}++/** What the seed wrote to `.seed.json`; undefined until the worktree has been seeded. */+function readSeed(dir: string): SeedManifest | undefined {+ try {+ return JSON.parse(readFileSync(join(dir, '.seed.json'), 'utf8'));+ } catch {+ return undefined;+ }+}++/** The seed's login as `DEV_LOGIN` wants it, `email/password`, so the one-click button appears once the worktree is seeded. */+function seededDevLogin(w: { dir: string }): string | undefined {+ const user = readSeed(w.dir)?.user;+ if (typeof user?.email !== 'string' || typeof user?.password !== 'string') {+ return undefined;+ }+ return `${user.email}/${user.password}`;+}+/** The product's MCP on this worktree's API, authenticated with the seed's root client. */function seededMcp(w: {dir: string;url(process: string): string;}): Record<string, { url: string }> {- try {- const seed = JSON.parse(readFileSync(join(w.dir, '.seed.json'), 'utf8'));- if (typeof seed?.mcp?.token !== 'string') {- return {};- }- return {- openpanel: { url: `${w.url('api')}/mcp?token=${seed.mcp.token}` },- };- } catch {+ const token = readSeed(w.dir)?.mcp?.token;+ if (typeof token !== 'string') {return {};}+ return {+ openpanel: { url: `${w.url('api')}/mcp?token=${token}` },+ };}// The one file the hub reads from this repo. Its shape is `hub.config.d.ts` in the hub repo,@@ -75,6 +95,9 @@ export default {KAFKA_EVENTS_TOPIC: `events-${w.name}`,KAFKA_EVENTS_DLQ_TOPIC: `events-${w.name}-dlq`,KAFKA_CONSUMER_GROUP: `api-${w.name}`,+ // The seed's login, read at each process start; a process started before the seed picks it+ // up on its next restart. The loader refuses DEV_LOGIN under NODE_ENV=production.+ DEV_LOGIN: seededDevLogin(w),}),// A worktree name is a DNS label; a database name is an identifier, so hyphens become underscores.diff --git a/packages/core/src/config.ts b/packages/core/src/config.tsindex 78a8dd4ce..1967a91ba 100644--- a/packages/core/src/config.ts+++ b/packages/core/src/config.ts@@ -36,6 +36,16 @@ export interface AuthConfig {google: OAuthClientConfig;/** The same Google client, redirected at the Search Console callback. */googleGsc: OAuthClientConfig;+ /**+ * DEV_LOGIN: a one-click sign-in for a local box, as `email/password`. The+ * loader refuses it under NODE_ENV=production, so it is never set there.+ */+ devLogin: DevLoginConfig | undefined;+}++export interface DevLoginConfig {+ email: string;+ password: string;}export interface CookieConfig {diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsindex 85d796fe3..02afd7b39 100644--- a/packages/core/src/index.ts+++ b/packages/core/src/index.ts@@ -46,7 +46,11 @@ export {isRetryableStatus,ProviderError,} from './clients/provider-error';-export { KAFKA_SASL_MECHANISMS, type KafkaSaslMechanism } from './config';+export {+ type DevLoginConfig,+ KAFKA_SASL_MECHANISMS,+ type KafkaSaslMechanism,+} from './config';export type {AppDeps,CoreConfig,diff --git a/packages/core/src/modules/auth/auth.constants.ts b/packages/core/src/modules/auth/auth.constants.tsindex 8538f4a4d..320bb0b1c 100644--- a/packages/core/src/modules/auth/auth.constants.ts+++ b/packages/core/src/modules/auth/auth.constants.ts@@ -33,6 +33,8 @@ export const zSignInEmail = z.object({});export type ISignInEmail = z.infer<typeof zSignInEmail>;+export const zSignInDev = z.object({ inviteId: zShortId.nullish() });+export const zSignUpEmail = z.object({firstName: zPersonName,diff --git a/packages/core/src/modules/auth/auth.rpc.test.ts b/packages/core/src/modules/auth/auth.rpc.test.tsindex 54096319c..b7e75dc73 100644--- a/packages/core/src/modules/auth/auth.rpc.test.ts+++ b/packages/core/src/modules/auth/auth.rpc.test.ts@@ -32,6 +32,7 @@ test('providers reports which OAuth features are configured, as booleans only',google: false,github: false,gsc: false,+ devLogin: false,});const config = testCoreConfig();@@ -55,10 +56,36 @@ test('providers reports which OAuth features are configured, as booleans only',cookieOptions: COOKIE_OPTIONS,});const providers = await authRouter.createCaller(trpcCtx).providers();- expect(providers).toEqual({ google: true, github: false, gsc: true });+ expect(providers).toEqual({+ google: true,+ github: false,+ gsc: true,+ devLogin: false,+ });expect(JSON.stringify(providers)).not.toContain('secret');});+test('providers says a dev login exists without reporting its credentials', async () => {+ const config = testCoreConfig();+ config.auth.devLogin = { email: '[email protected]', password: 'pw' };+ const { ctx } = stubHttpCtx({ config }, EMPTY_SESSION);+ const trpcCtx = await makeTrpcContext(ctx, new Headers(), {+ cookieOptions: COOKIE_OPTIONS,+ });+ const providers = await authRouter.createCaller(trpcCtx).providers();+ expect(providers.devLogin).toBe(true);+ expect(JSON.stringify(providers)).not.toContain('openpanel.local');+ expect(JSON.stringify(providers)).not.toContain('pw');+});++test('signInDev is refused when DEV_LOGIN is not configured', async () => {+ const caller = await anonCaller();+ await expect(caller.signInDev({})).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ message: 'Dev login is not configured on this deployment',+ });+});+test('totpStatus rejects an unauthenticated caller', async () => {const caller = await anonCaller();await expect(caller.totpStatus()).rejects.toMatchObject({diff --git a/packages/core/src/modules/auth/auth.rpc.ts b/packages/core/src/modules/auth/auth.rpc.tsindex 8d20d355a..ae01858cb 100644--- a/packages/core/src/modules/auth/auth.rpc.ts+++ b/packages/core/src/modules/auth/auth.rpc.ts@@ -13,6 +13,7 @@ import {zProvider,zRequestResetPassword,zResetPassword,+ zSignInDev,zSignInEmail,zSignInShare,zSignUpEmail,@@ -30,6 +31,7 @@ import {resetPasswordWithToken,setupTotp,signInToShare,+ signInWithDevLogin,signInWithEmail,signInWithTotp,signOutUser,@@ -69,6 +71,14 @@ export const authRouter = createTRPCRouter({signInWithEmail(ctx, input, ctx.setCookie, ctx.logger)),+ /** One click on a local box; `DEV_LOGIN` cannot be set in production. */+ signInDev: publicProcedure+ .use(rateLimit({ max: 10, windowMs: 60_000 }))+ .input(zSignInDev)+ .mutation(({ input, ctx }) =>+ signInWithDevLogin(ctx, input, ctx.setCookie, ctx.logger)+ ),+signInTotp: publicProcedure.use(rateLimit({ max: 5, windowMs: 60_000 })).input(z.object({ code: zTotpOrRecoveryCode }))diff --git a/packages/core/src/modules/auth/auth.service.ts b/packages/core/src/modules/auth/auth.service.tsindex 25b9a1d16..2a9f606f9 100644--- a/packages/core/src/modules/auth/auth.service.ts+++ b/packages/core/src/modules/auth/auth.service.ts@@ -316,6 +316,7 @@ export interface ConfiguredProviders {google: boolean;github: boolean;gsc: boolean;+ devLogin: boolean;}/** A provider counts as configured only when a sign-in could complete: the@@ -323,14 +324,44 @@ export interface ConfiguredProviders {export function getConfiguredProviders(config: CoreConfig): ConfiguredProviders {- const { google, github, googleGsc } = config.auth;+ const { google, github, googleGsc, devLogin } = config.auth;return {google: Boolean(google.clientId && google.redirectUri),github: Boolean(github.clientId && github.redirectUri),gsc: Boolean(googleGsc.clientId && googleGsc.redirectUri),+ devLogin: devLogin !== undefined,};}+/**+ * The configured `DEV_LOGIN` credentials go through the ordinary email+ * sign-in, so the account must exist and the password must match; the+ * credentials themselves never leave the API.+ */+export function signInWithDevLogin(+ deps: ServiceDeps,+ input: SignInDevInput,+ setCookie: ISetCookie,+ logger: Pick<Logger, 'error'>+): Promise<SignInEmailResult> {+ const devLogin = deps.config.auth.devLogin;+ if (!devLogin) {+ throw new TRPCBadRequestError(+ 'Dev login is not configured on this deployment'+ );+ }+ return signInWithEmail(+ deps,+ { ...devLogin, inviteId: input.inviteId },+ setCookie,+ logger+ );+}++export interface SignInDevInput {+ inviteId?: string | null;+}+/*** No registration check here. At this point we have no identity for the* caller — the IdP hasn't been hit yet — so we cannot tell a returning userdiff --git a/packages/core/test/config-fixture.ts b/packages/core/test/config-fixture.tsindex 4db16bd8c..14c7c8586 100644--- a/packages/core/test/config-fixture.ts+++ b/packages/core/test/config-fixture.ts@@ -33,6 +33,7 @@ export function testCoreConfig(github: { clientId: '', clientSecret: '', redirectUri: '' },google: { clientId: '', clientSecret: '', redirectUri: '' },googleGsc: { clientId: '', clientSecret: '', redirectUri: '' },+ devLogin: undefined,},cookies: {secret: 'test-cookie-secret',