Debian Codegraph @

web/src/app/utils.test.js

raw
1 import { describe, expect, it } from "vitest";
2 import { THEME, DATE_FORMAT, TIME_FORMAT } from "./Prefs";
3 import {
4 topicUrl,
5 topicUrlWs,
6 topicUrlJsonPollWithSince,
7 accountUrl,
8 accountTokenUrl,
9 shortUrl,
10 expandUrl,
11 expandSecureUrl,
12 validUrl,
13 validTopic,
14 disallowedTopic,
15 encodeBase64,
16 encodeBase64Url,
17 bearerAuth,
18 basicAuth,
19 withBearerAuth,
20 maybeWithAuth,
21 splitNoEmpty,
22 sanitizeUrl,
23 hashCode,
24 formatBytes,
25 formatNumber,
26 formatPrice,
27 formatShortDuration,
28 formatDate,
29 formatDateTime,
30 formatTime,
31 getKebabCaseLangStr,
32 darkModeEnabled,
33 urlB64ToUint8Array,
34 } from "./utils";
35
36 describe("URL builders", () => {
37 it("build topic URLs", () => {
38 expect(topicUrl("https://ntfy.sh", "mytopic")).toBe("https://ntfy.sh/mytopic");
39 expect(topicUrlJsonPollWithSince("https://ntfy.sh", "mytopic", 123)).toBe("https://ntfy.sh/mytopic/json?poll=1&since=123");
40 });
41
42 it("rewrite the scheme for websocket URLs", () => {
43 expect(topicUrlWs("https://ntfy.sh", "mytopic")).toBe("wss://ntfy.sh/mytopic/ws");
44 expect(topicUrlWs("http://localhost:8080", "mytopic")).toBe("ws://localhost:8080/mytopic/ws");
45 });
46
47 it("build account URLs", () => {
48 expect(accountUrl("https://ntfy.sh")).toBe("https://ntfy.sh/v1/account");
49 expect(accountTokenUrl("https://ntfy.sh")).toBe("https://ntfy.sh/v1/account/token");
50 });
51 });
52
53 describe("url helpers", () => {
54 it("strip the scheme with shortUrl", () => {
55 expect(shortUrl("https://ntfy.sh/mytopic")).toBe("ntfy.sh/mytopic");
56 });
57
58 it("expand a bare host to both schemes", () => {
59 expect(expandUrl("ntfy.sh")).toEqual(["https://ntfy.sh", "http://ntfy.sh"]);
60 expect(expandSecureUrl("ntfy.sh")).toBe("https://ntfy.sh");
61 });
62
63 it("validate http(s) URLs", () => {
64 expect(validUrl("https://ntfy.sh")).toBeTruthy();
65 expect(validUrl("http://ntfy.sh")).toBeTruthy();
66 expect(validUrl("ftp://ntfy.sh")).toBeFalsy();
67 });
68 });
69
70 describe("topic validation", () => {
71 it("rejects disallowed topics (from config.disallowed_topics)", () => {
72 expect(disallowedTopic("app")).toBe(true);
73 expect(disallowedTopic("mytopic")).toBe(false);
74 expect(validTopic("app")).toBe(false);
75 });
76
77 it("accepts well-formed topic names and rejects malformed ones", () => {
78 expect(validTopic("valid_Topic-123")).toBeTruthy();
79 expect(validTopic("bad/slash")).toBeFalsy();
80 expect(validTopic("with space")).toBeFalsy();
81 expect(validTopic("")).toBeFalsy();
82 });
83 });
84
85 describe("base64 + auth headers", () => {
86 it("encodes base64 and base64url", () => {
87 expect(encodeBase64("hello")).toBe("aGVsbG8=");
88 expect(encodeBase64Url("hello")).toBe("aGVsbG8");
89 });
90
91 it("builds bearer and basic auth headers", () => {
92 expect(bearerAuth("tok")).toBe("Bearer tok");
93 expect(basicAuth("phil", "secret")).toBe(`Basic ${encodeBase64("phil:secret")}`);
94 expect(withBearerAuth({ "Content-Type": "application/json" }, "tok")).toEqual({
95 "Content-Type": "application/json",
96 Authorization: "Bearer tok",
97 });
98 });
99
100 it("picks the right scheme in maybeWithAuth", () => {
101 expect(maybeWithAuth({}, { username: "u", password: "p" }).Authorization).toBe(basicAuth("u", "p"));
102 expect(maybeWithAuth({}, { token: "tok" }).Authorization).toBe(bearerAuth("tok"));
103 expect(maybeWithAuth({ a: 1 }, undefined)).toEqual({ a: 1 });
104 });
105 });
106
107 describe("misc pure helpers", () => {
108 it("splitNoEmpty trims and drops empty entries", () => {
109 expect(splitNoEmpty("a, b, ,c ", ",")).toEqual(["a", "b", "c"]);
110 expect(splitNoEmpty("", ",")).toEqual([]);
111 });
112
113 it("hashCode is deterministic", () => {
114 expect(hashCode("")).toBe(0);
115 expect(hashCode("a")).toBe(97);
116 expect(hashCode("hello")).toBe(hashCode("hello"));
117 });
118
119 it("formatBytes is human readable", () => {
120 expect(formatBytes(0)).toBe("0 bytes");
121 expect(formatBytes(1024)).toBe("1 KB");
122 expect(formatBytes(1536)).toBe("1.5 KB");
123 });
124
125 it("formatNumber abbreviates round thousands", () => {
126 expect(formatNumber(0)).toBe(0);
127 expect(formatNumber(1000)).toBe("1k");
128 expect(formatNumber(1500)).toBe((1500).toLocaleString());
129 });
130
131 it("formatPrice renders cents as dollars", () => {
132 expect(formatPrice(100)).toBe("$1");
133 expect(formatPrice(150)).toBe("$1.5");
134 });
135
136 it("formatShortDuration picks the largest fitting unit", () => {
137 expect(formatShortDuration(60000, "en")).toContain("minute");
138 expect(formatShortDuration(3600000, "en")).toContain("hour");
139 });
140
141 it("getKebabCaseLangStr normalizes language tags", () => {
142 expect(getKebabCaseLangStr("en_US")).toBe("en-US");
143 expect(getKebabCaseLangStr(undefined)).toBe("en");
144 expect(getKebabCaseLangStr("")).toBe("en");
145 });
146
147 it("darkModeEnabled honors the theme preference", () => {
148 expect(darkModeEnabled(false, THEME.DARK)).toBe(true);
149 expect(darkModeEnabled(true, THEME.LIGHT)).toBe(false);
150 expect(darkModeEnabled(true, THEME.SYSTEM)).toBe(true);
151 expect(darkModeEnabled(false, THEME.SYSTEM)).toBe(false);
152 });
153
154 it("urlB64ToUint8Array decodes web push keys", () => {
155 expect(Array.from(urlB64ToUint8Array("AQID"))).toEqual([1, 2, 3]);
156 });
157 });
158
159 describe("date/time formatting", () => {
160 // 2026-03-08 14:30 in the runner's local timezone (the same wall-clock time Intl renders).
161 const ts = Math.floor(new Date(2026, 2, 8, 14, 30, 0).getTime() / 1000);
162
163 it("ISO 8601 mode renders YYYY-MM-DD HH:mm regardless of locale", () => {
164 expect(formatDateTime(ts, DATE_FORMAT.ISO8601)).toBe("2026-03-08 14:30");
165 expect(formatDate(ts, DATE_FORMAT.ISO8601)).toBe("2026-03-08");
166 });
167
168 it("ISO 8601 mode zero-pads single-digit months, days, hours and minutes", () => {
169 const early = Math.floor(new Date(2026, 0, 5, 9, 7, 0).getTime() / 1000);
170 expect(formatDateTime(early, DATE_FORMAT.ISO8601)).toBe("2026-01-05 09:07");
171 });
172
173 it("default mode follows the browser locale, not the UI translation language", () => {
174 // The format must depend only on the browser's default locale -- passing a language
175 // tag (the old behavior) must NOT change the output anymore.
176 const browserDefault = new Intl.DateTimeFormat(undefined, { dateStyle: "short", timeStyle: "short" }).format(new Date(ts * 1000));
177 expect(formatDateTime(ts, DATE_FORMAT.SYSTEM)).toBe(browserDefault);
178 expect(formatDateTime(ts, "fr")).toBe(browserDefault);
179 expect(formatDateTime(ts, "en_US")).toBe(browserDefault);
180 expect(formatDateTime(ts, undefined)).toBe(browserDefault);
181 });
182
183 it("only ISO 8601 zero-pads; DMY, dot-separated DMY and MDY all drop leading zeros", () => {
184 expect(formatDate(ts, DATE_FORMAT.DMY)).toBe("8/3/2026");
185 expect(formatDate(ts, DATE_FORMAT.DMY_DOT)).toBe("8.3.2026");
186 expect(formatDate(ts, DATE_FORMAT.MDY)).toBe("3/8/2026");
187 // Double-digit day/month are left intact.
188 const ts2 = Math.floor(new Date(2026, 11, 25, 14, 30, 0).getTime() / 1000);
189 expect(formatDate(ts2, DATE_FORMAT.DMY)).toBe("25/12/2026");
190 expect(formatDate(ts2, DATE_FORMAT.DMY_DOT)).toBe("25.12.2026");
191 expect(formatDate(ts2, DATE_FORMAT.MDY)).toBe("12/25/2026");
192 // The same ordering prefixes the datetime variant.
193 expect(formatDateTime(ts, DATE_FORMAT.DMY)).toMatch(/^8\/3\/2026 /);
194 expect(formatDateTime(ts, DATE_FORMAT.DMY_DOT)).toMatch(/^8\.3\.2026 /);
195 expect(formatDateTime(ts, DATE_FORMAT.MDY)).toMatch(/^3\/8\/2026 /);
196 });
197
198 it("formatTime renders only the time, honoring the 12/24-hour choice", () => {
199 const local24 = new Intl.DateTimeFormat(undefined, { timeStyle: "short", hour12: false }).format(new Date(ts * 1000));
200 expect(formatTime(ts, TIME_FORMAT.H24)).toBe(local24);
201 expect(formatTime(ts, TIME_FORMAT.H24)).toContain("14:30");
202 expect(formatTime(ts, TIME_FORMAT.H12)).toContain("2:30");
203 });
204
205 it("time format selects 12-hour vs 24-hour independently of the date format", () => {
206 const local24 = new Intl.DateTimeFormat(undefined, { timeStyle: "short", hour12: false }).format(new Date(ts * 1000));
207 expect(formatDateTime(ts, DATE_FORMAT.DMY, TIME_FORMAT.H24)).toBe(`8/3/2026 ${local24}`);
208
209 const h12 = formatDateTime(ts, DATE_FORMAT.SYSTEM, TIME_FORMAT.H12);
210 const h24 = formatDateTime(ts, DATE_FORMAT.SYSTEM, TIME_FORMAT.H24);
211 expect(h24).toContain("14:30");
212 expect(h12).toContain("2:30");
213 expect(h12).not.toBe(h24);
214 });
215
216 it("ISO 8601 is always 24-hour regardless of the time format", () => {
217 expect(formatDateTime(ts, DATE_FORMAT.ISO8601, TIME_FORMAT.H12)).toBe("2026-03-08 14:30");
218 });
219 });
220
221 describe("sanitizeUrl", () => {
222 it("keeps safe absolute URLs", () => {
223 expect(sanitizeUrl("https://ntfy.sh")).toBe("https://ntfy.sh");
224 expect(sanitizeUrl("http://example.com/foo?bar=1")).toBe("http://example.com/foo?bar=1");
225 expect(sanitizeUrl("mailto:[email protected]")).toBe("mailto:[email protected]");
226 expect(sanitizeUrl("ftp://ftp.example.com/file.txt")).toBe("ftp://ftp.example.com/file.txt");
227 expect(sanitizeUrl("ftps://ftp.example.com/file.txt")).toBe("ftps://ftp.example.com/file.txt");
228 });
229
230 it("keeps relative URLs, fragments and query strings", () => {
231 expect(sanitizeUrl("/docs")).toBe("/docs");
232 expect(sanitizeUrl("./foo")).toBe("./foo");
233 expect(sanitizeUrl("#section")).toBe("#section");
234 expect(sanitizeUrl("?q=1")).toBe("?q=1");
235 expect(sanitizeUrl("foo/bar")).toBe("foo/bar");
236 });
237
238 it("does not treat a colon after a slash/query/hash as a protocol", () => {
239 expect(sanitizeUrl("/path:with:colons")).toBe("/path:with:colons");
240 expect(sanitizeUrl("foo?x=a:b")).toBe("foo?x=a:b");
241 });
242
243 it("strips dangerous protocols", () => {
244 /* eslint-disable no-script-url -- these javascript: literals are exactly what we're testing */
245 expect(sanitizeUrl("javascript:alert(document.domain)")).toBe("");
246 expect(sanitizeUrl("JavaScript:alert(1)")).toBe("");
247 expect(sanitizeUrl(" javascript:alert(1)")).toBe("");
248 /* eslint-enable no-script-url */
249 expect(sanitizeUrl("vbscript:msgbox(1)")).toBe("");
250 expect(sanitizeUrl("data:text/html,<script>alert(1)</script>")).toBe("");
251 });
252
253 it("handles empty and nullish input", () => {
254 expect(sanitizeUrl("")).toBe("");
255 expect(sanitizeUrl(undefined)).toBe("");
256 expect(sanitizeUrl(null)).toBe("");
257 });
258 });