ser2netweb 3.1.0__tar.gz → 3.1.1__tar.gz

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.
Files changed (134) hide show
  1. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/PKG-INFO +1 -1
  2. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/__init__.py +1 -1
  3. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/api.py +45 -37
  4. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/auth.py +39 -20
  5. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/certinfo.py +1 -1
  6. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/ldap_auth.py +35 -23
  7. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/oidc_auth.py +34 -20
  8. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/proxy.py +37 -26
  9. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/__init__.py +3 -2
  10. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/cluster.py +109 -57
  11. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/common.py +6 -5
  12. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/console.py +34 -20
  13. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/forms.py +48 -27
  14. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/login.py +38 -26
  15. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/mappings.py +38 -30
  16. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/ops.py +30 -19
  17. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/settings.py +115 -94
  18. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/system.py +23 -16
  19. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/routes/totp.py +34 -24
  20. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/server.py +25 -14
  21. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/tlsupload.py +8 -3
  22. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/totp.py +4 -3
  23. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb.egg-info/PKG-INFO +1 -1
  24. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/COMMERCIAL_LICENSE.md +0 -0
  25. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/LICENSE +0 -0
  26. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/MANIFEST.in +0 -0
  27. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/NOTICE +0 -0
  28. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/THIRD-PARTY-NOTICES.md +0 -0
  29. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/packaging/README.pypi.md +0 -0
  30. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/pyproject.toml +0 -0
  31. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/__main__.py +0 -0
  32. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/accounts.py +0 -0
  33. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/capture.py +0 -0
  34. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/certwatch.py +0 -0
  35. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/cli.py +0 -0
  36. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/clock.py +0 -0
  37. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/clockwatch.py +0 -0
  38. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/config.py +0 -0
  39. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/console.py +0 -0
  40. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/datalock.py +0 -0
  41. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/__init__.py +0 -0
  42. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/access.py +0 -0
  43. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/bindhint.py +0 -0
  44. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/bridge.py +0 -0
  45. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/cluster.py +0 -0
  46. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/modbus.py +0 -0
  47. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/modbus_gateway.py +0 -0
  48. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/mqtt_pub.py +0 -0
  49. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/netguard.py +0 -0
  50. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/netinfo.py +0 -0
  51. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/pool.py +0 -0
  52. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/portdiag.py +0 -0
  53. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/portlist.py +0 -0
  54. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/protocols/__init__.py +0 -0
  55. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/protocols/base.py +0 -0
  56. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/protocols/raw.py +0 -0
  57. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/protocols/rfc2217.py +0 -0
  58. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/protocols/telnet.py +0 -0
  59. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/serial_compat.py +0 -0
  60. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/serial_io.py +0 -0
  61. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/serial_link.py +0 -0
  62. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/serial_transport.py +0 -0
  63. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/sockopts.py +0 -0
  64. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/sparkplug.py +0 -0
  65. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/sparkplug_node.py +0 -0
  66. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/supervisor.py +0 -0
  67. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/engine/tls.py +0 -0
  68. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/envvars.py +0 -0
  69. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/explain.py +0 -0
  70. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/healthcheck.py +0 -0
  71. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/i18n.py +0 -0
  72. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/importer.py +0 -0
  73. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/layout.py +0 -0
  74. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/licences.py +0 -0
  75. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/locale/tr.json +0 -0
  76. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/logsetup.py +0 -0
  77. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/logtext.py +0 -0
  78. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/notify.py +0 -0
  79. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/optional.py +0 -0
  80. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/reload.py +0 -0
  81. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/runtime.py +0 -0
  82. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/sdnotify.py +0 -0
  83. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/ser2net_import.py +0 -0
  84. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/signins.py +0 -0
  85. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/standalone.py +0 -0
  86. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/state.py +0 -0
  87. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/storage.py +0 -0
  88. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/textfold.py +0 -0
  89. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/tlsreload.py +0 -0
  90. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/watchdog.py +0 -0
  91. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/__init__.py +0 -0
  92. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/httpguard.py +0 -0
  93. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/selfsigned.py +0 -0
  94. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/starlette_compat.py +0 -0
  95. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/app.css +0 -0
  96. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/app.js +0 -0
  97. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/htmx.min.js +0 -0
  98. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/points.js +0 -0
  99. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/theme.js +0 -0
  100. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/xterm-addon-fit.js +0 -0
  101. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/xterm.css +0 -0
  102. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/static/xterm.js +0 -0
  103. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_cluster_body.html +0 -0
  104. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_console.html +0 -0
  105. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_footer.html +0 -0
  106. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_login_notice.html +0 -0
  107. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_macros.html +0 -0
  108. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_mapping_form.html +0 -0
  109. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_mapping_log.html +0 -0
  110. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_mapping_traces.html +0 -0
  111. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_mappings_body.html +0 -0
  112. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_modbus_read.html +0 -0
  113. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_ports_table.html +0 -0
  114. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_serial_port_select.html +0 -0
  115. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/_shell.html +0 -0
  116. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/audit.html +0 -0
  117. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/base.html +0 -0
  118. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/dashboard.html +0 -0
  119. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/licenses.html +0 -0
  120. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/login.html +0 -0
  121. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/login_totp.html +0 -0
  122. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/settings.html +0 -0
  123. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/setup.html +0 -0
  124. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/web/templates/totp.html +0 -0
  125. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb/winservice.py +0 -0
  126. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb.egg-info/SOURCES.txt +0 -0
  127. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb.egg-info/dependency_links.txt +0 -0
  128. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb.egg-info/entry_points.txt +0 -0
  129. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb.egg-info/requires.txt +0 -0
  130. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/ser2netweb.egg-info/top_level.txt +0 -0
  131. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/setup.cfg +0 -0
  132. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/tools/licenses/npm/htmx.org.txt +0 -0
  133. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/tools/licenses/npm/xterm-addon-fit.txt +0 -0
  134. {ser2netweb-3.1.0 → ser2netweb-3.1.1}/tools/licenses/npm/xterm.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ser2netweb
