@farm.js/auth 0.1.51-beta.3 → 0.1.60

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/README.md CHANGED
@@ -165,7 +165,11 @@ enable `server.trustProxy` so visitors are not all counted as the proxy's addres
165
165
 
166
166
  - `@farm.js/auth/server`: the `auth.session()` and `auth.user()` helpers.
167
167
  - `@farm.js/auth/client`: `useAuth`, `signIn`, `signUp`, `signOut`, `getSession`, and
168
- `createFarmAuthClient`.
168
+ `createFarmAuthClient`. React Native screens (`page.native.tsx`) use the same import: Metro
169
+ resolves its `react-native` build, which calls the auth routes through `serverFetch` from
170
+ `@farm.js/native` (an optional peer). `signIn` and `signUp` go through the mobile shell's native
171
+ code, which keeps the session cookie in the WebView and issues the device token; social sign-in
172
+ rejects there for now. Web bundles do not change.
169
173
  - `@farm.js/auth`: `resolveFarmAuthConfig` and the configuration and session types, such as
170
174
  `FarmAuthConfig`, `FarmAuthSession`, and `FarmAuthUser`.
171
175
  - `@farm.js/auth/internal`: loaded by Farm core and `farm auth migrate`. Applications do not
@@ -0,0 +1,275 @@
1
+ import type * as web from "./client.js";
2
+ import type { FarmAuthCredentials, FarmAuthSignUpInput } from "./types.js";
3
+ /**
4
+ * Same options as the web client. `basePath` must match `auth.basePath` and, like every
5
+ * `serverFetch` path, sits under the app's base path on `mobile.server`. `baseURL` does not apply:
6
+ * native screens always call `mobile.server`, the only origin the device token is sent to.
7
+ */
8
+ export declare const createFarmAuthClient: typeof web.createFarmAuthClient;
9
+ export declare const getSession: () => Promise<{
10
+ data: {
11
+ user: import("better-auth").StripEmptyObjects<{
12
+ id: string;
13
+ createdAt: Date;
14
+ updatedAt: Date;
15
+ email: string;
16
+ emailVerified: boolean;
17
+ name: string;
18
+ image?: string | null | undefined;
19
+ }>;
20
+ session: import("better-auth").StripEmptyObjects<{
21
+ id: string;
22
+ createdAt: Date;
23
+ updatedAt: Date;
24
+ userId: string;
25
+ expiresAt: Date;
26
+ token: string;
27
+ ipAddress?: string | null | undefined;
28
+ userAgent?: string | null | undefined;
29
+ }>;
30
+ } | null;
31
+ error: null;
32
+ } | {
33
+ data: null;
34
+ error: {
35
+ code?: string | undefined | undefined;
36
+ message?: string | undefined | undefined;
37
+ status: number;
38
+ statusText: string;
39
+ };
40
+ }>, signIn: (input: FarmAuthCredentials) => Promise<{
41
+ data: Omit<{
42
+ redirect: boolean;
43
+ token: string;
44
+ url?: string | undefined;
45
+ user: {
46
+ id: string;
47
+ createdAt: Date;
48
+ updatedAt: Date;
49
+ email: string;
50
+ emailVerified: boolean;
51
+ name: string;
52
+ image?: string | null | undefined | undefined;
53
+ };
54
+ }, "user"> & {
55
+ user: import("better-auth").StripEmptyObjects<{
56
+ id: string;
57
+ createdAt: Date;
58
+ updatedAt: Date;
59
+ email: string;
60
+ emailVerified: boolean;
61
+ name: string;
62
+ image?: string | null | undefined;
63
+ }>;
64
+ };
65
+ error: null;
66
+ } | {
67
+ data: null;
68
+ error: {
69
+ code?: string | undefined | undefined;
70
+ message?: string | undefined | undefined;
71
+ status: number;
72
+ statusText: string;
73
+ };
74
+ }>, signOut: () => Promise<{
75
+ data: {
76
+ success: boolean;
77
+ url: string | undefined;
78
+ redirect: boolean | undefined;
79
+ };
80
+ error: null;
81
+ } | {
82
+ data: null;
83
+ error: {
84
+ code?: string | undefined | undefined;
85
+ message?: string | undefined | undefined;
86
+ status: number;
87
+ statusText: string;
88
+ };
89
+ }>, signUp: (input: FarmAuthSignUpInput) => Promise<{
90
+ data: (Omit<{
91
+ token: null;
92
+ user: {
93
+ id: string;
94
+ createdAt: Date;
95
+ updatedAt: Date;
96
+ email: string;
97
+ emailVerified: boolean;
98
+ name: string;
99
+ image?: string | null | undefined | undefined;
100
+ };
101
+ }, "user"> & {
102
+ user: import("better-auth").StripEmptyObjects<{
103
+ id: string;
104
+ createdAt: Date;
105
+ updatedAt: Date;
106
+ email: string;
107
+ emailVerified: boolean;
108
+ name: string;
109
+ image?: string | null | undefined;
110
+ }>;
111
+ }) | (Omit<{
112
+ token: string;
113
+ user: {
114
+ id: string;
115
+ createdAt: Date;
116
+ updatedAt: Date;
117
+ email: string;
118
+ emailVerified: boolean;
119
+ name: string;
120
+ image?: string | null | undefined | undefined;
121
+ };
122
+ }, "user"> & {
123
+ user: import("better-auth").StripEmptyObjects<{
124
+ id: string;
125
+ createdAt: Date;
126
+ updatedAt: Date;
127
+ email: string;
128
+ emailVerified: boolean;
129
+ name: string;
130
+ image?: string | null | undefined;
131
+ }>;
132
+ });
133
+ error: null;
134
+ } | {
135
+ data: null;
136
+ error: {
137
+ code?: string | undefined | undefined;
138
+ message?: string | undefined | undefined;
139
+ status: number;
140
+ statusText: string;
141
+ };
142
+ }>, useAuth: () => {
143
+ user: import("better-auth").StripEmptyObjects<{
144
+ id: string;
145
+ createdAt: Date;
146
+ updatedAt: Date;
147
+ email: string;
148
+ emailVerified: boolean;
149
+ name: string;
150
+ image?: string | null | undefined;
151
+ }> | null;
152
+ session: import("better-auth").StripEmptyObjects<{
153
+ id: string;
154
+ createdAt: Date;
155
+ updatedAt: Date;
156
+ userId: string;
157
+ expiresAt: Date;
158
+ token: string;
159
+ ipAddress?: string | null | undefined;
160
+ userAgent?: string | null | undefined;
161
+ }> | null;
162
+ isPending: boolean;
163
+ isRefetching: boolean;
164
+ error: import("better-auth/react").BetterFetchError | null;
165
+ refetch: (queryParams?: {
166
+ query?: import("better-auth").SessionQueryParams;
167
+ } | undefined) => Promise<void>;
168
+ signIn: (input: FarmAuthCredentials) => Promise<{
169
+ data: Omit<{
170
+ redirect: boolean;
171
+ token: string;
172
+ url?: string | undefined;
173
+ user: {
174
+ id: string;
175
+ createdAt: Date;
176
+ updatedAt: Date;
177
+ email: string;
178
+ emailVerified: boolean;
179
+ name: string;
180
+ image?: string | null | undefined | undefined;
181
+ };
182
+ }, "user"> & {
183
+ user: import("better-auth").StripEmptyObjects<{
184
+ id: string;
185
+ createdAt: Date;
186
+ updatedAt: Date;
187
+ email: string;
188
+ emailVerified: boolean;
189
+ name: string;
190
+ image?: string | null | undefined;
191
+ }>;
192
+ };
193
+ error: null;
194
+ } | {
195
+ data: null;
196
+ error: {
197
+ code?: string | undefined | undefined;
198
+ message?: string | undefined | undefined;
199
+ status: number;
200
+ statusText: string;
201
+ };
202
+ }>;
203
+ signUp: (input: FarmAuthSignUpInput) => Promise<{
204
+ data: (Omit<{
205
+ token: null;
206
+ user: {
207
+ id: string;
208
+ createdAt: Date;
209
+ updatedAt: Date;
210
+ email: string;
211
+ emailVerified: boolean;
212
+ name: string;
213
+ image?: string | null | undefined | undefined;
214
+ };
215
+ }, "user"> & {
216
+ user: import("better-auth").StripEmptyObjects<{
217
+ id: string;
218
+ createdAt: Date;
219
+ updatedAt: Date;
220
+ email: string;
221
+ emailVerified: boolean;
222
+ name: string;
223
+ image?: string | null | undefined;
224
+ }>;
225
+ }) | (Omit<{
226
+ token: string;
227
+ user: {
228
+ id: string;
229
+ createdAt: Date;
230
+ updatedAt: Date;
231
+ email: string;
232
+ emailVerified: boolean;
233
+ name: string;
234
+ image?: string | null | undefined | undefined;
235
+ };
236
+ }, "user"> & {
237
+ user: import("better-auth").StripEmptyObjects<{
238
+ id: string;
239
+ createdAt: Date;
240
+ updatedAt: Date;
241
+ email: string;
242
+ emailVerified: boolean;
243
+ name: string;
244
+ image?: string | null | undefined;
245
+ }>;
246
+ });
247
+ error: null;
248
+ } | {
249
+ data: null;
250
+ error: {
251
+ code?: string | undefined | undefined;
252
+ message?: string | undefined | undefined;
253
+ status: number;
254
+ statusText: string;
255
+ };
256
+ }>;
257
+ signOut: () => Promise<{
258
+ data: {
259
+ success: boolean;
260
+ url: string | undefined;
261
+ redirect: boolean | undefined;
262
+ };
263
+ error: null;
264
+ } | {
265
+ data: null;
266
+ error: {
267
+ code?: string | undefined | undefined;
268
+ message?: string | undefined | undefined;
269
+ status: number;
270
+ statusText: string;
271
+ };
272
+ }>;
273
+ };
274
+ export type { FarmAuthClientOptions, FarmAuthCredentials, FarmAuthSignUpInput } from "./types.js";
275
+ //# sourceMappingURL=client.native.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.native.d.ts","sourceRoot":"","sources":["../src/client.native.ts"],"names":[],"mappings":"AAYA,OAAO,KAAK,KAAK,GAAG,MAAM,aAAa,CAAC;AACxC,OAAO,KAAK,EAAyB,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAgDlG;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,EAAE,OAAO,GAAG,CAAC,oBA4J7C,CAAC;AAIF,eAAO,MAAQ,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAE,OAAO;;;;;;;;;;;;;;;IAAE,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAAE,OAAO;;;;;;;;;;;;;;;;;;;;;;;;aA7Ld,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA6L+B,CAAC;AAE9E,YAAY,EAAE,qBAAqB,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,191 @@
1
+ /**
2
+ * `@farm.js/auth/client` for React Native screens (`page.native.tsx`). Metro resolves this file
3
+ * through the `react-native` export condition; web builds never see it, so web bundles do not
4
+ * change. It has the web client's exports and types, and calls the same auth routes through
5
+ * `serverFetch` from `@farm.js/native`, which sends the device's session token. Sign-in and
6
+ * sign-up go through the shell's native code, which keeps the session cookie in the WebView and
7
+ * issues the device token from it.
8
+ */
9
+ import { useSyncExternalStore } from "react";
10
+ import { serverFetch, signOut as forgetDevice } from "@farm.js/native";
11
+ import { shellSignIn } from "@farm.js/native/internal";
12
+ import { normalizeBasePath } from "./config.js";
13
+ const SOCIAL_SIGN_IN_UNSUPPORTED = "@farm.js/auth/client: social and OAuth sign-in need a browser session and are not supported " +
14
+ "on native screens yet. Sign in with email and password, or on a web screen.";
15
+ // The ISO timestamps Better Auth's client turns into Dates, so `createdAt` and `expiresAt` are
16
+ // Dates here as on the web.
17
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,7})?(?:Z|[+-]\d{2}:\d{2})$/;
18
+ function parseBody(text) {
19
+ if (!text)
20
+ return null;
21
+ try {
22
+ return JSON.parse(text, (key, value) => {
23
+ if (key === "__proto__")
24
+ return undefined;
25
+ if (typeof value === "string" && ISO_DATE.test(value)) {
26
+ const date = new Date(value);
27
+ return Number.isNaN(date.getTime()) ? value : date;
28
+ }
29
+ return value;
30
+ });
31
+ }
32
+ catch {
33
+ return text;
34
+ }
35
+ }
36
+ function isRecord(value) {
37
+ return typeof value === "object" && value !== null && !Array.isArray(value);
38
+ }
39
+ /**
40
+ * Same options as the web client. `basePath` must match `auth.basePath` and, like every
41
+ * `serverFetch` path, sits under the app's base path on `mobile.server`. `baseURL` does not apply:
42
+ * native screens always call `mobile.server`, the only origin the device token is sent to.
43
+ */
44
+ export const createFarmAuthClient = (options = {}) => {
45
+ const basePath = normalizeBasePath(options.basePath);
46
+ // The status-and-body result Better Auth's client returns.
47
+ function toResult(status, statusText, text) {
48
+ const body = parseBody(text);
49
+ if (status >= 200 && status < 300)
50
+ return { data: (body ?? null), error: null };
51
+ return {
52
+ data: null,
53
+ error: { ...(isRecord(body) ? body : {}), status, statusText },
54
+ };
55
+ }
56
+ // From `serverFetch`. Async, so a screen that is not rendered yet (no `mobile.server`) rejects
57
+ // instead of throwing.
58
+ async function request(route, init) {
59
+ const response = await serverFetch(`${basePath}${route}`, init);
60
+ return toResult(response.status, response.statusText, await response.text());
61
+ }
62
+ async function loadSession(query) {
63
+ const search = Object.entries(query ?? {})
64
+ .filter(([, value]) => value !== undefined)
65
+ .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
66
+ .join("&");
67
+ const result = await request(`/get-session${search ? `?${search}` : ""}`, {
68
+ method: "GET",
69
+ });
70
+ // A 401 here means the device has no valid token: signed out, as the web client reports it.
71
+ if (result.error?.status === 401)
72
+ return { data: null, error: null };
73
+ return result;
74
+ }
75
+ const signedOut = {
76
+ data: null,
77
+ error: null,
78
+ isPending: false,
79
+ isRefetching: false,
80
+ };
81
+ let state = { ...signedOut, isPending: true };
82
+ let latest = 0;
83
+ const listeners = new Set();
84
+ function setState(next) {
85
+ state = next;
86
+ for (const listener of listeners)
87
+ listener();
88
+ }
89
+ // Better Auth's useSession states, in the same order: pending until the first answer, a 401
90
+ // clears the user, a thrown error keeps the last one.
91
+ async function refetch(queryParams) {
92
+ const id = ++latest;
93
+ setState({ ...state, isPending: state.data === null, error: null, isRefetching: true });
94
+ try {
95
+ const result = await loadSession(queryParams?.query);
96
+ if (id !== latest)
97
+ return;
98
+ setState(result.error
99
+ ? { ...signedOut, data: state.data, error: result.error }
100
+ : { ...signedOut, data: result.data });
101
+ }
102
+ catch (error) {
103
+ if (id !== latest)
104
+ return;
105
+ setState({ ...signedOut, data: state.data, error: error });
106
+ }
107
+ }
108
+ function subscribe(listener) {
109
+ listeners.add(listener);
110
+ // The first mounted hook loads the session, after React has subscribed.
111
+ if (listeners.size === 1)
112
+ void Promise.resolve().then(() => refetch());
113
+ return () => {
114
+ listeners.delete(listener);
115
+ };
116
+ }
117
+ const getState = () => state;
118
+ /**
119
+ * The web client's route and body, sent by the shell's native code. On success the WebView has
120
+ * the session cookie (web screens are signed in too), the device has its token, and `useAuth`
121
+ * has the user before this resolves. The shell never returns cookies or tokens to JS; the body
122
+ * is Better Auth's, as the web client gets it.
123
+ */
124
+ async function credentials(route, input) {
125
+ if ("provider" in input)
126
+ throw new Error(SOCIAL_SIGN_IN_UNSUPPORTED);
127
+ const reply = await shellSignIn(`${basePath}${route}`, input);
128
+ // The shell has no reason phrase to pass on; HTTP/2 responses on the web have none either.
129
+ const result = toResult(reply.status, "", reply.body);
130
+ if (result.error === null)
131
+ await refetch();
132
+ return result;
133
+ }
134
+ function signIn(input) {
135
+ return credentials("/sign-in/email", input);
136
+ }
137
+ function signUp(input) {
138
+ return credentials("/sign-up/email", input);
139
+ }
140
+ /**
141
+ * End the server session, then forget this device: revoke its token, delete it from the
142
+ * Keystore or Keychain, and clear the WebView's cookies. The device step runs even when the
143
+ * server call fails or the phone is offline; the server's error is still returned or thrown.
144
+ */
145
+ async function signOut() {
146
+ let result;
147
+ let failure;
148
+ let failed = false;
149
+ try {
150
+ result = await request("/sign-out", { method: "POST" });
151
+ }
152
+ catch (error) {
153
+ failed = true;
154
+ failure = error;
155
+ }
156
+ try {
157
+ await forgetDevice();
158
+ }
159
+ catch (error) {
160
+ if (!failed)
161
+ throw error;
162
+ }
163
+ finally {
164
+ latest += 1;
165
+ setState(signedOut);
166
+ }
167
+ if (failed)
168
+ throw failure;
169
+ return result;
170
+ }
171
+ function getSession() {
172
+ return loadSession();
173
+ }
174
+ function useAuth() {
175
+ const current = useSyncExternalStore(subscribe, getState, getState);
176
+ return {
177
+ user: current.data?.user ?? null,
178
+ session: current.data?.session ?? null,
179
+ isPending: current.isPending,
180
+ isRefetching: current.isRefetching,
181
+ error: current.error,
182
+ refetch,
183
+ signIn,
184
+ signUp,
185
+ signOut,
186
+ };
187
+ }
188
+ return { signIn, signUp, signOut, getSession, useAuth };
189
+ };
190
+ const defaultClient = createFarmAuthClient();
191
+ export const { getSession, signIn, signOut, signUp, useAuth } = defaultClient;
package/dist/config.d.ts CHANGED
@@ -1,3 +1,5 @@
1
1
  import type { FarmAuthUserConfig, ResolvedFarmAuthConfig } from "./types.js";
