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

const fs = require("fs");
const cp = require("child_process");

async function main(args, sshOriginalCommand) {
  const [_, __, username] = args;

  if (username == null || username.trim() === "") {
    console.log(
      `Hi ${process.env.USER}!\nLooks like we could not find your username.`
    );
    process.exit(128);
  }

  if (sshOriginalCommand == null) {
    console.log(
      `Hi ${process.env.USER}!\nYou've successfully authenticated, but I do not provide interactive shell access.`
    );
    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 }
        : 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\n`,
    { encoding: "utf8" }
  );

  // console.log(
  //   `username: ${username}\npublicKey: ${publicKey}\ncommand: ${command}\nrepoSlug: ${repoSlug}\n`
  // );

  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\n`,
      { encoding: "utf8" }
    );
    console.log("Forbidden access.");
    process.exit(128);
    return;
  }

  const json = await res.json();

  console.log(JSON.stringify(json));

  fs.appendFileSync(
    "/home/git/ssh_commands.log",
    `${JSON.stringify(json, null, 2)}\n-----------\n\n`,
    { encoding: "utf8" }
  );

  if (json.success === false) {
    console.log("Forbidden access.");
    process.exit(128);
  }

  // success!
  process.exit(0);
}

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