forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDesktopDeveloperSecretStore.swift
More file actions
190 lines (173 loc) · 5.76 KB
/
Copy pathDesktopDeveloperSecretStore.swift
File metadata and controls
190 lines (173 loc) · 5.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import Foundation
import OmiSupport
/// File-backed secret store for non-production desktop bundles.
///
/// Production-family apps keep using the login keychain. Developer bundles (Omi Dev,
/// named `omi-*` apps, ad-hoc / Apple Development local builds) persist the same
/// service/account strings in a JSON file so rebuilds never prompt SecurityAgent.
///
/// Layout:
/// `~/Library/Application Support/<DesktopLocalProfile.storageDirectoryName>/developer-secrets/<bundle-id>.json`.
/// Omi Dev shares the `Omi` Application Support root with stable, so the file is keyed
/// by bundle id. Keys are `service + NUL + account` (`"\u{0}"`).
final class DesktopDeveloperSecretStore: @unchecked Sendable {
static let shared = DesktopDeveloperSecretStore()
static let directoryName = "developer-secrets"
static let keySeparator = "\u{0}"
private let lock = NSLock()
private let fileManager: FileManager
private let rootDirectoryOverride: URL?
private let bundleIdentifierOverride: String?
private var cache: [String: String]?
private var didLogUnreadableFile = false
init(
rootDirectory: URL? = nil,
bundleIdentifier: String? = nil,
fileManager: FileManager = .default
) {
self.rootDirectoryOverride = rootDirectory
self.bundleIdentifierOverride = bundleIdentifier
self.fileManager = fileManager
}
static func storageKey(service: String, account: String) -> String {
"\(service)\(keySeparator)\(account)"
}
static func fileURL(rootDirectory: URL, bundleIdentifier: String) -> URL {
rootDirectory
.appendingPathComponent(directoryName, isDirectory: true)
.appendingPathComponent("\(bundleIdentifier).json", isDirectory: false)
}
func readString(service: String, account: String) -> String? {
lock.lock()
defer { lock.unlock() }
let values = loadLocked()
let key = Self.storageKey(service: service, account: account)
guard let value = values[key], !value.isEmpty else {
return nil
}
return value
}
@discardableResult
func setString(_ value: String, service: String, account: String) -> Bool {
lock.lock()
defer { lock.unlock() }
var values = loadLocked()
values[Self.storageKey(service: service, account: account)] = value
guard persistLocked(values) else {
return false
}
cache = values
return true
}
func delete(service: String, account: String) {
lock.lock()
defer { lock.unlock() }
var values = loadLocked()
let key = Self.storageKey(service: service, account: account)
guard values.removeValue(forKey: key) != nil else {
return
}
if persistLocked(values) {
cache = values
}
}
func secretsDirectoryURL() -> URL {
fileURL().deletingLastPathComponent()
}
func fileURL() -> URL {
Self.fileURL(rootDirectory: rootDirectory(), bundleIdentifier: resolvedBundleIdentifier())
}
private func rootDirectory() -> URL {
rootDirectoryOverride ?? DesktopLocalProfile.applicationSupportURL()
}
private func resolvedBundleIdentifier() -> String {
if let bundleIdentifierOverride, !bundleIdentifierOverride.isEmpty {
return bundleIdentifierOverride
}
if let bundleIdentifier = Bundle.main.bundleIdentifier, !bundleIdentifier.isEmpty {
return bundleIdentifier
}
return "unknown.bundle"
}
private func loadLocked() -> [String: String] {
if let cache {
return cache
}
let loaded = readFileLocked()
cache = loaded
return loaded
}
private func readFileLocked() -> [String: String] {
let url = fileURL()
guard fileManager.fileExists(atPath: url.path) else {
return [:]
}
do {
let data = try Data(contentsOf: url)
guard !data.isEmpty else {
return [:]
}
let object = try JSONSerialization.jsonObject(with: data)
guard let dictionary = object as? [String: Any] else {
logUnreadableFileLocked(url)
return [:]
}
var values: [String: String] = [:]
for (key, value) in dictionary {
if let string = value as? String {
values[key] = string
}
}
return values
} catch {
logUnreadableFileLocked(url)
return [:]
}
}
private func logUnreadableFileLocked(_ url: URL) {
guard !didLogUnreadableFile else { return }
didLogUnreadableFile = true
log("DesktopDeveloperSecretStore: ignoring unreadable secrets file at \(url.path)")
}
private func persistLocked(_ values: [String: String]) -> Bool {
let url = fileURL()
let directory = url.deletingLastPathComponent()
do {
try fileManager.createDirectory(at: directory, withIntermediateDirectories: true)
try fileManager.setAttributes(
[.posixPermissions: 0o700],
ofItemAtPath: directory.path
)
let data = try JSONSerialization.data(
withJSONObject: values,
options: [.prettyPrinted, .sortedKeys]
)
let tempURL = directory.appendingPathComponent(
".\(url.lastPathComponent).\(UUID().uuidString)",
isDirectory: false
)
let created = fileManager.createFile(
atPath: tempURL.path,
contents: data,
attributes: [.posixPermissions: 0o600]
)
guard created else {
log("DesktopDeveloperSecretStore: failed to create temp secrets file at \(tempURL.path)")
return false
}
if fileManager.fileExists(atPath: url.path) {
_ = try fileManager.replaceItemAt(url, withItemAt: tempURL)
} else {
try fileManager.moveItem(at: tempURL, to: url)
}
try fileManager.setAttributes(
[.posixPermissions: 0o600],
ofItemAtPath: url.path
)
return true
} catch {
log("DesktopDeveloperSecretStore: failed to persist secrets file (\(error.localizedDescription))")
return false
}
}
}