()
| 91 | |
| 92 | // Helper function to get auth headers (reused by middleware and file operations) |
| 93 | async function getAuthHeaders(): Promise<Record<string, string>> { |
| 94 | const storeState = useAuthStore.getState(); |
| 95 | let token = storeState.token; |
| 96 | // For local auth, always use 'local-dev' org ID |
| 97 | const organizationId = storeState.provider === 'local' ? 'local-dev' : storeState.organizationId; |
| 98 | |
| 99 | // For Clerk auth, always fetch a fresh token on-demand to prevent expiration issues |
| 100 | // This ensures we never use a stale/expired token |
| 101 | if (storeState.provider === 'clerk') { |
| 102 | try { |
| 103 | const freshToken = await getFreshClerkToken(); |
| 104 | if (freshToken) { |
| 105 | token = freshToken; |
| 106 | // Update store with fresh token so it's available for next time |
| 107 | storeState.setToken(freshToken); |
| 108 | } else { |
| 109 | // If we can't get a fresh token, fall back to store token |
| 110 | } |
| 111 | } catch (_error) { |
| 112 | // Fall back to store token if fresh token fetch fails |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | const headers: Record<string, string> = {}; |
| 117 | |
| 118 | // For local auth with admin credentials, use Basic Auth |
| 119 | if (storeState.provider === 'local' && storeState.adminUsername && storeState.adminPassword) { |
| 120 | const credentials = btoa(`${storeState.adminUsername}:${storeState.adminPassword}`); |
| 121 | headers['Authorization'] = `Basic ${credentials}`; |
| 122 | } else if (token && token.trim().length > 0) { |
| 123 | // Use Bearer token (for Clerk) |
| 124 | const headerValue = token.startsWith('Bearer ') ? token : `Bearer ${token}`; |
| 125 | headers['Authorization'] = headerValue; |
| 126 | } |
| 127 | |
| 128 | if (organizationId && organizationId.trim().length > 0) { |
| 129 | headers['X-Organization-Id'] = organizationId; |
| 130 | } |
| 131 | |
| 132 | return headers; |
| 133 | } |
| 134 | |
| 135 | // Create type-safe API client |
| 136 | const apiClient = createShipSecClient({ |
no test coverage detected