48 lines
1.7 KiB
JavaScript
Executable File
48 lines
1.7 KiB
JavaScript
Executable File
const {setup, sign, verify} = require("verlikify");
|
|
const uidgen = require("./uidgen");
|
|
|
|
setup("./.verlikify", "ec", {namedCurve:"sect113r1", privateKeyEncoding:{format:"pem", type:"sec1"}, publicKeyEncoding:{format:"pem", type:"spki"}})
|
|
const createToken = (id=uidgen(true), scopes = ["default"])=>{
|
|
const tokenData = Buffer.from(JSON.stringify({id, scopes, now:Date.now()})).toString("base64")
|
|
const tokensig = sign(tokenData);
|
|
return `${tokensig}.${tokenData}`
|
|
}
|
|
const checkToken = (token, scopes=["default"], cutoffTime=0)=>{
|
|
// console.log(scopes)
|
|
const [tokensig, tokenData] = token.split(".");
|
|
const jsontd = JSON.parse(Buffer.from(tokenData, "base64").toString())
|
|
console.log(jsontd.now - cutoffTime, scopes, jsontd.scopes)
|
|
if (jsontd.now < cutoffTime){
|
|
return {valid: false, reason:"token has expired"}
|
|
}
|
|
if(scopes.includes("refreshlogin")||!(jsontd.scopes.includes("admin")||scopes.includes("default"))){
|
|
let scopemismatch = false
|
|
scopes.forEach((scope)=>{
|
|
if(!jsontd.scopes.includes(scope)){
|
|
console.log(scope)
|
|
scopemismatch = {valid: false, reason:"required scopes not in token"}
|
|
}
|
|
})
|
|
if(scopemismatch){
|
|
//console.log(scopemismatch)
|
|
return scopemismatch
|
|
}
|
|
}
|
|
if(!verify(tokenData, tokensig)){
|
|
return {valid: false, reason:"signature mismatch"}
|
|
}
|
|
return {valid: true}
|
|
}
|
|
const encodePW = (password, id)=>{
|
|
if(!id){
|
|
id = uidgen();
|
|
}
|
|
return {uid: id, pass: sign(id+password)}
|
|
}
|
|
const verifyPW = (uid, password, pass)=>{
|
|
return verify(uid+password, pass)
|
|
}
|
|
module.exports = {
|
|
createToken, checkToken, encodePW, verifyPW
|
|
}
|