bydev 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.
- bydev/__init__.py +168 -0
- bydev/_api.py +157 -0
- bydev/_generated.py +271 -0
- bydev/_support.py +195 -0
- bydev/_tokens.py +131 -0
- bydev/_verifier.py +165 -0
- bydev/aio.py +55 -0
- bydev/client.py +160 -0
- bydev/defaults.py +117 -0
- bydev/errors.py +78 -0
- bydev/login.py +140 -0
- bydev/models.py +660 -0
- bydev/platform.py +403 -0
- bydev/ports.py +182 -0
- bydev/py.typed +0 -0
- bydev/server.py +90 -0
- bydev/session.py +556 -0
- bydev-0.1.0.dist-info/METADATA +185 -0
- bydev-0.1.0.dist-info/RECORD +22 -0
- bydev-0.1.0.dist-info/WHEEL +4 -0
- bydev-0.1.0.dist-info/licenses/LICENSE-APACHE +202 -0
- bydev-0.1.0.dist-info/licenses/LICENSE-MIT +21 -0
bydev/_support.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""안쪽 도우미 — 응답 읽기 · single-flight · 반올림 · 시각 · 인코딩."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import binascii
|
|
7
|
+
import hashlib
|
|
8
|
+
import json
|
|
9
|
+
import math
|
|
10
|
+
import threading
|
|
11
|
+
from collections.abc import Callable
|
|
12
|
+
from datetime import UTC, datetime, timedelta
|
|
13
|
+
from typing import Any, Generic, TypeVar
|
|
14
|
+
|
|
15
|
+
from ._generated import Codes
|
|
16
|
+
from .errors import BydevError
|
|
17
|
+
from .ports import RandomSource, Signal, TaskScheduler
|
|
18
|
+
|
|
19
|
+
T = TypeVar("T")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def dumps(value: Any) -> str:
|
|
23
|
+
"""간결한 JSON — 객체 키는 이름순, 한글을 `\\uXXXX`로 바꾸지 않는다(다른 SDK와 같은 모양)."""
|
|
24
|
+
return json.dumps(value, ensure_ascii=False, separators=(",", ":"), sort_keys=True)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def loads(data: bytes | str) -> Any:
|
|
28
|
+
"""JSON이 아니면 None — 엄격하게(NaN · Infinity 거부)."""
|
|
29
|
+
|
|
30
|
+
def reject(token: str) -> Any:
|
|
31
|
+
raise ValueError(token)
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
return json.loads(data, parse_constant=reject)
|
|
35
|
+
except (ValueError, UnicodeDecodeError):
|
|
36
|
+
return None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _is_int(v: Any) -> bool:
|
|
40
|
+
return (isinstance(v, int) and not isinstance(v, bool)) or (
|
|
41
|
+
isinstance(v, float) and v.is_integer() and abs(v) < 9e15
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class Reader:
|
|
46
|
+
"""응답 읽기(명세 3.2) — 처음 어긋난 곳을 `PROTOCOL_ERROR`로 기억하고 기본값으로 이어 읽는다. 모르는 필드는 버린다."""
|
|
47
|
+
|
|
48
|
+
_MISSING: Any = object()
|
|
49
|
+
|
|
50
|
+
def __init__(self) -> None:
|
|
51
|
+
self.error: BydevError | None = None
|
|
52
|
+
|
|
53
|
+
def _fail(self, path: str, want: str, got: Any) -> None:
|
|
54
|
+
if self.error is not None:
|
|
55
|
+
return
|
|
56
|
+
message = (
|
|
57
|
+
f"응답에 {path}가 없다"
|
|
58
|
+
if got is self._MISSING
|
|
59
|
+
else f"응답의 {path}가 {want}가 아니다 ({dumps(got)})"
|
|
60
|
+
)
|
|
61
|
+
self.error = BydevError(Codes.PROTOCOL_ERROR, message)
|
|
62
|
+
|
|
63
|
+
def get(self, obj: dict[str, Any], key: str) -> Any:
|
|
64
|
+
return obj.get(key, self._MISSING)
|
|
65
|
+
|
|
66
|
+
def obj(self, v: Any, path: str) -> dict[str, Any]:
|
|
67
|
+
if isinstance(v, dict):
|
|
68
|
+
return v
|
|
69
|
+
self._fail(path, "객체", v)
|
|
70
|
+
return {}
|
|
71
|
+
|
|
72
|
+
def text(self, v: Any, path: str) -> str:
|
|
73
|
+
if isinstance(v, str):
|
|
74
|
+
return v
|
|
75
|
+
self._fail(path, "문자열", v)
|
|
76
|
+
return ""
|
|
77
|
+
|
|
78
|
+
def integer(self, v: Any, path: str) -> int:
|
|
79
|
+
if _is_int(v):
|
|
80
|
+
return int(v)
|
|
81
|
+
self._fail(path, "정수", v)
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
def flag(self, v: Any, path: str) -> bool:
|
|
85
|
+
if isinstance(v, bool):
|
|
86
|
+
return v
|
|
87
|
+
self._fail(path, "참/거짓", v)
|
|
88
|
+
return False
|
|
89
|
+
|
|
90
|
+
def items(self, v: Any, path: str) -> list[Any]:
|
|
91
|
+
if isinstance(v, list):
|
|
92
|
+
return v
|
|
93
|
+
self._fail(path, "배열", v)
|
|
94
|
+
return []
|
|
95
|
+
|
|
96
|
+
def opt_text(self, v: Any, path: str) -> str | None:
|
|
97
|
+
return None if v is None or v is self._MISSING else self.text(v, path)
|
|
98
|
+
|
|
99
|
+
def opt_integer(self, v: Any, path: str) -> int | None:
|
|
100
|
+
return None if v is None or v is self._MISSING else self.integer(v, path)
|
|
101
|
+
|
|
102
|
+
def finish(self, value: T) -> T:
|
|
103
|
+
if self.error is not None:
|
|
104
|
+
raise self.error
|
|
105
|
+
return value
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
class _Flight(Generic[T]):
|
|
109
|
+
def __init__(self) -> None:
|
|
110
|
+
self.done = Signal()
|
|
111
|
+
self.value: T | None = None
|
|
112
|
+
self.error: BaseException | None = None
|
|
113
|
+
self.ok = False
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class SingleFlight(Generic[T]):
|
|
117
|
+
"""한 번에 하나만 도는 작업이다 — 기다리는 쪽은 `TaskScheduler.wait`로 기다린다(명세 2절 · 6절 1)."""
|
|
118
|
+
|
|
119
|
+
def __init__(self) -> None:
|
|
120
|
+
self._lock = threading.Lock()
|
|
121
|
+
self._current: _Flight[T] | None = None
|
|
122
|
+
|
|
123
|
+
def run(self, scheduler: TaskScheduler, work: Callable[[], T]) -> T:
|
|
124
|
+
with self._lock:
|
|
125
|
+
running = self._current
|
|
126
|
+
if running is None:
|
|
127
|
+
flight: _Flight[T] = _Flight()
|
|
128
|
+
self._current = flight
|
|
129
|
+
if running is not None:
|
|
130
|
+
scheduler.wait(running.done)
|
|
131
|
+
if running.error is not None:
|
|
132
|
+
raise running.error
|
|
133
|
+
if not running.ok:
|
|
134
|
+
raise BydevError(Codes.PROTOCOL_ERROR, "작업 결과가 없다")
|
|
135
|
+
return running.value # type: ignore[return-value]
|
|
136
|
+
try:
|
|
137
|
+
value = work()
|
|
138
|
+
flight.value, flight.ok = value, True
|
|
139
|
+
return value
|
|
140
|
+
except BaseException as e:
|
|
141
|
+
flight.error = e
|
|
142
|
+
raise
|
|
143
|
+
finally:
|
|
144
|
+
with self._lock:
|
|
145
|
+
self._current = None
|
|
146
|
+
flight.done.fire()
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def rounded_ms(x: float) -> int:
|
|
150
|
+
"""`floor(x + 0.5)` 밀리초 — 명세 2절의 반올림."""
|
|
151
|
+
return math.floor(x + 0.5)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def seconds(sec: float) -> int:
|
|
155
|
+
"""초(소수 가능) → 밀리초."""
|
|
156
|
+
return rounded_ms(sec * 1000)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def jittered(random: RandomSource, base_ms: int, lo: float, hi: float) -> int:
|
|
160
|
+
"""`round(base × (min + (max − min) × r))`."""
|
|
161
|
+
return rounded_ms(base_ms * (lo + (hi - lo) * random.random()))
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def sha256_hex(data: bytes) -> str:
|
|
165
|
+
return hashlib.sha256(data).hexdigest()
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def b64url(text: str) -> bytes | None:
|
|
169
|
+
try:
|
|
170
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
171
|
+
except (binascii.Error, ValueError):
|
|
172
|
+
return None
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def format_iso(ms: int) -> str:
|
|
176
|
+
"""UTC ISO 8601 — 밀리초가 0이면 뗀다(`2026-10-06T13:00:00Z` · `…:00.250Z`)."""
|
|
177
|
+
sec, millis = divmod(ms, 1000)
|
|
178
|
+
base = datetime.fromtimestamp(sec, UTC).strftime("%Y-%m-%dT%H:%M:%S")
|
|
179
|
+
return f"{base}Z" if millis == 0 else f"{base}.{millis:03d}Z"
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def parse_iso(text: str) -> int | None:
|
|
183
|
+
"""RFC 3339(`Z` 또는 `±hh:mm`, 소수 초 허용) → Unix 밀리초. 읽지 못하면 None."""
|
|
184
|
+
if len(text) < 20 or text[10] not in "Tt":
|
|
185
|
+
return None
|
|
186
|
+
try:
|
|
187
|
+
parsed = datetime.fromisoformat(text[:-1] + "+00:00" if text[-1] in "Zz" else text)
|
|
188
|
+
except ValueError:
|
|
189
|
+
return None
|
|
190
|
+
if parsed.tzinfo is None:
|
|
191
|
+
return None
|
|
192
|
+
return (parsed - _EPOCH) // timedelta(milliseconds=1)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
_EPOCH = datetime(1970, 1, 1, tzinfo=UTC)
|
bydev/_tokens.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""명세 3.5 · 3.6 · 6절 — 기록 보관 · 갱신 · 인증 요청 감싸기 · 로그아웃."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from collections.abc import Callable
|
|
7
|
+
|
|
8
|
+
from ._api import Api, ApiResponse, Req
|
|
9
|
+
from ._generated import Codes, Rules
|
|
10
|
+
from ._support import SingleFlight, format_iso, seconds
|
|
11
|
+
from .errors import BydevError, storage
|
|
12
|
+
from .models import TokenSet
|
|
13
|
+
from .ports import CredentialRecord
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TokenManager:
|
|
17
|
+
def __init__(self, api: Api, client_id: str) -> None:
|
|
18
|
+
self.api = api
|
|
19
|
+
self._client_id = client_id
|
|
20
|
+
self._lock = threading.Lock()
|
|
21
|
+
self._access: tuple[str, int] | None = None
|
|
22
|
+
self._refreshing: SingleFlight[str] = SingleFlight()
|
|
23
|
+
|
|
24
|
+
def _set_access(self, value: tuple[str, int] | None) -> None:
|
|
25
|
+
with self._lock:
|
|
26
|
+
self._access = value
|
|
27
|
+
|
|
28
|
+
def load(self) -> CredentialRecord | None:
|
|
29
|
+
try:
|
|
30
|
+
record = self.api.ports.store.load()
|
|
31
|
+
except Exception as e:
|
|
32
|
+
raise storage(e, "보안 저장소를 읽지 못했다") from e
|
|
33
|
+
return record if record is not None and record.version == Rules.STORAGE_RECORD_VERSION else None
|
|
34
|
+
|
|
35
|
+
def adopt(self, tokens: TokenSet) -> None:
|
|
36
|
+
"""6절 3 · 5절 — 저장한 뒤에 쓴다."""
|
|
37
|
+
self._set_access(None)
|
|
38
|
+
ports = self.api.ports
|
|
39
|
+
record = CredentialRecord(1, tokens.refresh_token, tokens.scope, format_iso(ports.clock.now_ms()))
|
|
40
|
+
try:
|
|
41
|
+
ports.store.save(record)
|
|
42
|
+
except Exception as e:
|
|
43
|
+
raise storage(e, "새 로그인을 보안 저장소에 두지 못했다 — 새 토큰을 쓰지 않는다") from e
|
|
44
|
+
self._set_access((tokens.access_token, ports.clock.now_ms() + tokens.expires_in * 1000))
|
|
45
|
+
|
|
46
|
+
def _access_token(self) -> str:
|
|
47
|
+
with self._lock:
|
|
48
|
+
access = self._access
|
|
49
|
+
if (
|
|
50
|
+
access is not None
|
|
51
|
+
and access[1] - Rules.TOKEN_REFRESH_SKEW_SEC * 1000 > self.api.ports.clock.now_ms()
|
|
52
|
+
):
|
|
53
|
+
return access[0]
|
|
54
|
+
return self.refresh()
|
|
55
|
+
|
|
56
|
+
def refresh(self) -> str:
|
|
57
|
+
"""6절 1 — 한 번에 하나."""
|
|
58
|
+
self._set_access(None)
|
|
59
|
+
return self._refreshing.run(self.api.ports.scheduler, self._do_refresh)
|
|
60
|
+
|
|
61
|
+
def _do_refresh(self) -> str:
|
|
62
|
+
record = self.load()
|
|
63
|
+
if record is None:
|
|
64
|
+
raise BydevError(Codes.NOT_SIGNED_IN, "로그인이 없다 — 먼저 로그인한다")
|
|
65
|
+
doc = self.api.discovery()
|
|
66
|
+
attempt = 0
|
|
67
|
+
while True:
|
|
68
|
+
body = {
|
|
69
|
+
"grant_type": "refresh_token",
|
|
70
|
+
"client_id": self._client_id,
|
|
71
|
+
"refresh_token": record.refresh_token,
|
|
72
|
+
}
|
|
73
|
+
try:
|
|
74
|
+
tokens = TokenSet.read(self.api.send(Req("POST", doc.token_endpoint, body)).json)
|
|
75
|
+
self.adopt(tokens)
|
|
76
|
+
return tokens.access_token
|
|
77
|
+
except BydevError as e:
|
|
78
|
+
if e.code == Codes.INVALID_GRANT:
|
|
79
|
+
self._forget_stored()
|
|
80
|
+
raise
|
|
81
|
+
if not e.is_transient or attempt >= len(Rules.TOKEN_REFRESH_RETRY_DELAYS_SEC):
|
|
82
|
+
raise
|
|
83
|
+
self.api.ports.scheduler.sleep(seconds(Rules.TOKEN_REFRESH_RETRY_DELAYS_SEC[attempt]))
|
|
84
|
+
attempt += 1
|
|
85
|
+
|
|
86
|
+
def authed(self, send: Callable[[str], ApiResponse]) -> ApiResponse:
|
|
87
|
+
"""3.5절 — 만료면 한 번만 갱신하고 다시 보낸다."""
|
|
88
|
+
token = self._access_token()
|
|
89
|
+
try:
|
|
90
|
+
return send(token)
|
|
91
|
+
except BydevError as e:
|
|
92
|
+
if e.code != Codes.EXPIRED_TOKEN:
|
|
93
|
+
raise
|
|
94
|
+
fresh = self.refresh()
|
|
95
|
+
try:
|
|
96
|
+
return send(fresh)
|
|
97
|
+
except BydevError as e:
|
|
98
|
+
# 갓 받은 토큰도 거절됐다 — 다음 요청이 같은 토큰을 다시 쓰지 않게 버린다
|
|
99
|
+
if e.code == Codes.EXPIRED_TOKEN:
|
|
100
|
+
self._set_access(None)
|
|
101
|
+
raise
|
|
102
|
+
|
|
103
|
+
def _forget_stored(self) -> None:
|
|
104
|
+
self._set_access(None)
|
|
105
|
+
try:
|
|
106
|
+
self.api.ports.store.clear()
|
|
107
|
+
except Exception:
|
|
108
|
+
self.api.ports.logger.warn("끝난 로그인의 기록을 지우지 못했다")
|
|
109
|
+
|
|
110
|
+
def logout(self) -> bool:
|
|
111
|
+
"""7절 — 폐기 요청은 한 번, 결과와 상관없이 지운다. 서버가 폐기했는지를 돌려준다."""
|
|
112
|
+
record = self.load()
|
|
113
|
+
revoked = False
|
|
114
|
+
if record is not None:
|
|
115
|
+
try:
|
|
116
|
+
doc = self.api.discovery()
|
|
117
|
+
body = {
|
|
118
|
+
"client_id": self._client_id,
|
|
119
|
+
"token": record.refresh_token,
|
|
120
|
+
"token_type_hint": "refresh_token",
|
|
121
|
+
}
|
|
122
|
+
self.api.send(Req("POST", doc.revocation_endpoint, body))
|
|
123
|
+
revoked = True
|
|
124
|
+
except BydevError:
|
|
125
|
+
revoked = False
|
|
126
|
+
self._set_access(None)
|
|
127
|
+
try:
|
|
128
|
+
self.api.ports.store.clear()
|
|
129
|
+
except Exception as e:
|
|
130
|
+
raise storage(e, "로그인 기록을 지우지 못했다") from e
|
|
131
|
+
return revoked
|
bydev/_verifier.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""명세 9절 — 토큰 검증 · JWKS 캐시 · 세대번호 단조 확인."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from cryptography.exceptions import InvalidSignature
|
|
10
|
+
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
|
|
11
|
+
|
|
12
|
+
from ._api import Api, Req
|
|
13
|
+
from ._generated import Codes, Rules
|
|
14
|
+
from ._support import Reader, SingleFlight, b64url, loads
|
|
15
|
+
from .errors import BydevError
|
|
16
|
+
from .models import AccessClaims, LicenseClaims
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True)
|
|
20
|
+
class Expectation:
|
|
21
|
+
sid: str
|
|
22
|
+
device_id: str
|
|
23
|
+
generation: int
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class _KeySet:
|
|
28
|
+
keys: dict[str, Ed25519PublicKey]
|
|
29
|
+
fetched_at_ms: int
|
|
30
|
+
expires_at_ms: int
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _invalid(message: str) -> BydevError:
|
|
34
|
+
return BydevError(Codes.TOKEN_INVALID, message)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _regressed(got: int, seen: int) -> BydevError:
|
|
38
|
+
return BydevError(Codes.GENERATION_REGRESSED, f"세대번호 {got} < 이미 본 {seen}")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Verifier:
|
|
42
|
+
def __init__(self, api: Api, client_id: str, *, track_generations: bool) -> None:
|
|
43
|
+
self._api = api
|
|
44
|
+
self._client_id = client_id
|
|
45
|
+
self._track = track_generations
|
|
46
|
+
self._lock = threading.Lock()
|
|
47
|
+
self._set: _KeySet | None = None
|
|
48
|
+
self._fetching: SingleFlight[_KeySet] = SingleFlight()
|
|
49
|
+
self._generations: dict[str, int] = {}
|
|
50
|
+
|
|
51
|
+
def _verify_signed(self, token: str, typ: str) -> dict[str, Any]:
|
|
52
|
+
"""9절 1 ~ 4. 페이로드를 돌려준다."""
|
|
53
|
+
parts = token.split(".")
|
|
54
|
+
if len(parts) != 3:
|
|
55
|
+
raise _invalid("JWT 형식이 아니다")
|
|
56
|
+
head_raw, body_raw, sig = (b64url(p) for p in parts)
|
|
57
|
+
header = loads(head_raw) if head_raw is not None else None
|
|
58
|
+
payload = loads(body_raw) if body_raw is not None else None
|
|
59
|
+
if not isinstance(header, dict) or not isinstance(payload, dict) or sig is None:
|
|
60
|
+
raise _invalid("JWT를 읽지 못했다")
|
|
61
|
+
if header.get("alg") != "EdDSA":
|
|
62
|
+
raise _invalid(f"alg {header.get('alg')}")
|
|
63
|
+
if header.get("typ") != typ:
|
|
64
|
+
raise _invalid(f"typ {header.get('typ')}")
|
|
65
|
+
kid = header.get("kid")
|
|
66
|
+
if not isinstance(kid, str):
|
|
67
|
+
raise _invalid("kid가 없다")
|
|
68
|
+
key = self._key_for(kid)
|
|
69
|
+
try:
|
|
70
|
+
key.verify(sig, f"{parts[0]}.{parts[1]}".encode())
|
|
71
|
+
except InvalidSignature:
|
|
72
|
+
raise _invalid("서명이 맞지 않는다") from None
|
|
73
|
+
doc = self._api.discovery()
|
|
74
|
+
if payload.get("iss") != doc.issuer:
|
|
75
|
+
raise _invalid("iss가 다르다")
|
|
76
|
+
if payload.get("aud") != self._client_id:
|
|
77
|
+
raise _invalid("aud가 이 client_id가 아니다")
|
|
78
|
+
exp = payload.get("exp")
|
|
79
|
+
now_sec = self._api.ports.clock.now_ms() / 1000
|
|
80
|
+
if (
|
|
81
|
+
not isinstance(exp, int | float)
|
|
82
|
+
or isinstance(exp, bool)
|
|
83
|
+
or exp <= now_sec - Rules.TOKEN_CLOCK_LEEWAY_SEC
|
|
84
|
+
):
|
|
85
|
+
raise _invalid("만료된 토큰")
|
|
86
|
+
return payload
|
|
87
|
+
|
|
88
|
+
def verify_license(self, token: str, expect: Expectation | None, min_generation: int) -> LicenseClaims:
|
|
89
|
+
payload = self._verify_signed(token, "license+jwt")
|
|
90
|
+
try:
|
|
91
|
+
claims = LicenseClaims.read(payload)
|
|
92
|
+
except BydevError:
|
|
93
|
+
raise _invalid("클레임 모양이 다르다") from None
|
|
94
|
+
if expect is not None:
|
|
95
|
+
if claims.sid != expect.sid:
|
|
96
|
+
raise _invalid("sid가 세션과 다르다")
|
|
97
|
+
if claims.device_id != expect.device_id:
|
|
98
|
+
raise _invalid("device_id가 세션과 다르다")
|
|
99
|
+
if claims.generation != expect.generation:
|
|
100
|
+
raise _invalid("generation이 세션과 다르다")
|
|
101
|
+
if min_generation > 0 and claims.generation < min_generation:
|
|
102
|
+
raise _regressed(claims.generation, min_generation)
|
|
103
|
+
if self._track:
|
|
104
|
+
slot = f"{claims.sub}|{claims.device_id}"
|
|
105
|
+
with self._lock:
|
|
106
|
+
seen = self._generations.get(slot)
|
|
107
|
+
if seen is None or claims.generation >= seen:
|
|
108
|
+
self._generations[slot] = claims.generation
|
|
109
|
+
seen = None
|
|
110
|
+
if seen is not None:
|
|
111
|
+
raise _regressed(claims.generation, seen)
|
|
112
|
+
return claims
|
|
113
|
+
|
|
114
|
+
def verify_access(self, token: str) -> AccessClaims:
|
|
115
|
+
payload = self._verify_signed(token, "at+jwt")
|
|
116
|
+
try:
|
|
117
|
+
return AccessClaims.read(payload)
|
|
118
|
+
except BydevError:
|
|
119
|
+
raise _invalid("클레임 모양이 다르다") from None
|
|
120
|
+
|
|
121
|
+
def _key_for(self, kid: str) -> Ed25519PublicKey:
|
|
122
|
+
"""9.1절 — 지난 캐시는 쓰지 않는다 · 모르는 kid는 1분에 한 번만 다시 받는다."""
|
|
123
|
+
now = self._api.ports.clock.now_ms()
|
|
124
|
+
with self._lock:
|
|
125
|
+
current = self._set
|
|
126
|
+
keys = current if current is not None and now < current.expires_at_ms else self._fetch_keys()
|
|
127
|
+
if kid in keys.keys:
|
|
128
|
+
return keys.keys[kid]
|
|
129
|
+
if now - keys.fetched_at_ms < Rules.JWKS_UNKNOWN_KID_REFETCH_MIN_INTERVAL_SEC * 1000:
|
|
130
|
+
raise _invalid(f"모르는 kid {kid}")
|
|
131
|
+
fresh = self._fetch_keys()
|
|
132
|
+
if kid not in fresh.keys:
|
|
133
|
+
raise _invalid(f"모르는 kid {kid}")
|
|
134
|
+
return fresh.keys[kid]
|
|
135
|
+
|
|
136
|
+
def _fetch_keys(self) -> _KeySet:
|
|
137
|
+
def fetch() -> _KeySet:
|
|
138
|
+
doc = self._api.discovery()
|
|
139
|
+
res = self._api.send(Req("GET", doc.jwks_uri))
|
|
140
|
+
r = Reader()
|
|
141
|
+
root = r.obj(res.json, "$")
|
|
142
|
+
keys: dict[str, Ed25519PublicKey] = {}
|
|
143
|
+
for jwk in r.items(r.get(root, "keys"), "keys"):
|
|
144
|
+
if not isinstance(jwk, dict) or jwk.get("kty") != "OKP" or jwk.get("crv") != "Ed25519":
|
|
145
|
+
continue
|
|
146
|
+
kid, x = jwk.get("kid"), jwk.get("x")
|
|
147
|
+
raw = b64url(x) if isinstance(x, str) else None
|
|
148
|
+
if isinstance(kid, str) and kid and raw is not None and len(raw) == 32:
|
|
149
|
+
keys[kid] = Ed25519PublicKey.from_public_bytes(raw)
|
|
150
|
+
else:
|
|
151
|
+
self._api.ports.logger.warn("JWKS 키를 읽지 못했다")
|
|
152
|
+
r.finish(None)
|
|
153
|
+
age = Rules.JWKS_DEFAULT_MAX_AGE_SEC
|
|
154
|
+
for part in res.headers.get("cache-control", "").split(","):
|
|
155
|
+
part = part.strip()
|
|
156
|
+
if part.startswith("max-age=") and part[8:].isdigit():
|
|
157
|
+
age = int(part[8:])
|
|
158
|
+
break
|
|
159
|
+
fetched = self._api.ports.clock.now_ms()
|
|
160
|
+
result = _KeySet(keys, fetched, fetched + age * 1000)
|
|
161
|
+
with self._lock:
|
|
162
|
+
self._set = result
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
return self._fetching.run(self._api.ports.scheduler, fetch)
|
bydev/aio.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""asyncio에서 쓰는 감싸개 — 블로킹 호출을 `asyncio.to_thread`로 넘긴다. 상태 기계 · 타이머는 `LicenseClient`와 같다."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
|
|
7
|
+
from .client import Config, LicenseClient
|
|
8
|
+
from .login import LoginAttempt, LoginResult
|
|
9
|
+
from .models import DevicePage, DeviceRelease, Entitlement, LicenseClaims, Profile, UpdateCheck
|
|
10
|
+
from .session import LicenseSession
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class AsyncLicenseClient:
|
|
14
|
+
"""`LicenseClient`의 asyncio 판이다. 세션 구독 함수는 SDK의 스레드에서 불린다 — 이벤트 루프로는 `loop.call_soon_threadsafe`로 넘긴다."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, config: Config) -> None:
|
|
17
|
+
self.sync = LicenseClient(config)
|
|
18
|
+
|
|
19
|
+
async def start_login(self) -> LoginAttempt:
|
|
20
|
+
return await asyncio.to_thread(self.sync.start_login)
|
|
21
|
+
|
|
22
|
+
async def wait_login(self, attempt: LoginAttempt) -> LoginResult:
|
|
23
|
+
"""`attempt.wait()`를 스레드에서 기다린다. 취소는 `attempt.cancel()`."""
|
|
24
|
+
return await asyncio.to_thread(attempt.wait)
|
|
25
|
+
|
|
26
|
+
async def has_credentials(self) -> bool:
|
|
27
|
+
return await asyncio.to_thread(self.sync.has_credentials)
|
|
28
|
+
|
|
29
|
+
async def entitlement(self) -> Entitlement:
|
|
30
|
+
return await asyncio.to_thread(self.sync.entitlement)
|
|
31
|
+
|
|
32
|
+
async def devices(self, cursor: str | None = None, limit: int | None = None) -> DevicePage:
|
|
33
|
+
return await asyncio.to_thread(self.sync.devices, cursor, limit)
|
|
34
|
+
|
|
35
|
+
async def release_device(self, device_id: str) -> DeviceRelease:
|
|
36
|
+
return await asyncio.to_thread(self.sync.release_device, device_id)
|
|
37
|
+
|
|
38
|
+
async def profile(self) -> Profile:
|
|
39
|
+
return await asyncio.to_thread(self.sync.profile)
|
|
40
|
+
|
|
41
|
+
async def check_for_update(self, target: str, current_version: str) -> UpdateCheck:
|
|
42
|
+
return await asyncio.to_thread(self.sync.check_for_update, target, current_version)
|
|
43
|
+
|
|
44
|
+
def verify_download(self, data: bytes, sha256: str) -> None:
|
|
45
|
+
self.sync.verify_download(data, sha256)
|
|
46
|
+
|
|
47
|
+
async def verify_token(self, token: str) -> LicenseClaims:
|
|
48
|
+
return await asyncio.to_thread(self.sync.verify_token, token)
|
|
49
|
+
|
|
50
|
+
async def logout(self) -> bool:
|
|
51
|
+
return await asyncio.to_thread(self.sync.logout)
|
|
52
|
+
|
|
53
|
+
def session(self) -> LicenseSession:
|
|
54
|
+
"""세션 — `start` · `take_over` · `retry`는 블로킹하지 않는다. `stop`은 반납을 보내니 `await asyncio.to_thread(session.stop)`."""
|
|
55
|
+
return self.sync.session()
|