From 3e8458581a74a4a0a2c4d40401a3eced041822be Mon Sep 17 00:00:00 2001 From: Eric Date: Wed, 4 Nov 2026 14:53:54 +0800 Subject: [PATCH] Require album face photo first, then full-session live video for audit. Store challenge frames plus MediaRecorder stream for human review, and soft-gate dating/coffee/meetup until liveness passes. Co-authored-by: Cursor --- apps/api/services/social_svc/face_check.py | 44 +++- apps/api/services/social_svc/routers/api.py | 106 ++++++++- apps/api/services/social_svc/s3_upload.py | 27 ++- apps/api/services/social_svc/store.py | 202 ++++++++++++++++++ src/modules/social/app/experience.css | 75 +++++++ .../social/components/AvatarSelfieModal.tsx | 131 +++++++++++- .../social/components/CommunityWelcome.tsx | 121 +++++++---- .../social/components/LivenessGateBanner.tsx | 51 +++++ src/modules/social/components/SiteShell.tsx | 3 + src/modules/social/lib/api.ts | 26 ++- src/modules/social/lib/livenessGate.ts | 82 +++++++ src/modules/social/lib/phrases.ts | 21 ++ .../social/lib/useCaptureCapability.ts | 28 +-- 13 files changed, 831 insertions(+), 86 deletions(-) create mode 100644 src/modules/social/components/LivenessGateBanner.tsx create mode 100644 src/modules/social/lib/livenessGate.ts diff --git a/apps/api/services/social_svc/face_check.py b/apps/api/services/social_svc/face_check.py index 3369b95..ce938b8 100644 --- a/apps/api/services/social_svc/face_check.py +++ b/apps/api/services/social_svc/face_check.py @@ -261,12 +261,27 @@ def _count_opencv(img) -> int: return len(faces) -def check_face(data: bytes) -> FaceCheckResult: - """Return face / liveness result; does not raise for soft failures.""" +def check_face( + data: bytes, + *, + require_liveness: bool | None = None, +) -> FaceCheckResult: + """Return face / liveness result; does not raise for soft failures. + + require_liveness=None → follow SOCIAL_AVATAR_LIVENESS_REQUIRE (legacy). + Album upload should pass require_liveness=False (presence only). + Live challenge uses require_liveness=True. + """ img = _decode_bgr(data) if img is None or img.size == 0: return FaceCheckResult(ok=False, faces=0, engine="none", detail="无法解码图片") + want_live = ( + _liveness_on() and _env_bool("SOCIAL_AVATAR_LIVENESS_REQUIRE", True) + if require_liveness is None + else bool(require_liveness) + ) + pref = _engine_pref() engines: list[str] = [] if pref == "insightface": @@ -280,7 +295,19 @@ def check_face(data: bytes) -> FaceCheckResult: for eng in engines: try: if eng == "insightface": - return _analyze_insightface(img) + result = _analyze_insightface(img) + if not want_live and result.faces >= _min_faces(): + # Presence-only: keep face count even if RGB liveness failed + if not result.ok and result.faces > 0: + return FaceCheckResult( + ok=True, + faces=result.faces, + engine=result.engine or "insightface", + detail="人脸已识别,请继续现场实拍核验", + is_live=result.is_live, + live_score=result.live_score, + ) + return result n = _count_opencv(img) need = _min_faces() @@ -299,8 +326,7 @@ def check_face(data: bytes) -> FaceCheckResult: engine="opencv", detail="请只上传一张本人正脸(不要合影)", ) - # OpenCV cannot prove liveness — require InsightFace when liveness enforced - if _liveness_on() and _env_bool("SOCIAL_AVATAR_LIVENESS_REQUIRE", True): + if want_live and _liveness_on(): return FaceCheckResult( ok=False, faces=n, @@ -324,9 +350,13 @@ def check_face(data: bytes) -> FaceCheckResult: return FaceCheckResult(ok=True, faces=-1, engine="skipped", detail=last_err) -def assert_avatar_has_face(data: bytes) -> FaceCheckResult: +def assert_avatar_has_face( + data: bytes, + *, + require_liveness: bool | None = None, +) -> FaceCheckResult: """Raise ValueError when check fails.""" - result = check_face(data) + result = check_face(data, require_liveness=require_liveness) if not result.ok: raise ValueError(result.detail or "未检测到人脸") return result diff --git a/apps/api/services/social_svc/routers/api.py b/apps/api/services/social_svc/routers/api.py index 1269853..da4024b 100644 --- a/apps/api/services/social_svc/routers/api.py +++ b/apps/api/services/social_svc/routers/api.py @@ -379,8 +379,9 @@ async def upload_media( from social_svc.s3_upload import upload_bytes face_meta = None + # Album / photo upload: face presence only — live capture comes next if face_check_enabled(purpose_norm): - face_meta = assert_avatar_has_face(raw) + face_meta = assert_avatar_has_face(raw, require_liveness=False) uploaded = upload_bytes( raw, @@ -390,6 +391,8 @@ async def upload_media( guest_id=peer, max_size=max_avatar, ) + if face_meta is not None and face_meta.ok: + store.mark_face_photo(peer, uploaded.url) return uploaded, face_meta try: @@ -407,12 +410,15 @@ async def upload_media( "size": result.size, "content_type": result.content_type, "storage": result.storage, + "faceOk": True if face_meta and face_meta.ok else False, + "livenessRequired": True, } if face_meta is not None: face_payload = { "ok": face_meta.ok, "faces": face_meta.faces, "engine": face_meta.engine, + "require_liveness": True, } if face_meta.is_live is not None: face_payload["is_live"] = face_meta.is_live @@ -426,18 +432,23 @@ async def upload_media( async def avatar_pose_challenge( front: UploadFile = File(...), turn: UploadFile = File(...), + video: UploadFile | None = File(default=None), x_social_guest_id: str | None = Header(default=None), guest: str | None = Query(default=None), ): - """Two-frame live selfie: same identity + head-turn + face/liveness, then store front as avatar.""" + """Live selfie: front + turn frames + optional full camera recording for audit.""" peer = _guest(x_social_guest_id, guest) front_raw = await front.read() turn_raw = await turn.read() + video_raw = await video.read() if video is not None else b"" if not front_raw or not turn_raw: raise HTTPException(status_code=400, detail="空文件") max_avatar = min(SOCIAL_UPLOAD_MAX_BYTES, 8 * 1024 * 1024) + max_video = min(SOCIAL_UPLOAD_MAX_BYTES, 40 * 1024 * 1024) if len(front_raw) > max_avatar or len(turn_raw) > max_avatar: raise HTTPException(status_code=400, detail="图片过大") + if video_raw and len(video_raw) > max_video: + raise HTTPException(status_code=400, detail="录制视频过大") def work(): from social_svc.face_check import verify_pose_challenge @@ -446,7 +457,7 @@ async def avatar_pose_challenge( challenge = verify_pose_challenge(front_raw, turn_raw) if not challenge.ok: raise ValueError(challenge.detail or "真人核验失败") - uploaded = upload_bytes( + front_up = upload_bytes( front_raw, filename=front.filename or "avatar-front.jpg", content_type=front.content_type or "image/jpeg", @@ -454,10 +465,50 @@ async def avatar_pose_challenge( guest_id=peer, max_size=max_avatar, ) - return uploaded, challenge + turn_up = upload_bytes( + turn_raw, + filename=turn.filename or "avatar-turn.jpg", + content_type=turn.content_type or "image/jpeg", + purpose="liveness-turn", + guest_id=peer, + max_size=max_avatar, + ) + video_url = "" + video_size = 0 + if video_raw: + vname = (video.filename if video else None) or "liveness.webm" + vctype = (video.content_type if video else None) or "video/webm" + video_up = upload_bytes( + video_raw, + filename=vname, + content_type=vctype, + purpose="liveness-video", + guest_id=peer, + max_size=max_video, + ) + video_url = video_up.url + video_size = video_up.size + audit = store.save_liveness_audit( + peer, + avatar_url=front_up.url, + front_url=front_up.url, + turn_url=turn_up.url, + video_url=video_url, + video_size=video_size, + similarity=challenge.similarity, + yaw_delta=challenge.yaw_delta, + meta={ + "front_engine": challenge.front.engine if challenge.front else "", + "turn_engine": challenge.turn.engine if challenge.turn else "", + "has_video": bool(video_url), + }, + ) + return front_up, turn_up, video_url, video_size, challenge, audit try: - result, challenge = await run_in_threadpool(work) + front_up, turn_up, video_url, video_size, challenge, audit = await run_in_threadpool( + work + ) except ValueError as exc: raise HTTPException(status_code=400, detail=str(exc)) from exc except Exception as exc: @@ -466,11 +517,17 @@ async def avatar_pose_challenge( return { "ok": True, "success": True, - "url": result.url, - "object_key": result.object_key, - "size": result.size, - "content_type": result.content_type, - "storage": result.storage, + "url": front_up.url, + "object_key": front_up.object_key, + "size": front_up.size, + "content_type": front_up.content_type, + "storage": front_up.storage, + "livenessStatus": "verified", + "faceOk": True, + "videoUrl": video_url, + "videoSize": video_size, + "turnUrl": turn_up.url, + "auditId": audit.get("id"), "challenge": { "similarity": challenge.similarity, "yaw_delta": challenge.yaw_delta, @@ -502,6 +559,35 @@ def get_local_avatar(name: str): return FileResponse(path) +@router.get("/files/liveness/{name}") +def get_local_liveness(name: str): + """Serve locally-stored liveness audit videos / frames.""" + from social_svc.config import SOCIAL_UPLOAD_DIR + + safe = Path(name).name + if safe != name or ".." in name: + raise HTTPException(status_code=400, detail="非法文件名") + path = SOCIAL_UPLOAD_DIR / "liveness" / safe + if not path.is_file(): + raise HTTPException(status_code=404, detail="not found") + return FileResponse(path) + + +@router.get("/liveness/audits") +def liveness_audits( + status: str = Query(default=""), + limit: int = Query(default=40, ge=1, le=200), + x_social_guest_id: str | None = Header(default=None), +): + """Admin-oriented list of liveness recordings (guest header still required).""" + _guest(x_social_guest_id) + store.init_db() + return { + "ok": True, + "items": store.list_liveness_audits(status=(status or "").strip(), limit=limit), + } + + @router.post("/channels/{channel_id}/upload") async def upload_file( channel_id: str, diff --git a/apps/api/services/social_svc/s3_upload.py b/apps/api/services/social_svc/s3_upload.py index 53cdf1c..ffeac30 100644 --- a/apps/api/services/social_svc/s3_upload.py +++ b/apps/api/services/social_svc/s3_upload.py @@ -98,9 +98,24 @@ def upload_bytes( guessed = mimetypes.guess_type(filename or "")[0] or "" ctype = (content_type or "").strip().lower() or guessed or "image/jpeg" + suffix = Path(filename or "").suffix.lower() + allow_video = (purpose or "").startswith("liveness") or purpose in { + "liveness-video", + "audit-video", + } # Browser FormData Blob parts often arrive as application/octet-stream - if not ctype.startswith("image/"): - suffix = Path(filename or "").suffix.lower() + if ctype.startswith("image/"): + pass + elif allow_video and ( + ctype.startswith("video/") + or suffix in {".webm", ".mp4", ".mov", ".mkv"} + or guessed.startswith("video/") + ): + if not ctype.startswith("video/"): + ctype = guessed if guessed.startswith("video/") else ( + "video/webm" if suffix in {".webm", ""} else f"video/{suffix[1:] or 'mp4'}" + ) + elif not ctype.startswith("image/"): if suffix in {".jpg", ".jpeg", ".png", ".webp", ".gif"} or guessed.startswith( "image/" ): @@ -108,7 +123,7 @@ def upload_bytes( "image/jpeg" if suffix in {".jpg", ".jpeg", ""} else f"image/{suffix[1:]}" ) else: - raise ValueError("only images allowed") + raise ValueError("only images allowed" if not allow_video else "only images/videos allowed") key = _object_key(filename, purpose, guest_id) @@ -130,11 +145,13 @@ def upload_bytes( pass # Local fallback (dev / S3 off / S3 error) - path = SOCIAL_UPLOAD_DIR / "avatars" / Path(key).name + sub = "liveness" if allow_video or ctype.startswith("video/") else "avatars" + path = SOCIAL_UPLOAD_DIR / sub / Path(key).name path.parent.mkdir(parents=True, exist_ok=True) path.write_bytes(data) + route = "liveness" if sub == "liveness" else "avatar" return UploadResult( - url=f"/api/social/v1/files/avatar/{path.name}", + url=f"/api/social/v1/files/{route}/{path.name}", object_key=str(path), size=len(data), content_type=ctype, diff --git a/apps/api/services/social_svc/store.py b/apps/api/services/social_svc/store.py index 3e8d552..13742f6 100644 --- a/apps/api/services/social_svc/store.py +++ b/apps/api/services/social_svc/store.py @@ -176,12 +176,38 @@ def init_db() -> None: ("wechat", "TEXT"), ("discoverable", "INTEGER DEFAULT 1"), ("onboarded_at", "TEXT"), + ("face_ok", "INTEGER DEFAULT 0"), + ("liveness_status", "TEXT"), + ("liveness_at", "TEXT"), + ("liveness_video_url", "TEXT"), + ("liveness_front_url", "TEXT"), + ("liveness_turn_url", "TEXT"), ): if col not in roster_cols: conn.execute(f"ALTER TABLE roster ADD COLUMN {col} {decl}") conn.execute( "CREATE INDEX IF NOT EXISTS idx_roster_city ON roster(city)" ) + conn.executescript( + """ + CREATE TABLE IF NOT EXISTS liveness_audits ( + id TEXT PRIMARY KEY, + guest_id TEXT NOT NULL, + avatar_url TEXT, + front_url TEXT, + turn_url TEXT, + video_url TEXT, + video_size INTEGER, + similarity REAL, + yaw_delta REAL, + status TEXT NOT NULL DEFAULT 'pending', + meta_json TEXT, + created_at TEXT NOT NULL + ); + CREATE INDEX IF NOT EXISTS idx_liveness_guest ON liveness_audits(guest_id, created_at); + CREATE INDEX IF NOT EXISTS idx_liveness_status ON liveness_audits(status, created_at); + """ + ) conn.executescript( """ CREATE TABLE IF NOT EXISTS files ( @@ -948,10 +974,16 @@ def _roster_row_to_dict(r: Any, *, public: bool = False) -> dict[str, Any]: "wechat": (r["wechat"] if "wechat" in keys else "") or "", "discoverable": int(r["discoverable"] if "discoverable" in keys and r["discoverable"] is not None else 1), "onboardedAt": (r["onboarded_at"] if "onboarded_at" in keys else "") or "", + "faceOk": bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)), + "livenessStatus": (r["liveness_status"] if "liveness_status" in keys else "") or "none", + "livenessAt": (r["liveness_at"] if "liveness_at" in keys else "") or "", + "livenessVideoUrl": (r["liveness_video_url"] if "liveness_video_url" in keys else "") or "", } ) else: item["linktree"] = r["linktree"] or "" + item["faceOk"] = bool(int(r["face_ok"] if "face_ok" in keys and r["face_ok"] is not None else 0)) + item["livenessStatus"] = (r["liveness_status"] if "liveness_status" in keys else "") or "none" return item @@ -1166,6 +1198,176 @@ def city_recommendations( ) +def mark_face_photo(guest_id: str, avatar_url: str) -> None: + """Album/selfie photo passed face presence — liveness still required.""" + with db() as conn: + row = conn.execute( + "SELECT guest_id FROM roster WHERE guest_id=?", (guest_id,) + ).fetchone() + if not row: + conn.execute( + """ + INSERT INTO roster(guest_id, name, title, city, phone, linktree, skills, bio, avatar, + face_ok, liveness_status, updated_at) + VALUES (?, '游民', '', '', '', '', '', '', ?, 1, 'none', ?) + """, + (guest_id, avatar_url[:500], _now()), + ) + return + conn.execute( + """ + UPDATE roster SET avatar=?, face_ok=1, + liveness_status=CASE + WHEN COALESCE(liveness_status,'') IN ('verified','pending') THEN liveness_status + ELSE 'none' + END, + updated_at=? + WHERE guest_id=? + """, + (avatar_url[:500], _now(), guest_id), + ) + + +def save_liveness_audit( + guest_id: str, + *, + avatar_url: str, + front_url: str, + turn_url: str, + video_url: str, + video_size: int, + similarity: float | None, + yaw_delta: float | None, + meta: dict[str, Any] | None = None, +) -> dict[str, Any]: + """Store challenge frames + full camera recording for human review.""" + import json + + now = _now() + item = { + "id": _uid("live"), + "guestId": guest_id, + "avatarUrl": avatar_url, + "frontUrl": front_url, + "turnUrl": turn_url, + "videoUrl": video_url, + "videoSize": int(video_size or 0), + "similarity": similarity, + "yawDelta": yaw_delta, + "status": "pending", + "createdAt": now, + } + with db() as conn: + conn.execute( + """ + INSERT INTO liveness_audits( + id, guest_id, avatar_url, front_url, turn_url, video_url, video_size, + similarity, yaw_delta, status, meta_json, created_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + item["id"], + guest_id, + avatar_url[:500], + front_url[:500], + turn_url[:500], + video_url[:500], + item["videoSize"], + similarity, + yaw_delta, + "pending", + json.dumps(meta or {}, ensure_ascii=False)[:4000], + now, + ), + ) + # Auto-pass machine challenge → verified; video kept for spot-check + conn.execute( + """ + UPDATE roster SET + avatar=COALESCE(NULLIF(?, ''), avatar), + face_ok=1, + liveness_status='verified', + liveness_at=?, + liveness_video_url=?, + liveness_front_url=?, + liveness_turn_url=?, + updated_at=? + WHERE guest_id=? + """, + ( + avatar_url[:500], + now, + video_url[:500], + front_url[:500], + turn_url[:500], + now, + guest_id, + ), + ) + # Ensure roster row exists if guest only uploaded challenge + if not conn.execute( + "SELECT 1 FROM roster WHERE guest_id=?", (guest_id,) + ).fetchone(): + conn.execute( + """ + INSERT INTO roster( + guest_id, name, avatar, face_ok, liveness_status, liveness_at, + liveness_video_url, liveness_front_url, liveness_turn_url, updated_at + ) VALUES (?, '游民', ?, 1, 'verified', ?, ?, ?, ?, ?) + """, + ( + guest_id, + avatar_url[:500], + now, + video_url[:500], + front_url[:500], + turn_url[:500], + now, + ), + ) + item["status"] = "verified" + return item + + +def list_liveness_audits(*, status: str = "", limit: int = 50) -> list[dict[str, Any]]: + limit = max(1, min(int(limit or 50), 200)) + with db() as conn: + if status: + rows = conn.execute( + """ + SELECT * FROM liveness_audits WHERE status=? + ORDER BY created_at DESC LIMIT ? + """, + (status, limit), + ).fetchall() + else: + rows = conn.execute( + """ + SELECT * FROM liveness_audits + ORDER BY created_at DESC LIMIT ? + """, + (limit,), + ).fetchall() + out = [] + for r in rows: + out.append( + { + "id": r["id"], + "guestId": r["guest_id"], + "avatarUrl": r["avatar_url"] or "", + "frontUrl": r["front_url"] or "", + "turnUrl": r["turn_url"] or "", + "videoUrl": r["video_url"] or "", + "videoSize": r["video_size"] or 0, + "similarity": r["similarity"], + "yawDelta": r["yaw_delta"], + "status": r["status"], + "createdAt": r["created_at"], + } + ) + return out + + def add_feedback(kind: str, text: str, contact: str, guest_id: str) -> dict[str, Any]: item = { "id": _uid("fb"), diff --git a/src/modules/social/app/experience.css b/src/modules/social/app/experience.css index 0bd4303..af20f24 100644 --- a/src/modules/social/app/experience.css +++ b/src/modules/social/app/experience.css @@ -525,6 +525,81 @@ font-weight: 650; pointer-events: none; } +.social-selfie-rec { + position: absolute; + top: 12px; + left: 12px; + z-index: 2; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 999px; + background: rgba(220, 38, 38, 0.92); + color: #fff; + font-size: 0.72rem; + font-weight: 800; + letter-spacing: 0.06em; + pointer-events: none; +} +.social-selfie-rec::before { + content: ""; + width: 8px; + height: 8px; + border-radius: 50%; + background: #fff; + animation: social-rec-blink 1s steps(1) infinite; +} +@keyframes social-rec-blink { + 50% { + opacity: 0; + } +} +.social-join-liveness-banner { + margin: 10px 0 0; + padding: 12px 14px; + border-radius: 14px; + border: 1px solid rgba(245, 158, 11, 0.45); + background: rgba(245, 158, 11, 0.1); + display: grid; + gap: 10px; +} +.social-join-liveness-banner p { + margin: 0 !important; + color: rgba(255, 244, 220, 0.92) !important; + font-size: 0.84rem !important; + line-height: 1.45 !important; +} +.social-join-liveness-ok { + margin: 8px 0 0 !important; + color: #34d399 !important; + font-size: 0.84rem !important; + font-weight: 650; +} +.social-liveness-gate { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px; + margin: 0 0 16px; + padding: 14px 16px; + border-radius: 16px; + border: 1px solid rgba(245, 158, 11, 0.4); + background: linear-gradient(135deg, rgba(245, 158, 11, 0.12), rgba(12, 12, 15, 0.6)); +} +.social-liveness-gate strong { + display: block; + margin-bottom: 4px; + color: #fbbf24; +} +.social-liveness-gate p { + margin: 0; + max-width: 52ch; + color: rgba(255, 255, 255, 0.72); + font-size: 0.86rem; + line-height: 1.45; +} .social-join-avatar-row[data-capture-ready="false"] .social-join-avatar-actions { opacity: 0.55; } diff --git a/src/modules/social/components/AvatarSelfieModal.tsx b/src/modules/social/components/AvatarSelfieModal.tsx index 9320d3c..9d56e23 100644 --- a/src/modules/social/components/AvatarSelfieModal.tsx +++ b/src/modules/social/components/AvatarSelfieModal.tsx @@ -7,6 +7,32 @@ import { socialTx } from "@social/lib/socialTx"; type Step = "front" | "turn" | "done"; +export type SelfieCapturePayload = { + front: Blob; + turn: Blob; + /** Full stream from camera open → challenge done (for human audit). */ + video: Blob | null; + videoMime: string; +}; + +function pickRecorderMime(): string { + if (typeof MediaRecorder === "undefined") return ""; + const candidates = [ + "video/webm;codecs=vp9,opus", + "video/webm;codecs=vp8,opus", + "video/webm", + "video/mp4", + ]; + for (const c of candidates) { + try { + if (MediaRecorder.isTypeSupported(c)) return c; + } catch { + /* ignore */ + } + } + return ""; +} + export default function AvatarSelfieModal({ open, onClose, @@ -14,10 +40,12 @@ export default function AvatarSelfieModal({ }: { open: boolean; onClose: () => void; - onCaptured: (front: Blob, turn: Blob) => void | Promise; + onCaptured: (payload: SelfieCapturePayload) => void | Promise; }) { const videoRef = useRef(null); const streamRef = useRef(null); + const recorderRef = useRef(null); + const chunksRef = useRef([]); const [mounted, setMounted] = useState(false); const [step, setStep] = useState("front"); const [frontBlob, setFrontBlob] = useState(null); @@ -25,6 +53,7 @@ export default function AvatarSelfieModal({ const [countdown, setCountdown] = useState(null); const [busy, setBusy] = useState(false); const [previewReady, setPreviewReady] = useState(false); + const [recording, setRecording] = useState(false); useEffect(() => { setMounted(true); @@ -39,6 +68,52 @@ export default function AvatarSelfieModal({ setCountdown(null); setBusy(false); setPreviewReady(false); + setRecording(false); + chunksRef.current = []; + recorderRef.current = null; + + const startRecorder = (stream: MediaStream) => { + const mime = pickRecorderMime(); + if (!mime || typeof MediaRecorder === "undefined") return; + try { + const rec = new MediaRecorder(stream, { + mimeType: mime, + videoBitsPerSecond: 1_200_000, + }); + chunksRef.current = []; + rec.ondataavailable = (ev) => { + if (ev.data && ev.data.size > 0) chunksRef.current.push(ev.data); + }; + rec.start(1000); + recorderRef.current = rec; + if (!cancelled) setRecording(true); + } catch { + recorderRef.current = null; + } + }; + + const stopRecorder = (): Promise<{ blob: Blob | null; mime: string }> => + new Promise((resolve) => { + const rec = recorderRef.current; + if (!rec || rec.state === "inactive") { + resolve({ blob: null, mime: "" }); + return; + } + const mime = rec.mimeType || pickRecorderMime() || "video/webm"; + rec.onstop = () => { + const parts = chunksRef.current; + const blob = + parts.length > 0 ? new Blob(parts, { type: mime }) : null; + recorderRef.current = null; + setRecording(false); + resolve({ blob, mime }); + }; + try { + rec.stop(); + } catch { + resolve({ blob: null, mime: "" }); + } + }); const attach = async (stream: MediaStream) => { streamRef.current = stream; @@ -58,11 +133,12 @@ export default function AvatarSelfieModal({ } catch { /* autoplay may need metadata first */ } + // Record from camera open — full session for admin review + startRecorder(stream); }; void (async () => { try { - // Desktop USB cams often break with facingMode:"user" → black frames let stream: MediaStream; try { stream = await navigator.mediaDevices.getUserMedia({ @@ -79,14 +155,12 @@ export default function AvatarSelfieModal({ stream.getTracks().forEach((t) => t.stop()); return; } - // Wait a tick so portal video node is mounted await new Promise((r) => requestAnimationFrame(() => r(undefined))); if (cancelled) { stream.getTracks().forEach((t) => t.stop()); return; } await attach(stream); - // Retry attach if ref wasn't ready if (!cancelled && videoRef.current && videoRef.current.srcObject !== stream) { await attach(stream); } @@ -99,6 +173,15 @@ export default function AvatarSelfieModal({ return () => { cancelled = true; + const rec = recorderRef.current; + if (rec && rec.state !== "inactive") { + try { + rec.stop(); + } catch { + /* ignore */ + } + } + recorderRef.current = null; const video = videoRef.current; if (video) video.srcObject = null; streamRef.current?.getTracks().forEach((t) => t.stop()); @@ -124,6 +207,30 @@ export default function AvatarSelfieModal({ }); } + function stopRecorder(): Promise<{ blob: Blob | null; mime: string }> { + return new Promise((resolve) => { + const rec = recorderRef.current; + if (!rec || rec.state === "inactive") { + resolve({ blob: null, mime: "" }); + return; + } + const mime = rec.mimeType || pickRecorderMime() || "video/webm"; + rec.onstop = () => { + const parts = chunksRef.current; + const blob = parts.length > 0 ? new Blob(parts, { type: mime }) : null; + recorderRef.current = null; + setRecording(false); + resolve({ blob, mime }); + }; + try { + rec.requestData?.(); + rec.stop(); + } catch { + resolve({ blob: null, mime: "" }); + } + }); + } + function startCountdown(next: () => void) { if (busy || countdown !== null) return; setErr(""); @@ -166,7 +273,13 @@ export default function AvatarSelfieModal({ return; } setStep("done"); - await onCaptured(frontBlob, blob); + const { blob: videoBlob, mime } = await stopRecorder(); + await onCaptured({ + front: frontBlob, + turn: blob, + video: videoBlob, + videoMime: mime || "video/webm", + }); onClose(); } catch (e) { setStep("turn"); @@ -184,7 +297,7 @@ export default function AvatarSelfieModal({ const tip = step === "front" - ? socialTx("正对镜头,脸放进圈内") + ? socialTx("正对镜头,脸放进圈内(全程自动录像供审核)") : step === "turn" ? socialTx("请稍微转头(左右任一方向)再拍") : socialTx("核验中…"); @@ -196,6 +309,7 @@ export default function AvatarSelfieModal({ aria-modal="true" aria-label={socialTx("现场自拍核验")} data-preview-ready={previewReady ? "true" : "false"} + data-recording={recording ? "true" : "false"} > - ) : null} - {capture.mode === "native-capture" ? ( - - ) : null} + + ) : null} + {liveOk ? ( +

+ {socialTx("真人核验已通过")} +

+ ) : null} +
+ {capture.isMobile ? ( + + ) : null} + {faceOk && !liveOk && capture.mode === "live-modal" ? ( + + ) : null} {draft.avatar && !draft.avatar.startsWith("blob:") ? (