Sheldon  Grant

Sheldon Grant

1676351602

ChatGPT-Proxy: Forward Requests and inject Cloudflare Cookies

ChatGPT-Proxy

Forward requests and inject CloudFlare cookies.

Installation

One-click scripts

  • With Docker: curl https://raw.githubusercontent.com/acheong08/ChatGPT-Proxy/main/scripts/run-with-docker.sh | sh

Simple steps

  1. Clone the repository
  2. Check if Pipenv is installed. If not, run pip install pipenv -U.
  3. Then, run pipenv update -d in this directory, to automatically install the requirements of the proxy.
  4. Run pipenv run proxy in the base directory, and enjoy it! Uvicorn will provide a high-performance HTTP server for the API service.

Options

These options can be configured by setting environment variables using -e KEY="VALUE" in the docker run command.

EnvDefaultExampleDescription
GPT_PROXY-socks5://127.0.0.1:1080The proxy of your server.
GPT_HOST0.0.0.0127.0.0.1The hostname of your server.
GPT_PORT50008080The port of your server.

Download Details:

Author: Acheong08
Source Code: https://github.com/acheong08/ChatGPT-Proxy 
License: Unlicense license

#chatgpt #python #cloudflare #cookies 

ChatGPT-Proxy: Forward Requests and inject Cloudflare Cookies
Bongani  Ngema

Bongani Ngema

1671212400

Difference between: Session Cookies Vs Tokens

The two most common types of authentication are session cookies and tokens.

Session Cookies

  • Session Cookies are small data stored both on the server and the client.
  • The server often keeps track of sessions in a database or memory.
  • A browser controls cookies on the client side. They're included with every request.
  • Session cookies are stateful.
  • Each session has a unique ID that the server uses to identify the current user and all the information related to that user.
  • Cookies allow a domain and its subdomains to exchange information.
  • Sharing cookie information with another domain is not possible.
  • You can use the "HttpOnly" setting to prevent JavaScript tampering on client sites.
  • Remember that only HTTPS connections are secure for cookies. The "Secure" flag can be used for this reason. It ensures that cookies will be sent only if the connection type is HTTPS.

Tokens

  • In essence, tokens are a collection of letters and numbers.
  • Tokens have no state. It implies that no information about the token needs to be stored on the server.
  • The tokens stand alone. This signifies that the token has all the data needed for server-side verification.
  • Since no database searches are necessary, they are appropriate for API authentication.
  • Tokens are incredibly adaptable and work with multiple platforms.
  • Additionally, there is nothing like domain restriction. Tokens can be transferred between various domains. Because they are self-contained, they are larger in size than cookies.

Original article source at: https://www.c-sharpcorner.com/

#cookies #tokens 

Difference between: Session Cookies Vs Tokens

How to Check If A Cookie Exists in PHP

Check if a cookie exists in PHP

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/

#php #cookies 

How to Check If A Cookie Exists in PHP

5 Popular Node.js Cookies Libraries

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.

1 - Tough-cookie

RFC6265 Cookies and CookieJar for Node.js

Installation

It's so easy! Install with npm or your preferred package manager.

npm install tough-cookie

Synopsis

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.

View on Github

2 - Axios-cookiejar-support

Add tough-cookie support to axios.

Install

npm install axios tough-cookie axios-cookiejar-support

Usage

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.

Extended Request Config

import type { CookieJar } from 'tough-cookie';

declare module 'axios' {
  interface AxiosRequestConfig {
    jar?: CookieJar;
  }
}

View on Github

3 - Universal-cookie

Universal cookies for JavaScript

Getting started

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>

API - Cookies class

constructor([cookieHeader])

Create a cookies context

  • cookieHeader (string|object): specify the cookie header or object

get(name, [options])

Get a cookie value

  • name (string): cookie name
  • options (object):
    • doNotParse (boolean): do not convert the cookie into an object no matter what

View on Github

4 - Cookie

