ys_base 0.2.4__tar.gz → 0.2.6__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 (55) hide show
  1. {ys_base-0.2.4 → ys_base-0.2.6}/PKG-INFO +8 -1
  2. {ys_base-0.2.4 → ys_base-0.2.6}/README.md +7 -0
  3. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_app_server.py +81 -0
  4. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_iso_reference.py +20 -0
  5. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/__init__.py +1 -1
  6. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/master.py +34 -8
  7. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/app_server.py +13 -2
  8. {ys_base-0.2.4 → ys_base-0.2.6}/.gitignore +0 -0
  9. {ys_base-0.2.4 → ys_base-0.2.6}/.python-version +0 -0
  10. {ys_base-0.2.4 → ys_base-0.2.6}/pyproject.toml +0 -0
  11. {ys_base-0.2.4 → ys_base-0.2.6}/tests/memory_store.py +0 -0
  12. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_api_token.py +0 -0
  13. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_cache.py +0 -0
  14. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_contracts.py +0 -0
  15. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_crypto.py +0 -0
  16. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_files.py +0 -0
  17. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_files_migrate.py +0 -0
  18. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_http_errors.py +0 -0
  19. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_logging.py +0 -0
  20. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_mongo_store.py +0 -0
  21. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_rpc_client.py +0 -0
  22. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_runtime_info.py +0 -0
  23. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_search.py +0 -0
  24. {ys_base-0.2.4 → ys_base-0.2.6}/tests/test_store_delta.py +0 -0
  25. {ys_base-0.2.4 → ys_base-0.2.6}/uv.lock +0 -0
  26. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/_pinyin_data.py +0 -0
  27. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/auth/__init__.py +0 -0
  28. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/auth/api_token.py +0 -0
  29. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/auth/client.py +0 -0
  30. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/auth/delta.py +0 -0
  31. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/cache.py +0 -0
  32. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/__init__.py +0 -0
  33. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/authorization.py +0 -0
  34. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/base.py +0 -0
  35. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/enums.py +0 -0
  36. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/iso_reference.py +0 -0
  37. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/platform.py +0 -0
  38. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/contracts/relations.py +0 -0
  39. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/crypto.py +0 -0
  40. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/files.py +0 -0
  41. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/files_migrate.py +0 -0
  42. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/py.typed +0 -0
  43. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/search.py +0 -0
  44. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/__init__.py +0 -0
  45. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/errors.py +0 -0
  46. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/http_errors.py +0 -0
  47. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/jwt_verify.py +0 -0
  48. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/logging.py +0 -0
  49. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/router.py +0 -0
  50. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/server/runtime_info.py +0 -0
  51. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/store/__init__.py +0 -0
  52. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/store/base.py +0 -0
  53. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/store/mongo.py +0 -0
  54. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/ws/__init__.py +0 -0
  55. {ys_base-0.2.4 → ys_base-0.2.6}/ys_base/ws/rpc_client.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: ys_base
3
- Version: 0.2.4
3
+ Version: 0.2.6
4
4
  Summary: YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架
5
5
  Author-email: ys <popsars@gmail.com>
6
6
  License: MIT
@@ -50,6 +50,13 @@ uv run pytest
50
50
  - `AppServer` 注册时向 Auth 上报 `runtime`:Python 版本、自家 Python 包(`ys-base`、装了的 `ys-trade-sdk`)版本、`web/package.json` 里 `@ysgroup/*` 的版本、主机名、进程号、启动时间。只报版本,不报路径、环境变量和配置。镜像里要带上 `web/package.json`(Template 的 `deploy/Dockerfile` 已复制),没有时前端版本为空。Auth 在应用管理「运行状态」里展示。
51
51
  - 浏览器经业务系统登录(`login`)和兑换跳转码(`exchange_sso_code`)时,`AppServer` 把浏览器连接的对端地址写进转给 Auth 的 `client_ip`(覆盖浏览器自己带的值),Auth 只认已注册应用连接上报的这个字段。
52
52
 
