Git Product home page Git Product logo

cookie-parser's People

Contributors

arilfrankel avatar basarat avatar choskim avatar defunctzombie avatar diogoduailibe avatar dougwilson avatar freeall avatar jamielinux avatar jonathanong avatar kevinsimper avatar linusu avatar oliviertassinari avatar sanzseraph avatar tanja-4732 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cookie-parser's Issues

How do I clear the cookie(s)?

Hi friends, i'm using cookie-parser and I'm trying to figure out how to clear the cookies. I don't see documentation for this anywhere. Please let me know how, thanks!

Node.js v20.9.0 fetch API can't get set-cookie header set by cookie-parser

Node.js Version:
v20.9.0

Platform:
Microsoft Windows NT 10.0.22631.0 x64

my node version:

PS C:\> node -v
v20.9.0

my server-side code:

const express = require('express');
const cookieParser = require('cookie-parser')

const app = express()

app.use(cookieParser())

app.get('/', (req, res) => {
    console.log(req.headers);
    res.cookie('sessionCookie', 'your-session-id', { maxAge: 900000 });
    res.redirect(302, '/redirected');
});

app.get('/redirected', (req, res) => {
    const sessionCookie = req.cookies['sessionCookie'];
    res.send(`Session Cookie Value: ${sessionCookie}`);
});

const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running at http://localhost:${PORT}`);
});

my client-side code:

async function runFetch(url) {
    const resp = await fetch(url);
    console.log(resp.status);
    //console.log(resp.headers);
    console.log(resp.headers.getSetCookie());
}
runFetch('http://127.0.0.1:3000').catch(err => console.log(err));
runFetch('http://www.redhat.com').catch(err => console.log(err));

server output:

{
  host: '127.0.0.1:3000',
  connection: 'keep-alive',
  accept: '*/*',
  'accept-language': '*',
  'sec-fetch-mode': 'cors',
  'user-agent': 'node',
  'accept-encoding': 'gzip, deflate'
}
{
  host: '127.0.0.1:3000',
  connection: 'keep-alive',
  accept: '*/*',
  'accept-language': '*',
  'sec-fetch-mode': 'cors',
  'user-agent': 'node',
  'accept-encoding': 'gzip, deflate'
}

client output:

200
[]
200
[
'akaalb_prod_rhdc=1700055912~op=lb_prod_rhdc_rhdc:prod_rhdc_mbp_aws_us_west_2|~rv=37~m=prod_rhdc_mpp_aws_us_west_2:0|~os=c98352339ebdffee81b2eed3a8c275410b6cb2~id=10f1b14eeaa863899f92f6927e53ffafcf3; path=/; Expires=Wed, 15 Nov 2023 13:45:29 GMT; HttpOnly; Secure; SameSite=None; Domain=.www.redhat.com'
]

How often does it reproduce? Is there a required condition?
everytime

What is the expected behavior? Why is that the expected behavior?
The response returned by fetch() should return the set-cookie header by calling it's getSetCookie() method.

What do you see instead?
I don't get any set-cookie header from my server-side code. maybe a bug of cookie-parser but I can't fingure out.

Why does signed cookie not populate in req.signedCookies?

Looks like signedCookies is not being populated.

res.cookie('ok', {why: "ok"}, {signed: true});
logger.info("signed cookies", req.signedCookies);
//=> signed cookies {}

logger.info("cookies", req.cookies);
//=> cookies { ok: 's:j:{"why":"ok"}.qVInqKcYbSXfZ+1m99smJV1t6IHoaZCcmOYVpRDpxUsvl/gaUqnV9Oy2/nbv2qt75iEvez/jXdTO1WAMgKJ/WQ' }

My cookies automatically expire after 30 minutes

I am using cookie-parser for express but I am confused by the way my cookies behave :

I set my cookie to expires after 1 hour but it expires always after 30 minutes

res.cookie('mycookie', 'value',{expire: Date.now() + 3600000,secure:true,httpOnly:true});

I also tried

res.cookie('mycookie','value',{maxAge:3600000,secure:true,httpOnly:true});

