设备名与令牌解耦 + iOS Broker 应用内登录 / 消息 / 图库 / 记录持久化 + 三端 bug 修复

设备名与令牌解耦(presence 按 device_id 键控):
- hub 主键改稳定 device_id(presence / online / kick 用之),peer 路由仍按设备名经 hub 内 clientFor 解析——不动传输核心;Client 加 Name + 连接键,PresenceDevice 加 device_id,sse 传 claims.DeviceID,publishPresence 按 device_id 判在线、name 取自 devices 表
- 改名走已有 PATCH /api/devices/{device_id}(不重铸会话、不换 token、不中断 SSE)+ hub.Rename 更新活跃连接名 + 重广播 presence,全端即时无重复项;sessions 列表 name 用 devices 表覆盖 broker Label;web 改名从重铸迁到 PATCH,iOS 设置页即时改名;DeviceItem / DeviceInfo 按 device_id 键控判本机
- 移除「需移除两次」:publishPresence 不再把「有 device_id 但无 devices 行」的 live 连接当在线(吊销后用未过期 token 重连的僵尸),只显示 code-less 连接;合法重登新建行故正常
- revoke 对无 broker 会话的本地行也清(清掉合成测试 / 幽灵设备);跨端吊销 / 断连一律按 device_id Kick

iOS Broker 应用内登录(免扫码):
- BrokerLogin.swift:ASWebAuthenticationSession 跑 broker /device/authorize + /device/token 的 PKCE 设备授权流(对齐桌面 loopback,自定义 scheme cdrop://auth-callback 回调)→ /api/auth/device-session 代铸出带真名 + 稳定 device_id 的设备会话;DeviceIDStore 跨登录复用 device_id 杜绝重登重复
- LoginView 主登录改 broker 账号登录、扫码降级为可展开备选

iOS 功能补全:
- 设备间消息(引擎 main.ts 单条增量过桥 + onNativeEvent sendMessage;EngineController 消息状态 + 新 MessagesView 会话 UI;后端 /api/message 已就绪)
- 图库发送(PhotosPicker 文件 / 图库菜单 → stagePhotoData → 复用 cdrop-file 发送链路;NSPhotoLibraryUsageDescription)
- 传输历史 / 消息记录持久化(RecordsStore 落 Application Support JSON,跨重启存活)+ 长按删除 + 清空(二次确认)
- 进行中传输主动取消 / 立即切中继(详情页两按钮,复用引擎桥命令)
- 身份愈合(引擎 /api/me 取真实显示名经 identityUpdated 回报 Keychain,修扫码登录「用户显示 UUID」)
- 触发本地网络权限(NWBrowser 浏览 _cdrop._tcp)使 WKWebView WebRTC 取 host 候选

iOS 发送 / 启动修复:
- 发送在读文件即失败:引擎在 https 源下 fetch("cdrop-file://") 跨源 + Range 头触发 CORS 预检被拦 → 改走原生桥 bridgeFileSource / readFileSlice(512 KiB 分块 base64),绕开 CORS、整文件仍不整体进内存
- 冷启重开「missing injected session」:EngineWebView.makeUIView 在 boot 注入前确定性接好 auth,消除注入竞态

桌面 bug 修复:
- 登出静默失败:window.confirm 在 Wails WebView 失效(返回 falsy 致动作被静默跳过)→ 跨平台 DOM 确认弹窗(utils/confirm 的 Promise 式 confirmDialog + ui/ConfirmHost 的 Mantine Modal)取代之;登出改 await 先吊销 broker 会话再清本地(桌面 clearDesktopSession 会丢 Go 侧 refresh 的竞态)
- 扫 iOS 登录二维码被拒「不是本站的码」:wails:// 源永不等 https 站点源 → 桌面放宽 parseLinkApprovalUrl 的 origin 等值校验(仍留 /link 路径 + r/c;批准 r/c 一律发往本端后端、外站码只 404,无开放重定向)
- macOS 本地网络权限触发(localnetwork_darwin NWBrowser + Info.plist 键);相机修复(NSCameraUsageDescription)

web / 跨端:
- presence 透传 device_id + 离线检测按 device_id;会话列表随 presence 防抖重拉(已登出设备自动从列表消失,不再需手动刷新);移除设备 / 清剪贴板 / 撤销令牌 / 登出均改 DOM 确认弹窗

分发 / 签名:
- 真机签名从手动 scaffold 改自动 provisioning(删 Signing.xcconfig,project.yml 去 profile specifier,just ios-device 用 -allowProvisioningUpdates + ASC 团队 key);App Group 改名 group.net.commilitia.Commilitia-Drop(含 entitlements)
- hub 测试加 device_id 键控 + 改名解耦回归(-race)
This commit is contained in:
2026-06-27 03:50:04 +08:00
parent 44096069a7
commit 127070e226
51 changed files with 1655 additions and 227 deletions
+3 -2
View File
@@ -7,5 +7,6 @@ DerivedData/
*.xcuserstate
.DS_Store
# 真机签名的账号特定值(Team ID + profile 名)——公开仓库不留账号标识,见 REALDEVICE.md。
Local.xcconfig
# 真机签名的账号凭据——公开仓库不留账号标识。ASC API Key 的 .p8 + Team/Key/Issuer ID
# 走根目录 gitignore 的 .env(见 REALDEVICE.md);.p8 若落本目录一并忽略。
*.p8
+1 -1
View File
@@ -10,7 +10,7 @@
模拟器无需签名即生效;真机须付费 ADP 注册该 group(账号门控)。 -->
<key>com.apple.security.application-groups</key>
<array>
<string>group.net.commilitia.cdrop</string>
<string>group.net.commilitia.Commilitia-Drop</string>
</array>
</dict>
</plist>
+33 -40
View File
@@ -1,15 +1,15 @@
# cdrop iOS 真机分发手册
把 cdrop 装到你自己的 iPhone(开发签名1 年 profile)。代码侧全部就绪并经模拟器验证;真机只差**账号 + 门户 + 签名**这一层。本手册走**手动签名 + 全 CLI**路线——门户你手动建(一次),构建装机一条命令,**全程不碰 Xcode GUI**
把 cdrop 装到你自己的 iPhone(开发签名)。代码侧全部就绪并经模拟器验证;真机只差**账号 + 签名**这一层。本手册走 **ASC API Key 自动 provisioning + 全 CLI** 路线——一把 App Store Connect API Key`-allowProvisioningUpdates` 自动登记连接的设备 + 创建/更新 App ID / App Group / Push / profile / 开发证书,构建装机一条命令,**全程不碰 Xcode GUI、不必手动建 profile**(绕过手动 profile「设备列表只剩 Mac」的坑)
## 包名与标识(门户里要用的)
## 包名与标识
| 项 | 值 |
|---|---|
| 主 app Bundle ID | `net.commilitia.Commilitia-Drop` |
| Share Extension | `net.commilitia.Commilitia-Drop.share` |
| 控件扩展 | `net.commilitia.Commilitia-Drop.widgets` |
| App Group | `group.net.commilitia.cdrop`(与包名相互独立,刻意不同名) |
| App Group | `group.net.commilitia.Commilitia-Drop` |
| APNs topic(服务端 `CDROP_APNS_TOPIC` | `net.commilitia.Commilitia-Drop` |
## 前置
@@ -19,61 +19,54 @@
---
## A. 门户操作(developer.apple.com/account,一次性)
## A. ASC API Key + .env(核心,一次性)
> 入口:登录后左侧 **Certificates, Identifiers & Profiles**(证书 / 标识符 / 描述文件总枢纽)——A1–A5 都在这里面;A6 在 **Keys**Team ID 在 **Membership details**10 位,记下)
`-allowProvisioningUpdates` 凭一把 App Store Connect API Key 替你在门户自动登记设备、建/改 App ID(含 App Groups + Push 能力)、建 App Group、建 profile、建/下开发证书——**不必手动建 profile**。
1. **证书**Apple Development):本机「钥匙串访问」可能已有(「我的证书」分类里看)。没有就:钥匙串访问菜单 → 证书助理 → 从证书颁发机构请求证书 → 存到磁盘 → 门户 **Certificates** → Apple Development → 传 CSR → 下载 `.cer` 双击安装。
2. **App IDs ×3****Identifiers** → → App IDs → AppBundle ID 选 **Explicit**):
- `net.commilitia.Commilitia-Drop` — 勾 **App Groups** + **Push Notifications**
- `net.commilitia.Commilitia-Drop.share` — 勾 **App Groups**
- `net.commilitia.Commilitia-Drop.widgets` — 勾 **App Groups**
3. **App Group****Identifiers** 页类型筛选切到 **App Groups**`group.net.commilitia.cdrop`。再回上面 3 个 App ID 各自的 App Groups 能力里 **Edit/Configure** 关联它(三个都要)。
4. **设备****Devices** → → 填 UDID(插上手机后 `just ios-devices` 读)。
5. **描述文件 ×3****Profiles** → **iOS App Development**,非 Distribution):每个选对应 App ID + 证书 + 设备,命名清楚(建议 `CDrop Dev` / `CDrop Share Dev` / `CDrop Widgets Dev`)→ 下载 → 双击安装。
6. **APNs Auth Key****Keys** → → 勾 Apple Push Notifications service):下载 `AuthKey_XXXXX.p8`(仅一次),记 **Key ID** + **Issuer ID**(服务端发推送用,见 D)。这把 `.p8` 与 A1 的证书是两码事。
**生成 API Key**appstoreconnect.apple.com → **用户和访问****集成****App Store Connect API****团队密钥** → 「+」→ 角色 **Admin**(要能管设备 / profile / 标识符)→ 命名 → 生成 → 下载 `AuthKey_XXXXX.p8`**仅一次**)。记下三样:
> 常见坑:Bundle ID 选 **Explicit** 不是 WildcardApp Group 务必 3 个 App ID 都关联;Profile 选 **Development** 不要 Distribution。
- **Key ID**(密钥行里那串,10 位)
- **Issuer ID**(密钥页顶部,UUID 形)
- **Team ID**(账号 **Membership** 里,10 位)
**配 `.env`**(仓库根目录,已 gitignore,公开仓库不留账号凭据):
```
CDROP_TEAM_ID=ABCDE12345
CDROP_ASC_KEY_PATH=/绝对路径/AuthKey_XXXXX.p8
CDROP_ASC_KEY_ID=XXXXXXXXXX
CDROP_ASC_ISSUER_ID=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
```
`.p8` 放仓库外即可,`CDROP_ASC_KEY_PATH` 指它绝对路径(落本目录则被 `*.p8` 忽略)。
> 你若已在门户手动建过 App ID / App Group / 证书,自动 provisioning 会复用、不冲突。**「手动建 profile 时设备列表只剩 Mac」**=那台 iPhone 在 **Devices** 里被登记成了 macOS 平台(登记表单 Platform 默认 macOS);自动 provisioning 直接按连接的真机重登记,绕过此坑。
**顺手:APNs Auth Key**(发推送用,与上面 ASC Key 是两码事):门户 **Keys** → 勾 **Apple Push Notifications service** → 下载 `AuthKey_YYYYY.p8`(仅一次),记 Key ID + Issuer ID(服务端配,见 C)。
---
## B. 本地签名配置(gitignore,填一次
`ios/CDrop/Local.xcconfig` 写入(此文件已 gitignore,公开仓库不留你的账号标识):
```
CDROP_TEAM_ID = ABCDE12345
CDROP_PROFILE_APP = CDrop Dev
CDROP_PROFILE_SHARE = CDrop Share Dev
CDROP_PROFILE_WIDGETS = CDrop Widgets Dev
```
- `CDROP_TEAM_ID`A0 的 Team ID;三个 `CDROP_PROFILE_*`A5 你起的 profile 名(**名字**,不是文件路径)。
- 机制:`Signing.xcconfig`(已提交)仅对 **device SDKiphoneos** 套用手动签名 + 这些值;**模拟器**仍走 `project.yml` 的 ad-hoc`CODE_SIGN_IDENTITY = "-"`),故缺 `Local.xcconfig` 也不影响模拟器构建。
---
## C. 构建装机(全 CLI
## B. 构建装机(全 CLI
```sh
just ios-devices # 手机插 USB,读 UDID(填进门户 A4 + 下行)
just ios-device <你的设备UDID> # 真机构建(手动签名)+ devicectl 装机
just ios-devices # 手机插 USB,读 UDID
just ios-device <你的设备UDID> # 自动 provisioning 构建 + devicectl 装机
```
- `just ios-device` `xcodegen generate``xcodebuild`device,手动签名走 `Local.xcconfig`)→ `xcrun devicectl device install app`。无 Xcode GUI。
- `just ios-device` `xcodegen generate``xcodebuild -allowProvisioningUpdates`(凭 .env 的 ASC Key 自动签名 + 登记设备 + 建 profile)→ `xcrun devicectl device install app`。无 Xcode GUI。
- 首次装机后,iPhone 上首启该开发者 app 即可直接跑(付费 ADP 开发证书,无需手动「信任开发者」)。
---
## D. 服务端前置
## C. 服务端前置
1. **引擎可达**:真机上引擎 WebView 加载 `https://drop.commilitia.net/engine.html`——**该文件随 cdrop 二进制部署到 prod**`//go:embed` 进 binary`just docker-image` 含最新 `dist`)。手机要用,prod 须是含本轮改动的最新部署。
2. **APNs 真发**:把 A6 的 `.p8` 放到服务器,给后端容器配 `CDROP_APNS_KEY_PATH` / `CDROP_APNS_KEY_ID` / `CDROP_APNS_TEAM_ID` / `CDROP_APNS_TOPIC=net.commilitia.Commilitia-Drop` / `CDROP_APNS_ENV`Xcode 开发构建的 device token 属 **sandbox**,故联调填 `sandbox`)。缺配置则推送惰性关闭,其余功能照常。
1. **引擎可达**:真机上引擎 WebView 加载 `https://drop.commilitia.net/engine.html`——该文件随 cdrop 二进制部署到 prod(`//go:embed` 进 binary`just docker-image` 含最新 `dist`)。手机要用,prod 须是含本轮改动的最新部署。
2. **APNs 真发**:把 A 里那把 **APNs Auth Key** `.p8` 放到服务器,给后端容器配 `CDROP_APNS_KEY_PATH` / `CDROP_APNS_KEY_ID` / `CDROP_APNS_TEAM_ID` / `CDROP_APNS_TOPIC=net.commilitia.Commilitia-Drop` / `CDROP_APNS_ENV`Xcode 开发构建的 device token 属 **sandbox**,故联调填 `sandbox`)。缺配置则推送惰性关闭,其余功能照常。
3. 本机联调可选:环境变量 `CDROP_ENGINE_URL` 指向可达引擎。
---
## E. 只能真机验的清单
## D. 只能真机验的清单
代码已实现,下列是真机才能验的点:
@@ -83,6 +76,6 @@ just ios-device <你的设备UDID> # 真机构建(手动签名)+ devicectl
- [ ] 发送 / 接收:选文件 → 选设备 → 对端收到;对端发来落 Files(Documents)。
- [ ] **大文件流式发送**(R-iOS-4 已实现):发大文件,WebView 内存应有界(按 Range 块拉取,不整文件入内存)。
- [ ] **后台续传**R-iOS-1 / R-iOS-3):传输中切后台 → `BGContinuedProcessingTask` 系统进度 UI;验 WKWebView JS 是否随之保活(不保活则退化为回前台续传,可接受)。
- [ ] **APNs 推送**:离线设备收「收到文件」通知(需 D2 的 `.p8`)。
- [ ] **APNs 推送**:离线设备收「收到文件」通知(需 C2 的 `.p8`)。
- [ ] **Share Extension**:别的 app 分享 → 选 Commilitia Drop → 唤起主 app 选设备发送。
- [ ] **控制中心剪贴板两控件**:控制中心加「上传 / 拉取剪贴板」控件 → 锁屏 / 解锁态点按 → 云剪贴板读写。
+1 -1
View File
@@ -5,7 +5,7 @@
<!-- 与主 app 共享的 App GroupShare Extension 把待发文件搬进收件箱(见 AppGroup.swift)。 -->
<key>com.apple.security.application-groups</key>
<array>
<string>group.net.commilitia.cdrop</string>
<string>group.net.commilitia.Commilitia-Drop</string>
</array>
</dict>
</plist>
+1 -1
View File
@@ -8,7 +8,7 @@ import Foundation
// /
enum AppGroup
{
static let identifier = "group.net.commilitia.cdrop"
static let identifier = "group.net.commilitia.Commilitia-Drop"
// App Group nil
static func inboxURL() -> URL?
-11
View File
@@ -1,11 +0,0 @@
// 真机签名配置。仅对 device SDK(iphoneos)生效——模拟器仍走 project.yml base 的 ad-hoc
// 签名(CODE_SIGN_IDENTITY = "-"),无需 Apple 账号即可构建 / 跑模拟器。
//
// 账号特定值(Team ID、各 target 的 profile 名)放在同目录 **gitignore** 的 Local.xcconfig
// 里(公开仓库不留账号标识)。Local.xcconfig 不存在时下面的可选 include 跳过,device 构建会
// 因缺 Team/profile 失败——这正是预期(真机构建须先按 REALDEVICE.md 建好 Local.xcconfig)。
#include? "Local.xcconfig"
CODE_SIGN_STYLE[sdk=iphoneos*] = Manual
CODE_SIGN_IDENTITY[sdk=iphoneos*] = Apple Development
DEVELOPMENT_TEAM[sdk=iphoneos*] = $(CDROP_TEAM_ID)
+172 -4
View File
@@ -1,3 +1,4 @@
import AuthenticationServices
import Foundation
import Observation
import UIKit
@@ -35,14 +36,19 @@ final class AuthManager
var session: Session?
var qrPayload: String?
var statusText: String = t("ios.login.generating")
// broker
var statusText: String = ""
// denied/expired/
var qrExpired = false
// startQRLogin
// statusText / qrPayload
// startQRLogin / startBrokerLogin
// statusText / session
private var loginGeneration = 0
// Broker ASWebAuthenticationSession presentationContextProvider weak
// session /
private var brokerFlow: BrokerAuthFlow?
// Keychain app Keychain.swift
private static let keychainService = "net.commilitia.cdrop.session"
private static let keychainAccount = "session"
@@ -110,14 +116,152 @@ final class AuthManager
}
}
// Broker device-authorization + PKCE BrokerLogin.swift
// broker ASWebAuthenticationSession code bootstrap
// cdrop / device_id full + Keychain
func startBrokerLogin() async
{
loginGeneration += 1
let gen = loginGeneration
qrExpired = false
statusText = t("ios.login.brokerStarting")
do
{
let cfg = try await fetchAuthConfig()
guard !cfg.brokerURL.isEmpty, !cfg.brokerApp.isEmpty else { throw BrokerLoginError.incompleteConfig }
let verifier = PKCE.randomToken(64)
let challenge = PKCE.challenge(for: verifier)
let state = PKCE.randomToken(24)
let redirectURI = "cdrop://auth-callback"
var comp = URLComponents(string: cfg.brokerURL.trimmingTrailingSlash() + "/device/authorize")!
comp.queryItems = [
URLQueryItem(name: "app", value: cfg.brokerApp),
URLQueryItem(name: "redirect_uri", value: redirectURI),
URLQueryItem(name: "state", value: state),
URLQueryItem(name: "code_challenge", value: challenge),
URLQueryItem(name: "code_challenge_method", value: "S256"),
URLQueryItem(name: "description", value: "Commilitia Drop iOS"),
]
guard let authURL = comp.url else { throw BrokerLoginError.incompleteConfig }
let flow = BrokerAuthFlow()
brokerFlow = flow
let callback = try await flow.run(url: authURL, callbackScheme: "cdrop")
brokerFlow = nil
if gen != loginGeneration { return }
let items = URLComponents(url: callback, resolvingAgainstBaseURL: false)?.queryItems ?? []
guard items.first(where: { $0.name == "state" })?.value == state
else { throw BrokerLoginError.stateMismatch }
guard let code = items.first(where: { $0.name == "code" })?.value, !code.isEmpty
else { throw BrokerLoginError.missingCode }
let bootstrap = try await exchangeDeviceToken(
brokerURL: cfg.brokerURL, code: code, verifier: verifier, redirectURI: redirectURI)
let ds = try await mintDeviceSession(bootstrap: bootstrap)
if gen != loginGeneration { return }
DeviceIDStore.value = ds.device_id
let realName = (ds.name?.isEmpty == false) ? ds.name! : ds.user_id
session = Session(accessToken: ds.access_token,
refreshToken: ds.refresh_token,
user: User(id: ds.user_id, name: realName, avatar: ds.avatar),
deviceName: ds.device_name ?? DeviceNameStore.value,
deviceId: ds.device_id,
scope: "full")
persist()
}
catch
{
brokerFlow = nil
if gen != loginGeneration { return }
//
if let asErr = error as? ASWebAuthenticationSessionError, asErr.code == .canceledLogin
{
statusText = t("ios.login.waiting")
return
}
statusText = t("ios.login.failed")
}
}
func logout()
{
session = nil
qrPayload = nil
statusText = t("ios.login.generating")
statusText = ""
Keychain.delete(service: Self.keychainService, account: Self.keychainAccount)
}
// ---- Broker / / ----
private struct AuthConfig { let brokerURL: String; let brokerApp: String }
private struct DeviceTokenResp: Decodable
{
let access: String
let refresh: String
let access_expires: Int64
}
// access/refresh + device_id + user_id/name/avatar
private struct DeviceSessionResp: Decodable
{
let access_token: String
let refresh_token: String
let device_id: String
let device_name: String?
let user_id: String
let name: String?
let avatar: String?
}
private func fetchAuthConfig() async throws -> AuthConfig
{
let (data, _) = try await URLSession.shared.data(from: URL(string: "\(apiBase)/api/auth/config")!)
let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:]
return AuthConfig(brokerURL: obj["broker_url"] as? String ?? "",
brokerApp: obj["broker_app"] as? String ?? "")
}
private func exchangeDeviceToken(
brokerURL: String, code: String, verifier: String, redirectURI: String) async throws -> String
{
var req = URLRequest(url: URL(string: brokerURL.trimmingTrailingSlash() + "/device/token")!)
req.httpMethod = "POST"
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
req.httpBody = try JSONSerialization.data(withJSONObject: [
"code": code, "code_verifier": verifier, "redirect_uri": redirectURI,
])
let (data, resp) = try await URLSession.shared.data(for: req)
let status = (resp as? HTTPURLResponse)?.statusCode ?? 0
guard status == 200 else { throw BrokerLoginError.tokenFailed(status) }
let tr = try JSONDecoder().decode(DeviceTokenResp.self, from: data)
guard !tr.access.isEmpty else { throw BrokerLoginError.badResponse }
return tr.access
}
private func mintDeviceSession(bootstrap: String) async throws -> DeviceSessionResp
{
var req = URLRequest(url: URL(string: "\(apiBase)/api/auth/device-session")!)
req.httpMethod = "POST"
req.setValue("Bearer \(bootstrap)", forHTTPHeaderField: "Authorization")
req.setValue("application/json", forHTTPHeaderField: "Content-Type")
req.setValue("ios", forHTTPHeaderField: "X-Device-Type")
req.httpBody = try JSONSerialization.data(withJSONObject: [
"device_id": DeviceIDStore.value,
"device_name": DeviceNameStore.value,
"device_type": "ios",
])
let (data, resp) = try await URLSession.shared.data(for: req)
let status = (resp as? HTTPURLResponse)?.statusCode ?? 0
guard status == 200 else { throw BrokerLoginError.deviceSessionFailed(status) }
return try JSONDecoder().decode(DeviceSessionResp.self, from: data)
}
// Keychain
private func persist()
{
@@ -136,6 +280,30 @@ final class AuthManager
persist()
}
// updateIdentity /api/me QR subject UUID
// identityUpdated + Keychain使 UUID#12
// /
func updateIdentity(name: String, avatar: String?)
{
guard let cur = session else { return }
let av = (avatar?.isEmpty == false) ? avatar : cur.user.avatar
session = Session(accessToken: cur.accessToken, refreshToken: cur.refreshToken,
user: User(id: cur.user.id, name: name, avatar: av),
deviceName: cur.deviceName, deviceId: cur.deviceId, scope: cur.scope)
persist()
}
// updateDeviceNamePATCH /api/devices/{device_id} renamed
// + Keychain使 boot /
func updateDeviceName(_ name: String)
{
guard let cur = session else { return }
session = Session(accessToken: cur.accessToken, refreshToken: cur.refreshToken,
user: cur.user, deviceName: name,
deviceId: cur.deviceId, scope: cur.scope)
persist()
}
// CDROP_DEBUG_SESSION=1
// prod + 401 engine.html WKWebView
func debugSession()
+111
View File
@@ -0,0 +1,111 @@
import AuthenticationServices
import CryptoKit
import Foundation
import UIKit
// Broker device-authorization + PKCE desktop/platform/oauth.goiOS
// loopback ASWebAuthenticationSession + scheme cdrop://auth-callback
// 1. GET {broker}/device/authorize?app=cdrop&redirect_uri=cdrop://auth-callback&state&code_challenge&S256
// 2. broker SSO cdrop://auth-callback?code=..&state=..
// 3. POST {broker}/device/token {code, code_verifier, redirect_uri} bootstrap
// 4. POST {api}/api/auth/device-sessionBearer bootstrap cdrop / device_id
//
// broker cdrop redirect_uri cdrop://auth-callback loopback
enum BrokerLoginError: Error
{
case incompleteConfig
case cannotStart
case noCallback
case stateMismatch
case missingCode
case tokenFailed(Int)
case deviceSessionFailed(Int)
case badResponse
}
// ASWebAuthenticationSession async + session
// presentationContextProvider weak session AuthManager
@MainActor
final class BrokerAuthFlow: NSObject, ASWebAuthenticationPresentationContextProviding
{
private var session: ASWebAuthenticationSession?
// URLcdrop://auth-callback?code=..&state=.. /
func run(url: URL, callbackScheme: String) async throws -> URL
{
try await withCheckedThrowingContinuation
{ cont in
let s = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme)
{ [weak self] callback, error in
self?.session = nil
if let error { cont.resume(throwing: error) }
else if let callback { cont.resume(returning: callback) }
else { cont.resume(throwing: BrokerLoginError.noCallback) }
}
s.presentationContextProvider = self
// Safari broker SSO SSO
s.prefersEphemeralWebBrowserSession = false
self.session = s
if !s.start() { cont.resume(throwing: BrokerLoginError.cannotStart) }
}
}
func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor
{
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
return scenes.flatMap { $0.windows }.first { $0.isKeyWindow }
?? scenes.first?.windows.first
?? ASPresentationAnchor()
}
}
// device_idbroker meta / UserDefaults
// device_idbroker R2 UPSERT
// web localStorage cdrop.device_id
enum DeviceIDStore
{
private static let key = "cdrop.device_id"
static var value: String
{
get { UserDefaults.standard.string(forKey: key) ?? "" }
set { UserDefaults.standard.set(newValue, forKey: key) }
}
}
// PKCE / randStringn base64url n PKCE unreserved
enum PKCE
{
static func randomToken(_ n: Int) -> String
{
var bytes = [UInt8](repeating: 0, count: n)
_ = SecRandomCopyBytes(kSecRandomDefault, n, &bytes)
return String(Data(bytes).base64URLEncoded().prefix(n))
}
static func challenge(for verifier: String) -> String
{
let digest = SHA256.hash(data: Data(verifier.utf8))
return Data(digest).base64URLEncoded()
}
}
extension Data
{
// base64url- / _ + / PKCE challenge /
func base64URLEncoded() -> String
{
base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
}
}
extension String
{
func trimmingTrailingSlash() -> String
{
hasSuffix("/") ? String(dropLast()) : self
}
}
+49 -13
View File
@@ -2,34 +2,70 @@ import CoreImage.CIFilterBuiltins
import SwiftUI
import UIKit
// + cdrop AuthManager
// Broker ASWebAuthenticationSession
// AuthManager
struct LoginView: View
{
@Environment(AuthManager.self) private var auth
@State private var showQR = false
var body: some View
{
VStack(spacing: 24)
VStack(spacing: 20)
{
Spacer()
Text(t("app.brand"))
.font(.largeTitle)
.bold()
qrArea
Text(auth.statusText)
.font(.callout)
.foregroundStyle(auth.qrExpired ? Color.red : Color.secondary)
refreshButton
Text(t("ios.login.guide"))
.font(.footnote)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, 40)
// broker
Button { Task { await auth.startBrokerLogin() } }
label:
{
Label(t("ios.login.broker"), systemImage: "person.crop.circle")
.frame(maxWidth: .infinity)
}
.buttonStyle(.glassProminent)
.padding(.horizontal, 40)
if !auth.statusText.isEmpty
{
Text(auth.statusText)
.font(.callout)
.foregroundStyle(auth.qrExpired ? Color.red : Color.secondary)
.multilineTextAlignment(.center)
.padding(.horizontal, 40)
}
//
DisclosureGroup(isExpanded: $showQR)
{
VStack(spacing: 16)
{
qrArea
refreshButton
Text(t("ios.login.guide"))
.font(.footnote)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
}
.padding(.top, 12)
}
label:
{
Text(t("ios.login.scanAlt"))
.font(.subheadline)
}
.padding(.horizontal, 40)
.onChange(of: showQR)
{
if showQR, auth.qrPayload == nil { Task { await auth.startQRLogin() } }
}
Spacer()
}
.padding()
.tint(.cdropAccent)
.task { await auth.startQRLogin() }
}
// glassProminent
+4 -3
View File
@@ -1,9 +1,10 @@
import Foundation
import UIKit
// UserDefaults qr/start device_name
// (userID, deviceName) presence线
// internal/httpapi/qr.go
// UserDefaults qr/start device_name
// PATCH /api/devices/{device_id}
// device_id + 广 presence token renamed + Keychain
// EngineController / AuthManager
enum DeviceNameStore
{
private static let key = "cdrop.deviceName"
+182 -8
View File
@@ -9,16 +9,30 @@ import WebKit
// web hub.ts handlePresence
struct DeviceItem: Identifiable, Equatable
{
// deviceID broker meta / /
// name deviceID presence name
let deviceID: String
let name: String
let type: String
let online: Bool
let lastSeen: Double
var id: String { name }
var id: String { deviceID.isEmpty ? name : deviceID }
}
// web store MessageRecord RecordsStore
// app
struct MessageItem: Identifiable, Equatable, Codable
{
let id: String
let direction: String // incoming | outgoing
let peerName: String
let text: String
let sentAt: Double
}
// web engine/main.ts toWire ice*
// P2P TURN
struct TransferItem: Identifiable, Equatable
struct TransferItem: Identifiable, Equatable, Codable
{
let sessionId: String
let direction: String
@@ -52,6 +66,7 @@ final class EngineController: NSObject
var devices: [DeviceItem] = [] // 线 / 线 presence presence
var transfers: [TransferItem] = [] // transfers
var history: [TransferItem] = [] // transferDone 30
var messages: [MessageItem] = [] // message
// SSE / + presence +
// warn/error 401
@@ -80,9 +95,13 @@ final class EngineController: NSObject
return URL(string: "https://drop.commilitia.net/engine.html")!
}
// boot app AppRoot.onAppear
// boot EngineWebView.makeUIView boot #11
var auth: AuthManager?
// idbroker metapresence PATCH
// /api/devices/{device_id}
var selfDeviceID: String { auth?.session?.deviceId ?? "" }
private var webView: WKWebView?
private let downloads = DownloadManager()
@@ -90,10 +109,17 @@ final class EngineController: NSObject
// WKURLSchemeHandler
private var outgoing: [String: URL] = [:]
// /
private static let historyCap = 50
private static let messagesCap = 200
override init()
{
super.init()
PushRegistry.shared.engine = self
// /
history = RecordsStore.load([TransferItem].self, "history") ?? []
messages = RecordsStore.load([MessageItem].self, "messages") ?? []
}
// makeWebView WebView __CDROP_BOOT__device_type:"ios"
@@ -133,6 +159,8 @@ final class EngineController: NSObject
deviceName = currentDeviceName()
//
PushRegistry.shared.requestAuthorizationAndRegister()
// #5使 WKWebView WebRTC host
LocalNetworkPermission.trigger()
return wv
}
@@ -146,6 +174,10 @@ final class EngineController: NSObject
devices = []
transfers = []
history = []
messages = []
//
RecordsStore.clear("history")
RecordsStore.clear("messages")
status = t("ios.engine.disconnected")
deviceName = ""
PushRegistry.shared.reset()
@@ -157,6 +189,32 @@ final class EngineController: NSObject
CDropAPI.clearWidgetDeviceID()
}
// D/
func deleteTransferRecord(_ sessionId: String)
{
history.removeAll { $0.sessionId == sessionId }
RecordsStore.save(history, "history")
}
func clearHistory()
{
history.removeAll()
RecordsStore.clear("history")
}
// H/
func deleteMessage(_ id: String)
{
messages.removeAll { $0.id == id }
RecordsStore.save(messages, "messages")
}
func clearMessages()
{
messages.removeAll()
RecordsStore.clear("messages")
}
// Documents Files app /
func receivedFiles() -> [URL] { downloads.receivedFiles() }
func deleteReceivedFile(_ url: URL) { downloads.deleteReceivedFile(url) }
@@ -193,11 +251,44 @@ final class EngineController: NSObject
sendCommand("clipboardPull", payload: [:])
}
// /
func revokeDevice(_ name: String)
// / device_idDELETE /api/devices/{device_id}
// #2
func revokeDevice(_ deviceID: String)
{
deviceActionStatus = ""
sendCommand("revokeDevice", payload: [ "name": name ])
sendCommand("revokeDevice", payload: [ "device_id": deviceID ])
}
// O CANCELLED transfers / transferDone
func cancelTransfer(_ sessionId: String)
{
sendCommand("cancelTransfer", payload: [ "sessionId": sessionId ])
}
// O ICE relay /
func switchToRelay(_ sessionId: String)
{
sendCommand("switchToRelay", payload: [ "sessionId": sessionId ])
}
// { to=, text } POST /api/message
// store.addMessage message outgoing
func sendMessage(to peerName: String, text: String)
{
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, !peerName.isEmpty else { return }
sendCommand("sendMessage", payload: [ "to": peerName, "text": trimmed ])
}
// { device_id=, name } PATCH /api/devices/
// {device_id} token "renamed"
// + Keychain handleNotify device_id
func renameSelf(to name: String)
{
let id = selfDeviceID
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
guard !id.isEmpty, !trimmed.isEmpty else { return }
sendCommand("renameSelf", payload: [ "device_id": id, "name": trimmed ])
}
// APNs PushRegistry.didRegisterready
@@ -282,6 +373,20 @@ final class EngineController: NSObject
pendingShareFiles = []
}
// #14PhotosPicker PhotosPickerItem loadTransferable
// cdrop-file scheme Range
// URL temporaryDirectory nil
func stagePhotoData(_ data: Data, suggestedName: String) -> URL?
{
let dir = FileManager.default.temporaryDirectory
.appendingPathComponent("PhotoOutbox/\(UUID().uuidString)", isDirectory: true)
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let name = suggestedName.isEmpty ? "photo.jpg" : suggestedName
let dest = dir.appendingPathComponent(name)
do { try data.write(to: dest); return dest }
catch { return nil }
}
// cdrop-file://<id> URL
// start...Access
private func stageOutgoingFile(_ url: URL) -> String
@@ -291,6 +396,24 @@ final class EngineController: NSObject
outgoing[id] = url
return "cdrop-file://\(id)"
}
// [start,end) seek base64 bridgeFileSource
// url cdrop-file://<id>id stageOutgoingFile /
fileprivate func readOutgoingSlice(url: String, start: Int, end: Int) throws -> String
{
guard let id = URL(string: url)?.host, let fileURL = outgoing[id]
else
{
throw NSError(domain: "cdrop.engine", code: 404,
userInfo: [NSLocalizedDescriptionKey: "no staged file: \(url)"])
}
let handle = try FileHandle(forReadingFrom: fileURL)
defer { try? handle.close() }
try handle.seek(toOffset: UInt64(max(0, start)))
let count = max(0, end - start)
let data = (try handle.read(upToCount: count)) ?? Data()
return data.base64EncodedString()
}
}
// MARK: - JS RPC +
@@ -337,6 +460,12 @@ extension EngineController: WKScriptMessageHandler
case "abortDownload":
downloads.abort(sessionId: payload["sessionId"] as? String ?? "")
resolve(id: id, ok: true, value: nil)
case "readFileSlice":
// seek [start,end) base64 bridgeFileSource
let b64 = try readOutgoingSlice(url: payload["url"] as? String ?? "",
start: Self.intOf(payload["start"]),
end: Self.intOf(payload["end"]))
resolve(id: id, ok: true, value: b64)
default:
resolve(id: id, ok: false, value: "unknown method: \(method)")
}
@@ -380,6 +509,21 @@ extension EngineController: WKScriptMessageHandler
transfers = raw.compactMap { ($0 as? [String: Any]).flatMap(Self.parseTransfer) }
syncBackgroundTask()
}
case "message":
// + + +
//
if let p = payload as? [String: Any],
let m = p["message"] as? [String: Any],
let item = Self.parseMessage(m)
{
messages.removeAll { $0.id == item.id }
messages.insert(item, at: 0)
if messages.count > Self.messagesCap
{
messages.removeLast(messages.count - Self.messagesCap)
}
RecordsStore.save(messages, "messages")
}
case "transferDone":
// sessionId
if let p = payload as? [String: Any], let item = Self.parseTransfer(p)
@@ -387,8 +531,9 @@ extension EngineController: WKScriptMessageHandler
transfers.removeAll { $0.sessionId == item.sessionId }
history.removeAll { $0.sessionId == item.sessionId }
history.insert(item, at: 0)
if history.count > 30 { history.removeLast(history.count - 30) }
if history.count > Self.historyCap { history.removeLast(history.count - Self.historyCap) }
syncBackgroundTask()
RecordsStore.save(history, "history") //
}
case "sendStarted":
// transfers
@@ -420,6 +565,23 @@ extension EngineController: WKScriptMessageHandler
clipboardStatus = t("ios.clipboard.uploaded")
case "deviceRevoked":
deviceActionStatus = t("ios.devices.revoked")
case "identityUpdated":
// /api/me QR UUID + Keychain
// UUID#12
if let p = payload as? [String: Any], let name = p["name"] as? String, !name.isEmpty
{
auth?.updateIdentity(name: name, avatar: p["avatar"] as? String)
}
case "renamed":
// PATCH /api/devices/{device_id} + 广 presence
// Keychain 使 boot
if let p = payload as? [String: Any], let name = p["name"] as? String, !name.isEmpty
{
DeviceNameStore.value = name
auth?.updateDeviceName(name)
deviceName = name
deviceActionStatus = t("ios.settings.deviceName.success")
}
case "error":
// error /
if let p = payload as? [String: Any]
@@ -580,12 +742,24 @@ extension EngineController
static func parseDevice(_ d: [String: Any]) -> DeviceItem?
{
guard let name = d["name"] as? String, let type = d["type"] as? String else { return nil }
return DeviceItem(name: name,
// web store DeviceInfocamelCasedeviceId / lastSeen
return DeviceItem(deviceID: d["deviceId"] as? String ?? "",
name: name,
type: type,
online: boolOf(d["online"]),
lastSeen: doubleOf(d["lastSeen"]))
}
static func parseMessage(_ m: [String: Any]) -> MessageItem?
{
guard let id = m["id"] as? String, let text = m["text"] as? String else { return nil }
return MessageItem(id: id,
direction: m["direction"] as? String ?? "incoming",
peerName: m["peerName"] as? String ?? "",
text: text,
sentAt: doubleOf(m["sentAt"]))
}
static func parseTransfer(_ t: [String: Any]) -> TransferItem?
{
guard let sessionId = t["sessionId"] as? String else { return nil }
@@ -6,9 +6,14 @@ import WebKit
struct EngineWebView: UIViewRepresentable
{
let controller: EngineController
// WebView __CDROP_BOOT__
// makeUIView AppRoot.onAppear controller.auth nilboot
// session:null missing injected session boot #11
let auth: AuthManager
func makeUIView(context: Context) -> WKWebView
{
controller.auth = auth
return controller.makeWebView()
}
+2
View File
@@ -56,6 +56,8 @@
<string>Commilitia Drop 使用相机扫描二维码登录新设备。</string>
<key>NSLocalNetworkUsageDescription</key>
<string>Commilitia Drop 需要访问本地网络以发现同内网设备并建立直连传输。</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Commilitia Drop 需要访问照片库,以便从相册选取图片或视频发送给其他设备。</string>
<key>UIBackgroundModes</key>
<array>
<string>remote-notification</string>
@@ -0,0 +1,26 @@
import Foundation
import Network
// #5iOS 14+ App 访 WKWebView
// WebRTC host 退 srflx / relayWKWebView
// 宿 App 访 _cdrop._tcp
// NWBrowser RTCPeerConnection host / mDNS
// browser project.yml
// NSLocalNetworkUsageDescription + NSBonjourServices(_cdrop._tcp)
enum LocalNetworkPermission
{
private static var browser: NWBrowser?
// 访
//
static func trigger()
{
guard browser == nil else { return }
let params = NWParameters()
params.includePeerToPeer = true
let b = NWBrowser(for: .bonjour(type: "_cdrop._tcp", domain: nil), using: params)
b.browseResultsChangedHandler = { _, _ in }
browser = b
b.start(queue: .main)
}
}
+164
View File
@@ -0,0 +1,164 @@
import SwiftUI
// #13 + in-memory app
// web POST /api/messagehub SendTo 线
// 线线线
struct MessagesView: View
{
@Environment(EngineController.self) private var engine
@State private var draft = ""
@State private var target = ""
@State private var showClearConfirm = false
// device_id
private var targets: [DeviceItem]
{
let selfID = engine.selfDeviceID
return engine.devices.filter
{ d in
if !selfID.isEmpty, !d.deviceID.isEmpty { return d.deviceID != selfID }
return d.name != engine.deviceName
}
}
// store
private var ordered: [MessageItem] { engine.messages.reversed() }
var body: some View
{
VStack(spacing: 0)
{
if engine.messages.isEmpty
{
ContentUnavailableView(t("ios.messages.empty"), systemImage: "message")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
else
{
ScrollViewReader
{ proxy in
ScrollView
{
LazyVStack(alignment: .leading, spacing: 10)
{
ForEach(ordered)
{ msg in
messageRow(msg)
.id(msg.id)
.contextMenu
{
Button(role: .destructive) { engine.deleteMessage(msg.id) }
label: { Label(t("transfer.action.delete"), systemImage: "trash") }
}
}
}
.padding()
}
.onChange(of: engine.messages.count) { scrollToLast(proxy) }
.onAppear { scrollToLast(proxy) }
}
}
composeBar
}
.navigationTitle(t("ios.tab.messages"))
.toolbar
{
if !engine.messages.isEmpty
{
ToolbarItem(placement: .topBarTrailing)
{
Button(role: .destructive) { showClearConfirm = true }
label: { Label(t("ios.records.clear"), systemImage: "trash") }
}
}
}
.confirmationDialog(t("ios.records.clearConfirm"), isPresented: $showClearConfirm, titleVisibility: .visible)
{
Button(t("ios.records.clear"), role: .destructive) { engine.clearMessages() }
Button(t("common.cancel"), role: .cancel) { }
}
.onAppear { if target.isEmpty { target = targets.first?.name ?? "" } }
}
private func scrollToLast(_ proxy: ScrollViewProxy)
{
guard let last = ordered.last else { return }
withAnimation { proxy.scrollTo(last.id, anchor: .bottom) }
}
private func messageRow(_ msg: MessageItem) -> some View
{
let outgoing = msg.direction == "outgoing"
return HStack
{
if outgoing { Spacer(minLength: 48) }
VStack(alignment: outgoing ? .trailing : .leading, spacing: 2)
{
Text(msg.peerName)
.font(.caption2)
.foregroundStyle(.secondary)
Text(msg.text)
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(outgoing ? Color.cdropAccent.opacity(0.18) : Color(.secondarySystemBackground),
in: RoundedRectangle(cornerRadius: 14))
.textSelection(.enabled)
}
if !outgoing { Spacer(minLength: 48) }
}
.frame(maxWidth: .infinity, alignment: outgoing ? .trailing : .leading)
}
@ViewBuilder
private var composeBar: some View
{
VStack(spacing: 6)
{
if targets.isEmpty
{
Text(t("ios.messages.noPeers"))
.font(.caption)
.foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
}
else
{
HStack(spacing: 10)
{
Menu
{
ForEach(targets)
{ dev in
Button(dev.name) { target = dev.name }
}
}
label:
{
Label(target.isEmpty ? t("ios.send.pickDevice") : target,
systemImage: "chevron.up.chevron.down")
.font(.caption)
.lineLimit(1)
}
TextField(t("ios.messages.placeholder"), text: $draft, axis: .vertical)
.textFieldStyle(.roundedBorder)
.lineLimit(1...4)
.submitLabel(.send)
.onSubmit { send() }
Button { send() }
label: { Image(systemName: "paperplane.fill").font(.title3) }
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || target.isEmpty)
}
}
}
.padding()
.background(.bar)
}
private func send()
{
let text = draft.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty, !target.isEmpty else { return }
engine.sendMessage(to: target, text: text)
draft = ""
}
}
+33
View File
@@ -0,0 +1,33 @@
import Foundation
// / Application Support JSON
// Documents UserDefaults
// / / / EngineController
enum RecordsStore
{
private static func fileURL(_ name: String) -> URL?
{
guard let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
else { return nil }
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
return dir.appendingPathComponent("cdrop-\(name).json")
}
static func save<T: Encodable>(_ value: T, _ name: String)
{
guard let url = fileURL(name), let data = try? JSONEncoder().encode(value) else { return }
try? data.write(to: url, options: .atomic)
}
static func load<T: Decodable>(_ type: T.Type, _ name: String) -> T?
{
guard let url = fileURL(name), let data = try? Data(contentsOf: url) else { return nil }
return try? JSONDecoder().decode(type, from: data)
}
static func clear(_ name: String)
{
guard let url = fileURL(name) else { return }
try? FileManager.default.removeItem(at: url)
}
}
+15 -1
View File
@@ -301,6 +301,9 @@
"ios.login.guide": "Scan to approve from another signed-in device",
"ios.login.expired": "Code expired — please try again",
"ios.login.failed": "Sign-in failed — please try again",
"ios.login.broker": "Sign In",
"ios.login.brokerStarting": "Opening sign-in…",
"ios.login.scanAlt": "Sign in by scanning from another device",
"ios.login.refresh": "Refresh QR Code",
"ios.login.needFull": "This device needs full access — choose \"Trust this device\" when approving.",
"ios.send.pickDevice": "Choose a device",
@@ -343,7 +346,18 @@
"ios.settings.user": "User",
"ios.settings.logout": "Sign Out",
"ios.settings.deviceName": "Device Name",
"ios.settings.deviceNameNote": "Renaming takes effect on next sign-in",
"ios.settings.deviceNameNote": "Renaming takes effect at once and syncs to all devices, without affecting sign-in.",
"ios.settings.deviceName.success": "Device name updated",
"ios.tab.messages": "Messages",
"ios.send.fromFiles": "From Files",
"ios.send.fromPhotos": "From Photos",
"ios.messages.empty": "No messages yet",
"ios.messages.noPeers": "No device to message",
"ios.messages.placeholder": "Type a message…",
"ios.records.clear": "Clear",
"ios.records.clearConfirm": "Clear all records? This cannot be undone.",
"ios.transfer.cancel": "Cancel transfer",
"ios.transfer.forceRelay": "Relay now",
"ios.settings.deviceCount": "Known Devices",
"ios.settings.signaling": "Signaling",
"ios.settings.presenceEvents": "Presence Events",
+15 -1
View File
@@ -301,6 +301,9 @@
"ios.login.guide": "用另一台已登录的设备扫码批准",
"ios.login.expired": "二维码已失效,请重试",
"ios.login.failed": "登录失败,请重试",
"ios.login.broker": "登录",
"ios.login.brokerStarting": "正在打开登录…",
"ios.login.scanAlt": "用其他设备扫码登录",
"ios.login.refresh": "刷新二维码",
"ios.login.needFull": "此设备需要完整权限,批准时请选择“信任此设备”",
"ios.send.pickDevice": "选择接收设备",
@@ -343,7 +346,18 @@
"ios.settings.user": "用户",
"ios.settings.logout": "退出登录",
"ios.settings.deviceName": "设备名称",
"ios.settings.deviceNameNote": "改名将在下次登录后生效",
"ios.settings.deviceNameNote": "改名即时生效并同步到所有设备,不影响登录。",
"ios.settings.deviceName.success": "设备名已更新",
"ios.tab.messages": "消息",
"ios.send.fromFiles": "从文件",
"ios.send.fromPhotos": "从图库",
"ios.messages.empty": "暂无消息",
"ios.messages.noPeers": "没有可发送消息的设备",
"ios.messages.placeholder": "输入消息…",
"ios.records.clear": "清空",
"ios.records.clearConfirm": "确定清空全部记录?此操作不可撤销。",
"ios.transfer.cancel": "取消传输",
"ios.transfer.forceRelay": "立即切到中继",
"ios.settings.deviceCount": "已知设备",
"ios.settings.signaling": "信令连接",
"ios.settings.presenceEvents": "在线事件",
+15 -1
View File
@@ -301,6 +301,9 @@
"ios.login.guide": "用另一台已登入的裝置掃碼核准",
"ios.login.expired": "QR 碼已失效,請重試",
"ios.login.failed": "登入失敗,請重試",
"ios.login.broker": "登入",
"ios.login.brokerStarting": "正在開啟登入…",
"ios.login.scanAlt": "用其他裝置掃碼登入",
"ios.login.refresh": "重新整理 QR 碼",
"ios.login.needFull": "此裝置需要完整權限,批准時請選擇「信任此裝置」",
"ios.send.pickDevice": "選擇接收裝置",
@@ -343,7 +346,18 @@
"ios.settings.user": "使用者",
"ios.settings.logout": "登出",
"ios.settings.deviceName": "裝置名稱",
"ios.settings.deviceNameNote": "改名將在下次登入後生效",
"ios.settings.deviceNameNote": "改名即時生效並同步到所有裝置,不影響登入。",
"ios.settings.deviceName.success": "裝置名稱已更新",
"ios.tab.messages": "訊息",
"ios.send.fromFiles": "從檔案",
"ios.send.fromPhotos": "從相簿",
"ios.messages.empty": "尚無訊息",
"ios.messages.noPeers": "沒有可傳送訊息的裝置",
"ios.messages.placeholder": "輸入訊息…",
"ios.records.clear": "清空",
"ios.records.clearConfirm": "確定清空全部記錄?此操作無法復原。",
"ios.transfer.cancel": "取消傳輸",
"ios.transfer.forceRelay": "立即切到中繼",
"ios.settings.deviceCount": "已知裝置",
"ios.settings.signaling": "信令連線",
"ios.settings.presenceEvents": "上線事件",
+116 -5
View File
@@ -1,3 +1,4 @@
import PhotosUI
import SwiftUI
import UIKit
import UniformTypeIdentifiers
@@ -9,6 +10,9 @@ import UniformTypeIdentifiers
struct RootView: View
{
@Environment(EngineController.self) private var engine
// auth AppRoot .environment(auth) EngineWebView.makeUIView
// boot missing injected session#11
@Environment(AuthManager.self) private var auth
// CDROP_TAB
@State private var selection = ProcessInfo.processInfo.environment["CDROP_TAB"] ?? "transfer"
@@ -30,6 +34,13 @@ struct RootView: View
DeviceListView()
}
}
Tab(t("ios.tab.messages"), systemImage: "message", value: "messages")
{
NavigationStack
{
MessagesView()
}
}
Tab(t("ios.tab.files"), systemImage: "folder", value: "files")
{
NavigationStack
@@ -49,7 +60,7 @@ struct RootView: View
.tint(.cdropAccent)
.background
{
EngineWebView(controller: engine)
EngineWebView(controller: engine, auth: auth)
.frame(width: 0, height: 0)
.opacity(0)
.allowsHitTesting(false)
@@ -78,9 +89,12 @@ struct TransferListView: View
{
@Environment(EngineController.self) private var engine
@State private var showImporter = false
@State private var showPhotoPicker = false
@State private var photoItem: PhotosPickerItem?
@State private var pickedURL: URL?
@State private var showDevicePicker = false
@State private var showNoDevices = false
@State private var showClearConfirm = false
// 线 EngineController.sendableDevices
private var sendableDevices: [DeviceItem]
@@ -115,6 +129,12 @@ struct TransferListView: View
ForEach(engine.history)
{ item in
transferLink(item)
.contextMenu
{
Button(role: .destructive)
{ engine.deleteTransferRecord(item.sessionId) }
label: { Label(t("transfer.action.delete"), systemImage: "trash") }
}
}
}
}
@@ -122,9 +142,33 @@ struct TransferListView: View
}
}
.navigationTitle(t("ios.tab.transfer"))
.toolbar
{
if !engine.history.isEmpty
{
ToolbarItem(placement: .topBarTrailing)
{
Button(role: .destructive) { showClearConfirm = true }
label: { Label(t("ios.records.clear"), systemImage: "trash") }
}
}
}
.confirmationDialog(t("ios.records.clearConfirm"), isPresented: $showClearConfirm, titleVisibility: .visible)
{
Button(t("ios.records.clear"), role: .destructive) { engine.clearHistory() }
Button(t("common.cancel"), role: .cancel) { }
}
.overlay(alignment: .bottomTrailing)
{
Button { showImporter = true }
// Files / Photos PhotosPicker
// #14
Menu
{
Button { showImporter = true }
label: { Label(t("ios.send.fromFiles"), systemImage: "folder") }
Button { showPhotoPicker = true }
label: { Label(t("ios.send.fromPhotos"), systemImage: "photo.on.rectangle") }
}
label:
{
Image(systemName: "paperplane.fill")
@@ -143,6 +187,9 @@ struct TransferListView: View
else { showDevicePicker = true }
}
}
.photosPicker(isPresented: $showPhotoPicker, selection: $photoItem,
matching: .any(of: [ .images, .videos ]))
.onChange(of: photoItem) { loadPhoto() }
.confirmationDialog(t("ios.send.pickDevice"), isPresented: $showDevicePicker, titleVisibility: .visible)
{
ForEach(sendableDevices)
@@ -184,6 +231,32 @@ struct TransferListView: View
engine.sendFile(to: device, fileURL: url)
pickedURL = nil
}
// #14
private func loadPhoto()
{
guard let item = photoItem else { return }
Task
{
guard let data = try? await item.loadTransferable(type: Data.self),
let url = engine.stagePhotoData(data, suggestedName: suggestedPhotoName(item))
else { return }
await MainActor.run
{
pickedURL = url
photoItem = nil
if sendableDevices.isEmpty { showNoDevices = true }
else { showDevicePicker = true }
}
}
}
// jpg mov
private func suggestedPhotoName(_ item: PhotosPickerItem) -> String
{
let ext = item.supportedContentTypes.first?.preferredFilenameExtension ?? "jpg"
return "photo-\(UUID().uuidString.prefix(8)).\(ext)"
}
}
// / / /
@@ -262,6 +335,21 @@ struct TransferDetailView: View
{
List
{
// / O
if isActive(item)
{
Section
{
Button(role: .destructive) { engine.cancelTransfer(item.sessionId) }
label: { Label(t("ios.transfer.cancel"), systemImage: "xmark.circle") }
if item.mode != "relay"
{
Button { engine.switchToRelay(item.sessionId) }
label: { Label(t("ios.transfer.forceRelay"),
systemImage: "antenna.radiowaves.left.and.right") }
}
}
}
Section
{
LabeledContent(t("ios.detail.direction"),
@@ -343,7 +431,13 @@ struct DeviceListView: View
engine.devices.sorted { a, b in isSelf(a) && !isSelf(b) }
}
private func isSelf(_ dev: DeviceItem) -> Bool { dev.name == engine.deviceName }
// device_idselfDeviceID
private func isSelf(_ dev: DeviceItem) -> Bool
{
let selfID = engine.selfDeviceID
if !selfID.isEmpty, !dev.deviceID.isEmpty { return dev.deviceID == selfID }
return dev.name == engine.deviceName
}
var body: some View
{
@@ -385,7 +479,7 @@ struct DeviceListView: View
{
Button(t("ios.devices.remove"), role: .destructive)
{
if let target = revokeTarget { engine.revokeDevice(target.name) }
if let target = revokeTarget { engine.revokeDevice(target.deviceID) }
}
Button(t("common.cancel"), role: .cancel) { }
}
@@ -438,9 +532,17 @@ struct SettingsView: View
Section
{
LabeledContent(t("ios.settings.user"), value: user.name)
// PATCH /api/devices/{device_id}
// token EngineController.renameSelf
TextField(t("ios.settings.deviceName"), text: $deviceNameDraft)
.submitLabel(.done)
.onChange(of: deviceNameDraft) { DeviceNameStore.value = deviceNameDraft }
.onSubmit { commitRename() }
if !engine.deviceActionStatus.isEmpty
{
Text(engine.deviceActionStatus)
.font(.caption)
.foregroundStyle(.secondary)
}
Button(role: .destructive) { logout() }
label:
{
@@ -511,6 +613,15 @@ struct SettingsView: View
return t("ios.engine.disconnected")
}
// 稿PATCH /api/devices/{device_id} /
// renamed + Keychain + engine.deviceName
private func commitRename()
{
let trimmed = deviceNameDraft.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != (auth.session?.deviceName ?? "") else { return }
engine.renameSelf(to: trimmed)
}
// SSE + WebView Keychain auth
private func logout()
{
+1 -1
View File
@@ -5,7 +5,7 @@
<!-- 与主 app 共享的 App Group:控件读取 widget_session.json(主 app 代铸的控件会话)。 -->
<key>com.apple.security.application-groups</key>
<array>
<string>group.net.commilitia.cdrop</string>
<string>group.net.commilitia.Commilitia-Drop</string>
</array>
</dict>
</plist>
+2 -14
View File
@@ -18,9 +18,6 @@ targets:
type: application
platform: iOS
deploymentTarget: "26.0"
configFiles:
Debug: Signing.xcconfig
Release: Signing.xcconfig
sources:
- path: Sources
- path: Shared
@@ -63,6 +60,8 @@ targets:
NSBonjourServices:
- "_cdrop._tcp"
NSCameraUsageDescription: "Commilitia Drop 使用相机扫描二维码登录新设备。"
# 图库选择:从相册选取图片 / 视频发送(PhotosPicker,见 RootView #14)。
NSPhotoLibraryUsageDescription: "Commilitia Drop 需要访问照片库,以便从相册选取图片或视频发送给其他设备。"
settings:
base:
PRODUCT_BUNDLE_IDENTIFIER: net.commilitia.Commilitia-Drop
@@ -71,18 +70,12 @@ targets:
# APNs 推送的 aps-environment entitlement(见 CDrop.entitlements)。模拟器取令牌可用;
# 真机签名须付费 ADP 开 Push 能力(账号门控)。
CODE_SIGN_ENTITLEMENTS: CDrop.entitlements
# 真机:用门户 profile 手动签名(仅 device SDK;模拟器走 base ad-hoc)。profile 名取自
# gitignore 的 Local.xcconfig(见 Signing.xcconfig / REALDEVICE.md)。
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]": "$(CDROP_PROFILE_APP)"
# Share Extension:抓分享文件 → App Group 收件箱 → 深链主 app 选设备发送(只交接、不跑引擎,
# 见 PLAN §I5)。只编 ShareViewController + 共享的 AppGroup,绝不拉主 app Sources(避超 120MB)。
CDropShare:
type: app-extension
platform: iOS
deploymentTarget: "26.0"
configFiles:
Debug: Signing.xcconfig
Release: Signing.xcconfig
sources:
- path: Share
- path: Shared
@@ -103,16 +96,12 @@ targets:
PRODUCT_BUNDLE_IDENTIFIER: net.commilitia.Commilitia-Drop.share
TARGETED_DEVICE_FAMILY: "1,2"
CODE_SIGN_ENTITLEMENTS: Share/CDropShare.entitlements
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]": "$(CDROP_PROFILE_SHARE)"
# 控制中心剪贴板两控件(WidgetKit ControlWidgetiOS 18+PLAN §I4)。纯原生 REST + 控件专用
# 设备会话(不跑引擎)。i18n JSON 一并打包使控件标签随设备语言(t() 经 no-subdir 回退读 bundle)。
CDropWidgets:
type: app-extension
platform: iOS
deploymentTarget: "26.0"
configFiles:
Debug: Signing.xcconfig
Release: Signing.xcconfig
sources:
- path: Widgets
- path: Shared
@@ -128,7 +117,6 @@ targets:
PRODUCT_BUNDLE_IDENTIFIER: net.commilitia.Commilitia-Drop.widgets
TARGETED_DEVICE_FAMILY: "1,2"
CODE_SIGN_ENTITLEMENTS: Widgets/CDropWidgets.entitlements
"PROVISIONING_PROFILE_SPECIFIER[sdk=iphoneos*]": "$(CDROP_PROFILE_WIDGETS)"
schemes:
CDrop:
build:
+1 -1
View File
@@ -111,7 +111,7 @@ Share Extension 落法(据上):**抓文件 → 写 App Group 容器 →
| **I6** APNs | 服务端通道(§3)+ 原生注册;不含剪贴板 | `.p8` + 真机硬等账号 |
| **I7** 打磨与分发 | 后台窗口;图标 / 启动屏(复用品牌资产);旁加载分发 | 硬等账号 |
> **实现状态(2026-06-27**I1/I2/I3/I4/I5/I6 的**代码**全部落地——发送端流式(R-iOS-4FileSource + 原生 Range,整文件不进 WebView 内存);后台续传(BGContinuedProcessingTask);APNs(后端 `internal/apns` ES256 + 原生注册经引擎桥);Share ExtensionApp Group 收件箱 + `cdrop://share` 深链);控制中心两控件(**专用 broker 设备会话**,纯原生 REST,不与引擎抢 refresh 轮换)。模拟器验 + ultracode 多 agent 审查修讫(0 HIGH,修 2 MED + 7 LOW)。**I0 账号 / 证书 + 真机签名 / 真发推送 / 旁加载分发**仍账号门控——手册 `ios/CDrop/REALDEVICE.md`手动签名 + `just ios-device` 全 CLI 装机,门户手动建)。包名 `net.commilitia.Commilitia-Drop`。
> **实现状态(2026-06-27**I1/I2/I3/I4/I5/I6 的**代码**全部落地——发送端流式(R-iOS-4FileSource + 原生 Range,整文件不进 WebView 内存);后台续传(BGContinuedProcessingTask);APNs(后端 `internal/apns` ES256 + 原生注册经引擎桥);Share ExtensionApp Group 收件箱 + `cdrop://share` 深链);控制中心两控件(**专用 broker 设备会话**,纯原生 REST,不与引擎抢 refresh 轮换)。模拟器验 + ultracode 多 agent 审查修讫(0 HIGH,修 2 MED + 7 LOW)。**I0 账号 / 证书 + 真机签名 / 真发推送 / 旁加载分发**仍账号门控——手册 `ios/CDrop/REALDEVICE.md`ASC API Key 自动 provisioning + `just ios-device` 全 CLI 装机,`-allowProvisioningUpdates` 自动登记设备 / 建 profile)。包名 `net.commilitia.Commilitia-Drop`App Group `group.net.commilitia.Commilitia-Drop`。
---