var proc = require('child_process') var fs = require('fs') var http = require('http') var URL = require('url') var crypto = require('crypto') var os = require('os') function escapeHTML (html) { return String(html) .replace(//g, '>') } function noPublish(content, cb) { cb(new Error('missing publish function')) } function noPrivatePublish(content, recps, cb) { cb(new Error('missing private publish function')) } function confirm(opts, cb) { var content = opts.content var browser = opts.browser var recps = opts.recps var publish = opts.publish || noPublish var privatePublish = opts.privatePublish || noPrivatePublish if (!browser) { return cb(new TypeError('missing browser option')) } if (recps && !Array.isArray(recps)) { return cb(new TypeError('recps should be array')) } var token = crypto.randomBytes(32).toString('base64') function publish1(content, recps, cb) { if (recps) privatePublish(content, recps, cb) else publish(content, cb) } var server = http.createServer(function (req, res) { var url = URL.parse(req.url, true) if (url.pathname !== '/') { res.writeHead(404) return res.end('Not Found') } if (url.query.token === token) { if (url.query.publish) { return publish1(content, recps, function (err, msg) { if (err) { res.writeHead(500, {'Content-Type': 'text/html'}) res.end('publish error' + '

' + escapeHTML(err.name || err) + '

' + '
' + escapeHTML(err.stack || '') + '
' + '') server.close() return cb(err) } var json = JSON.stringify(msg, 0, 2) res.writeHead(200, {'Content-Type': 'text/html'}) res.end('published' + '
' + escapeHTML(json) + '
' + '') server.close() return cb(null, msg) }) } if (url.query.cancel) { res.writeHead(200, {'Content-Type': 'text/html'}) res.end('canceled' + '

Cancelled

' + '') server.close() return cb(new Error('User cancelled')) } } var contentJson = JSON.stringify(content, null, 2) var recpsJson = JSON.stringify(recps, null, 2) res.writeHead(200, {'Content-Type': 'text/html'}) res.end('publish' + '
' + (recps ? '
' + recpsJson + '
' : '') + '
' + escapeHTML(contentJson) + '
' + '' + ' ' + '' + '
' + '') }).listen(0, '127.0.0.1', function () { var port = this.address().port var url = 'http://127.0.0.1:' + port + '/' proc.spawn(browser, [url], {stdio: 'inherit'}) }).on('error', cb) } module.exports = function (opts) { var publish = opts.publish var privatePublish = opts.privatePublish var config = opts.config || {} var browser = config.browser || (os.platform() === 'darwin' ? 'open' : 'xdg-open') var name = opts.name || 'confirm' return { publish: function (content, cb) { confirm({ publish: publish, content: content, browser: browser, }, cb) }, privatePublish: function (content, recps, cb) { confirm({ privatePublish: privatePublish, recps: recps, content: content, browser: browser, }, cb) } } }