2
2
  export declare function resolveFarmAuthConfig(input: FarmAuthUserConfig | undefined): ResolvedFarmAuthConfig;
3
+ /** `auth.basePath` as the server mounts it. Shared with the native client. */
4
+ export declare function normalizeBasePath(value: string | undefined): string;
3
5
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAK7E,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,kBAAkB,GAAG,SAAS,GACpC,sBAAsB,CAiDxB"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAK7E,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,kBAAkB,GAAG,SAAS,GACpC,sBAAsB,CAiDxB;AAED,8EAA8E;AAC9E,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAOnE"}
package/dist/config.js CHANGED
@@ -47,7 +47,8 @@ export function resolveFarmAuthConfig(input) {
47
47
  validateFarmAuthConfig(resolved);
48
48
  return resolved;
49
49
  }
50
- function normalizeBasePath(value) {
50
+ /** `auth.basePath` as the server mounts it. Shared with the native client. */
51
+ export function normalizeBasePath(value) {
51
52
  const route = (value || "/api/auth").trim();
52
53
  if (!route)
53
54
  return "/api/auth";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@farm.js/auth",
3
- "version": "0.1.51-beta.3",
3
+ "version": "0.1.60",
4
4
  "description": "Farm-native authentication with email/password, server helpers, and React hooks",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,6 +28,7 @@
28
28
  },
29
29
  "./client": {
30
30
  "types": "./dist/client.d.ts",
31
+ "react-native": "./dist/client.native.js",
31
32
  "import": "./dist/client.js",
32
33
  "default": "./dist/client.js"
33
34
  },
@@ -51,10 +52,17 @@
51
52
  "react": "19.2.8",
52
53
  "typescript": "^5.3.3",
53
54
  "vite": "8.3.4",
54
- "vitest": "5.0.5"
55
+ "vitest": "5.0.5",
56
+ "@farm.js/native": "0.1.0-beta.2"
55
57
  },
56
58
  "peerDependencies": {
57
- "react": "^18.2.0 || ^19.0.0"
59
+ "react": "^18.2.0 || ^19.0.0",
60
+ "@farm.js/native": "^0.1.0-beta.2"
61
+ },
62
+ "peerDependenciesMeta": {
63
+ "@farm.js/native": {
64
+ "optional": true
65
+ }
58
66
  },
59
67
  "optionalDependencies": {
60
68
  "better-sqlite3": "12.8.0"