chickinfry 0.5.0.dev1__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.
@@ -0,0 +1,250 @@
1
+ """Windows owner-only creation; loaded only on Windows."""
2
+
3
+ import ctypes
4
+ from collections.abc import Iterator
5
+ from contextlib import ExitStack, contextmanager
6
+ from ctypes import wintypes
7
+ from pathlib import Path
8
+ from typing import cast
9
+
10
+ from .errors import _storage_error
11
+
12
+
13
+ def _api(name: str) -> ctypes.CDLL:
14
+ loader = getattr(ctypes, "WinDLL", None)
15
+ if loader is None:
16
+ raise _storage_error("failed_precondition")
17
+ return cast(ctypes.CDLL, loader(name, use_last_error=True))
18
+
19
+
20
+ class _Attributes(ctypes.Structure):
21
+ _fields_ = [
22
+ ("length", wintypes.DWORD),
23
+ ("descriptor", ctypes.c_void_p),
24
+ ("inherit", wintypes.BOOL),
25
+ ]
26
+
27
+
28
+ def _user_sid() -> str:
29
+ kernel = _api("kernel32")
30
+ security = _api("advapi32")
31
+ kernel.GetCurrentProcess.argtypes = []
32
+ kernel.GetCurrentProcess.restype = wintypes.HANDLE
33
+ security.OpenProcessToken.argtypes = [
34
+ wintypes.HANDLE,
35
+ wintypes.DWORD,
36
+ ctypes.POINTER(wintypes.HANDLE),
37
+ ]
38
+ security.OpenProcessToken.restype = wintypes.BOOL
39
+ security.GetTokenInformation.argtypes = [
40
+ wintypes.HANDLE,
41
+ ctypes.c_int,
42
+ ctypes.c_void_p,
43
+ wintypes.DWORD,
44
+ ctypes.POINTER(wintypes.DWORD),
45
+ ]
46
+ security.GetTokenInformation.restype = wintypes.BOOL
47
+ security.ConvertSidToStringSidW.argtypes = [
48
+ ctypes.c_void_p,
49
+ ctypes.POINTER(ctypes.c_void_p),
50
+ ]
51
+ security.ConvertSidToStringSidW.restype = wintypes.BOOL
52
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
53
+ kernel.CloseHandle.restype = wintypes.BOOL
54
+ token = wintypes.HANDLE()
55
+ if not security.OpenProcessToken(
56
+ kernel.GetCurrentProcess(), 8, ctypes.byref(token)
57
+ ):
58
+ raise _storage_error("failed_precondition")
59
+ pointer = ctypes.c_void_p()
60
+ try:
61
+ size = wintypes.DWORD()
62
+ security.GetTokenInformation(token, 1, None, 0, ctypes.byref(size))
63
+ if not size.value:
64
+ raise _storage_error("failed_precondition")
65
+ buffer = ctypes.create_string_buffer(size.value)
66
+ if not security.GetTokenInformation(token, 1, buffer, size, ctypes.byref(size)):
67
+ raise _storage_error("failed_precondition")
68
+ sid = ctypes.cast(buffer, ctypes.POINTER(ctypes.c_void_p)).contents
69
+ if not security.ConvertSidToStringSidW(sid, ctypes.byref(pointer)):
70
+ raise _storage_error("failed_precondition")
71
+ return ctypes.wstring_at(pointer)
72
+ finally:
73
+ if pointer.value is not None:
74
+ _free(pointer)
75
+ kernel.CloseHandle(token)
76
+
77
+
78
+ def _descriptor(directory: bool = False) -> tuple[ctypes.c_void_p, _Attributes]:
79
+ security = _api("advapi32")
80
+ pointer = ctypes.c_void_p()
81
+ convert = security.ConvertStringSecurityDescriptorToSecurityDescriptorW
82
+ convert.argtypes = [
83
+ wintypes.LPCWSTR,
84
+ wintypes.DWORD,
85
+ ctypes.POINTER(ctypes.c_void_p),
86
+ ctypes.c_void_p,
87
+ ]
88
+ convert.restype = wintypes.BOOL
89
+ sid = _user_sid()
90
+ flags = "OICI" if directory else ""
91
+ if not convert(
92
+ f"O:{sid}D:P(A;{flags};FA;;;{sid})",
93
+ 1,
94
+ ctypes.byref(pointer),
95
+ None,
96
+ ):
97
+ raise _storage_error("failed_precondition")
98
+ return pointer, _Attributes(ctypes.sizeof(_Attributes), pointer, False)
99
+
100
+
101
+ def _free(pointer: ctypes.c_void_p) -> None:
102
+ kernel = _api("kernel32")
103
+ kernel.LocalFree.argtypes = [ctypes.c_void_p]
104
+ kernel.LocalFree.restype = ctypes.c_void_p
105
+ kernel.LocalFree(pointer)
106
+
107
+
108
+ def _mkdir(path: Path) -> None:
109
+ pointer, attributes = _descriptor(True)
110
+ try:
111
+ kernel = _api("kernel32")
112
+ create = kernel.CreateDirectoryW
113
+ create.argtypes = [wintypes.LPCWSTR, ctypes.POINTER(_Attributes)]
114
+ create.restype = wintypes.BOOL
115
+ if not create(str(path), ctypes.byref(attributes)):
116
+ if int(getattr(ctypes, "get_last_error")()) == 183:
117
+ raise FileExistsError
118
+ raise _storage_error("failed_precondition")
119
+ finally:
120
+ _free(pointer)
121
+
122
+
123
+ def _create(path: Path) -> None:
124
+ pointer, attributes = _descriptor()
125
+ try:
126
+ kernel = _api("kernel32")
127
+ create = kernel.CreateFileW
128
+ create.argtypes = [
129
+ wintypes.LPCWSTR,
130
+ wintypes.DWORD,
131
+ wintypes.DWORD,
132
+ ctypes.POINTER(_Attributes),
133
+ wintypes.DWORD,
134
+ wintypes.DWORD,
135
+ wintypes.HANDLE,
136
+ ]
137
+ create.restype = wintypes.HANDLE
138
+ handle = create(
139
+ str(path), 0x40000000, 0, ctypes.byref(attributes), 1, 0x80, None
140
+ )
141
+ if handle == ctypes.c_void_p(-1).value:
142
+ if int(getattr(ctypes, "get_last_error")()) in (80, 183):
143
+ raise FileExistsError
144
+ raise _storage_error("failed_precondition")
145
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
146
+ kernel.CloseHandle.restype = wintypes.BOOL
147
+ kernel.CloseHandle(handle)
148
+ finally:
149
+ _free(pointer)
150
+
151
+
152
+ def _check_acl(path: Path) -> None:
153
+ security = _api("advapi32")
154
+ get = security.GetNamedSecurityInfoW
155
+ get.argtypes = [
156
+ wintypes.LPWSTR,
157
+ wintypes.DWORD,
158
+ wintypes.DWORD,
159
+ ctypes.c_void_p,
160
+ ctypes.c_void_p,
161
+ ctypes.c_void_p,
162
+ ctypes.c_void_p,
163
+ ctypes.POINTER(ctypes.c_void_p),
164
+ ]
165
+ get.restype = wintypes.DWORD
166
+ pointer = ctypes.c_void_p()
167
+ if get(str(path), 1, 5, None, None, None, None, ctypes.byref(pointer)) != 0:
168
+ raise _storage_error("failed_precondition")
169
+ text = ctypes.c_void_p()
170
+ try:
171
+ convert = security.ConvertSecurityDescriptorToStringSecurityDescriptorW
172
+ convert.argtypes = [
173
+ ctypes.c_void_p,
174
+ wintypes.DWORD,
175
+ wintypes.DWORD,
176
+ ctypes.POINTER(ctypes.c_void_p),
177
+ ctypes.c_void_p,
178
+ ]
179
+ convert.restype = wintypes.BOOL
180
+ if not convert(pointer, 1, 5, ctypes.byref(text), None):
181
+ raise _storage_error("failed_precondition")
182
+ sid = _user_sid()
183
+ if ctypes.wstring_at(text) not in {
184
+ f"O:{sid}D:P(A;;FA;;;{sid})",
185
+ f"O:{sid}D:P(A;OICI;FA;;;{sid})",
186
+ f"O:{sid}D:AI(A;ID;FA;;;{sid})",
187
+ }:
188
+ raise _storage_error("failed_precondition")
189
+ finally:
190
+ if text.value is not None:
191
+ _free(text)
192
+ _free(pointer)
193
+
194
+
195
+ class _AttributeTag(ctypes.Structure):
196
+ _fields_ = [("attributes", wintypes.DWORD), ("tag", wintypes.DWORD)]
197
+
198
+
199
+ @contextmanager
200
+ def _pin_directory(path: Path) -> Iterator[None]:
201
+ if not path.is_absolute() or ".." in path.parts:
202
+ raise _storage_error("failed_precondition")
203
+ kernel = _api("kernel32")
204
+ create = kernel.CreateFileW
205
+ create.argtypes = [
206
+ wintypes.LPCWSTR,
207
+ wintypes.DWORD,
208
+ wintypes.DWORD,
209
+ ctypes.c_void_p,
210
+ wintypes.DWORD,
211
+ wintypes.DWORD,
212
+ wintypes.HANDLE,
213
+ ]
214
+ create.restype = wintypes.HANDLE
215
+ information = kernel.GetFileInformationByHandleEx
216
+ information.argtypes = [
217
+ wintypes.HANDLE,
218
+ ctypes.c_int,
219
+ ctypes.c_void_p,
220
+ wintypes.DWORD,
221
+ ]
222
+ information.restype = wintypes.BOOL
223
+ kernel.CloseHandle.argtypes = [wintypes.HANDLE]
224
+ kernel.CloseHandle.restype = wintypes.BOOL
225
+ with ExitStack() as held:
226
+ for folder in (*reversed(path.parents), path):
227
+ # Excluding FILE_SHARE_DELETE pins every ancestor against rename/removal.
228
+ handle = create(str(folder), 0x80, 3, None, 3, 0x02200000, None)
229
+ if handle == ctypes.c_void_p(-1).value:
230
+ if (
231
+ int(getattr(ctypes, "get_last_error")()) not in (2, 3)
232
+ or folder == folder.parent
233
+ ):
234
+ raise _storage_error("failed_precondition")
235
+ try:
236
+ _mkdir(folder)
237
+ except FileExistsError:
238
+ pass
239
+ handle = create(str(folder), 0x80, 3, None, 3, 0x02200000, None)
240
+ if handle == ctypes.c_void_p(-1).value:
241
+ raise _storage_error("failed_precondition")
242
+ held.callback(kernel.CloseHandle, handle)
243
+ info = _AttributeTag()
244
+ if (
245
+ not information(handle, 9, ctypes.byref(info), ctypes.sizeof(info))
246
+ or not info.attributes & 0x10
247
+ or info.attributes & 0x400
248
+ ):
249
+ raise _storage_error("failed_precondition")
250
+ yield
@@ -0,0 +1,76 @@
1
+ import re
2
+ from dataclasses import dataclass
3
+ from itertools import islice
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class FieldError:
8
+ """A declared input path and its public validation code."""
9
+
10
+ path: str
11
+ code: str
12
+
13
+
14
+ def _string(value: object) -> str | None:
15
+ return str.__str__(value) if isinstance(value, str) else None
16
+
17
+
18
+ def _message(value: object) -> str | None:
19
+ try:
20
+ text = _string(value)
21
+ if text is None or re.search(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]", text):
22
+ return None
23
+ return text if len(text.encode("utf-8")) <= 1024 else None
24
+ except Exception:
25
+ return None
26
+
27
+
28
+ def _fields(
29
+ value: object, declared: frozenset[str] | None = None
30
+ ) -> tuple[FieldError, ...]:
31
+ try:
32
+ if isinstance(value, tuple):
33
+ items = tuple(islice(tuple.__iter__(value), 33))
34
+ elif isinstance(value, list):
35
+ items = tuple(islice(list.__iter__(value), 33))
36
+ else:
37
+ return ()
38
+ if len(items) > 32:
39
+ return ()
40
+ allowed = None
41
+ if declared is not None:
42
+ if not isinstance(declared, frozenset):
43
+ return ()
44
+ allowed = frozenset(_string(name) for name in frozenset.__iter__(declared))
45
+ result: list[FieldError] = []
46
+ field = r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*"
47
+ for item in items:
48
+ if isinstance(item, FieldError):
49
+ path, code = _string(item.path), _string(item.code)
50
+ elif isinstance(item, dict):
51
+ entries = tuple(islice(dict.items(item), 3))
52
+ record = {_string(key): value for key, value in entries}
53
+ if len(entries) != 2 or set(record) != {"path", "code"}:
54
+ return ()
55
+ path, code = _string(record["path"]), _string(record["code"])
56
+ else:
57
+ return ()
58
+ if (
59
+ path is None
60
+ or code is None
61
+ or len(path.encode("utf-8", errors="surrogatepass")) > 256
62
+ or not re.fullmatch(
63
+ field + r"(?:\." + field + r"|\[(?:0|[1-9][0-9]*)\])*", path
64
+ )
65
+ or not re.fullmatch(r"[a-z_]{1,64}", code)
66
+ or any(
67
+ int(index) > 4294967295
68
+ for index in re.findall(r"\[([0-9]+)\]", path)
69
+ )
70
+ or (allowed is not None and path not in allowed)
71
+ ):
72
+ return ()
73
+ result.append(FieldError(path, code))
74
+ return tuple(result)
75
+ except Exception:
76
+ return ()
@@ -0,0 +1,165 @@
1
+ import importlib.util
2
+ import json
3
+ import math
4
+ import re
5
+ import sys
6
+ import zlib
7
+ from collections.abc import Mapping
8
+ from http.cookiejar import Cookie, DefaultCookiePolicy
9
+ from typing import cast
10
+ from urllib.request import Request
11
+
12
+ from ._conformance import _observer
13
+ from .errors import ClientError, FieldError, OperationError, _local_error
14
+
15
+ _REQUEST_LIMIT = 4 * 1024 * 1024
16
+ _RESPONSE_LIMIT = 1024 * 1024
17
+ _HEADERS = {"Accept-Encoding": "gzip, deflate", "Cache-Control": "no-store"}
18
+
19
+
20
+ def _check_environment() -> None:
21
+ if (
22
+ sys.platform in {"emscripten", "wasi"}
23
+ or "pyodide" in sys.modules
24
+ or importlib.util.find_spec("pyodide") is not None
25
+ ):
26
+ raise ClientError("unimplemented")
27
+
28
+
29
+ def _timeout(value: float) -> float:
30
+ if (
31
+ isinstance(value, bool)
32
+ or not isinstance(value, (float, int))
33
+ or not math.isfinite(value)
34
+ or value <= 0
35
+ ):
36
+ raise _local_error("invalid_argument", "invalid_timeout")
37
+ return float(value)
38
+
39
+
40
+ def _operation(value: str) -> None:
41
+ if not isinstance(value, str) or not re.fullmatch(
42
+ r"[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*", value
43
+ ):
44
+ raise _local_error("invalid_argument", "invalid_operation")
45
+
46
+
47
+ def _reject_constant(value: str) -> object:
48
+ raise ValueError
49
+
50
+
51
+ def _json_value(body: bytes) -> object:
52
+ try:
53
+ return cast(
54
+ object, json.loads(body.decode("utf-8"), parse_constant=_reject_constant)
55
+ )
56
+ except (ValueError, UnicodeError, RecursionError):
57
+ pass
58
+ raise ClientError("internal")
59
+
60
+
61
+ def _serialize(payload: bytes | Mapping[str, object]) -> bytes:
62
+ body: bytes | None = None
63
+ try:
64
+ if isinstance(payload, bytes):
65
+ body = payload
66
+ elif isinstance(payload, Mapping):
67
+ if any(not isinstance(key, str) for key in payload):
68
+ raise ValueError
69
+ body = json.dumps(
70
+ dict(payload),
71
+ ensure_ascii=False,
72
+ separators=(",", ":"),
73
+ allow_nan=False,
74
+ ).encode("utf-8")
75
+ except (ValueError, TypeError, UnicodeError, RecursionError):
76
+ pass
77
+ if body is None:
78
+ raise ClientError("invalid_argument")
79
+ if len(body) > _REQUEST_LIMIT:
80
+ raise ClientError("resource_exhausted")
81
+ try:
82
+ if isinstance(_json_value(body), dict):
83
+ return body
84
+ except ClientError:
85
+ pass
86
+ raise ClientError("invalid_argument")
87
+
88
+
89
+ def _response(data: bytes, status: int) -> object:
90
+ invalid = False
91
+ try:
92
+ value = _json_value(data)
93
+ except ClientError:
94
+ invalid = True
95
+ value = None
96
+ if not 200 <= status < 300:
97
+ code = value.get("error") if isinstance(value, dict) else None
98
+ if not isinstance(code, str) or re.fullmatch(r"[a-z_]+", code) is None:
99
+ raise _local_error("internal", "operation_failed", status)
100
+ failure = OperationError(
101
+ code,
102
+ status,
103
+ cast(str | None, value.get("message")) if isinstance(value, dict) else None,
104
+ cast(tuple[FieldError, ...], value.get("fields"))
105
+ if isinstance(value, dict)
106
+ else (),
107
+ )
108
+ failure._valid_error_envelope = True
109
+ raise failure
110
+ if invalid:
111
+ raise ClientError("internal", status)
112
+ return value
113
+
114
+
115
+ class _NoCookies(DefaultCookiePolicy):
116
+ def set_ok(self, cookie: Cookie, request: Request) -> bool:
117
+ return False
118
+
119
+ def return_ok(self, cookie: Cookie, request: Request) -> bool:
120
+ return False
121
+
122
+
123
+ class _Body:
124
+ def __init__(self, encoding: str, status: int) -> None:
125
+ self._status = status
126
+ encoding = encoding.lower()
127
+ if encoding not in {"identity", "gzip", "deflate"}:
128
+ raise ClientError("internal", status)
129
+ self._decoder = (
130
+ zlib.decompressobj(31 if encoding == "gzip" else 15)
131
+ if encoding != "identity"
132
+ else None
133
+ )
134
+ self._body = bytearray()
135
+ self._raw_size = 0
136
+
137
+ def feed(self, chunk: bytes) -> None:
138
+ observation = _observer.get()
139
+ self._raw_size += len(chunk)
140
+ if self._raw_size > _RESPONSE_LIMIT:
141
+ if observation is not None:
142
+ observation.notify("limit", self)
143
+ raise _local_error("resource_exhausted", "response_too_large", self._status)
144
+ decoded: bytes | None = None
145
+ try:
146
+ # Decompression bombs are also limited to the remaining budget plus one byte.
147
+ decoded = (
148
+ self._decoder.decompress(chunk, _RESPONSE_LIMIT - len(self._body) + 1)
149
+ if self._decoder
150
+ else chunk
151
+ )
152
+ except zlib.error:
153
+ pass
154
+ if decoded is None:
155
+ raise ClientError("internal", self._status)
156
+ self._body.extend(decoded)
157
+ if len(self._body) > _RESPONSE_LIMIT:
158
+ if observation is not None:
159
+ observation.notify("limit", self)
160
+ raise _local_error("resource_exhausted", "response_too_large", self._status)
161
+
162
+ def finish(self) -> bytes:
163
+ if self._decoder and (not self._decoder.eof or self._decoder.unused_data):
164
+ raise ClientError("internal", self._status)
165
+ return bytes(self._body)
chickinfry/_input.py ADDED
@@ -0,0 +1,129 @@
1
+ """Server-only readers and the shared budget for generated input decoders."""
2
+
3
+ import json
4
+ import math
5
+ from collections.abc import Callable, Mapping
6
+ from typing import TypeVar, cast
7
+
8
+ from .server import MAX_REQUEST_BYTES, OperationError
9
+
10
+ T = TypeVar("T")
11
+
12
+
13
+ def read_record(value: object) -> dict[str, object]:
14
+ if not isinstance(value, dict) or any(not isinstance(key, str) for key in value):
15
+ raise ValueError("An object with string keys is required.")
16
+ return cast(dict[str, object], value)
17
+
18
+
19
+ def read_string(value: object) -> str:
20
+ if not isinstance(value, str):
21
+ raise ValueError("A string is required.")
22
+ return value
23
+
24
+
25
+ def read_list(value: object, decode: Callable[[object], T]) -> list[T]:
26
+ if not isinstance(value, list):
27
+ raise ValueError("A list is required.")
28
+ return [decode(item) for item in value]
29
+
30
+
31
+ def read_nullable(value: object, decode: Callable[[object], T]) -> T | None:
32
+ return None if value is None else decode(value)
33
+
34
+
35
+ def _string_size(value: str) -> int:
36
+ return len(
37
+ json.dumps(value, ensure_ascii=False).encode("utf-8", errors="backslashreplace")
38
+ )
39
+
40
+
41
+ def _number_size(value: int | float) -> int:
42
+ try:
43
+ number = float(value)
44
+ except OverflowError:
45
+ return 4
46
+ if not math.isfinite(number):
47
+ return 4
48
+ if number == 0:
49
+ return 1
50
+ sign = 1 if number < 0 else 0
51
+ mantissa, _, exponent = repr(abs(number)).partition("e")
52
+ integer, _, fraction = mantissa.partition(".")
53
+ raw = (integer + fraction).lstrip("0")
54
+ digits = raw.rstrip("0")
55
+ power = int(exponent or "0") - len(fraction) + len(raw) - len(digits)
56
+ count, point = len(digits), len(digits) + power
57
+ # ECMAScript Number::toString uses this decimal layout for binary64 values.
58
+ if count <= point <= 21:
59
+ return sign + point
60
+ if 0 < point <= 21:
61
+ return sign + count + 1
62
+ if -6 < point <= 0:
63
+ return sign + 2 - point + count
64
+ return sign + count + (1 if count > 1 else 0) + 2 + len(str(abs(point - 1)))
65
+
66
+
67
+ def _json_size(value: object) -> int:
68
+ size = 0
69
+ pending: list[object] = [value]
70
+ while pending:
71
+ current = pending.pop()
72
+ if current is None or current is True:
73
+ size += 4
74
+ elif current is False:
75
+ size += 5
76
+ elif isinstance(current, str):
77
+ size += _string_size(current)
78
+ elif isinstance(current, (int, float)):
79
+ size += _number_size(current)
80
+ elif isinstance(current, Mapping):
81
+ size += 2 + max(0, len(current) - 1) + len(current)
82
+ for key, child in current.items():
83
+ if not isinstance(key, str):
84
+ raise ValueError("A string key is required.")
85
+ size += _string_size(key)
86
+ pending.append(child)
87
+ elif isinstance(current, list):
88
+ size += 2 + max(0, len(current) - 1)
89
+ pending.extend(current)
90
+ else:
91
+ raise ValueError("A JSON value is required.")
92
+ return size
93
+
94
+
95
+ class InputBudget:
96
+ def __init__(self, value: Mapping[str, object]) -> None:
97
+ self.size = _json_size(value)
98
+ self._check()
99
+ # Retain records so object identities cannot be reused during decoding.
100
+ self._counts: dict[int, tuple[Mapping[str, object], int]] = {}
101
+
102
+ def default(self, record: Mapping[str, object], key: str, literal: str) -> object:
103
+ count = self._counts.get(id(record), (record, len(record)))[1]
104
+ self.size += (
105
+ _string_size(key)
106
+ + 1
107
+ + (1 if count else 0)
108
+ + len(literal.encode("utf-8", errors="backslashreplace"))
109
+ )
110
+ self._check()
111
+ self._counts[id(record)] = (record, count + 1)
112
+ return cast(object, json.loads(literal))
113
+
114
+ def _check(self) -> None:
115
+ if self.size > MAX_REQUEST_BYTES:
116
+ raise OperationError("request_too_large", 413)
117
+
118
+
119
+ def read_field(
120
+ record: Mapping[str, object],
121
+ key: str,
122
+ budget: InputBudget,
123
+ default: str | None = None,
124
+ ) -> object:
125
+ if key in record:
126
+ return record[key]
127
+ if default is None:
128
+ raise ValueError("A required field is missing.")
129
+ return budget.default(record, key, default)
chickinfry/_origin.py ADDED
@@ -0,0 +1,60 @@
1
+ import ipaddress
2
+ import re
3
+ from urllib.parse import urlsplit
4
+
5
+ from .errors import _local_error
6
+
7
+
8
+ def canonical_origin(origin: str) -> str:
9
+ if (
10
+ not isinstance(origin, str)
11
+ or not origin
12
+ or any(ord(char) <= 32 or ord(char) == 127 for char in origin)
13
+ or any(char in origin for char in "? #@\\%")
14
+ ):
15
+ raise _local_error("invalid_argument", "invalid_origin")
16
+ result: str | None = None
17
+ try:
18
+ parsed = urlsplit(origin)
19
+ host = parsed.hostname
20
+ port = parsed.port
21
+ if any(char in parsed.netloc for char in "[]") and not re.fullmatch(
22
+ r"\[[^\[\]]+\](?::[0-9]+)?", parsed.netloc
23
+ ):
24
+ raise ValueError
25
+ if (
26
+ parsed.scheme in {"http", "https"}
27
+ and host
28
+ and parsed.path in {"", "/"}
29
+ and not parsed.netloc.endswith(":")
30
+ and (port is None or port > 0)
31
+ ):
32
+ address: ipaddress.IPv4Address | ipaddress.IPv6Address | None = None
33
+ try:
34
+ address = ipaddress.ip_address(host)
35
+ except ValueError:
36
+ pass
37
+ if parsed.scheme == "https" or (
38
+ address
39
+ and (
40
+ address.is_loopback
41
+ if isinstance(address, ipaddress.IPv4Address)
42
+ else address == ipaddress.IPv6Address("::1")
43
+ )
44
+ ):
45
+ if address:
46
+ host = (
47
+ f"[{address.compressed}]"
48
+ if address.version == 6
49
+ else str(address)
50
+ )
51
+ elif not re.fullmatch(r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?", host):
52
+ raise ValueError
53
+ default = 443 if parsed.scheme == "https" else 80
54
+ suffix = f":{port}" if port and port != default else ""
55
+ result = f"{parsed.scheme}://{host}{suffix}"
56
+ except ValueError:
57
+ pass
58
+ if result is None:
59
+ raise _local_error("invalid_argument", "invalid_origin")
60
+ return result