@amedia/user 0.13.38 → 0.13.40

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 (87) hide show
  1. package/README.md +252 -24
  2. package/dist/user.cjs +1 -1
  3. package/dist/user.cjs.map +3 -3
  4. package/dist/user.d.ts +5 -5
  5. package/dist/user.js +1 -1
  6. package/dist/user.js.map +3 -3
  7. package/package.json +10 -8
  8. package/src/actions/authentication.spec.ts +51 -0
  9. package/src/actions/authentication.ts +43 -0
  10. package/src/actions/authorization.spec.ts +369 -0
  11. package/src/actions/authorization.ts +117 -0
  12. package/src/actions/preferences.spec.ts +41 -0
  13. package/src/actions/preferences.ts +41 -0
  14. package/src/actions/storage.ts +22 -0
  15. package/src/actions/userData.spec.ts +133 -0
  16. package/src/actions/userData.ts +68 -0
  17. package/src/autologin/index.spec.ts +239 -0
  18. package/src/autologin/index.ts +92 -0
  19. package/src/autologin/thirdPartyCookie.spec.ts +95 -0
  20. package/src/autologin/thirdPartyCookie.ts +55 -0
  21. package/src/cache/engines/global.spec.ts +62 -0
  22. package/src/cache/engines/global.ts +49 -0
  23. package/src/cache/index.spec.ts +130 -0
  24. package/src/cache/index.ts +48 -0
  25. package/src/cache/types.ts +12 -0
  26. package/src/clients/europa.spec.ts +209 -0
  27. package/src/clients/europa.ts +183 -0
  28. package/src/clients/jupiter.spec.ts +179 -0
  29. package/src/clients/jupiter.ts +119 -0
  30. package/src/clients/mercury.spec.ts +59 -0
  31. package/src/clients/mercury.ts +48 -0
  32. package/src/clients/mercuryLog.spec.ts +20 -0
  33. package/src/clients/mercuryLog.ts +67 -0
  34. package/src/clients/nebula.spec.ts +70 -0
  35. package/src/clients/nebula.ts +83 -0
  36. package/src/clients/pluto.spec.ts +165 -0
  37. package/src/clients/pluto.ts +118 -0
  38. package/src/eventHandlers/activation.ts +36 -0
  39. package/src/eventHandlers/authentication.ts +34 -0
  40. package/src/eventHandlers/eventMap.ts +34 -0
  41. package/src/eventHandlers/state.spec.ts +48 -0
  42. package/src/eventHandlers/state.ts +23 -0
  43. package/src/eventHandlers/storage.spec.ts +114 -0
  44. package/src/eventHandlers/storage.ts +45 -0
  45. package/src/eventHandlers/userAttributes.spec.ts +93 -0
  46. package/src/eventHandlers/userAttributes.ts +31 -0
  47. package/src/exceptions/FetchTimeoutError.ts +8 -0
  48. package/src/exceptions/PaywallError.ts +16 -0
  49. package/src/index-authentcation.spec.ts +26 -0
  50. package/src/index-storage.spec.ts +144 -0
  51. package/src/index-subscription.spec.ts +213 -0
  52. package/src/index.ts +40 -0
  53. package/src/janitor/index.spec.ts +18 -0
  54. package/src/janitor/index.ts +59 -0
  55. package/src/janitor/jobs/accessCookieRefresher.spec.ts +213 -0
  56. package/src/janitor/jobs/accessCookieRefresher.ts +98 -0
  57. package/src/janitor/jobs/daxsubCookie.spec.ts +109 -0
  58. package/src/janitor/jobs/daxsubCookie.ts +38 -0
  59. package/src/janitor/jobs/removeUserStorage.spec.ts +34 -0
  60. package/src/janitor/jobs/removeUserStorage.ts +12 -0
  61. package/src/lib/PaywallUnlockRequest.spec.ts +363 -0
  62. package/src/lib/PaywallUnlockRequest.ts +143 -0
  63. package/src/lib/UserDataRequest.spec.ts +231 -0
  64. package/src/lib/UserDataRequest.ts +267 -0
  65. package/src/lib/cookie.ts +121 -0
  66. package/src/lib/rpc.ts +19 -0
  67. package/src/store/index.spec.ts +49 -0
  68. package/src/store/index.ts +64 -0
  69. package/src/types.ts +22 -0
  70. package/src/utils/customEventWrapper.ts +58 -0
  71. package/src/utils/debouncer.spec.ts +252 -0
  72. package/src/utils/debouncer.ts +123 -0
  73. package/src/utils/deepEquals.ts +42 -0
  74. package/src/utils/expectBootLogs.ts +9 -0
  75. package/src/utils/getGlobalThis.ts +17 -0
  76. package/src/utils/getOrUpdate.spec.ts +166 -0
  77. package/src/utils/getOrUpdate.ts +66 -0
  78. package/src/utils/localhostCheck.ts +10 -0
  79. package/src/utils/location.ts +31 -0
  80. package/src/utils/log.spec.ts +148 -0
  81. package/src/utils/log.ts +124 -0
  82. package/src/utils/loginState.ts +24 -0
  83. package/src/utils/networkError.ts +11 -0
  84. package/src/utils/queue.ts +32 -0
  85. package/src/utils/type.ts +19 -0
  86. package/src/utils/url.spec.ts +33 -0
  87. package/src/utils/url.ts +37 -0
