Skip to content

An open-source, faster Devin alternative

TypeScript
4.9 KB
Raw Blame
#!/usr/bin/env node
// Git credential helper for GitHub on a slack-presence host (work 045).
//
// git → this helper → the host agent's token socket → the gateway, which mints a
// GitHub App installation token (one hour). The host caches tokens in memory;
// nothing is written to disk. Configure once, globally, for the runner user:
//
//   git config --global credential.https://github.com.helper ''        # drop other helpers
//   git config --global --add credential.https://github.com.helper /opt/slack-presence/bin/git-credential-slack-presence
//   git config --global credential.https://github.com.useHttpPath true # send owner/name, so tokens can be narrowed
//
// Socket protocol: connect to $SP_TOKEN_SOCKET, the session's runner's own socket
// (work 080: the host knows the session from which socket is asked), or else
// $SP_RUN/token.sock (default /run/slack-presence), which names no session;
// send one JSON line {"repos"?: ["owner/name"]}, read one JSON line
// {"token", "expiresAt"} or {"error"}.
//
// Also used by bin/gh: `git-credential-slack-presence token` prints the bare token.
// And by bin/opencomputer (work 067): `git-credential-slack-presence opencomputer`
// asks with {"kind": "opencomputer"} and prints a one-hour OpenComputer key and its
// API URL, one per line.
//
// Automations (work 067): after it deploys an automation, the computer pushes
// its code to the organization's automations repository on Code.Storage, one
// folder per automation, `https://<org>.code.storage/automations-<account>.git`.
// `git-credential-slack-presence automation-remote` prints that remote (no
// credentials; the first ask creates the repository), and `get` for a
// *.code.storage host answers with a one-hour push credential for it
// ({"kind": "automation-repo"}). Configured like GitHub:
//
//   git config --global credential.https://*.code.storage.helper .../git-credential-slack-presence
//   git config --global credential.https://*.code.storage.useHttpPath true
//
// Only `get` answers; `store` and `erase` are no-ops. On any failure it prints
// nothing, so git falls through (and fails without prompting on a host).

(async () => {
  const net = await import('node:net');
  const path = await import('node:path');
  const op = process.argv[2];
  if (op !== 'get' && op !== 'token' && op !== 'opencomputer' && op !== 'automation-remote') return;

  const input = op === 'get' ? await new Promise((res) => {
    let s = '';
    process.stdin.setEncoding('utf8').on('data', (d) => (s += d)).on('end', () => res(s));
  }) : 'protocol=https\nhost=github.com\n';
  const attrs = Object.fromEntries(String(input).split('\n').filter((l) => l.includes('=')).map((l) => [l.slice(0, l.indexOf('=')), l.slice(l.indexOf('=') + 1)]));
  if (attrs.protocol && attrs.protocol !== 'https') return;
  const codeStorage = op === 'get' && /^[a-z0-9][a-z0-9-]*\.code\.storage$/.test(attrs.host || '');
  if (!codeStorage && op === 'get' && attrs.host !== 'github.com') return;

  let req;
  if (op === 'automation-remote' || codeStorage) {
    if (codeStorage && !/^automations-[A-Za-z0-9_-]+\.git$/.test(attrs.path || '')) return;
    req = { kind: 'automation-repo' };
  } else {
    const repo = (attrs.path || '').replace(/\.git$/, '').match(/^([^/]+\/[^/]+)/)?.[1];
    req = op === 'opencomputer' ? { kind: 'opencomputer' } : repo ? { repos: [repo] } : {};
  }
  const sock = process.env.SP_TOKEN_SOCKET || path.join(process.env.SP_RUN || '/run/slack-presence', 'token.sock');

  const res = await new Promise((resolve, reject) => {
    const c = net.connect(sock);
    let buf = '';
    c.setTimeout(20000, () => c.destroy(new Error('timed out')));
    c.on('connect', () => c.write(JSON.stringify(req) + '\n'));
    c.on('data', (d) => {
      buf += d;
      const i = buf.indexOf('\n');
      if (i < 0) return;
      c.end();
      try { resolve(JSON.parse(buf.slice(0, i))); } catch (e) { reject(e); }
    });
    c.on('error', reject);
    c.on('close', () => reject(new Error('closed without an answer')));
  });
  if (!res.token) throw new Error(res.error || 'no token');

  if (op === 'opencomputer') {
    if (!res.apiUrl) throw new Error('the gateway does not hand out OpenComputer keys yet');
    return void process.stdout.write(`${res.token}\n${res.apiUrl}\n`);
  }
  if (op === 'automation-remote') {
    if (!res.remoteUrl) throw new Error('the gateway does not hand out automation repositories yet');
    return void process.stdout.write(`${res.remoteUrl}\n`);
  }
  if (op === 'token') return void process.stdout.write(res.token + '\n');
  const expiry = Date.parse(res.expiresAt);
  const username = codeStorage ? res.username || 't' : 'x-access-token';
  process.stdout.write(`username=${username}\npassword=${res.token}\n` + (expiry ? `password_expiry_utc=${Math.floor(expiry / 1000)}\n` : ''));
})().catch((e) => {
  process.stderr.write(`git-credential-slack-presence: ${e.message}\n`);
  process.exitCode = 1;
});