├── .circleci
└── config.yml
├── .gitignore
├── .npmignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── bundle
└── bundle.js
├── bundleEntry.d.ts
├── bundleEntry.js
├── bundleEntry.ts
├── hooks
└── pre-commit
├── index.d.ts
├── index.js
├── index.ts
├── package-lock.json
├── package.json
├── processLock.d.ts
├── processLock.js
├── processLock.ts
├── scripts
└── postinstall.js
├── setupHooks
├── test
├── counterTest.html
├── index.test.js
├── multiLockTest.html
├── releaseOnClose.html
└── singleTabMultiLock.html
├── tsconfig.json
└── webpack.config.js
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 | orbs:
3 | slack: circleci/slack@3.4.2
4 | jobs:
5 | publish:
6 | docker:
7 | - image: circleci/node:8.10.0
8 | steps:
9 | - checkout
10 | - run: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" >> ~/.npmrc
11 | - run: npm publish
12 | - slack/status
13 | test:
14 | docker:
15 | - image: circleci/node:latest-browsers
16 | steps:
17 | - checkout
18 | - run: npm i -d
19 | - run: npm run test
20 | - slack/status
21 |
22 | workflows:
23 | version: 2
24 | test:
25 | jobs:
26 | - test:
27 | context:
28 | - slack-notification
29 | filters:
30 | branches:
31 | only:
32 | - master
33 | tagged-build:
34 | jobs:
35 | - publish:
36 | context:
37 | - slack-notification
38 | filters:
39 | tags:
40 | only: /v[0-9]+(\.[0-9]+)*/
41 | branches:
42 | ignore: /.*/
43 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .history/
2 | node_modules
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | **/*.ts
2 | !**/*.d.ts
3 | .git/
4 | test/
5 | hooks/
6 | bundle/
7 | .circleci/
8 | webpack.config.js
9 | tsconfig.json
10 | setupHooks
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 | All notable changes to this project will be documented in this file.
3 |
4 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
5 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6 |
7 | ## [1.3.0] - 2023-04-25
8 | - Allows passing of custom storage handler which can be used to override the fact that this lib writes to localstorage
9 |
10 | ## [1.2.15] - 2021-08-09
11 |
12 | ### Changed
13 | - Readme and post install message
14 |
15 | ## [1.2.14] - 2021-04-29
16 | ### Changed
17 | - Dependency upgrade:
18 | - https://github.com/supertokens/browser-tabs-lock/pull/21
19 | - https://github.com/supertokens/browser-tabs-lock/pull/19
20 | - https://github.com/supertokens/browser-tabs-lock/pull/16
21 |
22 |
23 | ## [1.2.13] - 2021-04-24
24 | ### Changed
25 | - Upgraded version of Lodash: https://github.com/supertokens/browser-tabs-lock/issues/20
26 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2019 SuperTokens, VRAI Labs Pvt. Ltd, India
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | this software and associated documentation files (the "Software"), to deal in
7 | the Software without restriction, including without limitation the rights to
8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software is furnished to do so,
10 | subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://supertokens.io)
2 |
3 | [](https://github.com/supertokens/auth-node-mysql-ref-jwt/blob/master/LICENSE)
4 |
5 |
7 | [](https://join.slack.com/t/webmobilesecurity/shared_invite/enQtODM4MDM2MTQ1MDYyLTFiNmNhYzRlNGNjODhkNjc5MDRlYTBmZTBiNjFhOTFhYjI1MTc3ZWI2ZjY3Y2M3ZjY1MGJhZmRiNDFjNDNjOTM)
8 |
9 |
10 | # Browser Tabs Lock
11 |
12 | Using this package, you can easily get lock functionality across tabs on all modern browsers.
13 |
14 | **This library was originally designed to be used as a part of our project - SuperTokens - an open source auth solution for web and mobile apps. Support us by checking it out [here](https://supertokens.io).**
15 |
16 | We are also offering free, one-to-one implementation support:
17 | - Schedule a short call with us on https://calendly.com/supertokens-rishabh.
18 |
19 |
20 | ## Some things to note about:
21 | - This is not a reentrant lock. So please do not attempt to re-acquire a lock using the same lock instance with the same key without releasing the acquired lock / key first.
22 | - Theoretically speaking, it is impossible to have foolproof locking built on top of javascript in the browser. One can only make it so that in all practical scenarios, it emulates locking.
23 |
24 | ## Installation using Node:
25 | ```bash
26 | npm i --save browser-tabs-lock
27 | ```
28 |
29 | ### Usage in an async function:
30 | ```js
31 | import SuperTokensLock from "browser-tabs-lock";
32 |
33 | let superTokensLock = new SuperTokensLock()
34 | async function lockingIsFun() {
35 | if (await superTokensLock.acquireLock("hello", 5000)) {
36 | // lock has been acquired... we can do anything we want now.
37 | // ...
38 | await superTokensLock.releaseLock("hello");
39 | } else {
40 | // failed to acquire lock after trying for 5 seconds.
41 | }
42 | }
43 | ```
44 |
45 | ### Usage using callbacks:
46 |
47 | ```js
48 | import SuperTokensLock from "browser-tabs-lock";
49 |
50 | let superTokensLock = new SuperTokensLock()
51 | superTokensLock.acquireLock("hello", 5000).then((success) => {
52 | if (success) {
53 | // lock has been acquired... we can do anything we want now.
54 | // ...
55 | superTokensLock.releaseLock("hello").then(() => {
56 | // lock released, continue
57 | });
58 | } else {
59 | // failed to acquire lock after trying for 5 seconds.
60 | }
61 | });
62 | ```
63 |
64 | ## Installation using plain JS
65 |
66 | As of version 1.2.0 of browser-tabs-lock the package can also be used as in plain javascript script.
67 |
68 | ### Add the script
69 |
70 | ```html
71 |
75 | ```
76 |
77 | ### Creating and using the lock
78 |
79 | ```js
80 | let lock = new supertokenslock.getNewInstance();
81 | lock.acquireLock("hello")
82 | .then(success => {
83 | if (success) {
84 | // lock has been acquired... we can do anything we want now.
85 | ...
86 | lock.releaseLock("hello").then(() => {
87 | // lock released, continue
88 | });
89 | } else {
90 | // failed to acquire lock after trying for 5 seconds.
91 | }
92 | });
93 | ```
94 |
95 |
96 | Also note, that if your web app only needs to work on google chrome, you can use the [Web Locks API](https://developer.mozilla.org/en-US/docs/Web/API/Lock) instead. This probably has true locking!
97 |
98 | ## Migrating from 1.1x to 1.2x
99 |
100 | In some cases, version 1.1x did not entirely ensure mutual exclusion. To explain the problem:
101 |
102 | Lets say you create two lock instances L1 and L2. L1 acquires a lock with key K1 and is performing some action that takes 20 seconds to finish.
103 |
104 | Immediately after L1 acquires a lock, L2 tries to acquire a lock with the same key(K1). Normally L2 would not be able to acquire the lock until L1 releases it (in this case after 20 seconds) or when the tab that uses L1 is closed abruptly. However it is seen that sometimes L2 is able to acquire the lock automatically after 10 seconds (note that L1 has still not released the lock) - thereby breaking mutual exclusion.
105 |
106 | This bug has been fixed and released in version 1.2x of browser-tabs-lock. We highly recommend users to upgrade to 1.2x versions.
107 |
108 | After upgrading the only change that requires attention to is that ```lock.releaseLock``` is now an asynchronous function and needs to be handled accordingly.
109 |
110 | #### Using async/await
111 |
112 | Simply change calls to releaseLock from
113 |
114 | ```js
115 | lock.releaseLock("hello");
116 | ```
117 |
118 | to
119 |
120 | ```js
121 | await lock.releaseLock("hello");
122 | ```
123 |
124 | #### Using callbacks
125 |
126 | Simple change calls to releaseLock from
127 |
128 | ```js
129 | lock.releaseLock("hello");
130 | ```
131 |
132 | to
133 |
134 | ```js
135 | lock.releaseLock("hello")
136 | .then(() => {
137 | // continue
138 | });
139 | ```
140 |
141 | ## Test coverage
142 |
143 | In an effort to make this package as production ready as possible we use puppeteer to run browser-tabs-lock in a headless browser environment and perform the following action:
144 |
145 | - Create 15 tabs in the browser. Each tab tries to acquire a lock with the same key(K1) and then updates a counter in local storage(C1) as well as updates a counter local to that tab(Ct). The local counter(Ct) serves as a way to know how many times that particular tab has updated local storage counter(C1). This process happens recursively for 20 seconds. After 20 seconds we signal all tabs to stop and after all of them have stopped, we calculate the sum of all the local counter values(sum(Ct...Cn)) for each tab and compare that with the value in local storage(C1). If the two values are the same and the value in local storage matches an estimated value then we know that all tabs use locking in a proper manner.
146 |
147 | - Create a tab(T1) which acquires a lock with a key(K1). We then create another tab(T2) that tries to acquire a lock with the same key(K1) and after waiting for some time we verify that the second tab(T2) does not acquire the lock. We close both tabs, note however that tab 1(T1) still had not released the lock. We create another tab(T3) that tries to acquire a lock with the same key(K1) and we verify that the tab is able to acquire the lock. This way we can be sure that locks are released when the tab that holds it(in this case T1) is closed abruptly.
148 |
149 | - Create a tab that creates two separate instances of the lock object I1 and I2. I1 acquires a lock with a key(K1), immediately after I2 tries to acquire the lock with the same key(K1). We verify that I2 cannot acquire the lock even after some time has passed. I1 then releases the lock and immediately after I2 tries the acquire it, we verify that I2 can now acquire the lock.
150 |
151 | - Create a tab that holds 15 separate lock instances. Each instance tries to acquire the lock using the same key(K1), it then updates a counter(C1) in local storage and also updates a local counter value specific to this instance (Ci). After incrementing the counters the instance recursively repeats this process. We wait for 20 seconds after which we signal each instance to stop and wait for all of them to stop. We then get the counter value from storage(C1) and add all local counter values(sum(Ci....Cn)) and compare the 2 values. We verify that the values are the same and the value in local storage(C1) matches an estimated value. This way we can be sure that in a single tab multiple lock instances using the same key work correctly.
152 |
153 | ## Support, questions and bugs
154 | For now, we are most reachable via team@supertokens.io and via the GitHub issues feature
155 |
156 | ## Authors
157 | Created with :heart: by the folks at [SuperTokens](https://supertokens.io). We are a startup passionate about security and solving software challenges in a way that's helpful for everyone! Please feel free to give us feedback at team@supertokens.io, until our website is ready :grinning:
158 |
--------------------------------------------------------------------------------
/bundle/bundle.js:
--------------------------------------------------------------------------------
1 | var supertokenslock=function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=0)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(1);t.getNewInstance=function(){return new r.default}},function(e,t,n){"use strict";var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{c(r.next(e))}catch(e){i(e)}}function u(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){e.done?o(e.value):new n((function(t){t(e.value)})).then(a,u)}c((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!(o=(o=a.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]0?setTimeout(n,t):n(null)}}window.addEventListener("storage",u),e.addToWaiting(u);var c=setTimeout(u,Math.max(0,t-Date.now()))}))];case 1:return n.sent(),[2]}}))}))},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter((function(e){return e!==t})))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach((function(e){return e()}))},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}}))}))},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,(function(){var n,r,i,c;return o(this,(function(o){switch(o.label){case 0:return n=void 0===this.storageHandler?u:this.storageHandler,r="browser-tabs-lock-key-"+t,null===(i=n.getItemSync(r))?[2]:(c=JSON.parse(i)).id!==this.id?[3,2]:[4,a.default().lock(c.iat)];case 1:o.sent(),this.acquiredIatSet.delete(c.iat),n.removeItemSync(r),a.default().unlock(c.iat),e.notifyWaiters(),o.label=2;case 2:return[2]}}))}))},e.lockCorrector=function(t){for(var n=Date.now()-5e3,r=t,o=[],i=0;;){var a=r.keySync(i);if(null===a)break;o.push(a),i++}for(var u=!1,c=0;c SuperTokensLock;
3 | export { getNewInstance };
4 |
--------------------------------------------------------------------------------
/bundleEntry.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 | var index_1 = require("./index");
4 | var getNewInstance = function () {
5 | return new index_1.default();
6 | };
7 | exports.getNewInstance = getNewInstance;
8 |
--------------------------------------------------------------------------------
/bundleEntry.ts:
--------------------------------------------------------------------------------
1 | import SuperTokensLock from "./index";
2 |
3 | var getNewInstance = () => {
4 | return new SuperTokensLock();
5 | }
6 |
7 | export {getNewInstance};
--------------------------------------------------------------------------------
/hooks/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # Delete existing bundle
4 | rm -rf bundle
5 | git add bundle
6 |
7 | npm run pack
8 |
9 | if [ $? -ne 0 ]
10 | then
11 | exit 1
12 | fi
13 |
14 | git add bundle/*
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | export declare type StorageHandler = {
2 | key: (index: number) => Promise;
3 | getItem: (key: string) => Promise;
4 | clear: () => Promise;
5 | removeItem: (key: string) => Promise;
6 | setItem: (key: string, value: string) => Promise;
7 | /**
8 | * Sync versions of the storage functions
9 | */
10 | keySync: (index: number) => string | null;
11 | getItemSync: (key: string) => string | null;
12 | clearSync: () => void;
13 | removeItemSync: (key: string) => void;
14 | setItemSync: (key: string, value: string) => void;
15 | };
16 | export default class SuperTokensLock {
17 | private static waiters;
18 | private id;
19 | private acquiredIatSet;
20 | private storageHandler;
21 | constructor(storageHandler?: StorageHandler);
22 | /**
23 | * @async
24 | * @memberOf Lock
25 | * @function acquireLock
26 | * @param {string} lockKey - Key for which the lock is being acquired
27 | * @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock
28 | * @returns {Promise}
29 | * @description Will return true if lock is being acquired, else false.
30 | * Also the lock can be acquired for maximum 10 secs
31 | */
32 | acquireLock(lockKey: string, timeout?: number): Promise;
33 | private refreshLockWhileAcquired;
34 | private waitForSomethingToChange;
35 | private static addToWaiting;
36 | private static removeFromWaiting;
37 | private static notifyWaiters;
38 | /**
39 | * @function releaseLock
40 | * @memberOf Lock
41 | * @param {string} lockKey - Key for which lock is being released
42 | * @returns {void}
43 | * @description Release a lock.
44 | */
45 | releaseLock(lockKey: string): Promise;
46 | /**
47 | * @function releaseLock
48 | * @memberOf Lock
49 | * @param {string} lockKey - Key for which lock is being released
50 | * @returns {void}
51 | * @description Release a lock.
52 | */
53 | private releaseLock__private__;
54 | /**
55 | * @function lockCorrector
56 | * @returns {void}
57 | * @description If a lock is acquired by a tab and the tab is closed before the lock is
58 | * released, this function will release those locks
59 | */
60 | private static lockCorrector;
61 | }
62 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3 | return new (P || (P = Promise))(function (resolve, reject) {
4 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6 | function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
7 | step((generator = generator.apply(thisArg, _arguments || [])).next());
8 | });
9 | };
10 | var __generator = (this && this.__generator) || function (thisArg, body) {
11 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
12 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
13 | function verb(n) { return function (v) { return step([n, v]); }; }
14 | function step(op) {
15 | if (f) throw new TypeError("Generator is already executing.");
16 | while (_) try {
17 | if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
18 | if (y = 0, t) op = [op[0] & 2, t.value];
19 | switch (op[0]) {
20 | case 0: case 1: t = op; break;
21 | case 4: _.label++; return { value: op[1], done: false };
22 | case 5: _.label++; y = op[1]; op = [0]; continue;
23 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
24 | default:
25 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
26 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
27 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
28 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
29 | if (t[2]) _.ops.pop();
30 | _.trys.pop(); continue;
31 | }
32 | op = body.call(thisArg, _);
33 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
34 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
35 | }
36 | };
37 | var _this = this;
38 | Object.defineProperty(exports, "__esModule", { value: true });
39 | var processLock_1 = require("./processLock");
40 | /**
41 | * @author: SuperTokens (https://github.com/supertokens)
42 | * This library was created as a part of a larger project, SuperTokens(https://supertokens.io) - the best session management solution.
43 | * You can also check out our other projects on https://github.com/supertokens
44 | *
45 | * To contribute to this package visit https://github.com/supertokens/browser-tabs-lock
46 | * If you face any problems you can file an issue on https://github.com/supertokens/browser-tabs-lock/issues
47 | *
48 | * If you have any questions or if you just want to say hi visit https://supertokens.io/discord
49 | */
50 | /**
51 | * @constant
52 | * @type {string}
53 | * @default
54 | * @description All the locks taken by this package will have this as prefix
55 | */
56 | var LOCK_STORAGE_KEY = 'browser-tabs-lock-key';
57 | var DEFAULT_STORAGE_HANDLER = {
58 | key: function (index) { return __awaiter(_this, void 0, void 0, function () {
59 | return __generator(this, function (_a) {
60 | throw new Error("Unsupported");
61 | });
62 | }); },
63 | getItem: function (key) { return __awaiter(_this, void 0, void 0, function () {
64 | return __generator(this, function (_a) {
65 | throw new Error("Unsupported");
66 | });
67 | }); },
68 | clear: function () { return __awaiter(_this, void 0, void 0, function () {
69 | return __generator(this, function (_a) {
70 | return [2 /*return*/, window.localStorage.clear()];
71 | });
72 | }); },
73 | removeItem: function (key) { return __awaiter(_this, void 0, void 0, function () {
74 | return __generator(this, function (_a) {
75 | throw new Error("Unsupported");
76 | });
77 | }); },
78 | setItem: function (key, value) { return __awaiter(_this, void 0, void 0, function () {
79 | return __generator(this, function (_a) {
80 | throw new Error("Unsupported");
81 | });
82 | }); },
83 | keySync: function (index) {
84 | return window.localStorage.key(index);
85 | },
86 | getItemSync: function (key) {
87 | return window.localStorage.getItem(key);
88 | },
89 | clearSync: function () {
90 | return window.localStorage.clear();
91 | },
92 | removeItemSync: function (key) {
93 | return window.localStorage.removeItem(key);
94 | },
95 | setItemSync: function (key, value) {
96 | return window.localStorage.setItem(key, value);
97 | },
98 | };
99 | /**
100 | * @function delay
101 | * @param {number} milliseconds - How long the delay should be in terms of milliseconds
102 | * @returns {Promise}
103 | */
104 | function delay(milliseconds) {
105 | return new Promise(function (resolve) { return setTimeout(resolve, milliseconds); });
106 | }
107 | /**
108 | * @function generateRandomString
109 | * @params {number} length - How long the random string should be
110 | * @returns {string}
111 | * @description returns random string whose length is equal to the length passed as parameter
112 | */
113 | function generateRandomString(length) {
114 | var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
115 | var randomstring = '';
116 | for (var i = 0; i < length; i++) {
117 | var INDEX = Math.floor(Math.random() * CHARS.length);
118 | randomstring += CHARS[INDEX];
119 | }
120 | return randomstring;
121 | }
122 | /**
123 | * @function getLockId
124 | * @returns {string}
125 | * @description Generates an id which will be unique for the browser tab
126 | */
127 | function getLockId() {
128 | return Date.now().toString() + generateRandomString(15);
129 | }
130 | var SuperTokensLock = /** @class */ (function () {
131 | function SuperTokensLock(storageHandler) {
132 | this.acquiredIatSet = new Set();
133 | this.storageHandler = undefined;
134 | this.id = getLockId();
135 | this.acquireLock = this.acquireLock.bind(this);
136 | this.releaseLock = this.releaseLock.bind(this);
137 | this.releaseLock__private__ = this.releaseLock__private__.bind(this);
138 | this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
139 | this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
140 | this.storageHandler = storageHandler;
141 | if (SuperTokensLock.waiters === undefined) {
142 | SuperTokensLock.waiters = [];
143 | }
144 | }
145 | /**
146 | * @async
147 | * @memberOf Lock
148 | * @function acquireLock
149 | * @param {string} lockKey - Key for which the lock is being acquired
150 | * @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock
151 | * @returns {Promise}
152 | * @description Will return true if lock is being acquired, else false.
153 | * Also the lock can be acquired for maximum 10 secs
154 | */
155 | SuperTokensLock.prototype.acquireLock = function (lockKey, timeout) {
156 | if (timeout === void 0) { timeout = 5000; }
157 | return __awaiter(this, void 0, void 0, function () {
158 | var iat, MAX_TIME, STORAGE_KEY, STORAGE, lockObj, TIMEOUT_KEY, lockObjPostDelay, parsedLockObjPostDelay;
159 | return __generator(this, function (_a) {
160 | switch (_a.label) {
161 | case 0:
162 | iat = Date.now() + generateRandomString(4);
163 | MAX_TIME = Date.now() + timeout;
164 | STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
165 | STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
166 | _a.label = 1;
167 | case 1:
168 | if (!(Date.now() < MAX_TIME)) return [3 /*break*/, 8];
169 | return [4 /*yield*/, delay(30)];
170 | case 2:
171 | _a.sent();
172 | lockObj = STORAGE.getItemSync(STORAGE_KEY);
173 | if (!(lockObj === null)) return [3 /*break*/, 5];
174 | TIMEOUT_KEY = this.id + "-" + lockKey + "-" + iat;
175 | // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.
176 | return [4 /*yield*/, delay(Math.floor(Math.random() * 25))];
177 | case 3:
178 | // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.
179 | _a.sent();
180 | STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
181 | id: this.id,
182 | iat: iat,
183 | timeoutKey: TIMEOUT_KEY,
184 | timeAcquired: Date.now(),
185 | timeRefreshed: Date.now()
186 | }));
187 | return [4 /*yield*/, delay(30)];
188 | case 4:
189 | _a.sent(); // this is to prevent race conditions. This time must be more than the time it takes for storage.setItem
190 | lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
191 | if (lockObjPostDelay !== null) {
192 | parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
193 | if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
194 | this.acquiredIatSet.add(iat);
195 | this.refreshLockWhileAcquired(STORAGE_KEY, iat);
196 | return [2 /*return*/, true];
197 | }
198 | }
199 | return [3 /*break*/, 7];
200 | case 5:
201 | SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
202 | return [4 /*yield*/, this.waitForSomethingToChange(MAX_TIME)];
203 | case 6:
204 | _a.sent();
205 | _a.label = 7;
206 | case 7:
207 | iat = Date.now() + generateRandomString(4);
208 | return [3 /*break*/, 1];
209 | case 8: return [2 /*return*/, false];
210 | }
211 | });
212 | });
213 | };
214 | SuperTokensLock.prototype.refreshLockWhileAcquired = function (storageKey, iat) {
215 | return __awaiter(this, void 0, void 0, function () {
216 | var _this = this;
217 | return __generator(this, function (_a) {
218 | setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
219 | var STORAGE, lockObj, parsedLockObj;
220 | return __generator(this, function (_a) {
221 | switch (_a.label) {
222 | case 0: return [4 /*yield*/, processLock_1.default().lock(iat)];
223 | case 1:
224 | _a.sent();
225 | if (!this.acquiredIatSet.has(iat)) {
226 | processLock_1.default().unlock(iat);
227 | return [2 /*return*/];
228 | }
229 | STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
230 | lockObj = STORAGE.getItemSync(storageKey);
231 | if (lockObj !== null) {
232 | parsedLockObj = JSON.parse(lockObj);
233 | parsedLockObj.timeRefreshed = Date.now();
234 | STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
235 | processLock_1.default().unlock(iat);
236 | }
237 | else {
238 | processLock_1.default().unlock(iat);
239 | return [2 /*return*/];
240 | }
241 | this.refreshLockWhileAcquired(storageKey, iat);
242 | return [2 /*return*/];
243 | }
244 | });
245 | }); }, 1000);
246 | return [2 /*return*/];
247 | });
248 | });
249 | };
250 | SuperTokensLock.prototype.waitForSomethingToChange = function (MAX_TIME) {
251 | return __awaiter(this, void 0, void 0, function () {
252 | return __generator(this, function (_a) {
253 | switch (_a.label) {
254 | case 0: return [4 /*yield*/, new Promise(function (resolve) {
255 | var resolvedCalled = false;
256 | var startedAt = Date.now();
257 | var MIN_TIME_TO_WAIT = 50; // ms
258 | var removedListeners = false;
259 | function stopWaiting() {
260 | if (!removedListeners) {
261 | window.removeEventListener('storage', stopWaiting);
262 | SuperTokensLock.removeFromWaiting(stopWaiting);
263 | clearTimeout(timeOutId);
264 | removedListeners = true;
265 | }
266 | if (!resolvedCalled) {
267 | resolvedCalled = true;
268 | var timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
269 | if (timeToWait > 0) {
270 | setTimeout(resolve, timeToWait);
271 | }
272 | else {
273 | resolve(null);
274 | }
275 | }
276 | }
277 | window.addEventListener('storage', stopWaiting);
278 | SuperTokensLock.addToWaiting(stopWaiting);
279 | var timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
280 | })];
281 | case 1:
282 | _a.sent();
283 | return [2 /*return*/];
284 | }
285 | });
286 | });
287 | };
288 | SuperTokensLock.addToWaiting = function (func) {
289 | this.removeFromWaiting(func);
290 | if (SuperTokensLock.waiters === undefined) {
291 | return;
292 | }
293 | SuperTokensLock.waiters.push(func);
294 | };
295 | SuperTokensLock.removeFromWaiting = function (func) {
296 | if (SuperTokensLock.waiters === undefined) {
297 | return;
298 | }
299 | SuperTokensLock.waiters = SuperTokensLock.waiters.filter(function (i) { return i !== func; });
300 | };
301 | SuperTokensLock.notifyWaiters = function () {
302 | if (SuperTokensLock.waiters === undefined) {
303 | return;
304 | }
305 | var waiters = SuperTokensLock.waiters.slice(); // so that if Lock.waiters is changed it's ok.
306 | waiters.forEach(function (i) { return i(); });
307 | };
308 | /**
309 | * @function releaseLock
310 | * @memberOf Lock
311 | * @param {string} lockKey - Key for which lock is being released
312 | * @returns {void}
313 | * @description Release a lock.
314 | */
315 | SuperTokensLock.prototype.releaseLock = function (lockKey) {
316 | return __awaiter(this, void 0, void 0, function () {
317 | return __generator(this, function (_a) {
318 | switch (_a.label) {
319 | case 0: return [4 /*yield*/, this.releaseLock__private__(lockKey)];
320 | case 1: return [2 /*return*/, _a.sent()];
321 | }
322 | });
323 | });
324 | };
325 | /**
326 | * @function releaseLock
327 | * @memberOf Lock
328 | * @param {string} lockKey - Key for which lock is being released
329 | * @returns {void}
330 | * @description Release a lock.
331 | */
332 | SuperTokensLock.prototype.releaseLock__private__ = function (lockKey) {
333 | return __awaiter(this, void 0, void 0, function () {
334 | var STORAGE, STORAGE_KEY, lockObj, parsedlockObj;
335 | return __generator(this, function (_a) {
336 | switch (_a.label) {
337 | case 0:
338 | STORAGE = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
339 | STORAGE_KEY = LOCK_STORAGE_KEY + "-" + lockKey;
340 | lockObj = STORAGE.getItemSync(STORAGE_KEY);
341 | if (lockObj === null) {
342 | return [2 /*return*/];
343 | }
344 | parsedlockObj = JSON.parse(lockObj);
345 | if (!(parsedlockObj.id === this.id)) return [3 /*break*/, 2];
346 | return [4 /*yield*/, processLock_1.default().lock(parsedlockObj.iat)];
347 | case 1:
348 | _a.sent();
349 | this.acquiredIatSet.delete(parsedlockObj.iat);
350 | STORAGE.removeItemSync(STORAGE_KEY);
351 | processLock_1.default().unlock(parsedlockObj.iat);
352 | SuperTokensLock.notifyWaiters();
353 | _a.label = 2;
354 | case 2: return [2 /*return*/];
355 | }
356 | });
357 | });
358 | };
359 | /**
360 | * @function lockCorrector
361 | * @returns {void}
362 | * @description If a lock is acquired by a tab and the tab is closed before the lock is
363 | * released, this function will release those locks
364 | */
365 | SuperTokensLock.lockCorrector = function (storageHandler) {
366 | var MIN_ALLOWED_TIME = Date.now() - 5000;
367 | var STORAGE = storageHandler;
368 | var KEYS = [];
369 | var currIndex = 0;
370 | while (true) {
371 | var key = STORAGE.keySync(currIndex);
372 | if (key === null) {
373 | break;
374 | }
375 | KEYS.push(key);
376 | currIndex++;
377 | }
378 | var notifyWaiters = false;
379 | for (var i = 0; i < KEYS.length; i++) {
380 | var LOCK_KEY = KEYS[i];
381 | if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
382 | var lockObj = STORAGE.getItemSync(LOCK_KEY);
383 | if (lockObj !== null) {
384 | var parsedlockObj = JSON.parse(lockObj);
385 | if ((parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME) ||
386 | (parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME)) {
387 | STORAGE.removeItemSync(LOCK_KEY);
388 | notifyWaiters = true;
389 | }
390 | }
391 | }
392 | }
393 | if (notifyWaiters) {
394 | SuperTokensLock.notifyWaiters();
395 | }
396 | };
397 | SuperTokensLock.waiters = undefined;
398 | return SuperTokensLock;
399 | }());
400 | exports.default = SuperTokensLock;
401 |
--------------------------------------------------------------------------------
/index.ts:
--------------------------------------------------------------------------------
1 | import getProcessLock from './processLock';
2 |
3 | /**
4 | * @author: SuperTokens (https://github.com/supertokens)
5 | * This library was created as a part of a larger project, SuperTokens(https://supertokens.io) - the best session management solution.
6 | * You can also check out our other projects on https://github.com/supertokens
7 | *
8 | * To contribute to this package visit https://github.com/supertokens/browser-tabs-lock
9 | * If you face any problems you can file an issue on https://github.com/supertokens/browser-tabs-lock/issues
10 | *
11 | * If you have any questions or if you just want to say hi visit https://supertokens.io/discord
12 | */
13 |
14 |
15 | /**
16 | * @constant
17 | * @type {string}
18 | * @default
19 | * @description All the locks taken by this package will have this as prefix
20 | */
21 | const LOCK_STORAGE_KEY = 'browser-tabs-lock-key';
22 |
23 | declare let setTimeout: any;
24 | declare let window: any;
25 | declare let clearTimeout: any;
26 |
27 | export type StorageHandler = {
28 | key: (index: number) => Promise;
29 | getItem: (key: string) => Promise;
30 | clear: () => Promise;
31 | removeItem: (key: string) => Promise;
32 | setItem: (key: string, value: string) => Promise;
33 | /**
34 | * Sync versions of the storage functions
35 | */
36 | keySync: (index: number) => string | null;
37 | getItemSync: (key: string) => string | null;
38 | clearSync: () => void;
39 | removeItemSync: (key: string) => void;
40 | setItemSync: (key: string, value: string) => void;
41 | };
42 |
43 | const DEFAULT_STORAGE_HANDLER: StorageHandler = {
44 | key: async (index: number) => {
45 | throw new Error("Unsupported");
46 | },
47 | getItem: async (key: string) => {
48 | throw new Error("Unsupported");
49 | },
50 | clear: async () => {
51 | return window.localStorage.clear();
52 | },
53 | removeItem: async (key: string) => {
54 | throw new Error("Unsupported");
55 | },
56 | setItem: async (key: string, value: string) => {
57 | throw new Error("Unsupported");
58 | },
59 | keySync: (index: number) => {
60 | return window.localStorage.key(index);
61 | },
62 | getItemSync: (key: string) => {
63 | return window.localStorage.getItem(key);
64 | },
65 | clearSync: () => {
66 | return window.localStorage.clear();
67 | },
68 | removeItemSync: (key: string) => {
69 | return window.localStorage.removeItem(key);
70 | },
71 | setItemSync: (key: string, value: string) => {
72 | return window.localStorage.setItem(key, value);
73 | },
74 |
75 | }
76 |
77 | /**
78 | * @function delay
79 | * @param {number} milliseconds - How long the delay should be in terms of milliseconds
80 | * @returns {Promise}
81 | */
82 | function delay(milliseconds: number): Promise {
83 | return new Promise(resolve => setTimeout(resolve, milliseconds));
84 | }
85 |
86 | /**
87 | * @function generateRandomString
88 | * @params {number} length - How long the random string should be
89 | * @returns {string}
90 | * @description returns random string whose length is equal to the length passed as parameter
91 | */
92 | function generateRandomString(length: number): string {
93 | const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
94 | let randomstring = '';
95 | for (let i = 0; i < length; i++) {
96 | const INDEX = Math.floor(Math.random() * CHARS.length);
97 | randomstring += CHARS[INDEX];
98 | }
99 | return randomstring;
100 | }
101 |
102 | /**
103 | * @function getLockId
104 | * @returns {string}
105 | * @description Generates an id which will be unique for the browser tab
106 | */
107 | function getLockId(): string {
108 | return Date.now().toString() + generateRandomString(15)
109 | }
110 |
111 | export default class SuperTokensLock {
112 | private static waiters: Array | undefined = undefined;
113 | private id: string;
114 | private acquiredIatSet: Set = new Set();
115 | private storageHandler: StorageHandler | undefined = undefined;
116 |
117 | constructor(storageHandler?: StorageHandler) {
118 | this.id = getLockId();
119 | this.acquireLock = this.acquireLock.bind(this);
120 | this.releaseLock = this.releaseLock.bind(this);
121 | this.releaseLock__private__ = this.releaseLock__private__.bind(this);
122 | this.waitForSomethingToChange = this.waitForSomethingToChange.bind(this);
123 | this.refreshLockWhileAcquired = this.refreshLockWhileAcquired.bind(this);
124 | this.storageHandler = storageHandler;
125 | if (SuperTokensLock.waiters === undefined) {
126 | SuperTokensLock.waiters = [];
127 | }
128 | }
129 |
130 | /**
131 | * @async
132 | * @memberOf Lock
133 | * @function acquireLock
134 | * @param {string} lockKey - Key for which the lock is being acquired
135 | * @param {number} [timeout=5000] - Maximum time for which the function will wait to acquire the lock
136 | * @returns {Promise}
137 | * @description Will return true if lock is being acquired, else false.
138 | * Also the lock can be acquired for maximum 10 secs
139 | */
140 | async acquireLock(lockKey: string, timeout: number = 5000) {
141 | let iat = Date.now() + generateRandomString(4);
142 | const MAX_TIME = Date.now() + timeout;
143 | const STORAGE_KEY = `${LOCK_STORAGE_KEY}-${lockKey}`;
144 | const STORAGE: StorageHandler = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
145 | while (Date.now() < MAX_TIME) {
146 | await delay(30);
147 | let lockObj = STORAGE.getItemSync(STORAGE_KEY);
148 | if (lockObj === null) {
149 | const TIMEOUT_KEY = `${this.id}-${lockKey}-${iat}`;
150 | // there is a problem if setItem happens at the exact same time for 2 different processes.. so we add some random delay here.
151 | await delay(Math.floor(Math.random() * 25));
152 | STORAGE.setItemSync(STORAGE_KEY, JSON.stringify({
153 | id: this.id,
154 | iat,
155 | timeoutKey: TIMEOUT_KEY,
156 | timeAcquired: Date.now(),
157 | timeRefreshed: Date.now()
158 | }));
159 | await delay(30); // this is to prevent race conditions. This time must be more than the time it takes for storage.setItem
160 | let lockObjPostDelay = STORAGE.getItemSync(STORAGE_KEY);
161 | if (lockObjPostDelay !== null) {
162 | let parsedLockObjPostDelay = JSON.parse(lockObjPostDelay);
163 | if (parsedLockObjPostDelay.id === this.id && parsedLockObjPostDelay.iat === iat) {
164 | this.acquiredIatSet.add(iat);
165 | this.refreshLockWhileAcquired(STORAGE_KEY, iat);
166 | return true;
167 | }
168 | }
169 | } else {
170 | SuperTokensLock.lockCorrector(this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler);
171 | await this.waitForSomethingToChange(MAX_TIME);
172 |
173 | }
174 | iat = Date.now() + generateRandomString(4);
175 | }
176 | return false;
177 | }
178 |
179 | private async refreshLockWhileAcquired(storageKey: string, iat: string) {
180 | setTimeout(async () => {
181 | await getProcessLock().lock(iat);
182 | if (!this.acquiredIatSet.has(iat)) {
183 | getProcessLock().unlock(iat);
184 | return;
185 | }
186 | const STORAGE: StorageHandler = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
187 | let lockObj = STORAGE.getItemSync(storageKey);
188 | if (lockObj !== null) {
189 | let parsedLockObj = JSON.parse(lockObj);
190 | parsedLockObj.timeRefreshed = Date.now();
191 | STORAGE.setItemSync(storageKey, JSON.stringify(parsedLockObj));
192 | getProcessLock().unlock(iat);
193 | } else {
194 | getProcessLock().unlock(iat);
195 | return;
196 | }
197 | this.refreshLockWhileAcquired(storageKey, iat);
198 | }, 1000);
199 | }
200 |
201 | private async waitForSomethingToChange(MAX_TIME: number) {
202 | await new Promise(resolve => {
203 | let resolvedCalled = false;
204 | let startedAt = Date.now();
205 | const MIN_TIME_TO_WAIT = 50; // ms
206 | let removedListeners = false;
207 | function stopWaiting() {
208 | if (!removedListeners) {
209 | window.removeEventListener('storage', stopWaiting);
210 | SuperTokensLock.removeFromWaiting(stopWaiting);
211 | clearTimeout(timeOutId);
212 | removedListeners = true;
213 | }
214 | if (!resolvedCalled) {
215 | resolvedCalled = true;
216 | let timeToWait = MIN_TIME_TO_WAIT - (Date.now() - startedAt);
217 | if (timeToWait > 0) {
218 | setTimeout(resolve, timeToWait);
219 | } else {
220 | resolve(null);
221 | }
222 | }
223 | }
224 | window.addEventListener('storage', stopWaiting);
225 | SuperTokensLock.addToWaiting(stopWaiting);
226 | let timeOutId = setTimeout(stopWaiting, Math.max(0, MAX_TIME - Date.now()));
227 | });
228 | }
229 |
230 | private static addToWaiting(func: any) {
231 | this.removeFromWaiting(func);
232 | if (SuperTokensLock.waiters === undefined) {
233 | return;
234 | }
235 | SuperTokensLock.waiters.push(func);
236 | }
237 |
238 | private static removeFromWaiting(func: any) {
239 | if (SuperTokensLock.waiters === undefined) {
240 | return;
241 | }
242 | SuperTokensLock.waiters = SuperTokensLock.waiters.filter(i => i !== func);
243 | }
244 |
245 | private static notifyWaiters() {
246 | if (SuperTokensLock.waiters === undefined) {
247 | return;
248 | }
249 | let waiters = [...SuperTokensLock.waiters]; // so that if Lock.waiters is changed it's ok.
250 | waiters.forEach(i => i());
251 | }
252 |
253 | /**
254 | * @function releaseLock
255 | * @memberOf Lock
256 | * @param {string} lockKey - Key for which lock is being released
257 | * @returns {void}
258 | * @description Release a lock.
259 | */
260 | async releaseLock(lockKey: string) {
261 | return await this.releaseLock__private__(lockKey);
262 | }
263 |
264 | /**
265 | * @function releaseLock
266 | * @memberOf Lock
267 | * @param {string} lockKey - Key for which lock is being released
268 | * @returns {void}
269 | * @description Release a lock.
270 | */
271 | private async releaseLock__private__(lockKey: string) {
272 | const STORAGE: StorageHandler = this.storageHandler === undefined ? DEFAULT_STORAGE_HANDLER : this.storageHandler;
273 | const STORAGE_KEY = `${LOCK_STORAGE_KEY}-${lockKey}`;
274 | let lockObj = STORAGE.getItemSync(STORAGE_KEY);
275 | if (lockObj === null) {
276 | return;
277 | }
278 | let parsedlockObj = JSON.parse(lockObj);
279 | if (parsedlockObj.id === this.id) {
280 | await getProcessLock().lock(parsedlockObj.iat);
281 |
282 | this.acquiredIatSet.delete(parsedlockObj.iat);
283 | STORAGE.removeItemSync(STORAGE_KEY);
284 |
285 | getProcessLock().unlock(parsedlockObj.iat);
286 |
287 | SuperTokensLock.notifyWaiters();
288 | }
289 | }
290 |
291 | /**
292 | * @function lockCorrector
293 | * @returns {void}
294 | * @description If a lock is acquired by a tab and the tab is closed before the lock is
295 | * released, this function will release those locks
296 | */
297 | private static lockCorrector(storageHandler: StorageHandler) {
298 | const MIN_ALLOWED_TIME = Date.now() - 5000;
299 | const STORAGE = storageHandler;
300 | const KEYS: string[] = [];
301 | let currIndex = 0;
302 | while (true) {
303 | let key = STORAGE.keySync(currIndex);
304 | if (key === null) {
305 | break;
306 | }
307 | KEYS.push(key);
308 | currIndex++;
309 | }
310 | let notifyWaiters = false;
311 | for (let i = 0; i < KEYS.length; i++) {
312 | const LOCK_KEY = KEYS[i];
313 | if (LOCK_KEY.includes(LOCK_STORAGE_KEY)) {
314 | let lockObj = STORAGE.getItemSync(LOCK_KEY);
315 | if (lockObj !== null) {
316 | let parsedlockObj = JSON.parse(lockObj);
317 | if ((parsedlockObj.timeRefreshed === undefined && parsedlockObj.timeAcquired < MIN_ALLOWED_TIME) ||
318 | (parsedlockObj.timeRefreshed !== undefined && parsedlockObj.timeRefreshed < MIN_ALLOWED_TIME)) {
319 | STORAGE.removeItemSync(LOCK_KEY);
320 | notifyWaiters = true;
321 | }
322 | }
323 | }
324 | }
325 | if (notifyWaiters) {
326 | SuperTokensLock.notifyWaiters();
327 | }
328 | }
329 | }
330 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "browser-tabs-lock",
3 | "version": "1.3.0",
4 | "description": "provides locking mechanism to sync across browser tabs",
5 | "main": "index.js",
6 | "scripts": {
7 | "pack-test": "npm run pack && npx mocha --timeout 40000 --exit",
8 | "pack": "rm -f ./bundle/* && ./node_modules/.bin/webpack -p",
9 | "build": "npx tsc -p tsconfig.json",
10 | "test": "npx mocha --timeout 40000 --exit",
11 | "postinstall": "node scripts/postinstall.js"
12 | },
13 | "repository": {
14 | "type": "git",
15 | "url": "git+https://github.com/supertokens/browser-tabs-lock.git"
16 | },
17 | "devDependencies": {
18 | "puppeteer": "2.0.0",
19 | "typescript": "3.5.2",
20 | "mocha": "6.1.4",
21 | "mocha-jsdom": "2.0.0",
22 | "webpack": "^4.35.0",
23 | "webpack-cli": "^3.3.5"
24 | },
25 | "dependencies": {
26 | "lodash": ">=4.17.21"
27 | },
28 | "keywords": [
29 | "browser",
30 | "tabs",
31 | "browser sync",
32 | "tabs synchronization",
33 | "locks",
34 | "tabs lock",
35 | "locking in browser",
36 | "chrome",
37 | "firefox",
38 | "IE",
39 | "safari"
40 | ],
41 | "contributors": [
42 | "bhumilsarvaiya",
43 | "rishabhpoddar",
44 | "nkshah2",
45 | "supertokens"
46 | ],
47 | "license": "MIT",
48 | "bugs": {
49 | "url": "https://github.com/supertokens/browser-tabs-lock/issues"
50 | },
51 | "homepage": "https://github.com/supertokens/browser-tabs-lock#readme"
52 | }
--------------------------------------------------------------------------------
/processLock.d.ts:
--------------------------------------------------------------------------------
1 | declare class ProcessLocking {
2 | static instance: undefined | ProcessLocking;
3 | private locked;
4 | static getInstance(): ProcessLocking;
5 | private addToLocked;
6 | isLocked: (key: string) => boolean;
7 | lock: (key: string) => Promise;
8 | unlock: (key: string) => void;
9 | }
10 | export default function getLock(): ProcessLocking;
11 | export {};
12 |
--------------------------------------------------------------------------------
/processLock.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | Object.defineProperty(exports, "__esModule", { value: true });
3 | var ProcessLocking = /** @class */ (function () {
4 | function ProcessLocking() {
5 | var _this = this;
6 | this.locked = new Map();
7 | this.addToLocked = function (key, toAdd) {
8 | var callbacks = _this.locked.get(key);
9 | if (callbacks === undefined) {
10 | if (toAdd === undefined) {
11 | _this.locked.set(key, []);
12 | }
13 | else {
14 | _this.locked.set(key, [toAdd]);
15 | }
16 | }
17 | else {
18 | if (toAdd !== undefined) {
19 | callbacks.unshift(toAdd);
20 | _this.locked.set(key, callbacks);
21 | }
22 | }
23 | };
24 | this.isLocked = function (key) {
25 | return _this.locked.has(key);
26 | };
27 | this.lock = function (key) {
28 | return new Promise(function (resolve, reject) {
29 | if (_this.isLocked(key)) {
30 | _this.addToLocked(key, resolve);
31 | }
32 | else {
33 | _this.addToLocked(key);
34 | resolve();
35 | }
36 | });
37 | };
38 | this.unlock = function (key) {
39 | var callbacks = _this.locked.get(key);
40 | if (callbacks === undefined || callbacks.length === 0) {
41 | _this.locked.delete(key);
42 | return;
43 | }
44 | var toCall = callbacks.pop();
45 | _this.locked.set(key, callbacks);
46 | if (toCall !== undefined) {
47 | setTimeout(toCall, 0);
48 | }
49 | };
50 | }
51 | ProcessLocking.getInstance = function () {
52 | if (ProcessLocking.instance === undefined) {
53 | ProcessLocking.instance = new ProcessLocking();
54 | }
55 | return ProcessLocking.instance;
56 | };
57 | return ProcessLocking;
58 | }());
59 | function getLock() {
60 | return ProcessLocking.getInstance();
61 | }
62 | exports.default = getLock;
63 |
--------------------------------------------------------------------------------
/processLock.ts:
--------------------------------------------------------------------------------
1 | declare let setTimeout: any;
2 | class ProcessLocking {
3 | static instance: undefined | ProcessLocking;
4 | private locked: Map void)[]> = new Map void)[]>();
5 |
6 |
7 | static getInstance() {
8 | if (ProcessLocking.instance === undefined) {
9 | ProcessLocking.instance = new ProcessLocking();
10 | }
11 | return ProcessLocking.instance;
12 | }
13 |
14 | private addToLocked = (key: string, toAdd?: () => void) => {
15 | let callbacks = this.locked.get(key);
16 | if (callbacks === undefined) {
17 | if (toAdd === undefined) {
18 | this.locked.set(key, []);
19 | } else {
20 | this.locked.set(key, [toAdd]);
21 | }
22 | } else {
23 | if (toAdd !== undefined) {
24 | callbacks.unshift(toAdd);
25 | this.locked.set(key, callbacks);
26 | }
27 | }
28 | }
29 |
30 | isLocked = (key: string): boolean => {
31 | return this.locked.has(key);
32 | }
33 |
34 | lock = (key: string): Promise => {
35 | return new Promise((resolve, reject) => {
36 | if (this.isLocked(key)) {
37 | this.addToLocked(key, resolve);
38 | } else {
39 | this.addToLocked(key);
40 | resolve();
41 | }
42 | });
43 | }
44 |
45 | unlock = (key: string) => {
46 | let callbacks = this.locked.get(key);
47 | if (callbacks === undefined || callbacks.length === 0) {
48 | this.locked.delete(key);
49 | return;
50 | }
51 | let toCall = callbacks.pop();
52 | this.locked.set(key, callbacks);
53 | if (toCall !== undefined) {
54 | setTimeout(toCall, 0);
55 | }
56 | }
57 | }
58 |
59 | export default function getLock(): ProcessLocking {
60 | return ProcessLocking.getInstance();
61 | }
--------------------------------------------------------------------------------
/scripts/postinstall.js:
--------------------------------------------------------------------------------
1 | let message = '\u001B[93mThank you for using browser-tabs-lock (\u001B[34m https://github.com/supertokens/browser-tabs-lock \u001B[93m).\n\n' +
2 | '\u001B[93mThis library was created as a part of a larger project, SuperTokens(\u001B[34m https://supertokens.io \u001B[93m) - an open source auth solution.\u001B[0m\n' +
3 | '\u001B[93mYou can also check out our other projects on \u001B[34mhttps://github.com/supertokens\u001B[93m\n\u001B[0m';
4 |
5 | console.log(message);
6 |
--------------------------------------------------------------------------------
/setupHooks:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | cp hooks/pre-commit .git/hooks/pre-commit
4 | chmod +x .git/hooks/pre-commit
--------------------------------------------------------------------------------
/test/counterTest.html:
--------------------------------------------------------------------------------
1 |
2 |
36 |
37 |
38 | HI
39 |
40 |
41 |
--------------------------------------------------------------------------------
/test/index.test.js:
--------------------------------------------------------------------------------
1 | let puppeteer = require("puppeteer");
2 |
3 | const wait = async (timeout) => new Promise((resolve) => {
4 | setTimeout(resolve, timeout);
5 | });
6 |
7 | describe("Test simple locking", async function () {
8 | it("Test that locking works when using more than 2 tabs", async function () {
9 | const domain = "file://" + process.cwd() + "/test/counterTest.html";
10 | const browser = await puppeteer.launch({
11 | args: ["--no-sandbox", "--disable-setuid-sandbox"],
12 | });
13 | const page0 = await browser.newPage();
14 |
15 | // Reset localStorage for testing domain
16 | await page0.goto(domain, { waitUntil: "load" });
17 | await page0.evaluate(() => {
18 | localStorage.setItem("tabs-global-counter", "0");
19 | });
20 |
21 | // Create multiple tabs and run script in each
22 | let tabCount = 15;
23 | let pages = [];
24 | for (let i = 0; i < tabCount; i++) {
25 | const page = await browser.newPage();
26 | await page.goto(domain, { waitUntil: "load" });
27 | await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
28 | page.evaluate(() => {
29 | doTask();
30 | });
31 | pages.push(page);
32 | }
33 |
34 | await wait(20000);
35 |
36 | for (let i = 0; i < pages.length; i++) {
37 | let page = pages[i];
38 | await page.evaluate(() => {
39 | isStopped = true;
40 | })
41 | }
42 |
43 | pages.forEach(page => {
44 | page.evaluate(() => {
45 | isStopped = true;
46 | })
47 | });
48 |
49 | let haveAllStopped = false;
50 |
51 | while (!haveAllStopped) {
52 | let results = [];
53 |
54 | for (let i = 0; i < pages.length; i++) {
55 | let page = pages[i];
56 | let result = await page.evaluate(() => {
57 | return hasActuallyStopped;
58 | });
59 | results.push(result);
60 | }
61 |
62 | if (!results.includes(false)) {
63 | haveAllStopped = true;
64 | }
65 | }
66 |
67 | let globalCounter = await page0.evaluate(() => {
68 | return parseInt(localStorage.getItem("tabs-global-counter"));
69 | });
70 |
71 | let tabCounterSum = 0;
72 |
73 | for (let i = 0; i < pages.length; i++) {
74 | let page = pages[i];
75 |
76 | let currentTabCounter = await page.evaluate(() => {
77 | return tabCounter;
78 | })
79 |
80 | tabCounterSum += currentTabCounter;
81 | }
82 |
83 | browser.close()
84 |
85 | if (tabCounterSum !== globalCounter || globalCounter <= 320) {
86 | throw new Error(`Numbers dont match: \nGlobal counter = ${globalCounter} \n tabCounterSum = ${tabCounterSum}`);
87 | }
88 | });
89 |
90 |
91 | it("Test that acquiring the same lock on multiple tabs succeeds after the first tab is closed", async function () {
92 | const domain = "file://" + process.cwd() + "/test/releaseOnClose.html";
93 | const browser = await puppeteer.launch({
94 | args: ["--no-sandbox", "--disable-setuid-sandbox"],
95 | });
96 |
97 | const page1 = await browser.newPage();
98 | await page1.goto(domain, { waitUntil: "load" });
99 | await page1.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
100 | await page1.evaluate(() => {
101 | doTask()
102 | })
103 |
104 | await wait(2000);
105 |
106 | let success = await page1.evaluate(() => {
107 | return didAcquireLock;
108 | });
109 |
110 | let page2 = await browser.newPage();
111 | await page2.goto(domain, { waitUntil: "load" });
112 | await page2.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
113 | await page2.evaluate(() => {
114 | doTask()
115 | })
116 |
117 | await wait(10000);
118 |
119 | success = await page2.evaluate(() => {
120 | return didAcquireLock;
121 | });
122 |
123 | if (success !== false) {
124 | throw new Error("Acquiring the same lock on a different tab without releasing it succeeded when it should have failed");
125 | }
126 |
127 | await page2.close();
128 |
129 | await page1.close();
130 |
131 | if (!page1.isClosed()) {
132 | throw new Error("Page 1 did not close even after calling page.close()")
133 | }
134 |
135 | page2 = await browser.newPage()
136 | await page2.goto(domain, { waitUntil: "load" });
137 | await page2.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
138 | await page2.evaluate(() => {
139 | doTask()
140 | })
141 |
142 | await wait(10000);
143 |
144 | success = await page2.evaluate(() => {
145 | return didAcquireLock;
146 | });
147 |
148 | if (!success) {
149 | throw new Error("Acquiring lock on page 2 failed even after page 1 closed");
150 | }
151 |
152 | browser.close();
153 | });
154 |
155 | it("Test that acquiring the same lock twice from the same tab fails", async function () {
156 | const domain = "file://" + process.cwd() + "/test/multiLockTest.html";
157 | const browser = await puppeteer.launch({
158 | args: ["--no-sandbox", "--disable-setuid-sandbox"],
159 | });
160 |
161 | const page = await browser.newPage();
162 | await page.goto(domain, { waitUntil: "load" });
163 | await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" })
164 | await page.evaluate(() => {
165 | doTask();
166 | })
167 |
168 | await wait(10000);
169 |
170 | let success = await page.evaluate(() => {
171 | return didAcquireLock;
172 | });
173 |
174 | if (success) {
175 | throw new Error("Acquiring the same lock twice in the same tab succeeded");
176 | }
177 |
178 | await page.evaluate(() => {
179 | shouldRelease = true;
180 | });
181 |
182 | await wait(10000);
183 |
184 | success = await page.evaluate(() => {
185 | return didAcquireLock;
186 | });
187 |
188 | if (!success) {
189 | throw new Error("Acquiring lock failed even after first lock released");
190 | }
191 |
192 | browser.close();
193 | });
194 |
195 | it("Test that multiple lock instances in the same tab using the same key works as expected", async function () {
196 | const domain = "file://" + process.cwd() + "/test/singleTabMultiLock.html";
197 | const browser = await puppeteer.launch({
198 | args: ["--no-sandbox", "--disable-setuid-sandbox"],
199 | });
200 |
201 | const page0 = await browser.newPage();
202 |
203 | // Reset localStorage for testing domain
204 | await page0.goto(domain, { waitUntil: "load" });
205 | await page0.evaluate(() => {
206 | localStorage.setItem("tabs-global-counter", "0");
207 | });
208 | page0.close();
209 |
210 | const page = await browser.newPage();
211 | await page.goto(domain, { waitUntil: "load" });
212 | await page.addScriptTag({ path: `./bundle/bundle.js`, type: "text/javascript" });
213 | await page.evaluate(() => {
214 | start();
215 | });
216 |
217 | await wait(20000);
218 |
219 | await page.evaluate(() => {
220 | shouldStop = true;
221 | });
222 |
223 | let haveAllStopped = false;
224 |
225 | while (!haveAllStopped) {
226 | let stopValues = await page.evaluate(() => {
227 | return didStopValues;
228 | });
229 |
230 | if (!stopValues.includes(false)) {
231 | haveAllStopped = true;
232 | }
233 | }
234 |
235 | let globalCounter = await page.evaluate(() => {
236 | return parseInt(localStorage.getItem("tabs-global-counter"));
237 | });
238 |
239 | let localCounterValues = await page.evaluate(() => {
240 | return localCounterValues;
241 | });
242 |
243 | let localCounterSum = 0;
244 |
245 | for (let i = 0; i < localCounterValues.length; i++) {
246 | localCounterSum += localCounterValues[i];
247 | }
248 |
249 | browser.close()
250 |
251 | if (localCounterSum !== globalCounter || globalCounter <= 300) {
252 | throw new Error(`Numbers dont match: \nGlobal counter = ${globalCounter} \n localCounterSum = ${localCounterSum}`);
253 | }
254 | });
255 | });
--------------------------------------------------------------------------------
/test/multiLockTest.html:
--------------------------------------------------------------------------------
1 |
2 |
39 |
40 |
41 | HI
42 |
43 |
44 |
--------------------------------------------------------------------------------
/test/releaseOnClose.html:
--------------------------------------------------------------------------------
1 |
2 |
18 |
19 |
20 | HI
21 |
22 |
23 |
--------------------------------------------------------------------------------
/test/singleTabMultiLock.html:
--------------------------------------------------------------------------------
1 |
2 |
51 |
52 |
53 | HI
54 |
55 |
56 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "lib": [
5 | "es6"
6 | ],
7 | "noImplicitAny": true,
8 | "allowSyntheticDefaultImports": true,
9 | "strictNullChecks": true,
10 | "noImplicitThis": true,
11 | "module": "commonJS",
12 | "moduleResolution": "node",
13 | "declaration": true
14 | },
15 | "compileOnSave": true
16 | }
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | var webpack = require("webpack");
2 | var path = require("path");
3 |
4 | var BUILD_DIR = path.resolve(__dirname, "");
5 | var APP_DIR = path.resolve(__dirname, "");
6 | var version = JSON.stringify(require("./package.json").version);
7 |
8 | var config = {
9 | entry: APP_DIR + "/bundleEntry.js",
10 | output: {
11 | path: BUILD_DIR + "/bundle",
12 | filename: `bundle.js`,
13 | library: "supertokenslock",
14 | }
15 | };
16 |
17 | module.exports = config;
--------------------------------------------------------------------------------