lime-csr-js 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.js ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * @module utils
3
+ * @description Security helpers — output sanitization against XSS.
4
+ *
5
+ * Source: LimeVideo legacy index.js (this dependency was removed, converted to pure functions).
6
+ */
7
+
8
+ /**
9
+ * Makes a value safe against XSS by converting it to HTML entities.
10
+ *
11
+ * @param {*} value
12
+ * @returns {string}
13
+ */
14
+ export function escapeHtml(value = "") {
15
+ return String(value ?? "").replace(
16
+ /[&<>"']/g,
17
+ (char) =>
18
+ ({
19
+ "&": "&amp;",
20
+ "<": "&lt;",
21
+ ">": "&gt;",
22
+ '"': "&quot;",
23
+ "'": "&#039;",
24
+ })[char],
25
+ );
26
+ }
27
+
28
+ /**
29
+ * Returns a string safe for use as an HTML attribute value.
30
+ * In addition to escapeHtml, also escapes backticks (against template injection).
31
+ *
32
+ * @param {*} value
33
+ * @returns {string}
34
+ */
35
+ export function safeAttr(value = "") {
36
+ return escapeHtml(value).replace(/`/g, "&#096;");
37
+ }
38
+
39
+ /**
40
+ * Is a URL's protocol on the safe whitelist (http/https only, root-relative
41
+ * paths (/), and #anchor)? Returns false for protocol-relative URLs (//) and
42
+ * dangerous schemes (javascript:, data:, etc.).
43
+ *
44
+ * Does NOT escape (returns only a boolean) — a shared core for consumers that
45
+ * need the raw value (e.g. bindings.js, which uses setAttribute); safeUrl
46
+ * adds escaping on top of this.
47
+ *
48
+ * @param {*} value
49
+ * @returns {boolean}
50
+ */
51
+ export function isSafeUrlProtocol(value = "") {
52
+ const url = String(value ?? "").trim();
53
+ if (!url) return false;
54
+ return (
55
+ /^https?:\/\//i.test(url) ||
56
+ (url.startsWith("/") && !url.startsWith("//")) ||
57
+ url.startsWith("#")
58
+ );
59
+ }
60
+
61
+ /**
62
+ * Returns a safe URL; only allows http/https, root-relative paths (/), and #anchor.
63
+ * Returns an empty string for protocol-relative URLs (//) and dangerous schemes
64
+ * (javascript:, data:, etc.).
65
+ *
66
+ * @param {*} value
67
+ * @returns {string}
68
+ */
69
+ export function safeUrl(value = "") {
70
+ const url = String(value ?? "").trim();
71
+ return isSafeUrlProtocol(url) ? safeAttr(url) : "";
72
+ }
73
+
74
+ /**
75
+ * Returns a safe `url('...')` for CSS style values like `background-image`.
76
+ *
77
+ * @param {*} value
78
+ * @returns {string}
79
+ */
80
+ export function safeStyleUrl(value = "") {
81
+ const url = safeUrl(value);
82
+ if (!url) return "";
83
+ return `url('${url.replace(/'/g, "%27")}')`;
84
+ }