Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package io.github.personal.momoflow

import android.content.Context
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.util.Base64
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.spec.GCMParameterSpec

/**
* Cortex access token is separate from the Open API token. Do not persist the
* legacy token supplied to exchangeLegacyToken(), or put secrets in preferences.
*/
class CortexCredentialStore(context: Context) {
private val prefs = context.getSharedPreferences("momoflow_cortex_secret", Context.MODE_PRIVATE)
private val alias = "momoflow_cortex_access_v1"
private val flags = Base64.NO_WRAP

fun saveAccessToken(token: String) {
require(token.isNotBlank())
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
if (!ks.containsAlias(alias)) {
val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
generator.init(KeyGenParameterSpec.Builder(
alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
).setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256).build())
generator.generateKey()
}
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.ENCRYPT_MODE, ks.getKey(alias, null))
val ciphertext = cipher.doFinal(token.trim().toByteArray(Charsets.UTF_8))
check(prefs.edit()
.putString("iv", Base64.encodeToString(cipher.iv, flags))
.putString("ciphertext", Base64.encodeToString(ciphertext, flags))
.commit()) { "Cortex 凭证未能安全保存" }
}

fun accessToken(): String? {
val iv = prefs.getString("iv", null) ?: return null
val ciphertext = prefs.getString("ciphertext", null) ?: return null
return try {
val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
cipher.init(Cipher.DECRYPT_MODE, ks.getKey(alias, null),
GCMParameterSpec(128, Base64.decode(iv, flags)))
String(cipher.doFinal(Base64.decode(ciphertext, flags)), Charsets.UTF_8)
} catch (_: Exception) {
null
}
}

fun clear() {
check(prefs.edit().clear().commit()) { "Cortex 凭证清除失败" }
}
}
116 changes: 116 additions & 0 deletions app/src/main/java/io/github/personal/momoflow/CortexFeedbackLedger.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package io.github.personal.momoflow

import android.content.Context
import org.json.JSONObject
import java.security.MessageDigest
import java.util.UUID

/** Three states shown to users, regardless of whether transport was foreground or Cortex. */
enum class FeedbackOutcome(val label: String) {
PENDING("待确认"), SUCCEEDED("已成功"), FAILED("已失败")
}

object FeedbackOutcomePolicy {
fun fromOfficialReadback(status: OfficialSyncStatus): FeedbackOutcome = when (status) {
OfficialSyncStatus.OBSERVED_MATCH -> FeedbackOutcome.SUCCEEDED
OfficialSyncStatus.CONFLICT, OfficialSyncStatus.INVALID_WORD -> FeedbackOutcome.FAILED
else -> FeedbackOutcome.PENDING
}
}

data class FeedbackOperation(
val id: String,
val vocId: String,
val mark: LocalMark,
val day: String,
val accountDigest: String,
val outcome: FeedbackOutcome,
val explanation: String,
) {
fun toJson(): JSONObject = JSONObject()
.put("id", id).put("voc_id", vocId).put("mark", mark.wire)
.put("day", day).put("account_digest", accountDigest)
.put("outcome", outcome.name).put("explanation", explanation)

companion object {
fun parse(o: JSONObject) = FeedbackOperation(
o.getString("id"), o.getString("voc_id"),
LocalMark.entries.first { it.wire == o.getString("mark") },
o.getString("day"), o.getString("account_digest"),
FeedbackOutcome.valueOf(o.getString("outcome")),
o.optString("explanation"),
)
}
}

/**
* Committed before the user leaves for a foreground action. A pending item
* survives process death; it is never silently treated as a successful write.
* Transaction records contain no Bearer token, cookies or passwords.
*/
class CortexFeedbackLedger(context: Context) {
private val prefs = context.getSharedPreferences("momoflow_cortex_ledger", Context.MODE_PRIVATE)

private fun digest(token: String): String =
MessageDigest.getInstance("SHA-256")
.digest(token.toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it.toInt() and 0xff) }

private fun key(vocId: String): String = "operation." + MessageDigest.getInstance("SHA-256")
.digest(vocId.toByteArray(Charsets.UTF_8))
.joinToString("") { "%02x".format(it.toInt() and 0xff) }

@Synchronized
fun current(vocId: String, openApiToken: String): FeedbackOperation? = try {
prefs.getString(key(vocId), null)?.let { FeedbackOperation.parse(JSONObject(it)) }
?.takeIf { it.accountDigest == digest(openApiToken) && it.day == StudyDay.today() }
} catch (_: Exception) { null }

