From 1bf5278d3088c9b366c19937130c030b41c7cee0 Mon Sep 17 00:00:00 2001 From: cel Date: Thu, 26 Nov 2020 18:40:05 -0500 Subject: Support ssb-uri in request URLs and search --- lib/serve.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/lib/serve.js b/lib/serve.js index f09bd2f..aad2510 100644 --- a/lib/serve.js +++ b/lib/serve.js @@ -25,11 +25,13 @@ var split = require('pull-split') var utf8 = require('pull-utf8-decoder') var webresolve = require('ssb-web-resolver') var Url = require('url') +var Base64URL = require('base64-url') module.exports = Serve var hlCssDir = path.join(require.resolve('highlight.js'), '../../styles') +var ssbURIRegex = /^(?:\/+)(ssb:(message|blob|feed)([:\/])([^:?]*?)([:/])([^?]*)(\\?.*)?)$/ var urlIdRegex = /^(?:\/+(([%&@]|%25|%26)(?:[A-Za-z0-9\/+]|%2[Ff]|%2[Bb]){43}(?:=|%3D)\.(?:sha256|ed25519))([^?]*)?|(\/.*?))(?:\?(.*))?$/ function ctype(name) { @@ -448,6 +450,33 @@ Serve.prototype.publishMayRedirect = function (content, cb) { } } +Serve.prototype.translateFromURI = function (url) { + var m = ssbURIRegex.exec(url) + if (!m) return + var uri = m[1] + var prefix = m[2] + var separator = m[3] + var format = m[4] + var separator2 = m[5] + var hash = m[6] + var qs = m[7] || '' + if (separator !== separator2) return + hash = Base64URL.unescape(hash) + if (separator === '/') { + // ssb-custom-uri + try { hash = decodeURIComponent(hash) } + catch(e) {} + } + var sigil + switch (prefix) { + case 'message': sigil = '%'; break + case 'blob': sigil = '&'; break + case 'feed': sigil = '@'; break + default: return + } + return sigil + hash + '.' + format + qs +} + Serve.prototype.handle = function () { var m = urlIdRegex.exec(this.req.url) this.query = m[5] ? qs.parse(m[5]) : {} @@ -499,6 +528,10 @@ Serve.prototype.redirect = function (dest) { } Serve.prototype.path = function (url) { + if (url.substr(0, 5) === '/ssb:') { + var link = this.translateFromURI(url) + if (link) return this.redirect(this.app.render.toUrl(link)) + } var m url = url.replace(/^\/+/, '/') switch (url) { @@ -732,6 +765,8 @@ Serve.prototype.search = function (ext) { var maybeId = searchQ.substr(6) if (u.isRef(maybeId)) searchQ = maybeId } + var link = this.translateFromURI('/' + searchQ) + if (link) return self.redirect(self.app.render.toUrl(link)) if (u.isRef(searchQ) || searchQ[0] === '#') { return self.redirect(self.app.render.toUrl(searchQ)) -- cgit v1.2.3