whithout success. My cookie always expires after 30 minutes, even when I set 5 minutes , it expires 30 minutes later. I really can't figure out what's wrong.

Thanks for helping

Null prototype using Object.create(null)

Hi,

Using Object.create(null) causes the cookies and signedCookies objects to have a null prototype instead of Object.prototype, which in turn breaks code utilizing native or extended Object functions.

Please, can you fix the code to use normal object definitions such as var cookies = {}; ??

Thank you!

Support for multiple secrets

Currently only one secret may be used with cookie-parser at a time. While you of course wouldn't actually be using and writing cookies with multiple keys, it's possible someone may want to slowly rollover their secret key to a new value for a non-critical/non-emergency reason that does not require suddenly making all cookies written with the old secret key invalid.

pillarjs/cookies handles this by allowing a keygrip instance to be passed instead, and keygrip support secondary secret keys.

Cannot read property 'cookie' of undefined

Hi

I'm currently working with socket.io and the client sends a request but apperently the req.headers is undefined.

So in the index.js file on line 27, I would suggest to do a check if the request object has headers and then take cookie of the headers.
If there are no headers raise an exception and pass it to the callback.

Thanks!

    var cookies = req.headers.cookie;
                             ^
TypeError: Cannot read property 'cookie' of undefined
    at Array.cookieParser [as 0] (C:\nodejs\generator-rappit\test\temp\node_modules\cookie-parser\index.js:27:30)
    at run (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\lib\namespace.js:114:11)
    at Namespace.run (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\lib\namespace.js:126:3)
    at Namespace.add (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\lib\namespace.js:155:8)
    at Client.connect (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\lib\client.js:67:20)
    at Server.onconnection (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\lib\index.js:230:10)
    at Server.EventEmitter.emit (events.js:95:17)
    at Server.handshake (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\node_modules\engine.io\lib\server.js:242:8)
    at Server.handleRequest (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\node_modules\engine.io\lib\server.js:176:10)
    at Server.<anonymous> (C:\nodejs\generator-rappit\test\temp\node_modules\socket.io\node_modules\engine.io\lib\engine.io.js:119:14)

signedCookie is unlikely to be used correctly

cookie-parser's signedCookie function has the following behavior when it encounters an unsigned value:

"If the value was not signed, the original value is returned."

This is subtle behavior, and it seems unlikely that a caller would actually know to check that the return value was different from what was passed in. If the caller depends on the signature mechanism to prevent tampering this could be a serious problem.

A cursory check shows all 3 callers on github are not checking the return value:

https://github.com/search?q=%22cookieparser.signedCookie%22+-path%3AcookieParser&type=Code&ref=advsearch&l=&l=

I'd suggest changing the API to return false if passed a non-signature cookie value, similar to failing the signature check.

Provide types for the cookies in typescript

When I do a type declartion like the following:

// custom.d.ts
declare namespace Express {
  export interface Request {
    test_key: string,
    cookies: {
      cookie_name: string;
    };
  }
}

req.test_key is properly typed but req.cookies remains any.

Is there a way to type cookies?

How to change/set domain, seems impossible?

I don't know if it is a bug or question;
Using Node.js/ Express/ cookie-parser, in back-end server sub-domain, I tried to set domain, but it seems impossible:
1- no effect:

server.use(
cookieParser(
'sessionid', {
name: 'session',
domain: '.firouzeh-mfg.ir',
maxAge: 24 * 60 * 60 * 1000
}
)
)

2- This prevent even setting cookie: cookie not added to response

res.cookie('sessionid', req.userData.SessionId, {
maxAge: settings.SESSION_TIME_OUT,
httpOnly: true,
domain:settings.COOKIE_DOMAIN});

3- This add cookie with defauld url:

res.cookie('idlang', req.userData.IdLang, { maxAge: settings.SESSION_TIME_OUT, httpOnly: true });

Is it a bug issue or bad coding?
Thank you

Docs on signedCookie seem to be off

cookieParser.signedCookie(str, secret)

Parse a cookie value as a signed cookie. This will return the parsed unsigned value if it was a signed cookie and the signature was valid, otherwise it will return the passed value.

