@sasjs/cli 4.18.6 → 4.20.0

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.
@@ -200,27 +200,6 @@ describe('AddCommand - cred', function () {
200
200
  expect(command.subCommand).toEqual('cred');
201
201
  expect(command.insecure).toEqual(true);
202
202
  });
203
- it('should parse a sasjs add cred command invoked with the alias sasjs auth', function () {
204
- var args = __spreadArray(__spreadArray([], __read(defaultArgs), false), ['auth', '-i'], false);
205
- var command = new addCommand_1.AddCommand(args);
206
- expect(command.name).toEqual('add');
207
- expect(command.insecure).toEqual(true);
208
- });
209
- it('should call the addCredential handler when executed with the alias sasjs auth', function () { return __awaiter(void 0, void 0, void 0, function () {
210
- var args, command;
211
- return __generator(this, function (_a) {
212
- switch (_a.label) {
213
- case 0:
214
- args = __spreadArray(__spreadArray([], __read(defaultArgs), false), ['auth', '-t', 'test'], false);
215
- command = new addCommand_1.AddCommand(args);
216
- return [4 /*yield*/, command.execute()];
217
- case 1:
218
- _a.sent();
219
- expect(addCredentialModule.addCredential).toHaveBeenCalledWith(target, false, types_1.TargetScope.Local);
220
- return [2 /*return*/];
221
- }
222
- });
223
- }); });
224
203
  it('should call the addCredential handler when executed without the insecure option', function () { return __awaiter(void 0, void 0, void 0, function () {
225
204
  var args, command;
226
205
  return __generator(this, function (_a) {
@@ -0,0 +1,10 @@
1
+ import { ReturnCode } from '../../types/command';
2
+ import { TargetCommand } from '../../types/command/targetCommand';
3
+ export declare class AuthCommand extends TargetCommand {
4
+ constructor(args: string[]);
5
+ get insecure(): boolean;
6
+ get passwordStdin(): boolean;
7
+ execute(): Promise<ReturnCode.Success | ReturnCode.InternalError>;
8
+ executeLogin(): Promise<ReturnCode.Success | ReturnCode.InternalError>;
9
+ executeCred(): Promise<ReturnCode.Success | ReturnCode.InternalError>;
10
+ }
@@ -0,0 +1,207 @@
1
+ "use strict";
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
18
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
19
+ return new (P || (P = Promise))(function (resolve, reject) {
20
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
21
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
22
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
23
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
24
+ });
25
+ };
26
+ var __generator = (this && this.__generator) || function (thisArg, body) {
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
+ function verb(n) { return function (v) { return step([n, v]); }; }
30
+ function step(op) {
31
+ if (f) throw new TypeError("Generator is already executing.");
32
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
33
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
34
+ if (y = 0, t) op = [op[0] & 2, t.value];
35
+ switch (op[0]) {
36
+ case 0: case 1: t = op; break;
37
+ case 4: _.label++; return { value: op[1], done: false };
38
+ case 5: _.label++; y = op[1]; op = [0]; continue;
39
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
40
+ default:
41
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
42
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
43
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
44
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
45
+ if (t[2]) _.ops.pop();
46
+ _.trys.pop(); continue;
47
+ }
48
+ op = body.call(thisArg, _);
49
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
50
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
51
+ }
52
+ };
53
+ Object.defineProperty(exports, "__esModule", { value: true });
54
+ exports.AuthCommand = void 0;
55
+ var types_1 = require("../../types");
56
+ var command_1 = require("../../types/command");
57
+ var targetCommand_1 = require("../../types/command/targetCommand");
58
+ var addCredential_1 = require("../add/addCredential");
59
+ var login_1 = require("./login");
60
+ var AuthSubCommand;
61
+ (function (AuthSubCommand) {
62
+ AuthSubCommand["Login"] = "login";
63
+ })(AuthSubCommand || (AuthSubCommand = {}));
64
+ // The syntax here uses square brackets for the subCommand (i.e. makes it
65
+ // optional) since `sasjs auth` without a subCommand retains its historical
66
+ // behaviour (it used to be an alias of `sasjs add cred`).
67
+ var syntax = 'auth [subCommand] [options]';
68
+ var usage = 'sasjs auth login --target <target-name> | sasjs auth [options]';
69
+ var description = "Authenticates against the specified target.\n" +
70
+ "With the 'login' subCommand, authentication is performed with a SAS username and password " +
71
+ "(no OAuth client/secret required, SASVIYA targets only) and the resulting tokens are saved.\n" +
72
+ "Without a subCommand, behaves like 'sasjs add cred' (client/secret based authentication).\n" +
73
+ "\n" +
74
+ "Non-interactive use (CI/agents): set SAS_USERNAME and SAS_PASSWORD environment variables, " +
75
+ "or pipe the password and use --password-stdin.";
76
+ var examples = [
77
+ {
78
+ command: 'sasjs auth login --target <target-name>',
79
+ description: 'Logs in with SAS username/password (no client/secret required).'
80
+ },
81
+ {
82
+ command: 'sasjs auth login -t <target-name>',
83
+ description: ''
84
+ },
85
+ {
86
+ command: 'SAS_USERNAME=usr SAS_PASSWORD=pass sasjs auth login -t <target-name>',
87
+ description: 'Non-interactive: read credentials from SAS_USERNAME/SAS_PASSWORD env vars (CI/agents).'
88
+ },
89
+ {
90
+ command: 'echo "$SAS_PASSWORD" | sasjs auth login --password-stdin -t <target-name>',
91
+ description: 'Non-interactive: read the password from stdin (avoids shell history).'
92
+ },
93
+ {
94
+ command: 'sasjs auth --target <target-name>',
95
+ description: 'Legacy behaviour, equivalent to `sasjs add cred`.'
96
+ }
97
+ ];
98
+ var AuthCommand = /** @class */ (function (_super) {
99
+ __extends(AuthCommand, _super);
100
+ function AuthCommand(args) {
101
+ var parseOptions = {
102
+ insecure: {
103
+ type: 'boolean',
104
+ alias: 'i',
105
+ default: false,
106
+ description: 'Allows the command to bypass the HTTPs requirement. Not recommended.'
107
+ },
108
+ passwordStdin: {
109
+ type: 'boolean',
110
+ default: false,
111
+ description: 'Read the password from stdin instead of prompting or reading the ' +
112
+ 'SAS_PASSWORD env var. Use this in CI/scripts to avoid leaking the ' +
113
+ 'password in shell history (e.g. ' +
114
+ '`echo "$SAS_PASSWORD" | sasjs auth login --password-stdin -t <target>`).'
115
+ }
116
+ };
117
+ return _super.call(this, args, { parseOptions: parseOptions, usage: usage, description: description, examples: examples, syntax: syntax }) || this;
118
+ }
119
+ Object.defineProperty(AuthCommand.prototype, "insecure", {
120
+ get: function () {
121
+ return !!this.parsed.insecure;
122
+ },
123
+ enumerable: false,
124
+ configurable: true
125
+ });
126
+ Object.defineProperty(AuthCommand.prototype, "passwordStdin", {
127
+ get: function () {
128
+ return !!this.parsed.passwordStdin;
129
+ },
130
+ enumerable: false,
131
+ configurable: true
132
+ });
133
+ AuthCommand.prototype.execute = function () {
134
+ return __awaiter(this, void 0, void 0, function () {
135
+ var _a;
136
+ return __generator(this, function (_b) {
137
+ switch (_b.label) {
138
+ case 0:
139
+ if (!(this.subCommand === AuthSubCommand.Login)) return [3 /*break*/, 2];
140
+ return [4 /*yield*/, this.executeLogin()];
141
+ case 1:
142
+ _a = _b.sent();
143
+ return [3 /*break*/, 4];
144
+ case 2: return [4 /*yield*/, this.executeCred()];
145
+ case 3:
146
+ _a = _b.sent();
147
+ _b.label = 4;
148
+ case 4: return [2 /*return*/, _a];
149
+ }
150
+ });
151
+ });
152
+ };
153
+ AuthCommand.prototype.executeLogin = function () {
154
+ var _a;
155
+ return __awaiter(this, void 0, void 0, function () {
156
+ var target, err_1;
157
+ return __generator(this, function (_b) {
158
+ switch (_b.label) {
159
+ case 0: return [4 /*yield*/, this.getTargetInfo()];
160
+ case 1:
161
+ target = (_b.sent()).target;
162
+ _b.label = 2;
163
+ case 2:
164
+ _b.trys.push([2, 4, , 5]);
165
+ return [4 /*yield*/, (0, login_1.authLogin)(target, this.insecure, this.passwordStdin)];
166
+ case 3:
167
+ _b.sent();
168
+ return [2 /*return*/, command_1.ReturnCode.Success];
169
+ case 4:
170
+ err_1 = _b.sent();
171
+ (_a = process.logger) === null || _a === void 0 ? void 0 : _a.error('Error logging in.', (err_1 === null || err_1 === void 0 ? void 0 : err_1.message) || err_1);
172
+ return [2 /*return*/, command_1.ReturnCode.InternalError];
173
+ case 5: return [2 /*return*/];
174
+ }
175
+ });
176
+ });
177
+ };
178
+ AuthCommand.prototype.executeCred = function () {
179
+ var _a, _b;
180
+ return __awaiter(this, void 0, void 0, function () {
181
+ var _c, target, isLocal, scope, err_2;
182
+ return __generator(this, function (_d) {
183
+ switch (_d.label) {
184
+ case 0: return [4 /*yield*/, this.getTargetInfo()];
185
+ case 1:
186
+ _c = _d.sent(), target = _c.target, isLocal = _c.isLocal;
187
+ scope = isLocal ? types_1.TargetScope.Local : types_1.TargetScope.Global;
188
+ _d.label = 2;
189
+ case 2:
190
+ _d.trys.push([2, 4, , 5]);
191
+ return [4 /*yield*/, (0, addCredential_1.addCredential)(target, this.insecure, scope)];
192
+ case 3:
193
+ _d.sent();
194
+ (_a = process.logger) === null || _a === void 0 ? void 0 : _a.success('Credentials successfully added!');
195
+ return [2 /*return*/, command_1.ReturnCode.Success];
196
+ case 4:
197
+ err_2 = _d.sent();
198
+ (_b = process.logger) === null || _b === void 0 ? void 0 : _b.error('Error adding credentials.', err_2.toString());
199
+ return [2 /*return*/, command_1.ReturnCode.InternalError];
200
+ case 5: return [2 /*return*/];
201
+ }
202
+ });
203
+ });
204
+ };
205
+ return AuthCommand;
206
+ }(targetCommand_1.TargetCommand));
207
+ exports.AuthCommand = AuthCommand;
@@ -0,0 +1,33 @@
1
+ import { Target } from '@sasjs/utils';
2
+ /**
3
+ * Authenticates against a SASVIYA target using a SAS username and password
4
+ * (OAuth2 resource owner password grant against the built-in, secret-less
5
+ * `sas.cli` client) and persists the resulting token pair. This enables all
6
+ * authenticated commands (`sasjs run`, `sasjs deploy`, etc.) on estates where
7
+ * no administrator-registered OAuth client/secret is available.
8
+ *
9
+ * Credentials are resolved in this order (highest precedence first):
10
+ *
11
+ * Username: SAS_USERNAME env var > interactive prompt (TTY only)
12
+ * Password: --password-stdin > SAS_PASSWORD env var > interactive prompt (TTY only)
13
+ *
14
+ * When `--password-stdin` is set, stdin is consumed for the password, so the
15
+ * username MUST come from the SAS_USERNAME env var (interactive prompting is
16
+ * not possible because stdin is already redirected).
17
+ *
18
+ * If no TTY is available and no env var / stdin flag supplies the credential,
19
+ * the function throws with a message pointing the caller at the env vars or
20
+ * `--password-stdin` flag — this makes `sasjs auth login` safe to call from
21
+ * CI pipelines and non-interactive agents.
22
+ *
23
+ * The password is used only to mint the tokens and is never stored. When the
24
+ * access token expires, re-run `sasjs auth login -t <target>`.
25
+ * @param {Target} target - the target to authenticate against.
26
+ * @param {boolean} insecure - when true, bypasses TLS certificate validation
27
+ * (for self-signed cert Viya servers). Mirrors the `--insecure` flag on
28
+ * `sasjs add cred`.
29
+ * @param {boolean} passwordStdin - when true, reads the password from stdin
30
+ * (like `docker login --password-stdin`) instead of prompting or reading
31
+ * the SAS_PASSWORD env var. The username must then come from SAS_USERNAME.
32
+ */
33
+ export declare const authLogin: (target: Target, insecure?: boolean, passwordStdin?: boolean) => Promise<void>;
@@ -0,0 +1,237 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
+ return new (P || (P = Promise))(function (resolve, reject) {
16
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
20
+ });
21
+ };
22
+ var __generator = (this && this.__generator) || function (thisArg, body) {
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
+ function verb(n) { return function (v) { return step([n, v]); }; }
26
+ function step(op) {
27
+ if (f) throw new TypeError("Generator is already executing.");
28
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
+ if (y = 0, t) op = [op[0] & 2, t.value];
31
+ switch (op[0]) {
32
+ case 0: case 1: t = op; break;
33
+ case 4: _.label++; return { value: op[1], done: false };
34
+ case 5: _.label++; y = op[1]; op = [0]; continue;
35
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
+ default:
37
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
+ if (t[2]) _.ops.pop();
42
+ _.trys.pop(); continue;
43
+ }
44
+ op = body.call(thisArg, _);
45
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
+ }
48
+ };
49
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
50
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
51
+ var m = o[Symbol.asyncIterator], i;
52
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
53
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
54
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
55
+ };
56
+ var __importDefault = (this && this.__importDefault) || function (mod) {
57
+ return (mod && mod.__esModule) ? mod : { "default": mod };
58
+ };
59
+ Object.defineProperty(exports, "__esModule", { value: true });
60
+ exports.authLogin = void 0;
61
+ var prompts_1 = __importDefault(require("prompts"));
62
+ var utils_1 = require("@sasjs/utils");
63
+ var utils_2 = require("../../utils");
64
+ /**
65
+ * Reads a single line/value from stdin until EOF or newline, then trims
66
+ * trailing whitespace. Used by the `--password-stdin` flow so passwords can
67
+ * be piped without appearing in shell history or process argument lists.
68
+ */
69
+ var readPasswordFromStdin = function () { return __awaiter(void 0, void 0, void 0, function () {
70
+ var data, _a, _b, _c, chunk, e_1_1;
71
+ var _d, e_1, _e, _f;
72
+ return __generator(this, function (_g) {
73
+ switch (_g.label) {
74
+ case 0:
75
+ data = '';
76
+ _g.label = 1;
77
+ case 1:
78
+ _g.trys.push([1, 6, 7, 12]);
79
+ _a = true, _b = __asyncValues(process.stdin);
80
+ _g.label = 2;
81
+ case 2: return [4 /*yield*/, _b.next()];
82
+ case 3:
83
+ if (!(_c = _g.sent(), _d = _c.done, !_d)) return [3 /*break*/, 5];
84
+ _f = _c.value;
85
+ _a = false;
86
+ try {
87
+ chunk = _f;
88
+ data += chunk.toString();
89
+ }
90
+ finally {
91
+ _a = true;
92
+ }
93
+ _g.label = 4;
94
+ case 4: return [3 /*break*/, 2];
95
+ case 5: return [3 /*break*/, 12];
96
+ case 6:
97
+ e_1_1 = _g.sent();
98
+ e_1 = { error: e_1_1 };
99
+ return [3 /*break*/, 12];
100
+ case 7:
101
+ _g.trys.push([7, , 10, 11]);
102
+ if (!(!_a && !_d && (_e = _b.return))) return [3 /*break*/, 9];
103
+ return [4 /*yield*/, _e.call(_b)];
104
+ case 8:
105
+ _g.sent();
106
+ _g.label = 9;
107
+ case 9: return [3 /*break*/, 11];
108
+ case 10:
109
+ if (e_1) throw e_1.error;
110
+ return [7 /*endfinally*/];
111
+ case 11: return [7 /*endfinally*/];
112
+ case 12:
113
+ // Trim trailing newline/carriage-return only; leading/trailing spaces are
114
+ // intentionally preserved in case a password genuinely contains them.
115
+ return [2 /*return*/, data.replace(/[\r\n]+$/g, '')];
116
+ }
117
+ });
118
+ }); };
119
+ /**
120
+ * Authenticates against a SASVIYA target using a SAS username and password
121
+ * (OAuth2 resource owner password grant against the built-in, secret-less
122
+ * `sas.cli` client) and persists the resulting token pair. This enables all
123
+ * authenticated commands (`sasjs run`, `sasjs deploy`, etc.) on estates where
124
+ * no administrator-registered OAuth client/secret is available.
125
+ *
126
+ * Credentials are resolved in this order (highest precedence first):
127
+ *
128
+ * Username: SAS_USERNAME env var > interactive prompt (TTY only)
129
+ * Password: --password-stdin > SAS_PASSWORD env var > interactive prompt (TTY only)
130
+ *
131
+ * When `--password-stdin` is set, stdin is consumed for the password, so the
132
+ * username MUST come from the SAS_USERNAME env var (interactive prompting is
133
+ * not possible because stdin is already redirected).
134
+ *
135
+ * If no TTY is available and no env var / stdin flag supplies the credential,
136
+ * the function throws with a message pointing the caller at the env vars or
137
+ * `--password-stdin` flag — this makes `sasjs auth login` safe to call from
138
+ * CI pipelines and non-interactive agents.
139
+ *
140
+ * The password is used only to mint the tokens and is never stored. When the
141
+ * access token expires, re-run `sasjs auth login -t <target>`.
142
+ * @param {Target} target - the target to authenticate against.
143
+ * @param {boolean} insecure - when true, bypasses TLS certificate validation
144
+ * (for self-signed cert Viya servers). Mirrors the `--insecure` flag on
145
+ * `sasjs add cred`.
146
+ * @param {boolean} passwordStdin - when true, reads the password from stdin
147
+ * (like `docker login --password-stdin`) instead of prompting or reading
148
+ * the SAS_PASSWORD env var. The username must then come from SAS_USERNAME.
149
+ */
150
+ var authLogin = function (target, insecure, passwordStdin) {
151
+ if (insecure === void 0) { insecure = false; }
152
+ if (passwordStdin === void 0) { passwordStdin = false; }
153
+ return __awaiter(void 0, void 0, void 0, function () {
154
+ var isTty, envUser, envPass, user, hint, pass, promptedPass, _a, access_token, refresh_token, _b, id, name;
155
+ var _c, _d, _e;
156
+ return __generator(this, function (_f) {
157
+ switch (_f.label) {
158
+ case 0:
159
+ if (target.serverType !== utils_1.ServerType.SasViya) {
160
+ throw new Error("'sasjs auth login' is only supported for SASVIYA targets. " +
161
+ "Target '".concat(target.name, "' is of type '").concat(target.serverType, "'. ") +
162
+ "Use 'sasjs add cred -t ".concat(target.name, "' instead."));
163
+ }
164
+ if (!target.serverUrl) {
165
+ throw new Error("Target '".concat(target.name, "' does not have a serverUrl configured."));
166
+ }
167
+ if (insecure) {
168
+ target = new utils_1.Target(__assign(__assign({}, target.toJson(false)), { httpsAgentOptions: __assign(__assign({}, target.httpsAgentOptions), { allowInsecureRequests: true, rejectUnauthorized: false }) }));
169
+ (_c = process.logger) === null || _c === void 0 ? void 0 : _c.warn('Executing with insecure connection.');
170
+ }
171
+ isTty = !!process.stdin.isTTY;
172
+ envUser = process.env.SAS_USERNAME;
173
+ envPass = process.env.SAS_PASSWORD;
174
+ if (!envUser) return [3 /*break*/, 1];
175
+ user = envUser;
176
+ return [3 /*break*/, 4];
177
+ case 1:
178
+ if (!(isTty && !passwordStdin)) return [3 /*break*/, 3];
179
+ return [4 /*yield*/, (0, utils_1.getString)('Please enter your SAS username', function (v) { return !!v || 'Username is required.'; })];
180
+ case 2:
181
+ user = _f.sent();
182
+ return [3 /*break*/, 4];
183
+ case 3:
184
+ hint = passwordStdin
185
+ ? "When using --password-stdin, the username must be provided via the SAS_USERNAME environment variable (stdin is used for the password)."
186
+ : "No TTY is available for an interactive prompt. Set the SAS_USERNAME environment variable (and SAS_PASSWORD, or use --password-stdin).";
187
+ throw new Error("A SAS username is required but was not provided. ".concat(hint));
188
+ case 4:
189
+ if (!passwordStdin) return [3 /*break*/, 6];
190
+ return [4 /*yield*/, readPasswordFromStdin()];
191
+ case 5:
192
+ pass = _f.sent();
193
+ if (!pass) {
194
+ throw new Error("--password-stdin was specified but no password was read from stdin. " +
195
+ "Pipe the password, e.g. echo \"$SAS_PASSWORD\" | sasjs auth login --password-stdin -t ".concat(target.name, "."));
196
+ }
197
+ return [3 /*break*/, 10];
198
+ case 6:
199
+ if (!envPass) return [3 /*break*/, 7];
200
+ pass = envPass;
201
+ return [3 /*break*/, 10];
202
+ case 7:
203
+ if (!isTty) return [3 /*break*/, 9];
204
+ return [4 /*yield*/, (0, prompts_1.default)({
205
+ type: 'password',
206
+ name: 'pass',
207
+ message: 'Please enter your SAS password'
208
+ }, {
209
+ onCancel: function () {
210
+ throw new Error('Input cancelled.');
211
+ }
212
+ })];
213
+ case 8:
214
+ promptedPass = (_f.sent()).pass;
215
+ pass = promptedPass;
216
+ return [3 /*break*/, 10];
217
+ case 9: throw new Error("A SAS password is required but was not provided. " +
218
+ "Set the SAS_PASSWORD environment variable, or pipe the password and use --password-stdin " +
219
+ "(e.g. echo \"$SAS_PASSWORD\" | sasjs auth login --password-stdin -t ".concat(target.name, ")."));
220
+ case 10: return [4 /*yield*/, (0, utils_2.getTokensWithPasswordGrant)(target, user, pass)];
221
+ case 11:
222
+ _a = _f.sent(), access_token = _a.access_token, refresh_token = _a.refresh_token;
223
+ return [4 /*yield*/, (0, utils_2.fetchLoggedInUser)(target, access_token)];
224
+ case 12:
225
+ _b = _f.sent(), id = _b.id, name = _b.name;
226
+ return [4 /*yield*/, (0, utils_2.saveTokens)(target.name, access_token, refresh_token || '')];
227
+ case 13:
228
+ _f.sent();
229
+ (_d = process.logger) === null || _d === void 0 ? void 0 : _d.success("Logged in as ".concat(id || 'unknown user').concat(name ? " (".concat(name, ")") : '', " on ").concat(target.serverUrl, "."));
230
+ (_e = process.logger) === null || _e === void 0 ? void 0 : _e.info("The access token is valid for the duration configured on the server (12 hours by default). " +
231
+ "When it expires, re-run 'sasjs auth login -t ".concat(target.name, "'."));
232
+ return [2 /*return*/];
233
+ }
234
+ });
235
+ });
236
+ };
237
+ exports.authLogin = authLogin;
@@ -0,0 +1 @@
1
+ export {};