@p0security/cli 0.8.0 → 0.8.2

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.
Files changed (49) hide show
  1. package/dist/commands/__tests__/ssh.test.js +11 -10
  2. package/dist/commands/scp.d.ts +1 -1
  3. package/dist/commands/scp.js +11 -5
  4. package/dist/commands/shared/index.d.ts +4 -0
  5. package/dist/commands/shared/index.js +67 -0
  6. package/dist/commands/{shared.d.ts → shared/ssh.d.ts} +7 -14
  7. package/dist/commands/{shared.js → shared/ssh.js} +30 -64
  8. package/dist/commands/ssh.d.ts +1 -1
  9. package/dist/commands/ssh.js +10 -4
  10. package/dist/common/retry.d.ts +9 -0
  11. package/dist/common/retry.js +50 -0
  12. package/dist/common/subprocess.d.ts +10 -0
  13. package/dist/common/subprocess.js +72 -0
  14. package/dist/drivers/auth.d.ts +1 -1
  15. package/dist/drivers/auth.js +7 -3
  16. package/dist/plugins/aws/config.d.ts +1 -1
  17. package/dist/plugins/aws/idc/index.d.ts +16 -0
  18. package/dist/plugins/aws/idc/index.js +150 -0
  19. package/dist/plugins/aws/ssh.d.ts +13 -0
  20. package/dist/plugins/aws/ssh.js +24 -0
  21. package/dist/plugins/aws/types.d.ts +42 -16
  22. package/dist/plugins/google/ssh-key.d.ts +14 -0
  23. package/dist/plugins/google/ssh-key.js +80 -0
  24. package/dist/plugins/google/ssh.d.ts +15 -0
  25. package/dist/plugins/google/ssh.js +29 -0
  26. package/dist/plugins/google/types.d.ts +57 -0
  27. package/dist/plugins/google/types.js +2 -0
  28. package/dist/plugins/login.d.ts +3 -0
  29. package/dist/plugins/login.js +10 -0
  30. package/dist/plugins/oidc/login.d.ts +33 -2
  31. package/dist/plugins/oidc/login.js +100 -60
  32. package/dist/plugins/okta/aws.d.ts +1 -1
  33. package/dist/plugins/okta/aws.js +2 -2
  34. package/dist/plugins/okta/login.js +11 -1
  35. package/dist/plugins/ping/login.d.ts +2 -1
  36. package/dist/plugins/ping/login.js +11 -1
  37. package/dist/plugins/{aws/ssm → ssh}/index.d.ts +3 -2
  38. package/dist/plugins/ssh/index.js +311 -0
  39. package/dist/plugins/ssh/types.d.ts +4 -0
  40. package/dist/plugins/ssh-agent/index.js +5 -39
  41. package/dist/types/aws/oidc.d.ts +36 -0
  42. package/dist/types/aws/oidc.js +12 -0
  43. package/dist/types/oidc.d.ts +21 -0
  44. package/dist/types/request.d.ts +9 -11
  45. package/dist/types/request.js +0 -10
  46. package/dist/types/ssh.d.ts +27 -0
  47. package/dist/types/ssh.js +5 -0
  48. package/package.json +1 -1
  49. package/dist/plugins/aws/ssm/index.js +0 -213
@@ -21,49 +21,15 @@ This file is part of @p0security/cli
21
21
  You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
22
22
  **/
23
23
  const keys_1 = require("../../common/keys");
24
+ const subprocess_1 = require("../../common/subprocess");
24
25
  const stdio_1 = require("../../drivers/stdio");
