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 <cursoragent@cursor.com>
This commit is contained in:
parent
ac754c700b
commit
3e8458581a
@ -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
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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,
|
||||
|
||||
@ -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"),
|
||||
|
||||
@ -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;
|
||||
}
|
||||
|
||||
@ -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<void>;
|
||||
onCaptured: (payload: SelfieCapturePayload) => void | Promise<void>;
|
||||
}) {
|
||||
const videoRef = useRef<HTMLVideoElement>(null);
|
||||
const streamRef = useRef<MediaStream | null>(null);
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [step, setStep] = useState<Step>("front");
|
||||
const [frontBlob, setFrontBlob] = useState<Blob | null>(null);
|
||||
@ -25,6 +53,7 @@ export default function AvatarSelfieModal({
|
||||
const [countdown, setCountdown] = useState<number | null>(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"}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
@ -227,6 +341,11 @@ export default function AvatarSelfieModal({
|
||||
<div className="social-selfie-guide" aria-hidden>
|
||||
<i className="social-selfie-oval" />
|
||||
</div>
|
||||
{recording ? (
|
||||
<span className="social-selfie-rec" aria-live="polite">
|
||||
REC
|
||||
</span>
|
||||
) : null}
|
||||
{!previewReady && !err ? (
|
||||
<p className="social-selfie-loading">{socialTx("正在打开摄像头…")}</p>
|
||||
) : null}
|
||||
|
||||
@ -19,11 +19,19 @@ import {
|
||||
import { WechatOaModal } from "~/components/social-follow";
|
||||
import SiteShell from "./SiteShell";
|
||||
import JoinPayModal from "./JoinPayModal";
|
||||
import AvatarSelfieModal from "./AvatarSelfieModal";
|
||||
import AvatarSelfieModal, {
|
||||
type SelfieCapturePayload,
|
||||
} from "./AvatarSelfieModal";
|
||||
import { PageIntro } from "./SocialUI";
|
||||
import { useSocialConfig } from "./SocialExperience";
|
||||
import { socialApi } from "@social/lib/api";
|
||||
import { useCaptureCapability } from "@social/lib/useCaptureCapability";
|
||||
import {
|
||||
getLivenessState,
|
||||
isLivenessVerified,
|
||||
markFaceOk,
|
||||
markLivenessVerified,
|
||||
} from "@social/lib/livenessGate";
|
||||
import {
|
||||
JOIN_AVAILABILITY_OPTIONS,
|
||||
JOIN_EDUCATION_OPTIONS,
|
||||
@ -321,31 +329,30 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
const [avatarBusy, setAvatarBusy] = useState(false);
|
||||
const [avatarErr, setAvatarErr] = useState("");
|
||||
const [selfieOpen, setSelfieOpen] = useState(false);
|
||||
const [faceOk, setFaceOk] = useState(false);
|
||||
const [liveOk, setLiveOk] = useState(false);
|
||||
const [err, setErr] = useState("");
|
||||
const lock = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
const s = getLivenessState();
|
||||
setFaceOk(s.faceOk);
|
||||
setLiveOk(s.livenessStatus === "verified");
|
||||
}, []);
|
||||
|
||||
/** Step 1: always prefer album / clear face photo */
|
||||
const openPrimaryCapture = () => {
|
||||
if (capture.mode === "live-modal") {
|
||||
setSelfieOpen(true);
|
||||
return;
|
||||
}
|
||||
if (capture.mode === "native-capture") {
|
||||
captureInputRef.current?.click();
|
||||
return;
|
||||
}
|
||||
avatarInputRef.current?.click();
|
||||
};
|
||||
|
||||
const avatarHint = (() => {
|
||||
if (avatarBusy) return socialTx("检测人脸并上传中…");
|
||||
if (!capture.ready) return socialTx("检测设备中…");
|
||||
if (capture.mode === "live-modal") {
|
||||
return socialTx("电脑已检测到摄像头:建议现场预览自拍(正脸 + 微转头)");
|
||||
if (liveOk) return socialTx("真人核验已通过,头像可用于社区");
|
||||
if (faceOk) {
|
||||
return socialTx("已检测到人脸。请继续现场实拍(全程录像)以开放约会等功能");
|
||||
}
|
||||
if (capture.mode === "native-capture") {
|
||||
return socialTx("手机可调用前置摄像头拍照核验;也可从相册选");
|
||||
}
|
||||
return socialTx("当前无可用摄像头,请从相册上传清晰正脸");
|
||||
return socialTx("请先上传清晰正脸照片(自拍或相册),通过人脸检测后再实拍核验");
|
||||
})();
|
||||
|
||||
useEffect(() => {
|
||||
@ -430,8 +437,14 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
saveJson("roster", { ...roster, avatar: url });
|
||||
return next;
|
||||
});
|
||||
markFaceOk();
|
||||
setFaceOk(true);
|
||||
setAvatarErr("");
|
||||
requestAnimationFrame(() => URL.revokeObjectURL(localUrl));
|
||||
// After face photo OK → nudge live capture (do not auto-open camera)
|
||||
if (!isLivenessVerified() && capture.mode === "live-modal") {
|
||||
setErr("");
|
||||
}
|
||||
} catch (e) {
|
||||
setDraft((current) => ({ ...current, avatar: "" }));
|
||||
URL.revokeObjectURL(localUrl);
|
||||
@ -447,17 +460,21 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
}
|
||||
};
|
||||
|
||||
const onSelfieChallenge = async (front: Blob, turn: Blob) => {
|
||||
const onSelfieChallenge = async (payload: SelfieCapturePayload) => {
|
||||
setAvatarBusy(true);
|
||||
setAvatarErr("");
|
||||
setErr("");
|
||||
const preview = URL.createObjectURL(front);
|
||||
const preview = URL.createObjectURL(payload.front);
|
||||
setDraft((current) => ({ ...current, avatar: preview }));
|
||||
try {
|
||||
const uploaded = await socialApi.uploadAvatarChallenge(front, turn);
|
||||
const uploaded = await socialApi.uploadAvatarChallenge(
|
||||
payload.front,
|
||||
payload.turn,
|
||||
payload.video,
|
||||
payload.videoMime,
|
||||
);
|
||||
const url = (uploaded?.url || "").trim();
|
||||
if (!url) throw new Error(socialTx("头像上传失败"));
|
||||
// Persist immediately so later profile / discovery pages keep the face.
|
||||
setDraft((current) => {
|
||||
const next = { ...current, avatar: url };
|
||||
saveJson("join-profile", next);
|
||||
@ -474,11 +491,13 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
saveJson("roster", { ...roster, avatar: url });
|
||||
return next;
|
||||
});
|
||||
markFaceOk();
|
||||
markLivenessVerified({ videoUrl: uploaded.videoUrl || "" });
|
||||
setFaceOk(true);
|
||||
setLiveOk(true);
|
||||
setAvatarErr("");
|
||||
// Revoke blob only after remote URL is committed (avoids blank <img>)
|
||||
requestAnimationFrame(() => URL.revokeObjectURL(preview));
|
||||
} catch (e) {
|
||||
setDraft((current) => ({ ...current, avatar: "" }));
|
||||
URL.revokeObjectURL(preview);
|
||||
const raw =
|
||||
e instanceof Error ? e.message.slice(0, 160).trim() : "";
|
||||
@ -781,39 +800,57 @@ function JoinProfileForm({ onDone }: { onDone: () => void }) {
|
||||
{avatarErr}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="social-join-avatar-actions">
|
||||
{capture.mode === "live-modal" ? (
|
||||
{faceOk && !liveOk ? (
|
||||
<div className="social-join-liveness-banner" role="status">
|
||||
<p>
|
||||
{socialTx(
|
||||
"人脸已通过。必须完成现场实拍核验(全程录像,供人工审核),否则约会 / 咖啡聊 / 视频厅等功能无法开放。",
|
||||
)}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-action"
|
||||
disabled={avatarBusy || !capture.ready}
|
||||
disabled={avatarBusy || capture.mode !== "live-modal"}
|
||||
onClick={() => setSelfieOpen(true)}
|
||||
>
|
||||
{socialTx("电脑摄像头自拍")}
|
||||
{socialTx("开始实拍核验")}
|
||||
</button>
|
||||
) : null}
|
||||
{capture.mode === "native-capture" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-action"
|
||||
disabled={avatarBusy || !capture.ready}
|
||||
onClick={() => captureInputRef.current?.click()}
|
||||
>
|
||||
{socialTx("打开前置摄像头")}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
{liveOk ? (
|
||||
<p className="social-join-liveness-ok" role="status">
|
||||
{socialTx("真人核验已通过")}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="social-join-avatar-actions">
|
||||
<button
|
||||
type="button"
|
||||
className={`social-join-avatar-action${
|
||||
capture.mode === "album-only" ? "" : " is-ghost"
|
||||
}`}
|
||||
className="social-join-avatar-action"
|
||||
disabled={avatarBusy}
|
||||
onClick={() => avatarInputRef.current?.click()}
|
||||
>
|
||||
{capture.mode === "album-only"
|
||||
? socialTx("从相册上传正脸")
|
||||
: socialTx("从相册选")}
|
||||
{socialTx("上传正脸照片")}
|
||||
</button>
|
||||
{capture.isMobile ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-action is-ghost"
|
||||
disabled={avatarBusy}
|
||||
onClick={() => captureInputRef.current?.click()}
|
||||
>
|
||||
{socialTx("手机拍照上传")}
|
||||
</button>
|
||||
) : null}
|
||||
{faceOk && !liveOk && capture.mode === "live-modal" ? (
|
||||
<button
|
||||
type="button"
|
||||
className="social-join-avatar-action is-ghost"
|
||||
disabled={avatarBusy || !capture.ready}
|
||||
onClick={() => setSelfieOpen(true)}
|
||||
>
|
||||
{socialTx("现场实拍核验")}
|
||||
</button>
|
||||
) : null}
|
||||
{draft.avatar && !draft.avatar.startsWith("blob:") ? (
|
||||
<button
|
||||
type="button"
|
||||
|
||||
51
src/modules/social/components/LivenessGateBanner.tsx
Normal file
51
src/modules/social/components/LivenessGateBanner.tsx
Normal file
@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useSyncExternalStore } from "react";
|
||||
import {
|
||||
getLivenessState,
|
||||
pathNeedsLiveness,
|
||||
} from "@social/lib/livenessGate";
|
||||
import { socialPath } from "@social/lib/socialPath";
|
||||
import { socialTx } from "@social/lib/socialTx";
|
||||
|
||||
const CHANGE = "nomadro-social-storage";
|
||||
|
||||
function subscribe(cb: () => void) {
|
||||
window.addEventListener(CHANGE, cb);
|
||||
window.addEventListener("storage", cb);
|
||||
return () => {
|
||||
window.removeEventListener(CHANGE, cb);
|
||||
window.removeEventListener("storage", cb);
|
||||
};
|
||||
}
|
||||
|
||||
/** Soft lock banner on date / coffee / meetup / map until live selfie passes. */
|
||||
export default function LivenessGateBanner() {
|
||||
const pathname = usePathname();
|
||||
const snap = useSyncExternalStore(
|
||||
subscribe,
|
||||
() => JSON.stringify(getLivenessState()),
|
||||
() => JSON.stringify({ faceOk: false, livenessStatus: "none" }),
|
||||
);
|
||||
const state = JSON.parse(snap) as ReturnType<typeof getLivenessState>;
|
||||
if (!pathNeedsLiveness(pathname)) return null;
|
||||
if (state.livenessStatus === "verified") return null;
|
||||
|
||||
return (
|
||||
<aside className="social-liveness-gate" role="status">
|
||||
<div>
|
||||
<strong>{socialTx("需完成真人实拍核验")}</strong>
|
||||
<p>
|
||||
{state.faceOk
|
||||
? socialTx("你已上传人脸照片。请到加入页完成现场实拍(全程录像),才能使用本页功能。")
|
||||
: socialTx("请先上传含清晰正脸的照片,再完成现场实拍核验,否则约会 / 咖啡聊等功能无法开放。")}
|
||||
</p>
|
||||
</div>
|
||||
<Link className="social-btn coral" href={socialPath("/join?step=profile")}>
|
||||
{socialTx("去核验")}
|
||||
</Link>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@ -18,6 +18,7 @@ import { useSocialI18n } from "@social/lib/useSocialI18n";
|
||||
import { SocialMobileDock } from "./SocialNavigation";
|
||||
import SocialQuickRail from "./SocialQuickRail";
|
||||
import SocialBrandLogo from "./SocialBrandLogo";
|
||||
import LivenessGateBanner from "./LivenessGateBanner";
|
||||
|
||||
export default function SiteShell({
|
||||
children,
|
||||
@ -246,6 +247,7 @@ export default function SiteShell({
|
||||
</a>
|
||||
{nav}
|
||||
<main className="social-main social-main--immersive" id="social-main" data-page={title || t.brand}>
|
||||
<LivenessGateBanner />
|
||||
{children}
|
||||
</main>
|
||||
<SocialMobileDock />
|
||||
@ -283,6 +285,7 @@ export default function SiteShell({
|
||||
<div className="social-workspace-grid">
|
||||
<main className="social-main" id="social-main" data-page={title || t.brand}>
|
||||
<SocialQuickRail />
|
||||
<LivenessGateBanner />
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
|
||||
@ -257,11 +257,15 @@ export const socialApi = {
|
||||
}>(`/roster/discovery${qs ? `?${qs}` : ""}`, { ttlMs: 20_000 });
|
||||
},
|
||||
|
||||
/** Two-frame live selfie challenge → verified front frame stored as avatar. */
|
||||
uploadAvatarChallenge: async (front: Blob, turn: Blob) => {
|
||||
/** Live challenge: front + turn frames + full camera recording for audit. */
|
||||
uploadAvatarChallenge: async (
|
||||
front: Blob,
|
||||
turn: Blob,
|
||||
video?: Blob | null,
|
||||
videoMime = "video/webm",
|
||||
) => {
|
||||
const form = new FormData();
|
||||
// Explicit File+MIME — bare Blob parts often become application/octet-stream
|
||||
// and social_svc upload_bytes rejects non-image content types.
|
||||
const frontFile =
|
||||
front instanceof File && front.type.startsWith("image/")
|
||||
? front
|
||||
@ -272,12 +276,22 @@ export const socialApi = {
|
||||
: new File([turn], "turn.jpg", { type: "image/jpeg" });
|
||||
form.append("front", frontFile);
|
||||
form.append("turn", turnFile);
|
||||
if (video && video.size > 0) {
|
||||
const ext = videoMime.includes("mp4") ? "mp4" : "webm";
|
||||
const vFile =
|
||||
video instanceof File
|
||||
? video
|
||||
: new File([video], `liveness.${ext}`, {
|
||||
type: videoMime || "video/webm",
|
||||
});
|
||||
form.append("video", vFile);
|
||||
}
|
||||
const res = await fetch(`${BASE}/avatar/challenge`, {
|
||||
method: "POST",
|
||||
headers: { "X-Social-Guest-Id": getGuestId() },
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(90000),
|
||||
signal: AbortSignal.timeout(120000),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let msg = "";
|
||||
@ -294,6 +308,10 @@ export const socialApi = {
|
||||
url: string;
|
||||
object_key: string;
|
||||
storage?: string;
|
||||
livenessStatus?: string;
|
||||
faceOk?: boolean;
|
||||
videoUrl?: string;
|
||||
auditId?: string;
|
||||
challenge?: {
|
||||
similarity?: number;
|
||||
yaw_delta?: number;
|
||||
|
||||
82
src/modules/social/lib/livenessGate.ts
Normal file
82
src/modules/social/lib/livenessGate.ts
Normal file
@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { loadJson, saveJson } from "./storage";
|
||||
|
||||
export const LIVENESS_KEY = "social-liveness";
|
||||
export const FACE_OK_KEY = "social-face-ok";
|
||||
|
||||
export type LivenessState = {
|
||||
faceOk: boolean;
|
||||
livenessStatus: "none" | "pending" | "verified" | "rejected";
|
||||
verifiedAt?: string;
|
||||
videoUrl?: string;
|
||||
};
|
||||
|
||||
const EMPTY: LivenessState = {
|
||||
faceOk: false,
|
||||
livenessStatus: "none",
|
||||
};
|
||||
|
||||
export function getLivenessState(): LivenessState {
|
||||
return loadJson<LivenessState>(LIVENESS_KEY, EMPTY);
|
||||
}
|
||||
|
||||
function bump(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.dispatchEvent(new Event("nomadro-social-storage"));
|
||||
}
|
||||
|
||||
export function markFaceOk(): void {
|
||||
const cur = getLivenessState();
|
||||
saveJson(LIVENESS_KEY, {
|
||||
...cur,
|
||||
faceOk: true,
|
||||
livenessStatus:
|
||||
cur.livenessStatus === "verified" ? "verified" : cur.livenessStatus || "none",
|
||||
});
|
||||
try {
|
||||
localStorage.setItem(FACE_OK_KEY, "1");
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
bump();
|
||||
}
|
||||
|
||||
export function markLivenessVerified(opts?: { videoUrl?: string }): void {
|
||||
saveJson(LIVENESS_KEY, {
|
||||
faceOk: true,
|
||||
livenessStatus: "verified",
|
||||
verifiedAt: new Date().toISOString(),
|
||||
videoUrl: opts?.videoUrl || "",
|
||||
});
|
||||
bump();
|
||||
}
|
||||
|
||||
export function isLivenessVerified(): boolean {
|
||||
return getLivenessState().livenessStatus === "verified";
|
||||
}
|
||||
|
||||
export function isFaceOk(): boolean {
|
||||
const s = getLivenessState();
|
||||
if (s.faceOk) return true;
|
||||
try {
|
||||
return localStorage.getItem(FACE_OK_KEY) === "1";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Features locked until live selfie + video audit pass. */
|
||||
export const LIVENESS_GATED_PATHS = [
|
||||
"/social/date",
|
||||
"/social/coffeechat",
|
||||
"/social/meetup",
|
||||
"/social/map",
|
||||
] as const;
|
||||
|
||||
export function pathNeedsLiveness(pathname: string): boolean {
|
||||
const p = pathname.replace(/\/$/, "") || "/";
|
||||
return LIVENESS_GATED_PATHS.some(
|
||||
(g) => p === g || p.startsWith(`${g}/`),
|
||||
);
|
||||
}
|
||||
@ -343,6 +343,27 @@ export const SOCIAL_PHRASES_EN: Record<string, string> = {
|
||||
"Prefer a front-camera selfie — we check face presence & liveness",
|
||||
"建议现场自拍核验:正脸 + 微转头":
|
||||
"Live selfie check: front face + slight head turn",
|
||||
"请先上传清晰正脸照片(自拍或相册),通过人脸检测后再实拍核验":
|
||||
"Upload a clear front-face photo first — then do a live capture",
|
||||
"已检测到人脸。请继续现场实拍(全程录像)以开放约会等功能":
|
||||
"Face found — finish live capture (full recording) to unlock dating & more",
|
||||
"真人核验已通过,头像可用于社区":
|
||||
"Liveness verified — avatar ready for the community",
|
||||
"人脸已通过。必须完成现场实拍核验(全程录像,供人工审核),否则约会 / 咖啡聊 / 视频厅等功能无法开放。":
|
||||
"Face OK. Live capture with full recording is required for dating / coffeechat / rooms — kept for human review.",
|
||||
"开始实拍核验": "Start live verification",
|
||||
"真人核验已通过": "Liveness verified",
|
||||
"上传正脸照片": "Upload front-face photo",
|
||||
"手机拍照上传": "Phone camera upload",
|
||||
"现场实拍核验": "Live selfie verification",
|
||||
"正对镜头,脸放进圈内(全程自动录像供审核)":
|
||||
"Face the camera — full session is recorded for review",
|
||||
"需完成真人实拍核验": "Live selfie verification required",
|
||||
"你已上传人脸照片。请到加入页完成现场实拍(全程录像),才能使用本页功能。":
|
||||
"Face photo saved — finish live capture on the join page to use this feature.",
|
||||
"请先上传含清晰正脸的照片,再完成现场实拍核验,否则约会 / 咖啡聊等功能无法开放。":
|
||||
"Upload a clear face photo, then live-verify — dating / coffeechat stay locked until then.",
|
||||
"去核验": "Verify now",
|
||||
"请填写当前城市,方便同城推荐":
|
||||
"Add your city so we can recommend people nearby",
|
||||
"请至少选一个「想认识 / 想做什么」":
|
||||
|
||||
@ -10,8 +10,12 @@ export type CaptureCapability = {
|
||||
canMedia: boolean;
|
||||
/** at least one videoinput after permission/enumerate */
|
||||
hasCamera: boolean;
|
||||
/** PC + camera → live preview modal; mobile + camera → capture input; else album */
|
||||
mode: "live-modal" | "native-capture" | "album-only";
|
||||
/**
|
||||
* album-first UX:
|
||||
* - live-modal: can run getUserMedia + MediaRecorder for audit video
|
||||
* - album-only: no camera API
|
||||
*/
|
||||
mode: "live-modal" | "album-only";
|
||||
};
|
||||
|
||||
function detectMobile(): boolean {
|
||||
@ -29,9 +33,6 @@ function detectMobile(): boolean {
|
||||
|
||||
/**
|
||||
* Soft probe only — never call getUserMedia here (avoids permission prompt on join page).
|
||||
* - enumerated videoinput → true
|
||||
* - MediaDevices present but list empty/hidden → optimistic true (real open happens on click)
|
||||
* - no MediaDevices → false
|
||||
*/
|
||||
async function probeCamera(): Promise<boolean> {
|
||||
if (typeof navigator === "undefined") return false;
|
||||
@ -44,16 +45,16 @@ async function probeCamera(): Promise<boolean> {
|
||||
if (list.some((d) => d.kind === "videoinput")) return true;
|
||||
}
|
||||
} catch {
|
||||
/* fall through — still optimistic if API exists */
|
||||
/* fall through */
|
||||
}
|
||||
|
||||
// Browsers often hide cams until permission; still offer camera UX.
|
||||
// Optimistic: API exists → offer live modal; real open happens on click
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* PC/手机 + 是否有摄像头 → 头像采集 UX 分流。
|
||||
* 不在 SSR 假设有摄像头;挂载后再探测。
|
||||
* 照片优先走相册;真人核验统一走 live-modal(可录整段视频)。
|
||||
*/
|
||||
export function useCaptureCapability(): CaptureCapability {
|
||||
const [state, setState] = useState<CaptureCapability>({
|
||||
@ -72,10 +73,13 @@ export function useCaptureCapability(): CaptureCapability {
|
||||
void (async () => {
|
||||
const hasCamera = canMedia ? await probeCamera() : false;
|
||||
if (cancelled) return;
|
||||
let mode: CaptureCapability["mode"] = "album-only";
|
||||
if (hasCamera && isMobile) mode = "native-capture";
|
||||
else if (hasCamera && !isMobile) mode = "live-modal";
|
||||
setState({ ready: true, isMobile, canMedia, hasCamera, mode });
|
||||
setState({
|
||||
ready: true,
|
||||
isMobile,
|
||||
canMedia,
|
||||
hasCamera,
|
||||
mode: hasCamera ? "live-modal" : "album-only",
|
||||
});
|
||||
})();
|
||||
|
||||
return () => {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user