OAuth2 / JWT / OpenID Connect for mocking auth... which isn't that different from doing it for real, actually. https://mock.pocketid.app
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

85 lines
1.6 KiB

'use strict';
var Hashcash = require('./hashcash.js');
var _sites = {};
module.exports = async function (opts) {
if (!opts.headers) {
opts.headers = {};
}
if (opts.json) {
if (true === opts.json) {
opts.body = JSON.stringify(opts.body);
} else {
opts.body = JSON.stringify(opts.json);
}
if (!opts.headers['Content-Type'] && !opts.headers['content-type']) {
opts.headers['Content-Type'] = 'application/json';
}
}
if (!opts.mode) {
opts.mode = 'cors';
}
var url = new URL(opts.url);
if (!_sites[url.hostname]) {
_sites[url.hostname] = { nonces: [] };
}
var site = _sites[url.hostname];
var hc = site.hashcashChallenge;
if (hc) {
delete site.hashcashChallenge;
site.hashcash = await Hashcash.solve(hc);
}
if (site.hashcash) {
opts.headers.Hashcash = site.hashcash;
}
var response = await window.fetch(opts.url, opts);
var headerNames = response.headers.keys();
var hs = {};
var h;
while (true) {
h = headerNames.next();
if (h.done) {
break;
}
hs[h.value] = response.headers.get(h.value);
}
var body;
if (hs['content-type'].includes('application/json')) {
body = await response.json();
} else {
body = await response.text();
try {
body = JSON.parse(body);
} catch (e) {
// ignore
}
}
var resp = {};
resp.body = body;
resp.headers = hs;
resp.toJSON = function () {
return {
headers: hs,
body: body
};
};
if (resp.headers['hashcash-challenge']) {
_sites[url.hostname].hashcashChallenge =
resp.headers['hashcash-challenge'];
}
if (resp.headers.nonce) {
site.nonces.push(resp.headers.nonce);
}
console.log(resp);
return resp;
};