HTTP server cookie parsing and serialization.

Installation

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install cookie

API

var cookie = require('cookie');

cookie.parse(str, options)

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' }

View on Github

5 - Cookies

Signed and unsigned cookies based on Keygrip.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install cookies

API

new Cookies(request, response [, options])

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.

Cookies.express(keys)

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.

View on Github

Thank you for following this article. 

Related videos:

React Node.js Video Sharing App Full Tutorial (Redux, JWT, Cookies)

#node #cookies 

5 Popular Node.js Cookies Libraries

Package Gorilla/sessions Provides Cookie, Filesystem Sessions

sessions  

gorilla/sessions provides cookie and filesystem sessions and infrastructure for custom session backends.

The key features are:

  • Simple API: use it as an easy way to set signed (and optionally encrypted) cookies.
  • Built-in backends to store sessions in cookies or the filesystem.
  • Flash messages: session values that last until read.
  • Convenient way to switch session persistency (aka "remember me") and set other attributes.
  • Mechanism to rotate authentication and encryption keys.
  • Multiple sessions per request, even using different backends.
  • Interfaces and infrastructure for custom session backends: sessions from different stores can be retrieved and batch-saved using a common API.

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.

Store Implementations

Other implementations of the sessions.Store interface:

Download Details:

Author: gorilla
Source Code: https://github.com/gorilla/sessions 
License: BSD-3-Clause license

#go #golang #cookies 

Package Gorilla/sessions Provides Cookie, Filesystem Sessions

A Most Easily Usable Cookie Management Library in Dart

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!

1.1. Introduction

1.1.1. Install Library

With Dart:

 dart pub add sweet_cookie_jar

With Flutter:

 flutter pub add sweet_cookie_jar

1.1.2. Import It

import 'package:sweet_cookie_jar/sweet_cookie_jar.dart';

1.1.3. Use SweetCookieJar

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;
    }
}

1.2. License

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.

1.3. More Information

SweetCookieJar was designed and implemented by Kato Shinya.

Use this package as a library

Depend on it

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.

Import it

Now in your Dart code, you can use:

import 'package:sweet_cookie_jar/sweet_cookie_jar.dart'; 

example/example.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

#dart #android #cookies 

A Most Easily Usable Cookie Management Library in Dart
Royce  Reinger

Royce Reinger

1660090680

Http-cookie: A Ruby Library to Handle HTTP Cookies

HTTP::Cookie

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.

Installation

Add this line to your application's Gemfile:

gem 'http-cookie'

And then execute:

$ bundle

Or install it yourself as:

$ gem install http-cookie

Usage

########################
# 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

Incompatibilities with Mechanize::Cookie/CookieJar

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.

File formats

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.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Download Details:

Author: Sparklemotion
Source Code: https://github.com/sparklemotion/http-cookie 
License: MIT license

#ruby #http #cookies 

Http-cookie: A Ruby Library to Handle HTTP Cookies
Royce  Reinger

Royce Reinger

1660083240

Faraday-cookie_jar: Client-side Cookie Management for Faraday

Faraday::CookieJar

Faraday middleware to manage client-side cookies

Description

This gem is a piece of Faraday middleware that adds client-side Cookies management, using http-cookie gem.

Installation

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

Usage

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

Download Details:

Author: Miyagawa
Source Code: https://github.com/miyagawa/faraday-cookie_jar 
License: MIT license

#ruby #cookies #client #side 

Faraday-cookie_jar: Client-side Cookie Management for Faraday
Rupert  Beatty

Rupert Beatty

1658298180

Make Your Laravel App Comply with The Crazy EU Cookie Law

Make your Laravel app comply with the crazy EU cookie law

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.

Installation

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.

Usage

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.

dialog

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

Customising the dialog texts

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.

Customising the dialog contents

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.

Using the middleware

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.

Notice

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.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Support us

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.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security-related issues, please email freek@spatie.be instead of using the issue tracker.

