diff --git a/apps/ios/Cook/App/RootView.swift b/apps/ios/Cook/App/RootView.swift index 41c4fbb21..9cc1a75f0 100644 --- a/apps/ios/Cook/App/RootView.swift +++ b/apps/ios/Cook/App/RootView.swift @@ -17,6 +17,7 @@ struct RootView: View { @Query(filter: #Predicate { $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 @@ -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() diff --git a/apps/ios/Cook/Model/CookFeatures.swift b/apps/ios/Cook/Model/CookFeatures.swift index c8c962680..22e924e63 100644 --- a/apps/ios/Cook/Model/CookFeatures.swift +++ b/apps/ios/Cook/Model/CookFeatures.swift @@ -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" diff --git a/apps/ios/Cook/Model/CookUniversalLink.swift b/apps/ios/Cook/Model/CookUniversalLink.swift index ef77fc07b..1d9e3eb82 100644 --- a/apps/ios/Cook/Model/CookUniversalLink.swift +++ b/apps/ios/Cook/Model/CookUniversalLink.swift @@ -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", diff --git a/apps/ios/Cook/Model/WeChatAuthorization.swift b/apps/ios/Cook/Model/WeChatAuthorization.swift new file mode 100644 index 000000000..e8ec56869 --- /dev/null +++ b/apps/ios/Cook/Model/WeChatAuthorization.swift @@ -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)? + private var timeout: Task? + + 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, 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)) + } +} diff --git a/apps/ios/Cook/Model/YunlefunAccountService.swift b/apps/ios/Cook/Model/YunlefunAccountService.swift index 0dcc63f38..78523f4fa 100644 --- a/apps/ios/Cook/Model/YunlefunAccountService.swift +++ b/apps/ios/Cook/Model/YunlefunAccountService.swift @@ -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 @@ -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 { @@ -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 { @@ -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 @@ -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 } @@ -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 { diff --git a/apps/ios/Cook/Model/YunlefunAccountStore.swift b/apps/ios/Cook/Model/YunlefunAccountStore.swift index 569f424a9..7f1d533a3 100644 --- a/apps/ios/Cook/Model/YunlefunAccountStore.swift +++ b/apps/ios/Cook/Model/YunlefunAccountStore.swift @@ -10,22 +10,34 @@ final class YunlefunAccountStore { private(set) var canRetry = false private(set) var sessionRevision = UUID() private(set) var offlineSubject: String? + private(set) var weChatBindingMessage: String? @ObservationIgnored private let service: YunlefunAccountServing @ObservationIgnored private let vault: YunlefunAccountVault @ObservationIgnored private let authorization: YunlefunAuthorizing + @ObservationIgnored private let weChat: WeChatAuthorizing + @ObservationIgnored private let appAuthorization: YunlefunAppAuthorization @ObservationIgnored private var credential: YunlefunCredential? @ObservationIgnored private var didRestore = false /// A previously verified session may keep its own offline library visible. /// Sign-out/invalid credentials clear this identity before any async work. var dataAccountID: String? { account?.id ?? offlineSubject } + var canUseWeChat: Bool { weChat.isAvailable } + var isAwaitingYunlefunApp: Bool { appAuthorization.isWaiting } init(service: YunlefunAccountServing? = nil, vault: YunlefunAccountVault? = nil, - authorization: YunlefunAuthorizing? = nil) { + authorization: YunlefunAuthorizing? = nil, + weChat: WeChatAuthorizing? = nil, + appAuthorization: YunlefunAppAuthorization? = nil) { self.service = service ?? YunlefunAccountService() self.vault = vault ?? KeychainYunlefunAccountVault() self.authorization = authorization ?? SystemYunlefunAuthorization() + self.weChat = weChat ?? WeChatAuthorization(enabled: CookFeatures.weChatLoginEnabled) + // Tests that provide their own browser must never launch another app. + self.appAuthorization = appAuthorization ?? (authorization == nil + ? YunlefunAppAuthorization() + : YunlefunAppAuthorization(openApp: { _ in false })) } func restore() async { @@ -62,18 +74,67 @@ final class YunlefunAccountStore { } func signIn() async { + await completeSignIn { + let fields: [String: String] + switch try await appAuthorization.authorize(YunlefunSSO()) { + case .authorized(let approvedFields): + fields = approvedFields + case .useWeb: + // Start a new transaction after the app attempt has been invalidated. + try Task.checkCancellation() + let transaction = try YunlefunSSO() + let callback = try await authorization.authorize(transaction) + fields = try transaction.exchangeFields(callback: callback) + } + try Task.checkCancellation() + return try await self.service.signIn(fields: fields, deviceID: UUID().uuidString) + } + } + + func signInWithWeChat() async { + await completeSignIn { + let code = try await self.weChat.authorize() + try Task.checkCancellation() + return try await self.service.signInWithWeChat(code: code, deviceID: UUID().uuidString) + } + } + + func handleWeChat(_ url: URL) -> Bool { weChat.handle(url) } + func handleWeChat(_ activity: NSUserActivity) -> Bool { weChat.handle(activity) } + + func bindWeChat() async { + guard !isBusy, let current = credential, account?.id == current.subject else { return } + isBusy = true + message = nil + weChatBindingMessage = nil + defer { isBusy = false } + do { + guard current.expiresAt.timeIntervalSinceNow > 60 else { + throw YunlefunAccountError.expiredSession + } + let code = try await weChat.authorize() + try Task.checkCancellation() + guard current.expiresAt > Date() else { throw YunlefunAccountError.expiredSession } + // Yunlefun atomically checks both sides of the binding against the current session. + try await service.bindWeChat(code: code, credential: current) + weChatBindingMessage = "已将微信绑定到当前云乐坊账号。" + } catch is CancellationError { + // Closing WeChat leaves the active account intact. + } catch { + message = errorMessage(error) + } + } + + private func completeSignIn(_ nextCredential: () async throws -> YunlefunCredential) async { guard !isBusy else { return } isBusy = true message = nil + weChatBindingMessage = nil let previousCanRetry = canRetry canRetry = false defer { isBusy = false } do { - let transaction = try YunlefunSSO() - let callback = try await authorization.authorize(transaction) - try Task.checkCancellation() - let fields = try transaction.exchangeFields(callback: callback) - let next = try await service.signIn(fields: fields, deviceID: UUID().uuidString) + let next = try await nextCredential() let user = try await service.account(next) try Task.checkCancellation() try vault.save(next) @@ -90,6 +151,10 @@ final class YunlefunAccountStore { } } + func handleYunlefunCallback(_ url: URL) -> Bool { appAuthorization.handle(url) } + func continueYunlefunOnWeb() { appAuthorization.useWeb() } + func cancelYunlefunAppAuthorization() { appAuthorization.cancel() } + func retry() async { await refreshSession() } func signOut() async { @@ -104,6 +169,7 @@ final class YunlefunAccountStore { account = nil sessionRevision = UUID() message = nil + weChatBindingMessage = nil canRetry = false if let previous { do { try await service.signOut(previous) } @@ -162,6 +228,8 @@ final class YunlefunAccountStore { } private func errorMessage(_ error: Error) -> String { - (error as? YunlefunAccountError)?.localizedDescription ?? "暂时无法连接云乐坊,请检查网络后重试。" + (error as? WeChatAccountError)?.localizedDescription + ?? (error as? YunlefunAccountError)?.localizedDescription + ?? "暂时无法连接云乐坊,请检查网络后重试。" } } diff --git a/apps/ios/Cook/Model/YunlefunAppAuthorization.swift b/apps/ios/Cook/Model/YunlefunAppAuthorization.swift new file mode 100644 index 000000000..4fd75b41d --- /dev/null +++ b/apps/ios/Cook/Model/YunlefunAppAuthorization.swift @@ -0,0 +1,84 @@ +import Foundation +import Observation +import UIKit + +/// Holds the cross-app transaction only while Cook is running. +@MainActor @Observable +final class YunlefunAppAuthorization { + enum Outcome { + case authorized([String: String]) + case useWeb + } + + typealias OpenApp = @MainActor (URL) async -> Bool + + private(set) var isWaiting = false + @ObservationIgnored private let openApp: OpenApp + @ObservationIgnored private var pending: (transaction: YunlefunSSO, continuation: CheckedContinuation)? + @ObservationIgnored private var timeout: Task? + @ObservationIgnored private var opening: Task? + + init(openApp: @escaping OpenApp = { await UIApplication.shared.open($0, options: [.universalLinksOnly: true]) }) { + self.openApp = openApp + } + + func authorize(_ transaction: YunlefunSSO) async throws -> Outcome { + guard pending == nil else { throw YunlefunAccountError.unavailable } + let nonce = transaction.nonce + return try await withTaskCancellationHandler { + try Task.checkCancellation() + return try await withCheckedThrowingContinuation { continuation in + pending = (transaction, continuation) + opening = Task { [weak self, openApp] in + guard !Task.isCancelled else { return } + let opened = await openApp(transaction.appAuthorizationURL) + guard let self, self.pending?.transaction.nonce == nonce else { return } + if opened { self.isWaiting = true } + else { self.finish(.success(.useWeb), nonce: nonce) } + } + timeout = Task { [weak self] in + do { try await Task.sleep(for: .seconds(YunlefunSSO.lifetime)) } + catch { return } + self?.finish(.failure(YunlefunAccountError.invalidCallback), nonce: nonce) + } + } + } onCancel: { + Task { @MainActor in self.finish(.failure(CancellationError()), nonce: nonce) } + } + } + + /// Only a valid callback for the pending transaction can finish the attempt. + @discardableResult + func handle(_ url: URL) -> Bool { + guard YunlefunSSO.isCallback(url) else { return false } + guard let pending, let result = try? pending.transaction.callbackResult(url) else { return true } + let nonce = pending.transaction.nonce + switch result { + case .authorized(let fields): finish(.success(.authorized(fields)), nonce: nonce) + case .denied: finish(.failure(CancellationError()), nonce: nonce) + case .selectAccountOnWeb: finish(.success(.useWeb), nonce: nonce) + } + return true + } + + func useWeb() { + guard isWaiting, let nonce = pending?.transaction.nonce else { return } + finish(.success(.useWeb), nonce: nonce) + } + + func cancel() { + guard let nonce = pending?.transaction.nonce else { return } + finish(.failure(CancellationError()), nonce: nonce) + } + + private func finish(_ result: Result, nonce: String) { + guard let pending, pending.transaction.nonce == nonce else { return } + self.pending = nil + isWaiting = false + opening?.cancel() + opening = nil + timeout?.cancel() + timeout = nil + pending.continuation.resume(with: result) + } +} diff --git a/apps/ios/Cook/Model/YunlefunAuthorization.swift b/apps/ios/Cook/Model/YunlefunAuthorization.swift index aedf6e74a..2ab2aa76e 100644 --- a/apps/ios/Cook/Model/YunlefunAuthorization.swift +++ b/apps/ios/Cook/Model/YunlefunAuthorization.swift @@ -19,9 +19,12 @@ final class SystemYunlefunAuthorization: NSObject, YunlefunAuthorizing, ASWebAut func authorize(_ transaction: YunlefunSSO) async throws -> URL { guard #available(iOS 17.4, *) else { throw YunlefunAccountError.requiresUpdate } - guard session == nil, - let window = UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }) - .filter({ $0.activationState == .foregroundActive }).flatMap(\.windows).first(where: \.isKeyWindow) else { + guard session == nil else { throw YunlefunAccountError.unavailable } + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + // A return link can arrive just before the scene finishes becoming active. + let window = scenes.first { $0.activationState == .foregroundActive && $0.keyWindow != nil }?.keyWindow + ?? scenes.first { $0.activationState == .foregroundInactive && $0.keyWindow != nil }?.keyWindow + guard let window else { throw YunlefunAccountError.unavailable } anchor = window diff --git a/apps/ios/Cook/Model/YunlefunSSO.swift b/apps/ios/Cook/Model/YunlefunSSO.swift index a8b2a19e9..92a62496e 100644 --- a/apps/ios/Cook/Model/YunlefunSSO.swift +++ b/apps/ios/Cook/Model/YunlefunSSO.swift @@ -20,8 +20,11 @@ struct YunlefunSSO { createdAt = now } - var authorizationURL: URL { - var url = URLComponents(string: "\(Self.issuer)/auth/sso")! + var authorizationURL: URL { authorizationURL(path: "/auth/sso") } + var appAuthorizationURL: URL { authorizationURL(path: "/auth/app") } + + private func authorizationURL(path: String) -> URL { + var url = URLComponents(string: Self.issuer + path)! url.queryItems = [ URLQueryItem(name: "client_id", value: Self.clientID), URLQueryItem(name: "redirect_uri", value: Self.redirectURI), @@ -34,14 +37,24 @@ struct YunlefunSSO { return url.url! } - func exchangeFields(callback: URL, now: Date = Date()) throws -> [String: String] { + static func isCallback(_ url: URL) -> Bool { + guard var parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { return false } + parts.fragment = nil + return parts.string == redirectURI + } + + enum Callback { + case authorized([String: String]) + case denied + case selectAccountOnWeb + } + + func callbackResult(_ callback: URL, now: Date = Date()) throws -> Callback { guard now >= createdAt, now.timeIntervalSince(createdAt) < Self.lifetime, - var url = URLComponents(url: callback, resolvingAgainstBaseURL: false), - let fragment = url.fragment, fragment.hasPrefix("ylf_sso="), fragment.count < 4096 else { + Self.isCallback(callback), let fragment = callback.fragment, + fragment.hasPrefix("ylf_sso="), fragment.count < 4096 else { throw YunlefunAccountError.invalidCallback } - url.fragment = nil - guard url.string == Self.redirectURI else { throw YunlefunAccountError.invalidCallback } let encoded = String(fragment.dropFirst("ylf_sso=".count)) guard let data = Data(base64URL: encoded), let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any], @@ -49,19 +62,29 @@ struct YunlefunSSO { payload["nonce"] as? String == nonce, payload["iss"] as? String == Self.issuer, let ok = payload["ok"] as? Bool else { throw YunlefunAccountError.invalidCallback } guard ok else { - if payload["reason"] as? String == "access_denied" { throw CancellationError() } + guard payload["code"] == nil else { throw YunlefunAccountError.invalidCallback } + if payload["reason"] as? String == "access_denied" { return .denied } + if payload["reason"] as? String == "account_selection_required" { return .selectAccountOnWeb } throw YunlefunAccountError.authorizationFailed } - guard let code = payload["code"] as? String, + guard payload["reason"] == nil, let code = payload["code"] as? String, code.range(of: "^[A-Za-z0-9_-]{43}$", options: .regularExpression) != nil else { throw YunlefunAccountError.invalidCallback } - return ["action": "exchangeSsoCode", "clientId": Self.clientID, - "redirectUri": Self.redirectURI, "scope": Self.scope, - "code": code, "nonce": nonce, "codeVerifier": verifier] + return .authorized(["action": "exchangeSsoCode", "clientId": Self.clientID, + "redirectUri": Self.redirectURI, "scope": Self.scope, + "code": code, "nonce": nonce, "codeVerifier": verifier]) + } + + func exchangeFields(callback: URL, now: Date = Date()) throws -> [String: String] { + switch try callbackResult(callback, now: now) { + case .authorized(let fields): return fields + case .denied: throw CancellationError() + case .selectAccountOnWeb: throw YunlefunAccountError.authorizationFailed + } } - private static func randomToken() throws -> String { + static func randomToken() throws -> String { var bytes = [UInt8](repeating: 0, count: 32) guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw YunlefunAccountError.secureStorage diff --git a/apps/ios/Cook/Views/MembershipView.swift b/apps/ios/Cook/Views/MembershipView.swift index 47d39642c..4207dfe53 100644 --- a/apps/ios/Cook/Views/MembershipView.swift +++ b/apps/ios/Cook/Views/MembershipView.swift @@ -58,6 +58,7 @@ struct MembershipView: View { Button("登录云乐坊账号") { Task { await accounts.signIn() } } .disabled(accounts.isBusy) .accessibilityIdentifier("membership.signIn") + YunlefunAppAuthorizationStatus() } } else if !membership.purchasesEnabled { Section { Text("App 内购买暂未开放。已购会员可在登录后核对现有权益。") } diff --git a/apps/ios/Cook/Views/YunlefunAccountSection.swift b/apps/ios/Cook/Views/YunlefunAccountSection.swift index fcca5b21f..088d4772e 100644 --- a/apps/ios/Cook/Views/YunlefunAccountSection.swift +++ b/apps/ios/Cook/Views/YunlefunAccountSection.swift @@ -26,6 +26,7 @@ struct YunlefunAccountSection: View { .accessibilityIdentifier("account.profile") } else { AccountSignInButton() + WeChatSignInButton() } AccountSessionStatus() } @@ -65,8 +66,21 @@ struct YunlefunAccountView: View { } footer: { Text("在云乐坊网站管理个人资料、登录方式与账号注销。") } + if accounts.canUseWeChat { + Section { + WeChatAuthorizationButton(binding: true) + if let message = accounts.weChatBindingMessage { + Text(message).font(.footnote).foregroundStyle(.secondary) + } + } footer: { + Text("在微信确认授权后,即可用此微信登录当前云乐坊账号。") + } + } } else { - Section { AccountSignInButton() } + Section { + AccountSignInButton() + WeChatSignInButton() + } } if accounts.message != nil || accounts.canRetry { Section { AccountSessionStatus() } @@ -93,6 +107,47 @@ struct YunlefunAccountView: View { } } +private struct WeChatSignInButton: View { + @Environment(YunlefunAccountStore.self) private var accounts + + var body: some View { + if accounts.canUseWeChat { + WeChatAuthorizationButton(binding: false) + } + } +} + +private struct WeChatAuthorizationButton: View { + @Environment(YunlefunAccountStore.self) private var accounts + @Environment(\.openURL) private var openURL + @State private var confirming = false + let binding: Bool + + private var title: String { binding ? "绑定微信到当前账号" : "使用微信登录" } + + var body: some View { + Button { confirming = true } label: { + Label(title, systemImage: "bubble.left.and.bubble.right") + } + .disabled(accounts.isBusy) + .accessibilityIdentifier(binding ? "account.bindWeChat" : "account.signInWithWeChat") + .confirmationDialog(title, isPresented: $confirming, titleVisibility: .visible) { + Button("同意并继续") { + Task { + if binding { await accounts.bindWeChat() } + else { await accounts.signInWithWeChat() } + } + } + Button("查看微信 OpenSDK 个人信息处理规则") { + openURL(URL(string: "https://weixin.qq.com/cgi-bin/readtemplate?t=opensdk_agreement&lang=zh_CN")!) + } + Button("取消", role: .cancel) {} + } message: { + Text("继续会打开微信。云食册仅使用微信授权信息来验证身份并登录或绑定云乐坊账号。") + } + } +} + private struct AccountSignInButton: View { @Environment(YunlefunAccountStore.self) private var accounts @@ -113,12 +168,25 @@ private struct AccountSignInButton: View { .disabled(accounts.isBusy) .accessibilityValue(accounts.isBusy ? "正在处理账号" : "") .accessibilityIdentifier("account.signIn") + YunlefunAppAuthorizationStatus() } else { Text("升级至 iOS 17.4 后可登录云乐坊账号").foregroundStyle(.secondary) } } } +struct YunlefunAppAuthorizationStatus: View { + @Environment(YunlefunAccountStore.self) private var accounts + + var body: some View { + if accounts.isAwaitingYunlefunApp { + Text("请在云乐坊 App 中确认授权").font(.footnote).foregroundStyle(.secondary) + Button("改用网页登录") { accounts.continueYunlefunOnWeb() } + Button("取消登录", role: .cancel) { accounts.cancelYunlefunAppAuthorization() } + } + } +} + /// 在原账号行内预留进度位置,避免授权开始或取消时插入列表行、挤压文字。 private struct AccountActivityIndicator: View { @Environment(YunlefunAccountStore.self) private var accounts diff --git a/apps/ios/Cook/WeChat/CookWeChatBridge.h b/apps/ios/Cook/WeChat/CookWeChatBridge.h new file mode 100644 index 000000000..aeabda7ad --- /dev/null +++ b/apps/ios/Cook/WeChat/CookWeChatBridge.h @@ -0,0 +1,16 @@ +#import + +NS_ASSUME_NONNULL_BEGIN + +typedef void (^CookWeChatResponse)(NSInteger status, NSString *_Nullable state, NSString *_Nullable code); + +/// Keeps Tencent's SDK and its device-only library out of the regular Swift build. +@interface CookWeChatBridge : NSObject ++ (BOOL)prepare:(NSString *)appID universalLink:(NSString *)universalLink NS_SWIFT_NAME(prepare(appID:universalLink:)); ++ (BOOL)isLinked NS_SWIFT_NAME(isLinked()); ++ (void)sendAuth:(NSString *)state completion:(void (^)(BOOL))completion NS_SWIFT_NAME(sendAuth(state:completion:)); ++ (BOOL)handleURL:(NSURL *)url response:(CookWeChatResponse)response NS_SWIFT_NAME(handle(url:response:)); ++ (BOOL)handleActivity:(NSUserActivity *)activity response:(CookWeChatResponse)response NS_SWIFT_NAME(handle(activity:response:)); +@end + +NS_ASSUME_NONNULL_END diff --git a/apps/ios/Cook/WeChat/CookWeChatBridge.m b/apps/ios/Cook/WeChat/CookWeChatBridge.m new file mode 100644 index 000000000..21c52b0c1 --- /dev/null +++ b/apps/ios/Cook/WeChat/CookWeChatBridge.m @@ -0,0 +1,77 @@ +#import "CookWeChatBridge.h" +#import + +#if !TARGET_OS_SIMULATOR && defined(COOK_HAS_WECHAT_SDK) +#import "WXApi.h" + +@interface CookWeChatDelegate : NSObject +@property (nonatomic, copy, nullable) CookWeChatResponse response; +@end + +@implementation CookWeChatDelegate +- (void)onResp:(BaseResp *)response { + if (![response isKindOfClass:SendAuthResp.class]) return; + SendAuthResp *auth = (SendAuthResp *)response; + CookWeChatResponse handler = self.response; + if (handler) handler(auth.errCode, auth.state, auth.code); +} +@end + +// WXApi receives its delegate at URL handling time; keep it alive for an asynchronous reply. +static CookWeChatDelegate *CookWeChatSharedDelegate(void) { + static CookWeChatDelegate *delegate; + static dispatch_once_t once; + dispatch_once(&once, ^{ delegate = [CookWeChatDelegate new]; }); + return delegate; +} +#endif + +@implementation CookWeChatBridge ++ (BOOL)prepare:(NSString *)appID universalLink:(NSString *)universalLink { +#if !TARGET_OS_SIMULATOR && defined(COOK_HAS_WECHAT_SDK) + return [WXApi registerApp:appID universalLink:universalLink]; +#else + return NO; +#endif +} + ++ (BOOL)isLinked { +#if !TARGET_OS_SIMULATOR && defined(COOK_HAS_WECHAT_SDK) + return YES; +#else + return NO; +#endif +} + ++ (void)sendAuth:(NSString *)state completion:(void (^)(BOOL))completion { +#if !TARGET_OS_SIMULATOR && defined(COOK_HAS_WECHAT_SDK) + SendAuthReq *request = [SendAuthReq new]; + request.scope = @"snsapi_userinfo"; + request.state = state; + request.nonautomatic = YES; + [WXApi sendReq:request completion:completion]; +#else + completion(NO); +#endif +} + ++ (BOOL)handleURL:(NSURL *)url response:(CookWeChatResponse)response { +#if !TARGET_OS_SIMULATOR && defined(COOK_HAS_WECHAT_SDK) + CookWeChatDelegate *delegate = CookWeChatSharedDelegate(); + delegate.response = response; + return [WXApi handleOpenURL:url delegate:delegate]; +#else + return NO; +#endif +} + ++ (BOOL)handleActivity:(NSUserActivity *)activity response:(CookWeChatResponse)response { +#if !TARGET_OS_SIMULATOR && defined(COOK_HAS_WECHAT_SDK) + CookWeChatDelegate *delegate = CookWeChatSharedDelegate(); + delegate.response = response; + return [WXApi handleOpenUniversalLink:activity delegate:delegate]; +#else + return NO; +#endif +} +@end diff --git a/apps/ios/CookTests/WeChatAuthorizationTests.swift b/apps/ios/CookTests/WeChatAuthorizationTests.swift new file mode 100644 index 000000000..407934cca --- /dev/null +++ b/apps/ios/CookTests/WeChatAuthorizationTests.swift @@ -0,0 +1,63 @@ +import XCTest +@testable import Cook + +@MainActor +final class WeChatAuthorizationTests: XCTestCase { + func testDisabledBuildDoesNotCallSDK() async { + let auth = WeChatAuthorization(enabled: false, driver: .init(isInstalled: { + XCTFail("Disabled builds must not probe WeChat") + return true + })) + XCTAssertFalse(auth.isAvailable) + do { + _ = try await auth.authorize() + XCTFail("Disabled builds must not launch WeChat") + } catch WeChatAccountError.unavailable {} catch { XCTFail("Unexpected error") } + } + + func testSDKReplyMustMatchAnActiveRequest() async throws { + let sent = expectation(description: "WeChat request sent") + var state = "" + var reply: CookWeChatResponse? + let auth = WeChatAuthorization(enabled: true, driver: .init( + isInstalled: { true }, + register: { id, link in + XCTAssertEqual(id, WeChatAuthorization.appID) + XCTAssertEqual(link, WeChatAuthorization.universalLink) + return true + }, + send: { value, completed in + state = value + completed(true) + sent.fulfill() + }, + handleActivity: { _, completion in reply = completion; return true } + )) + let validLink = try XCTUnwrap(URL(string: "https://cook.yunyoujun.cn/auth/wechat/?code=ignored")) + XCTAssertFalse(auth.handle(validLink), "A link received outside authorization is only a navigation link") + let attempt = Task { try await auth.authorize() } + defer { attempt.cancel() } + await fulfillment(of: [sent], timeout: 2) + XCTAssertEqual(state.count, 43) + XCTAssertFalse(auth.handle(try XCTUnwrap(URL(string: "https://example.org/auth/wechat/")))) + XCTAssertTrue(auth.handle(validLink)) + let response = try XCTUnwrap(reply) + response(0, "another-transaction", "wrong-code") + response(0, state, "verified-code") + let code = try await attempt.value + XCTAssertEqual(code, "verified-code") + XCTAssertFalse(auth.handle(validLink), "A completed transaction cannot handle a replay") + } + + func testCancellationAndInvalidCodesNeverReturnAnAuthorizationCode() throws { + for status in [-2, -4] { + XCTAssertThrowsError(try WeChatAuthorization.validatedCode(status: status, code: "ignored")) { + XCTAssertTrue($0 is CancellationError) + } + } + for code in [nil, "", "injected&key", String(repeating: "x", count: 513)] { + XCTAssertThrowsError(try WeChatAuthorization.validatedCode(status: 0, code: code)) + } + XCTAssertThrowsError(try WeChatAuthorization.validatedCode(status: -1, code: "valid-looking")) + } +} diff --git a/apps/ios/CookTests/YunlefunAccountTests.swift b/apps/ios/CookTests/YunlefunAccountTests.swift index fa2297dcf..53db36344 100644 --- a/apps/ios/CookTests/YunlefunAccountTests.swift +++ b/apps/ios/CookTests/YunlefunAccountTests.swift @@ -7,6 +7,9 @@ private func callback(_ transaction: YunlefunSSO, changes: [String: Any] = [:], var payload: [String: Any] = ["nonce": transaction.nonce, "iss": YunlefunSSO.issuer, "ok": true, "code": String(repeating: "a", count: 43)] payload.merge(changes) { _, new in new } + if payload["ok"] as? Bool == false, changes["code"] == nil { + payload.removeValue(forKey: "code") + } let encoded = try JSONSerialization.data(withJSONObject: payload).base64EncodedString() .replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") return URL(string: redirect + "#ylf_sso=" + encoded)! @@ -19,6 +22,11 @@ final class YunlefunSSOTests: XCTestCase { let query = Dictionary(uniqueKeysWithValues: url.queryItems!.map { ($0.name, $0.value!) }) XCTAssertEqual(url.scheme, "https") XCTAssertEqual(url.host, "www.yunle.fun") + XCTAssertEqual(url.path, "/auth/sso") + let app = URLComponents(url: transaction.appAuthorizationURL, resolvingAgainstBaseURL: false)! + XCTAssertEqual(app.host, url.host) + XCTAssertEqual(app.path, "/auth/app") + XCTAssertEqual(app.queryItems, url.queryItems) XCTAssertEqual(query["client_id"], "cook-mobile") XCTAssertEqual(query["redirect_uri"], YunlefunSSO.redirectURI) XCTAssertEqual(query["scope"], "identity:bootstrap") @@ -83,6 +91,9 @@ private final class AccountServiceStub: YunlefunAccountServing { var signOutCount = 0 var failure: Error? var profileFailure: Error? + var weChatSignInCount = 0 + var weChatBindingCount = 0 + var boundSubject: String? func signIn(fields: [String: String], deviceID: String) async throws -> YunlefunCredential { signInCount += 1 if let failure { throw failure } @@ -102,19 +113,153 @@ private final class AccountServiceStub: YunlefunAccountServing { signOutCount += 1 if let failure { throw failure } } + func signInWithWeChat(code: String, deviceID: String) async throws -> YunlefunCredential { + weChatSignInCount += 1 + if let failure { throw failure } + return credential + } + func bindWeChat(code: String, credential: YunlefunCredential) async throws { + weChatBindingCount += 1 + boundSubject = credential.subject + } +} + +@MainActor +private final class WeChatAuthorizationStub: WeChatAuthorizing { + var isAvailable = true + var cancelled = false + var count = 0 + func authorize() async throws -> String { + count += 1 + if cancelled { throw CancellationError() } + return "wechat-code" + } + func handle(_ url: URL) -> Bool { false } + func handle(_ activity: NSUserActivity) -> Bool { false } } @MainActor private final class AuthorizationStub: YunlefunAuthorizing { var cancelled = false var invalid = false + var transactions: [YunlefunSSO] = [] func authorize(_ transaction: YunlefunSSO) async throws -> URL { + transactions.append(transaction) if cancelled { throw CancellationError() } return try callback(transaction, changes: invalid ? ["nonce": "forged"] : [:]) } func cancel() { cancelled = true } } +@MainActor +final class YunlefunAppAuthorizationTests: XCTestCase { + func testUnavailableAppFallsBackToExistingWebAuthorization() async throws { + let service = AccountServiceStub() + let browser = AuthorizationStub() + var launchedURL: URL? + let app = YunlefunAppAuthorization(openApp: { launchedURL = $0; return false }) + let store = YunlefunAccountStore(service: service, vault: MemoryYunlefunAccountVault(), + authorization: browser, appAuthorization: app) + + await store.signIn() + + let launch = try XCTUnwrap(launchedURL) + let web = try XCTUnwrap(browser.transactions.first) + XCTAssertEqual(launch.path, "/auth/app") + XCTAssertFalse(launch.absoluteString.contains(web.nonce)) + XCTAssertEqual(browser.transactions.count, 1) + XCTAssertEqual(service.signInCount, 1) + XCTAssertEqual(store.account?.id, service.credential.subject) + XCTAssertFalse(store.isAwaitingYunlefunApp) + } + + func testAppCallbackMustMatchTheActiveAttemptAndExchangesOnlyOnce() async throws { + let service = AccountServiceStub() + let browser = AuthorizationStub() + let launched = expectation(description: "Opened Yunlefun app") + var nonce: String? + let app = YunlefunAppAuthorization(openApp: { + nonce = URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "nonce" }?.value + launched.fulfill() + return true + }) + let store = YunlefunAccountStore(service: service, vault: MemoryYunlefunAccountVault(), + authorization: browser, appAuthorization: app) + let fixture = try YunlefunSSO() + let valid = try callback(fixture, changes: ["nonce": "replace"]) + XCTAssertTrue(store.handleYunlefunCallback(valid)) // No attempt yet. + let task = Task { await store.signIn() } + defer { task.cancel() } + await fulfillment(of: [launched], timeout: 2) + XCTAssertTrue(store.isAwaitingYunlefunApp) + XCTAssertTrue(store.handleYunlefunCallback(valid)) + XCTAssertTrue(store.isAwaitingYunlefunApp) + XCTAssertEqual(service.signInCount, 0) + let response = try callback(fixture, changes: ["nonce": XCTUnwrap(nonce)]) + XCTAssertTrue(store.handleYunlefunCallback(response)) + await task.value + XCTAssertTrue(store.handleYunlefunCallback(response)) + XCTAssertEqual(service.signInCount, 1) + XCTAssertTrue(browser.transactions.isEmpty) + XCTAssertEqual(store.account?.id, service.credential.subject) + XCTAssertFalse(store.isAwaitingYunlefunApp) + } + + func testSelectAnotherAccountUsesFreshWebAttemptWhileDenialDoesNot() async throws { + for reason in ["account_selection_required", "access_denied"] { + let service = AccountServiceStub() + let browser = AuthorizationStub() + let launched = expectation(description: "Opened app for \(reason)") + var nonce: String? + let app = YunlefunAppAuthorization(openApp: { + nonce = URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "nonce" }?.value + launched.fulfill() + return true + }) + let store = YunlefunAccountStore(service: service, vault: MemoryYunlefunAccountVault(), + authorization: browser, appAuthorization: app) + let fixture = try YunlefunSSO() + let task = Task { await store.signIn() } + defer { task.cancel() } + await fulfillment(of: [launched], timeout: 2) + let currentNonce = try XCTUnwrap(nonce) + let result = try callback(fixture, changes: ["nonce": currentNonce, "ok": false, "reason": reason]) + XCTAssertTrue(store.handleYunlefunCallback(result)) + await task.value + let usedBrowser = reason == "account_selection_required" + XCTAssertEqual(browser.transactions.count, usedBrowser ? 1 : 0) + XCTAssertEqual(service.signInCount, usedBrowser ? 1 : 0) + if usedBrowser { XCTAssertNotEqual(browser.transactions.first?.nonce, currentNonce) } + } + } + + func testManuallySwitchingToWebInvalidatesThePendingAppCallback() async throws { + let service = AccountServiceStub() + let browser = AuthorizationStub() + let launched = expectation(description: "Opened app before switching to web") + var appNonce: String? + let app = YunlefunAppAuthorization(openApp: { + appNonce = URLComponents(url: $0, resolvingAgainstBaseURL: false)?.queryItems?.first { $0.name == "nonce" }?.value + launched.fulfill() + return true + }) + let store = YunlefunAccountStore(service: service, vault: MemoryYunlefunAccountVault(), + authorization: browser, appAuthorization: app) + let task = Task { await store.signIn() } + defer { task.cancel() } + await fulfillment(of: [launched], timeout: 2) + XCTAssertTrue(store.isAwaitingYunlefunApp) + let staleCallback = try callback(YunlefunSSO(), changes: ["nonce": XCTUnwrap(appNonce)]) + store.continueYunlefunOnWeb() + XCTAssertTrue(store.handleYunlefunCallback(staleCallback)) + await task.value + XCTAssertFalse(store.isAwaitingYunlefunApp) + XCTAssertEqual(browser.transactions.count, 1) + XCTAssertNotEqual(browser.transactions.first?.nonce, appNonce) + XCTAssertEqual(service.signInCount, 1) + } +} + @MainActor private final class FailingAccountVault: YunlefunAccountVault { var credential: YunlefunCredential? @@ -133,6 +278,45 @@ private final class FailingAccountVault: YunlefunAccountVault { @MainActor final class YunlefunAccountStoreTests: XCTestCase { + func testWeChatBindingRequiresCurrentAccountAndKeepsItsSession() async { + let service = AccountServiceStub() + let weChat = WeChatAuthorizationStub() + let store = YunlefunAccountStore(service: service, vault: MemoryYunlefunAccountVault(), + authorization: AuthorizationStub(), weChat: weChat) + await store.bindWeChat() + XCTAssertEqual(weChat.count, 0) + await store.signIn() + await store.bindWeChat() + XCTAssertEqual(service.weChatBindingCount, 1) + XCTAssertEqual(service.boundSubject, "user-1") + XCTAssertEqual(weChat.count, 1) + XCTAssertEqual(store.account?.id, "user-1") + await store.signOut() + await store.signInWithWeChat() + XCTAssertEqual(store.account?.id, "user-1") + XCTAssertEqual(service.weChatSignInCount, 1) + } + + func testUnlinkedWeChatAndCancelledBindingDoNotReplaceSession() async { + let service = AccountServiceStub() + let weChat = WeChatAuthorizationStub() + let vault = MemoryYunlefunAccountVault() + let store = YunlefunAccountStore(service: service, vault: vault, + authorization: AuthorizationStub(), weChat: weChat) + service.failure = WeChatAccountError.bindingRequired + await store.signInWithWeChat() + XCTAssertNil(vault.credential) + XCTAssertEqual(store.message, WeChatAccountError.bindingRequired.errorDescription) + service.failure = nil + await store.signIn() + weChat.cancelled = true + let revision = store.sessionRevision + await store.bindWeChat() + XCTAssertEqual(store.sessionRevision, revision) + XCTAssertEqual(vault.credential, service.credential) + XCTAssertEqual(service.weChatBindingCount, 0) + XCTAssertNil(store.message) + } func testKeychainFailuresDoNotReportSuccessfulLoginOrLogout() async { let service = AccountServiceStub() let vault = FailingAccountVault() @@ -242,6 +426,64 @@ private actor AccountTransportStub { @MainActor final class YunlefunAccountServiceTests: XCTestCase { + func testWeChatExchangesCodeWithYunlefunAndUsesExistingUIDTicket() async throws { + let transport = AccountTransportStub([ + (200, #"{"ok":true,"ticket":"sso-ticket","subject":"user-1"}"#), + (200, #"{"access_token":"access","refresh_token":"refresh","sub":"user-1","expires_in":7200}"#), + ]) + let service = YunlefunAccountService(transport: { try await transport.send($0) }) + let credential = try await service.signInWithWeChat(code: "wechat-code", deviceID: "installation") + XCTAssertEqual(credential.subject, "user-1") + let requests = await transport.requests + XCTAssertEqual(requests.map { $0.url?.path }, ["/sso-ticket", "/auth/v1/signin/custom"]) + XCTAssertEqual(requests[0].url?.host, "api.yunle.fun") + XCTAssertEqual(requests[0].value(forHTTPHeaderField: "Origin"), "https://cook.yunyoujun.cn") + XCTAssertNil(requests[0].value(forHTTPHeaderField: "Authorization")) + let exchange = try JSONSerialization.jsonObject(with: requests[0].httpBody!) as? [String: String] + XCTAssertEqual(exchange, ["action": "exchangeCookWeChatCode", "clientId": "cook-mobile", "code": "wechat-code"]) + let signIn = try JSONSerialization.jsonObject(with: requests[1].httpBody!) as? [String: String] + XCTAssertEqual(signIn, ["provider_id": "custom", "ticket": "sso-ticket"]) + } + + func testWeChatBindingUsesCurrentBearerAndNeverSendsUID() async throws { + let transport = AccountTransportStub([(200, #"{"ok":true}"#)]) + let service = YunlefunAccountService(transport: { try await transport.send($0) }) + try await service.bindWeChat(code: "wechat-code", credential: AccountServiceStub().credential) + let requests = await transport.requests + let request = try XCTUnwrap(requests.first) + XCTAssertEqual(request.url?.absoluteString, "https://api.yunle.fun/sso-ticket") + XCTAssertEqual(request.value(forHTTPHeaderField: "Authorization"), "Bearer access") + XCTAssertEqual(request.value(forHTTPHeaderField: "x-device-id"), "installation") + let body = try JSONSerialization.jsonObject(with: request.httpBody!) as? [String: String] + XCTAssertEqual(body, ["action": "bindCookWeChat", "clientId": "cook-mobile", "code": "wechat-code"]) + } + + func testWeChatRejectsSessionForAnUnexpectedUID() async throws { + let transport = AccountTransportStub([ + (200, #"{"ok":true,"ticket":"sso-ticket","subject":"user-1"}"#), + (200, #"{"access_token":"access","refresh_token":"refresh","sub":"wrong-user","expires_in":7200}"#), + (200, "{}"), + ]) + let service = YunlefunAccountService(transport: { try await transport.send($0) }) + do { + _ = try await service.signInWithWeChat(code: "wechat-code", deviceID: "installation") + XCTFail("Ticket opened a different account") + } catch YunlefunAccountError.invalidResponse {} + let requests = await transport.requests + XCTAssertEqual(requests.last?.url?.path, "/auth/v1/user/signout") + } + + func testWeChatDoesNotRetryOrCreateAccountForAnUnboundIdentity() async throws { + let transport = AccountTransportStub([(404, #"{"ok":false,"reason":"wechat_binding_required"}"#)]) + let service = YunlefunAccountService(transport: { try await transport.send($0) }) + do { + _ = try await service.signInWithWeChat(code: "wechat-code", deviceID: "installation") + XCTFail("Unbound identity returned a session") + } catch WeChatAccountError.bindingRequired {} + let requests = await transport.requests + XCTAssertEqual(requests.count, 1) + } + func testProfileDecodesAvatarWithoutRequiringItForLogin() throws { let profile = try JSONDecoder().decode(YunlefunAccount.self, from: Data(#"{"sub":"user-1","name":"云游君","picture":"https://images.example/avatar.png"}"#.utf8)) XCTAssertEqual(profile.avatarURL?.absoluteString, "https://images.example/avatar.png") diff --git a/apps/ios/README.md b/apps/ios/README.md index 7facfd0b7..a6727c022 100644 --- a/apps/ios/README.md +++ b/apps/ios/README.md @@ -86,11 +86,9 @@ CI 的 `ios-tests` 矩阵在 iPhone 和 iPad 模拟器上分组跑单元测试 「我的 → AI 设置」可选择会员内置 DeepSeek,或保存自己的 DeepSeek Key。有效会员由服务器核验;普通用户仍可使用自己的 Key 或本地识别。在做菜搜索框输入想法后,点击「预览条件」修改条件;模型请求仅在主动选择智能找菜并确认发送时发生。来源、额度、隐私与验证边界见[会员 AI 接入](../../docs/dev/ios-managed-ai.md)。 -原生云乐坊登录的客户端登记、HTTPS 回调发布条件和会话验证见 [账号接入](../../docs/dev/ios-account.md)。微信登录暂缓,申请资料见 [微信移动应用申请](../../docs/dev/wechat-mobile-application.md)。登录与 iCloud 数据同步相互独立。 +原生云乐坊登录的客户端登记、HTTPS 回调发布条件和会话验证见 [账号接入](../../docs/dev/ios-account.md)。原生微信登录的配置和验收见 [微信登录联调](../../docs/dev/ios-wechat-login.md)。登录与 iCloud 数据同步相互独立。 -原生微信入口预留构建开关 `COOK_WECHAT_LOGIN_ENABLED`,Debug / Release 均默认 `NO`,通过 `Info.plist` 的 `CookWeChatLoginEnabled` 供 `CookFeatures.weChatLoginEnabled` 读取。只有显式 `YES` 才开启;缺失或未展开的值保持关闭。后续接入微信按钮和发起授权动作时,统一使用该属性控制入口。审核通过且 SDK、同一云乐坊账号绑定联调完成后,可在 `project.yml` 修改默认值并重新生成工程,或通过 `xcodebuild ... COOK_WECHAT_LOGIN_ENABLED=YES` 覆盖本次构建,再重新打包分发。 - -此开关目前仅预留配置,尚无原生微信按钮或 SDK 消费它;单独改成 `YES` 不会提供微信登录能力。开关不控制现有云乐坊授权网页、Universal Links 或 iCloud 同步,也不是远程开关。 +原生微信入口由 `COOK_WECHAT_LOGIN_ENABLED` 控制,Debug / Release 默认 `NO`。仅在显式启用的 iPhoneOS 构建中下载和链接微信 OpenSDK,安装了微信才显示入口。启用前须验证微信开放平台权限和云乐坊统一登录服务;开关不控制现有云乐坊授权网页或 iCloud 同步。 ## 冰箱拍照录入 diff --git a/apps/ios/project.yml b/apps/ios/project.yml index a1bb31ee9..d06186bdf 100644 --- a/apps/ios/project.yml +++ b/apps/ios/project.yml @@ -45,6 +45,13 @@ targets: product: YunleSupportUI - package: CookCore preBuildScripts: + - name: Prepare WeChat OpenSDK for enabled device builds + script: bash "$SRCROOT/scripts/prepare-wechat-sdk.sh" + basedOnDependencyAnalysis: false + outputFiles: + - $(TARGET_TEMP_DIR)/CookWeChatSDK/libWechatOpenSDK.a + - $(TARGET_TEMP_DIR)/CookWeChatSDK/WXApi.h + - $(TARGET_TEMP_DIR)/CookWeChatSDK/WXApiObject.h - name: 拷贝共享数据 script: bash "$SRCROOT/scripts/copy-data.sh" basedOnDependencyAnalysis: false @@ -62,11 +69,15 @@ targets: CookAIServiceURL: $(COOK_AI_SERVICE_URL) # Guidance has its own capability and deployment gate; never infer it from search. CookAIGuidanceServiceURL: $(COOK_AI_GUIDANCE_SERVICE_URL) - # 预留给原生微信入口;只在 SDK、账号绑定与审核均就绪后开启。 + # 只在 SDK、账号绑定与审核均就绪后开启。 CookWeChatLoginEnabled: $(COOK_WECHAT_LOGIN_ENABLED) CookMembershipUIEnabled: $(COOK_MEMBERSHIP_UI_ENABLED) CookMembershipPurchasesEnabled: $(COOK_MEMBERSHIP_PURCHASES_ENABLED) - LSApplicationQueriesSchemes: [bilibili] + LSApplicationQueriesSchemes: [bilibili, weixin, weixinULAPI, weixinURLParamsAPI] + CFBundleURLTypes: + - CFBundleURLName: fun.yunle.cook.wechat + CFBundleTypeRole: Editor + CFBundleURLSchemes: [wxce6c7405dd756b9d] NSUbiquitousContainers: iCloud.fun.yunle.cook: NSUbiquitousContainerIsDocumentScopePublic: true @@ -106,6 +117,13 @@ targets: PRODUCT_NAME: Cook PRODUCT_BUNDLE_IDENTIFIER: fun.yunle.cook COOK_WECHAT_LOGIN_ENABLED: NO + SWIFT_OBJC_BRIDGING_HEADER: Cook/WeChat/CookWeChatBridge.h + # The vendor arm64 slice is for iPhoneOS, not Apple Silicon Simulator. + 'GCC_PREPROCESSOR_DEFINITIONS[sdk=iphoneos*]': $(inherited) $(COOK_WECHAT_DEFINITIONS_$(COOK_WECHAT_LOGIN_ENABLED)) + 'HEADER_SEARCH_PATHS[sdk=iphoneos*]': $(inherited) "$(TARGET_TEMP_DIR)/CookWeChatSDK" + 'OTHER_LDFLAGS[sdk=iphoneos*]': $(inherited) $(COOK_WECHAT_LDFLAGS_$(COOK_WECHAT_LOGIN_ENABLED)) + COOK_WECHAT_DEFINITIONS_YES: COOK_HAS_WECHAT_SDK=1 + COOK_WECHAT_LDFLAGS_YES: -force_load "$(TARGET_TEMP_DIR)/CookWeChatSDK/libWechatOpenSDK.a" -framework Security -framework UIKit -framework CoreGraphics -framework WebKit -lz -lsqlite3 -lc++ COOK_MEMBERSHIP_UI_ENABLED: NO COOK_MEMBERSHIP_PURCHASES_ENABLED: NO COOK_AI_SERVICE_URL: https://api.yunle.fun/cook-ai-intent diff --git a/apps/ios/scripts/prepare-wechat-sdk.sh b/apps/ios/scripts/prepare-wechat-sdk.sh new file mode 100644 index 000000000..86997119d --- /dev/null +++ b/apps/ios/scripts/prepare-wechat-sdk.sh @@ -0,0 +1,45 @@ +#!/bin/bash +set -euo pipefail + +# Standalone distribution listed by Tencent's WechatOpenSDK 2.0.9 podspec. +# Do not fetch or link the SDK in Simulator or ordinary device builds. +[[ "${PLATFORM_NAME:-}" == iphoneos ]] || exit 0 +sdk_dir="${TARGET_TEMP_DIR}/CookWeChatSDK" +privacy_bundle="${TARGET_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/WeChatOpenSDKPrivacy.bundle" +if [[ "${COOK_WECHAT_LOGIN_ENABLED:-}" != YES ]]; then + rm -rf -- "$privacy_bundle" + exit 0 +fi + +version=2.0.9 +sha=f40037787bb9ca8742d90b945cc82163bb123e156f9330316dd5df43782d351d +work=$(mktemp -d "${TARGET_TEMP_DIR}/wechat-sdk.XXXXXX") +trap 'rm -rf -- "$work"' EXIT +if [[ -n "${COOK_WECHAT_SDK_ARCHIVE:-}" ]]; then + cp -- "$COOK_WECHAT_SDK_ARCHIVE" "$work/sdk.zip" +else + curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \ + --connect-timeout 10 --max-time 45 --output "$work/sdk.zip" \ + "https://dldir1.qq.com/WechatWebDev/opensdk/cocoapods/OpenSDK${version}.zip" +fi +if ! printf '%s %s\n' "$sha" "$work/sdk.zip" | shasum -a 256 --check --status; then + echo 'error: WeChat OpenSDK archive does not match the pinned SHA-256' >&2 + exit 1 +fi +unzip -q "$work/sdk.zip" "OpenSDK${version}/WXApi.h" "OpenSDK${version}/WXApiObject.h" \ + "OpenSDK${version}/libWechatOpenSDK.a" "OpenSDK${version}/PrivacyInfo.xcprivacy" -d "$work" +vendor="$work/OpenSDK${version}" +mkdir -p "$sdk_dir" "$privacy_bundle" +install -m 644 "$vendor/WXApi.h" "$vendor/WXApiObject.h" "$vendor/libWechatOpenSDK.a" "$sdk_dir/" +install -m 644 "$vendor/PrivacyInfo.xcprivacy" "$privacy_bundle/PrivacyInfo.xcprivacy" +cat > "$privacy_bundle/Info.plist" <<'PLIST' + + + + + CFBundleIdentifierfun.yunle.cook.wechat-sdk-privacy + CFBundlePackageTypeBNDL + CFBundleVersion1 + + +PLIST diff --git a/docs/dev/ios-account.md b/docs/dev/ios-account.md index fdfc23b25..42302e96d 100644 --- a/docs/dev/ios-account.md +++ b/docs/dev/ios-account.md @@ -4,7 +4,7 @@ ## 页面层级 -「我的」首页只保留账号摘要,以及我的菜谱、食材和厨具、做菜偏好、提醒、数据与同步、隐私、帮助与反馈、关于云食册等入口。做菜偏好与提醒开关在各自二级页;iCloud 说明和网页数据导入导出集中在「数据与同步」;账号管理、注销与退出移入账号详情页。密码和验证码继续使用系统认证窗口访问云乐坊统一登录,客户端不新增一套密码表单。 +「我的」首页只保留账号摘要,以及我的菜谱、食材和厨具、做菜偏好、提醒、数据与同步、隐私、帮助与反馈、关于云食册等入口。做菜偏好与提醒开关在各自二级页;iCloud 说明和网页数据导入导出集中在「数据与同步」;账号管理、注销与退出移入账号详情页。登录优先通过 `https://www.yunle.fun/auth/app` 打开云乐坊 App 确认;系统无法打开时继续使用现有系统网页授权。用户可取消等待或改用网页;在云乐坊选择「使用其他账号」也会用新事务打开网页。云食册不收集密码和验证码。 ## 客户端登记 @@ -32,7 +32,7 @@ 1. 在 Apple Developer 的 `fun.yunle.cook` 标识符开启 Associated Domains,并更新签名描述文件。 2. 将 `apps/web/public/.well-known/apple-app-site-association` 发布到 `https://cook.yunyoujun.cn/.well-known/apple-app-site-association`。保留 `webcredentials.apps` 的 `QT792GAY4C.fun.yunle.cook` 和原生 `/auth/wechat/*` applinks;2026-10-26 按 [0016](../decisions/0016-native-android-and-capacitor-retirement) 从源码移除旧 Capacitor 应用关联。`/auth/callback?platform=native` 仍供当前系统授权会话使用,不能随旧外壳一并删除。 3. 用正确的 `APPLE_DEVELOPMENT_TEAM` 生成工程。`project.yml` 已声明 `webcredentials:cook.yunyoujun.cn`,并为后续微信登录声明 `applinks:cook.yunyoujun.cn`;如果改签名团队,必须同步修改站点 AASA。 -4. 等 Apple 的关联域名缓存更新后,真机验证系统授权窗口和 HTTPS 回调。模拟器编译、协议测试均不能替代此步骤。 +4. 跨 App 回跳复用已登记的 `/auth/callback?platform=native`,AASA 仅关联包含 `ylf_sso=` 结果片段的原生回调。部署 Cook 的 AASA 后,核对 Apple CDN,并真机验证已安装云乐坊时的切换与回跳、未安装或系统无法打开时的网页授权,以及「使用其他账号」的网页回跳。网页流程的回调仍由系统认证窗口接收;未完成这些验证前不要将功能视为已上线。 2026-10-24 已将 AASA 发布到 EdgeOne 生产项目 `yunyoujun-cook`(部署 `dpwz3nca44ld`)。生产域名与 Apple CDN 均返回 HTTP 200、`application/json`,内容一致且包含原生 `webcredentials`。Apple App ID `JJLY23S94L` 已回读确认开启 Associated Domains,Xcode 自动更新了开发描述文件。 diff --git a/docs/dev/ios-wechat-login.md b/docs/dev/ios-wechat-login.md new file mode 100644 index 000000000..7c284c82d --- /dev/null +++ b/docs/dev/ios-wechat-login.md @@ -0,0 +1,35 @@ +# 云食册原生微信登录联调 + +当前代码仅为内部联调准备。普通构建默认关闭微信入口,也不下载或链接 OpenSDK。 + +## 开放平台 + +- 移动应用 AppID:`wxce6c7405dd756b9d`,Bundle ID:`fun.yunle.cook`。 +- Universal Links:`https://cook.yunyoujun.cn/auth/wechat/`(保留末尾的斜杠)。源站及 Apple CDN 已在 [#221](https://github.com/YunYouJun/cook/issues/221) 验证文件,但该 issue 的云乐坊系统 SSO 回调不是微信 SDK 验收。 +- 维护者已报告移动应用审核通过;进入「接口信息」确认微信登录权限状态。若显示未获得,在微信开放平台申请开通。不要把控制台会话链接或 AppSecret 写进 issue、Git、App 配置或日志。 + +## 云乐坊统一登录后端 + +App 使用移动应用 AppID 拉起微信。拿到授权码后,调用现有 `https://api.yunle.fun/sso-ticket`:首次绑定用 `bindCookWeChat`,并提供当前云乐坊会话;登录用 `exchangeCookWeChatCode`,取得原 UID 的 custom ticket。CloudBase 继续承载云乐坊账号和会话;不新增 OAuth 身份源,也不修改网站的 `wx_open`。 + +第一次使用先用原方式登录云乐坊,在云食册「我的 → 云乐坊账号」选择绑定并在微信确认授权。服务端把微信换码得到的身份关联到当前云乐坊会话的 UID。之后退出,再用微信登录会回到同一个 UID;不会覆盖已有绑定。云乐坊网站的微信登录和绑定独立管理。未绑定的微信不能直接登录或创建账号;没有云乐坊账号时,先按现有流程注册并登录,再回来绑定。 + +移动应用 AppSecret 只填在云乐坊后端 `sso-ticket` 云函数的私有环境变量 `COOK_WECHAT_APP_SECRET`;不用填 CloudBase 的「微信登录」配置,也不要发到聊天里。后端启用前需完成集合权限、注销清理和真实身份字段验证。 + +## 构建和验收 + +从仓库根目录生成菜谱数据并重新生成 Xcode 工程。使用已配置的 Apple 开发签名,在本地真机联调构建中显式开启: + +```sh +pnpm convert +xcodegen generate --spec apps/ios/project.yml +xcodebuild -project apps/ios/Cook.xcodeproj -scheme Cook \ + -destination 'generic/platform=iOS' COOK_WECHAT_LOGIN_ENABLED=YES build +``` + +启用的 iPhoneOS 构建下载腾讯发布的 OpenSDK 2.0.9 ZIP,校验固定 SHA-256 后链接设备切片,并将 SDK 的隐私清单随包带上。离线构建可通过 `COOK_WECHAT_SDK_ARCHIVE` 指向相同 ZIP;模拟器和关闭开关的构建都不需要它。 + +1. 安装签名构建。在已安装微信的 iPhone 上,从「我的」触发授权,分别验证成功、取消、拒绝、冷启动无待处理事务和热回跳。没有微信时保留原云乐坊入口。 +2. 使用未绑定的测试微信登录,确认没有新建用户。用没有网站微信绑定的现有云乐坊账号登录,在云食册账号详情完成绑定;退出后用微信登录,在本机比对两次 UID,再检查收藏同步和会员权益。重复绑定、冲突、受限账号与网络中断不能覆盖绑定或替换原有会话。 +3. 记录构建号、签名、设备版本、微信版本与脱敏结果;授权码、token、OpenID 和 UnionID 不进记录。核对网站原有 `wx_open` 登录仍正常。 +4. 上线前更新隐私政策和 App Store 隐私申报,按 [App Review 4.8](https://developer.apple.com/app-store/review/guidelines/#login-services) 核对等效登录方式。真机和服务端验证通过前保持默认关闭。 diff --git a/docs/dev/wechat-mobile-application.md b/docs/dev/wechat-mobile-application.md index 30d0f4f6b..e12c96c49 100644 --- a/docs/dev/wechat-mobile-application.md +++ b/docs/dev/wechat-mobile-application.md @@ -2,6 +2,8 @@ 核验日期:2026-10-25。**当前没有微信移动应用创建成功或提交审核的回执,微信 SDK 尚未接入。** 本文用于管理员手动操作;微信开放平台表单尚未被读取,菜单名称、材料尺寸、主体资格及审核要求以当前页面为准。浏览器工具此前因站点安全策略拒绝访问该平台,本轮未绕过此限制。 +2026-11-13 更新:维护者报告移动应用审核通过;下文保留申请时的记录。AppID、当前接入与后续真机验收见 [原生微信登录联调](./ios-wechat-login.md)。 + ## 先看当前状态 | 项目 | 已核验结果 | diff --git a/docs/privacy.md b/docs/privacy.md index 0e7477377..9ebffa52b 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -1,6 +1,6 @@ # 云食册隐私政策 -更新日期:2026 年 11 月 10 日 +更新日期:2026 年 11 月 13 日 本政策适用于海州区云乐坊信息技术工作室(以下简称“我们”)运营的「云食册」原生 iOS App,我们是本政策所述个人信息处理活动的责任主体。云食册产品官网为 [cook.yunle.fun](https://cook.yunle.fun/),由同一工作室运营;开源项目由云游君(YunYouJun)开发维护。网页版及从 App 打开的第三方网站,适用各自的隐私政策。隐私问题和数据删除请求可发送至 [me@yunyoujun.cn](mailto:me@yunyoujun.cn)。 @@ -50,9 +50,9 @@ App 为每个账号保存独立的本机缓存,支持离线使用;缓存不 ### 微信登录 -当前版本尚未提供原生微信登录,未集成微信 OpenSDK,也不会通过该 SDK 收集微信账号信息。若你在云乐坊网站主动使用或绑定微信,相关授权在网站完成,适用该网站和微信授权页面展示的隐私说明。 +若你的构建提供原生微信登录,且你主动选择微信登录或绑定并确认继续,云食册会使用深圳市腾讯计算机系统有限公司的微信 OpenSDK 拉起微信授权并接收回调。微信授权码由云乐坊统一登录服务兑换:绑定时,将验证过的微信身份关联到你当前登录的云乐坊账号;之后用微信登录时,验证身份并登录同一个账号。服务端保存用于登录的微信身份摘要和云乐坊账号标识,账号注销时清理。授权范围以微信页面显示为准;云食册不会用微信昵称或头像覆盖现有云乐坊资料。SDK 本身的信息处理见 [微信 OpenSDK 个人信息处理规则](https://weixin.qq.com/cgi-bin/readtemplate?t=opensdk_agreement&lang=zh_CN)。 -后续开放原生微信登录时,将用于登录或绑定同一个云乐坊账号。我们会在功能启用前更新本政策,说明所用 SDK 的提供者、实际处理的信息、处理目的及隐私说明,并在需要时征求同意。微信登录不会改变上述本机数据与 iCloud 的管理方式。 +你可以取消授权或改用云乐坊账号登录;没有微信登录入口的构建不会通过 OpenSDK 获取微信授权信息。若你在云乐坊网站使用或绑定微信,相关授权在网站完成。微信登录不会改变上述本机数据与 iCloud 的管理方式。 ## 私人菜谱