Remove redundant signing logic from IP session cookie

This commit is contained in:
Calvin Montgomery 2017-05-01 21:51:11 -07:00
parent 6bfbbc0c01
commit de309d675e
2 changed files with 14 additions and 46 deletions

View File

@ -2,7 +2,7 @@
"author": "Calvin Montgomery",
"name": "CyTube",
"description": "Online media synchronizer and chat",
"version": "3.36.0",
"version": "3.36.1",
"repository": {
"url": "http://github.com/calzoneman/sync"
},

View File

@ -2,71 +2,39 @@ import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
const STATE_FOLDER_PATH = path.resolve(__dirname, '..', '..', '..', 'state');
const SALT_PATH = path.resolve(__dirname, '..', '..', '..', 'state', 'ipsessionsalt.json');
const NO_EXPIRATION = new Date('Fri, 31 Dec 9999 23:59:59 GMT');
var SALT;
try {
SALT = require(SALT_PATH);
} catch (error) {
SALT = crypto.randomBytes(32).toString('base64');
try {
fs.mkdirSync(STATE_FOLDER_PATH);
} catch (error) {
if (error.code !== 'EEXIST') {
throw error;
}
}
fs.writeFileSync(SALT_PATH, JSON.stringify(SALT));
}
function sha256(input) {
var hash = crypto.createHash("sha256");
hash.update(input);
return hash.digest("base64");
}
export function createIPSessionCookie(ip, date) {
const hashInput = [
ip,
date.getTime(),
SALT
].join(':');
return [
date.getTime(),
sha256(hashInput)
ip,
date.getTime()
].join(':');
}
export function verifyIPSessionCookie(ip, cookie) {
const parts = cookie.split(':');
if (parts.length !== 2) {
return false;
return null;
}
const timestamp = parseInt(parts[0], 10);
if (isNaN(timestamp)) {
return false;
if (parts[0] !== ip) {
return null;
}
const date = new Date(timestamp);
const expected = createIPSessionCookie(ip, date);
if (expected !== cookie) {
return false;
const unixtime = parseInt(parts[1], 10);
const date = new Date(unixtime);
if (isNaN(date.getTime())) {
return null;
}
return {
date: date,
};
return { date };
}
export function ipSessionCookieMiddleware(req, res, next) {
var firstSeen = new Date();
var hasSession = false;
let firstSeen = new Date();
let hasSession = false;
if (req.signedCookies && req.signedCookies['ip-session']) {
var sessionMatch = verifyIPSessionCookie(req.realIP, req.signedCookies['ip-session']);
const sessionMatch = verifyIPSessionCookie(req.realIP, req.signedCookies['ip-session']);
if (sessionMatch) {
hasSession = true;
firstSeen = sessionMatch.date;