Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
"@hookform/resolvers": "^3.3.4",
"@nethesis/chat-island": "0.1.73",
"@nethesis/nethesis-solid-svg-icons": "github:nethesis/Font-Awesome#ns-solid",
"@nethesis/phone-island": "^1.1.8",
"@nethesis/phone-island": "^1.1.9",
"@tailwindcss/forms": "^0.5.7",
"@types/lodash": "^4.14.202",
"@types/node": "^18.19.9",
Expand Down
2 changes: 1 addition & 1 deletion src/main/classes/controllers/AccountController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export class AccountController {

try {
// Make a simple API call to verify the token is still accepted by the server
// Use the API client so path selection (/api vs /webrest) follows account settings/fallback logic
// The API client picks /api or /webrest from the type of the saved token
const { NethVoiceAPI } = useNethVoiceAPI(lastLoggedAccount)
const me = await NethVoiceAPI.User.me()

Expand Down
1 change: 0 additions & 1 deletion src/shared/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ export type Account = {
shortcut?: string
commandBarShortcut?: string
preferredDevices?: PreferredDevices
apiBasePath?: string // Store which API path works for this account
authenticationMethod?: AuthenticationMethod
}

Expand Down
159 changes: 28 additions & 131 deletions src/shared/useNethVoiceAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,16 +55,16 @@ export const useNethVoiceAPI = (
const { GET, POST, DELETE } = useNetwork()
let isFirstHeartbeat = true
let account: Account | undefined = loggedAccount || undefined
// Use account's stored API path preference, or default to primary
let currentApiBasePath = account?.apiBasePath || PRIMARY_API_BASE_PATH
// The API path is decided at login and follows the token it produced:
// only a legacy hash token, given by a PBX without the middleware, uses
// /webrest. The apiBasePath saved by older releases is ignored: they
// stored /webrest after any 404 and the account stayed stuck there.
let currentApiBasePath =
account?.accessToken && !account?.jwtToken
? FALLBACK_API_BASE_PATH
: PRIMARY_API_BASE_PATH

if (account?.apiBasePath) {
Log.debug(
`Using stored API path for ${account.username}: ${account.apiBasePath}`,
)
} else {
Log.debug(`Using default API path: ${PRIMARY_API_BASE_PATH}`)
}
Log.debug(`Using API path: ${currentApiBasePath}`)

function buildApiPath(endpoint: string): string {
const result = (() => {
Expand Down Expand Up @@ -127,39 +127,11 @@ export const useNethVoiceAPI = (
try {
return await GET(_joinUrl(path), _getHeaders(hasAuth))
} catch (e) {
// Check if we should try fallback path for critical endpoints
if (shouldTryFallback(path, e)) {
return await _GETWithFallback(path, hasAuth)
}
console.error(e)
throw e
}
}

async function _GETWithFallback(path: string, hasAuth = true): Promise<any> {
// Switch to fallback path and rebuild the correct path
currentApiBasePath = FALLBACK_API_BASE_PATH
if (account) {
account.apiBasePath = FALLBACK_API_BASE_PATH
}

// Extract the endpoint from the original path and rebuild with fallback
const endpoint = path.replace(PRIMARY_API_BASE_PATH, '')
const fallbackPath = buildApiPath(endpoint)

try {
Log.debug(`Trying fallback path: ${fallbackPath}`)
const result = await GET(_joinUrl(fallbackPath), _getHeaders(hasAuth))

Log.info('Switched to fallback API path: /webrest')
return result
} catch (fallbackError) {
Log.warning('Fallback also failed:', fallbackError)
console.error(fallbackError)
throw fallbackError
}
}

async function _POST(
path: string,
data?: object,
Expand All @@ -168,11 +140,6 @@ export const useNethVoiceAPI = (
try {
return await POST(_joinUrl(path), data, _getHeaders(hasAuth))
} catch (e) {
// Check if we should try fallback path for critical endpoints
if (shouldTryFallback(path, e)) {
return await _POSTWithFallback(path, data, hasAuth)
}

// the error carries the request body, with the credentials
if (
!path.includes('login') &&
Expand All @@ -184,82 +151,6 @@ export const useNethVoiceAPI = (
}
}

function shouldTryFallback(path: string, error: any): boolean {
// Only try fallback if we're using primary path
if (currentApiBasePath !== PRIMARY_API_BASE_PATH) {
return false
}
if (path.includes('/user/nethlink') || path.includes('/password')) {
return false
}

// Try fallback for connection errors (404, 503, or network failures)
const isConnectionError =
error?.response?.status === 404 ||
error?.response?.status === 503 ||
!error?.response

// For auth endpoints, always try fallback on connection errors
const isCriticalAuthEndpoint =
path.includes('login') || path.includes('2fa/verify-otp')
if (isCriticalAuthEndpoint && isConnectionError) {
return true
}

// For other endpoints, try fallback only on 404 (endpoint not found)
// This indicates the API structure is different (middleware vs webrest)
if (error?.response?.status === 404) {
return true
}

return false
}

async function _POSTWithFallback(
path: string,
data?: object,
hasAuth = true,
): Promise<any> {
const originalPath = path

// Switch to fallback path
currentApiBasePath = FALLBACK_API_BASE_PATH
if (account) {
account.apiBasePath = FALLBACK_API_BASE_PATH
}
Log.info('Switched to fallback API path: /webrest')

// For login endpoint, we need special handling for webrest authentication
if (originalPath.includes('/login')) {
Log.debug('Login fallback: switching to hash-based authentication')
// The login function will now use webrest logic since currentApiBasePath is changed
// We need to throw the original error to let the login function handle the retry
throw new Error('FALLBACK_TO_WEBREST')
}

// For other endpoints, try the direct fallback
const endpoint = path.replace(PRIMARY_API_BASE_PATH, '')
const fallbackPath = buildApiPath(endpoint)

try {
Log.debug(`Trying fallback path: ${fallbackPath}`)
const result = await POST(
_joinUrl(fallbackPath),
data,
_getHeaders(hasAuth),
)
return result
} catch (fallbackError) {
Log.warning('Fallback also failed:', fallbackError)
if (
!originalPath.includes('login') &&
!originalPath.includes('2fa/verify-otp')
)
console.error(fallbackError)
throw fallbackError
}
}

const AstProxy = {
groups: async () => await _GET(buildApiPath('/astproxy/opgroups')),
extensions: async (): Promise<ExtensionsType> =>
Expand Down Expand Up @@ -314,6 +205,8 @@ export const useNethVoiceAPI = (
username,
theme: 'system',
}
// Always probe the middleware first, whatever the previous session used
currentApiBasePath = PRIMARY_API_BASE_PATH

// Try JWT authentication first (for /api)
if (currentApiBasePath === PRIMARY_API_BASE_PATH) {
Expand All @@ -326,7 +219,6 @@ export const useNethVoiceAPI = (
...account,
jwtToken: response.token,
lastAccess: moment().toISOString(),
apiBasePath: PRIMARY_API_BASE_PATH,
} as Account

// Check if 2FA is required
Expand All @@ -349,11 +241,15 @@ export const useNethVoiceAPI = (
throw new Error('No token received')
}
} catch (reason: any) {
// Check if this is a fallback trigger
if (reason.message === 'FALLBACK_TO_WEBREST') {
Log.debug('Retrying login with webrest authentication')
// Fallback has set currentApiBasePath to FALLBACK_API_BASE_PATH
// Continue to webrest authentication below
// No middleware on this PBX (/api/login itself answered 404 or
// 405, no token yet): use the legacy /webrest login. Network
// errors and other statuses never switch the path.
if (
[404, 405].includes(reason.response?.status) &&
!account?.jwtToken
) {
Log.info('No /api/login on this PBX, using /webrest')
Comment thread
tonyco97 marked this conversation as resolved.
Resolved
currentApiBasePath = FALLBACK_API_BASE_PATH
} else {
// Handle other specific error cases
if (
Expand All @@ -367,10 +263,15 @@ export const useNethVoiceAPI = (
throw expiredError
} else if (reason.response?.status === 401) {
throw new Error('Wrong username or password')
} else if (reason.response?.status === 404) {
throw new Error('Network connection lost')
} else if (reason.message === 'User not authorized for NethLink') {
throw reason
} else if (
(reason.isAxiosError && !reason.response) ||
reason.response?.status === 404
) {
// no answer from the PBX: only failed requests count, not
// the plain errors thrown inside the try block
throw new Error('Network connection lost')
} else {
console.error('Login error:', reason)
throw new Error('Unauthorized')
Expand All @@ -397,7 +298,6 @@ export const useNethVoiceAPI = (
...account,
accessToken,
lastAccess: moment().toISOString(),
apiBasePath: FALLBACK_API_BASE_PATH,
} as Account
const me = await User.me()
account.data = me
Expand Down Expand Up @@ -468,13 +368,13 @@ export const useNethVoiceAPI = (
if (!username) {
throw new Error('Unauthorized')
}
currentApiBasePath = PRIMARY_API_BASE_PATH
account = {
host,
username,
theme: 'system',
jwtToken: token,
lastAccess: moment().toISOString(),
apiBasePath: PRIMARY_API_BASE_PATH,
authenticationMethod: method,
} as Account
const me = await User.me()
Expand Down Expand Up @@ -560,9 +460,6 @@ export const useNethVoiceAPI = (
} finally {
// Reset to primary API path for next login attempt
currentApiBasePath = PRIMARY_API_BASE_PATH
if (account) {
account.apiBasePath = PRIMARY_API_BASE_PATH
}
}
},

Expand Down
Loading