ipfs_proxy.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const { createProxyMiddleware } = require('http-proxy-middleware')
  2. const debug = require('debug')('joystream:ipfs-proxy')
  3. /*
  4. For this proxying to work correctly, ensure IPFS HTTP Gateway is configured as a path gateway:
  5. This can be done manually with the following command:
  6. $ ipfs config --json Gateway.PublicGateways '{"localhost": null }'
  7. The implicit default config is below which is not what we want!
  8. $ ipfs config --json Gateway.PublicGateways '{
  9. "localhost": {
  10. "Paths": ["/ipfs", "/ipns"],
  11. "UseSubdomains": true
  12. }
  13. }'
  14. https://github.com/ipfs/go-ipfs/blob/master/docs/config.md#gateway
  15. */
  16. const pathFilter = function (path, req) {
  17. return path.match('^/asset/v1/') && (req.method === 'GET' || req.method === 'HEAD')
  18. }
  19. const createPathRewriter = (resolve) => {
  20. return async (_path, req) => {
  21. const hash = await resolve(req.params.id)
  22. return `/ipfs/${hash}`
  23. }
  24. }
  25. const createResolver = (storage) => {
  26. return async (id) => await storage.resolveContentIdWithTimeout(5000, id)
  27. }
  28. const createProxy = (storage) => {
  29. const pathRewrite = createPathRewriter(createResolver(storage))
  30. return createProxyMiddleware(pathFilter, {
  31. // Default path to local IPFS HTTP GATEWAY
  32. target: 'http://localhost:8080/',
  33. pathRewrite,
  34. // capture redirect when IPFS HTTP Gateway is configured with 'UseDomains':true
  35. // and treat it as an error.
  36. onProxyRes: function (proxRes, _req, res) {
  37. if (proxRes.statusCode === 301) {
  38. debug('IPFS HTTP Gateway is allowing UseSubdomains. Killing stream')
  39. proxRes.destroy()
  40. // TODO: Maybe redirect - temporary to /v0/asset/contentId ?
  41. res.status(500).end()
  42. }
  43. },
  44. })
  45. }
  46. module.exports = {
  47. createProxy,
  48. }