const fs = require("fs");
async function main(args, sshOriginalCommand) {
const [_, __, username] = args;
if (username == null || username.trim() === "") {
process.exit(128);
}
if (sshOriginalCommand == null) {
process.exit(128);
}
const authorizedKeysBuffer = fs.readFileSync(
"/home/git/.ssh/authorized_keys",
{ encoding: "utf8" }
);
const authKeys = authorizedKeysBuffer
.split("\n")
.map((line) =>
line.startsWith("#")
? { type: "comment", text: line }
: line.trim() !== ""
? { type: "key", text: line.trim() }
: null
)
.filter((x) => x != null && x.type === "key");
const pk = authKeys.find((key) =>
key.text.includes(`command="ssh_command ${username}"`)
)?.text;
const sshRsaIndex = pk.indexOf("ssh-rsa");
const publicKey = pk.substring(sshRsaIndex);
const [command, repoSlug] = sshOriginalCommand
.split(" ")
.map((part) => part.replace(/\'/g, "").trim());
fs.appendFileSync(
"/home/git/ssh_commands.log",
`username: ${username}\npublicKey: ${publicKey}\ncommand: ${command}\nrepoSlug: ${repoSlug}\n-----------\n`,
{ encoding: "utf8" }
);
const res = await fetch(`http://localhost:1337/_ssh/auth`, {
method: "POST",
body: JSON.stringify({
command,
repoSlug,
username,
publicKey,
}),
});
if (res.ok === false) {
const text = await res.text();
fs.appendFileSync(
"/home/git/ssh_commands.log",
`${res.status}: ${res.statusText} - ${text}\n-----------\n`,
{ encoding: "utf8" }
);
process.exit(128);
}
const json = await res.json();
fs.appendFileSync(
"/home/git/ssh_commands.log",
`${res.status}: ${res.statusText} - ${JSON.stringify(json)}\n-----------\n`,
{ encoding: "utf8" }
);
if (json.success === false) {
process.exit(128);
}
console.log(JSON.stringify(json));
process.exit(0);
}
main(process.argv, process.env.SSH_ORIGINAL_COMMAND);