/**
* A second notification tap does not mint another operation while the
* original is unresolved; a different mark must be cancelled first.
*/
@Synchronized
fun begin(vocId: String, mark: LocalMark, openApiToken: String): FeedbackOperation {
val existing = current(vocId, openApiToken)
check(existing?.outcome != FeedbackOutcome.PENDING) {
"该单词已有待确认反馈,请先核验或取消,不能重复发起"
}
val operation = FeedbackOperation(
UUID.randomUUID().toString(), vocId, mark, StudyDay.today(),
digest(openApiToken), FeedbackOutcome.PENDING, "已建立基线,等待墨墨官方记录回读"
)
check(prefs.edit().putString(key(vocId), operation.toJson().toString()).commit()) {
"无法保存反馈事务,未执行任何操作"
}
return operation
}

@Synchronized
fun recordReadback(
vocId: String, openApiToken: String,
status: OfficialSyncStatus, explanation: String
): FeedbackOperation? {
val existing = current(vocId, openApiToken) ?: return null
if (existing.outcome != FeedbackOutcome.PENDING) return existing
val updated = existing.copy(
outcome = FeedbackOutcomePolicy.fromOfficialReadback(status),
explanation = explanation.take(800)
)
check(prefs.edit().putString(key(vocId), updated.toJson().toString()).commit())
return updated
}

@Synchronized
fun clear() {
check(prefs.edit().clear().commit()) { "无法清理旧账号的 Cortex 反馈事务" }
}

@Synchronized
fun cancel(vocId: String, openApiToken: String) {
val existing = current(vocId, openApiToken) ?: return
if (existing.outcome != FeedbackOutcome.PENDING) return
val updated = existing.copy(outcome = FeedbackOutcome.FAILED, explanation = "操作已取消,未确认服务端反馈")
check(prefs.edit().putString(key(vocId), updated.toJson().toString()).commit())
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package io.github.personal.momoflow

import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL

/**
* Isolated Cortex HTTP boundary, based on the supplied 5.6.10 gateway evidence.
* Only verified read endpoints and explicit legacy-token exchange are exposed.
* The speculative protobuf uplink is intentionally NOT available here.
*/
class CortexGatewayService {
private val origin = "https://cortex.maimemo.com/cortex"

fun exchangeLegacyToken(legacyToken: String): String {
require(legacyToken.isNotBlank()) { "旧版登录 Token 不能为空" }
val result = request("POST", "/api/v1/tokens/exchange", null,
JSONObject().put("legacy_token", legacyToken.trim()))
val payload = result.optJSONObject("data") ?: result
val tokens = payload.optJSONObject("tokens") ?: payload
val access = tokens.optString("access_token").ifBlank {
tokens.optString("accessToken")
}
if (access.isBlank()) throw ApiException("Cortex 换取接口未返回 access_token;未保存凭证")
return access
}

/** Unmodified server JSON: callers must not assume a checkpoint field's shape. */
fun checkpoints(accessToken: String): JSONObject =
request("GET", "/api/v1/study/checkpoints", accessToken)

/** Aggregate-only read, never treated as per-word feedback confirmation. */
fun overview(accessToken: String): JSONObject =
request("GET", "/api/v1/study/overview", accessToken)

private fun request(
method: String, path: String, accessToken: String?,
payload: JSONObject? = null
): JSONObject {
require(path in setOf(
"/api/v1/tokens/exchange", "/api/v1/study/checkpoints", "/api/v1/study/overview"
)) { "未登记的 Cortex 端点" }
if (method == "GET") require(!accessToken.isNullOrBlank())
val connection = (URL(origin + path).openConnection() as HttpURLConnection)
try {
connection.requestMethod = method
connection.instanceFollowRedirects = false // never forward credentials
connection.connectTimeout = 10_000
connection.readTimeout = 15_000
connection.setRequestProperty("Accept", "application/json")
if (!accessToken.isNullOrBlank())
connection.setRequestProperty("Authorization", "Bearer ${accessToken.trim()}")
if (payload != null) {
connection.doOutput = true
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8")
connection.outputStream.use {
it.write(payload.toString().toByteArray(Charsets.UTF_8))
}
}
val status = connection.responseCode
if (status == 401 || status == 403) throw ApiException("Cortex 身份验证失败(HTTP $status)")
if (status == 429) throw ApiException("Cortex 请求过于频繁,请稍后再试")
if (status !in 200..299) throw ApiException("Cortex 接口返回 HTTP $status")
val raw = connection.inputStream.use { input ->
val bytes = input.readBytes()
if (bytes.size > 512 * 1024) throw ApiException("Cortex 响应过大")
bytes.toString(Charsets.UTF_8)
}
val json = try { JSONObject(raw) }
catch (_: Exception) { throw ApiException("Cortex 响应不是有效 JSON") }
if (json.has("success") && !json.optBoolean("success", true))
throw ApiException("Cortex 服务端表示请求失败")
return json
} catch (e: ApiException) {
throw e
} catch (_: Exception) {
// Never expose request URLs with query parameters, headers, or tokens.
throw ApiException("Cortex 网络连接异常,请检查网络与账号会话")
} finally {
connection.disconnect()
}
}
}
Loading
Loading