3
- Version: 3.1.0
3
+ Version: 3.1.1
4
4
  Summary: Serial-to-network bridge with a web UI: raw TCP, telnet, RFC 2217, UDP, Modbus gateway, MQTT
5
5
  Author-email: Halis KILIÇ <mail@haliskilic.com.tr>
6
6
  License-Expression: AGPL-3.0-only
@@ -1,7 +1,7 @@
1
1
  """ser2netweb — serial-to-network bridge with a web config UI."""
2
2
 
3
3
  # Single source of truth for the version (ser2netweb.py and the web layer import this).
4
- __version__ = "3.1.0"
4
+ __version__ = "3.1.1"
5
5
 
6
6
  # The product's name: up to 2.9.x it was ser2net (no relation to the C ser2net it can
7
7
  # import the configuration of; NOTICE)
@@ -12,11 +12,11 @@ from __future__ import annotations
12
12
  import asyncio
13
13
  import dataclasses
14
14
  import typing
15
- from typing import TYPE_CHECKING, Optional
15
+ from typing import TYPE_CHECKING, Any, Optional
16
16
 
17
17
  from starlette.exceptions import HTTPException
18
18
  from starlette.requests import Request
19
- from starlette.responses import JSONResponse, PlainTextResponse
19
+ from starlette.responses import JSONResponse, PlainTextResponse, Response
20
20
 
21
21
  from .. import __version__, capture, config, importer
