cookies are now parsed and populated on ctx.cookie by deault
[squeep-api-dingus] / lib / dingus.js
index a5f77ab19fa02f1df8d8fec140ef5347c94eb5f2..f060c18f00d251f610a97929fdce663c9f01de89 100644 (file)
@@ -35,6 +35,8 @@ const defaultOptions = {
   querystring,
 };
 
+const cookieSplitRE = /; */;
+
 class Dingus {
   /**
    * @param {Object} logger object which implements logging methods
@@ -179,15 +181,40 @@ class Dingus {
 
 
   /**
-   * Called before every request handler.
-   * Sets tracking identifiers and client information on ctx.
+   * Sets ctx.cookie from Cookie header.
    * @param {http.ClientRequest} req 
    * @param {http.ServerResponse} res 
    * @param {object} ctx 
    */
+  static ingestCookie(req, res, ctx) {
+    ctx.cookie = {};
+    req.getHeader(Enum.Header.Cookie)?.split(cookieSplitRE).forEach((cookie) => {
+      const [ name, value ] = common.splitFirst(cookie, '=', null).map((x) => {
+        try {
+          return decodeURIComponent(x.trim());
+        } catch (e) {
+          return x;
+        }
+      });
+      if (name && !(name in ctx.cookie)) {
+        const isQuoted = value?.startsWith('"') && value.endsWith('"');
+        ctx.cookie[name] = isQuoted ? value.slice(1, -1) : value; // eslint-disable-line security/detect-object-injection
+      }
+    });
+  }
+
+
+  /**
+   * Called before every request handler.
+   * Sets tracking identifiers and client information on ctx.
+   * @param {http.ClientRequest} req
+   * @param {http.ServerResponse} res
+   * @param {object} ctx
+   */
   async preHandler(req, res, ctx) {
-    Dingus.tagContext(req, res, ctx);
+    this.constructor.tagContext(req, res, ctx);
     this.clientAddressContext(req, res, ctx);
+    this.constructor.ingestCookie(req, res, ctx);
   }