Skip to content

Commit

Permalink
Improve cookie parsing for the CookieChanger module
Browse files Browse the repository at this point in the history
This includes parsing an empty cookie, which allows the CookieChanger users
to add values even if no cookie was sent in the first place. It also enables
adding a method for removing cookies in the future.

Unit tests for the parsing of basic cookies are included.
  • Loading branch information
klemens committed Oct 27, 2016
1 parent 0914bb5 commit 00976ec
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lib/CookieChanger.js
Expand Up @@ -3,6 +3,7 @@ const {Ci} = require("chrome");

// export CookieChanger
exports.CookieChanger = CookieChanger;
exports.Cookies = Cookies;

// save all CookieChangers
var listeners = [];
Expand Down Expand Up @@ -44,6 +45,11 @@ function Cookies(cookieString) {

cookieString.split(/; */).forEach((cookie) => {
var i = cookie.indexOf("=");

if(i == -1) {
return;
}

this.cookies.set(cookie.substring(0, i), cookie.substring(i + 1));
});
}
Expand Down Expand Up @@ -95,18 +101,18 @@ function httpListener(event) {
});

if(applicableListeners.length > 0) {
var cookieString = "";
try {
var cookieString = request.getRequestHeader("Cookie");
} catch(ex) {
return;
}
cookieString = request.getRequestHeader("Cookie");
} catch(ex) {}

var cookies = new Cookies(cookieString);

applicableListeners.forEach((listener) => {
listener.callback(cookies);
});

// setting an empty string (no cookies) deletes the header
request.setRequestHeader("Cookie", cookies.unparse(), false);
}
}
Expand Down
28 changes: 28 additions & 0 deletions test/test-cookies.js
@@ -0,0 +1,28 @@
const {Cookies, modifyPrefCookie} = require("../lib/CookieChanger");

exports.testCookieParsing = (assert) => {
var t = (cookieString) => {
return (new Cookies(cookieString)).unparse();
};

assert.equal(t(""), "");
assert.equal(t("a=b"), "a=b");
assert.equal(t("a=1; b=2"), "a=1; b=2");
assert.equal(t("b=2; a=1"), "b=2; a=1");

assert.equal(t("a=1; b=2"), "a=1; b=2");
assert.equal(t("a=1; ; b=2"), "a=1; b=2");
assert.equal(t("a=1;; b=2"), "a=1; b=2");
assert.equal(t("a=1;;b=2"), "a=1; b=2");
assert.equal(t("a=1 ;b=2"), "a=1 ; b=2");

// Cookies uses a Map as its backend
assert.equal(t("a=1; a=2"), "a=2");

assert.equal(t("abc"), "");
assert.equal(t("abc="), "abc=");
assert.equal(t("=abc"), "=abc");
assert.equal(t("a=1; abc; b=2"), "a=1; b=2");
};

require('sdk/test').run(exports);

0 comments on commit 00976ec

Please sign in to comment.