Credits

Author: Spatie
Source Code: https://github.com/spatie/laravel-cookie-consent 
License: MIT license

#laravel #javascript #php #cookies 

Make Your Laravel App Comply with The Crazy EU Cookie Law
Gordon  Taylor

Gordon Taylor

1658061240

Pillarjs/cookies: Signed and unsigned cookies based on Keygrip

Cookies    

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.

Install

This is a Node.js module available through the npm registry. Installation is done using the npm install command:

$ npm install cookies

Features

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.

API

new Cookies(request, response [, options])

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.

Cookies.express(keys)

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.

cookies.get(name [, options])

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:

  • If the signature cookie hash matches the first key, the original cookie value is returned.
  • If the signature cookie hash matches any other key, the original cookie value is returned AND an outbound header is set to update the signature cookie's value to the hash of the first key. This enables automatic freshening of signature cookies that have become stale due to key rotation.
  • If the signature cookie hash does not match any key, nothing is returned, and an outbound header with an expired date is used to delete the cookie.

cookies.set(name [, values [, options]])

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 expiry
  • expires: 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.

Secure cookies

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:

  • if the protocol property of the request is set to https, or
  • if the connection.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:

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.

Example

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

#javascript #node #cookies 

Pillarjs/cookies: Signed and unsigned cookies based on Keygrip

Simple Cake 3 Plugin to Automatically Authenticate Users with Cookies

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. 

Requirements

  • CakePHP 3.X

Installation

Run : composer require xety/cake3-cookieauth:1.* Or add it in your composer.json:

"require": {
    "xety/cake3-cookieauth": "1.*"
},

Configuration

'Xety/Cake3CookieAuth.Cookie' => [
    'cookie' => [
        'name' => 'CookieAuth'
    ]
]

All others configuration option can be found on the official CakePHP documentation.

Usage

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')
    ]);
}

Contribute

Follow this guide to contribute

Author: Xety
Source Code: https://github.com/Xety/Cake3-CookieAuth 
License: MIT license

#php #cookies #cakephp 

Simple Cake 3 Plugin to Automatically Authenticate Users with Cookies

Node-cookiejar: Simple Cookie Library for Node (not Bound to Request)

CookieJar

Simple robust cookie library

Exports

CookieAccessInfo(domain,path,secure,script)

class to determine matching qualities of a cookie

Properties

  • String domain - domain to match
  • String path - path to match
  • Boolean secure - access is secure (ssl generally)
  • Boolean script - access is from a script

Cookie(cookiestr_or_cookie, request_domain, request_path)

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

  • String name - name of the cookie
  • String value - string associated with the cookie
  • String domain - domain to match (on a cookie a '.' at the start means a wildcard matching anything ending in the rest)
  • Boolean explicit_domain - if the domain was explicitly set via the cookie string
  • String path - base path to match (matches any path starting with this '/' is root)
  • Boolean explicit_path - if the path was explicitly set via the cookie string
  • Boolean noscript - if it should be kept from scripts
  • Boolean secure - should it only be transmitted over secure means
  • Number expiration_date - number of millis since 1970 at which this should be removed

Methods

  • String toString() - the set-cookie: string for this cookie
  • String toValueString() - the cookie: string for this cookie
  • Cookie parse(cookiestr, request_domain, request_path) - parses the string onto this cookie or a new one if called directly
  • Boolean matches(access_info) - returns true if the access_info allows retrieval of this cookie
  • Boolean collidesWith(cookie) - returns true if the cookies cannot exist in the same space (domain and path match)

CookieJar()

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 jar
  • Cookie[] setCookies(cookiestr_or_list, request_domain, request_path) - modify (or add if not already-existing) a large number of cookies to the jar
  • Cookie getCookie(cookie_name,access_info) - get a cookie with the name and access_info matching
  • Cookie[] getCookies(access_info) - grab all cookies matching this access_info