@@ -0,0 +1,183 @@
1
+ import { Unknown, Dictionary, String, Static } from 'runtypes';
2
+
3
+ import cache from '../cache';
4
+ import getOrUpdate from '../utils/getOrUpdate';
5
+ import log from '../utils/log';
6
+ import Debouncer from '../utils/debouncer';
7
+
8
+ const CACHE_DURATION = 5 * 60000; // 5 minutes
9
+ const DEBOUNCE_WAIT_TIME = 20; // 20ms wait before actually calling Europa
10
+
11
+ export const EuropaSchema = Dictionary(Unknown, String);
12
+
13
+ export const clearLocalCache = () => cache.remove('europa');
14
+
15
+ const doFetch = (url: string, method: string = 'GET', body?: Object) =>
16
+ fetch(url, {
17
+ method,
18
+ body: body && JSON.stringify(body),
19
+ headers: {
20
+ 'Content-Type': 'application/json',
21
+ Accept: 'application/json',
22
+ },
23
+ });
24
+
25
+ function mergeCache(
26
+ cachedData: Static<typeof EuropaSchema> | void,
27
+ newData: Static<typeof EuropaSchema>
28
+ ) {
29
+ return Object.entries(newData).reduce(
30
+ (mergedNamespaces, [namespace, data]) => ({
31
+ ...mergedNamespaces,
32
+ [namespace]: data,
33
+ }),
34
+ cachedData || {}
35
+ );
36
+ }
37
+
38
+ const updateNamespaceInCache = async (namespace: string, data: Object) => {
39
+ const cachedData = await cache.get('europa', EuropaSchema);
40
+ const updatedData = mergeCache(cachedData, { [namespace]: data });
41
+ return cache.set('europa', updatedData, Date.now() + CACHE_DURATION);
42
+ };
43
+
44
+ export const updateNamespace = async (namespace: string, data: Object) => {
45
+ const res = await doFetch(`/api/europa/v1/me/${namespace}`, 'PATCH', data);
46
+ if (!res.ok) {
47
+ log.error(
48
+ `Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
49
+ res
50
+ );
51
+ return {};
52
+ }
53
+ return updateNamespaceInCache(namespace, data);
54
+ };
55
+
56
+ const debouncer = new Debouncer<string[], typeof EuropaSchema>(
57
+ DEBOUNCE_WAIT_TIME,
58
+ [],
59
+ Debouncer.stringListParamsAccumulator,
60
+ (params) =>
61
+ doFetch(`/api/europa/v1/me/${params.join(',')}`).then(async (response) => {
62
+ const body = await response.text();
63
+ if (!response.ok) {
64
+ if (response.status === 500 || response.status === 503) {
65
+ log.error(
66
+ `Could not get namespaces for: ${params}, status: ${response.status}`,
67
+ { response, body }
68
+ );
69
+ } else {
70
+ log.warn(
71
+ `Could not get namespaces for: ${params}, status: ${response.status}`,
72
+ { response, body }
73
+ );
74
+ }
75
+ return {};
76
+ }
77
+ return JSON.parse(body).namespaces;
78
+ })
79
+ );
80
+
81
+ export const getNamespaces = async <
82
+ S extends { [namespace: string]: { [index: string]: unknown } },
83
+ Namespaces extends Array<keyof S>
84
+ >(
85
+ namespaces: Namespaces,
86
+ options: { ignoreCache: boolean } = { ignoreCache: false }
87
+ ): Promise<Pick<S, Namespaces[number]>> => {
88
+ if (namespaces.length === 0) {
89
+ throw new Error('namespaces array cannot be of length 0');
90
+ }
91
+
92
+ let missingNamespaces = namespaces as string[];
93
+ const cachedData = (await cache.get('europa', EuropaSchema)) || {
94
+ namespaces: {},
95
+ };
96
+ if (!options.ignoreCache) {
97
+ missingNamespaces = (
98
+ cachedData
99
+ ? namespaces.filter(
100
+ (namespace) =>
101
+ !Object.keys(cachedData).includes(namespace as string)
102
+ )
103
+ : namespaces
104
+ ) as string[];
105
+ if (cachedData && missingNamespaces.length === 0) {
106
+ // Yay! Everything we need is in the cache!
107
+ return Promise.resolve(cachedData as Pick<S, Namespaces[number]>);
108
+ }
109
+ }
110
+
111
+ const fetchedNamespaces = await debouncer.perform(missingNamespaces);
112
+ Object.entries(fetchedNamespaces).forEach(([namespace, fetchedNamespace]) =>
113
+ updateNamespaceInCache(namespace, fetchedNamespace as Object)
114
+ );
115
+
116
+ return Promise.resolve(
117
+ // @ts-ignore
118
+ Object.entries(mergeCache(cachedData, fetchedNamespaces))
119
+ .filter(([namespace]) => namespaces.includes(namespace))
120
+ .reduce(
121
+ (returnedEntries, [namespace, data]) => ({
122
+ ...returnedEntries,
123
+ [namespace]: data,
124
+ }),
125
+ {} as Pick<S, Namespaces[number]>
126
+ )
127
+ );
128
+ };
129
+
130
+ export const saveNamespace = (namespace: string, data: Object) =>
131
+ doFetch(`/api/europa/v1/me/${namespace}`, 'PUT', data)
132
+ .then((res) => {
133
+ if (!res.ok) {
134
+ log.error(
135
+ `Could not get save namespace, namespace:${namespace} status: ${res.status}, statusText: ${res.statusText}`,
136
+ res
137
+ );
138
+ }
139
+ return {};
140
+ })
141
+ .then(() => getNamespaces([namespace], { ignoreCache: true })); // updates cache
142
+
143
+ export const getAllNamespaces = () =>
144
+ getOrUpdate(
145
+ 'europa',
146
+ EuropaSchema,
147
+ () =>
148
+ doFetch(`/api/europa/v1/me`)
149
+ .then((res) => {
150
+ if (!res.ok) {
151
+ log.error(
152
+ `Could not get all namespaces, status: ${res.status}, statusText: ${res.statusText}`,
153
+ res
154
+ );
155
+ return {};
156
+ }
157
+ return res.json();
158
+ })
159
+ .then((data) => {
160
+ const europaValidData = EuropaSchema.check(data);
161
+ try {
162
+ return {
163
+ ttl: CACHE_DURATION,
164
+ data: europaValidData,
165
+ };
166
+ } catch (error) {
167
+ log.error(error, { data });
168
+ throw error;
169
+ }
170
+ }),
171
+ () => false
172
+ );
173
+ export const deleteNamespaceKey = (namespace: string, key: string) =>
174
+ doFetch(`/api/europa/v1/me/${namespace}/${key}`, 'DELETE')
175
+ .then((res) => {
176
+ if (!res.ok) {
177
+ log.error(
178
+ `Could not get namespace: ${namespace}, status: ${res.status}, statusText: ${res.statusText}`,
179
+ res
180
+ );
181
+ }
182
+ })
183
+ .then(() => getNamespaces([namespace], { ignoreCache: true })); // updates cache
@@ -0,0 +1,179 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import cache from '../cache';
3
+ import log from '../utils/log';
4
+ import {
5
+ checkForAccess,
6
+ getUserAccess,
7
+ AccessFeatures,
8
+ CheckAccessForPaper,
9
+ GetVstoken,
10
+ GetNonUserAccess,
11
+ getNonUserAccess,
12
+ } from './jupiter';
13
+ import anything = jasmine.anything;
14
+
15
+ beforeEach(async () => {
16
+ await cache.clear();
17
+ });
18
+
19
+ describe('jupiter service', () => {
20
+ describe('GET /check_access_for_paper', () => {
21
+ const publicationDomain = 'www.rb.no';
22
+ const accessFeatures: AccessFeatures = ['newspaper'];
23
+
24
+ it('should check access for paper', async () => {
25
+ const response: CheckAccessForPaper = {
26
+ status: 'success',
27
+ access: 'granted',
28
+ publication: {
29
+ domain: 'www.rb.no',
30
+ id: 95,
31
+ },
32
+ access_features: ['amedia_staff', 'newspaper'],
33
+ };
34
+
35
+ fetch.mockResponseOnce(JSON.stringify(response));
36
+
37
+ await expect(
38
+ checkForAccess(publicationDomain, accessFeatures)
39
+ ).resolves.toEqual({
40
+ access: ['amedia_staff', 'newspaper'],
41
+ });
42
+
43
+ expect(fetch).toHaveBeenCalledWith(
44
+ `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
45
+ ','
46
+ )}`
47
+ );
48
+ });
49
+
50
+ it('should deny access for user not logged in', async () => {
51
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
52
+ status: 400,
53
+ });
54
+
55
+ await expect(
56
+ checkForAccess(publicationDomain, accessFeatures)
57
+ ).rejects.toBeUndefined();
58
+ });
59
+
60
+ it('should fail on runtime validation', async () => {
61
+ fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
62
+ log.error = jest.fn();
63
+
64
+ await expect(
65
+ checkForAccess(publicationDomain, accessFeatures)
66
+ ).rejects.toBeUndefined();
67
+ });
68
+
69
+ it('should not cache when access denied', (done) => {
70
+ fetch.mockResponseOnce(
71
+ JSON.stringify({
72
+ status: 'success',
73
+ access: 'denied',
74
+ publication: {
75
+ domain: 'www.rb.no',
76
+ id: 95,
77
+ },
78
+ access_features: [],
79
+ })
80
+ );
81
+ const cacheSetSpy = spyOn(cache, 'set');
82
+ expect(checkForAccess(publicationDomain, accessFeatures))
83
+ .resolves.toEqual({ access: [] })
84
+ .then(() => {
85
+ expect(cacheSetSpy).toHaveBeenCalledWith(
86
+ 'checkForAccess',
87
+ anything(),
88
+ 0
89
+ );
90
+ })
91
+ .then(done);
92
+ });
93
+ });
94
+
95
+ describe('POST /get_vstoken', () => {
96
+ const publicationDomain = 'www.rb.no';
97
+
98
+ it('should return vstoken', async () => {
99
+ const response: GetVstoken = {
100
+ status: 'success',
101
+ cookie: 'ofofb:16187:amedia_staff,newspaper,plussalt:cc2c2c:rb:jupiter',
102
+ access_features: ['newspaper', 'plussalt'],
103
+ };
104
+
105
+ fetch.mockResponseOnce(JSON.stringify(response));
106
+
107
+ await expect(getUserAccess(publicationDomain)).resolves.toEqual(response);
108
+
109
+ expect(fetch).toHaveBeenCalledWith(
110
+ `/api/jupiter/v1/get_vstoken/${publicationDomain}`,
111
+ {
112
+ method: 'post',
113
+ }
114
+ );
115
+ });
116
+
117
+ it('should deny access for user not logged in', async () => {
118
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
119
+ status: 400,
120
+ });
121
+
122
+ await expect(getUserAccess(publicationDomain)).rejects.toThrow(
123
+ 'Request not ok (400: Bad Request).'
124
+ );
125
+ });
126
+
127
+ it('should fail on runtime validation', async () => {
128
+ fetch.mockResponseOnce(JSON.stringify({ access_features: 'foo' }));
129
+ log.error = jest.fn();
130
+
131
+ await expect(getUserAccess(publicationDomain)).rejects.toThrow(
132
+ 'Expected { status: "success"; cookie: string; access_features: string[]; }, but was incompatible'
133
+ );
134
+ });
135
+ });
136
+
137
+ describe('POST /non_user_access', () => {
138
+ const publicationDomain = 'www.rb.no';
139
+
140
+ it('should return none user access', async () => {
141
+ const response: GetNonUserAccess = {
142
+ status: 'success',
143
+ vstoken_cookie: 'd82ab3842a:2619693230:::rb:jupiter',
144
+ uuid: '',
145
+ access_features: [],
146
+ };
147
+
148
+ fetch.mockResponseOnce(JSON.stringify(response));
149
+
150
+ await expect(getNonUserAccess(publicationDomain)).resolves.toEqual(
151
+ response
152
+ );
153
+
154
+ expect(fetch).toHaveBeenCalledWith(
155
+ `/api/jupiter/v1/non_user_access/${publicationDomain}`,
156
+ { method: 'post' }
157
+ );
158
+ });
159
+
160
+ it('should deny access for user not logged in', async () => {
161
+ fetch.mockResponseOnce(JSON.stringify({ status: 'no_session_found' }), {
162
+ status: 400,
163
+ });
164
+
165
+ await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
166
+ 'Request not ok (400: Bad Request).'
167
+ );
168
+ });
169
+
170
+ it('should fail on runtime validation', async () => {
171
+ fetch.mockResponseOnce(JSON.stringify({ vstoken_cookie: 3 }));
172
+ log.error = jest.fn();
173
+
174
+ await expect(getNonUserAccess(publicationDomain)).rejects.toThrow(
175
+ 'Expected { status: "success"; vstoken_cookie: string; uuid: string; access_features: string[]; }, but was incompatible'
176
+ );
177
+ });
178
+ });
179
+ });
@@ -0,0 +1,119 @@
1
+ import {
2
+ Array,
3
+ Literal,
4
+ Number,
5
+ Record,
6
+ Static,
7
+ String,
8
+ Union,
9
+ } from 'runtypes';
10
+ import getOrUpdate from '../utils/getOrUpdate';
11
+ import { UserAttributes } from '../types';
12
+ import log from '../utils/log';
13
+
14
+ export type AccessFeatures = string[];
15
+
16
+ const PublicationSchema = Record({
17
+ id: Number,
18
+ domain: String,
19
+ });
20
+ export const CheckAccessForPaperSchema = Record({
21
+ status: Literal('success'),
22
+ access: Union(Literal('granted'), Literal('denied')),
23
+ publication: PublicationSchema,
24
+ access_features: Array(String),
25
+ });
26
+
27
+ export type CheckAccessForPaper = Static<typeof CheckAccessForPaperSchema>;
28
+
29
+ const GetVstokenSchema = Record({
30
+ status: Literal('success'),
31
+ cookie: String,
32
+ access_features: Array(String),
33
+ });
34
+
35
+ export type GetVstoken = Static<typeof GetVstokenSchema>;
36
+
37
+ const GetNonUserAccessSchema = Record({
38
+ status: Literal('success'),
39
+ vstoken_cookie: String,
40
+ uuid: String,
41
+ access_features: Array(String),
42
+ });
43
+
44
+ export type GetNonUserAccess = Static<typeof GetNonUserAccessSchema>;
45
+
46
+ export const checkForAccess = (
47
+ publicationDomain: string,
48
+ accessFeatures: AccessFeatures
49
+ ): Promise<Pick<UserAttributes, 'access'>> =>
50
+ getOrUpdate('checkForAccess', CheckAccessForPaperSchema, () =>
51
+ fetch(
52
+ `/api/jupiter/v1/check_access_for_paper/${publicationDomain}/?require=any&access_features=${accessFeatures.join(
53
+ ','
54
+ )}`
55
+ )
56
+ .then((response) => {
57
+ if (!response.ok) {
58
+ // TODO Handle this.
59
+ throw new Error(
60
+ `Request not ok (${response.status}: ${response.statusText}).`
61
+ );
62
+ }
63
+ return response.json();
64
+ })
65
+ .then((json) => {
66
+ try {
67
+ const data = CheckAccessForPaperSchema.check(json);
68
+ return {
69
+ ttl: data.access === 'granted' ? 1000 * 10 : 0, // 10 seconds
70
+ data,
71
+ };
72
+ } catch (error) {
73
+ log.error(error, { json });
74
+ throw error;
75
+ }
76
+ })
77
+ ).then((data) => ({ access: data.access_features }));
78
+
79
+ export const getUserAccess = (publicationDomain: string): Promise<GetVstoken> =>
80
+ fetch(`/api/jupiter/v1/get_vstoken/${publicationDomain}`, { method: 'post' })
81
+ .then((response) => {
82
+ if (!response.ok) {
83
+ throw new Error(
84
+ `Request not ok (${response.status}: ${response.statusText}).`
85
+ );
86
+ }
87
+ return response.json();
88
+ })
89
+ .then((json) => {
90
+ try {
91
+ return GetVstokenSchema.check(json);
92
+ } catch (error) {
93
+ log.error(error, { json });
94
+ throw error;
95
+ }
96
+ });
97
+
98
+ export const getNonUserAccess = (
99
+ publicationDomain: string
100
+ ): Promise<GetNonUserAccess> =>
101
+ fetch(`/api/jupiter/v1/non_user_access/${publicationDomain}`, {
102
+ method: 'post',
103
+ })
104
+ .then((response) => {
105
+ if (!response.ok) {
106
+ throw new Error(
107
+ `Request not ok (${response.status}: ${response.statusText}).`
108
+ );
109
+ }
110
+ return response.json();
111
+ })
112
+ .then((json) => {
113
+ try {
114
+ return GetNonUserAccessSchema.check(json);
115
+ } catch (error) {
116
+ log.error(error, { json });
117
+ throw error;
118
+ }
119
+ });
@@ -0,0 +1,59 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import { activateSubscription, UserDeactivatedError } from './mercury';
3
+
4
+ describe('activateSubscription()', () => {
5
+ it('should throw error if user is deactivated', async () => {
6
+ fetch.mockResponse(JSON.stringify({ status: 'user_deactivated' }), {
7
+ status: 401,
8
+ });
9
+ await expect(activateSubscription(['newspaper'])).rejects.toThrow(
10
+ UserDeactivatedError
11
+ );
12
+ });
13
+
14
+ it('should return empty list if user not found', async () => {
15
+ fetch.mockResponse(JSON.stringify({ status: 'no_session_found' }), {
16
+ status: 401,
17
+ });
18
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([]);
19
+ });
20
+
21
+ it('should return list if access features even if requested access is not "granted"', async () => {
22
+ fetch.mockResponse(
23
+ JSON.stringify({
24
+ status: 'success',
25
+ access: 'denied',
26
+ access_features: ['newspaper'],
27
+ })
28
+ );
29
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([
30
+ 'newspaper',
31
+ ]);
32
+ });
33
+
34
+ it('should return list of access features even if status is not "success"', async () => {
35
+ fetch.mockResponse(
36
+ JSON.stringify({
37
+ status: 'unknown',
38
+ access: 'granted',
39
+ access_features: ['newspaper'],
40
+ })
41
+ );
42
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([
43
+ 'newspaper',
44
+ ]);
45
+ });
46
+
47
+ it('should return ["newspaper"] if status is "success" and access is "granted"', async () => {
48
+ fetch.mockResponse(
49
+ JSON.stringify({
50
+ status: 'success',
51
+ access: 'granted',
52
+ access_features: ['newspaper'],
53
+ })
54
+ );
55
+ await expect(activateSubscription(['newspaper'])).resolves.toEqual([
56
+ 'newspaper',
57
+ ]);
58
+ });
59
+ });
@@ -0,0 +1,48 @@
1
+ import log from '../utils/log';
2
+ import { getCurrentPublicationDomain } from '../utils/url';
3
+
4
+ export class UserDeactivatedError extends Error {}
5
+
6
+ const EXPECTED_ERRORS = [
7
+ 'no_session_found', // Not logged in
8
+ 'subscription_not_found', // No active subscription
9
+ 'publication_not_subscribable', // Activation is not possible on current publication
10
+ ];
11
+
12
+ export const activateSubscription = async (
13
+ accessFeatures: string[]
14
+ ): Promise<string[]> =>
15
+ fetch(
16
+ `/api/mercury/v2/access/activate?publication_wwwdomain=${getCurrentPublicationDomain()}&access_features=${accessFeatures.join(
17
+ ','
18
+ )}`,
19
+ {
20
+ method: 'post',
21
+ }
22
+ ).then(async (response) => {
23
+ const body = await response.text();
24
+ let data;
25
+ try {
26
+ data = JSON.parse(body);
27
+ } catch (error) {
28
+ log.error(
29
+ `Activate subscription failed. Mercury (HTTP/${response.status}: ${body})`,
30
+ { error, response, accessFeatures, body }
31
+ );
32
+ }
33
+ if (!response.ok) {
34
+ // User deactivated
35
+ if (data?.status === 'user_deactivated') {
36
+ throw new UserDeactivatedError();
37
+ }
38
+ if (EXPECTED_ERRORS.includes(data?.status)) {
39
+ return [];
40
+ }
41
+ log.error(
42
+ `Activate subscription failed. Mercury (HTTP/${response.status}: ${body})`,
43
+ { response, accessFeatures, body }
44
+ );
45
+ return [];
46
+ }
47
+ return data?.access_features;
48
+ });
@@ -0,0 +1,20 @@
1
+ import fetch from 'jest-fetch-mock';
2
+ import backendLog from './mercuryLog';
3
+
4
+ describe('Mercury backendlog', () => {
5
+ it('should include level in url', () => {
6
+ backendLog.error('jest message', {});
7
+ expect(fetch).toHaveBeenCalledWith(
8
+ expect.stringContaining('/error'),
9
+ expect.anything()
10
+ );
11
+ expect(fetch).toHaveBeenCalledTimes(1);
12
+ });
13
+
14
+ it('should include additional context as query parameters', () => {
15
+ backendLog.error('jest message', { referrer: 'https://www.rb.no/' });
16
+ const formData = fetch.mock.calls[0][1]?.body as FormData;
17
+
18
+ expect(formData?.get('referrer')).toEqual('https://www.rb.no/');
19
+ });
20
+ });
@@ -0,0 +1,67 @@
1
+ import { getCurrentHostname, getCurrentUrl } from '../utils/url';
2
+ import { isBoolean, isNumber, isString } from '../utils/type';
3
+
4
+ type Context = Record<string, unknown>;
5
+
6
+ /**
7
+ * Extracted from mercury.tsx so other calls to mercury can log properly
8
+ */
9
+ function postLog(url: string, query: { [index: string]: any }) {
10
+ const body = new FormData();
11
+ Object.keys(query).forEach((key) => body.append(key, query[key]));
12
+ const options: RequestInit = {
13
+ method: 'POST',
14
+ body,
15
+ headers: {
16
+ Accept: 'application/json',
17
+ },
18
+ };
19
+ fetch(url, options).then((res) => {
20
+ if (!res.ok) {
21
+ // eslint-disable-next-line no-console
22
+ console.error(
23
+ `Failed to send log to backend: Error, status: ${res.status}, text: ${res.statusText}`
24
+ );
25
+ }
26
+ });
27
+ }
28
+
29
+ const backendLog = (level: string, message: string, context: Context) => {
30
+ const internalContext: Context = {};
31
+ Object.keys(context).forEach((key) => {
32
+ const currentContext = context[key];
33
+ if (
34
+ isString(currentContext) ||
35
+ isNumber(currentContext) ||
36
+ isBoolean(currentContext)
37
+ ) {
38
+ internalContext[key] = currentContext;
39
+ return;
40
+ }
41
+ try {
42
+ internalContext[key] = JSON.stringify(currentContext);
43
+ } catch {
44
+ internalContext[key] = currentContext;
45
+ }
46
+ });
47
+ const extendedContext = {
48
+ ...internalContext,
49
+ message,
50
+ url: getCurrentUrl(),
51
+ domain: getCurrentHostname(),
52
+ };
53
+ postLog(`/api/mercury/v1/log/${level}`, extendedContext);
54
+ };
55
+
56
+ const log = {
57
+ error: (message: string, context: Context) =>
58
+ backendLog('error', message, context),
59
+ warn: (message: string, context: Context) =>
60
+ backendLog('warn', message, context),
61
+ info: (message: string, context: Context) =>
62
+ backendLog('info', message, context),
63
+ debug: (message: string, context: Context) =>
64
+ backendLog('debug', message, context),
65
+ };
66
+
67
+ export default log;