From 2737043f8602a1a75fc4a030c7783355a30d5487 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 16 Nov 2026 10:10:31 +0000 Subject: [PATCH] =?UTF-8?q?feat(bangumi):=20=E7=BD=91=E9=A1=B5=E6=8E=A7?= =?UTF-8?q?=E5=88=B6=E5=8F=B0=E8=B4=A6=E5=8F=B7=E5=AF=86=E7=A0=81=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E7=A0=81=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 电视遥控器很难对焦邮箱、密码和验证码。网页控制台代电视向 Bangumi 提交登录并换 OAuth token,密码不落盘。电视端 WebView 登录和手动粘贴 token 保持不变。 Co-authored-by: ModerRAS --- docs/agents/pre-pr-checklist.md | 21 + .../settings-web-control-parity-checklist.md | 2 +- .../tv/scraper/core/BangumiOAuthClient.kt | 17 +- .../core/BangumiPasswordLoginClient.kt | 385 ++++++++++++++++++ .../core/BangumiPasswordLoginClientTest.kt | 229 +++++++++++ specs/bangumi-web-login/design.md | 37 ++ specs/bangumi-web-login/requirements.md | 40 ++ specs/bangumi-web-login/tasks.md | 17 + .../tv/webcontrol/BangumiWebConsoleLogin.kt | 182 +++++++++ .../tv/webcontrol/NanoHttpWebControlServer.kt | 13 + .../SharedWebControlEndpointService.kt | 1 + .../webcontrol/WebControlEndpointService.kt | 8 + .../tv/webcontrol/WebControlModels.kt | 17 + .../webcontrol/BangumiWebConsoleLoginTest.kt | 225 ++++++++++ .../webcontrol/WebControlSettingsRouteTest.kt | 39 ++ web-control/frontend/src/App.vue | 184 ++++++++- web-control/frontend/src/styles.css | 47 +++ .../tv/webcontrol/WebControlService.kt | 31 +- 18 files changed, 1489 insertions(+), 6 deletions(-) create mode 100644 scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClient.kt create mode 100644 scraper-core/src/test/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClientTest.kt create mode 100644 specs/bangumi-web-login/design.md create mode 100644 specs/bangumi-web-login/requirements.md create mode 100644 specs/bangumi-web-login/tasks.md create mode 100644 web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLogin.kt create mode 100644 web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLoginTest.kt diff --git a/docs/agents/pre-pr-checklist.md b/docs/agents/pre-pr-checklist.md index 88551d9e..09ddcb76 100644 --- a/docs/agents/pre-pr-checklist.md +++ b/docs/agents/pre-pr-checklist.md @@ -353,3 +353,24 @@ Not device-verified: - 长片(>10 分钟)连续播放下的响度曲线主观听感 —— 手头 fixture 最长 2 分钟;算法分支由单测覆盖,真机只验证链路不断、无崩溃、无可闻爆音 - WebUI 浏览器端点选(无浏览器环境;TV/WebAPI 双向 parity 已覆盖同一 DTO) + +### Bangumi 网页控制台账号登录 + +网页控制台「元数据」可以直接填 Bangumi 邮箱、密码和验证码。电视端 WebView 登录仍保留。密码只出现在发往 Bangumi 的那一次表单里,不写入凭据、不放进接口响应。 + +Own checks: + +- 单测 `BangumiPasswordLoginClientTest`:登录页 formhash、验证码图、验证码错误重试、锁号文案、已授权应用直接 302 回环、连不上 Bangumi 的固定文案。失败文案不包含密码 +- 单测 `BangumiWebConsoleLoginTest`:验证码 challenge、提交后走现有 coordinator 换 token、验证码错误可重试、空字段在出网前拒绝、未配置 client、取消/超过 10 分钟要重新取验证码、退出清 token +- 路由单测:`POST /api/metadata/bangumi-login` 响应体不包含密码 +- 浏览器:元数据页能打开账号表单、验证码图可点刷新、错误验证码留在表单里、成功后收起表单并显示有效期;手动粘贴 token 仍在同一张卡片 + +Cross-checks: + +- 手动粘贴 / 清除 Bangumi token、TMDB token、同步全部进度的接口不变 +- TV 设置里的 WebView 登录仍调用同一个 `BangumiOAuthCoordinator`;网页 `start` 会替换尚未完成的那一次授权 +- 出站代理仍是 `rssProxy*`,网页登录的 OkHttp 在取验证码和提交前套用同一份配置 + +Not device-verified: + +- HK1 上用真实 Bangumi 账号走完验证码并看到收藏同步。本环境没有盒子,也没有发版用的 client id/secret。单测用 MockWebServer 固定了 Bangumi 登录页和授权页的 HTML 结构;线上页面改版后要再对一次真实验证码 diff --git a/docs/agents/settings-web-control-parity-checklist.md b/docs/agents/settings-web-control-parity-checklist.md index 73f71bcc..64fd00f2 100644 --- a/docs/agents/settings-web-control-parity-checklist.md +++ b/docs/agents/settings-web-control-parity-checklist.md @@ -82,7 +82,7 @@ Suggested scope for the subagent: |---|---|---|---|---| | Topping DAC 控制(toppingctl 协议) | ✅ AUDIO_DSP 区内 `ToppingDacControls` | ✅ `/api/topping/{status,volume,preset,flat,gain,power,preamp,usb-permission}` | ✅ 音频 DSP 视图 Topping DAC 卡片 | 音量仅 DX5 II(音量不在 HID 上的型号禁用输入);> −10 dB 需确认;未 confirmed 型号拒写 | | 出站代理(Bangumi API / Archive / RSS / OAuth 登录页) | ✅ 设置 →「出站代理」面板(`settings_proxy_panel_desc` 已含「Bangumi 登录页」,字段 `rssProxy*`);OAuth 对话框运行时把同一配置装到内置 WebView(`BangumiOAuthWebViewProxy`,进程级 override) | ✅ `GET/PUT /api/proxy`(`NetworkProxyDto` ↔ `CloudDriveAutomationConfig.rssProxy*`) | ✅「代理配置」视图的出站代理卡片(说明文案已含「Bangumi 登录页」) | 配置面三端同源;WebView 代理是设备进程级能力,Web 端只读写配置、不参与 apply | -| Bangumi OAuth 直连登录(回环回调 + WebView 代理) | ✅ 元数据区登录按钮 + WebView 对话框(配了出站代理则走应用代理,未配则直连)+ 外部浏览器入口 | ➖ 刻意不同步(回环回调/鉴权全在设备本地;token 管理沿用已有 bangumi-token 端点) | ➖ 同左(手动贴 token 链路不变;代理说明文案已同步「Bangumi 登录页」) | surface-specific:Web 侧无法完成 127.0.0.1 回调,也无法安装 WebView 代理;有效期/状态/代理提示仅 TV 展示 | +| Bangumi 登录 | ✅ 元数据区 WebView / 外部浏览器,回环 `127.0.0.1:13712/callback` | ✅ `POST /api/metadata/bangumi-login/start|captcha|cancel` 与 `POST /api/metadata/bangumi-login`(邮箱、密码、验证码)。手动 token 仍走 `bangumi-token`。密码不入库、不回显 | ✅ 元数据页账号登录:验证码由电视代拉(走出站代理),通过后设备换 token | 网页不把浏览器重定向到 `127.0.0.1`。TV WebView 与网页登录共用 `BangumiOAuthCoordinator`。未配 client id/secret 时网页返回 `not_configured` | ## Fast File Pointers - TV settings UI: `ui-tv/src/main/kotlin/com/miruplay/tv/ui/settings/` diff --git a/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiOAuthClient.kt b/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiOAuthClient.kt index a67fcc53..da44382d 100644 --- a/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiOAuthClient.kt +++ b/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiOAuthClient.kt @@ -10,17 +10,31 @@ import kotlinx.serialization.json.Json import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request +import java.net.URLDecoder import java.net.URLEncoder import java.util.concurrent.TimeUnit object BangumiOAuthConstants { const val AUTHORIZE_URL = "https://bgm.tv/oauth/authorize" const val TOKEN_URL = "https://bgm.tv/oauth/access_token" + const val USER_AGENT = "ModerRAS/MiruPlay/0.1.0 (Android TV) (https://github.com/ModerRAS/MiruPlay)" const val CALLBACK_PORT = 13712 const val CALLBACK_PATH = "/callback" const val CALLBACK_URL = "http://127.0.0.1:$CALLBACK_PORT$CALLBACK_PATH" + fun queryParameter(url: String, name: String): String? { + val query = url.substringAfter('?', "").substringBefore('#') + if (query.isBlank()) return null + for (part in query.split('&')) { + val key = URLDecoder.decode(part.substringBefore('='), Charsets.UTF_8.name()) + if (key == name) { + return URLDecoder.decode(part.substringAfter('=', ""), Charsets.UTF_8.name()) + } + } + return null + } + fun authorizeUrl( clientId: String, state: String, @@ -135,7 +149,7 @@ class BangumiOAuthClient( val request = Request.Builder() .url(tokenUrl) .post(body) - .addHeader("User-Agent", DEFAULT_USER_AGENT) + .addHeader("User-Agent", BangumiOAuthConstants.USER_AGENT) .addHeader("Accept", "application/json") .build() proxyClient.newCall(request).execute().use { response -> @@ -167,7 +181,6 @@ class BangumiOAuthClient( companion object { const val SOURCE_NAME = "Bangumi" - private const val DEFAULT_USER_AGENT = "ModerRAS/MiruPlay/0.1.0 (Android TV) (https://github.com/ModerRAS/MiruPlay)" private fun defaultClient(): OkHttpClient = OkHttpClient.Builder() diff --git a/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClient.kt b/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClient.kt new file mode 100644 index 00000000..b0d07d4c --- /dev/null +++ b/scraper-core/src/main/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClient.kt @@ -0,0 +1,385 @@ +package com.miruplay.tv.scraper.core + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import okhttp3.Cookie +import okhttp3.CookieJar +import okhttp3.FormBody +import okhttp3.HttpUrl +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.HttpUrl.Companion.toHttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import org.jsoup.Jsoup +import java.net.URLEncoder +import java.util.concurrent.TimeUnit + +fun interface BangumiPasswordLoginClientFactory { + fun create(): BangumiPasswordLoginApi +} + +interface BangumiPasswordLoginApi { + fun configureProxy(proxyConfig: BangumiHttpProxyConfig) + suspend fun startChallenge(): BangumiPasswordLoginStep + suspend fun refreshCaptcha(): BangumiPasswordLoginStep + suspend fun loginAndAuthorize( + email: String, + password: String, + captcha: String, + clientId: String, + redirectUri: String, + state: String, + ): BangumiPasswordLoginStep +} + +sealed interface BangumiPasswordLoginStep { + data class Challenge(val image: ByteArray, val contentType: String) : BangumiPasswordLoginStep + data class Retry(val message: String, val image: ByteArray, val contentType: String) : BangumiPasswordLoginStep + data class Authorized(val callbackUrl: String) : BangumiPasswordLoginStep + data class Failed(val message: String) : BangumiPasswordLoginStep +} + +/** + * Server-side Bangumi login used by the web console. + * + * The password is written only into the `FollowTheRabbit` form body for that + * call. It is not stored on this session. Cookies and the login formhash stay + * so a wrong captcha can be retried without asking Bangumi to start over. + */ +class BangumiPasswordLoginClient private constructor( + httpClient: OkHttpClient?, + private val baseUrl: String, + private val userAgent: String, + private val clockMillis: () -> Long, + private val captchaSuffix: () -> Int, +) : BangumiPasswordLoginApi { + constructor( + baseUrl: String = DEFAULT_BASE_URL, + userAgent: String = BangumiOAuthConstants.USER_AGENT, + clockMillis: () -> Long = System::currentTimeMillis, + captchaSuffix: () -> Int = { (1..6).random() }, + ) : this( + httpClient = null, + baseUrl = baseUrl, + userAgent = userAgent, + clockMillis = clockMillis, + captchaSuffix = captchaSuffix, + ) + private val cookieJar = MemoryCookieJar() + private val proxyClient = BangumiProxyAwareOkHttpClient( + (httpClient ?: defaultClient()).newBuilder() + .cookieJar(cookieJar) + .followRedirects(false) + .followSslRedirects(false) + .build(), + ) + private var loginAction: String = "/FollowTheRabbit" + private var formhash: String = "" + + override fun configureProxy(proxyConfig: BangumiHttpProxyConfig) { + proxyClient.configureProxy(proxyConfig) + } + + override suspend fun startChallenge(): BangumiPasswordLoginStep = guarded { loadLoginForm() } + + override suspend fun refreshCaptcha(): BangumiPasswordLoginStep = guarded { + if (formhash.isBlank()) { + BangumiPasswordLoginStep.Failed("请先获取验证码") + } else { + fetchCaptcha() + } + } + + override suspend fun loginAndAuthorize( + email: String, + password: String, + captcha: String, + clientId: String, + redirectUri: String, + state: String, + ): BangumiPasswordLoginStep = guarded { + if (formhash.isBlank()) return@guarded BangumiPasswordLoginStep.Failed("请先获取验证码") + val posted = execute( + Request.Builder() + .url(resolveUrl(loginAction)) + .header("Referer", resolveUrl("/login")) + .header("Origin", origin()) + .post( + FormBody.Builder() + .add("formhash", formhash) + .add("referer", "") + .add("dreferer", "") + .add("email", email) + .add("password", password) + .add("captcha_challenge_field", captcha) + .add("loginsubmit", "登录") + .build(), + ) + .build(), + ) + val landed = followSameSite(posted, redirectUri) + landed.callbackUrl?.let { return@guarded BangumiPasswordLoginStep.Authorized(withOAuthState(it, state)) } + if (!cookieJar.has("chii_auth")) { + val message = parseBangumiNotice(landed.body) ?: "账号、密码或验证码不正确。" + if (message.contains("不能登录")) return@guarded BangumiPasswordLoginStep.Failed(message) + return@guarded when (val again = loadLoginForm()) { + is BangumiPasswordLoginStep.Challenge -> + BangumiPasswordLoginStep.Retry(message, again.image, again.contentType) + is BangumiPasswordLoginStep.Failed -> BangumiPasswordLoginStep.Failed(message) + else -> BangumiPasswordLoginStep.Failed(message) + } + } + + val authorizeUrl = authorizeUrl(clientId, redirectUri, state) + val authorize = execute(htmlGet(authorizeUrl)) + val authorizeLanded = followSameSite(authorize, redirectUri) + authorizeLanded.callbackUrl?.let { + return@guarded BangumiPasswordLoginStep.Authorized(withOAuthState(it, state)) + } + if (authorizeLanded.body.contains("id=\"loginForm\"") || authorizeLanded.body.contains("id='loginForm'")) { + return@guarded BangumiPasswordLoginStep.Failed("Bangumi 没有保持登录状态,请重试。") + } + val form = parseAuthorizeForm(authorizeLanded.body) + ?: return@guarded BangumiPasswordLoginStep.Failed( + parseBangumiNotice(authorizeLanded.body) ?: "Bangumi 授权页没有返回可提交的表单。", + ) + val submitted = execute( + Request.Builder() + .url(resolveUrl(form.action)) + .header("Referer", authorizeUrl) + .header("Origin", origin()) + .post( + FormBody.Builder().apply { + form.fields.forEach { (name, value) -> add(name, value) } + }.build(), + ) + .build(), + ) + val done = followSameSite(submitted, redirectUri) + done.callbackUrl?.let { return@guarded BangumiPasswordLoginStep.Authorized(withOAuthState(it, state)) } + BangumiPasswordLoginStep.Failed(parseBangumiNotice(done.body) ?: "Bangumi 授权没有返回验证码。") + } + + private suspend fun guarded(block: () -> BangumiPasswordLoginStep): BangumiPasswordLoginStep = + withContext(Dispatchers.IO) { + try { + block() + } catch (cancelled: CancellationException) { + throw cancelled + } catch (_: Exception) { + BangumiPasswordLoginStep.Failed("无法连接 Bangumi,请检查电视的出站代理或网络。") + } + } + + private fun loadLoginForm(): BangumiPasswordLoginStep { + val page = execute(htmlGet(resolveUrl("/login"))) + if (page.code !in 200..299) { + return BangumiPasswordLoginStep.Failed("Bangumi 登录页打开失败(HTTP ${page.code})。") + } + val parsed = parseBangumiLoginForm(page.body) + ?: return BangumiPasswordLoginStep.Failed("Bangumi 登录页没有返回表单。") + loginAction = parsed.first + formhash = parsed.second + return fetchCaptcha() + } + + private fun fetchCaptcha(): BangumiPasswordLoginStep { + val suffix = captchaSuffix().coerceIn(1, 6) + val page = execute( + Request.Builder() + .url(resolveUrl("/signup/captcha?${clockMillis()}$suffix")) + .header("Referer", resolveUrl("/login")) + .header("Accept", "image/gif,image/png,image/*;q=0.8") + .get() + .build(), + ) + if (page.code !in 200..299 || page.bytes.isEmpty()) { + return BangumiPasswordLoginStep.Failed("无法获取 Bangumi 验证码。") + } + if (page.bytes.size > MAX_BODY_BYTES) { + return BangumiPasswordLoginStep.Failed("Bangumi 验证码响应过大。") + } + return BangumiPasswordLoginStep.Challenge(page.bytes, imageContentType(page.contentType)) + } + + private fun authorizeUrl(clientId: String, redirectUri: String, state: String): String = + resolveUrl( + "/oauth/authorize?client_id=${clientId.urlEncode()}" + + "&response_type=code" + + "&redirect_uri=${redirectUri.urlEncode()}" + + "&state=${state.urlEncode()}", + ) + + private fun htmlGet(url: String): Request = + Request.Builder() + .url(url) + .header("Accept", "text/html,application/xhtml+xml") + .get() + .build() + + private fun followSameSite(initial: HttpResult, redirectUri: String): Landed { + var current = initial + repeat(MAX_REDIRECTS) { + val location = current.location ?: return Landed(current.body, null) + if (isBangumiOAuthCallback(location, redirectUri)) return Landed(current.body, location) + if (!sameSite(location)) return Landed(current.body, null) + current = execute(htmlGet(location)) + } + return Landed(current.body, null) + } + + private fun execute(request: Request): HttpResult { + val decorated = request.newBuilder().header("User-Agent", userAgent).build() + proxyClient.newCall(decorated).execute().use { response -> + val bytes = response.body?.bytes() ?: ByteArray(0) + if (bytes.size > MAX_BODY_BYTES) { + throw IllegalStateException("Bangumi 响应过大") + } + val type = response.header("Content-Type").orEmpty() + val location = response.header("Location")?.trim()?.takeIf { it.isNotEmpty() } + ?.let { response.request.url.resolve(it)?.toString() ?: it } + val text = if (type.startsWith("image/")) "" else String(bytes, Charsets.UTF_8) + return HttpResult( + code = response.code, + location = location, + body = text, + contentType = type, + bytes = bytes, + ) + } + } + + private fun resolveUrl(reference: String): String { + val base = if (baseUrl.endsWith("/")) baseUrl else "$baseUrl/" + return base.toHttpUrl().resolve(reference)?.toString() + ?: throw IllegalStateException("无法解析 Bangumi 地址") + } + + private fun origin(): String = baseUrl.trimEnd('/') + + private fun sameSite(url: String): Boolean { + val base = origin().toHttpUrl() + val target = url.toHttpUrlOrNull() ?: return false + return target.scheme == base.scheme && target.host == base.host && target.port == base.port + } + + private fun String.urlEncode(): String = URLEncoder.encode(this, Charsets.UTF_8.name()) + + private data class HttpResult( + val code: Int, + val location: String?, + val body: String, + val contentType: String, + val bytes: ByteArray, + ) + + private data class Landed(val body: String, val callbackUrl: String?) + + private class MemoryCookieJar : CookieJar { + private val cookies = mutableListOf() + + override fun saveFromResponse(url: HttpUrl, newCookies: List) { + synchronized(cookies) { + val now = System.currentTimeMillis() + for (cookie in newCookies) { + cookies.removeAll { it.name == cookie.name && it.domain == cookie.domain && it.path == cookie.path } + if (cookie.expiresAt > now && cookie.value.isNotEmpty()) cookies += cookie + } + } + } + + override fun loadForRequest(url: HttpUrl): List = synchronized(cookies) { + cookies.filter { it.matches(url) } + } + + fun has(name: String): Boolean = synchronized(cookies) { + cookies.any { it.name == name && it.value.isNotBlank() } + } + } + + companion object { + const val DEFAULT_BASE_URL = "https://bgm.tv" + private const val MAX_REDIRECTS = 5 + private const val MAX_BODY_BYTES = 2_000_000 + + private fun defaultClient(): OkHttpClient = + OkHttpClient.Builder() + .connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .build() + } +} + +internal fun parseBangumiLoginForm(html: String): Pair? { + val form = Jsoup.parse(html).selectFirst("#loginForm") + ?: Jsoup.parse(html).selectFirst("form[action*=FollowTheRabbit]") + ?: return null + val hash = form.selectFirst("input[name=formhash]")?.attr("value").orEmpty() + if (hash.isBlank()) return null + val action = form.attr("action").ifBlank { "/FollowTheRabbit" } + return action to hash +} + +internal data class BangumiAuthorizeForm( + val action: String, + val fields: List>, +) + +internal fun parseAuthorizeForm(html: String): BangumiAuthorizeForm? { + val form = Jsoup.parse(html).select("form").firstOrNull { element -> + element.selectFirst("input[name=formhash]") != null && + ( + element.attr("action").contains("oauth/authorize") || + element.select("input[type=submit], button").any { control -> + control.attr("value").contains("授权") || control.text().contains("授权") + } + ) + } ?: return null + val fields = mutableListOf>() + for (input in form.select("input[name]")) { + val type = input.attr("type").lowercase() + if (type == "submit" || type == "button" || type == "image") continue + if ((type == "checkbox" || type == "radio") && !input.hasAttr("checked")) continue + fields += input.attr("name") to input.attr("value") + } + val submit = form.select("input[type=submit], button").firstOrNull { control -> + control.attr("value").contains("授权") || control.text().contains("授权") + } + val submitName = submit?.attr("name")?.ifBlank { "submit" } ?: "submit" + val submitValue = submit?.attr("value")?.ifBlank { null } ?: submit?.text()?.ifBlank { null } ?: "授权" + if (fields.none { it.first == submitName }) fields += submitName to submitValue + if (fields.none { it.first == "formhash" && it.second.isNotBlank() }) return null + return BangumiAuthorizeForm(form.attr("action").ifBlank { "/oauth/authorize" }, fields) +} + +internal fun parseBangumiNotice(html: String): String? { + if (html.isBlank()) return null + val document = Jsoup.parse(html) + val text = document.selectFirst("#colunmNotice .message p.text")?.text()?.trim() + ?: document.selectFirst(".message p.text")?.text()?.trim() + return text?.takeIf { it.isNotBlank() } +} + +internal fun isBangumiOAuthCallback(location: String, redirectUri: String): Boolean { + if (location.startsWith(redirectUri)) return true + val url = location.toHttpUrlOrNull() ?: return false + val path = url.encodedPath + return (url.host == "127.0.0.1" || url.host == "localhost") && + (path == "/callback" || path == "/callback/") +} + +internal fun withOAuthState(callbackUrl: String, state: String): String { + if (BangumiOAuthConstants.queryParameter(callbackUrl, "state") != null) return callbackUrl + val separator = if ('?' in callbackUrl) '&' else '?' + return callbackUrl + separator + "state=" + URLEncoder.encode(state, Charsets.UTF_8.name()) +} + +internal fun imageContentType(header: String): String { + val mime = header.substringBefore(';').trim().lowercase() + return if (mime == "image/gif" || mime == "image/png" || mime == "image/jpeg" || mime == "image/webp") { + mime + } else { + "image/gif" + } +} diff --git a/scraper-core/src/test/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClientTest.kt b/scraper-core/src/test/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClientTest.kt new file mode 100644 index 00000000..d35f7228 --- /dev/null +++ b/scraper-core/src/test/kotlin/com/miruplay/tv/scraper/core/BangumiPasswordLoginClientTest.kt @@ -0,0 +1,229 @@ +package com.miruplay.tv.scraper.core + +import kotlinx.coroutines.runBlocking +import okhttp3.mockwebserver.Dispatcher +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.RecordedRequest +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class BangumiPasswordLoginClientTest { + @Test + fun `parsers read the live login form, authorize form, and error notice`() { + val login = """ +
+ + + + + +
+ """.trimIndent() + assertEquals("/FollowTheRabbit" to "4a09722d", parseBangumiLoginForm(login)) + + val authorize = """ +
+ + + +
+ """.trimIndent() + val form = parseAuthorizeForm(authorize)!! + assertEquals("/oauth/authorize?client_id=test-id", form.action) + assertEquals("auth-hash", form.fields.first { it.first == "formhash" }.second) + assertEquals("授权", form.fields.first { it.first == "submit" }.second) + + val error = """ +

