@amedia/user 0.13.39 → 0.13.41

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.
Files changed (86) hide show
  1. package/dist/user.cjs +1 -1
  2. package/dist/user.cjs.map +3 -3
  3. package/dist/user.d.ts +5 -5
  4. package/dist/user.js +1 -1
  5. package/dist/user.js.map +3 -3
  6. package/package.json +5 -3
  7. package/src/actions/authentication.spec.ts +51 -0
  8. package/src/actions/authentication.ts +43 -0
  9. package/src/actions/authorization.spec.ts +369 -0
  10. package/src/actions/authorization.ts +117 -0
  11. package/src/actions/preferences.spec.ts +41 -0
  12. package/src/actions/preferences.ts +41 -0
  13. package/src/actions/storage.ts +22 -0
  14. package/src/actions/userData.spec.ts +133 -0
  15. package/src/actions/userData.ts +68 -0
  16. package/src/autologin/index.spec.ts +239 -0
  17. package/src/autologin/index.ts +92 -0
  18. package/src/autologin/thirdPartyCookie.spec.ts +95 -0
  19. package/src/autologin/thirdPartyCookie.ts +55 -0
  20. package/src/cache/engines/global.spec.ts +62 -0
  21. package/src/cache/engines/global.ts +49 -0
  22. package/src/cache/index.spec.ts +130 -0
  23. package/src/cache/index.ts +48 -0
  24. package/src/cache/types.ts +12 -0
  25. package/src/clients/europa.spec.ts +209 -0
  26. package/src/clients/europa.ts +183 -0
  27. package/src/clients/jupiter.spec.ts +179 -0
  28. package/src/clients/jupiter.ts +119 -0
  29. package/src/clients/mercury.spec.ts +59 -0
  30. package/src/clients/mercury.ts +48 -0
  31. package/src/clients/mercuryLog.spec.ts +20 -0
  32. package/src/clients/mercuryLog.ts +67 -0
  33. package/src/clients/nebula.spec.ts +70 -0
  34. package/src/clients/nebula.ts +83 -0
  35. package/src/clients/pluto.spec.ts +165 -0
  36. package/src/clients/pluto.ts +118 -0
  37. package/src/eventHandlers/activation.ts +36 -0
  38. package/src/eventHandlers/authentication.ts +34 -0
  39. package/src/eventHandlers/eventMap.ts +34 -0
  40. package/src/eventHandlers/state.spec.ts +48 -0
  41. package/src/eventHandlers/state.ts +23 -0
  42. package/src/eventHandlers/storage.spec.ts +114 -0
  43. package/src/eventHandlers/storage.ts +45 -0
  44. package/src/eventHandlers/userAttributes.spec.ts +93 -0
  45. package/src/eventHandlers/userAttributes.ts +31 -0
  46. package/src/exceptions/FetchTimeoutError.ts +8 -0
  47. package/src/exceptions/PaywallError.ts +16 -0
  48. package/src/index-authentcation.spec.ts +26 -0
  49. package/src/index-storage.spec.ts +144 -0
  50. package/src/index-subscription.spec.ts +213 -0
  51. package/src/index.ts +40 -0
  52. package/src/janitor/index.spec.ts +18 -0
  53. package/src/janitor/index.ts +59 -0
  54. package/src/janitor/jobs/accessCookieRefresher.spec.ts +213 -0
  55. package/src/janitor/jobs/accessCookieRefresher.ts +98 -0
  56. package/src/janitor/jobs/daxsubCookie.spec.ts +109 -0
  57. package/src/janitor/jobs/daxsubCookie.ts +38 -0
  58. package/src/janitor/jobs/removeUserStorage.spec.ts +34 -0
  59. package/src/janitor/jobs/removeUserStorage.ts +12 -0
  60. package/src/lib/PaywallUnlockRequest.spec.ts +363 -0
  61. package/src/lib/PaywallUnlockRequest.ts +143 -0
  62. package/src/lib/UserDataRequest.spec.ts +231 -0
  63. package/src/lib/UserDataRequest.ts +267 -0
  64. package/src/lib/cookie.ts +121 -0
  65. package/src/lib/rpc.ts +19 -0
  66. package/src/store/index.spec.ts +49 -0
  67. package/src/store/index.ts +64 -0
  68. package/src/types.ts +22 -0
  69. package/src/utils/customEventWrapper.ts +58 -0
  70. package/src/utils/debouncer.spec.ts +252 -0
  71. package/src/utils/debouncer.ts +123 -0
  72. package/src/utils/deepEquals.ts +42 -0
  73. package/src/utils/expectBootLogs.ts +9 -0
  74. package/src/utils/getGlobalThis.ts +17 -0
  75. package/src/utils/getOrUpdate.spec.ts +166 -0
  76. package/src/utils/getOrUpdate.ts +66 -0
  77. package/src/utils/localhostCheck.ts +10 -0
  78. package/src/utils/location.ts +31 -0
  79. package/src/utils/log.spec.ts +148 -0
  80. package/src/utils/log.ts +124 -0
  81. package/src/utils/loginState.ts +24 -0
  82. package/src/utils/networkError.ts +11 -0
  83. package/src/utils/queue.ts +32 -0
  84. package/src/utils/type.ts +19 -0
  85. package/src/utils/url.spec.ts +33 -0
  86. package/src/utils/url.ts +37 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amedia/user",
