mirror of
https://github.com/sasjs/adapter.git
synced 2026-04-18 19:53:14 +00:00
Compare commits
12 Commits
dependabot
...
fix/sessio
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
706fd8e470 | ||
|
|
53ebeb1cf5 | ||
|
|
fe5f0e87b7 | ||
|
|
b92487819a | ||
|
|
3cc37e0b5b | ||
|
|
d87b9ecc34 | ||
|
|
3b00ae4bef | ||
|
|
87efdfff2e | ||
|
|
73556c9fdf | ||
|
|
72318ced00 | ||
|
|
d7053ba628 | ||
|
|
52371da4db |
5
.github/workflows/server-tests.yml
vendored
5
.github/workflows/server-tests.yml
vendored
@@ -97,6 +97,7 @@ jobs:
|
||||
npm i
|
||||
jq '.sasJsConfig.serverUrl |= "${{ secrets.SASJS_SERVER_URL }}"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
||||
jq '.sasJsConfig.serverType |= "SASJS"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
||||
jq '.sasJsConfig.loginMechanism |= "Default"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
||||
jq '.userName |= "${{ secrets.SASJS_USERNAME }}"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
||||
jq '.password |= "${{ secrets.SASJS_PASSWORD }}"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
||||
|
||||
@@ -110,8 +111,10 @@ jobs:
|
||||
shell: bash
|
||||
|
||||
- name: Run cypress on sasjs
|
||||
env:
|
||||
TERM: dumb
|
||||
run: |
|
||||
sed -i "s|sasjsTestsUrl: '.*'|sasjsTestsUrl: 'http://localhost:5173'|g" ./cypress.config.js
|
||||
sed -i "s|sasjsTestsUrl: '.*'|sasjsTestsUrl: 'http://localhost:3000'|g" ./cypress.config.js
|
||||
sed -i "s|username: '.*'|username: '${{ secrets.SASJS_USERNAME }}'|g" ./cypress.config.js
|
||||
sed -i "s|password: '.*'|password: '${{ secrets.SASJS_PASSWORD }}'|g" ./cypress.config.js
|
||||
cat ./cypress.config.js
|
||||
|
||||
@@ -9,7 +9,7 @@ module.exports = defineConfig({
|
||||
supportFile: 'cypress/support/index.js'
|
||||
},
|
||||
env: {
|
||||
sasjsTestsUrl: 'http://localhost:5173',
|
||||
sasjsTestsUrl: 'http://localhost:3000',
|
||||
username: '',
|
||||
password: '',
|
||||
screenshotOnRunFailure: false,
|
||||
|
||||
@@ -9,10 +9,12 @@ context('sasjs-tests', function () {
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
cy.reload()
|
||||
cy.visit(sasjsTestsUrl)
|
||||
})
|
||||
|
||||
function loginIfNeeded() {
|
||||
cy.get('login-form, tests-view', { timeout: 30000 }).should('exist')
|
||||
|
||||
cy.get('body').then(($body) => {
|
||||
if ($body.find('login-form').length > 0) {
|
||||
cy.get('login-form')
|
||||
|
||||
27
package-lock.json
generated
27
package-lock.json
generated
@@ -7,8 +7,8 @@
|
||||
"name": "@sasjs/adapter",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@sasjs/utils": "3.5.6",
|
||||
"axios": "^1.13.5",
|
||||
"@sasjs/utils": "^3.5.6",
|
||||
"axios": "1.15.0",
|
||||
"axios-cookiejar-support": "5.0.5",
|
||||
"form-data": "4.0.4",
|
||||
"https": "1.0.0",
|
||||
@@ -3527,14 +3527,14 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.13.5",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.13.5.tgz",
|
||||
"integrity": "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==",
|
||||
"version": "1.15.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz",
|
||||
"integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.11",
|
||||
"form-data": "^4.0.5",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
"proxy-from-env": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/axios-cookiejar-support": {
|
||||
@@ -8564,9 +8564,7 @@
|
||||
}
|
||||
},
|
||||
"node_modules/lodash": {
|
||||
"version": "4.17.23",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz",
|
||||
"integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==",
|
||||
"version": "4.17.21",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
@@ -12417,10 +12415,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
|
||||
"license": "MIT"
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-2.1.0.tgz",
|
||||
"integrity": "sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10"
|
||||
}
|
||||
},
|
||||
"node_modules/psl": {
|
||||
"version": "1.15.0",
|
||||
|
||||
@@ -76,8 +76,8 @@
|
||||
},
|
||||
"main": "index.js",
|
||||
"dependencies": {
|
||||
"@sasjs/utils": "3.5.6",
|
||||
"axios": "^1.13.5",
|
||||
"@sasjs/utils": "^3.5.6",
|
||||
"axios": "1.15.0",
|
||||
"axios-cookiejar-support": "5.0.5",
|
||||
"form-data": "4.0.4",
|
||||
"https": "1.0.0",
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"targets": [
|
||||
{
|
||||
"name": "4gl",
|
||||
"serverUrl": "https://sas9.4gl.io",
|
||||
"serverUrl": "https://sas.4gl.io",
|
||||
"serverType": "SASJS",
|
||||
"httpsAgentOptions": {
|
||||
"allowInsecureRequests": false
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { defineConfig } from 'vite'
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: 3000
|
||||
},
|
||||
build: {
|
||||
assetsInlineLimit: 0,
|
||||
assetsDir: ''
|
||||
|
||||
@@ -375,7 +375,7 @@ export class AuthManager {
|
||||
*
|
||||
*/
|
||||
public async logOut() {
|
||||
this.requestClient.clearCsrfTokens()
|
||||
this.requestClient.resetInMemoryAuthState()
|
||||
|
||||
return this.requestClient.get(this.logoutUrl, undefined).then(() => true)
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ export class RequestClient implements HttpClient {
|
||||
protected csrfToken: CsrfToken = { headerName: '', value: '' }
|
||||
protected fileUploadCsrfToken: CsrfToken | undefined
|
||||
protected httpClient!: AxiosInstance
|
||||
private isRecoveringFromNetworkError = false
|
||||
|
||||
constructor(
|
||||
protected baseUrl: string,
|
||||
@@ -77,6 +78,36 @@ export class RequestClient implements HttpClient {
|
||||
localStorage.setItem('refreshToken', '')
|
||||
}
|
||||
|
||||
public resetInMemoryAuthState() {
|
||||
const logger = process.logger || console
|
||||
const clearedCookies: string[] = []
|
||||
|
||||
this.clearCsrfTokens()
|
||||
if (typeof localStorage !== 'undefined') {
|
||||
this.clearLocalStorageTokens()
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
clearedCookies.push(...this.clearAllCookies())
|
||||
}
|
||||
|
||||
logger.warn('[resetInMemoryAuthState] cleared', {
|
||||
cookies: clearedCookies,
|
||||
localStorage: typeof localStorage !== 'undefined'
|
||||
})
|
||||
}
|
||||
|
||||
private clearAllCookies(): string[] {
|
||||
const cookies = document.cookie.split(';')
|
||||
const cleared: string[] = []
|
||||
for (const cookie of cookies) {
|
||||
const name = cookie.split('=')[0].trim()
|
||||
if (!name) continue
|
||||
document.cookie = `${name}=; Max-Age=0; Path=/;`
|
||||
cleared.push(name)
|
||||
}
|
||||
return cleared
|
||||
}
|
||||
|
||||
public getBaseUrl() {
|
||||
return this.httpClient.defaults.baseURL || ''
|
||||
}
|
||||
@@ -354,9 +385,14 @@ export class RequestClient implements HttpClient {
|
||||
const csrfTokenKey = Object.keys(params).find((k) =>
|
||||
k?.toLowerCase().includes('csrf')
|
||||
)
|
||||
const logger = process.logger || console
|
||||
|
||||
if (csrfTokenKey) {
|
||||
this.csrfToken.value = params[csrfTokenKey]
|
||||
this.csrfToken.headerName = this.csrfToken.headerName || 'x-csrf-token'
|
||||
logger.warn('[authorize] CSRF from form', {
|
||||
headerName: this.csrfToken.headerName
|
||||
})
|
||||
}
|
||||
|
||||
const formData = new FormData()
|
||||
@@ -371,15 +407,23 @@ export class RequestClient implements HttpClient {
|
||||
throw new Error('Auth Form URL is null or undefined.')
|
||||
}
|
||||
|
||||
logger.warn('[authorize] posting to', { authUrl })
|
||||
|
||||
return await this.httpClient
|
||||
.post(authUrl, formData, {
|
||||
responseType: 'text',
|
||||
headers: { Accept: '*/*', 'Content-Type': 'text/plain' }
|
||||
})
|
||||
.then((res) => res.data)
|
||||
.then((res) => {
|
||||
logger.warn('[authorize] success', { status: res.status })
|
||||
return res.data
|
||||
})
|
||||
.catch((error) => {
|
||||
const logger = process.logger || console
|
||||
logger.error(error)
|
||||
logger.error('[authorize] failed', {
|
||||
code: error?.code,
|
||||
status: error?.response?.status,
|
||||
message: error?.message
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
@@ -578,9 +622,16 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
|
||||
protected parseAndSetCsrfToken = (response: AxiosResponse) => {
|
||||
const token = this.parseCsrfToken(response)
|
||||
const logger = process.logger || console
|
||||
|
||||
if (token) {
|
||||
this.csrfToken = token
|
||||
logger.warn('[parseAndSetCsrfToken] set', {
|
||||
headerName: token.headerName,
|
||||
hasValue: !!token.value
|
||||
})
|
||||
} else {
|
||||
logger.warn('[parseAndSetCsrfToken] no token found in response')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -600,6 +651,11 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
}
|
||||
}
|
||||
|
||||
private logHandleError(step: string, details?: Record<string, any>) {
|
||||
const logger = process.logger || console
|
||||
logger.warn(`[handleError] ${step}`, details || '')
|
||||
}
|
||||
|
||||
protected handleError = async (
|
||||
e: any,
|
||||
callback: any,
|
||||
@@ -607,7 +663,19 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
) => {
|
||||
const response = e.response as AxiosResponse
|
||||
|
||||
this.logHandleError('entered', {
|
||||
errorType: e?.constructor?.name,
|
||||
code: e?.code,
|
||||
status: response?.status,
|
||||
url: e?.config?.url || response?.config?.url,
|
||||
hasResponse: !!response,
|
||||
isRecovering: this.isRecoveringFromNetworkError
|
||||
})
|
||||
|
||||
if (e instanceof AuthorizeError) {
|
||||
this.logHandleError('AuthorizeError — fetching confirmUrl', {
|
||||
confirmUrl: e.confirmUrl
|
||||
})
|
||||
const res = await this.httpClient
|
||||
.get(e.confirmUrl, {
|
||||
responseType: 'text',
|
||||
@@ -617,13 +685,24 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
throw prefixMessage(err, 'Error while getting error confirmUrl. ')
|
||||
})
|
||||
|
||||
if (isAuthorizeFormRequired(res?.data as string)) {
|
||||
const needsAuthorize = isAuthorizeFormRequired(res?.data as string)
|
||||
this.logHandleError(
|
||||
'AuthorizeError — authorize form required: ' + needsAuthorize
|
||||
)
|
||||
|
||||
if (needsAuthorize) {
|
||||
await this.authorize(res.data as string).catch((err) => {
|
||||
throw prefixMessage(err, 'Error while authorizing request. ')
|
||||
})
|
||||
}
|
||||
|
||||
this.logHandleError('AuthorizeError — retrying callback')
|
||||
return await callback().catch((err: any) => {
|
||||
this.logHandleError('AuthorizeError — callback failed', {
|
||||
errorType: err?.constructor?.name,
|
||||
code: err?.code,
|
||||
message: err?.message
|
||||
})
|
||||
throw prefixMessage(
|
||||
err,
|
||||
'Error while executing callback in handleError. '
|
||||
@@ -632,12 +711,14 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
}
|
||||
|
||||
if (e instanceof LoginRequiredError) {
|
||||
this.logHandleError('LoginRequiredError — clearing CSRF and re-throwing')
|
||||
this.clearCsrfTokens()
|
||||
|
||||
throw e
|
||||
}
|
||||
|
||||
if (e instanceof InvalidSASjsCsrfError) {
|
||||
this.logHandleError('InvalidSASjsCsrfError — re-fetching CSRF cookie')
|
||||
// Fetching root and creating CSRF cookie
|
||||
await this.httpClient
|
||||
.get('/', {
|
||||
@@ -649,13 +730,22 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
response.data
|
||||
)?.[1]
|
||||
|
||||
this.logHandleError(
|
||||
'InvalidSASjsCsrfError — cookie found: ' + !!cookie
|
||||
)
|
||||
if (cookie) document.cookie = cookie
|
||||
})
|
||||
.catch((err) => {
|
||||
throw prefixMessage(err, 'Error while re-fetching CSRF token.')
|
||||
})
|
||||
|
||||
this.logHandleError('InvalidSASjsCsrfError — retrying callback')
|
||||
return await callback().catch((err: any) => {
|
||||
this.logHandleError('InvalidSASjsCsrfError — callback failed', {
|
||||
errorType: err?.constructor?.name,
|
||||
code: err?.code,
|
||||
message: err?.message
|
||||
})
|
||||
throw prefixMessage(
|
||||
err,
|
||||
'Error while executing callback in handleError. '
|
||||
@@ -666,8 +756,20 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
if (response?.status === 403 || response?.status === 449) {
|
||||
this.parseAndSetCsrfToken(response)
|
||||
|
||||
if (this.csrfToken.headerName && this.csrfToken.value) {
|
||||
const hasToken = !!(this.csrfToken.headerName && this.csrfToken.value)
|
||||
this.logHandleError('403/449 — parsed CSRF from response', {
|
||||
hasToken,
|
||||
headerName: this.csrfToken.headerName
|
||||
})
|
||||
|
||||
if (hasToken) {
|
||||
this.logHandleError('403/449 — retrying callback with new CSRF')
|
||||
return await callback().catch((err: any) => {
|
||||
this.logHandleError('403/449 — callback failed', {
|
||||
errorType: err?.constructor?.name,
|
||||
code: err?.code,
|
||||
message: err?.message
|
||||
})
|
||||
throw prefixMessage(
|
||||
err,
|
||||
'Error while executing callback in handleError. '
|
||||
@@ -675,6 +777,9 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
})
|
||||
}
|
||||
|
||||
this.logHandleError(
|
||||
'403/449 — no CSRF in response, throwing original error'
|
||||
)
|
||||
throw e
|
||||
} else if (response?.status === 404) {
|
||||
throw new NotFoundError(response.config.url!)
|
||||
@@ -687,6 +792,41 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
||||
throw new CertificateError(e.message)
|
||||
}
|
||||
|
||||
if (
|
||||
e.isAxiosError &&
|
||||
!response &&
|
||||
e.code === 'ERR_NETWORK' &&
|
||||
!this.isRecoveringFromNetworkError
|
||||
) {
|
||||
// Opaque ERR_NETWORK usually means the server rejected stale credentials.
|
||||
// Wipe in-memory auth state so the retry either succeeds
|
||||
// or surfaces a clean LoginRequiredError.
|
||||
this.logHandleError('ERR_NETWORK — clearing all auth state and retrying')
|
||||
this.resetInMemoryAuthState()
|
||||
this.isRecoveringFromNetworkError = true
|
||||
try {
|
||||
return await callback()
|
||||
} catch (retryErr: any) {
|
||||
// Retry also failed — session is dead, surface LoginRequiredError
|
||||
// so the app can prompt re-authentication.
|
||||
this.logHandleError(
|
||||
'ERR_NETWORK — retry failed, throwing LoginRequiredError',
|
||||
{
|
||||
errorType: retryErr?.constructor?.name,
|
||||
code: retryErr?.code,
|
||||
message: retryErr?.message
|
||||
}
|
||||
)
|
||||
throw new LoginRequiredError()
|
||||
} finally {
|
||||
this.isRecoveringFromNetworkError = false
|
||||
}
|
||||
}
|
||||
|
||||
this.logHandleError('unhandled — throwing as-is', {
|
||||
message: e?.message,
|
||||
code: e?.code
|
||||
})
|
||||
if (e.message) throw e
|
||||
else throw prefixMessage(e, 'Error while handling error. ')
|
||||
}
|
||||
|
||||
@@ -23,6 +23,13 @@ export class Sas9RequestClient extends RequestClient {
|
||||
}
|
||||
}
|
||||
|
||||
public resetInMemoryAuthState() {
|
||||
super.resetInMemoryAuthState()
|
||||
if (this.httpClient.defaults.jar) {
|
||||
;(this.httpClient.defaults.jar as tough.CookieJar).removeAllCookiesSync()
|
||||
}
|
||||
}
|
||||
|
||||
public async login(username: string, password: string, jobsPath: string) {
|
||||
const codeInjectorPath = `/User Folders/${username}/My Folder/sasjs/runner`
|
||||
if (this.httpClient.defaults.jar) {
|
||||
|
||||
@@ -589,6 +589,42 @@ ${resHeaders[0]}: ${resHeaders[1]}${
|
||||
requestClient['handleError'](error, () => {}, false)
|
||||
).resolves.toEqual(undefined)
|
||||
})
|
||||
|
||||
it('should clear CSRF and retry once on opaque ERR_NETWORK', async () => {
|
||||
const networkError = {
|
||||
isAxiosError: true,
|
||||
code: 'ERR_NETWORK',
|
||||
message: 'Network Error'
|
||||
}
|
||||
requestClient['csrfToken'] = { headerName: 'h', value: 'v' }
|
||||
const callback = jest.fn().mockResolvedValue('ok')
|
||||
|
||||
await expect(
|
||||
requestClient['handleError'](networkError, callback)
|
||||
).resolves.toEqual('ok')
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1)
|
||||
expect(requestClient['csrfToken']).toEqual({ headerName: '', value: '' })
|
||||
})
|
||||
|
||||
it('should throw LoginRequiredError if retry also fails with ERR_NETWORK', async () => {
|
||||
const networkError = {
|
||||
isAxiosError: true,
|
||||
code: 'ERR_NETWORK',
|
||||
message: 'Network Error'
|
||||
}
|
||||
const innerHandle = jest.fn(() =>
|
||||
requestClient['handleError'](networkError, () =>
|
||||
Promise.reject(networkError)
|
||||
)
|
||||
)
|
||||
|
||||
await expect(
|
||||
requestClient['handleError'](networkError, innerHandle)
|
||||
).rejects.toThrow(LoginRequiredError)
|
||||
|
||||
expect(innerHandle).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user