anbot

425ca29 / push-auth.mjs

5339 bytes

import { execFileSync, spawnSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import {
  base64Decode, base64Encode, createRecord, importAuthorKey, parseJson, requireThat, signBytes,
  utf8Encode, verifyBytes
} from './core.mjs'
import { verifyPushAnnouncement } from './social.mjs'

const challengeLifetime = 60_000
const tokenLifetime = 5 * 60_000
const maxEntries = 1024
const identifier = () => base64Encode(globalThis.crypto.getRandomValues(new Uint8Array(32)), true)
const message = (origin, repoId, nonce) =>
  utf8Encode(JSON.stringify(['anbot-git-push-v1', origin, repoId, nonce]))

function store(map, identity, lifetime, announcement) {
  const now = Date.now()
  for (const [key, entry] of map) {
    if (entry.expires <= now) map.delete(key)
  }
  requireThat(map.size < maxEntries, 'Too many pending authentications')
  const key = identifier()
  map.set(key, { identity, expires: now + lifetime, announcement })
  return key
}

async function readBody(request) {
  const chunks = []
  let bytes = 0
  for await (const chunk of request) {
    bytes += chunk.length
    requireThat(bytes <= 16384, 'Authentication request too large')
    chunks.push(chunk)
  }
  return parseJson(Buffer.concat(chunks))
}

function json(response, status, value) {
  response.writeHead(status, {
    'Content-Type': 'application/json', 'Cache-Control': 'no-store'
  }).end(JSON.stringify(value))
}

export function pushAuth(allowlist, origin, repoId) {
  const challenges = new Map()
  const tokens = new Map()
  const allowed = author => readFileSync(allowlist, 'utf8')
    .split(/\r?\n/).some(line => line.trim() === author)

  return {
    async challenge(request, response) {
      try {
        if (request.method === 'GET') {
          const author = request.headers['x-anbot-author']
          await importAuthorKey(author)
          const nonce = store(challenges, author, challengeLifetime)
          json(response, 200, { repoId, nonce })
          return
        }
        const { author, nonce, proof, announcement } = await readBody(request)
        const entry = challenges.get(nonce)
        challenges.delete(nonce)
        requireThat(entry?.expires > Date.now() && author === entry.identity &&
          typeof proof === 'string', 'Invalid authentication')
        const signature = base64Decode(proof)
        requireThat(signature.length === 64 &&
          await verifyBytes(await importAuthorKey(author), message(origin, repoId, nonce), signature),
        'Invalid authentication')
        const authorized = allowed(author)
        console.log(`ANBot push identity verified: ${author} (${authorized ? 'allowed' : 'not allowlisted'})`)
        requireThat(authorized, 'Identity is not allowlisted')
        if (announcement !== undefined) await verifyPushAnnouncement(announcement, author, repoId)
        json(response, 200, { token: store(tokens, author, tokenLifetime, announcement) })
      } catch {
        json(response, 403, { error: 'Push access denied' })
      }
    },
    authorized(request) {
      const token = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(request.headers.authorization)?.[1]
      const entry = tokens.get(token)
      return entry?.expires > Date.now() && allowed(entry.identity) ? entry : null
    }
  }
}

export async function pushWithIdentity(identity, remote, source, branch) {
  const url = new URL(remote)
  requireThat((url.protocol === 'https:' ||
    (url.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))) &&
    !url.username && !url.password && !url.search && !url.hash,
  'Use an HTTPS clone URL or local loopback URL')
  const authUrl = url.href.replace(/\/$/, '') + '/anbot-auth'
  const options = { redirect: 'error', signal: AbortSignal.timeout(15000) }
  const challenge = await fetch(authUrl, {
    ...options, headers: { 'X-ANBot-Author': identity.author }
  })
  requireThat(challenge.ok, 'Push access denied or unavailable for ' + identity.author)
  const { repoId, nonce } = await challenge.json()
  const ref = `refs/heads/${branch}`
  const commit = execFileSync('git', ['-C', source, 'show-ref', '--verify', '--hash', ref],
    { encoding: 'utf8' }).trim()
  const announcement = await createRecord(identity, { anbot: 1, type: 'git-push', repoId, ref, commit })
  const proof = base64Encode(await signBytes(identity.privateKey, message(url.origin, repoId, nonce)))
  const accepted = await fetch(authUrl, {
    ...options, method: 'POST', headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ author: identity.author, nonce, proof, announcement })
  })
  requireThat(accepted.ok, 'Push access denied for ' + identity.author)
  const { token } = await accepted.json()
  requireThat(/^[A-Za-z0-9_-]{43}$/.test(token), 'Invalid push token')
  const result = spawnSync('git', ['-C', source, 'push', '--', url.href,
    `${commit}:${ref}`], {
    stdio: 'inherit',
    env: {
      ...process.env, GIT_CONFIG_COUNT: '3', GIT_TERMINAL_PROMPT: '0',
      GIT_CONFIG_KEY_0: 'http.extraHeader', GIT_CONFIG_VALUE_0: '',
      GIT_CONFIG_KEY_1: 'http.extraHeader', GIT_CONFIG_VALUE_1: 'Authorization: Bearer ' + token,
      GIT_CONFIG_KEY_2: 'http.followRedirects', GIT_CONFIG_VALUE_2: 'false'
    }
  })
  if (result.error) throw result.error
  requireThat(result.status === 0, 'Git push failed')
}

Git ยท Social feed