readwebform 0.4.0__py3-none-any.whl

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.
readwebform/parser.py ADDED
@@ -0,0 +1,285 @@
1
+ """
2
+ HTML parsing, validation, rewriting and page templating for readwebform.
3
+ """
4
+
5
+ import html as html_mod
6
+ import re
7
+ import sys
8
+ from html.parser import HTMLParser
9
+ from typing import Optional
10
+
11
+
12
+ class FormDetector(HTMLParser):
13
+ """
14
+ Locate and inspect the <form> element(s) in an HTML document.
15
+
16
+ Comments and CDATA are skipped by HTMLParser, so a ``<form>`` inside a
17
+ comment is neither counted nor rewritten.
18
+ """
19
+
20
+ def __init__(self, source: str):
21
+ super().__init__(convert_charrefs=True)
22
+ self._line_starts = _line_starts(source)
23
+ self.form_count = 0
24
+ self.form_action: Optional[str] = None
25
+ self.has_submit_button = False
26
+ self.in_form = False
27
+ # Position of the first form's start tag within the source
28
+ self.form_start: Optional[int] = None
29
+ self.form_tag_text: Optional[str] = None
30
+ self.form_attrs: list[tuple[str, Optional[str]]] = []
31
+
32
+ def _index(self) -> int:
33
+ lineno, offset = self.getpos()
34
+ return self._line_starts[lineno - 1] + offset
35
+
36
+ def handle_starttag(self, tag: str, attrs: list):
37
+ attrs_dict = dict(attrs)
38
+
39
+ if tag == 'form':
40
+ self.form_count += 1
41
+ self.in_form = True
42
+ if self.form_count == 1:
43
+ self.form_action = attrs_dict.get('action') or ''
44
+ self.form_start = self._index()
45
+ self.form_tag_text = self.get_starttag_text()
46
+ self.form_attrs = list(attrs)
47
+
48
+ if self.in_form and tag in ('input', 'button'):
49
+ default_type = 'text' if tag == 'input' else 'submit'
50
+ if (attrs_dict.get('type') or default_type).lower() == 'submit':
51
+ self.has_submit_button = True
52
+
53
+ def handle_endtag(self, tag: str):
54
+ if tag == 'form':
55
+ self.in_form = False
56
+
57
+
58
+ def _line_starts(source: str) -> list[int]:
59
+ """Character index at which each line starts; HTMLParser counts lines by '\\n'."""
60
+ starts = [0]
61
+ for i, ch in enumerate(source):
62
+ if ch == '\n':
63
+ starts.append(i + 1)
64
+ return starts
65
+
66
+
67
+ def _detect(html: str) -> FormDetector:
68
+ detector = FormDetector(html)
69
+ detector.feed(html)
70
+ detector.close()
71
+ return detector
72
+
73
+
74
+ def validate_html(html: str, warn_no_submit: bool = True) -> tuple[bool, Optional[str]]:
75
+ """
76
+ Validate that HTML contains exactly one form element.
77
+
78
+ Args:
79
+ html: HTML content to validate
80
+ warn_no_submit: Whether to warn on stderr if no submit button is found
81
+
82
+ Returns:
83
+ Tuple of (is_valid, error_message)
84
+ """
85
+ try:
86
+ detector = _detect(html)
87
+ except Exception as e:
88
+ return False, f'Failed to parse HTML: {e}'
89
+
90
+ if detector.form_count == 0:
91
+ return False, 'No <form> element found in HTML'
92
+ if detector.form_count > 1:
93
+ return False, f'Multiple <form> elements found ({detector.form_count}), exactly one required'
94
+
95
+ if detector.form_action and is_external_url(detector.form_action):
96
+ return False, f'External form action URL rejected: {detector.form_action}'
97
+
98
+ if warn_no_submit and not detector.has_submit_button:
99
+ print('Warning: No submit button found in form', file=sys.stderr)
100
+
101
+ return True, None
102
+
103
+
104
+ def is_external_url(url: str) -> bool:
105
+ """Check if a URL is external (absolute http(s) or protocol-relative)."""
106
+ if not url:
107
+ return False
108
+ return bool(re.match(r'^\s*(https?:)?//', url, re.IGNORECASE))
109
+
110
+
111
+ def inject_csrf_token(html: str, csrf_token: str, endpoint: str) -> str:
112
+ """
113
+ Rewrite the form's start tag to post to our endpoint and add the CSRF field.
114
+
115
+ Any existing ``action`` and ``method`` attributes are removed; other
116
+ attributes (``enctype``, ``id``, ``class``...) are preserved. Attribute
117
+ values are re-escaped, and the hidden CSRF input is inserted immediately
118
+ after the start tag.
119
+
120
+ Args:
121
+ html: Original HTML content (must contain a <form>)
122
+ csrf_token: CSRF token to inject
123
+ endpoint: Server endpoint path
124
+
125
+ Returns:
126
+ Modified HTML
127
+ """
128
+ detector = _detect(html)
129
+ if detector.form_start is None or detector.form_tag_text is None:
130
+ return html
131
+
132
+ attrs = [(k, v) for k, v in detector.form_attrs if k.lower() not in ('action', 'method')]
133
+ attrs += [('action', endpoint), ('method', 'POST')]
134
+
135
+ parts = ['<form']
136
+ for key, value in attrs:
137
+ if value is None:
138
+ parts.append(f' {key}')
139
+ else:
140
+ parts.append(f' {key}="{html_mod.escape(value, quote=True)}"')
141
+ new_tag = ''.join(parts) + '>'
142
+
143
+ csrf_field = (f'<input type="hidden" name="_csrf_token" '
144
+ f'value="{html_mod.escape(csrf_token, quote=True)}">')
145
+
146
+ start = detector.form_start
147
+ end = start + len(detector.form_tag_text)
148
+ return html[:start] + new_tag + csrf_field + html[end:]
149
+
150
+
151
+ PAGE_CSS = '''
152
+ body {
153
+ font-family: system-ui, -apple-system, sans-serif;
154
+ max-width: 600px;
155
+ margin: 40px auto;
156
+ padding: 20px;
157
+ line-height: 1.6;
158
+ }
159
+ h1 {
160
+ font-size: 1.5em;
161
+ margin: 0 0 10px;
162
+ }
163
+ label {
164
+ display: block;
165
+ margin: 15px 0 5px;
166
+ font-weight: 500;
167
+ }
168
+ input, textarea, select {
169
+ width: 100%;
170
+ padding: 8px;
171
+ border: 1px solid #ccc;
172
+ border-radius: 4px;
173
+ box-sizing: border-box;
174
+ }
175
+ input[type="checkbox"], input[type="radio"] {
176
+ width: auto;
177
+ margin-right: 8px;
178
+ }
179
+ input[type="checkbox"] + label, input[type="radio"] + label {
180
+ display: inline;
181
+ font-weight: normal;
182
+ }
183
+ fieldset {
184
+ border: none;
185
+ padding: 0;
186
+ margin: 15px 0 0;
187
+ }
188
+ legend {
189
+ font-weight: 500;
190
+ padding: 0;
191
+ }
192
+ button, input[type="submit"] {
193
+ width: auto;
194
+ margin-top: 20px;
195
+ margin-right: 10px;
196
+ padding: 10px 20px;
197
+ background: #007bff;
198
+ color: white;
199
+ border: none;
200
+ border-radius: 4px;
201
+ cursor: pointer;
202
+ }
203
+ button:hover, input[type="submit"]:hover {
204
+ background: #0056b3;
205
+ }
206
+ button.cancel {
207
+ background: #6c757d;
208
+ }
209
+ button.cancel:hover {
210
+ background: #5a6268;
211
+ }
212
+ '''
213
+
214
+
215
+ def render_page(content_html: str, title: Optional[str] = None, text: Optional[str] = None) -> str:
216
+ """
217
+ Wrap form markup in a complete, styled HTML document.
218
+
219
+ Args:
220
+ content_html: Markup to place in the body (normally a <form>)
221
+ title: Page title; shown in the browser tab and as a heading above the form
222
+ text: Instructional text shown above the form
223
+
224
+ Returns:
225
+ Complete HTML document
226
+ """
227
+ title_text = escape_html(title) if title else 'Form'
228
+ heading = f'<h1>{escape_html(title)}</h1>\n ' if title else ''
229
+ paragraph = f'<p>{escape_html(text)}</p>\n ' if text else ''
230
+
231
+ return f'''<!DOCTYPE html>
232
+ <html>
233
+ <head>
234
+ <meta charset="UTF-8">
235
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
236
+ <title>{title_text}</title>
237
+ <style>{PAGE_CSS} </style>
238
+ </head>
239
+ <body>
240
+ {heading}{paragraph}{content_html}
241
+ </body>
242
+ </html>'''
243
+
244
+
245
+ def wrap_html_fragment(html: str, title: Optional[str] = None, text: Optional[str] = None) -> str:
246
+ """
247
+ Ensure HTML is a complete document, adding title and text if given.
248
+
249
+ A fragment is wrapped in the standard page template. A complete document
250
+ is left as-is except that a ``<title>`` is added if missing and the
251
+ heading/text are inserted immediately before the form.
252
+
253
+ Args:
254
+ html: HTML content (fragment or complete document)
255
+ title: Optional page title
256
+ text: Optional instructional text
257
+
258
+ Returns:
259
+ Complete HTML document
260
+ """
261
+ if not re.search(r'<!DOCTYPE|<html', html, re.IGNORECASE):
262
+ return render_page(html, title, text)
263
+
264
+ if title and not re.search(r'<title[\s>]', html, re.IGNORECASE):
265
+ html = re.sub(r'<head[^>]*>', lambda m: m.group(0) + f'<title>{escape_html(title)}</title>',
266
+ html, count=1, flags=re.IGNORECASE)
267
+
268
+ prefix = ''
269
+ if title:
270
+ prefix += f'<h1>{escape_html(title)}</h1>'
271
+ if text:
272
+ prefix += f'<p>{escape_html(text)}</p>'
273
+ if prefix:
274
+ detector = _detect(html)
275
+ if detector.form_start is not None:
276
+ html = html[:detector.form_start] + prefix + html[detector.form_start:]
277
+
278
+ return html
279
+
280
+
281
+ def escape_html(text: Optional[str]) -> str:
282
+ """Escape HTML special characters (including quotes) in text."""
283
+ if not text:
284
+ return ''
285
+ return html_mod.escape(text, quote=True)
readwebform/py.typed ADDED
File without changes