@instroc/auth 1.0.2 → 1.1.1

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/dist/index.js CHANGED
@@ -1,569 +1,28 @@
1
- // src/provider.tsx
2
1
  import {
3
- createContext,
4
- useContext,
5
- useState,
6
- useCallback,
7
- useEffect,
8
- useRef
9
- } from "react";
10
-
11
- // src/errors.ts
12
- var AuthError = class _AuthError extends Error {
13
- constructor(message, status, code) {
14
- super(message);
15
- this.name = "AuthError";
16
- this.status = status;
17
- this.code = code;
18
- Object.setPrototypeOf(this, _AuthError.prototype);
19
- }
20
- };
21
- function authErrorFromResponse(response, data, fallbackMessage) {
22
- const body = data ?? {};
23
- const message = body.error || fallbackMessage;
24
- return new AuthError(message, response.status, body.code);
25
- }
26
-
27
- // src/provider.tsx
28
- import { jsx } from "react/jsx-runtime";
29
- var AuthContext = createContext(null);
30
- var STORAGE_KEY = "instroc_auth_session";
31
- function AuthProvider({
32
- children,
33
- projectId: initialProjectId,
34
- baseUrl = "/api/baas",
35
- persistSession = true,
36
- onAuthStateChange
37
- }) {
38
- const [projectId, setProjectId] = useState(
39
- initialProjectId || null
40
- );
41
- const [user, setUser] = useState(null);
42
- const [session, setSession] = useState(null);
43
- const [loading, setLoading] = useState(true);
44
- const [error, setError] = useState(null);
45
- const [authConfig, setAuthConfig] = useState(null);
46
- const [visibilityConfig, setVisibilityConfig] = useState(null);
47
- const refreshTimeoutRef = useRef(null);
48
- const buildUrl = useCallback(
49
- (endpoint) => {
50
- if (!projectId) {
51
- throw new Error("Project ID is required");
52
- }
53
- return `${baseUrl}/${projectId}/auth/${endpoint}`;
54
- },
55
- [projectId, baseUrl]
56
- );
57
- const authFetch = useCallback(
58
- (url, init) => fetch(url, { ...init, credentials: "include" }),
59
- []
60
- );
61
- const saveSession = useCallback(
62
- (sessionData) => {
63
- if (persistSession && typeof window !== "undefined") {
64
- if (sessionData) {
65
- localStorage.setItem(STORAGE_KEY, JSON.stringify(sessionData));
66
- } else {
67
- localStorage.removeItem(STORAGE_KEY);
68
- }
69
- }
70
- },
71
- [persistSession]
72
- );
73
- const loadSession = useCallback(() => {
74
- if (persistSession && typeof window !== "undefined") {
75
- const stored = localStorage.getItem(STORAGE_KEY);
76
- if (stored) {
77
- try {
78
- return JSON.parse(stored);
79
- } catch {
80
- localStorage.removeItem(STORAGE_KEY);
81
- }
82
- }
83
- }
84
- return null;
85
- }, [persistSession]);
86
- const scheduleRefresh = useCallback(
87
- (expiresAt) => {
88
- if (refreshTimeoutRef.current) {
89
- clearTimeout(refreshTimeoutRef.current);
90
- }
91
- const expiresTime = new Date(expiresAt).getTime();
92
- const now = Date.now();
93
- const refreshIn = expiresTime - now - 5 * 60 * 1e3;
94
- if (refreshIn > 0) {
95
- refreshTimeoutRef.current = setTimeout(async () => {
96
- try {
97
- await refreshSession();
98
- } catch (err) {
99
- console.warn("Token refresh failed:", err);
100
- setUser(null);
101
- setSession(null);
102
- saveSession(null);
103
- }
104
- }, refreshIn);
105
- }
106
- },
107
- [saveSession]
108
- );
109
- const updateAuthState = useCallback(
110
- (newUser, newSession) => {
111
- setUser(newUser);
112
- setSession(newSession);
113
- saveSession(newSession);
114
- if (newSession) {
115
- scheduleRefresh(newSession.expires_at);
116
- }
117
- if (onAuthStateChange) {
118
- onAuthStateChange(newUser);
119
- }
120
- },
121
- [saveSession, scheduleRefresh, onAuthStateChange]
122
- );
123
- const fetchUser = useCallback(async () => {
124
- const storedSession = loadSession();
125
- if (!storedSession || !projectId) {
126
- setLoading(false);
127
- return;
128
- }
129
- try {
130
- const response = await authFetch(buildUrl("me"), {
131
- headers: {
132
- Authorization: `Bearer ${storedSession.access_token}`
133
- }
134
- });
135
- if (response.ok) {
136
- const data = await response.json();
137
- updateAuthState(data.user, storedSession);
138
- } else if (response.status === 401) {
139
- try {
140
- const refreshResponse = await authFetch(buildUrl("refresh"), {
141
- method: "POST",
142
- headers: { "Content-Type": "application/json" },
143
- body: JSON.stringify({ refreshToken: storedSession.refresh_token })
144
- });
145
- if (refreshResponse.ok) {
146
- const refreshData = await refreshResponse.json();
147
- const newSession = {
148
- ...storedSession,
149
- access_token: refreshData.access_token,
150
- expires_at: refreshData.expires_at
151
- };
152
- const userResponse = await authFetch(buildUrl("me"), {
153
- headers: {
154
- Authorization: `Bearer ${newSession.access_token}`
155
- }
156
- });
157
- if (userResponse.ok) {
158
- const userData = await userResponse.json();
159
- updateAuthState(userData.user, newSession);
160
- } else {
161
- updateAuthState(null, null);
162
- }
163
- } else {
164
- updateAuthState(null, null);
165
- }
166
- } catch {
167
- updateAuthState(null, null);
168
- }
169
- } else {
170
- updateAuthState(null, null);
171
- }
172
- } catch (err) {
173
- console.error("Failed to fetch user:", err);
174
- updateAuthState(null, null);
175
- } finally {
176
- setLoading(false);
177
- }
178
- }, [projectId, loadSession, buildUrl, updateAuthState]);
179
- useEffect(() => {
180
- if (projectId) {
181
- fetchUser();
182
- } else {
183
- setLoading(false);
184
- }
185
- return () => {
186
- if (refreshTimeoutRef.current) {
187
- clearTimeout(refreshTimeoutRef.current);
188
- }
189
- };
190
- }, [projectId, fetchUser]);
191
- const login = useCallback(
192
- async (credentials) => {
193
- setError(null);
194
- setLoading(true);
195
- try {
196
- const response = await authFetch(buildUrl("login"), {
197
- method: "POST",
198
- headers: { "Content-Type": "application/json" },
199
- body: JSON.stringify(credentials)
200
- });
201
- const data = await response.json();
202
- if (!response.ok) {
203
- throw authErrorFromResponse(response, data, "Login failed");
204
- }
205
- const authResponse = data;
206
- updateAuthState(authResponse.user, authResponse.session);
207
- } catch (err) {
208
- const message = err instanceof Error ? err.message : "Login failed";
209
- setError(message);
210
- throw err;
211
- } finally {
212
- setLoading(false);
213
- }
214
- },
215
- [buildUrl, updateAuthState]
216
- );
217
- const signup = useCallback(
218
- async (credentials) => {
219
- setError(null);
220
- setLoading(true);
221
- try {
222
- const response = await authFetch(buildUrl("signup"), {
223
- method: "POST",
224
- headers: { "Content-Type": "application/json" },
225
- body: JSON.stringify(credentials)
226
- });
227
- const data = await response.json();
228
- if (!response.ok) {
229
- throw authErrorFromResponse(response, data, "Signup failed");
230
- }
231
- const authResponse = data;
232
- if (authResponse.needsVerification) {
233
- return {
234
- status: "needs_verification",
235
- email: credentials.email
236
- };
237
- }
238
- if (authResponse.needsApproval) {
239
- updateAuthState(authResponse.user, authResponse.session);
240
- return { status: "needs_approval", user: authResponse.user };
241
- }
242
- if (authResponse.session.access_token) {
243
- updateAuthState(authResponse.user, authResponse.session);
244
- return { status: "authenticated", user: authResponse.user };
245
- }
246
- return {
247
- status: "needs_verification",
248
- email: credentials.email
249
- };
250
- } catch (err) {
251
- const message = err instanceof Error ? err.message : "Signup failed";
252
- setError(message);
253
- throw err;
254
- } finally {
255
- setLoading(false);
256
- }
257
- },
258
- [buildUrl, updateAuthState]
259
- );
260
- const logout = useCallback(async () => {
261
- try {
262
- if (session) {
263
- await authFetch(buildUrl("logout"), {
264
- method: "POST",
265
- headers: {
266
- Authorization: `Bearer ${session.access_token}`
267
- }
268
- });
269
- }
270
- } catch (err) {
271
- console.error("Logout error:", err);
272
- } finally {
273
- updateAuthState(null, null);
274
- if (refreshTimeoutRef.current) {
275
- clearTimeout(refreshTimeoutRef.current);
276
- }
277
- }
278
- }, [session, buildUrl, updateAuthState]);
279
- const updateProfile = useCallback(
280
- async (data) => {
281
- if (!session) {
282
- throw new AuthError("Not authenticated", 401);
283
- }
284
- setError(null);
285
- try {
286
- const response = await authFetch(buildUrl("me"), {
287
- method: "PATCH",
288
- headers: {
289
- "Content-Type": "application/json",
290
- Authorization: `Bearer ${session.access_token}`
291
- },
292
- body: JSON.stringify(data)
293
- });
294
- const result = await response.json();
295
- if (!response.ok) {
296
- throw authErrorFromResponse(response, result, "Update failed");
297
- }
298
- setUser(result.user);
299
- } catch (err) {
300
- const message = err instanceof Error ? err.message : "Update failed";
301
- setError(message);
302
- throw err;
303
- }
304
- },
305
- [session, buildUrl]
306
- );
307
- const refreshSession = useCallback(async () => {
308
- if (!session)
309
- return;
310
- const response = await authFetch(buildUrl("refresh"), {
311
- method: "POST",
312
- headers: { "Content-Type": "application/json" },
313
- body: JSON.stringify({ refreshToken: session.refresh_token })
314
- });
315
- const data = await response.json();
316
- if (!response.ok) {
317
- throw authErrorFromResponse(response, data, "Refresh failed");
318
- }
319
- const refreshData = data;
320
- const newSession = {
321
- ...session,
322
- access_token: refreshData.access_token,
323
- expires_at: refreshData.expires_at
324
- };
325
- updateAuthState(user, newSession);
326
- }, [session, user, buildUrl, updateAuthState]);
327
- const forgotPassword = useCallback(
328
- async (email) => {
329
- setError(null);
330
- try {
331
- const response = await authFetch(buildUrl("forgot-password"), {
332
- method: "POST",
333
- headers: { "Content-Type": "application/json" },
334
- body: JSON.stringify({ email })
335
- });
336
- const data = await response.json();
337
- if (!response.ok) {
338
- throw authErrorFromResponse(response, data, "Request failed");
339
- }
340
- } catch (err) {
341
- const message = err instanceof Error ? err.message : "Request failed";
342
- setError(message);
343
- throw err;
344
- }
345
- },
346
- [buildUrl]
347
- );
348
- const resetPassword = useCallback(
349
- async (token, newPassword) => {
350
- setError(null);
351
- try {
352
- const response = await authFetch(buildUrl("reset-password"), {
353
- method: "POST",
354
- headers: { "Content-Type": "application/json" },
355
- body: JSON.stringify({ token, password: newPassword })
356
- });
357
- const data = await response.json();
358
- if (!response.ok) {
359
- throw authErrorFromResponse(response, data, "Reset failed");
360
- }
361
- } catch (err) {
362
- const message = err instanceof Error ? err.message : "Reset failed";
363
- setError(message);
364
- throw err;
365
- }
366
- },
367
- [buildUrl]
368
- );
369
- const signInWithOAuth = useCallback(
370
- (provider) => {
371
- if (!projectId) {
372
- setError("Project ID is required");
373
- return;
374
- }
375
- const currentUrl = window.location.origin + window.location.pathname;
376
- const oauthUrl = `${baseUrl}/${projectId}/auth/oauth/${provider}?redirect_uri=${encodeURIComponent(currentUrl)}`;
377
- window.location.href = oauthUrl;
378
- },
379
- [projectId, baseUrl]
380
- );
381
- const verifyOTP = useCallback(
382
- async (email, code) => {
383
- setError(null);
384
- setLoading(true);
385
- try {
386
- const response = await authFetch(buildUrl("verify-email"), {
387
- method: "POST",
388
- headers: { "Content-Type": "application/json" },
389
- body: JSON.stringify({ email, otp: code })
390
- });
391
- const data = await response.json();
392
- if (!response.ok) {
393
- throw authErrorFromResponse(response, data, "Verification failed");
394
- }
395
- if (data.session) {
396
- updateAuthState(data.user, data.session);
397
- }
398
- } catch (err) {
399
- const message = err instanceof Error ? err.message : "Verification failed";
400
- setError(message);
401
- throw err;
402
- } finally {
403
- setLoading(false);
404
- }
405
- },
406
- [buildUrl, updateAuthState]
407
- );
408
- const resendOTP = useCallback(
409
- async (email) => {
410
- setError(null);
411
- try {
412
- const response = await authFetch(buildUrl("resend-verification"), {
413
- method: "POST",
414
- headers: { "Content-Type": "application/json" },
415
- body: JSON.stringify({ email })
416
- });
417
- const data = await response.json();
418
- if (!response.ok) {
419
- throw authErrorFromResponse(response, data, "Failed to resend code");
420
- }
421
- } catch (err) {
422
- const message = err instanceof Error ? err.message : "Failed to resend code";
423
- setError(message);
424
- throw err;
425
- }
426
- },
427
- [buildUrl]
428
- );
429
- const fetchAuthConfig = useCallback(async () => {
430
- if (!projectId)
431
- return;
432
- try {
433
- const response = await fetch(`${baseUrl}/${projectId}/auth/config`);
434
- if (response.ok) {
435
- const data = await response.json();
436
- setAuthConfig(data.config || null);
437
- setVisibilityConfig(
438
- data.visibility || {
439
- projectName: "App",
440
- visibility: "public",
441
- requireLogin: false,
442
- logoUrl: null,
443
- welcomeMessage: null
444
- }
445
- );
446
- }
447
- } catch (err) {
448
- console.error("Failed to fetch auth config:", err);
449
- }
450
- }, [projectId, baseUrl]);
451
- const parseOAuthCallback = useCallback(() => {
452
- if (typeof window === "undefined")
453
- return;
454
- const hash = window.location.hash;
455
- if (hash && hash.startsWith("#auth=")) {
456
- try {
457
- const authData = decodeURIComponent(hash.substring(6));
458
- const tokenData = JSON.parse(authData);
459
- if (tokenData.access_token && tokenData.refresh_token) {
460
- const newSession = {
461
- access_token: tokenData.access_token,
462
- refresh_token: tokenData.refresh_token,
463
- expires_at: tokenData.expires_at
464
- };
465
- saveSession(newSession);
466
- setSession(newSession);
467
- window.history.replaceState({}, "", window.location.pathname);
468
- return true;
469
- }
470
- } catch {
471
- }
472
- }
473
- const params = new URLSearchParams(window.location.search);
474
- const verifyEmailToken = params.get("verify_email");
475
- if (verifyEmailToken && projectId) {
476
- fetch(buildUrl("verify-email"), {
477
- method: "POST",
478
- headers: { "Content-Type": "application/json" },
479
- body: JSON.stringify({ token: verifyEmailToken })
480
- }).then((res) => res.json()).then(() => {
481
- window.history.replaceState({}, "", window.location.pathname);
482
- }).catch(() => {
483
- window.history.replaceState({}, "", window.location.pathname);
484
- });
485
- return true;
486
- }
487
- const accessToken = params.get("access_token");
488
- const refreshToken = params.get("refresh_token");
489
- const expiresAt = params.get("expires_at");
490
- if (accessToken && refreshToken && expiresAt) {
491
- const newSession = {
492
- access_token: accessToken,
493
- refresh_token: refreshToken,
494
- expires_at: expiresAt
495
- };
496
- saveSession(newSession);
497
- setSession(newSession);
498
- window.history.replaceState({}, "", window.location.pathname);
499
- return true;
500
- }
501
- return false;
502
- }, [projectId, buildUrl, saveSession]);
503
- useEffect(() => {
504
- fetchAuthConfig();
505
- }, [fetchAuthConfig]);
506
- useEffect(() => {
507
- parseOAuthCallback();
508
- }, [parseOAuthCallback]);
509
- const value = {
510
- user,
511
- session,
512
- loading,
513
- error,
514
- login,
515
- signup,
516
- logout,
517
- signInWithOAuth,
518
- verifyOTP,
519
- resendOTP,
520
- updateProfile,
521
- refreshSession,
522
- forgotPassword,
523
- resetPassword,
524
- setProjectId,
525
- projectId,
526
- authConfig,
527
- visibilityConfig
528
- };
529
- return /* @__PURE__ */ jsx(AuthContext.Provider, { value, children });
530
- }
531
- function useAuthContext() {
532
- const context = useContext(AuthContext);
533
- if (!context) {
534
- throw new Error("useAuthContext must be used within an AuthProvider");
535
- }
536
- return context;
537
- }
538
-
539
- // src/use-auth.ts
540
- function useAuth() {
541
- return useAuthContext();
542
- }
543
- function useUser() {
544
- const { user, loading } = useAuthContext();
545
- return { user, loading };
546
- }
547
- function useSession() {
548
- const { session, loading } = useAuthContext();
549
- return { session, loading };
550
- }
551
- function useAuthRequired() {
552
- const { user, loading, session } = useAuthContext();
553
- if (loading) {
554
- return { user: null, session: null, loading: true };
555
- }
556
- if (!user) {
557
- throw new Error("Authentication required");
558
- }
559
- return { user, session, loading: false };
560
- }
2
+ AuthError,
3
+ AuthProvider,
4
+ useAuth,
5
+ useAuthContext,
6
+ useAuthRequired,
7
+ useForgotPasswordForm,
8
+ useLoginForm,
9
+ useOtpForm,
10
+ useResetPasswordForm,
11
+ useSession,
12
+ useSignupForm,
13
+ useUser
14
+ } from "./chunk-T7NGX4DQ.js";
561
15
  export {
562
16
  AuthError,
563
17
  AuthProvider,
564
18
  useAuth,
565
19
  useAuthContext,
566
20
  useAuthRequired,
21
+ useForgotPasswordForm,
22
+ useLoginForm,
23
+ useOtpForm,
24
+ useResetPasswordForm,
567
25
  useSession,
26
+ useSignupForm,
568
27
  useUser
569
28
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@instroc/auth",
3
- "version": "1.0.2",
4
- "description": "Authentication hooks for Instroc Cloud — useAuth, useUser, AuthProvider",
3
+ "version": "1.1.1",
4
+ "description": "Authentication hooks for Instroc Cloud — useAuth, useUser, AuthProvider, and headless form hooks",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
@@ -9,6 +9,10 @@
9
9
  ".": {
10
10
  "import": "./dist/index.js",
11
11
  "types": "./dist/index.d.ts"
12
+ },
13
+ "./forms": {
14
+ "import": "./dist/forms.js",
15
+ "types": "./dist/forms.d.ts"
12
16
  }
13
17
  },
14
18
  "files": [