fix: harden analytics writes and hide internal server errors from client

This commit is contained in:
Francis Cao committed 2026-06-22 22:07:07 -07:00
1 parent 770b4d59d2
commit 129681ebd7
15 files changed
+217 -128

No files matched your search

+20 -6
View File
@@ -268,12 +268,26 @@ export const SHARE_ID_REGEX = /^[a-zA-Z0-9]{8,50}$/;
export const DATETIME_REGEX =
/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3})?(Z|\+[0-9]{2}:[0-9]{2})?$/;
export const URL_LENGTH = 500;
export const PAGE_TITLE_LENGTH = 500;
export const EVENT_NAME_LENGTH = 50;
export const TAG_LENGTH = 50;
export const HOSTNAME_LENGTH = 100;
export const FIELD_VALUE_LENGTH = 255;
export const FIELD_LENGTH = {
browser: 20,
os: 20,
device: 20,
screen: 11,
language: 35,
country: 2,
region: 20,
city: 50,
distinctId: 50,
url: 500,
pageTitle: 500,
eventName: 50,
tag: 50,
hostname: 100,
fieldValue: 255,
dataKey: 500,
stringValue: 500,
currency: 10,
} as const;
export const UTM_PARAMS = ['utm_campaign', 'utm_content', 'utm_medium', 'utm_source', 'utm_term'];
+17
View File
@@ -0,0 +1,17 @@
import { describe, expect, test } from 'vitest';
import { DATA_TYPE, FIELD_LENGTH } from './constants';
import { getStoredStringValue } from './data';
describe('getStoredStringValue', () => {
test('truncates oversized string values to the storage limit', () => {
expect(getStoredStringValue('x'.repeat(FIELD_LENGTH.stringValue + 25), DATA_TYPE.string)).toHaveLength(
FIELD_LENGTH.stringValue,
);
});
test('drops oversized array payloads instead of storing invalid truncated JSON', () => {
const oversizedArray = JSON.stringify([`x${'y'.repeat(FIELD_LENGTH.stringValue)}`]);
expect(getStoredStringValue(oversizedArray, DATA_TYPE.array)).toBeNull();
});
});
+12 -1
View File
@@ -1,4 +1,5 @@
import { DATA_TYPE, DATETIME_REGEX } from './constants';
import { DATA_TYPE, DATETIME_REGEX, FIELD_LENGTH } from './constants';
import { truncateString } from './format';
import type { DynamicDataType } from './types';
export interface KeyValueData {
@@ -49,6 +50,16 @@ export function getStringValue(value: string, dataType: number) {
return value;
}
export function getStoredStringValue(value: string, dataType: number) {
const stringValue = getStringValue(value, dataType);
if (dataType === DATA_TYPE.array && stringValue.length > FIELD_LENGTH.stringValue) {
return null;
}
return truncateString(stringValue, FIELD_LENGTH.stringValue);
}
export function createKeyValue(key: string, value: any): KeyValueData {
const type = getDataType(value);
let dataType: DynamicDataType;
+5
View File
@@ -37,3 +37,8 @@ test('stringToColor', () => {
expect(format.stringToColor('hello')).toBe('#d218e9');
expect(format.stringToColor('goodbye')).toBe('#11e956');
});
test('truncateString', () => {
expect(format.truncateString('hello', 3)).toBe('hel');
expect(format.truncateString(undefined, 3)).toBeUndefined();
});
+7
View File
@@ -118,3 +118,10 @@ export function formatLongCurrency(value: number, currency: string, locale = 'en
return formatCurrency(n, currency, locale);
}
export function truncateString<T extends string | null | undefined>(
value: T,
maxLength: number,
): T extends string ? string : T {
return (value ? value.substring(0, maxLength) : value) as T extends string ? string : T;
}
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, test, vi } from 'vitest';
import { serverError } from './response';
describe('serverError', () => {
test('does not expose internal error details in the response body', async () => {
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const response = serverError(new Error('database exploded'));
expect(await response.json()).toEqual({
error: {
message: 'Server error',
code: 'server-error',
status: 500,
},
});
logSpy.mockRestore();
});
test('allows intentional server error messages', async () => {
const response = serverError('Redis is disabled');
expect(await response.json()).toEqual({
error: {
message: 'Redis is disabled',
code: 'server-error',
status: 500,
},
});
});
});
+9 -3
View File
@@ -1,3 +1,5 @@
import { serializeError } from 'serialize-error';
export function ok() {
return Response.json({ ok: true });
}
@@ -52,14 +54,18 @@ export function notFound(error?: Record<string, any>) {
);
}
export function serverError(error?: Record<string, any>) {
export function serverError(error?: unknown) {
if (error && typeof error !== 'string') {
// eslint-disable-next-line no-console
console.log(serializeError(error));
}
return Response.json(
{
error: {
message: 'Server error',
message: typeof error === 'string' ? error : 'Server error',
code: 'server-error',
status: 500,
...error,
},
},
{ status: 500 },