@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 ADDED
@@ -0,0 +1,35 @@
1
+ OhAuthCat SDK and CLI Licence
2
+
3
+ Copyright (c) 2026 Generic Technologies Private Limited. All rights reserved.
4
+ OhAuthCat is a product of Generic Technologies Private Limited.
5
+
6
+ This software development kit (the "Software") is licensed, not sold, under
7
+ the OhAuthCat SDK and CLI Licence, version 1.0, published at
8
+ https://ohauthcat.com/legal/sdk-licence (the "Licence"). By downloading,
9
+ installing or using the Software you accept the Licence. The summary below is
10
+ for convenience; if it differs from the Licence, the Licence prevails.
11
+
12
+ While you have an active agreement with OhAuthCat for its hosted service, you
13
+ may use, copy, read, modify and make derivative works of the Software, and
14
+ distribute it, modified or not, only as an integrated part of your own
15
+ application, solely to access and use the OhAuthCat service.
16
+
17
+ You must not:
18
+
19
+ 1. use the Software, or any modified version or part of it, with any service
20
+ other than the OhAuthCat service;
21
+ 2. distribute, publish or make the Software, or any modified version or part
22
+ of it, available on its own, as a standalone library, package, SDK, fork or
23
+ tool;
24
+ 3. remove or alter any copyright notice, this file or THIRD_PARTY_LICENSES;
25
+ 4. use the Software or its source code to build or help build a product or
26
+ service that competes with the OhAuthCat service; or
27
+ 5. license or distribute the Software under terms that would require it to be
28
+ disclosed or licensed as open source or distributed free of charge.
29
+
30
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
31
+ IMPLIED, TO THE EXTENT THE LAW ALLOWS. LIABILITY IS LIMITED AS SET OUT IN THE
32
+ LICENCE.
33
+
34
+ Third-party components distributed with the Software are listed in
35
+ THIRD_PARTY_LICENSES and are governed by their own licences.
@@ -0,0 +1,27 @@
1
+ require "json"
2
+ package = JSON.parse(File.read(File.join(__dir__, "package.json")))
3
+
4
+ Pod::Spec.new do |s|
5
+ s.name = "OhAuthCatReactNative"
6
+ s.version = package["version"]
7
+ s.summary = package["description"]
8
+ s.homepage = "https://ohauthcat.com"
9
+ s.license = { :type => "Proprietary", :file => "LICENSE" }
10
+ s.author = "OhAuthCat"
11
+ s.platforms = { :ios => "15.0" }
12
+ s.swift_version = "5.9"
13
+ s.source = { :git => "https://bitbucket.org/the-genie-team/ohauthcat-sdk-react-native.git", :tag => "v#{s.version}" }
14
+ # ios/OhAuthCat/ holds the OhAuthCat Swift SDK sources, copied from
15
+ # ohauthcat-sdk-swift (native-sources.json), so this pod needs nothing from
16
+ # CocoaPods trunk, which turns read-only on 2026-12-02.
17
+ s.source_files = "ios/**/*.{h,m,mm,swift}"
18
+ s.frameworks = "AuthenticationServices", "Security", "CryptoKit"
19
+ # Classic bridge module; React Native's new architecture runs it through
20
+ # the interop layer. install_modules_dependencies adds React-Core and, on
21
+ # the new architecture, the codegen headers.
22
+ if respond_to?(:install_modules_dependencies, true)
23
+ install_modules_dependencies(s)
24
+ else
25
+ s.dependency "React-Core"
26
+ end
27
+ end
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # OhAuthCat for React Native
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ End-user sign-in through the OhAuthCat hosted login. The flows (PKCE, state, nonce, callback and ID-token checks, refresh single-flight, revocation) are pure TypeScript; the device parts come from a `Platform`:
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @ohauthcat/react-native
9
+ cd ios && pod install
10
+ ```
11
+
12
+ ### Before the first release
13
+
14
+ Until the package is on npm, build the tarball from this repository (private; read access to `bitbucket.org/the-genie-team/ohauthcat-sdk-react-native` over SSH). Use `--branch v0.0.2` once the tag exists, `--branch dev` before then. The Android build needs `com.ohauthcat:ohauthcat-android` on Maven Central; `pod install` needs nothing beyond React Native's own pods (the Swift SDK is compiled inside this package's pod).
15
+
16
+ ```sh
17
+ git clone --depth 1 --branch dev git@bitbucket.org:the-genie-team/ohauthcat-sdk-react-native.git
18
+ (cd ohauthcat-sdk-react-native && pnpm install --frozen-lockfile && pnpm pack)
19
+ npm install ./ohauthcat-sdk-react-native/ohauthcat-react-native-0.0.2.tgz
20
+ cd ios && pod install
21
+ ```
22
+
23
+ Documentation: https://docs.ohauthcat.com. Licensed under the OhAuthCat SDK Licence (see `LICENSE`); third-party notices are in `THIRD_PARTY_LICENSES`.
24
+
25
+ - `openAuthSession`: the system browser (ASWebAuthenticationSession / Custom Tabs);
26
+ - `secureStore`: Keychain / Keystore-encrypted storage (never AsyncStorage);
27
+ - `randomBytes`: the platform CSPRNG;
28
+ - `passkeys`: AuthenticationServices / Credential Manager.
29
+
30
+ `nativePlatform(NativeModules.OhAuthCat, decode, fetch)` builds it from a native module with the `NativeModuleShape` interface, which wraps this repo's iOS and Android SDKs.
31
+
32
+ ```ts
33
+ import { NativeModules } from "react-native";
34
+ import {
35
+ OhAuthCatClient,
36
+ nativePlatform,
37
+ base64UrlDecode,
38
+ } from "@ohauthcat/react-native";
39
+
40
+ const client = new OhAuthCatClient(
41
+ {
42
+ loginOrigin: "https://login.ohauthcat.com",
43
+ clientId: "pk_live_…",
44
+ redirectUri: "com.example.app:/oauth/callback",
45
+ },
46
+ nativePlatform(NativeModules.OhAuthCat, base64UrlDecode, fetch),
47
+ );
48
+ const user = await client.signIn();
49
+ const token = await client.getAccessToken();
50
+ ```
51
+
52
+ Methods match the browser client: `signIn`, `signOut`, `getAccessToken`, `refresh`, `getUser`, `switchOrganization`, `isSignedIn`, plus `signInSilently` (`prompt=none`) and `passkeys(backend)`. `signOut()` ends the hosted login session in the system browser (RP-initiated logout at the issuer's `end_session_endpoint`, back to `redirectUri`; in oauth mode `/oauth/{env}/logout` with a fresh `state`, and `redirectUri` must be one of the client's `post_logout_redirect_uris`); `signOut({ endSession: false })` revokes the refresh token instead. The `PasskeyBackend` calls your own backend, which uses the server SDKs' `NativePasskeys`; see the iOS or Android README. Once the environment activates a custom sign-in host (`PUT /v1/environment/signin_host`), new passkeys use that host as their RP ID, so add it to the app's associated domains (`webcredentials:<host>`) and Android asset links, and keep `signin.<domain>` for passkeys created earlier.
53
+
54
+ ## Development
55
+
56
+ Node 24 and pnpm 10.30.3 (`corepack enable`).
57
+
58
+ ```sh
59
+ pnpm install --frozen-lockfile
60
+ pnpm fmt:check && pnpm lint && pnpm typecheck && pnpm check:licenses
61
+ timeout 300 pnpm test
62
+ sh scripts/release-guard.test.sh
63
+ pnpm pack
64
+ node scripts/check-shared.mjs # local: shared flow copies match ../ohauthcat-sdk-js
65
+ node scripts/check-native-sources.mjs # local: ios/OhAuthCat matches ../ohauthcat-sdk-swift at the recorded tag
66
+ scripts/build-rn-sample.sh android # or ios; needs the native SDKs published
67
+ ```
68
+
69
+ ## Native modules
70
+
71
+ - iOS: `OhAuthCatReactNative.podspec` compiles the OhAuthCat Swift SDK from `ios/OhAuthCat/` (copied from `ohauthcat-sdk-swift`, pinned in `native-sources.json`; no CocoaPods trunk dependency); `ios/OhAuthCatModule.swift` adapts the SDK's `NativeBridge`.
72
+ - Android: `android/` is an autolinked library module (`OhAuthCatPackage`) over `com.ohauthcat.android.bridge.NativeBridge`; it expects the SDK published as `com.ohauthcat:ohauthcat-android` (released from `ohauthcat-sdk-android`). Set `manifestPlaceholders["ohauthcatRedirectScheme"]` in the app.
73
+ - Architecture: classic bridge modules, which React Native's new architecture runs through its interop layer. `src/specs/NativeOhAuthCat.ts` holds the contract for a later native TurboModule; `package.json` has no `codegenConfig` yet, because autolinking would then expect codegen output that a classic module does not produce.
74
+ - The bridge validates every value from JavaScript (URL schemes, storage keys, sizes); rejections carry a `code` that `fromNativeError` maps to `OhAuthCatError`.
@@ -0,0 +1,7 @@
1
+ The OhAuthCat React Native SDK (@ohauthcat/react-native) bundles no
2
+ third-party code. It declares a peer dependency that the application installs
3
+ itself: react-native (MIT). Its native modules link the OhAuthCat iOS SDK
4
+ (CocoaPods "OhAuthCat") and the OhAuthCat Android SDK
5
+ (com.ohauthcat:ohauthcat-android), both under the OhAuthCat SDK Licence; see
6
+ their THIRD_PARTY_LICENSES. Development and test tools are not included in the
7
+ distributed package.
@@ -0,0 +1,25 @@
1
+ // React Native library module, autolinked by the React Native CLI.
2
+ // The app supplies the Android Gradle Plugin, Kotlin and react-android.
3
+ apply plugin: "com.android.library"
4
+ apply plugin: "org.jetbrains.kotlin.android"
5
+
6
+ android {
7
+ namespace "com.ohauthcat.reactnative"
8
+ compileSdk 35
9
+ defaultConfig { minSdk 26 }
10
+ compileOptions {
11
+ sourceCompatibility JavaVersion.VERSION_17
12
+ targetCompatibility JavaVersion.VERSION_17
13
+ }
14
+ }
15
+
16
+ repositories {
17
+ google()
18
+ mavenCentral()
19
+ }
20
+
21
+ dependencies {
22
+ implementation "com.facebook.react:react-android"
23
+ implementation "com.ohauthcat:ohauthcat-android:0.0.2"
24
+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2"
25
+ }
@@ -0,0 +1 @@
1
+ <manifest />
@@ -0,0 +1,80 @@
1
+ package com.ohauthcat.reactnative
2
+
3
+ import com.facebook.react.bridge.Promise
4
+ import com.facebook.react.bridge.ReactApplicationContext
5
+ import com.facebook.react.bridge.ReactContextBaseJavaModule
6
+ import com.facebook.react.bridge.ReactMethod
7
+ import com.ohauthcat.android.CredentialManagerPasskeys
8
+ import com.ohauthcat.android.CustomTabsAuthenticator
9
+ import com.ohauthcat.android.OhAuthCatException
10
+ import com.ohauthcat.android.PasskeyAuthenticator
11
+ import com.ohauthcat.android.bridge.NativeBridge
12
+ import kotlinx.coroutines.CoroutineScope
13
+ import kotlinx.coroutines.Dispatchers
14
+ import kotlinx.coroutines.SupervisorJob
15
+ import kotlinx.coroutines.cancel
16
+ import kotlinx.coroutines.launch
17
+
18
+ /** React Native module `OhAuthCat`: a thin adapter over [NativeBridge] (unit-tested in the Android SDK). */
19
+ class OhAuthCatModule(private val ctx: ReactApplicationContext) : ReactContextBaseJavaModule(ctx) {
20
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
21
+
22
+ /** Passkeys need the current activity, so the authenticator is resolved per call. */
23
+ private val passkeys = object : PasskeyAuthenticator {
24
+ private fun auth() = ctx.currentActivity?.let { CredentialManagerPasskeys(it) }
25
+ ?: throw OhAuthCatException.PasskeyUnavailable("no foreground activity")
26
+ override suspend fun register(optionsJson: String) = auth().register(optionsJson)
27
+ override suspend fun assert(optionsJson: String) = auth().assert(optionsJson)
28
+ }
29
+
30
+ private val bridge = NativeBridge.create(ctx, { url, redirect ->
31
+ CustomTabsAuthenticator(ctx.currentActivity ?: ctx).authenticate(url, redirect)
32
+ }, passkeys)
33
+
34
+ override fun getName() = NAME
35
+
36
+ override fun invalidate() {
37
+ scope.cancel()
38
+ super.invalidate()
39
+ }
40
+
41
+ private fun run(promise: Promise, work: suspend () -> Any?) {
42
+ scope.launch {
43
+ try {
44
+ promise.resolve(work())
45
+ } catch (e: Throwable) {
46
+ promise.reject(NativeBridge.codeOf(e), e.message ?: "error", e)
47
+ }
48
+ }
49
+ }
50
+
51
+ @ReactMethod(isBlockingSynchronousMethod = true)
52
+ fun randomBytesBase64(length: Double): String? =
53
+ try {
54
+ bridge.randomBytesBase64(length.toInt())
55
+ } catch (e: OhAuthCatException) {
56
+ null
57
+ }
58
+
59
+ @ReactMethod
60
+ fun openAuthSession(url: String, redirectUri: String, promise: Promise) = run(promise) { bridge.openAuthSession(url, redirectUri) }
61
+
62
+ @ReactMethod
63
+ fun secureGet(key: String, promise: Promise) = run(promise) { bridge.secureGet(key) }
64
+
65
+ @ReactMethod
66
+ fun secureSet(key: String, value: String, promise: Promise) = run(promise) { bridge.secureSet(key, value); null }
67
+
68
+ @ReactMethod
69
+ fun secureRemove(key: String, promise: Promise) = run(promise) { bridge.secureRemove(key); null }
70
+
71
+ @ReactMethod
72
+ fun passkeyRegister(optionsJson: String, promise: Promise) = run(promise) { bridge.passkeyRegister(optionsJson) }
73
+
74
+ @ReactMethod
75
+ fun passkeyAssert(optionsJson: String, promise: Promise) = run(promise) { bridge.passkeyAssert(optionsJson) }
76
+
77
+ companion object {
78
+ const val NAME = "OhAuthCat"
79
+ }
80
+ }
@@ -0,0 +1,15 @@
1
+ package com.ohauthcat.reactnative
2
+
3
+ import com.facebook.react.ReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.uimanager.ViewManager
7
+
8
+ // Classic bridge package; the new architecture loads it through the interop layer.
9
+ @Suppress("OVERRIDE_DEPRECATION")
10
+ class OhAuthCatPackage : ReactPackage {
11
+ override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> =
12
+ listOf(OhAuthCatModule(reactContext))
13
+
14
+ override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> = emptyList()
15
+ }
@@ -0,0 +1,72 @@
1
+ import type { ClientOptions, ResolvedConfig } from "./config.js";
2
+ import type { TokenSet, User } from "./flow.js";
3
+ import type { Platform } from "./platform.js";
4
+ /** Server side of a passkey ceremony (WebAuthn JSON). */
5
+ export interface PasskeyBackend {
6
+ registrationOptions(): Promise<string>;
7
+ finishRegistration(credentialJson: string): Promise<void>;
8
+ assertionOptions(): Promise<string>;
9
+ finishAssertion(credentialJson: string): Promise<TokenSet>;
10
+ }
11
+ export interface SignInOptions {
12
+ organizationId?: string;
13
+ prompt?: "login" | "consent" | "none";
14
+ }
15
+ export interface SignOutOptions {
16
+ /**
17
+ * Also end the hosted login session (OIDC RP-initiated logout) in the
18
+ * system browser, so the next `signIn` asks for credentials again.
19
+ * Defaults to true when an ID token is held. The browser returns to
20
+ * `redirectUri`. In oauth mode the logout goes to the issuer's
21
+ * `end_session_endpoint` (`/oauth/{env}/logout`) with a fresh `state`,
22
+ * and `redirectUri` must be one of the client's
23
+ * `post_logout_redirect_uris`.
24
+ */
25
+ endSession?: boolean;
26
+ }
27
+ /**
28
+ * End-user sign-in for React Native. Method names match the OhAuthCat
29
+ * browser client: `signIn`, `signOut`, `getAccessToken`, `refresh`,
30
+ * `getUser`, `switchOrganization`, `isSignedIn`.
31
+ */
32
+ export declare class OhAuthCatClient {
33
+ readonly config: ResolvedConfig;
34
+ private readonly platform;
35
+ private inflight;
36
+ private signingIn;
37
+ constructor(options: ClientOptions, platform: Platform);
38
+ private random;
39
+ private load;
40
+ private save;
41
+ /** Opens the hosted login, validates the callback and stores the tokens. */
42
+ signIn(opts?: SignInOptions): Promise<User>;
43
+ /** Re-runs the hosted login for another organization. */
44
+ switchOrganization(organizationId: string): Promise<User>;
45
+ getUser(): Promise<User | null>;
46
+ isSignedIn(): Promise<boolean>;
47
+ /** A valid access token, refreshing first when it is about to expire. */
48
+ getAccessToken(): Promise<string>;
49
+ /** Refreshes now; concurrent callers share one request (refresh tokens rotate). */
50
+ refresh(): Promise<TokenSet>;
51
+ private doRefresh;
52
+ /**
53
+ * Signs in without showing a page (`prompt=none`): a live hosted-login
54
+ * session completes at once, otherwise it rejects with `login_required`
55
+ * (or `interaction_required` when an organization must be chosen).
56
+ */
57
+ signInSilently(opts?: Omit<SignInOptions, "prompt">): Promise<User>;
58
+ /**
59
+ * Always clears locally. With an ID token, ends the hosted login session
60
+ * through OIDC RP-initiated logout at the issuer's `end_session_endpoint`
61
+ * (which also ends its refresh tokens); otherwise revokes the refresh
62
+ * token (RFC 7009).
63
+ */
64
+ signOut(opts?: SignOutOptions): Promise<void>;
65
+ /** Passkey ceremonies through one seam: backend options, platform ceremony, backend check. */
66
+ passkeys(backend: PasskeyBackend): {
67
+ register(): Promise<void>;
68
+ signIn(): Promise<TokenSet>;
69
+ };
70
+ }
71
+ /** Validates WebAuthn options and strips a `publicKey` wrapper. */
72
+ export declare function passkeyOptions(json: string, registration: boolean): string;
package/dist/client.js ADDED
@@ -0,0 +1,265 @@
1
+ import { resolveConfig } from "./config.js";
2
+ import { base64UrlDecode, base64UrlEncode } from "./encoding.js";
3
+ import { OhAuthCatError } from "./errors.js";
4
+ import { buildAuthorizationRequest, codeFromCallback, decodeJwt, deserializeTokens, errorFromBody, formEncode, postForm, serializeTokens, tokenRequest, userFromClaims, validateIdToken, } from "./flow.js";
5
+ const STORE_KEY = "ohauthcat.session.v1";
6
+ /**
7
+ * End-user sign-in for React Native. Method names match the OhAuthCat
8
+ * browser client: `signIn`, `signOut`, `getAccessToken`, `refresh`,
9
+ * `getUser`, `switchOrganization`, `isSignedIn`.
10
+ */
11
+ export class OhAuthCatClient {
12
+ config;
13
+ platform;
14
+ inflight = null;
15
+ signingIn = false;
16
+ constructor(options, platform) {
17
+ this.config = resolveConfig(options);
18
+ this.platform = platform;
19
+ }
20
+ random() {
21
+ return base64UrlEncode(this.platform.randomBytes(32));
22
+ }
23
+ async load() {
24
+ let raw;
25
+ try {
26
+ raw = await this.platform.secureStore.get(STORE_KEY);
27
+ }
28
+ catch (e) {
29
+ throw OhAuthCatError.client("storage", e instanceof Error ? e.message : "read failed");
30
+ }
31
+ if (raw === null)
32
+ return null;
33
+ const t = deserializeTokens(raw);
34
+ if (!t)
35
+ await this.platform.secureStore.remove(STORE_KEY);
36
+ return t;
37
+ }
38
+ async save(t) {
39
+ try {
40
+ await this.platform.secureStore.set(STORE_KEY, serializeTokens(t));
41
+ }
42
+ catch (e) {
43
+ throw OhAuthCatError.client("storage", e instanceof Error ? e.message : "write failed");
44
+ }
45
+ }
46
+ /** Opens the hosted login, validates the callback and stores the tokens. */
47
+ async signIn(opts = {}) {
48
+ if (this.signingIn) {
49
+ throw OhAuthCatError.client("invalid_configuration", "a sign-in is already in progress");
50
+ }
51
+ this.signingIn = true;
52
+ try {
53
+ const req = buildAuthorizationRequest(this.config, { state: this.random(), nonce: this.random(), verifier: this.random() }, opts);
54
+ const callback = await this.platform.openAuthSession(req.url, this.config.redirectUri);
55
+ const code = codeFromCallback(this.config, req, callback);
56
+ const tokens = await tokenRequest(this.platform.fetch, this.config, {
57
+ grant_type: "authorization_code",
58
+ code,
59
+ code_verifier: req.verifier,
60
+ redirect_uri: this.config.redirectUri,
61
+ client_id: this.config.clientId,
62
+ }, this.platform.now(), null);
63
+ if (!tokens.idToken)
64
+ throw OhAuthCatError.client("invalid_id_token", "missing");
65
+ const claims = decodeJwt(tokens.idToken);
66
+ validateIdToken(claims, this.config, req.nonce, this.platform.now());
67
+ const org = claims["org_id"];
68
+ // A sign-in asked for one organization must come back from that
69
+ // organization: a missing org_id (for example an existing session with
70
+ // no organization) is refused like a different one.
71
+ if (req.organizationId && org !== req.organizationId) {
72
+ throw OhAuthCatError.client("organization_mismatch", typeof org === "string"
73
+ ? "different organization"
74
+ : "no organization");
75
+ }
76
+ const user = userFromClaims(claims);
77
+ if (!user)
78
+ throw OhAuthCatError.client("invalid_id_token", "sub");
79
+ await this.save(tokens);
80
+ return user;
81
+ }
82
+ finally {
83
+ this.signingIn = false;
84
+ }
85
+ }
86
+ /** Re-runs the hosted login for another organization. */
87
+ async switchOrganization(organizationId) {
88
+ const id = organizationId.trim();
89
+ if (id === "")
90
+ throw OhAuthCatError.client("invalid_configuration", "organizationId is required");
91
+ return this.signIn({ organizationId: id });
92
+ }
93
+ async getUser() {
94
+ const t = await this.load();
95
+ if (!t?.idToken)
96
+ return null;
97
+ try {
98
+ return userFromClaims(decodeJwt(t.idToken));
99
+ }
100
+ catch {
101
+ return null;
102
+ }
103
+ }
104
+ async isSignedIn() {
105
+ return (await this.load()) !== null;
106
+ }
107
+ /** A valid access token, refreshing first when it is about to expire. */
108
+ async getAccessToken() {
109
+ const t = await this.load();
110
+ if (!t)
111
+ throw OhAuthCatError.client("not_signed_in");
112
+ if (this.platform.now() + 30_000 < t.expiresAt)
113
+ return t.accessToken;
114
+ return (await this.refresh()).accessToken;
115
+ }
116
+ /** Refreshes now; concurrent callers share one request (refresh tokens rotate). */
117
+ refresh() {
118
+ if (this.inflight)
119
+ return this.inflight;
120
+ const p = this.doRefresh().finally(() => {
121
+ this.inflight = null;
122
+ });
123
+ this.inflight = p;
124
+ return p;
125
+ }
126
+ async doRefresh() {
127
+ const current = await this.load();
128
+ if (!current?.refreshToken)
129
+ throw OhAuthCatError.client("not_signed_in");
130
+ try {
131
+ const next = await tokenRequest(this.platform.fetch, this.config, {
132
+ grant_type: "refresh_token",
133
+ refresh_token: current.refreshToken,
134
+ client_id: this.config.clientId,
135
+ }, this.platform.now(), current.refreshToken);
136
+ const merged = {
137
+ ...next,
138
+ idToken: next.idToken ?? current.idToken,
139
+ };
140
+ await this.save(merged);
141
+ return merged;
142
+ }
143
+ catch (e) {
144
+ if (e instanceof OhAuthCatError && e.requiresSignIn) {
145
+ await this.platform.secureStore.remove(STORE_KEY);
146
+ }
147
+ throw e;
148
+ }
149
+ }
150
+ /**
151
+ * Signs in without showing a page (`prompt=none`): a live hosted-login
152
+ * session completes at once, otherwise it rejects with `login_required`
153
+ * (or `interaction_required` when an organization must be chosen).
154
+ */
155
+ signInSilently(opts = {}) {
156
+ return this.signIn({ ...opts, prompt: "none" });
157
+ }
158
+ /**
159
+ * Always clears locally. With an ID token, ends the hosted login session
160
+ * through OIDC RP-initiated logout at the issuer's `end_session_endpoint`
161
+ * (which also ends its refresh tokens); otherwise revokes the refresh
162
+ * token (RFC 7009).
163
+ */
164
+ async signOut(opts = {}) {
165
+ let current;
166
+ try {
167
+ current = await this.load();
168
+ }
169
+ catch {
170
+ current = null;
171
+ }
172
+ await this.platform.secureStore.remove(STORE_KEY);
173
+ const endpoint = this.config.endSessionEndpoint;
174
+ if (opts.endSession !== false && endpoint && current?.idToken) {
175
+ const q = formEncode({
176
+ id_token_hint: current.idToken,
177
+ client_id: this.config.clientId,
178
+ post_logout_redirect_uri: this.config.redirectUri,
179
+ ...(this.config.mode.kind === "oauth" ? { state: this.random() } : {}),
180
+ });
181
+ try {
182
+ await this.platform.openAuthSession(`${endpoint}?${q}`, this.config.redirectUri);
183
+ }
184
+ catch {
185
+ // Cancelled or offline: the device is signed out; the hosted
186
+ // session ends when it expires.
187
+ }
188
+ return;
189
+ }
190
+ const url = this.config.revocationEndpoint;
191
+ if (!url || !current?.refreshToken)
192
+ return;
193
+ try {
194
+ const r = await postForm(this.platform.fetch, url, {
195
+ token: current.refreshToken,
196
+ token_type_hint: "refresh_token",
197
+ client_id: this.config.clientId,
198
+ });
199
+ if (r.status < 200 || r.status > 299)
200
+ throw errorFromBody(r.status, r.body);
201
+ }
202
+ catch {
203
+ // Already signed out locally; the token expires on its own.
204
+ }
205
+ }
206
+ /** Passkey ceremonies through one seam: backend options, platform ceremony, backend check. */
207
+ passkeys(backend) {
208
+ const auth = this.platform.passkeys;
209
+ const need = () => {
210
+ if (!auth)
211
+ throw OhAuthCatError.client("passkey_unavailable", "this device has no passkey support");
212
+ return auth;
213
+ };
214
+ return {
215
+ register: async () => {
216
+ const a = need();
217
+ const opts = passkeyOptions(await backend.registrationOptions(), true);
218
+ await backend.finishRegistration(await a.register(opts));
219
+ },
220
+ signIn: async () => {
221
+ const a = need();
222
+ const opts = passkeyOptions(await backend.assertionOptions(), false);
223
+ const t = await backend.finishAssertion(await a.assert(opts));
224
+ await this.save(t);
225
+ return t;
226
+ },
227
+ };
228
+ }
229
+ }
230
+ function rec(v) {
231
+ return typeof v === "object" && v !== null && !Array.isArray(v)
232
+ ? Object.fromEntries(Object.entries(v))
233
+ : null;
234
+ }
235
+ /** Validates WebAuthn options and strips a `publicKey` wrapper. */
236
+ export function passkeyOptions(json, registration) {
237
+ let outer;
238
+ try {
239
+ outer = rec(JSON.parse(json));
240
+ }
241
+ catch {
242
+ outer = null;
243
+ }
244
+ if (!outer)
245
+ throw OhAuthCatError.client("invalid_response", "passkey options");
246
+ // `public_key` is how the OhAuthCat API wraps options a backend may forward as is.
247
+ const o = rec(outer["publicKey"]) ?? rec(outer["public_key"]) ?? outer;
248
+ const bad = () => OhAuthCatError.client("invalid_response", "passkey options");
249
+ const ch = o["challenge"];
250
+ if (typeof ch !== "string" || !base64UrlDecode(ch)?.length)
251
+ throw bad();
252
+ if (registration) {
253
+ const user = rec(o["user"]);
254
+ const rp = rec(o["rp"]);
255
+ const uid = user?.["id"];
256
+ if (typeof uid !== "string" || !base64UrlDecode(uid))
257
+ throw bad();
258
+ if (typeof rp?.["id"] !== "string" || rp["id"] === "")
259
+ throw bad();
260
+ }
261
+ else if (typeof o["rpId"] !== "string" || o["rpId"] === "") {
262
+ throw bad();
263
+ }
264
+ return JSON.stringify(o);
265
+ }
@@ -0,0 +1,39 @@
1
+ export type IssuerMode = {
2
+ kind: "user_management";
3
+ } | {
4
+ kind: "oauth";
5
+ environmentId: string;
6
+ };
7
+ export interface ClientOptions {
8
+ /** Hosted login origin, for example `https://login.ohauthcat.com`. */
9
+ loginOrigin: string;
10
+ /** The environment's publishable key, or an OAuth client ID in oauth mode. */
11
+ clientId: string;
12
+ redirectUri: string;
13
+ mode?: IssuerMode;
14
+ scopes?: readonly string[];
15
+ }
16
+ export interface ResolvedConfig {
17
+ origin: string;
18
+ clientId: string;
19
+ redirectUri: string;
20
+ mode: IssuerMode;
21
+ scopes: readonly string[];
22
+ issuer: string;
23
+ authorizationEndpoint: string;
24
+ tokenEndpoint: string;
25
+ revocationEndpoint: string | null;
26
+ /** OIDC RP-initiated logout; only the user_management issuer serves one. */
27
+ endSessionEndpoint: string | null;
28
+ }
29
+ /** Minimal absolute-URI split (scheme, authority, path, query, fragment). RFC 3986 App. B. */
30
+ export interface UriParts {
31
+ scheme: string;
32
+ host: string;
33
+ port: string;
34
+ path: string;
35
+ query: string;
36
+ fragment: string | null;
37
+ }
38
+ export declare function parseUri(s: string): UriParts | null;
39
+ export declare function resolveConfig(o: ClientOptions): ResolvedConfig;