jkhsjdhjs / node-fetch-cookies

node-fetch wrapper that adds support for cookie-jars
MIT License
28 stars 16 forks source link

Cookies without an expiration date should also be retained #25

Open NabiKAZ opened 10 months ago

NabiKAZ commented 10 months ago

Thanks for your nice project.

I understand that deleting or not saving expired cookies from the file is normal behavior. But sometimes some sites return tokens in the cookie that, despite the expiration of the cookie date and removal from the browser, that token is still valid in subsequent requests and there is no need to request again to get that token. So I don't need that cookie to be deleted. I have to solve this problem. https://github.com/jkhsjdhjs/node-fetch-cookies/blob/db40f03ecfcaff613202637191060bf9d63d355c/src/cookie-jar.mjs#L108-L109 This code: this.cookiesValid(false) to this: this.cookiesValid(true) I changed.

It might be a good idea to add a parameter to the main class to select and manage this feature.

NabiKAZ commented 10 months ago

I did a review and found that my previous problem was not related to keeping expired cookies. It means that the cookies whose expiration date has reached should be deleted in any case. The problem was related to the time when the expiration date was not set for the cookie, which caused the cookie not to be saved.

That is, for example, in cases where the site returns the cookie like this:

'set-cookie': [ 'test=test; expires=Thu, 08-Feb-2024 18:49:56 GMT; Max-Age=10; path=/' ]

Saved file:

[{"name":"test","value":"test","expiry":"2024-02-08T18:49:56.105Z","path":"/","domain":"ex.com","subdomains":false,"secure":false}]

It is not a problem because there is an expiration date and it is checked by cookiesValid and hasExpired.

But when the site returns the cookie like this:

'set-cookie': [ 'test=test' ]

Saved file:

[{"name":"test","value":"test","domain":"ex.com","subdomains":false,"path":"/","secure":false,"expiry":null}]

Because the expiration date is null, this cookie is assumed to be expired and will never be saved. While browsers accept it and set a standard value like this:

Expires / Max-Age: "Session"

So as a quick fix I solved the problem with a small change in the cookiesValid function, for which I am sending a PR.