53
+ ## 登录后强制改密(0.2.6 起)
54
+
55
+ - 密码不是本人设的(初始密码、管理员重置后未改、没有本人改密记录)时,Auth 对子系统的 `login`、`refresh` 回复里 `user` 带 `must_change_password: true` 和 `password_change_reason`(`initial` / `reset` / `unknown`),签发的 Access Token 带 `pwd_change: true`。Root、非人类账号、一次性密码登录和门户跳转码进入的会话不强制。
56
+ - `AppServer` 在业务系统 `resolve_user` 之后把这两个字段原样放回登录回执(各系统的 `resolve_user` 不用管它们)。
57
+ - 令牌带 `pwd_change` 的会话只能改密码(`change_password` 照常转给 Auth)、退出和保存明暗偏好,其余业务事件一律回 403「为了账号安全,请先修改密码后再继续使用」。常量 `PASSWORD_CHANGE_ALLOWED_EVENTS`、`PASSWORD_CHANGE_REQUIRED_MESSAGE` 在 `ys_base.server.app_server`。
58
+ - 前端用 `@ysgroup/ui` 的 `YsForcedPasswordChange` 整屏拦截(0.1.50 起),写法见 Template `App.vue`。
59
+
53
60
  ## 列表搜索(0.1.98 起)
54
61
 
55
62
  服务端过滤的列表用 `ys_base.search`,规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
@@ -31,6 +31,13 @@ uv run pytest
31
31
  - `AppServer` 注册时向 Auth 上报 `runtime`:Python 版本、自家 Python 包(`ys-base`、装了的 `ys-trade-sdk`)版本、`web/package.json` 里 `@ysgroup/*` 的版本、主机名、进程号、启动时间。只报版本,不报路径、环境变量和配置。镜像里要带上 `web/package.json`(Template 的 `deploy/Dockerfile` 已复制),没有时前端版本为空。Auth 在应用管理「运行状态」里展示。
32
32
  - 浏览器经业务系统登录(`login`)和兑换跳转码(`exchange_sso_code`)时,`AppServer` 把浏览器连接的对端地址写进转给 Auth 的 `client_ip`(覆盖浏览器自己带的值),Auth 只认已注册应用连接上报的这个字段。
33
33
 
34
+ ## 登录后强制改密(0.2.6 起)
35
+
36
+ - 密码不是本人设的(初始密码、管理员重置后未改、没有本人改密记录)时,Auth 对子系统的 `login`、`refresh` 回复里 `user` 带 `must_change_password: true` 和 `password_change_reason`(`initial` / `reset` / `unknown`),签发的 Access Token 带 `pwd_change: true`。Root、非人类账号、一次性密码登录和门户跳转码进入的会话不强制。
37
+ - `AppServer` 在业务系统 `resolve_user` 之后把这两个字段原样放回登录回执(各系统的 `resolve_user` 不用管它们)。
38
+ - 令牌带 `pwd_change` 的会话只能改密码(`change_password` 照常转给 Auth)、退出和保存明暗偏好,其余业务事件一律回 403「为了账号安全,请先修改密码后再继续使用」。常量 `PASSWORD_CHANGE_ALLOWED_EVENTS`、`PASSWORD_CHANGE_REQUIRED_MESSAGE` 在 `ys_base.server.app_server`。
39
+ - 前端用 `@ysgroup/ui` 的 `YsForcedPasswordChange` 整屏拦截(0.1.50 起),写法见 Template `App.vue`。
40
+
34
41
  ## 列表搜索(0.1.98 起)
35
42
 
36
43
  服务端过滤的列表用 `ys_base.search`,规则与前端 `@ysgroup/core` 的 `ysSearchText` / `ysMatch` 完全相同
@@ -1216,3 +1216,84 @@ async def test_start_keeps_synced_user_app_mirror(monkeypatch):
1216
1216
  await server.start()
1217
1217
  assert await store.get("_auth_user_app", "ua1") is not None
1218
1218
  assert store.cursors["_auth_user_app"] == 7
