From d8daec760210c680ef72558f53548c402b4141d0 Mon Sep 17 00:00:00 2001 From: jureuk7 Date: Tue, 15 Sep 2026 13:56:28 +0900 Subject: [PATCH 1/5] Add Sparkle update checks and package delivery --- Package.resolved | 15 ++ Package.swift | 17 ++- README.md | 17 ++- Resources/Info.plist | 8 + Sources/GeulGuardInput/AppDelegate.swift | 43 +++++- .../GeulGuardInputController.swift | 27 ++++ .../GeulGuardInput/GeulGuardPreferences.swift | 6 + Sources/GeulGuardInput/UpdateController.swift | 141 ++++++++++++++++++ .../InputControllerTests.swift | 22 +++ .../UpdateConfigurationTests.swift | 53 +++++++ docs/agent-setup.md | 5 + docs/updates.md | 120 +++++++++++++++ scripts/build-app.sh | 32 +++- scripts/release-pkg.sh | 21 +++ scripts/update-metadata.swift | 108 ++++++++++++++ 15 files changed, 625 insertions(+), 10 deletions(-) create mode 100644 Package.resolved create mode 100644 Sources/GeulGuardInput/UpdateController.swift create mode 100644 Tests/GeulGuardInputTests/UpdateConfigurationTests.swift create mode 100644 docs/updates.md create mode 100644 scripts/update-metadata.swift diff --git a/Package.resolved b/Package.resolved new file mode 100644 index 0000000..c89ffbf --- /dev/null +++ b/Package.resolved @@ -0,0 +1,15 @@ +{ + "originHash" : "b6922c05244430d6d49427388cb55d40441f7d27e015b377004e561aceb20972", + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100", + "version" : "2.10.0" + } + } + ], + "version" : 3 +} diff --git a/Package.swift b/Package.swift index f309c2f..0c5a35b 100644 --- a/Package.swift +++ b/Package.swift @@ -11,18 +11,29 @@ let package = Package( .library(name: "HangulCore", targets: ["HangulCore"]), .executable(name: "GeulGuardInput", targets: ["GeulGuardInput"]) ], + dependencies: [ + .package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.0") + ], targets: [ .target(name: "HangulCore"), .executableTarget( name: "GeulGuardInput", - dependencies: ["HangulCore"], + dependencies: ["HangulCore", .product(name: "Sparkle", package: "Sparkle")], linkerSettings: [ .linkedFramework("AppKit"), .linkedFramework("InputMethodKit"), - .linkedFramework("SwiftUI") + .linkedFramework("SwiftUI"), + .linkedFramework("Carbon"), + .unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@executable_path/../Frameworks"]) + ] + ), + .testTarget( + name: "GeulGuardInputTests", + dependencies: ["GeulGuardInput"], + linkerSettings: [ + .unsafeFlags(["-Xlinker", "-rpath", "-Xlinker", "@loader_path/../../.."]) ] ), - .testTarget(name: "GeulGuardInputTests", dependencies: ["GeulGuardInput"]), .testTarget( name: "HangulCoreTests", dependencies: ["HangulCore"] diff --git a/README.md b/README.md index bbcc097..56ff35b 100644 --- a/README.md +++ b/README.md @@ -37,6 +37,20 @@ Binary를 `/Library/Input Methods`에 설치하므로 관리자 암호가 필요 확인·변경할 수 있습니다. 글가드는 `Shift+Space`를 한/영 전환으로 가로채지 않습니다. ESC는 조합 중인 한글만 확정하며 입력 소스를 바꾸지 않습니다. +## 업데이트 + +업데이트가 설정된 배포본에서는 메뉴 막대의 글가드 아이콘 → `업데이트 확인…`으로 +새 버전을 확인합니다. 앱이 시작될 때 백그라운드에서 한 번 자동 확인하며 새 버전이 +있을 때만 안내합니다. 설정의 `앱 시작 시 업데이트 확인`에서 끌 수 있습니다. +설치는 사용자 확인과 관리자 인증을 거칩니다. + +설치 전에 입력 중인 글자를 확정하고 ABC로 전환하세요. 조합 중인 글자가 남거나 +현재 소스가 ABC가 아니면 업데이트를 위한 종료를 막습니다. 설치 후 글가드를 다시 +선택하고, 새 버전이 반영되지 않으면 작업 저장 후 로그아웃·로그인하세요. +업데이터가 없는 기존 버전은 업데이트 기능을 포함한 PKG를 한 번 수동 설치해야 합니다. +피드·공개키를 지정하지 않은 개발 빌드에서는 업데이트 메뉴와 설정이 비활성화됩니다. +배포 준비와 검증 절차는 [업데이트 배포 문서](docs/updates.md)를 참고하세요. + ## 권장 사용법: ABC + 글가드 두벌식 + Karabiner 영어는 **ABC**, 한글은 **글가드 두벌식**, Caps Lock 전환은 **Karabiner-Elements**가 @@ -106,7 +120,8 @@ Shift로 직접 입력하는 쌍자음과 겹받침 조합에는 영향을 주 ## 개인정보 키 입력은 현재 포커스된 앱으로 전달하기 위해 메모리에서만 처리합니다. 네트워크 -연결, 입력 기록, 접근성 권한을 사용하지 않습니다. +연결은 업데이트 확인·다운로드에만 사용하며, 키 입력을 기록하거나 전송하지 않습니다. +접근성 권한을 사용하지 않습니다. 선택 구성인 Karabiner-Elements는 키를 재매핑하기 위한 별도의 macOS 권한과 드라이버를 사용합니다. 글가드 자체의 권한과 구분하세요. diff --git a/Resources/Info.plist b/Resources/Info.plist index 562a6c2..c3d77f7 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -64,6 +64,14 @@ LSMinimumSystemVersion 14.0 + SUEnableAutomaticChecks + + SUAllowsAutomaticUpdates + + SUAutomaticallyUpdate + + SUSendProfileInfo + NSPrincipalClass NSApplication TISInputSourceID diff --git a/Sources/GeulGuardInput/AppDelegate.swift b/Sources/GeulGuardInput/AppDelegate.swift index 5f48fe8..d4b3811 100644 --- a/Sources/GeulGuardInput/AppDelegate.swift +++ b/Sources/GeulGuardInput/AppDelegate.swift @@ -2,11 +2,13 @@ import AppKit import SwiftUI @MainActor -final class AppDelegate: NSObject, NSApplicationDelegate { +final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation { + private lazy var updates = UpdateController() private var statusItem: NSStatusItem? private var settingsWindow: NSWindow? func applicationDidFinishLaunching(_ notification: Notification) { + _ = updates configureStatusItem() if ProcessInfo.processInfo.arguments.contains("--settings") { showSettings() @@ -15,10 +17,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { @objc private func showSettings() { if settingsWindow == nil { - let rootView = SettingsView() + let rootView = SettingsView(updates: updates) let window = NSWindow(contentViewController: NSHostingController(rootView: rootView)) window.title = "글가드 설정" - window.setContentSize(NSSize(width: 520, height: 540)) + window.setContentSize(NSSize(width: 520, height: 680)) window.styleMask = [.titled, .closable, .miniaturizable] window.isReleasedWhenClosed = false settingsWindow = window @@ -29,10 +31,22 @@ final class AppDelegate: NSObject, NSApplicationDelegate { settingsWindow?.makeKeyAndOrderFront(nil) } + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + updates.confirmTermination() + } + + @objc private func checkForUpdates() { + updates.checkForUpdates() + } + @objc private func quit() { NSApp.terminate(nil) } + func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { + menuItem.action != #selector(checkForUpdates) || updates.canCheckForUpdates + } + private func configureStatusItem() { let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) item.button?.toolTip = "글가드 · 한글 입력기" @@ -47,6 +61,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate { let menu = NSMenu() menu.addItem(withTitle: "설정…", action: #selector(showSettings), keyEquivalent: ",") + let updateItem = menu.addItem(withTitle: "업데이트 확인…", action: #selector(checkForUpdates), keyEquivalent: "") + updateItem.target = self menu.addItem(.separator()) menu.addItem(withTitle: "글가드 종료", action: #selector(quit), keyEquivalent: "q") item.menu = menu @@ -55,6 +71,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } private struct SettingsView: View { + @ObservedObject var updates: UpdateController @AppStorage(GeulGuardPreferences.combineRepeatedInitialsKey) private var combineRepeatedInitials = true @@ -77,7 +94,7 @@ private struct SettingsView: View { feature("한/영 전환", "macOS 입력 메뉴나 시스템 단축키로 ABC ↔ 글가드를 전환합니다.") feature("커서 이동 안전", "방향키·Tab·Return·단축키 전에 조합 문자를 먼저 확정합니다.") feature("ESC 확정", "조합 중인 한글만 확정합니다. 영어는 ABC 입력 소스를 사용하세요.") - feature("개인정보 보호", "네트워크 연결, 키 입력 저장, 접근성 권한이 없습니다.") + feature("개인정보 보호", "업데이트 확인·다운로드에만 네트워크를 사용하며 키 입력을 저장하거나 전송하지 않습니다.") Divider() @@ -89,15 +106,31 @@ private struct SettingsView: View { .foregroundStyle(.secondary) } + Divider() + + VStack(alignment: .leading, spacing: 8) { + Text("업데이트").font(.headline) + Toggle("앱 시작 시 업데이트 확인", isOn: Binding( + get: { updates.checksOnLaunch }, + set: { updates.setChecksOnLaunch($0) } + )) + .disabled(!updates.isAvailable) + Text(updates.status) + .font(.callout) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer() + Text("시스템 설정 → 키보드 → 텍스트 입력 → 편집에서 ‘ABC’와 ‘글가드 두벌식’을 추가하세요.") .font(.callout) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } .padding(28) - .frame(minWidth: 520, minHeight: 540) + .frame(minWidth: 520, minHeight: 680) } private func feature(_ title: String, _ description: String) -> some View { diff --git a/Sources/GeulGuardInput/GeulGuardInputController.swift b/Sources/GeulGuardInput/GeulGuardInputController.swift index 3c44398..e5f024f 100644 --- a/Sources/GeulGuardInput/GeulGuardInputController.swift +++ b/Sources/GeulGuardInput/GeulGuardInputController.swift @@ -1,14 +1,22 @@ import AppKit import HangulCore import InputMethodKit +import os @objc(GeulGuardInputController) final class GeulGuardInputController: IMKInputController { + private static let composingSessions = OSAllocatedUnfairLock(initialState: Set()) + + static var hasPendingComposition: Bool { + composingSessions.withLock { !$0.isEmpty } + } + private var composer = HangulComposer() private let noReplacement = NSRange(location: NSNotFound, length: NSNotFound) override func handle(_ event: NSEvent!, client sender: Any!) -> Bool { guard let event, let client = sender as? IMKTextInput else { return false } + defer { recordCompositionState() } guard event.modifierFlags.intersection([.command, .control, .option]).isEmpty else { commitComposition(to: client) @@ -44,6 +52,7 @@ final class GeulGuardInputController: IMKInputController { } override func commitComposition(_ sender: Any!) { + defer { recordCompositionState() } guard let client = sender as? IMKTextInput else { composer.cancel() return @@ -52,6 +61,7 @@ final class GeulGuardInputController: IMKInputController { } override func deactivateServer(_ sender: Any!) { + defer { recordCompositionState() } if let client = sender as? IMKTextInput { commitComposition(to: client) } else { @@ -60,6 +70,23 @@ final class GeulGuardInputController: IMKInputController { super.deactivateServer(sender) } + deinit { + let identifier = ObjectIdentifier(self) + _ = Self.composingSessions.withLock { $0.remove(identifier) } + } + + private func recordCompositionState() { + let identifier = ObjectIdentifier(self) + let hasComposition = composer.hasComposition + Self.composingSessions.withLock { sessions in + if hasComposition { + sessions.insert(identifier) + } else { + sessions.remove(identifier) + } + } + } + private func apply(_ update: CompositionUpdate, to client: IMKTextInput) { if !update.committed.isEmpty { client.insertText(update.committed, replacementRange: noReplacement) diff --git a/Sources/GeulGuardInput/GeulGuardPreferences.swift b/Sources/GeulGuardInput/GeulGuardPreferences.swift index 5502264..0a8b58a 100644 --- a/Sources/GeulGuardInput/GeulGuardPreferences.swift +++ b/Sources/GeulGuardInput/GeulGuardPreferences.swift @@ -1,6 +1,12 @@ import Foundation enum GeulGuardPreferences { + static let checkForUpdatesOnLaunchKey = "checkForUpdatesOnLaunch" + + static var checksForUpdatesOnLaunch: Bool { + UserDefaults.standard.object(forKey: checkForUpdatesOnLaunchKey) as? Bool ?? true + } + static let combineRepeatedInitialsKey = "combineRepeatedInitials" static var combinesRepeatedInitials: Bool { diff --git a/Sources/GeulGuardInput/UpdateController.swift b/Sources/GeulGuardInput/UpdateController.swift new file mode 100644 index 0000000..6692761 --- /dev/null +++ b/Sources/GeulGuardInput/UpdateController.swift @@ -0,0 +1,141 @@ +import AppKit +import Carbon +import Combine +import Sparkle + +struct UpdateConfiguration { + static func isValid(_ info: [String: Any]) -> Bool { + guard let address = info["SUFeedURL"] as? String, + let url = URL(string: address), url.scheme == "https", + let host = url.host, !host.isEmpty, + url.user == nil, url.password == nil, + let key = info["SUPublicEDKey"] as? String, + Data(base64Encoded: key)?.count == 32 else { return false } + return true + } + + static func isOfficialPackage(_ url: URL?) -> Bool { + guard let url, url.scheme == "https", url.host == "github.com", + url.user == nil, url.password == nil, url.port == nil, + url.query == nil, url.fragment == nil else { return false } + let parts = url.pathComponents + return parts.count == 7 && parts[1...4] == ["jureuk7", "GeulGuard", "releases", "download"] + && !parts[5].isEmpty && parts[6] == "GeulGuard.pkg" + } + + static func canTerminateForUpdate(sourceID: String?, hasComposition: Bool) -> Bool { + sourceID == "com.apple.keylayout.ABC" && !hasComposition + } +} + +@MainActor +final class UpdateController: NSObject, ObservableObject, SPUUpdaterDelegate { + @Published private(set) var isAvailable = false + @Published private(set) var canCheckForUpdates = false + @Published private(set) var checksOnLaunch = GeulGuardPreferences.checksForUpdatesOnLaunch + @Published private(set) var status = "이 빌드에서는 업데이트를 사용할 수 없습니다." + private var controller: SPUStandardUpdaterController? + private var observations: [NSKeyValueObservation] = [] + private(set) var isInstallingUpdate = false + + override init() { + super.init() + guard UpdateConfiguration.isValid(Bundle.main.infoDictionary ?? [:]) else { return } + let controller = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: self, userDriverDelegate: nil) + self.controller = controller + controller.updater.automaticallyChecksForUpdates = false + controller.updater.automaticallyDownloadsUpdates = false + controller.updater.sendsSystemProfile = false + do { + try controller.updater.start() + isAvailable = true + status = "설치 시 관리자 인증이 필요하며, 로그아웃 후 다시 로그인해야 할 수 있습니다." + observations = [ + controller.updater.observe(\.canCheckForUpdates, options: [.initial, .new]) { [weak self] _, _ in + Task { @MainActor [weak self] in self?.refreshState() } + } + ] + refreshState() + if checksOnLaunch { + controller.updater.checkForUpdatesInBackground() + } + } catch { + status = "업데이트를 시작하지 못했습니다. 공식 배포본을 다시 설치해 주세요." + } + } + + private func refreshState() { + canCheckForUpdates = controller?.updater.canCheckForUpdates ?? false + } + + func setChecksOnLaunch(_ enabled: Bool) { + guard isAvailable else { return } + UserDefaults.standard.set(enabled, forKey: GeulGuardPreferences.checkForUpdatesOnLaunchKey) + checksOnLaunch = enabled + } + + @objc func checkForUpdates() { + guard isAvailable, controller?.updater.canCheckForUpdates == true else { return } + controller?.checkForUpdates(nil) + } + + func updater(_ updater: SPUUpdater, shouldProceedWithUpdate updateItem: SUAppcastItem, + updateCheck: SPUUpdateCheck) throws { + guard updateItem.installationType == "package", + UpdateConfiguration.isOfficialPackage(updateItem.fileURL) else { + throw NSError(domain: "dev.jureuk.GeulGuard.Update", code: 1, + userInfo: [NSLocalizedDescriptionKey: "공식 글가드 PKG 업데이트가 아닙니다."]) + } + } + + func allowedSystemProfileKeys(for updater: SPUUpdater) -> [String]? { [] } + + func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) { + isInstallingUpdate = true + } + + func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem, + immediateInstallationBlock immediateInstallHandler: @escaping () -> Void) -> Bool { + isInstallingUpdate = true + return false + } + + func updater(_ updater: SPUUpdater, userDidMake choice: SPUUserUpdateChoice, + forUpdate updateItem: SUAppcastItem, state: SPUUserUpdateState) { + if state.stage == .installing { + isInstallingUpdate = true + } + } + + func updater(_ updater: SPUUpdater, didAbortWithError error: Error) { + isInstallingUpdate = false + } + + func confirmTermination() -> NSApplication.TerminateReply { + guard isInstallingUpdate else { return .terminateNow } + let alert = NSAlert() + alert.messageText = "글가드 업데이트를 설치할까요?" + alert.informativeText = "입력 중인 글자를 확정하고 메뉴 막대에서 ABC로 전환해 주세요. 설치 후 글가드를 다시 선택하세요. 반영되지 않으면 작업을 저장한 뒤 로그아웃하고 다시 로그인해 주세요." + alert.addButton(withTitle: "설치 계속") + alert.addButton(withTitle: "취소") + guard alert.runModal() == .alertFirstButtonReturn else { return .terminateCancel } + guard UpdateConfiguration.canTerminateForUpdate( + sourceID: Self.currentInputSourceID, + hasComposition: GeulGuardInputController.hasPendingComposition + ) else { + let blocked = NSAlert() + blocked.messageText = "ABC로 전환한 뒤 다시 시도해 주세요" + blocked.informativeText = "조합 중인 글자가 남아 있거나 현재 입력 소스가 ABC가 아닙니다. 업데이트 창에서 설치를 다시 시도할 수 있습니다." + blocked.addButton(withTitle: "확인") + blocked.runModal() + return .terminateCancel + } + return .terminateNow + } + + private static var currentInputSourceID: String? { + guard let source = TISCopyCurrentKeyboardInputSource()?.takeRetainedValue(), + let value = TISGetInputSourceProperty(source, kTISPropertyInputSourceID) else { return nil } + return Unmanaged.fromOpaque(value).takeUnretainedValue() as String + } +} diff --git a/Tests/GeulGuardInputTests/InputControllerTests.swift b/Tests/GeulGuardInputTests/InputControllerTests.swift index 705c59b..299e52c 100644 --- a/Tests/GeulGuardInputTests/InputControllerTests.swift +++ b/Tests/GeulGuardInputTests/InputControllerTests.swift @@ -5,6 +5,28 @@ import XCTest final class InputControllerTests: XCTestCase { @MainActor + func testUpdateWaitsForEveryCompositionToFinish() { + let firstClient = TextClient() + let secondClient = TextClient() + let first = GeulGuardInputController(server: nil, delegate: nil, client: nil)! + var second: GeulGuardInputController? = GeulGuardInputController(server: nil, delegate: nil, client: nil)! + XCTAssertFalse(GeulGuardInputController.hasPendingComposition) + XCTAssertTrue(first.handle(key("r", code: 15), client: firstClient)) + XCTAssertTrue(second!.handle(key("k", code: 40), client: secondClient)) + XCTAssertTrue(GeulGuardInputController.hasPendingComposition) + first.deactivateServer(firstClient) + XCTAssertEqual(firstClient.string, "ㄱ") + XCTAssertTrue(GeulGuardInputController.hasPendingComposition) + second?.commitComposition(secondClient) + XCTAssertEqual(secondClient.string, "ㅏ") + XCTAssertFalse(GeulGuardInputController.hasPendingComposition) + XCTAssertTrue(second!.handle(key("r", code: 15), client: secondClient)) + second = nil + XCTAssertFalse(GeulGuardInputController.hasPendingComposition) + } + + @MainActor + func testEmptyCommitDoesNotEraseSelectedEnglishText() { let client = TextClient() client.string = "abcdef" diff --git a/Tests/GeulGuardInputTests/UpdateConfigurationTests.swift b/Tests/GeulGuardInputTests/UpdateConfigurationTests.swift new file mode 100644 index 0000000..83618d2 --- /dev/null +++ b/Tests/GeulGuardInputTests/UpdateConfigurationTests.swift @@ -0,0 +1,53 @@ +import XCTest +@testable import GeulGuardInput + +final class UpdateConfigurationTests: XCTestCase { + private let publicKey = Data(repeating: 1, count: 32).base64EncodedString() + + func testLaunchChecksDefaultOnAndRespectOptOut() { + let defaults = UserDefaults.standard + let key = GeulGuardPreferences.checkForUpdatesOnLaunchKey + let previous = defaults.object(forKey: key) + defer { + if let previous { defaults.set(previous, forKey: key) } + else { defaults.removeObject(forKey: key) } + } + defaults.removeObject(forKey: key) + XCTAssertTrue(GeulGuardPreferences.checksForUpdatesOnLaunch) + defaults.set(false, forKey: key) + XCTAssertFalse(GeulGuardPreferences.checksForUpdatesOnLaunch) + defaults.set(true, forKey: key) + XCTAssertTrue(GeulGuardPreferences.checksForUpdatesOnLaunch) + } + + func testUpdatesRequireHTTPSAndACompletePublicKey() { + XCTAssertFalse(UpdateConfiguration.isValid([:])) + for address in ["http://example.com/appcast.xml", "file:///tmp/feed", "https://user:pass@example.com/feed"] { + XCTAssertFalse(UpdateConfiguration.isValid(["SUFeedURL": address, "SUPublicEDKey": publicKey])) + } + XCTAssertFalse(UpdateConfiguration.isValid(["SUFeedURL": "https://example.com/feed", "SUPublicEDKey": "placeholder"])) + XCTAssertTrue(UpdateConfiguration.isValid(["SUFeedURL": "https://example.com/feed", "SUPublicEDKey": publicKey])) + } + + func testOnlyOfficialVersionedPackagesAreAccepted() { + XCTAssertTrue(UpdateConfiguration.isOfficialPackage(URL(string: "https://github.com/jureuk7/GeulGuard/releases/download/v0.6.0/GeulGuard.pkg"))) + for address in [ + "http://github.com/jureuk7/GeulGuard/releases/download/v0.6.0/GeulGuard.pkg", + "https://github.com/attacker/GeulGuard/releases/download/v0.6.0/GeulGuard.pkg", + "https://github.com/jureuk7/GeulGuard/releases/latest/download/GeulGuard.pkg", + "https://github.com/jureuk7/GeulGuard/releases/download/v0.6.0/GeulGuard.zip", + "https://github.com/jureuk7/GeulGuard/releases/download/v0.6.0/GeulGuard.pkg?redirect=1", + "https://github.com:443/jureuk7/GeulGuard/releases/download/v0.6.0/GeulGuard.pkg" + ] { + XCTAssertFalse(UpdateConfiguration.isOfficialPackage(URL(string: address)), address) + } + XCTAssertFalse(UpdateConfiguration.isOfficialPackage(nil)) + } + + func testUnknownOrHangulSourceAndPendingTextBlockTermination() { + XCTAssertTrue(UpdateConfiguration.canTerminateForUpdate(sourceID: "com.apple.keylayout.ABC", hasComposition: false)) + XCTAssertFalse(UpdateConfiguration.canTerminateForUpdate(sourceID: "com.apple.keylayout.ABC", hasComposition: true)) + XCTAssertFalse(UpdateConfiguration.canTerminateForUpdate(sourceID: nil, hasComposition: false)) + XCTAssertFalse(UpdateConfiguration.canTerminateForUpdate(sourceID: "dev.jureuk.inputmethod.GeulGuard", hasComposition: false)) + } +} diff --git a/docs/agent-setup.md b/docs/agent-setup.md index 86634d4..82d9603 100644 --- a/docs/agent-setup.md +++ b/docs/agent-setup.md @@ -29,6 +29,11 @@ ABC 영어 입력, 글가드 한글 입력, Karabiner의 Caps Lock 전환이다. ABC와 `글가드 두벌식`을 추가한다. 단순 파일 복사만으로 입력 소스 등록 완료를 선언하지 않는다. 4. 설치된 버전과 실제 선택 가능한 `글가드 두벌식`을 확인한다. +업데이터가 포함된 배포본의 업데이트는 글가드 메뉴의 ‘업데이트 확인…’에서 +진행할 수 있다. 입력 중인 글자를 확정하고 ABC로 전환한 뒤 설치를 진행한다. +관리자 인증·필요 시 로그아웃·설치 후 실제 입력 확인은 위와 동일하게 구분한다. +업데이트 기능이 비활성화된 개발 빌드는 공식 PKG 설치 경로를 사용한다. + 소스 빌드를 명시적으로 요청한 경우에만 README의 개발 설치 경로를 사용한다. 개발 설치는 사용자 Library, PKG는 시스템 Library에 설치하므로 중복에 주의한다. 클린 설치를 요청한 경우 ABC 전환 후 기존 글가드 입력 소스를 제거하고, 확인된 diff --git a/docs/updates.md b/docs/updates.md new file mode 100644 index 0000000..4979610 --- /dev/null +++ b/docs/updates.md @@ -0,0 +1,120 @@ +# 업데이트 배포 + +글가드는 Sparkle 2로 업데이트를 확인하고, 공식 GitHub Release의 서명·공증된 +PKG를 설치한다. 업데이트 설치에는 사용자 동의와 macOS 관리자 인증이 필요하다. +입력기의 설치 경로는 `/Library/Input Methods`다. PKG 설치 성공과 새 입력기의 +활성화는 별개이며, 새 버전 적용에 로그아웃·로그인이 필요할 수 있다. + +## 빌드 설정 + +`scripts/build-app.sh`는 SwiftPM의 Sparkle 프레임워크를 앱에 복사하고 내부 +XPC 서비스, Autoupdate, Updater.app, 프레임워크, 앱 순서로 서명한다. 프레임워크의 +심볼릭 링크와 실행 권한을 보존한다. 기존 `CONFIGURATION`, +`GEUL_GUARD_ARCHITECTURES`, `GEUL_GUARD_SCRATCH_PATH`, `CODESIGN_IDENTITY` 설정을 +그대로 사용한다. 개발 빌드는 기본적으로 ad-hoc 서명이다. + +다음 두 환경변수는 **공개 정보**이며 빌드한 앱의 Info.plist에 포함된다. + +| 환경변수 | 용도 | +| --- | --- | +| `GEUL_GUARD_UPDATE_FEED_URL` | `SUFeedURL`에 기록할 고정 HTTPS appcast 주소 | +| `GEUL_GUARD_UPDATE_PUBLIC_KEY` | `SUPublicEDKey`에 기록할 Base64 Ed25519 공개키, 디코딩 후 32바이트 | + +둘 다 생략하면 업데이트 서버가 설정되지 않은 개발 빌드다. 하나만 지정하거나 +유효하지 않은 값을 지정하면 빌드가 실패한다. 피드 URL에는 사용자명·암호를 +넣을 수 없다. 비공개 키를 환경변수나 저장소에 넣지 않는다. + +## 릴리스 준비 + +릴리스 담당자는 고정 HTTPS 피드 호스팅과 Sparkle 서명 키를 먼저 준비한다. +Sparkle의 `generate_keys`는 키체인에 키를 저장하는 도구다. 키 생성은 자동 빌드에 +포함되지 않으며, 운영자가 [공식 키 관리 안내](https://sparkle-project.org/documentation/) +에 따라 별도로 수행한다. PKG 업데이트는 키 분실 시 일반 앱 번들의 키 교체 +대체 경로를 지원하지 않으므로 키 보관 정책을 먼저 정한다. + +`scripts/release-pkg.sh`에는 위 두 공개 설정 외에 다음 환경변수가 필요하다. + +| 환경변수 | 용도 | +| --- | --- | +| `DEVELOPER_ID_APPLICATION` | 키체인의 앱 서명 인증서 이름 | +| `DEVELOPER_ID_INSTALLER` | 키체인의 설치 패키지 서명 인증서 이름 | +| `NOTARY_PROFILE` | 기존 notarytool 키체인 프로필 이름 | +| `GEUL_GUARD_RELEASE_DOWNLOAD_URL` | `https://github.com/jureuk7/GeulGuard/releases/download/v버전/GeulGuard.pkg` 형식의 공식 다운로드 주소 | +| `GEUL_GUARD_RELEASE_PATH` | 선택 사항. 격리된 릴리스 작업 디렉터리 | + +다운로드 주소의 버전은 빌드된 앱의 `CFBundleShortVersionString`과 같아야 한다. +`latest/download` 같은 가변 주소는 허용하지 않는다. 새 릴리스의 +`CFBundleVersion`은 기존 버전보다 증가해야 한다. + +릴리스 스크립트는 universal 앱과 서명된 PKG를 생성하고 공증·staple·Gatekeeper +검증을 수행한다. 그 후 Sparkle의 `sign_update`가 키체인의 기본 `ed25519` +계정으로 최종 PKG를 서명한다. 키 파일과 비공개 키 환경변수는 사용하지 않는다. +`scripts/update-metadata.swift`는 PKG 서명을 앱에 내장된 공개키로 검증한 뒤 +`dist/appcast.xml`을 만든다. 따라서 키체인의 키와 앱의 공개키가 다르면 실패한다. + +appcast는 빌드된 앱의 버전·최소 macOS, 최종 PKG의 크기·EdDSA 서명, +`installationType="package"`를 포함하는 단일 최신 버전 피드다. 기존 피드의 +항목을 합치거나 배포하지 않는다. 공식 `generate_appcast`는 PKG 자동 생성을 +지원하지 않으므로 이 전용 생성기를 사용한다. + +## 게시 순서와 검증 + +1. 서명·공증된 구버전과 신버전을 준비하고 테스트용 HTTPS 피드로 검증한다. +2. 사용자 확인, 취소, 다운로드 실패, 서명 불일치, 조합 중 설치 시도를 확인한다. +3. 관리자 인증 후 PKG 설치와 새 입력기의 활성화를 각각 확인한다. 조합 내용, + 기존 입력 소스와 Karabiner 규칙이 보존되는지 확인한다. +4. 공식 GitHub Release의 버전별 주소에 최종 `GeulGuard.pkg`를 게시한다. + 이미 공개한 버전의 PKG 파일은 교체하지 않는다. +5. 해당 주소의 다운로드와 바이트 일치를 확인한 후 마지막으로 고정 HTTPS + 주소에 `dist/appcast.xml`을 게시한다. 피드의 최소 OS보다 오래된 사용자를 + 계속 지원하려면 기존 호환 항목도 함께 보존해야 한다. + +스크립트는 업로드, GitHub Release 생성, 사용자 Mac 설치 또는 설정 변경을 +수행하지 않는다. ad-hoc 빌드의 실행만으로 PKG 업데이트 호환성을 주장하지 +않는다. 실제 입력 앱별 호환성 범위는 [compatibility.md](compatibility.md)를 따른다. + +## 개발 검증 + +각 스크립트는 `--help`를 지원하며 알 수 없는 인수를 거절한다. +`update-metadata.swift`의 메타데이터 생성은 공개 RFC 8032 서명 벡터로 검사할 수 +있다. 이 검사는 XML 생성과 서명 검증 검사이며, 실제 PKG 설치 검증을 대신하지 +않는다. + +참고: [Sparkle PKG 업데이트](https://sparkle-project.org/documentation/package-updates/), +[Sparkle 설치·서명 문서](https://sparkle-project.org/documentation/). + +## 입력 중 설치 보호 + +앱 시작 시 한 번 자동 확인하는 것이 기본값이며 설정에서 끌 수 있다. 주기적 자동 확인과 자동 다운로드·무인 설치는 비활성화한다. 사용자가 +설치를 선택하면 종료 확인창을 표시한다. ABC가 현재 입력 소스이고 모든 입력 +세션의 조합이 끝난 경우에만 앱 종료를 허용한다. API로 입력 소스를 강제로 +전환하지 않으며, 기존 입력 소스와 Karabiner 설정도 변경하지 않는다. + +| 보안·입력 불변식 | 구현 위치 | +| --- | --- | +| 피드·공개키 미설정 시 업데이터 비활성 | `Sources/GeulGuardInput/UpdateController.swift`의 `UpdateConfiguration.isValid` | +| 공식 버전별 PKG만 허용, Sparkle에서 다운로드 서명 검증 | `UpdateController.updater(_:shouldProceedWithUpdate:updateCheck:)`, `SUPublicEDKey` | +| 키 입력·시스템 프로필을 업데이트 요청에 포함하지 않음 | `UpdateController.init`, `allowedSystemProfileKeys(for:)` | +| ABC 전환·조합 종료 확인 전 업데이트 종료 거부 | `UpdateController.confirmTermination`, `GeulGuardInputController.hasPendingComposition` | +| 비공개 키를 파일·환경변수에 수집하지 않음 | `scripts/release-pkg.sh`의 키체인 `sign_update` 호출 | + +## 2026-09-15 개발 검증 기록 + +- Swift 테스트 32개 통과: 기존 조합·입력·표시 검사와 업데이트 설정·URL 제한· + 모든 세션의 조합 종료 감지·시작 시 확인 기본값/비활성화 검사. +- 앱 번들 빌드와 Sparkle 내부 구성요소를 포함한 `codesign --verify --deep --strict` + 통과. 테스트 런너에는 Sparkle 프레임워크를 찾도록 전용 rpath를 추가했다. +- 별도 QA 번들 ID로 실제 설정 화면을 열어 시작 시 확인 기본 켜짐, 끄기/켜기, + 재실행 후 설정 유지, 미설정 빌드의 비활성 상태를 확인했다. 설정 화면에는 + 중복 수동 확인 버튼이 없다. +- 테스트용 공개키와 HTTPS 피드를 지정한 QA 앱에서 시작 시 마지막 확인 시간이 + 갱신되고, 옵션을 끈 뒤 재실행하면 갱신되지 않으며, 다시 켜고 실행하면 + 갱신되는 것을 확인했다. 테스트 피드 실패 시 시작을 막는 경고창은 없었다. +- 공개 RFC 8032 벡터로 appcast 생성/XML 문법, 잘못된 주소·HTTP 피드·변조된 + 데이터의 거부를 확인했다. 테스트 벡터는 배포용 키가 아니다. + +아직 검증하지 않은 항목: 메뉴바 항목의 실제 마우스 클릭, 새 버전 발견 안내, +관리자 인증을 거친 서명·공증 PKG 업데이트, 취소 후 재시도 및 업데이트 후 +실제 입력 앱에서의 재활성화. 공개 피드·Sparkle 배포 키를 준비하고 실제 +구버전→신버전으로 검증한 뒤 배포해야 한다. 현재 작업은 사용자 입력 소스나 +Karabiner 설정을 변경하지 않았으며 배포 PKG 설치·공개 게시를 수행하지 않았다. diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 6ff45a5..105012c 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -1,6 +1,14 @@ #!/bin/bash set -euo pipefail +if [[ "${1:-}" == "--help" && $# -eq 1 ]]; then + echo "Usage: scripts/build-app.sh (configuration via environment; see docs/updates.md)" + exit 0 +elif [[ $# -ne 0 ]]; then + echo "잘못된 인수입니다. --help를 확인하세요" >&2 + exit 2 +fi + project_root="$(cd "$(dirname "$0")/.." && pwd)" configuration="${CONFIGURATION:-debug}" scratch_path="${GEUL_GUARD_SCRATCH_PATH:-${TMPDIR:-/tmp}/GeulGuardBuild}" @@ -16,6 +24,7 @@ if [[ ${#architectures[@]} -eq 0 ]]; then fi binary_paths=() +sparkle_framework="" for architecture in "${architectures[@]}"; do architecture_scratch="$scratch_path/build-$architecture" module_cache="$architecture_scratch/ModuleCache" @@ -41,8 +50,14 @@ for architecture in "${architectures[@]}"; do SWIFTPM_MODULECACHE_OVERRIDE="$module_cache" \ "${build_arguments[@]}" --show-bin-path)" binary_paths+=("$binary_directory/GeulGuardInput") + sparkle_framework="$architecture_scratch/artifacts/sparkle/Sparkle/Sparkle.xcframework/macos-arm64_x86_64/Sparkle.framework" done +if [[ ! -d "$sparkle_framework" ]]; then + echo "Sparkle 프레임워크를 찾을 수 없습니다: $sparkle_framework" >&2 + exit 1 +fi + binary_path="$scratch_path/GeulGuardInput" if [[ ${#binary_paths[@]} -eq 1 ]]; then COPYFILE_DISABLE=1 cp "${binary_paths[0]}" "$binary_path" @@ -53,9 +68,11 @@ fi if [[ -d "$app_path" ]]; then mv "$app_path" "$scratch_path/GeulGuard.previous.$$.app" fi -mkdir -p "$app_path/Contents/MacOS" "$app_path/Contents/Resources" +mkdir -p "$app_path/Contents/MacOS" "$app_path/Contents/Resources" "$app_path/Contents/Frameworks" +COPYFILE_DISABLE=1 cp -R "$sparkle_framework" "$app_path/Contents/Frameworks/" COPYFILE_DISABLE=1 cp "$binary_path" "$app_path/Contents/MacOS/GeulGuardInput" COPYFILE_DISABLE=1 cp "$project_root/Resources/Info.plist" "$app_path/Contents/Info.plist" +swift "$project_root/scripts/update-metadata.swift" configure "$app_path/Contents/Info.plist" for localization in ko en; do mkdir -p "$app_path/Contents/Resources/${localization}.lproj" COPYFILE_DISABLE=1 cp \ @@ -68,6 +85,19 @@ COPYFILE_DISABLE=1 cp \ "$project_root/Resources/GeulGuard.icns" \ "$app_path/Contents/Resources/GeulGuard.icns" xattr -cr "$app_path" +sign_arguments=(--force --sign "$codesign_identity") +if [[ "$codesign_identity" != "-" ]]; then + sign_arguments+=(--options runtime --timestamp) +fi +framework_version="$app_path/Contents/Frameworks/Sparkle.framework/Versions/B" +for component in \ + "$framework_version/XPCServices/Downloader.xpc" \ + "$framework_version/XPCServices/Installer.xpc" \ + "$framework_version/Autoupdate" \ + "$framework_version/Updater.app" \ + "$app_path/Contents/Frameworks/Sparkle.framework"; do + codesign "${sign_arguments[@]}" "$component" +done if [[ "$codesign_identity" == "-" ]]; then codesign --force --sign - "$app_path" else diff --git a/scripts/release-pkg.sh b/scripts/release-pkg.sh index 032f56e..dbb746f 100755 --- a/scripts/release-pkg.sh +++ b/scripts/release-pkg.sh @@ -1,12 +1,26 @@ #!/bin/bash set -euo pipefail +if [[ "${1:-}" == "--help" && $# -eq 1 ]]; then + echo "Usage: scripts/release-pkg.sh (signed PKG and appcast; environment in docs/updates.md)" + exit 0 +elif [[ $# -ne 0 ]]; then + echo "잘못된 인수입니다. --help를 확인하세요" >&2 + exit 2 +fi + project_root="$(cd "$(dirname "$0")/.." && pwd)" application_identity="${DEVELOPER_ID_APPLICATION:-}" installer_identity="${DEVELOPER_ID_INSTALLER:-}" notary_profile="${NOTARY_PROFILE:-}" release_scratch="${GEUL_GUARD_RELEASE_PATH:-${TMPDIR:-/tmp}/GeulGuardRelease}" package_path="$project_root/dist/GeulGuard.pkg" +download_url="${GEUL_GUARD_RELEASE_DOWNLOAD_URL:-}" + +if [[ -z "${GEUL_GUARD_UPDATE_FEED_URL:-}" || -z "${GEUL_GUARD_UPDATE_PUBLIC_KEY:-}" || -z "$download_url" ]]; then + echo "GEUL_GUARD_UPDATE_FEED_URL, GEUL_GUARD_UPDATE_PUBLIC_KEY, GEUL_GUARD_RELEASE_DOWNLOAD_URL이 필요합니다" >&2 + exit 2 +fi if [[ -z "$application_identity" || -z "$installer_identity" || -z "$notary_profile" ]]; then echo "DEVELOPER_ID_APPLICATION, DEVELOPER_ID_INSTALLER, NOTARY_PROFILE이 필요합니다" >&2 @@ -48,4 +62,11 @@ xcrun stapler staple "$package_path" xcrun stapler validate "$package_path" spctl --assess --type install --verbose=2 "$package_path" +sign_update="$release_scratch/build/build-x86_64/artifacts/sparkle/Sparkle/bin/sign_update" +signature_path="$release_scratch/update-signature.txt" +"$sign_update" "$package_path" > "$signature_path" +swift "$project_root/scripts/update-metadata.swift" appcast \ + "$app_path/Contents/Info.plist" "$package_path" "$signature_path" \ + "$download_url" "$project_root/dist/appcast.xml" + echo "$package_path" diff --git a/scripts/update-metadata.swift b/scripts/update-metadata.swift new file mode 100644 index 0000000..8d90f4d --- /dev/null +++ b/scripts/update-metadata.swift @@ -0,0 +1,108 @@ +#!/usr/bin/env swift +import CryptoKit +import Foundation + +func fail(_ message: String) -> Never { + FileHandle.standardError.write(Data("\(message)\n".utf8)) + exit(2) +} + +func readPlist(_ path: String) throws -> [String: Any] { + let data = try Data(contentsOf: URL(fileURLWithPath: path)) + guard let plist = try PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] else { + fail("앱 Info.plist를 읽을 수 없습니다") + } + return plist +} + +func validFeed(_ value: String) -> Bool { + guard let url = URLComponents(string: value) else { return false } + return url.scheme == "https" && !(url.host ?? "").isEmpty && url.user == nil && url.password == nil && url.fragment == nil +} + +func xml(_ value: String) -> String { + value.replacingOccurrences(of: "&", with: "&") + .replacingOccurrences(of: "<", with: "<") + .replacingOccurrences(of: ">", with: ">") + .replacingOccurrences(of: "\"", with: """) + .replacingOccurrences(of: "'", with: "'") +} + +let args = Array(CommandLine.arguments.dropFirst()) +if args == ["--help"] { + print(""" + Usage: + swift scripts/update-metadata.swift configure INFO_PLIST + swift scripts/update-metadata.swift appcast INFO_PLIST PKG SIGNATURE_FILE DOWNLOAD_URL OUTPUT_XML + configure reads public GEUL_GUARD_UPDATE_FEED_URL and GEUL_GUARD_UPDATE_PUBLIC_KEY. + appcast validates the sign_update signature against the built app's public key. + No private keys are read, generated or exported by this script. + """) + exit(0) +} + +do { + switch args.first { + case "configure" where args.count == 2: + let environment = ProcessInfo.processInfo.environment + let feed = environment["GEUL_GUARD_UPDATE_FEED_URL"] ?? "" + let key = environment["GEUL_GUARD_UPDATE_PUBLIC_KEY"] ?? "" + guard !feed.isEmpty || !key.isEmpty else { exit(0) } + guard validFeed(feed), let decoded = Data(base64Encoded: key), decoded.count == 32 else { + fail("업데이트 설정에 유효한 HTTPS 피드 주소와 32바이트 Base64 공개키가 필요합니다") + } + var plist = try readPlist(args[1]) + plist["SUFeedURL"] = feed + plist["SUPublicEDKey"] = key + let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) + try data.write(to: URL(fileURLWithPath: args[1]), options: .atomic) + case "appcast" where args.count == 6: + let plist = try readPlist(args[1]) + guard let version = plist["CFBundleVersion"] as? String, + let shortVersion = plist["CFBundleShortVersionString"] as? String, + let minimumOS = plist["LSMinimumSystemVersion"] as? String, + let feed = plist["SUFeedURL"] as? String, validFeed(feed), + let publicKey = plist["SUPublicEDKey"] as? String, + let keyData = Data(base64Encoded: publicKey) else { + fail("빌드된 앱에 버전, 최소 OS 또는 업데이트 설정이 없습니다") + } + let expectedURL = "https://github.com/jureuk7/GeulGuard/releases/download/v\(shortVersion)/GeulGuard.pkg" + guard args[4] == expectedURL else { fail("다운로드 URL은 공식 버전별 GitHub Release PKG 주소여야 합니다: \(expectedURL)") } + let signatureOutput = try String(contentsOfFile: args[3], encoding: .utf8) + let pattern = #"sparkle:edSignature="([A-Za-z0-9+/=]+)""# + let expression = try NSRegularExpression(pattern: pattern) + let range = NSRange(signatureOutput.startIndex..., in: signatureOutput) + guard let match = expression.firstMatch(in: signatureOutput, range: range), + let signatureRange = Range(match.range(at: 1), in: signatureOutput), + let signature = Data(base64Encoded: String(signatureOutput[signatureRange])) else { + fail("sign_update 출력에 EdDSA 서명이 없습니다") + } + let packageData = try Data(contentsOf: URL(fileURLWithPath: args[2]), options: .mappedIfSafe) + let verificationKey = try Curve25519.Signing.PublicKey(rawRepresentation: keyData) + guard verificationKey.isValidSignature(signature, for: packageData) else { + fail("PKG 서명이 앱에 내장된 공개키와 일치하지 않습니다") + } + let appcast = """ + + + + GeulGuard Updates + \(xml(feed)) + 글가드 업데이트 + + GeulGuard \(xml(shortVersion)) + \(xml(version)) + \(xml(shortVersion)) + \(xml(minimumOS)) + + + + + """ + try Data((appcast + "\n").utf8).write(to: URL(fileURLWithPath: args[5]), options: .atomic) + default: + fail("잘못된 인수입니다. --help를 확인하세요") + } +} catch { + fail("업데이트 메타데이터 처리 실패: \(error.localizedDescription)") +} From 80fc7148bba63141af8fd4fca9d2eadf94103a37 Mon Sep 17 00:00:00 2001 From: jureuk7 Date: Tue, 15 Sep 2026 14:13:25 +0900 Subject: [PATCH 2/5] Clarify network use in the security policy --- SECURITY.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index bf57657..cd32b6c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -10,5 +10,6 @@ Issue에 재현 정보를 올리지 마세요. GitHub의 **Report a vulnerabilit ## Privacy boundary -GeulGuard는 네트워크 연결, 키 입력 저장, 접근성 권한을 사용하지 않는 것을 보안 -불변식으로 유지합니다. +GeulGuard는 업데이트 확인·다운로드에만 네트워크를 사용합니다. 키 입력을 저장하거나 +전송하지 않으며, 접근성 권한을 사용하지 않는 것을 보안 불변식으로 유지합니다. +업데이트 확인 설정과 배포 검증 절차는 [업데이트 문서](docs/updates.md)를 참고하세요. From 2a34db0c744e188998c350a3899ff8d41b88544b Mon Sep 17 00:00:00 2001 From: jureuk7 Date: Tue, 15 Sep 2026 19:53:34 +0900 Subject: [PATCH 3/5] Configure production Sparkle feed and public key --- config/updates.env | 2 ++ docs/updates.md | 11 +++++++++++ 2 files changed, 13 insertions(+) create mode 100644 config/updates.env diff --git a/config/updates.env b/config/updates.env new file mode 100644 index 0000000..826d896 --- /dev/null +++ b/config/updates.env @@ -0,0 +1,2 @@ +export GEUL_GUARD_UPDATE_FEED_URL='https://geulguard.jureuk.dev/.well-known/appcast.xml' +export GEUL_GUARD_UPDATE_PUBLIC_KEY='Zmr/aLL+Cd5kcUu19VCz3Y9PMTTHgb61z557JabFQWU=' diff --git a/docs/updates.md b/docs/updates.md index 4979610..0737e81 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -20,6 +20,17 @@ XPC 서비스, Autoupdate, Updater.app, 프레임워크, 앱 순서로 서명한 | `GEUL_GUARD_UPDATE_FEED_URL` | `SUFeedURL`에 기록할 고정 HTTPS appcast 주소 | | `GEUL_GUARD_UPDATE_PUBLIC_KEY` | `SUPublicEDKey`에 기록할 Base64 Ed25519 공개키, 디코딩 후 32바이트 | +공식 배포용 공개 설정은 `config/updates.env`에 보관한다. 저장소 루트에서 +다음 명령을 실행한 같은 터미널에서 빌드·릴리스 스크립트를 실행한다. + +```sh +source config/updates.env +``` + +피드는 `https://geulguard.jureuk.dev/.well-known/appcast.xml`이다. +이 파일에는 공개키와 공개 URL만 포함하며, 개인키·공증 자격 증명은 넣지 않는다. +개발 빌드에 자동 적용하지 않으며 명시적으로 불러온 경우에만 적용한다. + 둘 다 생략하면 업데이트 서버가 설정되지 않은 개발 빌드다. 하나만 지정하거나 유효하지 않은 값을 지정하면 빌드가 실패한다. 피드 URL에는 사용자명·암호를 넣을 수 없다. 비공개 키를 환경변수나 저장소에 넣지 않는다. From f40d161b21069cd4fac81d4432fb6fa0b7a890a6 Mon Sep 17 00:00:00 2001 From: jureuk7 Date: Tue, 15 Sep 2026 20:01:20 +0900 Subject: [PATCH 4/5] Prepare version 0.6.0 for update validation --- CHANGELOG.md | 6 ++++++ Resources/Info.plist | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3455610..98b9b54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to GeulGuard are documented in this file. +## [0.6.0] - Unreleased + +- 앱 시작 시 업데이트를 한 번 확인하며, 설정에서 시작 시 확인을 끌 수 있습니다. +- 메뉴의 ‘업데이트 확인…’으로 새 버전을 확인하고 서명된 PKG 업데이트를 설치할 수 있습니다. +- 업데이트 설치를 위해 앱을 종료하기 전에 ABC 입력 소스와 한글 조합 종료를 확인합니다. + ## [0.5.0] - 2026-09-13 - 연속 자음의 쌍자음 조합을 설정에서 켜거나 끌 수 있습니다. 끄면 `ㄱㄱ`을 `ㄲ`으로 합치지 않고 각각 입력합니다. diff --git a/Resources/Info.plist b/Resources/Info.plist index c3d77f7..e4aa56c 100644 --- a/Resources/Info.plist +++ b/Resources/Info.plist @@ -19,9 +19,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 0.5.0 + 0.6.0 CFBundleVersion - 6 + 7 ComponentInputModeDict tsInputModeListKey From 5278d6c85d30482d6ea293711d1779ff240a1d6d Mon Sep 17 00:00:00 2001 From: Hyunmyeong Joo Date: Tue, 15 Sep 2026 20:58:56 +0900 Subject: [PATCH 5/5] Add optional logout prompt after updates (#7) --- Sources/GeulGuardInput/AppDelegate.swift | 3 + Sources/GeulGuardInput/UpdateController.swift | 18 +++++ .../GeulGuardInput/UpdateLogoutPrompt.swift | 70 +++++++++++++++++++ .../UpdateLogoutPromptTests.swift | 33 +++++++++ docs/updates.md | 14 ++++ 5 files changed, 138 insertions(+) create mode 100644 Sources/GeulGuardInput/UpdateLogoutPrompt.swift create mode 100644 Tests/GeulGuardInputTests/UpdateLogoutPromptTests.swift diff --git a/Sources/GeulGuardInput/AppDelegate.swift b/Sources/GeulGuardInput/AppDelegate.swift index d4b3811..30aace7 100644 --- a/Sources/GeulGuardInput/AppDelegate.swift +++ b/Sources/GeulGuardInput/AppDelegate.swift @@ -10,6 +10,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation { func applicationDidFinishLaunching(_ notification: Notification) { _ = updates configureStatusItem() + Task { @MainActor in + updates.presentPostUpdateLogoutIfNeeded() + } if ProcessInfo.processInfo.arguments.contains("--settings") { showSettings() } diff --git a/Sources/GeulGuardInput/UpdateController.swift b/Sources/GeulGuardInput/UpdateController.swift index 6692761..e151bca 100644 --- a/Sources/GeulGuardInput/UpdateController.swift +++ b/Sources/GeulGuardInput/UpdateController.swift @@ -34,12 +34,18 @@ final class UpdateController: NSObject, ObservableObject, SPUUpdaterDelegate { @Published private(set) var canCheckForUpdates = false @Published private(set) var checksOnLaunch = GeulGuardPreferences.checksForUpdatesOnLaunch @Published private(set) var status = "이 빌드에서는 업데이트를 사용할 수 없습니다." + private let logoutPrompt = UpdateLogoutPrompt() + private var shouldOfferLogout = false + private var installingVersion: String? private var controller: SPUStandardUpdaterController? private var observations: [NSKeyValueObservation] = [] private(set) var isInstallingUpdate = false override init() { super.init() + if let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String { + shouldOfferLogout = logoutPrompt.consumeInstalledUpdate(currentVersion: version) + } guard UpdateConfiguration.isValid(Bundle.main.infoDictionary ?? [:]) else { return } let controller = SPUStandardUpdaterController(startingUpdater: false, updaterDelegate: self, userDriverDelegate: nil) self.controller = controller @@ -64,6 +70,12 @@ final class UpdateController: NSObject, ObservableObject, SPUUpdaterDelegate { } } + func presentPostUpdateLogoutIfNeeded() { + guard shouldOfferLogout else { return } + shouldOfferLogout = false + logoutPrompt.present() + } + private func refreshState() { canCheckForUpdates = controller?.updater.canCheckForUpdates ?? false } @@ -91,11 +103,13 @@ final class UpdateController: NSObject, ObservableObject, SPUUpdaterDelegate { func allowedSystemProfileKeys(for updater: SPUUpdater) -> [String]? { [] } func updater(_ updater: SPUUpdater, willInstallUpdate item: SUAppcastItem) { + installingVersion = item.versionString isInstallingUpdate = true } func updater(_ updater: SPUUpdater, willInstallUpdateOnQuit item: SUAppcastItem, immediateInstallationBlock immediateInstallHandler: @escaping () -> Void) -> Bool { + installingVersion = item.versionString isInstallingUpdate = true return false } @@ -103,12 +117,15 @@ final class UpdateController: NSObject, ObservableObject, SPUUpdaterDelegate { func updater(_ updater: SPUUpdater, userDidMake choice: SPUUserUpdateChoice, forUpdate updateItem: SUAppcastItem, state: SPUUserUpdateState) { if state.stage == .installing { + installingVersion = updateItem.versionString isInstallingUpdate = true } } func updater(_ updater: SPUUpdater, didAbortWithError error: Error) { isInstallingUpdate = false + installingVersion = nil + logoutPrompt.cancelInstallation() } func confirmTermination() -> NSApplication.TerminateReply { @@ -130,6 +147,7 @@ final class UpdateController: NSObject, ObservableObject, SPUUpdaterDelegate { blocked.runModal() return .terminateCancel } + if let installingVersion { logoutPrompt.recordInstallation(version: installingVersion) } return .terminateNow } diff --git a/Sources/GeulGuardInput/UpdateLogoutPrompt.swift b/Sources/GeulGuardInput/UpdateLogoutPrompt.swift new file mode 100644 index 0000000..9a721a7 --- /dev/null +++ b/Sources/GeulGuardInput/UpdateLogoutPrompt.swift @@ -0,0 +1,70 @@ +import AppKit +import Carbon + +@MainActor +final class UpdateLogoutPrompt { + private static let pendingVersionKey = "updatePendingLogoutVersion" + private let defaults: UserDefaults + private let requestLogout: @MainActor () throws -> Void + + init(defaults: UserDefaults = .standard, + requestLogout: @escaping @MainActor () throws -> Void = UpdateLogoutPrompt.requestSystemLogout) { + self.defaults = defaults + self.requestLogout = requestLogout + } + + func recordInstallation(version: String) { + defaults.set(version, forKey: Self.pendingVersionKey) + } + + func cancelInstallation() { + defaults.removeObject(forKey: Self.pendingVersionKey) + } + + func consumeInstalledUpdate(currentVersion: String) -> Bool { + guard let expected = defaults.string(forKey: Self.pendingVersionKey) else { return false } + cancelInstallation() + return expected == currentVersion + } + + func present() { + NSApp.activate(ignoringOtherApps: true) + handleChoice(Self.makeAlert().runModal()) + } + + static func makeAlert() -> NSAlert { + let alert = NSAlert() + alert.messageText = "글가드 업데이트가 설치되었습니다" + alert.informativeText = "새 버전이 바로 적용되지 않았다면 로그아웃한 뒤 다시 로그인해 주세요. 지금 로그아웃하려면 다른 앱에서 작업 중인 내용을 먼저 저장하세요." + alert.addButton(withTitle: "나중에") + alert.addButton(withTitle: "지금 로그아웃") + alert.buttons[0].keyEquivalent = "\r" + alert.buttons[1].keyEquivalent = "" + return alert + } + + func handleChoice(_ choice: NSApplication.ModalResponse) { + guard choice == .alertSecondButtonReturn else { return } + do { + try requestLogout() + } catch { + let alert = NSAlert() + alert.messageText = "로그아웃을 요청하지 못했습니다" + alert.informativeText = "작업을 저장한 뒤 Apple 메뉴에서 로그아웃을 선택해 주세요." + alert.addButton(withTitle: "확인") + alert.runModal() + } + } + + static func logoutEvent() -> NSAppleEventDescriptor { + NSAppleEventDescriptor(eventClass: AEEventClass(kCoreEventClass), + eventID: AEEventID(kAELogOut), + targetDescriptor: NSAppleEventDescriptor(bundleIdentifier: "com.apple.loginwindow"), + returnID: AEReturnID(kAutoGenerateReturnID), + transactionID: AETransactionID(kAnyTransactionID)) + } + + private static func requestSystemLogout() throws { + _ = try logoutEvent().sendEvent(options: [.noReply, .canInteract], timeout: 10) + } +} diff --git a/Tests/GeulGuardInputTests/UpdateLogoutPromptTests.swift b/Tests/GeulGuardInputTests/UpdateLogoutPromptTests.swift new file mode 100644 index 0000000..e527488 --- /dev/null +++ b/Tests/GeulGuardInputTests/UpdateLogoutPromptTests.swift @@ -0,0 +1,33 @@ +import XCTest +import Carbon +@testable import GeulGuardInput + +@MainActor +final class UpdateLogoutPromptTests: XCTestCase { + func testPromptRequiresMatchingInstalledVersionAndIsConsumedOnce() { + let name = "GeulGuard.LogoutTest.\(UUID().uuidString)" + let defaults = UserDefaults(suiteName: name)! + defer { defaults.removePersistentDomain(forName: name) } + let prompt = UpdateLogoutPrompt(defaults: defaults, requestLogout: {}) + XCTAssertFalse(prompt.consumeInstalledUpdate(currentVersion: "7")) + prompt.recordInstallation(version: "8") + XCTAssertFalse(prompt.consumeInstalledUpdate(currentVersion: "7")) + prompt.recordInstallation(version: "8") + XCTAssertTrue(prompt.consumeInstalledUpdate(currentVersion: "8")) + XCTAssertFalse(prompt.consumeInstalledUpdate(currentVersion: "8")) + prompt.recordInstallation(version: "9") + prompt.cancelInstallation() + XCTAssertFalse(prompt.consumeInstalledUpdate(currentVersion: "9")) + } + + func testOnlyExplicitLogoutChoiceRequestsLogout() { + var requests = 0 + let prompt = UpdateLogoutPrompt(requestLogout: { requests += 1 }) + prompt.handleChoice(.alertFirstButtonReturn) + prompt.handleChoice(.abort) + XCTAssertEqual(requests, 0) + prompt.handleChoice(.alertSecondButtonReturn) + XCTAssertEqual(requests, 1) + XCTAssertEqual(UpdateLogoutPrompt.logoutEvent().eventID, AEEventID(kAELogOut)) + } +} diff --git a/docs/updates.md b/docs/updates.md index 0737e81..580cbbd 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -129,3 +129,17 @@ appcast는 빌드된 앱의 버전·최소 macOS, 최종 PKG의 크기·EdDSA 실제 입력 앱에서의 재활성화. 공개 피드·Sparkle 배포 키를 준비하고 실제 구버전→신버전으로 검증한 뒤 배포해야 한다. 현재 작업은 사용자 입력 소스나 Karabiner 설정을 변경하지 않았으며 배포 PKG 설치·공개 게시를 수행하지 않았다. + +## 업데이트 후 로그아웃 안내 + +이 기능이 포함된 버전에서 Sparkle 설치를 진행하면 대상 빌드 번호를 기록한다. +재실행한 앱의 빌드가 대상과 일치할 때 ‘나중에’와 ‘지금 로그아웃’ 안내를 한 번 +표시한다. ‘나중에’가 기본 선택이며, 새 버전이 바로 적용되었다면 로그아웃하지 +않고 사용할 수 있다. ‘지금 로그아웃’은 작업 저장을 안내한 뒤 macOS의 일반 +로그아웃 확인 절차를 요청한다. 강제 종료하거나 즉시 세션을 종료하지 않는다. +요청이 실패하면 Apple 메뉴를 통한 수동 로그아웃을 안내한다. + +설치 취소·실패 또는 대상 빌드와 다른 앱 실행에서는 설치 완료 안내를 표시하지 +않는다. 이전 버전에는 설치 대상 기록 기능이 없으므로, 이 기능을 처음 설치하는 +업데이트에서는 안내가 나오지 않을 수 있다. PKG를 직접 설치한 경우에도 별도 +안내를 표시하지 않는다. 안내를 미뤘다면 필요할 때 Apple 메뉴에서 로그아웃한다.