git ssb

10+

Matt McKegg / patchwork



Tree: 79a7648a67be6e62f470c97d30dd7256f2e7edea

Files: 79a7648a67be6e62f470c97d30dd7256f2e7edea / lib / serve-blobs.js

1581 bytesRaw
1var pull = require('pull-stream')
2var cat = require('pull-cat')
3var toPull = require('stream-to-pull-stream')
4var ident = require('pull-identify-filetype')
5var mime = require('mime-types')
6var URL = require('url')
7var http = require('http')
8
9module.exports = function (context, cb) {
10 return http.createServer(ServeBlobs(context.sbot)).listen(context.config.blobsPort, cb)
11}
12
13function ServeBlobs (sbot) {
14 return function (req, res, next) {
15 var parsed = URL.parse(req.url, true)
16 var hash = decodeURIComponent(parsed.pathname.slice(1))
17 sbot.blobs.want(hash, function (_, has) {
18 if (!has) return respond(res, 404, 'File not found')
19 // optional name override
20 if (parsed.query.name) {
21 res.setHeader('Content-Disposition', 'inline; filename=' + encodeURIComponent(parsed.query.name))
22 }
23
24 // serve
25 res.setHeader('Content-Security-Policy', BlobCSP())
26 respondSource(res, sbot.blobs.get(hash), false)
27 })
28 }
29}
30
31function respondSource (res, source, wrap) {
32 if (wrap) {
33 res.writeHead(200, {'Content-Type': 'text/html'})
34 pull(
35 cat([
36 pull.once('<html><body><script>'),
37 source,
38 pull.once('</script></body></html>')
39 ]),
40 toPull.sink(res)
41 )
42 } else {
43 pull(
44 source,
45 ident(function (type) {
46 if (type) res.writeHead(200, {'Content-Type': mime.lookup(type)})
47 }),
48 toPull.sink(res)
49 )
50 }
51}
52
53function respond (res, status, message) {
54 res.writeHead(status)
55 res.end(message)
56}
57
58function BlobCSP () {
59 return 'default-src none; sandbox'
60}
61

Built with git-ssb-web