@ohauthcat/react-native 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +35 -0
- package/OhAuthCatReactNative.podspec +27 -0
- package/README.md +73 -2
- package/THIRD_PARTY_LICENSES +7 -0
- package/android/build.gradle +25 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/ohauthcat/reactnative/OhAuthCatModule.kt +80 -0
- package/android/src/main/java/com/ohauthcat/reactnative/OhAuthCatPackage.kt +15 -0
- package/dist/client.d.ts +72 -0
- package/dist/client.js +265 -0
- package/dist/config.d.ts +39 -0
- package/dist/config.js +67 -0
- package/dist/encoding.d.ts +8 -0
- package/dist/encoding.js +148 -0
- package/dist/errors.d.ts +41 -0
- package/dist/errors.js +57 -0
- package/dist/flow.d.ts +60 -0
- package/dist/flow.js +226 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/platform.d.ts +61 -0
- package/dist/platform.js +92 -0
- package/ios/OhAuthCat/Authorization.swift +112 -0
- package/ios/OhAuthCat/Browser.swift +55 -0
- package/ios/OhAuthCat/Configuration.swift +97 -0
- package/ios/OhAuthCat/Errors.swift +74 -0
- package/ios/OhAuthCat/NativeBridge.swift +118 -0
- package/ios/OhAuthCat/OhAuthCatClient.swift +137 -0
- package/ios/OhAuthCat/Passkeys.swift +177 -0
- package/ios/OhAuthCat/TokenStore.swift +89 -0
- package/ios/OhAuthCat/Tokens.swift +81 -0
- package/ios/OhAuthCat/Transport.swift +101 -0
- package/ios/OhAuthCatModule.m +17 -0
- package/ios/OhAuthCatModule.swift +72 -0
- package/package.json +60 -3
- package/react-native.config.cjs +12 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// End-user sign-in for iOS and macOS apps.
|
|
4
|
+
///
|
|
5
|
+
/// One client per app. All state changes are serialized by the actor, and
|
|
6
|
+
/// concurrent `accessToken()` callers share one refresh (single flight).
|
|
7
|
+
public actor OhAuthCatClient {
|
|
8
|
+
public let configuration: Configuration
|
|
9
|
+
private let store: TokenStore
|
|
10
|
+
private let tokens: TokenClient
|
|
11
|
+
private let browser: WebAuthenticator
|
|
12
|
+
private let now: @Sendable () -> Date
|
|
13
|
+
private var refreshTask: Task<TokenSet, Error>?
|
|
14
|
+
private var signInInProgress = false
|
|
15
|
+
|
|
16
|
+
public init(configuration: Configuration, browser: WebAuthenticator, store: TokenStore = KeychainTokenStore(),
|
|
17
|
+
transport: HTTPTransport = URLSessionTransport(), now: @escaping @Sendable () -> Date = { Date() }) {
|
|
18
|
+
self.configuration = configuration
|
|
19
|
+
self.store = store
|
|
20
|
+
self.browser = browser
|
|
21
|
+
self.now = now
|
|
22
|
+
self.tokens = TokenClient(configuration: configuration, transport: transport, now: now)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/// Opens the hosted login, validates the callback and stores the tokens.
|
|
26
|
+
/// Pass `organizationID` to sign in to (or switch to) one organization.
|
|
27
|
+
@discardableResult
|
|
28
|
+
public func signIn(organizationID: String? = nil, prompt: String? = nil) async throws -> User {
|
|
29
|
+
guard !signInInProgress else { throw OhAuthCatError.invalidConfiguration("a sign-in is already in progress") }
|
|
30
|
+
signInInProgress = true
|
|
31
|
+
defer { signInInProgress = false }
|
|
32
|
+
let req = AuthorizationRequest(configuration: configuration, organizationID: organizationID, prompt: prompt)
|
|
33
|
+
let callback = try await browser.authenticate(url: req.url, callbackScheme: configuration.redirectURI.scheme)
|
|
34
|
+
let code = try req.code(from: callback, configuration: configuration)
|
|
35
|
+
let set = try await tokens.exchange(code: code, verifier: req.pkce.verifier)
|
|
36
|
+
guard let id = set.idToken else { throw OhAuthCatError.invalidIDToken("missing") }
|
|
37
|
+
let claims = try JWTClaims(jwt: id)
|
|
38
|
+
try claims.validateIDToken(issuer: configuration.issuer, clientID: configuration.clientID, nonce: req.nonce, now: now())
|
|
39
|
+
if let org = organizationID, let got = claims.string("org_id"), got != org {
|
|
40
|
+
throw OhAuthCatError.invalidIDToken("org_id")
|
|
41
|
+
}
|
|
42
|
+
refreshTask?.cancel()
|
|
43
|
+
refreshTask = nil
|
|
44
|
+
try store.save(set)
|
|
45
|
+
guard let user = claims.user else { throw OhAuthCatError.invalidIDToken("sub") }
|
|
46
|
+
return user
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Signs in without showing a page (`prompt=none`): a live hosted-login
|
|
50
|
+
/// session completes at once, otherwise it throws `login_required` (or
|
|
51
|
+
/// `interaction_required` when an organization must be chosen).
|
|
52
|
+
@discardableResult
|
|
53
|
+
public func signInSilently(organizationID: String? = nil) async throws -> User {
|
|
54
|
+
try await signIn(organizationID: organizationID, prompt: "none")
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/// Re-runs the hosted login for another organization. A live hosted
|
|
58
|
+
/// session completes without asking for credentials again.
|
|
59
|
+
@discardableResult
|
|
60
|
+
public func switchOrganization(_ organizationID: String) async throws -> User {
|
|
61
|
+
let id = organizationID.trimmingCharacters(in: .whitespaces)
|
|
62
|
+
guard !id.isEmpty else { throw OhAuthCatError.invalidConfiguration("organizationID is required") }
|
|
63
|
+
return try await signIn(organizationID: id)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// The signed-in user from the stored ID token, or nil.
|
|
67
|
+
public func currentUser() throws -> User? {
|
|
68
|
+
guard let id = try store.load()?.idToken else { return nil }
|
|
69
|
+
return (try? JWTClaims(jwt: id))?.user
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
public func isSignedIn() throws -> Bool { try store.load() != nil }
|
|
73
|
+
|
|
74
|
+
/// A valid access token, refreshing first when it is about to expire.
|
|
75
|
+
public func accessToken() async throws -> String {
|
|
76
|
+
guard let current = try store.load() else { throw OhAuthCatError.notSignedIn }
|
|
77
|
+
if !current.isExpired(now: now()) { return current.accessToken }
|
|
78
|
+
return try await refresh().accessToken
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// Refreshes now. Concurrent callers await the same request: refresh
|
|
82
|
+
/// tokens rotate, and a second use of one revokes the whole session.
|
|
83
|
+
@discardableResult
|
|
84
|
+
public func refresh() async throws -> TokenSet {
|
|
85
|
+
if let task = refreshTask { return try await task.value }
|
|
86
|
+
guard let current = try store.load() else { throw OhAuthCatError.notSignedIn }
|
|
87
|
+
guard let rt = current.refreshToken else { throw OhAuthCatError.notSignedIn }
|
|
88
|
+
let client = tokens
|
|
89
|
+
let task = Task { try await client.refresh(rt, previousIDToken: current.idToken) }
|
|
90
|
+
refreshTask = task
|
|
91
|
+
defer { refreshTask = nil }
|
|
92
|
+
do {
|
|
93
|
+
let set = try await task.value
|
|
94
|
+
try store.save(set)
|
|
95
|
+
return set
|
|
96
|
+
} catch let OhAuthCatError.server(code, status) where code.requiresSignIn {
|
|
97
|
+
try? store.clear()
|
|
98
|
+
throw OhAuthCatError.server(code: code, status: status)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/// Always clears the local session. With `endSession` (the default) and
|
|
103
|
+
/// an ID token, it ends the hosted login session through OIDC
|
|
104
|
+
/// RP-initiated logout in the browser, which also ends its refresh
|
|
105
|
+
/// tokens, and returns to `redirectURI`. In OAuth provider mode
|
|
106
|
+
/// `redirectURI` must be one of the client's `post_logout_redirect_uris`. Otherwise it
|
|
107
|
+
/// revokes the refresh token (RFC 7009). Failures never keep the user
|
|
108
|
+
/// signed in on the device.
|
|
109
|
+
public func signOut(endSession: Bool = true) async throws {
|
|
110
|
+
refreshTask?.cancel()
|
|
111
|
+
refreshTask = nil
|
|
112
|
+
let current = try? store.load()
|
|
113
|
+
try store.clear()
|
|
114
|
+
if endSession, let url = logoutURL(idToken: current?.idToken) {
|
|
115
|
+
_ = try? await browser.authenticate(url: url, callbackScheme: configuration.redirectURI.scheme)
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
if let rt = current?.refreshToken {
|
|
119
|
+
try? await tokens.revoke(rt, hint: "refresh_token")
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/// The RP-initiated logout URL for an ID token, or nil where the issuer has none.
|
|
124
|
+
func logoutURL(idToken: String?) -> URL? {
|
|
125
|
+
guard let idToken, let endpoint = configuration.endSessionEndpoint,
|
|
126
|
+
var parts = URLComponents(url: endpoint, resolvingAgainstBaseURL: false) else { return nil }
|
|
127
|
+
parts.queryItems = [
|
|
128
|
+
URLQueryItem(name: "id_token_hint", value: idToken),
|
|
129
|
+
URLQueryItem(name: "client_id", value: configuration.clientID),
|
|
130
|
+
URLQueryItem(name: "post_logout_redirect_uri", value: configuration.redirectURI.absoluteString),
|
|
131
|
+
]
|
|
132
|
+
if case .oauth = configuration.mode {
|
|
133
|
+
parts.queryItems?.append(URLQueryItem(name: "state", value: Random.token()))
|
|
134
|
+
}
|
|
135
|
+
return parts.url
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
#if canImport(AuthenticationServices)
|
|
3
|
+
import AuthenticationServices
|
|
4
|
+
#endif
|
|
5
|
+
|
|
6
|
+
/// WebAuthn options as the server sends them (the subset native platforms need).
|
|
7
|
+
public struct PasskeyRequestOptions: Equatable, Sendable {
|
|
8
|
+
public let challenge: Data
|
|
9
|
+
public let relyingPartyID: String
|
|
10
|
+
/// Set for registration; nil for an assertion.
|
|
11
|
+
public let userID: Data?
|
|
12
|
+
public let userName: String?
|
|
13
|
+
|
|
14
|
+
/// Parses `publicKey` creation or request options JSON (WebAuthn L3
|
|
15
|
+
/// JSON form, base64url binary fields; a top-level `publicKey` wrapper is accepted).
|
|
16
|
+
public init(json: Data) throws {
|
|
17
|
+
guard var obj = try? JSONSerialization.jsonObject(with: json) as? [String: Any] else {
|
|
18
|
+
throw OhAuthCatError.invalidResponse
|
|
19
|
+
}
|
|
20
|
+
// `public_key` is how the OhAuthCat API wraps options a backend may forward as is.
|
|
21
|
+
if let inner = (obj["publicKey"] ?? obj["public_key"]) as? [String: Any] { obj = inner }
|
|
22
|
+
guard let c = obj["challenge"] as? String, let challenge = Data(base64URLEncoded: c), !challenge.isEmpty else {
|
|
23
|
+
throw OhAuthCatError.invalidResponse
|
|
24
|
+
}
|
|
25
|
+
let rp = (obj["rp"] as? [String: Any])?["id"] as? String ?? obj["rpId"] as? String
|
|
26
|
+
guard let rp, !rp.isEmpty else { throw OhAuthCatError.invalidResponse }
|
|
27
|
+
self.challenge = challenge
|
|
28
|
+
self.relyingPartyID = rp
|
|
29
|
+
if let user = obj["user"] as? [String: Any] {
|
|
30
|
+
guard let idStr = user["id"] as? String, let id = Data(base64URLEncoded: idStr) else {
|
|
31
|
+
throw OhAuthCatError.invalidResponse
|
|
32
|
+
}
|
|
33
|
+
userID = id
|
|
34
|
+
userName = user["name"] as? String
|
|
35
|
+
} else {
|
|
36
|
+
userID = nil
|
|
37
|
+
userName = nil
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/// The server side of a passkey ceremony: your own backend endpoints, which
|
|
43
|
+
/// call OhAuthCat's headless passkey routes with the secret key (the server
|
|
44
|
+
/// SDKs' `NativePasskeys`). Never put a secret key on the device. Payloads
|
|
45
|
+
/// are WebAuthn JSON.
|
|
46
|
+
public protocol PasskeyBackend: Sendable {
|
|
47
|
+
func registrationOptions() async throws -> Data
|
|
48
|
+
func finishRegistration(credential: Data) async throws
|
|
49
|
+
func assertionOptions() async throws -> Data
|
|
50
|
+
func finishAssertion(credential: Data) async throws -> TokenSet
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// The platform side: AuthenticationServices on Apple platforms.
|
|
54
|
+
public protocol PasskeyAuthenticator: Sendable {
|
|
55
|
+
/// Returns the WebAuthn registration response JSON.
|
|
56
|
+
func register(_ options: PasskeyRequestOptions) async throws -> Data
|
|
57
|
+
/// Returns the WebAuthn assertion response JSON.
|
|
58
|
+
func assert(_ options: PasskeyRequestOptions) async throws -> Data
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Runs passkey ceremonies through one seam: backend options, platform
|
|
62
|
+
/// ceremony, backend verification.
|
|
63
|
+
public struct Passkeys: Sendable {
|
|
64
|
+
let backend: PasskeyBackend
|
|
65
|
+
let authenticator: PasskeyAuthenticator
|
|
66
|
+
|
|
67
|
+
public init(backend: PasskeyBackend, authenticator: PasskeyAuthenticator) {
|
|
68
|
+
self.backend = backend
|
|
69
|
+
self.authenticator = authenticator
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
public func register() async throws {
|
|
73
|
+
let opts = try PasskeyRequestOptions(json: try await backend.registrationOptions())
|
|
74
|
+
guard opts.userID != nil else { throw OhAuthCatError.invalidResponse }
|
|
75
|
+
try await backend.finishRegistration(credential: try await authenticator.register(opts))
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
public func signIn() async throws -> TokenSet {
|
|
79
|
+
let opts = try PasskeyRequestOptions(json: try await backend.assertionOptions())
|
|
80
|
+
return try await backend.finishAssertion(credential: try await authenticator.assert(opts))
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
#if canImport(AuthenticationServices) && (os(iOS) || os(macOS))
|
|
85
|
+
/// AuthenticationServices passkeys (iOS 15+, macOS 12+). The app must list
|
|
86
|
+
/// the relying party in its Associated Domains (`webcredentials:`).
|
|
87
|
+
@MainActor
|
|
88
|
+
public final class PlatformPasskeyAuthenticator: NSObject, PasskeyAuthenticator,
|
|
89
|
+
ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {
|
|
90
|
+
private let anchor: @MainActor () -> ASPresentationAnchor
|
|
91
|
+
private var pending: CheckedContinuation<Data, Error>?
|
|
92
|
+
|
|
93
|
+
public init(anchor: @escaping @MainActor () -> ASPresentationAnchor) { self.anchor = anchor }
|
|
94
|
+
|
|
95
|
+
public nonisolated func register(_ o: PasskeyRequestOptions) async throws -> Data {
|
|
96
|
+
try await run { () throws -> ASAuthorizationRequest in
|
|
97
|
+
guard let uid = o.userID else { throw OhAuthCatError.invalidResponse }
|
|
98
|
+
let p = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: o.relyingPartyID)
|
|
99
|
+
return p.createCredentialRegistrationRequest(challenge: o.challenge, name: o.userName ?? "", userID: uid)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
public nonisolated func assert(_ o: PasskeyRequestOptions) async throws -> Data {
|
|
104
|
+
try await run { () throws -> ASAuthorizationRequest in
|
|
105
|
+
ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: o.relyingPartyID)
|
|
106
|
+
.createCredentialAssertionRequest(challenge: o.challenge)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
private func run(_ make: () throws -> ASAuthorizationRequest) async throws -> Data {
|
|
111
|
+
guard pending == nil else { throw OhAuthCatError.passkeyUnavailable("a passkey ceremony is in progress") }
|
|
112
|
+
let req = try make()
|
|
113
|
+
return try await withCheckedThrowingContinuation { cont in
|
|
114
|
+
pending = cont
|
|
115
|
+
let c = ASAuthorizationController(authorizationRequests: [req])
|
|
116
|
+
c.delegate = self
|
|
117
|
+
c.presentationContextProvider = self
|
|
118
|
+
c.performRequests()
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private func finish(_ r: Result<Data, Error>) {
|
|
123
|
+
let c = pending
|
|
124
|
+
pending = nil
|
|
125
|
+
c?.resume(with: r)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
public nonisolated func authorizationController(controller: ASAuthorizationController,
|
|
129
|
+
didCompleteWithAuthorization auth: ASAuthorization) {
|
|
130
|
+
MainActor.assumeIsolated {
|
|
131
|
+
if let reg = auth.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration {
|
|
132
|
+
finish(Result { try PasskeyJSON.registration(id: reg.credentialID, clientData: reg.rawClientDataJSON,
|
|
133
|
+
attestation: reg.rawAttestationObject) })
|
|
134
|
+
} else if let a = auth.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {
|
|
135
|
+
finish(Result { try PasskeyJSON.assertion(id: a.credentialID, clientData: a.rawClientDataJSON,
|
|
136
|
+
authenticatorData: a.rawAuthenticatorData,
|
|
137
|
+
signature: a.signature, userHandle: a.userID) })
|
|
138
|
+
} else {
|
|
139
|
+
finish(.failure(OhAuthCatError.passkeyUnavailable("unexpected credential")))
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
public nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
|
|
145
|
+
let cancelled = (error as? ASAuthorizationError)?.code == .canceled
|
|
146
|
+
MainActor.assumeIsolated {
|
|
147
|
+
finish(.failure(cancelled ? OhAuthCatError.cancelled : OhAuthCatError.passkeyUnavailable(error.localizedDescription)))
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
public nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
|
|
152
|
+
MainActor.assumeIsolated { anchor() }
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
#endif
|
|
156
|
+
|
|
157
|
+
/// Builds WebAuthn JSON responses (base64url fields) from platform output.
|
|
158
|
+
enum PasskeyJSON {
|
|
159
|
+
static func registration(id: Data, clientData: Data, attestation: Data?) throws -> Data {
|
|
160
|
+
guard let attestation else { throw OhAuthCatError.passkeyUnavailable("no attestation object") }
|
|
161
|
+
return try JSONSerialization.data(withJSONObject: [
|
|
162
|
+
"id": id.base64URLEncoded(), "rawId": id.base64URLEncoded(), "type": "public-key",
|
|
163
|
+
"response": ["clientDataJSON": clientData.base64URLEncoded(), "attestationObject": attestation.base64URLEncoded()],
|
|
164
|
+
], options: [.sortedKeys])
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
static func assertion(id: Data, clientData: Data, authenticatorData: Data, signature: Data, userHandle: Data?) throws -> Data {
|
|
168
|
+
var response: [String: String] = [
|
|
169
|
+
"clientDataJSON": clientData.base64URLEncoded(), "authenticatorData": authenticatorData.base64URLEncoded(),
|
|
170
|
+
"signature": signature.base64URLEncoded(),
|
|
171
|
+
]
|
|
172
|
+
if let userHandle { response["userHandle"] = userHandle.base64URLEncoded() }
|
|
173
|
+
return try JSONSerialization.data(withJSONObject: [
|
|
174
|
+
"id": id.base64URLEncoded(), "rawId": id.base64URLEncoded(), "type": "public-key", "response": response,
|
|
175
|
+
], options: [.sortedKeys])
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import Security
|
|
3
|
+
|
|
4
|
+
/// Where the session's tokens live. Apps use `KeychainTokenStore`.
|
|
5
|
+
public protocol TokenStore: Sendable {
|
|
6
|
+
func load() throws -> TokenSet?
|
|
7
|
+
func save(_ tokens: TokenSet) throws
|
|
8
|
+
func clear() throws
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/// Keychain-backed store: a generic password item readable only on this
|
|
12
|
+
/// device after the first unlock, never synced to iCloud.
|
|
13
|
+
public struct KeychainTokenStore: TokenStore {
|
|
14
|
+
let service: String
|
|
15
|
+
let account: String
|
|
16
|
+
let accessGroup: String?
|
|
17
|
+
|
|
18
|
+
public init(service: String = "com.ohauthcat.sdk", account: String = "session", accessGroup: String? = nil) {
|
|
19
|
+
self.service = service
|
|
20
|
+
self.account = account
|
|
21
|
+
self.accessGroup = accessGroup
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
private var query: [String: Any] {
|
|
25
|
+
var q: [String: Any] = [
|
|
26
|
+
kSecClass as String: kSecClassGenericPassword,
|
|
27
|
+
kSecAttrService as String: service,
|
|
28
|
+
kSecAttrAccount as String: account,
|
|
29
|
+
]
|
|
30
|
+
if let accessGroup { q[kSecAttrAccessGroup as String] = accessGroup }
|
|
31
|
+
return q
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
func loadData() throws -> Data? {
|
|
35
|
+
var q = query
|
|
36
|
+
q[kSecReturnData as String] = true
|
|
37
|
+
q[kSecMatchLimit as String] = kSecMatchLimitOne
|
|
38
|
+
var out: CFTypeRef?
|
|
39
|
+
let status = SecItemCopyMatching(q as CFDictionary, &out)
|
|
40
|
+
if status == errSecItemNotFound { return nil }
|
|
41
|
+
guard status == errSecSuccess, let data = out as? Data else { throw OhAuthCatError.storage("keychain read \(status)") }
|
|
42
|
+
return data
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public func load() throws -> TokenSet? {
|
|
46
|
+
guard let data = try loadData() else { return nil }
|
|
47
|
+
do {
|
|
48
|
+
return try JSONDecoder().decode(TokenSet.self, from: data)
|
|
49
|
+
} catch {
|
|
50
|
+
try? clear()
|
|
51
|
+
return nil
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public func save(_ tokens: TokenSet) throws {
|
|
56
|
+
try saveData(try JSONEncoder().encode(tokens))
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
func saveData(_ data: Data) throws {
|
|
60
|
+
let attrs: [String: Any] = [
|
|
61
|
+
kSecValueData as String: data,
|
|
62
|
+
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
|
|
63
|
+
]
|
|
64
|
+
var status = SecItemUpdate(query as CFDictionary, attrs as CFDictionary)
|
|
65
|
+
if status == errSecItemNotFound {
|
|
66
|
+
var add = query
|
|
67
|
+
add.merge(attrs) { $1 }
|
|
68
|
+
status = SecItemAdd(add as CFDictionary, nil)
|
|
69
|
+
}
|
|
70
|
+
guard status == errSecSuccess else { throw OhAuthCatError.storage("keychain write \(status)") }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
public func clear() throws {
|
|
74
|
+
let status = SecItemDelete(query as CFDictionary)
|
|
75
|
+
guard status == errSecSuccess || status == errSecItemNotFound else {
|
|
76
|
+
throw OhAuthCatError.storage("keychain delete \(status)")
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/// In-memory store for tests and previews. Never use it in a shipped app.
|
|
82
|
+
public final class InMemoryTokenStore: TokenStore, @unchecked Sendable {
|
|
83
|
+
private let lock = NSLock()
|
|
84
|
+
private var tokens: TokenSet?
|
|
85
|
+
public init(_ tokens: TokenSet? = nil) { self.tokens = tokens }
|
|
86
|
+
public func load() throws -> TokenSet? { lock.withLock { tokens } }
|
|
87
|
+
public func save(_ t: TokenSet) throws { lock.withLock { tokens = t } }
|
|
88
|
+
public func clear() throws { lock.withLock { tokens = nil } }
|
|
89
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The tokens of one signed-in session. Stored only in the secure store.
|
|
4
|
+
public struct TokenSet: Codable, Equatable, Sendable {
|
|
5
|
+
public let accessToken: String
|
|
6
|
+
public let refreshToken: String?
|
|
7
|
+
public let idToken: String?
|
|
8
|
+
/// Seconds since 1970 when the access token expires.
|
|
9
|
+
public let expiresAt: TimeInterval
|
|
10
|
+
|
|
11
|
+
public init(accessToken: String, refreshToken: String?, idToken: String?, expiresAt: TimeInterval) {
|
|
12
|
+
self.accessToken = accessToken
|
|
13
|
+
self.refreshToken = refreshToken
|
|
14
|
+
self.idToken = idToken
|
|
15
|
+
self.expiresAt = expiresAt
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/// True when the access token expires within `leeway` seconds.
|
|
19
|
+
public func isExpired(now: Date, leeway: TimeInterval = 30) -> Bool {
|
|
20
|
+
now.timeIntervalSince1970 + leeway >= expiresAt
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/// The signed-in user, read from the ID token claims.
|
|
25
|
+
public struct User: Equatable, Sendable {
|
|
26
|
+
public let id: String
|
|
27
|
+
public let email: String?
|
|
28
|
+
public let emailVerified: Bool?
|
|
29
|
+
public let name: String?
|
|
30
|
+
public let organizationID: String?
|
|
31
|
+
public let role: String?
|
|
32
|
+
public let roles: [String]
|
|
33
|
+
public let permissions: [String]
|
|
34
|
+
public let sessionID: String?
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/// Decoded, validated JWT claims. The ID token comes straight from the
|
|
38
|
+
/// token endpoint over TLS, so its signature is not checked on the device
|
|
39
|
+
/// (OIDC Core §3.1.3.7); iss, aud, exp and nonce are.
|
|
40
|
+
struct JWTClaims {
|
|
41
|
+
let raw: [String: Any]
|
|
42
|
+
|
|
43
|
+
init(jwt: String) throws {
|
|
44
|
+
let parts = jwt.split(separator: ".", omittingEmptySubsequences: false)
|
|
45
|
+
guard parts.count == 3, let data = Data(base64URLEncoded: String(parts[1])),
|
|
46
|
+
let obj = try? JSONSerialization.jsonObject(with: data), let dict = obj as? [String: Any]
|
|
47
|
+
else { throw OhAuthCatError.invalidIDToken("malformed") }
|
|
48
|
+
raw = dict
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
func string(_ k: String) -> String? { raw[k] as? String }
|
|
52
|
+
func strings(_ k: String) -> [String] {
|
|
53
|
+
if let a = raw[k] as? [String] { return a }
|
|
54
|
+
if let s = raw[k] as? String { return s.split(separator: " ").map(String.init) }
|
|
55
|
+
return []
|
|
56
|
+
}
|
|
57
|
+
func number(_ k: String) -> Double? { (raw[k] as? NSNumber)?.doubleValue }
|
|
58
|
+
|
|
59
|
+
func validateIDToken(issuer: String, clientID: String, nonce: String?, now: Date, leeway: TimeInterval = 60) throws {
|
|
60
|
+
guard string("iss") == issuer else { throw OhAuthCatError.invalidIDToken("iss") }
|
|
61
|
+
let aud = strings("aud")
|
|
62
|
+
guard aud.contains(clientID) else { throw OhAuthCatError.invalidIDToken("aud") }
|
|
63
|
+
if aud.count > 1, string("azp") != clientID { throw OhAuthCatError.invalidIDToken("azp") }
|
|
64
|
+
guard let exp = number("exp"), exp + leeway > now.timeIntervalSince1970 else {
|
|
65
|
+
throw OhAuthCatError.invalidIDToken("exp")
|
|
66
|
+
}
|
|
67
|
+
if let nonce {
|
|
68
|
+
guard let got = string("nonce"), constantTimeEqual(got, nonce) else {
|
|
69
|
+
throw OhAuthCatError.invalidIDToken("nonce")
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
guard let sub = string("sub"), !sub.isEmpty else { throw OhAuthCatError.invalidIDToken("sub") }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
var user: User? {
|
|
76
|
+
guard let sub = string("sub") else { return nil }
|
|
77
|
+
return User(id: sub, email: string("email"), emailVerified: raw["email_verified"] as? Bool,
|
|
78
|
+
name: string("name"), organizationID: string("org_id"), role: string("role"),
|
|
79
|
+
roles: strings("roles"), permissions: strings("permissions"), sessionID: string("sid"))
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
|
|
3
|
+
/// The HTTP seam; `URLSessionTransport` in apps, a fake in tests.
|
|
4
|
+
public protocol HTTPTransport: Sendable {
|
|
5
|
+
func postForm(_ url: URL, form: [String: String]) async throws -> (status: Int, body: Data)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/// The SDK version, kept in step with the other SDKs.
|
|
9
|
+
public let ohAuthCatSDKVersion = "0.0.2"
|
|
10
|
+
|
|
11
|
+
/// Headers sent on every token-endpoint request, so the edge can tell SDK traffic apart.
|
|
12
|
+
let formRequestHeaders: [String: String] = [
|
|
13
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
14
|
+
"Accept": "application/json",
|
|
15
|
+
"User-Agent": "ohauthcat-sdk-swift/\(ohAuthCatSDKVersion)",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
public struct URLSessionTransport: HTTPTransport {
|
|
19
|
+
let session: URLSession
|
|
20
|
+
public init(session: URLSession = .shared) { self.session = session }
|
|
21
|
+
|
|
22
|
+
public func postForm(_ url: URL, form: [String: String]) async throws -> (status: Int, body: Data) {
|
|
23
|
+
var req = URLRequest(url: url)
|
|
24
|
+
req.httpMethod = "POST"
|
|
25
|
+
for (name, value) in formRequestHeaders {
|
|
26
|
+
req.setValue(value, forHTTPHeaderField: name)
|
|
27
|
+
}
|
|
28
|
+
req.httpBody = formEncode(form).data(using: .utf8)
|
|
29
|
+
req.timeoutInterval = 30
|
|
30
|
+
do {
|
|
31
|
+
let (data, resp) = try await session.data(for: req)
|
|
32
|
+
return ((resp as? HTTPURLResponse)?.statusCode ?? 0, data)
|
|
33
|
+
} catch {
|
|
34
|
+
throw OhAuthCatError.network(error.localizedDescription)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
func formEncode(_ form: [String: String]) -> String {
|
|
40
|
+
var allowed = CharacterSet.alphanumerics
|
|
41
|
+
allowed.insert(charactersIn: "-._~")
|
|
42
|
+
return form.sorted(by: { $0.key < $1.key }).map { k, v in
|
|
43
|
+
(k.addingPercentEncoding(withAllowedCharacters: allowed) ?? "") + "="
|
|
44
|
+
+ (v.addingPercentEncoding(withAllowedCharacters: allowed) ?? "")
|
|
45
|
+
}.joined(separator: "&")
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// Token endpoint client (RFC 6749 §4.1.3, §6; RFC 7009).
|
|
49
|
+
struct TokenClient: Sendable {
|
|
50
|
+
let configuration: Configuration
|
|
51
|
+
let transport: HTTPTransport
|
|
52
|
+
let now: @Sendable () -> Date
|
|
53
|
+
|
|
54
|
+
func exchange(code: String, verifier: String) async throws -> TokenSet {
|
|
55
|
+
try await tokenRequest([
|
|
56
|
+
"grant_type": "authorization_code", "code": code, "code_verifier": verifier,
|
|
57
|
+
"redirect_uri": configuration.redirectURI.absoluteString, "client_id": configuration.clientID,
|
|
58
|
+
], previousRefresh: nil)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
func refresh(_ refreshToken: String, previousIDToken: String?) async throws -> TokenSet {
|
|
62
|
+
let t = try await tokenRequest([
|
|
63
|
+
"grant_type": "refresh_token", "refresh_token": refreshToken, "client_id": configuration.clientID,
|
|
64
|
+
], previousRefresh: refreshToken)
|
|
65
|
+
// A refresh may omit the ID token; keep the last one.
|
|
66
|
+
return TokenSet(accessToken: t.accessToken, refreshToken: t.refreshToken, idToken: t.idToken ?? previousIDToken,
|
|
67
|
+
expiresAt: t.expiresAt)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
func revoke(_ token: String, hint: String) async throws {
|
|
71
|
+
guard let url = configuration.revocationEndpoint else { return }
|
|
72
|
+
let (status, body) = try await transport.postForm(url, form: [
|
|
73
|
+
"token": token, "token_type_hint": hint, "client_id": configuration.clientID,
|
|
74
|
+
])
|
|
75
|
+
guard (200..<300).contains(status) else { throw Self.error(status: status, body: body) }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
private func tokenRequest(_ form: [String: String], previousRefresh: String?) async throws -> TokenSet {
|
|
79
|
+
let (status, body) = try await transport.postForm(configuration.tokenEndpoint, form: form)
|
|
80
|
+
guard (200..<300).contains(status) else { throw Self.error(status: status, body: body) }
|
|
81
|
+
guard let obj = try? JSONSerialization.jsonObject(with: body) as? [String: Any],
|
|
82
|
+
let access = obj["access_token"] as? String, !access.isEmpty,
|
|
83
|
+
(obj["token_type"] as? String)?.lowercased() == "bearer"
|
|
84
|
+
else { throw OhAuthCatError.invalidResponse }
|
|
85
|
+
let expiresIn = (obj["expires_in"] as? NSNumber)?.doubleValue ?? 600
|
|
86
|
+
let refresh = (obj["refresh_token"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
|
87
|
+
let id = (obj["id_token"] as? String).flatMap { $0.isEmpty ? nil : $0 }
|
|
88
|
+
return TokenSet(accessToken: access, refreshToken: refresh ?? previousRefresh, idToken: id,
|
|
89
|
+
expiresAt: now().timeIntervalSince1970 + expiresIn)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static func error(status: Int, body: Data) -> OhAuthCatError {
|
|
93
|
+
if let obj = try? JSONSerialization.jsonObject(with: body) as? [String: Any] {
|
|
94
|
+
if let code = obj["error"] as? String { return .server(code: ErrorCode(rawValue: code), status: status) }
|
|
95
|
+
if let err = obj["error"] as? [String: Any], let code = err["code"] as? String {
|
|
96
|
+
return .server(code: ErrorCode(rawValue: code), status: status)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return .server(code: status >= 500 ? .serverError : .invalidRequest, status: status)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#import <React/RCTBridgeModule.h>
|
|
2
|
+
|
|
3
|
+
@interface RCT_EXTERN_MODULE(OhAuthCat, NSObject)
|
|
4
|
+
|
|
5
|
+
RCT_EXTERN__BLOCKING_SYNCHRONOUS_METHOD(randomBytesBase64:(nonnull NSNumber *)length)
|
|
6
|
+
RCT_EXTERN_METHOD(openAuthSession:(NSString *)url redirectUri:(NSString *)redirectUri
|
|
7
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
|
|
8
|
+
RCT_EXTERN_METHOD(secureGet:(NSString *)key resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
|
|
9
|
+
RCT_EXTERN_METHOD(secureSet:(NSString *)key value:(NSString *)value
|
|
10
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
|
|
11
|
+
RCT_EXTERN_METHOD(secureRemove:(NSString *)key resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
|
|
12
|
+
RCT_EXTERN_METHOD(passkeyRegister:(NSString *)optionsJson
|
|
13
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
|
|
14
|
+
RCT_EXTERN_METHOD(passkeyAssert:(NSString *)optionsJson
|
|
15
|
+
resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject)
|
|
16
|
+
|
|
17
|
+
@end
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import AuthenticationServices
|
|
2
|
+
import Foundation
|
|
3
|
+
import React
|
|
4
|
+
import UIKit
|
|
5
|
+
|
|
6
|
+
/// React Native module `OhAuthCat`: a thin adapter over `NativeBridge`
|
|
7
|
+
/// (which `swift test` covers in the iOS SDK).
|
|
8
|
+
@objc(OhAuthCat)
|
|
9
|
+
final class OhAuthCatModule: NSObject {
|
|
10
|
+
private let bridge: NativeBridge
|
|
11
|
+
|
|
12
|
+
override init() {
|
|
13
|
+
let anchor: @MainActor () -> ASPresentationAnchor = {
|
|
14
|
+
UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
|
15
|
+
.flatMap(\.windows).first(where: \.isKeyWindow) ?? ASPresentationAnchor()
|
|
16
|
+
}
|
|
17
|
+
bridge = MainActor.assumeIsolated {
|
|
18
|
+
NativeBridge(browser: SystemWebAuthenticator(anchor: anchor),
|
|
19
|
+
passkeys: PlatformPasskeyAuthenticator(anchor: anchor))
|
|
20
|
+
}
|
|
21
|
+
super.init()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
@objc static func requiresMainQueueSetup() -> Bool { true }
|
|
25
|
+
|
|
26
|
+
@objc func randomBytesBase64(_ length: NSNumber) -> Any {
|
|
27
|
+
(try? bridge.randomBytesBase64(length.intValue)) ?? NSNull()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
private func run(_ resolve: @escaping RCTPromiseResolveBlock, _ reject: @escaping RCTPromiseRejectBlock,
|
|
31
|
+
_ work: @escaping @Sendable () async throws -> Any?) {
|
|
32
|
+
Task {
|
|
33
|
+
do { resolve(try await work() ?? NSNull()) } catch {
|
|
34
|
+
reject(NativeBridge.code(of: error), String(describing: error), nil)
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
@objc func openAuthSession(_ url: String, redirectUri: String, resolve: @escaping RCTPromiseResolveBlock,
|
|
40
|
+
reject: @escaping RCTPromiseRejectBlock) {
|
|
41
|
+
let b = bridge
|
|
42
|
+
run(resolve, reject) { try await b.openAuthSession(url: url, redirectURI: redirectUri) }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
@objc func secureGet(_ key: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
|
|
46
|
+
let b = bridge
|
|
47
|
+
run(resolve, reject) { try b.secureGet(key) }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
@objc func secureSet(_ key: String, value: String, resolve: @escaping RCTPromiseResolveBlock,
|
|
51
|
+
reject: @escaping RCTPromiseRejectBlock) {
|
|
52
|
+
let b = bridge
|
|
53
|
+
run(resolve, reject) { try b.secureSet(key, value); return nil }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
@objc func secureRemove(_ key: String, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
|
|
57
|
+
let b = bridge
|
|
58
|
+
run(resolve, reject) { try b.secureRemove(key); return nil }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
@objc func passkeyRegister(_ optionsJson: String, resolve: @escaping RCTPromiseResolveBlock,
|
|
62
|
+
reject: @escaping RCTPromiseRejectBlock) {
|
|
63
|
+
let b = bridge
|
|
64
|
+
run(resolve, reject) { try await b.passkeyRegister(optionsJson) }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
@objc func passkeyAssert(_ optionsJson: String, resolve: @escaping RCTPromiseResolveBlock,
|
|
68
|
+
reject: @escaping RCTPromiseRejectBlock) {
|
|
69
|
+
let b = bridge
|
|
70
|
+
run(resolve, reject) { try await b.passkeyAssert(optionsJson) }
|
|
71
|
+
}
|
|
72
|
+
}
|