summaryrefslogtreecommitdiffstats
path: root/toolkit/components/extensions/test/xpcshell/test_ext_contentscript_module_import.js
blob: 3e4e5dd98312a6de92716295e1c80536699aee5d (plain)
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
"use strict";

const server = createHttpServer({ hosts: ["example.com"] });

server.registerPathHandler("/dummy", (request, response) => {
  response.setStatusLine(request.httpVersion, 200, "OK");
  response.setHeader("Content-Type", "text/html", false);
  response.write("<!DOCTYPE html><html></html>");
});

server.registerPathHandler("/script.js", (request, response) => {
  ok(false, "Unexpected request to /script.js");
});

/* eslint-disable no-eval, no-implied-eval */

const MODULE1 = `
  import {foo} from "./module2.js";
  export let bar = foo;

  let count = 0;

  export function counter () { return count++; }
`;

const MODULE2 = `export let foo = 2;`;

add_task(async function test_disallowed_import() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      content_scripts: [
        {
          matches: ["http://example.com/dummy"],
          js: ["main.js"],
        },
      ],
    },

    files: {
      "main.js": async function () {
        let disallowedURLs = [
          "data:text/javascript,void 0",
          "javascript:void 0",
          "http://example.com/script.js",
          URL.createObjectURL(
            new Blob(["void 0", { type: "text/javascript" }])
          ),
        ];

        for (let url of disallowedURLs) {
          await browser.test.assertRejects(
            import(url),
            /error loading dynamically imported module/,
            `should reject import("${url}")`
          );
        }

        browser.test.sendMessage("done");
      },
    },
  });

  await extension.startup();
  let contentPage = await ExtensionTestUtils.loadContentPage(
    "http://example.com/dummy"
  );
  await extension.awaitMessage("done");
  await extension.unload();
  await contentPage.close();
});

add_task(async function test_normal_import() {
  Services.prefs.setBoolPref("extensions.content_web_accessible.enabled", true);

  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      content_scripts: [
        {
          matches: ["http://example.com/dummy"],
          js: ["main.js"],
        },
      ],
    },

    files: {
      "main.js": async function () {
        /* global exportFunction */
        const url = browser.runtime.getURL("module1.js");

        await browser.test.assertRejects(
          import(url),
          /error loading dynamically imported module/,
          "Cannot import script that is not web-accessible from page context"
        );

        await browser.test.assertRejects(
          window.eval(`import("${url}")`),
          /error loading dynamically imported module/,
          "Cannot import script that is not web-accessible from page context"
        );

        let promise = new Promise((resolve, reject) => {
          exportFunction(resolve, window, { defineAs: "resolve" });
          exportFunction(reject, window, { defineAs: "reject" });
        });

        window.setTimeout(`import("${url}").then(resolve, reject)`, 0);

        await browser.test.assertRejects(
          promise,
          /error loading dynamically imported module/,
          "Cannot import script that is not web-accessible from page context"
        );

        browser.test.sendMessage("done");
      },
      "module1.js": MODULE1,
      "module2.js": MODULE2,
    },
  });

  await extension.startup();
  let contentPage = await ExtensionTestUtils.loadContentPage(
    "http://example.com/dummy"
  );

  await extension.awaitMessage("done");

  // Web page can not import non-web-accessible files.
  await contentPage.spawn([extension.uuid], async uuid => {
    let files = ["main.js", "module1.js", "module2.js"];

    for (let file of files) {
      let url = `moz-extension://${uuid}/${file}`;
      await Assert.rejects(
        content.eval(`import("${url}")`),
        /error loading dynamically imported module/,
        "Cannot import script that is not web-accessible"
      );
    }
  });

  await extension.unload();
  await contentPage.close();
});

add_task(async function test_import_web_accessible() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      content_scripts: [
        {
          matches: ["http://example.com/dummy"],
          js: ["main.js"],
        },
      ],
      web_accessible_resources: ["module1.js", "module2.js"],
    },

    files: {
      "main.js": async function () {
        let mod = await import(browser.runtime.getURL("module1.js"));
        browser.test.assertEq(mod.bar, 2);
        browser.test.assertEq(mod.counter(), 0);
        browser.test.sendMessage("done");
      },
      "module1.js": MODULE1,
      "module2.js": MODULE2,
    },
  });

  await extension.startup();
  let contentPage = await ExtensionTestUtils.loadContentPage(
    "http://example.com/dummy"
  );
  await extension.awaitMessage("done");

  // Web page can import web-accessible files,
  // even after WebExtension imported the same files.
  await contentPage.spawn([extension.uuid], async uuid => {
    let base = `moz-extension://${uuid}`;

    await Assert.rejects(
      content.eval(`import("${base}/main.js")`),
      /error loading dynamically imported module/,
      "Cannot import script that is not web-accessible"
    );

    let promise = content.eval(`import("${base}/module1.js")`);
    let mod = (await promise.wrappedJSObject).wrappedJSObject;
    Assert.equal(mod.bar, 2, "exported value should match");
    Assert.equal(mod.counter(), 0, "Counter should be fresh");
    Assert.equal(mod.counter(), 1, "Counter should be fresh");

    promise = content.eval(`import("${base}/module2.js")`);
    mod = (await promise.wrappedJSObject).wrappedJSObject;
    Assert.equal(mod.foo, 2, "exported value should match");
  });

  await extension.unload();
  await contentPage.close();
});

add_task(async function test_import_web_accessible_after_page() {
  let extension = ExtensionTestUtils.loadExtension({
    manifest: {
      content_scripts: [
        {
          matches: ["http://example.com/dummy"],
          js: ["main.js"],
        },
      ],
      web_accessible_resources: ["module1.js", "module2.js"],
    },

    files: {
      "main.js": async function () {
        browser.test.onMessage.addListener(async msg => {
          browser.test.assertEq(msg, "import");

          const url = browser.runtime.getURL("module1.js");
          let mod = await import(url);
          browser.test.assertEq(mod.bar, 2);
          browser.test.assertEq(mod.counter(), 0, "Counter should be fresh");

          let promise = window.eval(`import("${url}")`);
          let mod2 = (await promise.wrappedJSObject).wrappedJSObject;
          browser.test.assertEq(
            mod2.counter(),
            2,
            "Counter should have been incremented by page"
          );

          browser.test.sendMessage("done");
        });
        browser.test.sendMessage("ready");
      },
      "module1.js": MODULE1,
      "module2.js": MODULE2,
    },
  });

  await extension.startup();
  let contentPage = await ExtensionTestUtils.loadContentPage(
    "http://example.com/dummy"
  );
  await extension.awaitMessage("ready");

  // The web page imports the web-accessible files first,
  // when the WebExtension imports the same file, they should
  // not be shared.
  await contentPage.spawn([extension.uuid], async uuid => {
    let base = `moz-extension://${uuid}`;

    await Assert.rejects(
      content.eval(`import("${base}/main.js")`),
      /error loading dynamically imported module/,
      "Cannot import script that is not web-accessible"
    );

    let promise = content.eval(`import("${base}/module1.js")`);
    let mod = (await promise.wrappedJSObject).wrappedJSObject;
    Assert.equal(mod.bar, 2, "exported value should match");
    Assert.equal(mod.counter(), 0);
    Assert.equal(mod.counter(), 1);

    promise = content.eval(`import("${base}/module2.js")`);
    mod = (await promise.wrappedJSObject).wrappedJSObject;
    Assert.equal(mod.foo, 2, "exported value should match");
  });

  extension.sendMessage("import");

  await extension.awaitMessage("done");

  await extension.unload();
  await contentPage.close();
});