summaryrefslogtreecommitdiff
path: root/src/bg/main.js
blob: 2eb28968e4e5b50ce3e87a5b200db7dcdf954141 (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
 var ns = (() => {
   'use strict';

   const popupURL = browser.extension.getURL("/ui/popup.html");
   let popupFor = tabId => `${popupURL}#tab${tabId}`;

   let ctxMenuId = "noscript-ctx-menu";

   async function toggleCtxMenuItem(show = ns.local.showCtxMenuItem) {
     if (!"contextMenus" in browser) return;
     let id = ctxMenuId;
     try {
         await browser.contextMenus.remove(id);
     } catch (e) {}

     if (show) {
       browser.contextMenus.create({
         id,
         title: "NoScript",
         contexts: ["all"]
       });
     }
   }

   async function init() {
     let policyData = (await Storage.get("sync", "policy")).policy;
     if (policyData && policyData.DEFAULT) {
       ns.policy = new Policy(policyData);
       await ChildPolicies.update(policyData);
     } else {
       await include("/legacy/Legacy.js");
       ns.policy = await Legacy.createOrMigratePolicy();
       ns.savePolicy();
     }
     
     
     await include("/bg/defaults.js");
     await ns.defaults;
     await include(["/bg/RequestGuard.js", "/bg/RequestUtil.js"]);
     await RequestGuard.start();
     await XSS.start(); // we must start it anyway to initialize sub-objects
     if (!ns.sync.xss) {
       XSS.stop();
     }
     Commands.install();
   };

   var Commands = {
     openPageUI() {
       try {
         browser.browserAction.openPopup();
         return;
       } catch (e) {
         debug(e);
       }
       browser.windows.create({
         url: popupURL,
         width: 800,
         height: 600,
         type: "panel"
       });
     },

     togglePermissions() {},
     install() {


       if ("command" in browser) {
         // keyboard shortcuts
         browser.commands.onCommand.addListener(cmd => {
           if (cmd in Commands) {
             Commands[cmd]();
           }
         });
       }

       if ("contextMenus" in browser) {
         toggleCtxMenuItem();
         browser.contextMenus.onClicked.addListener((info, tab) => {
           if (info.menuItemId == ctxMenuId) {
             this.openPageUI();
           }
         });
       }

       // wiring main UI
       let ba = browser.browserAction;
       if ("setIcon" in ba) {
         //desktop
         ba.setPopup({
           popup: popupURL
         });
       } else {
         // mobile
         ba.onClicked.addListener(async tab => {
           try {
             await browser.tabs.remove(await browser.tabs.query({
               url: popupURL
             }));
           } catch (e) {}
           await browser.tabs.create({
             url: popupFor(tab.id)
           });
         });
       }
     }
   }

   var MessageHandler = {
     responders: {

       async updateSettings(settings, sender) {
         await Settings.update(settings);
         toggleCtxMenuItem();
       },
       async broadcastSettings({
         tabId = -1
       }) {
         let policy = ns.policy.dry(true);
         let seen = tabId !== -1 ? await ns.collectSeen(tabId) : null;
         let xssUserChoices = await XSS.getUserChoices();
         browser.runtime.sendMessage({
           type: "settings",
           policy,
           seen,
           xssUserChoices,
           local: ns.local,
           sync: ns.sync,
           unrestrictedTab: ns.unrestrictedTabs.has(tabId),
         });
       },

       exportSettings(m, sender, sendResponse) {
         sendResponse(Settings.export());
         return false;
       },

       async importSettings({
         data
       }) {
         return await Settings.import(data);
       },

       async openStandalonePopup() {
         let win = await browser.windows.getLastFocused();
         let [tab] = (await browser.tabs.query({
           lastFocusedWindow: true,
           active: true
         }));

         if (!tab || tab.id === -1) {
           log("No tab found to open the UI for");
           return;
         }
         browser.windows.create({
           url: popupFor(tab.id),
           width: 800,
           height: 600,
           top: win.top + 48,
           left: win.left + 48,
           type: "panel"
         });
       }
     },
     onMessage(m, sender, sendResponse) {
       let {
         type
       } = m;
       let {
         responders
       } = MessageHandler;


       if (type && (type = type.replace(/^NoScript\./, '')) in responders) {
         return responders[type](m, sender, sendResponse);
       } else {
         debug("Received unkown message", m, sender);
       }
       return false;
     },

     listen() {
       browser.runtime.onMessage.addListener(this.onMessage);
     },
   }



   return {
     running: false,
     policy: null,
     local: null,
     sync: null,
     unrestrictedTabs: new Set(),
     isEnforced(tabId = -1) {
       return this.policy.enforced && (tabId === -1 || !this.unrestrictedTabs.has(tabId));
     },

     start() {
       if (this.running) return;
       this.running = true;

       deferWebTraffic(init(), 
          async () => {

           await include("/bg/Settings.js");
           MessageHandler.listen();

           log("STARTED");

           this.devMode = (await browser.management.getSelf()).installType === "development";
           if (this.local.debug) {
             if (this.devMode) {
               include("/test/run.js");
             }
           } else {
             debug = () => {}; // suppress verbosity
           }
         });
     },

     stop() {
       if (!this.running) return;
       this.running = false;
       RequestGuard.stop();
       log("STOPPED");
     },

     async savePolicy() {
       if (this.policy) {
         await ChildPolicies.update(this.policy);
         await Storage.set("sync", {
           policy: this.policy.dry()
         });
         await browser.webRequest.handlerBehaviorChanged()
       }
       return this.policy;
     },



     async save(obj) {
       if (obj && obj.storage) {
         let toBeSaved = {
           [obj.storage]: obj
         };
         Storage.set(obj.storage, toBeSaved);
       }
       return obj;
     },

     async collectSeen(tabId) {

       try {
         let seen = Array.from(await browser.tabs.sendMessage(tabId, {
           type: "collect"
         }, {
           frameId: 0
         }));
         debug("Collected seen", seen);
         return seen;
       } catch (e) {
         // probably a page where content scripts cannot run, let's open the options instead
         error(e, "Cannot collect noscript activity data");
       }

       return null;
     },
   };
 })();

 ns.start();