35 lines
945 B
JavaScript
35 lines
945 B
JavaScript
// Compact signed tokens: base64url(json) + '.' + hmac. Used to hand the client
|
|
// opaque URLs for proxy/remux/subs without exposing an open proxy.
|
|
const crypto = require('crypto');
|
|
|
|
let secret = '';
|
|
|
|
function init(s) {
|
|
secret = s;
|
|
}
|
|
|
|
function mac(body) {
|
|
return crypto.createHmac('sha256', secret).update(body).digest('base64url').slice(0, 22);
|
|
}
|
|
|
|
function sign(obj) {
|
|
const body = Buffer.from(JSON.stringify(obj)).toString('base64url');
|
|
return `${body}.${mac(body)}`;
|
|
}
|
|
|
|
function verify(token) {
|
|
const i = String(token || '').lastIndexOf('.');
|
|
if (i <= 0) return null;
|
|
const body = token.slice(0, i);
|
|
const sig = Buffer.from(token.slice(i + 1));
|
|
const want = Buffer.from(mac(body));
|
|
if (sig.length !== want.length || !crypto.timingSafeEqual(sig, want)) return null;
|
|
try {
|
|
return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
module.exports = { init, sign, verify };
|