Skip to content

Commit 21a271b

Browse files
nan-licursoragent
andcommitted
feat: [PR4] identity model JWT, the JWT repo, and the public API
The surface an app talks to under Identity Verification: it hands the SDK a token for a user, and the SDK tells it when that token stopped being accepted. OSUserJwtRepo holds the token per external ID and remembers who has already been asked for one, so an app is asked once per user rather than once per rejected request. A listener registered after start or login still hears about an ask that already fired, since the alternative is an app that never learns it owes a token for the user it just logged in. Removes the beta JWT surface this replaces: requiresUserAuth, which nothing ever read, along with onJwtExpired and its handler typealiases. Anyone on the beta JWT API moves to addUserJwtInvalidatedListener and updateUserJwt. storeJwt lands here in the form the public API needs; the later PR that introduces the queues extends it to release the work held for want of a token. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent f3edc79 commit 21a271b

17 files changed

Lines changed: 1273 additions & 37 deletions

‎iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj‎

Lines changed: 32 additions & 0 deletions
Large diffs are not rendered by default.

‎iOS_SDK/OneSignalSDK/OneSignalOSCoreMocks/OSCoreMocks.swift‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,16 @@ public class OSCoreMocks: NSObject {
3434
public static func resetOperationRepo() {
3535
OSOperationRepo.sharedInstance.reset()
3636
}
37+
38+
/// Puts the shared JWT config back to unhydrated.
39+
public static func resetSharedJwtConfig() {
40+
OSUserJwtConfig.shared.resetRequirementToUnknownForTests()
41+
}
42+
43+
/// Hydrates the shared JWT config. Non-IV tests hydrate `false` so the Operation Repo will flush.
44+
public static func hydrateSharedJwtConfig(requiresUserAuth: Bool) {
45+
OSUserJwtConfig.shared.hydrate(requiresUserAuth: requiresUserAuth)
46+
}
3747
}
3848

