@instroc/auth 1.0.1 → 1.1.0

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