forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRuntimeOwnerIdentity.swift
More file actions
648 lines (600 loc) · 25.8 KB
/
Copy pathRuntimeOwnerIdentity.swift
File metadata and controls
648 lines (600 loc) · 25.8 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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
import Foundation
private struct RuntimeOwnerDefaultsReference: @unchecked Sendable {
let value: UserDefaults
}
/// Immutable authority captured by delayed owner-bound work. Owner identity
/// alone is insufficient because signing out and back into the same uid must
/// still revoke continuations from the previous authenticated session.
struct RuntimeOwnerAuthorizationSnapshot: Equatable, Sendable {
let ownerID: String
fileprivate let generation: UInt64
fileprivate let authorityNonce: UUID
/// Session generation captured with the owner. A fresh snapshot after a
/// same-owner sign-out/sign-in must not authorize work carrying the prior
/// session's provenance.
var authorizationGeneration: UInt64 { generation }
/// Per-process authority identity. Generation counters restart at zero in a
/// new process, so durable native notification payloads must carry this
/// nonce before they can be compared with a fresh snapshot.
var authorizationNonce: UUID { authorityNonce }
}
final class RuntimeOwnerAuthorizationAuthority: @unchecked Sendable {
static let shared = RuntimeOwnerAuthorizationAuthority()
private let authorityNonce = UUID()
private let lock = NSLock()
private var generation: UInt64 = 0
private var ownerID: String?
private var revoked = false
private var bootstrapped = false
func beginTransition() {
lock.withLock {
generation &+= 1
ownerID = nil
revoked = true
}
}
func endTransition(ownerID: String?) {
let normalized = Self.normalize(ownerID)
lock.withLock {
self.ownerID = normalized
revoked = false
bootstrapped = true
}
}
func capture(ownerID: String?, expectedOwnerID: String?) -> RuntimeOwnerAuthorizationSnapshot? {
let normalized = Self.normalize(ownerID)
let normalizedExpectedOwnerID = Self.normalize(expectedOwnerID)
return lock.withLock {
if !bootstrapped {
guard let normalized, !revoked else { return nil }
// Durable auth may predate construction of this in-memory authority.
// This is the only path allowed to adopt an owner without a transition.
self.ownerID = normalized
bootstrapped = true
} else if self.ownerID != normalized {
revokeUnexpectedOwnerMismatch()
return nil
}
guard let normalized, !revoked else { return nil }
if expectedOwnerID != nil, normalizedExpectedOwnerID != normalized { return nil }
return RuntimeOwnerAuthorizationSnapshot(
ownerID: normalized, generation: generation, authorityNonce: authorityNonce)
}
}
func isCurrent(
_ snapshot: RuntimeOwnerAuthorizationSnapshot,
ownerID: String?
) -> Bool {
let normalized = Self.normalize(ownerID)
return lock.withLock {
guard bootstrapped else { return false }
guard self.ownerID == normalized else {
revokeUnexpectedOwnerMismatch()
return false
}
return !revoked
&& normalized == snapshot.ownerID
&& generation == snapshot.generation
&& authorityNonce == snapshot.authorityNonce
}
}
/// Durable auth changed without crossing the exclusive transition boundary.
/// Advance and revoke once, then stay fail-closed until a legitimate
/// beginTransition/endTransition pair establishes the next generation.
private func revokeUnexpectedOwnerMismatch() {
if !revoked { generation &+= 1 }
ownerID = nil
revoked = true
}
private static func normalize(_ ownerID: String?) -> String? {
guard let ownerID else { return nil }
let normalized = ownerID.trimmingCharacters(in: .whitespacesAndNewlines)
return normalized.isEmpty ? nil : normalized
}
}
/// Unforgeable authority for the one cleanup phase that precedes an effective
/// owner mutation. It can terminalize work for exactly the captured previous
/// owner and exactly one transition generation; it cannot authorize new work.
struct RuntimeOwnerTransitionCleanupCapability: Equatable, Sendable {
let previousOwnerID: String?
fileprivate let generation: UInt64
fileprivate let nonce: UUID
fileprivate init(previousOwnerID: String?, generation: UInt64, nonce: UUID) {
self.previousOwnerID = previousOwnerID
self.generation = generation
self.nonce = nonce
}
}
private final class RuntimeOwnerTransitionCleanupAuthority: @unchecked Sendable {
static let shared = RuntimeOwnerTransitionCleanupAuthority()
private let lock = NSLock()
private var generation: UInt64 = 0
private var activeCapability: RuntimeOwnerTransitionCleanupCapability?
func begin(previousOwnerID: String?) -> RuntimeOwnerTransitionCleanupCapability {
lock.withLock {
precondition(activeCapability == nil, "Effective-owner cleanup capability overlapped")
generation &+= 1
let capability = RuntimeOwnerTransitionCleanupCapability(
previousOwnerID: previousOwnerID,
generation: generation,
nonce: UUID())
activeCapability = capability
return capability
}
}
func end(_ capability: RuntimeOwnerTransitionCleanupCapability) {
lock.withLock {
guard activeCapability == capability else {
assertionFailure("Effective-owner cleanup capability generation mismatched")
return
}
activeCapability = nil
}
}
func activeCapability(forPreviousOwnerID ownerID: String) -> RuntimeOwnerTransitionCleanupCapability? {
lock.withLock {
guard let activeCapability, activeCapability.previousOwnerID == ownerID else { return nil }
return activeCapability
}
}
func authorizes(
_ capability: RuntimeOwnerTransitionCleanupCapability,
previousOwnerID: String?
) -> Bool {
lock.withLock {
activeCapability == capability && capability.previousOwnerID == previousOwnerID
}
}
}
private final class RuntimeOwnerTransitionCleanupCapabilitySlot: @unchecked Sendable {
private let lock = NSLock()
private var capability: RuntimeOwnerTransitionCleanupCapability?
func store(_ capability: RuntimeOwnerTransitionCleanupCapability) {
lock.withLock { self.capability = capability }
}
func load() -> RuntimeOwnerTransitionCleanupCapability? {
lock.withLock { capability }
}
func take() -> RuntimeOwnerTransitionCleanupCapability? {
lock.withLock {
defer { capability = nil }
return capability
}
}
}
private final class EffectiveOwnerAuthorizationRevocation: @unchecked Sendable {
static let shared = EffectiveOwnerAuthorizationRevocation()
private let lock = NSLock()
private var active = false
func begin() { lock.withLock { active = true } }
func end() { lock.withLock { active = false } }
var isActive: Bool { lock.withLock { active } }
}
extension Notification.Name {
/// Effective owner changed (sign-in, sign-out, account switch, or an
/// automation override). Carries no owner id or other user content.
///
/// **Post it on the main thread.** `performEffectiveOwnerTransition` does
/// (`await MainActor.run`), and observers depend on both halves of that:
/// `NotificationCenter` delivers synchronously on the posting thread, which is
/// what lets a surface fence itself *during* the transition rather than a
/// runloop later — see `IntegrationNudgeCoordinator`. Most observers are
/// `@MainActor` types whose sink closure carries an isolation check on entry,
/// so a post from a background thread fails `dispatch_assert_queue` and traps,
/// taking the whole process rather than one observer. Nothing inside the
/// closure can guard against that: the check runs before its first statement,
/// and hopping upstream would trade the crash for losing the synchronous
/// fence. The poster is the only place that can be both correct and prompt.
static let runtimeOwnerDidChange = Notification.Name("com.omi.desktop.runtimeOwnerDidChange")
}
/// Resolves the owner id used by kernel / continuity surfaces.
///
/// Non-production automation may temporarily override the owner for isolation
/// tests without rewriting Firebase `auth_userId`. Writing a synthetic uid into
/// `auth_userId` makes `AuthService.getIdToken()` treat real tokens as stale and
/// call `clearTokens()`, leaving a ghost signed-in session.
enum RuntimeOwnerIdentity {
static var effectiveOwnerTransitionInProgress: Bool {
EffectiveOwnerAuthorizationRevocation.shared.isActive
}
/// Test-only seam over the process-global revocation behind
/// `effectiveOwnerTransitionInProgress`.
///
/// Deliberately scoped rather than exposing `begin()`/`end()`: an active revocation makes
/// `currentOwnerId` return nil for *every* caller in the process, and the revocation lives
/// on a `private` singleton no suite can clear. A test that leaked it would strand every
/// later suite in the same binary with no way to recover — the #12039 failure shape. The
/// `defer` makes that leak unrepresentable.
/// `@MainActor` rather than isolation-generic: every caller is a `@MainActor` XCTestCase,
/// and `#isolation` appears nowhere else in this codebase — not a construct to introduce
/// for a test seam.
@MainActor
static func withEffectiveOwnerTransitionForTests<T>(
_ body: @MainActor () async throws -> T
) async rethrows -> T {
// Restore the entry state rather than ending unconditionally. The revocation is a
// shared boolean, not a counter, so a bare `end()` in `defer` would clear a
// revocation this scope never started: an outer scope's, or — worse — a leak
// inherited from an earlier suite, which is the exact condition `setUp` exists to
// report. Swallowing that leak here would hide the bug this seam was built to find.
let wasRevokedOnEntry = EffectiveOwnerAuthorizationRevocation.shared.isActive
EffectiveOwnerAuthorizationRevocation.shared.begin()
defer {
if !wasRevokedOnEntry {
EffectiveOwnerAuthorizationRevocation.shared.end()
}
}
return try await body()
}
/// Clears a revocation that leaked from elsewhere in the test process, so one suite's
/// abandoned owner transition cannot silently fail every suite that runs after it.
static func resetEffectiveOwnerTransitionForTests() {
EffectiveOwnerAuthorizationRevocation.shared.end()
}
/// Returns the cleanup-only capability for an already-running physical or
/// kernel effect owned by `ownerID`. New work must never consult this seam.
static func transitionCleanupCapability(
forPreviousOwnerID ownerID: String
) -> RuntimeOwnerTransitionCleanupCapability? {
RuntimeOwnerTransitionCleanupAuthority.shared.activeCapability(
forPreviousOwnerID: ownerID)
}
static func authorizesTransitionCleanup(
_ capability: RuntimeOwnerTransitionCleanupCapability,
previousOwnerID: String?
) -> Bool {
RuntimeOwnerTransitionCleanupAuthority.shared.authorizes(
capability,
previousOwnerID: previousOwnerID)
}
/// Central production boundary for every mutation that can change the
/// effective runtime owner. The notification is delivered on MainActor while
/// the exclusive transition reservation is still held, so owner-derived
/// caches purge before work for the new owner can acquire a commit lease.
static func performEffectiveOwnerTransition<T: Sendable>(
defaults: UserDefaults = .standard,
allowAutomationOverride: Bool = AppBuild.isNonProduction,
plannedNextOwner:
@escaping @Sendable (
_ defaults: UserDefaults, _ previousOwner: String?
) -> String?,
quiesceVoice:
@escaping @Sendable (
_ previousOwner: String?, _ cleanupCapability: RuntimeOwnerTransitionCleanupCapability
) async -> Void = { previousOwner, cleanupCapability in
await PushToTalkManager.shared.quiesceForEffectiveOwnerTransition(
previousOwnerID: previousOwner,
cleanupCapability: cleanupCapability)
},
revokeKernelOwner: (
@Sendable (
_ previousOwner: String, _ cleanupCapability: RuntimeOwnerTransitionCleanupCapability
) async -> Void
)? = nil,
retargetLocalStorage:
@escaping @Sendable (
_ previousOwner: String?, _ nextOwner: String?
) async -> Void = { previousOwner, nextOwner in
await RuntimeOwnerIdentity.retargetOwnerBoundLocalStorage(
previousOwner: previousOwner,
nextOwner: nextOwner)
},
prepareLocalStorageTransition:
@escaping @Sendable (
_ previousOwner: String?, _ plannedNextOwner: String?
) async throws -> Void = { _, _ in
RewindIndexer.shared.suspendForOwnerTransition()
try await RewindStorage.shared.resetForOwnerTransition()
},
ownerDidChange: @escaping @Sendable () async -> Void = {
await MainActor.run {
NotificationCenter.default.post(name: .runtimeOwnerDidChange, object: nil)
}
},
_ transition: @escaping @Sendable (UserDefaults) async throws -> T
) async throws -> T {
let defaultsReference = RuntimeOwnerDefaultsReference(value: defaults)
let cleanupCapabilitySlot = RuntimeOwnerTransitionCleanupCapabilitySlot()
return try await EffectiveOwnerTransitionFence.shared.performEffectiveOwnerTransition(
currentOwner: {
persistedOwnerId(
defaults: defaultsReference.value,
allowAutomationOverride: allowAutomationOverride)
},
plannedNextOwner: { previousOwner in
plannedNextOwner(defaultsReference.value, previousOwner)
},
beginAuthorizationRevocation: { previousOwner in
// Issue the exact previous-owner cleanup capability before public owner
// resolution is revoked. Existing terminalization tasks can capture it
// without ever regaining general owner authority.
cleanupCapabilitySlot.store(
RuntimeOwnerTransitionCleanupAuthority.shared.begin(
previousOwnerID: previousOwner))
RuntimeOwnerAuthorizationAuthority.shared.beginTransition()
EffectiveOwnerAuthorizationRevocation.shared.begin()
},
endAuthorizationRevocation: {
if let cleanupCapability = cleanupCapabilitySlot.take() {
RuntimeOwnerTransitionCleanupAuthority.shared.end(cleanupCapability)
} else {
assertionFailure("Effective-owner cleanup capability was not installed")
}
RuntimeOwnerAuthorizationAuthority.shared.endTransition(
ownerID: persistedOwnerId(
defaults: defaultsReference.value,
allowAutomationOverride: allowAutomationOverride))
EffectiveOwnerAuthorizationRevocation.shared.end()
},
quiescePreviousOwner: { previousOwner, _ in
guard let cleanupCapability = cleanupCapabilitySlot.load(),
RuntimeOwnerTransitionCleanupAuthority.shared.authorizes(
cleanupCapability,
previousOwnerID: previousOwner)
else {
assertionFailure("Effective-owner cleanup capability was revoked before quiescence")
return
}
await quiesceVoice(previousOwner, cleanupCapability)
guard let previousOwner else { return }
if let revokeKernelOwner {
await revokeKernelOwner(previousOwner, cleanupCapability)
} else if defaultsReference.value === UserDefaults.standard {
await AgentRuntimeProcess.shared.revokeOwnerRuntime(
previousOwnerID: previousOwner,
cleanupCapability: cleanupCapability)
}
},
prepareLocalStorageTransition: prepareLocalStorageTransition,
finalizeLocalStorageTransition: {
await RewindIndexer.shared.resumeAfterOwnerTransition()
},
transition: {
try await transition(defaultsReference.value)
},
retargetLocalStorage: retargetLocalStorage,
ownerDidChange: ownerDidChange)
}
/// Capture the current owner plus the authenticated-session generation.
/// Returns nil during a transition or when the expected owner is stale.
nonisolated static func captureAuthorizationSnapshot(
expectedOwnerID: String? = nil
) -> RuntimeOwnerAuthorizationSnapshot? {
RuntimeOwnerAuthorizationAuthority.shared.capture(
ownerID: currentOwnerId(),
expectedOwnerID: expectedOwnerID)
}
/// Revalidate immediately before every delayed mutation and after every await
/// that precedes UI/default/notification publication.
nonisolated static func isAuthorizationCurrent(
_ snapshot: RuntimeOwnerAuthorizationSnapshot
) -> Bool {
RuntimeOwnerAuthorizationAuthority.shared.isCurrent(
snapshot,
ownerID: currentOwnerId())
}
private static func retargetOwnerBoundLocalStorage(
previousOwner: String?,
nextOwner: String?
) async {
guard previousOwner != nextOwner else {
await RewindDatabase.shared.retargetEffectiveOwner(to: nextOwner)
return
}
// These actors retain pools, directories, encoders, or owner-derived
// values. Purge them while the transition reservation is still held so
// automation swaps and every auth path share the same hard boundary.
await AgentVMService.shared.cancelForOwnerTransition()
await AgentSyncService.shared.stop(flushPendingChanges: false)
// Wait for an active file scan to leave its actor before closing the pool
// it captured. New-owner mutations remain parked by the fence.
await FileIndexerService.shared.invalidateCache()
await OCREmbeddingService.shared.reset()
await RewindDatabase.shared.retargetEffectiveOwner(to: nextOwner)
await TranscriptionStorage.shared.invalidateCache()
await MemoryStorage.shared.invalidateCache()
await ActionItemStorage.shared.invalidateCache()
await ProactiveStorage.shared.invalidateCache()
await NoteStorage.shared.invalidateCache()
await AIUserProfileService.shared.invalidateCache()
await StagedTaskStorage.shared.invalidateCache()
await GoalStorage.shared.invalidateCache()
await TaskChatMessageStorage.shared.invalidateCache()
await KnowledgeGraphStorage.shared.invalidateCache()
await MainActor.run {
FloatingBarUsageLimiter.shared.reset()
}
}
/// Active kernel owner: automation override (non-prod) or real auth uid.
/// Returns nil during the exclusive A→B transition so neither account can
/// authorize work before physical resources and owner projections are clear.
///
/// - Parameter allowAutomationOverride: Defaults to `AppBuild.isNonProduction`.
/// Tests inject `true` so hermetic suites do not depend on the XCTest host
/// bundle id.
static func currentOwnerId(
defaults: UserDefaults = .standard,
allowAutomationOverride: Bool = AppBuild.isNonProduction
) -> String? {
guard !effectiveOwnerTransitionInProgress else { return nil }
return persistedOwnerId(
defaults: defaults,
allowAutomationOverride: allowAutomationOverride)
}
private static func persistedOwnerId(
defaults: UserDefaults,
allowAutomationOverride: Bool
) -> String? {
if allowAutomationOverride,
let override = defaults.string(forKey: .automationOwnerOverride)?
.trimmingCharacters(in: .whitespacesAndNewlines),
!override.isEmpty
{
return override
}
guard
let value = defaults.string(forKey: .authUserId)?
.trimmingCharacters(in: .whitespacesAndNewlines),
!value.isEmpty
else {
return nil
}
return value
}
/// Apply a synthetic owner for automation without mutating Firebase credentials.
@discardableResult
static func applyAutomationOwnerOverride(
_ ownerBId: String,
defaults: UserDefaults = .standard
) async -> String? {
let trimmed = ownerBId.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return nil }
do {
return try await performEffectiveOwnerTransition(
defaults: defaults,
allowAutomationOverride: true,
plannedNextOwner: { _, _ in trimmed }
) { defaults in
let ownerA = defaults.string(forKey: .authUserId)?
.trimmingCharacters(in: .whitespacesAndNewlines)
defaults.set(trimmed, forKey: .automationOwnerOverride)
// Preserve an existing backup (nested/re-entrant swap). Only seed when absent
// so a second override cannot replace the real Firebase uid with owner B.
let existingBackup = defaults.string(forKey: .automationOwnerABackup)?
.trimmingCharacters(in: .whitespacesAndNewlines)
if existingBackup == nil || existingBackup?.isEmpty == true,
let ownerA, !ownerA.isEmpty, ownerA != trimmed
{
defaults.set(ownerA, forKey: .automationOwnerABackup)
}
return ownerA
}
} catch {
logError("RuntimeOwnerIdentity: Could not prepare local storage for automation owner", error: error)
return nil
}
}
/// Installs an automation owner only if the owner is still absent after this
/// request has acquired the serialized effective-owner transition fence.
/// A preflight outside that fence could otherwise overwrite a real owner
/// that signed in while a reset was queued.
static func applyAutomationOwnerOverrideIfMissing(
_ ownerID: String,
defaults: UserDefaults = .standard
) async -> Bool {
let trimmed = ownerID.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return false }
do {
return try await performEffectiveOwnerTransition(
defaults: defaults,
allowAutomationOverride: true,
plannedNextOwner: { _, previousOwner in previousOwner ?? trimmed }
) { defaults in
guard persistedOwnerId(defaults: defaults, allowAutomationOverride: true) == nil else {
return false
}
defaults.set(trimmed, forKey: .automationOwnerOverride)
return true
}
} catch {
logError("RuntimeOwnerIdentity: Could not prepare local storage for temporary owner", error: error)
return false
}
}
/// Temporarily establishes a non-production owner only when no effective
/// owner exists. Harness reset operations still execute through the normal
/// owner-scoped kernel boundary; they do not bypass it because a faulted
/// auth endpoint left the bundle in auth recovery.
static func withAutomationOwnerIfMissing<Result: Sendable>(
_ ownerID: String,
defaults: UserDefaults = .standard,
operation: @MainActor () async throws -> Result
) async rethrows -> Result {
let normalizedOwnerID = ownerID.trimmingCharacters(in: .whitespacesAndNewlines)
precondition(!normalizedOwnerID.isEmpty, "automation owner must not be empty")
let installedTemporaryOwner = await applyAutomationOwnerOverrideIfMissing(
normalizedOwnerID,
defaults: defaults)
do {
let result = try await operation()
if installedTemporaryOwner {
_ = await clearAutomationOwnerOverride(defaults: defaults)
}
return result
} catch {
if installedTemporaryOwner {
_ = await clearAutomationOwnerOverride(defaults: defaults)
}
throw error
}
}
/// Clear the automation override and heal a legacy synthetic auth_userId if needed.
@discardableResult
static func clearAutomationOwnerOverride(
defaults: UserDefaults = .standard
) async -> (restored: Bool, ownerId: String?) {
do {
return try await performEffectiveOwnerTransition(
defaults: defaults,
allowAutomationOverride: true,
plannedNextOwner: { defaults, previousOwner in
plannedOwnerAfterClearingAutomationOverride(
defaults: defaults,
previousOwner: previousOwner)
}
) { defaults in
let override = defaults.string(forKey: .automationOwnerOverride)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let hadOverride = !(override?.isEmpty ?? true)
let backup = defaults.string(forKey: .automationOwnerABackup)?
.trimmingCharacters(in: .whitespacesAndNewlines)
defaults.removeObject(forKey: .automationOwnerOverride)
if let backup, !backup.isEmpty {
let currentAuthUserId = defaults.string(forKey: .authUserId)?
.trimmingCharacters(in: .whitespacesAndNewlines)
// Only rewrite auth_userId when it still looks like a synthetic overwrite
// (empty, equals the override we cleared, or legacy backup-only heal).
// Never clobber a legitimately updated auth uid from a mid-session sign-in.
let shouldHealAuthUserId =
currentAuthUserId == nil
|| currentAuthUserId?.isEmpty == true
|| (hadOverride && currentAuthUserId == override)
|| (!hadOverride && currentAuthUserId != backup)
if shouldHealAuthUserId {
defaults.set(backup, forKey: .authUserId)
}
defaults.removeObject(forKey: .automationOwnerABackup)
return (true, defaults.string(forKey: .authUserId) ?? backup)
}
if hadOverride {
return (true, defaults.string(forKey: .authUserId))
}
return (false, nil)
}
} catch {
logError("RuntimeOwnerIdentity: Could not prepare local storage while clearing automation owner", error: error)
return (false, currentOwnerId(defaults: defaults, allowAutomationOverride: true))
}
}
private static func plannedOwnerAfterClearingAutomationOverride(
defaults: UserDefaults,
previousOwner: String?
) -> String? {
let override = defaults.string(forKey: .automationOwnerOverride)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let hadOverride = !(override?.isEmpty ?? true)
let backup = defaults.string(forKey: .automationOwnerABackup)?
.trimmingCharacters(in: .whitespacesAndNewlines)
let currentAuthUserId = defaults.string(forKey: .authUserId)?
.trimmingCharacters(in: .whitespacesAndNewlines)
if let backup, !backup.isEmpty {
let shouldHealAuthUserId =
currentAuthUserId == nil
|| currentAuthUserId?.isEmpty == true
|| (hadOverride && currentAuthUserId == override)
|| (!hadOverride && currentAuthUserId != backup)
return shouldHealAuthUserId ? backup : currentAuthUserId
}
return hadOverride ? currentAuthUserId : previousOwner
}
}