OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
fix: session issues
Carl-Gerhard Lindesvärd6dca57d7ce3a
diff --git a/apps/start/src/routes/_app.tsx b/apps/start/src/routes/_app.tsxindex 2c4139d7e..678f1cea5 100644--- a/apps/start/src/routes/_app.tsx+++ b/apps/start/src/routes/_app.tsx@@ -1,14 +1,14 @@+import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';+import { ConstructionIcon } from 'lucide-react';import { FullPageEmptyState } from '@/components/full-page-empty-state';import { Sidebar } from '@/components/sidebar';-import { Button, LinkButton, buttonVariants } from '@/components/ui/button';+import { buttonVariants } from '@/components/ui/button';import { useAppContext } from '@/hooks/use-app-context';import { cn } from '@/utils/cn';-import { Outlet, createFileRoute, redirect } from '@tanstack/react-router';-import { ConstructionIcon } from 'lucide-react';export const Route = createFileRoute('/_app')({beforeLoad: async ({ context }) => {- if (!context.session.session) {+ if (!context.session?.session) {throw redirect({ to: '/login' });}},@@ -21,16 +21,16 @@ function AppLayout() {if (isMaintenance) {return (<FullPageEmptyState- icon={ConstructionIcon}className="min-h-screen"- title="Maintenance mode"description="We are currently performing maintenance on the system. Please check back later."+ icon={ConstructionIcon}+ title="Maintenance mode"><a- href="https://status.openpanel.dev/"className={cn(buttonVariants())}- target="_blank"+ href="https://status.openpanel.dev/"rel="noopener noreferrer"+ target="_blank">Check out our status page</a>@@ -41,9 +41,9 @@ function AppLayout() {return (<div className="flex h-screen w-full"><Sidebar />- <div className="lg:pl-72 w-full">- <div className="block lg:hidden bg-background h-16 w-full fixed top-0 z-10 border-b" />- <div className="block lg:hidden h-16" />+ <div className="w-full lg:pl-72">+ <div className="fixed top-0 z-10 block h-16 w-full border-b bg-background lg:hidden" />+ <div className="block h-16 lg:hidden" /><Outlet /></div></div>diff --git a/apps/start/src/routes/_login.tsx b/apps/start/src/routes/_login.tsxindex e5add47a7..f4fc47a10 100644--- a/apps/start/src/routes/_login.tsx+++ b/apps/start/src/routes/_login.tsx@@ -1,11 +1,10 @@+import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';import { LoginLeftPanel } from '@/components/login-left-panel';import { LoginNavbar } from '@/components/login-navbar';-import { SkeletonDashboard } from '@/components/skeleton-dashboard';-import { Outlet, createFileRoute, redirect } from '@tanstack/react-router';export const Route = createFileRoute('/_login')({beforeLoad: async ({ context }) => {- if (context.session.session) {+ if (context.session?.session) {throw redirect({ to: '/' });}},@@ -14,12 +13,12 @@ export const Route = createFileRoute('/_login')({function AuthLayout() {return (- <div className="relative min-h-screen grid md:grid-cols-2">+ <div className="relative grid min-h-screen md:grid-cols-2"><LoginNavbar /><div className="hidden md:block"><LoginLeftPanel /></div>- <div className="center-center w-full max-w-md mx-auto px-4">+ <div className="center-center mx-auto w-full max-w-md px-4"><Outlet /></div></div>diff --git a/apps/start/src/routes/_public.onboarding.tsx b/apps/start/src/routes/_public.onboarding.tsxindex 653d98bbc..8fdfb54ca 100644--- a/apps/start/src/routes/_public.onboarding.tsx+++ b/apps/start/src/routes/_public.onboarding.tsx@@ -1,16 +1,15 @@+import { useQuery } from '@tanstack/react-query';+import { createFileRoute, redirect } from '@tanstack/react-router';+import { MailIcon } from 'lucide-react';+import { z } from 'zod';import { Or } from '@/components/auth/or';import { SignInGithub } from '@/components/auth/sign-in-github';import { SignInGoogle } from '@/components/auth/sign-in-google';import { SignUpEmailForm } from '@/components/auth/sign-up-email-form';import FullPageLoadingState from '@/components/full-page-loading-state';-import { LogoSquare } from '@/components/logo';import { useTRPC } from '@/integrations/trpc/react';-import { PAGE_TITLES, createEntityTitle } from '@/utils/title';-import { useQuery } from '@tanstack/react-query';-import { createFileRoute, redirect } from '@tanstack/react-router';-import { motion } from 'framer-motion';-import { MailIcon } from 'lucide-react';-import { z } from 'zod';+import { createEntityTitle, PAGE_TITLES } from '@/utils/title';+const validateSearch = z.object({inviteId: z.string().optional(),});@@ -22,7 +21,7 @@ export const Route = createFileRoute('/_public/onboarding')({],}),beforeLoad: async ({ context }) => {- if (context.session.session) {+ if (context.session?.session) {throw redirect({ to: '/' });}},@@ -34,7 +33,7 @@ export const Route = createFileRoute('/_public/onboarding')({await context.queryClient.prefetchQuery(context.trpc.organization.getInvite.queryOptions({inviteId: search.data.inviteId,- }),+ }));}},@@ -47,36 +46,36 @@ function Component() {const { data: invite } = useQuery(trpc.organization.getInvite.queryOptions({- inviteId: inviteId,+ inviteId,},{enabled: !!inviteId,- },- ),+ }+ ));return (- <div className="col gap-8 w-full text-left">+ <div className="col w-full gap-8 text-left"><div>- <h1 className="text-3xl font-bold text-foreground mb-2">+ <h1 className="mb-2 font-bold text-3xl text-foreground">Create an account</h1><p className="text-muted-foreground">Let's start with creating your account. By creating an account youaccept the{' '}<a- target="_blank"+ className="underline transition-colors hover:text-foreground"href="https://openpanel.dev/terms"rel="noreferrer"- className="underline hover:text-foreground transition-colors"+ target="_blank">Terms of Service</a>{' '}and{' '}<a- target="_blank"+ className="underline transition-colors hover:text-foreground"href="https://openpanel.dev/privacy"rel="noreferrer"- className="underline hover:text-foreground transition-colors"+ target="_blank">Privacy Policy</a>@@ -85,8 +84,8 @@ function Component() {</div>{invite && !invite.isExpired && (- <div className="bg-card border border-border rounded-lg p-6 mb-6">- <h2 className="text-xl font-semibold mb-2">+ <div className="mb-6 rounded-lg border border-border bg-card p-6">+ <h2 className="mb-2 font-semibold text-xl">Invitation to {invite.organization?.name}</h2><p className="text-muted-foreground">@@ -96,8 +95,8 @@ function Component() {</div>)}{invite?.isExpired && (- <div className="bg-destructive/10 border border-destructive/20 rounded-lg p-6 mb-6">- <h2 className="text-xl font-semibold mb-2 text-destructive">+ <div className="mb-6 rounded-lg border border-destructive/20 bg-destructive/10 p-6">+ <h2 className="mb-2 font-semibold text-destructive text-xl">Invitation to {invite.organization?.name} has expired</h2><p className="text-muted-foreground">@@ -108,14 +107,14 @@ function Component() {)}<div className="space-y-6">- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">- <SignInGithub type="sign-up" inviteId={inviteId} />- <SignInGoogle type="sign-up" inviteId={inviteId} />+ <div className="grid grid-cols-1 gap-4 md:grid-cols-2">+ <SignInGithub inviteId={inviteId} type="sign-up" />+ <SignInGoogle inviteId={inviteId} type="sign-up" /></div><Or className="my-6" />- <div className="flex items-center gap-2 font-semibold mb-4 text-lg">+ <div className="mb-4 flex items-center gap-2 font-semibold text-lg"><MailIcon className="size-4" />Sign up with email</div>diff --git a/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx b/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsxindex 9ab2daceb..1c9803e8c 100644--- a/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx+++ b/apps/start/src/routes/_steps.onboarding.$projectId.connect.tsx@@ -1,3 +1,6 @@+import { useQuery } from '@tanstack/react-query';+import { createFileRoute, redirect } from '@tanstack/react-router';+import { LockIcon, XIcon } from 'lucide-react';import { ButtonContainer } from '@/components/button-container';import CopyInput from '@/components/forms/copy-input';import { FullPageEmptyState } from '@/components/full-page-empty-state';@@ -8,10 +11,7 @@ import ConnectWeb from '@/components/onboarding/connect-web';import { LinkButton } from '@/components/ui/button';import { useClientSecret } from '@/hooks/use-client-secret';import { useTRPC } from '@/integrations/trpc/react';-import { PAGE_TITLES, createEntityTitle } from '@/utils/title';-import { useQuery } from '@tanstack/react-query';-import { createFileRoute, redirect } from '@tanstack/react-router';-import { LockIcon, XIcon } from 'lucide-react';+import { createEntityTitle, PAGE_TITLES } from '@/utils/title';export const Route = createFileRoute('/_steps/onboarding/$projectId/connect')({head: () => ({@@ -20,7 +20,7 @@ export const Route = createFileRoute('/_steps/onboarding/$projectId/connect')({],}),beforeLoad: async ({ context }) => {- if (!context.session.session) {+ if (!context.session?.session) {throw redirect({ to: '/onboarding' });}},@@ -29,7 +29,7 @@ export const Route = createFileRoute('/_steps/onboarding/$projectId/connect')({await context.queryClient.prefetchQuery(context.trpc.project.getProjectWithClients.queryOptions({projectId: params.projectId,- }),+ }));},pendingComponent: FullPageLoadingState,@@ -39,7 +39,7 @@ function Component() {const { projectId } = Route.useParams();const trpc = useTRPC();const { data: project } = useQuery(- trpc.project.getProjectWithClients.queryOptions({ projectId }),+ trpc.project.getProjectWithClients.queryOptions({ projectId }));const client = project?.clients[0];const [secret] = useClientSecret();@@ -47,24 +47,24 @@ function Component() {if (!client) {return (<FullPageEmptyState- title="No project found"description="The project you are looking for does not exist. Please reload the page."icon={XIcon}+ title="No project found"/>);}return (- <div className="p-4 col gap-8">+ <div className="col gap-8 p-4"><div className="flex flex-col gap-4">- <div className="flex items-center gap-2 text-xl font-bold capitalize">+ <div className="flex items-center gap-2 font-bold text-xl capitalize"><LockIcon className="size-4" />Credentials</div><CopyInput label="Client ID" value={client.id} /><CopyInput label="Secret" value={secret} /></div>- <div className="h-px bg-muted -mx-4" />+ <div className="-mx-4 h-px bg-muted" />{project?.types?.map((type) => {const Component = {website: ConnectWeb,@@ -72,15 +72,15 @@ function Component() {backend: ConnectBackend,}[type];- return <Component key={type} client={{ ...client, secret }} />;+ return <Component client={{ ...client, secret }} key={type} />;})}<ButtonContainer><div /><LinkButton+ className="min-w-28 self-start"href={'/onboarding/$projectId/verify'}params={{ projectId }}size="lg"- className="min-w-28 self-start">Next</LinkButton>diff --git a/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx b/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsxindex 8f87c9977..f66695764 100644--- a/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx+++ b/apps/start/src/routes/_steps.onboarding.$projectId.verify.tsx@@ -1,3 +1,7 @@+import { useQuery } from '@tanstack/react-query';+import { createFileRoute, Link, redirect } from '@tanstack/react-router';+import { BoxSelectIcon } from 'lucide-react';+import { useEffect, useState } from 'react';import { ButtonContainer } from '@/components/button-container';import { FullPageEmptyState } from '@/components/full-page-empty-state';import FullPageLoadingState from '@/components/full-page-loading-state';@@ -6,18 +10,14 @@ import VerifyListener from '@/components/onboarding/onboarding-verify-listener';import { LinkButton } from '@/components/ui/button';import { useTRPC } from '@/integrations/trpc/react';import { cn } from '@/lib/utils';-import { PAGE_TITLES, createEntityTitle } from '@/utils/title';-import { useQuery } from '@tanstack/react-query';-import { Link, createFileRoute, redirect } from '@tanstack/react-router';-import { BoxSelectIcon } from 'lucide-react';-import { useEffect, useState } from 'react';+import { createEntityTitle, PAGE_TITLES } from '@/utils/title';export const Route = createFileRoute('/_steps/onboarding/$projectId/verify')({head: () => ({meta: [{ title: createEntityTitle('Verify', PAGE_TITLES.ONBOARDING) }],}),beforeLoad: async ({ context }) => {- if (!context.session.session) {+ if (!context.session?.session) {throw redirect({ to: '/onboarding' });}},@@ -26,7 +26,7 @@ export const Route = createFileRoute('/_steps/onboarding/$projectId/verify')({await context.queryClient.prefetchQuery(context.trpc.project.getProjectWithClients.queryOptions({projectId: params.projectId,- }),+ }));},pendingComponent: FullPageLoadingState,@@ -37,10 +37,10 @@ function Component() {const { projectId } = Route.useParams();const trpc = useTRPC();const { data: events, refetch } = useQuery(- trpc.event.events.queryOptions({ projectId }),+ trpc.event.events.queryOptions({ projectId }));const { data: project } = useQuery(- trpc.project.getProjectWithClients.queryOptions({ projectId }),+ trpc.project.getProjectWithClients.queryOptions({ projectId }));useEffect(() => {@@ -51,34 +51,34 @@ function Component() {if (!project) {return (- <FullPageEmptyState title="Project not found" icon={BoxSelectIcon} />+ <FullPageEmptyState icon={BoxSelectIcon} title="Project not found" />);}const client = project.clients[0];if (!client) {- return <FullPageEmptyState title="Client not found" icon={BoxSelectIcon} />;+ return <FullPageEmptyState icon={BoxSelectIcon} title="Client not found" />;}return (- <div className="p-4 col gap-8">+ <div className="col gap-8 p-4"><VerifyListener- project={project}client={client}events={events?.data ?? []}onVerified={() => {refetch();setIsVerified(true);}}+ project={project}/><CurlPreview project={project} /><ButtonContainer><LinkButton+ className="min-w-28 self-start"href={`/onboarding/${project.id}/connect`}size="lg"- className="min-w-28 self-start"variant={'secondary'}>Back@@ -87,28 +87,28 @@ function Component() {<div className="flex items-center gap-8">{!isVerified && (<Link- to={'/$organizationId/$projectId'}+ className="text-muted-foreground underline"params={{organizationId: project!.organizationId,projectId: project!.id,}}- className=" text-muted-foreground underline"+ to={'/$organizationId/$projectId'}>Skip for now</Link>)}<LinkButton- to={'/$organizationId/$projectId'}+ className={cn(+ 'min-w-28 self-start',+ !isVerified && 'pointer-events-none select-none opacity-20'+ )}params={{organizationId: project!.organizationId,projectId: project!.id,}}size="lg"- className={cn(- 'min-w-28 self-start',- !isVerified && 'pointer-events-none select-none opacity-20',- )}+ to={'/$organizationId/$projectId'}>Your dashboard</LinkButton>diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsxindex 94044da7b..1e223c39f 100644--- a/apps/start/src/routes/_steps.onboarding.project.tsx+++ b/apps/start/src/routes/_steps.onboarding.project.tsx@@ -1,14 +1,3 @@-import AnimateHeight from '@/components/animate-height';-import { ButtonContainer } from '@/components/button-container';-import { CheckboxItem } from '@/components/forms/checkbox-item';-import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';-import TagInput from '@/components/forms/tag-input';-import FullPageLoadingState from '@/components/full-page-loading-state';-import { Button } from '@/components/ui/button';-import { Combobox } from '@/components/ui/combobox';-import { Label } from '@/components/ui/label';-import { useClientSecret } from '@/hooks/use-client-secret';-import { handleError, useTRPC } from '@/integrations/trpc/react';import { zodResolver } from '@hookform/resolvers/zod';import { zOnboardingProject } from '@openpanel/validation';import { useMutation, useQuery } from '@tanstack/react-query';@@ -27,6 +16,17 @@ import {useWatch,} from 'react-hook-form';import { z } from 'zod';+import AnimateHeight from '@/components/animate-height';+import { ButtonContainer } from '@/components/button-container';+import { CheckboxItem } from '@/components/forms/checkbox-item';+import { InputWithLabel, WithLabel } from '@/components/forms/input-with-label';+import TagInput from '@/components/forms/tag-input';+import FullPageLoadingState from '@/components/full-page-loading-state';+import { Button } from '@/components/ui/button';+import { Combobox } from '@/components/ui/combobox';+import { Label } from '@/components/ui/label';+import { useClientSecret } from '@/hooks/use-client-secret';+import { handleError, useTRPC } from '@/integrations/trpc/react';const validateSearch = z.object({inviteId: z.string().optional(),@@ -35,7 +35,7 @@ export const Route = createFileRoute('/_steps/onboarding/project')({component: Component,validateSearch,beforeLoad: async ({ context }) => {- if (!context.session.session) {+ if (!context.session?.session) {throw redirect({ to: '/onboarding' });}},@@ -45,7 +45,7 @@ export const Route = createFileRoute('/_steps/onboarding/project')({await context.queryClient.prefetchQuery(context.trpc.organization.getInvite.queryOptions({inviteId: search.data.inviteId,- }),+ }));}},@@ -57,7 +57,7 @@ type IForm = z.infer<typeof zOnboardingProject>;function Component() {const trpc = useTRPC();const { data: organizations } = useQuery(- trpc.organization.list.queryOptions(undefined, { initialData: [] }),+ trpc.organization.list.queryOptions(undefined, { initialData: [] }));const [, setSecret] = useClientSecret();const navigate = useNavigate();@@ -73,7 +73,7 @@ function Component() {},});},- }),+ }));const form = useForm<IForm>({@@ -134,10 +134,8 @@ function Component() {<Label>Workspace</Label><ComboboxclassName="w-full"- placeholder="Select workspace"- icon={BuildingIcon}error={formState.errors.organizationId?.message}- value={field.value}+ icon={BuildingIcon}items={organizations.filter((item) => item.id)@@ -147,6 +145,8 @@ function Component() {})) ?? []}onChange={field.onChange}+ placeholder="Select workspace"+ value={field.value}/></div>);@@ -155,26 +155,26 @@ function Component() {) : (<><InputWithLabel- label="Workspace name"+ error={form.formState.errors.organization?.message}info="This is the name of your workspace. It can be anything you like."+ label="Workspace name"placeholder="Eg. The Music Company"- error={form.formState.errors.organization?.message}{...form.register('organization')}/><Controller- name="timezone"control={form.control}+ name="timezone"render={({ field }) => (<WithLabel label="Timezone"><Combobox- placeholder="Select timezone"+ className="w-full"items={Intl.supportedValuesOf('timeZone').map((item) => ({value: item,label: item,}))}- value={field.value}onChange={field.onChange}- className="w-full"+ placeholder="Select timezone"+ value={field.value}/></WithLabel>)}@@ -182,24 +182,24 @@ function Component() {</>)}<InputWithLabel+ error={form.formState.errors.project?.message}label="Project name"placeholder="Eg. The Music App"- error={form.formState.errors.project?.message}{...form.register('project')}className="col-span-2"/></div>- <div className="flex flex-col divide-y mt-4">+ <div className="mt-4 flex flex-col divide-y"><Controller- name="website"control={form.control}+ name="website"render={({ field }) => (<CheckboxItem+ description="Track events and conversion for your website"+ disabled={isApp}error={form.formState.errors.website?.message}Icon={MonitorIcon}label="Website"- disabled={isApp}- description="Track events and conversion for your website"{...field}><AnimateHeight open={isWebsite && !isApp}>@@ -223,20 +223,13 @@ function Component() {/><Controller- name="cors"control={form.control}+ name="cors"render={({ field }) => (<WithLabel label="Allowed domains"><TagInput{...field}error={form.formState.errors.cors?.message}- placeholder="Accept events from these domains"- value={field.value ?? []}- renderTag={(tag) =>- tag === '*'- ? 'Accept events from any domains'- : tag- }onChange={(newValue) => {field.onChange(newValue.map((item) => {@@ -249,9 +242,16 @@ function Component() {return trimmed;}return `https://${trimmed}`;- }),+ }));}}+ placeholder="Accept events from these domains"+ renderTag={(tag) =>+ tag === '*'+ ? 'Accept events from any domains'+ : tag+ }+ value={field.value ?? []}/></WithLabel>)}@@ -262,28 +262,28 @@ function Component() {)}/><Controller- name="app"control={form.control}+ name="app"render={({ field }) => (<CheckboxItem- error={form.formState.errors.app?.message}+ description="Track events and conversion for your app"disabled={isWebsite}+ error={form.formState.errors.app?.message}Icon={SmartphoneIcon}label="App"- description="Track events and conversion for your app"{...field}/>)}/><Controller- name="backend"control={form.control}+ name="backend"render={({ field }) => (<CheckboxItem+ description="Track events and conversion for your backend / API"error={form.formState.errors.backend?.message}Icon={ServerIcon}label="Backend / API"- description="Track events and conversion for your backend / API"{...field}/>)}@@ -291,13 +291,13 @@ function Component() {</div></div>- <ButtonContainer className="p-4 border-t">+ <ButtonContainer className="border-t p-4"><div /><Button- type="submit"- size="lg"className="min-w-28 self-start"loading={mutation.isPending}+ size="lg"+ type="submit">Next</Button>diff --git a/apps/start/src/routes/index.tsx b/apps/start/src/routes/index.tsxindex e040477ff..8f5c8a3dd 100644--- a/apps/start/src/routes/index.tsx+++ b/apps/start/src/routes/index.tsx@@ -11,7 +11,7 @@ import { createTitle } from '@/utils/title';export const Route = createFileRoute('/')({beforeLoad: ({ context }) => {- if (!context.session.session) {+ if (!context.session?.session) {throw redirect({ to: '/login' });}},diff --git a/packages/auth/src/cookie.ts b/packages/auth/src/cookie.tsindex dcbf4a681..09fab968d 100644--- a/packages/auth/src/cookie.ts+++ b/packages/auth/src/cookie.ts@@ -4,10 +4,10 @@ import { COOKIE_OPTIONS } from '../constants';export function setSessionTokenCookie(setCookie: ISetCookie,token: string,- expiresAt: Date,+ expiresAt: Date): void {setCookie('session', token, {- maxAge: expiresAt.getTime() - new Date().getTime(),+ maxAge: Math.floor((expiresAt.getTime() - new Date().getTime()) / 1000),...COOKIE_OPTIONS,});}