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
8 changes: 8 additions & 0 deletions apps/ios/Cook/App/RootView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ struct RootView: View {
@Query(filter: #Predicate<FridgeItem> { $0.deletedAt == nil }) private var fridgeItems: [FridgeItem]
@Query private var preferenceRecords: [Preferences]
@Environment(CookSession.self) private var session
@Environment(YunlefunAccountStore.self) private var accounts
@AppStorage(FridgeReminder.enabledKey) private var remindersEnabled = false
@AppStorage(FridgeReminder.timeKey) private var reminderMinutes = FridgeReminder.defaultMinutes
@Environment(FeedbackClient.self) private var feedback
Expand Down Expand Up @@ -45,11 +46,18 @@ struct RootView: View {
.minimizesTabBarOnScroll()
.environment(router)
.onOpenURL { url in
if accounts.handleWeChat(url) { return }
if accounts.handleYunlefunCallback(url) { return }
if router.openUniversalLink(url) {
// Never log query parameters, which may contain authorization codes.
Logger(subsystem: "fun.yunle.cook", category: "UniversalLink").notice("Opened account area from WeChat universal link")
}
}
.onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { activity in
if accounts.handleWeChat(activity) { return }
guard let url = activity.webpageURL, !accounts.handleYunlefunCallback(url) else { return }
router.openUniversalLink(url)
}
.modifier(PrivateRecipeDeletionSync())
.onChange(of: preferenceRecords.map(\.snapshot), initial: true) {
session.refreshPreferences()
Expand Down
2 changes: 1 addition & 1 deletion apps/ios/Cook/Model/CookFeatures.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ enum CookFeatures {
static var membershipPurchasesEnabled: Bool {
Bundle.main.object(forInfoDictionaryKey: "CookMembershipPurchasesEnabled") as? String == "YES"
}
/// Reserved for the future native WeChat entry, not Yunlefun web sign-in or link handling.
/// Controls the native WeChat entry; the existing Yunlefun login remains available.
/// Only an explicit YES enables it; missing or unresolved build settings stay disabled.
static var weChatLoginEnabled: Bool {
Bundle.main.object(forInfoDictionaryKey: "CookWeChatLoginEnabled") as? String == "YES"
Expand Down
4 changes: 2 additions & 2 deletions apps/ios/Cook/Model/CookUniversalLink.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import Foundation

enum CookUniversalLink {
/// The registered WeChat link namespace only opens the account area for now.
/// SDK callbacks must later be verified by OpenSDK and the server before changing a session.
/// The registered WeChat link namespace is also used by the account-area fallback.
/// A link without a matching OpenSDK response never changes a session.
static func isWeChatLink(_ url: URL) -> Bool {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
components.scheme?.lowercased() == "https",
Expand Down
132 changes: 132 additions & 0 deletions apps/ios/Cook/Model/WeChatAuthorization.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import Foundation
import UIKit

enum WeChatAccountError: LocalizedError {
case unavailable, authorizationFailed, bindingRequired, alreadyBound, accountRestricted
case phoneVerificationRequired, identityUnverified, rateLimited

var errorDescription: String? {
switch self {
case .unavailable: return "微信登录暂不可用,请使用云乐坊账号登录。"
case .authorizationFailed: return "微信授权未完成,请重试。"
case .bindingRequired: return "此微信尚未关联云食册。请先登录原来的云乐坊账号,再到账号详情绑定。"
case .alreadyBound: return "当前账号已绑定微信,或此微信已被绑定。请检查账号绑定状态。"
case .accountRestricted: return "此云乐坊账号暂不可用,请在云乐坊网站检查账号状态。"
case .phoneVerificationRequired: return "请先在云乐坊网站验证手机号,再使用微信登录。"
case .identityUnverified: return "无法确认此微信与云乐坊账号的关联,请使用原来的登录方式。"
case .rateLimited: return "操作过于频繁,请稍后重新发起微信授权。"
}
}
}

@MainActor
protocol WeChatAuthorizing {
var isAvailable: Bool { get }
func authorize() async throws -> String
func handle(_ url: URL) -> Bool
func handle(_ activity: NSUserActivity) -> Bool
}

/// WeChat sends results through OpenSDK. A URL alone never supplies a code to CloudBase.
@MainActor
final class WeChatAuthorization: WeChatAuthorizing {
struct Driver {
// Checking the URL scheme does not initialize OpenSDK before consent.
var isInstalled: @MainActor () -> Bool = {
CookWeChatBridge.isLinked() && UIApplication.shared.canOpenURL(URL(string: "weixin://")!)
}
var register: (String, String) -> Bool = { CookWeChatBridge.prepare(appID: $0, universalLink: $1) }
var send: (String, @escaping @Sendable (Bool) -> Void) -> Void = { CookWeChatBridge.sendAuth(state: $0, completion: $1) }
var handleURL: (URL, @escaping CookWeChatResponse) -> Bool = { CookWeChatBridge.handle(url: $0, response: $1) }
var handleActivity: (NSUserActivity, @escaping CookWeChatResponse) -> Bool = { CookWeChatBridge.handle(activity: $0, response: $1) }
}

static let appID = "wxce6c7405dd756b9d"
static let universalLink = "https://cook.yunyoujun.cn/auth/wechat/"
private let enabled: Bool
private let driver: Driver
private var registered = false
private var pending: (state: String, deadline: ContinuousClock.Instant, reply: CheckedContinuation<String, Error>)?
private var timeout: Task<Void, Never>?

init(enabled: Bool, driver: Driver? = nil) {
self.enabled = enabled
self.driver = driver ?? Driver()
}

var isAvailable: Bool {
enabled && driver.isInstalled()
}

private func prepare() -> Bool {
guard isAvailable else { return false }
if !registered {
registered = driver.register(Self.appID, Self.universalLink)
}
return registered
}

func authorize() async throws -> String {
guard pending == nil, prepare() else { throw WeChatAccountError.unavailable }
let state = try YunlefunSSO.randomToken()
return try await withTaskCancellationHandler {
try Task.checkCancellation()
return try await withCheckedThrowingContinuation { reply in
pending = (state, .now.advanced(by: .seconds(180)), reply)
timeout = Task { [weak self] in
do { try await Task.sleep(for: .seconds(180)) } catch { return }
self?.finish(.failure(WeChatAccountError.authorizationFailed), state: state)
}
driver.send(state) { [weak self] sent in
guard !sent else { return }
Task { @MainActor in self?.finish(.failure(WeChatAccountError.unavailable), state: state) }
}
}
} onCancel: {
Task { @MainActor in self.finish(.failure(CancellationError()), state: state) }
}
}

func handle(_ url: URL) -> Bool {
guard pending != nil else { return false }
if CookUniversalLink.isWeChatLink(url) {
let activity = NSUserActivity(activityType: NSUserActivityTypeBrowsingWeb)
activity.webpageURL = url
return handle(activity)
}
guard url.scheme?.lowercased() == Self.appID else { return false }
return driver.handleURL(url, response)
}

func handle(_ activity: NSUserActivity) -> Bool {
guard pending != nil, activity.activityType == NSUserActivityTypeBrowsingWeb,
let url = activity.webpageURL, CookUniversalLink.isWeChatLink(url) else { return false }
return driver.handleActivity(activity, response)
}

private var response: CookWeChatResponse {
{ [weak self] status, state, code in
guard let state, !state.isEmpty else { return }
Task { @MainActor in
self?.finish(Result { try Self.validatedCode(status: status, code: code) }, state: state)
}
}
}

nonisolated static func validatedCode(status: Int, code: String?) throws -> String {
if status == -2 || status == -4 { throw CancellationError() }
guard status == 0, let code, (1...512).contains(code.utf8.count),
code.utf8.allSatisfy({ (48...57).contains($0) || (65...90).contains($0)
|| (97...122).contains($0) || $0 == 45 || $0 == 95 })
else { throw WeChatAccountError.authorizationFailed }
return code
}

private func finish(_ result: Result<String, Error>, state: String) {
guard let pending, pending.state == state else { return }
self.pending = nil
timeout?.cancel()
timeout = nil
pending.reply.resume(with: .now < pending.deadline ? result : .failure(WeChatAccountError.authorizationFailed))
}
}
66 changes: 61 additions & 5 deletions apps/ios/Cook/Model/YunlefunAccountService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,25 @@ protocol YunlefunAccountServing {
func refresh(_ credential: YunlefunCredential) async throws -> YunlefunCredential
func account(_ credential: YunlefunCredential) async throws -> YunlefunAccount
func signOut(_ credential: YunlefunCredential) async throws
func signInWithWeChat(code: String, deviceID: String) async throws -> YunlefunCredential
func bindWeChat(code: String, credential: YunlefunCredential) async throws
}

extension YunlefunAccountServing {
func signInWithWeChat(code: String, deviceID: String) async throws -> YunlefunCredential {
throw WeChatAccountError.unavailable
}
func bindWeChat(code: String, credential: YunlefunCredential) async throws {
throw WeChatAccountError.unavailable
}
}

/// 仅访问固定 HTTPS 端点,不接收重定向,不共享 Cookie,也不记录凭据。
struct YunlefunAccountService: YunlefunAccountServing {
typealias Transport = @Sendable (URLRequest) async throws -> (Data, URLResponse)
static let gateway = "https://yunlefun-8g7ybcxc7345c490.api.tcloudbasegateway.com/auth/v1/"
private static let ticketURL = URL(string: "https://api.yunle.fun/sso-ticket")!
private static let cookOrigin = "https://cook.yunyoujun.cn"
private static let logger = Logger(subsystem: "fun.yunle.cook", category: "account")
private let transport: Transport

Expand All @@ -88,8 +101,7 @@ struct YunlefunAccountService: YunlefunAccountServing {
}

func signIn(fields: [String: String], deviceID: String) async throws -> YunlefunCredential {
let data = try await request(URL(string: "https://api.yunle.fun/sso-ticket")!, fields: fields,
origin: "https://cook.yunyoujun.cn")
let data = try await request(Self.ticketURL, fields: fields, origin: Self.cookOrigin)
guard let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
payload["ok"] as? Bool == true, let ticket = payload["ticket"] as? String, !ticket.isEmpty,
["access_token", "refresh_token", "session"].allSatisfy({ payload[$0] == nil }) else {
Expand All @@ -105,6 +117,35 @@ struct YunlefunAccountService: YunlefunAccountServing {
return next
}

func signInWithWeChat(code: String, deviceID: String) async throws -> YunlefunCredential {
let data = try await request(Self.ticketURL, fields: [
"action": "exchangeCookWeChatCode", "clientId": YunlefunSSO.clientID, "code": code,
], origin: Self.cookOrigin, weChat: true)
guard let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
Set(payload.keys) == ["ok", "ticket", "subject"],
payload["ok"] as? Bool == true, let ticket = payload["ticket"] as? String,
!ticket.isEmpty, ticket.utf8.count <= 32_768,
let subject = payload["subject"] as? String, !subject.isEmpty else {
throw YunlefunAccountError.invalidResponse
}
let credential = try await token("signin/custom", fields: ["provider_id": "custom", "ticket": ticket], deviceID: deviceID)
guard credential.subject == subject else {
try? await signOut(credential)
throw YunlefunAccountError.invalidResponse
}
return credential
}

func bindWeChat(code: String, credential: YunlefunCredential) async throws {
let data = try await request(Self.ticketURL, fields: [
"action": "bindCookWeChat", "clientId": YunlefunSSO.clientID, "code": code,
], credential: credential, origin: Self.cookOrigin, weChat: true)
guard let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
Set(payload.keys) == ["ok"], payload["ok"] as? Bool == true else {
throw YunlefunAccountError.invalidResponse
}
}

func account(_ credential: YunlefunCredential) async throws -> YunlefunAccount {
let data = try await request(URL(string: "\(Self.gateway)user/me")!, method: "GET", credential: credential)
guard let user = try? JSONDecoder().decode(YunlefunAccount.self, from: data) else {
Expand Down Expand Up @@ -136,7 +177,8 @@ struct YunlefunAccountService: YunlefunAccountServing {
}

private func request(_ url: URL, method: String = "POST", fields: [String: String]? = nil,
credential: YunlefunCredential? = nil, deviceID: String? = nil, origin: String? = nil) async throws -> Data {
credential: YunlefunCredential? = nil, deviceID: String? = nil, origin: String? = nil,
weChat: Bool = false) async throws -> Data {
var request = URLRequest(url: url)
request.httpMethod = method
request.cachePolicy = .reloadIgnoringLocalCacheData
Expand All @@ -150,11 +192,25 @@ struct YunlefunAccountService: YunlefunAccountServing {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
let (data, response) = try await transport(request)
guard let http = response as? HTTPURLResponse, data.count < 256 * 1024 else { throw YunlefunAccountError.invalidResponse }
guard let http = response as? HTTPURLResponse, http.url == url,
data.count < 256 * 1024 else { throw YunlefunAccountError.invalidResponse }
guard (200..<300).contains(http.statusCode) else {
let failure = try? JSONDecoder().decode(ServiceFailure.self, from: data)
// Only a fixed endpoint path and HTTP code; never log response bodies, tokens or user identifiers.
Self.logger.error("Account endpoint \(url.path, privacy: .public) returned HTTP \(http.statusCode)")
if weChat {
switch failure?.reason {
case "wechat_binding_required": throw WeChatAccountError.bindingRequired
case "binding_conflict": throw WeChatAccountError.alreadyBound
case "account_restricted": throw WeChatAccountError.accountRestricted
case "phone_verification_required": throw WeChatAccountError.phoneVerificationRequired
case "wechat_identity_unverified": throw WeChatAccountError.identityUnverified
case "wechat_code_invalid": throw WeChatAccountError.authorizationFailed
case "not_authenticated": throw YunlefunAccountError.expiredSession
case "rate_limited": throw WeChatAccountError.rateLimited
default: throw WeChatAccountError.unavailable
}
}
if http.statusCode == 401 || ["invalid_grant", "invalid_token", "unauthenticated", "user_not_found", "user_disabled"].contains(failure?.error ?? "") {
throw YunlefunAccountError.expiredSession
}
Expand All @@ -172,7 +228,7 @@ struct YunlefunAccountService: YunlefunAccountServing {
case accessToken = "access_token", refreshToken = "refresh_token", subject = "sub", expiresIn = "expires_in"
}
}
private struct ServiceFailure: Decodable { let error: String? }
private struct ServiceFailure: Decodable { let error: String?; let reason: String? }
}

private final class AccountRedirectPolicy: NSObject, URLSessionTaskDelegate {
Expand Down
Loading
Loading