呜咕,出错了

+

验证码错误,请返回重试。

+ """.trimIndent() + assertEquals("验证码错误,请返回重试。", parseBangumiNotice(error)) + assertTrue(isBangumiOAuthCallback("http://127.0.0.1:13712/callback?code=abc&state=s", BangumiOAuthConstants.CALLBACK_URL)) + assertEquals( + "http://127.0.0.1:13712/callback?code=abc&state=kept", + withOAuthState("http://127.0.0.1:13712/callback?code=abc&state=kept", "other"), + ) + assertTrue(withOAuthState("http://127.0.0.1:13712/callback?code=abc", "s 1").contains("state=s+1") || + withOAuthState("http://127.0.0.1:13712/callback?code=abc", "s 1").contains("state=s%201")) + assertEquals("image/png", imageContentType("image/png; charset=binary")) + assertEquals("image/gif", imageContentType("text/html")) + } + + @Test + fun `wrong captcha retries and a later correct captcha returns the callback without storing the password`() = runBlocking { + val posts = mutableListOf() + MockWebServer().use { server -> + server.dispatcher = scriptedDispatcher(posts, authorizeRedirect = false) + val client = BangumiPasswordLoginClient( + baseUrl = server.url("/").toString().trimEnd('/'), + captchaSuffix = { 1 }, + clockMillis = { 10L }, + ) + val challenge = client.startChallenge() + assertTrue(challenge is BangumiPasswordLoginStep.Challenge) + assertEquals("image/gif", (challenge as BangumiPasswordLoginStep.Challenge).contentType) + assertTrue(challenge.image.contentEquals(TINY_GIF)) + + val retry = client.loginAndAuthorize( + email = "user@example.com", + password = SECRET, + captcha = "bad", + clientId = "test-id", + redirectUri = BangumiOAuthConstants.CALLBACK_URL, + state = "state-1", + ) + assertTrue(retry is BangumiPasswordLoginStep.Retry) + val retryStep = retry as BangumiPasswordLoginStep.Retry + assertEquals("验证码错误,请返回重试。", retryStep.message) + assertFalse(retryStep.message.contains(SECRET)) + assertTrue(retryStep.image.contentEquals(TINY_GIF)) + + val authorized = client.loginAndAuthorize( + email = "user@example.com", + password = SECRET, + captcha = "ok", + clientId = "test-id", + redirectUri = BangumiOAuthConstants.CALLBACK_URL, + state = "state-1", + ) + assertTrue(authorized is BangumiPasswordLoginStep.Authorized) + assertEquals( + "http://127.0.0.1:13712/callback?code=auth-code&state=state-1", + (authorized as BangumiPasswordLoginStep.Authorized).callbackUrl, + ) + assertTrue(posts.any { it.contains("password=$SECRET") && it.contains("captcha_challenge_field=bad") }) + assertTrue(posts.any { it.contains("password=$SECRET") && it.contains("captcha_challenge_field=ok") }) + assertTrue(posts.any { it.contains("formhash=auth-hash") && it.contains("submit=") }) + assertFalse(client.toString().contains(SECRET)) + } + } + + @Test + fun `already approved app is a redirect straight to the loopback callback`() = runBlocking { + MockWebServer().use { server -> + server.dispatcher = scriptedDispatcher(mutableListOf(), authorizeRedirect = true) + val client = BangumiPasswordLoginClient(baseUrl = server.url("/").toString().trimEnd('/')) + assertTrue(client.startChallenge() is BangumiPasswordLoginStep.Challenge) + val authorized = client.loginAndAuthorize( + email = "user@example.com", + password = SECRET, + captcha = "ok", + clientId = "test-id", + redirectUri = BangumiOAuthConstants.CALLBACK_URL, + state = "state-1", + ) as BangumiPasswordLoginStep.Authorized + assertEquals( + "http://127.0.0.1:13712/callback?code=auth-code&state=state-1", + authorized.callbackUrl, + ) + } + } + + @Test + fun `lockout message is returned without a new captcha`() = runBlocking { + MockWebServer().use { server -> + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.path.orEmpty() + return when { + path.startsWith("/login") -> MockResponse().setBody(LOGIN_HTML) + path.startsWith("/signup/captcha") -> image() + path.startsWith("/FollowTheRabbit") -> MockResponse().setBody(LOCKOUT_HTML) + else -> MockResponse().setResponseCode(404) + } + } + } + val client = BangumiPasswordLoginClient(baseUrl = server.url("/").toString().trimEnd('/')) + client.startChallenge() + val failed = client.loginAndAuthorize( + email = "user@example.com", + password = SECRET, + captcha = "ok", + clientId = "test-id", + redirectUri = BangumiOAuthConstants.CALLBACK_URL, + state = "state-1", + ) + assertEquals( + "累计 5 次错误尝试,15 分钟内您将不能登录本站。", + (failed as BangumiPasswordLoginStep.Failed).message, + ) + assertFalse(failed.message.contains(SECRET)) + } + } + + @Test + fun `unreachable Bangumi becomes a fixed message`() = runBlocking { + val server = MockWebServer() + server.start() + val client = BangumiPasswordLoginClient(baseUrl = server.url("/").toString().trimEnd('/')) + server.shutdown() + val failed = client.startChallenge() as BangumiPasswordLoginStep.Failed + assertEquals("无法连接 Bangumi,请检查电视的出站代理或网络。", failed.message) + } + + private fun scriptedDispatcher(posts: MutableList, authorizeRedirect: Boolean): Dispatcher = + object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse { + val path = request.path.orEmpty() + if (request.method == "POST") posts += request.body.readUtf8() + return when { + path.startsWith("/login") -> MockResponse().setBody(LOGIN_HTML).setHeader("Set-Cookie", "chii_sid=sid; Path=/") + path.startsWith("/signup/captcha") -> image() + path.startsWith("/FollowTheRabbit") -> { + val badCaptcha = posts.last().contains("captcha_challenge_field=bad") + if (badCaptcha) { + MockResponse().setBody(ERROR_HTML) + } else { + MockResponse().setResponseCode(302) + .setHeader("Set-Cookie", "chii_auth=yes; Path=/") + .setHeader("Location", "/") + } + } + request.method == "GET" && path.startsWith("/oauth/authorize") -> + if (authorizeRedirect) { + MockResponse().setResponseCode(302).setHeader("Location", CALLBACK) + } else { + MockResponse().setBody(AUTHORIZE_HTML) + } + request.method == "POST" && path.startsWith("/oauth/authorize") -> + MockResponse().setResponseCode(302).setHeader("Location", CALLBACK) + path == "/" -> MockResponse().setBody("") + else -> MockResponse().setResponseCode(404) + } + } + } + + private fun image(): MockResponse = + MockResponse() + .setHeader("Content-Type", "image/gif") + .setBody(okio.Buffer().write(TINY_GIF)) + + private companion object { + const val SECRET = "s3cret-token-value" + const val CALLBACK = "http://127.0.0.1:13712/callback?code=auth-code&state=state-1" + val TINY_GIF = byteArrayOf( + 0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x3b, + ) + const val LOGIN_HTML = """ +
+ +
+ """ + const val ERROR_HTML = """ +

