@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.
@@ -0,0 +1,61 @@
1
+ import { OhAuthCatError } from "./errors.js";
2
+ /**
3
+ * What the SDK needs from the device. `nativePlatform()` builds it from the
4
+ * `OhAuthCat` native module (backed by the iOS and Android SDKs in this
5
+ * repo); tests and custom setups pass their own.
6
+ */
7
+ export interface Platform {
8
+ /** Cryptographically secure random bytes. */
9
+ randomBytes(length: number): Uint8Array;
10
+ /** Opens the system browser (ASWebAuthenticationSession / Custom Tabs); resolves with the callback URL. */
11
+ openAuthSession(url: string, redirectUri: string): Promise<string>;
12
+ /** Keychain / Keystore-encrypted storage. Never AsyncStorage. */
13
+ secureStore: SecureStore;
14
+ /** Platform passkey ceremonies, when the device supports them. */
15
+ passkeys?: PasskeyAuthenticator;
16
+ fetch: FetchLike;
17
+ now(): number;
18
+ }
19
+ export interface SecureStore {
20
+ get(key: string): Promise<string | null>;
21
+ set(key: string, value: string): Promise<void>;
22
+ remove(key: string): Promise<void>;
23
+ }
24
+ export interface PasskeyAuthenticator {
25
+ /** WebAuthn creation options JSON in, registration response JSON out. */
26
+ register(optionsJson: string): Promise<string>;
27
+ /** WebAuthn request options JSON in, assertion response JSON out. */
28
+ assert(optionsJson: string): Promise<string>;
29
+ }
30
+ /** Sent on every token-endpoint request, so the edge can tell SDK traffic apart. */
31
+ export declare const USER_AGENT = "ohauthcat-sdk-react-native/0.0.2";
32
+ export interface FetchResponseLike {
33
+ status: number;
34
+ text(): Promise<string>;
35
+ }
36
+ export type FetchLike = (url: string, init: {
37
+ method: "POST";
38
+ headers: Record<string, string>;
39
+ body: string;
40
+ }) => Promise<FetchResponseLike>;
41
+ /** The shape the native module must expose (Promise-based RN module). */
42
+ export interface NativeModuleShape {
43
+ /** Null when the native side refuses the length. */
44
+ randomBytesBase64(length: number): string | null;
45
+ openAuthSession(url: string, redirectUri: string): Promise<string>;
46
+ secureGet(key: string): Promise<string | null>;
47
+ secureSet(key: string, value: string): Promise<void>;
48
+ secureRemove(key: string): Promise<void>;
49
+ passkeyRegister?(optionsJson: string): Promise<string>;
50
+ passkeyAssert?(optionsJson: string): Promise<string>;
51
+ }
52
+ /** Maps a native promise rejection (`code` set by the module) to an OhAuthCatError. */
53
+ export declare function fromNativeError(e: unknown): OhAuthCatError;
54
+ /** Validates an unknown native module at the boundary. */
55
+ export declare function isNativeModule(v: unknown): v is NativeModuleShape;
56
+ /**
57
+ * Builds the platform from `NativeModules.OhAuthCat`. Pass the module in
58
+ * (`import { NativeModules } from "react-native"`) so this package does not
59
+ * load react-native itself.
60
+ */
61
+ export declare function nativePlatform(nativeModule: unknown, decodeBase64: (s: string) => Uint8Array | null, fetchImpl: FetchLike): Platform;
@@ -0,0 +1,92 @@
1
+ import { OhAuthCatError } from "./errors.js";
2
+ /** Sent on every token-endpoint request, so the edge can tell SDK traffic apart. */
3
+ export const USER_AGENT = "ohauthcat-sdk-react-native/0.0.2";
4
+ function isRecord(v) {
5
+ return typeof v === "object" && v !== null;
6
+ }
7
+ function hasFns(v, names) {
8
+ return names.every((n) => typeof v[n] === "function");
9
+ }
10
+ /** Maps a native promise rejection (`code` set by the module) to an OhAuthCatError. */
11
+ export function fromNativeError(e) {
12
+ if (e instanceof OhAuthCatError)
13
+ return e;
14
+ const code = isRecord(e) && typeof e["code"] === "string" ? e["code"] : "";
15
+ const msg = e instanceof Error ? e.message : "native error";
16
+ const kind = nativeKind(code);
17
+ return kind
18
+ ? OhAuthCatError.client(kind, msg)
19
+ : new OhAuthCatError("native_error", msg);
20
+ }
21
+ function nativeKind(code) {
22
+ switch (code) {
23
+ case "cancelled":
24
+ case "invalid_configuration":
25
+ case "storage":
26
+ case "passkey_unavailable":
27
+ case "network":
28
+ case "invalid_response":
29
+ return code;
30
+ default:
31
+ return null;
32
+ }
33
+ }
34
+ async function native(p) {
35
+ try {
36
+ return await p;
37
+ }
38
+ catch (e) {
39
+ throw fromNativeError(e);
40
+ }
41
+ }
42
+ /** Validates an unknown native module at the boundary. */
43
+ export function isNativeModule(v) {
44
+ return (isRecord(v) &&
45
+ hasFns(v, [
46
+ "randomBytesBase64",
47
+ "openAuthSession",
48
+ "secureGet",
49
+ "secureSet",
50
+ "secureRemove",
51
+ ]));
52
+ }
53
+ /**
54
+ * Builds the platform from `NativeModules.OhAuthCat`. Pass the module in
55
+ * (`import { NativeModules } from "react-native"`) so this package does not
56
+ * load react-native itself.
57
+ */
58
+ export function nativePlatform(nativeModule, decodeBase64, fetchImpl) {
59
+ if (!isNativeModule(nativeModule)) {
60
+ throw OhAuthCatError.client("native_module_missing", "link the OhAuthCat native module");
61
+ }
62
+ const m = nativeModule;
63
+ const reg = m.passkeyRegister?.bind(m);
64
+ const asrt = m.passkeyAssert?.bind(m);
65
+ const platform = {
66
+ randomBytes(length) {
67
+ const raw = m.randomBytesBase64(length);
68
+ const b = raw === null ? null : decodeBase64(raw);
69
+ if (b?.length !== length)
70
+ throw OhAuthCatError.client("invalid_response", "random bytes");
71
+ return b;
72
+ },
73
+ openAuthSession: (url, redirectUri) => native(m.openAuthSession(url, redirectUri)),
74
+ secureStore: {
75
+ get: (k) => native(m.secureGet(k)),
76
+ set: (k, v) => native(m.secureSet(k, v)),
77
+ remove: (k) => native(m.secureRemove(k)),
78
+ },
79
+ fetch: (url, init) => fetchImpl(url, {
80
+ ...init,
81
+ headers: { ...init.headers, "User-Agent": USER_AGENT },
82
+ }),
83
+ now: () => Date.now(),
84
+ };
85
+ if (reg && asrt) {
86
+ platform.passkeys = {
87
+ register: (o) => native(reg(o)),
88
+ assert: (o) => native(asrt(o)),
89
+ };
90
+ }
91
+ return platform;
92
+ }
@@ -0,0 +1,112 @@
1
+ import CryptoKit
2
+ import Foundation
3
+ import Security
4
+
5
+ public enum Random {
6
+ /// 32 bytes from the system CSPRNG, base64url without padding.
7
+ public static func token(byteCount: Int = 32) -> String {
8
+ var bytes = [UInt8](repeating: 0, count: byteCount)
9
+ let status = SecRandomCopyBytes(kSecRandomDefault, byteCount, &bytes)
10
+ precondition(status == errSecSuccess, "system random generator failed")
11
+ return Data(bytes).base64URLEncoded()
12
+ }
13
+ }
14
+
15
+ extension Data {
16
+ func base64URLEncoded() -> String {
17
+ base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_")
18
+ .replacingOccurrences(of: "=", with: "")
19
+ }
20
+
21
+ init?(base64URLEncoded s: String) {
22
+ var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
23
+ while b.count % 4 != 0 { b += "=" }
24
+ self.init(base64Encoded: b)
25
+ }
26
+ }
27
+
28
+ /// RFC 7636 PKCE with S256.
29
+ public struct PKCE: Sendable {
30
+ public let verifier: String
31
+ public let challenge: String
32
+
33
+ public init(verifier: String = Random.token()) {
34
+ self.verifier = verifier
35
+ self.challenge = PKCE.challenge(for: verifier)
36
+ }
37
+
38
+ public static func challenge(for verifier: String) -> String {
39
+ Data(SHA256.hash(data: Data(verifier.utf8))).base64URLEncoded()
40
+ }
41
+ }
42
+
43
+ /// One in-flight authorization: the URL to open plus the secrets that
44
+ /// bind the callback to it. Never persisted.
45
+ public struct AuthorizationRequest: Sendable {
46
+ public let url: URL
47
+ public let state: String
48
+ public let nonce: String
49
+ public let pkce: PKCE
50
+ public let organizationID: String?
51
+
52
+ public init(configuration c: Configuration, organizationID: String? = nil, prompt: String? = nil,
53
+ state: String = Random.token(), nonce: String = Random.token(), pkce: PKCE = PKCE()) {
54
+ var items = [
55
+ URLQueryItem(name: "response_type", value: "code"),
56
+ URLQueryItem(name: "client_id", value: c.clientID),
57
+ URLQueryItem(name: "redirect_uri", value: c.redirectURI.absoluteString),
58
+ URLQueryItem(name: "code_challenge", value: pkce.challenge),
59
+ URLQueryItem(name: "code_challenge_method", value: "S256"),
60
+ URLQueryItem(name: "state", value: state),
61
+ URLQueryItem(name: "nonce", value: nonce),
62
+ ]
63
+ if case .oauth = c.mode { items.append(URLQueryItem(name: "scope", value: c.scopes.joined(separator: " "))) }
64
+ if let org = organizationID?.trimmingCharacters(in: .whitespaces), !org.isEmpty {
65
+ items.append(URLQueryItem(name: "organization_id", value: org))
66
+ }
67
+ if let prompt { items.append(URLQueryItem(name: "prompt", value: prompt)) }
68
+ var comps = URLComponents(url: c.authorizationEndpoint, resolvingAgainstBaseURL: false)!
69
+ comps.queryItems = items
70
+ // URLComponents leaves '+' unescaped; encode it so it is not read as a space.
71
+ comps.percentEncodedQuery = comps.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
72
+ self.url = comps.url!
73
+ self.state = state
74
+ self.nonce = nonce
75
+ self.pkce = pkce
76
+ self.organizationID = organizationID
77
+ }
78
+
79
+ /// Validates the redirect the browser returned and extracts the code.
80
+ public func code(from callback: URL, configuration c: Configuration) throws -> String {
81
+ guard Self.sameEndpoint(callback, c.redirectURI) else { throw OhAuthCatError.redirectMismatch }
82
+ let items = URLComponents(url: callback, resolvingAgainstBaseURL: false)?.queryItems ?? []
83
+ func value(_ name: String) -> String? { items.first(where: { $0.name == name })?.value }
84
+ // State is checked before anything else the callback says, including errors.
85
+ guard let got = value("state"), constantTimeEqual(got, state) else { throw OhAuthCatError.stateMismatch }
86
+ if let iss = value("iss"), iss != c.issuer { throw OhAuthCatError.issuerMismatch }
87
+ if let err = value("error"), !err.isEmpty {
88
+ throw OhAuthCatError.server(code: ErrorCode(rawValue: err), status: 0)
89
+ }
90
+ guard let code = value("code"), !code.isEmpty else { throw OhAuthCatError.missingCode }
91
+ return code
92
+ }
93
+
94
+ /// Scheme, host, port and path must match exactly (the server matches
95
+ /// redirect URIs exactly too).
96
+ static func sameEndpoint(_ a: URL, _ b: URL) -> Bool {
97
+ a.scheme?.lowercased() == b.scheme?.lowercased() && a.host?.lowercased() == b.host?.lowercased()
98
+ && a.port == b.port && normalizedPath(a) == normalizedPath(b)
99
+ }
100
+
101
+ private static func normalizedPath(_ u: URL) -> String {
102
+ URLComponents(url: u, resolvingAgainstBaseURL: false)?.percentEncodedPath ?? ""
103
+ }
104
+ }
105
+
106
+ func constantTimeEqual(_ a: String, _ b: String) -> Bool {
107
+ let x = Array(a.utf8), y = Array(b.utf8)
108
+ guard x.count == y.count else { return false }
109
+ var diff: UInt8 = 0
110
+ for i in 0..<x.count { diff |= x[i] ^ y[i] }
111
+ return diff == 0
112
+ }
@@ -0,0 +1,55 @@
1
+ import Foundation
2
+ #if canImport(AuthenticationServices)
3
+ import AuthenticationServices
4
+ #endif
5
+
6
+ /// Opens the hosted login in the system browser and returns the callback URL.
7
+ public protocol WebAuthenticator: Sendable {
8
+ func authenticate(url: URL, callbackScheme: String?) async throws -> URL
9
+ }
10
+
11
+ #if canImport(AuthenticationServices) && (os(iOS) || os(macOS))
12
+ /// ASWebAuthenticationSession: the system browser, sharing cookies with
13
+ /// Safari unless `ephemeral` is set (an ephemeral session cannot reuse a
14
+ /// hosted-login session, so organization switches would ask again).
15
+ @MainActor
16
+ public final class SystemWebAuthenticator: NSObject, WebAuthenticator, ASWebAuthenticationPresentationContextProviding {
17
+ private let anchor: @MainActor () -> ASPresentationAnchor
18
+ private let ephemeral: Bool
19
+ private var session: ASWebAuthenticationSession?
20
+
21
+ public init(ephemeral: Bool = false, anchor: @escaping @MainActor () -> ASPresentationAnchor) {
22
+ self.anchor = anchor
23
+ self.ephemeral = ephemeral
24
+ }
25
+
26
+ public nonisolated func authenticate(url: URL, callbackScheme: String?) async throws -> URL {
27
+ try await start(url: url, callbackScheme: callbackScheme)
28
+ }
29
+
30
+ private func start(url: URL, callbackScheme: String?) async throws -> URL {
31
+ guard session == nil else { throw OhAuthCatError.invalidConfiguration("a sign-in is already in progress") }
32
+ return try await withCheckedThrowingContinuation { (cont: CheckedContinuation<URL, Error>) in
33
+ let s = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) { [weak self] callback, error in
34
+ Task { @MainActor in self?.session = nil }
35
+ if let callback { cont.resume(returning: callback); return }
36
+ if let e = error as? ASWebAuthenticationSessionError, e.code == .canceledLogin {
37
+ cont.resume(throwing: OhAuthCatError.cancelled); return
38
+ }
39
+ cont.resume(throwing: OhAuthCatError.network(error?.localizedDescription ?? "browser failed"))
40
+ }
41
+ s.presentationContextProvider = self
42
+ s.prefersEphemeralWebBrowserSession = ephemeral
43
+ session = s
44
+ if !s.start() {
45
+ session = nil
46
+ cont.resume(throwing: OhAuthCatError.invalidConfiguration("the browser session could not start"))
47
+ }
48
+ }
49
+ }
50
+
51
+ public nonisolated func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
52
+ MainActor.assumeIsolated { anchor() }
53
+ }
54
+ }
55
+ #endif
@@ -0,0 +1,97 @@
1
+ import Foundation
2
+
3
+ /// Which OhAuthCat issuer the app signs in against.
4
+ public enum IssuerMode: Equatable, Sendable {
5
+ /// End-user auth (hosted login): `client_id` is the environment's
6
+ /// publishable key; endpoints `/user_management/authorize` and `/token`.
7
+ case userManagement
8
+ /// The environment's OAuth 2.1 / OIDC provider: issuer
9
+ /// `<origin>/oauth/<environmentID>`, with revocation and userinfo.
10
+ case oauth(environmentID: String)
11
+ }
12
+
13
+ /// SDK configuration. All URLs are validated in `init`.
14
+ public struct Configuration: Equatable, Sendable {
15
+ /// The hosted login origin, for example `https://login.ohauthcat.com`.
16
+ public let loginOrigin: URL
17
+ public let clientID: String
18
+ public let redirectURI: URL
19
+ public let mode: IssuerMode
20
+ public let scopes: [String]
21
+
22
+ public init(loginOrigin: URL, clientID: String, redirectURI: URL, mode: IssuerMode = .userManagement,
23
+ scopes: [String] = ["openid", "profile", "email"]) throws {
24
+ guard loginOrigin.scheme == "https" || Configuration.isLoopback(loginOrigin), loginOrigin.host != nil else {
25
+ throw OhAuthCatError.invalidConfiguration("loginOrigin must be an https URL")
26
+ }
27
+ let trimmed = clientID.trimmingCharacters(in: .whitespacesAndNewlines)
28
+ guard !trimmed.isEmpty else { throw OhAuthCatError.invalidConfiguration("clientID is required") }
29
+ guard let scheme = redirectURI.scheme?.lowercased(), !scheme.isEmpty, redirectURI.fragment == nil else {
30
+ throw OhAuthCatError.invalidConfiguration("redirectURI must be absolute and carry no fragment")
31
+ }
32
+ if scheme == "http" && !Configuration.isLoopback(redirectURI) {
33
+ throw OhAuthCatError.invalidConfiguration("redirectURI must not be plain http")
34
+ }
35
+ if case .oauth(let env) = mode, env.trimmingCharacters(in: .whitespaces).isEmpty {
36
+ throw OhAuthCatError.invalidConfiguration("environmentID is required in oauth mode")
37
+ }
38
+ self.loginOrigin = loginOrigin
39
+ self.clientID = trimmed
40
+ self.redirectURI = redirectURI
41
+ self.mode = mode
42
+ self.scopes = scopes
43
+ }
44
+
45
+ static func isLoopback(_ url: URL) -> Bool {
46
+ url.scheme == "http" && ["127.0.0.1", "localhost", "::1", "[::1]"].contains(url.host ?? "")
47
+ }
48
+
49
+ private var origin: String {
50
+ var s = loginOrigin.absoluteString
51
+ while s.hasSuffix("/") { s.removeLast() }
52
+ return s
53
+ }
54
+
55
+ /// The issuer the ID token's `iss` (and the callback `iss`) must equal.
56
+ public var issuer: String {
57
+ switch mode {
58
+ case .userManagement: return origin
59
+ case .oauth(let env): return origin + "/oauth/" + env
60
+ }
61
+ }
62
+
63
+ public var authorizationEndpoint: URL {
64
+ switch mode {
65
+ case .userManagement: return URL(string: origin + "/user_management/authorize")!
66
+ case .oauth: return URL(string: issuer + "/authorize")!
67
+ }
68
+ }
69
+
70
+ public var tokenEndpoint: URL {
71
+ switch mode {
72
+ case .userManagement: return URL(string: origin + "/user_management/token")!
73
+ case .oauth: return URL(string: issuer + "/token")!
74
+ }
75
+ }
76
+
77
+ /// RFC 7009 revocation.
78
+ public var revocationEndpoint: URL? {
79
+ switch mode {
80
+ case .userManagement: return URL(string: origin + "/user_management/revoke")!
81
+ case .oauth: return URL(string: issuer + "/revoke")!
82
+ }
83
+ }
84
+
85
+ /// OIDC RP-initiated logout: the issuer's `end_session_endpoint`.
86
+ public var endSessionEndpoint: URL? {
87
+ switch mode {
88
+ case .userManagement: return URL(string: origin + "/user_management/logout")!
89
+ case .oauth: return URL(string: issuer + "/logout")!
90
+ }
91
+ }
92
+
93
+ public var userInfoEndpoint: URL? {
94
+ if case .oauth = mode { return URL(string: issuer + "/userinfo")! }
95
+ return nil
96
+ }
97
+ }
@@ -0,0 +1,74 @@
1
+ import Foundation
2
+
3
+ /// Errors raised by the OhAuthCat mobile SDK.
4
+ ///
5
+ /// Server errors carry the stable code from the OhAuthCat error catalogue
6
+ /// (or the RFC 6749 OAuth error code the token endpoint answers with), so
7
+ /// apps can branch on `code` without parsing messages.
8
+ public enum OhAuthCatError: Error, Equatable, Sendable {
9
+ /// The configuration is invalid (for example a non-https issuer).
10
+ case invalidConfiguration(String)
11
+ /// The user closed the browser before finishing the sign-in.
12
+ case cancelled
13
+ /// The callback URL did not match the configured redirect URI.
14
+ case redirectMismatch
15
+ /// The `state` in the callback did not match the one this SDK sent.
16
+ case stateMismatch
17
+ /// The callback named an issuer other than the configured one (RFC 9207).
18
+ case issuerMismatch
19
+ /// The callback carried no authorization code.
20
+ case missingCode
21
+ /// The ID token failed validation (issuer, audience, expiry or nonce).
22
+ case invalidIDToken(String)
23
+ /// No signed-in session is stored.
24
+ case notSignedIn
25
+ /// The server answered with an error code.
26
+ case server(code: ErrorCode, status: Int)
27
+ /// The network request failed.
28
+ case network(String)
29
+ /// The server answered with a body this SDK could not read.
30
+ case invalidResponse
31
+ /// The secure token store failed.
32
+ case storage(String)
33
+ /// Passkeys are not available (no backend configured, or the platform refused).
34
+ case passkeyUnavailable(String)
35
+ }
36
+
37
+ /// A stable error code from the OhAuthCat error catalogue or RFC 6749.
38
+ public struct ErrorCode: RawRepresentable, Hashable, Sendable, CustomStringConvertible {
39
+ public let rawValue: String
40
+ public init(rawValue: String) { self.rawValue = rawValue }
41
+ public var description: String { rawValue }
42
+
43
+ // RFC 6749 §5.2 token endpoint errors.
44
+ public static let invalidRequest = ErrorCode(rawValue: "invalid_request")
45
+ public static let invalidClient = ErrorCode(rawValue: "invalid_client")
46
+ public static let invalidGrant = ErrorCode(rawValue: "invalid_grant")
47
+ public static let unauthorizedClient = ErrorCode(rawValue: "unauthorized_client")
48
+ public static let unsupportedGrantType = ErrorCode(rawValue: "unsupported_grant_type")
49
+ public static let invalidScope = ErrorCode(rawValue: "invalid_scope")
50
+ public static let accessDenied = ErrorCode(rawValue: "access_denied")
51
+ public static let serverError = ErrorCode(rawValue: "server_error")
52
+ public static let temporarilyUnavailable = ErrorCode(rawValue: "temporarily_unavailable")
53
+ public static let loginRequired = ErrorCode(rawValue: "login_required")
54
+ public static let consentRequired = ErrorCode(rawValue: "consent_required")
55
+
56
+ // OhAuthCat error catalogue codes reachable from end-user sign-in.
57
+ public static let redirectURINotAllowed = ErrorCode(rawValue: "redirect_uri_not_allowed")
58
+ public static let refreshTokenReused = ErrorCode(rawValue: "refresh_token_reused")
59
+ public static let userBlocked = ErrorCode(rawValue: "user_blocked")
60
+ public static let userCredentialsInvalid = ErrorCode(rawValue: "user_credentials_invalid")
61
+ public static let userCodeInvalid = ErrorCode(rawValue: "user_code_invalid")
62
+ public static let userFactorInvalid = ErrorCode(rawValue: "user_factor_invalid")
63
+ public static let mfaRequired = ErrorCode(rawValue: "mfa_required")
64
+ public static let signInBlocked = ErrorCode(rawValue: "sign_in_blocked")
65
+ public static let botChallengeFailed = ErrorCode(rawValue: "bot_challenge_failed")
66
+ public static let oauthThirdPartyDenied = ErrorCode(rawValue: "oauth_third_party_denied")
67
+ public static let organizationNotFound = ErrorCode(rawValue: "organization_not_found")
68
+ public static let rateLimited = ErrorCode(rawValue: "rate_limited")
69
+
70
+ /// True when the session is gone and the user must sign in again.
71
+ public var requiresSignIn: Bool {
72
+ [.invalidGrant, .refreshTokenReused, .userBlocked, .loginRequired].contains(self)
73
+ }
74
+ }
@@ -0,0 +1,118 @@
1
+ import Foundation
2
+ import Security
3
+
4
+ /// Keyed secret storage used by the React Native bridge.
5
+ public protocol KeyedSecretStore: Sendable {
6
+ func read(_ key: String) throws -> String?
7
+ func write(_ key: String, _ value: String) throws
8
+ func delete(_ key: String) throws
9
+ }
10
+
11
+ /// Keychain items per key (AfterFirstUnlockThisDeviceOnly, never synced).
12
+ public struct KeychainKeyedStore: KeyedSecretStore {
13
+ let service: String
14
+ public init(service: String = "com.ohauthcat.rn") { self.service = service }
15
+
16
+ public func read(_ key: String) throws -> String? {
17
+ let s = KeychainTokenStore(service: service, account: key)
18
+ return try s.loadData().map { String(decoding: $0, as: UTF8.self) }
19
+ }
20
+
21
+ public func write(_ key: String, _ value: String) throws {
22
+ try KeychainTokenStore(service: service, account: key).saveData(Data(value.utf8))
23
+ }
24
+
25
+ public func delete(_ key: String) throws { try KeychainTokenStore(service: service, account: key).clear() }
26
+ }
27
+
28
+ /// In-memory keyed store for tests.
29
+ public final class InMemoryKeyedStore: KeyedSecretStore, @unchecked Sendable {
30
+ private let lock = NSLock()
31
+ private var values: [String: String] = [:]
32
+ public init() {}
33
+ public func read(_ key: String) throws -> String? { lock.withLock { values[key] } }
34
+ public func write(_ key: String, _ value: String) throws { lock.withLock { values[key] = value } }
35
+ public func delete(_ key: String) throws { _ = lock.withLock { values.removeValue(forKey: key) } }
36
+ }
37
+
38
+ /// The platform half of the React Native SDK, free of React Native types so
39
+ /// `swift test` covers it; the RN `OhAuthCatModule` delegates to it. Every
40
+ /// input from JavaScript is validated here.
41
+ public struct NativeBridge: Sendable {
42
+ public static let maxRandom = 1024
43
+ public static let maxValue = 64 * 1024
44
+
45
+ let store: KeyedSecretStore
46
+ let browser: WebAuthenticator
47
+ let passkeys: PasskeyAuthenticator?
48
+
49
+ public init(store: KeyedSecretStore = KeychainKeyedStore(), browser: WebAuthenticator, passkeys: PasskeyAuthenticator? = nil) {
50
+ self.store = store
51
+ self.browser = browser
52
+ self.passkeys = passkeys
53
+ }
54
+
55
+ public func randomBytesBase64(_ length: Int) throws -> String {
56
+ guard (1...Self.maxRandom).contains(length) else {
57
+ throw OhAuthCatError.invalidConfiguration("length must be 1...\(Self.maxRandom)")
58
+ }
59
+ return Random.token(byteCount: length)
60
+ }
61
+
62
+ public func openAuthSession(url: String, redirectURI: String) async throws -> String {
63
+ guard let u = URL(string: url), let host = u.host, !host.isEmpty,
64
+ u.scheme == "https" || Configuration.isLoopback(u) else {
65
+ throw OhAuthCatError.invalidConfiguration("url must be https")
66
+ }
67
+ guard let r = URL(string: redirectURI), let scheme = r.scheme, !scheme.isEmpty else {
68
+ throw OhAuthCatError.invalidConfiguration("redirectUri is not a valid URI")
69
+ }
70
+ return try await browser.authenticate(url: u, callbackScheme: scheme).absoluteString
71
+ }
72
+
73
+ public func secureGet(_ key: String) throws -> String? { try store.read(Self.check(key)) }
74
+
75
+ public func secureSet(_ key: String, _ value: String) throws {
76
+ guard value.utf8.count <= Self.maxValue else { throw OhAuthCatError.invalidConfiguration("value too large") }
77
+ try store.write(Self.check(key), value)
78
+ }
79
+
80
+ public func secureRemove(_ key: String) throws { try store.delete(Self.check(key)) }
81
+
82
+ public var hasPasskeys: Bool { passkeys != nil }
83
+
84
+ public func passkeyRegister(_ optionsJSON: String) async throws -> String {
85
+ let a = try need()
86
+ return String(decoding: try await a.register(PasskeyRequestOptions(json: Data(optionsJSON.utf8))), as: UTF8.self)
87
+ }
88
+
89
+ public func passkeyAssert(_ optionsJSON: String) async throws -> String {
90
+ let a = try need()
91
+ return String(decoding: try await a.assert(PasskeyRequestOptions(json: Data(optionsJSON.utf8))), as: UTF8.self)
92
+ }
93
+
94
+ private func need() throws -> PasskeyAuthenticator {
95
+ guard let passkeys else { throw OhAuthCatError.passkeyUnavailable("no passkey support") }
96
+ return passkeys
97
+ }
98
+
99
+ static func check(_ key: String) throws -> String {
100
+ let ok = !key.isEmpty && key.count <= 128
101
+ && key.unicodeScalars.allSatisfy { CharacterSet(charactersIn: "._-").contains($0) || ($0.isASCII && CharacterSet.alphanumerics.contains($0)) }
102
+ guard ok else { throw OhAuthCatError.invalidConfiguration("invalid storage key") }
103
+ return key
104
+ }
105
+
106
+ /// The error code JavaScript sees; matches the TS `ClientErrorKind` values.
107
+ public static func code(of error: Error) -> String {
108
+ switch error as? OhAuthCatError {
109
+ case .cancelled?: return "cancelled"
110
+ case .invalidConfiguration?: return "invalid_configuration"
111
+ case .storage?: return "storage"
112
+ case .passkeyUnavailable?: return "passkey_unavailable"
113
+ case .network?: return "network"
114
+ case .invalidResponse?: return "invalid_response"
115
+ default: return "native_error"
116
+ }
117
+ }
118
+ }