The code reads different. If the cookie seems signed but cannot be unsigned properly, false is returned, not the original argument: https://github.com/expressjs/cookie-parser/blob/master/index.js#L149.

I'd send a PR but wanted to check first.

[ FEATURE ] Support for ES6 imports

I've been trying to import cookieParser, it seems that there are no default exports setup for them.

import cookieParser from 'cookie-parser'; // Does not work

Could not find a declaration file for module 'cookie-parser'. '/node_modules/cookie-parser/index.js' implicitly has an 'any' type.

Expected Outcome:

import cookieParser from 'cookie-parser';

or

import * as cookieParser from 'cookie-parser';

Should import cookieParser

cookie 0.5.0

Hi,

the dependency lib cookie got updated last year in April to version 0.5.0.
Could you please update to the new version? There are no breaking changes.

Thank you!

create and remove cookies

Does this library have simplified methods for creating and removing cookies?
e.g. like what used to exist?

res.clearCookie('cookiename');
res.cookie('cookiename', 'cookievalue', { maxAge: 900000, httpOnly: true });

Clear Cookies Feature?

Any hopes of a destroy all cookies feature for development purposes?

I know i could just clear my browser cookies but would help if there was an API route I could navigate to clear them...

cookieParser.signedCookie seems to not work properly

Hello everyone. I'm trying to "decode" a signed cookie I receive in a websocket session. First, here is how I setup my express session with cookie-parser:

static.ts file

import * as cookieParser from 'cookie-parser';
import * as express from 'express';
import * as session from 'express-session';

const app = express();

app.use(cookieParser('foobarbaz1234567foobarbaz1234567'));
app.use(session({
  cookie: {
    httpOnly: true,
    maxAge: 600000, // 3600000 for 1 hour & 600000 for 10 minutes
    secure: process.env.VSCodeDebug && process.env.VSCodeDebug === 'true' ? false : true,
  },
  genid: () => genuuid(),
  resave: false,
  saveUninitialized: false,
  secret: 'foobarbaz1234567foobarbaz1234567',
  store: mystore,
}));

Somewhere in my code, when I receive a websocket connection, I'm able to get the signed cookie. But I want to decode it in order to have the session ID stored inside.

This is what I'm trying to do:

image

As you can see, i'm using the same secret password with "signedCookie" than in the cookieParser initialization. The result of signedCookie returns everytime the same string as the signed cookie (temp3 value in my current example). And according to your documentation:
image
it kinda says that the signature is invalid or something like that. Is it possible that I'm missing something in my approch ? In my database where the cookie is stored, I can see the decoded cookie (i.e the session ID). So I guess that something looks wrong with "signedCookie" function (or maybe with my approch).

You can see bellow what I have in my request parameter.
Also, bellow, you can see what I observe when I'm trying to user signedCookie function. The output of this function is the same as the input (signedSession). And the secret is the same as in the cookie-parser configuration.

Here is what I have in my webSocketSingleton.ts file
import * as cookieParser from 'cookie-parser';
image

Here is what I observe when using the signedCookie function

image

Here is the content of the "req" parameter

image

image

Can you help me please to resolve this issue ? Thank you in advance for your answer

Support ignoring signed cookies, when no secret provided

I'm using cookie parser in a situation where there are both signed and unsigned cookies in the request. If cookie-parser is put in the stack without the secret option, and the request contains a signed cookie, then this will throw an error.

IMO it would be better to simply ignore signed cookies when there is no secret provided, so that unsigned cookies could still be parsed. (Or an option for this).

Inaccurate docs about JSONCookie, JSONCookies, signedCookie and signedCookies

Nowadays you need to decode the cookie value using decodeURIComponent() before using any of the following functions:

  1. cookieParser.JSONCookie
  2. cookieParser.JSONCookies (decodeURIComponent for each cookie)
  3. cookieParser.signedCookie
  4. cookieParser.signedCookies (decodeURIComponent for each cookie)

