OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.
organization: validate the timezone at the door and fall back to UTC when a stored one is unknown
Carl-Gerhard Lindesvärd9ee155825145
diff --git a/apps/start/src/components/organization/edit-organization.tsx b/apps/start/src/components/organization/edit-organization.tsxindex 4bf54b13e..b6d64818f 100644--- a/apps/start/src/components/organization/edit-organization.tsx+++ b/apps/start/src/components/organization/edit-organization.tsx@@ -70,10 +70,12 @@ export default function EditOrganization({<WithLabel label="Timezone"><ComboboxclassName="w-full"- items={Intl.supportedValuesOf('timeZone').map((item) => ({- value: item,- label: item,- }))}+ items={['UTC', ...Intl.supportedValuesOf('timeZone')].map(+ (item) => ({+ value: item,+ label: item,+ })+ )}onChange={field.onChange}placeholder="Select timezone"value={field.value}diff --git a/apps/start/src/routes/_steps.onboarding.project.tsx b/apps/start/src/routes/_steps.onboarding.project.tsxindex 857f4398c..59372ca77 100644--- a/apps/start/src/routes/_steps.onboarding.project.tsx+++ b/apps/start/src/routes/_steps.onboarding.project.tsx@@ -196,10 +196,12 @@ function Component() {<WithLabel label="Timezone"><ComboboxclassName="w-full"- items={Intl.supportedValuesOf('timeZone').map((item) => ({- value: item,- label: item,- }))}+ items={['UTC', ...Intl.supportedValuesOf('timeZone')].map(+ (item) => ({+ value: item,+ label: item,+ })+ )}onChange={field.onChange}placeholder="Select timezone"searchablediff --git a/packages/core/src/modules/onboarding/onboarding.constants.ts b/packages/core/src/modules/onboarding/onboarding.constants.tsindex d48d773d4..b6ec62f53 100644--- a/packages/core/src/modules/onboarding/onboarding.constants.ts+++ b/packages/core/src/modules/onboarding/onboarding.constants.ts@@ -5,6 +5,7 @@// Isomorphic by the AGENTS.md rule: zod and nothing else.import { z } from 'zod';+import { zTimezone } from '../organization/organization.constants';export const zOnboardingProject = z.object({@@ -16,7 +17,7 @@ export const zOnboardingProject = zwebsite: z.boolean(),app: z.boolean(),backend: z.boolean(),- timezone: z.string().optional(),+ timezone: zTimezone.optional(),}).superRefine((data, ctx) => {if (!(data.organization || data.organizationId)) {diff --git a/packages/core/src/modules/organization/organization.constants.test.ts b/packages/core/src/modules/organization/organization.constants.test.tsnew file mode 100644index 000000000..7e77cad1f--- /dev/null+++ b/packages/core/src/modules/organization/organization.constants.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'bun:test';+import { zEditOrganization, zTimezone } from './organization.constants';++describe('zTimezone', () => {+ it('accepts IANA zones, trims, and canonicalises case', () => {+ expect(zTimezone.parse('Europe/Stockholm')).toBe('Europe/Stockholm');+ expect(zTimezone.parse('UTC')).toBe('UTC');+ expect(zTimezone.parse('utc')).toBe('UTC');+ expect(zTimezone.parse(' Etc/UTC ')).toBe('Etc/UTC');+ });++ it('rejects unknown zones before they can be stored', () => {+ expect(zTimezone.safeParse('Not/AZone').success).toBe(false);+ expect(zTimezone.safeParse('').success).toBe(false);+ expect(+ zEditOrganization.safeParse({+ id: 'org_1',+ name: 'Acme',+ timezone: 'Mars/Olympus',+ }).success+ ).toBe(false);+ });+});diff --git a/packages/core/src/modules/organization/organization.constants.ts b/packages/core/src/modules/organization/organization.constants.tsindex 0b6e61454..22fed8104 100644--- a/packages/core/src/modules/organization/organization.constants.ts+++ b/packages/core/src/modules/organization/organization.constants.ts@@ -35,8 +35,35 @@ export const zUpdateMemberAccess = z.object({access: z.array(zProjectAccessGrant),});+export const DEFAULT_TIMEZONE = 'UTC';++/** True when the runtime's ICU knows the zone (accepts aliases like `Etc/UTC`, `utc`). */+export function isValidTimezone(value: string): boolean {+ try {+ new Intl.DateTimeFormat('en-US', { timeZone: value });+ return true;+ } catch {+ return false;+ }+}++/** The spelling ICU resolves (`utc` → `UTC`), so one zone has one stored form. */+export function canonicalTimezone(value: string): string {+ return new Intl.DateTimeFormat('en-US', { timeZone: value }).resolvedOptions()+ .timeZone;+}++// An unknown zone stored on the organization used to turn every date-driven+// query in it into `Invalid Date` 500s, so the zone is checked at the door.+export const zTimezone = z+ .string()+ .trim()+ .min(1)+ .refine(isValidTimezone, { message: 'Unknown IANA time zone' })+ .transform(canonicalTimezone);+export const zEditOrganization = z.object({id: z.string().min(2),name: z.string().min(2),- timezone: z.string().min(1),+ timezone: zTimezone,});diff --git a/packages/core/src/modules/organization/organization.service.test.ts b/packages/core/src/modules/organization/organization.service.test.tsindex 05ff2868a..f43c7ef92 100644--- a/packages/core/src/modules/organization/organization.service.test.ts+++ b/packages/core/src/modules/organization/organization.service.test.ts@@ -5,6 +5,7 @@import { afterAll, beforeAll, beforeEach, expect, mock, test } from 'bun:test';import { testCoreConfig } from '../../../test/config-fixture';+import { recordingLogger } from '../../../test/service-deps';interface FakeOrganization {id: string;@@ -410,6 +411,7 @@ const $transaction = mock(async (ops: Promise<unknown>[]) => Promise.all(ops));// the `@openpanel/redis` stand-in below stays.const chCommand = mock(async () => undefined);const deps = {+ logger: recordingLogger(),db: {organization,project,@@ -779,6 +781,15 @@ test('runDeleteCron is a no-op when nothing is due', async () => {expect(organizationStore.has('org_healthy')).toBe(true);});+test('getSettingsForOrganization falls back to UTC when the stored timezone is unknown', async () => {+ organizationStore.set(+ 'org_1',+ makeOrganization({ id: 'org_1', timezone: 'Not/AZone' })+ );+ const result = await subject.getSettingsForOrganization(deps, 'org_1');+ expect(result).toEqual({ timezone: 'UTC' });+});+test('getSettingsForOrganization falls back to UTC when the organization has no timezone', async () => {organizationStore.set('org_1',diff --git a/packages/core/src/modules/organization/organization.service.ts b/packages/core/src/modules/organization/organization.service.tsindex e3fedc4ec..565e3e2de 100644--- a/packages/core/src/modules/organization/organization.service.ts+++ b/packages/core/src/modules/organization/organization.service.ts@@ -54,6 +54,7 @@ import {} from '../../shared/access-lookups';import { formatClickhouseDate } from '../../shared/ch-dates';import { TABLE_NAMES } from '../../shared/ch-tables';+import { DEFAULT_TIMEZONE, isValidTimezone } from './organization.constants';export type IServiceOrganization = Awaited<ReturnType<typeof getOrganizationById>@@ -64,7 +65,6 @@ export type IServiceMember = Prisma.MemberGetPayload<{}> & { access: ProjectAccess[] };export type IServiceProjectAccess = ProjectAccess;-const DEFAULT_TIMEZONE = 'UTC';// Grace period between a scheduled deletion and the `delete` cron sweeping it// up — matches V1's `addHours(new Date(), 24)`.// Session bookkeeping rows are worker-generated (the reaper can emit@@ -458,10 +458,29 @@ export async function getSettingsForOrganization(});return {- timezone: organization.timezone || DEFAULT_TIMEZONE,+ timezone: resolveTimezone(deps, organization.id, organization.timezone),};}+// One bad stored zone must not take the whole organization down.+function resolveTimezone(+ deps: ServiceDeps,+ organizationId: string,+ stored: string | null+): string {+ if (!stored) {+ return DEFAULT_TIMEZONE;+ }+ if (isValidTimezone(stored)) {+ return stored;+ }+ deps.logger.warn(+ { organizationId, timezone: stored },+ 'organization has an invalid timezone; using UTC'+ );+ return DEFAULT_TIMEZONE;+}+export async function getSettingsForProject(deps: ServiceDeps,projectId: string@@ -477,7 +496,11 @@ export async function getSettingsForProject(});return {- timezone: project.organization.timezone || DEFAULT_TIMEZONE,+ timezone: resolveTimezone(+ deps,+ project.organization.id,+ project.organization.timezone+ ),};}diff --git a/packages/core/src/modules/report/src/chart-dates.ts b/packages/core/src/modules/report/src/chart-dates.tsindex 2aa3f634c..21df66a03 100644--- a/packages/core/src/modules/report/src/chart-dates.ts+++ b/packages/core/src/modules/report/src/chart-dates.ts@@ -7,7 +7,21 @@import { DateTime } from '@openpanel/shared';import type { IChartRange, IReportInput } from '../report.constants';-export function getDatesFromRange(range: IChartRange, timezone: string) {+const FALLBACK_TIMEZONE = 'UTC';++// Luxon renders "Invalid DateTime" for an unknown zone, which then reaches+// ClickHouse as a date literal; fall back rather than poison every query.+function usableTimezone(timezone: string): string {+ return DateTime.now().setZone(timezone).isValid+ ? timezone+ : FALLBACK_TIMEZONE;+}++export function getDatesFromRange(+ range: IChartRange,+ requestedTimezone: string+) {+ const timezone = usableTimezone(requestedTimezone);if (range === '30min' || range === 'lastHour') {const minutes = range === '30min' ? 30 : 60;const startDate = DateTime.now()