@dhis2/app-service-offline 2.12.0-beta.1 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -33,6 +33,12 @@ Object.defineProperty(exports, "useOnlineStatus", {
33
33
  return _onlineStatus.useOnlineStatus;
34
34
  }
35
35
  });
36
+ Object.defineProperty(exports, "clearSensitiveCaches", {
37
+ enumerable: true,
38
+ get: function () {
39
+ return _clearSensitiveCaches.clearSensitiveCaches;
40
+ }
41
+ });
36
42
 
37
43
  var _offlineProvider = require("./lib/offline-provider");
38
44
 
@@ -40,4 +46,6 @@ var _cacheableSection = require("./lib/cacheable-section");
40
46
 
41
47
  var _cacheableSectionState = require("./lib/cacheable-section-state");
42
48
 
43
- var _onlineStatus = require("./lib/online-status");
49
+ var _onlineStatus = require("./lib/online-status");
50
+
51
+ var _clearSensitiveCaches = require("./lib/clear-sensitive-caches");
@@ -0,0 +1,131 @@
1
+ "use strict";
2
+
3
+ var _FDBFactory = _interopRequireDefault(require("fake-indexeddb/lib/FDBFactory"));
4
+
5
+ var _idb = require("idb");
6
+
7
+ require("fake-indexeddb/auto");
8
+
9
+ var _clearSensitiveCaches = require("../clear-sensitive-caches");
10
+
11
+ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
12
+
13
+ // Mocks for CacheStorage API
14
+ const keysMockDefault = jest.fn().mockImplementation(async () => []);
15
+ const deleteMockDefault = jest.fn().mockImplementation(async () => null);
16
+ const cachesDefault = {
17
+ keys: keysMockDefault,
18
+ delete: deleteMockDefault
19
+ };
20
+ window.caches = cachesDefault;
21
+ afterEach(() => {
22
+ window.caches = cachesDefault;
23
+ jest.clearAllMocks();
24
+ }); // silence debug logs for these tests
25
+
26
+ const originalDebug = console.debug;
27
+ beforeAll(() => {
28
+ jest.spyOn(console, 'debug').mockImplementation((...args) => {
29
+ const pattern = /Clearing sensitive caches/;
30
+
31
+ if (typeof args[0] === 'string' && pattern.test(args[0])) {
32
+ return;
33
+ }
34
+
35
+ return originalDebug.call(console, ...args);
36
+ });
37
+ });
38
+ afterAll(() => {
39
+ ;
40
+ console.debug.mockRestore();
41
+ });
42
+ it('does not fail if there are no caches or no sections-db', () => {
43
+ return expect((0, _clearSensitiveCaches.clearSensitiveCaches)()).resolves.toBeDefined();
44
+ });
45
+ it('clears potentially sensitive caches', async () => {
46
+ const keysMock = jest.fn().mockImplementation(async () => ['cache1', 'cache2', 'app-shell']);
47
+ window.caches = { ...cachesDefault,
48
+ keys: keysMock
49
+ };
50
+ await (0, _clearSensitiveCaches.clearSensitiveCaches)();
51
+ expect(deleteMockDefault).toHaveBeenCalledTimes(3);
52
+ expect(deleteMockDefault.mock.calls[0][0]).toBe('cache1');
53
+ expect(deleteMockDefault.mock.calls[1][0]).toBe('cache2');
54
+ expect(deleteMockDefault.mock.calls[2][0]).toBe('app-shell');
55
+ });
56
+ it('preserves keepable caches', async () => {
57
+ const keysMock = jest.fn().mockImplementation(async () => ['cache1', 'cache2', 'app-shell', 'other-assets', 'workbox-precache-v2-https://hey.howareya.now/']);
58
+ window.caches = { ...cachesDefault,
59
+ keys: keysMock
60
+ };
61
+ await (0, _clearSensitiveCaches.clearSensitiveCaches)();
62
+ expect(deleteMockDefault).toHaveBeenCalledTimes(3);
63
+ expect(deleteMockDefault.mock.calls[0][0]).toBe('cache1');
64
+ expect(deleteMockDefault.mock.calls[1][0]).toBe('cache2');
65
+ expect(deleteMockDefault.mock.calls[2][0]).toBe('app-shell');
66
+ expect(deleteMockDefault).not.toHaveBeenCalledWith('other-assets');
67
+ expect(deleteMockDefault).not.toHaveBeenCalledWith('workbox-precache-v2-https://hey.howareya.now/');
68
+ });
69
+ describe('clears sections-db', () => {
70
+ // Test DB
71
+ function openTestDB(dbName) {
72
+ // simplified version of app platform openDB logic
73
+ return (0, _idb.openDB)(dbName, 1, {
74
+ upgrade(db) {
75
+ db.createObjectStore(_clearSensitiveCaches.SECTIONS_STORE, {
76
+ keyPath: 'sectionId'
77
+ });
78
+ }
79
+
80
+ });
81
+ }
82
+
83
+ afterEach(() => {
84
+ // reset indexedDB state
85
+ window.indexedDB = new _FDBFactory.default();
86
+ });
87
+ it('clears sections-db if it exists', async () => {
88
+ // Open and populate test DB
89
+ const db = await openTestDB(_clearSensitiveCaches.SECTIONS_DB);
90
+ await db.put(_clearSensitiveCaches.SECTIONS_STORE, {
91
+ sectionId: 'id-1',
92
+ lastUpdated: new Date(),
93
+ requests: 3
94
+ });
95
+ await db.put(_clearSensitiveCaches.SECTIONS_STORE, {
96
+ sectionId: 'id-2',
97
+ lastUpdated: new Date(),
98
+ requests: 3
99
+ });
100
+ await (0, _clearSensitiveCaches.clearSensitiveCaches)(); // Sections-db should be cleared
101
+
102
+ const allSections = await db.getAll(_clearSensitiveCaches.SECTIONS_STORE);
103
+ expect(allSections).toHaveLength(0);
104
+ });
105
+ it("doesn't clear sections-db if it doesn't exist and doesn't open a new one", async () => {
106
+ const openMock = jest.fn();
107
+ window.indexedDB.open = openMock;
108
+ expect(await indexedDB.databases()).not.toContain(_clearSensitiveCaches.SECTIONS_DB);
109
+ await (0, _clearSensitiveCaches.clearSensitiveCaches)();
110
+ expect(openMock).not.toHaveBeenCalled();
111
+ return expect(await indexedDB.databases()).not.toContain(_clearSensitiveCaches.SECTIONS_DB);
112
+ });
113
+ it("doesn't handle IDB if 'databases' property is not on window.indexedDB", async () => {
114
+ // Open DB -- 'indexedDB.open' _would_ get called in this test
115
+ // if 'databases' property exists
116
+ await openTestDB(_clearSensitiveCaches.SECTIONS_DB);
117
+ const openMock = jest.fn();
118
+ window.indexedDB.open = openMock; // Remove 'databases' from indexedDB prototype for this test
119
+ // (simulates Firefox environment)
120
+
121
+ const idbProto = Object.getPrototypeOf(window.indexedDB);
122
+ const databases = idbProto.databases;
123
+ delete idbProto.databases;
124
+ expect('databases' in window.indexedDB).toBe(false);
125
+ await expect((0, _clearSensitiveCaches.clearSensitiveCaches)()).resolves.toBeDefined();
126
+ expect(openMock).not.toHaveBeenCalled(); // Restore indexedDB prototype for later tests
127
+
128
+ idbProto.databases = databases;
129
+ expect('databases' in window.indexedDB).toBe(true);
130
+ });
131
+ });
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.clearSensitiveCaches = clearSensitiveCaches;
7
+ exports.SECTIONS_STORE = exports.SECTIONS_DB = void 0;
8
+ // IndexedDB names; should be the same as in @dhis2/pwa
9
+ const SECTIONS_DB = 'sections-db';
10
+ exports.SECTIONS_DB = SECTIONS_DB;
11
+ const SECTIONS_STORE = 'sections-store'; // Non-sensitive caches that can be kept:
12
+
13
+ exports.SECTIONS_STORE = SECTIONS_STORE;
14
+ const KEEPABLE_CACHES = [/^workbox-precache/, // precached static assets
15
+ /^other-assets/ // static assets cached at runtime - shouldn't be sensitive
16
+ ];
17
+
18
+ /*
19
+ * Clears the 'sections-db' IndexedDB if it exists. Designed to avoid opening
20
+ * a new DB if it doesn't exist yet. Firefox can't check if 'sections-db'
21
+ * exists, in which circumstance the IndexedDB is unaffected. It's inelegant
22
+ * but acceptable because the IndexedDB has no sensitive data (only metadata
23
+ * of recorded sections), and the OfflineInterface handles discrepancies
24
+ * between CacheStorage and IndexedDB.
25
+ */
26
+ const clearDB = async dbName => {
27
+ if (!('databases' in indexedDB)) {
28
+ // FF does not have indexedDB.databases. For that, just clear caches,
29
+ // and offline interface will handle discrepancies in PWA apps.
30
+ return;
31
+ }
32
+
33
+ const dbs = await window.indexedDB.databases();
34
+
35
+ if (!dbs.some(({
36
+ name
37
+ }) => name === dbName)) {
38
+ // Sections-db is not created; nothing to do here
39
+ return;
40
+ }
41
+
42
+ return new Promise((resolve, reject) => {
43
+ // IndexedDB fun:
44
+ const openDBRequest = indexedDB.open(dbName);
45
+
46
+ openDBRequest.onsuccess = e => {
47
+ const db = e.target.result;
48
+ const tx = db.transaction(SECTIONS_STORE, 'readwrite'); // When the transaction completes is when the operation is done:
49
+
50
+ tx.oncomplete = () => resolve();
51
+
52
+ tx.onerror = e => reject(e.target.error);
53
+
54
+ const os = tx.objectStore(SECTIONS_STORE);
55
+ const clearReq = os.clear();
56
+
57
+ clearReq.onerror = e => reject(e.target.error);
58
+ };
59
+
60
+ openDBRequest.onerror = e => {
61
+ reject(e.target.error);
62
+ };
63
+ });
64
+ };
65
+ /**
66
+ * Used to clear caches and 'sections-db' IndexedDB when a user logs out or a
67
+ * different user logs in to prevent someone from accessing a different user's
68
+ * caches. Should be able to be used in a non-PWA app.
69
+ */
70
+
71
+
72
+ async function clearSensitiveCaches(dbName = SECTIONS_DB) {
73
+ console.debug('Clearing sensitive caches');
74
+ const cacheKeys = await caches.keys();
75
+ return Promise.all([clearDB(dbName), // remove caches if not in keepable list
76
+ ...cacheKeys.map(key => {
77
+ if (!KEEPABLE_CACHES.some(pattern => pattern.test(key))) {
78
+ // .then() satisfies typescript
79
+ return caches.delete(key).then(() => undefined);
80
+ }
81
+ })]).then(responses => {
82
+ // Return true if any caches have been cleared
83
+ // (caches.delete() returns true if a cache is deleted successfully)
84
+ // PWA apps can reload to restore their app shell cache
85
+ return responses.some(response => response);
86
+ });
87
+ }
package/build/es/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  export { OfflineProvider } from './lib/offline-provider';
2
2
  export { CacheableSection, useCacheableSection } from './lib/cacheable-section';
