diff --git a/cleanup.js b/cleanup.js index 7c7b6a8..62ecc37 100644 --- a/cleanup.js +++ b/cleanup.js @@ -15,30 +15,30 @@ function killSshAgent() { } } -function restoreGitConfig(maxTries = 3) { +async function restoreGitConfig(maxTries = 3) { try { console.log("Restoring git config"); - const result = alterGitConfigWithRetry(() => { + const result = await alterGitConfigWithRetry(() => { return execSync( `${gitCmd} config --global --get-regexp ".git@${keyFilePrefix}."`, ); - }); + }, maxTries); const sections = result .toString() .split(os.EOL) .map((section) => { return section.substring(0, section.indexOf(".insteadof")); }); - new Set(sections).forEach((section) => { + for (const section of new Set(sections)) { if (section !== "") { console.log(`Removing git config section ${section}`); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return execSync( `${gitCmd} config --global --remove-section ${section}`, ); - }); + }, maxTries); } - }); + } } catch (error) { console.log(error.message); console.log("Error restoring git config, proceeding anyway"); @@ -90,7 +90,9 @@ function removeHostEntries() { } } -killSshAgent(); -restoreGitConfig(); -removeCustomSshKeys(); -removeHostEntries(); +(async () => { + killSshAgent(); + await restoreGitConfig(); + removeCustomSshKeys(); + removeHostEntries(); +})(); diff --git a/dist/cleanup.js b/dist/cleanup.js index fb798db..7d1484e 100644 --- a/dist/cleanup.js +++ b/dist/cleanup.js @@ -3457,7 +3457,7 @@ const wait = (msec) => setTimeout(resolve, msec); }); -function alterGitConfigWithRetry(alterFunction, maxTries = 3) { +async function alterGitConfigWithRetry(alterFunction, maxTries = 3) { let tries = 0; while (tries < maxTries) { try { @@ -3471,11 +3471,9 @@ function alterGitConfigWithRetry(alterFunction, maxTries = 3) { if (tries === maxTries) { throw error; } - (async () => { - const delay = Math.floor(Math.random() * 2000); - core.debug(`Retrying in ${delay}ms...`); - await wait(delay); - })(); + const delay = 2000 + Math.floor(Math.random() * 2000); + core.debug(`Retrying in ${delay}ms...`); + await wait(delay); } } } @@ -3675,30 +3673,30 @@ function killSshAgent() { } } -function restoreGitConfig(maxTries = 3) { +async function restoreGitConfig(maxTries = 3) { try { console.log("Restoring git config"); - const result = alterGitConfigWithRetry(() => { + const result = await alterGitConfigWithRetry(() => { return execSync( `${gitCmd} config --global --get-regexp ".git@${keyFilePrefix}."`, ); - }); + }, maxTries); const sections = result .toString() .split(os.EOL) .map((section) => { return section.substring(0, section.indexOf(".insteadof")); }); - new Set(sections).forEach((section) => { + for (const section of new Set(sections)) { if (section !== "") { console.log(`Removing git config section ${section}`); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return execSync( `${gitCmd} config --global --remove-section ${section}`, ); - }); + }, maxTries); } - }); + } } catch (error) { console.log(error.message); console.log("Error restoring git config, proceeding anyway"); @@ -3750,10 +3748,12 @@ function removeHostEntries() { } } -killSshAgent(); -restoreGitConfig(); -removeCustomSshKeys(); -removeHostEntries(); +(async () => { + killSshAgent(); + await restoreGitConfig(); + removeCustomSshKeys(); + removeHostEntries(); +})(); module.exports = __webpack_exports__; /******/ })() diff --git a/dist/index.js b/dist/index.js index e569738..41db209 100644 --- a/dist/index.js +++ b/dist/index.js @@ -3457,7 +3457,7 @@ const wait = (msec) => setTimeout(resolve, msec); }); -function alterGitConfigWithRetry(alterFunction, maxTries = 3) { +async function alterGitConfigWithRetry(alterFunction, maxTries = 3) { let tries = 0; while (tries < maxTries) { try { @@ -3471,11 +3471,9 @@ function alterGitConfigWithRetry(alterFunction, maxTries = 3) { if (tries === maxTries) { throw error; } - (async () => { - const delay = Math.floor(Math.random() * 2000); - core.debug(`Retrying in ${delay}ms...`); - await wait(delay); - })(); + const delay = 2000 + Math.floor(Math.random() * 2000); + core.debug(`Retrying in ${delay}ms...`); + await wait(delay); } } } @@ -3674,89 +3672,94 @@ const { homePath, sshAgentCmd, sshAddCmd, gitCmd } = __nccwpck_require__(644); const { keyFilePrefix } = __nccwpck_require__(334); const { alterGitConfigWithRetry } = __nccwpck_require__(561); -try { - const privateKey = core.getInput("ssh-private-key"); - const logPublicKey = core.getBooleanInput("log-public-key", { - default: true, - }); - const fetchGithubHostKeys = core.getBooleanInput("fetch-github-host-keys", { - default: false, - }); +(async () => { + try { + const privateKey = core.getInput("ssh-private-key"); + const logPublicKey = core.getBooleanInput("log-public-key", { + default: true, + }); + const fetchGithubHostKeys = core.getBooleanInput("fetch-github-host-keys", { + default: false, + }); - if (!privateKey) { - core.setFailed( - "The ssh-private-key argument is empty. Maybe the secret has not been configured, or you are using a wrong secret name in your workflow file.", - ); + if (!privateKey) { + core.setFailed( + "The ssh-private-key argument is empty. Maybe the secret has not been configured, or you are using a wrong secret name in your workflow file.", + ); - process.exit(1); - } + process.exit(1); + } - const homeSsh = `${homePath}/.ssh`; - fs.mkdirSync(homeSsh, { recursive: true }); + const homeSsh = `${homePath}/.ssh`; + fs.mkdirSync(homeSsh, { recursive: true }); - if (fetchGithubHostKeys) { - console.log("Fetching GitHub host keys"); - try { - // Use curl which is available on all GitHub Actions runners (Linux, macOS, Windows) - const curlCmd = - process.platform === "win32" - ? "curl.exe --silent https://api.github.com/meta" - : "curl --silent https://api.github.com/meta"; - - const metaJson = child_process.execSync(curlCmd, { encoding: "utf8" }); - - const meta = JSON.parse(metaJson); - const knownHostsFile = `${homeSsh}/known_hosts`; - const hostKeyLines = `${meta.ssh_keys.map((key) => `github.com ${key}`).join("\n")}\n`; - fs.appendFileSync(knownHostsFile, hostKeyLines); - console.log( - `Added ${meta.ssh_keys.length} GitHub host key(s) to known_hosts`, - ); - } catch (error) { - console.warn(`Failed to fetch GitHub host keys: ${error.message}`); + if (fetchGithubHostKeys) { + console.log("Fetching GitHub host keys"); + try { + // Use curl which is available on all GitHub Actions runners (Linux, macOS, Windows) + const curlCmd = + process.platform === "win32" + ? "curl.exe --silent https://api.github.com/meta" + : "curl --silent https://api.github.com/meta"; + + const metaJson = child_process.execSync(curlCmd, { encoding: "utf8" }); + + const meta = JSON.parse(metaJson); + const knownHostsFile = `${homeSsh}/known_hosts`; + const hostKeyLines = `${meta.ssh_keys.map((key) => `github.com ${key}`).join("\n")}\n`; + fs.appendFileSync(knownHostsFile, hostKeyLines); + console.log( + `Added ${meta.ssh_keys.length} GitHub host key(s) to known_hosts`, + ); + } catch (error) { + console.warn(`Failed to fetch GitHub host keys: ${error.message}`); + } } - } - console.log("Starting ssh-agent"); + console.log("Starting ssh-agent"); - const authSock = core.getInput("ssh-auth-sock"); - const sshAgentArgs = authSock && authSock.length > 0 ? ["-a", authSock] : []; + const authSock = core.getInput("ssh-auth-sock"); + const sshAgentArgs = + authSock && authSock.length > 0 ? ["-a", authSock] : []; - // Extract auth socket path and agent pid and set them as job variables - child_process - .execFileSync(sshAgentCmd, sshAgentArgs) - .toString() - .split("\n") - .forEach((line) => { - const matches = /^(SSH_AUTH_SOCK|SSH_AGENT_PID)=(.*); export \1/.exec( - line, - ); + // Extract auth socket path and agent pid and set them as job variables + child_process + .execFileSync(sshAgentCmd, sshAgentArgs) + .toString() + .split("\n") + .forEach((line) => { + const matches = /^(SSH_AUTH_SOCK|SSH_AGENT_PID)=(.*); export \1/.exec( + line, + ); - if (matches && matches.length > 0) { - // This will also set process.env accordingly, so changes take effect for this script - core.exportVariable(matches[1], matches[2]); - console.log(`${matches[1]}=${matches[2]}`); - } - }); + if (matches && matches.length > 0) { + // This will also set process.env accordingly, so changes take effect for this script + core.exportVariable(matches[1], matches[2]); + console.log(`${matches[1]}=${matches[2]}`); + } + }); - console.log("Adding private key(s) to agent"); + console.log("Adding private key(s) to agent"); - privateKey.split(/(?=-----BEGIN)/).forEach((key) => { - child_process.execFileSync(sshAddCmd, ["-"], { input: `${key.trim()}\n` }); - }); + privateKey.split(/(?=-----BEGIN)/).forEach((key) => { + child_process.execFileSync(sshAddCmd, ["-"], { + input: `${key.trim()}\n`, + }); + }); + + console.log("Key(s) added:"); - console.log("Key(s) added:"); + child_process.execFileSync(sshAddCmd, ["-l"], { stdio: "inherit" }); - child_process.execFileSync(sshAddCmd, ["-l"], { stdio: "inherit" }); + console.log("Configuring deployment key(s)"); - console.log("Configuring deployment key(s)"); + const publicKeys = child_process + .execFileSync(sshAddCmd, ["-L"]) + .toString() + .trim() + .split(/\r?\n/); - child_process - .execFileSync(sshAddCmd, ["-L"]) - .toString() - .trim() - .split(/\r?\n/) - .forEach((key) => { + for (const key of publicKeys) { const parts = key.match(/\bgithub\.com[:/]([_.a-z0-9-]+\/[_.a-z0-9-]+)/i); if (!parts) { @@ -3765,7 +3768,7 @@ try { `Comment for (public) key '${key}' does not match GitHub URL pattern. Not treating it as a GitHub deploy key.`, ); } - return; + continue; } const sha256 = crypto.createHash("sha256").update(key).digest("hex"); @@ -3774,17 +3777,17 @@ try { fs.writeFileSync(`${homeSsh}/${keyFile}`, `${key}\n`, { mode: "600" }); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return child_process.execSync( `${gitCmd} config --global --replace-all url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "https://github.com/${ownerAndRepo}"`, ); }); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return child_process.execSync( `${gitCmd} config --global --add url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "git@github.com:${ownerAndRepo}"`, ); }); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return child_process.execSync( `${gitCmd} config --global --add url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "ssh://git@github.com/${ownerAndRepo}"`, ); @@ -3797,17 +3800,18 @@ try { console.log( `Added deploy-key mapping: Use identity '${homeSsh}/${keyFile}' for GitHub repository ${ownerAndRepo}`, ); - }); -} catch (error) { - if (error.code === "ENOENT") { - console.log( - `The '${error.path}' executable could not be found. Please make sure it is on your PATH and/or the necessary packages are installed.`, - ); - console.log(`PATH is set to: ${process.env.PATH}`); - } + } + } catch (error) { + if (error.code === "ENOENT") { + console.log( + `The '${error.path}' executable could not be found. Please make sure it is on your PATH and/or the necessary packages are installed.`, + ); + console.log(`PATH is set to: ${process.env.PATH}`); + } - core.setFailed(error.message); -} + core.setFailed(error.message); + } +})(); module.exports = __webpack_exports__; /******/ })() diff --git a/index.js b/index.js index 9d421ed..648008c 100644 --- a/index.js +++ b/index.js @@ -6,89 +6,94 @@ const { homePath, sshAgentCmd, sshAddCmd, gitCmd } = require("./paths.js"); const { keyFilePrefix } = require("./consts.js"); const { alterGitConfigWithRetry } = require("./utils.js"); -try { - const privateKey = core.getInput("ssh-private-key"); - const logPublicKey = core.getBooleanInput("log-public-key", { - default: true, - }); - const fetchGithubHostKeys = core.getBooleanInput("fetch-github-host-keys", { - default: false, - }); - - if (!privateKey) { - core.setFailed( - "The ssh-private-key argument is empty. Maybe the secret has not been configured, or you are using a wrong secret name in your workflow file.", - ); - - process.exit(1); - } - - const homeSsh = `${homePath}/.ssh`; - fs.mkdirSync(homeSsh, { recursive: true }); +(async () => { + try { + const privateKey = core.getInput("ssh-private-key"); + const logPublicKey = core.getBooleanInput("log-public-key", { + default: true, + }); + const fetchGithubHostKeys = core.getBooleanInput("fetch-github-host-keys", { + default: false, + }); - if (fetchGithubHostKeys) { - console.log("Fetching GitHub host keys"); - try { - // Use curl which is available on all GitHub Actions runners (Linux, macOS, Windows) - const curlCmd = - process.platform === "win32" - ? "curl.exe --silent https://api.github.com/meta" - : "curl --silent https://api.github.com/meta"; + if (!privateKey) { + core.setFailed( + "The ssh-private-key argument is empty. Maybe the secret has not been configured, or you are using a wrong secret name in your workflow file.", + ); - const metaJson = child_process.execSync(curlCmd, { encoding: "utf8" }); + process.exit(1); + } - const meta = JSON.parse(metaJson); - const knownHostsFile = `${homeSsh}/known_hosts`; - const hostKeyLines = `${meta.ssh_keys.map((key) => `github.com ${key}`).join("\n")}\n`; - fs.appendFileSync(knownHostsFile, hostKeyLines); - console.log( - `Added ${meta.ssh_keys.length} GitHub host key(s) to known_hosts`, - ); - } catch (error) { - console.warn(`Failed to fetch GitHub host keys: ${error.message}`); + const homeSsh = `${homePath}/.ssh`; + fs.mkdirSync(homeSsh, { recursive: true }); + + if (fetchGithubHostKeys) { + console.log("Fetching GitHub host keys"); + try { + // Use curl which is available on all GitHub Actions runners (Linux, macOS, Windows) + const curlCmd = + process.platform === "win32" + ? "curl.exe --silent https://api.github.com/meta" + : "curl --silent https://api.github.com/meta"; + + const metaJson = child_process.execSync(curlCmd, { encoding: "utf8" }); + + const meta = JSON.parse(metaJson); + const knownHostsFile = `${homeSsh}/known_hosts`; + const hostKeyLines = `${meta.ssh_keys.map((key) => `github.com ${key}`).join("\n")}\n`; + fs.appendFileSync(knownHostsFile, hostKeyLines); + console.log( + `Added ${meta.ssh_keys.length} GitHub host key(s) to known_hosts`, + ); + } catch (error) { + console.warn(`Failed to fetch GitHub host keys: ${error.message}`); + } } - } - console.log("Starting ssh-agent"); + console.log("Starting ssh-agent"); - const authSock = core.getInput("ssh-auth-sock"); - const sshAgentArgs = authSock && authSock.length > 0 ? ["-a", authSock] : []; + const authSock = core.getInput("ssh-auth-sock"); + const sshAgentArgs = + authSock && authSock.length > 0 ? ["-a", authSock] : []; - // Extract auth socket path and agent pid and set them as job variables - child_process - .execFileSync(sshAgentCmd, sshAgentArgs) - .toString() - .split("\n") - .forEach((line) => { - const matches = /^(SSH_AUTH_SOCK|SSH_AGENT_PID)=(.*); export \1/.exec( - line, - ); + // Extract auth socket path and agent pid and set them as job variables + child_process + .execFileSync(sshAgentCmd, sshAgentArgs) + .toString() + .split("\n") + .forEach((line) => { + const matches = /^(SSH_AUTH_SOCK|SSH_AGENT_PID)=(.*); export \1/.exec( + line, + ); - if (matches && matches.length > 0) { - // This will also set process.env accordingly, so changes take effect for this script - core.exportVariable(matches[1], matches[2]); - console.log(`${matches[1]}=${matches[2]}`); - } - }); + if (matches && matches.length > 0) { + // This will also set process.env accordingly, so changes take effect for this script + core.exportVariable(matches[1], matches[2]); + console.log(`${matches[1]}=${matches[2]}`); + } + }); - console.log("Adding private key(s) to agent"); + console.log("Adding private key(s) to agent"); - privateKey.split(/(?=-----BEGIN)/).forEach((key) => { - child_process.execFileSync(sshAddCmd, ["-"], { input: `${key.trim()}\n` }); - }); + privateKey.split(/(?=-----BEGIN)/).forEach((key) => { + child_process.execFileSync(sshAddCmd, ["-"], { + input: `${key.trim()}\n`, + }); + }); + + console.log("Key(s) added:"); - console.log("Key(s) added:"); + child_process.execFileSync(sshAddCmd, ["-l"], { stdio: "inherit" }); - child_process.execFileSync(sshAddCmd, ["-l"], { stdio: "inherit" }); + console.log("Configuring deployment key(s)"); - console.log("Configuring deployment key(s)"); + const publicKeys = child_process + .execFileSync(sshAddCmd, ["-L"]) + .toString() + .trim() + .split(/\r?\n/); - child_process - .execFileSync(sshAddCmd, ["-L"]) - .toString() - .trim() - .split(/\r?\n/) - .forEach((key) => { + for (const key of publicKeys) { const parts = key.match(/\bgithub\.com[:/]([_.a-z0-9-]+\/[_.a-z0-9-]+)/i); if (!parts) { @@ -97,7 +102,7 @@ try { `Comment for (public) key '${key}' does not match GitHub URL pattern. Not treating it as a GitHub deploy key.`, ); } - return; + continue; } const sha256 = crypto.createHash("sha256").update(key).digest("hex"); @@ -106,17 +111,17 @@ try { fs.writeFileSync(`${homeSsh}/${keyFile}`, `${key}\n`, { mode: "600" }); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return child_process.execSync( `${gitCmd} config --global --replace-all url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "https://github.com/${ownerAndRepo}"`, ); }); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return child_process.execSync( `${gitCmd} config --global --add url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "git@github.com:${ownerAndRepo}"`, ); }); - alterGitConfigWithRetry(() => { + await alterGitConfigWithRetry(() => { return child_process.execSync( `${gitCmd} config --global --add url."git@${keyFile}.github.com:${ownerAndRepo}".insteadOf "ssh://git@github.com/${ownerAndRepo}"`, ); @@ -129,14 +134,15 @@ try { console.log( `Added deploy-key mapping: Use identity '${homeSsh}/${keyFile}' for GitHub repository ${ownerAndRepo}`, ); - }); -} catch (error) { - if (error.code === "ENOENT") { - console.log( - `The '${error.path}' executable could not be found. Please make sure it is on your PATH and/or the necessary packages are installed.`, - ); - console.log(`PATH is set to: ${process.env.PATH}`); - } + } + } catch (error) { + if (error.code === "ENOENT") { + console.log( + `The '${error.path}' executable could not be found. Please make sure it is on your PATH and/or the necessary packages are installed.`, + ); + console.log(`PATH is set to: ${process.env.PATH}`); + } - core.setFailed(error.message); -} + core.setFailed(error.message); + } +})(); diff --git a/utils.js b/utils.js index 2d4081e..384215b 100644 --- a/utils.js +++ b/utils.js @@ -8,7 +8,7 @@ const wait = (msec) => setTimeout(resolve, msec); }); -function alterGitConfigWithRetry(alterFunction, maxTries = 3) { +async function alterGitConfigWithRetry(alterFunction, maxTries = 3) { let tries = 0; while (tries < maxTries) { try { @@ -22,11 +22,9 @@ function alterGitConfigWithRetry(alterFunction, maxTries = 3) { if (tries === maxTries) { throw error; } - (async () => { - const delay = Math.floor(Math.random() * 2000); - core.debug(`Retrying in ${delay}ms...`); - await wait(delay); - })(); + const delay = 2000 + Math.floor(Math.random() * 2000); + core.debug(`Retrying in ${delay}ms...`); + await wait(delay); } } }