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/platform.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
"""명세 2절 표 — 운영체제별 기본 구현. 원본 지문 · 토큰을 명령 줄 인자로 넘기지 않는다(비밀은 표준 입력으로만).
|
|
2
|
+
|
|
3
|
+
TS · Go · Kotlin과 같은 명령 모양이다. 클라이언트의 기본 저장소는 메모리다 — 앱이 이 중에서 고른다.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import contextlib
|
|
9
|
+
import os
|
|
10
|
+
import re
|
|
11
|
+
import shutil
|
|
12
|
+
import socket
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import tempfile
|
|
16
|
+
import time
|
|
17
|
+
import uuid
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Protocol
|
|
20
|
+
|
|
21
|
+
from ._generated import DevicePlatform, Rules
|
|
22
|
+
from ._support import dumps, loads
|
|
23
|
+
from .ports import CredentialRecord, CredentialStore, FingerprintSource, LogSink
|
|
24
|
+
from .session import DeviceInfo
|
|
25
|
+
|
|
26
|
+
# Windows에서 명령(powershell · reg)을 콘솔 창 없이 띄운다(CREATE_NO_WINDOW). GUI 앱(pythonw · 묶은 실행 파일)이 띄운 콘솔 명령은 창이 깜빡이고,
|
|
27
|
+
# 콘솔을 만들지 못하면 0xC0000142로 끝난다(명세 2절). 다른 운영체제는 0
|
|
28
|
+
_NO_CONSOLE = 0x08000000 if sys.platform == "win32" else 0
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class ExitCodeError(OSError):
|
|
32
|
+
"""명령이 0이 아닌 코드로 끝났다. ``stderr``는 그 명령의 오류 출력이다."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, program: str, code: int, stderr: str = "") -> None:
|
|
35
|
+
super().__init__(f"{program}가 {code}로 끝났다")
|
|
36
|
+
self.code = code
|
|
37
|
+
self.stderr = stderr
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class _Os(Protocol):
|
|
41
|
+
"""명령 실행 · 파일 — 단위 시험이 바꿔 끼운다."""
|
|
42
|
+
|
|
43
|
+
name: str
|
|
44
|
+
|
|
45
|
+
def exec(self, program: str, args: list[str], stdin: str | None = None) -> str: ...
|
|
46
|
+
|
|
47
|
+
def has(self, program: str) -> bool: ...
|
|
48
|
+
|
|
49
|
+
def read_file(self, path: str) -> str | None: ...
|
|
50
|
+
|
|
51
|
+
def write_file(self, path: str, content: str) -> None: ...
|
|
52
|
+
|
|
53
|
+
def remove(self, path: str) -> None: ...
|
|
54
|
+
|
|
55
|
+
def new_id(self) -> str: ...
|
|
56
|
+
|
|
57
|
+
def sleep(self, seconds: float) -> None: ...
|
|
58
|
+
|
|
59
|
+
def machine_guid(self) -> str | None:
|
|
60
|
+
"""Windows 레지스트리 API로 읽은 MachineGuid — 읽지 못하면 None(그때는 reg 명령으로)."""
|
|
61
|
+
...
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _os_name() -> str:
|
|
65
|
+
if sys.platform.startswith("win"):
|
|
66
|
+
return "windows"
|
|
67
|
+
if sys.platform == "darwin":
|
|
68
|
+
return "macos"
|
|
69
|
+
if sys.platform.startswith("linux"):
|
|
70
|
+
return "linux"
|
|
71
|
+
return "other"
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _RealOs:
|
|
75
|
+
name = _os_name()
|
|
76
|
+
|
|
77
|
+
def exec(self, program: str, args: list[str], stdin: str | None = None) -> str:
|
|
78
|
+
# 고정된 프로그램 · 인자 — 비밀은 표준 입력으로만
|
|
79
|
+
done = subprocess.run(
|
|
80
|
+
[program, *args],
|
|
81
|
+
input=(stdin or "").encode(),
|
|
82
|
+
# 오류 출력도 받아 실어 보낸다 — secret-tool은 "항목 없음"과 오류를 같은 종료 코드(1)로 내고 오류 출력으로만 가른다
|
|
83
|
+
capture_output=True,
|
|
84
|
+
check=False,
|
|
85
|
+
creationflags=_NO_CONSOLE,
|
|
86
|
+
)
|
|
87
|
+
if done.returncode != 0:
|
|
88
|
+
raise ExitCodeError(program, done.returncode, done.stderr.decode(errors="replace"))
|
|
89
|
+
return done.stdout.decode()
|
|
90
|
+
|
|
91
|
+
def has(self, program: str) -> bool:
|
|
92
|
+
return shutil.which(program) is not None
|
|
93
|
+
|
|
94
|
+
def read_file(self, path: str) -> str | None:
|
|
95
|
+
try:
|
|
96
|
+
return Path(path).read_text(encoding="utf-8")
|
|
97
|
+
except (FileNotFoundError, IsADirectoryError, NotADirectoryError):
|
|
98
|
+
return None
|
|
99
|
+
|
|
100
|
+
def write_file(self, path: str, content: str) -> None:
|
|
101
|
+
"""사용자만 읽는 권한(0600) 임시 파일 뒤 이름 바꾸기 — 반쯤 쓴 파일이 남지 않게, 다른 사용자가 읽는 틈이 없게."""
|
|
102
|
+
target = Path(path).absolute()
|
|
103
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
104
|
+
# mkstemp는 0600으로 만든다(POSIX)
|
|
105
|
+
fd, temp = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".tmp", dir=target.parent)
|
|
106
|
+
try:
|
|
107
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
108
|
+
f.write(content)
|
|
109
|
+
os.replace(temp, target)
|
|
110
|
+
finally:
|
|
111
|
+
with contextlib.suppress(FileNotFoundError):
|
|
112
|
+
os.unlink(temp)
|
|
113
|
+
|
|
114
|
+
def remove(self, path: str) -> None:
|
|
115
|
+
with contextlib.suppress(FileNotFoundError):
|
|
116
|
+
os.unlink(path)
|
|
117
|
+
|
|
118
|
+
def new_id(self) -> str:
|
|
119
|
+
return str(uuid.uuid4())
|
|
120
|
+
|
|
121
|
+
def sleep(self, seconds: float) -> None:
|
|
122
|
+
time.sleep(seconds)
|
|
123
|
+
|
|
124
|
+
def machine_guid(self) -> str | None:
|
|
125
|
+
"""명령을 띄우지 않고 표준 라이브러리 winreg로 읽는다(명세 10절) — 32비트 Python도 64비트 보기를 읽는다(KEY_WOW64_64KEY)."""
|
|
126
|
+
if sys.platform != "win32":
|
|
127
|
+
return None
|
|
128
|
+
import winreg # Windows에만 있다
|
|
129
|
+
|
|
130
|
+
try:
|
|
131
|
+
with winreg.OpenKey(
|
|
132
|
+
winreg.HKEY_LOCAL_MACHINE,
|
|
133
|
+
r"SOFTWARE\Microsoft\Cryptography",
|
|
134
|
+
0,
|
|
135
|
+
winreg.KEY_READ | winreg.KEY_WOW64_64KEY,
|
|
136
|
+
) as key:
|
|
137
|
+
value, kind = winreg.QueryValueEx(key, "MachineGuid")
|
|
138
|
+
except OSError:
|
|
139
|
+
return None
|
|
140
|
+
return value if kind == winreg.REG_SZ and isinstance(value, str) else None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
_REAL = _RealOs()
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def app_data_dir(app_name: str, *, _os: str | None = None) -> str:
|
|
147
|
+
"""운영체제 · 앱 이름별 데이터 폴더다."""
|
|
148
|
+
home = Path.home()
|
|
149
|
+
match _os or _REAL.name:
|
|
150
|
+
case "windows":
|
|
151
|
+
return str(Path(os.environ.get("APPDATA") or home / "AppData" / "Roaming") / app_name)
|
|
152
|
+
case "macos":
|
|
153
|
+
return str(home / "Library" / "Application Support" / app_name)
|
|
154
|
+
case _:
|
|
155
|
+
return str(Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") / app_name)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def system_device_info() -> DeviceInfo:
|
|
159
|
+
"""`Config.device`의 기본값 — 컴퓨터 이름(64자까지)과 운영체제."""
|
|
160
|
+
platform = {
|
|
161
|
+
"windows": DevicePlatform.WINDOWS,
|
|
162
|
+
"macos": DevicePlatform.MACOS,
|
|
163
|
+
"linux": DevicePlatform.LINUX,
|
|
164
|
+
}.get(_REAL.name, DevicePlatform.OTHER)
|
|
165
|
+
name = (os.environ.get("COMPUTERNAME") or socket.gethostname() or "").strip() or "PC"
|
|
166
|
+
return DeviceInfo(name[:64], platform)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
_MACHINE_GUID = re.compile(r"MachineGuid\s+REG_SZ\s+(\S+)")
|
|
170
|
+
_PLATFORM_UUID = re.compile(r'"IOPlatformUUID"\s*=\s*"([^"]+)"')
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class _OsFingerprint:
|
|
174
|
+
def __init__(self, install_id_file: str | None, os_: _Os) -> None:
|
|
175
|
+
self._file = install_id_file
|
|
176
|
+
self._os = os_
|
|
177
|
+
|
|
178
|
+
def read(self) -> str | None:
|
|
179
|
+
# 실패하거나 빈 값이면 설치 ID로 물러나기 전에 다시 읽는다(명세 10절) — 일시적인 실패 하나로 같은 PC가 다른 기기가 되지 않게
|
|
180
|
+
for attempt in range(max(Rules.FINGERPRINT_SOURCE_READ_ATTEMPTS, 1)):
|
|
181
|
+
if attempt > 0:
|
|
182
|
+
self._os.sleep(Rules.FINGERPRINT_SOURCE_READ_RETRY_DELAY_MS / 1000)
|
|
183
|
+
try:
|
|
184
|
+
machine = (self._machine_id() or "").strip()
|
|
185
|
+
except OSError:
|
|
186
|
+
machine = ""
|
|
187
|
+
if machine:
|
|
188
|
+
return machine
|
|
189
|
+
if self._file is None:
|
|
190
|
+
return None
|
|
191
|
+
saved = (self._os.read_file(self._file) or "").strip()
|
|
192
|
+
if saved:
|
|
193
|
+
return saved
|
|
194
|
+
fresh = self._os.new_id()
|
|
195
|
+
self._os.write_file(self._file, fresh)
|
|
196
|
+
return fresh
|
|
197
|
+
|
|
198
|
+
def _machine_id(self) -> str | None:
|
|
199
|
+
match self._os.name:
|
|
200
|
+
case "windows":
|
|
201
|
+
api = (
|
|
202
|
+
self._os.machine_guid() or ""
|
|
203
|
+
).strip() # 레지스트리 API가 먼저 — 프로세스를 띄우지 않는다
|
|
204
|
+
if api:
|
|
205
|
+
return api
|
|
206
|
+
out = self._os.exec(
|
|
207
|
+
"reg", ["query", r"HKLM\SOFTWARE\Microsoft\Cryptography", "/v", "MachineGuid"]
|
|
208
|
+
)
|
|
209
|
+
m = _MACHINE_GUID.search(out)
|
|
210
|
+
return m.group(1) if m else None
|
|
211
|
+
case "macos":
|
|
212
|
+
m = _PLATFORM_UUID.search(self._os.exec("ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"]))
|
|
213
|
+
return m.group(1) if m else None
|
|
214
|
+
case _:
|
|
215
|
+
first = self._os.read_file("/etc/machine-id")
|
|
216
|
+
return first if first and first.strip() else self._os.read_file("/var/lib/dbus/machine-id")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def fingerprint_source(install_id_file: str | None = None) -> FingerprintSource:
|
|
220
|
+
"""명세 10절 · 2절 표의 지문 출처 — Windows MachineGuid · macOS IOPlatformUUID · Linux /etc/machine-id.
|
|
221
|
+
|
|
222
|
+
읽지 못하면 `install_id_file`의 설치 ID(없으면 만든다). `install_id_file`이 None이면 None(SDK가 클라이언트 수명 동안의 난수 ID로 물러난다).
|
|
223
|
+
"""
|
|
224
|
+
return _OsFingerprint(install_id_file, _REAL)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def _parse_record(text: str | None) -> CredentialRecord | None:
|
|
228
|
+
o = loads(text) if text else None
|
|
229
|
+
if not isinstance(o, dict) or o.get("version") != Rules.STORAGE_RECORD_VERSION:
|
|
230
|
+
return None
|
|
231
|
+
token = o.get("refreshToken")
|
|
232
|
+
if not isinstance(token, str) or not token:
|
|
233
|
+
return None
|
|
234
|
+
scope, saved_at = o.get("scope"), o.get("savedAt")
|
|
235
|
+
return CredentialRecord(
|
|
236
|
+
1, token, scope if isinstance(scope, str) else "", saved_at if isinstance(saved_at, str) else ""
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def _write_record(r: CredentialRecord) -> str:
|
|
241
|
+
return dumps(
|
|
242
|
+
{"version": r.version, "refreshToken": r.refresh_token, "scope": r.scope, "savedAt": r.saved_at}
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
class _FileStore:
|
|
247
|
+
def __init__(self, path: str, logger: LogSink | None, os_: _Os) -> None:
|
|
248
|
+
self._path = path
|
|
249
|
+
self._os = os_
|
|
250
|
+
if logger is not None:
|
|
251
|
+
logger.warn(
|
|
252
|
+
"로그인 기록을 암호화하지 않은 사용자 전용 파일에 둔다 — 운영체제 보안 저장소를 쓸 수 없는 환경"
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
def load(self) -> CredentialRecord | None:
|
|
256
|
+
return _parse_record(self._os.read_file(self._path))
|
|
257
|
+
|
|
258
|
+
def save(self, record: CredentialRecord) -> None:
|
|
259
|
+
self._os.write_file(self._path, _write_record(record))
|
|
260
|
+
|
|
261
|
+
def clear(self) -> None:
|
|
262
|
+
self._os.remove(self._path)
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _secret_tool_found_nothing(error: ExitCodeError) -> bool:
|
|
266
|
+
"""secret-tool이 항목을 찾지 못했다 — 오류 출력 없이 1로 끝난다.
|
|
267
|
+
|
|
268
|
+
오류(D-Bus 없음 · 잠긴 모음 · 없는 모음)도 1이지만 ``secret-tool: …``를 쓴다(2026-10-17 Debian 12 libsecret 0.20에서 확인).
|
|
269
|
+
"""
|
|
270
|
+
return error.code == 1 and error.stderr.strip() == ""
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class _SecretToolStore:
|
|
274
|
+
def __init__(self, account: str, os_: _Os) -> None:
|
|
275
|
+
self._account = account
|
|
276
|
+
self._os = os_
|
|
277
|
+
|
|
278
|
+
def _attributes(self, verb: str, *extra: str) -> list[str]:
|
|
279
|
+
return [verb, *extra, "service", Rules.STORAGE_SERVICE, "account", self._account]
|
|
280
|
+
|
|
281
|
+
def load(self) -> CredentialRecord | None:
|
|
282
|
+
try:
|
|
283
|
+
return _parse_record(self._os.exec("secret-tool", self._attributes("lookup")))
|
|
284
|
+
except ExitCodeError as e:
|
|
285
|
+
if _secret_tool_found_nothing(e):
|
|
286
|
+
return None
|
|
287
|
+
raise
|
|
288
|
+
|
|
289
|
+
def save(self, record: CredentialRecord) -> None:
|
|
290
|
+
self._os.exec(
|
|
291
|
+
"secret-tool", self._attributes("store", f"--label=bydev {self._account}"), _write_record(record)
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
def clear(self) -> None:
|
|
295
|
+
# 없는 항목을 지우는 것은 성공이다(로그아웃은 몇 번 해도 된다)
|
|
296
|
+
try:
|
|
297
|
+
self._os.exec("secret-tool", self._attributes("clear"))
|
|
298
|
+
except ExitCodeError as e:
|
|
299
|
+
if not _secret_tool_found_nothing(e):
|
|
300
|
+
raise
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
_PROTECT = (
|
|
304
|
+
"Add-Type -AssemblyName System.Security; $b=[Text.Encoding]::UTF8.GetBytes([Console]::In.ReadToEnd()); "
|
|
305
|
+
"[Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect($b,$null,'CurrentUser'))"
|
|
306
|
+
)
|
|
307
|
+
_UNPROTECT = (
|
|
308
|
+
"Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); "
|
|
309
|
+
"[Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($b,$null,'CurrentUser'))"
|
|
310
|
+
)
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
class _DpapiStore:
|
|
314
|
+
def __init__(self, path: str, os_: _Os) -> None:
|
|
315
|
+
self._path = path
|
|
316
|
+
self._os = os_
|
|
317
|
+
|
|
318
|
+
def _ps(self, script: str, data: str) -> str:
|
|
319
|
+
return self._os.exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], data)
|
|
320
|
+
|
|
321
|
+
def load(self) -> CredentialRecord | None:
|
|
322
|
+
sealed = (self._os.read_file(self._path) or "").strip()
|
|
323
|
+
return _parse_record(self._ps(_UNPROTECT, sealed)) if sealed else None
|
|
324
|
+
|
|
325
|
+
def save(self, record: CredentialRecord) -> None:
|
|
326
|
+
self._os.write_file(self._path, self._ps(_PROTECT, _write_record(record)).strip())
|
|
327
|
+
|
|
328
|
+
def clear(self) -> None:
|
|
329
|
+
self._os.remove(self._path)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def file_credential_store(path: str, logger: LogSink | None = None) -> CredentialStore:
|
|
333
|
+
"""사용자 전용 권한(0600) 파일 — **암호화하지 않는다.** 운영체제 보안 저장소를 쓸 수 없을 때만(warn 로그)."""
|
|
334
|
+
return _FileStore(path, logger, _REAL)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def dpapi_credential_store(path: str) -> CredentialStore:
|
|
338
|
+
"""Windows DPAPI(현재 사용자 범위)로 봉한 파일 — PowerShell에 표준 입력으로 넘긴다."""
|
|
339
|
+
return _DpapiStore(path, _REAL)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def secret_tool_credential_store(account: str) -> CredentialStore:
|
|
343
|
+
"""Linux Secret Service(libsecret `secret-tool`) — 비밀은 표준 입력으로 넘긴다. account는 client_id."""
|
|
344
|
+
return _SecretToolStore(account, _REAL)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _default_store(app_name: str, account: str, logger: LogSink | None, os_: _Os) -> CredentialStore:
|
|
348
|
+
file = str(Path(app_data_dir(app_name, _os=os_.name)) / "bydev-credentials")
|
|
349
|
+
if os_.name == "windows":
|
|
350
|
+
return _DpapiStore(file, os_)
|
|
351
|
+
if os_.name == "linux" and os_.has("secret-tool"):
|
|
352
|
+
return _SecretToolStore(account, os_)
|
|
353
|
+
return _FileStore(file, logger, os_)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def default_credential_store(app_name: str, account: str, logger: LogSink | None = None) -> CredentialStore:
|
|
357
|
+
"""운영체제에 맞는 기본 저장소 — Windows DPAPI 파일 · Linux Secret Service(`secret-tool`이 없으면 0600 파일 + warn) · macOS는 0600 파일 + warn.
|
|
358
|
+
|
|
359
|
+
macOS 키체인은 `keyring` 추가 설치(`bydev[keyring]`)의 `keyring_credential_store`로 쓴다 — `security` 명령은 비밀을 인자로 받아 쓰지 않는다
|
|
360
|
+
(ADR-0040 ⚠ 10). account는 client_id.
|
|
361
|
+
"""
|
|
362
|
+
return _default_store(app_name, account, logger, _REAL)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
class _KeyringStore:
|
|
366
|
+
def __init__(self, account: str, backend: Any) -> None:
|
|
367
|
+
self._account = account
|
|
368
|
+
self._backend = backend
|
|
369
|
+
|
|
370
|
+
def load(self) -> CredentialRecord | None:
|
|
371
|
+
return _parse_record(self._backend.get_password(Rules.STORAGE_SERVICE, self._account))
|
|
372
|
+
|
|
373
|
+
def save(self, record: CredentialRecord) -> None:
|
|
374
|
+
self._backend.set_password(Rules.STORAGE_SERVICE, self._account, _write_record(record))
|
|
375
|
+
|
|
376
|
+
def clear(self) -> None:
|
|
377
|
+
# 없는 항목을 지우면 백엔드가 던진다 — 지워진 것과 같다
|
|
378
|
+
with contextlib.suppress(*_keyring_errors()):
|
|
379
|
+
self._backend.delete_password(Rules.STORAGE_SERVICE, self._account)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _keyring_errors() -> tuple[type[BaseException], ...]:
|
|
383
|
+
try:
|
|
384
|
+
from keyring.errors import PasswordDeleteError
|
|
385
|
+
except ImportError:
|
|
386
|
+
return (LookupError,)
|
|
387
|
+
return (PasswordDeleteError, LookupError)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def keyring_credential_store(account: str, backend: Any = None) -> CredentialStore:
|
|
391
|
+
"""`keyring` 라이브러리의 저장소 — macOS 키체인 · Windows 자격 증명 관리자 · Secret Service. `pip install "bydev[keyring]"`로 깐다.
|
|
392
|
+
|
|
393
|
+
`backend`를 주면 그 백엔드(`keyring.backend.KeyringBackend`)를, 아니면 `keyring`이 고른 기본 백엔드를 쓴다. account는 client_id.
|
|
394
|
+
"""
|
|
395
|
+
if backend is None:
|
|
396
|
+
try:
|
|
397
|
+
import keyring
|
|
398
|
+
except ImportError as e:
|
|
399
|
+
raise ImportError(
|
|
400
|
+
'keyring_credential_store에는 keyring이 필요하다 — pip install "bydev[keyring]"'
|
|
401
|
+
) from e
|
|
402
|
+
backend = keyring.get_keyring()
|
|
403
|
+
return _KeyringStore(account, backend)
|
bydev/ports.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""명세 2절 — 바꿔 끼울 수 있는 포트. SDK 안에서 시계 · 타이머 · 난수를 직접 읽지 않는다.
|
|
2
|
+
|
|
3
|
+
이름은 명세의 Transport · CredentialStore · Clock · Scheduler · Random · FingerprintSource · Logger이고, `random` · `logging`과 헷갈리지 않게 Swift ·
|
|
4
|
+
Kotlin SDK와 같은 이름으로 바꿨다.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import threading
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from typing import Protocol
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class HttpRequest:
|
|
17
|
+
"""전송 포트가 보낼 요청이다. `body`가 None이면 본문이 없다. 헤더 이름은 소문자다."""
|
|
18
|
+
|
|
19
|
+
method: str
|
|
20
|
+
url: str
|
|
21
|
+
headers: dict[str, str]
|
|
22
|
+
body: bytes | None
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class HttpResponse:
|
|
27
|
+
"""받은 응답이다. 헤더 이름은 소문자다."""
|
|
28
|
+
|
|
29
|
+
status: int
|
|
30
|
+
headers: dict[str, str]
|
|
31
|
+
body: bytes
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class HttpTransport(Protocol):
|
|
35
|
+
"""요청을 보낸다. 연결 실패 · 시간 초과는 던진다(SDK가 `NETWORK_ERROR`로 감싼다). 3xx를 따라가지 않는다."""
|
|
36
|
+
|
|
37
|
+
def send(self, request: HttpRequest) -> HttpResponse: ...
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class CredentialRecord:
|
|
42
|
+
"""보안 저장소에 두는 기록이다(명세 3.6). access_token은 두지 않는다."""
|
|
43
|
+
|
|
44
|
+
version: int
|
|
45
|
+
refresh_token: str
|
|
46
|
+
scope: str
|
|
47
|
+
saved_at: str
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CredentialStore(Protocol):
|
|
51
|
+
"""로그인 기록을 둔다. 없으면 `load`가 None. 실패는 던진다(SDK가 `STORAGE_FAILED`로 감싼다)."""
|
|
52
|
+
|
|
53
|
+
def load(self) -> CredentialRecord | None: ...
|
|
54
|
+
|
|
55
|
+
def save(self, record: CredentialRecord) -> None: ...
|
|
56
|
+
|
|
57
|
+
def clear(self) -> None: ...
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class WallClock(Protocol):
|
|
61
|
+
"""지금 시각(Unix 밀리초) — 명세의 Clock."""
|
|
62
|
+
|
|
63
|
+
def now_ms(self) -> int: ...
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class Cancel:
|
|
67
|
+
"""예약 취소 손잡이. 놓아도 취소하지 않는다 — `cancel()`을 부른다."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, on_cancel: Callable[[], None]) -> None:
|
|
70
|
+
self._on_cancel = on_cancel
|
|
71
|
+
self._done = False
|
|
72
|
+
self._lock = threading.Lock()
|
|
73
|
+
|
|
74
|
+
def cancel(self) -> None:
|
|
75
|
+
with self._lock:
|
|
76
|
+
if self._done:
|
|
77
|
+
return
|
|
78
|
+
self._done = True
|
|
79
|
+
self._on_cancel()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
class Signal:
|
|
83
|
+
"""한 번 켜지는 신호 — 다른 작업의 끝(single-flight · 로그인)을 기다릴 때 쓴다. SDK는 `block()`을 직접 부르지 않고 `TaskScheduler.wait`를 거친다."""
|
|
84
|
+
|
|
85
|
+
def __init__(self) -> None:
|
|
86
|
+
self._event = threading.Event()
|
|
87
|
+
|
|
88
|
+
def fire(self) -> None:
|
|
89
|
+
self._event.set()
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def is_fired(self) -> bool:
|
|
93
|
+
return self._event.is_set()
|
|
94
|
+
|
|
95
|
+
def block(self, timeout: float | None = None) -> bool:
|
|
96
|
+
"""켜질 때까지(또는 `timeout`초까지) 막는다. 켜졌으면 True."""
|
|
97
|
+
return self._event.wait(timeout)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class TaskScheduler(Protocol):
|
|
101
|
+
"""나중 작업 · 기다림 — 명세의 Scheduler. SDK가 시간이나 다른 작업을 기다리는 곳은 모두 `sleep` · `wait`를 거친다(명세 2절 — 블로킹 언어).
|
|
102
|
+
|
|
103
|
+
SDK는 스스로 스레드를 만들지 않고 `after`로만 백그라운드 작업을 시작한다.
|
|
104
|
+
"""
|
|
105
|
+
|
|
106
|
+
def after(self, delay_ms: int, task: Callable[[], None]) -> Cancel: ...
|
|
107
|
+
|
|
108
|
+
def sleep(self, ms: int) -> None: ...
|
|
109
|
+
|
|
110
|
+
def wait(self, signal: Signal) -> None: ...
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class RandomSource(Protocol):
|
|
114
|
+
"""`[0, 1)` 실수와 UUID v4(소문자) — 명세의 Random."""
|
|
115
|
+
|
|
116
|
+
def random(self) -> float: ...
|
|
117
|
+
|
|
118
|
+
def uuid(self) -> str: ...
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class FingerprintSource(Protocol):
|
|
122
|
+
"""운영체제의 기기 식별자다. 없으면 None — 원본은 SDK 밖으로 나가지 않는다(해시만, 명세 10절)."""
|
|
123
|
+
|
|
124
|
+
def read(self) -> str | None: ...
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class LogSink(Protocol):
|
|
128
|
+
"""토큰 · 지문 출처 값은 넘어오지 않는다 — 명세의 Logger."""
|
|
129
|
+
|
|
130
|
+
def debug(self, message: str) -> None: ...
|
|
131
|
+
|
|
132
|
+
def info(self, message: str) -> None: ...
|
|
133
|
+
|
|
134
|
+
def warn(self, message: str) -> None: ...
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@dataclass
|
|
138
|
+
class Ports:
|
|
139
|
+
"""클라이언트가 쓰는 포트 묶음이다. 비운 칸은 기본 구현이다."""
|
|
140
|
+
|
|
141
|
+
transport: HttpTransport | None = None
|
|
142
|
+
store: CredentialStore | None = None
|
|
143
|
+
clock: WallClock | None = None
|
|
144
|
+
scheduler: TaskScheduler | None = None
|
|
145
|
+
random: RandomSource | None = None
|
|
146
|
+
fingerprint: FingerprintSource | None = None
|
|
147
|
+
logger: LogSink | None = None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@dataclass(frozen=True)
|
|
151
|
+
class ResolvedPorts:
|
|
152
|
+
"""기본값을 채운 포트."""
|
|
153
|
+
|
|
154
|
+
transport: HttpTransport
|
|
155
|
+
store: CredentialStore
|
|
156
|
+
clock: WallClock
|
|
157
|
+
scheduler: TaskScheduler
|
|
158
|
+
random: RandomSource
|
|
159
|
+
fingerprint: FingerprintSource
|
|
160
|
+
logger: LogSink
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def resolve(ports: Ports) -> ResolvedPorts:
|
|
164
|
+
from .defaults import (
|
|
165
|
+
MemoryCredentialStore,
|
|
166
|
+
NoFingerprint,
|
|
167
|
+
SecureRandom,
|
|
168
|
+
SilentLog,
|
|
169
|
+
SystemClock,
|
|
170
|
+
ThreadScheduler,
|
|
171
|
+
UrllibTransport,
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
return ResolvedPorts(
|
|
175
|
+
transport=ports.transport or UrllibTransport(),
|
|
176
|
+
store=ports.store or MemoryCredentialStore(),
|
|
177
|
+
clock=ports.clock or SystemClock(),
|
|
178
|
+
scheduler=ports.scheduler or ThreadScheduler(),
|
|
179
|
+
random=ports.random or SecureRandom(),
|
|
180
|
+
fingerprint=ports.fingerprint or NoFingerprint(),
|
|
181
|
+
logger=ports.logger or SilentLog(),
|
|
182
|
+
)
|
bydev/py.typed
ADDED
|
File without changes
|
bydev/server.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""명세 12절 — 판매자 서버 도우미(웹훅 서명 · 토큰 검증). 앱 쪽 클라이언트와 상태를 나누지 않는다."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import binascii
|
|
7
|
+
import hashlib
|
|
8
|
+
import hmac
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
|
|
12
|
+
from ._api import Api
|
|
13
|
+
from ._generated import Codes, Rules
|
|
14
|
+
from ._verifier import Verifier
|
|
15
|
+
from .client import USER_AGENT
|
|
16
|
+
from .defaults import SystemClock
|
|
17
|
+
from .errors import BydevError
|
|
18
|
+
from .models import AccessClaims, LicenseClaims
|
|
19
|
+
from .ports import Ports, WallClock, resolve
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class WebhookVerification:
|
|
24
|
+
"""검증된 웹훅의 id와 시각이다. 중복 수신은 id로 거른다."""
|
|
25
|
+
|
|
26
|
+
id: str
|
|
27
|
+
timestamp: int
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def verify_webhook(
|
|
31
|
+
secrets: Sequence[str],
|
|
32
|
+
headers: Mapping[str, str],
|
|
33
|
+
raw_body: bytes | str,
|
|
34
|
+
clock: WallClock | None = None,
|
|
35
|
+
) -> WebhookVerification:
|
|
36
|
+
"""서명을 검증한다(안내서 11장 · Standard Webhooks v1).
|
|
37
|
+
|
|
38
|
+
`raw_body`는 받은 그대로의 본문이다 — 파싱했다가 다시 만든 바이트는 서명이 맞지 않는다. 시크릿을 교체하는 중이면 둘 다 넘긴다. 헤더 이름의
|
|
39
|
+
대소문자는 가리지 않는다.
|
|
40
|
+
"""
|
|
41
|
+
lowered = {k.lower(): v for k, v in headers.items()}
|
|
42
|
+
wid, timestamp, signatures = (
|
|
43
|
+
lowered.get(k) for k in ("webhook-id", "webhook-timestamp", "webhook-signature")
|
|
44
|
+
)
|
|
45
|
+
if not wid or not timestamp or not signatures:
|
|
46
|
+
raise BydevError(
|
|
47
|
+
Codes.WEBHOOK_INVALID, "웹훅 헤더(webhook-id · webhook-timestamp · webhook-signature)가 없다"
|
|
48
|
+
)
|
|
49
|
+
now_sec = (clock or SystemClock()).now_ms() / 1000
|
|
50
|
+
if not timestamp.isdigit() or abs(now_sec - int(timestamp)) > Rules.WEBHOOK_TOLERANCE_SEC:
|
|
51
|
+
raise BydevError(Codes.WEBHOOK_INVALID, "웹훅 시각이 허용 범위 밖이다 — 재전송 공격일 수 있다")
|
|
52
|
+
candidates = []
|
|
53
|
+
for entry in signatures.split(" "):
|
|
54
|
+
version, _, value = entry.partition(",")
|
|
55
|
+
if version != Rules.WEBHOOK_SIGNATURE_VERSION or not value:
|
|
56
|
+
continue
|
|
57
|
+
try:
|
|
58
|
+
candidates.append(base64.b64decode(value, validate=True))
|
|
59
|
+
except (binascii.Error, ValueError):
|
|
60
|
+
continue
|
|
61
|
+
body = raw_body.encode() if isinstance(raw_body, str) else raw_body
|
|
62
|
+
signed = f"{wid}.{timestamp}.".encode() + body
|
|
63
|
+
for secret in secrets:
|
|
64
|
+
if not secret.startswith(Rules.WEBHOOK_SECRET_PREFIX):
|
|
65
|
+
raise BydevError(Codes.CONFIGURATION, f"웹훅 시크릿은 {Rules.WEBHOOK_SECRET_PREFIX}로 시작한다")
|
|
66
|
+
try:
|
|
67
|
+
key = base64.b64decode(secret[len(Rules.WEBHOOK_SECRET_PREFIX) :], validate=True)
|
|
68
|
+
except (binascii.Error, ValueError) as e:
|
|
69
|
+
raise BydevError(Codes.CONFIGURATION, "웹훅 시크릿을 읽지 못했다") from e
|
|
70
|
+
expected = hmac.new(key, signed, hashlib.sha256).digest()
|
|
71
|
+
if any(hmac.compare_digest(c, expected) for c in candidates):
|
|
72
|
+
return WebhookVerification(wid, int(timestamp))
|
|
73
|
+
raise BydevError(Codes.WEBHOOK_INVALID, "웹훅 서명이 맞지 않는다")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class ServerVerifier:
|
|
77
|
+
"""판매자 서버의 토큰 검증이다(안내서 09장) — JWKS를 받아 캐시한다. 인스턴스 하나를 오래 쓴다. `ports`는 전송 · 시계만 쓴다."""
|
|
78
|
+
|
|
79
|
+
def __init__(self, base_url: str, client_id: str, ports: Ports | None = None) -> None:
|
|
80
|
+
self._verifier = Verifier(
|
|
81
|
+
Api(base_url, resolve(ports or Ports()), USER_AGENT), client_id, track_generations=False
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
def verify_access_token(self, token: str) -> AccessClaims:
|
|
85
|
+
"""access_token(at+jwt)을 검증한다."""
|
|
86
|
+
return self._verifier.verify_access(token)
|
|
87
|
+
|
|
88
|
+
def verify_license_token(self, token: str, min_generation: int = 0) -> LicenseClaims:
|
|
89
|
+
"""licenseToken을 검증한다. min_generation — 같은 sub · device_id에서 이미 본 가장 큰 세대번호(0이면 보지 않는다)."""
|
|
90
|
+
return self._verifier.verify_license(token, None, min_generation)
|