s2auth 0.1.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.
- s2auth/__init__.py +3 -0
- s2auth/client/__init__.py +25 -0
- s2auth/client/connection_store.py +16 -0
- s2auth/client/dao.py +97 -0
- s2auth/client/main.py +7 -0
- s2auth/client/pairing.py +411 -0
- s2auth/client/pairing_core.py +504 -0
- s2auth/client/settings.py +43 -0
- s2auth/common/__init__.py +19 -0
- s2auth/common/connection_initiation.py +26 -0
- s2auth/common/exceptions.py +92 -0
- s2auth/common/hmac.py +228 -0
- s2auth/common/model/__init__.py +60 -0
- s2auth/common/model/s2_connect_common.py +62 -0
- s2auth/common/model/s2_connect_pairing.py +177 -0
- s2auth/common/model/s2_connect_session_init.py +98 -0
- s2auth/common/model/s2_connect_wan_endpoint_registry.py +78 -0
- s2auth/py.typed +0 -0
- s2auth/reference/__init__.py +0 -0
- s2auth/reference/client/main.py +249 -0
- s2auth/reference/server/__init__.py +0 -0
- s2auth/reference/server/connection.py +75 -0
- s2auth/reference/server/context.py +96 -0
- s2auth/reference/server/hooks.py +21 -0
- s2auth/reference/server/logging.py +51 -0
- s2auth/reference/server/main.py +106 -0
- s2auth/reference/server/pairing.py +248 -0
- s2auth/reference/server/run.py +45 -0
- s2auth/reference/server/versions.py +26 -0
- s2auth/server/__init__.py +12 -0
- s2auth/server/config.py +18 -0
- s2auth/server/connection_initiation.py +227 -0
- s2auth/server/context.py +326 -0
- s2auth/server/db.py +18 -0
- s2auth/server/hooks.py +225 -0
- s2auth/server/models.py +19 -0
- s2auth/server/pairing.py +375 -0
- s2auth/server/settings.py +48 -0
- s2auth/server/storage.py +31 -0
- s2auth/server/token_manager.py +125 -0
- s2auth-0.1.0.dist-info/METADATA +582 -0
- s2auth-0.1.0.dist-info/RECORD +45 -0
- s2auth-0.1.0.dist-info/WHEEL +4 -0
- s2auth-0.1.0.dist-info/entry_points.txt +4 -0
- s2auth-0.1.0.dist-info/licenses/LICENSE.md +202 -0
s2auth/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from s2auth.client.connection_store import ConnectionStore
|
|
2
|
+
from s2auth.client.pairing import (
|
|
3
|
+
ConnectResult,
|
|
4
|
+
PairingClient,
|
|
5
|
+
PairingClientHooks,
|
|
6
|
+
PairingResult,
|
|
7
|
+
UnpairResult,
|
|
8
|
+
build_pairing_settings,
|
|
9
|
+
detect_deployment,
|
|
10
|
+
strip_pairing_url,
|
|
11
|
+
)
|
|
12
|
+
from s2auth.client.settings import ClientSettings
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"ClientSettings",
|
|
16
|
+
"ConnectionStore",
|
|
17
|
+
"ConnectResult",
|
|
18
|
+
"PairingClient",
|
|
19
|
+
"PairingClientHooks",
|
|
20
|
+
"PairingResult",
|
|
21
|
+
"UnpairResult",
|
|
22
|
+
"build_pairing_settings",
|
|
23
|
+
"detect_deployment",
|
|
24
|
+
"strip_pairing_url",
|
|
25
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Protocol
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class ConnectionStore(Protocol):
|
|
7
|
+
"""Storage interface used by pairing client flows."""
|
|
8
|
+
|
|
9
|
+
def store_connection_details(self, s2_node_id: str, details: dict[str, Any]) -> None:
|
|
10
|
+
...
|
|
11
|
+
|
|
12
|
+
def load_connection_details(self, s2_node_id: str) -> dict[str, Any] | None:
|
|
13
|
+
...
|
|
14
|
+
|
|
15
|
+
def remove_connection_details(self, s2_node_id: str) -> bool:
|
|
16
|
+
...
|
s2auth/client/dao.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import JSON, Boolean, Select, String, create_engine, select
|
|
6
|
+
from sqlalchemy.inspection import inspect
|
|
7
|
+
from sqlalchemy.orm import (Mapped, declarative_base, mapped_column,
|
|
8
|
+
sessionmaker)
|
|
9
|
+
|
|
10
|
+
Base = declarative_base()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ConnectionDetail(Base):
|
|
14
|
+
__tablename__ = "connection_details"
|
|
15
|
+
|
|
16
|
+
s2_node_id: Mapped[str] = mapped_column(String, nullable=False, index=True, primary_key=True)
|
|
17
|
+
client_s2_node_id: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
18
|
+
pairing_server_url: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
19
|
+
verify_tls: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)
|
|
20
|
+
ssl_certfile: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
21
|
+
initiate_session_url: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
22
|
+
access_token: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
23
|
+
supported_s2_message_versions: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
|
|
24
|
+
supported_communication_protocols: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
|
|
25
|
+
supported_hmac_hashing_algorithms: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)
|
|
26
|
+
selected_s2_message_version: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
27
|
+
selected_communication_protocol: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
28
|
+
selected_hmac_hashing_algorithm: Mapped[Optional[str]] = mapped_column(String, nullable=True)
|
|
29
|
+
server_node_description: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
|
30
|
+
server_endpoint_description: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
|
31
|
+
|
|
32
|
+
class Dao:
|
|
33
|
+
"""
|
|
34
|
+
SQLAlchemy-backed data access object for storing/loading connection details.
|
|
35
|
+
Default database is SQLite file 'connection_details.db'.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, db_url: str = "sqlite:///connection_details.db") -> None:
|
|
39
|
+
# Create engine & session factory
|
|
40
|
+
self._engine = create_engine(db_url, future=True)
|
|
41
|
+
Base.metadata.create_all(self._engine)
|
|
42
|
+
|
|
43
|
+
self._SessionLocal = sessionmaker(
|
|
44
|
+
bind=self._engine,
|
|
45
|
+
autoflush=False,
|
|
46
|
+
autocommit=False,
|
|
47
|
+
future=True,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
def store_connection_details(self, s2_node_id: str, details: dict[str, Any]) -> None:
|
|
51
|
+
"""
|
|
52
|
+
Insert or overwrite a connection detail identified by s2_node_id.
|
|
53
|
+
"""
|
|
54
|
+
with self._SessionLocal() as session:
|
|
55
|
+
with session.begin():
|
|
56
|
+
obj = session.query(ConnectionDetail).filter(ConnectionDetail.s2_node_id == s2_node_id).one_or_none()
|
|
57
|
+
|
|
58
|
+
if obj is None:
|
|
59
|
+
obj = ConnectionDetail(s2_node_id=s2_node_id)
|
|
60
|
+
session.add(obj)
|
|
61
|
+
|
|
62
|
+
for detail_key, model_attr in details.items():
|
|
63
|
+
if hasattr(ConnectionDetail, detail_key):
|
|
64
|
+
setattr(obj, detail_key, model_attr)
|
|
65
|
+
else:
|
|
66
|
+
raise ValueError(f"Invalid detail key: {detail_key}")
|
|
67
|
+
|
|
68
|
+
def load_connection_details(self, s2_node_id: str) -> Optional[dict[str, Any]]:
|
|
69
|
+
"""Load the full connection details object for the given node ID."""
|
|
70
|
+
stmt: Select[Any] = (
|
|
71
|
+
select(ConnectionDetail)
|
|
72
|
+
.where(ConnectionDetail.s2_node_id == s2_node_id)
|
|
73
|
+
.limit(1)
|
|
74
|
+
)
|
|
75
|
+
with self._SessionLocal() as session:
|
|
76
|
+
obj = session.execute(stmt).scalars().first()
|
|
77
|
+
if obj is None:
|
|
78
|
+
return None
|
|
79
|
+
return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
|
|
80
|
+
|
|
81
|
+
def remove_connection_details(self, s2_node_id: str) -> bool:
|
|
82
|
+
"""Remove connection details for the given node ID.
|
|
83
|
+
|
|
84
|
+
Returns True when an entry was deleted, otherwise False.
|
|
85
|
+
"""
|
|
86
|
+
stmt: Select[Any] = (
|
|
87
|
+
select(ConnectionDetail)
|
|
88
|
+
.where(ConnectionDetail.s2_node_id == s2_node_id)
|
|
89
|
+
.limit(1)
|
|
90
|
+
)
|
|
91
|
+
with self._SessionLocal() as session:
|
|
92
|
+
with session.begin():
|
|
93
|
+
obj = session.execute(stmt).scalars().first()
|
|
94
|
+
if obj is None:
|
|
95
|
+
return False
|
|
96
|
+
session.delete(obj)
|
|
97
|
+
return True
|
s2auth/client/main.py
ADDED
s2auth/client/pairing.py
ADDED
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import ipaddress
|
|
4
|
+
import logging
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Awaitable, Callable
|
|
7
|
+
from urllib.parse import urlparse
|
|
8
|
+
from uuid import UUID, uuid4
|
|
9
|
+
|
|
10
|
+
import httpx
|
|
11
|
+
|
|
12
|
+
from s2auth.client import pairing_core
|
|
13
|
+
from s2auth.client.connection_store import ConnectionStore
|
|
14
|
+
from s2auth.client.dao import Dao
|
|
15
|
+
from s2auth.client.settings import ClientSettings
|
|
16
|
+
from s2auth.common.model.s2_connect_common import (
|
|
17
|
+
CommunicationProtocol,
|
|
18
|
+
Deployment,
|
|
19
|
+
NodeDescription,
|
|
20
|
+
NodeId,
|
|
21
|
+
Role,
|
|
22
|
+
)
|
|
23
|
+
from s2auth.common.model.s2_connect_pairing import HmacHashingAlgorithm
|
|
24
|
+
|
|
25
|
+
LOGGER = logging.getLogger(__name__)
|
|
26
|
+
|
|
27
|
+
HttpRequestHook = Callable[[httpx.Request], Awaitable[None]]
|
|
28
|
+
HttpResponseHook = Callable[[httpx.Response], Awaitable[None]]
|
|
29
|
+
HttpEventHooks = pairing_core.HttpEventHooks
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def strip_pairing_url(url_str: str) -> str:
|
|
33
|
+
"""Normalize a pairing URL by stripping known endpoint suffixes."""
|
|
34
|
+
|
|
35
|
+
endpoint_suffixes = (
|
|
36
|
+
"/requestPairing",
|
|
37
|
+
"/initiateSession",
|
|
38
|
+
"/requestConnectionDetails",
|
|
39
|
+
"/postConnectionDetails",
|
|
40
|
+
"/finalizePairing",
|
|
41
|
+
"/confirmToken",
|
|
42
|
+
)
|
|
43
|
+
url_str = url_str.rstrip("/")
|
|
44
|
+
|
|
45
|
+
for suffix in endpoint_suffixes:
|
|
46
|
+
if url_str.endswith(suffix):
|
|
47
|
+
url_str = url_str[: -len(suffix)]
|
|
48
|
+
break
|
|
49
|
+
return url_str.rstrip("/")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def detect_deployment(
|
|
53
|
+
pairing_url: str,
|
|
54
|
+
domain_name: str | None,
|
|
55
|
+
certificate_file: str | None,
|
|
56
|
+
) -> tuple[Deployment, str]:
|
|
57
|
+
"""Infer deployment mode from domain/certificate/host heuristics."""
|
|
58
|
+
|
|
59
|
+
if domain_name:
|
|
60
|
+
return Deployment.WAN, "domain provided"
|
|
61
|
+
if certificate_file:
|
|
62
|
+
return Deployment.LAN, "certificate_file provided"
|
|
63
|
+
|
|
64
|
+
hostname = (urlparse(pairing_url).hostname or "").lower()
|
|
65
|
+
if hostname in {"", "localhost"} or hostname.endswith(".local"):
|
|
66
|
+
return Deployment.LAN, f"host '{hostname or '<empty>'}' looked local"
|
|
67
|
+
|
|
68
|
+
try:
|
|
69
|
+
ip = ipaddress.ip_address(hostname)
|
|
70
|
+
if ip.is_private or ip.is_loopback or ip.is_link_local:
|
|
71
|
+
return Deployment.LAN, f"host '{hostname}' is private/local IP"
|
|
72
|
+
return Deployment.WAN, f"host '{hostname}' is public IP"
|
|
73
|
+
except ValueError:
|
|
74
|
+
# Non-IP hostname: treat as WAN by default.
|
|
75
|
+
return Deployment.WAN, f"host '{hostname}' looked public"
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def build_pairing_settings(
|
|
79
|
+
base_settings: ClientSettings,
|
|
80
|
+
*,
|
|
81
|
+
server_url: str,
|
|
82
|
+
pairing_token: str | None,
|
|
83
|
+
pairing_s2_node_id: str | None,
|
|
84
|
+
client_s2_node_id: str,
|
|
85
|
+
role: str,
|
|
86
|
+
deployment: str | None,
|
|
87
|
+
domain_name: str | None,
|
|
88
|
+
verify_tls: bool,
|
|
89
|
+
ssl_certfile: str | None,
|
|
90
|
+
supported_s2_message_versions: list[str] | None,
|
|
91
|
+
communication_protocols: list[str] | None,
|
|
92
|
+
supported_hmac_hashing_algorithms: list[str] | None,
|
|
93
|
+
brand: str,
|
|
94
|
+
client_device_type: str,
|
|
95
|
+
client_model_name: str,
|
|
96
|
+
) -> tuple[ClientSettings, list[str]]:
|
|
97
|
+
"""Resolve effective pairing settings from defaults plus overrides."""
|
|
98
|
+
|
|
99
|
+
warnings: list[str] = []
|
|
100
|
+
|
|
101
|
+
effective_supported_s2_versions = supported_s2_message_versions or base_settings.supported_s2_versions
|
|
102
|
+
effective_communication_protocols = communication_protocols or [
|
|
103
|
+
protocol.value for protocol in base_settings.supported_communication_protocols
|
|
104
|
+
]
|
|
105
|
+
effective_supported_hmac_hashing_algorithms = supported_hmac_hashing_algorithms or [
|
|
106
|
+
algorithm.value for algorithm in base_settings.supported_hmac_hashing_algorithms
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
normalized_server_url = strip_pairing_url(server_url)
|
|
110
|
+
effective_domain = domain_name
|
|
111
|
+
|
|
112
|
+
if deployment is None:
|
|
113
|
+
effective_deployment, reason = detect_deployment(
|
|
114
|
+
normalized_server_url,
|
|
115
|
+
effective_domain,
|
|
116
|
+
ssl_certfile,
|
|
117
|
+
)
|
|
118
|
+
warnings.append(f"Auto-detected deployment={effective_deployment.value} ({reason})")
|
|
119
|
+
if reason.startswith("host '"):
|
|
120
|
+
warnings.append(
|
|
121
|
+
"Deployment was inferred heuristically from server_url host; set --deployment explicitly to override."
|
|
122
|
+
)
|
|
123
|
+
else:
|
|
124
|
+
effective_deployment = Deployment(deployment.upper())
|
|
125
|
+
|
|
126
|
+
if effective_deployment == Deployment.WAN and effective_domain is None:
|
|
127
|
+
effective_domain = urlparse(server_url).hostname
|
|
128
|
+
if effective_domain is None:
|
|
129
|
+
raise ValueError("Could not auto-detect domain from --server_url; set --domain explicitly for WAN deployment.")
|
|
130
|
+
warnings.append(f"Auto-detected domain='{effective_domain}' from server_url")
|
|
131
|
+
|
|
132
|
+
runtime_settings = base_settings.model_copy(
|
|
133
|
+
update={
|
|
134
|
+
"server_url": server_url,
|
|
135
|
+
"pairing_token": pairing_token,
|
|
136
|
+
"pairing_s2_node_id": pairing_s2_node_id,
|
|
137
|
+
"client_s2_node_id": client_s2_node_id,
|
|
138
|
+
"client_role": Role(role),
|
|
139
|
+
"client_deployment": effective_deployment,
|
|
140
|
+
"domain_name": effective_domain,
|
|
141
|
+
"verify_tls": verify_tls,
|
|
142
|
+
"ssl_certfile": ssl_certfile,
|
|
143
|
+
"supported_s2_versions": effective_supported_s2_versions,
|
|
144
|
+
"supported_communication_protocols": list(map(CommunicationProtocol, effective_communication_protocols)),
|
|
145
|
+
"supported_hmac_hashing_algorithms": list(
|
|
146
|
+
map(HmacHashingAlgorithm, effective_supported_hmac_hashing_algorithms)
|
|
147
|
+
),
|
|
148
|
+
"cleint_brand": brand,
|
|
149
|
+
"client_device_type": client_device_type,
|
|
150
|
+
"client_model_name": client_model_name,
|
|
151
|
+
}
|
|
152
|
+
)
|
|
153
|
+
return runtime_settings, warnings
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass(frozen=True)
|
|
157
|
+
class PairingResult:
|
|
158
|
+
success: bool
|
|
159
|
+
pairing_s2_node_id: str
|
|
160
|
+
client_s2_node_id: str
|
|
161
|
+
connection_details: dict[str, object] | None
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
@dataclass(frozen=True)
|
|
165
|
+
class ConnectResult:
|
|
166
|
+
success: bool
|
|
167
|
+
pairing_s2_node_id: str
|
|
168
|
+
connection_details: dict[str, object] | None
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
@dataclass(frozen=True)
|
|
172
|
+
class UnpairResult:
|
|
173
|
+
success: bool
|
|
174
|
+
pairing_s2_node_id: str
|
|
175
|
+
previous_connection_details: dict[str, object] | None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@dataclass(frozen=True)
|
|
179
|
+
class PairingClientHooks:
|
|
180
|
+
on_operation_start: Callable[[str, str | None], None] | None = None
|
|
181
|
+
on_operation_success: Callable[[str, object], None] | None = None
|
|
182
|
+
on_operation_error: Callable[[str, Exception], None] | None = None
|
|
183
|
+
http_request: HttpRequestHook | None = None
|
|
184
|
+
http_response: HttpResponseHook | None = None
|
|
185
|
+
|
|
186
|
+
def http_event_hooks(self) -> HttpEventHooks | None:
|
|
187
|
+
if self.http_request is None and self.http_response is None:
|
|
188
|
+
return None
|
|
189
|
+
|
|
190
|
+
event_hooks: HttpEventHooks = {
|
|
191
|
+
"request": [],
|
|
192
|
+
"response": [],
|
|
193
|
+
}
|
|
194
|
+
if self.http_request is not None:
|
|
195
|
+
event_hooks["request"].append(self.http_request)
|
|
196
|
+
if self.http_response is not None:
|
|
197
|
+
event_hooks["response"].append(self.http_response)
|
|
198
|
+
return event_hooks
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class PairingClient:
|
|
202
|
+
"""High-level orchestration wrapper around existing pairing functions."""
|
|
203
|
+
|
|
204
|
+
def __init__(
|
|
205
|
+
self,
|
|
206
|
+
settings: ClientSettings,
|
|
207
|
+
storage: ConnectionStore | None = None,
|
|
208
|
+
hooks: PairingClientHooks | None = None,
|
|
209
|
+
) -> None:
|
|
210
|
+
self.settings = settings
|
|
211
|
+
self.storage = storage if storage is not None else Dao(settings.storage_db_url)
|
|
212
|
+
self.hooks = hooks if hooks is not None else PairingClientHooks()
|
|
213
|
+
self._http_event_hooks = self.hooks.http_event_hooks()
|
|
214
|
+
# Keep a generated fallback id for non-pairing flows where client id is not required.
|
|
215
|
+
self._client_node_id = uuid4()
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
def from_settings(
|
|
219
|
+
cls,
|
|
220
|
+
settings: ClientSettings,
|
|
221
|
+
storage: ConnectionStore | None = None,
|
|
222
|
+
hooks: PairingClientHooks | None = None,
|
|
223
|
+
) -> "PairingClient":
|
|
224
|
+
return cls(settings=settings, storage=storage, hooks=hooks)
|
|
225
|
+
|
|
226
|
+
async def pair(self) -> PairingResult:
|
|
227
|
+
self._emit_operation_start("pair", self.settings.pairing_s2_node_id)
|
|
228
|
+
pairing_uri = strip_pairing_url(self.settings.server_url)
|
|
229
|
+
deployment, domain_name = self._resolve_deployment_domain(pairing_uri)
|
|
230
|
+
client_node_id = self._resolve_client_node_id_for_pairing()
|
|
231
|
+
|
|
232
|
+
node_description = NodeDescription(
|
|
233
|
+
id=NodeId(client_node_id),
|
|
234
|
+
brand=self.settings.cleint_brand,
|
|
235
|
+
type=self.settings.client_device_type,
|
|
236
|
+
modelName=self.settings.client_model_name,
|
|
237
|
+
role=self.settings.client_role,
|
|
238
|
+
)
|
|
239
|
+
|
|
240
|
+
try:
|
|
241
|
+
if self._http_event_hooks is None:
|
|
242
|
+
success = await pairing_core.perform_pairing(
|
|
243
|
+
pairing_uri=pairing_uri,
|
|
244
|
+
pairing_code=self.settings.pairing_token,
|
|
245
|
+
storage=self.storage,
|
|
246
|
+
role=self.settings.client_role,
|
|
247
|
+
deployment=deployment,
|
|
248
|
+
supported_s2_message_versions=self.settings.supported_s2_versions,
|
|
249
|
+
supported_communication_protocols=[
|
|
250
|
+
protocol.value for protocol in self.settings.supported_communication_protocols
|
|
251
|
+
],
|
|
252
|
+
supportedHmacHashingAlgorithms=[
|
|
253
|
+
algorithm.value for algorithm in self.settings.supported_hmac_hashing_algorithms
|
|
254
|
+
],
|
|
255
|
+
s2_client_description=node_description,
|
|
256
|
+
domain_name=domain_name,
|
|
257
|
+
pairingS2NodeId=self.settings.pairing_s2_node_id,
|
|
258
|
+
verify_tls=self.settings.verify_tls,
|
|
259
|
+
ssl_certfile=self.settings.ssl_certfile,
|
|
260
|
+
)
|
|
261
|
+
else:
|
|
262
|
+
success = await pairing_core.perform_pairing(
|
|
263
|
+
pairing_uri=pairing_uri,
|
|
264
|
+
pairing_code=self.settings.pairing_token,
|
|
265
|
+
storage=self.storage,
|
|
266
|
+
role=self.settings.client_role,
|
|
267
|
+
deployment=deployment,
|
|
268
|
+
supported_s2_message_versions=self.settings.supported_s2_versions,
|
|
269
|
+
supported_communication_protocols=[
|
|
270
|
+
protocol.value for protocol in self.settings.supported_communication_protocols
|
|
271
|
+
],
|
|
272
|
+
supportedHmacHashingAlgorithms=[
|
|
273
|
+
algorithm.value for algorithm in self.settings.supported_hmac_hashing_algorithms
|
|
274
|
+
],
|
|
275
|
+
s2_client_description=node_description,
|
|
276
|
+
domain_name=domain_name,
|
|
277
|
+
pairingS2NodeId=self.settings.pairing_s2_node_id,
|
|
278
|
+
verify_tls=self.settings.verify_tls,
|
|
279
|
+
ssl_certfile=self.settings.ssl_certfile,
|
|
280
|
+
http_event_hooks=self._http_event_hooks,
|
|
281
|
+
)
|
|
282
|
+
except Exception as exc:
|
|
283
|
+
self._emit_operation_error("pair", exc)
|
|
284
|
+
raise
|
|
285
|
+
|
|
286
|
+
storage_key = self.settings.pairing_s2_node_id or str(client_node_id)
|
|
287
|
+
details = self.storage.load_connection_details(storage_key)
|
|
288
|
+
result = PairingResult(
|
|
289
|
+
success=success,
|
|
290
|
+
pairing_s2_node_id=storage_key,
|
|
291
|
+
client_s2_node_id=str(client_node_id),
|
|
292
|
+
connection_details=details,
|
|
293
|
+
)
|
|
294
|
+
self._emit_operation_success("pair", result)
|
|
295
|
+
return result
|
|
296
|
+
|
|
297
|
+
async def connect(self, pairing_s2_node_id: str | None = None) -> ConnectResult:
|
|
298
|
+
"""Initiate a session and return an operation result with stored details."""
|
|
299
|
+
|
|
300
|
+
resolved_pairing_s2_node_id = self._resolve_pairing_node_id(pairing_s2_node_id)
|
|
301
|
+
self._emit_operation_start("connect", resolved_pairing_s2_node_id)
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
if self._http_event_hooks is None:
|
|
305
|
+
success = await pairing_core.connect(
|
|
306
|
+
storage=self.storage,
|
|
307
|
+
pairing_s2_node_id=resolved_pairing_s2_node_id,
|
|
308
|
+
)
|
|
309
|
+
else:
|
|
310
|
+
success = await pairing_core.connect(
|
|
311
|
+
storage=self.storage,
|
|
312
|
+
pairing_s2_node_id=resolved_pairing_s2_node_id,
|
|
313
|
+
http_event_hooks=self._http_event_hooks,
|
|
314
|
+
)
|
|
315
|
+
except Exception as exc:
|
|
316
|
+
self._emit_operation_error("connect", exc)
|
|
317
|
+
raise
|
|
318
|
+
|
|
319
|
+
result = ConnectResult(
|
|
320
|
+
success=success,
|
|
321
|
+
pairing_s2_node_id=resolved_pairing_s2_node_id,
|
|
322
|
+
connection_details=self.storage.load_connection_details(resolved_pairing_s2_node_id),
|
|
323
|
+
)
|
|
324
|
+
self._emit_operation_success("connect", result)
|
|
325
|
+
return result
|
|
326
|
+
|
|
327
|
+
async def unpair(self, pairing_s2_node_id: str | None = None) -> UnpairResult:
|
|
328
|
+
"""Terminate pairing and return an operation result with pre-unpair details."""
|
|
329
|
+
|
|
330
|
+
resolved_pairing_s2_node_id = self._resolve_pairing_node_id(pairing_s2_node_id)
|
|
331
|
+
self._emit_operation_start("unpair", resolved_pairing_s2_node_id)
|
|
332
|
+
previous_connection_details = self.storage.load_connection_details(resolved_pairing_s2_node_id)
|
|
333
|
+
|
|
334
|
+
try:
|
|
335
|
+
if self._http_event_hooks is None:
|
|
336
|
+
success = await pairing_core.unpair(
|
|
337
|
+
storage=self.storage,
|
|
338
|
+
pairing_s2_node_id=resolved_pairing_s2_node_id,
|
|
339
|
+
)
|
|
340
|
+
else:
|
|
341
|
+
success = await pairing_core.unpair(
|
|
342
|
+
storage=self.storage,
|
|
343
|
+
pairing_s2_node_id=resolved_pairing_s2_node_id,
|
|
344
|
+
http_event_hooks=self._http_event_hooks,
|
|
345
|
+
)
|
|
346
|
+
except Exception as exc:
|
|
347
|
+
self._emit_operation_error("unpair", exc)
|
|
348
|
+
raise
|
|
349
|
+
|
|
350
|
+
result = UnpairResult(
|
|
351
|
+
success=success,
|
|
352
|
+
pairing_s2_node_id=resolved_pairing_s2_node_id,
|
|
353
|
+
previous_connection_details=previous_connection_details,
|
|
354
|
+
)
|
|
355
|
+
self._emit_operation_success("unpair", result)
|
|
356
|
+
return result
|
|
357
|
+
|
|
358
|
+
def _emit_operation_start(self, operation: str, pairing_s2_node_id: str | None) -> None:
|
|
359
|
+
if self.hooks.on_operation_start is None:
|
|
360
|
+
return
|
|
361
|
+
try:
|
|
362
|
+
self.hooks.on_operation_start(operation, pairing_s2_node_id)
|
|
363
|
+
except Exception as exc: # pragma: no cover
|
|
364
|
+
LOGGER.warning(f"on_operation_start hook failed: {exc}")
|
|
365
|
+
|
|
366
|
+
def _emit_operation_success(self, operation: str, result: object) -> None:
|
|
367
|
+
if self.hooks.on_operation_success is None:
|
|
368
|
+
return
|
|
369
|
+
try:
|
|
370
|
+
self.hooks.on_operation_success(operation, result)
|
|
371
|
+
except Exception as exc: # pragma: no cover
|
|
372
|
+
LOGGER.warning(f"on_operation_success hook failed: {exc}")
|
|
373
|
+
|
|
374
|
+
def _emit_operation_error(self, operation: str, error: Exception) -> None:
|
|
375
|
+
if self.hooks.on_operation_error is None:
|
|
376
|
+
return
|
|
377
|
+
try:
|
|
378
|
+
self.hooks.on_operation_error(operation, error)
|
|
379
|
+
except Exception as exc: # pragma: no cover
|
|
380
|
+
LOGGER.warning(f"on_operation_error hook failed: {exc}")
|
|
381
|
+
|
|
382
|
+
def _resolve_pairing_node_id(self, pairing_s2_node_id: str | None) -> str:
|
|
383
|
+
if pairing_s2_node_id is not None:
|
|
384
|
+
return pairing_s2_node_id
|
|
385
|
+
if self.settings.pairing_s2_node_id is not None:
|
|
386
|
+
return self.settings.pairing_s2_node_id
|
|
387
|
+
return str(self._client_node_id)
|
|
388
|
+
|
|
389
|
+
def _resolve_client_node_id_for_pairing(self) -> UUID:
|
|
390
|
+
configured_client_node_id = self.settings.client_s2_node_id
|
|
391
|
+
if configured_client_node_id is None:
|
|
392
|
+
return self._client_node_id
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
return UUID(configured_client_node_id)
|
|
396
|
+
except ValueError as exc:
|
|
397
|
+
raise ValueError("client_s2_node_id must be a valid UUID for pairing mode") from exc
|
|
398
|
+
|
|
399
|
+
def _resolve_deployment_domain(self, pairing_uri: str) -> tuple[str, str | None]:
|
|
400
|
+
deployment = self.settings.client_deployment
|
|
401
|
+
domain_name = self.settings.domain_name
|
|
402
|
+
|
|
403
|
+
if deployment is None:
|
|
404
|
+
deployment, _ = detect_deployment(pairing_uri, domain_name, self.settings.ssl_certfile)
|
|
405
|
+
|
|
406
|
+
deployment_value = deployment.value.upper()
|
|
407
|
+
|
|
408
|
+
if deployment_value == Deployment.WAN.value and domain_name is None:
|
|
409
|
+
domain_name = urlparse(pairing_uri).hostname
|
|
410
|
+
|
|
411
|
+
return deployment_value, domain_name
|