1219
+
1220
+
1221
+ @pytest.mark.asyncio
1222
+ async def test_login_keeps_auth_password_change_flag_even_if_resolver_drops_it():
1223
+ server = AppServer(_settings(), app_version="0.1.0", store=MemoryStore())
1224
+
1225
+ async def resolve_user(user):
1226
+ # 业务系统只返回自己的字段,不知道强制改密
1227
+ return {"_id": user["_id"], "role": "Viewer"}
1228
+
1229
+ server.resolve_user(resolve_user)
1230
+
1231
+ class FakeAuth(_ReadyAuth):
1232
+ connected = SimpleNamespace(is_set=lambda: True)
1233
+
1234
+ async def call(self, event, data):
1235
+ user = {"_id": "u1", "must_change_password": True, "password_change_reason": "initial"}
1236
+ return {"user": user, "access_token": "a"}
1237
+
1238
+ class FakeWs:
1239
+ async def send_text(self, payload):
1240
+ self.payload = payload
1241
+
1242
+ server.auth = FakeAuth()
1243
+ server.jwt = SimpleNamespace(trust_auth_response=lambda token: None)
1244
+ ws = FakeWs()
1245
+ await server._handle_front_msg(ws, {"id": "1", "event": "login", "data": {}})
1246
+
1247
+ user = json.loads(ws.payload)["data"]["user"]
1248
+ assert user["role"] == "Viewer"
1249
+ assert user["must_change_password"] is True
1250
+ assert user["password_change_reason"] == "initial"
1251
+
1252
+
1253
+ @pytest.mark.asyncio
1254
+ async def test_session_that_must_change_password_only_saves_preferences():
1255
+ server = AppServer(_settings(), app_version="0.1.0", store=MemoryStore())
1256
+ await server.store.open()
1257
+ called = []
1258
+
1259
+ @server.ws_event("private", readonly=True)
1260
+ async def private(ctx, data):
1261
+ called.append(ctx.user["sub"])
1262
+ return {"ok": True}
1263
+
1264
+ class FakeAuth(_ReadyAuth):
1265
+ connected = SimpleNamespace(is_set=lambda: True)
1266
+ registered = True
1267
+
1268
+ class FakeJwt:
1269
+ def __init__(self, claims):
1270
+ self.claims = claims
1271
+
1272
+ def verify(self, token):
1273
+ return dict(self.claims)
1274
+
1275
+ class FakeWs:
1276
+ async def send_text(self, payload):
1277
+ self.payload = json.loads(payload)
1278
+
1279
+ server.auth = FakeAuth()
1280
+ await server.store.upsert_local("_auth_users", {"_id": "u1"})
1281
+ await server.store.upsert_local("_local_users", {"_id": "u1", "username": "alice"})
1282
+ try:
1283
+ server.jwt = FakeJwt({"sub": "u1", "pwd_change": True})
1284
+ ws = FakeWs()
1285
+ await server._handle_front_msg(ws, {"id": "1", "event": "private", "data": {"access_token": "t"}})
1286
+ assert ws.payload["code"] == 403
1287
+ assert "修改密码" in ws.payload["message"]
1288
+ assert called == []
1289
+ # 明暗偏好照常能存(强制改密窗口也跟随明暗模式)
1290
+ await server._handle_front_msg(
1291
+ ws, {"id": "2", "event": "save_user_preferences", "data": {"access_token": "t", "theme_mode": "dark"}}
1292
+ )
1293
+ assert ws.payload["code"] == 0
1294
+ # 改完密码重新登录,新令牌不带标记就恢复正常
1295
+ server.jwt = FakeJwt({"sub": "u1"})
1296
+ await server._handle_front_msg(ws, {"id": "3", "event": "private", "data": {"access_token": "t"}})
1297
+ assert ws.payload["code"] == 0 and called == ["u1"]
1298
+ finally:
1299
+ await server.store.close()
@@ -11,6 +11,7 @@ from ys_base.contracts import (
11
11
  ENUM_META,
12
12
  ISO_REFERENCE_SOURCE,
13
13
  TABLES,
14
+ Account,
14
15
  ApprovalRole,
15
16
  CountryCode,
16
17
  CurrencyCode,
@@ -81,6 +82,25 @@ def test_owner_region_currencies_and_controllers():
81
82
  )
82
83
 
83
84
 
