Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / shared / lib / drawer / session.ts
blob439f72143e61d33c9ce30d6f21614ecee051bb31
1 import { captureMessage } from '@proton/shared/lib/helpers/sentry';
3 import type { ResumedSessionResult } from '../authentication/persistedSessionHelper';
4 import type { APP_NAMES } from '../constants';
5 import { SECOND } from '../constants';
6 import { createTimeoutError } from '../fetch/ApiError';
7 import { getIsAuthorizedApp, getIsDrawerPostMessage, postMessageFromIframe } from './helpers';
8 import { DRAWER_EVENTS, type SESSION_MESSAGE } from './interfaces';
10 export const resumeSessionDrawerApp = ({
11     parentApp,
12     localID: parentLocalID,
13 }: {
14     parentApp: APP_NAMES;
15     localID: number;
16 }) => {
17     let timeout: ReturnType<typeof setTimeout> | undefined;
19     return new Promise<ResumedSessionResult & { tag: SESSION_MESSAGE['payload']['tag'] }>((resolve, reject) => {
20         const handler = (event: MessageEvent) => {
21             if (!getIsDrawerPostMessage(event)) {
22                 return;
23             }
25             if (event.data.type === DRAWER_EVENTS.SESSION) {
26                 const { UID, keyPassword, User, localID, clientKey, offlineKey, persistent, trusted, tag } =
27                     event.data.payload;
28                 window.removeEventListener('message', handler);
30                 if (timeout) {
31                     clearTimeout(timeout);
32                 }
34                 resolve({
35                     tag,
36                     UID,
37                     keyPassword,
38                     clientKey,
39                     offlineKey,
40                     User,
41                     persistent,
42                     trusted,
43                     LocalID: localID ?? parentLocalID,
44                 });
45             }
46         };
48         postMessageFromIframe({ type: DRAWER_EVENTS.READY }, parentApp);
49         window.addEventListener('message', handler);
51         // Resolve the promise if the parent app does not respond
52         timeout = setTimeout(() => {
53             captureMessage('Drawer iframe session timeout', {
54                 level: 'info',
55                 extra: {
56                     parentApp,
57                     isAuthorizedApp: getIsAuthorizedApp(parentApp || ''),
58                     locationOrigin: window.location.origin,
59                     locationHref: window.location.href,
60                 },
61             });
63             reject(createTimeoutError({}));
64         }, 10 * SECOND);
65     });