3949
extension OSOperationRepo {

‎iOS_SDK/OneSignalSDK/OneSignalUser/Source/OSIdentityModel.swift‎

Lines changed: 65 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -38,12 +38,55 @@ class OSIdentityModel: OSModel {
3838
return internalGetAlias(OS_EXTERNAL_ID)
3939
}
4040

41-
// All access to aliases should go through helper methods with locking
41+
// All access to aliases and the JWT bearer token must go through the lock
4242
var aliases: [String: String] = [:]
43-
private let aliasesLock = NSRecursiveLock()
43+
private let lock = NSRecursiveLock()
4444

45-
// TODO: We need to make this token secure
46-
public var jwtBearerToken: String?
45+
// MARK: - JWT
46+
47+
private var jwtBearerTokenLocked: String?
48+
public var jwtBearerToken: String? {
49+
get {
50+
lock.withLock { jwtBearerTokenLocked }
51+
}
52+
set {
53+
// Notify outside the lock: the change notifier fires synchronously into listeners that
54+
// take locks of their own.
55+
let changed = lock.withLock {
56+
guard newValue != jwtBearerTokenLocked else { return false }
57+
jwtBearerTokenLocked = newValue
58+
return true
59+
}
60+
if changed {
61+
self.set(property: OS_JWT_BEARER_TOKEN, newValue: newValue)
62+
}
63+
}
64+
}
65+
66+
/// Returns the bearer token if it is valid, otherwise nil, snapshots once
67+
func getValidJwt() -> String? {
68+
let token = jwtBearerToken
69+
guard let token = token, !token.isEmpty, token != OS_JWT_TOKEN_INVALID else {
70+
return nil
71+
}
72+
return token
73+
}
74+
75+
/// Returns `true` if the transition occurred, `false` if `rejectedToken` is no longer the stored
76+
/// token. Comparing against the rejected token rather than the sentinel is what keeps a failure
77+
/// response that was already in flight from parking the replacement supplied after it left.
78+
@discardableResult
79+
func invalidateJwtBearerToken(rejectedToken: String) -> Bool {
80+
let changed = lock.withLock {
81+
guard jwtBearerTokenLocked == rejectedToken else { return false }
82+
jwtBearerTokenLocked = OS_JWT_TOKEN_INVALID
83+
return true
84+
}
85+
if changed {
86+
self.set(property: OS_JWT_BEARER_TOKEN, newValue: OS_JWT_TOKEN_INVALID)
87+
}
88+
return changed
89+
}
4790

4891
// MARK: - Initialization
4992

@@ -54,9 +97,10 @@ class OSIdentityModel: OSModel {
5497
}
5598

5699
override func encode(with coder: NSCoder) {
57-
aliasesLock.withLock {
100+
lock.withLock {
58101
super.encode(with: coder)
59102
coder.encode(aliases, forKey: "aliases")
103+
coder.encode(jwtBearerTokenLocked, forKey: OS_JWT_BEARER_TOKEN)
60104
}
61105
}
62106

@@ -66,19 +110,20 @@ class OSIdentityModel: OSModel {
66110
// log error
67111
return nil
68112
}
113+
self.jwtBearerTokenLocked = coder.decodeObject(forKey: OS_JWT_BEARER_TOKEN) as? String
69114
self.aliases = aliases
70115
}
71116

72117
/** Threadsafe getter for an alias */
73118
private func internalGetAlias(_ label: String) -> String? {
74-
aliasesLock.withLock {
119+
lock.withLock {
75120
return self.aliases[label]
76121
}
77122
}
78123

79124
/** Threadsafe setter or removal for aliases */
80125
private func internalAddAliases(_ aliases: [String: String]) {
81-
aliasesLock.withLock {
126+
lock.withLock {
82127
for (label, id) in aliases {
83128
// Remove the alias if the ID field is ""
84129
self.aliases[label] = id.isEmpty ? nil : id
@@ -91,7 +136,7 @@ class OSIdentityModel: OSModel {
91136
Called to clear the model's data in preparation for hydration via a fetch user call.
92137
*/
93138
func clearData() {
94-
aliasesLock.withLock {
139+
lock.withLock {
95140
self.aliases = [:]
96141
}
97142
}
@@ -120,14 +165,20 @@ class OSIdentityModel: OSModel {
120165
let newExternalId = remoteAliases[OS_EXTERNAL_ID]
121166

122167
internalAddAliases(remoteAliases)
123-
fireUserStateChanged(newOnesignalId: newOnesignalId, newExternalId: newExternalId)
168+
OSUserStateSnapshot.fireUserStateChanged(newOnesignalId: newOnesignalId, newExternalId: newExternalId)
124169
}
170+
}
125171

126-
/**
127-
Fires the user observer if `onesignal_id` OR `external_id` has changed from the previous snapshot (previous hydration).
128-
*/
129-
private func fireUserStateChanged(newOnesignalId: String?, newExternalId: String?) {
130-
let prevOnesignalId = OneSignalUserDefaults.initShared().getSavedString(forKey: OS_SNAPSHOT_ONESIGNAL_ID, defaultValue: nil)
172+
/**
173+
Owns the last user state the app was told about, so the observer only hears real changes.
174+
175+
Hydration is the usual source, but `logout` under Identity Verification also reports here: it creates
176+
no user on the server, so there is no hydration to carry the news that nobody is signed in.
177+
*/
178+
enum OSUserStateSnapshot {
179+
/// Fires the user observer if `onesignal_id` OR `external_id` differs from the last reported pair.
180+
static func fireUserStateChanged(newOnesignalId: String?, newExternalId: String?) {
181+
let prevOnesignalId = OneSignalUserDefaults.initShared().getSavedString(forKey: OS_SNAPSHOT_ONESIGNAL_ID, defaultValue: nil)
131182
let prevExternalId = OneSignalUserDefaults.initShared().getSavedString(forKey: OS_SNAPSHOT_EXTERNAL_ID, defaultValue: nil)
132183

133184
guard prevOnesignalId != newOnesignalId || prevExternalId != newExternalId else {

‎iOS_SDK/OneSignalSDK/OneSignalUser/Source/OSIdentityModelRepo.swift‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
*/
2727

2828
import Foundation
29+
import OneSignalCore
2930

3031
/**
3132
This class stores all Identity Models that are being used during an app session.
@@ -52,4 +53,64 @@ class OSIdentityModelRepo {
5253
return models[modelId]
5354
}
5455
}
56+
57+
func get(externalId: String) -> OSIdentityModel? {
58+
lock.withLock {
59+
return models.values.first { $0.externalId == externalId }
60+
}
61+
}
62+
63+
/**
64+
Repeated logins as the same user each create an Identity Model, so update them all.
65+
This can be optimized in the future to re-use an Identity Model if multiple logins are made for the same user.
66+
67+
Returns `false` if no Identity Model carries this external ID, in which case the token was not stored
68+
anywhere and nothing can sign with it.
69+
*/
70+
@discardableResult
71+
func updateJwtToken(externalId: String, token: String) -> Bool {
72+
let matchingModels = modelsMatching(externalId: externalId)
73+
guard !matchingModels.isEmpty else {
74+
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSIdentityModelRepo.updateJwtToken called for unknown external ID \(externalId)")
75+
return false
76+
}
77+
for model in matchingModels {
78+
model.jwtBearerToken = token
79+
}
80+
return true
81+
}
82+
83+
/// The token this user can currently sign with, or nil if there is none.
84+
func validJwt(externalId: String) -> String? {
85+
return modelsMatching(externalId: externalId).lazy.compactMap { $0.getValidJwt() }.first
86+
}
87+
88+
/**
89+
Invalidates the token on every Identity Model with this external ID, since repeated logins as the
90+
same user each create one. Only the models still holding `rejectedToken` transition, so a
91+
replacement that landed while the rejected request was in flight survives.
92+
93+
Returns `false` if no Identity Model carries this external ID, in which case there was nothing
94+
to park and nothing to tell the app about.
95+
*/
96+
@discardableResult
97+
func invalidateJwtToken(externalId: String, rejectedToken: String) -> Bool {
98+
let matchingModels = modelsMatching(externalId: externalId)
99+
guard !matchingModels.isEmpty else {
100+
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSIdentityModelRepo.invalidateJwtToken called for unknown external ID \(externalId)")
101+
return false
102+
}
103+
for model in matchingModels {
104+
model.invalidateJwtBearerToken(rejectedToken: rejectedToken)
105+
}
106+
return true
107+
}
108+
109+
/// Snapshot before touching the tokens: writing one fires the model's change notifier
110+
/// synchronously into listeners that take locks of their own.
111+
private func modelsMatching(externalId: String) -> [OSIdentityModel] {
112+
lock.withLock {
113+
models.values.filter { $0.externalId == externalId }
114+
}
115+
}
55116
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
Modified MIT License
3+
4+
Copyright 2026 OneSignal
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
1. The above copyright notice and this permission notice shall be included in
14+
all copies or substantial portions of the Software.
15+
16+
2. All copies of substantial portions of the Software may only be used in connection
17+
with services provided by OneSignal.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
*/
27+
28+
/**
29+
Tells the app that the JWT it supplied for `externalId` is no longer accepted, so it should mint a
30+
fresh one and hand it back through `OneSignal.updateUserJwt(externalId:token:)`.
31+
*/
32+
@objc public class OSUserJwtInvalidatedEvent: NSObject {
33+
@objc public let externalId: String
34+
35+
init(externalId: String) {
36+
self.externalId = externalId
37+
}
38+
39+
@objc public func jsonRepresentation() -> NSDictionary {
40+
return [
41+
"externalId": externalId
42+
]
43+
}
44+
}
45+
46+
@objc public protocol OSUserJwtInvalidatedListener {
47+
@objc func onUserJwtInvalidated(event: OSUserJwtInvalidatedEvent)
48+
}
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
/*
2+
Modified MIT License
3+
4+
Copyright 2026 OneSignal
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
1. The above copyright notice and this permission notice shall be included in
14+
all copies or substantial portions of the Software.
15+
16+
2. All copies of substantial portions of the Software may only be used in connection
17+
with services provided by OneSignal.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
*/
27+
28+
import Foundation
29+
import OneSignalCore
30+
31+
/**
32+
Identity Verification token access, keyed by `external_id`. Executors depend on this rather than on
33+
the User Manager so that no JWT lookup reaches for a singleton.
34+
*/
35+
protocol OSUserJwtProviding: AnyObject {
36+
/// The token this user can sign with, or nil if the SDK holds none.
37+
func validJwt(externalId: String) -> String?
38+
39+
/**
40+
Asks the app for a token for `externalId`.
41+
42+
Returns `true` if this call is the one that asked, which happens at most once per external ID
43+
per session so a burst of concurrent callers does not fire the event repeatedly.
44+
*/
45+
@discardableResult
46+
func askForToken(externalId: String) -> Bool
47+
48+
/// Parks the rejected token and asks the app for a replacement. Returns `true` if this call asked.
49+
@discardableResult
50+
func invalidateJwt(externalId: String, rejectedToken: String) -> Bool
51+
}
52+
53+
final class OSUserJwtRepo: OSUserJwtProviding {
54+
private let identityModelRepo: OSIdentityModelRepo
55+
private let notifyInvalidated: (String) -> Void
56+
57+
let lock = NSLock()
58+
/**
59+
External IDs the app has already been asked to re-sign.
60+
61+
In memory only. A model decoded at launch can already hold the invalid sentinel, leaving nothing
62+
to transition, so a fresh session has to be able to ask again — otherwise an app that was asked
63+
in a previous run is never told it still owes a token.
64+
*/
65+
var askedForToken: Set<String> = []
66+
67+
init(identityModelRepo: OSIdentityModelRepo, notifyInvalidated: @escaping (String) -> Void) {
68+
self.identityModelRepo = identityModelRepo
69+
self.notifyInvalidated = notifyInvalidated
70+
}
71+
72+
func validJwt(externalId: String) -> String? {
73+
return identityModelRepo.validJwt(externalId: externalId)
74+
}
75+
76+
/**
77+
Stores a token supplied by the app, and lets this user be asked again if it is ever rejected.
78+
Returns `false` for a token that was not stored, so callers do not go looking for held work to release.
79+
80+
An unusable token is ignored rather than stored: it would replace a good token with nothing to sign
81+
with, and clearing the ask for it would have the SDK and the app trade asks and replies on every flush.
82+
A token for an external ID the SDK has no Identity Model for lands nowhere, so it is not treated as an
83+
answer either.
84+
*/
85+
@discardableResult
86+
func updateJwt(externalId: String, token: String) -> Bool {
87+
guard !token.isEmpty, token != OS_JWT_TOKEN_INVALID else {
88+
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSUserJwtRepo.updateJwt ignored an unusable token for \(externalId)")
89+
return false
90+
}
91+
guard identityModelRepo.updateJwtToken(externalId: externalId, token: token) else {
92+
return false
93+
}
94+
lock.withLock { _ = askedForToken.remove(externalId) }
95+
return true
96+
}
97+
98+
@discardableResult
99+
func askForToken(externalId: String) -> Bool {
100+
guard lock.withLock({ askedForToken.insert(externalId).inserted }) else {
101+
return false
102+
}
103+
notifyInvalidated(externalId)
104+
return true
105+
}
106+
107+
/// External IDs already asked this session; cleared when a usable token is stored.
108+
func pendingTokenAsks() -> [String] {
109+
return lock.withLock { Array(askedForToken) }
110+
}
111+
112+
@discardableResult
113+
func invalidateJwt(externalId: String, rejectedToken: String) -> Bool {
114+
// No model for this user means the token could not have come from here. A Request stamped
115+
// with an owner whose model was cleared for hydration lands here, and it retries once the
116+
// aliases come back.
117+
guard identityModelRepo.invalidateJwtToken(externalId: externalId, rejectedToken: rejectedToken) else {
118+
return false
119+
}
120+
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSUserJwtRepo invalidated JWT for externalId: \(externalId)")
121+
// A replacement that landed while the rejected Request was in flight leaves the token above
122+
// untouched, and the retry signs with it, so there is nothing to ask the app for.
123+
guard identityModelRepo.validJwt(externalId: externalId) == nil else {
124+
return false
125+
}
126+
return askForToken(externalId: externalId)
127+
}
128+
}

0 commit comments

Comments
 (0)