Files: ce375da17a50a713361509fbf70ff5ccf225d1f4 / lib / serve-blobs.js
1581 bytesRaw
1 | var pull = require('pull-stream') |
2 | var cat = require('pull-cat') |
3 | var toPull = require('stream-to-pull-stream') |
4 | var ident = require('pull-identify-filetype') |
5 | var mime = require('mime-types') |
6 | var URL = require('url') |
7 | var http = require('http') |
8 | |
9 | module.exports = function (context, cb) { |
10 | return http.createServer(ServeBlobs(context.sbot)).listen(context.config.blobsPort, cb) |
11 | } |
12 | |
13 | function 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 | |
31 | function 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 | |
53 | function respond (res, status, message) { |
54 | res.writeHead(status) |
55 | res.end(message) |
56 | } |
57 | |
58 | function BlobCSP () { |
59 | return 'default-src none; sandbox' |
60 | } |
61 |
Built with git-ssb-web