1676351602
Forward requests and inject CloudFlare cookies.
curl https://raw.githubusercontent.com/acheong08/ChatGPT-Proxy/main/scripts/run-with-docker.sh | sh
pip install pipenv -U
.pipenv update -d
in this directory, to automatically install the requirements of the proxy.pipenv run proxy
in the base directory, and enjoy it! Uvicorn will provide a high-performance HTTP server for the API service.These options can be configured by setting environment variables using -e KEY="VALUE"
in the docker run
command.
Env | Default | Example | Description |
---|---|---|---|
GPT_PROXY | - | socks5://127.0.0.1:1080 | The proxy of your server. |
GPT_HOST | 0.0.0.0 | 127.0.0.1 | The hostname of your server. |
GPT_PORT | 5000 | 8080 | The port of your server. |
Author: Acheong08
Source Code: https://github.com/acheong08/ChatGPT-Proxy
License: Unlicense license
1671212400
The two most common types of authentication are session cookies and tokens.
Original article source at: https://www.c-sharpcorner.com/
1669438260
To check if a cookie exists in PHP, you need to call the isset()
function on the $_COOKIE
array variable.
For example, suppose you want to check for a cookie named lang
. You need to call the isset()
function inside an if
statement as shown below:
// π check if cookie exists
if (isset($_COOKIE["lang"])) {
print "lang cookie value: " . $_COOKIE["lang"];
} else {
print "lang cookie doesn't exists";
}
Keep in mind that a cookie can only be accessed after the page has been reloaded.
This is because cookies are sent as part of the header response when you request a page.
Checking for the cookie existence immediately after setting it with setcookie()
will cause PHP to return undefined array key warning:
<?php
if (!isset($_COOKIE["lang"])) {
setcookie("lang", "ja");
}
// π Warning: Undefined array key "lang"
// until next request
print $_COOKIE["lang"];
?>
If you want to check for the cookie without reloading, then you need to call the setcookie()
function and set the $_COOKIE
value in the next line.
This way, you can use that cookie without a page reload:
<?php
if (!isset($_COOKIE["lang"])) {
setcookie("lang", "ja");
$_COOKIE["lang"] = "ja";
}
// π prints "ja"
print $_COOKIE["lang"];
?>
By setting the $_COOKIE
key-value pair manually, you tricked the code to think that the cookie is set.
But this may also introduce a bug since your code thinks that the user has the cookie in the first place.
As an alternative, you can add a fallback value as a variable instead:
if (!isset($_COOKIE["lang"])) {
setcookie("lang", "ja");
}
$fallback_lang = "en";
// π if lang not set, prints fallback value
print isset($_COOKIE["lang"]) ? $_COOKIE["lang"] : $fallback_lang;
Using the ternary condition as shown above is considered the right approach because it doesnβt trick the code with a made-up cookie.
Now youβve learned how to check if a cookie exists in PHP. Good job! π
Original article source at: https://sebhastian.com/
1662757080
In today's post we will learn about 5 Popular Node.js Cookies Libraries.
Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides middleware for parsing of cookies.
RFC6265 Cookies and CookieJar for Node.js
It's so easy! Install with npm
or your preferred package manager.
npm install tough-cookie
var tough = require("tough-cookie");
var Cookie = tough.Cookie;
var cookie = Cookie.parse(header);
cookie.value = "somethingdifferent";
header = cookie.toString();
var cookiejar = new tough.CookieJar();
// Asynchronous!
var cookie = await cookiejar.setCookie(
cookie,
"https://currentdomain.example.com/path"
);
var cookies = await cookiejar.getCookies("https://example.com/otherpath");
// Or with callbacks!
cookiejar.setCookie(
cookie,
"https://currentdomain.example.com/path",
function (err, cookie) {
/* ... */
}
);
cookiejar.getCookies("http://example.com/otherpath", function (err, cookies) {
/* ... */
});
Why the name? NPM modules cookie
, cookies
and cookiejar
were already taken.
Add tough-cookie support to axios.
npm install axios tough-cookie axios-cookiejar-support
import axios from 'axios';
import { wrapper } from 'axios-cookiejar-support';
import { CookieJar } from 'tough-cookie';
const jar = new CookieJar();
const client = wrapper(axios.create({ jar }));
await client.get('https://example.com');
See examples for more details.
import type { CookieJar } from 'tough-cookie';
declare module 'axios' {
interface AxiosRequestConfig {
jar?: CookieJar;
}
}
Universal cookies for JavaScript
npm install universal-cookie
or in the browser (global variable UniversalCookie
):
<script crossorigin src="https://unpkg.com/universal-cookie@3/umd/universalCookie.min.js"></script>
constructor([cookieHeader])
Create a cookies context
get(name, [options])
Get a cookie value
HTTP server cookie parsing and serialization.
This is a Node.js module available through the npm registry. Installation is done using the npm install
command:
$ npm install cookie
var cookie = require('cookie');
Parse an HTTP Cookie
header string and returning an object of all cookie name-value pairs. The str
argument is the string representing a Cookie
header value and options
is an optional object containing additional parsing options.
var cookies = cookie.parse('foo=bar; equation=E%3Dmc%5E2');
// { foo: 'bar', equation: 'E=mc^2' }
Signed and unsigned cookies based on Keygrip.
This is a Node.js module available through the npm registry. Installation is done using the npm install
command:
$ npm install cookies
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.
This adds cookie support as a Connect middleware layer for use in Express apps, allowing inbound cookies to be read using req.cookies.get
and outbound cookies to be set using res.cookies.set
.
Thank you for following this article.
React Node.js Video Sharing App Full Tutorial (Redux, JWT, Cookies)
1661270303
gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.
The key features are:
Let's start with an example that shows the sessions API in a nutshell:
import (
"net/http"
"github.com/gorilla/sessions"
)
// Note: Don't store your key in your source code. Pass it via an
// environmental variable, or flag (or both), and don't accidentally commit it
// alongside your code. Ensure your key is sufficiently random - i.e. use Go's
// crypto/rand or securecookie.GenerateRandomKey(32) and persist the result.
var store = sessions.NewCookieStore([]byte(os.Getenv("SESSION_KEY")))
func MyHandler(w http.ResponseWriter, r *http.Request) {
// Get a session. We're ignoring the error resulted from decoding an
// existing session: Get() always returns a session, even if empty.
session, _ := store.Get(r, "session-name")
// Set some session values.
session.Values["foo"] = "bar"
session.Values[42] = 43
// Save it before we write to the response/return from the handler.
err := session.Save(r, w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
First we initialize a session store calling NewCookieStore()
and passing a secret key used to authenticate the session. Inside the handler, we call store.Get()
to retrieve an existing session or create a new one. Then we set some session values in session.Values, which is a map[interface{}]interface{}
. And finally we call session.Save()
to save the session in the response.
More examples are available on the Gorilla website.
Other implementations of the sessions.Store
interface:
Author: gorilla
Source Code: https://github.com/gorilla/sessions
License: BSD-3-Clause license
1660655104
A most easily usable cookie management library in Dart!
1. About
SweetCookieJar
is an open-sourced Dart library.
With SweetCookieJar
, you can easily manage cookie on your application.
SweetCookieJar
is a library that extends the functionality of the official Cookie class. It also works with Responses in the http package, and even if multiple set-cookie
are set in the response header, which is a weak point in the http package, SweetCookieJar
can manage these cookie information very easily!
No more difficult implementation is needed to handle multiple set-cookie
set in response header in Dart. Just pass the Response to the constructor of SweetCookieJar
!
With Dart:
dart pub add sweet_cookie_jar
With Flutter:
flutter pub add sweet_cookie_jar
import 'package:sweet_cookie_jar/sweet_cookie_jar.dart';
import 'package:sweet_cookie_jar/sweet_cookie_jar.dart';
void main() {
// The cookie set in the response header
// will be extracted by the constructor process.
final cookieJar = SweetCookieJar.from(response: response);
if (cookieJar.isEmpty) {
// It means that there is no cookie information
// in the response header.
return;
}
// You can find cookie by name easily.
final cookie = cookieJar.find(name: 'AWSALB');
print(cookie.name);
print(cookie.value);
// Also you can get cookie as JSON format.
print(cookie.toJson());
if (cookie.isExpired) {
// Do something when cookie is expired.
return;
}
}
Copyright (c) 2021, Kato Shinya. All rights reserved.
Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
SweetCookieJar
was designed and implemented by Kato Shinya.
Run this command:
With Dart:
$ dart pub add sweet_cookie_jar
With Flutter:
$ flutter pub add sweet_cookie_jar
This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get
):
dependencies:
sweet_cookie_jar: ^1.1.0
Alternatively, your editor might support dart pub get
or flutter pub get
. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:sweet_cookie_jar/sweet_cookie_jar.dart';
// Copyright (c) 2021, Kato Shinya. All rights reserved.
// Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:http/http.dart';
import 'package:sweet_cookie_jar/sweet_cookie_jar.dart';
class DemoSweetCookieJar {
void main() {
final response = Response.bytes(
[],
200,
headers: {
'set-cookie':
'AWSALB=CGSOoaFEi91n9xSfeeSxoUvs0A/TTQn9/Mbxe8dtkv50cBqJmHTwPw3; Expires=Tue, 14 Dec 2021 02:20:37 GMT; Path=/,AWSALBCORS=OHhxYMU0mU7WOoh+4RH5bxe8d6AytmnHaZNGUBqJmHTwPw3; Expires=Tue, 14 Dec 2021 02:20:37 GMT; Path=/; SameSite=None; Secure,jwt_token=test; Domain=.test; Max-Age=31536000; Path=/; expires=Wed, 07-Dec-2022 02:20:37 GMT; SameSite=lax; Secure,csrf_token=test==; Domain=.test; Max-Age=31536000; Path=/; expires=Wed, 07-Dec-2022 02:20:37 GMT,csrf_token=test==; Domain=.test; Max-Age=31536000; Path=/; expires=Wed, 07-Dec-2022 02:20:37 GMT,wuuid=77be8f46-4'
},
);
final cookieJar = SweetCookieJar.from(response: response);
if (cookieJar.isEmpty) {
// It means that there is no cookie information
// in the response header.
return;
}
final cookie = cookieJar.find(name: 'AWSALB');
print(cookie.name);
print(cookie.value);
print(cookie.toJson());
if (cookie.isExpired) {
// Do something
return;
}
}
}
Download Details:
Author: myConsciousness
Source Code: https://github.com/myConsciousness/sweet-cookie-jar
1660090680
HTTP::Cookie is a ruby library to handle HTTP cookies in a way both compliant with RFCs and compatible with today's major browsers.
It was originally a part of the Mechanize library, separated as an independent library in the hope of serving as a common component that is reusable from any HTTP related piece of software.
The following is an incomplete list of its features:
Its behavior is highly compatible with that of today's major web browsers.
It is based on and conforms to RFC 6265 (the latest standard for the HTTP cookie mechanism) to a high extent, with real world conventions deeply in mind.
It takes eTLD (effective TLD, also known as "Public Suffix") into account just as major browsers do, to reject cookies with an eTLD domain like "org", "co.jp", or "appspot.com". This feature is brought to you by the domain_name gem.
The number of cookies and the size are properly capped so that a cookie store does not get flooded.
It supports the legacy Netscape cookies.txt format for serialization, maximizing the interoperability with other implementations.
It supports the cookies.sqlite format adopted by Mozilla Firefox for backend store database which can be shared among multiple program instances.
It is relatively easy to add a new serialization format or a backend store because of its modular API.
Add this line to your application's Gemfile
:
gem 'http-cookie'
And then execute:
$ bundle
Or install it yourself as:
$ gem install http-cookie
########################
# Client side example 1
########################
# Initialize a cookie jar
jar = HTTP::CookieJar.new
# Load from a file
jar.load(filename) if File.exist?(filename)
# Store received cookies, where uri is the origin of this header
header["Set-Cookie"].each { |value|
jar.parse(value, uri)
}
# ...
# Set the Cookie header value, where uri is the destination URI
header["Cookie"] = HTTP::Cookie.cookie_value(jar.cookies(uri))
# Save to a file
jar.save(filename)
########################
# Client side example 2
########################
# Initialize a cookie jar using a Mozilla compatible SQLite3 backend
jar = HTTP::CookieJar.new(store: :mozilla, filename: 'cookies.sqlite')
# There is no need for load & save in this backend.
# Store received cookies, where uri is the origin of this header
header["Set-Cookie"].each { |value|
jar.parse(value, uri)
}
# ...
# Set the Cookie header value, where uri is the destination URI
header["Cookie"] = HTTP::Cookie.cookie_value(jar.cookies(uri))
########################
# Server side example
########################
# Generate a domain cookie
cookie1 = HTTP::Cookie.new("uid", "u12345", domain: 'example.org',
for_domain: true,
path: '/',
max_age: 7*86400)
# Add it to the Set-Cookie response header
header['Set-Cookie'] = cookie1.set_cookie_value
# Generate a host-only cookie
cookie2 = HTTP::Cookie.new("aid", "a12345", origin: my_url,
path: '/',
max_age: 7*86400)
# Add it to the Set-Cookie response header
header['Set-Cookie'] = cookie2.set_cookie_value
There are several incompatibilities between Mechanize::Cookie/CookieJar and HTTP::Cookie/CookieJar. Below is how to rewrite existing code written for Mechanize::Cookie with equivalent using HTTP::Cookie:
Mechanize::Cookie.parse
The parameter order changed in HTTP::Cookie.parse.
# before
cookies1 = Mechanize::Cookie.parse(uri, set_cookie1)
cookies2 = Mechanize::Cookie.parse(uri, set_cookie2, log)
# after
cookies1 = HTTP::Cookie.parse(set_cookie1, uri_or_url)
cookies2 = HTTP::Cookie.parse(set_cookie2, uri_or_url, logger: log)
# or you can directly store parsed cookies in your jar
jar.parse(set_cookie1, uri_or_url)
jar.parse(set_cookie1, uri_or_url, logger: log)
Mechanize::Cookie#version, #version=
There is no longer a sense of version in the HTTP cookie specification. The only version number ever defined was zero, and there will be no other version defined since the version attribute has been removed in RFC 6265.
Mechanize::Cookie#comment, #comment=
Ditto. The comment attribute has been removed in RFC 6265.
Mechanize::Cookie#set_domain
This method was unintentionally made public. Simply use HTTP::Cookie#domain=.
# before
cookie.set_domain(domain)
# after
cookie.domain = domain
Mechanize::CookieJar#add, #add!
Always use HTTP::CookieJar#add.
# before
jar.add!(cookie1)
jar.add(uri, cookie2)
# after
jar.add(cookie1)
cookie2.origin = uri; jar.add(cookie2) # or specify origin in parse() or new()
Mechanize::CookieJar#clear!
Use HTTP::Cookiejar#clear.
# before
jar.clear!
# after
jar.clear
Mechanize::CookieJar#save_as
Use HTTP::CookieJar#save.
# before
jar.save_as(file)
# after
jar.save(file)
Mechanize::CookieJar#jar
There is no direct access to the internal hash in HTTP::CookieJar since it has introduced an abstract store layer. If you want to tweak the internals of the hash store, try creating a new store class referring to the default store class HTTP::CookieJar::HashStore.
If you desperately need it you can access it by jar.store.instance_variable_get(:@jar)
, but there is no guarantee that it will remain available in the future.
HTTP::Cookie/CookieJar raise runtime errors to help migration, so after replacing the class names, try running your test code once to find out how to fix your code base.
The YAML serialization format has changed, and HTTP::CookieJar#load cannot import what is written in a YAML file saved by Mechanize::CookieJar#save_as. HTTP::CookieJar#load will not raise an exception if an incompatible YAML file is given, but the content is silently ignored.
Note that there is (obviously) no forward compatibillity with this. Trying to load a YAML file saved by HTTP::CookieJar with Mechanize::CookieJar will fail in runtime error.
On the other hand, there has been (and will ever be) no change in the cookies.txt format, so use it instead if compatibility is significant.
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)Author: Sparklemotion
Source Code: https://github.com/sparklemotion/http-cookie
License: MIT license
1660083240
Faraday middleware to manage client-side cookies
This gem is a piece of Faraday middleware that adds client-side Cookies management, using http-cookie gem.
Add this line to your application's Gemfile:
gem 'faraday-cookie_jar'
And then execute:
$ bundle
Or install it yourself as:
$ gem install faraday-cookie_jar
require 'faraday-cookie_jar'
conn = Faraday.new(:url => "http://example.com") do |builder|
builder.use :cookie_jar
builder.adapter Faraday.default_adapter
end
conn.get "/foo" # gets cookie
conn.get "/bar" # sends cookie
Author: Miyagawa
Source Code: https://github.com/miyagawa/faraday-cookie_jar
License: MIT license
1658298180
All sites owned by EU citizens or targeted towards EU citizens must comply with a crazy EU law. This law requires a dialog to be displayed to inform the users of your websites how cookies are being used. You can read more info on the legislation on the site of the European Commission.
This package provides an easily configurable view to display the message. Also included is JavaScript code to set a cookie when a user agrees with the cookie policy. The package will not display the dialog when that cookie has been set.
Spatie is a web design agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.
You can install the package via composer:
composer require spatie/laravel-cookie-consent
The package will automatically register itself.
Optionally you can publish the config-file:
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-config"
This is the contents of the published config-file:
return [
/*
* Use this setting to enable the cookie consent dialog.
*/
'enabled' => env('COOKIE_CONSENT_ENABLED', true),
/*
* The name of the cookie in which we store if the user
* has agreed to accept the conditions.
*/
'cookie_name' => 'laravel_cookie_consent',
/*
* Set the cookie duration in days. Default is 365 * 20.
*/
'cookie_lifetime' => 365 * 20,
];
The cookie domain is set by the 'domain' key in config/session.php, make sure you add a value in your .env for SESSION_DOMAIN. If you are using a domain with a port in the url such as 'localhost:3000', this package will not work until you do so.
To display the dialog all you have to do is include this view in your template:
//in your blade template
@include('cookie-consent::index')
This will render the following dialog that, when styled, will look very much like this one.
The default styling provided by this package uses TailwindCSS v2 to provide a floating banner at the bottom of the page.
When the user clicks "Allow cookies" a laravel_cookie_consent
cookie will be set and the dialog will be removed from the DOM. On the next request, Laravel will notice that the laravel_cookie_consent
has been set and will not display the dialog again
If you want to modify the text shown in the dialog you can publish the lang-files with this command:
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-translations"
This will publish this file to resources/lang/vendor/cookie-consent/en/texts.php
.
return [
'message' => 'Please be informed that this site uses cookies.',
'agree' => 'Allow cookies',
];
If you want to translate the values to, for example, French, just copy that file over to resources/lang/vendor/cookie-consent/fr/texts.php
and fill in the French translations.
If you need full control over the contents of the dialog. You can publish the views of the package:
php artisan vendor:publish --provider="Spatie\CookieConsent\CookieConsentServiceProvider" --tag="cookie-consent-views"
This will copy the index
and dialogContents
view files over to resources/views/vendor/cookie-consent
. You probably only want to modify the dialogContents
view. If you need to modify the JavaScript code of this package you can do so in the index
view file.
Instead of including cookie-consent::index
in your view you could opt to add the Spatie\CookieConsent\CookieConsentMiddleware
to your kernel:
// app/Http/Kernel.php
class Kernel extends HttpKernel
{
protected $middleware = [
// ...
\Spatie\CookieConsent\CookieConsentMiddleware::class,
];
// ...
}
This will automatically add cookie-consent::index
to the content of your response right before the closing body tag.
The legislation is pretty very vague on how to display the warning, which texts are necessary, and what options you need to provide. This package will go a long way towards compliance, but if you want to be 100% sure that your website is ok, you should consult a legal expert.
Please see CHANGELOG for more information what has changed recently.
composer test
We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.
Please see CONTRIBUTING for details.
If you discover any security-related issues, please email freek@spatie.be instead of using the issue tracker.
Author: Spatie
Source Code: https://github.com/spatie/laravel-cookie-consent
License: MIT license
1658061240
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.
This is a Node.js module available through the npm registry. Installation is done using the npm install
command:
$ npm install 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.
This adds cookie support as a Connect middleware layer for use in Express apps, allowing inbound cookies to be read using req.cookies.get
and outbound cookies to be set using res.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).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.
var http = require('http')
var Cookies = require('cookies')
// Optionally define keys to sign cookie values
// to prevent client tampering
var keys = ['keyboard cat']
var server = http.createServer(function (req, res) {
// Create a cookies object
var cookies = new Cookies(req, res, { keys: keys })
// Get a cookie
var 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/ !')
})
Author: pillarjs
Source Code: https://github.com/pillarjs/cookies
License: MIT license
1656085860
Cake3 CookieAuth
A simple Cake3 plugin to authenticate users with Cookies. This plugin is based on the awesome plugin FriendsOfCake/Authenticate but with a different setup.
Run : composer require xety/cake3-cookieauth:1.*
Or add it in your composer.json
:
"require": {
"xety/cake3-cookieauth": "1.*"
},
'Xety/Cake3CookieAuth.Cookie' => [
'cookie' => [
'name' => 'CookieAuth'
]
]
All others configuration option can be found on the official CakePHP documentation.
In your config/bootstrap.php
add :
Plugin::load('Xety/Cake3CookieAuth');
In your AppController
:
public $components = [
'Cookie',
'Auth' => [
'authenticate' => [
'Form',
'Xety/Cake3CookieAuth.Cookie'
]
]
];
In your AppController
, in the beforeFilter
action :
public function beforeFilter(Event $event) {
//Automaticaly Login.
if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
} else {
$this->Cookie->delete('CookieAuth');
}
}
}
//If you want to update some fields, like the last_login_date, or last_login_ip, just do :
public function beforeFilter(Event $event) {
//Automaticaly Login.
if (!$this->Auth->user() && $this->Cookie->read('CookieAuth')) {
$this->loadModel('Users');
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
$user = $this->Users->newEntity($user);
$user->isNew(false);
//Last login date
$user->last_login = new Time();
//Last login IP
$user->last_login_ip = $this->request->clientIp();
//etc...
$this->Users->save($user);
} else {
$this->Cookie->delete('CookieAuth');
}
}
}
In your login
action, after $this->Auth->setUser($user);
:
//It will write Cookie without RememberMe checkbox
$this->Cookie->configKey('CookieAuth', [
'expires' => '+1 year',
'httpOnly' => true
]);
$this->Cookie->write('CookieAuth', [
'username' => $this->request->data('username'),
'password' => $this->request->data('password')
]);
//If you want use a RememberMe checkbox in your form :
//In your view
echo $this->Form->checkbox('remember_me');
//In the login action :
if($this->request->data('remember_me')) {
$this->Cookie->configKey('CookieAuth', [
'expires' => '+1 year',
'httpOnly' => true
]);
$this->Cookie->write('CookieAuth', [
'username' => $this->request->data('username'),
'password' => $this->request->data('password')
]);
}
Follow this guide to contribute
Author: Xety
Source Code: https://github.com/Xety/Cake3-CookieAuth
License: MIT license
1655856960
CookieJar
Simple robust cookie library
class to determine matching qualities of a cookie
Properties
It turns input into a Cookie (singleton if given a Cookie), the request_domain
argument is used to default the domain if it is not explicit in the cookie string, the request_path
argument is used to set the path if it is not explicit in a cookie String.
Explicit domains/paths will cascade, implied domains/paths must exactly match (see http://en.wikipedia.org/wiki/HTTP_cookie#Domain_and_Pat).
Properties
Methods
String toString()
- the set-cookie: string for this cookieString toValueString()
- the cookie: string for this cookieCookie parse(cookiestr, request_domain, request_path)
- parses the string onto this cookie or a new one if called directlyBoolean matches(access_info)
- returns true if the access_info allows retrieval of this cookieBoolean collidesWith(cookie)
- returns true if the cookies cannot exist in the same space (domain and path match)class to hold numerous cookies from multiple domains correctly
Methods
Cookie setCookie(cookie, request_domain, request_path)
- modify (or add if not already-existing) a cookie to the jarCookie[] setCookies(cookiestr_or_list, request_domain, request_path)
- modify (or add if not already-existing) a large number of cookies to the jarCookie getCookie(cookie_name,access_info)
- get a cookie with the name and access_info matchingCookie[] getCookies(access_info)
- grab all cookies matching this access_infoAuthor: bmeck
Source Code: https://github.com/bmeck/node-cookiejar
License: MIT license
1646266020
Google Chrome blocks third-party cookies and that could potentially break websites and GSuite addons that rely on cookies for communication between different windows. This tutorial describes how you can selectively unblock third-party cookies in Chrome for using Google addons inside Google Sheets, Google Forms, Docs and Slides.
1643118000
Everything you need to know about Client-side Storage.
Web storage, sometimes known as DOM storage (Document Object Model storage), provides web application software methods and protocols used for storing data in a web browser.
Web storage is being standardized by the World Wide Web Consortium (W3C). It was originally part of the HTML5 specification, but is now in a separate specification.
Modern websites and web applications these days are becoming smarter than before and to achieve such smartness, the data storage system plays a very crucial role. Be it storing visitors' data & settings or any kind of information, web-storage is a breakthrough in the history of web applications. It offers a very basic need of storing persistent data in the browser itself which has literally spurred up its application from game-changing novelty to must-have features.
Usually, this kind of data doesn't need a well-organized backend database. The purpose of the data varies as per the website/webapp requirements. Different pages of the same website need to share data among themselves to behave alike and perfectly. This sharing of data among windows/tabs is very common these days and most of the sites or web apps use it for various jobs like User Authentication, Personalization (showing different views to a new visitor and on subsequent visits), Tracking user behavior, etc.
Before HTML5, storing application level data was possible only using cookies. Cookies can store up to 4KB of data, including the bytes consumed by the cookie name. This domain-specific data is sent along with every browser request. With the advent of HTML5, it's much easier now to store structured data on the client-side securely and faster than ever. HTML5 introduced the concept of Web Storage. Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity. HTML5 introduces two such web storage mechanisms: LocalStorage and SessionStorage. There are so many limitations in using cookies which can now be overcome using web storage.
There's no term as "Perfectly Secured Persistent Storage" available in the browsers as any type of storage system( persistent or non-persistent) can be manually tweaked by the end-user(assuming she knows a bit of geeky stuff :P).
The two mechanisms within Web Storage are as follows:
sessionStorage
maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).localStorage
does the same thing, but persists even when the browser is closed and reopened.Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)
The Web Storage API extends the
Window
object with two new properties βWindow.sessionStorage
andWindow.localStorage
β which provide access to the current domain's session and local Storage objects respectively, and aWindow.onstorage
event handler that fires when a storage area changes (e.g. a new item is stored.)
The storage event is fired on a document's Window object when a storage area changes.
![]() IE / Edge | ![]() Firefox | ![]() Chrome | ![]() Safari | ![]() Opera |
---|---|---|---|---|
IE8+, Edge12+ | 3.5+ | 4+ | 4+ | 11.5+ |
Following are various storage techniques which HTML5 storage provides. Each technique has its own pros and cons.
An
HTTP cookie
(web cookie, browser cookie) is a small piece of data that a server sends to the user's web browser. The browser may store it and send it back with the next request to the same server. Typically, it's used to tell if two requests came from the same browser β keeping a user logged-in, for example. It remembers stateful information for the stateless HTTP protocol.
Pros:
Cons:
The 4K limit is for the entire cookie, including name, value, expiry date etc. To support most browsers, keep the name under 4000 bytes, and the overall cookie size under 4093 bytes.
The data is sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - increasing the amount of traffic between client and server.
Typically, the following are allowed:
API
Read
Reading all cookies accessible from the domain
var allCookies = document.cookie;
Write
Writing a new cookie on a domain
document.cookie = newCookie;
As mentioned in the mdn docs, any of the following cookie attribute values can optionally follow the key-value pair, specifying the cookie to set/update, and preceded by a semi-colon separator:
;path=path
- (e.g., '/', '/mydir') If not specified, defaults to the current path of the current document location.
;domain=domain
- (e.g., 'example.com' or 'subdomain.example.com').
;max-age=max-age-in-seconds
- (e.g., 60*60*24*365 or 31536000 for a year)
;expires=date-in-GMTString-format
- If not specified it will expire at the end of a session.
;secure
- Cookie to only be transmitted over secure protocol as https
. Before Chrome 52
, this flag could appear with cookies from http
domains.
Resources - more on cookies
The read-only
localStorage
property allows you to access aStorage
object for theDocument
's origin; the stored data is saved across browser sessions.localStorage
is similar tosessionStorage
, except that while data stored inlocalStorage
has no expiration time, data stored insessionStorage
gets cleared when the page session ends β that is, when the page is closed.
Pros:
If you look at the Mozilla source code it can be seen that 5120KB (5MB which equals 2.5 Million characters on Chrome) is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 4KB cookie.
The data is not sent back to the server for every HTTP request (HTML, images, JavaScript, CSS, etc) - reducing the amount of traffic between client and server.
The data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
Structured data can be stored but it has to be stringified before storing.
Simple API to save, update, and delete data.
Cons:
It works on same-origin policy. So, data stored will only be available on the same origin.
It stores everything as a string.
API
setItem
setItem | Description |
---|---|
method | localStorage.setItem(key, value) |
params | key(String/Number), value(Number/String), though it accepts other types, the value is always stored as a string, so, stringifying data before storing is preferred and the best way to avoid errors while reading |
description | adds the key to the storage with the value, or update the key's value if it already exists. |
example | localStorage.setItem('test', document.getElementById('js-btn').value); |
getItem
getItem | Description |
---|---|
method | localStorage.getItem(key) |
params | key(String/Number) |
description | returns the value of the key passed. |
example | localStorage.getItem('test') |
removeItem
removeItem | Description |
---|---|
method | localStorage.removeItem(key) |
params | key(String/Number) |
description | removes the key from the storage. |
example | localStorage.removeItem('test') |
clear
clear | Description |
---|---|
method | localStorage.clear() |
params | None |
description | empties all the keys out of the storage. |
example | localStorage.clear() |
key
key | Description |
---|---|
method | localStorage.key(n) |
params | n(a Number) |
description | returns the name of the nth key in the storage. |
example | localStorage.key(0) |
length
length | Description |
---|---|
property | localStorage.length |
description | returns the length of all the keys |
example | localStorage.length |
Resources - more on localStorage
The
sessionStorage
property allows you to access a sessionStorage
object for the current origin. sessionStorage is similar toWindow.localStorage
, the only difference is while data stored in localStorage has no expiration set, data stored in sessionStorage gets cleared when the page session ends. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated, which differs from how session cookies work.
Pros:
Data can only be saved per window (or tab in browsers like Chrome and Firefox). Data saved is available for the current page, as well as for the future visits to the site on the same window. Once the window is closed, the storage is deleted.
Cons:
The data is available only inside the window/tab in which it was set.
The data is non-persistent i.e. it will be lost once the window/tab is closed.
Like localStorage
, it also works on same-origin policy. So, data stored on one protocol/domain/port will not be available for different protocol/domain/port.
API
setItem
setItem | Description |
---|---|
method | sessionStorage.setItem(key, value) |
params | key(String/Number), value(Number/String), though it accepts other types, the value is always stored as a string, so, stringifying data before storing is preferred and the best way to avoid errors while reading |
description | adds the key to the storage with the value, or update the key's value if it already exists. |
example | sessionStorage.setItem('test', document.getElementById('js-btn').value); |
getItem
getItem | Description |
---|---|
method | sessionStorage.getItem(key) |
params | key(String/Number) |
description | returns the value of the key passed. |
example | sessionStorage.getItem('test') |
removeItem
removeItem | Description |
---|---|
method | sessionStorage.removeItem(key) |
params | key(String/Number) |
description | removes the key from the storage. |
example | sessionStorage.removeItem('test') |
clear
clear | Description |
---|---|
method | sessionStorage.clear() |
params | None |
description | empties all the keys out of the storage. |
example | sessionStorage.clear() |
key
key | Description |
---|---|
method | sessionStorage.key(n) |
params | n(a Number) |
description | returns the name of the nth key in the storage. |
example | sessionStorage.key(0) |
length
length | Description |
---|---|
property | sessionStorage.length |
description | returns the length of all the keys |
example | sessionStorage.length |
Resources - more on sessionStorage
Web Storage | cookies | localStorage | sessionStorage |
---|---|---|---|
Size limit | Max 4kb (~2K chars) | Max 5mb (~2M chars) | Max 5mb (~2M chars) |
Data Storage | FileSytem | FileSytem | FileSytem |
Payload | In every HTTP req | Nothing | Nothing |
API | Fair | Simple | Simple |
Persistent | Yes | Yes | No |
Data Format | String | String | String |
Same-origin | Yes | Yes | Yes |
Cross-origin | No | No | No |
Browser Sipport | All | IE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+ | IE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+ |
Size limits info | limit | limit | limit |
One very interesting API, PostMessage is not a web-storage technique but it's the most efficient and reliable way of communicating between
cross-origin
browser windows/tabs. Along with web-storage APIs, it overcomes the web-storage restrictions of cross-origin.
Pros:
Safely enables cross-origin policy communication.
As a data point, the WebKit implementation (used by Safari and Chrome) doesn't currently enforce any limits (other than those imposed by running out of memory).
Cons:
Need to open a window from the current window and only then can communicate as long as you keep the windows open.
Security concerns - Sending strings via postMessage is that you will pick up other postMessage events published by other JavaScript plugins, so be sure to implement a targetOrigin and a sanity check for the data being passed on to the messages listener.
API:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow - A reference to another window; such a reference may be obtained, for example, using the contentWindow
property of an iframe
element, the object returned by window.open, or by named or numeric index on Window.frames, if you're trying to start the communication from iframe to parent window then parent is also a valid reference
message - Data to be sent to the other window. The data is serialized using the structured clone algorithm. This means you can pass a broad variety of data objects safely to the destination window without having to serialize them yourself. [1]
targetOrigin - Specifies what the origin of otherWindow
must be for the event to be dispatched, either as the literal string "*"
(indicating no preference) or as a URI. If at the time the event is scheduled to be dispatched the scheme, hostname, or port of otherWindow's document does not match that provided in targetOrigin
, the event will not be dispatched; only if all three match will the event be dispatched. This mechanism provides control over where messages are sent; for example, if postMessage()
was used to transmit a password, it would be absolutely critical that this argument be a URI whose origin is the same as the intended receiver of the message containing the password, to prevent interception of the password by a malicious third party. Always provide a specific targetOrigin, not *
, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site.
transfer(Optional) - Is a sequence of Transferable objects that are transferred with the message. The ownership of these objects is given to the destination side and they are no longer usable on the sending side.
Security concerns
If you do not expect to receive messages from other sites, do not add any event listeners for message
events. This is a completely foolproof way to avoid security problems.
If you do expect to receive messages from other sites, always verify the sender's identity using the origin
and possibly source
properties. Any window (including, for example, http://evil.example.com)
can send a message to any other window, and you have no guarantees that an unknown sender will not send malicious messages. Having verified identity, however, you still should always verify the syntax of the received message. Otherwise, a security hole in the site you trusted to send only trusted messages could then open a cross-site scripting hole in your site.
Always specify an exact target origin, not *
, when you use postMessage to send data to other windows. A malicious site can change the location of the window without your knowledge, and therefore it can intercept the data sent using postMessage
.
Resources - more on postMessage:
How to store data that works Cross-Origin too?
A combination of
postMessage and localStorage / sessionStorage
Using postMessage to communicate between multiple tabs and at the same time using localStorage/sessionStorage in all the newly opened tabs/windows to persist data being passed. Data will be persisted as long as the tabs/windows remain open in case of sessionStorage and in the case of localStorage unless the data is deleted by the system or manually flushing it using dev tools. So, even if the opener tab/window gets closed, the opened tabs/windows will have the entire data even after getting refreshed.
Please ensure your pull request adheres to the following guidelines:
[List Name](link)
Author: Softvar
Source Code: https://github.com/softvar/awesome-web-storage
License:
1643080140
Cookies.js
Cookies.js is a small client-side javascript library that makes managing cookies easy.
Features
Browser Compatibility
Getting the Library
Use in CommonJS/Node Environments Without window
A Note About Encoding
API Reference
The following browsers have passed all of the automated Cookies.js tests:
npm install cookies-js
bower install cookies-js
window
In environments where there is no native window
object, Cookies.js will export a factory method that accepts a window
instance. For example, using jsdom, you might do something like:
var jsdom = require('jsdom');
var window = jsdom.jsdom().parentWindow;
var Cookies = require('cookies-js')(window);
// Use Cookies as you normally would
RFC6265 defines a strict set of allowed characters for cookie keys and values. In order to effectively allow any character to be used in a key or value, Cookies.js will URI encode disallowed characters in their UTF-8 representation. As such, Cookies.js also expects cookie keys and values to already be URI encoded in a UTF-8 representation when it accesses cookies. Keep this in mind when working with cookies on the server side.
Do not use HttpUtility.UrlEncode and HttpUtility.UrlDecode on cookie keys or values. HttpUtility.UrlEncode
will improperly escape space characters to '+'
and lower case every escape sequence. HttpUtility.UrlDecode
will improperly unescape every '+'
to a space character. Instead, use System.Uri.EscapeDataString and System.Uri.UnescapeDataString.
Methods
Cookies.set(key, value [, options])
Cookies.get(key)
Cookies.expire(key [, options])
Properties
Cookies.enabled
Cookies.defaults
Alias: Cookies(key, value [, options])
Sets a cookie in the document. If the cookie does not already exist, it will be created. Returns the Cookies
object.
Option | Description | Default |
---|---|---|
path | A string value of the path of the cookie | "/" |
domain | A string value of the domain of the cookie | undefined |
expires | A number (of seconds), a date parsable string, or a Date object of when the cookie will expire | undefined |
secure | A boolean value of whether or not the cookie should only be available over SSL | false |
A default value for any option may be set in the Cookies.defaults
object.
Example Usage
// Setting a cookie value
Cookies.set('key', 'value');
// Chaining sets together
Cookies.set('key', 'value').set('hello', 'world');
// Setting cookies with additional options
Cookies.set('key', 'value', { domain: 'www.example.com', secure: true });
// Setting cookies with expiration values
Cookies.set('key', 'value', { expires: 600 }); // Expires in 10 minutes
Cookies.set('key', 'value', { expires: '01/01/2012' });
Cookies.set('key', 'value', { expires: new Date(2012, 0, 1) });
Cookies.set('key', 'value', { expires: Infinity });
// Using the alias
Cookies('key', 'value', { secure: true });
Alias: Cookies(key)
Returns the value of the most locally scoped cookie with the specified key.
Example Usage
// First set a cookie
Cookies.set('key', 'value');
// Get the cookie value
Cookies.get('key'); // "value"
// Using the alias
Cookies('key'); // "value"
Alias: Cookies(key, undefined
[, options])
Expires a cookie, removing it from the document. Returns the Cookies
object.
Option | Description | Default |
---|---|---|
path | A string value of the path of the cookie | "/" |
domain | A string value of the domain of the cookie | undefined |
A default value for any option may be set in the Cookies.defaults
object.
Example Usage
// First set a cookie and get its value
Cookies.set('key', 'value').get('key'); // "value"
// Expire the cookie and try to get its value
Cookies.expire('key').get('key'); // undefined
// Using the alias
Cookies('key', undefined);
A boolean value of whether or not the browser has cookies enabled.
Example Usage
if (Cookies.enabled) {
Cookies.set('key', 'value');
}
An object representing default options to be used when setting and expiring cookie values.
Option | Description | Default |
---|---|---|
path | A string value of the path of the cookie | "/" |
domain | A string value of the domain of the cookie | undefined |
expires | A number (of seconds), a date parsable string, or a Date object of when the cookie will expire | undefined |
secure | A boolean value of whether or not the cookie should only be available over SSL | false |
Example Usage
Cookies.defaults = {
path: '/',
secure: true
};
Cookies.set('key', 'value'); // Will be secure and have a path of '/'
Cookies.expire('key'); // Will expire the cookie with a path of '/'
Author: ScottHamper
Source Code: https://github.com/ScottHamper/Cookies
License: Unlicense License