diff --git a/app/src/doctor_workstation/core/esign.py b/app/src/doctor_workstation/core/esign.py index 498ed53d9..faa8d9357 100644 --- a/app/src/doctor_workstation/core/esign.py +++ b/app/src/doctor_workstation/core/esign.py @@ -99,6 +99,7 @@ def esign_doctor_status(value: Any) -> dict[str, Any]: quick_authorizing = value.get("quicksign_authorizing", False) quick_remaining = value.get("quicksign_remaining_times", 0) quick_unavailable = value.get("quicksign_unavailable_reason", "") + signer_name_editable = value.get("can_edit_signer_name", False) if ( not isinstance(enabled, bool) or not isinstance(status, str) or status not in _DOCTOR_IDENTITY_STATES @@ -113,6 +114,7 @@ def esign_doctor_status(value: Any) -> dict[str, Any]: or (quick_authorizing and ( not enabled or not quick_enabled or details or status not in {"authenticating", "binding_required"} )) + or not isinstance(signer_name_editable, bool) ): raise ApiProtocolError("医生签署身份状态格式不正确") result = {"enabled": enabled, "status": status, "cert_expires_at": expiry, @@ -122,6 +124,9 @@ def esign_doctor_status(value: Any) -> dict[str, Any]: result["quicksign_remaining_times"] = quick_remaining if quick_unavailable: result["quicksign_unavailable_reason"] = quick_unavailable + if enabled and signer_name_editable and not quick_authorizing: + # 服务端仅对未绑定签署账号的非医生审核人下发,医生账号仍以后台登记姓名认证。 + result["can_edit_signer_name"] = True if enabled and status == "authenticating" and value.get("auth_url"): result["auth_url"] = authentication_url(value["auth_url"]) return result @@ -134,6 +139,18 @@ def esign_doctor_mobile(value: Any) -> str: return mobile +# 与服务端 /^[\p{Han}A-Za-z][\p{Han}A-Za-z·()\-]{1,49}$/u 保持一致。 +_HAN = "\u3007\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\U00020000-\U0003134f" +_SIGNER_NAME = re.compile(f"[{_HAN}A-Za-z][{_HAN}A-Za-z·()\\-]{{1,49}}") + + +def esign_signer_name(value: Any) -> str: + name = value.strip() if isinstance(value, str) else "" + if not _SIGNER_NAME.fullmatch(name): + raise ValueError("证件姓名须为 2 至 50 个字符,以汉字或英文字母开头,可包含间隔号(·)、半角括号和连字符。") + return name + + def esign_sms_code(value: Any) -> str: code = value.strip() if isinstance(value, str) else "" if not re.fullmatch(r"[0-9]{6}", code): diff --git a/app/src/doctor_workstation/services/mock_repository.py b/app/src/doctor_workstation/services/mock_repository.py index 11bd0441a..08678f229 100755 --- a/app/src/doctor_workstation/services/mock_repository.py +++ b/app/src/doctor_workstation/services/mock_repository.py @@ -1335,7 +1335,7 @@ class DemoDoctorRepository: def get_esign_doctor_status(self) -> dict[str, Any]: return {"enabled": False, "status": "unbound", "cert_expires_at": 0} - def start_esign_doctor(self, mobile: str) -> dict[str, Any]: + def start_esign_doctor(self, mobile: str, signer_name: str | None = None) -> dict[str, Any]: return self.get_esign_doctor_status() def complete_esign_doctor(self, identity_number: str = "") -> dict[str, Any]: diff --git a/app/src/doctor_workstation/services/repository.py b/app/src/doctor_workstation/services/repository.py index ca70a50c2..619ceb813 100755 --- a/app/src/doctor_workstation/services/repository.py +++ b/app/src/doctor_workstation/services/repository.py @@ -267,7 +267,7 @@ class DoctorRepository(Protocol): def get_esign_doctor_status(self) -> dict[str, Any]: """Read the signed-in doctor's enrollment without a prescription ID.""" - def start_esign_doctor(self, mobile: str) -> dict[str, Any]: + def start_esign_doctor(self, mobile: str, signer_name: str | None = None) -> dict[str, Any]: """Start provider identity authentication for the signed-in doctor.""" def complete_esign_doctor(self, identity_number: str = "") -> dict[str, Any]: @@ -1856,10 +1856,13 @@ class RemoteDoctorRepository: "tcm.prescription/esignDoctorStatus", timeout=30.0, max_retries=0, )) - def start_esign_doctor(self, mobile: str) -> dict[str, Any]: - from ..core.esign import esign_doctor_mobile, esign_doctor_status + def start_esign_doctor(self, mobile: str, signer_name: str | None = None) -> dict[str, Any]: + from ..core.esign import esign_doctor_mobile, esign_doctor_status, esign_signer_name payload = {"mobile": esign_doctor_mobile(mobile)} if mobile else {} + if signer_name is not None: + # 仅未绑定签署账号的审核人可填写证件姓名,服务端会再次校验资格。 + payload["signer_name"] = esign_signer_name(signer_name) return esign_doctor_status(self._post_esign_proof( "esignDoctorStart", payload, "医生人脸认证启动状态待确认", forward_rejection=True, )) diff --git a/app/src/doctor_workstation/ui/dialogs/esign_doctor.py b/app/src/doctor_workstation/ui/dialogs/esign_doctor.py index b39898206..1adce2a43 100644 --- a/app/src/doctor_workstation/ui/dialogs/esign_doctor.py +++ b/app/src/doctor_workstation/ui/dialogs/esign_doctor.py @@ -19,7 +19,12 @@ from PySide6.QtWidgets import ( from shiboken6 import isValid from ...core.errors import ApiBusinessError, AuthenticationExpiredError -from ...core.esign import certificate_identity_number, esign_doctor_mobile, esign_doctor_status +from ...core.esign import ( + certificate_identity_number, + esign_doctor_mobile, + esign_doctor_status, + esign_signer_name, +) from ..design_system import clinical_stylesheet from ..widgets import MessageBanner, run_async from .esign_webview import UNAVAILABLE_MESSAGE, create_identity_view @@ -58,6 +63,7 @@ class EsignDoctorDialog(QDialog): self._closed = False self._generation = 0 self._retry_mobile = False + self._manual_check = False self._deadline: float | None = None self._native_window_id: int | None = None self._native_hide_pending = False @@ -77,6 +83,20 @@ class EsignDoctorDialog(QDialog): self.banner.label.setTextFormat(Qt.TextFormat.PlainText) layout.addWidget(self.banner) + self.signer_form = QWidget(self) + signer_layout = QVBoxLayout(self.signer_form) + signer_layout.setContentsMargins(0, 0, 0, 0) + signer_label = QLabel("证件姓名", self.signer_form) + self.signer_input = QLineEdit(self.signer_form) + self.signer_input.setInputMethodHints(Qt.InputMethodHint.ImhNoPredictiveText) + self.signer_input.setMaxLength(50) + self.signer_input.setPlaceholderText("请输入与本人有效证件一致的姓名") + self.signer_input.setAccessibleName("证件姓名") + signer_label.setBuddy(self.signer_input) + signer_layout.addWidget(signer_label) + signer_layout.addWidget(self.signer_input) + layout.addWidget(self.signer_form) + self.mobile_form = QWidget(self) mobile_layout = QVBoxLayout(self.mobile_form) mobile_layout.setContentsMargins(0, 0, 0, 0) @@ -120,7 +140,7 @@ class EsignDoctorDialog(QDialog): self.bind_button = QPushButton("确认绑定证书", self) self.bind_button.clicked.connect(self._bind) self.refresh_button = QPushButton("检查认证状态", self) - self.refresh_button.clicked.connect(self.refresh) + self.refresh_button.clicked.connect(self._check_status) self._buttons = (self.start_button, self.resume_button, self.bind_button, self.change_mobile_button, self.refresh_button) for button in self._buttons: @@ -152,9 +172,12 @@ class EsignDoctorDialog(QDialog): self.start_button.setText("授权快捷签" if quick_start else "开始人脸认证") self.resume_button.setText("继续快捷签授权" if quick_authorizing else "继续人脸认证") self.bind_button.setText("确认快捷签授权" if quick_authorizing else "确认绑定证书") - inputs = enrollment, binding and self.state.get("identity_details_required") is True - for visible, form, field in zip(inputs, (self.mobile_form, self.identity_form), - (self.mobile_input, self.identity_input), strict=True): + signer_editable = self.state.get("can_edit_signer_name") is True + self.change_mobile_button.setText("修改证件姓名" if signer_editable else "重新输入手机号") + inputs = (enrollment and signer_editable, enrollment, + binding and self.state.get("identity_details_required") is True) + for visible, form, field in zip(inputs, (self.signer_form, self.mobile_form, self.identity_form), + (self.signer_input, self.mobile_input, self.identity_input), strict=True): if not visible: field.setText("") form.setVisible(visible) @@ -180,6 +203,8 @@ class EsignDoctorDialog(QDialog): self.banner.show_message("当前环境未启用医生电子签署身份。", "info") else: message = (_QUICKSIGN_STATUS_TEXT[status] if self.state["quicksign_authorizing"] else _STATUS_TEXT[status]) + if self.state.get("can_edit_signer_name") and status in _NEEDS_MOBILE: + message = "请填写与本人有效证件一致的姓名和本人手机号码,完成人脸认证。" if self.state["quicksign_authorizing"] and status == "authenticating" and not self.state.get("auth_url"): message = "e签宝快捷签授权请求处理中,请稍后检查认证状态。" if status == "ready" and self.state["quicksign_enabled"]: @@ -199,10 +224,15 @@ class EsignDoctorDialog(QDialog): if status == "ready" and expires: date = QDateTime.fromSecsSinceEpoch(expires, _BEIJING_TIME).toString("yyyy-MM-dd HH:mm") message += f" 签署证书有效期至 {date}(北京时间)。" + if self._manual_check and status == "authenticating" and self.state.get("auth_url"): + # e签宝 在认证页查询结果时才拉取刷脸结论,未查询前服务端仍是“认证中”。 + message = ("e签宝 尚未确认刷脸结果。如手机已提示认证成功,请在下方认证页面点击「查询认证结果」," + "确认后这里会自动更新。") self.banner.show_message(message, "success" if status == "ready" else "info") + self._manual_check = False self._sync_actions() - def _request(self, method: str, proof: str | None = None) -> None: + def _request(self, method: str, *proof: str) -> None: if self._busy or self._closed: return self._busy = True @@ -227,6 +257,7 @@ class EsignDoctorDialog(QDialog): def failed(error: Exception) -> None: if not current(): return + self._manual_check = False self._stop_view() if method == "get_esign_doctor_status": self.state = {} @@ -250,9 +281,9 @@ class EsignDoctorDialog(QDialog): def work() -> Any: nonlocal proof try: - return getattr(repository, method)(proof) if proof is not None else getattr(repository, method)() + return getattr(repository, method)(*proof) finally: - proof = None + proof = () run_async(work, on_success=loaded, on_error=failed, on_finished=finished) @@ -263,10 +294,16 @@ class EsignDoctorDialog(QDialog): self.identity_input.setText("") self._request("get_esign_doctor_status") + def _check_status(self) -> None: + if self._busy or self._closed: + return + self._manual_check = True + self.refresh() + def _enter_mobile(self) -> None: self._retry_mobile = True self._sync_actions() - self.mobile_input.setFocus() + (self.signer_input if self.signer_form.isVisible() else self.mobile_input).setFocus() def _start(self) -> None: if not self.start_button.isEnabled() or not self.isVisible(): @@ -274,6 +311,14 @@ class EsignDoctorDialog(QDialog): if self.state.get("status") == "ready": self._request("start_esign_doctor", "") return + signer: tuple[str, ...] = () + if self.signer_form.isVisible(): + try: + signer = (esign_signer_name(self.signer_input.text()),) + except ValueError as error: + self.banner.show_message(str(error), "warning") + self.signer_input.setFocus() + return try: mobile = esign_doctor_mobile(self.mobile_input.text()) except ValueError as error: @@ -281,7 +326,8 @@ class EsignDoctorDialog(QDialog): self.banner.show_message(str(error), "warning") return self.mobile_input.setText("") - self._request("start_esign_doctor", mobile) + # 证件姓名不是凭证,被拒后保留以便修正;手机号仍按原规则提交后即清空。 + self._request("start_esign_doctor", mobile, *signer) def _bind(self) -> None: if not self.bind_button.isEnabled() or not self.isVisible(): @@ -295,7 +341,7 @@ class EsignDoctorDialog(QDialog): self.banner.show_message(str(error), "warning") return self.identity_input.setText("") - self._request("complete_esign_doctor", identity_number or None) + self._request("complete_esign_doctor", *([identity_number] if identity_number else [])) def _open_authentication(self) -> None: if (self._busy or self._closed or not self.isVisible() or self.identity_view is not None @@ -354,6 +400,7 @@ class EsignDoctorDialog(QDialog): def _suspend(self) -> None: self._generation += 1 + self.signer_input.setText("") self.mobile_input.setText("") self.identity_input.setText("") self._stop_view() diff --git a/app/src/doctor_workstation/ui/dialogs/esign_webview.py b/app/src/doctor_workstation/ui/dialogs/esign_webview.py index cd58824be..11c1b2755 100644 --- a/app/src/doctor_workstation/ui/dialogs/esign_webview.py +++ b/app/src/doctor_workstation/ui/dialogs/esign_webview.py @@ -26,6 +26,11 @@ else: UNAVAILABLE_MESSAGE = "当前安装缺少内置核身组件,请联系管理员修复或更新医生工作站后继续签署。" +def _policy_url(url: QUrl) -> str: + # 默认 toString() 会把 %20 解码成空格,导致含编码空格的官方资源或接口被误拦。 + return url.toString(QUrl.ComponentFormattingOption.FullyEncoded) + + if WEBENGINE_AVAILABLE: class IdentityPage(QWebEnginePage): blocked = Signal(str) @@ -38,7 +43,7 @@ if WEBENGINE_AVAILABLE: del navigation_type, is_main_frame if self.shutting_down: return url.toString() == "about:blank" - if authentication_navigation_allowed(url.toString()): + if authentication_navigation_allowed(_policy_url(url)): return True self.blocked.emit("核身页面请求离开系统支持的认证范围,已停止。请联系管理员检查核身方式。") return False @@ -63,7 +68,7 @@ if WEBENGINE_AVAILABLE: # Inline resources are allowed; top-level/iframe navigation still goes # through IdentityPage. Network access stays on official HTTPS hosts. if url.scheme() not in {"data", "blob", "about"}: - info.block(not authentication_navigation_allowed(url.toString())) + info.block(not authentication_navigation_allowed(_policy_url(url))) class EmbeddedIdentityView(QWidget): diff --git a/app/tests/test_esign_webview.py b/app/tests/test_esign_webview.py index 177576f1d..68415a168 100644 --- a/app/tests/test_esign_webview.py +++ b/app/tests/test_esign_webview.py @@ -33,6 +33,13 @@ def test_offsite_and_app_switch_navigation_is_rejected(url: str) -> None: assert not authentication_navigation_allowed(url) +def test_encoded_space_on_official_host_is_not_mistaken_for_control_character() -> None: + url = QUrl("https://asset.esign.cn/img/icon%20_world_.svg?t=1%202") + assert not authentication_navigation_allowed(url.toString()) + assert authentication_navigation_allowed(esign_webview._policy_url(url)) + assert not authentication_navigation_allowed(esign_webview._policy_url(QUrl("https://evil.test/a%20b"))) + + @pytest.mark.skipif(not esign_webview.WEBENGINE_AVAILABLE, reason="QtWebEngine unavailable") def test_page_blocks_popups_frames_custom_schemes_and_uploads() -> None: blocked: list[str] = [] diff --git a/app/tests/test_prescription_esign.py b/app/tests/test_prescription_esign.py index a5dc35cdb..12383e591 100644 --- a/app/tests/test_prescription_esign.py +++ b/app/tests/test_prescription_esign.py @@ -377,6 +377,79 @@ def test_doctor_retry_mobile_failure_does_not_reopen_previous_flow(immediate: No dialog.close() +def test_reviewer_signer_name_is_validated_and_sent_only_when_editable() -> None: + sent: list[dict[str, Any]] = [] + + def post(endpoint: str, payload: dict[str, Any], **_kwargs: Any) -> dict[str, Any]: + sent.append(dict(payload)) + return {"enabled": True, "status": "unbound", "can_edit_signer_name": True} + + repository = RemoteDoctorRepository(SimpleNamespace(get=None, post=post)) + assert repository.start_esign_doctor("13800138000", " 欧阳·娜娜 ")["can_edit_signer_name"] is True + repository.start_esign_doctor("13800138000") + with pytest.raises(ValueError, match="证件姓名"): + repository.start_esign_doctor("13800138000", "admin1") + assert sent == [{"mobile": "13800138000", "signer_name": "欧阳·娜娜"}, {"mobile": "13800138000"}] + doctor = doctor_module.esign_doctor_status({"enabled": True, "status": "unbound"}) + assert "can_edit_signer_name" not in doctor + with pytest.raises(ApiProtocolError): + doctor_module.esign_doctor_status({"enabled": True, "status": "unbound", "can_edit_signer_name": 1}) + + +def test_reviewer_enters_signer_name_before_face_authentication(immediate: None) -> None: + calls: list[tuple[str, ...]] = [] + result: dict[str, Any] = {"enabled": True, "status": "unbound", "can_edit_signer_name": True} + + def start(*proof: str) -> dict[str, Any]: + calls.append(proof) + return {**result, "status": "authenticating", "auth_url": "https://smlt.esign.cn/reviewer"} + + repository = SimpleNamespace(get_esign_doctor_status=lambda: result, start_esign_doctor=start) + dialog = doctor_module.EsignDoctorDialog(repository) + dialog.show() + assert dialog.signer_form.isVisible() and dialog.mobile_form.isVisible() + assert "证件一致的姓名" in dialog.banner.label.text() + dialog.signer_input.setText("张") + dialog.mobile_input.setText("13800138000") + dialog.start_button.click() + assert calls == [] and "证件姓名" in dialog.banner.label.text() + dialog.signer_input.setText("高兴亮") + dialog.start_button.click() + assert calls == [("13800138000", "高兴亮")] + assert dialog.identity_view.urls == ["https://smlt.esign.cn/reviewer"] + assert dialog.signer_form.isHidden() and dialog.signer_input.text() == "" + dialog.close() + + +def test_manual_check_while_provider_pending_explains_next_step(immediate: None) -> None: + result = {"enabled": True, "status": "authenticating", "auth_url": "https://smlt.esign.cn/doctor"} + dialog = doctor_module.EsignDoctorDialog(SimpleNamespace(get_esign_doctor_status=lambda: result)) + dialog.show() + view = dialog.identity_view + assert "查询认证结果" not in dialog.banner.label.text() + dialog.poll_timer.timeout.emit() + assert "查询认证结果" not in dialog.banner.label.text() + dialog.refresh_button.click() + assert "查询认证结果" in dialog.banner.label.text() and dialog.identity_view is view + result.update(status="binding_required") + dialog.refresh_button.click() + assert dialog.bind_button.isVisible() and "查询认证结果" not in dialog.banner.label.text() + dialog.close() + + +def test_reviewer_can_restart_authentication_with_another_signer_name(immediate: None) -> None: + result = {"enabled": True, "status": "authenticating", "auth_url": "https://smlt.esign.cn/old", + "can_edit_signer_name": True} + repository = SimpleNamespace(get_esign_doctor_status=lambda: result) + dialog = doctor_module.EsignDoctorDialog(repository) + dialog.show() + assert dialog.signer_form.isHidden() + assert dialog.change_mobile_button.text() == "修改证件姓名" + dialog.change_mobile_button.click() + assert dialog.signer_form.isVisible() and dialog.mobile_form.isVisible() + dialog.close() + + def test_enrolled_doctor_authorizes_quicksign_without_reentering_identity(immediate: None) -> None: calls: list[str] = [] result = {"enabled": True, "status": "ready", "cert_expires_at": 2_000_000_000,