root / receive.mjs
2072 bytes
import { spawn } from 'node:child_process'
import { mkdtempSync, rmSync } from 'node:fs'
import { join } from 'node:path'
import { pipeline } from 'node:stream/promises'
import { createGunzip } from 'node:zlib'
import { gitEnv, stageReceive } from './repository.mjs'
import { requireThat } from './storage.mjs'
export async function receivePush(root, identity, request, response, authorized) {
const directory = mkdtempSync(join(root, '.receive-'))
try {
const staged = await stageReceive(root, identity, directory)
const child = spawn('git', [
'-c', 'core.hooksPath=' + staged.hooks,
'-c', 'receive.denyDeletes=true',
'-c', 'receive.denyNonFastForwards=true',
'-c', 'receive.fsckObjects=true',
'-c', 'receive.maxInputSize=64m',
'receive-pack', '--stateless-rpc', staged.bare
], {
env: { ...gitEnv, ANBOT_RECEIVE_REF: staged.ref },
stdio: ['pipe', 'pipe', 'inherit']
})
const finished = new Promise((resolve, reject) => {
child.once('error', reject)
child.once('close', status => {
if (status === 0) resolve()
else reject(new Error('Git receive-pack failed'))
})
})
const chunks = []
let size = 0
child.stdout.on('data', chunk => {
size += chunk.length
if (size > 1048576) child.kill()
else chunks.push(chunk)
})
const upload = request.headers['content-encoding'] === 'gzip'
? pipeline(request, createGunzip(), child.stdin)
: pipeline(request, child.stdin)
try {
await Promise.all([finished, upload])
const authorization = authorized()
requireThat(authorization, 'Push authorization expired or was revoked')
await staged.publish(authorization)
response.writeHead(200, {
'Content-Type': 'application/x-git-receive-pack-result', 'Cache-Control': 'no-store'
}).end(Buffer.concat(chunks))
} catch (error) {
child.kill()
await finished.catch(() => {})
throw error
}
} finally {
rmSync(directory, { recursive: true, force: true })
}
}
Git ยท Social feed