.js
JavaScript
(text/javascript)
#!/usr/bin/node

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) {
        // Log error details
        fs.appendFileSync(
          "/home/git/ssh_commands.log",
          `${res.statusCode}: ${res.statusMessage} - ${responseBody}\n-----------\n`,
          { encoding: "utf8" },
        );
        process.exit(128);
      } else {
        // Parse JSON response
        try {
          json = JSON.parse(responseBody);
          // Do something with json if needed
        } catch (e) {
          // handle JSON parse error if necessary
        }
      }
    });
  });

  req.on("error", (e) => {
    // handle request error
    fs.appendFileSync(
      "/home/git/ssh_commands.log",
      `Request error: ${e.message}\n-----------\n`,
      { encoding: "utf8" },
    );
    process.exit(128);
  });

  // Write data to request body
  req.write(data);
  req.end();

  // 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);
  }

  // success!
  console.log(JSON.stringify(json));
  process.exit(0);
}

main(process.argv, process.env.SSH_ORIGINAL_COMMAND);