@oxyhq/auth 1.0.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/README.md +56 -0
- package/dist/cjs/WebOxyProvider.js +287 -0
- package/dist/cjs/hooks/mutations/index.js +23 -0
- package/dist/cjs/hooks/mutations/mutationFactory.js +126 -0
- package/dist/cjs/hooks/mutations/useAccountMutations.js +275 -0
- package/dist/cjs/hooks/mutations/useServicesMutations.js +149 -0
- package/dist/cjs/hooks/queries/index.js +35 -0
- package/dist/cjs/hooks/queries/queryKeys.js +82 -0
- package/dist/cjs/hooks/queries/useAccountQueries.js +141 -0
- package/dist/cjs/hooks/queries/useSecurityQueries.js +45 -0
- package/dist/cjs/hooks/queries/useServicesQueries.js +113 -0
- package/dist/cjs/hooks/queryClient.js +110 -0
- package/dist/cjs/hooks/useAssets.js +225 -0
- package/dist/cjs/hooks/useFileDownloadUrl.js +91 -0
- package/dist/cjs/hooks/useFileFiltering.js +81 -0
- package/dist/cjs/hooks/useFollow.js +159 -0
- package/dist/cjs/hooks/useFollow.types.js +4 -0
- package/dist/cjs/hooks/useQueryClient.js +16 -0
- package/dist/cjs/hooks/useSessionSocket.js +215 -0
- package/dist/cjs/hooks/useWebSSO.js +146 -0
- package/dist/cjs/index.js +115 -0
- package/dist/cjs/stores/accountStore.js +226 -0
- package/dist/cjs/stores/assetStore.js +192 -0
- package/dist/cjs/stores/authStore.js +47 -0
- package/dist/cjs/stores/followStore.js +154 -0
- package/dist/cjs/utils/authHelpers.js +154 -0
- package/dist/cjs/utils/avatarUtils.js +77 -0
- package/dist/cjs/utils/errorHandlers.js +128 -0
- package/dist/cjs/utils/sessionHelpers.js +90 -0
- package/dist/cjs/utils/storageHelpers.js +147 -0
- package/dist/esm/WebOxyProvider.js +282 -0
- package/dist/esm/hooks/mutations/index.js +10 -0
- package/dist/esm/hooks/mutations/mutationFactory.js +122 -0
- package/dist/esm/hooks/mutations/useAccountMutations.js +267 -0
- package/dist/esm/hooks/mutations/useServicesMutations.js +141 -0
- package/dist/esm/hooks/queries/index.js +14 -0
- package/dist/esm/hooks/queries/queryKeys.js +76 -0
- package/dist/esm/hooks/queries/useAccountQueries.js +131 -0
- package/dist/esm/hooks/queries/useSecurityQueries.js +40 -0
- package/dist/esm/hooks/queries/useServicesQueries.js +105 -0
- package/dist/esm/hooks/queryClient.js +104 -0
- package/dist/esm/hooks/useAssets.js +220 -0
- package/dist/esm/hooks/useFileDownloadUrl.js +86 -0
- package/dist/esm/hooks/useFileFiltering.js +78 -0
- package/dist/esm/hooks/useFollow.js +154 -0
- package/dist/esm/hooks/useFollow.types.js +3 -0
- package/dist/esm/hooks/useQueryClient.js +12 -0
- package/dist/esm/hooks/useSessionSocket.js +209 -0
- package/dist/esm/hooks/useWebSSO.js +143 -0
- package/dist/esm/index.js +48 -0
- package/dist/esm/stores/accountStore.js +219 -0
- package/dist/esm/stores/assetStore.js +180 -0
- package/dist/esm/stores/authStore.js +44 -0
- package/dist/esm/stores/followStore.js +151 -0
- package/dist/esm/utils/authHelpers.js +145 -0
- package/dist/esm/utils/avatarUtils.js +72 -0
- package/dist/esm/utils/errorHandlers.js +121 -0
- package/dist/esm/utils/sessionHelpers.js +84 -0
- package/dist/esm/utils/storageHelpers.js +108 -0
- package/dist/types/WebOxyProvider.d.ts +97 -0
- package/dist/types/hooks/mutations/index.d.ts +8 -0
- package/dist/types/hooks/mutations/mutationFactory.d.ts +75 -0
- package/dist/types/hooks/mutations/useAccountMutations.d.ts +68 -0
- package/dist/types/hooks/mutations/useServicesMutations.d.ts +22 -0
- package/dist/types/hooks/queries/index.d.ts +10 -0
- package/dist/types/hooks/queries/queryKeys.d.ts +64 -0
- package/dist/types/hooks/queries/useAccountQueries.d.ts +42 -0
- package/dist/types/hooks/queries/useSecurityQueries.d.ts +14 -0
- package/dist/types/hooks/queries/useServicesQueries.d.ts +31 -0
- package/dist/types/hooks/queryClient.d.ts +18 -0
- package/dist/types/hooks/useAssets.d.ts +34 -0
- package/dist/types/hooks/useFileDownloadUrl.d.ts +18 -0
- package/dist/types/hooks/useFileFiltering.d.ts +28 -0
- package/dist/types/hooks/useFollow.d.ts +61 -0
- package/dist/types/hooks/useFollow.types.d.ts +32 -0
- package/dist/types/hooks/useQueryClient.d.ts +6 -0
- package/dist/types/hooks/useSessionSocket.d.ts +13 -0
- package/dist/types/hooks/useWebSSO.d.ts +57 -0
- package/dist/types/index.d.ts +46 -0
- package/dist/types/stores/accountStore.d.ts +33 -0
- package/dist/types/stores/assetStore.d.ts +53 -0
- package/dist/types/stores/authStore.d.ts +16 -0
- package/dist/types/stores/followStore.d.ts +24 -0
- package/dist/types/utils/authHelpers.d.ts +98 -0
- package/dist/types/utils/avatarUtils.d.ts +33 -0
- package/dist/types/utils/errorHandlers.d.ts +34 -0
- package/dist/types/utils/sessionHelpers.d.ts +63 -0
- package/dist/types/utils/storageHelpers.d.ts +27 -0
- package/package.json +71 -0
- package/src/WebOxyProvider.tsx +372 -0
- package/src/global.d.ts +1 -0
- package/src/hooks/mutations/index.ts +25 -0
- package/src/hooks/mutations/mutationFactory.ts +215 -0
- package/src/hooks/mutations/useAccountMutations.ts +344 -0
- package/src/hooks/mutations/useServicesMutations.ts +164 -0
- package/src/hooks/queries/index.ts +36 -0
- package/src/hooks/queries/queryKeys.ts +88 -0
- package/src/hooks/queries/useAccountQueries.ts +152 -0
- package/src/hooks/queries/useSecurityQueries.ts +64 -0
- package/src/hooks/queries/useServicesQueries.ts +126 -0
- package/src/hooks/queryClient.ts +112 -0
- package/src/hooks/useAssets.ts +291 -0
- package/src/hooks/useFileDownloadUrl.ts +118 -0
- package/src/hooks/useFileFiltering.ts +115 -0
- package/src/hooks/useFollow.ts +175 -0
- package/src/hooks/useFollow.types.ts +33 -0
- package/src/hooks/useQueryClient.ts +17 -0
- package/src/hooks/useSessionSocket.ts +233 -0
- package/src/hooks/useWebSSO.ts +187 -0
- package/src/index.ts +144 -0
- package/src/stores/accountStore.ts +296 -0
- package/src/stores/assetStore.ts +281 -0
- package/src/stores/authStore.ts +63 -0
- package/src/stores/followStore.ts +181 -0
- package/src/utils/authHelpers.ts +183 -0
- package/src/utils/avatarUtils.ts +103 -0
- package/src/utils/errorHandlers.ts +194 -0
- package/src/utils/sessionHelpers.ts +151 -0
- package/src/utils/storageHelpers.ts +130 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { useCallback, useMemo, useEffect } from 'react';
|
|
2
|
+
import { useFollowStore } from '../stores/followStore';
|
|
3
|
+
import { useWebOxy } from '../WebOxyProvider';
|
|
4
|
+
export const useFollow = (userId) => {
|
|
5
|
+
const { oxyServices } = useWebOxy();
|
|
6
|
+
const userIds = useMemo(() => (Array.isArray(userId) ? userId : userId ? [userId] : []), [userId]);
|
|
7
|
+
const isSingleUser = typeof userId === 'string';
|
|
8
|
+
// Zustand selectors
|
|
9
|
+
const followState = useFollowStore();
|
|
10
|
+
// Single user helpers
|
|
11
|
+
const isFollowing = isSingleUser && userId ? followState.followingUsers[userId] ?? false : false;
|
|
12
|
+
const isLoading = isSingleUser && userId ? followState.loadingUsers[userId] ?? false : false;
|
|
13
|
+
const error = isSingleUser && userId ? followState.errors[userId] ?? null : null;
|
|
14
|
+
// Follower count helpers
|
|
15
|
+
const followerCount = isSingleUser && userId ? followState.followerCounts[userId] ?? null : null;
|
|
16
|
+
const followingCount = isSingleUser && userId ? followState.followingCounts[userId] ?? null : null;
|
|
17
|
+
const isLoadingCounts = isSingleUser && userId ? followState.loadingCounts[userId] ?? false : false;
|
|
18
|
+
const toggleFollow = useCallback(async () => {
|
|
19
|
+
if (!isSingleUser || !userId)
|
|
20
|
+
throw new Error('toggleFollow is only available for single user mode');
|
|
21
|
+
await followState.toggleFollowUser(userId, oxyServices, isFollowing);
|
|
22
|
+
}, [isSingleUser, userId, followState, oxyServices, isFollowing]);
|
|
23
|
+
const setFollowStatus = useCallback((following) => {
|
|
24
|
+
if (!isSingleUser || !userId)
|
|
25
|
+
throw new Error('setFollowStatus is only available for single user mode');
|
|
26
|
+
followState.setFollowingStatus(userId, following);
|
|
27
|
+
}, [isSingleUser, userId, followState]);
|
|
28
|
+
const fetchStatus = useCallback(async () => {
|
|
29
|
+
if (!isSingleUser || !userId)
|
|
30
|
+
throw new Error('fetchStatus is only available for single user mode');
|
|
31
|
+
await followState.fetchFollowStatus(userId, oxyServices);
|
|
32
|
+
}, [isSingleUser, userId, followState, oxyServices]);
|
|
33
|
+
const clearError = useCallback(() => {
|
|
34
|
+
if (!isSingleUser || !userId)
|
|
35
|
+
throw new Error('clearError is only available for single user mode');
|
|
36
|
+
followState.clearFollowError(userId);
|
|
37
|
+
}, [isSingleUser, userId, followState]);
|
|
38
|
+
const fetchUserCounts = useCallback(async () => {
|
|
39
|
+
if (!isSingleUser || !userId)
|
|
40
|
+
throw new Error('fetchUserCounts is only available for single user mode');
|
|
41
|
+
await followState.fetchUserCounts(userId, oxyServices);
|
|
42
|
+
}, [isSingleUser, userId, followState, oxyServices]);
|
|
43
|
+
const setFollowerCount = useCallback((count) => {
|
|
44
|
+
if (!isSingleUser || !userId)
|
|
45
|
+
throw new Error('setFollowerCount is only available for single user mode');
|
|
46
|
+
followState.setFollowerCount(userId, count);
|
|
47
|
+
}, [isSingleUser, userId, followState]);
|
|
48
|
+
const setFollowingCount = useCallback((count) => {
|
|
49
|
+
if (!isSingleUser || !userId)
|
|
50
|
+
throw new Error('setFollowingCount is only available for single user mode');
|
|
51
|
+
followState.setFollowingCount(userId, count);
|
|
52
|
+
}, [isSingleUser, userId, followState]);
|
|
53
|
+
// Auto-fetch counts when hook is used for a single user and counts are missing.
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
if (!isSingleUser || !userId)
|
|
56
|
+
return;
|
|
57
|
+
// If either count is not set and we're not already loading counts, trigger a fetch.
|
|
58
|
+
if ((followerCount === null || followingCount === null) && !isLoadingCounts) {
|
|
59
|
+
fetchUserCounts().catch((err) => console.warn('useFollow: fetchUserCounts failed', err));
|
|
60
|
+
}
|
|
61
|
+
}, [isSingleUser, userId, followerCount, followingCount, isLoadingCounts, fetchUserCounts]);
|
|
62
|
+
// Multiple user helpers
|
|
63
|
+
const followData = useMemo(() => {
|
|
64
|
+
const data = {};
|
|
65
|
+
userIds.forEach(uid => {
|
|
66
|
+
data[uid] = {
|
|
67
|
+
isFollowing: followState.followingUsers[uid] ?? false,
|
|
68
|
+
isLoading: followState.loadingUsers[uid] ?? false,
|
|
69
|
+
error: followState.errors[uid] ?? null,
|
|
70
|
+
};
|
|
71
|
+
});
|
|
72
|
+
return data;
|
|
73
|
+
}, [userIds, followState.followingUsers, followState.loadingUsers, followState.errors]);
|
|
74
|
+
const toggleFollowForUser = useCallback(async (targetUserId) => {
|
|
75
|
+
const currentState = followState.followingUsers[targetUserId] ?? false;
|
|
76
|
+
await followState.toggleFollowUser(targetUserId, oxyServices, currentState);
|
|
77
|
+
}, [followState, oxyServices]);
|
|
78
|
+
const setFollowStatusForUser = useCallback((targetUserId, following) => {
|
|
79
|
+
followState.setFollowingStatus(targetUserId, following);
|
|
80
|
+
}, [followState]);
|
|
81
|
+
const fetchStatusForUser = useCallback(async (targetUserId) => {
|
|
82
|
+
await followState.fetchFollowStatus(targetUserId, oxyServices);
|
|
83
|
+
}, [followState, oxyServices]);
|
|
84
|
+
const fetchAllStatuses = useCallback(async () => {
|
|
85
|
+
await Promise.all(userIds.map(uid => followState.fetchFollowStatus(uid, oxyServices)));
|
|
86
|
+
}, [userIds, followState, oxyServices]);
|
|
87
|
+
const clearErrorForUser = useCallback((targetUserId) => {
|
|
88
|
+
followState.clearFollowError(targetUserId);
|
|
89
|
+
}, [followState]);
|
|
90
|
+
const updateCountsFromFollowAction = useCallback((targetUserId, action, counts) => {
|
|
91
|
+
const currentUserId = oxyServices.getCurrentUserId() || undefined;
|
|
92
|
+
followState.updateCountsFromFollowAction(targetUserId, action, counts, currentUserId);
|
|
93
|
+
}, [followState, oxyServices]);
|
|
94
|
+
// Aggregate helpers for multiple users
|
|
95
|
+
const isAnyLoading = userIds.some(uid => followState.loadingUsers[uid]);
|
|
96
|
+
const hasAnyError = userIds.some(uid => !!followState.errors[uid]);
|
|
97
|
+
const allFollowing = userIds.every(uid => followState.followingUsers[uid]);
|
|
98
|
+
const allNotFollowing = userIds.every(uid => !followState.followingUsers[uid]);
|
|
99
|
+
if (isSingleUser && userId) {
|
|
100
|
+
return {
|
|
101
|
+
isFollowing,
|
|
102
|
+
isLoading,
|
|
103
|
+
error,
|
|
104
|
+
toggleFollow,
|
|
105
|
+
setFollowStatus,
|
|
106
|
+
fetchStatus,
|
|
107
|
+
clearError,
|
|
108
|
+
// Follower count methods
|
|
109
|
+
followerCount,
|
|
110
|
+
followingCount,
|
|
111
|
+
isLoadingCounts,
|
|
112
|
+
fetchUserCounts,
|
|
113
|
+
setFollowerCount,
|
|
114
|
+
setFollowingCount,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
followData,
|
|
119
|
+
toggleFollowForUser,
|
|
120
|
+
setFollowStatusForUser,
|
|
121
|
+
fetchStatusForUser,
|
|
122
|
+
fetchAllStatuses,
|
|
123
|
+
clearErrorForUser,
|
|
124
|
+
isAnyLoading,
|
|
125
|
+
hasAnyError,
|
|
126
|
+
allFollowing,
|
|
127
|
+
allNotFollowing,
|
|
128
|
+
};
|
|
129
|
+
};
|
|
130
|
+
// Convenience hook for just follower counts
|
|
131
|
+
export const useFollowerCounts = (userId) => {
|
|
132
|
+
const { oxyServices } = useWebOxy();
|
|
133
|
+
const followState = useFollowStore();
|
|
134
|
+
const followerCount = followState.followerCounts[userId] ?? null;
|
|
135
|
+
const followingCount = followState.followingCounts[userId] ?? null;
|
|
136
|
+
const isLoadingCounts = followState.loadingCounts[userId] ?? false;
|
|
137
|
+
const fetchUserCounts = useCallback(async () => {
|
|
138
|
+
await followState.fetchUserCounts(userId, oxyServices);
|
|
139
|
+
}, [userId, followState, oxyServices]);
|
|
140
|
+
const setFollowerCount = useCallback((count) => {
|
|
141
|
+
followState.setFollowerCount(userId, count);
|
|
142
|
+
}, [userId, followState]);
|
|
143
|
+
const setFollowingCount = useCallback((count) => {
|
|
144
|
+
followState.setFollowingCount(userId, count);
|
|
145
|
+
}, [userId, followState]);
|
|
146
|
+
return {
|
|
147
|
+
followerCount,
|
|
148
|
+
followingCount,
|
|
149
|
+
isLoadingCounts,
|
|
150
|
+
fetchUserCounts,
|
|
151
|
+
setFollowerCount,
|
|
152
|
+
setFollowingCount,
|
|
153
|
+
};
|
|
154
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { useQueryClient as useTanStackQueryClient } from '@tanstack/react-query';
|
|
2
|
+
/**
|
|
3
|
+
* Custom hook to access the QueryClient
|
|
4
|
+
* Provides type safety and ensures client is available
|
|
5
|
+
*/
|
|
6
|
+
export const useQueryClient = () => {
|
|
7
|
+
const queryClient = useTanStackQueryClient();
|
|
8
|
+
if (!queryClient) {
|
|
9
|
+
throw new Error('QueryClient is not available. Make sure OxyProvider is wrapping your app.');
|
|
10
|
+
}
|
|
11
|
+
return queryClient;
|
|
12
|
+
};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
|
+
import io from 'socket.io-client';
|
|
3
|
+
import { toast } from 'sonner';
|
|
4
|
+
import { logger } from '@oxyhq/core';
|
|
5
|
+
import { createDebugLogger } from '@oxyhq/core';
|
|
6
|
+
const debug = createDebugLogger('SessionSocket');
|
|
7
|
+
export function useSessionSocket({ userId, activeSessionId, currentDeviceId, refreshSessions, logout, clearSessionState, baseURL, onRemoteSignOut, onSessionRemoved }) {
|
|
8
|
+
const socketRef = useRef(null);
|
|
9
|
+
const joinedRoomRef = useRef(null);
|
|
10
|
+
// Store callbacks in refs to avoid re-joining when they change
|
|
11
|
+
const refreshSessionsRef = useRef(refreshSessions);
|
|
12
|
+
const logoutRef = useRef(logout);
|
|
13
|
+
const clearSessionStateRef = useRef(clearSessionState);
|
|
14
|
+
const onRemoteSignOutRef = useRef(onRemoteSignOut);
|
|
15
|
+
const onSessionRemovedRef = useRef(onSessionRemoved);
|
|
16
|
+
const activeSessionIdRef = useRef(activeSessionId);
|
|
17
|
+
const currentDeviceIdRef = useRef(currentDeviceId);
|
|
18
|
+
// Update refs when callbacks change
|
|
19
|
+
useEffect(() => {
|
|
20
|
+
refreshSessionsRef.current = refreshSessions;
|
|
21
|
+
logoutRef.current = logout;
|
|
22
|
+
clearSessionStateRef.current = clearSessionState;
|
|
23
|
+
onRemoteSignOutRef.current = onRemoteSignOut;
|
|
24
|
+
onSessionRemovedRef.current = onSessionRemoved;
|
|
25
|
+
activeSessionIdRef.current = activeSessionId;
|
|
26
|
+
currentDeviceIdRef.current = currentDeviceId;
|
|
27
|
+
}, [refreshSessions, logout, clearSessionState, onRemoteSignOut, onSessionRemoved, activeSessionId, currentDeviceId]);
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
if (!userId || !baseURL) {
|
|
30
|
+
// Clean up if userId or baseURL becomes invalid
|
|
31
|
+
if (socketRef.current && joinedRoomRef.current) {
|
|
32
|
+
socketRef.current.emit('leave', { userId: joinedRoomRef.current });
|
|
33
|
+
joinedRoomRef.current = null;
|
|
34
|
+
}
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const roomId = `user:${userId}`;
|
|
38
|
+
// Only create socket if it doesn't exist
|
|
39
|
+
if (!socketRef.current) {
|
|
40
|
+
socketRef.current = io(baseURL, {
|
|
41
|
+
transports: ['websocket'],
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const socket = socketRef.current;
|
|
45
|
+
// Only join if we haven't already joined this room
|
|
46
|
+
if (joinedRoomRef.current !== roomId) {
|
|
47
|
+
// Leave previous room if switching users
|
|
48
|
+
if (joinedRoomRef.current) {
|
|
49
|
+
socket.emit('leave', { userId: joinedRoomRef.current });
|
|
50
|
+
}
|
|
51
|
+
socket.emit('join', { userId: roomId });
|
|
52
|
+
joinedRoomRef.current = roomId;
|
|
53
|
+
debug.log('Emitting join for room:', roomId);
|
|
54
|
+
}
|
|
55
|
+
// Set up event handlers (only once per socket instance)
|
|
56
|
+
const handleConnect = () => {
|
|
57
|
+
debug.log('Socket connected:', socket.id);
|
|
58
|
+
};
|
|
59
|
+
const handleSessionUpdate = async (data) => {
|
|
60
|
+
debug.log('Received session_update:', data);
|
|
61
|
+
const currentActiveSessionId = activeSessionIdRef.current;
|
|
62
|
+
const currentDeviceId = currentDeviceIdRef.current;
|
|
63
|
+
// Handle different event types
|
|
64
|
+
if (data.type === 'session_removed') {
|
|
65
|
+
// Track removed session
|
|
66
|
+
if (data.sessionId && onSessionRemovedRef.current) {
|
|
67
|
+
onSessionRemovedRef.current(data.sessionId);
|
|
68
|
+
}
|
|
69
|
+
// If the removed sessionId matches the current activeSessionId, immediately clear state
|
|
70
|
+
if (data.sessionId === currentActiveSessionId) {
|
|
71
|
+
if (onRemoteSignOutRef.current) {
|
|
72
|
+
onRemoteSignOutRef.current();
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
toast.info('You have been signed out remotely.');
|
|
76
|
+
}
|
|
77
|
+
// Use clearSessionState since session was already removed server-side
|
|
78
|
+
// Await to ensure storage cleanup completes before continuing
|
|
79
|
+
try {
|
|
80
|
+
await clearSessionStateRef.current();
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (__DEV__) {
|
|
84
|
+
logger.error('Failed to clear session state after session_removed', error instanceof Error ? error : new Error(String(error)), { component: 'useSessionSocket' });
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
// Otherwise, just refresh the sessions list (with error handling)
|
|
90
|
+
refreshSessionsRef.current().catch((error) => {
|
|
91
|
+
// Silently handle errors from refresh - they're expected if sessions were removed
|
|
92
|
+
if (__DEV__) {
|
|
93
|
+
logger.debug('Failed to refresh sessions after session_removed', { component: 'useSessionSocket' }, error);
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
else if (data.type === 'device_removed') {
|
|
99
|
+
// Track all removed sessions from this device
|
|
100
|
+
if (data.sessionIds && onSessionRemovedRef.current) {
|
|
101
|
+
for (const sessionId of data.sessionIds) {
|
|
102
|
+
onSessionRemovedRef.current(sessionId);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
// If the removed deviceId matches the current device, immediately clear state
|
|
106
|
+
if (data.deviceId && data.deviceId === currentDeviceId) {
|
|
107
|
+
if (onRemoteSignOutRef.current) {
|
|
108
|
+
onRemoteSignOutRef.current();
|
|
109
|
+
}
|
|
110
|
+
else {
|
|
111
|
+
toast.info('This device has been removed. You have been signed out.');
|
|
112
|
+
}
|
|
113
|
+
// Use clearSessionState since sessions were already removed server-side
|
|
114
|
+
// Await to ensure storage cleanup completes before continuing
|
|
115
|
+
try {
|
|
116
|
+
await clearSessionStateRef.current();
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
if (__DEV__) {
|
|
120
|
+
logger.error('Failed to clear session state after device_removed', error instanceof Error ? error : new Error(String(error)), { component: 'useSessionSocket' });
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
// Otherwise, refresh sessions and device list (with error handling)
|
|
126
|
+
refreshSessionsRef.current().catch((error) => {
|
|
127
|
+
// Silently handle errors from refresh - they're expected if sessions were removed
|
|
128
|
+
if (__DEV__) {
|
|
129
|
+
logger.debug('Failed to refresh sessions after device_removed', { component: 'useSessionSocket' }, error);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
else if (data.type === 'sessions_removed') {
|
|
135
|
+
// Track all removed sessions
|
|
136
|
+
if (data.sessionIds && onSessionRemovedRef.current) {
|
|
137
|
+
for (const sessionId of data.sessionIds) {
|
|
138
|
+
onSessionRemovedRef.current(sessionId);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
// If the current activeSessionId is in the removed sessionIds list, immediately clear state
|
|
142
|
+
if (data.sessionIds && currentActiveSessionId && data.sessionIds.includes(currentActiveSessionId)) {
|
|
143
|
+
if (onRemoteSignOutRef.current) {
|
|
144
|
+
onRemoteSignOutRef.current();
|
|
145
|
+
}
|
|
146
|
+
else {
|
|
147
|
+
toast.info('You have been signed out remotely.');
|
|
148
|
+
}
|
|
149
|
+
// Use clearSessionState since sessions were already removed server-side
|
|
150
|
+
// Await to ensure storage cleanup completes before continuing
|
|
151
|
+
try {
|
|
152
|
+
await clearSessionStateRef.current();
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
if (__DEV__) {
|
|
156
|
+
logger.error('Failed to clear session state after sessions_removed', error instanceof Error ? error : new Error(String(error)), { component: 'useSessionSocket' });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
else {
|
|
161
|
+
// Otherwise, refresh sessions list (with error handling)
|
|
162
|
+
refreshSessionsRef.current().catch((error) => {
|
|
163
|
+
// Silently handle errors from refresh - they're expected if sessions were removed
|
|
164
|
+
if (__DEV__) {
|
|
165
|
+
logger.debug('Failed to refresh sessions after sessions_removed', { component: 'useSessionSocket' }, error);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
// For other event types (e.g., session_created), refresh sessions (with error handling)
|
|
172
|
+
refreshSessionsRef.current().catch((error) => {
|
|
173
|
+
// Log but don't throw - refresh errors shouldn't break the socket handler
|
|
174
|
+
if (__DEV__) {
|
|
175
|
+
logger.debug('Failed to refresh sessions after session_update', { component: 'useSessionSocket' }, error);
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
// If the current session was logged out (legacy behavior), handle it specially
|
|
179
|
+
if (data.sessionId === currentActiveSessionId) {
|
|
180
|
+
if (onRemoteSignOutRef.current) {
|
|
181
|
+
onRemoteSignOutRef.current();
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
toast.info('You have been signed out remotely.');
|
|
185
|
+
}
|
|
186
|
+
// Use clearSessionState since session was already removed server-side
|
|
187
|
+
// Await to ensure storage cleanup completes before continuing
|
|
188
|
+
try {
|
|
189
|
+
await clearSessionStateRef.current();
|
|
190
|
+
}
|
|
191
|
+
catch (error) {
|
|
192
|
+
debug.error('Failed to clear session state after session_update:', error);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
socket.on('connect', handleConnect);
|
|
198
|
+
socket.on('session_update', handleSessionUpdate);
|
|
199
|
+
return () => {
|
|
200
|
+
socket.off('connect', handleConnect);
|
|
201
|
+
socket.off('session_update', handleSessionUpdate);
|
|
202
|
+
// Only leave on unmount if we're still in this room
|
|
203
|
+
if (joinedRoomRef.current === roomId) {
|
|
204
|
+
socket.emit('leave', { userId: roomId });
|
|
205
|
+
joinedRoomRef.current = null;
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
}, [userId, baseURL]); // Only depend on userId and baseURL - callbacks are in refs
|
|
209
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web SSO Hook
|
|
3
|
+
*
|
|
4
|
+
* Handles cross-domain SSO for web apps using FedCM (Federated Credential Management).
|
|
5
|
+
*
|
|
6
|
+
* FedCM is the modern, privacy-preserving standard for cross-domain identity federation.
|
|
7
|
+
* It works across completely different TLDs (alia.onl, mention.earth, homiio.com, etc.)
|
|
8
|
+
* without relying on third-party cookies.
|
|
9
|
+
*
|
|
10
|
+
* For browsers without FedCM support, users will need to click a sign-in button
|
|
11
|
+
* which triggers a popup-based authentication flow.
|
|
12
|
+
*
|
|
13
|
+
* This is called automatically by OxyContext on web platforms.
|
|
14
|
+
*
|
|
15
|
+
* @see https://developer.mozilla.org/en-US/docs/Web/API/FedCM_API
|
|
16
|
+
*/
|
|
17
|
+
import { useEffect, useRef, useCallback } from 'react';
|
|
18
|
+
/**
|
|
19
|
+
* Check if we're running in a web browser environment (not React Native)
|
|
20
|
+
*/
|
|
21
|
+
function isWebBrowser() {
|
|
22
|
+
return typeof window !== 'undefined' &&
|
|
23
|
+
typeof document !== 'undefined' &&
|
|
24
|
+
typeof document.documentElement !== 'undefined';
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Check if we're on the identity provider domain (where FedCM would authenticate against itself)
|
|
28
|
+
* Only auth.oxy.so is the IdP - accounts.oxy.so is a client app like any other
|
|
29
|
+
*/
|
|
30
|
+
function isIdentityProvider() {
|
|
31
|
+
if (!isWebBrowser())
|
|
32
|
+
return false;
|
|
33
|
+
const hostname = window.location.hostname;
|
|
34
|
+
return hostname === 'auth.oxy.so';
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Hook for automatic cross-domain web SSO
|
|
38
|
+
*
|
|
39
|
+
* Uses FedCM (Federated Credential Management) - the modern browser-native
|
|
40
|
+
* identity federation API. This is the same technology that powers
|
|
41
|
+
* Google's cross-domain SSO (YouTube, Gmail, Maps, etc.).
|
|
42
|
+
*
|
|
43
|
+
* Key benefits:
|
|
44
|
+
* - Works across different TLDs (alia.onl ↔ mention.earth ↔ homiio.com)
|
|
45
|
+
* - No third-party cookies required
|
|
46
|
+
* - Privacy-preserving (browser mediates identity, IdP can't track)
|
|
47
|
+
* - Automatic silent sign-in after initial authentication
|
|
48
|
+
*
|
|
49
|
+
* For browsers without FedCM (Firefox, older browsers), automatic SSO
|
|
50
|
+
* is not possible. Users will see a sign-in button instead.
|
|
51
|
+
*/
|
|
52
|
+
export function useWebSSO({ oxyServices, onSessionFound, onSSOUnavailable, onError, enabled = true, }) {
|
|
53
|
+
const isCheckingRef = useRef(false);
|
|
54
|
+
const hasCheckedRef = useRef(false);
|
|
55
|
+
// Check FedCM support once
|
|
56
|
+
const fedCMSupported = isWebBrowser() && oxyServices.isFedCMSupported?.();
|
|
57
|
+
const checkSSO = useCallback(async () => {
|
|
58
|
+
if (!isWebBrowser() || isCheckingRef.current) {
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
// Don't use FedCM on the auth domain itself - it would authenticate against itself
|
|
62
|
+
if (isIdentityProvider()) {
|
|
63
|
+
onSSOUnavailable?.();
|
|
64
|
+
return null;
|
|
65
|
+
}
|
|
66
|
+
// FedCM is the only reliable cross-domain SSO mechanism
|
|
67
|
+
if (!fedCMSupported) {
|
|
68
|
+
onSSOUnavailable?.();
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
isCheckingRef.current = true;
|
|
72
|
+
try {
|
|
73
|
+
const session = await oxyServices.silentSignInWithFedCM?.();
|
|
74
|
+
if (session) {
|
|
75
|
+
await onSessionFound(session);
|
|
76
|
+
return session;
|
|
77
|
+
}
|
|
78
|
+
onSSOUnavailable?.();
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
catch (error) {
|
|
82
|
+
onSSOUnavailable?.();
|
|
83
|
+
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
isCheckingRef.current = false;
|
|
88
|
+
}
|
|
89
|
+
}, [oxyServices, onSessionFound, onSSOUnavailable, onError, fedCMSupported]);
|
|
90
|
+
/**
|
|
91
|
+
* Trigger interactive FedCM sign-in
|
|
92
|
+
* This shows the browser's native "Sign in with Oxy" prompt.
|
|
93
|
+
* Use this when silent mediation fails (user hasn't previously consented).
|
|
94
|
+
*/
|
|
95
|
+
const signInWithFedCM = useCallback(async () => {
|
|
96
|
+
if (!isWebBrowser() || isCheckingRef.current) {
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
if (!fedCMSupported) {
|
|
100
|
+
onError?.(new Error('FedCM is not supported in this browser'));
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
isCheckingRef.current = true;
|
|
104
|
+
try {
|
|
105
|
+
const session = await oxyServices.signInWithFedCM?.();
|
|
106
|
+
if (session) {
|
|
107
|
+
await onSessionFound(session);
|
|
108
|
+
return session;
|
|
109
|
+
}
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
onError?.(error instanceof Error ? error : new Error(String(error)));
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
isCheckingRef.current = false;
|
|
118
|
+
}
|
|
119
|
+
}, [oxyServices, onSessionFound, onError, fedCMSupported]);
|
|
120
|
+
// Auto-check SSO on mount (web only, FedCM only, not on auth domain)
|
|
121
|
+
useEffect(() => {
|
|
122
|
+
if (!enabled || !isWebBrowser() || hasCheckedRef.current || isIdentityProvider()) {
|
|
123
|
+
if (isIdentityProvider()) {
|
|
124
|
+
onSSOUnavailable?.();
|
|
125
|
+
}
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
hasCheckedRef.current = true;
|
|
129
|
+
if (fedCMSupported) {
|
|
130
|
+
checkSSO();
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
onSSOUnavailable?.();
|
|
134
|
+
}
|
|
135
|
+
}, [enabled, checkSSO, fedCMSupported, onSSOUnavailable]);
|
|
136
|
+
return {
|
|
137
|
+
checkSSO,
|
|
138
|
+
signInWithFedCM,
|
|
139
|
+
isChecking: isCheckingRef.current,
|
|
140
|
+
isFedCMSupported: fedCMSupported,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
export { isWebBrowser };
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @oxyhq/auth — OxyHQ Web Authentication SDK
|
|
3
|
+
*
|
|
4
|
+
* Headless authentication for React web apps (Next.js, Vite, CRA).
|
|
5
|
+
* Zero React Native / Expo dependencies.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```tsx
|
|
9
|
+
* import { WebOxyProvider, useAuth } from '@oxyhq/auth';
|
|
10
|
+
*
|
|
11
|
+
* function App() {
|
|
12
|
+
* return (
|
|
13
|
+
* <WebOxyProvider baseURL="https://api.oxy.so">
|
|
14
|
+
* <YourApp />
|
|
15
|
+
* </WebOxyProvider>
|
|
16
|
+
* );
|
|
17
|
+
* }
|
|
18
|
+
*
|
|
19
|
+
* function YourApp() {
|
|
20
|
+
* const { user, isAuthenticated, signIn, signOut } = useAuth();
|
|
21
|
+
* // ...
|
|
22
|
+
* }
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
// --- Provider & Hooks ---
|
|
26
|
+
export { WebOxyProvider, useWebOxy, useAuth } from './WebOxyProvider';
|
|
27
|
+
// --- Stores ---
|
|
28
|
+
export { useAuthStore } from './stores/authStore';
|
|
29
|
+
export { useAssetStore, useAssets as useAssetsStore, useAsset, useUploadProgress, useAssetLoading, useAssetErrors, useAssetsByApp, useAssetsByEntity, useAssetUsageCount, useIsAssetLinked, } from './stores/assetStore';
|
|
30
|
+
// --- Query Hooks ---
|
|
31
|
+
export { useUserProfile, useUserProfiles, useCurrentUser, useUserById, useUserByUsername, useUsersBySessions, usePrivacySettings, useSessions, useSession, useDeviceSessions, useUserDevices, useSecurityInfo, useSecurityActivity, useRecentSecurityActivity, } from './hooks/queries';
|
|
32
|
+
// --- Mutation Hooks ---
|
|
33
|
+
export { useUpdateProfile, useUploadAvatar, useUpdateAccountSettings, useUpdatePrivacySettings, useUploadFile, useSwitchSession, useLogoutSession, useLogoutAll, useUpdateDeviceName, useRemoveDevice, } from './hooks/mutations';
|
|
34
|
+
export { createProfileMutation, createGenericMutation, } from './hooks/mutations/mutationFactory';
|
|
35
|
+
// --- Custom Hooks ---
|
|
36
|
+
export { useSessionSocket } from './hooks/useSessionSocket';
|
|
37
|
+
export { useAssets, setOxyAssetInstance } from './hooks/useAssets';
|
|
38
|
+
export { useFileDownloadUrl, setOxyFileUrlInstance } from './hooks/useFileDownloadUrl';
|
|
39
|
+
export { useFollow, useFollowerCounts } from './hooks/useFollow';
|
|
40
|
+
export { useFileFiltering } from './hooks/useFileFiltering';
|
|
41
|
+
// --- Auth Helpers ---
|
|
42
|
+
export { ensureValidToken, withAuthErrorHandling, authenticatedApiCall, isAuthenticationError, SessionSyncRequiredError, AuthenticationFailedError, } from './utils/authHelpers';
|
|
43
|
+
// --- Error Handlers ---
|
|
44
|
+
export { handleAuthError, isInvalidSessionError, isTimeoutOrNetworkError, extractErrorMessage, } from './utils/errorHandlers';
|
|
45
|
+
// Re-export core for convenience
|
|
46
|
+
export { OxyServices, CrossDomainAuth, AuthManager, createAuthManager, createCrossDomainAuth, } from '@oxyhq/core';
|
|
47
|
+
import { WebOxyProvider as _WebOxyProvider } from './WebOxyProvider';
|
|
48
|
+
export default _WebOxyProvider;
|