22
22
  from ..config import (REDACTED, ROLE_RANK, ConfigError, ConfigWriteError, MappingConfig,
@@ -29,6 +29,7 @@ from .routes.mappings import snapshot_response
29
29
  from .routes.system import METRICS_TYPE, metrics_text
30
30
 
31
31
  if TYPE_CHECKING:
32
+ from ..config import AdminUI
32
33
  from ..state import AppState
33
34
 
34
35
  API_PREFIX = "/api/v1"
@@ -40,14 +41,14 @@ _BOOLEANS = {"true": True, "1": True, "yes": True, "false": False, "0": False, "
40
41
  API_VERSION = "1.2.0"
41
42
  API_FEATURES = ("warnings", "changed", "if-match", "traces", "capture", "pools")
42
43
 
43
- def _caller(request) -> str:
44
+ def _caller(request: Request) -> str:
44
45
  """Who calls, for the audit log: the token's name (api-token:<name>), 'api-token' for
45
46
  the token of api_token_hash."""
46
47
  token = getattr(request.state, "api_token", None)
47
48
  return token.audit_label if token is not None else "api-token"
48
49
 
49
50
 
50
- def _operator_token(request, state) -> bool:
51
+ def _operator_token(request: Request, state: AppState) -> bool:
51
52
  """Is the calling token an operator's or an admin's? (GuardMiddleware refuses a viewer
52
53
  token's POST, PUT, PATCH and DELETE itself; a GET that only they may make asks here.)"""
53
54
  token = getattr(request.state, "api_token", None)
@@ -81,14 +82,18 @@ def _mapping_view(mapping: MappingConfig, state: AppState,
81
82
  return view
82
83
 
83
84
 
84
- async def _check_tls_files(mapping) -> None:
85
+ async def _check_tls_files(mapping: MappingConfig) -> None:
85
86
  """MappingConfig.check_tls_files and check_mqtt_tls_files, off the event loop (they
86
87
  read the files)."""
87
88
  await asyncio.to_thread(mapping.check_tls_files)
88
89
  await asyncio.to_thread(mapping.check_mqtt_tls_files)
89
90
 
90
91
 
91
- def merge_patch(target, patch):
92
+ @typing.overload
93
+ def merge_patch(target: object, patch: dict) -> dict: ...
94
+ @typing.overload
95
+ def merge_patch(target: object, patch: object) -> object: ...
96
+ def merge_patch(target: object, patch: object) -> object:
92
97
  """RFC 7396 JSON merge patch: `patch` applied to `target` (neither is changed). An
93
98
  object in the patch is merged key by key into the target's (a missing or non-object
94
99
  target counts as empty), null removes a key, anything else replaces the value."""
@@ -103,7 +108,8 @@ def merge_patch(target, patch):
103
108
  return out
104
109
 
105
110
 
106
- def _edit_view(mapping, state, request=None) -> dict:
111
+ def _edit_view(mapping: MappingConfig, state: AppState,
112
+ request: Optional[Request] = None) -> dict:
107
113
  """The response to a create / update: the mapping as stored (_mapping_view), and when
108
114
  there are any, the `warnings` about what was sent (keys that are no setting, a setting
109
115
  replaced by a supported one) and about settings it has that do nothing
@@ -122,12 +128,12 @@ def _edit_view(mapping, state, request=None) -> dict:
122
128
  _BAD_INPUT = (ValueError, TypeError, AttributeError, OverflowError)
123
129
 
124
130
 
125
- def _etag(state, mapping) -> str:
131
+ def _etag(state: AppState, mapping: MappingConfig) -> str:
126
132
  """A mapping's ETag: its revision (config.mapping_revision), as a strong entity tag."""
127
133
  return f'"{mapping_revision(state.config.secret_key, mapping)}"'
128
134
 
129
135
 
130
- def _if_match(request, state, mapping) -> bool:
136
+ def _if_match(request: Request, state: AppState, mapping: MappingConfig) -> bool:
131
137
  """True unless the request has an If-Match header that names neither the mapping's
132
138
  current ETag nor "*" (RFC 9110: strong comparison, so a weak tag never matches). A
133
139
  client that sends no If-Match changes the mapping whatever its revision, as before."""
@@ -152,16 +158,16 @@ def _not_saved(e: ConfigError) -> JSONResponse:
152
158
 
153
159
 
154
160
  def build_api_routes(state: AppState) -> list[Route]:
155
- async def list_mappings(request):
161
+ async def list_mappings(request: Request) -> JSONResponse:
156
162
  return JSONResponse({"mappings": [_mapping_view(m, state, request) for m in state.config.mappings]})
157
163
 
158
- async def get_mapping(request):
164
+ async def get_mapping(request: Request) -> JSONResponse:
159
165
  m = state.config.get_mapping(request.path_params["mid"])
160
166
  if not m:
161
167
  return JSONResponse({"error": "not_found"}, status_code=404)
162
168
  return JSONResponse(_mapping_view(m, state, request), headers={"ETag": _etag(state, m)})
163
169
 
164
- async def create_mapping(request):
170
+ async def create_mapping(request: Request) -> Response:
165
171
  try:
166
172
  body = await request.json()
167
173
  except HTTPException: # a body over the size limit: 413
@@ -196,7 +202,7 @@ def build_api_routes(state: AppState) -> list[Route]:
196
202
  f"{API_PREFIX}/mappings/{mapping.id}"),
197
203
  "ETag": _etag(state, mapping)})
198
204
 
199
- async def update_mapping(request):
205
+ async def update_mapping(request: Request) -> Response:
200
206
  mid = request.path_params["mid"]
201
207
  if not valid_mapping_id(mid): # no mapping can have it (ids are checked on load)
202
208
  return JSONResponse({"error": "not_found"}, status_code=404)
@@ -250,7 +256,7 @@ def build_api_routes(state: AppState) -> list[Route]:
250
256
  view["changed"] = not same or restarted # False: the same settings, still running
251
257
  return JSONResponse(view, headers={"ETag": _etag(state, mapping)})
252
258
 
