@better-auth/expo 1.5.0-beta.1 → 1.5.0-beta.10
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.md +15 -12
- package/README.md +40 -29
- package/dist/client.d.mts +25 -13
- package/dist/client.mjs +41 -62
- package/dist/client.mjs.map +1 -0
- package/dist/index.d.mts +10 -1
- package/dist/index.mjs +13 -3
- package/dist/index.mjs.map +1 -0
- package/dist/plugins/index.d.mts +2 -1
- package/dist/plugins/index.mjs +2 -1
- package/dist/plugins/index.mjs.map +1 -0
- package/package.json +14 -14
package/LICENSE.md
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
1
|
The MIT License (MIT)
|
|
2
2
|
Copyright (c) 2024 - present, Bereket Engida
|
|
3
3
|
|
|
4
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
5
|
-
and associated documentation files (the
|
|
6
|
-
including without limitation the rights to
|
|
7
|
-
|
|
8
|
-
|
|
4
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
5
|
+
this software and associated documentation files (the “Software”), to deal in
|
|
6
|
+
the Software without restriction, including without limitation the rights to
|
|
7
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
8
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
9
|
+
subject to the following conditions:
|
|
9
10
|
|
|
10
|
-
The above copyright notice and this permission notice shall be included in all
|
|
11
|
-
substantial portions of the Software.
|
|
11
|
+
The above copyright notice and this permission notice shall be included in all
|
|
12
|
+
copies or substantial portions of the Software.
|
|
12
13
|
|
|
13
|
-
THE SOFTWARE IS PROVIDED
|
|
14
|
-
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
15
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
16
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
17
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
|
18
|
+
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
|
19
|
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
20
|
+
DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# Better Auth Expo Plugin
|
|
2
2
|
|
|
3
|
-
This plugin integrates Better Auth with Expo, allowing you to easily add
|
|
3
|
+
This plugin integrates Better Auth with Expo, allowing you to easily add
|
|
4
|
+
authentication to your Expo (React Native) applications.
|
|
5
|
+
It supports both Expo native and web apps.
|
|
4
6
|
|
|
5
7
|
## Installation
|
|
6
8
|
|
|
@@ -20,7 +22,8 @@ pnpm add better-auth @better-auth/expo
|
|
|
20
22
|
bun add better-auth @better-auth/expo
|
|
21
23
|
```
|
|
22
24
|
|
|
23
|
-
You will also need to install `expo-secure-store` for secure session and cookie
|
|
25
|
+
You will also need to install `expo-secure-store` for secure session and cookie
|
|
26
|
+
storage in your Expo app:
|
|
24
27
|
|
|
25
28
|
```bash
|
|
26
29
|
npm install expo-secure-store
|
|
@@ -36,24 +39,26 @@ bun add expo-secure-store
|
|
|
36
39
|
|
|
37
40
|
### Configure the Better Auth Backend
|
|
38
41
|
|
|
39
|
-
Ensure you have a Better Auth backend set up.
|
|
42
|
+
Ensure you have a Better Auth backend set up.
|
|
43
|
+
You can follow the main [Installation Guide][].
|
|
40
44
|
|
|
41
|
-
Then, add the Expo plugin to your Better Auth server configuration (e.g., in
|
|
45
|
+
Then, add the Expo plugin to your Better Auth server configuration (e.g., in
|
|
46
|
+
your `auth.ts` or `lib/auth.ts` file):
|
|
42
47
|
|
|
43
48
|
```typescript
|
|
44
49
|
// lib/auth.ts
|
|
45
|
-
import { betterAuth } from
|
|
46
|
-
import { expo } from
|
|
50
|
+
import { betterAuth } from 'better-auth';
|
|
51
|
+
import { expo } from '@better-auth/expo'; // Import the server plugin
|
|
47
52
|
|
|
48
53
|
export const auth = betterAuth({
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
54
|
+
// ...your other Better Auth options
|
|
55
|
+
baseURL: 'http://localhost:8081', // The base URL of your application server where the routes are mounted.
|
|
56
|
+
plugins: [expo()], // Add the Expo server plugin
|
|
57
|
+
emailAndPassword: {
|
|
58
|
+
enabled: true,
|
|
59
|
+
},
|
|
60
|
+
// Add other configurations like trustedOrigins
|
|
61
|
+
trustedOrigins: ['myapp://'], // Replace "myapp" with your app's scheme
|
|
57
62
|
});
|
|
58
63
|
```
|
|
59
64
|
|
|
@@ -63,33 +68,39 @@ In your Expo app, initialize the client (e.g., in `lib/auth-client.ts`):
|
|
|
63
68
|
|
|
64
69
|
```typescript
|
|
65
70
|
// lib/auth-client.ts
|
|
66
|
-
import { createAuthClient } from
|
|
67
|
-
import { expoClient } from
|
|
68
|
-
import * as SecureStore from
|
|
71
|
+
import { createAuthClient } from 'better-auth/react';
|
|
72
|
+
import { expoClient } from '@better-auth/expo/client'; // Import the client plugin
|
|
73
|
+
import * as SecureStore from 'expo-secure-store';
|
|
69
74
|
|
|
70
75
|
export const authClient = createAuthClient({
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
76
|
+
baseURL: 'http://localhost:8081', // Your Better Auth backend URL
|
|
77
|
+
plugins: [
|
|
78
|
+
expoClient({
|
|
79
|
+
scheme: 'myapp', // Your app's scheme (defined in app.json)
|
|
80
|
+
storagePrefix: 'myapp', // A prefix for storage keys
|
|
81
|
+
storage: SecureStore, // Pass SecureStore for token storage
|
|
82
|
+
}),
|
|
83
|
+
],
|
|
79
84
|
});
|
|
80
85
|
|
|
81
86
|
// You can also export specific methods if you prefer:
|
|
82
87
|
// export const { signIn, signUp, useSession } = authClient;
|
|
83
88
|
```
|
|
84
|
-
|
|
89
|
+
|
|
90
|
+
Make sure your app’s scheme (e.g., “myapp”) is defined in your `app.json`.
|
|
85
91
|
|
|
86
92
|
## Documentation
|
|
87
93
|
|
|
88
|
-
For more detailed information and advanced configurations, please refer to the
|
|
94
|
+
For more detailed information and advanced configurations, please refer to the
|
|
95
|
+
documentation:
|
|
89
96
|
|
|
90
|
-
|
|
91
|
-
|
|
97
|
+
* **Main Better Auth Installation:** [Installation Guide][]
|
|
98
|
+
* **Expo Integration Guide:** [Expo Integration Guide][]
|
|
92
99
|
|
|
93
100
|
## License
|
|
94
101
|
|
|
95
102
|
MIT
|
|
103
|
+
|
|
104
|
+
[expo integration guide]: https://www.better-auth.com/docs/integrations/expo
|
|
105
|
+
|
|
106
|
+
[installation guide]: https://www.better-auth.com/docs/installation
|
package/dist/client.d.mts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { parseSetCookieHeader } from "better-auth/cookies";
|
|
1
2
|
import { FocusManager, OnlineManager } from "better-auth/client";
|
|
3
|
+
import * as expo_web_browser0 from "expo-web-browser";
|
|
2
4
|
import * as _better_fetch_fetch0 from "@better-fetch/fetch";
|
|
3
5
|
import { ClientFetchOption, ClientStore } from "@better-auth/core";
|
|
4
6
|
|
|
@@ -9,17 +11,6 @@ declare function setupExpoFocusManager(): FocusManager;
|
|
|
9
11
|
declare function setupExpoOnlineManager(): OnlineManager;
|
|
10
12
|
//#endregion
|
|
11
13
|
//#region src/client.d.ts
|
|
12
|
-
interface CookieAttributes {
|
|
13
|
-
value: string;
|
|
14
|
-
expires?: Date | undefined;
|
|
15
|
-
"max-age"?: number | undefined;
|
|
16
|
-
domain?: string | undefined;
|
|
17
|
-
path?: string | undefined;
|
|
18
|
-
secure?: boolean | undefined;
|
|
19
|
-
httpOnly?: boolean | undefined;
|
|
20
|
-
sameSite?: ("Strict" | "Lax" | "None") | undefined;
|
|
21
|
-
}
|
|
22
|
-
declare function parseSetCookieHeader(header: string): Map<string, CookieAttributes>;
|
|
23
14
|
interface ExpoClientOptions {
|
|
24
15
|
scheme?: string | undefined;
|
|
25
16
|
storage: {
|
|
@@ -42,6 +33,26 @@ interface ExpoClientOptions {
|
|
|
42
33
|
*/
|
|
43
34
|
cookiePrefix?: string | string[] | undefined;
|
|
44
35
|
disableCache?: boolean | undefined;
|
|
36
|
+
/**
|
|
37
|
+
* Options to customize the Expo web browser behavior when opening authentication
|
|
38
|
+
* sessions. These are passed directly to `expo-web-browser`'s
|
|
39
|
+
* `Browser.openBrowserAsync`.
|
|
40
|
+
*
|
|
41
|
+
* For example, on iOS you can use `{ preferEphemeralSession: true }` to prevent
|
|
42
|
+
* the authentication session from sharing cookies with the user's default
|
|
43
|
+
* browser session:
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const client = createClient({
|
|
47
|
+
* expo: {
|
|
48
|
+
* webBrowserOptions: {
|
|
49
|
+
* preferEphemeralSession: true,
|
|
50
|
+
* },
|
|
51
|
+
* },
|
|
52
|
+
* });
|
|
53
|
+
* ```
|
|
54
|
+
*/
|
|
55
|
+
webBrowserOptions?: expo_web_browser0.AuthSessionOpenOptions;
|
|
45
56
|
}
|
|
46
57
|
declare function getSetCookie(header: string, prevCookie?: string | undefined): string;
|
|
47
58
|
declare function getCookie(cookie: string): string;
|
|
@@ -112,6 +123,7 @@ declare const expoClient: (opts: ExpoClientOptions) => {
|
|
|
112
123
|
authorization: "Bearer" | "Basic";
|
|
113
124
|
})) | undefined;
|
|
114
125
|
redirect?: RequestRedirect | undefined;
|
|
126
|
+
window?: null | undefined;
|
|
115
127
|
cache?: RequestCache | undefined;
|
|
116
128
|
credentials?: RequestCredentials | undefined;
|
|
117
129
|
integrity?: string | undefined;
|
|
@@ -121,7 +133,6 @@ declare const expoClient: (opts: ExpoClientOptions) => {
|
|
|
121
133
|
referrer?: string | undefined;
|
|
122
134
|
referrerPolicy?: ReferrerPolicy | undefined;
|
|
123
135
|
signal?: (AbortSignal | null) | undefined;
|
|
124
|
-
window?: null | undefined;
|
|
125
136
|
onRequest?: (<T extends Record<string, any>>(context: _better_fetch_fetch0.RequestContext<T>) => Promise<_better_fetch_fetch0.RequestContext | void> | _better_fetch_fetch0.RequestContext | void) | undefined;
|
|
126
137
|
onResponse?: ((context: _better_fetch_fetch0.ResponseContext) => Promise<Response | void | _better_fetch_fetch0.ResponseContext> | Response | _better_fetch_fetch0.ResponseContext | void) | undefined;
|
|
127
138
|
onSuccess?: ((context: _better_fetch_fetch0.SuccessContext<any>) => Promise<void> | void) | undefined;
|
|
@@ -164,4 +175,5 @@ declare const expoClient: (opts: ExpoClientOptions) => {
|
|
|
164
175
|
}[];
|
|
165
176
|
};
|
|
166
177
|
//#endregion
|
|
167
|
-
export { expoClient, getCookie, getSetCookie, hasBetterAuthCookies, normalizeCookieName, parseSetCookieHeader, setupExpoFocusManager, setupExpoOnlineManager, storageAdapter };
|
|
178
|
+
export { expoClient, getCookie, getSetCookie, hasBetterAuthCookies, normalizeCookieName, parseSetCookieHeader, setupExpoFocusManager, setupExpoOnlineManager, storageAdapter };
|
|
179
|
+
//# sourceMappingURL=client.d.mts.map
|
package/dist/client.mjs
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { safeJSONParse } from "@better-auth/core/utils/json";
|
|
2
|
+
import { SECURE_COOKIE_PREFIX, parseSetCookieHeader, parseSetCookieHeader as parseSetCookieHeader$1, stripSecureCookiePrefix } from "better-auth/cookies";
|
|
1
3
|
import Constants from "expo-constants";
|
|
2
4
|
import * as Linking from "expo-linking";
|
|
3
5
|
import { AppState, Platform } from "react-native";
|
|
@@ -7,6 +9,7 @@ import { kFocusManager, kOnlineManager } from "better-auth/client";
|
|
|
7
9
|
var ExpoFocusManager = class {
|
|
8
10
|
listeners = /* @__PURE__ */ new Set();
|
|
9
11
|
subscription;
|
|
12
|
+
isFocused;
|
|
10
13
|
subscribe(listener) {
|
|
11
14
|
this.listeners.add(listener);
|
|
12
15
|
return () => {
|
|
@@ -14,6 +17,8 @@ var ExpoFocusManager = class {
|
|
|
14
17
|
};
|
|
15
18
|
}
|
|
16
19
|
setFocused(focused) {
|
|
20
|
+
if (this.isFocused === focused) return;
|
|
21
|
+
this.isFocused = focused;
|
|
17
22
|
this.listeners.forEach((listener) => listener(focused));
|
|
18
23
|
}
|
|
19
24
|
setup() {
|
|
@@ -43,6 +48,7 @@ var ExpoOnlineManager = class {
|
|
|
43
48
|
};
|
|
44
49
|
}
|
|
45
50
|
setOnline(online) {
|
|
51
|
+
if (this.isOnline === online) return;
|
|
46
52
|
this.isOnline = online;
|
|
47
53
|
this.listeners.forEach((listener) => listener(online));
|
|
48
54
|
}
|
|
@@ -71,52 +77,8 @@ if (Platform.OS !== "web") {
|
|
|
71
77
|
setupExpoFocusManager();
|
|
72
78
|
setupExpoOnlineManager();
|
|
73
79
|
}
|
|
74
|
-
function parseSetCookieHeader(header) {
|
|
75
|
-
const cookieMap = /* @__PURE__ */ new Map();
|
|
76
|
-
splitSetCookieHeader(header).forEach((cookie) => {
|
|
77
|
-
const [nameValue, ...attributes] = cookie.split(";").map((p) => p.trim());
|
|
78
|
-
const [name, ...valueParts] = nameValue.split("=");
|
|
79
|
-
const cookieObj = { value: valueParts.join("=") };
|
|
80
|
-
attributes.forEach((attr) => {
|
|
81
|
-
const [attrName, ...attrValueParts] = attr.split("=");
|
|
82
|
-
const attrValue = attrValueParts.join("=");
|
|
83
|
-
cookieObj[attrName.toLowerCase()] = attrValue;
|
|
84
|
-
});
|
|
85
|
-
cookieMap.set(name, cookieObj);
|
|
86
|
-
});
|
|
87
|
-
return cookieMap;
|
|
88
|
-
}
|
|
89
|
-
function splitSetCookieHeader(setCookie) {
|
|
90
|
-
const parts = [];
|
|
91
|
-
let buffer = "";
|
|
92
|
-
let i = 0;
|
|
93
|
-
while (i < setCookie.length) {
|
|
94
|
-
const char = setCookie[i];
|
|
95
|
-
if (char === ",") {
|
|
96
|
-
const recent = buffer.toLowerCase();
|
|
97
|
-
const hasExpires = recent.includes("expires=");
|
|
98
|
-
const hasGmt = /gmt/i.test(recent);
|
|
99
|
-
if (hasExpires && !hasGmt) {
|
|
100
|
-
buffer += char;
|
|
101
|
-
i += 1;
|
|
102
|
-
continue;
|
|
103
|
-
}
|
|
104
|
-
if (buffer.trim().length > 0) {
|
|
105
|
-
parts.push(buffer.trim());
|
|
106
|
-
buffer = "";
|
|
107
|
-
}
|
|
108
|
-
i += 1;
|
|
109
|
-
if (setCookie[i] === " ") i += 1;
|
|
110
|
-
continue;
|
|
111
|
-
}
|
|
112
|
-
buffer += char;
|
|
113
|
-
i += 1;
|
|
114
|
-
}
|
|
115
|
-
if (buffer.trim().length > 0) parts.push(buffer.trim());
|
|
116
|
-
return parts;
|
|
117
|
-
}
|
|
118
80
|
function getSetCookie(header, prevCookie) {
|
|
119
|
-
const parsed = parseSetCookieHeader(header);
|
|
81
|
+
const parsed = parseSetCookieHeader$1(header);
|
|
120
82
|
let toSetCookie = {};
|
|
121
83
|
parsed.forEach((cookie, key) => {
|
|
122
84
|
const expiresAt = cookie["expires"];
|
|
@@ -145,6 +107,20 @@ function getCookie(cookie) {
|
|
|
145
107
|
return `${acc}; ${key}=${value.value}`;
|
|
146
108
|
}, "");
|
|
147
109
|
}
|
|
110
|
+
function getOAuthStateValue(cookieJson, cookiePrefix) {
|
|
111
|
+
if (!cookieJson) return null;
|
|
112
|
+
const parsed = safeJSONParse(cookieJson);
|
|
113
|
+
if (!parsed) return null;
|
|
114
|
+
const prefixes = Array.isArray(cookiePrefix) ? cookiePrefix : [cookiePrefix];
|
|
115
|
+
for (const prefix of prefixes) {
|
|
116
|
+
const candidates = [`${SECURE_COOKIE_PREFIX}${prefix}.oauth_state`, `${prefix}.oauth_state`];
|
|
117
|
+
for (const name of candidates) {
|
|
118
|
+
const value = parsed?.[name]?.value;
|
|
119
|
+
if (value) return value;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
148
124
|
function getOrigin(scheme) {
|
|
149
125
|
return Linking.createURL("", { scheme });
|
|
150
126
|
}
|
|
@@ -190,11 +166,11 @@ function hasSessionCookieChanged(prevCookie, newCookie) {
|
|
|
190
166
|
* @returns true if the header contains better-auth cookies, false otherwise
|
|
191
167
|
*/
|
|
192
168
|
function hasBetterAuthCookies(setCookieHeader, cookiePrefix) {
|
|
193
|
-
const cookies = parseSetCookieHeader(setCookieHeader);
|
|
169
|
+
const cookies = parseSetCookieHeader$1(setCookieHeader);
|
|
194
170
|
const cookieSuffixes = ["session_token", "session_data"];
|
|
195
171
|
const prefixes = Array.isArray(cookiePrefix) ? cookiePrefix : [cookiePrefix];
|
|
196
172
|
for (const name of cookies.keys()) {
|
|
197
|
-
const nameWithoutSecure =
|
|
173
|
+
const nameWithoutSecure = stripSecureCookiePrefix(name);
|
|
198
174
|
for (const prefix of prefixes) if (prefix) {
|
|
199
175
|
if (nameWithoutSecure.startsWith(prefix)) return true;
|
|
200
176
|
} else for (const suffix of cookieSuffixes) if (nameWithoutSecure.endsWith(suffix)) return true;
|
|
@@ -250,12 +226,12 @@ const expoClient = (opts) => {
|
|
|
250
226
|
const setCookie = context.response.headers.get("set-cookie");
|
|
251
227
|
if (setCookie) {
|
|
252
228
|
if (hasBetterAuthCookies(setCookie, cookiePrefix)) {
|
|
253
|
-
const prevCookie =
|
|
229
|
+
const prevCookie = storage.getItem(cookieName);
|
|
254
230
|
const toSetCookie = getSetCookie(setCookie || "", prevCookie ?? void 0);
|
|
255
231
|
if (hasSessionCookieChanged(prevCookie, toSetCookie)) {
|
|
256
232
|
storage.setItem(cookieName, toSetCookie);
|
|
257
233
|
store?.notify("$sessionSignal");
|
|
258
|
-
} else
|
|
234
|
+
} else storage.setItem(cookieName, toSetCookie);
|
|
259
235
|
}
|
|
260
236
|
}
|
|
261
237
|
if (context.request.url.toString().includes("/get-session") && !opts?.disableCache) {
|
|
@@ -274,13 +250,15 @@ const expoClient = (opts) => {
|
|
|
274
250
|
if (Platform.OS === "android") try {
|
|
275
251
|
Browser.dismissAuthSession();
|
|
276
252
|
} catch {}
|
|
277
|
-
const
|
|
278
|
-
const
|
|
253
|
+
const oauthStateValue = getOAuthStateValue(storage.getItem(cookieName), cookiePrefix);
|
|
254
|
+
const params = new URLSearchParams({ authorizationURL: signInURL });
|
|
255
|
+
if (oauthStateValue) params.append("oauthState", oauthStateValue);
|
|
256
|
+
const proxyURL = `${context.request.baseURL}/expo-authorization-proxy?${params.toString()}`;
|
|
257
|
+
const result = await Browser.openAuthSessionAsync(proxyURL, to, opts?.webBrowserOptions);
|
|
279
258
|
if (result.type !== "success") return;
|
|
280
|
-
const
|
|
281
|
-
const cookie = String(url.searchParams.get("cookie"));
|
|
259
|
+
const cookie = new URL(result.url).searchParams.get("cookie");
|
|
282
260
|
if (!cookie) return;
|
|
283
|
-
const toSetCookie = getSetCookie(cookie,
|
|
261
|
+
const toSetCookie = getSetCookie(cookie, storage.getItem(cookieName) ?? void 0);
|
|
284
262
|
storage.setItem(cookieName, toSetCookie);
|
|
285
263
|
store?.notify("$sessionSignal");
|
|
286
264
|
}
|
|
@@ -301,24 +279,24 @@ const expoClient = (opts) => {
|
|
|
301
279
|
};
|
|
302
280
|
if (options.body?.callbackURL) {
|
|
303
281
|
if (options.body.callbackURL.startsWith("/")) {
|
|
304
|
-
const url
|
|
305
|
-
options.body.callbackURL = url
|
|
282
|
+
const url = Linking.createURL(options.body.callbackURL, { scheme });
|
|
283
|
+
options.body.callbackURL = url;
|
|
306
284
|
}
|
|
307
285
|
}
|
|
308
286
|
if (options.body?.newUserCallbackURL) {
|
|
309
287
|
if (options.body.newUserCallbackURL.startsWith("/")) {
|
|
310
|
-
const url
|
|
311
|
-
options.body.newUserCallbackURL = url
|
|
288
|
+
const url = Linking.createURL(options.body.newUserCallbackURL, { scheme });
|
|
289
|
+
options.body.newUserCallbackURL = url;
|
|
312
290
|
}
|
|
313
291
|
}
|
|
314
292
|
if (options.body?.errorCallbackURL) {
|
|
315
293
|
if (options.body.errorCallbackURL.startsWith("/")) {
|
|
316
|
-
const url
|
|
317
|
-
options.body.errorCallbackURL = url
|
|
294
|
+
const url = Linking.createURL(options.body.errorCallbackURL, { scheme });
|
|
295
|
+
options.body.errorCallbackURL = url;
|
|
318
296
|
}
|
|
319
297
|
}
|
|
320
298
|
if (url.includes("/sign-out")) {
|
|
321
|
-
|
|
299
|
+
storage.setItem(cookieName, "{}");
|
|
322
300
|
store?.atoms.session?.set({
|
|
323
301
|
...store.atoms.session.get(),
|
|
324
302
|
data: null,
|
|
@@ -337,4 +315,5 @@ const expoClient = (opts) => {
|
|
|
337
315
|
};
|
|
338
316
|
|
|
339
317
|
//#endregion
|
|
340
|
-
export { expoClient, getCookie, getSetCookie, hasBetterAuthCookies, normalizeCookieName, parseSetCookieHeader, setupExpoFocusManager, setupExpoOnlineManager, storageAdapter };
|
|
318
|
+
export { expoClient, getCookie, getSetCookie, hasBetterAuthCookies, normalizeCookieName, parseSetCookieHeader, setupExpoFocusManager, setupExpoOnlineManager, storageAdapter };
|
|
319
|
+
//# sourceMappingURL=client.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.mjs","names":["parseSetCookieHeader"],"sources":["../src/focus-manager.ts","../src/online-manager.ts","../src/client.ts"],"sourcesContent":["import type { FocusListener, FocusManager } from \"better-auth/client\";\nimport { kFocusManager } from \"better-auth/client\";\nimport type { AppStateStatus } from \"react-native\";\nimport { AppState } from \"react-native\";\n\nclass ExpoFocusManager implements FocusManager {\n\tlisteners = new Set<FocusListener>();\n\tsubscription?: ReturnType<typeof AppState.addEventListener>;\n\tisFocused: boolean | undefined;\n\n\tsubscribe(listener: FocusListener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tsetFocused(focused: boolean) {\n\t\tif (this.isFocused === focused) return;\n\t\tthis.isFocused = focused;\n\t\tthis.listeners.forEach((listener) => listener(focused));\n\t}\n\n\tsetup() {\n\t\tthis.subscription = AppState.addEventListener(\n\t\t\t\"change\",\n\t\t\t(state: AppStateStatus) => {\n\t\t\t\tthis.setFocused(state === \"active\");\n\t\t\t},\n\t\t);\n\n\t\treturn () => {\n\t\t\tthis.subscription?.remove();\n\t\t};\n\t}\n}\n\nexport function setupExpoFocusManager() {\n\tif (!(globalThis as any)[kFocusManager]) {\n\t\t(globalThis as any)[kFocusManager] = new ExpoFocusManager();\n\t}\n\treturn (globalThis as any)[kFocusManager] as FocusManager;\n}\n","import type { OnlineListener, OnlineManager } from \"better-auth/client\";\nimport { kOnlineManager } from \"better-auth/client\";\n\nclass ExpoOnlineManager implements OnlineManager {\n\tlisteners = new Set<OnlineListener>();\n\tisOnline = true;\n\tunsubscribe?: () => void;\n\n\tsubscribe(listener: OnlineListener) {\n\t\tthis.listeners.add(listener);\n\t\treturn () => {\n\t\t\tthis.listeners.delete(listener);\n\t\t};\n\t}\n\n\tsetOnline(online: boolean) {\n\t\tif (this.isOnline === online) return;\n\t\tthis.isOnline = online;\n\t\tthis.listeners.forEach((listener) => listener(online));\n\t}\n\n\tsetup() {\n\t\timport(\"expo-network\")\n\t\t\t.then(({ addNetworkStateListener }) => {\n\t\t\t\tconst subscription = addNetworkStateListener((state) => {\n\t\t\t\t\tthis.setOnline(!!state.isInternetReachable);\n\t\t\t\t});\n\t\t\t\tthis.unsubscribe = () => subscription.remove();\n\t\t\t})\n\t\t\t.catch(() => {\n\t\t\t\t// fallback to always online\n\t\t\t\tthis.setOnline(true);\n\t\t\t});\n\n\t\treturn () => {\n\t\t\tthis.unsubscribe?.();\n\t\t};\n\t}\n}\n\nexport function setupExpoOnlineManager() {\n\tif (!(globalThis as any)[kOnlineManager]) {\n\t\t(globalThis as any)[kOnlineManager] = new ExpoOnlineManager();\n\t}\n\treturn (globalThis as any)[kOnlineManager] as OnlineManager;\n}\n","import type {\n\tBetterAuthClientPlugin,\n\tClientFetchOption,\n\tClientStore,\n} from \"@better-auth/core\";\nimport { safeJSONParse } from \"@better-auth/core/utils/json\";\nimport {\n\tparseSetCookieHeader,\n\tSECURE_COOKIE_PREFIX,\n\tstripSecureCookiePrefix,\n} from \"better-auth/cookies\";\nimport Constants from \"expo-constants\";\nimport * as Linking from \"expo-linking\";\nimport { Platform } from \"react-native\";\nimport { setupExpoFocusManager } from \"./focus-manager\";\nimport { setupExpoOnlineManager } from \"./online-manager\";\n\nif (Platform.OS !== \"web\") {\n\tsetupExpoFocusManager();\n\tsetupExpoOnlineManager();\n}\n\ninterface ExpoClientOptions {\n\tscheme?: string | undefined;\n\tstorage: {\n\t\tsetItem: (key: string, value: string) => any;\n\t\tgetItem: (key: string) => string | null;\n\t};\n\t/**\n\t * Prefix for local storage keys (e.g., \"my-app_cookie\", \"my-app_session_data\")\n\t * @default \"better-auth\"\n\t */\n\tstoragePrefix?: string | undefined;\n\t/**\n\t * Prefix(es) for server cookie names to filter (e.g., \"better-auth.session_token\")\n\t * This is used to identify which cookies belong to better-auth to prevent\n\t * infinite refetching when third-party cookies are set.\n\t * Can be a single string or an array of strings to match multiple prefixes.\n\t * @default \"better-auth\"\n\t * @example \"better-auth\"\n\t * @example [\"better-auth\", \"my-app\"]\n\t */\n\tcookiePrefix?: string | string[] | undefined;\n\tdisableCache?: boolean | undefined;\n\t/**\n\t * Options to customize the Expo web browser behavior when opening authentication\n\t * sessions. These are passed directly to `expo-web-browser`'s\n\t * `Browser.openBrowserAsync`.\n\t *\n\t * For example, on iOS you can use `{ preferEphemeralSession: true }` to prevent\n\t * the authentication session from sharing cookies with the user's default\n\t * browser session:\n\t *\n\t * ```ts\n\t * const client = createClient({\n\t * expo: {\n\t * webBrowserOptions: {\n\t * preferEphemeralSession: true,\n\t * },\n\t * },\n\t * });\n\t * ```\n\t */\n\twebBrowserOptions?: import(\"expo-web-browser\").AuthSessionOpenOptions;\n}\n\ninterface StoredCookie {\n\tvalue: string;\n\texpires: string | null;\n}\n\nexport function getSetCookie(header: string, prevCookie?: string | undefined) {\n\tconst parsed = parseSetCookieHeader(header);\n\tlet toSetCookie: Record<string, StoredCookie> = {};\n\tparsed.forEach((cookie, key) => {\n\t\tconst expiresAt = cookie[\"expires\"];\n\t\tconst maxAge = cookie[\"max-age\"];\n\t\tconst expires = maxAge\n\t\t\t? new Date(Date.now() + Number(maxAge) * 1000)\n\t\t\t: expiresAt\n\t\t\t\t? new Date(String(expiresAt))\n\t\t\t\t: null;\n\t\ttoSetCookie[key] = {\n\t\t\tvalue: cookie[\"value\"],\n\t\t\texpires: expires ? expires.toISOString() : null,\n\t\t};\n\t});\n\tif (prevCookie) {\n\t\ttry {\n\t\t\tconst prevCookieParsed = JSON.parse(prevCookie);\n\t\t\ttoSetCookie = {\n\t\t\t\t...prevCookieParsed,\n\t\t\t\t...toSetCookie,\n\t\t\t};\n\t\t} catch {\n\t\t\t//\n\t\t}\n\t}\n\treturn JSON.stringify(toSetCookie);\n}\n\nexport function getCookie(cookie: string) {\n\tlet parsed = {} as Record<string, StoredCookie>;\n\ttry {\n\t\tparsed = JSON.parse(cookie) as Record<string, StoredCookie>;\n\t} catch {}\n\tconst toSend = Object.entries(parsed).reduce((acc, [key, value]) => {\n\t\tif (value.expires && new Date(value.expires) < new Date()) {\n\t\t\treturn acc;\n\t\t}\n\t\treturn `${acc}; ${key}=${value.value}`;\n\t}, \"\");\n\treturn toSend;\n}\n\nfunction getOAuthStateValue(\n\tcookieJson: string | null,\n\tcookiePrefix: string | string[],\n): string | null {\n\tif (!cookieJson) return null;\n\n\tconst parsed = safeJSONParse<Record<string, StoredCookie>>(cookieJson);\n\tif (!parsed) return null;\n\n\tconst prefixes = Array.isArray(cookiePrefix) ? cookiePrefix : [cookiePrefix];\n\n\tfor (const prefix of prefixes) {\n\t\t// cookie strategy uses: <prefix>.oauth_state\n\t\tconst candidates = [\n\t\t\t`${SECURE_COOKIE_PREFIX}${prefix}.oauth_state`,\n\t\t\t`${prefix}.oauth_state`,\n\t\t];\n\n\t\tfor (const name of candidates) {\n\t\t\tconst value = parsed?.[name]?.value;\n\t\t\tif (value) return value;\n\t\t}\n\t}\n\n\treturn null;\n}\n\nfunction getOrigin(scheme: string) {\n\tconst schemeURI = Linking.createURL(\"\", { scheme });\n\treturn schemeURI;\n}\n\n/**\n * Compare if session cookies have actually changed by comparing their values.\n * Ignores expiry timestamps that naturally change on each request.\n *\n * @param prevCookie - Previous cookie JSON string\n * @param newCookie - New cookie JSON string\n * @returns true if session cookies have changed, false otherwise\n */\nfunction hasSessionCookieChanged(\n\tprevCookie: string | null,\n\tnewCookie: string,\n): boolean {\n\tif (!prevCookie) return true;\n\n\ttry {\n\t\tconst prev = JSON.parse(prevCookie) as Record<string, StoredCookie>;\n\t\tconst next = JSON.parse(newCookie) as Record<string, StoredCookie>;\n\n\t\t// Get all session-related cookie keys (session_token, session_data)\n\t\tconst sessionKeys = new Set<string>();\n\t\tObject.keys(prev).forEach((key) => {\n\t\t\tif (key.includes(\"session_token\") || key.includes(\"session_data\")) {\n\t\t\t\tsessionKeys.add(key);\n\t\t\t}\n\t\t});\n\t\tObject.keys(next).forEach((key) => {\n\t\t\tif (key.includes(\"session_token\") || key.includes(\"session_data\")) {\n\t\t\t\tsessionKeys.add(key);\n\t\t\t}\n\t\t});\n\n\t\t// Compare the values of session cookies (ignore expires timestamps)\n\t\tfor (const key of sessionKeys) {\n\t\t\tconst prevValue = prev[key]?.value;\n\t\t\tconst nextValue = next[key]?.value;\n\t\t\tif (prevValue !== nextValue) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t} catch {\n\t\t// If parsing fails, assume cookie changed\n\t\treturn true;\n\t}\n}\n\n/**\n * Check if the Set-Cookie header contains better-auth cookies.\n * This prevents infinite refetching when non-better-auth cookies (like third-party cookies) change.\n *\n * Supports multiple cookie naming patterns:\n * - Default: \"better-auth.session_token\", \"better-auth-passkey\", \"__Secure-better-auth.session_token\"\n * - Custom prefix: \"myapp.session_token\", \"myapp-passkey\", \"__Secure-myapp.session_token\"\n * - Custom full names: \"my_custom_session_token\", \"custom_session_data\"\n * - No prefix (cookiePrefix=\"\"): matches any cookie with known suffixes\n * - Multiple prefixes: [\"better-auth\", \"my-app\"] matches cookies starting with any of the prefixes\n *\n * @param setCookieHeader - The Set-Cookie header value\n * @param cookiePrefix - The cookie prefix(es) to check for. Can be a string, array of strings, or empty string.\n * @returns true if the header contains better-auth cookies, false otherwise\n */\nexport function hasBetterAuthCookies(\n\tsetCookieHeader: string,\n\tcookiePrefix: string | string[],\n): boolean {\n\tconst cookies = parseSetCookieHeader(setCookieHeader);\n\tconst cookieSuffixes = [\"session_token\", \"session_data\"];\n\tconst prefixes = Array.isArray(cookiePrefix) ? cookiePrefix : [cookiePrefix];\n\n\t// Check if any cookie is a better-auth cookie\n\tfor (const name of cookies.keys()) {\n\t\t// Remove __Secure- prefix if present for comparison\n\t\tconst nameWithoutSecure = stripSecureCookiePrefix(name);\n\n\t\t// Check against all provided prefixes\n\t\tfor (const prefix of prefixes) {\n\t\t\tif (prefix) {\n\t\t\t\t// When prefix is provided, check if cookie starts with the prefix\n\t\t\t\t// This matches all better-auth cookies including session cookies, passkey cookies, etc.\n\t\t\t\tif (nameWithoutSecure.startsWith(prefix)) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// When prefix is empty, check for common better-auth cookie patterns\n\t\t\t\tfor (const suffix of cookieSuffixes) {\n\t\t\t\t\tif (nameWithoutSecure.endsWith(suffix)) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Expo secure store does not support colons in the keys.\n * This function replaces colons with underscores.\n *\n * @see https://github.com/better-auth/better-auth/issues/5426\n *\n * @param name cookie name to be saved in the storage\n * @returns normalized cookie name\n */\nexport function normalizeCookieName(name: string) {\n\treturn name.replace(/:/g, \"_\");\n}\n\nexport function storageAdapter(storage: {\n\tgetItem: (name: string) => string | null;\n\tsetItem: (name: string, value: string) => void;\n}) {\n\treturn {\n\t\tgetItem: (name: string) => {\n\t\t\treturn storage.getItem(normalizeCookieName(name));\n\t\t},\n\t\tsetItem: (name: string, value: string) => {\n\t\t\treturn storage.setItem(normalizeCookieName(name), value);\n\t\t},\n\t};\n}\n\nexport const expoClient = (opts: ExpoClientOptions) => {\n\tlet store: ClientStore | null = null;\n\tconst storagePrefix = opts?.storagePrefix || \"better-auth\";\n\tconst cookieName = `${storagePrefix}_cookie`;\n\tconst localCacheName = `${storagePrefix}_session_data`;\n\tconst storage = storageAdapter(opts?.storage);\n\tconst isWeb = Platform.OS === \"web\";\n\tconst cookiePrefix = opts?.cookiePrefix || \"better-auth\";\n\n\tconst rawScheme =\n\t\topts?.scheme || Constants.expoConfig?.scheme || Constants.platform?.scheme;\n\tconst scheme = Array.isArray(rawScheme) ? rawScheme[0] : rawScheme;\n\n\tif (!scheme && !isWeb) {\n\t\tthrow new Error(\n\t\t\t\"Scheme not found in app.json. Please provide a scheme in the options.\",\n\t\t);\n\t}\n\treturn {\n\t\tid: \"expo\",\n\t\tgetActions(_, $store) {\n\t\t\tstore = $store;\n\t\t\treturn {\n\t\t\t\t/**\n\t\t\t\t * Get the stored cookie.\n\t\t\t\t *\n\t\t\t\t * You can use this to get the cookie stored in the device and use it in your fetch\n\t\t\t\t * requests.\n\t\t\t\t *\n\t\t\t\t * @example\n\t\t\t\t * ```ts\n\t\t\t\t * const cookie = client.getCookie();\n\t\t\t\t * fetch(\"https://api.example.com\", {\n\t\t\t\t * \theaders: {\n\t\t\t\t * \t\tcookie,\n\t\t\t\t * \t},\n\t\t\t\t * });\n\t\t\t\t */\n\t\t\t\tgetCookie: () => {\n\t\t\t\t\tconst cookie = storage.getItem(cookieName);\n\t\t\t\t\treturn getCookie(cookie || \"{}\");\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\tfetchPlugins: [\n\t\t\t{\n\t\t\t\tid: \"expo\",\n\t\t\t\tname: \"Expo\",\n\t\t\t\thooks: {\n\t\t\t\t\tasync onSuccess(context) {\n\t\t\t\t\t\tif (isWeb) return;\n\t\t\t\t\t\tconst setCookie = context.response.headers.get(\"set-cookie\");\n\t\t\t\t\t\tif (setCookie) {\n\t\t\t\t\t\t\t// Only process and notify if the Set-Cookie header contains better-auth cookies\n\t\t\t\t\t\t\t// This prevents infinite refetching when other cookies (like Cloudflare's __cf_bm) are present\n\t\t\t\t\t\t\tif (hasBetterAuthCookies(setCookie, cookiePrefix)) {\n\t\t\t\t\t\t\t\tconst prevCookie = storage.getItem(cookieName);\n\t\t\t\t\t\t\t\tconst toSetCookie = getSetCookie(\n\t\t\t\t\t\t\t\t\tsetCookie || \"\",\n\t\t\t\t\t\t\t\t\tprevCookie ?? undefined,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t// Only notify $sessionSignal if the session cookie values actually changed\n\t\t\t\t\t\t\t\t// This prevents infinite refetching when the server sends the same cookie with updated expiry\n\t\t\t\t\t\t\t\tif (hasSessionCookieChanged(prevCookie, toSetCookie)) {\n\t\t\t\t\t\t\t\t\tstorage.setItem(cookieName, toSetCookie);\n\t\t\t\t\t\t\t\t\tstore?.notify(\"$sessionSignal\");\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t// Still update the storage to refresh expiry times, but don't trigger refetch\n\t\t\t\t\t\t\t\t\tstorage.setItem(cookieName, toSetCookie);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tcontext.request.url.toString().includes(\"/get-session\") &&\n\t\t\t\t\t\t\t!opts?.disableCache\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst data = context.data;\n\t\t\t\t\t\t\tstorage.setItem(localCacheName, JSON.stringify(data));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (\n\t\t\t\t\t\t\tcontext.data?.redirect &&\n\t\t\t\t\t\t\t(context.request.url.toString().includes(\"/sign-in\") ||\n\t\t\t\t\t\t\t\tcontext.request.url.toString().includes(\"/link-social\")) &&\n\t\t\t\t\t\t\t!context.request?.body.includes(\"idToken\") // id token is used for silent sign-in\n\t\t\t\t\t\t) {\n\t\t\t\t\t\t\tconst callbackURL = JSON.parse(context.request.body)?.callbackURL;\n\t\t\t\t\t\t\tconst to = callbackURL;\n\t\t\t\t\t\t\tconst signInURL = context.data?.url;\n\t\t\t\t\t\t\tlet Browser: typeof import(\"expo-web-browser\") | undefined =\n\t\t\t\t\t\t\t\tundefined;\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\tBrowser = await import(\"expo-web-browser\");\n\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t\t\t'\"expo-web-browser\" is not installed as a dependency!',\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif (Platform.OS === \"android\") {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tBrowser.dismissAuthSession();\n\t\t\t\t\t\t\t\t} catch {}\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tconst storedCookieJson = storage.getItem(cookieName);\n\t\t\t\t\t\t\tconst oauthStateValue = getOAuthStateValue(\n\t\t\t\t\t\t\t\tstoredCookieJson,\n\t\t\t\t\t\t\t\tcookiePrefix,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst params = new URLSearchParams({\n\t\t\t\t\t\t\t\tauthorizationURL: signInURL,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (oauthStateValue) {\n\t\t\t\t\t\t\t\tparams.append(\"oauthState\", oauthStateValue);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tconst proxyURL = `${context.request.baseURL}/expo-authorization-proxy?${params.toString()}`;\n\t\t\t\t\t\t\tconst result = await Browser.openAuthSessionAsync(\n\t\t\t\t\t\t\t\tproxyURL,\n\t\t\t\t\t\t\t\tto,\n\t\t\t\t\t\t\t\topts?.webBrowserOptions,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (result.type !== \"success\") return;\n\t\t\t\t\t\t\tconst url = new URL(result.url);\n\t\t\t\t\t\t\tconst cookie = url.searchParams.get(\"cookie\");\n\t\t\t\t\t\t\tif (!cookie) return;\n\t\t\t\t\t\t\tconst prevCookie = storage.getItem(cookieName);\n\t\t\t\t\t\t\tconst toSetCookie = getSetCookie(cookie, prevCookie ?? undefined);\n\t\t\t\t\t\t\tstorage.setItem(cookieName, toSetCookie);\n\t\t\t\t\t\t\tstore?.notify(\"$sessionSignal\");\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tasync init(url, options) {\n\t\t\t\t\tif (isWeb) {\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\toptions: options as ClientFetchOption,\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t\toptions = options || {};\n\t\t\t\t\tconst storedCookie = storage.getItem(cookieName);\n\t\t\t\t\tconst cookie = getCookie(storedCookie || \"{}\");\n\t\t\t\t\toptions.credentials = \"omit\";\n\t\t\t\t\toptions.headers = {\n\t\t\t\t\t\t...options.headers,\n\t\t\t\t\t\tcookie,\n\t\t\t\t\t\t\"expo-origin\": getOrigin(scheme!),\n\t\t\t\t\t\t\"x-skip-oauth-proxy\": \"true\", // skip oauth proxy for expo\n\t\t\t\t\t};\n\t\t\t\t\tif (options.body?.callbackURL) {\n\t\t\t\t\t\tif (options.body.callbackURL.startsWith(\"/\")) {\n\t\t\t\t\t\t\tconst url = Linking.createURL(options.body.callbackURL, {\n\t\t\t\t\t\t\t\tscheme,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\toptions.body.callbackURL = url;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (options.body?.newUserCallbackURL) {\n\t\t\t\t\t\tif (options.body.newUserCallbackURL.startsWith(\"/\")) {\n\t\t\t\t\t\t\tconst url = Linking.createURL(options.body.newUserCallbackURL, {\n\t\t\t\t\t\t\t\tscheme,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\toptions.body.newUserCallbackURL = url;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (options.body?.errorCallbackURL) {\n\t\t\t\t\t\tif (options.body.errorCallbackURL.startsWith(\"/\")) {\n\t\t\t\t\t\t\tconst url = Linking.createURL(options.body.errorCallbackURL, {\n\t\t\t\t\t\t\t\tscheme,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\toptions.body.errorCallbackURL = url;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (url.includes(\"/sign-out\")) {\n\t\t\t\t\t\tstorage.setItem(cookieName, \"{}\");\n\t\t\t\t\t\tstore?.atoms.session?.set({\n\t\t\t\t\t\t\t...store.atoms.session.get(),\n\t\t\t\t\t\t\tdata: null,\n\t\t\t\t\t\t\terror: null,\n\t\t\t\t\t\t\tisPending: false,\n\t\t\t\t\t\t});\n\t\t\t\t\t\tstorage.setItem(localCacheName, \"{}\");\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\turl,\n\t\t\t\t\t\toptions: options as ClientFetchOption,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t} satisfies BetterAuthClientPlugin;\n};\n\nexport { parseSetCookieHeader } from \"better-auth/cookies\";\nexport * from \"./focus-manager\";\nexport * from \"./online-manager\";\n"],"mappings":";;;;;;;;AAKA,IAAM,mBAAN,M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M,aACjB;SAAI,QAAQ,KAAK,YAAY,WAAW,IAAI,EAAE;MAC7C,MAAM,MAAM,QAAQ,UAAU,QAAQ,KAAK,aAAa,EACvD,QACA,CAAC;AACF,cAAQ,KAAK,cAAc;;;AAG7B,QAAI,QAAQ,MAAM,oBACjB;SAAI,QAAQ,KAAK,mBAAmB,WAAW,IAAI,EAAE;MACpD,MAAM,MAAM,QAAQ,UAAU,QAAQ,KAAK,oBAAoB,EAC9D,QACA,CAAC;AACF,cAAQ,KAAK,qBAAqB;;;AAGpC,QAAI,QAAQ,MAAM,kBACjB;SAAI,QAAQ,KAAK,iBAAiB,WAAW,IAAI,EAAE;MAClD,MAAM,MAAM,QAAQ,UAAU,QAAQ,KAAK,kBAAkB,EAC5D,QACA,CAAC;AACF,cAAQ,KAAK,mBAAmB;;;AAGlC,QAAI,IAAI,SAAS,YAAY,EAAE;AAC9B,aAAQ,QAAQ,YAAY,KAAK;AACjC,YAAO,MAAM,SAAS,IAAI;MACzB,GAAG,MAAM,MAAM,QAAQ,KAAK;MAC5B,MAAM;MACN,OAAO;MACP,WAAW;MACX,CAAC;AACF,aAAQ,QAAQ,gBAAgB,KAAK;;AAEtC,WAAO;KACN;KACS;KACT;;GAEF,CACD;EACD"}
|
package/dist/index.d.mts
CHANGED
|
@@ -10,6 +10,13 @@ interface ExpoOptions {
|
|
|
10
10
|
*/
|
|
11
11
|
disableOriginOverride?: boolean | undefined;
|
|
12
12
|
}
|
|
13
|
+
declare module "@better-auth/core" {
|
|
14
|
+
interface BetterAuthPluginRegistry<AuthOptions, Options> {
|
|
15
|
+
expo: {
|
|
16
|
+
creator: typeof expo;
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
}
|
|
13
20
|
declare const expo: (options?: ExpoOptions | undefined) => {
|
|
14
21
|
id: "expo";
|
|
15
22
|
init: (ctx: better_auth0.AuthContext) => {
|
|
@@ -31,6 +38,7 @@ declare const expo: (options?: ExpoOptions | undefined) => {
|
|
|
31
38
|
method: "GET";
|
|
32
39
|
query: zod0.ZodObject<{
|
|
33
40
|
authorizationURL: zod0.ZodString;
|
|
41
|
+
oauthState: zod0.ZodOptional<zod0.ZodString>;
|
|
34
42
|
}, better_auth0.$strip>;
|
|
35
43
|
metadata: {
|
|
36
44
|
readonly scope: "server";
|
|
@@ -53,4 +61,5 @@ declare const expo: (options?: ExpoOptions | undefined) => {
|
|
|
53
61
|
options: ExpoOptions | undefined;
|
|
54
62
|
};
|
|
55
63
|
//#endregion
|
|
56
|
-
export { ExpoOptions, expo };
|
|
64
|
+
export { ExpoOptions, expo };
|
|
65
|
+
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -6,13 +6,22 @@ import * as z from "zod";
|
|
|
6
6
|
//#region src/routes.ts
|
|
7
7
|
const expoAuthorizationProxy = createAuthEndpoint("/expo-authorization-proxy", {
|
|
8
8
|
method: "GET",
|
|
9
|
-
query: z.object({
|
|
9
|
+
query: z.object({
|
|
10
|
+
authorizationURL: z.string(),
|
|
11
|
+
oauthState: z.string().optional()
|
|
12
|
+
}),
|
|
10
13
|
metadata: HIDE_METADATA
|
|
11
14
|
}, async (ctx) => {
|
|
15
|
+
const { oauthState } = ctx.query;
|
|
16
|
+
if (oauthState) {
|
|
17
|
+
const oauthStateCookie = ctx.context.createAuthCookie("oauth_state", { maxAge: 600 });
|
|
18
|
+
ctx.setCookie(oauthStateCookie.name, oauthState, oauthStateCookie.attributes);
|
|
19
|
+
return ctx.redirect(ctx.query.authorizationURL);
|
|
20
|
+
}
|
|
12
21
|
const { authorizationURL } = ctx.query;
|
|
13
22
|
const state = new URL(authorizationURL).searchParams.get("state");
|
|
14
23
|
if (!state) throw new APIError("BAD_REQUEST", { message: "Unexpected error" });
|
|
15
|
-
const stateCookie = ctx.context.createAuthCookie("state", { maxAge: 300
|
|
24
|
+
const stateCookie = ctx.context.createAuthCookie("state", { maxAge: 300 });
|
|
16
25
|
await ctx.setSignedCookie(stateCookie.name, state, ctx.context.secret, stateCookie.attributes);
|
|
17
26
|
return ctx.redirect(ctx.query.authorizationURL);
|
|
18
27
|
});
|
|
@@ -60,4 +69,5 @@ const expo = (options) => {
|
|
|
60
69
|
};
|
|
61
70
|
|
|
62
71
|
//#endregion
|
|
63
|
-
export { expo };
|
|
72
|
+
export { expo };
|
|
73
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/routes.ts","../src/index.ts"],"sourcesContent":["import { HIDE_METADATA } from \"better-auth\";\nimport { APIError, createAuthEndpoint } from \"better-auth/api\";\nimport * as z from \"zod\";\n\nexport const expoAuthorizationProxy = createAuthEndpoint(\n\t\"/expo-authorization-proxy\",\n\t{\n\t\tmethod: \"GET\",\n\t\tquery: z.object({\n\t\t\tauthorizationURL: z.string(),\n\t\t\toauthState: z.string().optional(),\n\t\t}),\n\t\tmetadata: HIDE_METADATA,\n\t},\n\tasync (ctx) => {\n\t\tconst { oauthState } = ctx.query;\n\t\tif (oauthState) {\n\t\t\tconst oauthStateCookie = ctx.context.createAuthCookie(\"oauth_state\", {\n\t\t\t\tmaxAge: 10 * 60, // 10 minutes\n\t\t\t});\n\t\t\tctx.setCookie(\n\t\t\t\toauthStateCookie.name,\n\t\t\t\toauthState,\n\t\t\t\toauthStateCookie.attributes,\n\t\t\t);\n\t\t\treturn ctx.redirect(ctx.query.authorizationURL);\n\t\t}\n\n\t\tconst { authorizationURL } = ctx.query;\n\t\tconst url = new URL(authorizationURL);\n\t\tconst state = url.searchParams.get(\"state\");\n\t\tif (!state) {\n\t\t\tthrow new APIError(\"BAD_REQUEST\", {\n\t\t\t\tmessage: \"Unexpected error\",\n\t\t\t});\n\t\t}\n\t\tconst stateCookie = ctx.context.createAuthCookie(\"state\", {\n\t\t\tmaxAge: 5 * 60, // 5 minutes\n\t\t});\n\t\tawait ctx.setSignedCookie(\n\t\t\tstateCookie.name,\n\t\t\tstate,\n\t\t\tctx.context.secret,\n\t\t\tstateCookie.attributes,\n\t\t);\n\t\treturn ctx.redirect(ctx.query.authorizationURL);\n\t},\n);\n","import type { BetterAuthPlugin } from \"@better-auth/core\";\nimport { createAuthMiddleware } from \"@better-auth/core/api\";\nimport { expoAuthorizationProxy } from \"./routes\";\n\nexport interface ExpoOptions {\n\t/**\n\t * Disable origin override for expo API routes\n\t * When set to true, the origin header will not be overridden for expo API routes\n\t */\n\tdisableOriginOverride?: boolean | undefined;\n}\n\ndeclare module \"@better-auth/core\" {\n\tinterface BetterAuthPluginRegistry<AuthOptions, Options> {\n\t\texpo: {\n\t\t\tcreator: typeof expo;\n\t\t};\n\t}\n}\n\nexport const expo = (options?: ExpoOptions | undefined) => {\n\treturn {\n\t\tid: \"expo\",\n\t\tinit: (ctx) => {\n\t\t\tconst trustedOrigins =\n\t\t\t\tprocess.env.NODE_ENV === \"development\" ? [\"exp://\"] : [];\n\n\t\t\treturn {\n\t\t\t\toptions: {\n\t\t\t\t\ttrustedOrigins,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\tasync onRequest(request, ctx) {\n\t\t\tif (options?.disableOriginOverride || request.headers.get(\"origin\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t/**\n\t\t\t * To bypass origin check from expo, we need to set the origin\n\t\t\t * header to the expo-origin header\n\t\t\t */\n\t\t\tconst expoOrigin = request.headers.get(\"expo-origin\");\n\t\t\tif (!expoOrigin) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst req = request.clone();\n\t\t\treq.headers.set(\"origin\", expoOrigin);\n\t\t\treturn {\n\t\t\t\trequest: req,\n\t\t\t};\n\t\t},\n\t\thooks: {\n\t\t\tafter: [\n\t\t\t\t{\n\t\t\t\t\tmatcher(context) {\n\t\t\t\t\t\treturn !!(\n\t\t\t\t\t\t\tcontext.path?.startsWith(\"/callback\") ||\n\t\t\t\t\t\t\tcontext.path?.startsWith(\"/oauth2/callback\") ||\n\t\t\t\t\t\t\tcontext.path?.startsWith(\"/magic-link/verify\") ||\n\t\t\t\t\t\t\tcontext.path?.startsWith(\"/verify-email\")\n\t\t\t\t\t\t);\n\t\t\t\t\t},\n\t\t\t\t\thandler: createAuthMiddleware(async (ctx) => {\n\t\t\t\t\t\tconst headers = ctx.context.responseHeaders;\n\t\t\t\t\t\tconst location = headers?.get(\"location\");\n\t\t\t\t\t\tif (!location) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst isProxyURL = location.includes(\"/oauth-proxy-callback\");\n\t\t\t\t\t\tif (isProxyURL) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst trustedOrigins = ctx.context.trustedOrigins.filter(\n\t\t\t\t\t\t\t(origin: string) => !origin.startsWith(\"http\"),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst isTrustedOrigin = trustedOrigins.some((origin: string) =>\n\t\t\t\t\t\t\tlocation?.startsWith(origin),\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!isTrustedOrigin) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst cookie = headers?.get(\"set-cookie\");\n\t\t\t\t\t\tif (!cookie) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst url = new URL(location);\n\t\t\t\t\t\turl.searchParams.set(\"cookie\", cookie);\n\t\t\t\t\t\tctx.setHeader(\"location\", url.toString());\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tendpoints: {\n\t\t\texpoAuthorizationProxy,\n\t\t},\n\t\toptions,\n\t} satisfies BetterAuthPlugin;\n};\n"],"mappings":";;;;;;AAIA,MAAa,yBAAyB,mBACrC,6BACA;CACC,QAAQ;CACR,OAAO,EAAE,OAAO;EACf,kBAAkB,EAAE,QAAQ;EAC5B,YAAY,EAAE,QAAQ,CAAC,UAAU;EACjC,CAAC;CACF,UAAU;CACV,EACD,OAAO,QAAQ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AAO,QAAQ;IAC5C,MAAM,UAAU,IAAI,QAAQ;IAC5B,MAAM,WAAW,SAAS,IAAI,WAAW;AACzC,QAAI,CAAC,SACJ;AAGD,QADmB,SAAS,SAAS,wBAAwB,CAE5D;AAQD,QAAI,CANmB,IAAI,QAAQ,eAAe,QAChD,WAAmB,CAAC,OAAO,WAAW,OAAO,CAC9C,CACsC,MAAM,WAC5C,UAAU,WAAW,OAAO,CAC5B,CAEA;IAED,MAAM,SAAS,SAAS,IAAI,aAAa;AACzC,QAAI,CAAC,OACJ;IAED,MAAM,MAAM,IAAI,IAAI,SAAS;AAC7B,QAAI,aAAa,IAAI,UAAU,OAAO;AACtC,QAAI,UAAU,YAAY,IAAI,UAAU,CAAC;KACxC;GACF,CACD,EACD;EACD,WAAW,EACV,wBACA;EACD;EACA"}
|
package/dist/plugins/index.d.mts
CHANGED
|
@@ -47,4 +47,5 @@ declare const lastLoginMethodClient: (config: LastLoginMethodClientConfig) => {
|
|
|
47
47
|
};
|
|
48
48
|
};
|
|
49
49
|
//#endregion
|
|
50
|
-
export { LastLoginMethodClientConfig, lastLoginMethodClient };
|
|
50
|
+
export { LastLoginMethodClientConfig, lastLoginMethodClient };
|
|
51
|
+
//# sourceMappingURL=index.d.mts.map
|
package/dist/plugins/index.mjs
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugins/last-login-method.ts"],"sourcesContent":["import type { Awaitable, BetterAuthClientPlugin } from \"@better-auth/core\";\n\nexport interface LastLoginMethodClientConfig {\n\tstorage: {\n\t\tsetItem: (key: string, value: string) => any;\n\t\tgetItem: (key: string) => string | null;\n\t\tdeleteItemAsync: (key: string) => Awaitable<void>;\n\t};\n\t/**\n\t * Prefix for local storage keys (e.g., \"my-app_last_login_method\")\n\t * @default \"better-auth\"\n\t */\n\tstoragePrefix?: string | undefined;\n\t/**\n\t * Custom resolve method for retrieving the last login method\n\t */\n\tcustomResolveMethod?:\n\t\t| ((url: string | URL) => Awaitable<string | undefined | null>)\n\t\t| undefined;\n}\n\nconst paths = [\n\t\"/callback/\",\n\t\"/oauth2/callback/\",\n\t\"/sign-in/email\",\n\t\"/sign-up/email\",\n];\nconst defaultResolveMethod = (url: string | URL) => {\n\tconst { pathname } = new URL(url.toString(), \"http://localhost\");\n\n\tif (paths.some((p) => pathname.includes(p))) {\n\t\treturn pathname.split(\"/\").pop();\n\t}\n\tif (pathname.includes(\"siwe\")) return \"siwe\";\n\tif (pathname.includes(\"/passkey/verify-authentication\")) {\n\t\treturn \"passkey\";\n\t}\n\n\treturn;\n};\n\nexport const lastLoginMethodClient = (config: LastLoginMethodClientConfig) => {\n\tconst resolveMethod = config.customResolveMethod || defaultResolveMethod;\n\tconst storagePrefix = config.storagePrefix || \"better-auth\";\n\tconst lastLoginMethodName = `${storagePrefix}_last_login_method`;\n\tconst storage = config.storage;\n\n\treturn {\n\t\tid: \"last-login-method-expo\",\n\t\tfetchPlugins: [\n\t\t\t{\n\t\t\t\tid: \"last-login-method-expo\",\n\t\t\t\tname: \"Last Login Method\",\n\t\t\t\thooks: {\n\t\t\t\t\tonResponse: async (ctx) => {\n\t\t\t\t\t\tconst lastMethod = await resolveMethod(ctx.request.url);\n\t\t\t\t\t\tif (!lastMethod) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tawait storage.setItem(lastLoginMethodName, lastMethod);\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t],\n\t\tgetActions() {\n\t\t\treturn {\n\t\t\t\t/**\n\t\t\t\t * Get the last used login method from storage\n\t\t\t\t *\n\t\t\t\t * @returns The last used login method or null if not found\n\t\t\t\t */\n\t\t\t\tgetLastUsedLoginMethod: (): string | null => {\n\t\t\t\t\treturn storage.getItem(lastLoginMethodName);\n\t\t\t\t},\n\t\t\t\t/**\n\t\t\t\t * Clear the last used login method from storage\n\t\t\t\t */\n\t\t\t\tclearLastUsedLoginMethod: async () => {\n\t\t\t\t\tawait storage.deleteItemAsync(lastLoginMethodName);\n\t\t\t\t},\n\t\t\t\t/**\n\t\t\t\t * Check if a specific login method was the last used\n\t\t\t\t * @param method The method to check\n\t\t\t\t * @returns True if the method was the last used, false otherwise\n\t\t\t\t */\n\t\t\t\tisLastUsedLoginMethod: (method: string): boolean => {\n\t\t\t\t\tconst lastMethod = storage.getItem(lastLoginMethodName);\n\t\t\t\t\treturn lastMethod === method;\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t} satisfies BetterAuthClientPlugin;\n};\n"],"mappings":";AAqBA,MAAM,QAAQ;CACb;CACA;CACA;CACA;CACA;AACD,MAAM,wBAAwB,QAAsB;CACnD,MAAM,EAAE,aAAa,IAAI,IAAI,IAAI,UAAU,EAAE,mBAAmB;AAEhE,KAAI,MAAM,MAAM,MAAM,SAAS,SAAS,EAAE,CAAC,CAC1C,QAAO,SAAS,MAAM,IAAI,CAAC,KAAK;AAEjC,KAAI,SAAS,SAAS,OAAO,CAAE,QAAO;AACtC,KAAI,SAAS,SAAS,iCAAiC,CACtD,QAAO;;AAMT,MAAa,yBAAyB,WAAwC;CAC7E,MAAM,gBAAgB,OAAO,uBAAuB;CAEpD,MAAM,sBAAsB,GADN,OAAO,iBAAiB,cACD;CAC7C,MAAM,UAAU,OAAO;AAEvB,QAAO;EACN,IAAI;EACJ,cAAc,CACb;GACC,IAAI;GACJ,MAAM;GACN,OAAO,EACN,YAAY,OAAO,QAAQ;IAC1B,MAAM,aAAa,MAAM,cAAc,IAAI,QAAQ,IAAI;AACvD,QAAI,CAAC,WACJ;AAGD,UAAM,QAAQ,QAAQ,qBAAqB,WAAW;MAEvD;GACD,CACD;EACD,aAAa;AACZ,UAAO;IAMN,8BAA6C;AAC5C,YAAO,QAAQ,QAAQ,oBAAoB;;IAK5C,0BAA0B,YAAY;AACrC,WAAM,QAAQ,gBAAgB,oBAAoB;;IAOnD,wBAAwB,WAA4B;AAEnD,YADmB,QAAQ,QAAQ,oBAAoB,KACjC;;IAEvB;;EAEF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@better-auth/expo",
|
|
3
|
-
"version": "1.5.0-beta.
|
|
3
|
+
"version": "1.5.0-beta.10",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Better Auth integration for Expo and React Native applications.",
|
|
6
6
|
"main": "dist/index.mjs",
|
|
@@ -55,22 +55,22 @@
|
|
|
55
55
|
"license": "MIT",
|
|
56
56
|
"devDependencies": {
|
|
57
57
|
"@better-fetch/fetch": "1.1.21",
|
|
58
|
-
"expo-constants": "~
|
|
59
|
-
"expo-
|
|
60
|
-
"expo-
|
|
61
|
-
"expo-web-browser": "~
|
|
62
|
-
"react-native": "~0.
|
|
63
|
-
"tsdown": "^0.
|
|
64
|
-
"@better-auth/core": "1.5.0-beta.
|
|
65
|
-
"better-auth": "1.5.0-beta.
|
|
58
|
+
"expo-constants": "~18.0.13",
|
|
59
|
+
"expo-linking": "~8.0.11",
|
|
60
|
+
"expo-network": "^8.0.8",
|
|
61
|
+
"expo-web-browser": "~15.0.10",
|
|
62
|
+
"react-native": "~0.83.1",
|
|
63
|
+
"tsdown": "^0.20.1",
|
|
64
|
+
"@better-auth/core": "1.5.0-beta.10",
|
|
65
|
+
"better-auth": "1.5.0-beta.10"
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
68
|
"expo-constants": ">=17.0.0",
|
|
69
69
|
"expo-linking": ">=7.0.0",
|
|
70
70
|
"expo-network": "^8.0.7",
|
|
71
71
|
"expo-web-browser": ">=14.0.0",
|
|
72
|
-
"better-auth": "1.5.0-beta.
|
|
73
|
-
"
|
|
72
|
+
"@better-auth/core": "1.5.0-beta.10",
|
|
73
|
+
"better-auth": "1.5.0-beta.10"
|
|
74
74
|
},
|
|
75
75
|
"peerDependenciesMeta": {
|
|
76
76
|
"expo-constants": {
|
|
@@ -88,15 +88,15 @@
|
|
|
88
88
|
},
|
|
89
89
|
"dependencies": {
|
|
90
90
|
"@better-fetch/fetch": "1.1.21",
|
|
91
|
-
"better-call": "1.
|
|
92
|
-
"zod": "^4.
|
|
91
|
+
"better-call": "1.2.0",
|
|
92
|
+
"zod": "^4.3.6"
|
|
93
93
|
},
|
|
94
94
|
"files": [
|
|
95
95
|
"dist"
|
|
96
96
|
],
|
|
97
97
|
"scripts": {
|
|
98
98
|
"test": "vitest",
|
|
99
|
-
"coverage": "vitest run --coverage",
|
|
99
|
+
"coverage": "vitest run --coverage --coverage.provider=istanbul",
|
|
100
100
|
"lint:types": "attw --profile esm-only --pack .",
|
|
101
101
|
"lint:package": "publint run --strict",
|
|
102
102
|
"build": "tsdown",
|