Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
@ts-stack/cookies
Advanced tools
This is a fork of cookies v0.9.1 writen in TypeScript, in ESM format (with support CommonJS format).
Cookies is a node.js module for getting and setting HTTP(S) cookies. Cookies can be signed to prevent tampering, using Keygrip. It can be used with the built-in node.js HTTP library, or as Connect/Express middleware.
npm install @ts-stack/cookies
Lazy: Since cookie verification against multiple keys could be expensive, cookies are only verified lazily when accessed, not eagerly on each request.
Secure: All cookies are httponly
by default, and cookies sent over SSL are secure
by default. An error will be thrown if you try to send secure cookies over an insecure socket.
Unobtrusive: Signed cookies are stored the same way as unsigned cookies, instead of in an obfuscated signing format. An additional signature cookie is stored for each signed cookie, using a standard naming convention (cookie-name.sig
). This allows other libraries to access the original cookies without having to know the signing mechanism.
Agnostic: This library is optimized for use with Keygrip, but does not require it; you can implement your own signing scheme instead if you like and use this library only to read/write cookies. Factoring the signing into a separate library encourages code reuse and allows you to use the same signing library for other areas where signing is needed, such as in URLs.
Create a new cookie jar for a given request
and response
pair. The request
argument is a Node.js HTTP incoming request object and the response
argument is a Node.js HTTP server response object.
A Keygrip object or an array of keys can optionally be passed as options.keys
to enable cryptographic signing based on SHA1 HMAC, using rotated credentials.
A Boolean can optionally be passed as options.secure
to explicitally specify if the connection is secure, rather than this module examining request
.
Note that since this only saves parameters without any other processing, it is very lightweight. Cookies are only parsed on demand when they are accessed.
Option keys
allowing inbound cookies to be read using cookies.get
and outbound cookies to be set using cookies.set
.
This extracts the cookie with the given name from the Cookie
header in the request. If such a cookie exists, its value is returned. Otherwise, nothing is returned.
{ signed: true }
can optionally be passed as the second parameter options. In this case, a signature cookie (a cookie of same name ending with the .sig
suffix appended) is fetched. If no such cookie exists, nothing is returned.
If the signature cookie does exist, the provided Keygrip object is used to check whether the hash of cookie-name=cookie-value matches that of any registered key:
This sets the given cookie in the response and returns the current context to allow chaining.
If the value is omitted, an outbound header with an expired date is used to delete the cookie.
If the options object is provided, it will be used to generate the outbound cookie header as follows:
maxAge
: a number representing the milliseconds from Date.now()
for expiryexpires
: a Date
object indicating the cookie's expiration date (expires at the end of session by default).path
: a string indicating the path of the cookie (/
by default).domain
: a string indicating the domain of the cookie (no default).secure
: a boolean indicating whether the cookie is only to be sent over HTTPS (false
by default for HTTP, true
by default for HTTPS). Read more about this option below.httpOnly
: a boolean indicating whether the cookie is only to be sent over HTTP(S), and not made available to client JavaScript (true
by default).partitioned
: a boolean indicating whether to partition the cookie in Chrome for the CHIPS Update (false
by default). If this is true, Cookies from embedded sites will be partitioned and only readable from the same top level site from which it was created.priority
: a string indicating the cookie priority. This can be set to 'low'
, 'medium'
, or 'high'
.sameSite
: a boolean or string indicating whether the cookie is a "same site" cookie (false
by default). This can be set to 'strict'
, 'lax'
, 'none'
, or true
(which maps to 'strict'
).signed
: a boolean indicating whether the cookie is to be signed (false
by default). If this is true, another cookie of the same name with the .sig
suffix appended will also be sent, with a 27-byte url-safe base64 SHA1 value representing the hash of cookie-name=cookie-value against the first Keygrip key. This signature key is used to detect tampering the next time a cookie is received.overwrite
: a boolean indicating whether to overwrite previously set cookies of the same name (false
by default). If this is true, all cookies set during the same request with the same name (regardless of path or domain) are filtered out of the Set-Cookie header when setting this cookie.To send a secure cookie, you set a cookie with the secure: true
option.
HTTPS is necessary for secure cookies. When cookies.set
is called with secure: true
and a secure connection is not detected, the cookie will not be set and an error will be thrown.
This module will test each request to see if it's secure by checking:
protocol
property of the request is set to https
, orconnection.encrypted
property of the request is set to true
.If your server is running behind a proxy and you are using secure: true
, you need to configure your server to read the request headers added by your proxy to determine whether the request is using a secure connection.
For more information about working behind proxies, consult the framework you are using:
app.proxy = true
If your Koa or Express server is properly configured, the protocol
property of the request will be set to match the protocol reported by the proxy in the X-Forwarded-Proto
header.
import http from 'http';
import { Cookies } from '@ts-stack/cookies';
// Optionally define keys to sign cookie values
// to prevent client tampering
const keys = ['keyboard cat']
const server = http.createServer((req, res) => {
// Create a cookies object
const cookies = new Cookies(req, res, { keys })
// Get a cookie
const lastVisit = cookies.get('LastVisit', { signed: true })
// Set the cookie to a value
cookies.set('LastVisit', new Date().toISOString(), { signed: true })
if (!lastVisit) {
res.setHeader('Content-Type', 'text/plain')
res.end('Welcome, first time visitor!')
} else {
res.setHeader('Content-Type', 'text/plain')
res.end('Welcome back! Nothing much changed since your last visit at ' + lastVisit + '.')
}
})
server.listen(3000, function () {
console.log('Visit us at http://127.0.0.1:3000/ !')
})
FAQs
Cookies, optionally signed using Keygrip.
The npm package @ts-stack/cookies receives a total of 13,019 weekly downloads. As such, @ts-stack/cookies popularity was classified as popular.
We found that @ts-stack/cookies demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.