253
- async def patch_mapping(request):
259
+ async def patch_mapping(request: Request) -> Response:
254
260
  """PATCH: an RFC 7396 JSON merge patch on the stored mapping. Only what the body
255
261
  names changes (an object is merged into the one it replaces, a list or a value
256
262
  replaces it, null resets a field to its default), unlike PUT, which replaces the
@@ -309,7 +315,7 @@ def build_api_routes(state: AppState) -> list[Route]:
309
315
  view["changed"] = not same or restarted
310
316
  return JSONResponse(view, headers={"ETag": _etag(state, mapping)})
311
317
 
312
- async def delete_mapping(request):
318
+ async def delete_mapping(request: Request) -> Response:
313
319
  mid = request.path_params["mid"]
314
320
  try:
315
321
  removed = await ops.delete_mapping(
@@ -324,7 +330,7 @@ def build_api_routes(state: AppState) -> list[Route]:
324
330
  state.audit(_client_ip(request), "api_mapping_delete", removed.name, user=_caller(request))
325
331
  return JSONResponse({"deleted": mid})
326
332
 
327
- async def mapping_action(request):
333
+ async def mapping_action(request: Request) -> Response:
328
334
  mid = request.path_params["mid"]
329
335
  action = request.path_params["action"]
330
336
  if action not in ("start", "stop", "restart"):
@@ -343,7 +349,7 @@ def build_api_routes(state: AppState) -> list[Route]:
343
349
  return JSONResponse(out)
344
350
 
345
351
  # ---------------- trace files, timed capture ----------------
346
- async def _trace_view(m) -> dict:
352
+ async def _trace_view(m: MappingConfig) -> dict:
347
353
  """A mapping's trace files and whether it is traced now: what GET .../traces
348
354
  answers (and the capture calls, with the capture as it is then)."""
349
355
  files = await asyncio.to_thread(state.trace_list, m.id)
@@ -354,7 +360,7 @@ def build_api_routes(state: AppState) -> list[Route]:
354
360
  "traces": [{"name": f["name"], "size": f["size"], "time": f["mtime"]}
355
361
  for f in files]}
356
362
 
357
- async def list_traces(request):
363
+ async def list_traces(request: Request) -> JSONResponse:
358
364
  """A mapping's trace files. Operator and admin tokens only, as the web UI's Trace
359
365
  panel: listing, downloading and deleting traces is for operators and up."""
360
366
  if not _operator_token(request, state):
@@ -364,7 +370,7 @@ def build_api_routes(state: AppState) -> list[Route]:
364
370
  return JSONResponse(_NOT_FOUND, status_code=404)
365
371
  return JSONResponse(await _trace_view(m))
366
372
 
367
- async def get_trace(request):
373
+ async def get_trace(request: Request) -> Response:
368
374
  """Download one trace file, as it is now. Traces hold what is sent to the device
369
375
  too (what a viewer does not see in the web UI either): operator and admin tokens
370
376
  only. Audited."""
@@ -385,7 +391,7 @@ def build_api_routes(state: AppState) -> list[Route]:
385
391
  return snapshot_response(fh, name, "text/plain; charset=utf-8",
386
392
  head=request.method == "HEAD")
387
393
 
388
- async def delete_traces(request):
394
+ async def delete_traces(request: Request) -> JSONResponse:
389
395
  """DELETE .../traces: all of the mapping's trace files; .../traces/{name}: that
390
396
  one (404 when the mapping has none of that name). A trace that is on goes on in a
391
397
  new file. Audited."""
@@ -407,7 +413,7 @@ def build_api_routes(state: AppState) -> list[Route]:
407
413
  # one file that could not be deleted (Windows: it is open for a download)
408
414
  return JSONResponse(answer, status_code=409 if name is not None and failed else 200)
409
415
 
410
- async def start_capture(request):
416
+ async def start_capture(request: Request) -> Response:
411
417
  """POST .../capture {"minutes": n}: trace the mapping for that long from now (a
412
418
  capture under way gets the new end), then stop by itself."""
413
419
  mid = request.path_params["mid"]
@@ -441,7 +447,7 @@ def build_api_routes(state: AppState) -> list[Route]:
441
447
  state.audit(_client_ip(request), "api_trace_capture_start", detail, user=_caller(request))
442
448
  return JSONResponse(await _trace_view(m) if m is not None else _NOT_FOUND)
443
449
 
444
- async def stop_capture(request):
450
+ async def stop_capture(request: Request) -> JSONResponse:
445
451
  """DELETE .../capture: end the mapping's timed capture now (`changed`: false when
