mirror of
https://github.com/sasjs/adapter.git
synced 2026-06-15 13:00:22 +00:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 63a863f9e2 |
@@ -97,7 +97,6 @@ jobs:
|
|||||||
npm i
|
npm i
|
||||||
jq '.sasJsConfig.serverUrl |= "${{ secrets.SASJS_SERVER_URL }}"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
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.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 '.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
|
jq '.password |= "${{ secrets.SASJS_PASSWORD }}"' ./public/config.json > ./public/config.temp && mv ./public/config.temp ./public/config.json
|
||||||
|
|
||||||
@@ -111,10 +110,8 @@ jobs:
|
|||||||
shell: bash
|
shell: bash
|
||||||
|
|
||||||
- name: Run cypress on sasjs
|
- name: Run cypress on sasjs
|
||||||
env:
|
|
||||||
TERM: dumb
|
|
||||||
run: |
|
run: |
|
||||||
sed -i "s|sasjsTestsUrl: '.*'|sasjsTestsUrl: 'http://localhost:3000'|g" ./cypress.config.js
|
sed -i "s|sasjsTestsUrl: '.*'|sasjsTestsUrl: 'http://localhost:5173'|g" ./cypress.config.js
|
||||||
sed -i "s|username: '.*'|username: '${{ secrets.SASJS_USERNAME }}'|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
|
sed -i "s|password: '.*'|password: '${{ secrets.SASJS_PASSWORD }}'|g" ./cypress.config.js
|
||||||
cat ./cypress.config.js
|
cat ./cypress.config.js
|
||||||
|
|||||||
@@ -0,0 +1,2 @@
|
|||||||
|
tasks:
|
||||||
|
- init: npm install && npm run build
|
||||||
+1
-1
@@ -9,7 +9,7 @@ module.exports = defineConfig({
|
|||||||
supportFile: 'cypress/support/index.js'
|
supportFile: 'cypress/support/index.js'
|
||||||
},
|
},
|
||||||
env: {
|
env: {
|
||||||
sasjsTestsUrl: 'http://localhost:3000',
|
sasjsTestsUrl: 'http://localhost:5173',
|
||||||
username: '',
|
username: '',
|
||||||
password: '',
|
password: '',
|
||||||
screenshotOnRunFailure: false,
|
screenshotOnRunFailure: false,
|
||||||
|
|||||||
@@ -9,12 +9,10 @@ context('sasjs-tests', function () {
|
|||||||
})
|
})
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
cy.visit(sasjsTestsUrl)
|
cy.reload()
|
||||||
})
|
})
|
||||||
|
|
||||||
function loginIfNeeded() {
|
function loginIfNeeded() {
|
||||||
cy.get('login-form, tests-view', { timeout: 30000 }).should('exist')
|
|
||||||
|
|
||||||
cy.get('body').then(($body) => {
|
cy.get('body').then(($body) => {
|
||||||
if ($body.find('login-form').length > 0) {
|
if ($body.find('login-form').length > 0) {
|
||||||
cy.get('login-form')
|
cy.get('login-form')
|
||||||
|
|||||||
Generated
+308
-221
File diff suppressed because it is too large
Load Diff
+3
-3
@@ -53,7 +53,7 @@
|
|||||||
"cp": "0.2.0",
|
"cp": "0.2.0",
|
||||||
"cypress": "^15.7.1",
|
"cypress": "^15.7.1",
|
||||||
"dotenv": "16.0.0",
|
"dotenv": "16.0.0",
|
||||||
"express": "4.17.3",
|
"express": "4.22.1",
|
||||||
"jest": "29.7.0",
|
"jest": "29.7.0",
|
||||||
"jest-environment-jsdom": "^29.7.0",
|
"jest-environment-jsdom": "^29.7.0",
|
||||||
"jest-extended": "4.0.2",
|
"jest-extended": "4.0.2",
|
||||||
@@ -76,8 +76,8 @@
|
|||||||
},
|
},
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@sasjs/utils": "^3.5.6",
|
"@sasjs/utils": "3.5.6",
|
||||||
"axios": "1.15.0",
|
"axios": "1.12.2",
|
||||||
"axios-cookiejar-support": "5.0.5",
|
"axios-cookiejar-support": "5.0.5",
|
||||||
"form-data": "4.0.4",
|
"form-data": "4.0.4",
|
||||||
"https": "1.0.0",
|
"https": "1.0.0",
|
||||||
|
|||||||
@@ -7,7 +7,7 @@
|
|||||||
"targets": [
|
"targets": [
|
||||||
{
|
{
|
||||||
"name": "4gl",
|
"name": "4gl",
|
||||||
"serverUrl": "https://sas.4gl.io",
|
"serverUrl": "https://sas9.4gl.io",
|
||||||
"serverType": "SASJS",
|
"serverType": "SASJS",
|
||||||
"httpsAgentOptions": {
|
"httpsAgentOptions": {
|
||||||
"allowInsecureRequests": false
|
"allowInsecureRequests": false
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
import { defineConfig } from 'vite'
|
import { defineConfig } from 'vite'
|
||||||
export default defineConfig({
|
export default defineConfig({
|
||||||
server: {
|
|
||||||
port: 3000
|
|
||||||
},
|
|
||||||
build: {
|
build: {
|
||||||
assetsInlineLimit: 0,
|
assetsInlineLimit: 0,
|
||||||
assetsDir: ''
|
assetsDir: ''
|
||||||
|
|||||||
@@ -375,7 +375,7 @@ export class AuthManager {
|
|||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
public async logOut() {
|
public async logOut() {
|
||||||
this.requestClient.resetInMemoryAuthState()
|
this.requestClient.clearCsrfTokens()
|
||||||
|
|
||||||
return this.requestClient.get(this.logoutUrl, undefined).then(() => true)
|
return this.requestClient.get(this.logoutUrl, undefined).then(() => true)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,9 +97,11 @@ export class WebJobExecutor extends BaseJobExecutor {
|
|||||||
apiUrl = apiUrl.replace('_program=', '__program=')
|
apiUrl = apiUrl.replace('_program=', '__program=')
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append context name to URL if provided and non-empty
|
// if context name exists and is not blank string
|
||||||
apiUrl += config.contextName?.trim()
|
// then add _contextname variable in apiUrl
|
||||||
? `&_contextname=${encodeURIComponent(config.contextName)}`
|
apiUrl +=
|
||||||
|
config.contextName && !/\s/.test(config.contextName)
|
||||||
|
? `&_contextname=${config.contextName}`
|
||||||
: ''
|
: ''
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,9 +28,6 @@ import {
|
|||||||
import { InvalidSASjsCsrfError } from '../types/errors/InvalidSASjsCsrfError'
|
import { InvalidSASjsCsrfError } from '../types/errors/InvalidSASjsCsrfError'
|
||||||
import { inspect } from 'util'
|
import { inspect } from 'util'
|
||||||
|
|
||||||
const getLogger = () =>
|
|
||||||
(typeof process !== 'undefined' && process.logger) || console
|
|
||||||
|
|
||||||
export class RequestClient implements HttpClient {
|
export class RequestClient implements HttpClient {
|
||||||
private requests: SASjsRequest[] = []
|
private requests: SASjsRequest[] = []
|
||||||
private requestsLimit: number = 10
|
private requestsLimit: number = 10
|
||||||
@@ -40,7 +37,6 @@ export class RequestClient implements HttpClient {
|
|||||||
protected csrfToken: CsrfToken = { headerName: '', value: '' }
|
protected csrfToken: CsrfToken = { headerName: '', value: '' }
|
||||||
protected fileUploadCsrfToken: CsrfToken | undefined
|
protected fileUploadCsrfToken: CsrfToken | undefined
|
||||||
protected httpClient!: AxiosInstance
|
protected httpClient!: AxiosInstance
|
||||||
private isRecoveringFromNetworkError = false
|
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
protected baseUrl: string,
|
protected baseUrl: string,
|
||||||
@@ -81,36 +77,6 @@ export class RequestClient implements HttpClient {
|
|||||||
localStorage.setItem('refreshToken', '')
|
localStorage.setItem('refreshToken', '')
|
||||||
}
|
}
|
||||||
|
|
||||||
public resetInMemoryAuthState() {
|
|
||||||
const logger = getLogger()
|
|
||||||
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() {
|
public getBaseUrl() {
|
||||||
return this.httpClient.defaults.baseURL || ''
|
return this.httpClient.defaults.baseURL || ''
|
||||||
}
|
}
|
||||||
@@ -388,14 +354,9 @@ export class RequestClient implements HttpClient {
|
|||||||
const csrfTokenKey = Object.keys(params).find((k) =>
|
const csrfTokenKey = Object.keys(params).find((k) =>
|
||||||
k?.toLowerCase().includes('csrf')
|
k?.toLowerCase().includes('csrf')
|
||||||
)
|
)
|
||||||
const logger = getLogger()
|
|
||||||
|
|
||||||
if (csrfTokenKey) {
|
if (csrfTokenKey) {
|
||||||
this.csrfToken.value = params[csrfTokenKey]
|
this.csrfToken.value = params[csrfTokenKey]
|
||||||
this.csrfToken.headerName = this.csrfToken.headerName || 'x-csrf-token'
|
this.csrfToken.headerName = this.csrfToken.headerName || 'x-csrf-token'
|
||||||
logger.warn('[authorize] CSRF from form', {
|
|
||||||
headerName: this.csrfToken.headerName
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const formData = new FormData()
|
const formData = new FormData()
|
||||||
@@ -410,23 +371,15 @@ export class RequestClient implements HttpClient {
|
|||||||
throw new Error('Auth Form URL is null or undefined.')
|
throw new Error('Auth Form URL is null or undefined.')
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.warn('[authorize] posting to', { authUrl })
|
|
||||||
|
|
||||||
return await this.httpClient
|
return await this.httpClient
|
||||||
.post(authUrl, formData, {
|
.post(authUrl, formData, {
|
||||||
responseType: 'text',
|
responseType: 'text',
|
||||||
headers: { Accept: '*/*', 'Content-Type': 'text/plain' }
|
headers: { Accept: '*/*', 'Content-Type': 'text/plain' }
|
||||||
})
|
})
|
||||||
.then((res) => {
|
.then((res) => res.data)
|
||||||
logger.warn('[authorize] success', { status: res.status })
|
|
||||||
return res.data
|
|
||||||
})
|
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
logger.error('[authorize] failed', {
|
const logger = process.logger || console
|
||||||
code: error?.code,
|
logger.error(error)
|
||||||
status: error?.response?.status,
|
|
||||||
message: error?.message
|
|
||||||
})
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -625,16 +578,9 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
|
|
||||||
protected parseAndSetCsrfToken = (response: AxiosResponse) => {
|
protected parseAndSetCsrfToken = (response: AxiosResponse) => {
|
||||||
const token = this.parseCsrfToken(response)
|
const token = this.parseCsrfToken(response)
|
||||||
const logger = getLogger()
|
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
this.csrfToken = token
|
this.csrfToken = token
|
||||||
logger.warn('[parseAndSetCsrfToken] set', {
|
|
||||||
headerName: token.headerName,
|
|
||||||
hasValue: !!token.value
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
logger.warn('[parseAndSetCsrfToken] no token found in response')
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -654,11 +600,6 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private logHandleError(step: string, details?: Record<string, any>) {
|
|
||||||
const logger = getLogger()
|
|
||||||
logger.warn(`[handleError] ${step}`, details || '')
|
|
||||||
}
|
|
||||||
|
|
||||||
protected handleError = async (
|
protected handleError = async (
|
||||||
e: any,
|
e: any,
|
||||||
callback: any,
|
callback: any,
|
||||||
@@ -666,19 +607,7 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
) => {
|
) => {
|
||||||
const response = e.response as AxiosResponse
|
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) {
|
if (e instanceof AuthorizeError) {
|
||||||
this.logHandleError('AuthorizeError — fetching confirmUrl', {
|
|
||||||
confirmUrl: e.confirmUrl
|
|
||||||
})
|
|
||||||
const res = await this.httpClient
|
const res = await this.httpClient
|
||||||
.get(e.confirmUrl, {
|
.get(e.confirmUrl, {
|
||||||
responseType: 'text',
|
responseType: 'text',
|
||||||
@@ -688,24 +617,13 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
throw prefixMessage(err, 'Error while getting error confirmUrl. ')
|
throw prefixMessage(err, 'Error while getting error confirmUrl. ')
|
||||||
})
|
})
|
||||||
|
|
||||||
const needsAuthorize = isAuthorizeFormRequired(res?.data as string)
|
if (isAuthorizeFormRequired(res?.data as string)) {
|
||||||
this.logHandleError(
|
|
||||||
'AuthorizeError — authorize form required: ' + needsAuthorize
|
|
||||||
)
|
|
||||||
|
|
||||||
if (needsAuthorize) {
|
|
||||||
await this.authorize(res.data as string).catch((err) => {
|
await this.authorize(res.data as string).catch((err) => {
|
||||||
throw prefixMessage(err, 'Error while authorizing request. ')
|
throw prefixMessage(err, 'Error while authorizing request. ')
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logHandleError('AuthorizeError — retrying callback')
|
|
||||||
return await callback().catch((err: any) => {
|
return await callback().catch((err: any) => {
|
||||||
this.logHandleError('AuthorizeError — callback failed', {
|
|
||||||
errorType: err?.constructor?.name,
|
|
||||||
code: err?.code,
|
|
||||||
message: err?.message
|
|
||||||
})
|
|
||||||
throw prefixMessage(
|
throw prefixMessage(
|
||||||
err,
|
err,
|
||||||
'Error while executing callback in handleError. '
|
'Error while executing callback in handleError. '
|
||||||
@@ -714,14 +632,12 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (e instanceof LoginRequiredError) {
|
if (e instanceof LoginRequiredError) {
|
||||||
this.logHandleError('LoginRequiredError — clearing CSRF and re-throwing')
|
|
||||||
this.clearCsrfTokens()
|
this.clearCsrfTokens()
|
||||||
|
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
|
|
||||||
if (e instanceof InvalidSASjsCsrfError) {
|
if (e instanceof InvalidSASjsCsrfError) {
|
||||||
this.logHandleError('InvalidSASjsCsrfError — re-fetching CSRF cookie')
|
|
||||||
// Fetching root and creating CSRF cookie
|
// Fetching root and creating CSRF cookie
|
||||||
await this.httpClient
|
await this.httpClient
|
||||||
.get('/', {
|
.get('/', {
|
||||||
@@ -733,22 +649,13 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
response.data
|
response.data
|
||||||
)?.[1]
|
)?.[1]
|
||||||
|
|
||||||
this.logHandleError(
|
|
||||||
'InvalidSASjsCsrfError — cookie found: ' + !!cookie
|
|
||||||
)
|
|
||||||
if (cookie) document.cookie = cookie
|
if (cookie) document.cookie = cookie
|
||||||
})
|
})
|
||||||
.catch((err) => {
|
.catch((err) => {
|
||||||
throw prefixMessage(err, 'Error while re-fetching CSRF token.')
|
throw prefixMessage(err, 'Error while re-fetching CSRF token.')
|
||||||
})
|
})
|
||||||
|
|
||||||
this.logHandleError('InvalidSASjsCsrfError — retrying callback')
|
|
||||||
return await callback().catch((err: any) => {
|
return await callback().catch((err: any) => {
|
||||||
this.logHandleError('InvalidSASjsCsrfError — callback failed', {
|
|
||||||
errorType: err?.constructor?.name,
|
|
||||||
code: err?.code,
|
|
||||||
message: err?.message
|
|
||||||
})
|
|
||||||
throw prefixMessage(
|
throw prefixMessage(
|
||||||
err,
|
err,
|
||||||
'Error while executing callback in handleError. '
|
'Error while executing callback in handleError. '
|
||||||
@@ -759,20 +666,8 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
if (response?.status === 403 || response?.status === 449) {
|
if (response?.status === 403 || response?.status === 449) {
|
||||||
this.parseAndSetCsrfToken(response)
|
this.parseAndSetCsrfToken(response)
|
||||||
|
|
||||||
const hasToken = !!(this.csrfToken.headerName && this.csrfToken.value)
|
if (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) => {
|
return await callback().catch((err: any) => {
|
||||||
this.logHandleError('403/449 — callback failed', {
|
|
||||||
errorType: err?.constructor?.name,
|
|
||||||
code: err?.code,
|
|
||||||
message: err?.message
|
|
||||||
})
|
|
||||||
throw prefixMessage(
|
throw prefixMessage(
|
||||||
err,
|
err,
|
||||||
'Error while executing callback in handleError. '
|
'Error while executing callback in handleError. '
|
||||||
@@ -780,9 +675,6 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
this.logHandleError(
|
|
||||||
'403/449 — no CSRF in response, throwing original error'
|
|
||||||
)
|
|
||||||
throw e
|
throw e
|
||||||
} else if (response?.status === 404) {
|
} else if (response?.status === 404) {
|
||||||
throw new NotFoundError(response.config.url!)
|
throw new NotFoundError(response.config.url!)
|
||||||
@@ -795,68 +687,6 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
|
|||||||
throw new CertificateError(e.message)
|
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, re-establish session via GET /,
|
|
||||||
// then retry the original request.
|
|
||||||
this.logHandleError('ERR_NETWORK — clearing all auth state')
|
|
||||||
this.resetInMemoryAuthState()
|
|
||||||
this.isRecoveringFromNetworkError = true
|
|
||||||
try {
|
|
||||||
// Re-establish session and CSRF cookie
|
|
||||||
this.logHandleError('ERR_NETWORK — re-establishing session via GET /')
|
|
||||||
const rootResponse = await this.httpClient
|
|
||||||
.get('/', { withXSRFToken: true })
|
|
||||||
.catch((err) => {
|
|
||||||
this.logHandleError('ERR_NETWORK — GET / failed', {
|
|
||||||
code: err?.code,
|
|
||||||
status: err?.response?.status,
|
|
||||||
message: err?.message
|
|
||||||
})
|
|
||||||
return err.response
|
|
||||||
})
|
|
||||||
|
|
||||||
if (rootResponse?.data) {
|
|
||||||
const cookie =
|
|
||||||
/<script>document.cookie = '(XSRF-TOKEN=.*; Max-Age=86400; SameSite=Strict; Path=\/;)'<\/script>/.exec(
|
|
||||||
rootResponse.data
|
|
||||||
)?.[1]
|
|
||||||
|
|
||||||
if (cookie && typeof document !== 'undefined') {
|
|
||||||
document.cookie = cookie
|
|
||||||
this.logHandleError('ERR_NETWORK — XSRF-TOKEN cookie restored')
|
|
||||||
}
|
|
||||||
|
|
||||||
this.parseAndSetCsrfToken(rootResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
this.logHandleError('ERR_NETWORK — retrying original request')
|
|
||||||
return await callback()
|
|
||||||
} catch (retryErr: any) {
|
|
||||||
// Session could not be recovered — surface LoginRequiredError
|
|
||||||
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
|
if (e.message) throw e
|
||||||
else throw prefixMessage(e, 'Error while handling error. ')
|
else throw prefixMessage(e, 'Error while handling error. ')
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,13 +23,6 @@ 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) {
|
public async login(username: string, password: string, jobsPath: string) {
|
||||||
const codeInjectorPath = `/User Folders/${username}/My Folder/sasjs/runner`
|
const codeInjectorPath = `/User Folders/${username}/My Folder/sasjs/runner`
|
||||||
if (this.httpClient.defaults.jar) {
|
if (this.httpClient.defaults.jar) {
|
||||||
|
|||||||
@@ -589,42 +589,6 @@ ${resHeaders[0]}: ${resHeaders[1]}${
|
|||||||
requestClient['handleError'](error, () => {}, false)
|
requestClient['handleError'](error, () => {}, false)
|
||||||
).resolves.toEqual(undefined)
|
).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