I'm trying to run Electron in headless mode to fetch content on remote server which requires cookies with prefix __Host-. However, the old code used to run
var cookie = {
url: cookieurl,
name: cookiename,
value: cookievalue
};
win.webContents.session.cookies.set(cookie)
.then(function(result)
{
loadUrl(win, indexUrl, output);
})
.catch(function(e)
{
throw Error("Failed to load cookie, e=" e);
});
and this seems to work just fine as long as cookiename does not start with __Host-. When I try to set cookie with prefix __Host- I get following exception instead:
Error: Failed to parse cookie
However, this limitation is not documented at https://www.electronjs.org/docs/latest/api/cookies
CodePudding user response:
This detail is not documented in the official documentation at https://www.electronjs.org/docs/latest/api/cookies but it's a logical result of other rules. Specifically the Set-Cookie HTTP header is defined to follow these rules:
<cookie-name>=<cookie-value>
...
Note: Some<cookie-name>have a specific semantic:
__Host-prefix:
Cookies with names starting with__Host-must be set with thesecureflag, must be from a secure page (HTTPS), must not have adomainspecified (and therefore, are not sent to subdomains), and the path must be/.
...
Attributes
...
SecureOptional
Indicates that the cookie is sent to the server only when a request is made with thehttps:scheme (except onlocalhost), and therefore, is more resistant to man-in-the-middle attacks.Note: Do not assume that
Secureprevents all access to sensitive information in cookies (session keys, login details, etc.). Cookies with this attribute can still be read/modified either with access to the client's hard disk or from JavaScript if theHttpOnlycookie attribute is not set.Insecure sites (http:) cannot set cookies with the
Secureattribute (since Chrome 52 and Firefox 52). For Firefox, the https: requirements are ignored when the Secure attribute is set by localhost (since Firefox 75).
Specifically, you cannot set cookie with name starting with __Host- prefix without also specifying secure. As a result, setting cookie as described in the question fails. Unfortunately, the exception is just Error: Failed to parse cookie instead of Error: cannot set cookie with "__Host-" prefix without also setting "secure" attribute.
Following should work as expected:
var cookie = {
url: cookieurl,
name: cookiename,
value: cookievalue,
secure: true,
// httpOnly: true,
// sameSite: "lax",
};
win.webContents.session.cookies.set(cookie)
.then(function(result)
{
loadUrl(win, indexUrl, output);
})
.catch(function(e)
{
throw Error("Failed to load cookie, e=" e);
});
The above example also has httpOnly and sameSite attributes in comments to work as a reminder that you probably want to consider these attributes, too.