Because it doesn't decode itself inside the function, now they just check if it starts with 'j:' or 's:' (before, it required an encodedURI and it would check if it starts with 'j%3A', for JSONCookie, or 's%3A', for signedCookie, and then both of these functions would decode the input to continue their codes), but in the documentation, it doesn't specify anywhere that the input needs to be decoded, even though I really prefer before when the function itself decoded the input, and it would cause less confusion because it would work with decoded and encoded values.

these prints are from expressjs/cookie-parser source code
image
image
these prints are from the README expressjs/cookie-parser
image
image

Conclusion:
The documentation is outdated.

Reading duplicated cookies

my bro sends weird cookies (after deleting and installing cookies again):

user_id=; session_id=; session_id=XXXXXXX; user_id=6

cookie-parser parse them as a ''

but expected reading a second value of each cookie

Specific cookie kinda broken

alright so i'm making some sessions as testing with cookies (i'm using editthiscookie)
it sets the cookie okay, but when i print all of the cookies, 1 of the cookies says undefined ALL the time. even if i delete the cookie, it still returns the name, and undefined.

i even did console.log(document.cookies) and it showed the correct value.

Cookie Parser not reading signed cookies

I have cookie-parser configured in my app.js file like so:

app.use(cookieParser(process.env.SECRET));

I am also using web-sessions for authentication with the same secret:

var webSession = {
    name: 'sid',
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false, // don't create the session until something is stored.
    unset: 'keep',
    rolling: true,
    cookie: {maxAge: 3600000} // one hour
};

I am setting a cookie as follows:

var cookie = req.signedCookies.cart;
if (cookie === undefined) {
    // no cart: set a new cookie
    var item = {
        id: req.body.id,
        quantity: 1
    };
    var cart = [item];
    res.cookie('cart', cart, {signed:true, maxAge: 604800000, httpOnly: true}); //maxAge=1 week.
    console.log('cookie created successfully');
    res.send('cookie created');
} else {
    // cart was already created
    console.log('cookie exists', cookie);
    // TODO: check if item is already in cart.
    cookie = cookieParser.signedCookie('cart', process.env.SECRET);
    console.log(cookie);
}

Output:

cookie created successfully
cookie exists [ { id: '15', quantity: 1 } ]
cart

I can read the signed cookie using the basic req.signedCookies, but when I try with cookieParser.signedCookie, it simply returns the value I pass to the function back to me. Is this is an error with me signing the cookie and configuring my secret's or a bug in cookie-parser?

How to sign a cookie manually?

For the sake of testing, I need to provide a signed cookie with HTTP request. So that, my server can consider it as a signed cookie and put it into req.signedCookies object.

However I cannot find a appropriate method in docs.
I'd like to do the following:

let signed = cookieParser.signYourCookie({ cookieName: 'cookieValue' }, secretString);
// => cookieName=cookieValue.9PuJzypXeGq3tc2fFvlukjgNZ518jk

That is an operation opposite to cookieParser.signedCookie(str, secret) (link)

export lib methods

Hi.

Upgrading a node project I noticed the function connect.utils.parseSignedCookies has moved to cookie-parser/lib/parse.js as signedCookies. I can't reach into it, because only the middleware is exported and the rest is private.

Would it be an idea to put the lib/parse.js functions on the exported function?

gr,

Tom

Cookies not setting in production

Hi am i using you cookie parser library in my nest js project. I am manly using your library for authentication.

I am trying to set a cookie called "jwt" when user has completed the authentication process. This is how the code looks like,

    response.cookie('jwt', accessToken, {
      maxAge: 15 * 60 * 1000,
      httpOnly: true,
      secure: env === 'production' ? true : false,
    });

This works as expected inn localhost but when i deploy the code it does not set the cookie. Also no errors or warnings are fired.
I have messed around allot with the options but i could not set the cookie.

This is not a issue with your package i am just looking for guidance on how to handle this since you have worked with this. I have searched everywhere on why cookies are not setting but there is no concrete answer. Most of the answers are suggestions on modifying the options.

Sorry if this is a stupid question, but i have had trouble with this for 2 weeks now. If this is not a appropriate question, just let me know and i will take it down.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.