@prunellejs/content 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,309 @@
1
+ // HTML allow-list sanitizer applied to rendered Markdown: drops dangerous tags, non-allowlisted attributes and unsafe URL schemes.
2
+
3
+ const DROP_CONTENT_TAGS = new Set([
4
+ 'script',
5
+ 'style',
6
+ 'iframe',
7
+ 'object',
8
+ 'applet',
9
+ 'noscript',
10
+ 'template',
11
+ ])
12
+
13
+ const ALLOWED_MD_TAGS = new Set([
14
+ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
15
+ 'p', 'br', 'hr', 'div', 'span', 'section', 'article', 'aside', 'header', 'footer', 'nav', 'main',
16
+ 'a', 'img', 'picture', 'source',
17
+ 'pre', 'code', 'kbd', 'samp', 'var',
18
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
19
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',
20
+ 'blockquote', 'q', 'cite', 'abbr', 'time', 'mark', 'small', 'ins', 'del', 's', 'u', 'b', 'i', 'strong', 'em', 'sup', 'sub', 'wbr',
21
+ 'details', 'summary', 'figure', 'figcaption',
22
+ 'input',
23
+ ])
24
+
25
+ // Strict attribute allowlist: blocks event handlers (on*), data-pru-*, data-persist, DOM clobbering (id/name), style, etc.
26
+ const GLOBAL_ALLOWED_ATTRS = new Set([
27
+ 'class',
28
+ 'title',
29
+ 'lang',
30
+ 'dir',
31
+ 'role',
32
+ 'aria-label',
33
+ 'aria-hidden',
34
+ 'aria-current',
35
+ 'aria-expanded',
36
+ 'aria-level',
37
+ 'aria-description',
38
+ 'aria-roledescription',
39
+ ])
40
+
41
+ const TAG_ALLOWED_ATTRS: Record<string, ReadonlySet<string>> = {
42
+ a: new Set(['href', 'rel', 'target', 'hreflang']),
43
+ img: new Set(['src', 'srcset', 'sizes', 'alt', 'width', 'height', 'loading', 'decoding', 'fetchpriority']),
44
+ source: new Set(['src', 'srcset', 'sizes', 'type', 'media', 'width', 'height']),
45
+ blockquote: new Set(['cite']),
46
+ q: new Set(['cite']),
47
+ del: new Set(['cite', 'datetime']),
48
+ ins: new Set(['cite', 'datetime']),
49
+ time: new Set(['datetime']),
50
+ ol: new Set(['start', 'reversed', 'type']),
51
+ li: new Set(['value']),
52
+ th: new Set(['colspan', 'rowspan', 'scope', 'align', 'valign', 'abbr']),
53
+ td: new Set(['colspan', 'rowspan', 'align', 'valign', 'abbr']),
54
+ col: new Set(['span', 'align']),
55
+ colgroup: new Set(['span', 'align']),
56
+ details: new Set(['open']),
57
+ }
58
+
59
+ const URL_ATTRS = new Set(['href', 'src', 'cite'])
60
+ const SAFE_DATA_IMAGE_RE = /^data:image\/(?:png|jpe?g|gif|webp|avif);base64,[a-z0-9+/=\s]+$/i
61
+ const SAFE_SCHEME_RE = /^(?:https?|mailto|tel):/i
62
+ const HAS_SCHEME_RE = /^[a-z][a-z0-9+.-]*:/i
63
+
64
+ function decodeHtmlEntities(rawVal: string): string {
65
+ return rawVal
66
+ .replace(/&#x([0-9a-f]+);?/gi, (_, hex: string) => {
67
+ const cp = Number.parseInt(hex, 16)
68
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
69
+ })
70
+ .replace(/&#([0-9]+);?/g, (_, dec: string) => {
71
+ const cp = Number.parseInt(dec, 10)
72
+ return Number.isFinite(cp) && cp <= 0x10FFFF ? String.fromCodePoint(cp) : ''
73
+ })
74
+ .replace(/&(colon|tab|newline|amp);/gi, (_, name: string) => {
75
+ const lower = name.toLowerCase()
76
+ if (lower === 'colon') return ':'
77
+ if (lower === 'tab') return '\t'
78
+ if (lower === 'newline') return '\n'
79
+ return '&'
80
+ })
81
+ }
82
+
83
+ function isSafeUrl(val: string): boolean {
84
+ const cleaned = decodeHtmlEntities(val).replace(/[\u0000-\u0020\u007F]+/g, '').trim()
85
+ if (cleaned === '')
86
+ return true
87
+ if (SAFE_SCHEME_RE.test(cleaned) || SAFE_DATA_IMAGE_RE.test(cleaned))
88
+ return true
89
+ if (HAS_SCHEME_RE.test(cleaned))
90
+ return false
91
+ return true
92
+ }
93
+
94
+ function parseTagAttributes(attrSrc: string): Array<{ name: string, value: string | null }> {
95
+ const attrs: Array<{ name: string, value: string | null }> = []
96
+ let i = 0
97
+ const len = attrSrc.length
98
+ while (i < len) {
99
+ while (i < len && /[\s/]/.test(attrSrc[i]!)) i++
100
+ if (i >= len) break
101
+ const nameStart = i
102
+ while (i < len && !/[\s=/>"'<]/.test(attrSrc[i]!)) i++
103
+ const name = attrSrc.slice(nameStart, i).toLowerCase()
104
+ if (!name) {
105
+ i++
106
+ continue
107
+ }
108
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
109
+ if (attrSrc[i] !== '=') {
110
+ attrs.push({ name, value: null })
111
+ continue
112
+ }
113
+ i++ // skip '='
114
+ while (i < len && /\s/.test(attrSrc[i]!)) i++
115
+ if (i >= len) {
116
+ attrs.push({ name, value: '' })
117
+ break
118
+ }
119
+ const quote = attrSrc[i]!
120
+ if (quote === '"' || quote === '\'') {
121
+ i++
122
+ const valStart = i
123
+ while (i < len && attrSrc[i] !== quote) i++
124
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
125
+ if (i < len) i++
126
+ }
127
+ else {
128
+ const valStart = i
129
+ while (i < len && !/[\s>]/.test(attrSrc[i]!)) i++
130
+ attrs.push({ name, value: attrSrc.slice(valStart, i) })
131
+ }
132
+ }
133
+ return attrs
134
+ }
135
+
136
+ function sanitizeInputTag(rawAttrs: Array<{ name: string, value: string | null }>): string {
137
+ const typeAttr = rawAttrs.find(a => a.name === 'type')
138
+ if (typeAttr?.value?.toLowerCase() !== 'checkbox')
139
+ return ''
140
+ const safeParts = ['type="checkbox"']
141
+ for (const a of rawAttrs) {
142
+ if (a.name === 'class' && a.value !== null)
143
+ safeParts.push(`class="${a.value.replaceAll('"', '&quot;')}"`)
144
+ else if (a.name === 'disabled')
145
+ safeParts.push('disabled')
146
+ else if (a.name === 'checked')
147
+ safeParts.push('checked')
148
+ }
149
+ return `<input ${safeParts.join(' ')}>`
150
+ }
151
+
152
+ type AllowedSlotPrefixes = string | ReadonlySet<string> | undefined
153
+
154
+ function matchesSlotPrefix(value: string | null, allowed: AllowedSlotPrefixes): boolean {
155
+ if (value === null || allowed === undefined)
156
+ return false
157
+ if (typeof allowed === 'string')
158
+ return value.startsWith(allowed)
159
+ for (const prefix of allowed) {
160
+ if (value.startsWith(prefix))
161
+ return true
162
+ }
163
+ return false
164
+ }
165
+
166
+ function isAllowedAttr(tagName: string, name: string, value: string | null, slotPrefixes: AllowedSlotPrefixes): boolean {
167
+ if (tagName === 'div' && name === 'data-pru-md-slot')
168
+ return matchesSlotPrefix(value, slotPrefixes)
169
+ return GLOBAL_ALLOWED_ATTRS.has(name) || TAG_ALLOWED_ATTRS[tagName]?.has(name) === true
170
+ }
171
+
172
+ function sanitizeAttributes(
173
+ tagName: string,
174
+ rawAttrs: Array<{ name: string, value: string | null }>,
175
+ slotPrefixes: AllowedSlotPrefixes,
176
+ ): string[] {
177
+ const safeParts: string[] = []
178
+ for (const a of rawAttrs) {
179
+ if (!isAllowedAttr(tagName, a.name, a.value, slotPrefixes))
180
+ continue
181
+ if (URL_ATTRS.has(a.name)) {
182
+ if (a.value === null || !isSafeUrl(a.value))
183
+ continue
184
+ }
185
+ else if (a.name === 'srcset' && a.value !== null) {
186
+ const candidates = a.value.split(',').map(s => s.trim().split(/\s+/)[0] ?? '')
187
+ if (!candidates.every(isSafeUrl))
188
+ continue
189
+ }
190
+ if (a.value === null)
191
+ safeParts.push(a.name)
192
+ else
193
+ safeParts.push(`${a.name}="${a.value.replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')}"`)
194
+ }
195
+ return safeParts
196
+ }
197
+
198
+ function findTagEndOffset(html: string, start: number): number {
199
+ let tagEnd = start
200
+ const len = html.length
201
+ let inQuote: string | null = null
202
+ while (tagEnd < len) {
203
+ const c = html[tagEnd]!
204
+ if (inQuote !== null) {
205
+ if (c === inQuote)
206
+ inQuote = null
207
+ }
208
+ else if (c === '"' || c === '\'') {
209
+ inQuote = c
210
+ }
211
+ else if (c === '>') {
212
+ return tagEnd
213
+ }
214
+ tagEnd++
215
+ }
216
+ return -1
217
+ }
218
+
219
+ function sanitizePass(html: string, slotPrefixes: AllowedSlotPrefixes): string {
220
+ let out = ''
221
+ let i = 0
222
+ const len = html.length
223
+
224
+ while (i < len) {
225
+ const lt = html.indexOf('<', i)
226
+ if (lt === -1) {
227
+ out += html.slice(i)
228
+ break
229
+ }
230
+ out += html.slice(i, lt)
231
+
232
+ // Strip HTML comments (including HTML5 `--!>` closer)
233
+ if (html.startsWith('<!--', lt)) {
234
+ const endStd = html.indexOf('-->', lt + 4)
235
+ const endBang = html.indexOf('--!>', lt + 4)
236
+ if (endStd === -1 && endBang === -1)
237
+ i = len
238
+ else if (endBang !== -1 && (endStd === -1 || endBang < endStd))
239
+ i = endBang + 4
240
+ else
241
+ i = endStd + 3
242
+ continue
243
+ }
244
+
245
+ let pos = lt + 1
246
+ const isClosing = html[pos] === '/'
247
+ if (isClosing)
248
+ pos++
249
+
250
+ const nameStart = pos
251
+ while (pos < len && /[A-Za-z0-9:-]/.test(html[pos]!)) pos++
252
+ const tagName = html.slice(nameStart, pos).toLowerCase()
253
+ if (!tagName) {
254
+ out += '&lt;'
255
+ i = lt + 1
256
+ continue
257
+ }
258
+
259
+ const tagEnd = findTagEndOffset(html, pos)
260
+ if (tagEnd === -1)
261
+ break
262
+
263
+ const attrSrc = html.slice(pos, tagEnd)
264
+ const selfClosing = !isClosing && /\/\s*$/.test(attrSrc)
265
+ i = tagEnd + 1
266
+
267
+ if (!isClosing && DROP_CONTENT_TAGS.has(tagName)) {
268
+ if (!selfClosing) {
269
+ const closeRe = new RegExp(`</${tagName}\\b[^>]*>`, 'gi')
270
+ closeRe.lastIndex = i
271
+ const m = closeRe.exec(html)
272
+ i = m ? m.index + m[0].length : len
273
+ }
274
+ continue
275
+ }
276
+
277
+ if (!ALLOWED_MD_TAGS.has(tagName))
278
+ continue
279
+
280
+ if (isClosing) {
281
+ if (tagName !== 'input' && tagName !== 'br' && tagName !== 'hr' && tagName !== 'img')
282
+ out += `</${tagName}>`
283
+ continue
284
+ }
285
+
286
+ const rawAttrs = parseTagAttributes(attrSrc)
287
+ if (tagName === 'input') {
288
+ out += sanitizeInputTag(rawAttrs)
289
+ continue
290
+ }
291
+
292
+ const safeParts = sanitizeAttributes(tagName, rawAttrs, slotPrefixes)
293
+ const attrOut = safeParts.length > 0 ? ` ${safeParts.join(' ')}` : ''
294
+ out += selfClosing ? `<${tagName}${attrOut} />` : `<${tagName}${attrOut}>`
295
+ }
296
+
297
+ return out
298
+ }
299
+
300
+ export function sanitizeMarkdownHtml(html: string, slotPrefixes?: AllowedSlotPrefixes): string {
301
+ let current = html
302
+ for (let pass = 0; pass < 3; pass++) {
303
+ const next = sanitizePass(current, slotPrefixes)
304
+ if (next === current)
305
+ return next
306
+ current = next
307
+ }
308
+ return current
309
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.