3
3
  export { useCachedSections } from './lib/cacheable-section-state';
4
- export { useOnlineStatus } from './lib/online-status';
4
+ export { useOnlineStatus } from './lib/online-status';
5
+ export { clearSensitiveCaches } from './lib/clear-sensitive-caches';
@@ -0,0 +1,123 @@
1
+ import FDBFactory from 'fake-indexeddb/lib/FDBFactory';
2
+ import { openDB } from 'idb';
3
+ import 'fake-indexeddb/auto';
4
+ import { clearSensitiveCaches, SECTIONS_DB, SECTIONS_STORE } from '../clear-sensitive-caches'; // Mocks for CacheStorage API
5
+
6
+ const keysMockDefault = jest.fn().mockImplementation(async () => []);
7
+ const deleteMockDefault = jest.fn().mockImplementation(async () => null);
8
+ const cachesDefault = {
9
+ keys: keysMockDefault,
10
+ delete: deleteMockDefault
11
+ };
12
+ window.caches = cachesDefault;
13
+ afterEach(() => {
14
+ window.caches = cachesDefault;
15
+ jest.clearAllMocks();
16
+ }); // silence debug logs for these tests
17
+
18
+ const originalDebug = console.debug;
19
+ beforeAll(() => {
20
+ jest.spyOn(console, 'debug').mockImplementation((...args) => {
21
+ const pattern = /Clearing sensitive caches/;
22
+
23
+ if (typeof args[0] === 'string' && pattern.test(args[0])) {
24
+ return;
25
+ }
26
+
27
+ return originalDebug.call(console, ...args);
28
+ });
29
+ });
30
+ afterAll(() => {
31
+ ;
32
+ console.debug.mockRestore();
33
+ });
34
+ it('does not fail if there are no caches or no sections-db', () => {
35
+ return expect(clearSensitiveCaches()).resolves.toBeDefined();
36
+ });
37
+ it('clears potentially sensitive caches', async () => {
38
+ const keysMock = jest.fn().mockImplementation(async () => ['cache1', 'cache2', 'app-shell']);
39
+ window.caches = { ...cachesDefault,
40
+ keys: keysMock
41
+ };
42
+ await clearSensitiveCaches();
43
+ expect(deleteMockDefault).toHaveBeenCalledTimes(3);
44
+ expect(deleteMockDefault.mock.calls[0][0]).toBe('cache1');
45
+ expect(deleteMockDefault.mock.calls[1][0]).toBe('cache2');
46
+ expect(deleteMockDefault.mock.calls[2][0]).toBe('app-shell');
47
+ });
48
+ it('preserves keepable caches', async () => {
49
+ const keysMock = jest.fn().mockImplementation(async () => ['cache1', 'cache2', 'app-shell', 'other-assets', 'workbox-precache-v2-https://hey.howareya.now/']);
50
+ window.caches = { ...cachesDefault,
51
+ keys: keysMock
52
+ };
53
+ await clearSensitiveCaches();
54
+ expect(deleteMockDefault).toHaveBeenCalledTimes(3);
55
+ expect(deleteMockDefault.mock.calls[0][0]).toBe('cache1');
56
+ expect(deleteMockDefault.mock.calls[1][0]).toBe('cache2');
57
+ expect(deleteMockDefault.mock.calls[2][0]).toBe('app-shell');
58
+ expect(deleteMockDefault).not.toHaveBeenCalledWith('other-assets');
59
+ expect(deleteMockDefault).not.toHaveBeenCalledWith('workbox-precache-v2-https://hey.howareya.now/');
60
+ });
61
+ describe('clears sections-db', () => {
62
+ // Test DB
63
+ function openTestDB(dbName) {
64
+ // simplified version of app platform openDB logic
65
+ return openDB(dbName, 1, {
66
+ upgrade(db) {
67
+ db.createObjectStore(SECTIONS_STORE, {
68
+ keyPath: 'sectionId'
69
+ });
70
+ }
71
+
72
+ });
73
+ }
74
+
75
+ afterEach(() => {
76
+ // reset indexedDB state
77
+ window.indexedDB = new FDBFactory();
78
+ });
79
+ it('clears sections-db if it exists', async () => {
80
+ // Open and populate test DB
81
+ const db = await openTestDB(SECTIONS_DB);
82
+ await db.put(SECTIONS_STORE, {
83
+ sectionId: 'id-1',
84
+ lastUpdated: new Date(),
85
+ requests: 3
86
+ });
87
+ await db.put(SECTIONS_STORE, {
88
+ sectionId: 'id-2',
89
+ lastUpdated: new Date(),
90
+ requests: 3
91
+ });
92
+ await clearSensitiveCaches(); // Sections-db should be cleared
93
+
94
+ const allSections = await db.getAll(SECTIONS_STORE);
95
+ expect(allSections).toHaveLength(0);
96
+ });
97
+ it("doesn't clear sections-db if it doesn't exist and doesn't open a new one", async () => {
98
+ const openMock = jest.fn();
99
+ window.indexedDB.open = openMock;
100
+ expect(await indexedDB.databases()).not.toContain(SECTIONS_DB);
101
+ await clearSensitiveCaches();
102
+ expect(openMock).not.toHaveBeenCalled();
103
+ return expect(await indexedDB.databases()).not.toContain(SECTIONS_DB);
104
+ });
105
+ it("doesn't handle IDB if 'databases' property is not on window.indexedDB", async () => {
106
+ // Open DB -- 'indexedDB.open' _would_ get called in this test
107
+ // if 'databases' property exists
108
+ await openTestDB(SECTIONS_DB);
109
+ const openMock = jest.fn();
110
+ window.indexedDB.open = openMock; // Remove 'databases' from indexedDB prototype for this test
111
+ // (simulates Firefox environment)
112
+
113
+ const idbProto = Object.getPrototypeOf(window.indexedDB);
114
+ const databases = idbProto.databases;
115
+ delete idbProto.databases;
116
+ expect('databases' in window.indexedDB).toBe(false);
117
+ await expect(clearSensitiveCaches()).resolves.toBeDefined();
118
+ expect(openMock).not.toHaveBeenCalled(); // Restore indexedDB prototype for later tests
119
+
120
+ idbProto.databases = databases;
121
+ expect('databases' in window.indexedDB).toBe(true);
122
+ });
123
+ });
@@ -0,0 +1,78 @@
1
+ // IndexedDB names; should be the same as in @dhis2/pwa
2
+ export const SECTIONS_DB = 'sections-db';
3
+ export const SECTIONS_STORE = 'sections-store'; // Non-sensitive caches that can be kept:
4
+
5
+ const KEEPABLE_CACHES = [/^workbox-precache/, // precached static assets
6
+ /^other-assets/ // static assets cached at runtime - shouldn't be sensitive
7
+ ];
8
+
9
+ /*
10
+ * Clears the 'sections-db' IndexedDB if it exists. Designed to avoid opening
11
+ * a new DB if it doesn't exist yet. Firefox can't check if 'sections-db'
12
+ * exists, in which circumstance the IndexedDB is unaffected. It's inelegant
13
+ * but acceptable because the IndexedDB has no sensitive data (only metadata
14
+ * of recorded sections), and the OfflineInterface handles discrepancies
15
+ * between CacheStorage and IndexedDB.
16
+ */
17
+ const clearDB = async dbName => {
18
+ if (!('databases' in indexedDB)) {
19
+ // FF does not have indexedDB.databases. For that, just clear caches,
20
+ // and offline interface will handle discrepancies in PWA apps.
21
+ return;
22
+ }
23
+
24
+ const dbs = await window.indexedDB.databases();
25
+
26
+ if (!dbs.some(({
27
+ name
28
+ }) => name === dbName)) {
29
+ // Sections-db is not created; nothing to do here
30
+ return;
31
+ }
32
+
33
+ return new Promise((resolve, reject) => {
34
+ // IndexedDB fun:
35
+ const openDBRequest = indexedDB.open(dbName);
36
+
37
+ openDBRequest.onsuccess = e => {
38
+ const db = e.target.result;
39
+ const tx = db.transaction(SECTIONS_STORE, 'readwrite'); // When the transaction completes is when the operation is done:
40
+
41
+ tx.oncomplete = () => resolve();
42
+
43
+ tx.onerror = e => reject(e.target.error);
44
+
45
+ const os = tx.objectStore(SECTIONS_STORE);
46
+ const clearReq = os.clear();
47
+
48
+ clearReq.onerror = e => reject(e.target.error);
49
+ };
50
+
51
+ openDBRequest.onerror = e => {
52
+ reject(e.target.error);
53
+ };
54
+ });
55
+ };
56
+ /**
57
+ * Used to clear caches and 'sections-db' IndexedDB when a user logs out or a
58
+ * different user logs in to prevent someone from accessing a different user's
59
+ * caches. Should be able to be used in a non-PWA app.
60
+ */
61
+
62
+
63
+ export async function clearSensitiveCaches(dbName = SECTIONS_DB) {
64
+ console.debug('Clearing sensitive caches');
65
+ const cacheKeys = await caches.keys();
66
+ return Promise.all([clearDB(dbName), // remove caches if not in keepable list
67
+ ...cacheKeys.map(key => {
68
+ if (!KEEPABLE_CACHES.some(pattern => pattern.test(key))) {
69
+ // .then() satisfies typescript
70
+ return caches.delete(key).then(() => undefined);
71
+ }
72
+ })]).then(responses => {
73
+ // Return true if any caches have been cleared
74
+ // (caches.delete() returns true if a cache is deleted successfully)
75
+ // PWA apps can reload to restore their app shell cache
76
+ return responses.some(response => response);
77
+ });
78
+ }
@@ -2,3 +2,4 @@ export { OfflineProvider } from './lib/offline-provider';
2
2
  export { CacheableSection, useCacheableSection } from './lib/cacheable-section';
