@oxyhq/services 5.21.6 → 5.21.7

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.
Files changed (129) hide show
  1. package/lib/commonjs/crypto/keyManager.js +67 -22
  2. package/lib/commonjs/crypto/keyManager.js.map +1 -1
  3. package/lib/commonjs/index.js +66 -0
  4. package/lib/commonjs/index.js.map +1 -1
  5. package/lib/commonjs/ui/components/fileManagement/AnimatedButton.js +57 -0
  6. package/lib/commonjs/ui/components/fileManagement/AnimatedButton.js.map +1 -0
  7. package/lib/commonjs/ui/components/profile/EditBioModal.js +24 -156
  8. package/lib/commonjs/ui/components/profile/EditBioModal.js.map +1 -1
  9. package/lib/commonjs/ui/components/profile/EditDisplayNameModal.js +28 -178
  10. package/lib/commonjs/ui/components/profile/EditDisplayNameModal.js.map +1 -1
  11. package/lib/commonjs/ui/components/profile/EditEmailModal.js +32 -159
  12. package/lib/commonjs/ui/components/profile/EditEmailModal.js.map +1 -1
  13. package/lib/commonjs/ui/components/profile/EditLocationModal.js +45 -227
  14. package/lib/commonjs/ui/components/profile/EditLocationModal.js.map +1 -1
  15. package/lib/commonjs/ui/components/profile/EditUsernameModal.js +30 -155
  16. package/lib/commonjs/ui/components/profile/EditUsernameModal.js.map +1 -1
  17. package/lib/commonjs/ui/hooks/mutations/mutationFactory.js +177 -0
  18. package/lib/commonjs/ui/hooks/mutations/mutationFactory.js.map +1 -0
  19. package/lib/commonjs/ui/hooks/mutations/useAccountMutations.js +10 -123
  20. package/lib/commonjs/ui/hooks/mutations/useAccountMutations.js.map +1 -1
  21. package/lib/commonjs/ui/hooks/queries/useAccountQueries.js +2 -32
  22. package/lib/commonjs/ui/hooks/queries/useAccountQueries.js.map +1 -1
  23. package/lib/commonjs/ui/hooks/queries/useServicesQueries.js +2 -31
  24. package/lib/commonjs/ui/hooks/queries/useServicesQueries.js.map +1 -1
  25. package/lib/commonjs/ui/hooks/useFileFiltering.js +76 -0
  26. package/lib/commonjs/ui/hooks/useFileFiltering.js.map +1 -0
  27. package/lib/commonjs/ui/screens/FileManagementScreen.js +2 -2
  28. package/lib/commonjs/ui/screens/FileManagementScreen.js.map +1 -1
  29. package/lib/commonjs/ui/utils/authHelpers.js +164 -0
  30. package/lib/commonjs/ui/utils/authHelpers.js.map +1 -0
  31. package/lib/commonjs/ui/utils/avatarUtils.js +18 -61
  32. package/lib/commonjs/ui/utils/avatarUtils.js.map +1 -1
  33. package/lib/module/crypto/keyManager.js +67 -22
  34. package/lib/module/crypto/keyManager.js.map +1 -1
  35. package/lib/module/index.js +6 -0
  36. package/lib/module/index.js.map +1 -1
  37. package/lib/module/ui/components/fileManagement/AnimatedButton.js +50 -0
  38. package/lib/module/ui/components/fileManagement/AnimatedButton.js.map +1 -0
  39. package/lib/module/ui/components/profile/EditBioModal.js +24 -156
  40. package/lib/module/ui/components/profile/EditBioModal.js.map +1 -1
  41. package/lib/module/ui/components/profile/EditDisplayNameModal.js +28 -178
  42. package/lib/module/ui/components/profile/EditDisplayNameModal.js.map +1 -1
  43. package/lib/module/ui/components/profile/EditEmailModal.js +32 -159
  44. package/lib/module/ui/components/profile/EditEmailModal.js.map +1 -1
  45. package/lib/module/ui/components/profile/EditLocationModal.js +45 -227
  46. package/lib/module/ui/components/profile/EditLocationModal.js.map +1 -1
  47. package/lib/module/ui/components/profile/EditUsernameModal.js +30 -155
  48. package/lib/module/ui/components/profile/EditUsernameModal.js.map +1 -1
  49. package/lib/module/ui/hooks/mutations/mutationFactory.js +173 -0
  50. package/lib/module/ui/hooks/mutations/mutationFactory.js.map +1 -0
  51. package/lib/module/ui/hooks/mutations/useAccountMutations.js +10 -122
  52. package/lib/module/ui/hooks/mutations/useAccountMutations.js.map +1 -1
  53. package/lib/module/ui/hooks/queries/useAccountQueries.js +2 -32
  54. package/lib/module/ui/hooks/queries/useAccountQueries.js.map +1 -1
  55. package/lib/module/ui/hooks/queries/useServicesQueries.js +2 -31
  56. package/lib/module/ui/hooks/queries/useServicesQueries.js.map +1 -1
  57. package/lib/module/ui/hooks/useFileFiltering.js +72 -0
  58. package/lib/module/ui/hooks/useFileFiltering.js.map +1 -0
  59. package/lib/module/ui/screens/FileManagementScreen.js +2 -2
  60. package/lib/module/ui/screens/FileManagementScreen.js.map +1 -1
  61. package/lib/module/ui/utils/authHelpers.js +154 -0
  62. package/lib/module/ui/utils/authHelpers.js.map +1 -0
  63. package/lib/module/ui/utils/avatarUtils.js +18 -61
  64. package/lib/module/ui/utils/avatarUtils.js.map +1 -1
  65. package/lib/typescript/commonjs/crypto/keyManager.d.ts.map +1 -1
  66. package/lib/typescript/commonjs/index.d.ts +6 -0
  67. package/lib/typescript/commonjs/index.d.ts.map +1 -1
  68. package/lib/typescript/commonjs/ui/components/fileManagement/AnimatedButton.d.ts +16 -0
  69. package/lib/typescript/commonjs/ui/components/fileManagement/AnimatedButton.d.ts.map +1 -0
  70. package/lib/typescript/commonjs/ui/components/profile/EditBioModal.d.ts.map +1 -1
  71. package/lib/typescript/commonjs/ui/components/profile/EditDisplayNameModal.d.ts.map +1 -1
  72. package/lib/typescript/commonjs/ui/components/profile/EditEmailModal.d.ts.map +1 -1
  73. package/lib/typescript/commonjs/ui/components/profile/EditLocationModal.d.ts +1 -0
  74. package/lib/typescript/commonjs/ui/components/profile/EditLocationModal.d.ts.map +1 -1
  75. package/lib/typescript/commonjs/ui/components/profile/EditUsernameModal.d.ts.map +1 -1
  76. package/lib/typescript/commonjs/ui/hooks/mutations/mutationFactory.d.ts +76 -0
  77. package/lib/typescript/commonjs/ui/hooks/mutations/mutationFactory.d.ts.map +1 -0
  78. package/lib/typescript/commonjs/ui/hooks/mutations/useAccountMutations.d.ts +29 -4
  79. package/lib/typescript/commonjs/ui/hooks/mutations/useAccountMutations.d.ts.map +1 -1
  80. package/lib/typescript/commonjs/ui/hooks/queries/useAccountQueries.d.ts +1 -1
  81. package/lib/typescript/commonjs/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  82. package/lib/typescript/commonjs/ui/hooks/queries/useServicesQueries.d.ts +1 -1
  83. package/lib/typescript/commonjs/ui/hooks/queries/useServicesQueries.d.ts.map +1 -1
  84. package/lib/typescript/commonjs/ui/hooks/useFileFiltering.d.ts +29 -0
  85. package/lib/typescript/commonjs/ui/hooks/useFileFiltering.d.ts.map +1 -0
  86. package/lib/typescript/commonjs/ui/utils/authHelpers.d.ts +99 -0
  87. package/lib/typescript/commonjs/ui/utils/authHelpers.d.ts.map +1 -0
  88. package/lib/typescript/commonjs/ui/utils/avatarUtils.d.ts.map +1 -1
  89. package/lib/typescript/module/crypto/keyManager.d.ts.map +1 -1
  90. package/lib/typescript/module/index.d.ts +6 -0
  91. package/lib/typescript/module/index.d.ts.map +1 -1
  92. package/lib/typescript/module/ui/components/fileManagement/AnimatedButton.d.ts +16 -0
  93. package/lib/typescript/module/ui/components/fileManagement/AnimatedButton.d.ts.map +1 -0
  94. package/lib/typescript/module/ui/components/profile/EditBioModal.d.ts.map +1 -1
  95. package/lib/typescript/module/ui/components/profile/EditDisplayNameModal.d.ts.map +1 -1
  96. package/lib/typescript/module/ui/components/profile/EditEmailModal.d.ts.map +1 -1
  97. package/lib/typescript/module/ui/components/profile/EditLocationModal.d.ts +1 -0
  98. package/lib/typescript/module/ui/components/profile/EditLocationModal.d.ts.map +1 -1
  99. package/lib/typescript/module/ui/components/profile/EditUsernameModal.d.ts.map +1 -1
  100. package/lib/typescript/module/ui/hooks/mutations/mutationFactory.d.ts +76 -0
  101. package/lib/typescript/module/ui/hooks/mutations/mutationFactory.d.ts.map +1 -0
  102. package/lib/typescript/module/ui/hooks/mutations/useAccountMutations.d.ts +29 -4
  103. package/lib/typescript/module/ui/hooks/mutations/useAccountMutations.d.ts.map +1 -1
  104. package/lib/typescript/module/ui/hooks/queries/useAccountQueries.d.ts +1 -1
  105. package/lib/typescript/module/ui/hooks/queries/useAccountQueries.d.ts.map +1 -1
  106. package/lib/typescript/module/ui/hooks/queries/useServicesQueries.d.ts +1 -1
  107. package/lib/typescript/module/ui/hooks/queries/useServicesQueries.d.ts.map +1 -1
  108. package/lib/typescript/module/ui/hooks/useFileFiltering.d.ts +29 -0
  109. package/lib/typescript/module/ui/hooks/useFileFiltering.d.ts.map +1 -0
  110. package/lib/typescript/module/ui/utils/authHelpers.d.ts +99 -0
  111. package/lib/typescript/module/ui/utils/authHelpers.d.ts.map +1 -0
  112. package/lib/typescript/module/ui/utils/avatarUtils.d.ts.map +1 -1
  113. package/package.json +1 -1
  114. package/src/crypto/keyManager.ts +23 -22
  115. package/src/index.ts +25 -0
  116. package/src/ui/components/fileManagement/AnimatedButton.tsx +56 -0
  117. package/src/ui/components/profile/EditBioModal.tsx +38 -176
  118. package/src/ui/components/profile/EditDisplayNameModal.tsx +48 -195
  119. package/src/ui/components/profile/EditEmailModal.tsx +49 -180
  120. package/src/ui/components/profile/EditLocationModal.tsx +76 -263
  121. package/src/ui/components/profile/EditUsernameModal.tsx +47 -175
  122. package/src/ui/hooks/mutations/mutationFactory.ts +215 -0
  123. package/src/ui/hooks/mutations/useAccountMutations.ts +48 -136
  124. package/src/ui/hooks/queries/useAccountQueries.ts +6 -33
  125. package/src/ui/hooks/queries/useServicesQueries.ts +6 -32
  126. package/src/ui/hooks/useFileFiltering.ts +115 -0
  127. package/src/ui/screens/FileManagementScreen.tsx +2 -2
  128. package/src/ui/utils/authHelpers.ts +183 -0
  129. package/src/ui/utils/avatarUtils.ts +25 -65