446
452
  it had none). A trace that is on by options.trace_both is not touched."""
447
453
  mid = request.path_params["mid"]
@@ -463,7 +469,7 @@ def build_api_routes(state: AppState) -> list[Route]:
463
469
  view["warning"] = warning
464
470
  return JSONResponse(view)
465
471
 
466
- async def import_mappings(request):
472
+ async def import_mappings(request: Request) -> JSONResponse:
467
473
  """POST /import: many mappings in one change. The body is a mappings export
468
474
  ({"mappings": [...]}, which is also what GET /mappings answers), a whole
469
475
  config.json (only its mappings are used) or a classic ser2net.yaml / ser2net.conf.
@@ -511,10 +517,10 @@ def build_api_routes(state: AppState) -> list[Route]:
511
517
  return JSONResponse({**answer, "rows": rows, "summary": count, "valid": True,
512
518
  "problem": None, "applied": True})
513
519
 
514
- async def list_pools(request):
520
+ async def list_pools(request: Request) -> JSONResponse:
515
521
  return JSONResponse({"pools": ops.pool_rows(state)})
516
522
 
517
- async def put_pools(request):
523
+ async def put_pools(request: Request) -> Response:
518
524
  """PUT /pools: the body's pools ({"pools": [{"name", "port", "bind_ip",
519
525
  "enabled", "rotate"}, ...]}) replace all of them; they listen (or stop) at once."""
520
526
  try:
@@ -541,27 +547,27 @@ def build_api_routes(state: AppState) -> list[Route]:
541
547
  return JSONResponse({"pools": ops.pool_rows(state),
542
548
  **({"warnings": warnings} if warnings else {})})
543
549
 
544
- async def metrics(request):
550
+ async def metrics(request: Request) -> PlainTextResponse:
545
551
  return PlainTextResponse(await metrics_text(state), media_type=METRICS_TYPE)
546
552
 
547
- async def status(request):
553
+ async def status(request: Request) -> JSONResponse:
548
554
  certificates = [c.view() for c in await state.certwatch.current()]
549
555
  return JSONResponse({"mappings": state.supervisor.all_status(),
550
556
  "pools": state.supervisor.pools.status(),
551
557
  "certificates": certificates,
552
558
  "clock_steps": state.clockwatch.steps})
553
559
 
554
- async def ports(request):
560
+ async def ports(request: Request) -> JSONResponse:
555
561
  return JSONResponse({"ports": await state.ports.current()})
556
562
 
557
- async def health(request):
563
+ async def health(request: Request) -> JSONResponse:
558
564
  return JSONResponse({"status": "ok", "mappings": len(state.config.mappings)})
559
565
 
560
- async def info(request):
566
+ async def info(request: Request) -> JSONResponse:
561
567
  return JSONResponse({"version": __version__, "api": API_VERSION,
562
568
  "features": list(API_FEATURES)})
563
569
 
564
- async def openapi(request):
570
+ async def openapi(request: Request) -> JSONResponse:
565
571
  return JSONResponse(openapi_spec(state.config.admin_ui, proxy.base(request)))
566
572
 
567
573
  return [
@@ -695,7 +701,7 @@ _READ_ONLY = {("MappingOptions", "trace_until")}
695
701
  _JSON_TYPES = {str: "string", int: "integer", float: "number", bool: "boolean"}
696
702
 
697
703
 
698
- def _field_schema(cls, f, hint) -> dict:
704
+ def _field_schema(cls: type, f: dataclasses.Field, hint: Any) -> dict:
699
705
  """The schema of one config dataclass field: a $ref for a nested config class, else
700
706
  its JSON type with the default, the allowed values and a note where there are any."""
701
707
  if dataclasses.is_dataclass(hint):
@@ -732,7 +738,7 @@ def _field_schema(cls, f, hint) -> dict:
732
738
  return out
733
739
 
734
740
 
735
- def _schema_name(cls) -> str:
741
+ def _schema_name(cls: object) -> str:
736
742
  return next(name for name, c in _MAPPING_CLASSES.items() if c is cls)
737
743
 
738
744
 
@@ -778,7 +784,7 @@ def _json(schema_ref: str, description: str) -> dict:
778
784
  "schema": {"$ref": f"#/components/schemas/{schema_ref}"}}}}
779
785
 
780
786
 
