Merge branch 'dev' into codex/fix-umami-4044

This commit is contained in:
Mike Cao authored and GitHub committed 2026-03-09 23:28:33 -07:00
commit a1e7a8332a
655 files changed
+41216 -143048

No files matched your search

+1 -1
View File
@@ -18,5 +18,5 @@ test('getIpAddress: Standard header', () => {
});
test('getIpAddress: No header', () => {
expect(getIpAddress(new Headers())).toEqual(null);
expect(getIpAddress(new Headers())).toEqual(undefined);
});
+2 -3
View File
@@ -1,7 +1,6 @@
import debug from 'debug';
import { ROLE_PERMISSIONS, ROLES, SHARE_TOKEN_HEADER } from '@/lib/constants';
import { secret } from '@/lib/crypto';
import { getRandomChars } from '@/lib/generate';
import { createAuthKey, secret } from '@/lib/crypto';
import { createSecureToken, parseSecureToken, parseToken } from '@/lib/jwt';
import redis from '@/lib/redis';
import { ensureArray } from '@/lib/utils';
@@ -53,7 +52,7 @@ export async function checkAuth(request: Request) {
}
export async function saveAuth(data: any, expire = 0) {
const authKey = `auth:${getRandomChars(32)}`;
const authKey = `auth:${createAuthKey()}`;
if (redis.enabled) {
await redis.client.set(authKey, data);
+212
View File
@@ -0,0 +1,212 @@
import type { Board, BoardComponentConfig, BoardParameters } from './types';
export const BOARD_TYPES = {
dashboard: 'dashboard',
mixed: 'mixed',
website: 'website',
pixel: 'pixel',
link: 'link',
} as const;
export const BOARD_ENTITY_TYPES = {
website: 'website',
pixel: 'pixel',
link: 'link',
} as const;
export type BoardType = (typeof BOARD_TYPES)[keyof typeof BOARD_TYPES];
export type BoardEntityType = (typeof BOARD_ENTITY_TYPES)[keyof typeof BOARD_ENTITY_TYPES];
const boardTypes = new Set<string>(Object.values(BOARD_TYPES));
export function getLegacyBoardType(parameters?: BoardParameters): BoardType {
if (parameters?.pixelId) {
return BOARD_TYPES.pixel;
}
if (parameters?.linkId) {
return BOARD_TYPES.link;
}
if (parameters?.websiteId) {
return BOARD_TYPES.website;
}
return BOARD_TYPES.mixed;
}
export function normalizeBoardType(type?: string): BoardType | undefined {
if (type === 'open') {
return BOARD_TYPES.mixed;
}
if (type && boardTypes.has(type)) {
return type as BoardType;
}
return undefined;
}
export function getBoardType(
board?: Pick<Board, 'type' | 'parameters'> | Partial<Board>,
{ coerceDashboard = false }: { coerceDashboard?: boolean } = {},
): BoardType {
const type = board?.type;
if (type === BOARD_TYPES.dashboard && coerceDashboard) {
return getLegacyBoardType(board?.parameters);
}
const normalizedType = normalizeBoardType(type);
if (normalizedType) {
return normalizedType;
}
return getLegacyBoardType(board?.parameters);
}
export function isOpenBoardType(type?: string) {
return type === BOARD_TYPES.mixed || type === BOARD_TYPES.dashboard || type === 'open';
}
export function requiresBoardEntity(type?: string) {
return (
type === BOARD_TYPES.website || type === BOARD_TYPES.pixel || type === BOARD_TYPES.link
);
}
export function getBoardEntity(board?: Pick<Board, 'type' | 'parameters'> | Partial<Board>): {
entityType?: BoardEntityType;
entityId?: string;
} {
const type = getBoardType(board);
if (type === BOARD_TYPES.website) {
return {
entityType: BOARD_ENTITY_TYPES.website,
entityId: board?.parameters?.websiteId,
};
}
if (type === BOARD_TYPES.pixel) {
return {
entityType: BOARD_ENTITY_TYPES.pixel,
entityId: board?.parameters?.pixelId,
};
}
if (type === BOARD_TYPES.link) {
return {
entityType: BOARD_ENTITY_TYPES.link,
entityId: board?.parameters?.linkId,
};
}
return {};
}
export function getComponentEntity(config?: BoardComponentConfig): {
entityType?: BoardEntityType;
entityId?: string;
} {
if (config?.entityType && config?.entityId) {
return {
entityType: config.entityType,
entityId: config.entityId,
};
}
if (config?.websiteId) {
return {
entityType: BOARD_ENTITY_TYPES.website,
entityId: config.websiteId,
};
}
return {};
}
export function getResolvedComponentEntity(
board?: Pick<Board, 'type' | 'parameters'> | Partial<Board>,
config?: BoardComponentConfig,
) {
const boardEntity = getBoardEntity(board);
if (boardEntity.entityId) {
return boardEntity;
}
return getComponentEntity(config);
}
export function getFirstBoardComponentEntity(
board?: Pick<Board, 'type' | 'parameters'> | Partial<Board>,
) {
for (const row of board?.parameters?.rows ?? []) {
for (const column of row.columns ?? []) {
const entity = getComponentEntity(column.component);
if (entity.entityId) {
return entity;
}
}
}
return {};
}
export function getBoardWebsiteIds(
board?: Pick<Board, 'type' | 'parameters'> | Partial<Board>,
): string[] {
const ids = new Set<string>();
const boardEntity = getBoardEntity(board);
if (boardEntity.entityType === BOARD_ENTITY_TYPES.website && boardEntity.entityId) {
ids.add(boardEntity.entityId);
}
if (board?.parameters?.websiteId) {
ids.add(board.parameters.websiteId);
}
for (const row of board?.parameters?.rows ?? []) {
for (const column of row.columns ?? []) {
const entity = getComponentEntity(column.component);
if (entity.entityType === BOARD_ENTITY_TYPES.website && entity.entityId) {
ids.add(entity.entityId);
}
}
}
return [...ids];
}
export function clearBoardEntity(parameters: BoardParameters = {}): BoardParameters {
const { websiteId, pixelId, linkId, ...rest } = parameters;
return rest;
}
export function setBoardEntity(
parameters: BoardParameters = {},
type: BoardType,
entityId?: string,
): BoardParameters {
const next = clearBoardEntity(parameters);
if (type === BOARD_TYPES.website && entityId) {
next.websiteId = entityId;
}
if (type === BOARD_TYPES.pixel && entityId) {
next.pixelId = entityId;
}
if (type === BOARD_TYPES.link && entityId) {
next.linkId = entityId;
}
return next;
}
-1
View File
@@ -11,7 +11,6 @@ export function renderDateLabels(unit: string, locale: string) {
switch (unit) {
case 'minute':
return formatDate(d, 'h:mm', locale);
case 'hour':
return formatDate(d, 'p', locale);
case 'day':
+77 -19
View File
@@ -61,7 +61,7 @@ function getDateStringSQL(data: any, unit: string = 'utc', timezone?: string) {
function getDateSQL(field: string, unit: string, timezone?: string) {
if (timezone) {
return `toDateTime(date_trunc('${unit}', ${field}, '${timezone}'))`;
return `toDateTime(date_trunc('${unit}', ${field}, '${timezone}'), '${timezone}')`;
}
return `toDateTime(date_trunc('${unit}', ${field}))`;
}
@@ -70,47 +70,73 @@ function getSearchSQL(column: string, param: string = 'search'): string {
return `and positionCaseInsensitive(${column}, {${param}:String}) > 0`;
}
function mapFilter(column: string, operator: string, name: string, type: string = 'String') {
const value = `{${name}:${type}}`;
function mapFilter(
column: string,
operator: string,
name: string,
type: string = 'String',
paramName?: string,
) {
const param = paramName ?? name;
const value = `{${param}:${type}}`;
switch (operator) {
case OPERATORS.equals:
return `${column} = ${value}`;
return `${column} IN {${param}:Array(${type})}`;
case OPERATORS.notEquals:
return `${column} != ${value}`;
return `${column} NOT IN {${param}:Array(${type})}`;
case OPERATORS.contains:
return `positionCaseInsensitive(${column}, ${value}) > 0`;
case OPERATORS.doesNotContain:
return `positionCaseInsensitive(${column}, ${value}) = 0`;
case OPERATORS.regex:
return `match(${column}, ${value})`;
case OPERATORS.notRegex:
return `not match(${column}, ${value})`;
default:
return '';
}
}
function getFilterQuery(filters: Record<string, any>, options: QueryOptions = {}) {
const query = filtersObjectToArray(filters, options).reduce((arr, { name, column, operator }) => {
const isCohort = options?.isCohort;
const { isCohort, cohortMatch, cohortActionName } = options;
const isOr = isCohort ? cohortMatch === 'any' : filters.match === 'any';
const orClauses: string[] = [];
const andClauses: string[] = [];
filtersObjectToArray(filters, options).forEach(({ name, column, operator, paramName }) => {
if (isCohort) {
column = FILTER_COLUMNS[name.slice('cohort_'.length)];
}
if (column) {
if (name === 'eventType') {
arr.push(`and ${mapFilter(column, operator, name, 'UInt32')}`);
const isAlwaysAnd = name === 'eventType' || (isCohort && name === cohortActionName);
if (isAlwaysAnd) {
andClauses.push(
`and ${mapFilter(column, operator, name, name === 'eventType' ? 'UInt32' : 'String', paramName)}`,
);
} else if (isOr) {
orClauses.push(mapFilter(column, operator, name, 'String', paramName));
} else {
arr.push(`and ${mapFilter(column, operator, name)}`);
andClauses.push(`and ${mapFilter(column, operator, name, 'String', paramName)}`);
}
if (name === 'referrer') {
arr.push(`and referrer_domain != hostname`);
andClauses.push(`and referrer_domain != hostname`);
}
}
});
return arr;
}, []);
const parts: string[] = [];
return query.join('\n');
if (orClauses.length > 0) {
parts.push(`and (\n ${orClauses.join('\n or ')}\n)`);
}
parts.push(...andClauses);
return parts.join('\n');
}
function getCohortQuery(filters: Record<string, any>) {
@@ -118,7 +144,10 @@ function getCohortQuery(filters: Record<string, any>) {
return '';
}
const filterQuery = getFilterQuery(filters, { isCohort: true });
const cohortMatch = filters.cohort_match;
const cohortActionName = filters.cohort_actionName;
const filterQuery = getFilterQuery(filters, { isCohort: true, cohortMatch, cohortActionName });
return `join (
select distinct session_id
@@ -131,6 +160,25 @@ function getCohortQuery(filters: Record<string, any>) {
`;
}
function getExcludeBounceQuery(filters: Record<string, any>) {
if (!filters.excludeBounce === true) {
return '';
}
return `join
(select distinct session_id, visit_id
from website_event_stats_hourly
where website_id = {websiteId:UUID}
and created_at between {startDate:DateTime64} and {endDate:DateTime64}
and event_type = 1
group by session_id, visit_id
having sum(views) > 1
) excludeBounce
on excludeBounce.session_id = website_event.session_id
and excludeBounce.visit_id = website_event.visit_id
`;
}
function getDateQuery(filters: Record<string, any>) {
const { startDate, endDate, timezone } = filters;
@@ -154,10 +202,19 @@ function getDateQuery(filters: Record<string, any>) {
function getQueryParams(filters: Record<string, any>) {
return {
...filters,
...filtersObjectToArray(filters).reduce((obj, { name, value }) => {
if (name && value !== undefined) {
obj[name] = value;
}
...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value, paramName }) => {
const resolvedColumn =
column || (name?.startsWith('cohort_') && FILTER_COLUMNS[name.slice('cohort_'.length)]);
if (!resolvedColumn || !name || value === undefined) return obj;
const key = paramName ?? name;
obj[key] = ([OPERATORS.equals, OPERATORS.notEquals] as string[]).includes(operator)
? Array.isArray(value)
? value
: [value]
: value;
return obj;
}, {}),
@@ -174,6 +231,7 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
dateQuery: getDateQuery(filters),
queryParams: getQueryParams(filters),
cohortQuery: getCohortQuery(cohortFilters),
excludeBounceQuery: getExcludeBounceQuery(filters),
};
}
+33
View File
@@ -4,6 +4,7 @@ export const LOCALE_CONFIG = 'umami.locale';
export const TIMEZONE_CONFIG = 'umami.timezone';
export const DATE_RANGE_CONFIG = 'umami.date-range';
export const THEME_CONFIG = 'umami.theme';
export const CURRENCY_CONFIG = 'umami.currency';
export const DASHBOARD_CONFIG = 'umami.dashboard';
export const LAST_TEAM_CONFIG = 'umami.last-team';
export const VERSION_CHECK = 'umami.version-check';
@@ -25,6 +26,7 @@ export const DEFAULT_WEBSITE_LIMIT = 10;
export const DEFAULT_RESET_DATE = '2000-01-01';
export const DEFAULT_PAGE_SIZE = 20;
export const DEFAULT_DATE_COMPARE = 'prev';
export const DEFAULT_CURRENCY = 'USD';
export const REALTIME_RANGE = 30;
export const REALTIME_INTERVAL = 10000;
@@ -42,6 +44,11 @@ export const EVENT_COLUMNS = [
'event',
'tag',
'hostname',
'utmSource',
'utmMedium',
'utmCampaign',
'utmContent',
'utmTerm',
];
export const SESSION_COLUMNS = [
@@ -53,6 +60,7 @@ export const SESSION_COLUMNS = [
'country',
'city',
'region',
'distinctId',
];
export const SEGMENT_TYPES = {
@@ -67,6 +75,7 @@ export const FILTER_COLUMNS = {
referrer: 'referrer_domain',
domain: 'referrer_domain',
hostname: 'hostname',
distinctId: 'distinct_id',
title: 'page_title',
query: 'url_query',
os: 'os',
@@ -79,11 +88,25 @@ export const FILTER_COLUMNS = {
event: 'event_name',
tag: 'tag',
eventType: 'event_type',
utmSource: 'utm_source',
utmMedium: 'utm_medium',
utmCampaign: 'utm_campaign',
utmContent: 'utm_content',
utmTerm: 'utm_term',
};
export const COLLECTION_TYPE = {
event: 'event',
identify: 'identify',
performance: 'performance',
} as const;
export const WEB_VITALS_THRESHOLDS = {
lcp: { good: 2500, poor: 4000, unit: 'ms' },
inp: { good: 200, poor: 500, unit: 'ms' },
cls: { good: 0.1, poor: 0.25, unit: '' },
fcp: { good: 1800, poor: 3000, unit: 'ms' },
ttfb: { good: 800, poor: 1800, unit: 'ms' },
} as const;
export const EVENT_TYPE = {
@@ -91,6 +114,14 @@ export const EVENT_TYPE = {
customEvent: 2,
linkEvent: 3,
pixelEvent: 4,
performance: 5,
} as const;
export const ENTITY_TYPE = {
website: 1,
link: 2,
pixel: 3,
board: 4,
} as const;
export const DATA_TYPE = {
@@ -108,6 +139,8 @@ export const OPERATORS = {
notSet: 'ns',
contains: 'c',
doesNotContain: 'dnc',
regex: 're',
notRegex: 'nre',
true: 't',
false: 'f',
greaterThan: 'gt',
+13
View File
@@ -1,4 +1,5 @@
import crypto from 'node:crypto';
import { startOfDay, startOfMonth, startOfWeek } from 'date-fns';
import { v4, v5, v7 } from 'uuid';
const ALGORITHM = 'aes-256-gcm';
@@ -63,3 +64,15 @@ export function uuid(...args: any) {
return process.env.USE_UUIDV7 ? v7() : v4();
}
export function createAuthKey() {
return crypto.randomBytes(16).toString('hex');
}
export function getSalt(saltRotation: string, createdAt: Date): string {
return hash(
(saltRotation === 'day' ? startOfDay : saltRotation === 'week' ? startOfWeek : startOfMonth)(
createdAt,
).toUTCString(),
);
}
+24 -10
View File
@@ -9,6 +9,7 @@ import {
differenceInCalendarMonths,
differenceInCalendarWeeks,
differenceInCalendarYears,
differenceInDays,
differenceInHours,
differenceInMinutes,
endOfDay,
@@ -136,7 +137,12 @@ export function parseDateValue(value: string) {
return { num: +num, unit };
}
export function parseDateRange(value: string, locale = 'en-US', timezone?: string): DateRange {
export function parseDateRange(
value: string,
unitValue?: string,
locale = 'en-US',
timezone?: string,
): DateRange {
if (typeof value !== 'string') {
return null;
}
@@ -146,7 +152,7 @@ export function parseDateRange(value: string, locale = 'en-US', timezone?: strin
const startDate = new Date(+startTime);
const endDate = new Date(+endTime);
const unit = getMinimumUnit(startDate, endDate);
const unit = getMinimumUnit(startDate, endDate, true);
return {
startDate,
@@ -169,14 +175,14 @@ export function parseDateRange(value: string, locale = 'en-US', timezone?: strin
endDate: endOfHour(now),
offset: 0,
num: num || 1,
unit,
unit: unitValue || unit,
value,
};
case 'day':
return {
startDate: num ? subDays(startOfDay(now), num) : startOfDay(now),
endDate: endOfDay(now),
unit: num ? 'day' : 'hour',
unit: unitValue ? unitValue : num ? 'day' : 'hour',
offset: 0,
num: num || 1,
value,
@@ -187,7 +193,7 @@ export function parseDateRange(value: string, locale = 'en-US', timezone?: strin
? subWeeks(startOfWeek(now, { locale: dateLocale }), num)
: startOfWeek(now, { locale: dateLocale }),
endDate: endOfWeek(now, { locale: dateLocale }),
unit: 'day',
unit: unitValue || 'day',
offset: 0,
num: num || 1,
value,
@@ -196,7 +202,7 @@ export function parseDateRange(value: string, locale = 'en-US', timezone?: strin
return {
startDate: num ? subMonths(startOfMonth(now), num) : startOfMonth(now),
endDate: endOfMonth(now),
unit: num ? 'month' : 'day',
unit: unitValue ? unitValue : num ? 'month' : 'day',
offset: 0,
num: num || 1,
value,
@@ -205,7 +211,7 @@ export function parseDateRange(value: string, locale = 'en-US', timezone?: strin
return {
startDate: num ? subYears(startOfYear(now), num) : startOfYear(now),
endDate: endOfYear(now),
unit: 'month',
unit: unitValue || 'month',
offset: 0,
num: num || 1,
value,
@@ -273,12 +279,20 @@ export function getAllowedUnits(startDate: Date, endDate: Date) {
return index >= 0 ? units.splice(index) : [];
}
export function getMinimumUnit(startDate: number | Date, endDate: number | Date) {
export function getMinimumUnit(
startDate: number | Date,
endDate: number | Date,
isDateRange: boolean = false,
) {
if (differenceInMinutes(endDate, startDate) <= 60) {
return 'minute';
} else if (differenceInHours(endDate, startDate) <= 48) {
} else if (
isDateRange
? differenceInHours(endDate, startDate) <= 48
: differenceInDays(endDate, startDate) <= 30
) {
return 'hour';
} else if (differenceInCalendarMonths(endDate, startDate) <= 6) {
} else if (differenceInCalendarMonths(endDate, startDate) <= 7) {
return 'day';
} else if (differenceInCalendarMonths(endDate, startDate) <= 24) {
return 'month';
+18 -2
View File
@@ -10,6 +10,16 @@ import { safeDecodeURIComponent } from '@/lib/url';
const MAXMIND = 'maxmind';
const PROVIDER_HEADERS = [
// Umami custom headers (cloud mode only)
...(process.env.CLOUD_MODE
? [
{
countryHeader: 'x-umami-client-country',
regionHeader: 'x-umami-client-region',
cityHeader: 'x-umami-client-city',
},
]
: []),
// Cloudflare headers
{
countryHeader: 'cf-ipcountry',
@@ -28,6 +38,12 @@ const PROVIDER_HEADERS = [
regionHeader: 'cloudfront-viewer-country-region',
cityHeader: 'cloudfront-viewer-city',
},
// EdgeOne headers (requires custom request headers in Rule Priorities, see: https://edgeone.ai/document/46151)
{
countryHeader: 'eo-ipcountry',
regionHeader: 'eo-region-code',
cityHeader: 'eo-ipcity',
},
];
export function getDevice(userAgent: string, screen: string = '') {
@@ -60,13 +76,13 @@ function decodeHeader(s: string | undefined | null): string | undefined | null {
return Buffer.from(s, 'latin1').toString('utf-8');
}
export async function getLocation(ip: string = '', headers: Headers, hasPayloadIP: boolean) {
export async function getLocation(ip: string = '', headers: Headers, skipHeaders: boolean) {
// Ignore local ips
if (!ip || (await isLocalhost(ip))) {
return null;
}
if (!hasPayloadIP && !process.env.SKIP_LOCATION_HEADERS) {
if (!skipHeaders && !process.env.SKIP_LOCATION_HEADERS) {
for (const provider of PROVIDER_HEADERS) {
const countryHeader = headers.get(provider.countryHeader);
if (countryHeader) {
+15
View File
@@ -0,0 +1,15 @@
import type { Board, Link, Pixel, Website } from '@/generated/prisma/client';
import { getBoard, getLink, getPixel, getWebsite } from '@/queries/prisma';
export async function getEntity(entityId: string): Promise<Website | Link | Pixel | Board | null> {
const [website, link, pixel, board] = await Promise.all([
getWebsite(entityId),
getLink(entityId),
getPixel(entityId),
getBoard(entityId),
]);
const entity = website || link || pixel || board;
return entity;
}
+3 -1
View File
@@ -1,3 +1,5 @@
import { DEFAULT_CURRENCY } from './constants';
export function parseTime(val: number) {
const days = ~~(val / 86400);
const hours = ~~(val / 3600) - days * 24;
@@ -94,7 +96,7 @@ export function formatCurrency(value: number, currency: string, locale = 'en-US'
// Fallback to default currency format if an error occurs
formattedValue = new Intl.NumberFormat(locale, {
style: 'currency',
currency: 'USD',
currency: DEFAULT_CURRENCY,
});
}
+64 -9
View File
@@ -1,4 +1,7 @@
import ipaddr from 'ipaddr.js';
export const IP_ADDRESS_HEADERS = [
...(process.env.CLOUD_MODE ? ['x-umami-client-ip'] : []), // Umami custom header (cloud mode only)
'true-client-ip', // CDN
'cf-connecting-ip', // Cloudflare
'fastly-client-ip', // Fastly
@@ -13,35 +16,87 @@ export const IP_ADDRESS_HEADERS = [
'x-forwarded',
];
/**
* Normalize IP strings to a canonical form:
* - strips IPv4-mapped IPv6 (e.g. ::ffff:192.0.2.1 -> 192.0.2.1)
* - keeps valid IPv4/IPv6 as-is (canonically formatted by ipaddr.js)
*/
function normalizeIp(ip?: string | null) {
if (!ip) return ip;
try {
const parsed = ipaddr.parse(ip);
if (parsed.kind() === 'ipv6' && (parsed as ipaddr.IPv6).isIPv4MappedAddress()) {
return (parsed as ipaddr.IPv6).toIPv4Address().toString();
}
return parsed.toString();
} catch {
// Fallback: return original if parsing fails
return ip;
}
}
function resolveIp(ip?: string | null) {
if (!ip) return ip;
// First, try as-is
const normalized = normalizeIp(ip);
try {
ipaddr.parse(normalized);
return normalized;
} catch {
// try stripping port (handles IPv4:port; leaves IPv6 intact)
const stripped = stripPort(ip);
if (stripped !== ip) {
const normalizedStripped = normalizeIp(stripped);
try {
ipaddr.parse(normalizedStripped);
return normalizedStripped;
} catch {
return normalizedStripped;
}
}
return normalized;
}
}
export function getIpAddress(headers: Headers) {
const customHeader = process.env.CLIENT_IP_HEADER;
if (customHeader && headers.get(customHeader)) {
return headers.get(customHeader);
return resolveIp(headers.get(customHeader));
}
const header = IP_ADDRESS_HEADERS.find(name => {
return headers.get(name);
});
const header = IP_ADDRESS_HEADERS.find(name => headers.get(name));
if (!header) {
return undefined;
}
const ip = headers.get(header);
if (header === 'x-forwarded-for') {
return ip?.split(',')?.[0]?.trim();
return resolveIp(ip?.split(',')?.[0]?.trim());
}
if (header === 'forwarded') {
const match = ip.match(/for=(\[?[0-9a-fA-F:.]+\]?)/);
const match = ip.match(/for=(\[?[0-9a-fA-F:.]+]?)/);
if (match) {
return match[1];
return resolveIp(match[1]);
}
}
return ip;
return resolveIp(ip);
}
export function stripPort(ip: string) {
export function stripPort(ip?: string | null) {
if (!ip) {
return ip;
}
if (ip.startsWith('[')) {
const endBracket = ip.indexOf(']');
if (endBracket !== -1) {
+6
View File
@@ -38,3 +38,9 @@ export async function fetchSession(websiteId: string, sessionId: string): Promis
return session;
}
export async function fetchAccount(userId: string) {
const account = await redis.client.get(`account:${userId}`);
return account;
}
+35 -7
View File
@@ -9,10 +9,21 @@ export function parseFilterValue(param: any) {
const [, operator, value] = param.match(regex) || [];
return { operator: operator || OPERATORS.equals, value: value || param };
const resolvedOperator = operator || OPERATORS.equals;
const resolvedValue = value ?? param;
if (resolvedOperator === OPERATORS.equals || resolvedOperator === OPERATORS.notEquals) {
return { operator: resolvedOperator, value: resolvedValue.split(',') };
}
return { operator: resolvedOperator, value: resolvedValue };
}
return { operator: OPERATORS.equals, value: param };
if (Array.isArray(param)) {
return { operator: OPERATORS.equals, value: param };
}
return { operator: OPERATORS.equals, value: [param] };
}
export function isEqualsOperator(operator: any) {
@@ -20,7 +31,12 @@ export function isEqualsOperator(operator: any) {
}
export function isSearchOperator(operator: any) {
return [OPERATORS.contains, OPERATORS.doesNotContain].includes(operator);
return [
OPERATORS.contains,
OPERATORS.doesNotContain,
OPERATORS.regex,
OPERATORS.notRegex,
].includes(operator);
}
export function filtersObjectToArray(filters: QueryFilters, options: QueryOptions = {}): Filter[] {
@@ -35,15 +51,23 @@ export function filtersObjectToArray(filters: QueryFilters, options: QueryOption
return arr;
}
const baseName = key.replace(/\d+$/, '');
const paramName = key !== baseName ? key : undefined;
if (filter?.name && filter?.value !== undefined) {
return arr.concat({ ...filter, column: options?.columns?.[key] ?? FILTER_COLUMNS[key] });
return arr.concat({
...filter,
column: options?.columns?.[baseName] ?? FILTER_COLUMNS[baseName],
paramName: paramName ?? filter.paramName,
});
}
const { operator, value } = parseFilterValue(filter);
return arr.concat({
name: key,
column: options?.columns?.[key] ?? FILTER_COLUMNS[key],
name: baseName,
paramName,
column: options?.columns?.[baseName] ?? FILTER_COLUMNS[baseName],
operator,
value,
prefix: options?.prefix,
@@ -52,10 +76,14 @@ export function filtersObjectToArray(filters: QueryFilters, options: QueryOption
}
export function filtersArrayToObject(filters: Filter[]) {
const nameCounts: Record<string, number> = {};
return filters.reduce((obj, filter: Filter) => {
const { name, operator, value } = filter;
const count = nameCounts[name] ?? 0;
const key = count === 0 ? name : `${name}${count}`;
nameCounts[name] = count + 1;
obj[name] = `${operator}.${value}`;
obj[key] = `${operator}.${Array.isArray(value) ? value.join(',') : value}`;
return obj;
}, {});
+93 -24
View File
@@ -71,48 +71,82 @@ function getSearchSQL(column: string, param: string = 'search'): string {
return `and ${column} ilike {{${param}}}`;
}
function mapFilter(column: string, operator: string, name: string, type: string = '') {
const value = `{{${name}${type ? `::${type}` : ''}}}`;
function mapFilter(
column: string,
operator: string,
name: string,
type: string = '',
paramName?: string,
) {
const param = paramName ?? name;
const value = `{{${param}${type ? `::${type}` : ''}}}`;
if (name.startsWith('cohort_')) {
name = name.slice('cohort_'.length);
}
const table = SESSION_COLUMNS.includes(name) ? 'session' : 'website_event';
switch (operator) {
case OPERATORS.equals:
return `${column} = ${value}`;
return `${table}.${column} = ANY(${value})`;
case OPERATORS.notEquals:
return `${column} != ${value}`;
return `${table}.${column} != ALL(${value})`;
case OPERATORS.contains:
return `${column} ilike ${value}`;
return `${table}.${column} ilike ${value}`;
case OPERATORS.doesNotContain:
return `${column} not ilike ${value}`;
return `${table}.${column} not ilike ${value}`;
case OPERATORS.regex:
return `${table}.${column} ~ ${value}`;
case OPERATORS.notRegex:
return `${table}.${column} !~ ${value}`;
default:
return '';
}
}
function getFilterQuery(filters: Record<string, any>, options: QueryOptions = {}): string {
const query = filtersObjectToArray(filters, options).reduce(
(arr, { name, column, operator, prefix = '' }) => {
const isCohort = options?.isCohort;
const { isCohort, cohortMatch, cohortActionName } = options;
const isOr = isCohort ? cohortMatch === 'any' : filters.match === 'any';
const orClauses: string[] = [];
const andClauses: string[] = [];
filtersObjectToArray(filters, options).forEach(
({ name, column, operator, prefix = '', paramName }) => {
if (isCohort) {
column = FILTER_COLUMNS[name.slice('cohort_'.length)];
}
if (column) {
arr.push(`and ${mapFilter(`${prefix}${column}`, operator, name)}`);
const clause = mapFilter(`${prefix}${column}`, operator, name, '', paramName);
const isAlwaysAnd = name === 'eventType' || (isCohort && name === cohortActionName);
if (isAlwaysAnd) {
andClauses.push(`and ${clause}`);
} else if (isOr) {
orClauses.push(clause);
} else {
andClauses.push(`and ${clause}`);
}
if (name === 'referrer') {
arr.push(
`and (website_event.referrer_domain != website_event.hostname or website_event.referrer_domain is null)`,
andClauses.push(
`and (website_event.referrer_domain != regexp_replace(website_event.hostname, '^www.', '') or website_event.referrer_domain is null)`,
);
}
}
return arr;
},
[],
);
return query.join('\n');
const parts: string[] = [];
if (orClauses.length > 0) {
parts.push(`and (\n ${orClauses.join('\n or ')}\n)`);
}
parts.push(...andClauses);
return parts.join('\n');
}
function getCohortQuery(filters: QueryFilters = {}) {
@@ -120,7 +154,10 @@ function getCohortQuery(filters: QueryFilters = {}) {
return '';
}
const filterQuery = getFilterQuery(filters, { isCohort: true });
const cohortMatch = (filters as any).cohort_match;
const cohortActionName = (filters as any).cohort_actionName;
const filterQuery = getFilterQuery(filters, { isCohort: true, cohortMatch, cohortActionName });
return `join
(select distinct website_event.session_id
@@ -135,6 +172,25 @@ function getCohortQuery(filters: QueryFilters = {}) {
`;
}
function getExcludeBounceQuery(filters: Record<string, any>) {
if (!filters.excludeBounce === true) {
return '';
}
return `join
(select distinct session_id, visit_id
from website_event
where website_id = {{websiteId}}
and created_at between {{startDate}} and {{endDate}}
and event_type = 1
group by session_id, visit_id
having count(*) > 1
) excludeBounce
on excludeBounce.session_id = website_event.session_id
and excludeBounce.visit_id = website_event.visit_id
`;
}
function getDateQuery(filters: Record<string, any>) {
const { startDate, endDate } = filters;
@@ -152,10 +208,21 @@ function getDateQuery(filters: Record<string, any>) {
function getQueryParams(filters: Record<string, any>) {
return {
...filters,
...filtersObjectToArray(filters).reduce((obj, { name, operator, value }) => {
obj[name] = ([OPERATORS.contains, OPERATORS.doesNotContain] as Operator[]).includes(operator)
? `%${value}%`
: value;
...filtersObjectToArray(filters).reduce((obj, { name, column, operator, value, paramName }) => {
const resolvedColumn =
column || (name?.startsWith('cohort_') && FILTER_COLUMNS[name.slice('cohort_'.length)]);
if (!resolvedColumn) return obj;
const key = paramName ?? name;
if (([OPERATORS.contains, OPERATORS.doesNotContain] as Operator[]).includes(operator)) {
obj[key] = `%${value}%`;
} else if (([OPERATORS.equals, OPERATORS.notEquals] as Operator[]).includes(operator)) {
obj[key] = Array.isArray(value) ? value : [value];
} else {
obj[key] = value;
}
return obj;
}, {}),
@@ -163,9 +230,10 @@ function getQueryParams(filters: Record<string, any>) {
}
function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
const joinSession = Object.keys(filters).find(key =>
['referrer', ...SESSION_COLUMNS].includes(key),
);
const joinSession = Object.keys(filters).find(key => {
const baseName = key.replace(/\d+$/, '');
return ['referrer', ...SESSION_COLUMNS].includes(baseName);
});
const cohortFilters = Object.fromEntries(
Object.entries(filters).filter(([key]) => key.startsWith('cohort_')),
@@ -180,6 +248,7 @@ function parseFilters(filters: Record<string, any>, options?: QueryOptions) {
filterQuery: getFilterQuery(filters, options),
queryParams: getQueryParams(filters),
cohortQuery: getCohortQuery(cohortFilters),
excludeBounceQuery: getExcludeBounceQuery(filters),
};
}
+138 -3
View File
@@ -1,10 +1,145 @@
import { UmamiRedisClient } from '@umami/redis-client';
import debug from 'debug';
import { createClient, type RedisClientType } from 'redis';
const log = debug('umami:redis-client');
export const DELETED = '__DELETED__';
export const DEFAULT_TTL = 3600;
const logError = (err: unknown) => log(err);
class UmamiRedisClient {
url: string;
client: RedisClientType;
isConnected: boolean;
constructor(url: string) {
const client = createClient({ url }).on('error', logError);
this.url = url;
this.client = client as RedisClientType;
this.isConnected = false;
}
async connect() {
if (!this.isConnected) {
this.isConnected = true;
await this.client.connect();
log('Redis connected');
}
}
async get(key: string) {
await this.connect();
const data = await this.client.get(key);
try {
return JSON.parse(data as string);
} catch {
return null;
}
}
async set(key: string, value: any, time?: number) {
await this.connect();
const ttl = time && time > 0 ? time : DEFAULT_TTL;
return this.client.set(key, JSON.stringify(value), { EX: ttl });
}
async del(key: string) {
await this.connect();
return this.client.del(key);
}
async incr(key: string) {
await this.connect();
return this.client.incr(key);
}
async expire(key: string, seconds: number) {
await this.connect();
return this.client.expire(key, seconds);
}
async rateLimit(key: string, limit: number, seconds: number): Promise<boolean> {
await this.connect();
const res = await this.client.incr(key);
if (res === 1) {
await this.client.expire(key, seconds);
}
return res >= limit;
}
async fetch(key: string, query: () => Promise<any>, time?: number) {
const result = await this.get(key);
if (result === DELETED) return null;
if (!result && query) {
const data = await query();
if (data) {
await this.set(key, data, time);
}
return data;
}
return result;
}
async remove(key: string, soft = false) {
return soft ? this.set(key, DELETED) : this.del(key);
}
}
const REDIS = 'redis';
const enabled = !!process.env.REDIS_URL;
function getClient() {
const redis = new UmamiRedisClient({ url: process.env.REDIS_URL });
const redis = new UmamiRedisClient(process.env.REDIS_URL);
const originalConnect = redis.connect.bind(redis);
let connectPromise: Promise<void> | null = null;
const resetConnectionState = () => {
redis.isConnected = false;
};
redis.client.on('end', resetConnectionState);
redis.client.on('reconnecting', resetConnectionState);
redis.connect = async () => {
if (redis.client.isReady || redis.client.isOpen) {
redis.isConnected = true;
return;
}
if (connectPromise) {
return connectPromise;
}
connectPromise = (async () => {
try {
await originalConnect();
} catch (error) {
redis.isConnected = false;
throw error;
} finally {
connectPromise = null;
}
})();
return connectPromise;
};
if (process.env.NODE_ENV !== 'production') {
globalThis[REDIS] = redis;
@@ -13,6 +148,6 @@ function getClient() {
return redis;
}
const client = globalThis[REDIS] || getClient();
const client: UmamiRedisClient = globalThis[REDIS] || getClient();
export default { client, enabled };
+41 -8
View File
@@ -1,8 +1,9 @@
import { startOfMonth, subMonths } from 'date-fns';
import { z } from 'zod';
import { checkAuth } from '@/lib/auth';
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS } from '@/lib/constants';
import { DEFAULT_PAGE_SIZE, FILTER_COLUMNS, OPERATORS } from '@/lib/constants';
import { getAllowedUnits, getMinimumUnit, maxDate, parseDateRange } from '@/lib/date';
import { fetchWebsite } from '@/lib/load';
import { fetchAccount, fetchWebsite } from '@/lib/load';
import { filtersArrayToObject } from '@/lib/params';
import { badRequest, unauthorized } from '@/lib/response';
import type { QueryFilters } from '@/lib/types';
@@ -16,17 +17,25 @@ export async function parseRequest(
const url = new URL(request.url);
let query = Object.fromEntries(url.searchParams);
let body = await getJsonBody(request);
let error: () => undefined | undefined;
let error: () => undefined | undefined | Response;
let auth = null;
if (schema) {
const isGet = request.method === 'GET';
const rawQuery = query;
const result = schema.safeParse(isGet ? query : body);
if (!result.success) {
error = () => badRequest(z.treeifyError(result.error));
} else if (isGet) {
query = result.data;
// Re-add suffixed filter params (e.g., browser1, os2) stripped by Zod schema
for (const key of Object.keys(rawQuery)) {
if (/\d+$/.test(key) && !(key in query)) {
query[key] = rawQuery[key];
}
}
} else {
body = result.data;
}
@@ -70,10 +79,10 @@ export function getRequestDateRange(query: Record<string, string>) {
export function getRequestFilters(query: Record<string, any>) {
const result: Record<string, any> = {};
for (const key of Object.keys(FILTER_COLUMNS)) {
const value = query[key];
if (value !== undefined) {
result[key] = value;
for (const key of Object.keys(query)) {
const baseName = key.replace(/\d+$/, '');
if (baseName in FILTER_COLUMNS) {
result[key] = query[key];
}
}
@@ -82,6 +91,15 @@ export function getRequestFilters(query: Record<string, any>) {
export async function setWebsiteDate(websiteId: string, data: Record<string, any>) {
const website = await fetchWebsite(websiteId);
const cloudMode = !!process.env.CLOUD_MODE;
if (cloudMode && website && !website.teamId) {
const account = await fetchAccount(website.userId);
if (!account?.hasSubscription) {
data.startDate = maxDate(data.startDate, startOfMonth(subMonths(new Date(), 6)));
}
}
if (website?.resetAt) {
data.startDate = maxDate(data.startDate, new Date(website?.resetAt));
@@ -97,6 +115,8 @@ export async function getQueryFilters(
const dateRange = getRequestDateRange(params);
const filters = getRequestFilters(params);
let match = params?.match;
if (websiteId) {
await setWebsiteDate(websiteId, dateRange);
@@ -105,6 +125,10 @@ export async function getQueryFilters(
?.parameters as Record<string, any>;
Object.assign(filters, filtersArrayToObject(segmentParams.filters));
if (segmentParams.match) {
match = segmentParams.match;
}
}
if (params.cohort) {
@@ -120,7 +144,7 @@ export async function getQueryFilters(
cohortFilters.push({
name: `cohort_${cohortParams.action.type}`,
operator: 'eq',
operator: OPERATORS.equals,
value: cohortParams.action.value,
});
@@ -128,13 +152,22 @@ export async function getQueryFilters(
...filtersArrayToObject(cohortFilters),
cohort_startDate: startDate,
cohort_endDate: endDate,
...(cohortParams.match && {
cohort_match: cohortParams.match,
cohort_actionName: `cohort_${cohortParams.action.type}`,
}),
});
}
if (params.excludeBounce) {
Object.assign(filters, { excludeBounce: true });
}
}
return {
...dateRange,
...filters,
match,
page: params?.page,
pageSize: params?.pageSize ? params?.pageSize || DEFAULT_PAGE_SIZE : undefined,
orderBy: params?.orderBy,
+91 -3
View File
@@ -20,9 +20,28 @@ export const dateRangeParams = {
endDate: z.coerce.date().optional(),
timezone: timezoneParam.optional(),
unit: unitParam.optional(),
compare: z.string().optional(),
compare: z.enum(['prev', 'yoy']).optional(),
};
export function withDateRange<T extends z.ZodRawShape>(shape?: T) {
return z
.object({
...dateRangeParams,
...shape,
})
.superRefine((data: Record<string, unknown>, ctx) => {
const hasTimestamps = data.startAt != null && data.endAt != null;
const hasDates = data.startDate != null && data.endDate != null;
if (!hasTimestamps && !hasDates) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: 'Either startAt+endAt or startDate+endDate must be provided',
});
}
});
}
export const filterParams = {
path: z.string().optional(),
referrer: z.string().optional(),
@@ -36,11 +55,19 @@ export const filterParams = {
city: z.string().optional(),
tag: z.string().optional(),
hostname: z.string().optional(),
distinctId: z.string().optional(),
language: z.string().optional(),
event: z.string().optional(),
utmSource: z.string().optional(),
utmMedium: z.string().optional(),
utmCampaign: z.string().optional(),
utmContent: z.string().optional(),
utmTerm: z.string().optional(),
segment: z.uuid().optional(),
cohort: z.uuid().optional(),
eventType: z.coerce.number().int().positive().optional(),
excludeBounce: z.string().optional(),
match: z.enum(['all', 'any']).optional(),
};
export const searchParams = {
@@ -89,8 +116,14 @@ export const fieldsParam = z.enum([
'city',
'tag',
'hostname',
'distinctId',
'language',
'event',
'utmSource',
'utmMedium',
'utmCampaign',
'utmContent',
'utmTerm',
]);
export const reportTypeParam = z.enum([
@@ -99,11 +132,31 @@ export const reportTypeParam = z.enum([
'funnel',
'goal',
'journey',
'performance',
'retention',
'revenue',
'utm',
]);
export const operatorParam = z.enum([
'eq',
'neq',
's',
'ns',
'c',
'dnc',
're',
'nre',
't',
'f',
'gt',
'lt',
'gte',
'lte',
'bf',
'af',
]);
export const goalReportSchema = z.object({
type: z.literal('goal'),
parameters: z
@@ -149,6 +202,7 @@ export const journeyReportSchema = z.object({
steps: z.coerce.number().min(2).max(7),
startStep: z.string().optional(),
endStep: z.string().optional(),
eventType: z.coerce.number().int().positive().optional(),
}),
});
@@ -157,7 +211,7 @@ export const retentionReportSchema = z.object({
parameters: z.object({
startDate: z.coerce.date(),
endDate: z.coerce.date(),
timezone: z.string().optional(),
timezone: timezoneParam.optional(),
}),
});
@@ -169,13 +223,26 @@ export const utmReportSchema = z.object({
}),
});
export const performanceReportSchema = z.object({
type: z.literal('performance'),
parameters: z.object({
startDate: z.coerce.date(),
endDate: z.coerce.date(),
unit: unitParam.optional(),
timezone: timezoneParam.optional(),
metric: z.enum(['lcp', 'inp', 'cls', 'fcp', 'ttfb']).optional(),
}),
});
export const revenueReportSchema = z.object({
type: z.literal('revenue'),
parameters: z.object({
startDate: z.coerce.date(),
endDate: z.coerce.date(),
timezone: z.string().optional(),
unit: unitParam.optional(),
timezone: timezoneParam.optional(),
currency: z.string(),
compare: z.enum(['prev', 'yoy']).optional(),
}),
});
@@ -212,6 +279,7 @@ export const reportTypeSchema = z.discriminatedUnion('type', [
goalReportSchema,
funnelReportSchema,
journeyReportSchema,
performanceReportSchema,
retentionReportSchema,
utmReportSchema,
revenueReportSchema,
@@ -230,3 +298,23 @@ export const reportResultSchema = z.intersection(
);
export const segmentTypeParam = z.enum(['segment', 'cohort']);
export const segmentParamSchema = z.object({
filters: z
.array(
z.object({
name: z.string(),
operator: operatorParam,
value: z.string(),
}),
)
.optional(),
match: z.enum(['all', 'any']).optional(),
dateRange: z.string().optional(),
action: z
.object({
type: z.string(),
value: z.string(),
})
.optional(),
});
+51 -2
View File
@@ -1,4 +1,5 @@
import type { UseQueryOptions } from '@tanstack/react-query';
import type { Board as PrismaBoard } from '@/generated/prisma/client';
import type { DATA_TYPE, OPERATORS, ROLES } from './constants';
import type { TIME_UNIT } from './date';
@@ -19,17 +20,22 @@ export interface Auth {
isAdmin: boolean;
};
shareToken?: {
websiteId: string;
websiteId?: string;
websiteIds?: string[];
boardId?: string;
pixelId?: string;
linkId?: string;
};
}
export interface Filter {
name: string;
operator: Operator;
value: string;
value: string | string[];
type?: string;
column?: string;
prefix?: string;
paramName?: string;
}
export interface DateRange {
@@ -51,6 +57,8 @@ export interface QueryOptions {
limit?: number;
prefix?: string;
isCohort?: boolean;
cohortMatch?: string;
cohortActionName?: string;
}
export interface QueryFilters
@@ -90,6 +98,8 @@ export interface FilterParams {
segment?: string;
cohort?: string;
compare?: string;
excludeBounce?: boolean;
match?: 'all' | 'any';
}
export interface SortParams {
@@ -141,3 +151,42 @@ export interface ApiError extends Error {
code?: string;
message: string;
}
export interface BoardComponentConfig {
type: string;
entityType?: 'website' | 'pixel' | 'link';
entityId?: string;
websiteId?: string;
title?: string;
description?: string;
props?: Record<string, any>;
}
export interface BoardColumn {
id: string;
component?: BoardComponentConfig;
size?: number;
}
export interface BoardRow {
id: string;
columns: BoardColumn[];
size?: number;
}
export interface BoardParameters {
websiteId?: string;
pixelId?: string;
linkId?: string;
rows?: BoardRow[];
}
export interface Board extends Omit<PrismaBoard, 'parameters'> {
parameters: BoardParameters;
}
export interface WhiteLabel {
displayName: string;
domainName: string;
logoUrl: string;
}