aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/infrastructure/electron/impl/__tests__/lockWebContentsToFile.test.ts
blob: 6332db7bcaf67c8f3c3e9ddba707321dc2dd487c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*
 * Copyright (C)  2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { URL } from 'node:url';

import { jest } from '@jest/globals';
import { fake } from '@sophie/test-utils';
import type { Event, HandlerDetails, WebContents } from 'electron';
import { mocked } from 'jest-mock';

import type Resources from '../../../resources/Resources.js';
import lockWebContentsToFile from '../lockWebContentsToFile.js';

type WillNavigateHandler = (event: Event, url: string) => void;

const filePrefix =
  'file:///opt/sophie/resources/app.asar/packages/renderer/dist/';

function createFakeResources(prefix: string): Resources {
  return fake<Resources>({
    getRendererURL(path: string) {
      return new URL(path, prefix).toString();
    },
  });
}

function createAbortedError(): Error {
  const error = new Error('Aborted error');
  Object.assign(error, {
    errno: -3,
    code: 'ERR_ABORTED',
  });
  return error;
}

describe('when loadURL does not throw', () => {
  let willNavigate: WillNavigateHandler | undefined;

  let windowOpenHandler:
    | ((details: HandlerDetails) => { action: 'allow' | 'deny' })
    | undefined;

  const urlToLoad = `${filePrefix}index.html`;

  const fakeResources = createFakeResources(filePrefix);

  const fakeWebContents = fake<WebContents>({
    setWindowOpenHandler(handler) {
      windowOpenHandler = handler;
    },
    on(event, listener) {
      if (event === 'will-navigate') {
        willNavigate = listener as WillNavigateHandler;
      }
      return this as WebContents;
    },
    loadURL: jest.fn<WebContents['loadURL']>(),
  });

  const event: Event = {
    preventDefault: jest.fn(),
  };

  beforeEach(async () => {
    windowOpenHandler = undefined;
    willNavigate = undefined;
    mocked(fakeWebContents.loadURL).mockResolvedValueOnce();
    await lockWebContentsToFile(fakeResources, 'index.html', fakeWebContents);
  });

  test('loads the specified file', () => {
    expect(fakeWebContents.loadURL).toHaveBeenCalledWith(urlToLoad);
  });

  test('sets up will navigate and window open listeners', () => {
    expect(willNavigate).toBeDefined();
    expect(windowOpenHandler).toBeDefined();
  });

  test('prevents opening a window', () => {
    const { action } = windowOpenHandler!({
      url: 'https://example.com',
      frameName: 'newWindow',
      features: '',
      disposition: 'default',
      referrer: {
        url: urlToLoad,
        policy: 'default',
      },
    });
    expect(action).toBe('deny');
  });

  test('allows navigation to the loaded URL', () => {
    willNavigate!(event, urlToLoad);
    expect(event.preventDefault).not.toHaveBeenCalled();
  });

  test('does not allow navigation to another URL', () => {
    willNavigate!(
      event,
      'file:///opt/sophie/resources/app.asar/packages/renderer/not-allowed.html',
    );
    expect(event.preventDefault).toHaveBeenCalled();
  });
});

describe('when loadURL throws', () => {
  const fakeWebContents = fake<WebContents>({
    setWindowOpenHandler: jest.fn<WebContents['setWindowOpenHandler']>(),
    on: jest.fn<() => WebContents>(),
    loadURL: jest.fn<WebContents['loadURL']>(),
  });

  describe('when the URL points at a file', () => {
    const fakeResources = createFakeResources('http://localhost:3000');

    test('swallows ERR_ABORTED errors', async () => {
      const error = createAbortedError();
      mocked(fakeWebContents.loadURL).mockRejectedValueOnce(error);
      await expect(
        lockWebContentsToFile(fakeResources, 'index.html', fakeWebContents),
      ).resolves.not.toThrow();
    });

    test('passes through other errors', async () => {
      mocked(fakeWebContents.loadURL).mockRejectedValueOnce(
        new Error('other error'),
      );
      await expect(
        lockWebContentsToFile(fakeResources, 'index.html', fakeWebContents),
      ).rejects.toBeInstanceOf(Error);
    });
  });

  describe('when the URL points at a local server', () => {
    const fakeResources = createFakeResources(filePrefix);

    test('passes through ERR_ABORTED errors', async () => {
      const error = createAbortedError();
      mocked(fakeWebContents.loadURL).mockRejectedValueOnce(error);
      await expect(
        lockWebContentsToFile(fakeResources, 'index.html', fakeWebContents),
      ).rejects.toBeInstanceOf(Error);
    });

    test('passes through other errors', async () => {
      mocked(fakeWebContents.loadURL).mockRejectedValueOnce(
        new Error('other error'),
      );
      await expect(
        lockWebContentsToFile(fakeResources, 'index.html', fakeWebContents),
      ).rejects.toBeInstanceOf(Error);
    });
  });
});