3
- "version": "0.13.39",
3
+ "version": "0.13.41",
4
4
  "description": "Client lib for working with aID user and associated data",
5
5
  "repository": "https://github.com/amedia/amedia-user-js",
6
6
  "author": "Amedia Utvikling (ID og data)",
@@ -14,7 +14,8 @@
14
14
  }
15
15
  },
16
16
  "files": [
17
- "dist/*"
17
+ "dist/*",
18
+ "src/*"
18
19
  ],
19
20
  "typings": "dist/user.d.ts",
20
21
  "scripts": {
@@ -22,8 +23,9 @@
22
23
  "lint": "eslint ./src --ext .ts",
23
24
  "build": "npm install && node build.js",
24
25
  "typings": "tsc --noEmit",
26
+ "checkVersion": "node --experimental-json-modules checkVersion.js",
25
27
  "eik:package": "run-p typings lint && npm run test && npm run build && eik package",
26
- "prepublishOnly": "node checkVersion.cjs && run-p typings lint && npm run test && npm run build",
28
+ "prepublishOnly": "npm run checkVersion && run-p typings lint && npm run test && npm run build",
27
29
  "postpublish": "eik package"
28
30
  },
29
31
  "dependencies": {
@@ -0,0 +1,51 @@
1
+ import * as url from '../utils/url';
2
+ import * as location from '../utils/location';
3
+ import { login } from './authentication';
4
+
5
+ beforeEach(() => {
6
+ spyOn(url, 'getCurrentUrl').and.returnValue('https://www.telen.no/artikkel/');
7
+ spyOn(url, 'getCurrentPublicationDomain').and.returnValue('www.telen.no');
8
+ spyOn(location, 'navigateTo');
9
+ });
10
+
11
+ describe('authentication', () => {
12
+ describe('goToLoginPage', () => {
13
+ describe('when using URL or string for param', () => {
14
+ it('should return expected url for string', () => {
15
+ login('https://my.url/');
16
+ expect(location.navigateTo).toHaveBeenCalledWith(
17
+ 'https://www.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=https%3A%2F%2Fmy.url%2F'
18
+ );
19
+ });
20
+ it('should return expected url for URL', () => {
21
+ login(new URL('https://my.url'));
22
+ expect(location.navigateTo).toHaveBeenCalledWith(
23
+ 'https://www.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=https%3A%2F%2Fmy.url%2F'
24
+ );
25
+ });
26
+ });
27
+ describe('when changing environment', () => {
28
+ it('should resolve dev env', () => {
29
+ spyOn(url, 'getCurrentEnvironment').and.returnValue('localhost');
30
+ login('current');
31
+ expect(location.navigateTo).toHaveBeenCalledWith(
32
+ 'https://www.aid.no.localhost.api.no/aid/logg_inn/www.telen.no/?requestedUrl=current'
33
+ );
34
+ });
35
+ it('should resolve snap5 env', () => {
36
+ spyOn(url, 'getCurrentEnvironment').and.returnValue('snap5');
37
+ login('current');
38
+ expect(location.navigateTo).toHaveBeenCalledWith(
39
+ 'https://www-snap5.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=current'
40
+ );
41
+ });
42
+ it('should resolve prod env', () => {
43
+ spyOn(url, 'getCurrentEnvironment').and.returnValue('');
44
+ login('current');
45
+ expect(location.navigateTo).toHaveBeenCalledWith(
46
+ 'https://www.aid.no/aid/logg_inn/www.telen.no/?requestedUrl=current'
47
+ );
48
+ });
49
+ });
50
+ });
51
+ });
@@ -0,0 +1,43 @@
1
+ import { getCurrentSession, removeSession } from '../clients/pluto';
2
+ import cache from '../cache';
3
+ import { getRPCClient } from '../lib/rpc';
4
+ import { removeCookie } from '../lib/cookie';
5
+ import { getAidDomain, getCurrentPublicationDomain } from '../utils/url';
6
+ import log from '../utils/log';
7
+ import { UserAttributes } from '../types';
8
+ import { navigateTo } from '../utils/location';
9
+
10
+ export const login = (requestedUrl: URL | string) => {
11
+ const url = new URL(
12
+ `https://${getAidDomain()}/aid/logg_inn/${getCurrentPublicationDomain()}/`
13
+ );
14
+ url.searchParams.set(
15
+ 'requestedUrl',
16
+ requestedUrl instanceof URL ? requestedUrl.href : requestedUrl
17
+ );
18
+ navigateTo(url.href);
19
+ };
20
+
21
+ function clearCookies() {
22
+ removeCookie('VSTOKEN');
23
+ removeCookie('aid.session');
24
+ removeCookie('aid_invitation_code');
25
+ removeCookie('aid-reload-article');
26
+ removeCookie('daxsub');
27
+ }
28
+
29
+ export const logout = async () =>
30
+ // TODO: It now clears the entire cache. Might be too aggressive.
31
+ Promise.all([removeSession(getCurrentPublicationDomain()), cache.clear()])
32
+ .then(() => {
33
+ // TODO This should be separated from logout and instead be setup to listen on state changes on storage
34
+ getRPCClient().userAuthenticated(false);
35
+ clearCookies();
36
+ // In addition to removing the regular cookies we also want to remove VSTOKEN2 on explicit logout
37
+ removeCookie('VSTOKEN2');
38
+ })
39
+ .catch((reason) => {
40
+ log.error('Failure while logging out', reason);
41
+ });
42
+
43
+ export const getSession = (): Promise<UserAttributes> => getCurrentSession();
@@ -0,0 +1,369 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+
5
+ import {
6
+ activate,
7
+ getAccess,
8
+ hasAccess,
9
+ hasRecentlyPerformedPaywallReload,
10
+ setAccessCookies,
11
+ setHasPerformedPaywallReload,
12
+ setNonUserAccessCookie,
13
+ setUserAccessCookie,
14
+ } from './authorization';
15
+ import * as jupiter from '../clients/jupiter';
16
+ import * as cookie from '../lib/cookie';
17
+ import * as url from '../utils/url';
18
+ import * as mercury from '../clients/mercury';
19
+ import * as authentication from './authentication';
20
+ import { removeAllCookies } from '../lib/cookie';
21
+ import { AccessFeatures } from '../clients/jupiter';
22
+
23
+ const publicationDomain = 'www.avisnavn.no';
24
+
25
+ beforeEach(() => {
26
+ removeAllCookies();
27
+ jest.spyOn(cookie, 'setCookie');
28
+ });
29
+
30
+ describe('getAccess', () => {
31
+ beforeEach(() => {
32
+ url.setCurrentHostname('www.avisnavn.no');
33
+ jest
34
+ .spyOn(jupiter, 'checkForAccess')
35
+ .mockResolvedValue({ access: ['newspaper', 'plussalt'] });
36
+ });
37
+ it('returns list of access', async () => {
38
+ expect(await getAccess()).toEqual({
39
+ access: ['newspaper', 'plussalt'],
40
+ });
41
+ });
42
+ });
43
+
44
+ describe('activate', () => {
45
+ describe('when all is ok', () => {
46
+ beforeEach(() => {
47
+ jest
48
+ .spyOn(mercury, 'activateSubscription')
49
+ .mockResolvedValue(['whatever']);
50
+ });
51
+ it('Returns whatever mercury returns', async () => {
52
+ expect(await activate(['newspaper'])).toEqual(['whatever']);
53
+ expect(mercury.activateSubscription).toHaveBeenCalledWith(['newspaper']);
54
+ });
55
+ });
56
+
57
+ describe('when user is deactivated', () => {
58
+ beforeEach(() => {
59
+ jest
60
+ .spyOn(mercury, 'activateSubscription')
61
+ .mockRejectedValue(new mercury.UserDeactivatedError());
62
+ jest.spyOn(authentication, 'logout').mockResolvedValue(undefined);
63
+ });
64
+ it('Returns whatever mercury returns', async () => {
65
+ expect(await activate([])).toEqual([]);
66
+ expect(mercury.activateSubscription).toHaveBeenCalledWith([]);
67
+ expect(authentication.logout).toHaveBeenCalled();
68
+ });
69
+ });
70
+ });
71
+
72
+ describe('hasAccess', () => {
73
+ let access = false;
74
+ function itReturnsTrue() {
75
+ it('returns true', () => {
76
+ expect(access).toBeTruthy();
77
+ });
78
+ }
79
+ function itReturnsFalse() {
80
+ it('returns false', () => {
81
+ expect(access).not.toBeTruthy();
82
+ });
83
+ }
84
+ describe('with no access requested', () => {
85
+ beforeEach(() => {
86
+ access = hasAccess(['newspaper'], []);
87
+ });
88
+ itReturnsTrue();
89
+ });
90
+
91
+ describe('with access requested without access', () => {
92
+ beforeEach(() => {
93
+ access = hasAccess([], ['newspaper']);
94
+ });
95
+ itReturnsFalse();
96
+ });
97
+
98
+ describe('with access to some requested access feature', () => {
99
+ beforeEach(() => {
100
+ access = hasAccess(['newspaper'], ['all', 'plussalt', 'newspaper']);
101
+ });
102
+ itReturnsTrue();
103
+ });
104
+
105
+ describe('with access to other access features than requested requested access feature', () => {
106
+ beforeEach(() => {
107
+ access = hasAccess(['pluss', 'sport'], ['all', 'plussalt', 'newspaper']);
108
+ });
109
+ itReturnsFalse();
110
+ });
111
+ });
112
+
113
+ let cookieResponse: any;
114
+
115
+ function itReturnsCookieResponse(success: any, accessFeatures: AccessFeatures) {
116
+ it(`returns cookie response with success = ${success}`, () => {
117
+ expect(cookieResponse.success).toEqual(success);
118
+ });
119
+ it(`returns cookie response with accessFeatures = ${accessFeatures}`, () => {
120
+ expect(cookieResponse.accessFeatures).toEqual(accessFeatures);
121
+ });
122
+ }
123
+
124
+ function itSetsNoCookies() {
125
+ it('does not set any cookies', () => {
126
+ expect(cookie.setCookie).not.toHaveBeenCalled();
127
+ });
128
+ }
129
+
130
+ function itDoesNotSetVstokenCookie() {
131
+ it('does not set VSTOKEN cookie', () => {
132
+ expect(cookie.setCookie).not.toHaveBeenCalledWith('VSTOKEN');
133
+ });
134
+ }
135
+
136
+ function itSetsVstokenCookie() {
137
+ it('sets VSTOKEN cookie', () => {
138
+ expect(cookie.setCookie).toHaveBeenCalledWith(
139
+ 'VSTOKEN',
140
+ 'COOKIE_VALUE',
141
+ 365,
142
+ '/'
143
+ );
144
+ });
145
+ }
146
+
147
+ function itDoesNotSetVstoken2Cookie() {
148
+ it('does not set VSTOKEN2 cookie', () => {
149
+ expect(cookie.setCookie).not.toHaveBeenCalledWith('VSTOKEN2');
150
+ });
151
+ }
152
+
153
+ function itSetsVstoken2Cookie() {
154
+ it('sets VSTOKEN2 cookie', () => {
155
+ expect(cookie.setCookie).toHaveBeenCalledWith(
156
+ 'VSTOKEN2',
157
+ 'COOKIE2_VALUE',
158
+ 1,
159
+ '/'
160
+ );
161
+ });
162
+ }
163
+
164
+ function mockGetUserAccess(status: any, accessFeatures: AccessFeatures) {
165
+ beforeEach(async () => {
166
+ jest.spyOn(jupiter, 'getUserAccess').mockResolvedValue({
167
+ status,
168
+ cookie: 'COOKIE_VALUE',
169
+ access_features: accessFeatures,
170
+ });
171
+ });
172
+ }
173
+
174
+ function getUserAccessSucceeds(accessFeatures: AccessFeatures) {
175
+ mockGetUserAccess('success', accessFeatures);
176
+ }
177
+
178
+ function getUserAccessFails(accessFeatures: AccessFeatures) {
179
+ mockGetUserAccess('failure', accessFeatures);
180
+ }
181
+
182
+ function mockGetNonUserAccessSucceeds(
183
+ status: any,
184
+ accessFeatures: AccessFeatures
185
+ ) {
186
+ beforeEach(async () => {
187
+ jest.spyOn(jupiter, 'getNonUserAccess').mockResolvedValue({
188
+ status,
189
+ uuid: 'mycompany',
190
+ vstoken_cookie: 'COOKIE2_VALUE',
191
+ access_features: accessFeatures,
192
+ });
193
+ });
194
+ }
195
+
196
+ function getNonUserAccessSucceeds(accessFeatures: AccessFeatures) {
197
+ mockGetNonUserAccessSucceeds('success', accessFeatures);
198
+ }
199
+
200
+ function getNonUserAccessFails(accessFeatures: AccessFeatures) {
201
+ mockGetNonUserAccessSucceeds('failure', accessFeatures);
202
+ }
203
+
204
+ describe('setUserAccessCookie', () => {
205
+ describe('when getUserAccess is successful', () => {
206
+ getUserAccessSucceeds(['newspaper', 'plussalt']);
207
+ beforeEach(async () => {
208
+ cookieResponse = await setUserAccessCookie(publicationDomain);
209
+ });
210
+ itReturnsCookieResponse(true, ['newspaper', 'plussalt']);
211
+ itSetsVstokenCookie();
212
+ });
213
+
214
+ describe('when getUserAccess is not successful', () => {
215
+ getUserAccessFails(['newspaper', 'plussalt']);
216
+ beforeEach(async () => {
217
+ cookieResponse = await setUserAccessCookie(publicationDomain);
218
+ });
219
+ itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
220
+ itSetsNoCookies();
221
+ });
222
+ });
223
+
224
+ describe('setNonUserAccessCookie', () => {
225
+ describe('when getNonUserAccess is successful', () => {
226
+ getNonUserAccessSucceeds(['newspaper', 'plussalt']);
227
+ beforeEach(async () => {
228
+ cookieResponse = await setNonUserAccessCookie(publicationDomain);
229
+ });
230
+ itReturnsCookieResponse(true, ['newspaper', 'plussalt']);
231
+ itSetsVstoken2Cookie();
232
+ });
233
+
234
+ describe('when getNonUserAccess is not successful', () => {
235
+ getNonUserAccessFails(['newspaper', 'plussalt']);
236
+ beforeEach(async () => {
237
+ cookieResponse = await setNonUserAccessCookie(publicationDomain);
238
+ });
239
+ itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
240
+ itSetsNoCookies();
241
+ });
242
+ });
243
+
244
+ describe('setAccessCookies', () => {
245
+ describe('when both VSTOKEN and VSTOKEN2 requests succeed', () => {
246
+ getUserAccessSucceeds(['newspaper', 'plussalt']);
247
+ getNonUserAccessSucceeds(['sport', 'pluss', 'newspaper']);
248
+ beforeEach(async () => {
249
+ cookieResponse = await setAccessCookies(publicationDomain);
250
+ });
251
+ itReturnsCookieResponse(true, ['newspaper', 'pluss', 'plussalt', 'sport']);
252
+ itSetsVstokenCookie();
253
+ itSetsVstoken2Cookie();
254
+ });
255
+
256
+ describe('when VSTOKEN fails and VSTOKEN2 succeeds', () => {
257
+ getUserAccessFails(['newspaper']);
258
+ getNonUserAccessSucceeds(['sport', 'pluss', 'newspaper']);
259
+ beforeEach(async () => {
260
+ cookieResponse = await setAccessCookies(publicationDomain);
261
+ });
262
+ itReturnsCookieResponse(false, ['newspaper', 'pluss', 'sport']);
263
+ itDoesNotSetVstokenCookie();
264
+ itSetsVstoken2Cookie();
265
+ });
266
+
267
+ describe('when VSTOKEN succeeds and VSTOKEN2 fails', () => {
268
+ getUserAccessSucceeds(['newspaper', 'plussalt']);
269
+ getNonUserAccessFails(['newspaper']);
270
+ beforeEach(async () => {
271
+ cookieResponse = await setAccessCookies(publicationDomain);
272
+ });
273
+ itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
274
+ itSetsVstokenCookie();
275
+ itDoesNotSetVstoken2Cookie();
276
+ });
277
+
278
+ describe('when both VSTOKEN and VSTOKEN2 fails', () => {
279
+ getUserAccessFails(['newspaper', 'plussalt']);
280
+ getNonUserAccessFails(['newspaper']);
281
+ beforeEach(async () => {
282
+ cookieResponse = await setAccessCookies(publicationDomain);
283
+ });
284
+ itReturnsCookieResponse(false, ['newspaper', 'plussalt']);
285
+ itSetsNoCookies();
286
+ });
287
+ });
288
+
289
+ describe('reload loop protection', () => {
290
+ const currentUrl = 'http://www.avisnavn.no/myAwesomeArticle';
291
+ const otherUrl = 'https://www.avisnavn.no/someBoringArticle';
292
+
293
+ beforeEach(() => {
294
+ jest.spyOn(url, 'getCurrentUrl').mockReturnValue(currentUrl);
295
+ });
296
+
297
+ describe('setHasPerformedPaywallReload', () => {
298
+ describe('without requestedUrl', () => {
299
+ beforeEach(() => {
300
+ setHasPerformedPaywallReload();
301
+ });
302
+ it('sets aid-paywall-reload-performed with current URL as value', () => {
303
+ const twoMinutesFromNow = new Date().getTime() + 2 * 60 * 1000;
304
+ expect(cookie.setCookie).toHaveBeenCalledWith(
305
+ 'aid-paywall-reload-performed',
306
+ currentUrl,
307
+ expect.toBeWithin(twoMinutesFromNow - 5000, twoMinutesFromNow + 5000)
308
+ );
309
+ });
310
+ });
311
+ describe('with requestedUrl', () => {
312
+ beforeEach(() => {
313
+ setHasPerformedPaywallReload(otherUrl);
314
+ });
315
+ it('sets aid-paywall-reload-performed with current URL as value', () => {
316
+ const twoMinutesFromNow = new Date().getTime() + 2 * 60 * 1000;
317
+ expect(cookie.setCookie).toHaveBeenCalledWith(
318
+ 'aid-paywall-reload-performed',
319
+ otherUrl,
320
+ expect.toBeWithin(twoMinutesFromNow - 5000, twoMinutesFromNow + 5000)
321
+ );
322
+ });
323
+ });
324
+ });
325
+
326
+ describe('hasRecentlyPerformedPaywallReload', () => {
327
+ function itReturnsTrue() {
328
+ it('returns true', () => {
329
+ expect(hasRecentlyPerformedPaywallReload()).toBeTruthy();
330
+ });
331
+ }
332
+ function itReturnsFalse() {
333
+ it('returns false', () => {
334
+ expect(hasRecentlyPerformedPaywallReload()).toBeFalsy();
335
+ });
336
+ }
337
+ describe('when has recently tried to unlock paywall on same URL', () => {
338
+ beforeEach(() => {
339
+ setHasPerformedPaywallReload();
340
+ });
341
+ itReturnsTrue();
342
+ });
343
+ describe('when has recently tried to unlock paywall on different URL', () => {
344
+ beforeEach(() => {
345
+ jest
346
+ .spyOn(url, 'getCurrentUrl')
347
+ .mockReturnValueOnce(otherUrl)
348
+ .mockReturnValue(currentUrl);
349
+ setHasPerformedPaywallReload();
350
+ });
351
+ itReturnsFalse();
352
+ });
353
+ describe('when has recently tried to unlock paywall on different URL, and this URL is specified', () => {
354
+ beforeEach(() => {
355
+ jest
356
+ .spyOn(url, 'getCurrentUrl')
357
+ .mockReturnValueOnce(otherUrl) // This will be the value in our cookie
358
+ .mockReturnValue(currentUrl);
359
+ setHasPerformedPaywallReload();
360
+ });
361
+ it('returns true', () => {
362
+ expect(hasRecentlyPerformedPaywallReload(otherUrl)).toBeTruthy();
363
+ });
364
+ });
365
+ describe('when aid-paywall-reload-performed is not present', () => {
366
+ itReturnsFalse();
367
+ });
368
+ });
369
+ });
@@ -0,0 +1,117 @@
1
+ import {
2
+ checkForAccess,
3
+ getNonUserAccess,
4
+ getUserAccess,
5
+ } from '../clients/jupiter';
6
+ import { getCurrentPublicationDomain, getCurrentUrl } from '../utils/url';
7
+ import { UserAttributes } from '../types';
8
+ import { activateSubscription, UserDeactivatedError } from '../clients/mercury';
9
+ import { logout } from './authentication';
10
+ import { getCookie, setCookie } from '../lib/cookie';
11
+
12
+ type SetCookieResponse = { success: boolean; accessFeatures: string[] };
13
+
14
+ export const getAccess = (
15
+ accessFeatures: string[] = ['newspaper']
16
+ ): Promise<Pick<UserAttributes, 'access'>> =>
17
+ checkForAccess(getCurrentPublicationDomain(), accessFeatures);
18
+
19
+ export const activate = async (accessFeatures: string[]): Promise<string[]> => {
20
+ try {
21
+ return await activateSubscription(accessFeatures);
22
+ } catch (error) {
23
+ if (error instanceof UserDeactivatedError) {
24
+ await logout();
25
+ return [];
26
+ }
27
+ throw error;
28
+ }
29
+ };
30
+
31
+ export const hasAccess = (
32
+ currentAccessFeatures: string[],
33
+ requestedAccessFeatures: string[]
34
+ ): boolean =>
35
+ requestedAccessFeatures.length < 1 ||
36
+ requestedAccessFeatures.filter((requestedAccessFeature) =>
37
+ currentAccessFeatures.includes(requestedAccessFeature)
38
+ ).length > 0;
39
+
40
+ export const setUserAccessCookie = async (
41
+ publicationDomain: string
42
+ ): Promise<SetCookieResponse> => {
43
+ const vstoken = await getUserAccess(publicationDomain);
44
+ if (vstoken.status === 'success') {
45
+ /**
46
+ * The VSTOKEN cookie will live for 365 days, but a timestamp in the payload will ensure that it cannot
47
+ * be used to gain access for that long. The reason we want the cookie to live long is that it's also
48
+ * used to keep subscribers from seeing ads for buying the subscription they already have.
49
+ */
50
+ setCookie('VSTOKEN', vstoken.cookie, 365, '/');
51
+ }
52
+ return {
53
+ success: vstoken.status === 'success',
54
+ accessFeatures: vstoken.access_features,
55
+ };
56
+ };
57
+
58
+ export const setNonUserAccessCookie = async (
59
+ publicationDomain: string
60
+ ): Promise<SetCookieResponse> => {
61
+ const vstoken2 = await getNonUserAccess(publicationDomain);
62
+ if (vstoken2.status === 'success') {
63
+ setCookie('VSTOKEN2', vstoken2.vstoken_cookie, 1, '/');
64
+ }
65
+ return {
66
+ success: vstoken2.status === 'success',
67
+ accessFeatures: vstoken2.access_features,
68
+ };
69
+ };
70
+
71
+ export const setAccessCookies = async (
72
+ publicationDomain: string
73
+ ): Promise<SetCookieResponse> => {
74
+ const setters: Array<Promise<SetCookieResponse>> = [];
75
+ setters.push(
76
+ setUserAccessCookie(publicationDomain).catch(() =>
77
+ Promise.resolve({ success: false, accessFeatures: [] })
78
+ )
79
+ );
80
+ setters.push(
81
+ setNonUserAccessCookie(publicationDomain).catch(() =>
82
+ Promise.resolve({ success: false, accessFeatures: [] })
83
+ )
84
+ );
85
+ return Promise.all(setters).then((results) =>
86
+ results.reduce(
87
+ (accumulatedResult, result) => ({
88
+ success: accumulatedResult.success && result.success,
89
+ accessFeatures: accumulatedResult.accessFeatures
90
+ .concat(result.accessFeatures)
91
+ .filter((v, i, a) => a.indexOf(v) === i) // Remove duplicates by keeping only first copy
92
+ .sort(), // We want to keep result deterministic for easy testing
93
+ }),
94
+ {
95
+ success: true,
96
+ accessFeatures: [],
97
+ }
98
+ )
99
+ );
100
+ };
101
+
102
+ export const setHasPerformedPaywallReload = (requestedUrl?: string): void => {
103
+ const expires = new Date();
104
+ expires.setTime(expires.getTime() + 2 * 60 * 1000); // Add two minutes
105
+
106
+ setCookie(
107
+ 'aid-paywall-reload-performed',
108
+ requestedUrl || getCurrentUrl(),
109
+ expires
110
+ );
111
+ };
112
+
113
+ export const hasRecentlyPerformedPaywallReload = (
114
+ requestedUrl?: string
115
+ ): boolean =>
116
+ getCookie('aid-paywall-reload-performed') ===
117
+ (requestedUrl || getCurrentUrl());
@@ -0,0 +1,41 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
3
+ import { getPrivacyPreferences } from './preferences';
4
+
5
+ beforeEach(async () => {
6
+ await cache.clear();
7
+ });
8
+
9
+ const europaResponse = {
10
+ namespaces: {
11
+ privacy_preferences: {
12
+ allow_research_usage: 'true',
13
+ connect_with_surveys: true,
14
+ personalized_ads: 'false',
15
+ personalized_content: false,
16
+ },
17
+ },
18
+ };
19
+
20
+ describe('privacyPreferences', () => {
21
+ it('should return preferences', async () => {
22
+ fetch.mockResponse(JSON.stringify(europaResponse));
23
+ await getPrivacyPreferences();
24
+ expect(fetch).toHaveBeenCalledTimes(1);
25
+ });
26
+
27
+ it('should use cache if available', async () => {
28
+ fetch.mockResponse(JSON.stringify(europaResponse));
29
+
30
+ jest.spyOn(cache, 'get').mockReturnValue(
31
+ Promise.resolve({
32
+ allowResearchUsage: true,
33
+ connectWithSurveys: true,
34
+ personalizedAds: false,
35
+ personalizedContent: false,
36
+ })
37
+ );
38
+ await Promise.all([getPrivacyPreferences(), getPrivacyPreferences()]);
39
+ expect(fetch).toHaveBeenCalledTimes(0);
40
+ });
41
+ });
@@ -0,0 +1,41 @@
1
+ import { Record, Boolean } from 'runtypes';
2
+ import { getNamespaces } from '../clients/europa';
3
+ import { UserAttributes } from '../types';
4
+ import getOrUpdate from '../utils/getOrUpdate';
5
+
6
+ const CACHE_DURATION = 5 * 60000; // 5 minutes
7
+ const PRIVACY_PREFERENCES_CACHE_KEY = 'privacyPreferences';
8
+
9
+ export const PrivacyPreferencesSchema = Record({
10
+ allowResearchUsage: Boolean,
11
+ connectWithSurveys: Boolean,
12
+ personalizedAds: Boolean,
13
+ personalizedContent: Boolean,
14
+ });
15
+
16
+ const toBoolean = (val: string | boolean) => val === 'true' || val === true;
17
+
18
+ export const getPrivacyPreferences = async (): Promise<
19
+ Pick<UserAttributes, 'privacyPreferences'>
20
+ > =>
21
+ getOrUpdate(PRIVACY_PREFERENCES_CACHE_KEY, PrivacyPreferencesSchema, () =>
22
+ getNamespaces(['privacy_preferences']).then((namespaces) => {
23
+ const privacyPreferences: any = namespaces.privacy_preferences;
24
+
25
+ return {
26
+ ttl: CACHE_DURATION,
27
+ data: {
28
+ allowResearchUsage: toBoolean(
29
+ privacyPreferences.allow_research_usage
30
+ ),
31
+ connectWithSurveys: toBoolean(
32
+ privacyPreferences.connect_with_surveys
33
+ ),
34
+ personalizedAds: toBoolean(privacyPreferences.personalized_ads),
35
+ personalizedContent: toBoolean(
36
+ privacyPreferences.personalized_content
37
+ ),
38
+ },
39
+ };
40
+ })
41
+ ).then((data) => ({ privacyPreferences: data }));