25
- const node_child_process_1 = require("node:child_process");
26
- /** Spawns a subprocess with given command, args, and options.
27
- * May write content to its standard input.
28
- * Stdout and stderr of the subprocess is printed to stderr in debug mode.
29
- * The returned promise resolves or rejects with the exit code. */
30
- const asyncSpawn = ({ debug }, command, args, options, writeStdin) => __awaiter(void 0, void 0, void 0, function* () {
31
- return new Promise((resolve, reject) => {
32
- var _a;
33
- const child = (0, node_child_process_1.spawn)(command, args, options);
34
- if (writeStdin) {
35
- if (!child.stdin)
36
- return reject("Child process has no stdin");
37
- child.stdin.write(writeStdin);
38
- }
39
- child.stdout.on("data", (data) => {
40
- if (debug) {
41
- (0, stdio_1.print2)(data.toString("utf-8"));
42
- }
43
- });
44
- child.stderr.on("data", (data) => {
45
- if (debug) {
46
- (0, stdio_1.print2)(data.toString("utf-8"));
47
- }
48
- });
49
- child.on("exit", (code) => {
50
- if (code !== 0) {
51
- return reject(code);
52
- }
53
- resolve(code);
54
- });
55
- if (writeStdin) {
56
- (_a = child.stdin) === null || _a === void 0 ? void 0 : _a.end();
57
- }
58
- });
59
- });
60
26
  const isSshAgentRunning = (args) => __awaiter(void 0, void 0, void 0, function* () {
61
27
  try {
62
28
  if (args.debug)
63
29
  (0, stdio_1.print2)("Searching for active ssh-agents");
64
30
  // TODO: There's a possible edge-case but unlikely that ssh-agent has an invalid process or PID.
65
31
  // We can check to see if the active PID matches the current socket to mitigate this.
66
- yield asyncSpawn(args, `pgrep`, ["-x", "ssh-agent"]);
32
+ yield (0, subprocess_1.asyncSpawn)(args, `pgrep`, ["-x", "ssh-agent"]);
67
33
  if (args.debug)
68
34
  (0, stdio_1.print2)("At least one SSH agent is running");
69
35
  return true;
@@ -76,7 +42,7 @@ const isSshAgentRunning = (args) => __awaiter(void 0, void 0, void 0, function*
76
42
  });
77
43
  const isSshAgentAuthSocketSet = (args) => __awaiter(void 0, void 0, void 0, function* () {
78
44
  try {
79
- yield asyncSpawn(args, `sh`, ["-c", '[ -n "$SSH_AUTH_SOCK" ]']);
45
+ yield (0, subprocess_1.asyncSpawn)(args, `sh`, ["-c", '[ -n "$SSH_AUTH_SOCK" ]']);
80
46
  if (args.debug)
81
47
  (0, stdio_1.print2)(`SSH_AUTH_SOCK=${process.env.SSH_AUTH_SOCK}`);
82
48
  return true;
@@ -89,7 +55,7 @@ const isSshAgentAuthSocketSet = (args) => __awaiter(void 0, void 0, void 0, func
89
55
  });
90
56
  const privateKeyExists = (args) => __awaiter(void 0, void 0, void 0, function* () {
91
57
  try {
92
- yield asyncSpawn(args, `sh`, [
58
+ yield (0, subprocess_1.asyncSpawn)(args, `sh`, [
93
59
  "-c",
94
60
  `KEY_PATH="${keys_1.PRIVATE_KEY_PATH}" && KEY_FINGERPRINT=$(ssh-keygen -lf "$KEY_PATH" | awk '{print $2}') && ssh-add -l | grep -q "$KEY_FINGERPRINT" && exit 0 || exit 1`,
95
61
  ]);
@@ -106,7 +72,7 @@ const privateKeyExists = (args) => __awaiter(void 0, void 0, void 0, function* (
106
72
  exports.privateKeyExists = privateKeyExists;
107
73
  const addPrivateKey = (args) => __awaiter(void 0, void 0, void 0, function* () {
108
74
  try {
109
- yield asyncSpawn(args, `ssh-add`, [
75
+ yield (0, subprocess_1.asyncSpawn)(args, `ssh-add`, [
110
76
  keys_1.PRIVATE_KEY_PATH,
111
77
  ...(args.debug ? ["-v", "-v", "-v"] : ["-q"]),
112
78
  ]);
@@ -0,0 +1,36 @@
1
+ /** Copyright © 2024-present P0 Security
2
+
3
+ This file is part of @p0security/cli
4
+
5
+ @p0security/cli is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License.
6
+
7
+ @p0security/cli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
8
+
9
+ You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
10
+ **/
11
+ export declare type AWSClientInformation = {
12
+ authorizationEndpoint: string;
13
+ clientId: string;
14
+ clientIdIssuedAt: number;
15
+ clientSecret: string;
16
+ clientSecretExpiresAt: number;
17
+ tokenEndpoint: string;
18
+ };
19
+ /**
20
+ * AWS OIDC token response uses camelCase instead of snake_case
21
+ */
22
+ export declare type AWSTokenResponse = {
23
+ accessToken: string;
24
+ expiresIn: number;
25
+ idToken: string;
26
+ refreshToken: string;
27
+ tokenType: string;
28
+ };
29
+ export declare type AWSAuthorizeResponse = {
30
+ deviceCode: string;
31
+ expiresIn: number;
32
+ interval: number;
33
+ userCode: string;
34
+ verificationUri: string;
35
+ verificationUriComplete: string;
36
+ };
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ /** Copyright © 2024-present P0 Security
3
+
4
+ This file is part of @p0security/cli
5
+
6
+ @p0security/cli is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License.
7
+
8
+ @p0security/cli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
9
+
10
+ You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
11
+ **/
12
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,3 +1,4 @@
1
+ import { LoginPluginType } from "../plugins/login";
1
2
  /** Copyright © 2024-present P0 Security
2
3
 
3
4
  This file is part of @p0security/cli
@@ -39,3 +40,23 @@ export declare type TokenResponse = {
39
40
  export declare type TokenErrorResponse = {
40
41
  error: "access_denied" | "authorization_pending" | "bad grant type" | "expired_token" | "missing parameter" | "not found" | "slow_down";
41
42
  };
43
+ export declare type OidcLoginSteps<A> = {
44
+ providerType: LoginPluginType;
45
+ validateResponse: (response: Response) => Promise<Response>;
46
+ buildAuthorizeRequest: () => {
47
+ url: string;
48
+ init: RequestInit;
49
+ };
50
+ buildTokenRequest: (authorize: A) => {
51
+ url: string;
52
+ init: RequestInit;
53
+ };
54
+ processAuthzResponse: (authorize: A) => {
55
+ user_code: string;
56
+ verification_uri_complete: string;
57
+ };
58
+ processAuthzExpiry: (authorize: A) => {
59
+ expires_in: number;
60
+ interval: number;
61
+ };
62
+ };
@@ -8,22 +8,20 @@ This file is part of @p0security/cli
8
8
 
9
9
  You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
10
10
  **/
11
+ import { PluginSshRequest } from "./ssh";
11
12
  export declare const DONE_STATUSES: readonly ["DONE", "DONE_NOTIFIED"];
12
13
  export declare const DENIED_STATUSES: readonly ["DENIED", "DENIED_NOTIFIED"];
13
14
  export declare const ERROR_STATUSES: readonly ["ERRORED", "ERRORED", "ERRORED_NOTIFIED"];
14
- export declare type PluginRequest = {
15
- permission: object;
16
- generated?: object;
15
+ export declare type PermissionSpec<K extends string, P extends {
16
+ type: string;
17
+ }, G extends object | undefined = undefined> = {
18
+ type: K;
19
+ permission: P;
20
+ generated: G;
17
21
  };
18
- export declare type Request<P extends PluginRequest = {
19
- permission: object;
20
- }> = {
22
+ export declare type PluginRequest = PluginSshRequest;
23
+ export declare type Request<P extends PluginRequest> = P & {
21
24
  status: string;
22
- generatedRoles: {
23
- role: string;
24
- }[];
25
- generated: P["generated"];
26
- permission: P["permission"];
27
25
  principal: string;
28
26
  };
29
27
  export declare type RequestResponse<T> = {
@@ -1,16 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ERROR_STATUSES = exports.DENIED_STATUSES = exports.DONE_STATUSES = void 0;
4
- /** Copyright © 2024-present P0 Security
5
-
6
- This file is part of @p0security/cli
7
-
8
- @p0security/cli is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License.
9
-
10
- @p0security/cli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
11
-
12
- You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
13
- **/
14
4
  exports.DONE_STATUSES = ["DONE", "DONE_NOTIFIED"];
15
5
  exports.DENIED_STATUSES = ["DENIED", "DENIED_NOTIFIED"];
16
6
  exports.ERROR_STATUSES = [
@@ -0,0 +1,27 @@
1
+ /** Copyright © 2024-present P0 Security
2
+
3
+ This file is part of @p0security/cli
4
+
5
+ @p0security/cli is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 3 of the License.
6
+
7
+ @p0security/cli is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
8
+
9
+ You should have received a copy of the GNU General Public License along with @p0security/cli. If not, see <https://www.gnu.org/licenses/>.
10
+ **/
11
+ import { AwsSsh, AwsSshPermissionSpec, AwsSshRequest } from "../plugins/aws/types";
12
+ import { GcpSsh, GcpSshPermissionSpec, GcpSshRequest } from "../plugins/google/types";
13
+ import { Request } from "./request";
14
+ export declare type CliSshRequest = AwsSsh | GcpSsh;
15
+ export declare type PluginSshRequest = AwsSshPermissionSpec | GcpSshPermissionSpec;
16
+ export declare type CliPermissionSpec<P extends PluginSshRequest, C extends object | undefined> = P & {
17
+ cliLocalData: C;
18
+ };
19
+ export declare const SupportedSshProviders: readonly ["aws", "gcloud"];
20
+ export declare type SupportedSshProvider = (typeof SupportedSshProviders)[number];
21
+ export declare type SshProvider<PR extends PluginSshRequest = PluginSshRequest, O extends object | undefined = undefined, SR extends SshRequest = SshRequest> = {
22
+ requestToSsh: (request: CliPermissionSpec<PR, O>) => SR;
23
+ toCliRequest: (request: Request<PR>, options?: {
24
+ debug?: boolean;
25
+ }) => Promise<Request<CliSshRequest>>;
26
+ };
27
+ export declare type SshRequest = AwsSshRequest | GcpSshRequest;
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SupportedSshProviders = void 0;
4
+ // The prefix of installed SSH accounts in P0 is the provider name
5
+ exports.SupportedSshProviders = ["aws", "gcloud"];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@p0security/cli",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "Execute infra CLI commands with P0 grants",
5
5
  "main": "index.ts",
6
6
  "repository": {
@@ -1,213 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.sshOrScp = void 0;
13
- const keys_1 = require("../../../common/keys");
14
- const stdio_1 = require("../../../drivers/stdio");
15
- const aws_1 = require("../../okta/aws");
16
- const ssh_agent_1 = require("../../ssh-agent");
17
- const install_1 = require("./install");
18
- const node_child_process_1 = require("node:child_process");
19
- /** Matches the error message that AWS SSM print1 when access is not propagated */
20
- // Note that the resource will randomly be either the SSM document or the EC2 instance
21
- const UNPROVISIONED_ACCESS_MESSAGE = /An error occurred \(AccessDeniedException\) when calling the StartSession operation: User: arn:aws:sts::.*:assumed-role\/P0GrantsRole.* is not authorized to perform: ssm:StartSession on resource: arn:aws:.*:.*:.* because no identity-based policy allows the ssm:StartSession action/;
22
- /**
23
- * Matches the following error messages that AWS SSM print1 when ssh authorized
24
- * key access hasn't propagated to the instance yet.
25
- * - Connection closed by UNKNOWN port 65535
26
- * - scp: Connection closed
27
- * - kex_exchange_identification: Connection closed by remote host
28
- */
29
- const UNPROVISIONED_SCP_ACCESS_MESSAGE = /\bConnection closed\b.*\b(?:by UNKNOWN port \d+|by remote host)?/;
30
- /** Maximum amount of time after AWS SSM process starts to check for {@link UNPROVISIONED_ACCESS_MESSAGE}
31
- * in the process's stderr
32
- */
33
- const UNPROVISIONED_ACCESS_VALIDATION_WINDOW_MS = 5e3;
34
- /** Maximum number of attempts to start an SSM session
35
- *
36
- * Note that each attempt consumes ~ 1 s.
37
- */
38
- const MAX_SSM_RETRIES = 30;
39
- /** The name of the SessionManager port forwarding document. This document is managed by AWS. */
40
- const START_SSH_SESSION_DOCUMENT_NAME = "AWS-StartSSHSession";
41
- /** Checks if access has propagated through AWS to the SSM agent
42
- *
43
- * AWS takes about 8 minutes to fully resolve access after it is granted. During
44
- * this time, calls to `aws ssm start-session` will fail randomly with an
45
- * access denied exception.
46
- *
47
- * This function checks AWS to see if this exception is print1d to the SSM
48
- * error output within the first 5 seconds of startup. If it is, the returned
49
- * `isAccessPropagated()` function will return false. When this occurs, the
50
- * consumer of this function should retry the AWS SSM session.
51
- *
52
- * Note that this function requires interception of the AWS SSM stderr stream.
53
- * This works because AWS SSM wraps the session in a single-stream pty, so we
54
- * do not capture stderr emitted from the wrapped shell session.
55
- */
56
- const accessPropagationGuard = (child) => {
57
- let isEphemeralAccessDeniedException = false;
58
- const beforeStart = Date.now();
59
- child.stderr.on("data", (chunk) => {
60
- const chunkString = chunk.toString("utf-8");
61
- const match = chunkString.match(UNPROVISIONED_ACCESS_MESSAGE) ||
62
- chunkString.match(UNPROVISIONED_SCP_ACCESS_MESSAGE);
63
- if (match &&
64
- Date.now() <= beforeStart + UNPROVISIONED_ACCESS_VALIDATION_WINDOW_MS) {
65
- isEphemeralAccessDeniedException = true;
66
- return;
67
- }
68
- (0, stdio_1.print2)(chunkString);
69
- });
70
- return {
71
- isAccessPropagated: () => !isEphemeralAccessDeniedException,
72
- };
73
- };
74
- const createBaseSsmCommand = (args) => {
75
- return [
76
- "aws",
77
- "ssm",
78
- "start-session",
79
- "--region",
80
- args.region,
81
- "--target",
82
- args.instance,
83
- ];
84
- };
85
- const spawnChildProcess = (credential, command, args, stdio) => (0, node_child_process_1.spawn)(command, args, {
86
- env: Object.assign(Object.assign({}, process.env), credential),
87
- stdio,
88
- shell: false,
89
- });
90
- /** Starts an SSM session in the terminal by spawning `aws ssm` as a subprocess
91
- *
92
- * Requires `aws ssm` to be installed on the client machine.
93
- */
94
- function spawnSsmNode(options) {
95
- return __awaiter(this, void 0, void 0, function* () {
96
- return new Promise((resolve, reject) => {
97
- const child = spawnChildProcess(options.credential, options.command, options.args, options.stdio);
98
- const { isAccessPropagated } = accessPropagationGuard(child);
99
- const exitListener = child.on("exit", (code) => {
100
- var _a, _b;
101
- exitListener.unref();
102
- // In the case of ephemeral AccessDenied exceptions due to unpropagated
103
- // permissions, continually retry access until success
104
- if (!isAccessPropagated()) {
105
- const attemptsRemaining = (_a = options === null || options === void 0 ? void 0 : options.attemptsRemaining) !== null && _a !== void 0 ? _a : MAX_SSM_RETRIES;
106
- if (attemptsRemaining <= 0) {
107
- reject("Access did not propagate through AWS before max retry attempts were exceeded. Please contact support@p0.dev for assistance.");
108
- return;
109
- }
110
- spawnSsmNode(Object.assign(Object.assign({}, options), { attemptsRemaining: attemptsRemaining - 1 }))
111
- .then((code) => resolve(code))
112
- .catch(reject);
113
- return;
114
- }
115
- (_b = options.abortController) === null || _b === void 0 ? void 0 : _b.abort(code);
116
- (0, stdio_1.print2)(`SSH session terminated`);
117
- resolve(code);
118
- });
119
- });
120
- });
121
- }
122
- const createProxyCommands = (data, args, debug) => {
123
- const ssmCommand = [
124
- ...createBaseSsmCommand({
125
- region: data.region,
126
- instance: "%h",
127
- }),
128
- "--document-name",
129
- START_SSH_SESSION_DOCUMENT_NAME,
130
- "--parameters",
131
- '"portNumber=%p"',
132
- ];
133
- const commonArgs = [
134
- ...(debug ? ["-v"] : []),
135
- "-o",
136
- `ProxyCommand=${ssmCommand.join(" ")}`,
137
- ];
138
- if ("source" in args) {
139
- return {
140
- command: "scp",
141
- args: [
142
- ...commonArgs,
143
- // if a response is not received after three 5 minute attempts,
144
- // the connection will be closed.
145
- "-o",
146
- "ServerAliveCountMax=3",
147
- `-o`,
148
- "ServerAliveInterval=300",
149
- ...(args.recursive ? ["-r"] : []),
150
- args.source,
151
- args.destination,
152
- ],
153
- };
154
- }
155
- return {
156
- command: "ssh",
157
- args: [
158
- ...commonArgs,
159
- ...(args.A ? ["-A"] : []),
160
- ...(args.L ? ["-L", args.L] : []),
161
- ...(args.N ? ["-N"] : []),
162
- `${data.linuxUserName}@${data.id}`,
163
- ...(args.command ? [args.command] : []),
164
- ...args.arguments.map((argument) =>
165
- // escape all double quotes (") in commands such as `p0 ssh <instance>> echo 'hello; "world"'` because we
166
- // need to encapsulate command arguments in double quotes as we pass them along to the remote shell
167
- `"${String(argument).replace(/"/g, '\\"')}"`),
168
- ],
169
- };
170
- };
171
- /** Converts arguments for manual execution - arguments may have to be quoted or certain characters escaped when executing the commands from a shell */
172
- const transformForShell = (args) => {
173
- return args.map((arg) => {
174
- // The ProxyCommand option must be surrounded by single quotes
175
- if (arg.startsWith("ProxyCommand=")) {
176
- const [name, ...value] = arg.split("="); // contains the '=' character in the parameters option: ProxyCommand=aws ssm start-session ... --parameters "portNumber=%p"
177
- return `${name}='${value.join("=")}'`;
178
- }
179
- return arg;
180
- });
181
- };
182
- const sshOrScp = (authn, data, cmdArgs, privateKey) => __awaiter(void 0, void 0, void 0, function* () {
183
- if (!(yield (0, install_1.ensureSsmInstall)())) {
184
- throw "Please try again after installing the required AWS utilities";
185
- }
186
- if (!privateKey) {
187
- throw "Failed to load a private key for this request. Please contact support@p0.dev for assistance.";
188
- }
189
- const credential = yield (0, aws_1.assumeRoleWithOktaSaml)(authn, {
190
- account: data.accountId,
191
- role: data.role,
192
- });
193
- return (0, ssh_agent_1.withSshAgent)(cmdArgs, () => __awaiter(void 0, void 0, void 0, function* () {
194
- const { command, args } = createProxyCommands(data, cmdArgs, cmdArgs.debug);
195
- if (cmdArgs.debug) {
196
- const reproCommands = [
197
- `eval $(ssh-agent)`,
198
- `ssh-add "${keys_1.PRIVATE_KEY_PATH}"`,
199
- `eval $(p0 aws role assume ${data.role} --account ${data.accountId})`,
200
- `${command} ${transformForShell(args).join(" ")}`,
201
- ];
202
- (0, stdio_1.print2)(`Execute the following commands to create a similar SSH/SCP session:\n*** COMMANDS BEGIN ***\n${reproCommands.join("\n")}\n*** COMMANDS END ***"\n`);
203
- }
204
- return spawnSsmNode({
205
- credential,
206
- abortController: new AbortController(),
207
- command,
208
- args,
209
- stdio: ["inherit", "inherit", "pipe"],
210
- });
211
- }));
212
- });
213
- exports.sshOrScp = sshOrScp;