85
+ def test_account_currencies():
86
+ base = {
87
+ "team_id": "t",
88
+ "owner_id": "o",
89
+ "account": "1",
90
+ "cname": "a",
91
+ "type": "STOCK",
92
+ "broker_id": "b",
93
+ "trade_env": "LIVE",
94
+ }
95
+ account = Account.model_validate({**base, "currency_codes": ["cny", "USD", "CNY"], "base_currency_code": "usd"})
96
+ assert account.currency_codes == ["CNY", "USD"] and account.base_currency_code == "USD"
97
+ assert Account.model_validate(base).currency_codes == [] and Account.model_validate(base).base_currency_code == ""
98
+ with pytest.raises(ValidationError, match="ISO 4217"):
99
+ Account.model_validate({**base, "currency_codes": ["ABC"]})
100
+ with pytest.raises(ValidationError, match="本位币"):
101
+ Account.model_validate({**base, "currency_codes": ["USD"], "base_currency_code": "CNY"})
102
+
103
+
84
104
  def test_owner_approval_contract_and_relations():
85
105
  assert "approval_roles" in TABLES and "owner_approvals" in TABLES
86
106
  assert AUTHORIZATION_TABLE_META["owner_approvals"]["scope_mode"] == "derived"
@@ -1,4 +1,4 @@
1
1
  # -*- coding: utf-8 -*-
2
2
  """YS 统一 SDK:契约模型 / auth 客户端与差量同步 / 应用服务骨架。"""
3
3
 
4
- __version__ = "0.2.4"
4
+ __version__ = "0.2.6"
@@ -55,6 +55,20 @@ class TradingSeatGateway(BaseModel):
55
55
  count: int = Field(title="网关数量", ge=1)
56
56
 
57
57
 
58
+ def _normalize_currency_codes(v: list[str]) -> list[str]:
59
+ codes = list(dict.fromkeys(str(item).strip().upper() for item in v if str(item).strip()))
60
+ unknown = [code for code in codes if code not in CURRENCY_META]
61
+ if unknown:
62
+ raise ValueError(f"币种须为 ISO 4217 三位码: {', '.join(unknown)}")
63
+ return codes
64
+
65
+
66
+ def _check_base_currency(currency_codes: list[str], base_currency_code: str) -> None:
67
+ # 只校验「填了本位币就必须在币种里」;是否必须填写由写入方决定,部分字段投影不会因此失败。
68
+ if base_currency_code and currency_codes and base_currency_code not in currency_codes:
69
+ raise ValueError("本位币必须是已选币种之一")
70
+
71
+
58
72
  class Team(YsModel):
59
73
  name: str = Field(title="名称") # 唯一索引
60
74
  type: TeamType = Field(title="类型")
@@ -139,11 +153,7 @@ class Owner(YsModel):
139
153
  @field_validator("currency_codes")
140
154
  @classmethod
141
155
  def _currencies(cls, v: list[str]) -> list[str]:
142
- codes = list(dict.fromkeys(str(item).strip().upper() for item in v if str(item).strip()))
143
- unknown = [code for code in codes if code not in CURRENCY_META]
144
- if unknown:
145
- raise ValueError(f"币种须为 ISO 4217 三位码: {', '.join(unknown)}")
146
- return codes
156
+ return _normalize_currency_codes(v)
147
157
 
148
158
  @field_validator("base_currency_code")
149
159
  @classmethod
@@ -152,9 +162,7 @@ class Owner(YsModel):
152
162
 
153
163
  @model_validator(mode="after")
154
164
  def _base_in_currencies(self) -> "Owner":
155
- # 只校验「填了本位币就必须在币种里」;是否必须填写由写入方决定,部分字段投影不会因此失败。
156
- if self.base_currency_code and self.currency_codes and self.base_currency_code not in self.currency_codes:
157
- raise ValueError("本位币必须是已选币种之一")
165
+ _check_base_currency(self.currency_codes, self.base_currency_code)
158
166
  return self
159
167
 
160
168
  @field_validator("performance_fee_accrual_dates")
@@ -236,6 +244,24 @@ class Account(YsModel):
236
244
  # --- public ---
237
245
  memo: str = Field(default="", title="备注")
