const http = require("http");
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");
console.log("authkeys:", authKeys);
console.log("username", username);
let pk = authKeys.find(
(key) =>
key.text.includes(`command="ssh_command ${username}"`) ||
key.text.includes(`command="/usr/bin/ssh_command ${username}"`),
);
if (pk) {
pk = pk.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 data = JSON.stringify({
command,
repoSlug,
username,
publicKey,
});
const options = {
hostname: "localhost",
port: 1337,
path: "/_ssh/auth",
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.byteLength(data),
},
};
let json = {};
const req = http.request(options, (res) => {
let chunks = [];
res.on("data", (chunk) => {
chunks.push(chunk);
});
res.on("end", () => {
const responseBody = Buffer.concat(chunks).toString();
if (res.statusCode >= 400) {
fs.appendFileSync(
"/home/git/ssh_commands.log",
`${res.statusCode}: ${res.statusMessage} - ${responseBody}\n-----------\n`,
{ encoding: "utf8" },
);
process.exit(128);
} else {
try {
json = JSON.parse(responseBody);
} catch (e) {
}
}
});
});
req.on("error", (e) => {
fs.appendFileSync(
"/home/git/ssh_commands.log",
`Request error: ${e.message}\n-----------\n`,
{ encoding: "utf8" },
);
process.exit(128);
});
req.write(data);
req.end();
if (json.success === false) {
process.exit(128);
}
console.log(JSON.stringify(json));
process.exit(0);
}
main(process.argv, process.env.SSH_ORIGINAL_COMMAND);