@@ -1,8 +1,8 @@
1
1
  import { useQuery, useQueries } from '@tanstack/react-query';
2
2
  import type { User } from '../../../models/interfaces';
3
- import type { OxyServices } from '../../../core';
4
3
  import { queryKeys } from './queryKeys';
5
4
  import { useOxy } from '../../context/OxyContext';
5
+ import { authenticatedApiCall } from '../../utils/authHelpers';
6
6
 
7
7
  /**
8
8
  * Get user profile by session ID
@@ -138,38 +138,11 @@ export const usePrivacySettings = (userId?: string, options?: { enabled?: boolea
138
138
  throw new Error('User ID is required');
139
139
  }
140
140
 
141
- // Ensure we have a valid token before making the request
142
- if (!oxyServices.hasValidToken() && activeSessionId) {
143
- try {
144
- // Try to get token for the session
145
- await oxyServices.getTokenBySession(activeSessionId);
146
- } catch (tokenError) {
147
- // If getting token fails, might be an offline session - try syncing
148
- const errorMessage = tokenError instanceof Error ? tokenError.message : String(tokenError);
149
- if (errorMessage.includes('AUTH_REQUIRED_OFFLINE_SESSION') || errorMessage.includes('offline')) {
150
- // Session sync should be handled by the app layer (e.g., accounts app's useIdentity hook)
151
- throw new Error('Session needs to be synced. Please try again.');
152
- } else {
153
- throw tokenError;
154
- }
155
- }
156
- }
157
-
158
- try {
159
- return await oxyServices.getPrivacySettings(targetUserId);
160
- } catch (error: any) {
161
- const errorMessage = error?.message || '';
162
- const status = error?.status || error?.response?.status;
163
-
164
- // Handle authentication errors
165
- if (status === 401 || errorMessage.includes('Authentication required') || errorMessage.includes('Invalid or missing authorization header')) {
166
- // Session sync should be handled by the app layer
167
- throw new Error('Authentication failed. Please sign in again.');
168
- }
169
-
170
- // TanStack Query will automatically retry on network errors
171
- throw error;
172
- }
141
+ return authenticatedApiCall(
142
+ oxyServices,
143
+ activeSessionId,
144
+ () => oxyServices.getPrivacySettings(targetUserId)
145
+ );
173
146
  },
174
147
  enabled: (options?.enabled !== false) && !!targetUserId,
175
148
  staleTime: 2 * 60 * 1000, // 2 minutes
@@ -3,6 +3,7 @@ import type { ClientSession } from '../../../models/session';
3
3
  import { queryKeys } from './queryKeys';
4
4
  import { useOxy } from '../../context/OxyContext';
5
5
  import { fetchSessionsWithFallback, mapSessionsToClient } from '../../utils/sessionHelpers';
6
+ import { authenticatedApiCall } from '../../utils/authHelpers';
6
7
 
7
8
  /**
8
9
  * Get all active sessions for the current user
@@ -94,38 +95,11 @@ export const useUserDevices = (options?: { enabled?: boolean }) => {
94
95
  return useQuery({
95
96
  queryKey: queryKeys.devices.list(),
96
97
  queryFn: async () => {
97
- // Ensure we have a valid token before making the request
98
- if (!oxyServices.hasValidToken() && activeSessionId) {
99
- try {
100
- // Try to get token for the session
101
- await oxyServices.getTokenBySession(activeSessionId);
102
- } catch (tokenError) {
103
- // If getting token fails, might be an offline session - try syncing
104
- const errorMessage = tokenError instanceof Error ? tokenError.message : String(tokenError);
105
- if (errorMessage.includes('AUTH_REQUIRED_OFFLINE_SESSION') || errorMessage.includes('offline')) {
106
- // Session sync should be handled by the app layer
107
- throw new Error('Session needs to be synced. Please try again.');
108
- } else {
109
- throw tokenError;
110
- }
111
- }
112
- }
113
-
114
- try {
115
- return await oxyServices.getUserDevices();
116
- } catch (error: any) {
117
- const errorMessage = error?.message || '';
118
- const status = error?.status || error?.response?.status;
119
-
120
- // Handle authentication errors
121
- if (status === 401 || errorMessage.includes('Authentication required') || errorMessage.includes('Invalid or missing authorization header')) {
122
- // Session sync should be handled by the app layer
123
- throw new Error('Authentication failed. Please sign in again.');
124
- }
125
-
126
- // TanStack Query will automatically retry on network errors
127
- throw error;
128
- }
98
+ return authenticatedApiCall(
99
+ oxyServices,
100
+ activeSessionId,
101
+ () => oxyServices.getUserDevices()
102
+ );
129
103
  },
130
104
  enabled: (options?.enabled !== false) && isAuthenticated,
131
105
  staleTime: 5 * 60 * 1000,
@@ -0,0 +1,115 @@
1
+ import { useMemo, useState, useCallback } from 'react';
2
+ import type { FileMetadata } from '../../models/interfaces';
3
+
4
+ export type ViewMode = 'all' | 'photos' | 'videos' | 'documents' | 'audio';
5
+ export type SortBy = 'date' | 'size' | 'name' | 'type';
6
+ export type SortOrder = 'asc' | 'desc';
7
+
8
+ interface UseFileFilteringOptions {
9
+ files: FileMetadata[];
10
+ initialViewMode?: ViewMode;
11
+ initialSortBy?: SortBy;
12
+ initialSortOrder?: SortOrder;
13
+ }
14
+
15
+ interface UseFileFilteringReturn {
16
+ filteredFiles: FileMetadata[];
17
+ viewMode: ViewMode;
18
+ setViewMode: (mode: ViewMode) => void;
19
+ searchQuery: string;
20
+ setSearchQuery: (query: string) => void;
21
+ sortBy: SortBy;
22
+ setSortBy: (sort: SortBy) => void;
23
+ sortOrder: SortOrder;
24
+ setSortOrder: (order: SortOrder) => void;
25
+ toggleSortOrder: () => void;
26
+ }
27
+
28
+ /**
29
+ * Hook for file filtering, sorting, and search functionality
30
+ * Extracts common file management logic for reuse across components
31
+ */
32
+ export function useFileFiltering({
33
+ files,
34
+ initialViewMode = 'all',
35
+ initialSortBy = 'date',
36
+ initialSortOrder = 'desc',
37
+ }: UseFileFilteringOptions): UseFileFilteringReturn {
38
+ const [viewMode, setViewMode] = useState<ViewMode>(initialViewMode);
39
+ const [searchQuery, setSearchQuery] = useState('');
40
+ const [sortBy, setSortBy] = useState<SortBy>(initialSortBy);
41
+ const [sortOrder, setSortOrder] = useState<SortOrder>(initialSortOrder);
42
+
43
+ const toggleSortOrder = useCallback(() => {
44
+ setSortOrder((prev) => (prev === 'asc' ? 'desc' : 'asc'));
45
+ }, []);
46
+
47
+ const filteredFiles = useMemo(() => {
48
+ // Filter by view mode
49
+ let filteredByMode = files;
50
+ if (viewMode === 'photos') {
51
+ filteredByMode = files.filter((file) => file.contentType.startsWith('image/'));
52
+ } else if (viewMode === 'videos') {
53
+ filteredByMode = files.filter((file) => file.contentType.startsWith('video/'));
54
+ } else if (viewMode === 'documents') {
55
+ filteredByMode = files.filter(
56
+ (file) =>
57
+ file.contentType.includes('pdf') ||
58
+ file.contentType.includes('document') ||
59
+ file.contentType.includes('text') ||
60
+ file.contentType.includes('msword') ||
61
+ file.contentType.includes('excel') ||
62
+ file.contentType.includes('spreadsheet') ||
63
+ file.contentType.includes('presentation') ||
64
+ file.contentType.includes('powerpoint')
65
+ );
66
+ } else if (viewMode === 'audio') {
67
+ filteredByMode = files.filter((file) => file.contentType.startsWith('audio/'));
68
+ }
69
+
70
+ // Filter by search query
71
+ let filtered = filteredByMode;
72
+ if (searchQuery.trim()) {
73
+ const query = searchQuery.toLowerCase();
74
+ filtered = filteredByMode.filter(
75
+ (file) =>
76
+ file.filename.toLowerCase().includes(query) ||
77
+ file.contentType.toLowerCase().includes(query) ||
78
+ (file.metadata?.description &&
79
+ file.metadata.description.toLowerCase().includes(query))
80
+ );
81
+ }
82
+
83
+ // Sort files
84
+ const sorted = [...filtered].sort((a, b) => {
85
+ let comparison = 0;
86
+ if (sortBy === 'date') {
87
+ const dateA = new Date(a.uploadDate || 0).getTime();
88
+ const dateB = new Date(b.uploadDate || 0).getTime();
89
+ comparison = dateA - dateB;
90
+ } else if (sortBy === 'size') {
91
+ comparison = (a.length || 0) - (b.length || 0);
92
+ } else if (sortBy === 'name') {
93
+ comparison = (a.filename || '').localeCompare(b.filename || '');
94
+ } else if (sortBy === 'type') {
95
+ comparison = (a.contentType || '').localeCompare(b.contentType || '');
96
+ }
97
+ return sortOrder === 'asc' ? comparison : -comparison;
98
+ });
99
+
100
+ return sorted;
101
+ }, [files, searchQuery, viewMode, sortBy, sortOrder]);
102
+
103
+ return {
104
+ filteredFiles,
105
+ viewMode,
106
+ setViewMode,
107
+ searchQuery,
108
+ setSearchQuery,
109
+ sortBy,
110
+ setSortBy,
111
+ sortOrder,
112
+ setSortOrder,
113
+ toggleSortOrder,
114
+ };
115
+ }
@@ -549,8 +549,8 @@ const FileManagementScreen: React.FC<FileManagementScreenProps> = ({
549
549
  });
