@sasjs/adapter 6.2.2 → 6.3.1
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.
- package/ContextManager.d.ts +1 -1
- package/README.md +11 -0
- package/SASViyaApiClient.d.ts +6 -1
- package/SASViyaApiClient.js +67 -2
- package/SASjs.d.ts +3 -2
- package/SASjs.js +11 -5
- package/SASjsApiClient.d.ts +2 -1
- package/api/viya/executeOnComputeApi.d.ts +2 -1
- package/api/viya/pollJobState.d.ts +2 -1
- package/auth/AuthConfig.d.ts +11 -0
- package/auth/AuthConfig.js +2 -0
- package/auth/getTokens.d.ts +2 -1
- package/auth/getTokens.js +85 -0
- package/dist/minified_sas9.js +216 -216
- package/dist/sasjs-adapter.js +533 -365
- package/index.d.ts +1 -0
- package/job-execution/ComputeJobExecutor.d.ts +1 -1
- package/job-execution/JesJobExecutor.d.ts +1 -1
- package/job-execution/JobExecutor.d.ts +2 -1
- package/job-execution/SasjsJobExecutor.d.ts +2 -1
- package/job-execution/WebJobExecutor.d.ts +2 -1
- package/job-execution/WebJobExecutor.js +17 -5
- package/package.json +2 -2
- package/utils/parseViyaDebugResponse.d.ts +1 -1
- package/utils/parseViyaDebugResponse.js +2 -2
package/ContextManager.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { AuthConfig } from './auth/AuthConfig';
|
|
1
2
|
import { Context, EditContextInput, ContextAllAttributes } from './types';
|
|
2
3
|
import { RequestClient } from './request/RequestClient';
|
|
3
|
-
import { AuthConfig } from '@sasjs/utils/types';
|
|
4
4
|
export declare class ContextManager {
|
|
5
5
|
private serverUrl;
|
|
6
6
|
private requestClient;
|
package/README.md
CHANGED
|
@@ -109,6 +109,17 @@ sasJs.logIn('USERNAME','PASSWORD'
|
|
|
109
109
|
|
|
110
110
|
More examples of using authentication, and more, can be found in the [SASjs Seed Apps](https://github.com/search?q=topic%3Asasjs-app+org%3Asasjs+fork%3Atrue) on github.
|
|
111
111
|
|
|
112
|
+
### Viya client credentials
|
|
113
|
+
|
|
114
|
+
For noninteractive Viya execution, supply an application identity as `authConfig`:
|
|
115
|
+
|
|
116
|
+
```typescript
|
|
117
|
+
const auth = { grantType: 'client_credentials' as const, client: 'client-id', secret: 'client-secret' }
|
|
118
|
+
await sasJs.executeScript({ linesOfCode: ['%put hello;'], authConfig: auth })
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
The adapter requests an access token from SASLogon and reacquires it on expiry; this grant does not use a refresh token. The grant needs the client secret, so use it only where that secret stays private, such as a CLI or a server process, and not in an app delivered to a browser. The Viya client must have the permissions required by the requested operations. `SASViyaApiClient.withAccessTokenProvider(provider)` returns an independent client resolving a token per HTTP operation. `deployServicePack` also accepts such a provider in place of its access-token argument.
|
|
122
|
+
|
|
112
123
|
### SAS 9 credentials (deprecated)
|
|
113
124
|
|
|
114
125
|
Earlier versions logged into SAS 9 by passing a username and password, which were appended to the `_program` URL as `_username` and `_password`. This is deprecated.
|
package/SASViyaApiClient.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Job, Session, Context, ContextAllAttributes, Folder, File, EditContextInput, PollOptions } from './types';
|
|
2
|
-
import {
|
|
2
|
+
import { AuthConfig } from './auth/AuthConfig';
|
|
3
|
+
import { SasAuthResponse, MacroVar } from '@sasjs/utils/types';
|
|
3
4
|
import { RequestClient } from './request/RequestClient';
|
|
4
5
|
import { OnTokensRefreshed } from './auth/getTokens';
|
|
5
6
|
import { FileResource } from './types/FileResource';
|
|
@@ -25,9 +26,13 @@ export declare class SASViyaApiClient {
|
|
|
25
26
|
private contextManager;
|
|
26
27
|
private folderMap;
|
|
27
28
|
private folderMapGeneration;
|
|
29
|
+
private hasTokenProvider;
|
|
30
|
+
private providerBase?;
|
|
28
31
|
invalidateFolderCache(): void;
|
|
29
32
|
private fileExtensionMap;
|
|
30
33
|
private boolExtensionMap;
|
|
34
|
+
/** Return a Viya client that resolves the bearer before every request. */
|
|
35
|
+
withAccessTokenProvider(provider: () => Promise<string> | string): SASViyaApiClient;
|
|
31
36
|
/**
|
|
32
37
|
* A helper method used to call appendRequest method of RequestClient
|
|
33
38
|
* @param response - response from sasjs request
|
package/SASViyaApiClient.js
CHANGED
|
@@ -32,6 +32,11 @@ const refreshTokensForViya_1 = require("./auth/refreshTokensForViya");
|
|
|
32
32
|
const host_1 = require("./utils/host");
|
|
33
33
|
const NotFoundError_1 = require("./types/errors/NotFoundError");
|
|
34
34
|
const validateForcedServicePack_1 = require("./utils/validateForcedServicePack");
|
|
35
|
+
class TokenProviderError extends Error {
|
|
36
|
+
constructor(error) {
|
|
37
|
+
super(error instanceof Error ? error.message : String(error));
|
|
38
|
+
}
|
|
39
|
+
}
|
|
35
40
|
/**
|
|
36
41
|
* A client for interfacing with the SAS Viya REST API.
|
|
37
42
|
*
|
|
@@ -47,6 +52,7 @@ class SASViyaApiClient {
|
|
|
47
52
|
this.contextManager = new ContextManager_1.ContextManager(this.serverUrl, this.requestClient);
|
|
48
53
|
this.folderMap = new Map();
|
|
49
54
|
this.folderMapGeneration = 0;
|
|
55
|
+
this.hasTokenProvider = false;
|
|
50
56
|
this.fileExtensionMap = new Map();
|
|
51
57
|
this.boolExtensionMap = false; // required in case the map has zero entries
|
|
52
58
|
if (serverUrl)
|
|
@@ -57,6 +63,45 @@ class SASViyaApiClient {
|
|
|
57
63
|
this.folderMap.clear();
|
|
58
64
|
}
|
|
59
65
|
// after an attempt to populate it.
|
|
66
|
+
/** Return a Viya client that resolves the bearer before every request. */
|
|
67
|
+
withAccessTokenProvider(provider) {
|
|
68
|
+
const positions = {
|
|
69
|
+
get: 1,
|
|
70
|
+
delete: 1,
|
|
71
|
+
post: 2,
|
|
72
|
+
put: 2,
|
|
73
|
+
patch: 2,
|
|
74
|
+
uploadFile: 2
|
|
75
|
+
};
|
|
76
|
+
const base = this.providerBase || this.requestClient;
|
|
77
|
+
const requestClient = new Proxy(base, {
|
|
78
|
+
get(target, property) {
|
|
79
|
+
const value = Reflect.get(target, property, target);
|
|
80
|
+
if (typeof value !== 'function')
|
|
81
|
+
return value;
|
|
82
|
+
if (typeof property === 'string' &&
|
|
83
|
+
Object.prototype.hasOwnProperty.call(positions, property)) {
|
|
84
|
+
return (...args) => __awaiter(this, void 0, void 0, function* () {
|
|
85
|
+
if (property === 'post' && args[0] === '/SASLogon/oauth/token')
|
|
86
|
+
return value.apply(target, args);
|
|
87
|
+
try {
|
|
88
|
+
args[positions[property]] = yield provider();
|
|
89
|
+
}
|
|
90
|
+
catch (error) {
|
|
91
|
+
throw new TokenProviderError(error);
|
|
92
|
+
}
|
|
93
|
+
return value.apply(target, args);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
return value.bind(target);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
const client = new SASViyaApiClient(this.serverUrl, this.rootFolderName, this.contextName, requestClient);
|
|
100
|
+
client.hasTokenProvider = true;
|
|
101
|
+
client.providerBase = base;
|
|
102
|
+
client.debug = this.debug;
|
|
103
|
+
return client;
|
|
104
|
+
}
|
|
60
105
|
/**
|
|
61
106
|
* A helper method used to call appendRequest method of RequestClient
|
|
62
107
|
* @param response - response from sasjs request
|
|
@@ -230,6 +275,12 @@ class SASViyaApiClient {
|
|
|
230
275
|
*/
|
|
231
276
|
executeScript(jobPath_1, linesOfCode_1, contextName_1, authConfig_1) {
|
|
232
277
|
return __awaiter(this, arguments, void 0, function* (jobPath, linesOfCode, contextName, authConfig, data = null, debug = false, expectWebout = false, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
|
|
278
|
+
if (authConfig &&
|
|
279
|
+
'grantType' in authConfig &&
|
|
280
|
+
authConfig.grantType === 'client_credentials' &&
|
|
281
|
+
!this.hasTokenProvider) {
|
|
282
|
+
return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeScript(jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
|
|
283
|
+
}
|
|
233
284
|
return (0, executeOnComputeApi_1.executeOnComputeApi)(this.requestClient, this.sessionManager, this.rootFolderName, jobPath, linesOfCode, contextName, authConfig, data, debug, expectWebout, waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
|
|
234
285
|
});
|
|
235
286
|
}
|
|
@@ -814,6 +865,12 @@ class SASViyaApiClient {
|
|
|
814
865
|
*/
|
|
815
866
|
executeComputeJob(sasJob_1, contextName_1, debug_1, data_1, authConfig_1) {
|
|
816
867
|
return __awaiter(this, arguments, void 0, function* (sasJob, contextName, debug, data, authConfig, waitForResult = true, expectWebout = false, pollOptions, printPid = false, variables, onTokensRefreshed) {
|
|
868
|
+
if (authConfig &&
|
|
869
|
+
'grantType' in authConfig &&
|
|
870
|
+
authConfig.grantType === 'client_credentials' &&
|
|
871
|
+
!this.hasTokenProvider) {
|
|
872
|
+
return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeComputeJob(sasJob, contextName, debug, data, authConfig, waitForResult, expectWebout, pollOptions, printPid, variables, onTokensRefreshed);
|
|
873
|
+
}
|
|
817
874
|
let access_token = (authConfig || {}).access_token;
|
|
818
875
|
if (authConfig) {
|
|
819
876
|
;
|
|
@@ -872,6 +929,12 @@ class SASViyaApiClient {
|
|
|
872
929
|
executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed) {
|
|
873
930
|
return __awaiter(this, void 0, void 0, function* () {
|
|
874
931
|
var _a, _b, _c;
|
|
932
|
+
if (authConfig &&
|
|
933
|
+
'grantType' in authConfig &&
|
|
934
|
+
authConfig.grantType === 'client_credentials' &&
|
|
935
|
+
!this.hasTokenProvider) {
|
|
936
|
+
return this.withAccessTokenProvider(() => __awaiter(this, void 0, void 0, function* () { return (yield (0, getTokens_1.getTokens)(this.requestClient, authConfig)).access_token; })).executeJob(sasJob, contextName, debug, data, authConfig, onTokensRefreshed);
|
|
937
|
+
}
|
|
875
938
|
let access_token = (authConfig || {}).access_token;
|
|
876
939
|
if (authConfig) {
|
|
877
940
|
;
|
|
@@ -1023,7 +1086,8 @@ class SASViyaApiClient {
|
|
|
1023
1086
|
const { result: folder } = yield this.requestClient
|
|
1024
1087
|
.get(`${this.serverUrl}${url}`, accessToken)
|
|
1025
1088
|
.catch((err) => {
|
|
1026
|
-
if (err instanceof errors_1.CertificateError
|
|
1089
|
+
if (err instanceof errors_1.CertificateError ||
|
|
1090
|
+
err instanceof TokenProviderError)
|
|
1027
1091
|
throw err;
|
|
1028
1092
|
return { result: null };
|
|
1029
1093
|
});
|
|
@@ -1062,7 +1126,8 @@ class SASViyaApiClient {
|
|
|
1062
1126
|
const { result: folder } = yield this.requestClient
|
|
1063
1127
|
.get(`${this.serverUrl}${url}`, accessToken)
|
|
1064
1128
|
.catch((err) => {
|
|
1065
|
-
if (err instanceof errors_1.CertificateError
|
|
1129
|
+
if (err instanceof errors_1.CertificateError ||
|
|
1130
|
+
err instanceof TokenProviderError)
|
|
1066
1131
|
throw err;
|
|
1067
1132
|
return { result: null };
|
|
1068
1133
|
});
|
package/SASjs.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import { SASjsConfig, UploadFile, EditContextInput, PollOptions, VerboseMode, Lo
|
|
|
2
2
|
import { SASViyaApiClient } from './SASViyaApiClient';
|
|
3
3
|
import { SASjsAuthResponse } from './SASjsApiClient';
|
|
4
4
|
import { OnTokensRefreshed } from './auth/getTokens';
|
|
5
|
-
import {
|
|
5
|
+
import { AuthConfig } from './auth/AuthConfig';
|
|
6
|
+
import { MacroVar, ExtraResponseAttributes, SasAuthResponse, AuthConfigSas9 } from '@sasjs/utils/types';
|
|
6
7
|
import { AxiosResponse, AxiosError } from 'axios';
|
|
7
8
|
interface ExecuteScriptParams {
|
|
8
9
|
linesOfCode: string[];
|
|
@@ -364,7 +365,7 @@ export default class SASjs {
|
|
|
364
365
|
* @param isForced - move the entire existing appLoc to the recycle bin before deploying (including content omitted from this pack); defaults to false. Requires exclusive control of appLoc, its parent and recycle bin. A failure may leave an incomplete app; see README for recovery.
|
|
365
366
|
* @param onProgress - called immediately before each pack member is written, with its name, folder, type and 1-based position.
|
|
366
367
|
*/
|
|
367
|
-
deployServicePack(serviceJson: any, appLoc?: string, serverUrl?: string, accessToken?: string, isForced?: boolean, onProgress?: (progress: DeployProgress) => void): Promise<void>;
|
|
368
|
+
deployServicePack(serviceJson: any, appLoc?: string, serverUrl?: string, accessToken?: string | (() => Promise<string> | string), isForced?: boolean, onProgress?: (progress: DeployProgress) => void): Promise<void>;
|
|
368
369
|
/**
|
|
369
370
|
* Kicks off execution of the given job via the compute API.
|
|
370
371
|
* @returns an object representing the compute session created for the given job.
|
package/SASjs.js
CHANGED
|
@@ -622,6 +622,8 @@ class SASjs {
|
|
|
622
622
|
return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false, onProgress) {
|
|
623
623
|
var _a, _b, _c;
|
|
624
624
|
this.isMethodSupported('deployServicePack', [types_2.ServerType.SasViya]);
|
|
625
|
+
const tokenProvider = typeof accessToken === 'function' ? accessToken : undefined;
|
|
626
|
+
const staticToken = typeof accessToken === 'string' ? accessToken : undefined;
|
|
625
627
|
let sasApiClient = null;
|
|
626
628
|
if (serverUrl !== undefined || appLoc !== undefined) {
|
|
627
629
|
if (serverUrl === undefined)
|
|
@@ -670,14 +672,16 @@ class SASjs {
|
|
|
670
672
|
if (serverUrl === this.sasjsConfig.serverUrl)
|
|
671
673
|
deploymentClient.copyCsrfFrom(this.requestClient);
|
|
672
674
|
deploymentClient.restrictDeploymentTransport();
|
|
673
|
-
|
|
675
|
+
let api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
|
|
676
|
+
if (tokenProvider)
|
|
677
|
+
api = api.withAccessTokenProvider(tokenProvider);
|
|
674
678
|
(_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.invalidateFolderCache();
|
|
675
679
|
try {
|
|
676
|
-
const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc,
|
|
680
|
+
const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, staticToken);
|
|
677
681
|
try {
|
|
678
682
|
const parent = appLoc.slice(0, appLoc.lastIndexOf('/'));
|
|
679
683
|
const name = appLoc.slice(appLoc.lastIndexOf('/') + 1);
|
|
680
|
-
const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`,
|
|
684
|
+
const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, staticToken, false);
|
|
681
685
|
if (!root ||
|
|
682
686
|
root.name !== name ||
|
|
683
687
|
root.parentFolderUri !== `/folders/folders/${parentId}` ||
|
|
@@ -685,7 +689,7 @@ class SASjs {
|
|
|
685
689
|
typeof root.id !== 'string' ||
|
|
686
690
|
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(root.id))
|
|
687
691
|
throw new Error('Invalid created app folder identity');
|
|
688
|
-
yield this.createFoldersAndServices(appLoc, serviceJson.members,
|
|
692
|
+
yield this.createFoldersAndServices(appLoc, serviceJson.members, staticToken, api, false, {
|
|
689
693
|
onProgress,
|
|
690
694
|
index: 0,
|
|
691
695
|
total: countMembers(serviceJson.members),
|
|
@@ -709,7 +713,9 @@ class SASjs {
|
|
|
709
713
|
serviceJson.members[0].members.sort((member) => member.type === 'folder' ? -1 : 1);
|
|
710
714
|
}
|
|
711
715
|
const members = serviceJson.members;
|
|
712
|
-
|
|
716
|
+
if (tokenProvider)
|
|
717
|
+
sasApiClient = (sasApiClient || this.sasViyaApiClient).withAccessTokenProvider(tokenProvider);
|
|
718
|
+
yield this.createFoldersAndServices(appLoc, members, staticToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
|
|
713
719
|
});
|
|
714
720
|
}
|
|
715
721
|
/**
|
package/SASjsApiClient.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { AuthConfig
|
|
1
|
+
import { AuthConfig } from './auth/AuthConfig';
|
|
2
|
+
import { MacroVar, ServicePackSASjs } from '@sasjs/utils/types';
|
|
2
3
|
import { ExecutionQuery, Job, PollOptions } from './types';
|
|
3
4
|
import { OnTokensRefreshed } from './auth/getTokens';
|
|
4
5
|
import { StateReader } from './api/viya/pollJobState';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { AuthConfig
|
|
1
|
+
import { AuthConfig } from '../../auth/AuthConfig';
|
|
2
|
+
import { MacroVar } from '@sasjs/utils/types';
|
|
2
3
|
import { PollOptions } from '../..';
|
|
3
4
|
import { OnTokensRefreshed } from '../../auth/getTokens';
|
|
4
5
|
import { RequestClient } from '../../request/RequestClient';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { AuthConfig
|
|
1
|
+
import { AuthConfig } from '../../auth/AuthConfig';
|
|
2
|
+
import { ServerType } from '@sasjs/utils/types';
|
|
2
3
|
import { Job, PollOptions } from '../..';
|
|
3
4
|
import { OnTokensRefreshed } from '../../auth/getTokens';
|
|
4
5
|
import { RequestClient } from '../../request/RequestClient';
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { AuthConfig as UserAuthConfig } from '@sasjs/utils/types';
|
|
2
|
+
/** Viya client credentials are opt-in; existing user-token configurations remain supported. */
|
|
3
|
+
export type AuthConfig = UserAuthConfig | (UserAuthConfig & {
|
|
4
|
+
grantType: 'authorization_code';
|
|
5
|
+
}) | {
|
|
6
|
+
grantType: 'client_credentials';
|
|
7
|
+
client: string;
|
|
8
|
+
secret: string;
|
|
9
|
+
access_token?: string;
|
|
10
|
+
refresh_token?: string;
|
|
11
|
+
};
|
package/auth/getTokens.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { AuthConfig
|
|
1
|
+
import { AuthConfig } from './AuthConfig';
|
|
2
|
+
import { ServerType } from '@sasjs/utils/types';
|
|
2
3
|
import { RequestClient } from '../request/RequestClient';
|
|
3
4
|
/**
|
|
4
5
|
* Callback invoked with the rotated token pair after a successful internal
|
package/auth/getTokens.js
CHANGED
|
@@ -14,8 +14,90 @@ const auth_1 = require("@sasjs/utils/auth");
|
|
|
14
14
|
const types_1 = require("@sasjs/utils/types");
|
|
15
15
|
const refreshTokensForViya_1 = require("./refreshTokensForViya");
|
|
16
16
|
const refreshTokensForSasjs_1 = require("./refreshTokensForSasjs");
|
|
17
|
+
const getTokenRequestErrorPrefix_1 = require("./getTokenRequestErrorPrefix");
|
|
18
|
+
const errors_1 = require("../types/errors");
|
|
17
19
|
const host_1 = require("../utils/host");
|
|
18
20
|
const apiBasePath_1 = require("../apiBasePath");
|
|
21
|
+
const clientTokens = new WeakMap();
|
|
22
|
+
/**
|
|
23
|
+
* Returns the auth configuration for a Viya client-credentials identity,
|
|
24
|
+
* requesting an access token when there is none or the held one has expired.
|
|
25
|
+
* This grant has no refresh token.
|
|
26
|
+
*
|
|
27
|
+
* The token is also written to `authConfig.access_token`, as the user-token
|
|
28
|
+
* path below does: code further down an execution chain (the job poll, for
|
|
29
|
+
* one) reads the token from the shared `authConfig`, not from this return
|
|
30
|
+
* value.
|
|
31
|
+
*
|
|
32
|
+
* A token's lifetime is counted from the moment the request was sent, so the
|
|
33
|
+
* held token is dropped no later than the server's own expiry. No further
|
|
34
|
+
* margin is subtracted. A response that states no `expires_in` is never held:
|
|
35
|
+
* the next call requests a new token.
|
|
36
|
+
* @param requestClient - the pre-configured HTTP request client
|
|
37
|
+
* @param authConfig - the client ID and secret, with `grantType` set to
|
|
38
|
+
* `client_credentials`
|
|
39
|
+
* @param serverType - must be SASVIYA.
|
|
40
|
+
*/
|
|
41
|
+
function getClientCredentialsTokens(requestClient, authConfig, serverType) {
|
|
42
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
43
|
+
const { client, secret } = authConfig;
|
|
44
|
+
if (serverType !== types_1.ServerType.SasViya)
|
|
45
|
+
throw new Error('Client credentials require SAS Viya');
|
|
46
|
+
if (!client || !secret)
|
|
47
|
+
throw new Error('Client credentials require a client and secret');
|
|
48
|
+
const baseUrl = requestClient.getBaseUrl();
|
|
49
|
+
let state = clientTokens.get(authConfig);
|
|
50
|
+
if (!state ||
|
|
51
|
+
state.client !== client ||
|
|
52
|
+
state.secret !== secret ||
|
|
53
|
+
state.baseUrl !== baseUrl) {
|
|
54
|
+
state = { token: '', expiresAt: 0, client, secret, baseUrl };
|
|
55
|
+
clientTokens.set(authConfig, state);
|
|
56
|
+
}
|
|
57
|
+
let access_token;
|
|
58
|
+
if (!state.token || Date.now() >= state.expiresAt) {
|
|
59
|
+
if (!state.pending) {
|
|
60
|
+
const tokenState = state;
|
|
61
|
+
const requestedAt = Date.now();
|
|
62
|
+
const pair = `${client}:${secret}`;
|
|
63
|
+
const url = '/SASLogon/oauth/token';
|
|
64
|
+
const data = 'grant_type=client_credentials';
|
|
65
|
+
const headers = {
|
|
66
|
+
Authorization: 'Basic ' +
|
|
67
|
+
(typeof Buffer === 'undefined'
|
|
68
|
+
? btoa(pair)
|
|
69
|
+
: Buffer.from(pair).toString('base64')),
|
|
70
|
+
'Content-Type': 'application/x-www-form-urlencoded'
|
|
71
|
+
};
|
|
72
|
+
state.pending = requestClient
|
|
73
|
+
.post(url, data, undefined, 'application/x-www-form-urlencoded', headers)
|
|
74
|
+
.catch((err) => {
|
|
75
|
+
if (err instanceof errors_1.CertificateError)
|
|
76
|
+
throw err;
|
|
77
|
+
throw (0, getTokenRequestErrorPrefix_1.tokenRequestErrorMessage)(err, 'fetching access token', 'getTokens', types_1.ServerType.SasViya, url, data, headers, client, secret);
|
|
78
|
+
})
|
|
79
|
+
.then(({ result }) => {
|
|
80
|
+
if (!(result === null || result === void 0 ? void 0 : result.access_token))
|
|
81
|
+
throw new Error('Client credentials response did not contain an access token');
|
|
82
|
+
const expiresAt = requestedAt + (Number(result.expires_in) || 0) * 1000;
|
|
83
|
+
if (result.expires_in != null && Date.now() >= expiresAt)
|
|
84
|
+
throw new Error('Client credentials access token expired before receipt');
|
|
85
|
+
tokenState.token = result.access_token;
|
|
86
|
+
tokenState.expiresAt = expiresAt;
|
|
87
|
+
return tokenState.token;
|
|
88
|
+
})
|
|
89
|
+
.finally(() => {
|
|
90
|
+
tokenState.pending = undefined;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
access_token = yield state.pending;
|
|
94
|
+
}
|
|
95
|
+
else
|
|
96
|
+
access_token = state.token;
|
|
97
|
+
authConfig.access_token = access_token;
|
|
98
|
+
return Object.assign(Object.assign({}, authConfig), { access_token });
|
|
99
|
+
});
|
|
100
|
+
}
|
|
19
101
|
/**
|
|
20
102
|
* Returns the auth configuration, refreshing the tokens if necessary.
|
|
21
103
|
* This function can only be used by Node, if a server type is SASVIYA.
|
|
@@ -29,6 +111,9 @@ const apiBasePath_1 = require("../apiBasePath");
|
|
|
29
111
|
*/
|
|
30
112
|
function getTokens(requestClient_1, authConfig_1) {
|
|
31
113
|
return __awaiter(this, arguments, void 0, function* (requestClient, authConfig, serverType = types_1.ServerType.SasViya, onTokensRefreshed, apiBasePath = apiBasePath_1.DEFAULT_API_BASE_PATH) {
|
|
114
|
+
if ('grantType' in authConfig &&
|
|
115
|
+
authConfig.grantType === 'client_credentials')
|
|
116
|
+
return getClientCredentialsTokens(requestClient, authConfig, serverType);
|
|
32
117
|
const logger = (0, host_1.getLogger)();
|
|
33
118
|
// Note: client/secret are NOT mutated. The sas.cli public-client fallback
|
|
34
119
|
// is applied only to the refresh call itself, so a caller that round-trips
|