Author: bmeck
Source Code: https://github.com/bmeck/node-cookiejar 
License: MIT license

#node #cookies #javascript 

Node-cookiejar: Simple Cookie Library for Node (not Bound to Request)
Easter  Deckow

Easter Deckow

1646266020

How You Can Selectively Unblock Third-party Cookies in Chrome

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.

#googlechrome #cookies 

How You Can Selectively Unblock Third-party Cookies in Chrome
Reid  Rohan

Reid Rohan

1643118000

Everything You Need to Know About Client-side Storage

awesome-web-storage

Everything you need to know about Client-side Storage.

Table of Contents

Introduction

What is Web 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).

Web Storage concepts and usage

The two mechanisms within Web Storage are as follows:

  1. 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).
  2. localStorage does the same thing, but persists even when the browser is closed and reopened.

Web Storage interfaces

Storage

Allows you to set, retrieve and remove data for a specific domain and storage type (session or local.)

Window

The Web Storage API extends the Window object with two new properties β€” Window.sessionStorage and Window.localStorage β€” which provide access to the current domain's session and local Storage objects respectively, and a Window.onstorage event handler that fires when a storage area changes (e.g. a new item is stored.)

StorageEvent

The storage event is fired on a document's Window object when a storage area changes.

Browser Support

IE / Edge
IE / Edge
Firefox
Firefox
Chrome
Chrome
Safari
Safari
Opera
Opera
IE8+, Edge12+3.5+4+4+11.5+

Different Storage APIs

Following are various storage techniques which HTML5 storage provides. Each technique has its own pros and cons.

Cookies

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:

  • Session Management - Easy to use with logins, shopping carts, game scores, or anything else the server should remember

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:

  • 300 cookies in total
  • 4096 bytes per cookie
  • 20 cookies per domain
  • 81920 bytes per domain(Given 20 cookies of max size 4096 = 81920 bytes.)

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

localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage 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