781
- def openapi_spec(admin, base: str = "") -> dict:
787
+ def openapi_spec(admin: AdminUI | None, base: str = "") -> dict:
782
788
  """The OpenAPI 3.0 description of the REST API, written by hand (Starlette has no
783
789
  auto-generation) except for the mapping schemas (mapping_schemas). Every route in
784
790
  build_api_routes is in it (tests/test_rest_patch.py checks). `base`: the path prefix
@@ -999,8 +1005,9 @@ def openapi_spec(admin, base: str = "") -> dict:
999
1005
  def ref(name: str) -> dict:
1000
1006
  return {"$ref": f"#/components/responses/{name}"}
1001
1007
 
1002
- def op(summary: str, ok: tuple, *errors: str, write: bool = False, body=None,
1003
- description: str = "", parameters=None, operator: bool = False) -> dict:
1008
+ def op(summary: str, ok: tuple[str, str, str], *errors: str, write: bool = False,
1009
+ body: dict | None = None, description: str = "", parameters: list[dict] | None = None,
1010
+ operator: bool = False) -> dict:
1004
1011
  """One operation: its 2xx answer, the errors it can give, and the token errors
1005
1012
  every authenticated call can (403 for a call that changes something, or
1006
1013
  `operator`: one only operator and admin tokens may make)."""
@@ -1023,7 +1030,8 @@ def openapi_spec(admin, base: str = "") -> dict:
1023
1030
  out["parameters"] = parameters
1024
1031
  return out
1025
1032
 
1026
- def mapping_body(schema: str = "Mapping", types=("application/json",)) -> dict:
1033
+ def mapping_body(schema: str = "Mapping", types: tuple[str, ...] = ("application/json",),
1034
+ ) -> dict:
1027
1035
  return {"required": True, "content": {
1028
1036
  t: {"schema": {"$ref": f"#/components/schemas/{schema}"}} for t in types}}
1029
1037
 
@@ -33,10 +33,21 @@ import socket
33
33
  import time
34
34
  import unicodedata
35
35
  from collections import OrderedDict, deque
36
+ from collections.abc import Callable, Iterable, Mapping
37
+ from typing import TYPE_CHECKING, ParamSpec, TypeVar
36
38
 
37
39
  from ..engine.netguard import address_key # an IPv6 address by its /64, as the connection caps
38
40
  from . import proxy
39
41
 
42
+ if TYPE_CHECKING:
43
+ from starlette.requests import HTTPConnection
44
+ from starlette.responses import Response
45
+
46
+ from ..config import ApiToken, AppConfig, User
47
+
48
+ _P = ParamSpec("_P")
49
+ _T = TypeVar("_T")
50
+
40
51
  SESSION_COOKIE = "ser2net_session"
41
52
  CSRF_COOKIE = "ser2net_csrf"
42
53
 
@@ -74,7 +85,7 @@ def _cost(scheme: str) -> tuple[int, int, int] | None:
74
85
  return n, r, p
75
86
 
76
87
 
77
- def _parse(stored) -> tuple[tuple[int, int, int], bytes, bytes] | None:
88
+ def _parse(stored: object) -> tuple[tuple[int, int, int], bytes, bytes] | None:
78
89
  """(cost, salt, hash) of a hash_password() result (of any version), or None."""
79
90
  parts = str(stored).split("$")
80
91
  if len(parts) != 3:
@@ -174,7 +185,7 @@ def _payload_secret(secret: str) -> str:
174
185
  return hmac.new(secret.encode("utf-8"), b"ser2net signed payload", hashlib.sha256).hexdigest()
175
186
 
176
187
 
177
- def _is_int(value) -> bool:
188
+ def _is_int(value: object) -> bool:
178
189
  return isinstance(value, int) and not isinstance(value, bool)
179
190
 
180
191
 
@@ -300,7 +311,8 @@ def read_payload(secret: str, token: str | None) -> dict | None:
300
311
  return data
301
312
 
302
313
 
303
- def session_user(cfg, token: str | None, revoked: RevokedSessions | None = None):
314
+ def session_user(cfg: AppConfig, token: str | None,
315
+ revoked: RevokedSessions | None = None) -> User | None:
304
316
  """Resolve a session cookie to the live User it authenticates, or None.
305
317
  Confirms the signed username still exists, its pwd_version is current and its
306
318
  sign-in method (LDAP/OIDC) is still on, and that the session was not ended by a
@@ -365,7 +377,7 @@ def is_own_host(host_header: str | None) -> bool:
365
377
  _FORWARDED_HOST = re.compile(r'(?:^|[;,\s])host="?([^";,\s]+)', re.IGNORECASE)
366
378
 
367
379
 
368
- def _claimed_hosts(headers) -> list:
380
+ def _claimed_hosts(headers: Mapping[str, str]) -> list[str]:
369
381
  """Every host name the request claims: Host, plus X-Forwarded-Host / Forwarded
370
382
  host= when a reverse proxy sets them. All must be this machine for open access
371
383
  (requiring more names to match can only narrow it, so a client-supplied header
@@ -380,13 +392,13 @@ def _claimed_hosts(headers) -> list:
380
392
  return hosts
381
393
 
382
394
 
383
- def claims_own_host(headers) -> bool:
395
+ def claims_own_host(headers: Mapping[str, str]) -> bool:
384
396
  """Every host name the request claims is this machine (is_own_host): the
