Skip to content

Commit 25183b9

Browse files
committed
fix(ccusage): harden adapter date keys
Reject impossible calendar date filters before they reach range filtering so invalid CLI input cannot silently produce wrong reports. Build daily and monthly adapter keys from Intl formatToParts instead of parsing locale display strings. This keeps the existing timezone-aware Intl behavior while making machine-readable grouping keys independent of runtime date formatting patterns.
1 parent 2ea3cfc commit 25183b9

1 file changed

Lines changed: 77 additions & 8 deletions

File tree

‎apps/ccusage/src/adapter/shared.ts‎

Lines changed: 77 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,15 +21,28 @@ export function normalizeDateFilter(value: string | undefined): string | undefin
2121
if (value == null || value === '') {
2222
return undefined;
2323
}
24-
if (/^\d{8}$/u.test(value)) {
25-
return `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`;
26-
}
27-
if (/^\d{4}-\d{2}-\d{2}$/u.test(value)) {
28-
return value;
24+
const normalized = /^\d{8}$/u.test(value)
25+
? `${value.slice(0, 4)}-${value.slice(4, 6)}-${value.slice(6, 8)}`
26+
: /^\d{4}-\d{2}-\d{2}$/u.test(value)
27+
? value
28+
: undefined;
29+
if (normalized != null && isValidCalendarDate(normalized)) {
30+
return normalized;
2931
}
3032
throw new Error(`Invalid date: ${value}. Use YYYY-MM-DD or YYYYMMDD.`);
3133
}
3234

35+
function isValidCalendarDate(value: string): boolean {
36+
const [year, month, day] = value.split('-').map(Number);
37+
if (year == null || month == null || day == null) {
38+
return false;
39+
}
40+
const date = new Date(Date.UTC(year, month - 1, day));
41+
return (
42+
date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
43+
);
44+
}
45+
3346
export function toCompactDate(value: string | undefined): string | undefined {
3447
return value?.replaceAll('-', '');
3548
}
@@ -122,7 +135,13 @@ function getDateTimeFormatter(timezone: string): Intl.DateTimeFormat {
122135

123136
export function formatDateKey(timestamp: string, timezone?: string): string {
124137
const tz = safeTimeZone(timezone);
125-
const formatted = getDateFormatter(tz).format(new Date(timestamp));
138+
const date = new Date(timestamp);
139+
const formatter = getDateFormatter(tz);
140+
const formatted = [
141+
getDatePart(formatter, date, 'year'),
142+
getDatePart(formatter, date, 'month'),
143+
getDatePart(formatter, date, 'day'),
144+
].join('-');
126145
const cacheKey = `${tz}:${formatted}`;
127146
const cached = dateKeyCache.get(cacheKey);
128147
if (cached != null) {
@@ -135,8 +154,12 @@ export function formatDateKey(timestamp: string, timezone?: string): string {
135154

136155
export function formatMonthKey(timestamp: string, timezone?: string): string {
137156
const tz = safeTimeZone(timezone);
138-
const [year, month] = getMonthFormatter(tz).format(new Date(timestamp)).split('-');
139-
const formatted = `${year}-${month}`;
157+
const date = new Date(timestamp);
158+
const formatter = getMonthFormatter(tz);
159+
const formatted = [
160+
getDatePart(formatter, date, 'year'),
161+
getDatePart(formatter, date, 'month'),
162+
].join('-');
140163
const cacheKey = `${tz}:${formatted}`;
141164
const cached = monthKeyCache.get(cacheKey);
142165
if (cached != null) {
@@ -147,6 +170,18 @@ export function formatMonthKey(timestamp: string, timezone?: string): string {
147170
return formatted;
148171
}
149172

173+
function getDatePart(
174+
formatter: Intl.DateTimeFormat,
175+
date: Date,
176+
type: Intl.DateTimeFormatPartTypes,
177+
): string {
178+
const part = formatter.formatToParts(date).find((candidate) => candidate.type === type);
179+
if (part == null) {
180+
throw new Error(`Date part not found: ${type}`);
181+
}
182+
return part.value;
183+
}
184+
150185
export function formatDateTime(timestamp: string, timezone?: string): string {
151186
return getDateTimeFormatter(safeTimeZone(timezone)).format(new Date(timestamp));
152187
}
@@ -324,12 +359,46 @@ function addModels(target: Set<string>, models: Iterable<string>): void {
324359

325360
if (import.meta.vitest != null) {
326361
describe('adapter date formatting', () => {
362+
afterEach(() => {
363+
vi.unstubAllGlobals();
364+
});
365+
366+
it('rejects impossible calendar date filters', () => {
367+
expect(() => normalizeDateFilter('2026-02-31')).toThrow(
368+
'Invalid date: 2026-02-31. Use YYYY-MM-DD or YYYYMMDD.',
369+
);
370+
expect(() => normalizeDateFilter('20261340')).toThrow(
371+
'Invalid date: 20261340. Use YYYY-MM-DD or YYYYMMDD.',
372+
);
373+
});
374+
327375
it('formats cached date and month keys', () => {
328376
expect(formatDateKey('2026-05-16T12:34:56.000Z', 'UTC')).toBe('2026-05-16');
329377
expect(formatMonthKey('2026-05-16T12:34:56.000Z', 'UTC')).toBe('2026-05');
330378
expect(formatDateKey('2026-05-16T23:34:56.000Z', 'Asia/Tokyo')).toBe('2026-05-17');
331379
});
332380

381+
it('builds machine date keys from date parts rather than locale display text', () => {
382+
const DateTimeFormat = Intl.DateTimeFormat;
383+
class DateTimeFormatMock {
384+
constructor(locale?: string | string[], options?: Intl.DateTimeFormatOptions) {
385+
const formatter = new DateTimeFormat(locale, options);
386+
return {
387+
format: () => (options?.day == null ? '05/2026' : '05/16/2026'),
388+
formatToParts: (date: Date) => formatter.formatToParts(date),
389+
resolvedOptions: () => formatter.resolvedOptions(),
390+
} as Intl.DateTimeFormat;
391+
}
392+
}
393+
vi.stubGlobal('Intl', {
394+
...Intl,
395+
DateTimeFormat: DateTimeFormatMock,
396+
});
397+
398+
expect(formatDateKey('2026-05-16T12:34:56.000Z', 'Etc/GMT+11')).toBe('2026-05-16');
399+
expect(formatMonthKey('2026-05-16T12:34:56.000Z', 'Etc/GMT+11')).toBe('2026-05');
400+
});
401+
333402
it('does not reuse one UTC hour cache entry across non-hour timezone date boundaries', () => {
334403
expect(formatDateKey('2026-05-31T18:10:00.000Z', 'Asia/Kathmandu')).toBe('2026-05-31');
335404
expect(formatDateKey('2026-05-31T18:20:00.000Z', 'Asia/Kathmandu')).toBe('2026-06-01');

0 commit comments

Comments
 (0)