验证码错误,请返回重试。

+ """ + const val LOCKOUT_HTML = """ +

累计 5 次错误尝试,15 分钟内您将不能登录本站。

+ """ + const val AUTHORIZE_HTML = """ +
+ + + +
+ """ + } +} diff --git a/specs/bangumi-web-login/design.md b/specs/bangumi-web-login/design.md new file mode 100644 index 00000000..7d929e19 --- /dev/null +++ b/specs/bangumi-web-login/design.md @@ -0,0 +1,37 @@ +# 技术方案 + +## 架构 + +网页浏览器只访问电视上的 Web Control。电视用已有出站代理访问 `bgm.tv`:先取登录页 `formhash` 和 `/signup/captcha`,再把邮箱、密码、验证码 POST 到 `/FollowTheRabbit`。登录成功后,同一 cookie 会话提交 OAuth 授权表单。Bangumi 302 到已注册的 `http://127.0.0.1:13712/callback` 时,电视不跟随这次跳转,而是把回调交给现有的 `BangumiOAuthCoordinator` 换 token。 + +```mermaid +sequenceDiagram + participant Browser + participant WebControl + participant Bangumi + Browser->>WebControl: 开始登录 + WebControl->>Bangumi: GET /login 与验证码 + WebControl-->>Browser: 验证码图片 + Browser->>WebControl: 邮箱、密码、验证码 + WebControl->>Bangumi: POST /FollowTheRabbit + WebControl->>Bangumi: POST /oauth/authorize + Bangumi-->>WebControl: 302 回环回调 + WebControl->>Bangumi: 用 code 换 token + WebControl-->>Browser: 已登录与有效期 +``` + +## 接口 + +- `POST /api/metadata/bangumi-login/start`:开始一次登录,返回 `challenge` 和 `captchaImage`(data URL)。未配置 OAuth 应用时返回 `not_configured`。 +- `POST /api/metadata/bangumi-login/captcha`:同一会话换验证码。 +- `POST /api/metadata/bangumi-login`:正文为 `email`、`password`、`captcha`。成功为 `success`,验证码错误为 `challenge` 加新图片,其余失败为 `failed`。 +- `POST /api/metadata/bangumi-login/cancel`:放弃未完成的授权。 +- 响应不包含密码,也不回显 access token。`GET /api/metadata` 增加 `bangumiTokenExpiresAtMillis`,没有有效期时为 0。 + +## 安全 + +密码只进入当次发往 Bangumi 的表单,不写入 `AppCredentialStore`,也不出现在响应或固定错误文案里。会话最多保留 10 分钟。Web Control 原有访问令牌仍然保护这些接口。 + +## 测试 + +`BangumiPasswordLoginClient` 用 MockWebServer 固定 Bangumi 的 HTML。`BangumiWebConsoleLogin` 用假的登录客户端和现有 OAuth coordinator 验证换 token、重试、过期和空字段。路由测试确认响应体不含密码。 diff --git a/specs/bangumi-web-login/requirements.md b/specs/bangumi-web-login/requirements.md new file mode 100644 index 00000000..46ff2117 --- /dev/null +++ b/specs/bangumi-web-login/requirements.md @@ -0,0 +1,40 @@ +# 需求文档 + +## 介绍 + +Bangumi 登录目前要在电视上对焦邮箱、密码和验证码。网页控制台改为直接输入这三项,由电视代为完成 Bangumi 登录和授权。密码不保存在设备上。 + +## 需求 + +### 需求 1 - 网页填写账号 + +**用户故事:** 作为使用者,我希望在网页控制台输入 Bangumi 邮箱、密码和验证码,这样就不需要用遥控器在电视上选中这些输入框。 + +#### 验收标准 + +1. When 用户在网页控制台打开元数据页并选择 Bangumi 账号登录,the 网页控制台 shall 显示邮箱、密码和验证码输入,并展示由电视从 Bangumi 取回的验证码图片。 +2. When 用户点击验证码图片,the 网页控制台 shall 向电视请求一张新的验证码并替换当前图片。 +3. When 用户提交邮箱、密码和验证码且 Bangumi 接受登录,the MiruPlay shall 完成 OAuth 授权并把访问令牌保存到电视端加密凭据。 +4. While 用户已打开登录表单,when 验证码不正确,the 网页控制台 shall 留下邮箱和密码、显示 Bangumi 返回的错误,并换一张验证码。 +5. When Bangumi 拒绝继续登录(例如短时间内不能登录),the 网页控制台 shall 显示该错误并结束这一次登录。 +6. When 用户取消登录,或距离获取验证码已超过 10 分钟再提交,the MiruPlay shall 放弃这一次未完成的授权,并要求重新获取验证码。 + +### 需求 2 - 密码不留在设备上 + +**用户故事:** 作为使用者,我希望网页里输入的 Bangumi 密码只用来换授权,而不是变成又一份保存在电视上的口令。 + +#### 验收标准 + +1. When 登录请求已经完成或失败,the MiruPlay shall 不把密码写入凭据存储,也不在网页接口响应中回传密码。 +2. When 登录成功,the 网页控制台 shall 只显示已登录和授权有效期,不回显访问令牌明文。 +3. While 构建没有配置 Bangumi OAuth 应用信息,when 用户开始网页登录,the 网页控制台 shall 提示无法登录,并且不提交密码。 + +### 需求 3 - 原有入口保留 + +**用户故事:** 作为已经在用电视登录或手动令牌的使用者,我希望这些办法仍然可用。 + +#### 验收标准 + +1. When 用户在电视设置里使用 Bangumi 登录,the MiruPlay shall 继续打开原来的授权页,并用同一套令牌存储保存结果。 +2. When 用户在网页控制台粘贴或清除 Access Token,the MiruPlay shall 继续按原来的令牌接口保存或清除。 +3. When 电视配置了出站代理,the MiruPlay shall 用这份代理访问 Bangumi 登录页、验证码和令牌交换。 diff --git a/specs/bangumi-web-login/tasks.md b/specs/bangumi-web-login/tasks.md new file mode 100644 index 00000000..6def90f4 --- /dev/null +++ b/specs/bangumi-web-login/tasks.md @@ -0,0 +1,17 @@ +# 实施计划 + +- [x] 1. 电视代提交 Bangumi 邮箱、密码和验证码 +- 解析登录页 formhash 与授权页,验证码错误可重试,授权跳转不跟随到 127.0.0.1 +- _需求: 1, 2_ + +- [x] 2. WebAPI +- `bangumi-login` 的开始、刷新验证码、提交和取消;成功后仍用原来的 OAuth coordinator 保存 token +- _需求: 1, 2, 3_ + +- [x] 3. 网页控制台表单 +- 元数据页账号登录、验证码图片、手动粘贴 token 保留 +- _需求: 1, 3_ + +- [x] 4. 验证 +- 登录客户端、网页登录编排和路由单测;浏览器走通表单 +- _需求: 1, 2, 3_ diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLogin.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLogin.kt new file mode 100644 index 00000000..0b38a20c --- /dev/null +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLogin.kt @@ -0,0 +1,182 @@ +package com.miruplay.tv.webcontrol + +import com.miruplay.tv.model.metadataBangumiOAuthFailedMessage +import com.miruplay.tv.model.metadataBangumiOAuthNotConfiguredMessage +import com.miruplay.tv.model.metadataBangumiOAuthSuccessMessage +import com.miruplay.tv.scraper.core.BangumiHttpProxyConfig +import com.miruplay.tv.scraper.core.BangumiOAuthConstants +import com.miruplay.tv.scraper.core.BangumiPasswordLoginApi +import com.miruplay.tv.scraper.core.BangumiPasswordLoginClientFactory +import com.miruplay.tv.scraper.core.BangumiPasswordLoginStep +import com.miruplay.tv.sync.BangumiOAuthCoordinator +import com.miruplay.tv.sync.BangumiOAuthState +import java.util.Base64 +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock + +/** + * Web-console Bangumi login. + * + * The browser only talks to this device. The device loads the captcha and posts + * the password to Bangumi, then exchanges the loopback code through the same + * OAuth coordinator the TV uses. The password is not written to preferences. + */ +class BangumiWebConsoleLogin( + private val oauth: BangumiOAuthCoordinator, + private val newClient: BangumiPasswordLoginClientFactory, + private val proxyConfig: suspend () -> BangumiHttpProxyConfig, + private val tokenConfigured: () -> Boolean, + private val expiresAtMillis: () -> Long, + private val clockMillis: () -> Long = System::currentTimeMillis, +) { + private val mutex = Mutex() + private var session: BangumiPasswordLoginApi? = null + private var sessionStartedAtMillis: Long = 0L + + suspend fun start(): BangumiWebLoginDto = mutex.withLock { + val authorizeUrl = oauth.startAuthorize() + if (authorizeUrl.isNullOrBlank()) { + session = null + return@withLock snapshot( + status = NOT_CONFIGURED, + message = metadataBangumiOAuthNotConfiguredMessage().fallback, + ) + } + val client = newClient.create() + client.configureProxy(proxyConfig()) + when (val step = client.startChallenge()) { + is BangumiPasswordLoginStep.Challenge -> { + session = client + sessionStartedAtMillis = clockMillis() + snapshot(status = CHALLENGE, captcha = step) + } + is BangumiPasswordLoginStep.Failed -> { + oauth.cancel() + session = null + snapshot(status = FAILED, message = step.message) + } + else -> { + oauth.cancel() + session = null + snapshot(status = FAILED, message = "无法获取 Bangumi 验证码。") + } + } + } + + suspend fun refreshCaptcha(): BangumiWebLoginDto = mutex.withLock { + val client = liveSession() ?: return@withLock snapshot(status = FAILED, message = "请先获取验证码") + client.configureProxy(proxyConfig()) + when (val step = client.refreshCaptcha()) { + is BangumiPasswordLoginStep.Challenge -> snapshot(status = CHALLENGE, captcha = step) + is BangumiPasswordLoginStep.Failed -> snapshot(status = FAILED, message = step.message) + else -> snapshot(status = FAILED, message = "无法刷新验证码。") + } + } + + suspend fun submit(email: String, password: String, captcha: String): BangumiWebLoginDto = mutex.withLock { + val trimmedEmail = email.trim() + val trimmedCaptcha = captcha.trim() + if (trimmedEmail.isEmpty() || password.isEmpty() || trimmedCaptcha.isEmpty()) { + throw IllegalArgumentException("请填写邮箱、密码和验证码") + } + if (trimmedEmail.length > 320 || password.length > 256 || trimmedCaptcha.length > 64) { + throw IllegalArgumentException("邮箱、密码或验证码过长") + } + val client = liveSession() ?: return@withLock snapshot(status = FAILED, message = "验证码已过期,请重新获取") + val authorizing = oauth.state.value as? BangumiOAuthState.Authorizing + ?: return@withLock snapshot(status = FAILED, message = "登录已过期,请重新获取验证码") + val clientId = BangumiOAuthConstants.queryParameter(authorizing.url, "client_id").orEmpty() + val state = BangumiOAuthConstants.queryParameter(authorizing.url, "state").orEmpty() + if (clientId.isBlank() || state.isBlank()) { + return@withLock snapshot(status = FAILED, message = "登录已过期,请重新获取验证码") + } + client.configureProxy(proxyConfig()) + when ( + val step = client.loginAndAuthorize( + email = trimmedEmail, + password = password, + captcha = trimmedCaptcha, + clientId = clientId, + redirectUri = BangumiOAuthConstants.CALLBACK_URL, + state = state, + ) + ) { + is BangumiPasswordLoginStep.Authorized -> { + val accepted = oauth.submitCallbackUrl(step.callbackUrl) + session = null + if (!accepted) { + snapshot(status = FAILED, message = "授权校验失败,请重新登录") + } else { + when (val oauthState = oauth.state.value) { + BangumiOAuthState.Success -> + snapshot(status = SUCCESS, message = metadataBangumiOAuthSuccessMessage().fallback) + is BangumiOAuthState.Failed -> + snapshot(status = FAILED, message = oauthState.message.fallback) + else -> snapshot(status = FAILED, message = metadataBangumiOAuthFailedMessage().fallback) + } + } + } + is BangumiPasswordLoginStep.Retry -> + snapshot( + status = CHALLENGE, + message = step.message, + captchaImage = dataUrl(step.image, step.contentType), + ) + is BangumiPasswordLoginStep.Challenge -> snapshot(status = CHALLENGE, captcha = step) + is BangumiPasswordLoginStep.Failed -> { + oauth.cancel() + session = null + snapshot(status = FAILED, message = step.message) + } + } + } + + suspend fun cancel(): BangumiWebLoginDto = mutex.withLock { + session = null + oauth.cancel() + snapshot(status = IDLE, message = null) + } + + suspend fun logout(): BangumiWebLoginDto = mutex.withLock { + session = null + oauth.logout() + snapshot(status = IDLE, message = null) + } + + private fun liveSession(): BangumiPasswordLoginApi? { + val current = session ?: return null + if (clockMillis() - sessionStartedAtMillis > SESSION_TTL_MILLIS) { + session = null + oauth.cancel() + return null + } + return current + } + + private fun snapshot( + status: String, + message: String? = null, + captcha: BangumiPasswordLoginStep.Challenge? = null, + captchaImage: String? = captcha?.let { dataUrl(it.image, it.contentType) }, + ): BangumiWebLoginDto = BangumiWebLoginDto( + status = status, + message = message, + captchaImage = captchaImage, + tokenConfigured = tokenConfigured(), + expiresAtMillis = expiresAtMillis(), + ) + + companion object { + const val IDLE = "idle" + const val CHALLENGE = "challenge" + const val SUCCESS = "success" + const val FAILED = "failed" + const val NOT_CONFIGURED = "not_configured" + const val SESSION_TTL_MILLIS = 10L * 60L * 1000L + + private fun dataUrl(bytes: ByteArray, contentType: String): String { + val mime = contentType.substringBefore(';').trim().ifBlank { "image/gif" } + return "data:$mime;base64,${Base64.getEncoder().encodeToString(bytes)}" + } + } +} diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt index 92c2fce0..42b10e24 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/NanoHttpWebControlServer.kt @@ -228,6 +228,19 @@ open class NanoHttpWebControlServer( session.method == Method.DELETE && route == "/api/metadata/bangumi-token" -> { jsonResponse(MetadataSettingsDto.serializer(), webControlService.clearBangumiToken()) } + session.method == Method.POST && route == "/api/metadata/bangumi-login/start" -> { + jsonResponse(BangumiWebLoginDto.serializer(), webControlService.startBangumiWebLogin()) + } + session.method == Method.POST && route == "/api/metadata/bangumi-login/captcha" -> { + jsonResponse(BangumiWebLoginDto.serializer(), webControlService.refreshBangumiWebLoginCaptcha()) + } + session.method == Method.POST && route == "/api/metadata/bangumi-login/cancel" -> { + jsonResponse(BangumiWebLoginDto.serializer(), webControlService.cancelBangumiWebLogin()) + } + session.method == Method.POST && route == "/api/metadata/bangumi-login" -> { + val request = parseBody(session, BangumiWebLoginRequest.serializer()) + jsonResponse(BangumiWebLoginDto.serializer(), webControlService.submitBangumiWebLogin(request)) + } session.method == Method.POST && route == "/api/metadata/bangumi-sync" -> { jsonResponse(BangumiSyncAllResultDto.serializer(), webControlService.syncAllBangumi()) } diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/SharedWebControlEndpointService.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/SharedWebControlEndpointService.kt index 5231baaf..1ab60510 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/SharedWebControlEndpointService.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/SharedWebControlEndpointService.kt @@ -288,6 +288,7 @@ abstract class SharedWebControlEndpointService( MetadataSettingsDto( bangumiTokenConfigured = !securePreferences.bangumiAccessToken.isNullOrBlank(), tmdbTokenConfigured = !securePreferences.tmdbAccessToken.isNullOrBlank(), + bangumiTokenExpiresAtMillis = securePreferences.bangumiTokenExpiresAtMillis, ) override suspend fun saveBangumiToken(request: BangumiTokenRequest): MetadataSettingsDto { diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt index cafd359e..857be718 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlEndpointService.kt @@ -68,6 +68,14 @@ interface WebControlEndpointService { getBangumiArchive() suspend fun saveBangumiToken(request: BangumiTokenRequest): MetadataSettingsDto suspend fun clearBangumiToken(): MetadataSettingsDto + suspend fun startBangumiWebLogin(): BangumiWebLoginDto = + throw UnsupportedOperationException("Bangumi 网页登录不可用") + suspend fun refreshBangumiWebLoginCaptcha(): BangumiWebLoginDto = + throw UnsupportedOperationException("Bangumi 网页登录不可用") + suspend fun submitBangumiWebLogin(request: BangumiWebLoginRequest): BangumiWebLoginDto = + throw UnsupportedOperationException("Bangumi 网页登录不可用") + suspend fun cancelBangumiWebLogin(): BangumiWebLoginDto = + throw UnsupportedOperationException("Bangumi 网页登录不可用") suspend fun syncAllBangumi(): BangumiSyncAllResultDto = throw UnsupportedOperationException("Bangumi sync not supported") suspend fun saveTmdbToken(request: TmdbTokenRequest): MetadataSettingsDto = diff --git a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt index de4f014a..197145ad 100644 --- a/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt +++ b/web-control-core/src/main/kotlin/com/miruplay/tv/webcontrol/WebControlModels.kt @@ -307,6 +307,7 @@ data class LocalLogDownload( data class MetadataSettingsDto( val bangumiTokenConfigured: Boolean, val tmdbTokenConfigured: Boolean = false, + val bangumiTokenExpiresAtMillis: Long = 0L, ) @Serializable @@ -665,6 +666,22 @@ data class BangumiTokenRequest( val token: String, ) +@Serializable +data class BangumiWebLoginDto( + val status: String, + val message: String? = null, + val captchaImage: String? = null, + val tokenConfigured: Boolean = false, + val expiresAtMillis: Long = 0L, +) + +@Serializable +data class BangumiWebLoginRequest( + val email: String = "", + val password: String = "", + val captcha: String = "", +) + @Serializable data class BangumiSyncAllResultDto( val animeCount: Int, diff --git a/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLoginTest.kt b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLoginTest.kt new file mode 100644 index 00000000..59e043af --- /dev/null +++ b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/BangumiWebConsoleLoginTest.kt @@ -0,0 +1,225 @@ +package com.miruplay.tv.webcontrol + +import com.miruplay.tv.core.common.Result +import com.miruplay.tv.repository.AppCredentialStore +import com.miruplay.tv.scraper.core.BangumiHttpProxyConfig +import com.miruplay.tv.scraper.core.BangumiOAuthClientApi +import com.miruplay.tv.scraper.core.BangumiOAuthTokens +import com.miruplay.tv.scraper.core.BangumiPasswordLoginApi +import com.miruplay.tv.scraper.core.BangumiPasswordLoginClientFactory +import com.miruplay.tv.scraper.core.BangumiPasswordLoginStep +import com.miruplay.tv.sync.BangumiOAuthCoordinator +import com.miruplay.tv.sync.BangumiOAuthLoopbackFactory +import com.miruplay.tv.sync.BangumiOAuthLoopbackHandle +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.runBlocking +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class BangumiWebConsoleLoginTest { + @Test + fun `start returns captcha and submit exchanges the callback without echoing the password`() = runBlocking { + val password = "s3cret-token-value" + val harness = harness() + val started = harness.login.start() + assertEquals(BangumiWebConsoleLogin.CHALLENGE, started.status) + assertTrue(started.captchaImage!!.startsWith("data:image/gif;base64,")) + assertFalse(started.captchaImage!!.contains(password)) + + val done = harness.login.submit("user@example.com", password, "abcd") + assertEquals(BangumiWebConsoleLogin.SUCCESS, done.status) + assertEquals("Bangumi 登录成功。", done.message) + assertEquals(true, done.tokenConfigured) + assertEquals(9_999_999_999L, done.expiresAtMillis) + assertEquals("access-1", harness.credentials.bangumiAccessToken) + assertEquals(password, harness.api.lastPassword) + assertFalse(done.message.orEmpty().contains(password)) + assertNull(done.captchaImage) + } + + @Test + fun `wrong captcha keeps the session and a later submit can succeed`() = runBlocking { + val harness = harness() + harness.api.mode = LoginMode.RETRY + harness.login.start() + val retry = harness.login.submit("user@example.com", "pw", "bad") + assertEquals(BangumiWebConsoleLogin.CHALLENGE, retry.status) + assertEquals("验证码错误,请返回重试。", retry.message) + assertTrue(retry.captchaImage!!.contains("base64,")) + assertNull(harness.credentials.bangumiAccessToken) + + harness.api.mode = LoginMode.AUTHORIZED + val done = harness.login.submit("user@example.com", "pw", "ok") + assertEquals(BangumiWebConsoleLogin.SUCCESS, done.status) + assertEquals("access-1", harness.credentials.bangumiAccessToken) + } + + @Test + fun `blank fields are rejected before any Bangumi call`() = runBlocking { + val harness = harness() + harness.login.start() + val error = runCatching { harness.login.submit(" ", "pw", "code") }.exceptionOrNull() + assertTrue(error is IllegalArgumentException) + assertEquals("请填写邮箱、密码和验证码", error?.message) + assertEquals(0, harness.api.authorizeCalls) + } + + @Test + fun `missing oauth client reports not configured`() = runBlocking { + val harness = harness(configured = false) + val started = harness.login.start() + assertEquals(BangumiWebConsoleLogin.NOT_CONFIGURED, started.status) + assertEquals(0, harness.createdClients) + } + + @Test + fun `cancel and expiry both require a fresh captcha`() = runBlocking { + val clock = Clock() + val harness = harness(clock = clock) + harness.login.start() + harness.login.cancel() + val cancelled = harness.login.submit("user@example.com", "pw", "code") + assertEquals("验证码已过期,请重新获取", cancelled.message) + + harness.login.start() + clock.now += BangumiWebConsoleLogin.SESSION_TTL_MILLIS + 1 + val expired = harness.login.submit("user@example.com", "pw", "code") + assertEquals("验证码已过期,请重新获取", expired.message) + assertNull(harness.credentials.bangumiAccessToken) + } + + @Test + fun `logout clears a saved token`() = runBlocking { + val harness = harness() + harness.login.start() + harness.login.submit("user@example.com", "pw", "code") + harness.login.logout() + assertNull(harness.credentials.bangumiAccessToken) + assertEquals(0L, harness.credentials.bangumiTokenExpiresAtMillis) + } + + private fun harness(configured: Boolean = true, clock: Clock = Clock()): Harness { + val credentials = Credentials() + val oauthClient = OAuthClient(isConfigured = configured) + var created = 0 + val api = LoginApi() + val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined) + val coordinator = BangumiOAuthCoordinator( + credentials = credentials, + client = oauthClient, + loopbackFactory = BangumiOAuthLoopbackFactory { + object : BangumiOAuthLoopbackHandle { + override fun start() = Unit + override fun stop() = Unit + } + }, + scope = scope, + clockMillis = { clock.now }, + newState = { "state-1" }, + ) + val login = BangumiWebConsoleLogin( + oauth = coordinator, + newClient = BangumiPasswordLoginClientFactory { + created += 1 + api + }, + proxyConfig = { BangumiHttpProxyConfig.Disabled }, + tokenConfigured = { !credentials.bangumiAccessToken.isNullOrBlank() }, + expiresAtMillis = { credentials.bangumiTokenExpiresAtMillis }, + clockMillis = { clock.now }, + ) + return Harness(login, credentials, api, createdClients = { created }) + } + + private class Clock(var now: Long = 1_000L) + + private class Harness( + val login: BangumiWebConsoleLogin, + val credentials: Credentials, + val api: LoginApi, + private val createdClients: () -> Int, + ) { + val createdClientsCount: Int get() = createdClients() + } + + private val Harness.createdClients: Int get() = createdClientsCount + + private enum class LoginMode { AUTHORIZED, RETRY } + + private class LoginApi : BangumiPasswordLoginApi { + var mode = LoginMode.AUTHORIZED + var lastPassword: String? = null + var authorizeCalls = 0 + + override fun configureProxy(proxyConfig: BangumiHttpProxyConfig) = Unit + + override suspend fun startChallenge(): BangumiPasswordLoginStep = + BangumiPasswordLoginStep.Challenge(byteArrayOf(1, 2, 3), "image/gif") + + override suspend fun refreshCaptcha(): BangumiPasswordLoginStep = + BangumiPasswordLoginStep.Challenge(byteArrayOf(9), "image/gif") + + override suspend fun loginAndAuthorize( + email: String, + password: String, + captcha: String, + clientId: String, + redirectUri: String, + state: String, + ): BangumiPasswordLoginStep { + authorizeCalls += 1 + lastPassword = password + return when (mode) { + LoginMode.AUTHORIZED -> BangumiPasswordLoginStep.Authorized( + "http://127.0.0.1:13712/callback?code=auth-code&state=$state", + ) + LoginMode.RETRY -> BangumiPasswordLoginStep.Retry( + "验证码错误,请返回重试。", + byteArrayOf(4), + "image/gif", + ) + } + } + } + + private class OAuthClient(override val isConfigured: Boolean) : BangumiOAuthClientApi { + override val clientId: String = "test-id" + override fun configureProxy(proxyConfig: BangumiHttpProxyConfig) = Unit + override suspend fun exchangeCode(code: String, callbackUrl: String): Result = + Result.success(BangumiOAuthTokens("access-1", "refresh-1", 9_999_999_999L, 7L)) + override suspend fun refresh(refreshToken: String, callbackUrl: String): Result = + Result.success(BangumiOAuthTokens("access-2", "refresh-2", 9_999_999_999L, 7L)) + } + + private class Credentials : AppCredentialStore { + override var cloudDriveToken: String? = null + override var cloudDrivePassword: String? = null + override fun clearCloudDriveCredentials() { + cloudDriveToken = null + cloudDrivePassword = null + } + override var bangumiAccessToken: String? = null + override var bangumiRefreshToken: String? = null + override var bangumiTokenExpiresAtMillis: Long = 0L + override var tmdbAccessToken: String? = null + override var tmdbApiBaseUrlOverride: String? = null + override var otlpAccessToken: String? = null + override fun clearBangumiToken() { + bangumiAccessToken = null + bangumiRefreshToken = null + bangumiTokenExpiresAtMillis = 0L + } + override fun clearTmdbToken() { + tmdbAccessToken = null + tmdbApiBaseUrlOverride = null + } + override fun clearOtlpAccessToken() { + otlpAccessToken = null + } + } +} diff --git a/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt index 3aeab2d7..85b4aeb4 100644 --- a/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt +++ b/web-control-core/src/test/kotlin/com/miruplay/tv/webcontrol/WebControlSettingsRouteTest.kt @@ -11,6 +11,7 @@ import java.io.Closeable import java.io.InputStream import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Test @@ -193,6 +194,35 @@ class WebControlSettingsRouteTest { assertTrue(service.rotateCalled) } + @Test + fun `bangumi web login routes accept credentials and do not echo the password`() { + val service = SettingsStubService() + val server = NanoHttpWebControlServer( + webControlService = service, + webControlAccess = EnabledAccess, + staticAssets = WebControlStaticAssets { null }, + ) + val password = "s3cret-token-value" + + val start = server.serve(session(method = NanoHTTPD.Method.POST, uri = "/api/metadata/bangumi-login/start", body = "")) + assertEquals(NanoHTTPD.Response.Status.OK, start.status) + assertTrue(start.bodyText().contains("\"status\":\"challenge\"")) + + val submit = server.serve( + session( + method = NanoHTTPD.Method.POST, + uri = "/api/metadata/bangumi-login", + body = """{"email":"user@example.com","password":"$password","captcha":"abcd"}""", + ), + ) + assertEquals(NanoHTTPD.Response.Status.OK, submit.status) + val body = submit.bodyText() + assertTrue(body.contains("\"status\":\"success\"")) + assertFalse(body.contains(password)) + assertEquals("user@example.com", service.capturedBangumiLogin?.email) + assertEquals(password, service.capturedBangumiLogin?.password) + } + @Test fun `tmdb token routes save and clear`() { val service = SettingsStubService() @@ -297,6 +327,7 @@ class WebControlSettingsRouteTest { var capturedScan: ScanSettingsRequest? = null var capturedPlayback: PlaybackSettingsRequest? = null var capturedTmdbToken: String? = null + var capturedBangumiLogin: BangumiWebLoginRequest? = null var capturedAppControlAction: String? = null var capturedLocale: String? = null var tmdbCleared = false @@ -362,6 +393,14 @@ class WebControlSettingsRouteTest { return getMetadataSettings() } + override suspend fun startBangumiWebLogin(): BangumiWebLoginDto = + BangumiWebLoginDto(status = "challenge", captchaImage = "data:image/gif;base64,QQ==") + + override suspend fun submitBangumiWebLogin(request: BangumiWebLoginRequest): BangumiWebLoginDto { + capturedBangumiLogin = request + return BangumiWebLoginDto(status = "success", message = "Bangumi 登录成功。", tokenConfigured = true) + } + override suspend fun clearTmdbToken(): MetadataSettingsDto { tmdbCleared = true return MetadataSettingsDto(bangumiTokenConfigured = false, tmdbTokenConfigured = false) diff --git a/web-control/frontend/src/App.vue b/web-control/frontend/src/App.vue index a7b0e494..842c8074 100644 --- a/web-control/frontend/src/App.vue +++ b/web-control/frontend/src/App.vue @@ -572,6 +572,68 @@