-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmiddleware.js
160 lines (145 loc) · 5.49 KB
/
middleware.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
var spawn = require('child_process').spawn
var fs = require('fs')
var path = require('path')
var url = require('url')
var auth = require('basic-auth')
var chalk = require('chalk')
var fixturez = require('fixturez')
var htpasswd = require('htpasswd-js')
function pad (str) {
return (str + ' ').slice(0, 7)
}
function matchInfo (req) {
var u = url.parse(req.url)
if (req.method === 'GET' && u.pathname.endsWith('/info/refs')) {
return true
} else {
return false
}
}
function matchService (req) {
var u = url.parse(req.url, true)
if (req.method === 'GET' && u.pathname.endsWith('/info/refs')) {
return u.query.service
}
if (req.method === 'POST' && req.headers['content-type'] === 'application/x-git-upload-pack-request') {
return 'git-upload-pack'
}
if (req.method === 'POST' && req.headers['content-type'] === 'application/x-git-receive-pack-request') {
return 'git-receive-pack'
}
}
function factory (config) {
if (!config.root) throw new Error('Missing required "gitHttpServer.root" config option')
if (!config.route) throw new Error('Missing required "gitHttpServer.route" config option')
if (!config.route.startsWith('/')) throw new Error('"gitHttpServer.route" must start with a "/"')
// TODO: Make this configurable in karma.conf.js
var f = fixturez(config.root, {root: process.cwd(), glob: config.glob})
function getGitDir (req) {
var u = url.parse(req.url)
if (u.pathname.startsWith(config.route)) {
const info = matchInfo(req)
if (info) {
let gitdir = u.pathname.replace(config.route, '').replace(/\/info\/refs$/, '').replace(/^\//, '')
let fixtureName = path.posix.basename(gitdir)
return f.find(fixtureName)
}
const service = matchService(req)
if (service === 'git-upload-pack') {
let gitdir = u.pathname.replace(config.route, '').replace(/\/git-upload-pack$/, '').replace(/^\//, '')
let fixtureName = path.posix.basename(gitdir)
return f.find(fixtureName)
}
if (service === 'git-receive-pack') {
let gitdir = u.pathname.replace(config.route, '').replace(/\/git-receive-pack$/, '').replace(/^\//, '')
let fixtureName = path.posix.basename(gitdir)
return f.copy(fixtureName)
}
}
return null
}
return async function middleware (req, res, next) {
try {
// handle pre-flight OPTIONS
if (req.method === 'OPTIONS') {
res.statusCode = 204
res.end('')
console.log(chalk.green('[git-http-server] 204 ' + pad(req.method) + ' ' + req.url))
return
}
if (!next) next = () => void(0)
try {
var gitdir = getGitDir(req)
} catch (err) {
res.statusCode = 404
res.end(err.message + '\n')
console.log(chalk.red('[git-http-server] 404 ' + pad(req.method) + ' ' + req.url))
return
}
if (gitdir == null) return next()
// Check for a .htaccess file
let data = null
try {
data = fs.readFileSync(path.join(gitdir, '.htpasswd'), 'utf8')
} catch (err) {
// no .htaccess file, proceed without authentication
}
if (data) {
// The previous line would have failed if there wasn't an .htaccess file, so
// we must treat this as protected.
let cred = auth.parse(req.headers['authorization'])
if (cred === undefined) {
res.statusCode = 401
// The default reason phrase used in Node is "Unauthorized", but
// we will use "Authorization Required" to match what Github uses.
res.statusMessage = 'Authorization Required'
res.setHeader('WWW-Authenticate', 'Basic')
res.end('Unauthorized' + '\n')
console.log(chalk.green('[git-http-server] 401 ' + pad(req.method) + ' ' + req.url))
return
}
let valid = await htpasswd.authenticate({
username: cred.name,
password: cred.pass,
data
})
if (!valid) {
res.statusCode = 401
// The default reason phrase used in Node is "Unauthorized", but
// we will use "Authorization Required" to match what Github uses.
res.statusMessage = 'Authorization Required'
res.setHeader('WWW-Authenticate', 'Basic')
res.end('Bad credentials' + '\n')
console.log(chalk.green('[git-http-server] 401 ' + pad(req.method) + ' ' + req.url))
return
}
}
const info = matchInfo(req)
const service = matchService(req)
const env = req.headers['git-protocol'] ? { GIT_PROTOCOL: req.headers['git-protocol'] } : {}
const args = ['--stateless-rpc' ];
if (info) args.push('--advertise-refs')
args.push(gitdir)
if (info) {
res.setHeader('content-type', `application/x-${service}-advertisement`)
function pack (s) {
var n = (4 + s.length).toString(16);
return Array(4 - n.length + 1).join('0') + n + s;
}
res.write(pack('# service=' + service + '\n') + '0000');
} else {
res.setHeader('content-type', `application/x-${service}-result`)
}
const ps = spawn(service, args, { env })
req.pipe(ps.stdin)
ps.stdout.pipe(res)
console.log(chalk.green('[git-http-server] 200 ' + pad(req.method) + ' ' + req.url))
} catch (err) {
res.statusCode = 500
res.end(err + '\n')
console.log(chalk.red('[git-http-server] 500 ' + pad(req.method) + ' ' + req.url))
}
}
}
factory.$inject = ['config.gitHttpServer']
module.exports = factory