238
246
  primary_color: str = Field(default="#AAAAAA", title="主题色")
247
+ # 账户使用的币种(ISO 4217 三位码,可多选)和本位币(必须是其中之一);空表示未填
248
+ currency_codes: list[str] = Field(default_factory=list, title="币种")
249
+ base_currency_code: str = Field(default="", title="本位币")
250
+
251
+ @field_validator("currency_codes")
252
+ @classmethod
253
+ def _currencies(cls, v: list[str]) -> list[str]:
254
+ return _normalize_currency_codes(v)
255
+
256
+ @field_validator("base_currency_code")
257
+ @classmethod
258
+ def _base_currency(cls, v: str) -> str:
259
+ return str(v or "").strip().upper()
260
+
261
+ @model_validator(mode="after")
262
+ def _base_in_currencies(self) -> "Account":
263
+ _check_base_currency(self.currency_codes, self.base_currency_code)
264
+ return self
239
265
 
240
266
 
241
267
  class ExchangeAccount(YsModel):
@@ -52,6 +52,12 @@ AUTH_FORWARDED_EVENTS = FRONT_AUTH_EVENTS
52
52
  # 不与 Auth 或其他系统共用。本地还没有该用户时(没有本地用户表的系统)转给 Auth,由 Auth 按系统分开保存。
53
53
  PREFERENCES_EVENT = "save_user_preferences"
54
54
  PREFERENCES_CHANGED_EVENT = "user_preferences_changed"
55
+ # 强制改密:密码不是本人设的(初始、重置后、无本人改密记录)时,Auth 签的令牌带 pwd_change,
56
+ # 登录回执的 user 带 must_change_password、password_change_reason。带标记的会话只能改密码(change_password
57
+ # 照常转给 Auth)、退出和存明暗偏好,其余业务事件一律 403,前端绕过强制改密窗口也调不动。
58
+ PASSWORD_CHANGE_FIELDS = ("must_change_password", "password_change_reason")
59
+ PASSWORD_CHANGE_ALLOWED_EVENTS = frozenset({PREFERENCES_EVENT})
60
+ PASSWORD_CHANGE_REQUIRED_MESSAGE = "为了账号安全,请先修改密码后再继续使用"
55
61
  THEME_MODES = frozenset({"light", "dark"})
56
62
  # 同一条浏览器连接同时在处理的请求上限,超出直接回 429,防止一个页面把服务拖住。
57
63
  FRONT_MAX_INFLIGHT = 32
@@ -556,12 +562,14 @@ class AppServer:
556
562
  forwarded = forwarded | {"client_ip": str(getattr(client, "host", "") or "")}
557
563
  result = await self.auth.call(event, forwarded)
558
564
  if event in ("login", "exchange_sso_code", "refresh") and isinstance(result, dict):
559
- login_user = result.get("user", {}) or {}
565
+ auth_user = result.get("user", {}) or {}
560
566
  try:
561
- login_user = await self._resolve_user(login_user)
567
+ login_user = await self._resolve_user(auth_user)
562
568
  except BusinessError:
563
569
  await self._discard_auth_session(result)
564
570
  raise
571
+ # 各系统的 resolve_user 返回自己的用户字段,强制改密标记由底座原样带回浏览器
572
+ login_user = {**login_user, **{k: auth_user[k] for k in PASSWORD_CHANGE_FIELDS if k in auth_user}}
565
573
  result = {**result, "user": login_user}
566
574
  result = await self._with_local_preferences(result, str(login_user.get("_id", "")))
567
575
  ws.ys_user_id = str(login_user.get("_id", ""))
@@ -605,6 +613,9 @@ class AppServer:
605
613
  except Exception:
606
614
  await reply(code=401, message="令牌无效")
607
615
  return
616
+ if user.get("pwd_change") and event not in PASSWORD_CHANGE_ALLOWED_EVENTS:
617
+ await reply(code=403, message=PASSWORD_CHANGE_REQUIRED_MESSAGE)
618
+ return
608
619
  user_id = str(user.get("sub") or user.get("_id") or "")
609
620
  auth_user = await self.store.get("_auth_users", user_id) if user_id else None
610
621
  if auth_user is None:
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes