Skip to content

World's first open-source enterprise world model.

Reject impossible calendar dates before converting clock inputs (#766)

Maya Kid5a3442c56d8b
diff --git a/web/src/time.test.ts b/web/src/time.test.ts
new file mode 100644
index 00000000..7acf45fc
--- /dev/null
+++ b/web/src/time.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from "vitest";
+import { parseDateInput } from "./time";
+
+describe("parseDateInput", () => {
+ it.each([
+ "2023-02-29T10Z",
+ "2024-02-30T10:15Z",
+ "2026-04-31T10:15:30Z",
+ "2023-02-29T00:30+08:00",
+ "2023-02-29T23:30-08:00",
+ ])("rejects nonexistent calendar dates in %s", (input) => {
+ expect(parseDateInput(input)).toBeNull();
+ });
+
+ it.each([
+ ["2024-02-29T10Z", "2024-02-29T10:00:00.000Z", "hour"],
+ ["2024-02-29T00:30+08:00", "2024-02-28T16:30:00.000Z", "minute"],
+ ["2024-12-31T23:30:15-08:00", "2025-01-01T07:30:15.000Z", "second"],
+ ["2024", "2024-01-01T00:00:00.000Z", "year"],
+ ["2024-02", "2024-02-01T00:00:00.000Z", "month"],
+ ["2024-02-29", "2024-02-29T00:00:00.000Z", "day"],
+ ])("keeps the stated precision and offset of %s", (input, iso, precision) => {
+ expect(parseDateInput(input)).toEqual({ iso, precision });
+ });
+
+ it.each(["2023-02-29", "2024-02-30", "2024-13", "2024-00-01", "2024-02-29T10:15"])(
+ "still rejects invalid or timezone-free input %s", (input) => {
+ expect(parseDateInput(input)).toBeNull();
+ },
+ );
+});
diff --git a/web/src/time.ts b/web/src/time.ts
index 7fb9604b..64bd8a19 100644
--- a/web/src/time.ts
+++ b/web/src/time.ts
@@ -48,12 +48,13 @@ export function parseDateInput(
);
if (!shape) return null;
const [, y, m, d, hh, mi, ss, zone] = shape;
+ const iso = `${y}-${m ?? "01"}-${d ?? "01"}T00:00:00.000Z`;
+ const calendar = new Date(iso);
+ if (Number.isNaN(calendar.getTime())) return null;
+ // Validate the written calendar date before applying its offset: Date silently
+ // rolls February 30 into March, while a valid offset can legitimately change the day.
+ if (calendar.toISOString().slice(0, 10) !== iso.slice(0, 10)) return null;
if (hh === undefined) {
- const iso = `${y}-${m ?? "01"}-${d ?? "01"}T00:00:00.000Z`;
- const parsed = new Date(iso);
- if (Number.isNaN(parsed.getTime())) return null;
- // 溢出静默:2023-13-01 会变成 2024-01-01,2023-02-30 会变成 3 月
- if (parsed.toISOString().slice(0, 10) !== iso.slice(0, 10)) return null;
return { iso, precision: d ? "day" : m ? "month" : "year" };
}
// 钟点(0024):没有时区就不是一个时刻——不猜,让人补上 Z 或 +08:00;