• Stars
    star
    2,190
  • Rank 20,539 (Top 0.5 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created almost 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Cross domain local storage, with permissions

cross-storage

Cross domain local storage, with permissions. Enables multiple browser windows/tabs, across a variety of domains, to share a single localStorage. Features an API using ES6 promises.

Build Status

Overview

The library is a convenient alternative to sharing a root domain cookie. Unlike cookies, your client-side data isn't limited to a few kilobytes - you get up to 2.49M chars. For a client-heavy application, you can potentially shave a few KB off your request headers by avoiding cookies. This is all thanks to LocalStorage, which is available in IE 8+, FF 3.5+, Chrome 4+, as well as a majority of mobile browsers. For a list of compatible browsers, refer to caniuse.

How does it work? The library is divided into two types of components: hubs and clients. The hubs reside on a host of choice and interact directly with the LocalStorage API. The clients then load said hub over an embedded iframe and post messages, requesting data to be stored, retrieved, and deleted. This allows multiple clients to access and share the data located in a single store.

Care should be made to limit the origins of the bidirectional communication. As such, when initializing the hub, an array of permissions objects is passed. Any messages from clients whose origin does not match the pattern are ignored, as well as those not within the allowed set of methods. The set of permissions are enforced thanks to the same-origin policy. However, keep in mind that any user has full control of their local storage data - it's still client data. This only restricts access on a per-domain or web app level.

Hub

// Config s.t. subdomains can get, but only the root domain can set and del
CrossStorageHub.init([
  {origin: /\.example.com$/,            allow: ['get']},
  {origin: /:\/\/(www\.)?example.com$/, allow: ['get', 'set', 'del']}
]);

Note the $ for matching the end of the string. The RegExps in the above example will match origins such as valid.example.com, but not invalid.example.com.malicious.com.

Client

var storage = new CrossStorageClient('https://store.example.com/hub.html');

storage.onConnect().then(function() {
  return storage.set('newKey', 'foobar');
}).then(function() {
  return storage.get('existingKey', 'newKey');
}).then(function(res) {
  console.log(res.length); // 2
}).catch(function(err) {
  // Handle error
});

Installation

The library can be installed via bower:

bower install cross-storage

Or using npm:

npm install cross-storage

along with browserify:

var CrossStorageClient = require('cross-storage').CrossStorageClient;
var CrossStorageHub    = require('cross-storage').CrossStorageHub;

When serving the hub, you may want to set the CORS and CSP headers for your server depending on client/hub location. For example:

{
  'Access-Control-Allow-Origin':  '*',
  'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE',
  'Access-Control-Allow-Headers': 'X-Requested-With',
  'Content-Security-Policy':      "default-src 'unsafe-inline' *",
  'X-Content-Security-Policy':    "default-src 'unsafe-inline' *",
  'X-WebKit-CSP':                 "default-src 'unsafe-inline' *",
}

If using inline JS to create the hub, you'll need to specify unsafe-inline for the CSP headers. Otherwise, it can be left out if simply including the init code via another resource.

API

CrossStorageHub.init(permissions)

Accepts an array of objects with two keys: origin and allow. The value of origin is expected to be a RegExp, and allow, an array of strings. The cross storage hub is then initialized to accept requests from any of the matching origins, allowing access to the associated lists of methods. Methods may include any of: get, set, del, getKeys and clear. A 'ready' message is sent to the parent window once complete.

CrossStorageHub.init([
  {origin: /localhost:3000$/, allow: ['get', 'set', 'del', 'getKeys', 'clear']}
]);

new CrossStorageClient(url, [opts])

Constructs a new cross storage client given the url to a hub. By default, an iframe is created within the document body that points to the url. It also accepts an options object, which may include a timeout, frameId, and promise. The timeout, in milliseconds, is applied to each request and defaults to 5000ms. The options object may also include a frameId, identifying an existing frame on which to install its listeners. If the promise key is supplied the constructor for a Promise, that Promise library will be used instead of the default window.Promise.

var storage = new CrossStorageClient('http://localhost:3000/hub.html');

var storage = new CrossStorageClient('http://localhost:3000/hub.html', {
  timeout: 5000,
  frameId: 'storageFrame'
});

CrossStorageClient.prototype.onConnect()

Returns a promise that is fulfilled when a connection has been established with the cross storage hub. Its use is required to avoid sending any requests prior to initialization being complete.

storage.onConnect().then(function() {
  // ready!
});

CrossStorageClient.prototype.set(key, value)

Sets a key to the specified value. Returns a promise that is fulfilled on success, or rejected if any errors setting the key occurred, or the request timed out.

storage.onConnect().then(function() {
  return storage.set('key', JSON.stringify({foo: 'bar'}));
});

CrossStorageClient.prototype.get(key1, [key2], [...])

Accepts one or more keys for which to retrieve their values. Returns a promise that is settled on hub response or timeout. On success, it is fulfilled with the value of the key if only passed a single argument. Otherwise it's resolved with an array of values. On failure, it is rejected with the corresponding error message.

storage.onConnect().then(function() {
  return storage.get('key1');
}).then(function(res) {
  return storage.get('key1', 'key2', 'key3');
}).then(function(res) {
  // ...
});

CrossStorageClient.prototype.del(key1, [key2], [...])

Accepts one or more keys for deletion. Returns a promise that is settled on hub response or timeout.

storage.onConnect().then(function() {
  return storage.del('key1', 'key2');
});

CrossStorageClient.prototype.getKeys()

Returns a promise that, when resolved, passes an array of keys currently in storage.

storage.onConnect().then(function() {
  return storage.getKeys();
}).then(function(keys) {
  // ['key1', 'key2', ...]
});

CrossStorageClient.prototype.clear()

Returns a promise that, when resolved, indicates that all localStorage data has been cleared.

storage.onConnect().then(function() {
  return storage.clear();
});

CrossStorageClient.prototype.close()

Deletes the iframe and sets the connected state to false. The client can no longer be used after being invoked.

storage.onConnect().then(function() {
  return storage.set('key1', 'key2');
}).catch(function(err) {
  // Handle error
}).then(function() {
  storage.close();
});

Compatibility

For compatibility with older browsers, simply load a Promise polyfill such as es6-promise.

You can also use RSVP or any other ES6 compliant promise library. Supports IE8 and up using the above polyfill. A JSON polyfill is also required for IE8 in Compatibility View. Also note that catch is a reserved word in IE8, and so error handling with promises can be done as:

storage.onConnect().then(function() {
  return storage.get('key1');
}).then(function(res) {
  // ... on success
})['catch'](function(err) {
  // ... on error
});

Breaking Changes

API breaking changes were introduced in both 0.6 and 1.0. Refer to releases for details.

Notes on Safari 7+ (OSX, iOS)

All cross-domain local storage access is disabled by default with Safari 7+. This is a result of the "Block cookies and other website data" privacy setting being set to "From third parties and advertisers". Any cross-storage client code will not crash, however, it will only have access to a sandboxed, isolated local storage instance. As such, none of the data previously set by other origins will be accessible. If an option, one could fall back to using root cookies for those user agents, or requesting the data from a server-side store.

Compression

Most localStorage-compatible browsers offer at least ~5Mb of storage. But keys and values are defined as DOMStrings, which are UTF-8 encoded using single 16-bit sequences. That means a string of ~2.5 million ASCII characters will use up ~5Mb, since they're 2 bytes per char.

If you need to maximize your storage space, consider using lz-string. For smaller strings, it's not uncommon to see a 50% reduction in size when compressed, which will bring you a lot closer to 5 million characters. At that point, you're only limited by the average compression rate of your strings.

Building

The minified, production JavaScript can be generated with gulp by running gulp dist. If not already on your system, gulp can be installed using npm install -g gulp

Tests

Tests can be ran locally using npm test. Tests are ran using Zuul, and the Travis CI build uses Sauce Labs for multi-browser testing as well.

Copyright and license

Copyright 2016 Zendesk

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

More Repositories

1

android-floating-action-button

Floating Action Button for Android based on Material Design specification
Java
6,374
star
2

maxwell

Maxwell's daemon, a mysql-to-json kafka producer
Java
3,939
star
3

samson

Web interface for deployments, with plugin architecture and kubernetes support
Ruby
1,446
star
4

ruby-kafka

A Ruby client library for Apache Kafka
Ruby
1,268
star
5

helm-secrets

DEPRECATED A helm plugin that help manage secrets with Git workflow and store them anywhere
Shell
1,159
star
6

curly

The Curly template language allows separating your logic from the structure of your HTML templates.
Ruby
592
star
7

biz

Time calculations using business hours.
Ruby
486
star
8

racecar

Racecar: a simple framework for Kafka consumers in Ruby
Ruby
477
star
9

zendesk_api_client_rb

Official Ruby Zendesk API Client
Ruby
383
star
10

dropbox-api

Dropbox API Ruby Client
Ruby
362
star
11

zendesk_api_client_php

Official Zendesk API v2 client library for PHP
PHP
332
star
12

stronger_parameters

Type checking and type casting of parameters for Action Pack
Ruby
297
star
13

active_record_shards

Support for sharded databases and replicas for ActiveRecord
Ruby
247
star
14

delivery_boy

A simple way to publish messages to Kafka from Ruby applications
Ruby
236
star
15

android-db-commons

Some common utilities for ContentProvider/ContentResolver/Cursor and other db-related android stuff
Java
223
star
16

radar

High level API and backend for writing web apps that use push messaging
JavaScript
221
star
17

sunshine-conversations-web

The Smooch Web SDK will add live web messaging to your website or web app.
212
star
18

demo_apps

HTML
179
star
19

arturo

Feature Sliders for Rails
Ruby
174
star
20

belvedere

An image picker library for Android
Java
146
star
21

zendesk_jwt_sso_examples

Examples using JWT for Zendesk SSO
Ruby
142
star
22

sunshine-conversations-ios

Smooch
Objective-C
122
star
23

laika

Log, test, intercept and modify Apollo Client's operations
TypeScript
120
star
24

prop

Puts a cork in their requests
Ruby
117
star
25

zendesk_sdk_ios

Zendesk Mobile SDK for iOS
Objective-C
117
star
26

zopim-chat-web-sdk-sample-app

Zendesk Chat Web SDK sample app developed using React
JavaScript
98
star
27

copenhagen_theme

The default theme for Zendesk Guide
Handlebars
95
star
28

app_scaffold

A scaffold for developers to build ZAF v2 apps
JavaScript
90
star
29

node-publisher

A zero-configuration release automation tool for Node packages inspired by create-react-app and Travis CI.
JavaScript
76
star
30

zendesk_apps_tools

Ruby
75
star
31

zendesk_app_framework_sdk

The Zendesk App Framework (ZAF) SDK is a JavaScript library that simplifies cross-frame communication between iframed apps and the Zendesk App Framework
JavaScript
71
star
32

ios_sdk_demo_apps

This repository contains sample iOS code and applications which use our SDKs
Swift
64
star
33

zendesk_sdk_chat_ios

Mobile Chat SDK for iOS
Objective-C
63
star
34

kamcaptcha

A captcha plugin for Rails
Ruby
63
star
35

linksf

A mobile website to connect those in need in to services that can help them
JavaScript
62
star
36

sdk_demo_app_android

This is Remember The Date, an Android demo app for our Mobile SDK. All docs available on developer.zendesk.com
Java
61
star
37

zcli

A command-line tool for Zendesk
TypeScript
56
star
38

go-httpclerk

A simple HTTP request/response logger for Go supporting multiple formatters.
Go
51
star
39

property_sets

A way to store attributes in a side table.
Ruby
51
star
40

android-schema-utils

Android library for simplifying database schema and migrations management.
Java
48
star
41

android_sdk_demo_apps

This repository contains sample android code and applications which use our SDKs
Java
46
star
42

statsd-logger

StatsD + Datadog APM logging server for development - standalone or embedded
Go
44
star
43

sunshine-conversations-android

Smooch Android SDK
42
star
44

support_sdk_ios

Zendesk Support SDK for iOS
Objective-C
37
star
45

react-native-sunshine-conversations

React Native wrapper for Smooch.io
Java
36
star
46

docker-logs-tail

Docker Logs Tail simultaneously tails logs for all running Docker containers, interleaving them in the command line output
JavaScript
35
star
47

call_center

Ruby
34
star
48

curlybars

Handlebars.js compatible templating library in Ruby
Ruby
34
star
49

kasket

A caching layer for ActiveRecord. Puts a cap on your queries!
Ruby
33
star
50

ruby_memprofiler_pprof

Experimental memory profiler for Ruby that emits pprof files.
C
33
star
51

method_struct

Ruby
33
star
52

samlr

Clean room implementation of SAML for Ruby
Ruby
31
star
53

min-tfs-client

A lightweight python gRPC client to communicate with TensorFlow Serving
C++
31
star
54

sdk_demo_app_ios

This is Remember The Date, an iOS demo app for our Mobile SDK. All docs available on developer.zendesk.com
Objective-C
31
star
55

volunteer_portal

An event calendar focused on tracking and reporting volunteering opportunities
JavaScript
29
star
56

classic_asp_jwt

A JWT implementation in Classic ASP
ASP
29
star
57

basecrm-ruby

Base CRM API Client
Ruby
29
star
58

ultragrep

the grep that greps the hardest.
C
28
star
59

chariot-tooltips

A javascript library for creating on screen step by step tutorials.
JavaScript
26
star
60

clj-headlights

Clojure on Beam
Clojure
26
star
61

sunshine-conversations-javascript

Javascript API for Sunshine Conversations
JavaScript
26
star
62

android-autoprovider

Utility for creating ContentProviders without boilerplate and with heavy customization options.
Java
25
star
63

basecrm-php

Base CRM API client, PHP edition
PHP
23
star
64

migration_tools

Rake tasks for Rails that add groups to migrations
Ruby
23
star
65

large_object_store

Store large objects in memcache or others by slicing them.
Ruby
22
star
66

term-check

A GitHub app which runs checks for flagged terminology in GitHub repos
Go
22
star
67

basecrm-python

BaseCRM API Client for Python
Python
22
star
68

sdk_unity_plugin

This repository contains a unity plugin which wraps the Zendesk support SDKs
Objective-C
22
star
69

jazon

Test assertions on JSONs have never been easier
Java
21
star
70

ipcluster

Node.js master/worker clustering module for sticky session load balancing using IPTABLES
JavaScript
21
star
71

sunshine-conversations-python

Smooch API Library for Python
Python
21
star
72

cloudwatch-logger

Connects standard input to Amazon CloudWatch Logs
Go
20
star
73

forger

Android library for populating the ContentProvider with test data.
Java
19
star
74

radar_client

High level API and backend for writing web apps that use push messaging
JavaScript
19
star
75

double_doc

Write documentation with your code, to keep them in sync, ideal for public API docs.
Ruby
18
star
76

pakkr

Python pipeline utility library
Python
18
star
77

chat_sdk_ios

Zendesk Chat SDK
Objective-C
18
star
78

goship

Utility that helps find, connect and copy to particular cloud resources using configured providers
Go
18
star
79

url_builder_app

A Zendesk App to help you generate links for agents.
JavaScript
18
star
80

sunshine-conversations-api-quickstart-example

Sample code to get started with the Smooch REST APIs
JavaScript
17
star
81

zendesk_apps_support

Ruby
17
star
82

sunshine-conversations-desk

A sample business system built with Meteor and the Smooch API
CSS
17
star
83

apt-s3

apt method for private S3 buckets
Go
17
star
84

api_client

HTTP API Client Builder
Ruby
16
star
85

iron_bank

An opinionated Ruby interface to the Zuora REST API
Ruby
15
star
86

private_gem

Keeps your private gems private
Ruby
15
star
87

active_record_host_pool

Connect to multiple databases using one ActiveRecord connection
Ruby
15
star
88

sdk_messaging_ios

The Zendesk Messaging SDK
Objective-C
14
star
89

rate_my_app_ios

An open source version of the Rate My App feature from 1.x versions of the Support SDK.
Swift
14
star
90

input_sanitizer

A gem to sanitize hash of incoming data
Ruby
14
star
91

sunshine-conversations-conversation-extension-examples

A series of examples using Smooch conversation extensions
HTML
14
star
92

scala-flow

A lightweight library intended to make developing Google DataFlow jobs in Scala easier.
Scala
14
star
93

punchabunch

Punchabunch: A highly concurrent, easily configurable SSH local-forwarding proxy
Go
14
star
94

zendesk-jira-plugin

Java
13
star
95

sunshine-conversations-ruby

Smooch API Library for Ruby
Ruby
13
star
96

samson_secret_puller

kubernetes sidecar and app to publish secrets to a containerized app.
Ruby
13
star
97

sqlitemaster

Android library for getting existing db schema information from sqlite_master table.
Java
13
star
98

sunshine-conversations-wordpress

PHP
13
star
99

predictive_load

Ruby
12
star
100

sunshine-conversations-api-spec

Sunshine Conversations OpenAPI Specification for v2+
12
star