550
550
 
551
551
  // Attempt to refresh file list incrementally – fetch single file metadata if API allows
552
- if (result?.file || result?.files?.[0]) {
553
- const f = result.file || result.files[0];
552
+ const f = result?.file ?? result?.files?.[0];
553
+ if (f) {
554
554
  const merged: FileMetadata = {
555
555
  id: f.id,
556
556
  filename: f.originalName || f.sha256 || raw.name,
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Authentication helper utilities to reduce code duplication across hooks and utilities.
3
+ * These functions handle common token validation and authentication error patterns.
4
+ */
5
+
6
+ import type { OxyServices } from '../../core';
7
+
8
+ /**
9
+ * Error thrown when session sync is required
10
+ */
11
+ export class SessionSyncRequiredError extends Error {
12
+ constructor(message = 'Session needs to be synced. Please try again.') {
13
+ super(message);
14
+ this.name = 'SessionSyncRequiredError';
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Error thrown when authentication fails
20
+ */
21
+ export class AuthenticationFailedError extends Error {
22
+ constructor(message = 'Authentication failed. Please sign in again.') {
23
+ super(message);
24
+ this.name = 'AuthenticationFailedError';
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Ensures a valid token exists before making authenticated API calls.
30
+ * If no valid token exists and an active session ID is available,
31
+ * attempts to refresh the token using the session.
32
+ *
33
+ * @param oxyServices - The OxyServices instance
34
+ * @param activeSessionId - The active session ID (if available)
35
+ * @throws {SessionSyncRequiredError} If the session needs to be synced (offline session)
36
+ * @throws {Error} If token refresh fails for other reasons
37
+ *
38
+ * @example
39
+ * ```ts
40
+ * // In a mutation or query function:
41
+ * await ensureValidToken(oxyServices, activeSessionId);
42
+ * return await oxyServices.updateProfile(updates);
43
+ * ```
44
+ */
45
+ export async function ensureValidToken(
46
+ oxyServices: OxyServices,
47
+ activeSessionId: string | null | undefined
48
+ ): Promise<void> {
49
+ if (oxyServices.hasValidToken() || !activeSessionId) {
50
+ return;
51
+ }
52
+
53
+ try {
54
+ await oxyServices.getTokenBySession(activeSessionId);
55
+ } catch (tokenError) {
56
+ const errorMessage = tokenError instanceof Error ? tokenError.message : String(tokenError);
57
+
58
+ if (errorMessage.includes('AUTH_REQUIRED_OFFLINE_SESSION') || errorMessage.includes('offline')) {
59
+ throw new SessionSyncRequiredError();
60
+ }
61
+
62
+ throw tokenError;
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Options for handling API authentication errors
68
+ */
69
+ export interface HandleApiErrorOptions {
70
+ /** Optional callback to attempt session sync and retry */
71
+ syncSession?: () => Promise<unknown>;
72
+ /** The active session ID for retry attempts */
73
+ activeSessionId?: string | null;
74
+ /** The OxyServices instance for retry attempts */
75
+ oxyServices?: OxyServices;
76
+ }
77
+
78
+ /**
79
+ * Checks if an error is an authentication error (401 or auth-related message)
80
+ *
81
+ * @param error - The error to check
82
+ * @returns True if the error is an authentication error
83
+ */
84
+ export function isAuthenticationError(error: unknown): boolean {
85
+ if (!error || typeof error !== 'object') {
86
+ return false;
87
+ }
88
+
89
+ const errorObj = error as { message?: string; status?: number; response?: { status?: number } };
90
+ const errorMessage = errorObj.message || '';
91
+ const status = errorObj.status || errorObj.response?.status;
92
+
93
+ return (
94
+ status === 401 ||
95
+ errorMessage.includes('Authentication required') ||
96
+ errorMessage.includes('Invalid or missing authorization header')
97
+ );
98
+ }
99
+
100
+ /**
101
+ * Wraps an API call with authentication error handling.
102
+ * If an authentication error occurs, it can optionally attempt to sync the session and retry.
103
+ *
104
+ * @param apiCall - The API call function to execute
105
+ * @param options - Optional error handling configuration
106
+ * @returns The result of the API call
107
+ * @throws {AuthenticationFailedError} If authentication fails and cannot be recovered
108
+ * @throws {Error} If the API call fails for non-auth reasons
109
+ *
110
+ * @example
111
+ * ```ts
112
+ * // Simple usage:
113
+ * const result = await withAuthErrorHandling(
114
+ * () => oxyServices.updateProfile(updates)
115
+ * );
116
+ *
117
+ * // With retry on auth failure:
118
+ * const result = await withAuthErrorHandling(
119
+ * () => oxyServices.updateProfile(updates),
120
+ * { syncSession, activeSessionId, oxyServices }
121
+ * );
122
+ * ```
123
+ */
124
+ export async function withAuthErrorHandling<T>(
125
+ apiCall: () => Promise<T>,
126
+ options?: HandleApiErrorOptions
127
+ ): Promise<T> {
128
+ try {
129
+ return await apiCall();
130
+ } catch (error) {
131
+ if (!isAuthenticationError(error)) {
132
+ throw error;
133
+ }
134
+
135
+ // If we have sync capabilities, try to recover
136
+ if (options?.syncSession && options?.activeSessionId && options?.oxyServices) {
137
+ try {
138
+ await options.syncSession();
139
+ await options.oxyServices.getTokenBySession(options.activeSessionId);
140
+ // Retry the API call after refreshing token
141
+ return await apiCall();
142
+ } catch {
143
+ throw new AuthenticationFailedError();
144
+ }
145
+ }
146
+
147
+ throw new AuthenticationFailedError();
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Combines token validation and auth error handling for a complete authenticated API call.
153
+ * This is the recommended helper for most authenticated API operations.
154
+ *
155
+ * @param oxyServices - The OxyServices instance
156
+ * @param activeSessionId - The active session ID
157
+ * @param apiCall - The API call function to execute
158
+ * @param syncSession - Optional callback to sync session on auth failure
159
+ * @returns The result of the API call
160
+ *
161
+ * @example
162
+ * ```ts
163
+ * return await authenticatedApiCall(
164
+ * oxyServices,
165
+ * activeSessionId,
166
+ * () => oxyServices.updateProfile(updates)
167
+ * );
168
+ * ```
169
+ */
170
+ export async function authenticatedApiCall<T>(
171
+ oxyServices: OxyServices,
172
+ activeSessionId: string | null | undefined,
173
+ apiCall: () => Promise<T>,
174
+ syncSession?: () => Promise<unknown>
175
+ ): Promise<T> {
176
+ await ensureValidToken(oxyServices, activeSessionId);
177
+
178
+ return withAuthErrorHandling(apiCall, {
179
+ syncSession,
180
+ activeSessionId,
181
+ oxyServices,
182
+ });
183
+ }
@@ -4,6 +4,7 @@ import { useAccountStore } from '../stores/accountStore';
4
4
  import { useAuthStore } from '../stores/authStore';
5
5
  import { QueryClient } from '@tanstack/react-query';
6
6
  import { queryKeys, invalidateUserQueries, invalidateAccountQueries } from '../hooks/queries/queryKeys';
7
+ import { authenticatedApiCall } from './authHelpers';
7
8
 
8
9
  /**
9
10
  * Updates file visibility to public for avatar use.
@@ -57,7 +58,7 @@ export function refreshAvatarInStore(
57
58
  /**
58
59
  * Updates user profile with avatar and handles all side effects (query invalidation, accountStore update).
59
60
  * This function can be used from within OxyContext provider without requiring useOxy hook.
60
- *
61
+ *
61
62
  * @param updates - Profile updates including avatar
62
63
  * @param oxyServices - OxyServices instance
63
64
  * @param activeSessionId - Active session ID
@@ -72,72 +73,31 @@ export async function updateProfileWithAvatar(
72
73
  queryClient: QueryClient,
73
74
  syncSession?: () => Promise<User>
74
75
  ): Promise<User> {
75
- // Ensure we have a valid token before making the request
76
- if (!oxyServices.hasValidToken() && activeSessionId) {
77
- try {
78
- await oxyServices.getTokenBySession(activeSessionId);
79
- } catch (tokenError) {
80
- const errorMessage = tokenError instanceof Error ? tokenError.message : String(tokenError);
81
- if (errorMessage.includes('AUTH_REQUIRED_OFFLINE_SESSION') || errorMessage.includes('offline')) {
82
- if (syncSession) {
83
- try {
84
- await syncSession();
85
- await oxyServices.getTokenBySession(activeSessionId);
86
- } catch (syncError) {
87
- throw new Error('Session needs to be synced. Please try again.');
88
- }
89
- } else {
90
- throw tokenError;
91
- }
92
- } else {
93
- throw tokenError;
94
- }
95
- }
76
+ const data = await authenticatedApiCall<User>(
77
+ oxyServices,
78
+ activeSessionId,
79
+ () => oxyServices.updateProfile(updates),
80
+ syncSession
81
+ );
82
+
83
+ // Update cache with server response
84
+ queryClient.setQueryData(queryKeys.accounts.current(), data);
85
+ if (activeSessionId) {
86
+ queryClient.setQueryData(queryKeys.users.profile(activeSessionId), data);
96
87
  }
97
88
 
98
- try {
99
- const data = await oxyServices.updateProfile(updates);
100
-
101
- // Update cache with server response
102
- queryClient.setQueryData(queryKeys.accounts.current(), data);
103
- if (activeSessionId) {
104
- queryClient.setQueryData(queryKeys.users.profile(activeSessionId), data);
105
- }
106
-
107
- // Update authStore so frontend components see the changes immediately
108
- useAuthStore.getState().setUser(data);
109
-
110
- // If avatar was updated, refresh accountStore with cache-busted URL
111
- if (updates.avatar && activeSessionId) {
112
- refreshAvatarInStore(activeSessionId, updates.avatar, oxyServices);
113
- }
114
-
115
- // Invalidate all related queries to refresh everywhere
116
- invalidateUserQueries(queryClient);
117
- invalidateAccountQueries(queryClient);
118
-
119
- return data;
120
- } catch (error: any) {
121
- const errorMessage = error?.message || '';
122
- const status = error?.status || error?.response?.status;
123
-
124
- // Handle authentication errors
125
- if (status === 401 || errorMessage.includes('Authentication required') || errorMessage.includes('Invalid or missing authorization header')) {
126
- if (activeSessionId && syncSession) {
127
- try {
128
- await syncSession();
129
- await oxyServices.getTokenBySession(activeSessionId);
130
- // Retry the update after getting token
131
- return await updateProfileWithAvatar(updates, oxyServices, activeSessionId, queryClient, syncSession);
132
- } catch (retryError) {
133
- throw new Error('Authentication failed. Please sign in again.');
134
- }
135
- } else {
136
- throw new Error('No active session. Please sign in.');
137
- }
138
- }
139
-
140
- throw error;
89
+ // Update authStore so frontend components see the changes immediately
90
+ useAuthStore.getState().setUser(data);
91
+
92
+ // If avatar was updated, refresh accountStore with cache-busted URL
93
+ if (updates.avatar && activeSessionId) {
94
+ refreshAvatarInStore(activeSessionId, updates.avatar, oxyServices);
141
95
  }
96
+
97
+ // Invalidate all related queries to refresh everywhere
98
+ invalidateUserQueries(queryClient);
99
+ invalidateAccountQueries(queryClient);
100
+
101
+ return data;
142
102
  }
143
103