385
397
  DNS-rebinding guard of open access and first-run setup."""
386
398
  return all(is_own_host(h) for h in _claimed_hosts(headers))
387
399
 
388
400
 
389
- def foreign_host(headers) -> str:
401
+ def foreign_host(headers: Mapping[str, str]) -> str:
390
402
  """The first claimed host name that is not this machine ('' if there is none)."""
391
403
  return next((h for h in _claimed_hosts(headers) if not is_own_host(h)), "")
392
404
 
@@ -431,7 +443,7 @@ PROXY_HINT = ("behind a reverse proxy, pass the browser's address on as Host (ng
431
443
  "X-Forwarded-Host")
432
444
 
433
445
 
434
- def cross_site(headers, also=()) -> str:
446
+ def cross_site(headers: Mapping[str, str], also: Iterable[str] = ()) -> str:
435
447
  """Why the browser says a request was made by a page of another site, or '' when it
436
448
  doesn't: the forms and changes of the web UI, and its WebSockets (the console, the
437
449
  hex view). Sec-Fetch-Site (sent to HTTPS and localhost) must be same-origin or none;
@@ -457,7 +469,7 @@ def cross_site(headers, also=()) -> str:
457
469
  + ", ".join(repr(h[:100]) for h in claimed))
458
470
 
459
471
 
460
- def anonymous_user(cfg, headers):
472
+ def anonymous_user(cfg: AppConfig, headers: Mapping[str, str]) -> User | None:
461
473
  """The pseudo-user for a visitor without a session, or None when login is
462
474
  required (the default), setup isn't done yet, or a claimed host isn't this
463
475
  machine. Note: a reverse proxy that rewrites Host to 127.0.0.1 without passing
@@ -472,7 +484,8 @@ def anonymous_user(cfg, headers):
472
484
  return User(username=ANONYMOUS_USERNAME, role=ui.anonymous_role, source="anonymous")
473
485
 
474
486
 
475
- def request_user(cfg, token: str | None, headers, revoked: RevokedSessions | None = None):
487
+ def request_user(cfg: AppConfig, token: str | None, headers: Mapping[str, str],
488
+ revoked: RevokedSessions | None = None) -> User | None:
476
489
  """The user a request acts as: its session's user, else the anonymous pseudo-user
477
490
  when the login requirement is off, else None (must sign in). ``headers`` is the
478
491
  request's (or WebSocket's) header mapping; ``revoked`` the logged-out sessions."""
@@ -502,7 +515,7 @@ def verify_token(token: str, stored_hash: str) -> bool:
502
515
  return hmac.compare_digest(hash_token(token), stored_hash)
503
516
 
504
517
 
505
- def find_api_token(cfg, token: str):
518
+ def find_api_token(cfg: AppConfig, token: str) -> ApiToken | None:
506
519
  """The API token (config.ApiToken) a request's bearer token is: the one of
507
520
  cfg.api_token_hash — as an ApiToken without an id, named 'api-token' in the audit log
508
521
  like before there were others — or one of cfg.api_tokens. None when it is none of them.
@@ -522,7 +535,7 @@ def find_api_token(cfg, token: str):
522
535
  return found
523
536
 
524
537
 
525
- def bearer_token(request) -> str:
538
+ def bearer_token(request: HTTPConnection) -> str:
526
539
  """Extract the token from an `Authorization: Bearer <token>` header."""
527
540
  header = request.headers.get("authorization", "")
528
541
  if header[:7].lower() == "bearer ":
@@ -533,7 +546,7 @@ def bearer_token(request) -> str:
533
546
  # --------------------------------------------------------------------------
534
547
  # cookies
535
548
  # --------------------------------------------------------------------------
536
- def is_https(request, cfg) -> bool:
549
+ def is_https(request: HTTPConnection, cfg: AppConfig) -> bool:
537
550
  """Did the browser use HTTPS for this request? With admin TLS as the UI's listener
538
551
  serves it (AppState.serving_tls: a TLS change applies to new connections at once;
539
552
  without the app's state, as config.json sets it); when the request's scheme is https
@@ -548,7 +561,8 @@ def is_https(request, cfg) -> bool:
548
561
  return served or proxy.browser_https(request)
549
562
 
550
563
 
551
- def set_cookie(response, request, cfg, name: str, value: str, max_age: int,
564
+ def set_cookie(response: Response, request: HTTPConnection, cfg: AppConfig, name: str,
565
+ value: str, max_age: int,
552
566
  path: str = "/") -> None:
553
567
  """One of the UI's cookies: HttpOnly, SameSite=Lax, Secure whenever the browser used
