diff --git a/apps/ios/AppInfo.plist b/apps/ios/AppInfo.plist
index 47046ef..ceb3d8f 100644
--- a/apps/ios/AppInfo.plist
+++ b/apps/ios/AppInfo.plist
@@ -6,16 +6,5 @@
$(ATLAS_API_BASE_URL)
AtlasOIDCIssuer
$(ATLAS_OIDC_ISSUER)
- CFBundleURLTypes
-
-
- CFBundleTypeRole
- Editor
- CFBundleURLName
- com.tutudog.itematlas.oauth
- CFBundleURLSchemes
- com.tutudog.itematlas
-
-
diff --git a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj
index 96f099a..77a9372 100644
--- a/apps/ios/ItemAtlas.xcodeproj/project.pbxproj
+++ b/apps/ios/ItemAtlas.xcodeproj/project.pbxproj
@@ -117,7 +117,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 3;
+ CURRENT_PROJECT_VERSION = 4;
GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";
@@ -138,7 +138,7 @@
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
- CURRENT_PROJECT_VERSION = 3;
+ CURRENT_PROJECT_VERSION = 4;
GENERATE_INFOPLIST_FILE = YES;
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ATLAS_API_BASE_URL = "https://api-atlas.tutudog.com";
diff --git a/apps/ios/ItemAtlas/Account.swift b/apps/ios/ItemAtlas/Account.swift
index e721987..f63de32 100644
--- a/apps/ios/ItemAtlas/Account.swift
+++ b/apps/ios/ItemAtlas/Account.swift
@@ -1,22 +1,16 @@
-import AuthenticationServices
-import CryptoKit
import Foundation
import Observation
import Security
-import UIKit
struct AtlasError: LocalizedError {
let message: String
var errorDescription: String? { message }
init(_ message: String) { self.message = message }
}
-
struct AtlasEndpoints {
let api: URL
let issuer: URL
static let client = "atlas-ios"
- static let scheme = "com.tutudog.itematlas"
- static let redirect = "\(scheme):/oauth2/callback"
init() throws {
func endpoint(_ key: String) throws -> URL {
@@ -34,7 +28,6 @@ struct AtlasEndpoints {
private struct OIDCMetadata: Decodable {
let issuer: URL
- let authorization_endpoint: URL
let token_endpoint: URL
let revocation_endpoint: URL?
}
@@ -48,8 +41,25 @@ private struct Grant: Codable {
private struct SessionTokens: Codable {
let grant: Grant
let expires: Date
+ let native: Bool?
}
+private struct NativeGrant: Decodable {
+ let accessToken: String
+ let refreshToken: String
+ let expiresIn: Double
+
+ var grant: Grant {
+ Grant(access_token: accessToken, refresh_token: refreshToken, expires_in: expiresIn)
+ }
+}
+
+private struct Credentials: Encodable {
+ let username: String
+ let password: String
+}
+
+private struct Refresh: Encodable { let refreshToken: String }
private struct Problem: Decodable { let detail: String? }
private struct GrantError: Decodable { let error: String }
@@ -63,23 +73,9 @@ private final class NoRedirects: NSObject, URLSessionTaskDelegate {
@MainActor
@Observable
final class AtlasAccount {
- enum SignInProgress {
- case connecting
- case authenticating
- case finishing
-
- var title: String {
- switch self {
- case .connecting: "正在连接…"
- case .authenticating: "等待登录…"
- case .finishing: "正在完成登录…"
- }
- }
- }
-
private static let identityTimeout: TimeInterval = 15
private(set) var signedIn = false
- private(set) var signInProgress: SignInProgress?
+ private(set) var signingIn = false
private(set) var error: String?
private let configuration = try? AtlasEndpoints()
private let http: URLSession
@@ -87,7 +83,6 @@ final class AtlasAccount {
private var metadata: OIDCMetadata?
private var refreshTask: Task?
private var generation = UUID()
- private let browser = LoginBrowser()
init() {
let config = URLSessionConfiguration.ephemeral
@@ -103,45 +98,21 @@ final class AtlasAccount {
}
}
- func signIn() async {
- guard signInProgress == nil else { return }
- signInProgress = .connecting
+ func signIn(username: String, password: String) async {
+ guard !signingIn, !Task.isCancelled else { return }
+ signingIn = true
error = nil
- defer { signInProgress = nil }
+ defer { signingIn = false }
do {
guard let configuration else { throw AtlasError("登录服务地址未配置。") }
- let discovery = try await discover(configuration)
- let verifier = try Self.randomString()
- let state = try Self.randomString()
- let challenge = Self.base64URL(Data(SHA256.hash(data: Data(verifier.utf8))))
- guard var url = URLComponents(url: discovery.authorization_endpoint, resolvingAgainstBaseURL: false) else {
- throw AtlasError("登录地址无效。")
- }
- url.queryItems = [
- .init(name: "client_id", value: AtlasEndpoints.client), .init(name: "response_type", value: "code"),
- .init(name: "scope", value: "openid profile"), .init(name: "redirect_uri", value: AtlasEndpoints.redirect),
- .init(name: "state", value: state), .init(name: "code_challenge_method", value: "S256"),
- .init(name: "code_challenge", value: challenge)
- ]
- guard let authorizationURL = url.url else { throw AtlasError("登录地址无效。") }
- // Ephemeral browser sessions let a different person sign in after switching accounts.
- signInProgress = .authenticating
- let callback = try await browser.authenticate(authorizationURL)
- signInProgress = .finishing
- let result = URLComponents(url: callback, resolvingAgainstBaseURL: false)
- let parameters = result?.queryItems ?? []
- guard result?.scheme == AtlasEndpoints.scheme, result?.host == nil,
- result?.path == "/oauth2/callback", parameters.filter({ $0.name == "state" }).map(\.value) == [state],
- parameters.filter({ $0.name == "code" }).count == 1,
- let code = parameters.first(where: { $0.name == "code" })?.value, !code.isEmpty else {
- throw AtlasError("登录未完成,请重试。")
- }
- let grant = try await exchange(discovery.token_endpoint, [
- "grant_type": "authorization_code", "code": code, "code_verifier": verifier,
- "redirect_uri": AtlasEndpoints.redirect, "client_id": AtlasEndpoints.client
- ])
- try save(grant, configuration: configuration)
- } catch ASWebAuthenticationSessionError.canceledLogin {
+ let grant = try await nativeGrant("login", body: Credentials(username: username, password: password),
+ configuration: configuration)
+ try Task.checkCancellation()
+ try save(grant, native: true, configuration: configuration)
+ } catch is CancellationError {
+ } catch let error as URLError where error.code == .cancelled {
+ } catch is ExpiredGrant {
+ error = "账号或密码不正确。"
} catch is URLError {
error = "暂时连不上登录服务。请检查网络后重试。"
} catch {
@@ -149,12 +120,20 @@ final class AtlasAccount {
}
}
+ func clearSignInError() {
+ error = nil
+ }
+
func signOut() async {
guard let configuration else { return }
- let refreshToken = tokens?.grant.refresh_token
+ let previous = tokens
do { try clear(configuration) }
catch { self.error = error.localizedDescription; return }
- if let refreshToken, let discovery = try? await discover(configuration), let revoke = discovery.revocation_endpoint {
+ guard let previous else { return }
+ let refreshToken = previous.grant.refresh_token
+ if previous.native == true {
+ _ = try? await nativeRequest("logout", body: Refresh(refreshToken: refreshToken), configuration: configuration)
+ } else if let discovery = try? await discover(configuration), let revoke = discovery.revocation_endpoint {
let request = Self.form(revoke, ["client_id": AtlasEndpoints.client,
"token": refreshToken, "token_type_hint": "refresh_token"])
_ = try? await http.data(for: request)
@@ -198,14 +177,21 @@ final class AtlasAccount {
if let refreshTask { return try await refreshTask.value }
let currentGeneration = generation
let task = Task { @MainActor in
- let discovery = try await self.discover(configuration)
do {
- let grant = try await self.exchange(discovery.token_endpoint, [
- "grant_type": "refresh_token", "refresh_token": tokens.grant.refresh_token,
- "client_id": AtlasEndpoints.client
- ])
+ let grant: Grant
+ let native = tokens.native == true
+ if native {
+ grant = try await self.nativeGrant("refresh", body: Refresh(refreshToken: tokens.grant.refresh_token),
+ configuration: configuration)
+ } else {
+ let discovery = try await self.discover(configuration)
+ grant = try await self.exchange(discovery.token_endpoint, [
+ "grant_type": "refresh_token", "refresh_token": tokens.grant.refresh_token,
+ "client_id": AtlasEndpoints.client
+ ])
+ }
guard self.generation == currentGeneration else { throw CancellationError() }
- try self.save(grant, configuration: configuration)
+ try self.save(grant, native: native, configuration: configuration)
return grant.access_token
} catch is ExpiredGrant {
if self.generation == currentGeneration { try self.clear(configuration) }
@@ -224,7 +210,7 @@ final class AtlasAccount {
let (body, response) = try await http.data(for: request)
guard (response as? HTTPURLResponse)?.statusCode == 200,
let result = try? JSONDecoder().decode(OIDCMetadata.self, from: body), result.issuer == configuration.issuer,
- Self.sameOrigin(result.authorization_endpoint, result.issuer), Self.sameOrigin(result.token_endpoint, result.issuer),
+ Self.sameOrigin(result.token_endpoint, result.issuer),
result.revocation_endpoint.map({ Self.sameOrigin($0, result.issuer) }) ?? true else {
throw AtlasError("暂时连不上登录服务,请稍后重试。")
}
@@ -234,6 +220,30 @@ final class AtlasAccount {
private struct ExpiredGrant: Error {}
+ private func nativeRequest(_ action: String, body: some Encodable,
+ configuration: AtlasEndpoints) async throws -> (Data, Int) {
+ guard let url = URL(string: "/api/session/" + action, relativeTo: configuration.api)?.absoluteURL else {
+ throw AtlasError("登录地址无效。")
+ }
+ var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: Self.identityTimeout)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
+ request.httpBody = try JSONEncoder().encode(body)
+ let (data, response) = try await http.data(for: request)
+ return (data, (response as? HTTPURLResponse)?.statusCode ?? 0)
+ }
+
+ private func nativeGrant(_ action: String, body: some Encodable, configuration: AtlasEndpoints) async throws -> Grant {
+ let (data, status) = try await nativeRequest(action, body: body, configuration: configuration)
+ if status == 401 { throw ExpiredGrant() }
+ if status == 429 { throw AtlasError("操作太频繁,请稍等再试。") }
+ guard status == 200, let result = try? JSONDecoder().decode(NativeGrant.self, from: data),
+ !result.accessToken.isEmpty, !result.refreshToken.isEmpty, result.expiresIn > 0 else {
+ throw AtlasError("暂时连不上登录服务,请稍后重试。")
+ }
+ return result.grant
+ }
+
private func exchange(_ url: URL, _ parameters: [String: String]) async throws -> Grant {
let (body, response) = try await http.data(for: Self.form(url, parameters))
guard (response as? HTTPURLResponse)?.statusCode == 200,
@@ -245,8 +255,8 @@ final class AtlasAccount {
return grant
}
- private func save(_ grant: Grant, configuration: AtlasEndpoints) throws {
- let session = SessionTokens(grant: grant, expires: .now.addingTimeInterval(grant.expires_in))
+ private func save(_ grant: Grant, native: Bool, configuration: AtlasEndpoints) throws {
+ let session = SessionTokens(grant: grant, expires: .now.addingTimeInterval(grant.expires_in), native: native)
try TokenKeychain.save(session, key: configuration.issuer.absoluteString)
tokens = session
signedIn = true
@@ -277,18 +287,6 @@ final class AtlasAccount {
&& url.user == nil && url.password == nil && url.fragment == nil
}
- private static func randomString() throws -> String {
- var bytes = [UInt8](repeating: 0, count: 32)
- guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else {
- throw AtlasError("无法启动安全登录,请重试。")
- }
- return base64URL(Data(bytes))
- }
-
- private static func base64URL(_ data: Data) -> String {
- data.base64EncodedString().replacingOccurrences(of: "+", with: "-")
- .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
- }
}
private enum TokenKeychain {
@@ -330,36 +328,3 @@ private enum TokenKeychain {
if status != errSecSuccess { throw AtlasError("无法访问本机钥匙串,请解锁设备后重试。") }
}
}
-
-@MainActor
-private final class LoginBrowser: NSObject, ASWebAuthenticationPresentationContextProviding {
- private var anchor: ASPresentationAnchor?
- private var session: ASWebAuthenticationSession?
-
- func authenticate(_ url: URL) async throws -> URL {
- guard let window = UIApplication.shared.connectedScenes
- .compactMap({ $0 as? UIWindowScene }).filter({ $0.activationState == .foregroundActive })
- .flatMap(\.windows).first(where: \.isKeyWindow) else {
- throw AtlasError("找不到当前窗口,请返回见物后重试。")
- }
- anchor = window
- defer { anchor = nil; session = nil }
- return try await withCheckedThrowingContinuation { continuation in
- let authentication = ASWebAuthenticationSession(url: url, callbackURLScheme: AtlasEndpoints.scheme) { url, error in
- if let error { continuation.resume(throwing: error) }
- else if let url { continuation.resume(returning: url) }
- else { continuation.resume(throwing: AtlasError("登录未完成,请重试。")) }
- }
- authentication.presentationContextProvider = self
- authentication.prefersEphemeralWebBrowserSession = true
- session = authentication
- if !authentication.start() {
- continuation.resume(throwing: AtlasError("无法打开登录页面,请重试。"))
- }
- }
- }
-
- func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
- anchor ?? ASPresentationAnchor()
- }
-}
diff --git a/apps/ios/ItemAtlas/ItemAtlasApp.swift b/apps/ios/ItemAtlas/ItemAtlasApp.swift
index 4c346dc..5540e77 100644
--- a/apps/ios/ItemAtlas/ItemAtlasApp.swift
+++ b/apps/ios/ItemAtlas/ItemAtlasApp.swift
@@ -10,7 +10,9 @@ struct ItemAtlasApp: App {
if account.signedIn {
SpacesView(account: account)
} else {
- WelcomeView(account: account)
+ NavigationStack {
+ WelcomeView(account: account)
+ }
}
}
.tint(.atlasBlue)
diff --git a/apps/ios/ItemAtlas/SignInView.swift b/apps/ios/ItemAtlas/SignInView.swift
new file mode 100644
index 0000000..6d20b7f
--- /dev/null
+++ b/apps/ios/ItemAtlas/SignInView.swift
@@ -0,0 +1,138 @@
+import SwiftUI
+
+struct SignInView: View {
+ private enum Field: Hashable { case account, password }
+
+ let account: AtlasAccount
+ @Environment(\.colorScheme) private var colorScheme
+ @FocusState private var focusedField: Field?
+ @AccessibilityFocusState private var errorFocused: Bool
+ @State private var username = ""
+ @State private var password = ""
+ @State private var passwordVisible = false
+ @State private var submission: Task?
+
+ private var hasCredentials: Bool {
+ !username.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !password.isEmpty
+ }
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 26) {
+ EntryBrand()
+ VStack(alignment: .leading, spacing: 8) {
+ Text("登录我的空间")
+ .font(.largeTitle.bold())
+ .accessibilityAddTraits(.isHeader)
+ Text("登录后,继续管理你和家人的物品。")
+ .font(.subheadline)
+ .foregroundStyle(.primary.opacity(0.72))
+ }
+ VStack(alignment: .leading, spacing: 17) {
+ field(label: "账号", active: focusedField == .account) {
+ TextField("输入用户名", text: $username)
+ .textContentType(.username)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ .focused($focusedField, equals: .account)
+ .submitLabel(.next)
+ .onSubmit { focusedField = .password }
+ .accessibilityLabel("账号")
+ }
+ field(label: "密码", active: focusedField == .password) {
+ Group {
+ if passwordVisible {
+ TextField("输入密码", text: $password)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ } else {
+ SecureField("输入密码", text: $password)
+ }
+ }
+ .textContentType(.password)
+ .focused($focusedField, equals: .password)
+ .submitLabel(.go)
+ .onSubmit(submit)
+ .accessibilityLabel("密码")
+
+ Button {
+ passwordVisible.toggle()
+ } label: {
+ Image(systemName: passwordVisible ? "eye.slash" : "eye")
+ .frame(width: 44, height: 44)
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.secondary)
+ .accessibilityLabel(passwordVisible ? "隐藏密码" : "显示密码")
+ }
+ if let error = account.error {
+ Label(error, systemImage: "exclamationmark.circle")
+ .font(.footnote)
+ .foregroundStyle(Color.red)
+ .accessibilityFocused($errorFocused)
+ }
+ Button(action: submit) {
+ HStack(spacing: 8) {
+ if account.signingIn {
+ ProgressView().tint(.white).accessibilityHidden(true)
+ }
+ Text(account.signingIn ? "正在登录…" : "登录")
+ }
+ .font(.body.weight(.semibold))
+ .frame(maxWidth: .infinity, minHeight: 29)
+ }
+ .buttonStyle(.borderedProminent)
+ .buttonBorderShape(.roundedRectangle(radius: 14))
+ .controlSize(.large)
+ .disabled(!hasCredentials || account.signingIn)
+ }
+ }
+ .fixedSize(horizontal: false, vertical: true)
+ .frame(maxWidth: 440, alignment: .leading)
+ .padding(.horizontal, 24)
+ .padding(.top, 19)
+ .padding(.bottom, 32)
+ .frame(maxWidth: .infinity)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .background(Color.entryBackground(for: colorScheme).ignoresSafeArea())
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar(.visible, for: .navigationBar)
+ .onAppear { account.clearSignInError() }
+ .onChange(of: account.error) { _, error in
+ if error != nil { errorFocused = true }
+ }
+ .onDisappear {
+ submission?.cancel()
+ password = ""
+ }
+ }
+
+ private func field(label: String, active: Bool, @ViewBuilder content: () -> Content) -> some View {
+ VStack(alignment: .leading, spacing: 7) {
+ Text(label)
+ .font(.subheadline.weight(.semibold))
+ .accessibilityHidden(true)
+ HStack(spacing: 6, content: content)
+ .padding(.leading, 14)
+ .padding(.trailing, 8)
+ .frame(minHeight: 54)
+ .background(Color(uiColor: .secondarySystemGroupedBackground), in: .rect(cornerRadius: 13))
+ .overlay {
+ RoundedRectangle(cornerRadius: 13)
+ .strokeBorder(active ? .atlasBlue : Color(uiColor: .separator), lineWidth: active ? 2 : 1)
+ .allowsHitTesting(false)
+ }
+ }
+ }
+
+ private func submit() {
+ guard hasCredentials, !account.signingIn, submission == nil else { return }
+ focusedField = nil
+ passwordVisible = false
+ submission = Task {
+ await account.signIn(username: username, password: password)
+ submission = nil
+ }
+ }
+}
diff --git a/apps/ios/ItemAtlas/WelcomeView.swift b/apps/ios/ItemAtlas/WelcomeView.swift
index b490419..ae28f63 100644
--- a/apps/ios/ItemAtlas/WelcomeView.swift
+++ b/apps/ios/ItemAtlas/WelcomeView.swift
@@ -1,28 +1,38 @@
import SwiftUI
+struct EntryBrand: View {
+ var body: some View {
+ HStack(spacing: 9) {
+ Image("BrandMark")
+ .resizable()
+ .frame(width: 32, height: 32)
+ .clipShape(.rect(cornerRadius: 8))
+ .accessibilityHidden(true)
+ Text("见物").font(.headline)
+ }
+ }
+}
+
+extension Color {
+ static func entryBackground(for scheme: ColorScheme) -> Color {
+ scheme == .dark ? Color(uiColor: .systemBackground) : Color(red: 0.976, green: 0.969, blue: 0.951)
+ }
+}
+
struct WelcomeView: View {
let account: AtlasAccount
@Environment(\.colorScheme) private var colorScheme
@ScaledMetric(relativeTo: .largeTitle) private var headlineSize = 38.0
@State private var showingGuide = false
- @AccessibilityFocusState private var errorFocused: Bool
private var canvas: Color {
- colorScheme == .dark ? Color(uiColor: .systemBackground) : Color(red: 0.976, green: 0.969, blue: 0.951)
+ .entryBackground(for: colorScheme)
}
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 22) {
- HStack(spacing: 9) {
- Image("BrandMark")
- .resizable()
- .frame(width: 32, height: 32)
- .clipShape(.rect(cornerRadius: 8))
- .accessibilityHidden(true)
- Text("见物")
- .font(.headline)
- }
+ EntryBrand()
VStack(alignment: .leading, spacing: 9) {
Text("放在哪里,\n一找就知道。")
@@ -68,40 +78,22 @@ struct WelcomeView: View {
actions
}
.background(canvas.ignoresSafeArea())
+ .toolbar(.hidden, for: .navigationBar)
.sheet(isPresented: $showingGuide) {
WelcomeGuide()
}
- .onChange(of: account.error) { _, error in
- if error != nil { errorFocused = true }
- }
}
private var actions: some View {
VStack(spacing: 5) {
- if let error = account.error {
- Label(error, systemImage: "exclamationmark.circle")
- .font(.footnote)
- .foregroundStyle(.primary)
- .frame(maxWidth: .infinity, alignment: .leading)
- .padding(12)
- .background(.thinMaterial, in: .rect(cornerRadius: 12))
- .accessibilityFocused($errorFocused)
- .padding(.bottom, 4)
- }
-
- Button {
- Task { await account.signIn() }
+ NavigationLink {
+ SignInView(account: account)
} label: {
HStack(spacing: 9) {
- if let progress = account.signInProgress {
- ProgressView().tint(.white).accessibilityHidden(true)
- Text(progress.title)
- } else {
- Text(account.error == nil ? "登录我的空间" : "重试登录")
- Image(systemName: "arrow.right")
- .font(.subheadline.weight(.semibold))
- .accessibilityHidden(true)
- }
+ Text("登录我的空间")
+ Image(systemName: "arrow.right")
+ .font(.subheadline.weight(.semibold))
+ .accessibilityHidden(true)
}
.font(.body.weight(.semibold))
.frame(maxWidth: .infinity, minHeight: 29)
@@ -109,12 +101,9 @@ struct WelcomeView: View {
.buttonStyle(.borderedProminent)
.buttonBorderShape(.roundedRectangle(radius: 15))
.controlSize(.large)
- .disabled(account.signInProgress != nil)
-
Button("看看怎么用") { showingGuide = true }
.font(.subheadline.weight(.semibold))
.frame(minHeight: 44)
- .disabled(account.signInProgress != nil)
}
.frame(maxWidth: 472)
.padding(.horizontal, 24)
diff --git a/apps/ios/README.md b/apps/ios/README.md
index 53cf2c6..9eacd21 100644
--- a/apps/ios/README.md
+++ b/apps/ios/README.md
@@ -4,11 +4,11 @@
## 登录与空间
-未登录时展示首页和使用说明,两者都可以离线查看。点「登录我的空间」后,App 显示连接和完成登录的状态,随后进入当前账号的空间。取消会回到首页,连接失败可重试。
+未登录时展示首页和使用说明,两者都可以离线查看。点「登录我的空间」进入 SwiftUI 表单,表单内输入账号密码、查看登录进度和处理错误。返回后清除密码。登录成功才加载用户的空间。 [首页与登录设计稿](../../docs/ui/ios-welcome.md)
-登录用 iOS 系统认证窗口打开 Keycloak,授权码通过 `com.tutudog.itematlas:/oauth2/callback` 返回,使用 S256 PKCE。App 把会话凭证保存在设备钥匙串。物品、位置与收藏由服务端按账号和空间返回。首次登录可新建空间或使用邀请码,新空间显示空状态。 [首页与登录设计](../../docs/ui/ios-welcome.md)
+新登录通过 `POST /api/session/login`。App 把会话凭证保存在设备钥匙串,服务端按账号和空间返回物品、位置与收藏。首次登录可新建或通过邀请码加入空间,新空间显示空状态。升级后原 Keycloak 登录会话仍可刷新,退出后的再次登录走原生表单。
-构建时可用 `ATLAS_API_BASE_URL` 和 `ATLAS_OIDC_ISSUER` 覆盖默认 HTTPS 地址。新环境须先登记 `atlas-ios` 原生客户端和精确回调,配套 issuer、audience 和服务端校验。参见 [身份和图片部署](../../docs/deployment/identity-and-media.md)。 如果点登录时提示服务请求失败,先检查 [公网解析、登录发现地址和网关](../../docs/deployment/identity-and-media.md#ios-公网连通性验收)。
+构建时可用 `ATLAS_API_BASE_URL` 覆盖默认 HTTPS API。已有版本的 Keycloak 会话以 `ATLAS_OIDC_ISSUER` 区分。新环境要准备登录签名配置和用户,并验证 [公网路由和原生会话](../../docs/deployment/identity-and-media.md#ios-公网连通性验收)。
## 物品与图片
diff --git a/backend/README.md b/backend/README.md
index 1f1079f..37b4dd6 100644
--- a/backend/README.md
+++ b/backend/README.md
@@ -5,7 +5,8 @@ Java 21、Maven、Spring Boot 4.2、Spring Cloud Gateway 和 Spring AI。两个
| 模块 | 主要职责 |
| --- | --- |
| `gateway/` | 路由和请求大小限制。部署时可开启物品 GET 请求灰度。 |
-| `inventory-service/` | 家庭角色、位置、物品、移位、关联、搜索和个人偏好。 |
+| `api-auth/` | 业务服务共用的原生会话和 Keycloak JWT 验签配置。 |
+| `inventory-service/` | 原生会话、家庭角色、位置、物品、移位、关联、搜索和个人偏好。 |
| `intake-service/` | 原话、模型草稿、确认操作、后台投递和状态查询。 |
## 启动与验证
@@ -21,6 +22,8 @@ Compose 的 `local` profile 带 `owner`、`viewer`、`other` 三个演示用户
以下资源在 `/api/households/{householdId}` 下。家庭列表为 `GET /api/households`,提供方状态为 `GET /api/model-providers`。
+原生会话使用 `POST /api/session/login` 提交 `username` 和 `password`。续期和退出使用 `POST /api/session/refresh` 与 `POST /api/session/logout`,两者都提交 `refreshToken`。启用条件及原有空间绑定见 [iOS 原生会话](../docs/deployment/identity-and-media.md#ios-原生会话)。
+
| 资源 | 操作 |
| --- | --- |
| `/members`、`/invitations` | 所有者查看成员、调整权限、移除成员和管理一次性邀请。 [家庭邀请与成员权限](../docs/architecture/household-access.md) |
@@ -30,7 +33,7 @@ Compose 的 `local` profile 带 `owner`、`viewer`、`other` 三个演示用户
| `/drafts`、`/drafts/{id}` | 保留整理原话,返回候选或不可用状态。 |
| `/drafts/{id}/confirm`、`/operations/{id}` | 提交核对过的物品及位置,取得操作号和最终状态。重复提交同一版本返回原操作号。 |
-本地模型接入 Ollama。云端提供方当前返回待配置。正式环境的账户开通、附件、云模型额度和完整接口契约后续接入。
+本地模型接入 Ollama。云端提供方当前返回待配置。正式环境的自助开户、云模型额度和完整接口契约后续接入。
[系统架构](../docs/architecture/system.md) · [部署和回退](../docs/deployment/backend-release.md) · [Maven 标准目录](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html)
diff --git a/backend/api-auth/pom.xml b/backend/api-auth/pom.xml
new file mode 100644
index 0000000..3e57fac
--- /dev/null
+++ b/backend/api-auth/pom.xml
@@ -0,0 +1,17 @@
+
+
+ 4.0.0
+
+ com.tutudog.itematlas
+ item-atlas-backend
+ 0.1.0-SNAPSHOT
+
+ item-atlas-api-auth
+
+ org.springframework.bootspring-boot-autoconfigure
+ org.springframework.securityspring-security-oauth2-jose
+ org.springframework.bootspring-boot-starter-testtest
+
+
diff --git a/backend/api-auth/src/main/java/com/tutudog/itematlas/auth/NativeJwtTrust.java b/backend/api-auth/src/main/java/com/tutudog/itematlas/auth/NativeJwtTrust.java
new file mode 100644
index 0000000..7cc5158
--- /dev/null
+++ b/backend/api-auth/src/main/java/com/tutudog/itematlas/auth/NativeJwtTrust.java
@@ -0,0 +1,63 @@
+package com.tutudog.itematlas.auth;
+
+import com.nimbusds.jwt.SignedJWT;
+import java.security.KeyFactory;
+import java.security.interfaces.RSAPublicKey;
+import java.security.spec.X509EncodedKeySpec;
+import java.text.ParseException;
+import java.util.Base64;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Profile;
+import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
+import org.springframework.security.oauth2.jwt.BadJwtException;
+import org.springframework.security.oauth2.jwt.JwtAudienceValidator;
+import org.springframework.security.oauth2.jwt.JwtDecoder;
+import org.springframework.security.oauth2.jwt.JwtValidators;
+import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
+
+@Configuration(proxyBeanMethods = false)
+@Profile("!local")
+@ConditionalOnProperty(name = "atlas.native.issuer")
+public class NativeJwtTrust {
+ @Bean
+ JwtDecoder apiJwtDecoder(
+ @Value("${spring.security.oauth2.resourceserver.jwt.issuer-uri}") String oidcIssuer,
+ @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri:}") String jwks,
+ @Value("${spring.security.oauth2.resourceserver.jwt.audiences}") String audience,
+ @Value("${atlas.native.issuer}") String nativeIssuer,
+ @Value("${atlas.native.public-key}") String encodedKey) throws Exception {
+ if (nativeIssuer.isBlank() || nativeIssuer.equals(oidcIssuer)) {
+ throw new IllegalArgumentException("Native session issuer must be distinct from the OIDC issuer");
+ }
+ var nativeDecoder = NimbusJwtDecoder.withPublicKey(publicKey(encodedKey)).build();
+ verifyClaims(nativeDecoder, nativeIssuer, audience);
+ var oidcDecoder = jwks.isBlank() ? NimbusJwtDecoder.withIssuerLocation(oidcIssuer).build()
+ : NimbusJwtDecoder.withJwkSetUri(jwks).build();
+ verifyClaims(oidcDecoder, oidcIssuer, audience);
+ return token -> {
+ String issuer;
+ try {
+ // Select a configured verifier. Issuer, audience, signature and dates are checked by that verifier.
+ issuer = SignedJWT.parse(token).getJWTClaimsSet().getIssuer();
+ } catch (ParseException ex) {
+ throw new BadJwtException("Invalid access token", ex);
+ }
+ if (nativeIssuer.equals(issuer)) return nativeDecoder.decode(token);
+ if (oidcIssuer.equals(issuer)) return oidcDecoder.decode(token);
+ throw new BadJwtException("Unrecognized token issuer");
+ };
+ }
+
+ private static void verifyClaims(NimbusJwtDecoder decoder, String issuer, String audience) {
+ decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(
+ JwtValidators.createDefaultWithIssuer(issuer), new JwtAudienceValidator(audience)));
+ }
+
+ public static RSAPublicKey publicKey(String encodedKey) throws Exception {
+ var spec = new X509EncodedKeySpec(Base64.getDecoder().decode(encodedKey));
+ return (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(spec);
+ }
+}
diff --git a/backend/gateway/src/main/resources/application.yml b/backend/gateway/src/main/resources/application.yml
index f87c4e8..dc468bf 100644
--- a/backend/gateway/src/main/resources/application.yml
+++ b/backend/gateway/src/main/resources/application.yml
@@ -9,6 +9,14 @@ spring:
connect-timeout: 3000
response-timeout: 75s
routes:
+ - id: native-session
+ order: -20
+ uri: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081}
+ predicates:
+ - Method=POST
+ - Path=/api/session/login,/api/session/refresh,/api/session/logout
+ filters:
+ - RequestSize=4KB
- id: intake
order: -10
uri: ${ATLAS_INTAKE_URL:http://127.0.0.1:8082}
diff --git a/backend/intake-service/pom.xml b/backend/intake-service/pom.xml
index b82d6c1..8195953 100644
--- a/backend/intake-service/pom.xml
+++ b/backend/intake-service/pom.xml
@@ -11,6 +11,7 @@
item-atlas-intake-service
+ com.tutudog.itematlasitem-atlas-api-auth${project.version}
org.springframework.bootspring-boot-starter-webmvc
org.springframework.bootspring-boot-starter-security
org.springframework.bootspring-boot-starter-security-oauth2-resource-server
diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java
index e83ad20..e8bc6ca 100644
--- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java
+++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java
@@ -1,8 +1,10 @@
package com.tutudog.itematlas.intake;
+import com.tutudog.itematlas.auth.NativeJwtTrust;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
@@ -15,6 +17,7 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration(proxyBeanMethods = false)
+@Import(NativeJwtTrust.class)
class ApiSecurity {
@Bean
@Profile("!local")
diff --git a/backend/inventory-service/pom.xml b/backend/inventory-service/pom.xml
index 23446d7..0b09006 100644
--- a/backend/inventory-service/pom.xml
+++ b/backend/inventory-service/pom.xml
@@ -14,6 +14,7 @@
2.57.5
+ com.tutudog.itematlasitem-atlas-api-auth${project.version}
software.amazon.awssdks3${aws-sdk.version}
software.amazon.awssdkurl-connection-client${aws-sdk.version}
org.springframework.bootspring-boot-starter-webmvc
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java
index 69acd27..db362b7 100644
--- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java
@@ -1,8 +1,10 @@
package com.tutudog.itematlas.inventory;
+import com.tutudog.itematlas.auth.NativeJwtTrust;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
@@ -21,6 +23,7 @@ import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration(proxyBeanMethods = false)
+@Import(NativeJwtTrust.class)
class ApiSecurity {
@Bean
@Profile("!local")
@@ -64,6 +67,8 @@ class ApiSecurity {
.authorizeHttpRequests(request -> request
.requestMatchers("/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.GET, "/actuator/prometheus").permitAll()
+ .requestMatchers(HttpMethod.POST, "/api/session/login", "/api/session/refresh",
+ "/api/session/logout").permitAll()
.requestMatchers("/internal/**").hasAnyAuthority("SCOPE_atlas.deliver", "ROLE_DELIVERY")
.requestMatchers("/api/admin/**").access(AuthorizationManagers.allOf(
AuthorityAuthorizationManager.hasRole("ATLAS_SPACE_ADMIN"),
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/NativeSessionController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/NativeSessionController.java
new file mode 100644
index 0000000..5fbf48e
--- /dev/null
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/NativeSessionController.java
@@ -0,0 +1,54 @@
+package com.tutudog.itematlas.inventory;
+
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.http.CacheControl;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@Profile("!local")
+@ConditionalOnProperty(name = "atlas.native.private-key")
+@RequestMapping(path = "/api/session", consumes = MediaType.APPLICATION_JSON_VALUE)
+class NativeSessionController {
+ private final NativeSessions sessions;
+
+ NativeSessionController(NativeSessions sessions) {
+ this.sessions = sessions;
+ }
+
+ @PostMapping("/login")
+ ResponseEntity login(@RequestBody Credentials body) {
+ return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(sessions.login(body.username(), body.password()));
+ }
+
+ @PostMapping("/refresh")
+ ResponseEntity refresh(@RequestBody Refresh body) {
+ return ResponseEntity.ok().cacheControl(CacheControl.noStore()).body(sessions.refresh(body.refreshToken()));
+ }
+
+ @PostMapping("/logout")
+ ResponseEntity logout(@RequestBody Refresh body) {
+ sessions.logout(body.refreshToken());
+ return ResponseEntity.noContent().cacheControl(CacheControl.noStore()).build();
+ }
+
+ @ExceptionHandler(BadCredentialsException.class)
+ ResponseEntity invalidCredentials() {
+ return ResponseEntity.status(401).cacheControl(CacheControl.noStore()).build();
+ }
+
+ private record Credentials(String username, String password) {
+ @Override public String toString() { return "Credentials[redacted]"; }
+ }
+
+ private record Refresh(String refreshToken) {
+ @Override public String toString() { return "Refresh[redacted]"; }
+ }
+}
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/NativeSessions.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/NativeSessions.java
new file mode 100644
index 0000000..d4c21ee
--- /dev/null
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/NativeSessions.java
@@ -0,0 +1,167 @@
+package com.tutudog.itematlas.inventory;
+
+import com.nimbusds.jose.jwk.JWKSet;
+import com.nimbusds.jose.jwk.RSAKey;
+import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
+import com.tutudog.itematlas.auth.NativeJwtTrust;
+import java.nio.charset.StandardCharsets;
+import java.security.KeyFactory;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.interfaces.RSAPrivateKey;
+import java.security.spec.PKCS8EncodedKeySpec;
+import java.sql.Types;
+import java.time.Duration;
+import java.time.OffsetDateTime;
+import java.time.ZoneOffset;
+import java.util.Base64;
+import java.util.HexFormat;
+import java.util.List;
+import java.util.Locale;
+import java.util.UUID;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+import org.springframework.context.annotation.Profile;
+import org.springframework.jdbc.core.simple.JdbcClient;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
+import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
+import org.springframework.security.oauth2.jwt.JwsHeader;
+import org.springframework.security.oauth2.jwt.JwtClaimsSet;
+import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
+import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Profile("!local")
+@ConditionalOnProperty(name = "atlas.native.private-key")
+class NativeSessions {
+ private static final Duration ACCESS_LIFETIME = Duration.ofMinutes(5);
+ private static final Duration REFRESH_LIFETIME = Duration.ofDays(30);
+ private static final int ATTEMPT_LIMIT = 5;
+
+ private final JdbcClient db;
+ private final String issuer;
+ private final String audience;
+ private final NimbusJwtEncoder encoder;
+ private final SecureRandom random = new SecureRandom();
+ private final BCryptPasswordEncoder passwords = new BCryptPasswordEncoder(12);
+ private final String unknownAccountHash = passwords.encode(UUID.randomUUID().toString());
+
+ NativeSessions(JdbcClient db, @Value("${atlas.native.issuer}") String issuer,
+ @Value("${spring.security.oauth2.resourceserver.jwt.audiences}") String audience,
+ @Value("${atlas.native.public-key}") String publicKey,
+ @Value("${atlas.native.private-key}") String privateKey) throws Exception {
+ this.db = db;
+ this.issuer = issuer;
+ this.audience = audience;
+ var publicRsa = NativeJwtTrust.publicKey(publicKey);
+ var privateSpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
+ var privateRsa = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(privateSpec);
+ if (publicRsa.getModulus().bitLength() < 2048 || !publicRsa.getModulus().equals(privateRsa.getModulus())) {
+ throw new IllegalArgumentException("Native session keys do not form an RSA key pair of at least 2048 bits");
+ }
+ var key = new RSAKey.Builder(publicRsa).privateKey(privateRsa).build();
+ this.encoder = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));
+ }
+
+ @Transactional(noRollbackFor = BadCredentialsException.class)
+ public Grant login(String username, String password) {
+ String login = username == null ? "" : username.strip().toLowerCase(Locale.ROOT);
+ if (!login.matches("[a-z0-9][a-z0-9._@-]{0,63}") || password == null
+ || password.isEmpty() || password.getBytes(StandardCharsets.UTF_8).length > 72) {
+ throw badCredentials();
+ }
+ var account = db.sql("""
+ SELECT subject, password_hash, enabled, failed_attempts, retry_after
+ FROM native_account WHERE username = :username FOR UPDATE
+ """).param("username", login).query((rs, row) -> new Account(rs.getString("subject"),
+ rs.getString("password_hash"), rs.getBoolean("enabled"), rs.getInt("failed_attempts"),
+ rs.getObject("retry_after", OffsetDateTime.class))).optional();
+ var now = OffsetDateTime.now(ZoneOffset.UTC);
+ var eligible = account.filter(user -> user.enabled()
+ && (user.retryAfter() == null || !user.retryAfter().isAfter(now)));
+ boolean matches = passwords.matches(password, eligible.map(Account::hash).orElse(unknownAccountHash));
+ var user = eligible.orElseThrow(NativeSessions::badCredentials);
+ if (!matches) {
+ int attempts = user.retryAfter() == null ? user.failedAttempts() + 1 : 1;
+ setAttempts(login, attempts, attempts >= ATTEMPT_LIMIT ? now.plusMinutes(10) : null);
+ throw badCredentials();
+ }
+ if (user.failedAttempts() > 0) setAttempts(login, 0, null);
+ db.sql("DELETE FROM native_session WHERE subject = :subject AND expires_at <= :now")
+ .param("subject", user.subject()).param("now", now).update();
+ String refresh = randomToken();
+ db.sql("INSERT INTO native_session (refresh_hash, subject, expires_at) VALUES (:hash, :subject, :expires)")
+ .param("hash", digest(refresh)).param("subject", user.subject())
+ .param("expires", now.plus(REFRESH_LIFETIME)).update();
+ return grant(user.subject(), refresh, now);
+ }
+
+ @Transactional
+ public Grant refresh(String token) {
+ String previous = refreshHash(token);
+ String next = randomToken();
+ var now = OffsetDateTime.now(ZoneOffset.UTC);
+ // The same refresh token can only win one concurrent rotation, including across pods.
+ String subject = db.sql("""
+ UPDATE native_session s
+ SET previous_refresh_hash = s.refresh_hash, refresh_hash = :next
+ FROM native_account a
+ WHERE s.refresh_hash = :previous AND s.expires_at > :now AND a.subject = s.subject AND a.enabled
+ RETURNING s.subject
+ """).param("next", digest(next)).param("previous", previous).param("now", now)
+ .query(String.class).optional().orElseThrow(NativeSessions::badCredentials);
+ return grant(subject, next, now);
+ }
+
+ void logout(String token) {
+ db.sql("DELETE FROM native_session WHERE refresh_hash = :hash OR previous_refresh_hash = :hash")
+ .param("hash", refreshHash(token)).update();
+ }
+
+ private void setAttempts(String username, int attempts, OffsetDateTime retryAfter) {
+ db.sql("UPDATE native_account SET failed_attempts = :attempts, retry_after = :retry WHERE username = :username")
+ .param("attempts", attempts).param("retry", retryAfter, Types.TIMESTAMP_WITH_TIMEZONE)
+ .param("username", username).update();
+ }
+
+ private Grant grant(String subject, String refresh, OffsetDateTime now) {
+ var claims = JwtClaimsSet.builder().issuer(issuer).subject(subject).audience(List.of(audience))
+ .id(UUID.randomUUID().toString()).issuedAt(now.toInstant())
+ .expiresAt(now.plus(ACCESS_LIFETIME).toInstant()).build();
+ var header = JwsHeader.with(SignatureAlgorithm.RS256).build();
+ String access = encoder.encode(JwtEncoderParameters.from(header, claims)).getTokenValue();
+ return new Grant(access, refresh, ACCESS_LIFETIME.toSeconds());
+ }
+
+ private String randomToken() {
+ byte[] entropy = new byte[32];
+ random.nextBytes(entropy);
+ return Base64.getUrlEncoder().withoutPadding().encodeToString(entropy);
+ }
+
+ private static String refreshHash(String token) {
+ if (token == null || !token.matches("[A-Za-z0-9_-]{43}")) throw badCredentials();
+ return digest(token);
+ }
+
+ private static String digest(String value) {
+ try {
+ byte[] hash = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.US_ASCII));
+ return HexFormat.of().formatHex(hash);
+ } catch (NoSuchAlgorithmException ex) {
+ throw new IllegalStateException(ex);
+ }
+ }
+
+ private static BadCredentialsException badCredentials() {
+ return new BadCredentialsException("Invalid credentials or session");
+ }
+
+ private record Account(String subject, String hash, boolean enabled, int failedAttempts, OffsetDateTime retryAfter) {}
+
+ record Grant(String accessToken, String refreshToken, long expiresIn) {}
+}
diff --git a/backend/inventory-service/src/main/resources/db/migration/V5__native_sessions.sql b/backend/inventory-service/src/main/resources/db/migration/V5__native_sessions.sql
new file mode 100644
index 0000000..cc4700d
--- /dev/null
+++ b/backend/inventory-service/src/main/resources/db/migration/V5__native_sessions.sql
@@ -0,0 +1,17 @@
+CREATE TABLE native_account (
+ username varchar(64) PRIMARY KEY,
+ subject text NOT NULL UNIQUE,
+ password_hash text NOT NULL,
+ enabled boolean NOT NULL DEFAULT true,
+ failed_attempts integer NOT NULL DEFAULT 0,
+ retry_after timestamptz
+);
+
+CREATE TABLE native_session (
+ refresh_hash char(64) PRIMARY KEY,
+ previous_refresh_hash char(64) UNIQUE,
+ subject text NOT NULL REFERENCES native_account(subject) ON DELETE CASCADE,
+ expires_at timestamptz NOT NULL
+);
+
+CREATE INDEX native_session_subject ON native_session(subject);
diff --git a/backend/pom.xml b/backend/pom.xml
index 7690349..7960343 100644
--- a/backend/pom.xml
+++ b/backend/pom.xml
@@ -15,6 +15,7 @@
pom
+ api-auth
gateway
inventory-service
intake-service
diff --git a/backend/tests/native_session_smoke.py b/backend/tests/native_session_smoke.py
new file mode 100644
index 0000000..fd98ff3
--- /dev/null
+++ b/backend/tests/native_session_smoke.py
@@ -0,0 +1,71 @@
+"""Exercise a provisioned non-admin account. Password is read from stdin."""
+import argparse
+import json
+import sys
+from urllib.error import HTTPError
+from urllib.request import Request, urlopen
+
+
+def request(base, path, payload=None, token=None):
+ headers = {"Accept": "application/json"}
+ body = None
+ if payload is not None:
+ headers["Content-Type"] = "application/json"
+ body = json.dumps(payload).encode()
+ if token is not None:
+ headers["Authorization"] = "Bearer " + token
+ try:
+ response = urlopen(Request(base + path, body, headers), timeout=15)
+ except HTTPError as error:
+ response = error
+ with response:
+ return response.status, response.headers, response.read()
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("base", help="API origin")
+ parser.add_argument("username")
+ parser.add_argument("--wrong-password", action="store_true", help="Use only with dedicated test accounts")
+ args = parser.parse_args()
+ base = args.base.rstrip("/")
+ password = sys.stdin.readline().rstrip("\n")
+ if not password:
+ parser.error("Supply a password on stdin")
+
+ def post(action, payload):
+ return request(base, "/api/session/" + action, payload)
+
+ if args.wrong_password:
+ code, _, _ = post("login", {"username": args.username, "password": "wrong-" + password})
+ assert code == 401, f"wrong password returned HTTP {code}"
+
+ code, headers, body = post("login", {"username": args.username, "password": password})
+ assert code == 200 and headers.get("Cache-Control") == "no-store", f"login returned HTTP {code}"
+ grant = json.loads(body)
+ code, _, raw = request(base, "/api/households", token=grant["accessToken"])
+ assert code == 200 and isinstance(json.loads(raw), list), f"inventory returned HTTP {code}"
+ code, _, _ = request(base, "/api/model-providers", token=grant["accessToken"])
+ assert code == 200, f"intake returned HTTP {code}"
+ code, _, _ = request(base, "/api/households")
+ assert code == 401, f"anonymous inventory returned HTTP {code}"
+ admin_path = "/api/admin/households/00000000-0000-0000-0000-000000000001"
+ code, _, _ = request(base, admin_path, token=grant["accessToken"])
+ assert code in (403, 404), f"native user reached the admin API with HTTP {code}"
+
+ previous = grant["refreshToken"]
+ code, _, raw = post("refresh", {"refreshToken": previous})
+ assert code == 200, f"refresh returned HTTP {code}"
+ current = json.loads(raw)["refreshToken"]
+ assert previous != current, "refresh token did not rotate"
+ code, _, _ = post("refresh", {"refreshToken": previous})
+ assert code == 401, f"old refresh token returned HTTP {code}"
+ code, _, _ = post("logout", {"refreshToken": previous})
+ assert code == 204, f"logout returned HTTP {code}"
+ code, _, _ = post("refresh", {"refreshToken": current})
+ assert code == 401, f"revoked refresh token returned HTTP {code}"
+ print("PASS native login, both APIs, admin isolation, refresh rotation and logout")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/deploy/helm/item-atlas/templates/workloads.yaml b/deploy/helm/item-atlas/templates/workloads.yaml
index 82ceb4e..7418d36 100644
--- a/deploy/helm/item-atlas/templates/workloads.yaml
+++ b/deploy/helm/item-atlas/templates/workloads.yaml
@@ -105,23 +105,37 @@ spec:
- secretRef:
name: {{ $root.Values.mediaSecret | quote }}
{{- end }}
+ {{- with $root.Values.nativeSessions.verificationSecret }}
+ - secretRef:
+ name: {{ . | quote }}
+ {{- end }}
+ {{- if and (eq $workload.image "inventory-service") (not $workload.candidate) }}
+ {{- with $root.Values.nativeSessions.signingSecret }}
+ - secretRef:
+ name: {{ . | quote }}
+ {{- end }}
+ {{- end }}
{{- end }}
startupProbe:
httpGet:
path: /actuator/health/liveness
port: http
periodSeconds: 4
+ timeoutSeconds: 3
failureThreshold: 40
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: http
periodSeconds: 5
+ timeoutSeconds: 3
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: http
periodSeconds: 10
+ timeoutSeconds: 5
+ failureThreshold: 4
resources:
{{- toYaml (index $root.Values.resources $workload.image) | nindent 12 }}
---
diff --git a/deploy/helm/item-atlas/values.yaml b/deploy/helm/item-atlas/values.yaml
index 7e2f314..b4c320e 100644
--- a/deploy/helm/item-atlas/values.yaml
+++ b/deploy/helm/item-atlas/values.yaml
@@ -7,6 +7,9 @@ profile: release
inventorySecret: item-atlas-inventory
intakeSecret: item-atlas-intake
mediaSecret: ""
+nativeSessions:
+ verificationSecret: ""
+ signingSecret: ""
rollout:
maxSurge: 1
maxUnavailable: 0
diff --git a/deploy/public/README.md b/deploy/public/README.md
index 5a84e21..9416f3d 100644
--- a/deploy/public/README.md
+++ b/deploy/public/README.md
@@ -35,6 +35,19 @@ helm upgrade --install item-atlas deploy/helm/item-atlas -n item-atlas-public \
`jianwu` 主题继承 Keycloak 26.8.2 的 `keycloak.v2` 登录表单。首次导入会给 `atlas-ios` 设置 Login theme。已有 realm 在管理端打开 Clients → atlas-ios → Settings → Login theme,选择 `jianwu`。更新主题文件后重启 Keycloak Deployment 以刷新缓存。单副本重启期间登录入口会短暂中断。先检查主题文件和回调,再验收登录。遇到显示问题可把该客户端的 Login theme 恢复为默认。 [Keycloak 主题](https://www.keycloak.org/ui-customization/themes)
+### 原生会话配置
+
+启用公网 values 前准备两份 Secret。生成独立的 RSA 密钥对,至少 2048 位,原文件和备份保存到 SSD 的受控目录。
+
+| Secret | 内容 | 注入对象 |
+| --- | --- | --- |
+| `atlas-native-verification` | `ATLAS_NATIVE_ISSUER=https://api-atlas.tutudog.com/session` 与 `ATLAS_NATIVE_PUBLIC_KEY`(Base64 X.509 DER) | 物品、录入服务,并供只读候选验签 |
+| `atlas-native-signing` | `ATLAS_NATIVE_PRIVATE_KEY`(Base64 PKCS#8 DER) | 稳定版物品服务 |
+
+首次使用 Flyway V5 建表。运维核对用户原有的 Keycloak 用户编号后,将规范化用户名、原编号和 BCrypt 哈希插入 `native_account`。可用 `htpasswd -niB -C 12 "$ATLAS_USERNAME"` 从标准输入生成哈希,再只保存冒号后的哈希字段。更新密码时按用户事务更新哈希并清理该用户的 `native_session`,已有访问令牌最长 5 分钟到期。暂停账号时设置 `enabled=false`。
+
+渲染并加载本目录的 Nginx 模板,使 `/api/session/` 使用独立限流。在真机安装新版前先通过 [原生会话冒烟](../../docs/deployment/identity-and-media.md#ios-公网连通性验收)。若回退到早于 V5 的镜像,原生登录入口也随之回退,安排回退前先确认手机端的可用版本与登录路径。
+
## 转发和验收
在集群里用 FRP 客户端直连 `svc/item-atlas-gateway` 和 `svc/atlas-keycloak`。将 `frpc.toml.template` 渲染为受控文件,其中两条 STCP 各用独立密钥。云端 visitor 使用匹配的名称和密钥,只监听 Nginx 容器可达的私有网桥,由 systemd 管理。
@@ -48,6 +61,6 @@ kubectl -n item-atlas-public rollout status deployment/atlas-public-frpc --timeo
kubectl -n item-atlas-public logs deployment/atlas-public-frpc --tail=20
```
-日志应显示两个代理注册成功。渲染 `nginx.conf.template`,将两个 `ATLAS_VISITOR_*` 填为实际私有监听地址和端口。用 `nginx -t` 通过后重载。先用 `curl --resolve` 指定目标 IP,核对 TLS、OIDC discovery 和业务 API,再加入公网 A 记录。用公网 DNS 重新测试 iOS 授权码、PKCE 和回调,带令牌查询 `GET /api/households` 应返回 200。另查未登录的 API 及管理路径,预期分别为 401 和 404。 [iOS 验收步骤](../../docs/deployment/identity-and-media.md#ios-公网连通性验收)
+日志应显示两个代理注册成功。渲染 `nginx.conf.template`,将两个 `ATLAS_VISITOR_*` 填为实际私有监听地址和端口。用 `nginx -t` 通过后重载。先用 `curl --resolve` 指定目标 IP,核对 TLS、OIDC discovery 和业务 API,再加入公网 A 记录。通过公网跑原生会话冒烟,带令牌查询 `GET /api/households` 应返回 200。另查未登录的 API 及管理路径,预期分别为 401 和 404。仍有旧版 iOS 使用时再验一次 OIDC 授权码回调。 [iOS 验收步骤](../../docs/deployment/identity-and-media.md#ios-公网连通性验收)
工作 Mac 需要挂载 SSD 并运行 Linux VM,集群会启动 FRP 客户端并重连。通常检查顺序是 DNS、TLS、Nginx、STCP、Service 与应用。检查应用版本用 `helm history item-atlas -n item-atlas-public`,回退前先核对数据库迁移兼容性。需要关闭公网预览时停用该域名的独立 Nginx 站点。数据库和私有桶有独立备份流程。
diff --git a/deploy/public/nginx.conf.template b/deploy/public/nginx.conf.template
index 356fa5b..c24e781 100644
--- a/deploy/public/nginx.conf.template
+++ b/deploy/public/nginx.conf.template
@@ -1,3 +1,5 @@
+limit_req_zone $binary_remote_addr zone=atlas_native_session:1m rate=30r/m;
+
server {
listen 80;
server_name api-atlas.tutudog.com;
@@ -22,6 +24,12 @@ server {
proxy_read_timeout 90s;
location ^~ /api/admin/ { return 404; }
+ location ^~ /api/session/ {
+ client_max_body_size 4k;
+ limit_req zone=atlas_native_session burst=10 nodelay;
+ limit_req_status 429;
+ proxy_pass http://ATLAS_VISITOR_API;
+ }
location ^~ /api/ {
proxy_pass http://ATLAS_VISITOR_API;
}
diff --git a/deploy/public/values.yaml b/deploy/public/values.yaml
index be34a54..f83f2ed 100644
--- a/deploy/public/values.yaml
+++ b/deploy/public/values.yaml
@@ -1,4 +1,7 @@
mediaSecret: atlas-public-media
+nativeSessions:
+ verificationSecret: atlas-native-verification
+ signingSecret: atlas-native-signing
imagePullSecrets:
- name: item-atlas-registry
rollout:
diff --git a/docs/architecture/clients.md b/docs/architecture/clients.md
index 9809412..14b7745 100644
--- a/docs/architecture/clients.md
+++ b/docs/architecture/clients.md
@@ -14,6 +14,6 @@ H5 选 uni-app 是为了用贴合移动端的组件和构建方式。正式交
三个 Web 站点在自己的域名下通过 `/api` 访问网关,原生端连接 `https://api-atlas.tutudog.com`。家庭权限由后端校验,后台接口另验管理角色。模型尚未配置时界面显示状态,凭证从服务环境读取。
-各端按自己的导航、拍照、录音及权限规范单独设计。iOS 登录使用原生浏览器认证窗口,服务端通过成员关系核对空间访问。签名和商店发布在准备分发时配置。 [SwiftUI](https://developer.apple.com/swiftui/) · [Jetpack Compose](https://developer.android.com/compose)
+各端按自己的导航、拍照、录音及权限规范单独设计。iOS 在 SwiftUI 内提交账号密码,服务端按账号编号核对空间成员。Web 管理后台使用 Keycloak。签名和商店发布在准备分发时配置。 [SwiftUI](https://developer.apple.com/swiftui/) · [Jetpack Compose](https://developer.android.com/compose)
[客户端工程目录](../../apps/README.md) · [产品需求](../product/requirements.md) · [部署与域名](../deployment/overview.md)
diff --git a/docs/deployment/identity-and-media.md b/docs/deployment/identity-and-media.md
index 26a3f8f..8d3aaf7 100644
--- a/docs/deployment/identity-and-media.md
+++ b/docs/deployment/identity-and-media.md
@@ -4,35 +4,33 @@
```mermaid
flowchart LR
- phone[iOS 见物] -->|OIDC + PKCE| id[Keycloak]
- phone -->|HTTPS /api/households| edge[Nginx]
+ phone[iOS 见物] -->|HTTPS /api/session 与业务请求| edge[Nginx]
admin[管理后台] -->|OIDC + PKCE| id
admin -->|同源 /api/admin| gateway[Spring Cloud Gateway]
edge --> gateway
gateway --> inventory[物品服务]
- inventory -->|事务内附件关系与清理任务| pg[(PostgreSQL)]
+ inventory -->|会话、附件关系与清理任务| pg[(PostgreSQL)]
inventory -->|S3 Put Get Delete| oss[(私有对象存储)]
```
## Keycloak
1. 为登录环境选择固定 HTTPS issuer,填写到两个业务服务的 `ATLAS_OIDC_ISSUER_URI`。配置 `ATLAS_OIDC_AUDIENCE=item-atlas-api`。若 Pod 需要内网读取公钥,保持公网 issuer 不变,通过资源服务的 `SPRING_SECURITY_OAUTH2_RESOURCESERVER_JWT_JWK_SET_URI` 指定内网 JWKS 地址。
-2. 创建 public client `atlas-ios`,开启 Standard Flow 和 PKCE S256,关闭直接密码授予和隐式流程。Valid Redirect URIs 填 `com.tutudog.itematlas:/oauth2/callback`。给访问令牌添加 `item-atlas-api` audience。用后台创建用户并分配密码或账号激活流程。当前产品界面使用已有账号登录,可按环境选择开放注册。
+2. 为仍在使用的旧版 iOS 保留 public client `atlas-ios`。开启 Standard Flow 和 PKCE S256,关闭直接密码授予和隐式流程。Valid Redirect URIs 填 `com.tutudog.itematlas:/oauth2/callback`,访问令牌 audience 为 `item-atlas-api`。新版使用见物原生会话,升级前的令牌仍由 Keycloak 续期。
3. 创建 public client `atlas-admin`,开启 Standard Flow 和 PKCE S256。Valid Redirect URI、Web Origin、退出地址只填写管理后台的确切 HTTPS 地址。添加同一 API audience,把 realm role 映射为访问令牌的多值字符串 claim `atlas_roles`。只给管理员分配 `atlas-space-admin`。后端同时核对 `azp=atlas-admin` 和该角色。
4. 公开的 Nginx 只转发所需身份前端和业务路径。Keycloak 管理端保持独立访问控制。业务端拿用户 `sub` 查询当下的空间成员关系。退出或换号不会复用旧账号的内存数据。改用另一个 realm 前要核对既有 `sub` 的迁移。
[Keycloak OIDC 接口](https://www.keycloak.org/securing-apps/oidc-layers) · [Keycloak hostname 配置](https://www.keycloak.org/server/hostname) · [原生应用 OAuth 规范](https://datatracker.ietf.org/doc/html/rfc8252)
+## iOS 原生会话
+
+SwiftUI 登录页通过 HTTPS 发送账号密码。物品服务在 `native_account` 校验 BCrypt 哈希,并为同一个用户编号签发业务令牌。用既有账号开通时,复制其 Keycloak `sub` 到 `native_account.subject`,空间归属继续按原编号查询。原生凭据由运维开通,账号停用或重置密码时同步处理仍有访问权限的登录渠道。
+
+访问令牌使用独立 issuer 的 RS256 签名,有效期 5 分钟,audience 与业务 API 一致。两个业务服务验证其签名、受众和有效期。原生令牌只代表普通用户。刷新令牌为 32 字节随机值,数据库保存 SHA-256 摘要,30 天内可续期,每次刷新由一条原子 SQL 替换。退出时撤销刷新会话。公网 Nginx 限制登录接口的频率和请求体大小,账号校验另有失败计数。 [Spring Security 密码存储](https://docs.spring.io/spring-security/reference/features/authentication/password-storage.html)
+
## iOS 公网连通性验收
-默认 iOS 构建使用以下地址。首次登录先查询 issuer 的 discovery 文件,获取授权端点,然后打开系统登录窗口。进入空间前通过网关调用业务 API。
-
-| 配置 | 默认值 |
-| --- | --- |
-| `ATLAS_API_BASE_URL` | `https://api-atlas.tutudog.com` |
-| `ATLAS_OIDC_ISSUER` | `https://api-atlas.tutudog.com/auth/realms/item-atlas` |
-| `client_id` | `atlas-ios` |
-| 登录回调 | `com.tutudog.itematlas:/oauth2/callback` |
+默认 iOS API 为 `https://api-atlas.tutudog.com`。登录调用 `POST /api/session/login`。数据库开通用户后,运行 [会话冒烟脚本](../../backend/tests/native_session_smoke.py)。脚本从标准输入读取密码,并验证空间查询、录入服务、权限、刷新与退出。
从手机可访问的网络开始检查,用公开解析结果核对 A 或 AAAA 的实际目的地,再用 HTTPS 验证证书和两条路由。也可以用 `curl --resolve` 直连计划中的入口 IP,保留真实域名、TLS 和 Host,单独定位 DNS 问题。
@@ -47,11 +45,11 @@ curl -sS -o /dev/null -w '%{http_code}\n' "https://$host/api/households"
| 检查 | 通过条件 |
| --- | --- |
| 公网解析和 TLS | 解析到项目入口,TCP 和 HTTPS 可用,证书覆盖该域名。 |
-| Discovery | HTTP 200 和 JSON。`issuer` 等于 App 配置的完整 HTTPS 地址,授权及 token 端点也使用该 HTTPS 入口。 |
+| 原生登录 | 正确凭据返回 HTTP 200 和不缓存的令牌响应,错误凭据返回 401。 |
| 网关路径 | 未登录请求 `/api/households` 返回 HTTP 401。用正确的 access token 请求返回 200 和空间列表。 |
-| 真机登录 | 系统窗口能打开,授权码经精确回调交回 App,账号能进入自己的空间。 |
+| 真机登录 | 欢迎页推入原生表单,提交后进入原账号的空间。 |
-如果直接请求入口得到 Nginx 的 HTML 404,先查该域名的 `server_name`、`/auth/` 和 `/api/` 转发规则,以及 frp 通道对应的上游。再检查 Keycloak 的 realm、客户端回调和网关。集群内的 `atlas-keycloak` 与测试 realm 用于内网验收,正式手机入口使用独立配置的 HTTPS 身份服务。镜像发布和 Helm 健康检查本身无法验证公网路径。 [部署拓扑](overview.md) · [Keycloak hostname 配置](https://www.keycloak.org/server/hostname)
+入口返回 404 时按 Nginx、FRP、网关路由、物品服务配置的顺序排查。旧客户端续期失败另查 `/auth/`、Keycloak discovery 和客户端配置。镜像发布与 Helm 就绪之后,还要从手机可访问的网络验证公网路径。 [部署拓扑](overview.md) · [公网配置](../../deploy/public/README.md)
## 对象存储
diff --git a/docs/product/requirements.md b/docs/product/requirements.md
index 3584f69..7343906 100644
--- a/docs/product/requirements.md
+++ b/docs/product/requirements.md
@@ -16,7 +16,7 @@
## 质量要求
-- iOS 首次打开可浏览产品首页和使用说明。登录后才请求账号空间。系统认证取消后能回到首页,连接失败可重试。
+- iOS 首次打开可浏览产品首页和使用说明。账号密码在 App 内提交,成功后请求账号空间。登录页可返回首页,连接失败可重试。
- 不确定的提交结果可通过操作状态查询。确认失败时留下可恢复的草稿。
- 用带名称、别名、位置和数量的演示数据验证,有实际运行结果后再填写命中率、耗时和人工修正数。
- 备份恢复后核对物品、位置、历史和关系。演示使用独立数据。
diff --git a/docs/testing/cases.md b/docs/testing/cases.md
index 3908077..f2a444b 100644
--- a/docs/testing/cases.md
+++ b/docs/testing/cases.md
@@ -23,7 +23,8 @@ R01–R09 对应[需求与验收](../product/requirements.md)。实现和当前
| TC-17 照片裁剪和图片限制 | R09 | 选一张长图裁剪上传,分别读取清晰大图和缩略图。尝试上传超限或伪装格式的文件。 | 列表显示小图、详情显示裁剪结果,超限或不合法的图片被拒绝。 |
| TC-18 删除及 OSS 清理 | R09 | 分别删除照片、物品和空间,另用后台删除有图片的空间。暂停对象存储再恢复。 | 访问立即失效,原图和缩略图最终都被删掉。存储故障期间可观察到重试。 |
| TC-19 iOS 收起键盘 | 质量 | 在搜索、物品备注和批量录入分别输入中文,使用「收起键盘」。 | 键盘收起,已输入文字保留。 |
-| TC-20 iOS 登录前和取消 | R01 | 在未登录状态打开 App,查看并关闭使用说明。发起登录,再在系统认证窗口取消。 | 首页和说明可浏览。连接时按钮提示进度,取消后恢复登录入口,未显示其他账号的空间。 |
-| TC-21 iOS 登录连接失败后重试 | R01 | 重启未登录的 App,断网后点「登录我的空间」。恢复网络后点「重试登录」。 | 首页显示网络提示,重试时打开认证窗口。成功回调后进入当前账号空间。 |
+| TC-20 iOS 原生登录页 | R01 | 在未登录状态打开 App,查看并关闭使用说明。点「登录我的空间」,切换密码显隐,再返回。 | 原生导航打开表单,输入和错误都在 App 内。返回后清除密码,空间入口仍需登录。 |
+| TC-21 iOS 登录失败和重试 | R01 | 在原生表单提交错误密码,再断网提交。恢复网络,用正确账号密码继续。 | 表单分别提示凭据错误和网络失败,提交中禁止重复登录,恢复后显示当前账号空间。 |
+| TC-22 原生会话与权限 | R01 | 新会话查空间与模型提供方,尝试管理 API。刷新后用旧令牌重试,再退出。 | 两个业务服务都接受有效会话。普通账号无法访问管理 API。刷新令牌只用一次,退出后不可续期。 |
[测试与演示计划](plan.md)
diff --git a/docs/ui/README.md b/docs/ui/README.md
index ee6e788..700e406 100644
--- a/docs/ui/README.md
+++ b/docs/ui/README.md
@@ -6,7 +6,7 @@
- [本地预览](concept.html),用浏览器打开即可。移动网页展示找物和草稿审核,PC 展示位置目录、物品列表和详情。
- [H5 预览图](mobile-concept.png) · [PC 预览图](desktop-concept.png)
-- [iOS 首页与登录](ios-welcome.md)
+- [iOS 整体方向稿](ios/design-overview.png) · [原生登录页设计稿](ios/native-sign-in.png) · [iOS 设计与交互](ios-welcome.md)
- [低保真原型](wireframes.md) · [产品需求](../product/requirements.md) · [测试用例](../testing/cases.md)
找物列表采用小图和完整位置路径,柜子、收纳盒等末级位置加重显示。PC 左侧保留位置树,查看和移位可以在当前物品的详情里开始。草稿把待处理的内容放到最前面,用户仍可展开原话核对。录入按钮靠近移动端底部,待确认、可录入和跳过都用文字标明。
diff --git a/docs/ui/ios-welcome.md b/docs/ui/ios-welcome.md
index 941123e..ab9e385 100644
--- a/docs/ui/ios-welcome.md
+++ b/docs/ui/ios-welcome.md
@@ -1,5 +1,23 @@
# iOS 首页与登录
+[整体方向稿](ios/design-overview.png) · [原生登录页设计稿](ios/native-sign-in.png)
+
+## 整体设计
+
+用暖白、藏蓝和见物蓝统一入口、表单和物品详情。大标题用于说明当前任务,位置路径贴着物品名或照片,避免为了看位置多跳一页。页面跟随系统字号和深色模式。
+
+| 页面 | 布局与交互 |
+| --- | --- |
+| 欢迎 | 一张家里的抽屉照片和找物、批量记录、家庭共享的用途。主入口进入原生登录,使用说明离线可看。 |
+| 登录 | 系统返回按钮、小品牌行、大标题和两个带明确标签的原生输入框。密码默认隐藏,可切换显示。 |
+| 找物与收藏 | 搜索框贴近标题,缩略图左对齐,物品名和完整位置路径置于同一行组。保留可见的空结果和清除搜索动作。 |
+| 详情 | 标题、照片、完整位置路径依次展示。移位和编辑靠近位置,按角色展示可用动作。 |
+| 位置和录入 | 位置按房间、柜子、收纳盒逐层打开。录入先输入再核对草稿,保留原话、重试和手工录入。 |
+
+方向稿属于视觉参考,稿里的物品只用于说明设计。当前改版先完成原生登录,其余业务页按这一套层级逐页更新。
+
+## 首次打开
+
打开见物,先说明它能帮人找回家里的东西。首页从上到下放小号品牌标识、标题、收纳场景照片和三条用途。底部是「登录我的空间」和「看看怎么用」。首页和使用说明可以在离线时打开。
```text
@@ -19,8 +37,6 @@
看看怎么用
```
-## 首次打开
-
- 点「看看怎么用」打开原生说明页,介绍记录位置、搜索别名和邀请家人。关掉后回到首页。
- 登录前的场景照片和使用说明是产品介绍。用户确认账号后才加载空间。新账号可新建或通过邀请码加入,空空间按空状态显示。
- 背景用浅暖灰,按钮和图标沿用见物的蓝色。图片裁切保留抽屉主体。深色模式使用系统背景,标题、说明和按钮随 Dynamic Type 调整。小屏和大字号允许向下滚动。
@@ -29,10 +45,10 @@
| 状态 | 用户看到的内容 |
| --- | --- |
-| 点登录 | 底部按钮显示「正在连接…」,连接期间避免重复发起。 |
-| 系统窗口打开 | 见物主题展示账号和密码输入框。Keycloak 校验凭据,用户可用系统的取消操作返回首页。 |
-| 系统窗口关闭并回调 | App 显示「正在完成登录…」,随后进入用户的空间。 |
-| 连接或验证失败 | 首页显示能看懂的原因,并提供「重试登录」。 |
-| 取消 | 回到原入口,可以重新登录或继续查看使用说明。 |
+| 点「登录我的空间」 | 在当前 SwiftUI 导航栈推入原生登录页,系统返回键回到欢迎页。 |
+| 输入账号和密码 | 键盘 Next 进入密码框,支持系统密码填充和切换密码显隐。 |
+| 提交 | 键盘收起,按钮显示「正在登录…」并禁止重复请求。成功后显示当前账号的空间。 |
+| 连接或验证失败 | 错误在表单内显示,允许修正后重试。 |
+| 返回 | 取消未完成的请求并清除密码输入。 |
[UI 设计入口](README.md) · [iOS 验收用例](../testing/cases.md)
diff --git a/docs/ui/ios/design-overview.png b/docs/ui/ios/design-overview.png
new file mode 100644
index 0000000..29ba576
Binary files /dev/null and b/docs/ui/ios/design-overview.png differ
diff --git a/docs/ui/ios/native-sign-in.png b/docs/ui/ios/native-sign-in.png
new file mode 100644
index 0000000..b75508f
Binary files /dev/null and b/docs/ui/ios/native-sign-in.png differ