source: Klonkt/src/services/MarkdownService.js@ 3ccca13

main
Last change on this file since 3ccca13 was 7bc636b, checked in by Robin <robin@…>, 4 months ago

Initial commit — PrutFolio v1 source (pulled from Hetzner /srv/prutfolio)

  • Property mode set to 100644
File size: 1.6 KB
Line 
1import { marked } from 'marked';
2
3// Configure marked
4marked.setOptions({
5 breaks: true,
6 gfm: true, // GitHub Flavored Markdown
7 pedantic: false
8});
9
10export class MarkdownService {
11 /**
12 * Convert markdown to HTML
13 */
14 static render(markdown) {
15 try {
16 if (!markdown) return '';
17
18 // Sanitize: remove script tags and dangerous HTML
19 const sanitized = this.sanitize(markdown);
20
21 // Render markdown
22 const html = marked(sanitized);
23
24 return html;
25 } catch (err) {
26 console.error('❌ Markdown render error:', err);
27 return `<p>Error rendering content</p>`;
28 }
29 }
30
31 /**
32 * Sanitize markdown to prevent XSS
33 */
34 static sanitize(markdown) {
35 if (!markdown) return '';
36
37 // Remove script tags
38 let sanitized = markdown.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '');
39
40 // Remove on* event handlers
41 sanitized = sanitized.replace(/on\w+\s*=\s*["'][^"']*["']/gi, '');
42 sanitized = sanitized.replace(/on\w+\s*=\s*[^\s>]*/gi, '');
43
44 // Remove javascript: protocol
45 sanitized = sanitized.replace(/javascript:/gi, '');
46
47 return sanitized;
48 }
49
50 /**
51 * Extract plain text from markdown
52 */
53 static toPlainText(markdown) {
54 if (!markdown) return '';
55
56 return markdown
57 .replace(/[#*_`\[\]()]/g, '') // Remove markdown syntax
58 .replace(/\n+/g, ' ') // Collapse newlines
59 .trim();
60 }
61
62 /**
63 * Generate preview (first 200 chars)
64 */
65 static preview(markdown, length = 200) {
66 const plainText = this.toPlainText(markdown);
67 return plainText.substring(0, length) + (plainText.length > length ? '...' : '');
68 }
69}
70
71export default MarkdownService;
Note: See TracBrowser for help on using the repository browser.