setItemDescription
methodlocalStorage.setItem(key, value)
paramskey(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
descriptionadds the key to the storage with the value, or update the key's value if it already exists.
examplelocalStorage.setItem('test', document.getElementById('js-btn').value);

getItem

getItemDescription
methodlocalStorage.getItem(key)
paramskey(String/Number)
descriptionreturns the value of the key passed.
examplelocalStorage.getItem('test')

removeItem

removeItemDescription
methodlocalStorage.removeItem(key)
paramskey(String/Number)
descriptionremoves the key from the storage.
examplelocalStorage.removeItem('test')

clear

clearDescription
methodlocalStorage.clear()
paramsNone
descriptionempties all the keys out of the storage.
examplelocalStorage.clear()

key

keyDescription
methodlocalStorage.key(n)
paramsn(a Number)
descriptionreturns the name of the nth key in the storage.
examplelocalStorage.key(0)

length

lengthDescription
propertylocalStorage.length
descriptionreturns the length of all the keys
examplelocalStorage.length

Resources - more on localStorage

sessionStorage

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to Window.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:

Same as localStorage

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

setItemDescription
methodsessionStorage.setItem(key, value)
paramskey(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
descriptionadds the key to the storage with the value, or update the key's value if it already exists.
examplesessionStorage.setItem('test', document.getElementById('js-btn').value);

getItem

getItemDescription
methodsessionStorage.getItem(key)
paramskey(String/Number)
descriptionreturns the value of the key passed.
examplesessionStorage.getItem('test')

removeItem

removeItemDescription
methodsessionStorage.removeItem(key)
paramskey(String/Number)
descriptionremoves the key from the storage.
examplesessionStorage.removeItem('test')

clear

clearDescription
methodsessionStorage.clear()
paramsNone
descriptionempties all the keys out of the storage.
examplesessionStorage.clear()

key

keyDescription
methodsessionStorage.key(n)
paramsn(a Number)
descriptionreturns the name of the nth key in the storage.
examplesessionStorage.key(0)

length

lengthDescription
propertysessionStorage.length
descriptionreturns the length of all the keys
examplesessionStorage.length

Resources - more on sessionStorage


Comparison Table

Web StoragecookieslocalStoragesessionStorage
Size limitMax 4kb (~2K chars)Max 5mb (~2M chars)Max 5mb (~2M chars)
Data StorageFileSytemFileSytemFileSytem
PayloadIn every HTTP reqNothingNothing
APIFairSimpleSimple
PersistentYesYesNo
Data FormatStringStringString
Same-originYesYesYes
Cross-originNoNoNo
Browser SipportAllIE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+IE8+, Edge12+, Firefox3.5+, Safari4+, Opera11.5+
Size limits infolimitlimitlimit

Worth mentioning API for tackling cross-origin restriction

postMessage

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:

FAQs

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.

  • across-tabs - Easy communication between cross-origin browser tabs

Contributing Guidelines

Please ensure your pull request adheres to the following guidelines:

  • Search previous suggestions before making a new one, as yours may be a duplicate.
  • Make sure the list is useful before submitting. That implies it has enough content and every item has a good succinct description.
  • Make an individual pull request for each suggestion.
  • Use title-casing (AP style).
  • Use the following format: [List Name](link)
  • Link additions should be added to the bottom of the relevant category.
  • New categories or improvements to the existing categorization are welcome.
  • Check your spelling and grammar.
  • Make sure your text editor is set to remove trailing whitespace.
  • The pull request and commit should have a useful title.
  • The body of your commit message should contain a link to the repository.

Author: Softvar
Source Code: https://github.com/softvar/awesome-web-storage 
License: 

#javascript #cookies #localstorage 

Everything You Need to Know About Client-side Storage
Reid  Rohan

Reid Rohan

1643080140

Cookies: JavaScript Client-Side Cookie Manipulation Library

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

Features

  • RFC6265 compliant
  • Cross browser
  • Lightweight
  • No dependencies
  • Public domain
  • Supports AMD / CommonJS loaders

Browser Compatibility

The following browsers have passed all of the automated Cookies.js tests:

  • Chrome
  • Firefox 3+
  • Safari 4+
  • Opera 10+
  • Internet Explorer 6+

Getting the Library

Direct downloads

Node Package Manager

npm install cookies-js

Bower

bower install cookies-js

Use in CommonJS/Node Environments Without 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

A Note About Encoding

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.

.NET Users

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.

API Reference

Methods
Cookies.set(key, value [, options])
Cookies.get(key)
Cookies.expire(key [, options])

Properties
Cookies.enabled
Cookies.defaults

Methods

Cookies.set(key, value [, options])

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.

OptionDescriptionDefault
pathA string value of the path of the cookie"/"
domainA string value of the domain of the cookieundefined
expiresA number (of seconds), a date parsable string, or a Date object of when the cookie will expireundefined
secureA boolean value of whether or not the cookie should only be available over SSLfalse

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 });

Cookies.get(key)

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"

Cookies.expire(key [, options])

Alias: Cookies(key, undefined [, options])

Expires a cookie, removing it from the document. Returns the Cookies object.

OptionDescriptionDefault
pathA string value of the path of the cookie"/"
domainA string value of the domain of the cookieundefined

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);

Properties

Cookies.enabled

A boolean value of whether or not the browser has cookies enabled.

Example Usage

if (Cookies.enabled) {
    Cookies.set('key', 'value');
}

Cookies.defaults

An object representing default options to be used when setting and expiring cookie values.

OptionDescriptionDefault
pathA string value of the path of the cookie"/"
domainA string value of the domain of the cookieundefined
expiresA number (of seconds), a date parsable string, or a Date object of when the cookie will expireundefined
secureA boolean value of whether or not the cookie should only be available over SSLfalse

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

#cookies #javascript 

Cookies: JavaScript Client-Side Cookie Manipulation Library