3
3
  export { useCachedSections } from './lib/cacheable-section-state';
4
4
  export { useOnlineStatus } from './lib/online-status';
5
+ export { clearSensitiveCaches } from './lib/clear-sensitive-caches';
@@ -0,0 +1,16 @@
1
+ export declare const SECTIONS_DB = "sections-db";
2
+ export declare const SECTIONS_STORE = "sections-store";
3
+ declare global {
4
+ interface IDBFactory {
5
+ databases(): Promise<[{
6
+ name: string;
7
+ version: number;
8
+ }]>;
9
+ }
10
+ }
11
+ /**
12
+ * Used to clear caches and 'sections-db' IndexedDB when a user logs out or a
13
+ * different user logs in to prevent someone from accessing a different user's
14
+ * caches. Should be able to be used in a non-PWA app.
15
+ */
16
+ export declare function clearSensitiveCaches(dbName?: string): Promise<any>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dhis2/app-service-offline",
3
3
  "description": "A runtime service for online/offline detection and offline caching",
4
- "version": "2.12.0-beta.1",
4
+ "version": "2.12.0",
5
5
  "main": "./build/cjs/index.js",
6
6
  "module": "./build/es/index.js",
7
7
  "types": "build/types/index.d.ts",
@@ -33,7 +33,7 @@
33
33
  "coverage": "yarn test --coverage"
34
34
  },
35
35
  "peerDependencies": {
36
- "@dhis2/app-service-alerts": "2.12.0-beta.1",
36
+ "@dhis2/app-service-alerts": "2.12.0",
37
37
  "prop-types": "^15.7.2",
38
38
  "react": "^16.8.6",
39
39
  "react-dom": "^16.8.6"