554
568
  HTTPS (is_https), under the request's path prefix and with its name for the request
@@ -558,13 +572,15 @@ def set_cookie(response, request, cfg, name: str, value: str, max_age: int,
558
572
  secure=is_https(request, cfg))
559
573
 
560
574
 
561
- def delete_cookie(response, request, cfg, name: str, path: str = "/") -> None:
575
+ def delete_cookie(response: Response, request: HTTPConnection, cfg: AppConfig, name: str,
576
+ path: str = "/") -> None:
562
577
  response.delete_cookie(proxy.cookie_name(request, name, path),
563
578
  path=proxy.cookie_path(request, path),
564
579
  httponly=True, samesite="lax", secure=is_https(request, cfg))
565
580
 
566
581
 
567
- def cookie(request, name: str, path: str = "/", legacy: bool = True) -> str | None:
582
+ def cookie(request: HTTPConnection, name: str, path: str = "/",
583
+ legacy: bool = True) -> str | None:
568
584
  """The value of one of the UI's cookies (its name for this request: set_cookie); when
569
585
  the request has none under that name, the one under the name 2.8 and older gave it
570
586
  (proxy.legacy_cookie_name), unless `legacy` is False. Such a session cookie is moved to
@@ -575,7 +591,8 @@ def cookie(request, name: str, path: str = "/", legacy: bool = True) -> str | No
575
591
  return value
576
592
 
577
593
 
578
- def legacy_session(request, cfg, revoked: RevokedSessions | None = None) -> str | None:
594
+ def legacy_session(request: HTTPConnection, cfg: AppConfig,
595
+ revoked: RevokedSessions | None = None) -> str | None:
579
596
  """A session cookie of this UI under the name of 2.8 and older (a sign-in from before
580
597
  the upgrade), when the request has none under its name now: the token, only when it
581
598
  is a valid session here. Another instance on this host name may still use that name
@@ -588,7 +605,8 @@ def legacy_session(request, cfg, revoked: RevokedSessions | None = None) -> str
588
605
  return token if session_user(cfg, token, revoked) is not None else None
589
606
 
590
607
 
591
- def move_session(response, request, cfg, token: str) -> None:
608
+ def move_session(response: Response, request: HTTPConnection, cfg: AppConfig,
609
+ token: str) -> None:
592
610
  """Move a legacy_session to the session cookie's name now (the same token, until it
593
611
  expires anyway) - unless the response sets or deletes that cookie itself (a sign-in, a
594
612
  sign-out) - and delete it under the old name."""
@@ -609,7 +627,7 @@ def new_csrf_token() -> str:
609
627
  return secrets.token_urlsafe(32)
610
628
 
611
629
 
612
- def csrf_token_matches(request, token) -> bool:
630
+ def csrf_token_matches(request: HTTPConnection, token: object) -> bool:
613
631
  """Compare a supplied token (header or form field) against the CSRF cookie.
614
632
 
615
633
  Deliberately does NOT read the request body — reading it inside a
@@ -638,7 +656,8 @@ class LoginRateLimiter:
638
656
 
639
657
  MAX_ADDRESSES = 4096
640
658
 
641
- def __init__(self, max_attempts: int = 8, window_s: int = 300, key=None):
659
+ def __init__(self, max_attempts: int = 8, window_s: int = 300,
660
+ key: Callable[[str], str] | None = None) -> None:
642
661
  self.max_attempts = max_attempts
643
662
  self.window_s = window_s
644
663
  self._key = key or address_key
@@ -690,7 +709,7 @@ class SlowWork:
690
709
  def busy(self) -> bool:
691
710
  return self._pending >= self.limit + self.queue
692
711
 
693
- async def run(self, fn, /, *args, **kwargs):
712
+ async def run(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> _T:
694
713
  self._pending += 1
695
714
  try:
696
715
  async with self._slots:
@@ -136,7 +136,7 @@ def _with_ssl(path: str) -> CertInfo:
136
136
  raise CertReadError("not_pem") from None
137
137
 
138
138
 
139
- def _ip(value) -> str:
139
+ def _ip(value: object) -> str:
140
140
  """An IP address as cryptography writes it ('::1', not '0:0:0:0:0:0:0:1')."""
141
141
  text = str(value).strip()
142
142
  with contextlib.suppress(ValueError):