diff --git a/docs/ops/15_Google_Cloud_Launch_Readiness.md b/docs/ops/15_Google_Cloud_Launch_Readiness.md index 523ef96fc..eb42d509c 100644 --- a/docs/ops/15_Google_Cloud_Launch_Readiness.md +++ b/docs/ops/15_Google_Cloud_Launch_Readiness.md @@ -258,13 +258,44 @@ Production uses the same simplified shape, but every boundary is isolated from staging: 1. Separate Cloud SQL instance. -2. Separate secrets. -3. Separate Lark routes. -4. Separate Gmail sender. -5. Separate contract addresses. -6. Separate owner and signer wallets. -7. Separate domain. -8. Separate evidence directory. + +## Production Admin Entry Boundary + +Production `admin-front` and `gateway-admin` now use a public Cloud Run entry +surface, but the security boundary remains application-auth-first. + +Required invariants: + +1. `https://admin.synapse-network.ai/login` stays publicly reachable so human + operators can open the login page. +2. `https://admin-api.synapse-network.ai/health` may be publicly reachable for + health checks, but business routes must still require app-layer auth. +3. A bootstrap or seeded admin without `password_hash` must not be able to log + in and must not be able to enter a usable MFA enrollment path. +4. `MFA_ENROLLMENT_REQUIRED` is only valid after password verification succeeds + for an active admin who requires MFA but has no usable active Google + Authenticator factor. +5. `POST /api/admin/v1/auth/mfa/enroll/begin` and + `POST /api/admin/v1/auth/mfa/enroll/verify` must continue to require a valid + short-lived enrollment token minted by the password-verified login branch. +6. No admin session cookie may be issued until MFA enrollment verify succeeds + for first-bind flows. + +Operational interpretation: + +1. Public login page does not mean public admin access. +2. Password remains the first mandatory gate. +3. Google Authenticator TOTP remains the second gate for bound accounts and the + first-bind requirement for unbound `require_mfa=true` accounts. +4. Session cookie, CSRF, RBAC, lockout, audit trail, and high-risk TOTP step-up + remain the main runtime protections after the network edge is made public. +5. Separate secrets. +6. Separate Lark routes. +7. Separate Gmail sender. +8. Separate contract addresses. +9. Separate owner and signer wallets. +10. Separate domain. +11. Separate evidence directory. Production Cloud SQL minimum: diff --git a/docs/ops/20_Production_GCP_Operator_Checklist.md b/docs/ops/20_Production_GCP_Operator_Checklist.md index 78221dfa9..050a8b625 100644 --- a/docs/ops/20_Production_GCP_Operator_Checklist.md +++ b/docs/ops/20_Production_GCP_Operator_Checklist.md @@ -142,9 +142,11 @@ Operators must: 1. keep `admin-front` as the default human operator entrypoint 2. keep `gateway-admin` business routes protected by app-layer auth, CSRF, - TOTP step-up, and RBAC + password-first login, TOTP step-up, and RBAC 3. verify anonymous access reaches the login/API surface instead of Google Frontend `403` +4. ensure bootstrap admins still require a manually initialized password before + any MFA enrollment can begin Required production runtime settings: @@ -160,8 +162,16 @@ Expected public-entry behavior: 1. `https://admin.synapse-network.ai/login` returns `200` 2. `https://admin.synapse-network.ai/` routes to the app login flow instead of Cloud Run `Forbidden` -3. `https://admin-api.synapse-network.ai/health` returns `200` -4. anonymous protected admin API calls return application `401/403` +3. accounts without `password_hash` cannot log in and cannot reach a usable MFA + enrollment path +4. password-verified but unbound admins receive + `428 MFA_ENROLLMENT_REQUIRED` +5. `https://admin-api.synapse-network.ai/health` returns `200` +6. anonymous protected admin API calls return application `401/403` +7. MFA enrollment begin/verify only succeeds when the request carries a valid + login-minted enrollment token +8. first-bind accounts do not receive `synapse_admin_session` until Google + Authenticator enrollment verify succeeds ## 5. Private Cloud SQL Network Checks diff --git a/docs/projects/gateway-admin/Gateway_Admin_Operations_Runbook.md b/docs/projects/gateway-admin/Gateway_Admin_Operations_Runbook.md index 14bcc6751..1ccdce482 100644 --- a/docs/projects/gateway-admin/Gateway_Admin_Operations_Runbook.md +++ b/docs/projects/gateway-admin/Gateway_Admin_Operations_Runbook.md @@ -239,6 +239,16 @@ GATEWAY_INTERNAL_SERVICE_SUBJECTS=service:gateway-admin Docker bootstrap 只创建管理员账号、角色绑定和占位 MFA 记录,不会初始化密码。`admin_users.password_hash` 为 `NULL` 时,登录会返回通用“邮箱或密码不正确”。 +这个安全边界必须明确保持: + +1. 没有密码就不可登录。 +2. 没有密码就不能进入可用的 MFA enrollment 流程。 +3. 只有密码先验证通过,且账号 `require_mfa = true` 但没有可用 active + Google Authenticator 因子时,登录接口才允许返回 + `428 MFA_ENROLLMENT_REQUIRED`。 +4. Google Authenticator enrollment verify 成功前,不会签发 + `synapse_admin_session`。 + ```bash cd /Users/cliff/workspace/agent/Synapse-Network/services/gateway-admin .venv/bin/python scripts/set_bootstrap_password.py \ @@ -260,6 +270,18 @@ cd /Users/cliff/workspace/agent/Synapse-Network/services/gateway-admin 如果登录 MFA 开启,bootstrap 管理员默认没有可用 TOTP secret,需要先完成 MFA enrollment。Manual Setup Key 由 Gateway-admin 在 enrollment begin 时随机生成,Google Authenticator 只负责读取这个标准 TOTP secret,不会返回 secret 给我们。历史库里如果还存在 `__BOOTSTRAP_TOTP_SECRET__`,它只是不可用的 legacy 哨兵值,必须按未绑定 MFA 处理,不能展示给管理员、不能扫码使用。高危审核动作始终应保留 OTP step-up。 +推荐验证步骤: + +1. 先执行上面的 `set_bootstrap_password.py` +2. 打开 `https://admin.synapse-network.ai/login` +3. 使用刚设置的密码发起登录;只有密码正确时,才允许进入 MFA enrollment +4. expected result: `428 MFA_ENROLLMENT_REQUIRED` +5. 进入首绑流程,完成 Google Authenticator 扫码或手工录入 +6. 提交首个 6 位验证码后,正式获得后台 session + +如果第 3 步密码错误,预期结果必须始终是通用 `401 UNAUTHORIZED`,而不是 +`MFA_ENROLLMENT_REQUIRED`。 + ### 2.8 重置未绑定 MFA 的联调测试管理员 ```bash diff --git a/docs/reference/Service_Port_Map.md b/docs/reference/Service_Port_Map.md index b8b20338f..0c2ce3226 100644 --- a/docs/reference/Service_Port_Map.md +++ b/docs/reference/Service_Port_Map.md @@ -43,6 +43,10 @@ Production admin routing note: owns session, CSRF, MFA, and RBAC enforcement. 4. Anonymous requests to protected `gateway-admin` business routes should fail with application `401/403`, not Google Frontend `403`. +5. Public reachability does not bypass the bootstrap hardening path: accounts + without a password hash must still fail login before MFA enrollment can + begin, and first-bind Google Authenticator flows must not mint an admin + session until enrollment verify succeeds. ## Env Defaults diff --git a/docs/reference/agent-lessons/codex-admin-password-first-mfa-enrollment.md b/docs/reference/agent-lessons/codex-admin-password-first-mfa-enrollment.md new file mode 100644 index 000000000..4b3b50a60 --- /dev/null +++ b/docs/reference/agent-lessons/codex-admin-password-first-mfa-enrollment.md @@ -0,0 +1,3 @@ +# Agent Lessons: codex-admin-password-first-mfa-enrollment + +No new lessons. diff --git a/scripts/e2e/prod_public_docs_links_e2e.mjs b/scripts/e2e/prod_public_docs_links_e2e.mjs index 53c377dc3..66a288f2b 100644 --- a/scripts/e2e/prod_public_docs_links_e2e.mjs +++ b/scripts/e2e/prod_public_docs_links_e2e.mjs @@ -330,7 +330,7 @@ await check( "public health endpoint" ); await check("admin_login_page", `${ADMIN_ROOT}/login`, [200], (body) => { - assertContains(body, "System Authorization", "admin login title"); + assertContains(body, "Admin Console Login", "admin login title"); }); await check( "admin_root_entry", diff --git a/scripts/ui/dogfood_admin_front.mjs b/scripts/ui/dogfood_admin_front.mjs index 1759a2ad2..a30808e7b 100644 --- a/scripts/ui/dogfood_admin_front.mjs +++ b/scripts/ui/dogfood_admin_front.mjs @@ -442,7 +442,7 @@ async function closeTopModal(page) { } const authPageMatrix = [ - { route: "/login", name: "login", text: ["System Authorization"] }, + { route: "/login", name: "login", text: ["Admin Console Login"] }, { route: "/login/mfa-enroll", name: "login-mfa-enroll", diff --git a/scripts/ui/dogfood_admin_login_lockout.mjs b/scripts/ui/dogfood_admin_login_lockout.mjs index a06d86d82..9c68474fd 100644 --- a/scripts/ui/dogfood_admin_login_lockout.mjs +++ b/scripts/ui/dogfood_admin_login_lockout.mjs @@ -177,7 +177,7 @@ async function submitLogin(page, password) { item.request().method() === "POST", { timeout: 15000 } ), - page.getByRole("button", { name: /Execute Initialization/i }).click(), + page.getByRole("button", { name: /Continue Secure Sign-In/i }).click(), ]); const body = await response.json().catch(() => ({})); apiResponses.push({ diff --git a/services/admin-front/AGENTS.md b/services/admin-front/AGENTS.md index 2a29c47ed..e2bbdaa7d 100644 --- a/services/admin-front/AGENTS.md +++ b/services/admin-front/AGENTS.md @@ -52,7 +52,7 @@ Recommended prototype lookup order: - `services/admin-front/stitch/overview/`: console shell, dashboard density, card rhythm, signal surfaces, and global Sentinel tone. - `services/admin-front/stitch/admin_login/`: admin sign-in composition, security framing, CTA posture, and auth entry hierarchy. -- `services/admin-front/stitch/mfa_setup_registration/`: MFA enrollment, QR/manual key layout, verification cadence, and secure initialization mood. +- `services/admin-front/stitch/mfa_setup_registration/`: password-gated MFA enrollment, QR/manual key layout, verification cadence, and activation-state copy. - `services/admin-front/stitch/reset_successful/`: success-state composition, post-action confirmation rhythm, and return-entry CTA treatment. - `services/admin-front/stitch/synapse_sentinel/`: shared Sentinel design language and supporting visual rules. diff --git a/services/admin-front/src/app/login/mfa-enroll/page.tsx b/services/admin-front/src/app/login/mfa-enroll/page.tsx index 6c0c585cd..d873f1720 100644 --- a/services/admin-front/src/app/login/mfa-enroll/page.tsx +++ b/services/admin-front/src/app/login/mfa-enroll/page.tsx @@ -1,204 +1,57 @@ "use client"; -import { Box, Button, Flex, Grid, Stack, Text } from "@chakra-ui/react"; -import Image from "next/image"; -import QRCode from "qrcode"; +import { Stack } from "@chakra-ui/react"; import { useRouter } from "next/navigation"; -import { FormEvent, useEffect, useMemo, useRef, useState, useTransition } from "react"; -import { AuthCodeSlots } from "@/components/auth-code-slots"; import { AuthProtocolShell } from "@/components/auth-protocol-shell"; -import { clearPendingMfaEnrollment, readPendingMfaEnrollment } from "@/lib/admin-mfa-enrollment"; import { - beginAdminMfaEnrollment, - isAdminApiError, - verifyAdminMfaEnrollment, - type MfaEnrollBeginResponse, -} from "@/services/admin-api"; - -function formatCountdown(msRemaining: number): string { - const seconds = Math.max(0, Math.floor(msRemaining / 1000)); - const minutes = Math.floor(seconds / 60); - const remainder = String(seconds % 60).padStart(2, "0"); - return `${minutes}:${remainder}`; -} - -function formatEnrollmentLoadError(error: unknown): string { - if (isAdminApiError(error)) { - return error.message; - } - if (error instanceof Error && error.message === "Failed to fetch") { - return "无法连接管理后台认证服务,请确认 admin-front 已通过同源代理或正确的 API 地址访问 gateway-admin。"; - } - if (error instanceof Error && error.message) { - return error.message; - } - return "无法初始化 MFA 绑定"; -} + EnrollmentHero, + EnrollmentVerificationForm, + ManualEntryKeyCard, +} from "@/features/auth/mfa-enrollment-view"; +import { + formatCountdown, + useMfaEnrollmentState, +} from "@/features/auth/mfa-enrollment-state"; export default function MfaEnrollPage() { const router = useRouter(); - const [enrollment, setEnrollment] = useState(() => readPendingMfaEnrollment()); - const [beginState, setBeginState] = useState(null); - const [qrCodeDataUrl, setQrCodeDataUrl] = useState(null); - const [otpCode, setOtpCode] = useState(""); - const [requestError, setRequestError] = useState(null); - const [qrError, setQrError] = useState(null); - const [isPending, startTransition] = useTransition(); - const [now, setNow] = useState(() => Date.now()); - const [copied, setCopied] = useState(false); - const enrollmentRequestTokenRef = useRef(null); - const enrollmentRequestPromiseRef = useRef | null>(null); - - const expiresAt = useMemo(() => { - if (!enrollment) { - return 0; - } - return enrollment.createdAt + enrollment.expiresIn * 1000; - }, [enrollment]); - - useEffect(() => { - const enrollmentToken = enrollment?.enrollmentToken; - if (!enrollmentToken) { - enrollmentRequestTokenRef.current = null; - enrollmentRequestPromiseRef.current = null; - router.replace("/login"); - return; - } - const activeEnrollmentToken = enrollmentToken; - - let active = true; - async function loadEnrollment(): Promise { - try { - setQrCodeDataUrl(null); - if (enrollmentRequestTokenRef.current !== activeEnrollmentToken || enrollmentRequestPromiseRef.current === null) { - enrollmentRequestTokenRef.current = activeEnrollmentToken; - enrollmentRequestPromiseRef.current = beginAdminMfaEnrollment(activeEnrollmentToken); - } - const result = await enrollmentRequestPromiseRef.current; - if (!active) { - return; - } - setBeginState(result); - - try { - const dataUrl = await QRCode.toDataURL(result.otpauthUrl, { - width: 280, - margin: 2, - color: { - dark: "#0f172a", - light: "#ffffff", - }, - }); - if (active) { - setQrCodeDataUrl(dataUrl); - } - } catch (qrCodeError) { - if (active) { - setQrError(qrCodeError instanceof Error ? qrCodeError.message : "二维码渲染失败,请改用手动密钥完成绑定"); - } - } - } catch (beginError) { - if (!active) { - return; - } - enrollmentRequestPromiseRef.current = null; - setBeginState(null); - setRequestError(formatEnrollmentLoadError(beginError)); - } - } - - setRequestError(null); - setQrError(null); - loadEnrollment().catch(() => undefined); - - return () => { - active = false; - }; - }, [enrollment, router]); - - useEffect(() => { - const timer = globalThis.setInterval(() => setNow(Date.now()), 1000); - return () => globalThis.clearInterval(timer); - }, []); - - function handleRestart(): void { - clearPendingMfaEnrollment(); - enrollmentRequestTokenRef.current = null; - enrollmentRequestPromiseRef.current = null; - router.replace("/login"); - } - - async function handleCopyManualKey(): Promise { - if (!beginState?.manualEntryKey || typeof navigator === "undefined" || !navigator.clipboard) { - return; - } - await navigator.clipboard.writeText(beginState.manualEntryKey); - setCopied(true); - globalThis.setTimeout(() => setCopied(false), 1600); - } - - function handleSubmit(event: FormEvent): void { - event.preventDefault(); - if (!enrollment || !beginState) { - return; - } - - setRequestError(null); - startTransition(async () => { - try { - await verifyAdminMfaEnrollment({ - enrollmentToken: enrollment.enrollmentToken, - factorId: beginState.factorId, - otpCode, - }); - clearPendingMfaEnrollment(); - router.replace("/dashboard"); - } catch (submitError) { - if (isAdminApiError(submitError) && Date.now() >= expiresAt) { - clearPendingMfaEnrollment(); - setEnrollment(null); - } - setRequestError(submitError instanceof Error ? submitError.message : "MFA 绑定失败"); - } - }); - } + const { + enrollment, + beginState, + qrCodeDataUrl, + otpCode, + setOtpCode, + requestError, + qrError, + isPending, + msRemaining, + copied, + handleRestart, + handleCopyManualKey, + handleVerify, + } = useMfaEnrollmentState(router); if (!enrollment) { return null; } - const msRemaining = Math.max(0, expiresAt - now); - let qrCodePanel = ( - - Generating secure payload... - - ); - - if (qrError) { - qrCodePanel = ( - - QR render unavailable. Use the manual key below. - - ); - } - - if (qrCodeDataUrl) { - qrCodePanel = Google Authenticator enrollment QR code; - } - return ( 0 ? "Awaiting Verification" : "Challenge Expired" }, + { + label: "Status", + value: + msRemaining > 0 ? "Awaiting Verification" : "Challenge Expired", + }, ]} layout="centered" panelMaxW={{ base: "100%", xl: "960px" }} @@ -206,58 +59,25 @@ export default function MfaEnrollPage() { headerVariant="accent-bar" > - - - {qrCodePanel} - - - - - Scan this visual encryption key with your approved Authenticator application. The Sentinel Protocol requires a synchronized temporal token for workspace access. - - - - Encrypted Connection Established - - - - - - Manual Setup Key - - {beginState?.manualEntryKey ?? "Loading..."} - - - - -
- - - Initial Verification Code - Account: {beginState?.accountName ?? enrollment.maskedEmail} - - - - - - No admin session is issued until this code is verified successfully. Current TTL: {formatCountdown(msRemaining)} - - - {requestError ? {requestError} : null} - {qrError ? {qrError} : null} - - - - - - - -
+ + +
); -} \ No newline at end of file +} diff --git a/services/admin-front/src/app/login/page.tsx b/services/admin-front/src/app/login/page.tsx index 7395a7f87..4036a3aa6 100644 --- a/services/admin-front/src/app/login/page.tsx +++ b/services/admin-front/src/app/login/page.tsx @@ -120,11 +120,11 @@ export default function LoginPage() { return ( - {isPending ? "Executing..." : "Execute Initialization"} + {isPending ? "Authenticating..." : "Continue Secure Sign-In"} { }); it("builds rail description from login totp policy", () => { - expect(buildLoginRailDescription(enabledPolicy)).toBe("输入管理员邮箱、密码和验证码后进入控制台。"); - expect(buildLoginRailDescription(disabledPolicy)).toBe("输入管理员邮箱和密码后进入控制台。"); + expect(buildLoginRailDescription(enabledPolicy)).toBe( + "输入管理员邮箱、密码和 Google Authenticator 验证码后进入控制台。" + ); + expect(buildLoginRailDescription(disabledPolicy)).toBe( + "输入管理员邮箱和密码开始登录;若账号尚未绑定 Google Authenticator,将在密码验证通过后进入首绑流程。" + ); }); it("builds rail facts from login totp policy", () => { @@ -46,11 +50,13 @@ describe("login presenters", () => { it("shows an informational login prompt until a real login error exists", () => { expect(buildLoginFeedback(null, disabledPolicy)).toEqual({ tone: "info", - message: "请输入管理员邮箱和密码后进入控制台。", + message: + "请输入管理员邮箱和密码。只有密码验证通过后,系统才会允许未绑定账号进入 Google Authenticator 首绑流程。", }); expect(buildLoginFeedback(null, enabledPolicy)).toEqual({ tone: "info", - message: "请输入管理员邮箱、密码和 Google Authenticator 验证码后进入控制台。", + message: + "请输入管理员邮箱、密码和 Google Authenticator 验证码后进入控制台。", }); expect(buildLoginFeedback("登录失败", disabledPolicy)).toEqual({ tone: "error", @@ -59,20 +65,40 @@ describe("login presenters", () => { }); it("maps login failures to localized operator-facing messages", () => { - expect(buildLoginErrorMessage(null, "Invalid admin credentials")).toBe("邮箱或密码不正确,请检查后重试。"); - expect(buildLoginErrorMessage("INVALID_GOOGLE_AUTHENTICATOR_CODE", "Invalid Google Authenticator code")).toBe( - "验证码错误或已过期,请使用最新 6 位码重试。", + expect(buildLoginErrorMessage(null, "Invalid admin credentials")).toBe( + "邮箱或密码不正确,请检查后重试。" ); - expect(buildLoginErrorMessage(null, "otpCode is required when login TOTP is enabled")).toBe( - "请输入 Google Authenticator 的 6 位验证码。", + expect( + buildLoginErrorMessage( + "INVALID_GOOGLE_AUTHENTICATOR_CODE", + "Invalid Google Authenticator code" + ) + ).toBe("验证码错误或已过期,请使用最新 6 位码重试。"); + expect( + buildLoginErrorMessage( + null, + "otpCode is required when login TOTP is enabled" + ) + ).toBe("请输入 Google Authenticator 的 6 位验证码。"); + expect( + buildLoginErrorMessage( + "ADMIN_ACCOUNT_LOCKED", + "Admin account is temporarily locked. Try later or contact an owner." + ) + ).toBe("账号因连续登录失败已临时锁定,请 24 小时后重试或联系 Owner。"); + expect(buildLoginErrorMessage(null, "Failed to fetch")).toBe( + "暂时无法连接管理后台,请稍后重试。" ); - expect(buildLoginErrorMessage("ADMIN_ACCOUNT_LOCKED", "Admin account is temporarily locked. Try later or contact an owner.")).toBe( - "账号因连续登录失败已临时锁定,请 24 小时后重试或联系 Owner。", + expect( + buildLoginErrorMessage( + null, + 'Unexpected token "I", "Internal Server Error" is not valid JSON' + ) + ).toBe( + "认证服务返回了非预期响应,请检查 gateway-admin 是否已启动、日志是否有 Internal Server Error,并确认 admin-front 的 API 地址或代理配置正确。" ); - expect(buildLoginErrorMessage(null, "Failed to fetch")).toBe("暂时无法连接管理后台,请稍后重试。"); - expect(buildLoginErrorMessage(null, 'Unexpected token "I", "Internal Server Error" is not valid JSON')).toBe( - "认证服务返回了非预期响应,请检查 gateway-admin 是否已启动、日志是否有 Internal Server Error,并确认 admin-front 的 API 地址或代理配置正确。", + expect(buildLoginErrorMessage("UNKNOWN", "backend internal detail")).toBe( + "登录失败,请检查登录信息后重试。" ); - expect(buildLoginErrorMessage("UNKNOWN", "backend internal detail")).toBe("登录失败,请检查登录信息后重试。"); }); }); diff --git a/services/admin-front/src/features/auth/login-presenters.ts b/services/admin-front/src/features/auth/login-presenters.ts index dd0e3fb94..fce939160 100644 --- a/services/admin-front/src/features/auth/login-presenters.ts +++ b/services/admin-front/src/features/auth/login-presenters.ts @@ -5,40 +5,66 @@ export type LoginFeedback = { message: string; }; -export function isLoginTotpEnabled(security: AdminAuthSecurityPolicy | null): boolean { +export function isLoginTotpEnabled( + security: AdminAuthSecurityPolicy | null +): boolean { return Boolean(security?.loginTotpRequired); } -export function buildLoginRailDescription(security: AdminAuthSecurityPolicy | null): string { +export function buildLoginRailDescription( + security: AdminAuthSecurityPolicy | null +): string { if (isLoginTotpEnabled(security)) { - return "输入管理员邮箱、密码和验证码后进入控制台。"; + return "输入管理员邮箱、密码和 Google Authenticator 验证码后进入控制台。"; } - return "输入管理员邮箱和密码后进入控制台。"; + return "输入管理员邮箱和密码开始登录;若账号尚未绑定 Google Authenticator,将在密码验证通过后进入首绑流程。"; } -export function buildLoginRailFacts(security: AdminAuthSecurityPolicy | null): Array<{ label: string; value: string }> { +export function buildLoginRailFacts( + security: AdminAuthSecurityPolicy | null +): Array<{ label: string; value: string }> { return [ { label: "Primary Session", value: "cookie-session" }, - { label: "Login TOTP", value: isLoginTotpEnabled(security) ? "required" : "disabled" }, + { + label: "Login TOTP", + value: isLoginTotpEnabled(security) ? "required" : "disabled", + }, ]; } -export function buildLoginFeedback(error: string | null, security: AdminAuthSecurityPolicy | null): LoginFeedback { +export function buildLoginFeedback( + error: string | null, + security: AdminAuthSecurityPolicy | null +): LoginFeedback { if (error) { return { tone: "error", message: error }; } if (isLoginTotpEnabled(security)) { - return { tone: "info", message: "请输入管理员邮箱、密码和 Google Authenticator 验证码后进入控制台。" }; + return { + tone: "info", + message: + "请输入管理员邮箱、密码和 Google Authenticator 验证码后进入控制台。", + }; } - return { tone: "info", message: "请输入管理员邮箱和密码后进入控制台。" }; + return { + tone: "info", + message: + "请输入管理员邮箱和密码。只有密码验证通过后,系统才会允许未绑定账号进入 Google Authenticator 首绑流程。", + }; } -export function buildLoginErrorMessage(code: string | null, message: string | null): string { +export function buildLoginErrorMessage( + code: string | null, + message: string | null +): string { const normalizedMessage = (message ?? "").trim().toLowerCase(); - if (code === "INVALID_GOOGLE_AUTHENTICATOR_CODE" || normalizedMessage === "invalid google authenticator code") { + if ( + code === "INVALID_GOOGLE_AUTHENTICATOR_CODE" || + normalizedMessage === "invalid google authenticator code" + ) { return "验证码错误或已过期,请使用最新 6 位码重试。"; } @@ -54,7 +80,10 @@ export function buildLoginErrorMessage(code: string | null, message: string | nu return "账号因连续登录失败已临时锁定,请 24 小时后重试或联系 Owner。"; } - if (normalizedMessage === "failed to fetch" || normalizedMessage.includes("networkerror")) { + if ( + normalizedMessage === "failed to fetch" || + normalizedMessage.includes("networkerror") + ) { return "暂时无法连接管理后台,请稍后重试。"; } diff --git a/services/admin-front/src/features/auth/mfa-enrollment-state.ts b/services/admin-front/src/features/auth/mfa-enrollment-state.ts new file mode 100644 index 000000000..4cd7c4c34 --- /dev/null +++ b/services/admin-front/src/features/auth/mfa-enrollment-state.ts @@ -0,0 +1,366 @@ +"use client"; + +import QRCode from "qrcode"; +import { + useEffect, + useMemo, + useRef, + useState, + useTransition, + type MutableRefObject, +} from "react"; + +import { + clearPendingMfaEnrollment, + readPendingMfaEnrollment, +} from "@/lib/admin-mfa-enrollment"; +import { + beginAdminMfaEnrollment, + isAdminApiError, + verifyAdminMfaEnrollment, + type MfaEnrollBeginResponse, +} from "@/services/admin-api"; + +type ReplaceRouter = { + replace: (href: string) => void; +}; + +type EnrollmentRequestState = { + token: string | null; + promise: Promise | null; +}; + +type PendingEnrollment = ReturnType; + +type EnrollmentBootstrapState = { + enrollment: PendingEnrollment; + setEnrollment: (value: PendingEnrollment) => void; + beginState: MfaEnrollBeginResponse | null; + qrCodeDataUrl: string | null; + requestError: string | null; + setRequestError: (value: string | null) => void; + qrError: string | null; + expiresAt: number; + requestRef: MutableRefObject; +}; + +type QrCodePayload = { + dataUrl: string | null; + error: string | null; +}; + +type VerifyEnrollmentOptions = { + enrollment: NonNullable; + beginState: MfaEnrollBeginResponse; + otpCode: string; + expiresAt: number; + onExpired: () => void; + onSuccess: () => void; + onError: (message: string) => void; +}; + +export type MfaEnrollmentState = { + enrollment: PendingEnrollment; + beginState: MfaEnrollBeginResponse | null; + qrCodeDataUrl: string | null; + otpCode: string; + setOtpCode: (value: string) => void; + requestError: string | null; + qrError: string | null; + isPending: boolean; + msRemaining: number; + copied: boolean; + handleRestart: () => void; + handleCopyManualKey: () => Promise; + handleVerify: () => Promise; +}; + +export function formatCountdown(msRemaining: number): string { + const seconds = Math.max(0, Math.floor(msRemaining / 1000)); + const minutes = Math.floor(seconds / 60); + const remainder = String(seconds % 60).padStart(2, "0"); + return `${minutes}:${remainder}`; +} + +function formatEnrollmentLoadError(error: unknown): string { + if (isAdminApiError(error)) { + return error.message; + } + if (error instanceof Error && error.message === "Failed to fetch") { + return "无法连接管理后台认证服务,请确认 admin-front 已通过同源代理或正确的 API 地址访问 gateway-admin。"; + } + if (error instanceof Error && error.message) { + return error.message; + } + return "无法开始 Google Authenticator 绑定"; +} + +function formatQrCodeError(error: unknown): string { + if (error instanceof Error && error.message) { + return error.message; + } + return "二维码渲染失败,请改用手动密钥完成绑定"; +} + +async function buildQrCodeDataUrl(otpauthUrl: string): Promise { + return QRCode.toDataURL(otpauthUrl, { + width: 280, + margin: 2, + color: { + dark: "#0f172a", + light: "#ffffff", + }, + }); +} + +async function buildQrCodePayload(otpauthUrl: string): Promise { + try { + return { + dataUrl: await buildQrCodeDataUrl(otpauthUrl), + error: null, + }; + } catch (error) { + return { + dataUrl: null, + error: formatQrCodeError(error), + }; + } +} + +function resetEnrollmentRequestState( + requestRef: MutableRefObject +): void { + requestRef.current = { + token: null, + promise: null, + }; +} + +function ensureEnrollmentRequest( + enrollmentToken: string, + requestRef: MutableRefObject +): Promise { + const current = requestRef.current; + if (current.token === enrollmentToken && current.promise) { + return current.promise; + } + const promise = beginAdminMfaEnrollment(enrollmentToken); + requestRef.current = { + token: enrollmentToken, + promise, + }; + return promise; +} + +async function hydrateEnrollmentState(options: { + enrollmentToken: string; + requestRef: MutableRefObject; + isActive: () => boolean; + setBeginState: (value: MfaEnrollBeginResponse | null) => void; + setQrCodeDataUrl: (value: string | null) => void; + setQrError: (value: string | null) => void; + setRequestError: (value: string | null) => void; +}): Promise { + try { + const result = await ensureEnrollmentRequest( + options.enrollmentToken, + options.requestRef + ); + if (!options.isActive()) { + return; + } + options.setBeginState(result); + + const qrCodePayload = await buildQrCodePayload(result.otpauthUrl); + if (!options.isActive()) { + return; + } + options.setQrCodeDataUrl(qrCodePayload.dataUrl); + options.setQrError(qrCodePayload.error); + } catch (error) { + if (!options.isActive()) { + return; + } + options.requestRef.current.promise = null; + options.setBeginState(null); + options.setRequestError(formatEnrollmentLoadError(error)); + } +} + +async function copyToClipboard(value: string): Promise { + if (typeof navigator === "undefined" || !navigator.clipboard) { + return false; + } + await navigator.clipboard.writeText(value); + return true; +} + +async function verifyEnrollmentAndRoute( + options: VerifyEnrollmentOptions +): Promise { + try { + await verifyAdminMfaEnrollment({ + enrollmentToken: options.enrollment.enrollmentToken, + factorId: options.beginState.factorId, + otpCode: options.otpCode, + }); + options.onSuccess(); + } catch (error) { + if (isAdminApiError(error) && Date.now() >= options.expiresAt) { + options.onExpired(); + } + options.onError(error instanceof Error ? error.message : "MFA 绑定失败"); + } +} + +function useEnrollmentBootstrap( + router: ReplaceRouter +): EnrollmentBootstrapState { + const [enrollment, setEnrollment] = useState(() => + readPendingMfaEnrollment() + ); + const [beginState, setBeginState] = useState( + null + ); + const [qrCodeDataUrl, setQrCodeDataUrl] = useState(null); + const [requestError, setRequestError] = useState(null); + const [qrError, setQrError] = useState(null); + const requestRef = useRef({ + token: null, + promise: null, + }); + + const expiresAt = useMemo(() => { + if (!enrollment) { + return 0; + } + return enrollment.createdAt + enrollment.expiresIn * 1000; + }, [enrollment]); + + useEffect(() => { + const enrollmentToken = enrollment?.enrollmentToken; + if (!enrollmentToken) { + resetEnrollmentRequestState(requestRef); + router.replace("/login"); + return; + } + + let active = true; + setRequestError(null); + setQrError(null); + setQrCodeDataUrl(null); + + void hydrateEnrollmentState({ + enrollmentToken, + requestRef, + isActive: () => active, + setBeginState, + setQrCodeDataUrl, + setQrError, + setRequestError, + }); + + return () => { + active = false; + }; + }, [enrollment, router]); + + return { + enrollment, + setEnrollment, + beginState, + qrCodeDataUrl, + requestError, + setRequestError, + qrError, + expiresAt, + requestRef, + }; +} + +export function useMfaEnrollmentState( + router: ReplaceRouter +): MfaEnrollmentState { + const { + enrollment, + setEnrollment, + beginState, + qrCodeDataUrl, + requestError, + setRequestError, + qrError, + expiresAt, + requestRef, + } = useEnrollmentBootstrap(router); + const [otpCode, setOtpCode] = useState(""); + const [now, setNow] = useState(() => Date.now()); + const [copied, setCopied] = useState(false); + const [isPending, startTransition] = useTransition(); + + useEffect(() => { + const timer = globalThis.setInterval(() => setNow(Date.now()), 1000); + return () => globalThis.clearInterval(timer); + }, []); + + const handleRestart = (): void => { + clearPendingMfaEnrollment(); + resetEnrollmentRequestState(requestRef); + router.replace("/login"); + }; + + const handleCopyManualKey = async (): Promise => { + if (!beginState?.manualEntryKey) { + return; + } + const copiedToClipboard = await copyToClipboard(beginState.manualEntryKey); + if (!copiedToClipboard) { + return; + } + setCopied(true); + globalThis.setTimeout(() => setCopied(false), 1600); + }; + + const handleVerify = async (): Promise => { + if (!enrollment || !beginState) { + return; + } + + setRequestError(null); + return new Promise((resolve) => { + startTransition(async () => { + await verifyEnrollmentAndRoute({ + enrollment, + beginState, + otpCode, + expiresAt, + onExpired: () => { + clearPendingMfaEnrollment(); + setEnrollment(null); + }, + onSuccess: () => { + clearPendingMfaEnrollment(); + router.replace("/dashboard"); + }, + onError: setRequestError, + }); + resolve(); + }); + }); + }; + + return { + enrollment, + beginState, + qrCodeDataUrl, + otpCode, + setOtpCode, + requestError, + qrError, + isPending, + msRemaining: Math.max(0, expiresAt - now), + copied, + handleRestart, + handleCopyManualKey, + handleVerify, + }; +} diff --git a/services/admin-front/src/features/auth/mfa-enrollment-view.tsx b/services/admin-front/src/features/auth/mfa-enrollment-view.tsx new file mode 100644 index 000000000..c48ce8f86 --- /dev/null +++ b/services/admin-front/src/features/auth/mfa-enrollment-view.tsx @@ -0,0 +1,310 @@ +"use client"; + +import { Box, Button, Flex, Grid, Stack, Text } from "@chakra-ui/react"; +import Image from "next/image"; +import { FormEvent } from "react"; + +import { AuthCodeSlots } from "@/components/auth-code-slots"; +import { formatCountdown } from "@/features/auth/mfa-enrollment-state"; +import type { MfaEnrollBeginResponse } from "@/services/admin-api"; + +function QrCodePanel({ + qrCodeDataUrl, + qrError, +}: { + qrCodeDataUrl: string | null; + qrError: string | null; +}) { + if (qrCodeDataUrl) { + return ( + Google Authenticator enrollment QR code + ); + } + + if (qrError) { + return ( + + + QR render unavailable. Use the manual key below. + + + ); + } + + return ( + + + Generating Google Authenticator QR... + + + ); +} + +export function EnrollmentHero({ + qrCodeDataUrl, + qrError, +}: { + qrCodeDataUrl: string | null; + qrError: string | null; +}) { + return ( + + + + + + + + Scan this Google Authenticator enrollment key after password + verification. The{" "} + + Sentinel Protocol + {" "} + only activates the admin session after this first 6-digit code is + verified successfully. + + + + + Password Gate Passed + + + + + ); +} + +export function ManualEntryKeyCard({ + beginState, + copied, + onCopy, +}: { + beginState: MfaEnrollBeginResponse | null; + copied: boolean; + onCopy: () => Promise; +}) { + return ( + + + Manual Entry Key + + + + {beginState?.manualEntryKey ?? "Loading..."} + + + + + ); +} + +function EnrollmentAlert({ + message, + tone, +}: { + message: string; + tone: "error" | "warning"; +}) { + const palette = + tone === "error" + ? { + bg: "rgba(127, 29, 29, 0.22)", + border: "1px solid rgba(248, 113, 113, 0.24)", + color: "#fecaca", + } + : { + bg: "rgba(120, 53, 15, 0.2)", + border: "1px solid rgba(251, 191, 36, 0.24)", + color: "#fde68a", + }; + + return ( + + {message} + + ); +} + +export function EnrollmentVerificationForm({ + enrollmentEmail, + beginState, + otpCode, + setOtpCode, + isPending, + msRemaining, + requestError, + qrError, + onSubmit, + onRestart, +}: { + enrollmentEmail: string; + beginState: MfaEnrollBeginResponse | null; + otpCode: string; + setOtpCode: (value: string) => void; + isPending: boolean; + msRemaining: number; + requestError: string | null; + qrError: string | null; + onSubmit: () => Promise; + onRestart: () => void; +}) { + const handleSubmit = (event: FormEvent): void => { + event.preventDefault(); + void onSubmit(); + }; + + return ( +
+ + + + Google Authenticator Code + + + Account: {beginState?.accountName ?? enrollmentEmail} + + + + + + + + Password verification is complete. No admin session is issued until + this Google Authenticator code is verified successfully. Current + TTL: {formatCountdown(msRemaining)} + + + + {requestError ? ( + + ) : null} + {qrError ? : null} + + + + + + + +
+ ); +} diff --git a/services/admin-front/stitch/admin_login/code.html b/services/admin-front/stitch/admin_login/code.html index 22a8b5497..5ca7de964 100644 --- a/services/admin-front/stitch/admin_login/code.html +++ b/services/admin-front/stitch/admin_login/code.html @@ -1,203 +1,367 @@ - - - -Gateway-Admin Control Plane | Synapse Network - - - - + + + - - - - -
-
-
- -
-
-
-
-
-
- -
-
-
-
-hub -
-Synapse Network -Admin_Portal -
-
-
- -
-
- -
- -
-
-
- -
- -

- System Authorization -

-

Gateway Control Plane v4.0.8

-
- -
- -
- -
- -
-
- -
-
- -RECOVER_KEY -
-
- -visibility_off -
-
- -
- -
-
-vibration - -
-
-schedule -
-
-
- -
- -
-
- -
-
-Terminal_Status -Encrypted_Link -
-
-
-
-
-
-
- -
-
-
-
Layer-2 Validation Active
-
-
-
SECURE_SENTINEL_PROTOCOL_v4.2 // AGENT_ID: 88-ALPHA
-
-
-
- - - \ No newline at end of file +
+ +
+ SECURE_SENTINEL_PROTOCOL_v4.2 // AGENT_ID: 88-ALPHA +
+ + + + + + + diff --git a/services/admin-front/stitch/mfa_setup_registration/code.html b/services/admin-front/stitch/mfa_setup_registration/code.html index 543a47581..9971f2b23 100644 --- a/services/admin-front/stitch/mfa_setup_registration/code.html +++ b/services/admin-front/stitch/mfa_setup_registration/code.html @@ -1,14 +1,24 @@ - - - -MFA Initialization | SYNAPSE_NETWORK - - - - - + + + + - - - - -
-
SYNAPSE_NETWORK
- -
-security -sensors -account_circle -
-
- -
- -
- -
- -
-
- -
-

- Secure Sentinel Protocol -

-
- -

MFA Initialization Phase 1.0

-
-
-
- -
-
-MFA QR Code -
-
-

- Scan this visual encryption key with your approved Authenticator application. The Sentinel Protocol requires a synchronized temporal token for workspace access. -

-
-info -ENCRYPTED CONNECTION ESTABLISHED -
-
-
- -
- -
-ABCD 1234 EFGH 5678 - -
-
- -
- -
- - - - - - -
-
- - -
- -
-
-
-
- - - -
- -
-
- © 2024 SYNAPSE_SENTINEL :: NODE_ACTIVE :: 0x4F...32A + + + +
+
+ SYNAPSE_NETWORK +
+ +
+ security + sensors + account_circle +
+
+ +
+ +
+ +
+ +
+
+ +
+

+ Bind Google Authenticator +

+
+ +

+ MFA Enrollment +

+
+
+
+ +
+
+ MFA QR Code +
+
+

+ Scan this visual encryption key with your approved + Authenticator application. The + Sentinel Protocol + requires a synchronized temporal token for workspace access. +

+
+ info + ENCRYPTED CONNECTION ESTABLISHED +
+
+
+ +
+ +
+ ABCD 1234 EFGH 5678 + +
+
+ +
+ +
+ + + + + + +
+
+ + +
+ +
+
- -
- \ No newline at end of file + + + + + + + + + diff --git a/services/gateway-admin/tests/test_app.py b/services/gateway-admin/tests/test_app.py index 721cecfb6..9b361090a 100644 --- a/services/gateway-admin/tests/test_app.py +++ b/services/gateway-admin/tests/test_app.py @@ -970,7 +970,6 @@ def test_admin_auth_login_requires_mfa_enrollment_for_unbound_account() -> None: assert body["data"]["expiresIn"] == 600 assert body["data"]["totpIssuer"] == "Synapse Gateway Admin" - def test_admin_auth_login_requires_mfa_enrollment_for_bootstrap_placeholder_totp() -> None: email = f"bootstrap-placeholder-{uuid4().hex[:8]}@synapse-network.ai" store = _test_store() diff --git a/services/gateway-admin/tests/test_auth_password_gate.py b/services/gateway-admin/tests/test_auth_password_gate.py new file mode 100644 index 000000000..e25118e58 --- /dev/null +++ b/services/gateway-admin/tests/test_auth_password_gate.py @@ -0,0 +1,34 @@ +from uuid import uuid4 + +from src.domain import AdminUser +from src.domain.enums import AdminUserStatus +from test_app import PLACEHOLDER_PASSWORD, _test_store, client + + +def test_admin_auth_login_does_not_start_mfa_enrollment_without_password_hash() -> None: + email = f"missing-password-{uuid4().hex[:8]}@synapse-network.ai" + store = _test_store() + store.identity.create_user( + AdminUser( + admin_id=f"admin_{uuid4().hex[:12]}", + email=email, + display_name="No Password Bootstrap Admin", + status=AdminUserStatus.ACTIVE, + password_hash=None, + require_mfa=True, + ) + ) + client.cookies.clear() + + response = client.post( + "/api/admin/v1/auth/login", + json={ + "email": email, + "password": PLACEHOLDER_PASSWORD, + }, + ) + + assert response.status_code == 401 + body = response.json() + assert body["error"]["code"] == "UNAUTHORIZED" + assert "data" not in body