better-auth-nitro-ui 0.0.0-stage → 0.1.0

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,24 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 rohanskalkat
4
+
5
+ Portions adapted from `@better-auth/expo`:
6
+ Copyright (c) 2024 - present, Bereket Engida
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,206 @@
1
- # Temporary Holding Version
1
+ # better-auth-nitro-ui
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
+ Standalone [Better Auth](https://www.better-auth.com/) server and client integration for NitroUI applications. It provides the same native authentication model as `@better-auth/expo` without depending on Expo or React Native.
4
+
5
+ > **Status:** Initial implementation (`"private": true` until release readiness is confirmed).
6
+
7
+ ## Installation
8
+
9
+ ```sh
10
+ bun add better-auth-nitro-ui better-auth
11
+ # For native client integrations:
12
+ bun add nitro-web-browser nitro-keychain
13
+ ```
14
+
15
+ `nitro-web-browser` and `nitro-keychain` are optional peer dependencies because they contain native code. Install them in the consuming NitroUI application and run its normal native preparation step.
16
+
17
+ ## Entrypoints
18
+
19
+ - `better-auth-nitro-ui` — Better Auth server plugin
20
+ - `better-auth-nitro-ui/client` — Better Auth client plugin
21
+ - `better-auth-nitro-ui/adapters/keychain` — optional `nitro-keychain` storage adapter
22
+
23
+ ## Server setup
24
+
25
+ ```ts
26
+ import { betterAuth } from 'better-auth'
27
+ import { nitro } from 'better-auth-nitro-ui'
28
+
29
+ export const auth = betterAuth({
30
+ plugins: [nitro()],
31
+ trustedOrigins: ['myapp://'],
32
+ socialProviders: {
33
+ google: {
34
+ clientId: process.env.GOOGLE_CLIENT_ID!,
35
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
36
+ },
37
+ },
38
+ })
39
+ ```
40
+
41
+ The server plugin:
42
+
43
+ - accepts the native origin from the `nitro-origin` header;
44
+ - validates trusted custom-scheme redirects;
45
+ - injects cookies into trusted native deep links;
46
+ - exposes `/nitro-authorization-proxy` for browser-based OAuth;
47
+ - validates proxy targets against configured OAuth provider authorization endpoints.
48
+
49
+ For interoperability with an existing backend or client using `@better-auth/expo`, enable Expo-compatible wire names on both sides:
50
+
51
+ ```ts
52
+ nitro({ expoCompatibility: true })
53
+ ```
54
+
55
+ Compatibility mode uses `expo-origin` and `/expo-authorization-proxy`. It is a protocol setting only; it does not add Expo runtime dependencies.
56
+
57
+ ## Client setup
58
+
59
+ ### process.env compatibility shim
60
+
61
+ NitroUI 0.3.x installs `globalThis.process = { env: "development" }` where `env` is a bare string. Better Auth core probes `process.env` with the `in` operator while its modules evaluate, which crashes the app at startup with `TypeError: right operand of 'in' is not an object`. Add the shim as the first import of your app entry file so the shape is normalized before any `better-auth` module evaluates:
62
+
63
+ ```ts
64
+ import 'better-auth-nitro-ui/shim'
65
+ ```
66
+
67
+ The shim only activates when `process.env` is missing or not an object, so it is a no-op in conforming runtimes. It also runs automatically when `better-auth-nitro-ui/client` is imported, but a direct `better-auth/*` import that is evaluated earlier in the module graph can still crash first — the entry-file import is the reliable ordering.
68
+
69
+ Storage is injected explicitly. A scheme is required and is used to construct native callback URLs.
70
+
71
+ ```ts
72
+ import { createAuthClient } from 'better-auth/client'
73
+ import { nitroClient } from 'better-auth-nitro-ui/client'
74
+ import { createKeychainStorage } from 'better-auth-nitro-ui/adapters/keychain'
75
+
76
+ export const authClient = createAuthClient({
77
+ baseURL: 'https://api.example.com/api/auth',
78
+ plugins: [
79
+ nitroClient({
80
+ scheme: 'myapp',
81
+ storage: createKeychainStorage(),
82
+ }),
83
+ ],
84
+ })
85
+ ```
86
+
87
+ Relative callback paths are converted into application deep links:
88
+
89
+ ```ts
90
+ await authClient.signIn.social({
91
+ provider: 'google',
92
+ callbackURL: '/dashboard', // becomes myapp:///dashboard
93
+ })
94
+ ```
95
+
96
+ When `expoCompatibility` is enabled, use the same setting on the client:
97
+
98
+ ```ts
99
+ nitroClient({
100
+ scheme: 'myapp',
101
+ storage: createKeychainStorage(),
102
+ expoCompatibility: true,
103
+ })
104
+ ```
105
+
106
+ The client uses `nitro-web-browser` for system authentication sessions. Install and configure it in the consuming NitroUI application.
107
+
108
+ ## Storage contract
109
+
110
+ The client accepts any async-first string storage implementing:
111
+
112
+ ```ts
113
+ interface NitroAuthStorage {
114
+ getItem(key: string): string | null | Promise<string | null>
115
+ setItem(key: string, value: string): void | Promise<void>
116
+ removeItem?(key: string): void | Promise<void>
117
+ }
118
+ ```
119
+
120
+ The implementation normalizes keys for native stores, chunks large values into native-store-sized entries, and serializes concurrent writes per key.
121
+
122
+ ## nitro-keychain adapter
123
+
124
+ `createKeychainStorage()` stores Better Auth values as credential passwords using `nitro-keychain`. Keys are mapped to unique service names under the `better-auth-nitro-ui` prefix. Empty-string tombstones are represented by deleting the credential because Keychain and Keystore credentials cannot contain empty passwords.
125
+
126
+ ```ts
127
+ const storage = createKeychainStorage({
128
+ servicePrefix: 'com.example.myapp.auth',
129
+ // Additional nitro-keychain options are passed through.
130
+ })
131
+ ```
132
+
133
+ `nitro-keychain` is an optional peer dependency because it contains native code and must be installed and linked by the consuming application. On the iOS Simulator, keychain operations require a signed application build; unsigned `CODE_SIGNING_ALLOWED=NO` harness builds can exercise the storage contract with another storage implementation, while Android emulators can exercise the real keychain/keystore adapter directly.
134
+
135
+ ## Provenance
136
+
137
+ This package is a selective TypeScript adaptation of `@better-auth/expo@1.7.29`, with Expo and React Native dependencies replaced by NitroUI-native dependencies. Upstream MIT copyright attribution is preserved in `LICENSE`.
138
+
139
+ ## Supported flows and limitations
140
+
141
+ Supported:
142
+
143
+ - email/password and other non-browser Better Auth flows through the standard Better Auth client;
144
+ - persistent native cookies and cold-start session cache hydration;
145
+ - browser-based social/OAuth authorization through `nitro-web-browser` and the server authorization proxy;
146
+ - deep-link cookie propagation for trusted custom-scheme callbacks handled by the Better Auth server plugin;
147
+ - optional wire compatibility with existing `@better-auth/expo` backends.
148
+
149
+ Current limitations:
150
+
151
+ - The client does not automatically refetch sessions when an app returns to the foreground or when network connectivity is restored. NitroUI does not currently expose first-class lifecycle/connectivity primitives equivalent to React Native `AppState` and `expo-network`.
152
+ - Browser-based social sign-in resolves after cookies are merged but does not navigate the application. Navigation remains application-owned, matching Better Auth's native behavior.
153
+ - The server can generate trusted deep links containing cookies, but this package does not consume OS-delivered cold-start links because NitroUI does not yet provide a general incoming-link API. Browser Auth Session return URLs are handled internally by `nitro-web-browser`.
154
+ - iOS and Android are the intended native targets. Web, desktop, macOS, tvOS, Expo, and React Native runtimes are outside the package scope.
155
+ - Client and server `expoCompatibility` settings must match. A compatibility-mode client can also talk to an unmodified backend using `@better-auth/expo`.
156
+
157
+ ## Examples
158
+
159
+ The repository contains a runnable Hono server and NitroUI application under `examples/`:
160
+
161
+ - `examples/server` — Hono server using Better Auth, the `nitro()` server plugin, libsql, and Drizzle ORM. Auth tables persist in a local SQLite database (`file:./auth.db` by default; `DATABASE_URL` can also point at a separately running local libsql/sqld server).
162
+ - `examples/AuthExample` — NitroUI iOS/Android application using `nitroClient()` and the keychain storage adapter.
163
+
164
+ First install dependencies and build the workspace package once, because the examples consume it through its package entrypoints:
165
+
166
+ ```sh
167
+ bun install
168
+ bun run build
169
+ ```
170
+
171
+ Start the auth server in one terminal:
172
+
173
+ ```sh
174
+ bun run example:server
175
+ ```
176
+
177
+ The server listens on port `8787` and creates/migrates `examples/server/auth.db` automatically. Its schema and generated Drizzle migrations live in `examples/server/src/schema.ts` and `examples/server/drizzle/`. Regenerate migrations after schema changes with:
178
+
179
+ ```sh
180
+ bun --cwd examples/server db:generate
181
+ ```
182
+
183
+ Start the NitroUI dev server in another terminal:
184
+
185
+ ```sh
186
+ bun run example:app
187
+ ```
188
+
189
+ Press `i` or `a` in the NitroUI dev server to build and open the app. The app uses `authexample://` as its redirect scheme. Android emulator traffic targets the host through `10.0.2.2`; iOS simulator traffic uses `127.0.0.1`. For browser-based OAuth on Android or for any physical device, point both the app's `baseURL` in `examples/AuthExample/src/auth.ts` and the server's `BETTER_AUTH_URL` at the development machine's LAN address. Email/password works on the Android emulator through `10.0.2.2` without that change, but the system browser cannot use the emulator loopback address for provider callbacks.
190
+
191
+ Google sign-in is optional. Set `GOOGLE_CLIENT_ID` and `GOOGLE_CLIENT_SECRET` in `examples/server/.env` before starting the server; without them the email/password flow remains available and the Google button reports that the provider is not configured. `examples/server/.env.example` lists the supported environment variables.
192
+
193
+ With the auth server running, the example's device integration harness can be run with `bun --cwd examples/AuthExample test:android better-auth --device <adb-serial>` or `bun --cwd examples/AuthExample test:ios better-auth --device <simulator-udid>`.
194
+
195
+ The NitroUI example uses real keychain storage. Android emulator debug builds can use it directly. iOS simulator keychain access requires a signed application build; unsigned `CODE_SIGNING_ALLOWED=NO` harness-style builds cannot use the data-protection keychain. NitroUI's current text input API also has no secure-entry mode, so the example password field is visible and is intended only for local development credentials.
196
+
197
+ ## Validation
198
+
199
+ ```sh
200
+ bun install
201
+ bun run build
202
+ bun run typecheck
203
+ bun run test
204
+ bun run check
205
+ bun run pack:check
206
+ ```
@@ -0,0 +1,49 @@
1
+ import { t as NitroAuthStorage } from "../storage-nw1bx7BP.js";
2
+ export type KeychainAccessible = 'AccessibleWhenUnlocked' | 'AccessibleAfterFirstUnlock' | 'AccessibleAlways' | 'AccessibleWhenPasscodeSetThisDeviceOnly' | 'AccessibleWhenUnlockedThisDeviceOnly' | 'AccessibleAfterFirstUnlockThisDeviceOnly';
3
+ export type KeychainAccessControl = 'UserPresence' | 'BiometryAny' | 'BiometryCurrentSet' | 'DevicePasscode' | 'ApplicationPassword' | 'BiometryAnyOrDevicePasscode' | 'BiometryCurrentSetOrDevicePasscode';
4
+ export type KeychainAuthenticationType = 'AuthenticationWithBiometricsDevicePasscode' | 'AuthenticationWithBiometrics';
5
+ export type KeychainSecurityLevel = 'SECURE_SOFTWARE' | 'SECURE_HARDWARE' | 'ANY';
6
+ export type KeychainStorageType = 'KeystoreAESCBC' | 'KeystoreAESGCM_NoAuth' | 'KeystoreAESGCM' | 'KeystoreRSAECB';
7
+ export interface KeychainAuthenticationPrompt {
8
+ title?: string;
9
+ subtitle?: string;
10
+ description?: string;
11
+ cancel?: string;
12
+ }
13
+ export interface KeychainStorageAdapterOptions {
14
+ /** When the keychain item is accessible (iOS). */
15
+ accessible?: KeychainAccessible;
16
+ /** Access control policy required before reading the item. */
17
+ accessControl?: KeychainAccessControl;
18
+ /** Authentication type used for access-control policy checks. */
19
+ authenticationType?: KeychainAuthenticationType;
20
+ /** Authentication prompt configuration. */
21
+ authenticationPrompt?: KeychainAuthenticationPrompt;
22
+ /** Keychain access group for shared items (iOS). */
23
+ accessGroup?: string;
24
+ /** Whether to synchronize items to iCloud (iOS). */
25
+ cloudSync?: boolean;
26
+ /** Minimum required Keystore security level (Android). */
27
+ securityLevel?: KeychainSecurityLevel;
28
+ /** Explicit cryptographic storage implementation (Android). */
29
+ storage?: KeychainStorageType;
30
+ /**
31
+ * Prefix used when translating Better Auth storage keys into keychain
32
+ * service names.
33
+ * @default 'better-auth-nitro-ui'
34
+ */
35
+ servicePrefix?: string;
36
+ /**
37
+ * Keychain entries are credential-oriented, so a fixed non-empty username is
38
+ * stored alongside the Better Auth value.
39
+ * @default 'better-auth'
40
+ */
41
+ username?: string;
42
+ }
43
+ /**
44
+ * Adapts nitro-keychain's credential API to Better Auth's string storage
45
+ * contract. Better Auth values are stored as credential passwords. Empty
46
+ * values delete their credential because neither iOS Keychain nor Android
47
+ * Keystore can persist an empty password.
48
+ */
49
+ export declare function createKeychainStorage(options?: KeychainStorageAdapterOptions): NitroAuthStorage;
@@ -0,0 +1,48 @@
1
+ import { getGenericPassword, resetGenericPassword, setGenericPassword } from "nitro-keychain";
2
+ // src/adapters/keychain.ts
3
+ function toServiceName(prefix, key) {
4
+ return `${prefix}.${encodeURIComponent(key)}`;
5
+ }
6
+ /**
7
+ * Adapts nitro-keychain's credential API to Better Auth's string storage
8
+ * contract. Better Auth values are stored as credential passwords. Empty
9
+ * values delete their credential because neither iOS Keychain nor Android
10
+ * Keystore can persist an empty password.
11
+ */
12
+ function createKeychainStorage(options = {}) {
13
+ const { servicePrefix = "better-auth-nitro-ui", username = "better-auth", ...keychainOptions } = options;
14
+ const serviceFor = (key) => toServiceName(servicePrefix, key);
15
+ return {
16
+ async getItem(key) {
17
+ const credentials = await getGenericPassword({
18
+ ...keychainOptions,
19
+ service: serviceFor(key)
20
+ });
21
+ if (!credentials || credentials.username !== username) return null;
22
+ return credentials.password;
23
+ },
24
+ async setItem(key, value) {
25
+ const service = serviceFor(key);
26
+ if (value === "") {
27
+ await resetGenericPassword({
28
+ ...keychainOptions,
29
+ service
30
+ });
31
+ return;
32
+ }
33
+ if (!await setGenericPassword(username, value, {
34
+ ...keychainOptions,
35
+ service
36
+ })) throw new Error(`Unable to persist keychain value for "${service}"`);
37
+ },
38
+ async removeItem(key) {
39
+ await resetGenericPassword({
40
+ ...keychainOptions,
41
+ service: serviceFor(key)
42
+ });
43
+ }
44
+ };
45
+ }
46
+ export { createKeychainStorage };
47
+
48
+ //# sourceMappingURL=keychain.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keychain.js","names":[],"sources":["../../src/adapters/keychain.ts"],"sourcesContent":["import {\n getGenericPassword,\n resetGenericPassword,\n setGenericPassword,\n} from 'nitro-keychain'\nimport type { NitroAuthStorage } from '../storage'\n\nexport type KeychainAccessible =\n | 'AccessibleWhenUnlocked'\n | 'AccessibleAfterFirstUnlock'\n | 'AccessibleAlways'\n | 'AccessibleWhenPasscodeSetThisDeviceOnly'\n | 'AccessibleWhenUnlockedThisDeviceOnly'\n | 'AccessibleAfterFirstUnlockThisDeviceOnly'\n\nexport type KeychainAccessControl =\n | 'UserPresence'\n | 'BiometryAny'\n | 'BiometryCurrentSet'\n | 'DevicePasscode'\n | 'ApplicationPassword'\n | 'BiometryAnyOrDevicePasscode'\n | 'BiometryCurrentSetOrDevicePasscode'\n\nexport type KeychainAuthenticationType =\n | 'AuthenticationWithBiometricsDevicePasscode'\n | 'AuthenticationWithBiometrics'\n\nexport type KeychainSecurityLevel =\n | 'SECURE_SOFTWARE'\n | 'SECURE_HARDWARE'\n | 'ANY'\n\nexport type KeychainStorageType =\n | 'KeystoreAESCBC'\n | 'KeystoreAESGCM_NoAuth'\n | 'KeystoreAESGCM'\n | 'KeystoreRSAECB'\n\nexport interface KeychainAuthenticationPrompt {\n title?: string\n subtitle?: string\n description?: string\n cancel?: string\n}\n\nexport interface KeychainStorageAdapterOptions {\n /** When the keychain item is accessible (iOS). */\n accessible?: KeychainAccessible\n /** Access control policy required before reading the item. */\n accessControl?: KeychainAccessControl\n /** Authentication type used for access-control policy checks. */\n authenticationType?: KeychainAuthenticationType\n /** Authentication prompt configuration. */\n authenticationPrompt?: KeychainAuthenticationPrompt\n /** Keychain access group for shared items (iOS). */\n accessGroup?: string\n /** Whether to synchronize items to iCloud (iOS). */\n cloudSync?: boolean\n /** Minimum required Keystore security level (Android). */\n securityLevel?: KeychainSecurityLevel\n /** Explicit cryptographic storage implementation (Android). */\n storage?: KeychainStorageType\n\n /**\n * Prefix used when translating Better Auth storage keys into keychain\n * service names.\n * @default 'better-auth-nitro-ui'\n */\n servicePrefix?: string\n /**\n * Keychain entries are credential-oriented, so a fixed non-empty username is\n * stored alongside the Better Auth value.\n * @default 'better-auth'\n */\n username?: string\n}\n\nfunction toServiceName(prefix: string, key: string) {\n return `${prefix}.${encodeURIComponent(key)}`\n}\n\n/**\n * Adapts nitro-keychain's credential API to Better Auth's string storage\n * contract. Better Auth values are stored as credential passwords. Empty\n * values delete their credential because neither iOS Keychain nor Android\n * Keystore can persist an empty password.\n */\nexport function createKeychainStorage(\n options: KeychainStorageAdapterOptions = {},\n): NitroAuthStorage {\n const { servicePrefix = 'better-auth-nitro-ui', username = 'better-auth', ...keychainOptions } = options\n const serviceFor = (key: string) =>\n toServiceName(servicePrefix, key)\n\n return {\n async getItem(key) {\n const credentials = await getGenericPassword({\n ...keychainOptions,\n service: serviceFor(key),\n })\n if (!credentials || credentials.username !== username) return null\n return credentials.password\n },\n async setItem(key, value) {\n const service = serviceFor(key)\n if (value === '') {\n await resetGenericPassword({ ...keychainOptions, service })\n return\n }\n const result = await setGenericPassword(username, value, {\n ...keychainOptions,\n service,\n })\n if (!result) {\n throw new Error(`Unable to persist keychain value for \"${service}\"`)\n }\n },\n async removeItem(key) {\n await resetGenericPassword({\n ...keychainOptions,\n service: serviceFor(key),\n })\n },\n }\n}\n"],"mappings":";;AA8EA,SAAS,cAAc,QAAgB,KAAa;CAClD,OAAO,GAAG,OAAO,GAAG,mBAAmB,GAAG;AAC5C;;;;;;;AAQA,SAAgB,sBACd,UAAyC,CAAC,GACxB;CAClB,MAAM,EAAE,gBAAgB,wBAAwB,WAAW,eAAe,GAAG,oBAAoB;CACjG,MAAM,cAAc,QAClB,cAAc,eAAe,GAAG;CAElC,OAAO;EACL,MAAM,QAAQ,KAAK;GACjB,MAAM,cAAc,MAAM,mBAAmB;IAC3C,GAAG;IACH,SAAS,WAAW,GAAG;GACzB,CAAC;GACD,IAAI,CAAC,eAAe,YAAY,aAAa,UAAU,OAAO;GAC9D,OAAO,YAAY;EACrB;EACA,MAAM,QAAQ,KAAK,OAAO;GACxB,MAAM,UAAU,WAAW,GAAG;GAC9B,IAAI,UAAU,IAAI;IAChB,MAAM,qBAAqB;KAAE,GAAG;KAAiB;IAAQ,CAAC;IAC1D;GACF;GAKA,IAAI,CAAC,MAJgB,mBAAmB,UAAU,OAAO;IACvD,GAAG;IACH;GACF,CAAC,GAEC,MAAM,IAAI,MAAM,yCAAyC,QAAQ,EAAE;EAEvE;EACA,MAAM,WAAW,KAAK;GACpB,MAAM,qBAAqB;IACzB,GAAG;IACH,SAAS,WAAW,GAAG;GACzB,CAAC;EACH;CACF;AACF"}
@@ -0,0 +1,194 @@
1
+ import { ClientFetchOption, ClientStore } from "@better-auth/core";
2
+ import { n as createManagedStorage, r as normalizeCookieName, t as NitroAuthStorage } from "./storage-nw1bx7BP.js";
3
+ import { parseSetCookieHeader } from "better-auth/cookies/utils";
4
+ export interface NitroClientOptions {
5
+ scheme: string;
6
+ storage: NitroAuthStorage;
7
+ /**
8
+ * Prefix for local storage keys (e.g., "my-app_cookie", "my-app_session_data")
9
+ * @default "better-auth"
10
+ */
11
+ storagePrefix?: string | undefined;
12
+ /**
13
+ * Prefix(es) for server cookie names to filter (e.g., "better-auth.session_token")
14
+ * This is used to identify which cookies belong to better-auth to prevent
15
+ * infinite refetching when third-party cookies are set.
16
+ * Can be a single string or an array of strings to match multiple prefixes.
17
+ * @default "better-auth"
18
+ * @example "better-auth"
19
+ * @example ["better-auth", "my-app"]
20
+ */
21
+ cookiePrefix?: string | string[] | undefined;
22
+ disableCache?: boolean | undefined;
23
+ /**
24
+ * Use Expo-compatible wire names (`expo-origin` and `/expo-authorization-proxy`)
25
+ * instead of the default Nitro names. Must match the server plugin setting.
26
+ * @default false
27
+ */
28
+ expoCompatibility?: boolean | undefined;
29
+ /**
30
+ * Options to customize the Nitro web browser behavior when opening authentication
31
+ * sessions. These are passed directly to `nitro-web-browser`'s
32
+ * `openAuthSessionAsync`.
33
+ *
34
+ * For example, on iOS you can use `{ preferEphemeralSession: true }` to prevent
35
+ * the authentication session from sharing cookies with the user's default
36
+ * browser session:
37
+ *
38
+ * ```ts
39
+ * const client = createAuthClient({
40
+ * plugins: [
41
+ * nitroClient({
42
+ * scheme: 'myapp',
43
+ * storage,
44
+ * webBrowserOptions: {
45
+ * preferEphemeralSession: true,
46
+ * },
47
+ * }),
48
+ * ],
49
+ * })
50
+ * ```
51
+ */
52
+ webBrowserOptions?: NitroWebBrowserOptions | undefined;
53
+ }
54
+ export type NitroWebBrowserPresentationStyle = "fullScreen" | "pageSheet" | "formSheet" | "currentContext" | "overFullScreen" | "overCurrentContext" | "popover" | "automatic";
55
+ /**
56
+ * Options passed through to nitro-web-browser's openAuthSessionAsync.
57
+ */
58
+ export interface NitroWebBrowserOptions {
59
+ toolbarColor?: string | undefined;
60
+ browserPackage?: string | undefined;
61
+ enableBarCollapsing?: boolean | undefined;
62
+ secondaryToolbarColor?: string | undefined;
63
+ showTitle?: boolean | undefined;
64
+ enableDefaultShareMenuItem?: boolean | undefined;
65
+ showInRecents?: boolean | undefined;
66
+ createTask?: boolean | undefined;
67
+ useProxyActivity?: boolean | undefined;
68
+ controlsColor?: string | undefined;
69
+ dismissButtonStyle?: "done" | "close" | "cancel" | undefined;
70
+ readerMode?: boolean | undefined;
71
+ presentationStyle?: NitroWebBrowserPresentationStyle | undefined;
72
+ windowName?: string | undefined;
73
+ windowFeatures?: string | Record<string, number | boolean | string> | undefined;
74
+ additionalHeaderFields?: Record<string, string> | undefined;
75
+ preferEphemeralSession?: boolean | undefined;
76
+ preferUniversalLinks?: boolean | undefined;
77
+ }
78
+ export interface NitroAuthSessionResult {
79
+ type: string;
80
+ url?: string | undefined;
81
+ }
82
+ /**
83
+ * NitroUI installs fetch and Headers but does not yet install the Request
84
+ * constructor. Better Auth only needs a small client-side subset, so install a
85
+ * conservative polyfill when the runtime does not provide one.
86
+ */
87
+ export declare function installNitroFetchPolyfill(): void;
88
+ export declare function getSetCookie(header: string, prevCookie?: string | undefined): string;
89
+ export declare function getCookie(cookie: string | null): string;
90
+ /**
91
+ * Check if the Set-Cookie header contains better-auth cookies.
92
+ * This prevents infinite refetching when non-better-auth cookies (like third-party cookies) change.
93
+ *
94
+ * Supports multiple cookie naming patterns:
95
+ * - Default: "better-auth.session_token", "better-auth-passkey", "__Secure-better-auth.session_token"
96
+ * - Custom prefix: "myapp.session_token", "myapp-passkey", "__Secure-myapp.session_token"
97
+ * - Custom full names: "my_custom_session_token", "custom_session_data"
98
+ * - No prefix (cookiePrefix=""): matches any cookie with known suffixes
99
+ * - Multiple prefixes: ["better-auth", "my-app"] matches cookies starting with any of the prefixes
100
+ *
101
+ * @param setCookieHeader - The Set-Cookie header value
102
+ * @param cookiePrefix - The cookie prefix(es) to check for. Can be a string, array of strings, or empty string.
103
+ * @returns true if the header contains better-auth cookies, false otherwise
104
+ */
105
+ export declare function hasBetterAuthCookies(setCookieHeader: string, cookiePrefix: string | string[]): boolean;
106
+ export declare const nitroClient: (opts: NitroClientOptions) => {
107
+ id: "nitro";
108
+ version: string;
109
+ getActions(_fetch: unknown, $store: ClientStore): {
110
+ /**
111
+ * Get the stored cookie.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * const cookie = await client.getCookie();
116
+ * fetch("https://api.example.com", {
117
+ * headers: {
118
+ * cookie,
119
+ * },
120
+ * });
121
+ * ```
122
+ */
123
+ getCookie: () => Promise<string>;
124
+ };
125
+ fetchPlugins: {
126
+ id: string;
127
+ name: string;
128
+ hooks: {
129
+ onSuccess(context: import("@better-fetch/fetch").SuccessContext<any>): Promise<void>;
130
+ };
131
+ init(url: string, options: ({
132
+ cache?: RequestCache;
133
+ credentials?: RequestCredentials;
134
+ integrity?: string;
135
+ keepalive?: boolean;
136
+ method?: string;
137
+ mode?: RequestMode;
138
+ priority?: RequestPriority;
139
+ redirect?: RequestRedirect;
140
+ referrer?: string;
141
+ referrerPolicy?: ReferrerPolicy;
142
+ signal?: AbortSignal | null;
143
+ window?: null;
144
+ } & {
145
+ onRequest?: <T extends Record<string, any>>(context: import("@better-fetch/fetch").RequestContext<T>) => Promise<import("@better-fetch/fetch").RequestContext | void> | import("@better-fetch/fetch").RequestContext | void;
146
+ onResponse?: (context: import("@better-fetch/fetch").ResponseContext) => Promise<Response | void | import("@better-fetch/fetch").ResponseContext> | Response | import("@better-fetch/fetch").ResponseContext | void;
147
+ onSuccess?: ((context: import("@better-fetch/fetch").SuccessContext<any>) => Promise<void> | void) | undefined;
148
+ onError?: (context: import("@better-fetch/fetch").ErrorContext) => Promise<void> | void;
149
+ onRetry?: (response: import("@better-fetch/fetch").ResponseContext) => Promise<void> | void;
150
+ hookOptions?: {
151
+ cloneResponse?: boolean;
152
+ };
153
+ timeout?: number;
154
+ customFetchImpl?: import("@better-fetch/fetch").FetchEsque;
155
+ plugins?: import("@better-fetch/fetch").BetterFetchPlugin[];
156
+ baseURL?: string;
157
+ throw?: boolean;
158
+ auth?: {
159
+ type: "Basic";
160
+ username: string | (() => string | undefined) | undefined;
161
+ password: string | (() => string | undefined) | undefined;
162
+ } | {
163
+ type: "Bearer";
164
+ token: string | Promise<string | undefined> | (() => string | Promise<string | undefined> | undefined) | undefined;
165
+ } | {
166
+ type: "Custom";
167
+ prefix: string | (() => string | undefined) | undefined;
168
+ value: string | (() => string | undefined) | undefined;
169
+ };
170
+ headers?: {
171
+ [x: string]: string | undefined;
172
+ accept?: "application/json" | "application/octet-stream" | "text/plain" | (string & {});
173
+ "content-type"?: "application/json" | "application/octet-stream" | "application/x-www-form-urlencoded" | "multipart/form-data" | "text/plain" | (string & {});
174
+ authorization?: `Basic ${string}` | `Bearer ${string}` | (string & {});
175
+ } | {} | undefined;
176
+ body?: any;
177
+ query?: any;
178
+ params?: any;
179
+ duplex?: "full" | "half";
180
+ jsonParser?: (text: string) => Promise<any> | any;
181
+ retry?: import("@better-fetch/fetch").RetryOptions;
182
+ retryAttempt?: number;
183
+ method?: "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | (string & {});
184
+ output?: import("@better-fetch/fetch").StandardSchemaV1 | typeof Blob | typeof File;
185
+ errorSchema?: import("@better-fetch/fetch").StandardSchemaV1;
186
+ disableValidation?: boolean;
187
+ signal?: AbortSignal | null;
188
+ } & Record<string, any>) | undefined): Promise<{
189
+ url: string;
190
+ options: ClientFetchOption;
191
+ }>;
192
+ }[];
193
+ };
194
+ export { type NitroAuthStorage, createManagedStorage, normalizeCookieName, parseSetCookieHeader };