├── .github
└── workflows
│ └── unit-tests.yaml
├── .gitignore
├── .licensed.yaml
├── .mocharc.json
├── .nycrc.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── icon128.png
├── icon16.png
├── icon48.png
├── manifests
├── chrome
│ ├── managed-storage-schema.json
│ └── manifest.json
├── edge
│ ├── managed-storage-schema.json
│ └── manifest.json
└── firefox
│ └── manifest.json
├── package-lock.json
├── package.json
├── src
├── background
│ ├── BackgroundHub.ts
│ ├── EventCollector.spec.ts
│ ├── EventCollector.ts
│ ├── SensorEventAPI.ts
│ ├── background.ts
│ ├── install
│ │ ├── InstallKey.spec.ts
│ │ ├── InstallKey.ts
│ │ ├── InstallRequest.ts
│ │ ├── InstallResponse.spec.ts
│ │ ├── InstallResponse.ts
│ │ └── Installer.ts
│ ├── storage
│ │ ├── LocalStorage.ts
│ │ ├── ManagedStorage.ts
│ │ ├── SensorAPI.ts
│ │ └── Storage.ts
│ ├── text
│ │ ├── HashKeyManager.spec.ts
│ │ ├── HashKeyManager.ts
│ │ ├── KeyedHasher.ts
│ │ ├── TextCaptureSession.spec.ts
│ │ ├── TextCaptureSession.ts
│ │ ├── TextCaptureSessionManager.ts
│ │ ├── TextInputEventDeduplicator.ts
│ │ ├── TextInputEventFinalizer.spec.ts
│ │ └── TextInputEventFinalizer.ts
│ └── window
│ │ ├── WindowMetadata.ts
│ │ ├── WindowTracker.spec.ts
│ │ └── WindowTracker.ts
├── common
│ ├── concurrent
│ │ ├── Lock.spec.ts
│ │ ├── Lock.ts
│ │ ├── Semaphore.spec.ts
│ │ └── Semaphore.ts
│ ├── data
│ │ ├── UUID.spec.ts
│ │ └── UUID.ts
│ ├── events
│ │ ├── Event.spec.ts
│ │ ├── Event.ts
│ │ ├── TextInputEvent.ts
│ │ ├── WindowEvent.spec.ts
│ │ ├── WindowEvent.ts
│ │ ├── WindowLocationEvent.spec.ts
│ │ ├── WindowLocationEvent.ts
│ │ └── internal
│ │ │ ├── TextCaptureEvent.spec.ts
│ │ │ └── TextCaptureEvent.ts
│ └── utils
│ │ ├── Assert.spec.ts
│ │ ├── Assert.ts
│ │ ├── ByteUtils.spec.ts
│ │ └── ByteUtils.ts
└── content
│ ├── ContentHub.ts
│ ├── ElementRegistry.ts
│ ├── WindowLocationEventGenerator.spec.ts
│ ├── WindowLocationEventGenerator.ts
│ ├── content.ts
│ └── text
│ ├── HTMLInputEventManager.ts
│ ├── TextChunkEventManager.ts
│ ├── TextInputEventManager.ts
│ └── composition
│ ├── VirtualElementFocus.ts
│ ├── VirtualElementManager.ts
│ ├── VirtualTextAreaElement.spec.ts
│ └── VirtualTextAreaElement.ts
├── tsconfig.json
└── webpack.config.js
/.github/workflows/unit-tests.yaml:
--------------------------------------------------------------------------------
1 | name: Unit Tests
2 |
3 | on:
4 | pull_request:
5 | branches: [ main ]
6 |
7 | jobs:
8 | build:
9 |
10 | runs-on: ubuntu-latest
11 |
12 | steps:
13 | - name: Checkout Weaklayer Sensor
14 | uses: actions/checkout@v2
15 | - name: Setup Node
16 | uses: actions/setup-node@v1
17 | with:
18 | node-version: 12.x
19 | - run: npm install
20 | - run: npm run build
21 | - run: npm test
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules
3 | dist
4 | .nyc_output
5 | .licenses
6 |
--------------------------------------------------------------------------------
/.licensed.yaml:
--------------------------------------------------------------------------------
1 | name: 'Weaklayer Sensor'
2 |
3 | sources:
4 | npm: true
5 |
6 | allowed:
7 | - mit
8 | - apache-2.0
9 | - bsd-2-clause
10 | - bsd-3-clause
11 | - cc0-1.0
12 | - isc
13 | - mpl-2.0
14 |
15 | reviewed:
16 | npm:
17 | - pako
18 |
--------------------------------------------------------------------------------
/.mocharc.json:
--------------------------------------------------------------------------------
1 | {
2 | "extension": [
3 | "ts"
4 | ],
5 | "spec": "src/**/*.spec.ts",
6 | "require": "ts-node/register"
7 | }
--------------------------------------------------------------------------------
/.nycrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "cache": false,
3 | "exclude": [
4 | "**/*.spec.ts"
5 | ],
6 | "extensions": [
7 | ".ts"
8 | ]
9 | }
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Bugs
2 |
3 | If you think its a bad enough security bug then please email me.
4 | Email me anyway if you feel like it!
5 | Otherwise, please submit an issue on GitHub.
6 | Try to put it in the correct repo (sensor/gateway), but its no biggie if you choose the wrong one.
7 |
8 | # Feature Requests
9 |
10 | Please submit an issue on GitHub.
11 | Try to put it in the correct repo (sensor/gateway), but its no biggie if you choose the wrong one.
12 |
13 | # Contibuting Code
14 |
15 | I'm not accepting code contributions at this time.
16 | I want to maintain sole copyright ownership until I'm confident in the paths chosen for Wekalayer project licenses.
17 | That being said, please reach out if you are interested in contributing code.
18 | Your input could help with this process.
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Weaklayer Sensor
2 |
3 | **N.B.** As of early 2021, this project is no longer under active development and has been removed from browser extension stores. However, the Weaklayer sensor and gateway still work well at the time of writing. The sensor just requires installing from source now.
4 |
5 | Welcome to the Weaklayer Sensor repository!
6 | Weaklayer is a software system for Browser Detection and Response - like Endpoint Detection and Reponse (EDR) but in the browser.
7 | The Weaklayer Sensor (a browser extension) collects and sends security data to a Weaklayer Gateway instance you are running.
8 |
9 | The Weaklayer Sensor is written against the WebExtensions API using the [Mozilla WebExtension Polyfill](https://github.com/mozilla/webextension-polyfill).
10 | Here is a compatibility table for the Weaklayer Sensor and the browsers that implement this technology.
11 |
12 | | Browser | Supported | Minimum Version | Notes |
13 | |---------|-----------|-----------------|-------|
14 | | Firefox (Desktop) | ☑ | 57 | - |
15 | | Firefox (Android) | ☒ | - |
16 | | Chrome | ☑ | 51 | - |
17 | | Edge | ☑ | 79 | Edge on MacOS support is not available since managed storage is not functioning as expected on this platform. |
18 | | Opera | ☒ | - | Opera does not support the [Managed Storage API](https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/storage/managed) according to MDN. It might work still since Opera is Chromium-based. Please create a Github issue if this is important to you. |
19 | | Safari | ☒ | - | Safari 14 will have WebExtensions so this should be possible in the future. |
20 |
21 | ## Usage
22 |
23 | Detailed usage instructions can be found in the [Docs section of the Weaklayer Website](https://weaklayer.com/docs/).
24 | This includes instructions for installation and configuration.
25 | Things that follow in this README are for Weaklayer Sensor development.
26 |
27 | ## Building From Source
28 |
29 | This requires you have `npm` installed.
30 |
31 | ```
32 | git clone https://github.com/weaklayer/sensor.git
33 | cd sensor
34 | npm install
35 | npm test
36 | npm run build-firefox # or build-chrome or build-edge
37 | ```
38 |
39 | This produces a minified browser extension in the `dist` directory.
40 | You can load this extension in your browser's developer mode as an unpacked extension.
41 |
--------------------------------------------------------------------------------
/icon128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weaklayer/sensor/fdcb8d657ba61b09e16bf6a4616071a95691c98e/icon128.png
--------------------------------------------------------------------------------
/icon16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weaklayer/sensor/fdcb8d657ba61b09e16bf6a4616071a95691c98e/icon16.png
--------------------------------------------------------------------------------
/icon48.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/weaklayer/sensor/fdcb8d657ba61b09e16bf6a4616071a95691c98e/icon48.png
--------------------------------------------------------------------------------
/manifests/chrome/managed-storage-schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json-schema.org/draft-07/schema#",
3 | "description": "Weaklayer sensor configuration data",
4 | "type": "object",
5 | "required": [
6 | "api",
7 | "installKey",
8 | "label"
9 | ],
10 | "properties": {
11 | "api": {
12 | "type": "object",
13 | "description": "The API endpoint that the sensor should contact.",
14 | "required": [
15 | "protocol",
16 | "hostname",
17 | "port"
18 | ],
19 | "properties": {
20 | "protocol": {
21 | "type": "string",
22 | "enum": [
23 | "http",
24 | "https"
25 | ],
26 | "description": "The sensor api protocol. http or https."
27 | },
28 | "hostname": {
29 | "type": "string",
30 | "anyOf": [
31 | {
32 | "format": "idn-hostname"
33 | },
34 | {
35 | "format": "hostname"
36 | },
37 | {
38 | "format": "ipv4"
39 | },
40 | {
41 | "format": "ipv6"
42 | }
43 | ],
44 | "description": "The sensor api endpoint hostname."
45 | },
46 | "port": {
47 | "type": "integer",
48 | "minimum": 0,
49 | "maximum": 65535,
50 | "description": "The sensor api endpoint port."
51 | }
52 | }
53 | },
54 | "installKey": {
55 | "type": "object",
56 | "description": "The key that the sensor uses to install.",
57 | "required": [
58 | "group",
59 | "secret",
60 | "checksum"
61 | ],
62 | "properties": {
63 | "group": {
64 | "type": "string",
65 | "description": "The group that the sensor will install under.",
66 | "format": "uuid"
67 | },
68 | "secret": {
69 | "type": "string",
70 | "description": "Base64 encoded 512-bit secret that acts as a password for the sensor to install in the above group.",
71 | "pattern": "^[A-Za-z0-9+/]{86}==$"
72 | },
73 | "checksum": {
74 | "type": "string",
75 | "description": "Base64 encoded 32-bit checksum value that ensures the groupId and secret were entered correctly.",
76 | "pattern": "^[A-Za-z0-9+/]{43}=$"
77 | }
78 | }
79 | },
80 | "label": {
81 | "type": "string",
82 | "description": "A label that is applied to the sensor at installation. "
83 | }
84 | }
85 | }
--------------------------------------------------------------------------------
/manifests/chrome/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Weaklayer Sensor",
3 | "author": "Weaklayer",
4 | "version": "0.0.4",
5 | "description": "Browser Detection and Response",
6 | "manifest_version": 2,
7 | "icons": {
8 | "16": "icon16.png",
9 | "48": "icon48.png",
10 | "128": "icon128.png"
11 | },
12 | "incognito": "spanning",
13 | "background": {
14 | "scripts": [
15 | "browser-polyfill.min.js",
16 | "background.js"
17 | ],
18 | "persistent": true
19 | },
20 | "content_scripts": [
21 | {
22 | "js": [
23 | "browser-polyfill.min.js",
24 | "content.js"
25 | ],
26 | "matches": [
27 | ""
28 | ],
29 | "run_at": "document_start",
30 | "match_about_blank": true,
31 | "all_frames": true
32 | }
33 | ],
34 | "permissions": [
35 | "storage",
36 | ""
37 | ],
38 | "storage": {
39 | "managed_schema": "managed-storage-schema.json"
40 | },
41 | "minimum_chrome_version": "51"
42 | }
--------------------------------------------------------------------------------
/manifests/edge/managed-storage-schema.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json-schema.org/draft-07/schema#",
3 | "description": "Weaklayer sensor configuration data",
4 | "type": "object",
5 | "required": [
6 | "api",
7 | "installKey",
8 | "label"
9 | ],
10 | "properties": {
11 | "api": {
12 | "type": "object",
13 | "description": "The API endpoint that the sensor should contact.",
14 | "required": [
15 | "protocol",
16 | "hostname",
17 | "port"
18 | ],
19 | "properties": {
20 | "protocol": {
21 | "type": "string",
22 | "enum": [
23 | "http",
24 | "https"
25 | ],
26 | "description": "The sensor api protocol. http or https."
27 | },
28 | "hostname": {
29 | "type": "string",
30 | "anyOf": [
31 | {
32 | "format": "idn-hostname"
33 | },
34 | {
35 | "format": "hostname"
36 | },
37 | {
38 | "format": "ipv4"
39 | },
40 | {
41 | "format": "ipv6"
42 | }
43 | ],
44 | "description": "The sensor api endpoint hostname."
45 | },
46 | "port": {
47 | "type": "integer",
48 | "minimum": 0,
49 | "maximum": 65535,
50 | "description": "The sensor api endpoint port."
51 | }
52 | }
53 | },
54 | "installKey": {
55 | "type": "object",
56 | "description": "The key that the sensor uses to install.",
57 | "required": [
58 | "group",
59 | "secret",
60 | "checksum"
61 | ],
62 | "properties": {
63 | "group": {
64 | "type": "string",
65 | "description": "The group that the sensor will install under.",
66 | "format": "uuid"
67 | },
68 | "secret": {
69 | "type": "string",
70 | "description": "Base64 encoded 512-bit secret that acts as a password for the sensor to install in the above group.",
71 | "pattern": "^[A-Za-z0-9+/]{86}==$"
72 | },
73 | "checksum": {
74 | "type": "string",
75 | "description": "Base64 encoded 32-bit checksum value that ensures the groupId and secret were entered correctly.",
76 | "pattern": "^[A-Za-z0-9+/]{43}=$"
77 | }
78 | }
79 | },
80 | "label": {
81 | "type": "string",
82 | "description": "A label that is applied to the sensor at installation. "
83 | }
84 | }
85 | }
--------------------------------------------------------------------------------
/manifests/edge/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Weaklayer Sensor",
3 | "author": "Weaklayer",
4 | "version": "0.0.4",
5 | "description": "Browser Detection and Response",
6 | "manifest_version": 2,
7 | "icons": {
8 | "16": "icon16.png",
9 | "48": "icon48.png",
10 | "128": "icon128.png"
11 | },
12 | "incognito": "spanning",
13 | "background": {
14 | "scripts": [
15 | "browser-polyfill.min.js",
16 | "background.js"
17 | ],
18 | "persistent": true
19 | },
20 | "content_scripts": [
21 | {
22 | "js": [
23 | "browser-polyfill.min.js",
24 | "content.js"
25 | ],
26 | "matches": [
27 | ""
28 | ],
29 | "run_at": "document_start",
30 | "match_about_blank": true,
31 | "all_frames": true
32 | }
33 | ],
34 | "permissions": [
35 | "storage",
36 | ""
37 | ],
38 | "storage": {
39 | "managed_schema": "managed-storage-schema.json"
40 | },
41 | "minimum_chrome_version": "79"
42 | }
--------------------------------------------------------------------------------
/manifests/firefox/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "browser_specific_settings": {
3 | "gecko": {
4 | "id": "sensor@weaklayer.com",
5 | "strict_min_version": "57.0"
6 | }
7 | },
8 | "name": "Weaklayer Sensor",
9 | "author": "Weaklayer",
10 | "version": "0.0.4",
11 | "description": "Browser Detection and Response",
12 | "manifest_version": 2,
13 | "icons": {
14 | "16": "icon16.png",
15 | "48": "icon48.png",
16 | "128": "icon128.png"
17 | },
18 | "incognito": "spanning",
19 | "background": {
20 | "scripts": [
21 | "browser-polyfill.min.js",
22 | "background.js"
23 | ],
24 | "persistent": true
25 | },
26 | "content_scripts": [
27 | {
28 | "js": [
29 | "browser-polyfill.min.js",
30 | "content.js"
31 | ],
32 | "matches": [
33 | ""
34 | ],
35 | "run_at": "document_start",
36 | "match_about_blank": true,
37 | "all_frames": true
38 | }
39 | ],
40 | "permissions": [
41 | "storage",
42 | ""
43 | ]
44 | }
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "@weaklayer/sensor",
3 | "description": "Browser Detection and Response",
4 | "version": "0.0.4",
5 | "license": "AGPL-3.0-or-later",
6 | "private": true,
7 | "files": [
8 | "dist"
9 | ],
10 | "scripts": {
11 | "wipe": "npm run clean && rm -rf node_modules",
12 | "clean": "rm -rf ./dist && rm -rf ./.licenses",
13 | "build": "npm run clean && webpack --config webpack.config.js ",
14 | "build-firefox": "npm run build && cp manifests/firefox/* dist/",
15 | "build-chrome": "npm run build && cp manifests/chrome/* dist/",
16 | "build-edge": "npm run build && cp manifests/edge/* dist/",
17 | "package": "licensed cache && licensed status && licensed notices && cp .licenses/NOTICE dist/ && cd dist && zip -r weaklayer-sensor-binary-release.zip ./",
18 | "test": "nyc mocha"
19 | },
20 | "devDependencies": {
21 | "@types/base64-js": "^1.3.0",
22 | "@types/chai": "^4.2.12",
23 | "@types/firefox-webext-browser": "^78.0.1",
24 | "@types/jsdom": "^16.2.4",
25 | "@types/mocha": "^8.0.3",
26 | "@types/pako": "^1.0.1",
27 | "@types/uuid": "^8.3.0",
28 | "chai": "^4.2.0",
29 | "clean-webpack-plugin": "^3.0.0",
30 | "copy-webpack-plugin": "^6.1.0",
31 | "jsdom": "^16.4.0",
32 | "mocha": "^8.1.3",
33 | "nyc": "^15.1.0",
34 | "ts-loader": "^8.0.3",
35 | "ts-node": "^9.0.0",
36 | "typescript": "^4.0.2",
37 | "webpack": "^4.44.1",
38 | "webpack-cli": "^3.3.12"
39 | },
40 | "dependencies": {
41 | "base64-js": "1.3.1",
42 | "pako": "^1.0.11",
43 | "uuid": "8.3.1",
44 | "webextension-polyfill": "0.6.0"
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/background/BackgroundHub.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { windowEventType, isWindowEvent, normalizeWindowEvent } from '../common/events/WindowEvent'
21 |
22 | import { windowLocationEventType, isWindowLocationEvent, normalizeWindowLocationEvent } from '../common/events/WindowLocationEvent'
23 | import { textCaptureEventType, isTextCaptureEvent, normalizeTextCaptureEvent } from '../common/events/internal/TextCaptureEvent'
24 |
25 | import { Event, isEvent } from '../common/events/Event'
26 | import { WindowMetadata } from './window/WindowMetadata'
27 |
28 | export class BackgroundHub {
29 |
30 | private readonly eventHandler: (e: Event, w: WindowMetadata) => void
31 |
32 | private readonly verifierMap: Map boolean>
33 | private readonly normalizerMap: Map Event>
34 |
35 | constructor(eventHandler: (e: Event, w: WindowMetadata) => void) {
36 | browser.runtime.onConnect.addListener((p) => this.wirePort(p))
37 |
38 | this.eventHandler = eventHandler
39 |
40 | const vMap = new Map boolean>()
41 | vMap.set(windowEventType, (e: any) => isWindowEvent(e))
42 | vMap.set(windowLocationEventType, (e: any) => isWindowLocationEvent(e))
43 | vMap.set(textCaptureEventType, (e: any) => isTextCaptureEvent(e))
44 | this.verifierMap = vMap
45 |
46 | const nMap = new Map Event>()
47 | nMap.set
48 | nMap.set(windowEventType, (e: any) => normalizeWindowEvent(e))
49 | nMap.set(windowLocationEventType, (e: any) => normalizeWindowLocationEvent(e))
50 | nMap.set(textCaptureEventType, (e: any) => normalizeTextCaptureEvent(e))
51 |
52 | this.normalizerMap = nMap
53 | }
54 |
55 | private wirePort(port: browser.runtime.Port): void {
56 | // onConnect gives us some important metadata about the frame/window the connect came from
57 | const windowMetadata = new WindowMetadata(port.sender?.tab?.id, port.sender?.frameId)
58 |
59 | if (port.name === "EventPort") {
60 | port.onMessage.addListener((event) => this.verifyAndHandle(event, windowMetadata))
61 | } else {
62 | console.warn(`Wiring requested for unknown port type`)
63 | }
64 | }
65 |
66 | private verifyAndHandle(event: any, windowMetadata: WindowMetadata): void {
67 | if (isEvent(event)) {
68 | const verifier = this.verifierMap.get(event.type)
69 | const normalizer = this.normalizerMap.get(event.type)
70 | if (verifier && normalizer) {
71 | if (verifier(event)) {
72 | this.eventHandler(normalizer(event), windowMetadata)
73 | } else {
74 | console.warn(`Invalid event of type ${event.type} sent from content script`)
75 | }
76 | } else {
77 | console.warn(`Unknown event type ${event.type} sent from content script`)
78 | }
79 | }
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/background/EventCollector.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { EventCollector } from './EventCollector'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | import { Semaphore } from '../common/concurrent/Semaphore'
25 | import { Event } from '../common/events/Event';
26 | import { JSDOM } from 'jsdom'
27 |
28 |
29 | suite('EventCollector', () => {
30 |
31 | test('Process on immediate timeout', async () => {
32 | const fakeDom = new JSDOM()
33 | const semaphore = new Semaphore()
34 |
35 | let capturedEvent: Event | undefined = undefined
36 |
37 | const eventCollector = new EventCollector(async (events) => {
38 | capturedEvent = events[0]
39 | semaphore.setSignal()
40 | }, Number.MAX_SAFE_INTEGER, 1)
41 |
42 | const event: Event = { type: "Window", time: 1234 }
43 | eventCollector.consumeEvents([event], fakeDom.window)
44 |
45 | await semaphore.getSignal()
46 |
47 | assert.strictEqual(capturedEvent, event, "Captured event not equal")
48 | })
49 |
50 |
51 | test('Process on overall timeout', async () => {
52 | const fakeDom = new JSDOM()
53 | const semaphore = new Semaphore()
54 |
55 | let capturedEvent: Event | undefined = undefined
56 |
57 | const eventCollector = new EventCollector(async (events) => {
58 | capturedEvent = events[0]
59 | semaphore.setSignal()
60 | }, 1, Number.MAX_SAFE_INTEGER)
61 |
62 | const event: Event = { type: "Window", time: 1234 }
63 | eventCollector.consumeEvents([event], fakeDom.window)
64 |
65 | await semaphore.getSignal()
66 |
67 | assert.strictEqual(capturedEvent, event, "Captured event not equal")
68 | })
69 | })
70 |
--------------------------------------------------------------------------------
/src/background/EventCollector.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Event } from '../common/events/Event'
21 |
22 | export class EventCollector {
23 |
24 | private readonly eventsConsumer: (es: Array) => Promise
25 |
26 | private readonly overallTimeout: number
27 |
28 | private readonly immediateTimeout: number
29 |
30 | private readonly maxBufferSize: number
31 |
32 | private events: Array = new Array()
33 |
34 | private overallTimer: number | undefined = undefined
35 |
36 | private immediateTimer: number | undefined = undefined
37 |
38 | constructor(eventsConsumer: (es: Array) => Promise, overallTimeout: number = 10000, immediateTimeout: number = 1000, maxBufferSize: number = 10000) {
39 | this.eventsConsumer = eventsConsumer
40 | this.overallTimeout = overallTimeout
41 | this.immediateTimeout = immediateTimeout
42 | this.maxBufferSize = maxBufferSize
43 | }
44 |
45 | consumeEvents(events: Array, w: WindowOrWorkerGlobalScope = window): void {
46 |
47 | this.events.push(...events)
48 |
49 | if (!this.overallTimer) {
50 | // Hold onto events for 5s max before sending them off
51 | this.overallTimer = w.setTimeout(() => this.processEvents(w), this.overallTimeout)
52 | }
53 |
54 | if (this.immediateTimer) {
55 | w.clearTimeout(this.immediateTimer)
56 | }
57 | // Events can come in 500ms apart and they will get buffered
58 | this.immediateTimer = w.setTimeout(() => this.processEvents(w), this.immediateTimeout)
59 | }
60 |
61 | private async processEvents(w: WindowOrWorkerGlobalScope): Promise {
62 | if (this.overallTimer) {
63 | w.clearTimeout(this.overallTimer)
64 | this.overallTimer = undefined
65 | }
66 |
67 | if (this.immediateTimer) {
68 | w.clearTimeout(this.immediateTimer)
69 | this.immediateTimer = undefined
70 | }
71 |
72 | let eventsCapture = this.events
73 | this.events = new Array()
74 | try {
75 | await this.eventsConsumer(eventsCapture)
76 | } catch (e) {
77 | console.warn('Failed submitting events to gateway. Will retry soon.', e)
78 | if (eventsCapture.length > this.maxBufferSize) {
79 | // Throw out oldest events to get us down to the max buffer size
80 | eventsCapture = eventsCapture.slice(eventsCapture.length - this.maxBufferSize)
81 | }
82 | // 1) append to this.events (instead on assigning) as it could have been added to already during the above await
83 | // 2) append instead of calling consumeEvents so we dont queue up another immediate submission attempt
84 | this.events.push(...eventsCapture)
85 | }
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/background/SensorEventAPI.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { ManagedStorage } from './storage/ManagedStorage'
21 | import { Installer } from './install/Installer'
22 | import { Event } from '../common/events/Event'
23 | import { gzip } from 'pako'
24 |
25 | export class SensorEventAPI {
26 |
27 | private readonly installer: Installer
28 |
29 | constructor(installer: Installer) {
30 | this.installer = installer
31 | }
32 |
33 | async submit(events: Array): Promise {
34 |
35 | // Shouldn't happen, but don't issue a request if
36 | // called with length 0 array
37 | if (events.length <= 0) {
38 | return
39 | }
40 |
41 | // This will throw if things go bad with authentication (network error or failing response code)
42 | const headers = await this.getHeaders()
43 |
44 | const sensorApiBaseUrl: string = await ManagedStorage.getSensorApiEndpoint()
45 | const eventUrl = `${sensorApiBaseUrl}/events`
46 |
47 | // This will throw if things go bad
48 | const response = await fetch(eventUrl, {
49 | method: 'POST',
50 | body: gzip(JSON.stringify(events)),
51 | headers: headers
52 | })
53 |
54 | // Non 2XX. Didn't work. Throw so we can retry
55 | if (response.status < 200 || 300 <= response.status) {
56 | if (400 <= response.status && response.status < 500) {
57 | // With 4XX there was an auth problem. Attempt reinstall on the next go.
58 | this.installer.forceReinstall()
59 | }
60 |
61 | throw new Error(`Received response code ${response.status} for event submission.`)
62 | }
63 | }
64 |
65 | private async getHeaders(): Promise {
66 | const token = await this.installer.getAuthorizationToken()
67 | return new Headers({
68 | 'Content-Type': 'application/json',
69 | 'Content-Encoding': 'gzip',
70 | 'Authorization': `Bearer ${token}`
71 | })
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/background/background.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Installer } from './install/Installer'
21 | import { SensorEventAPI } from './SensorEventAPI'
22 | import { BackgroundHub } from './BackgroundHub'
23 | import { HashKeyManager } from './text/HashKeyManager'
24 | import { KeyedHasher } from './text/KeyedHasher'
25 | import { TextInputEventFinalizer } from './text/TextInputEventFinalizer'
26 | import { TextCaptureEvent, isTextCaptureEvent } from '../common/events/internal/TextCaptureEvent'
27 | import { EventCollector } from './EventCollector'
28 | import { WindowTracker } from './window/WindowTracker'
29 | import { isWindowEvent } from '../common/events/WindowEvent'
30 | import { LocalStorage } from './storage/LocalStorage'
31 | import { TextCaptureSessionManager } from './text/TextCaptureSessionManager'
32 | import { TextInputEventDeduplicator } from './text/TextInputEventDeduplicator'
33 |
34 | console.info(`
35 | Weaklayer Sensor is available under the terms of the GNU Affero General Public License (GNU AGPL).
36 | Please see the program source for the exact GNU AGPL version.
37 |
38 | The Weaklayer Sensor source is available at https://github.com/weaklayer/sensor
39 |
40 | The Weaklayer Gateway source is available at https://github.com/weaklayer/gateway
41 |
42 | For more information, please see https://weaklayer.com
43 | `)
44 |
45 | const installer = new Installer(() => LocalStorage.clearTextHashKey())
46 | const sensorEventApi = new SensorEventAPI(installer)
47 | const eventCollector = new EventCollector((es) => sensorEventApi.submit(es))
48 |
49 | const textHashKeyManager = new HashKeyManager()
50 | const textHasher: KeyedHasher = new KeyedHasher(() => textHashKeyManager.getHashKey())
51 | const textInputEventFinalizer = new TextInputEventFinalizer(text => textHasher.computeStringHash(text))
52 | const textInputEventDeduplicator = new TextInputEventDeduplicator(event => eventCollector.consumeEvents([event]))
53 |
54 | const textInputSessionManager: TextCaptureSessionManager = new TextCaptureSessionManager(5000, 300000, async (events: Array) => {
55 | const processedEvents = await textInputEventFinalizer.processTextCaptureEvents(events)
56 | processedEvents.forEach(async e => {
57 | textInputEventDeduplicator.processTextInput(e)
58 | })
59 | })
60 |
61 | const windowTracker = new WindowTracker()
62 |
63 | const eventHub = new BackgroundHub((event, windowMetadata) => {
64 | if (isWindowEvent(event)) {
65 | windowTracker.mutateWindow(event, windowMetadata)
66 | eventCollector.consumeEvents([event])
67 | } else if (isTextCaptureEvent(event)) {
68 | textInputSessionManager.trackTextCapture(event)
69 | } else {
70 | eventCollector.consumeEvents([event])
71 | }
72 | })
73 |
74 | // Manually trigger an auth token get on startup
75 | // This will force any required network calls
76 | // So the token is present locally when it is needed.
77 | installer.getAuthorizationToken().then(() => {
78 | console.info('Authorization token present.')
79 | })
80 |
--------------------------------------------------------------------------------
/src/background/install/InstallKey.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha';
22 | import { InstallKey, isInstallKey, normalizeInstallKey, isChecksumValid } from './InstallKey';
23 | import { JSDOM } from 'jsdom'
24 |
25 | suite('InstallKey', () => {
26 |
27 | test('Valid install key', async () => {
28 | const fakeDom = new JSDOM()
29 |
30 | const key = {
31 | group: "68886d61-572b-41a5-8edd-93a564fb5ba3",
32 | secret: "jTbup3jD+nWFRw2LW5k6v0dP+qf6cWXsc3IazN39GnaMeKEp13kpyh6AJFo3V1ckeD3dt0JXfoqmeOWr2jU29Q==",
33 | checksum: "jvqWXRmh9JAnbwDS19W59lOJXD2dZuRglhFtsJzDedU=",
34 | extra: "heyyy"
35 | }
36 |
37 | assert.isTrue(isInstallKey(key), "Valid install key identified as invalid")
38 |
39 | const normalizedInstallKey: InstallKey = normalizeInstallKey(key)
40 | assert.isTrue(isInstallKey(normalizedInstallKey), "Valid install key identified as invalid")
41 | assert.isFalse('extra' in normalizedInstallKey, "Install key normalization failed")
42 |
43 | })
44 | })
45 |
--------------------------------------------------------------------------------
/src/background/install/InstallKey.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { areArraysEqual } from '../../common/utils/ByteUtils'
21 | import { toByteArray } from 'base64-js'
22 | import { UUID } from '../../common/data/UUID'
23 |
24 | const uuidRegex: RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
25 | const secretRegex: RegExp = /^[A-Za-z0-9+/]{86}==$/
26 | const checksumRegex: RegExp = /^[A-Za-z0-9+/]{43}=$/
27 |
28 | export interface InstallKey {
29 | group: string // normal uuid string
30 | secret: string // base64 encoded binary secret
31 | checksum: string // base64 encoded checksum of groupid and secret
32 | }
33 |
34 | export function normalizeInstallKey(installKey: InstallKey): InstallKey {
35 | return {
36 | group: installKey.group,
37 | secret: installKey.secret,
38 | checksum: installKey.checksum
39 | }
40 | }
41 |
42 | export function isInstallKey(data: any): data is InstallKey {
43 | const validGroup: boolean = 'group' in data && typeof data.group === 'string' && uuidRegex.test(data.group)
44 | const validSecret: boolean = 'secret' in data && typeof data.secret === 'string' && secretRegex.test(data.secret)
45 | const validCheckSum: boolean = 'checksum' in data && typeof data.checksum === 'string' && checksumRegex.test(data.checksum)
46 |
47 | return validGroup && validSecret && validCheckSum
48 | }
49 |
50 | export async function isChecksumValid(installKey: InstallKey): Promise {
51 | const calculatedChecksum = await calculateChecksum(UUID.fromString(installKey.group), toByteArray(installKey.secret))
52 | return areArraysEqual(calculatedChecksum, toByteArray(installKey.checksum))
53 | }
54 |
55 | export async function calculateChecksum(groupId: UUID, installSecret: Uint8Array): Promise {
56 | const arrayView: Uint8Array = new Uint8Array(80)
57 | arrayView.set(groupId.asBytes(), 0)
58 | arrayView.set(installSecret, 16)
59 |
60 | const calculatedHash = await crypto.subtle.digest('SHA-256', arrayView)
61 |
62 | return new Uint8Array(calculatedHash)
63 | }
64 |
--------------------------------------------------------------------------------
/src/background/install/InstallRequest.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { InstallKey } from './InstallKey'
21 |
22 | export interface InstallRequest {
23 | key: InstallKey
24 | label: string
25 | }
26 |
--------------------------------------------------------------------------------
/src/background/install/InstallResponse.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha';
22 | import { InstallResponse, isInstallResponse, normalizeInstallResponse } from './InstallResponse';
23 |
24 | suite('InstallResponse', () => {
25 |
26 | test('Valid install response', async () => {
27 | const installResponse = {
28 | token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
29 | sensor: "68886d61-572b-41a5-8edd-93a564fb5ba3",
30 | expiresAt: 52435234,
31 | issuedAt: 412341,
32 | extra: "gsdfgs"
33 | }
34 |
35 | assert.isTrue(isInstallResponse(installResponse), "Valid install response identified as invalid")
36 |
37 | const normalizedInstallResponse: InstallResponse = normalizeInstallResponse(installResponse)
38 | assert.isTrue(isInstallResponse(normalizedInstallResponse), "Valid install response identified as invalid")
39 | assert.isFalse('extra' in normalizedInstallResponse, "Install response normalization failed")
40 | })
41 |
42 | })
43 |
--------------------------------------------------------------------------------
/src/background/install/InstallResponse.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 |
21 | const sensorRegex: RegExp = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/
22 | const tokenRegex: RegExp = /^[A-Za-z0-9-_=]+\.[A-Za-z0-9-_=]+\.?[A-Za-z0-9-_.+/=]*$/
23 |
24 | export interface InstallResponse {
25 | token: string
26 | sensor: string
27 | expiresAt: number
28 | issuedAt: number
29 | }
30 |
31 | export function normalizeInstallResponse(installResponse: InstallResponse): InstallResponse {
32 | return {
33 | token: installResponse.token,
34 | sensor: installResponse.sensor,
35 | expiresAt: installResponse.expiresAt,
36 | issuedAt: installResponse.issuedAt
37 | }
38 | }
39 |
40 | export function isInstallResponse(data: any): data is InstallResponse {
41 | const validToken: boolean = 'token' in data && typeof data.token === 'string' && tokenRegex.test(data.token)
42 | const validSensorId: boolean = 'sensor' in data && typeof data.sensor === 'string' && sensorRegex.test(data.sensor)
43 | const validExpiresAt: boolean = 'expiresAt' in data && typeof data.expiresAt === 'number' && Number.isInteger(data.expiresAt) && data.expiresAt >= 0
44 | const validIssuedAt: boolean = 'issuedAt' in data && typeof data.issuedAt === 'number' && Number.isInteger(data.issuedAt) && data.issuedAt >= 0
45 |
46 | return true
47 | }
48 |
--------------------------------------------------------------------------------
/src/background/install/Installer.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { LocalStorage } from '../storage/LocalStorage'
21 | import { InstallRequest } from './InstallRequest'
22 | import { InstallResponse, isInstallResponse, normalizeInstallResponse } from './InstallResponse'
23 | import { Lock } from '../../common/concurrent/Lock'
24 | import { ManagedStorage } from '../storage/ManagedStorage'
25 |
26 | export class Installer {
27 |
28 | private readonly lock: Lock = new Lock()
29 |
30 | private installInfo: InstallResponse | undefined = undefined
31 |
32 | // By initializing this to true, we (re)install on restart.
33 | // This is good because we will execute a reinstall
34 | // and get a new identity if the install key changes
35 | // And we'll keep expiring tokens at bay
36 | private installRequired: boolean = true
37 |
38 | private readonly identityChangeActions: () => Promise
39 | private shouldRunIdentityChangeActions: boolean = false
40 |
41 | // Takes a function that is run if the sensor's identity
42 | // i.e. its sensorId changes.
43 | constructor(identityChangeActions: () => Promise) {
44 | this.identityChangeActions = identityChangeActions
45 | }
46 |
47 | async getAuthorizationToken(): Promise {
48 | const info = await this.getInstallInfo()
49 | return info.token
50 | }
51 |
52 | // In theory this should get called
53 | // if the managed storage stuff changes
54 | // for example, new install key or sensor label
55 | // doesn't throw out the current info.
56 | // gets us to reinstall
57 | forceReinstall(): void {
58 | this.installRequired = true
59 | }
60 |
61 | private static installInfoExpiryApproaching(installInfo: InstallResponse): boolean {
62 | // We should attempt to renew the token if the token is 3/4 expired
63 | const threeQuartersExpiredPoint = 0.25 * installInfo.issuedAt + 0.75 * installInfo.expiresAt
64 |
65 | return (Date.now() * 1000) > threeQuartersExpiredPoint
66 | }
67 |
68 |
69 | // Here we have the logic for the conditions where the in memory value
70 | // is return. If we are not in that situation, then we need the lock
71 | // so we can perform the storage and network actions to get a valid
72 | // identity back into memory here.
73 | private async getInstallInfo(): Promise {
74 | if (this.installInfo && !this.installRequired) {
75 | if (!Installer.installInfoExpiryApproaching(this.installInfo)) {
76 | return this.installInfo
77 | }
78 | }
79 |
80 | const installInfo = await this.lock.syncExecute(() => this.getInstallInfoUnsafe())
81 |
82 | // The above call will set this flag
83 | // Do it this way so we can run the actions outside
84 | // of the locked execute
85 | // Mainly due to the concern of the identity change actions
86 | // calling this class and causing deadlock
87 | if (this.shouldRunIdentityChangeActions) {
88 | this.shouldRunIdentityChangeActions = false
89 | console.info('Running identity change actions.')
90 | await this.identityChangeActions()
91 | }
92 |
93 | return installInfo
94 | }
95 |
96 | private async getInstallInfoUnsafe(): Promise {
97 |
98 | // check if install info in memory
99 | // - if not in memory, try to fetch from storage
100 | // - update memory value if something retrieved from storage
101 | if (!this.installInfo) {
102 | try {
103 | const storageInfo = await LocalStorage.getInstallInfo()
104 | this.installInfo = storageInfo
105 | } catch (e) {
106 | console.info('Could not retrieve install info from storage. Proceeding with new install.', e)
107 | }
108 | }
109 |
110 | // check if the in-memory value is valid
111 | // - if valid, return the token
112 | // - if not valid, or still not present then perform install
113 | if (this.installInfo && !this.installRequired) {
114 | if (!Installer.installInfoExpiryApproaching(this.installInfo)) {
115 | return this.installInfo
116 | }
117 | }
118 |
119 | // Install info is either not present or expired
120 | // Get the install response from the backend
121 | // - write the new repsonse to storage
122 | // - copy new response into memory
123 | console.info('Executing sensor install.')
124 | const oldInstallInfo = this.installInfo
125 | const newInstallInfo = await Installer.renewAuthorizationTokenUnsafe(oldInstallInfo)
126 | this.installRequired = false
127 |
128 | let identityChange = true
129 | if (oldInstallInfo) {
130 | if (oldInstallInfo.sensor === newInstallInfo.sensor) {
131 | identityChange = false
132 | }
133 | }
134 | this.shouldRunIdentityChangeActions = identityChange
135 |
136 | await LocalStorage.setInstallInfo(newInstallInfo)
137 | this.installInfo = newInstallInfo
138 |
139 | return newInstallInfo
140 | }
141 |
142 | private static async renewAuthorizationTokenUnsafe(currentInfo?: InstallResponse): Promise {
143 |
144 | const sensorApi: string = await ManagedStorage.getSensorApiEndpoint()
145 |
146 | const installRequest: InstallRequest = {
147 | key: await ManagedStorage.getInstalKey(),
148 | label: await ManagedStorage.getSensorLabel(),
149 | }
150 |
151 | const headers = new Headers({
152 | 'Content-Type': 'application/json'
153 | })
154 |
155 | const token: string | undefined = currentInfo?.token
156 | if (token) {
157 | headers.append("Authorization", `Bearer ${token}`)
158 | }
159 |
160 | const response = await fetch(`${sensorApi}/install`, {
161 | method: 'POST',
162 | body: JSON.stringify(installRequest),
163 | headers: headers
164 | })
165 |
166 | if (200 <= response.status && response.status < 300) {
167 | const responseBody: any = await response.json()
168 | if (isInstallResponse(responseBody)) {
169 | return normalizeInstallResponse(responseBody)
170 | } else {
171 | throw new Error('Received install response that does not match the expected schema.')
172 | }
173 | } else {
174 | throw new Error(`Received response code ${response.status} for install.`)
175 | }
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/src/background/storage/LocalStorage.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from "../../common/utils/Assert"
21 |
22 | import { setStorageValue, getStorageValue, clearStorageValue, getStorageString } from './Storage'
23 | import { InstallResponse, isInstallResponse, normalizeInstallResponse } from "../install/InstallResponse"
24 | import { fromByteArray, toByteArray } from "base64-js"
25 |
26 | export class LocalStorage {
27 |
28 | private constructor() { }
29 |
30 | private static readonly installInfoKey = 'installInfo'
31 | private static readonly textHashKeyKey = 'textHashKey'
32 |
33 | static async getInstallInfo(): Promise {
34 | const storageValue = await getStorageValue(LocalStorage.installInfoKey, k => browser.storage.local.get(k))
35 | assert(isInstallResponse(storageValue), `Value set for ${LocalStorage.installInfoKey} in local storage does not conform to the expected schema.`)
36 | return normalizeInstallResponse(storageValue)
37 | }
38 |
39 | static async setInstallInfo(installInfo: InstallResponse): Promise {
40 | return setStorageValue(LocalStorage.installInfoKey, installInfo, (i) => browser.storage.local.set(i))
41 | }
42 |
43 | static async getTextHashKey(): Promise {
44 | const storageValue: string = await getStorageString(LocalStorage.textHashKeyKey, /^[A-Za-z0-9+/]{86}==$/, k => browser.storage.local.get(k))
45 | return toByteArray(storageValue)
46 | }
47 |
48 | static async setTextHashKey(textHashKey: Uint8Array): Promise {
49 | return setStorageValue(LocalStorage.textHashKeyKey, fromByteArray(textHashKey), (i) => browser.storage.local.set(i))
50 | }
51 |
52 | static async clearTextHashKey(): Promise {
53 | return clearStorageValue(LocalStorage.textHashKeyKey, k => browser.storage.local.remove(k))
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/background/storage/ManagedStorage.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { InstallKey, isInstallKey, normalizeInstallKey, isChecksumValid } from "../install/InstallKey"
21 | import { assert } from "../../common/utils/Assert"
22 | import { getStorageValue, getStorageString } from './Storage'
23 | import { SensorAPI, isSensorAPI, normalizeSensorAPI } from "./SensorAPI"
24 |
25 | export class ManagedStorage {
26 |
27 | private constructor() { }
28 |
29 | // always just get these values from here to keep getting the fresh values
30 | // some way to invalidate things if these change?
31 |
32 | private static readonly installKeyKey = 'installKey'
33 | private static readonly labelKey = 'label'
34 | private static readonly apiKey = 'api'
35 |
36 | static async getInstalKey(): Promise {
37 | const storageValue = await getStorageValue(ManagedStorage.installKeyKey, (k) => browser.storage.managed.get(k))
38 |
39 | assert(isInstallKey(storageValue), `Value set for ${ManagedStorage.installKeyKey} in managed storage does not conform to the expected schema.`)
40 | const installKey = normalizeInstallKey(storageValue)
41 |
42 | assert(await isChecksumValid(installKey), `Value set for ${ManagedStorage.installKeyKey} has a checksum that does not match.`)
43 | return installKey
44 | }
45 |
46 | static async getSensorLabel(): Promise {
47 | return getStorageString(ManagedStorage.labelKey, /^.*$/, (k) => browser.storage.managed.get(k))
48 | }
49 |
50 | static async getSensorApiEndpoint(): Promise {
51 | const api = await ManagedStorage.getSensorApi()
52 | return `${api.protocol}://${api.hostname}:${api.port}`
53 | }
54 |
55 | private static async getSensorApi(): Promise {
56 | const storageValue = await getStorageValue(ManagedStorage.apiKey, (k) => browser.storage.managed.get(k))
57 | assert(isSensorAPI(storageValue), `Value set for ${ManagedStorage.apiKey} in managed storage does not conform to the expected schema.`)
58 | return normalizeSensorAPI(storageValue)
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/background/storage/SensorAPI.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | export interface SensorAPI {
21 | protocol: string
22 | hostname: string
23 | port: number
24 | }
25 |
26 | export function normalizeSensorAPI(api: SensorAPI): SensorAPI {
27 | return {
28 | protocol: api.protocol,
29 | hostname: api.hostname,
30 | port: api.port
31 | }
32 | }
33 |
34 | export function isSensorAPI(data: any): data is SensorAPI {
35 | const validProtocol: boolean = 'protocol' in data && typeof data.protocol === 'string' && (data.protocol === 'http' || data.protocol === 'https')
36 | if (!validProtocol) {
37 | return false
38 | }
39 |
40 | const validHostname: boolean = 'hostname' in data && typeof data.hostname === 'string' && data.hostname.length >= 1 && data.hostname.length <= 255
41 | if (!validHostname) {
42 | return false
43 | }
44 |
45 | const validPort: boolean = 'port' in data && typeof data.port === 'number' && data.port >= 0 && data.port <= 65535 && Number.isInteger(data.port)
46 | if (!validPort) {
47 | return false
48 | }
49 |
50 | return true
51 | }
52 |
--------------------------------------------------------------------------------
/src/background/storage/Storage.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from "../../common/utils/Assert"
21 |
22 | type StorageGetter = (key?: string) => Promise<{ [key: string]: any }>
23 | type StorageSetter = (items: { [key: string]: any }) => Promise
24 | type StorageRemover = (keys: string) => Promise
25 |
26 | export async function getStorageString(key: string, regex: RegExp, storageGetter: StorageGetter): Promise {
27 | const storageValue = await getStorageValue(key, storageGetter)
28 |
29 | assert(typeof storageValue === 'string', `Value set for ${key} in storage is not the expected type of string.`)
30 | const stringValue: string = storageValue
31 |
32 | assert(regex.test(stringValue), `String value set for ${key} did not match the validation regex ${regex.toString()}.`)
33 | return stringValue
34 | }
35 |
36 | export async function getStorageValue(key: string, storageGetter: StorageGetter): Promise {
37 | const storageDoc = await storageGetter(key)
38 | assert(key in storageDoc, `A value for ${key} was not found in storage.`)
39 | return storageDoc[key]
40 | }
41 |
42 | export async function setStorageValue(key: string, value: any, storageSetter: StorageSetter): Promise {
43 | return storageSetter({ [key]: value })
44 | }
45 |
46 |
47 | export async function clearStorageValue(key: string, storageRemover: StorageRemover): Promise {
48 | return storageRemover(key)
49 | }
50 |
--------------------------------------------------------------------------------
/src/background/text/HashKeyManager.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha';
22 | import { HashKeyManager } from './HashKeyManager';
23 |
24 | suite('HashKeyManager', () => {
25 |
26 | test('Generates and stores new hash key', async () => {
27 | const key: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8])
28 |
29 | let keyStorage: Uint8Array | undefined = undefined
30 |
31 | const hashKeyManager = new HashKeyManager(
32 | () => { throw new Error('no hash key') },
33 | async (key) => { keyStorage = key },
34 | async () => { keyStorage = undefined },
35 | () => key
36 | )
37 |
38 | const newKey = await hashKeyManager.getHashKey()
39 |
40 | assert(keyStorage === key, "Stored key doesn't match expected")
41 | assert(newKey === key, "Newly generated key doesn't match expected")
42 |
43 | const cachedKey = await hashKeyManager.getHashKey()
44 |
45 | assert(cachedKey === key, "Cached key doesn't match expected")
46 |
47 | await hashKeyManager.clearHashKey()
48 |
49 | assert(keyStorage === undefined, "Stored key was not successfully cleared")
50 | })
51 |
52 | test('Returns stored hash key', async () => {
53 | const key: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8])
54 |
55 | const hashKeyManager = new HashKeyManager(
56 | async () => { return key },
57 | async (key) => { throw new Error("This shouldn't be called") },
58 | async () => { throw new Error("This shouldn't be called") },
59 | () => key
60 | )
61 |
62 | const storedKey = await hashKeyManager.getHashKey()
63 |
64 | assert(storedKey === key, "Key retrieved from storage doesn't match expected")
65 |
66 | const cachedKey = await hashKeyManager.getHashKey()
67 |
68 | assert(cachedKey === key, "Cached key doesn't match expected")
69 | })
70 | })
71 |
--------------------------------------------------------------------------------
/src/background/text/HashKeyManager.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { LocalStorage } from '../storage/LocalStorage'
21 | import { Lock } from '../../common/concurrent/Lock'
22 |
23 | export class HashKeyManager {
24 |
25 | private static readonly keyLength: number = 64
26 |
27 | private readonly keyStorageSupplier: () => Promise
28 | private readonly keyStorageConsumer: (key: Uint8Array) => Promise
29 | private readonly keyStorageClearer: () => Promise
30 | private readonly keyGenerator: () => Uint8Array
31 |
32 | private readonly lock: Lock = new Lock()
33 | private cachedValue?: Uint8Array = undefined
34 |
35 | constructor(keyStorageSupplier: () => Promise = () => LocalStorage.getTextHashKey(),
36 | keyStorageConsumer: (key: Uint8Array) => Promise = (key) => LocalStorage.setTextHashKey(key),
37 | keyStorageClearer: () => Promise = () => LocalStorage.clearTextHashKey(),
38 | keyGenerator: () => Uint8Array = () => crypto.getRandomValues(new Uint8Array(HashKeyManager.keyLength))) {
39 | this.keyStorageSupplier = keyStorageSupplier
40 | this.keyStorageConsumer = keyStorageConsumer
41 | this.keyStorageClearer = keyStorageClearer
42 | this.keyGenerator = keyGenerator
43 | }
44 |
45 | getHashKey(): Promise {
46 |
47 | if (this.cachedValue) {
48 | return Promise.resolve(this.cachedValue)
49 | }
50 |
51 | return this.lock.syncExecute(() => this.internalGetHashKeyUnsafe())
52 | }
53 |
54 | private async internalGetHashKeyUnsafe(): Promise {
55 | // check the cache again.
56 | // another execution might have set it while we
57 | // were waiting for the lock
58 | if (this.cachedValue) {
59 | return this.cachedValue
60 | }
61 |
62 | try {
63 | const storedKey: Uint8Array = await this.keyStorageSupplier()
64 | this.cachedValue = storedKey
65 | return storedKey
66 | } catch (e) {
67 | console.info('Could not retrieve hash key from local storage. Generating new hash key.', e)
68 | }
69 |
70 | const newKey: Uint8Array = this.keyGenerator()
71 |
72 | // important that we are able to persist the hash key
73 | // before we keep it in this class or return it
74 | await this.keyStorageConsumer(newKey)
75 |
76 | this.cachedValue = newKey
77 |
78 | return newKey
79 | }
80 |
81 | clearHashKey(): Promise {
82 | return this.lock.syncExecute(async () => {
83 | await this.keyStorageClearer()
84 | this.cachedValue = undefined
85 | })
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/src/background/text/KeyedHasher.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | export class KeyedHasher {
21 |
22 | private readonly textEncoder: TextEncoder = new TextEncoder()
23 | private readonly hashKeySupplier: () => Promise
24 |
25 | constructor(hashKeySupplier: () => Promise) {
26 | this.hashKeySupplier = hashKeySupplier
27 | }
28 |
29 | async computeStringHash(text: string): Promise {
30 | return this.computeBytesHash(this.textEncoder.encode(text))
31 | }
32 |
33 | async computeBytesHash(bytes: Uint8Array): Promise {
34 | const hmacKey = crypto.subtle.importKey('raw', await this.hashKeySupplier(), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign'])
35 | const hash = await crypto.subtle.sign('HMAC', await hmacKey, bytes)
36 | return new Uint8Array(hash)
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/background/text/TextCaptureSession.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha';
22 | import { createTextCaptureEvent } from '../../common/events/internal/TextCaptureEvent'
23 | import { TextCaptureSession } from './TextCaptureSession'
24 |
25 | suite('TextCaptureSession', () => {
26 | test('Prunes uninteresting events', async () => {
27 | const textCaptureSession = new TextCaptureSession()
28 |
29 | const event1 = createTextCaptureEvent('h', 'text', 22, 1, 2)
30 | const event2 = createTextCaptureEvent('he', 'text', 22, 1, 2)
31 | const event3 = createTextCaptureEvent('hel', 'text', 22, 1, 2)
32 | const event4 = createTextCaptureEvent('hell', 'text', 22, 1, 2)
33 | const event5 = createTextCaptureEvent('hello', 'text', 22, 1, 2)
34 | const event6 = createTextCaptureEvent('hell', 'text', 22, 1, 2)
35 | const event7 = createTextCaptureEvent('hel', 'text', 22, 1, 2)
36 | const event8 = createTextCaptureEvent('he', 'text', 22, 1, 2)
37 |
38 |
39 | // track out of order. should get sorted inside
40 | textCaptureSession.trackTextCapture(event5)
41 | textCaptureSession.trackTextCapture(event2)
42 | textCaptureSession.trackTextCapture(event4)
43 | textCaptureSession.trackTextCapture(event3)
44 | textCaptureSession.trackTextCapture(event1)
45 | textCaptureSession.trackTextCapture(event6)
46 | textCaptureSession.trackTextCapture(event7)
47 | textCaptureSession.trackTextCapture(event8)
48 |
49 | const events = textCaptureSession.getInterestingTextCaptures()
50 |
51 | assert(events.length === 3, 'Wrong number of interesting text Capture events')
52 | assert(events[0].text === 'h', 'Incorrect first event')
53 | assert(events[1].text === 'hello', 'Incorrect second event')
54 | assert(events[2].text === 'he', 'Incorrect third event')
55 | })
56 |
57 | test('Prunes with repeated strings at apex', async () => {
58 | const textCaptureSession = new TextCaptureSession()
59 |
60 | const event1 = createTextCaptureEvent('h', 'text', 22, 1, 2)
61 | const event2 = createTextCaptureEvent('he', 'text', 22, 1, 2)
62 | const event3 = createTextCaptureEvent('hel', 'text', 22, 1, 2)
63 | const event4 = createTextCaptureEvent('hell', 'text', 22, 1, 2)
64 | const event5 = createTextCaptureEvent('hello', 'text', 22, 1, 2)
65 | const event6 = createTextCaptureEvent('hello', 'text', 22, 1, 2)
66 | const event7 = createTextCaptureEvent('hello', 'text', 22, 1, 2)
67 | const event8 = createTextCaptureEvent('hell', 'text', 22, 1, 2)
68 | const event9 = createTextCaptureEvent('hel', 'text', 22, 1, 2)
69 | const event10 = createTextCaptureEvent('he', 'text', 22, 1, 2)
70 |
71 |
72 | // track out of order. should get sorted inside
73 | textCaptureSession.trackTextCapture(event5)
74 | textCaptureSession.trackTextCapture(event2)
75 | textCaptureSession.trackTextCapture(event4)
76 | textCaptureSession.trackTextCapture(event3)
77 | textCaptureSession.trackTextCapture(event1)
78 | textCaptureSession.trackTextCapture(event9)
79 | textCaptureSession.trackTextCapture(event6)
80 | textCaptureSession.trackTextCapture(event10)
81 | textCaptureSession.trackTextCapture(event7)
82 | textCaptureSession.trackTextCapture(event8)
83 |
84 | const events = textCaptureSession.getInterestingTextCaptures()
85 |
86 | assert(events.length === 3, 'Wrong number of interesting text Capture events')
87 | assert(events[0].text === 'h', 'Incorrect first event')
88 | assert(events[1].text === 'hello', 'Incorrect second event')
89 | assert(events[2].text === 'he', 'Incorrect third event')
90 | })
91 | })
92 |
--------------------------------------------------------------------------------
/src/background/text/TextCaptureSession.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { TextCaptureEvent } from '../../common/events/internal/TextCaptureEvent'
21 |
22 | export class TextCaptureSession {
23 |
24 | private readonly events: Array = new Array()
25 |
26 | trackTextCapture(textCaptureEvent: TextCaptureEvent) {
27 | this.events.push(textCaptureEvent)
28 | }
29 |
30 | getInterestingTextCaptures(): Array {
31 |
32 | // this array should be mostly sorted already
33 | // we make sure they are in order so we can
34 | // compare string lengths instead of doing substring operations
35 | this.events.sort((a, b) => {
36 | return a.time - b.time
37 | })
38 |
39 | const interestingCaptures: Array = new Array()
40 |
41 | // Always take the first entry
42 | if (this.events.length >= 1) {
43 | interestingCaptures.push(this.events[0])
44 | }
45 |
46 | if (this.events.length >= 3) {
47 | // Look for sliding window of 3 here.
48 | // We keep a capture if it is a spike or a dip in string length
49 | for (let i = 1; i < this.events.length - 1; i++) {
50 | const lastEntry = this.events[i - 1]
51 | const thisEntry = this.events[i]
52 | const nextEntry = this.events[i + 1]
53 |
54 | const lastText: string = lastEntry.text
55 | const thisText: string = thisEntry.text
56 | const nextText: string = nextEntry.text
57 |
58 | if (thisText.length > lastText.length && nextText.length > thisText.length) {
59 | // monotonic increasing string
60 | } else if (lastText.length > thisText.length && thisText.length > nextText.length) {
61 | // monotonic decreasing string
62 | } else {
63 | interestingCaptures.push(thisEntry)
64 | }
65 | }
66 | }
67 |
68 | // Always take the last entry because someone could backspace onto their password to finish
69 | if (this.events.length >= 2) {
70 | interestingCaptures.push(this.events[this.events.length - 1])
71 | }
72 |
73 | // Deduplicate captures
74 | const deduplicatedCaptures: Array = new Array()
75 |
76 | const seenStrings = new Set()
77 | for (let capture of interestingCaptures) {
78 | if (!seenStrings.has(capture.text)) {
79 | seenStrings.add(capture.text)
80 | deduplicatedCaptures.push(capture)
81 | }
82 | }
83 |
84 | return deduplicatedCaptures
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/background/text/TextCaptureSessionManager.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { TextCaptureSession } from "./TextCaptureSession"
21 | import { TextCaptureEvent } from "../../common/events/internal/TextCaptureEvent"
22 |
23 | export class TextCaptureSessionManager {
24 |
25 | private readonly sessionTimers: Map = new Map()
26 | private readonly globalTimers: Map = new Map()
27 | private readonly sessions: Map = new Map()
28 |
29 | private readonly sessionTimeoutMillis: number
30 | private readonly maxSessionLengthMillis: number
31 | private readonly interestingCaptureConsumer: (interestingCaptures: Array) => Promise
32 |
33 | constructor(sessionTimeoutMillis: number, maxSessionLengthMillis: number,
34 | interestingCaptureConsumer: (interestingCaptures: Array) => Promise) {
35 | this.interestingCaptureConsumer = interestingCaptureConsumer
36 | this.sessionTimeoutMillis = sessionTimeoutMillis
37 | this.maxSessionLengthMillis = maxSessionLengthMillis
38 | }
39 |
40 | trackTextCapture(event: TextCaptureEvent): void {
41 | const sessionId: number = event.elementReference
42 |
43 | let session: TextCaptureSession | undefined = this.sessions.get(sessionId)
44 | if (!session) {
45 | session = new TextCaptureSession()
46 | this.sessions.set(sessionId, session)
47 | }
48 |
49 | let sessionTimer: number | undefined = this.sessionTimers.get(sessionId)
50 | if (sessionTimer) {
51 | window.clearTimeout(sessionTimer)
52 | }
53 | this.sessionTimers.set(sessionId, window.setTimeout(() => this.processSession(sessionId), this.sessionTimeoutMillis))
54 |
55 | let globalTimer: number | undefined = this.globalTimers.get(sessionId)
56 | if (!globalTimer) {
57 | this.globalTimers.set(sessionId, window.setTimeout(() => this.processSession(sessionId), this.maxSessionLengthMillis))
58 | }
59 |
60 | session.trackTextCapture(event)
61 | }
62 |
63 | private processSession(sessionId: number): void {
64 | let sessionTimer: number | undefined = this.sessionTimers.get(sessionId)
65 | if (sessionTimer) {
66 | window.clearTimeout(sessionTimer)
67 | this.sessionTimers.delete(sessionId)
68 | }
69 |
70 | let globalTimer: number | undefined = this.globalTimers.get(sessionId)
71 | if (globalTimer) {
72 | window.clearTimeout(globalTimer)
73 | this.globalTimers.delete(sessionId)
74 | }
75 |
76 | let session: TextCaptureSession | undefined = this.sessions.get(sessionId)
77 | if (session) {
78 | this.sessions.delete(sessionId)
79 | const captures = session.getInterestingTextCaptures()
80 | this.interestingCaptureConsumer(captures)
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/background/text/TextInputEventDeduplicator.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { TextInputEvent } from "../../common/events/TextInputEvent"
21 |
22 | export class TextInputEventDeduplicator {
23 |
24 | // When html input elements are used, the same text input events are
25 | // generated twice. Once as an input element capture and the other as
26 | // a virtual input element capture
27 |
28 | private readonly discardTimers: Map = new Map()
29 | private readonly seenHashes: Map> = new Map>()
30 |
31 | private readonly windowLocationDiscardMillis: number
32 | private readonly inputEventConsumer: (textInputEvent: TextInputEvent) => void
33 |
34 |
35 | constructor(inputEventConsumer: (textInputEvent: TextInputEvent) => void, windowLocationDiscardMillis: number = 10000) {
36 | this.windowLocationDiscardMillis = windowLocationDiscardMillis
37 | this.inputEventConsumer = inputEventConsumer
38 | }
39 |
40 | async processTextInput(event: TextInputEvent): Promise {
41 |
42 | if (event.inputType === 'unknown' || event.inputType === 'composite') {
43 | // pause and give events of known input type a chance to make it first
44 | await new Promise(resolve => setTimeout(resolve, 1000))
45 | }
46 |
47 | const windowLocationReference: number = event.windowLocationReference
48 |
49 | let seenHashes: Set | undefined = this.seenHashes.get(windowLocationReference)
50 | if (!seenHashes) {
51 | seenHashes = new Set()
52 | this.seenHashes.set(windowLocationReference, seenHashes)
53 | }
54 |
55 | let discardTimer: number | undefined = this.discardTimers.get(windowLocationReference)
56 | if (discardTimer) {
57 | window.clearTimeout(discardTimer)
58 | }
59 | this.discardTimers.set(windowLocationReference, window.setTimeout(() => this.discard(windowLocationReference), this.windowLocationDiscardMillis))
60 |
61 | if (!seenHashes.has(event.textHash)) {
62 | seenHashes.add(event.textHash)
63 | this.inputEventConsumer(event)
64 | }
65 | }
66 |
67 | private discard(windowLocationReference: number): void {
68 |
69 | let discardTimer: number | undefined = this.discardTimers.get(windowLocationReference)
70 | if (discardTimer) {
71 | window.clearTimeout(discardTimer)
72 | }
73 |
74 | this.seenHashes.delete(windowLocationReference)
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/background/text/TextInputEventFinalizer.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha';
22 | import { TextInputEventFinalizer } from './TextInputEventFinalizer'
23 | import { fromByteArray } from 'base64-js'
24 | import { createTextCaptureEvent } from '../../common/events/internal/TextCaptureEvent';
25 |
26 | suite('TextInputEventFinalizer', () => {
27 | test('Calculates hash', async () => {
28 | const hash = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8])
29 | const finalizer = new TextInputEventFinalizer(async (text) => hash)
30 |
31 | const event = createTextCaptureEvent('hello', 'text', 22, 1, 2)
32 |
33 | const finalizedEvents = await finalizer.processTextCaptureEvents([event])
34 |
35 | assert(finalizedEvents[0].textHash === fromByteArray(hash), 'Finalized text input event hash incorrect')
36 | })
37 | })
38 |
--------------------------------------------------------------------------------
/src/background/text/TextInputEventFinalizer.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { TextInputEvent, createTextInputEvent } from '../../common/events/TextInputEvent'
21 | import { fromByteArray } from 'base64-js'
22 | import { TextCaptureEvent } from '../../common/events/internal/TextCaptureEvent'
23 |
24 | export class TextInputEventFinalizer {
25 |
26 | private readonly textHasher: (text: string) => Promise
27 |
28 | constructor(textHasher: (text: string) => Promise) {
29 | this.textHasher = textHasher
30 | }
31 |
32 | async processTextCaptureEvents(events: Array): Promise> {
33 |
34 | return Promise.all(events.map(async (e) => {
35 | // normalize the text before hashing.
36 | // this will avoid equivalent strings not matching because of different unicode representations
37 | // see https://flaviocopes.com/javascript-unicode/ for examples
38 | const hash = await this.textHasher(e.text.normalize())
39 |
40 | const textInputEvent = createTextInputEvent(e.time, fromByteArray(hash), e.text.length, e.inputType, e.windowLocationReference)
41 |
42 | return textInputEvent
43 | }))
44 | }
45 | }
--------------------------------------------------------------------------------
/src/background/window/WindowMetadata.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | export class WindowMetadata {
21 |
22 | readonly tabId?: number
23 | readonly frameId?: number
24 |
25 | constructor(tabId?: number, frameId?: number) {
26 | this.tabId = tabId
27 | this.frameId = frameId
28 | }
29 | }
--------------------------------------------------------------------------------
/src/background/window/WindowTracker.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha';
22 | import { createWindowEvent, WindowEvent } from '../../common/events/WindowEvent';
23 | import { WindowMetadata } from './WindowMetadata';
24 | import { WindowTracker } from './WindowTracker'
25 |
26 | suite('WindowTracker', () => {
27 | test('Correctly classifies windows', async () => {
28 | const windowTracker = new WindowTracker()
29 |
30 | const topLevelWindowMeta: WindowMetadata = new WindowMetadata(1, 0)
31 | const topLevelWindowEvent: WindowEvent = createWindowEvent()
32 | windowTracker.mutateWindow(topLevelWindowEvent, topLevelWindowMeta)
33 | assert(topLevelWindowEvent.isTopLevelWindow, "Top level window not marked as such")
34 | assert(topLevelWindowEvent.topLevelWindowReference === topLevelWindowEvent.time, "Top level window didn't reference itself")
35 |
36 | const childWindowMeta: WindowMetadata = new WindowMetadata(1, 233)
37 | const childWindowEvent: WindowEvent = createWindowEvent()
38 | windowTracker.mutateWindow(childWindowEvent, childWindowMeta)
39 | assert(!childWindowEvent.isTopLevelWindow, "Child window marked as top level window")
40 | assert(childWindowEvent.topLevelWindowReference === topLevelWindowEvent.time, "Child window does not reference top-level window")
41 | })
42 | })
43 |
--------------------------------------------------------------------------------
/src/background/window/WindowTracker.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { WindowEvent } from "../../common/events/WindowEvent"
21 | import { WindowMetadata } from "./WindowMetadata"
22 |
23 | export class WindowTracker {
24 |
25 | private readonly topLevelWindowMap: Map
26 |
27 | constructor() {
28 | this.topLevelWindowMap = new Map()
29 | }
30 |
31 | mutateWindow(event: WindowEvent, windowMetadata: WindowMetadata): void {
32 | if ('frameId' in windowMetadata && windowMetadata.frameId === 0) {
33 | this.mutateTopLevelWindow(event, windowMetadata)
34 | } else {
35 | // note that the frame id is only used for determining if something is a top level window
36 | // we can still track if tabId and url are set
37 | this.mutateLowerLevelWindow(event, windowMetadata)
38 | }
39 | }
40 |
41 | private mutateTopLevelWindow(event: WindowEvent, windowMetadata: WindowMetadata): void {
42 | event.isTopLevelWindow = true
43 | event.topLevelWindowReference = event.time
44 | if (windowMetadata.tabId) {
45 | // New top-level window/frame creation
46 | // This means that the tab has now been taken over by this window
47 | // We can stop tracking the old top-level window
48 | this.topLevelWindowMap.set(windowMetadata.tabId, event.time)
49 | } else {
50 | // tabId is missing so we can't effectively track it or anything else that comes in
51 | // log a warning and send the event off
52 | console.warn('New top-level window created but no tabId given')
53 | }
54 | }
55 |
56 | private async mutateLowerLevelWindow(event: WindowEvent, windowMetadata: WindowMetadata): Promise {
57 | event.isTopLevelWindow = false
58 | event.topLevelWindowReference = 0
59 | if (windowMetadata.tabId) {
60 | const topLevelWindow = this.topLevelWindowMap.get(windowMetadata.tabId)
61 | if (topLevelWindow) { // topLevelWindow won't be 0 if set
62 | event.topLevelWindowReference = topLevelWindow
63 | } else {
64 | console.warn('New window created but no top-level window set for given tab')
65 | }
66 | } else {
67 | // tabId is missing so we can't effectively track match it against a top level window
68 | console.warn('New window created but no tabId given')
69 | }
70 | }
71 | }
--------------------------------------------------------------------------------
/src/common/concurrent/Lock.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Lock } from './Lock'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 |
25 | suite('Lock', () => {
26 |
27 | test('Synchronously execute with lock', async () => {
28 | const lock = new Lock()
29 | const executeOrder = new Array()
30 |
31 | async function action(name: string) {
32 | executeOrder.push(name)
33 | }
34 |
35 | const actionOneDone = lock.syncExecute((s) => action(s), "one")
36 | const actionTwoDone = lock.syncExecute((s) => action(s), "two")
37 |
38 | await actionOneDone
39 | await actionTwoDone
40 |
41 | assert.deepStrictEqual(executeOrder, ["one", "two"])
42 | })
43 |
44 | })
45 |
--------------------------------------------------------------------------------
/src/common/concurrent/Lock.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Semaphore } from './Semaphore'
21 |
22 | type AsyncFunction = (...args: I[]) => Promise
23 |
24 | // N.B. This lock is not re-entrant
25 | export class Lock {
26 |
27 | private lastInLineSignal: Promise = Promise.resolve()
28 |
29 | async lock(): Promise<() => void> {
30 |
31 | // capture the promise of:
32 | // 1) who last had the lock in the case of no contention
33 | // 2) who currently has the lock if there is no lineup
34 | // 3) who is last in line for lock in case of a lineup
35 |
36 | const beforeMeSignal = this.lastInLineSignal
37 |
38 | const me = new Semaphore()
39 |
40 | // we are now last in line
41 | this.lastInLineSignal = me.getSignal()
42 |
43 | // wait for the signal that the lock hold before us is released
44 | await beforeMeSignal
45 |
46 | // we now have the lock
47 | // the unlock function we return
48 | // is the function that sets the signal
49 | // i.e. resolves the semaphore promise
50 | return () => me.setSignal()
51 | }
52 |
53 | async syncExecute(unsafeFun: AsyncFunction, ...args: Parameters>): ReturnType> {
54 | const unlock = await this.lock()
55 |
56 | try {
57 | return await unsafeFun(...args)
58 | } finally {
59 | unlock()
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/common/concurrent/Semaphore.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Semaphore } from './Semaphore'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | suite('Semaphore', () => {
25 |
26 | test('Waiting on semaphore signal', async () => {
27 | const s = new Semaphore()
28 | let flag = false
29 |
30 | // set the semphore later in a seperate line of execution
31 | setTimeout(() => {
32 | flag = true
33 | s.setSignal()
34 | }, 1)
35 |
36 | await s.getSignal()
37 |
38 | assert.strictEqual(flag, true, "Logic did not block until semaphore was set")
39 | })
40 |
41 | })
42 |
--------------------------------------------------------------------------------
/src/common/concurrent/Semaphore.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | export class Semaphore {
21 |
22 | private signalResolver: (() => void) | undefined = undefined
23 | private readonly signal: Promise
24 |
25 | constructor() {
26 | this.signal = new Promise(resolver => {
27 | this.signalResolver = resolver
28 | })
29 | }
30 |
31 | setSignal(): void {
32 | if (this.signalResolver) {
33 | this.signalResolver()
34 | } else {
35 | // we shouldn't ever end up in here
36 | // if we do then we can't ever really set the signal
37 | // since we didn't capture the resolver
38 |
39 | // the resolver should capture at some point though
40 | new Promise(resolve => setTimeout(resolve, 5000)).then(() => {
41 | if (this.signalResolver) {
42 | this.signalResolver()
43 | } else {
44 | console.error('Failed to set semaphore signal after 5 second wait.')
45 | }
46 | })
47 |
48 | console.error('Failed to resolve semaphore signal as the promise resolver was not captured. Will attempt to resolve again in 5 seconds.')
49 | }
50 | }
51 |
52 | getSignal(): Promise {
53 | return this.signal
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/common/data/UUID.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { UUID } from './UUID'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | suite('UUID', () => {
25 |
26 | test('UUID string operations', () => {
27 | const uuidString = '04a9104b-4b2e-4399-9cdd-b1f44886dc3c'
28 | const uuid = UUID.fromString(uuidString)
29 | const uuidString2 = uuid.asString()
30 | assert.strictEqual(uuidString2, uuidString, 'Parsed UUID did not match original string')
31 | })
32 |
33 | test('UUID byte operations', () => {
34 | const uuid1 = UUID.newRandomUuid()
35 | const bytes = uuid1.asBytes()
36 |
37 | const uuid2 = new UUID(bytes)
38 |
39 | assert.isTrue(UUID.equals(uuid1, uuid2))
40 | })
41 |
42 | })
43 |
--------------------------------------------------------------------------------
/src/common/data/UUID.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { v4 as uuidv4 } from 'uuid'
21 | import { hexStringToBytes, areArraysEqual } from '../utils/ByteUtils'
22 | import { assert } from '../utils/Assert'
23 |
24 | export class UUID {
25 |
26 | private readonly data: Uint8Array
27 |
28 | constructor(data: Uint8Array) {
29 | assert(data.length === 16, 'UUID is made of 16 bytes.')
30 | this.data = data
31 | }
32 |
33 | asBytes(): Uint8Array {
34 | return this.data
35 | }
36 |
37 | asString(): string {
38 | return uuidv4({ random: this.data })
39 | }
40 |
41 | static fromString(uuid: string): UUID {
42 | assert(uuid.length === 36, 'UUID strings must be 36 characters.')
43 |
44 | const stringSections = uuid.split('-')
45 | assert(stringSections.length === 5, 'UUID strings must have 4 hyphens.')
46 |
47 | const data = new Uint8Array(16)
48 |
49 | const sectionLengths = [8, 4, 4, 4, 12]
50 | const byteOffsets = [0, 4, 6, 8, 10]
51 | for (let i = 0; i < 5; i++) {
52 | const section = stringSections[i]
53 | assert(section.length === sectionLengths[i], 'UUID string not properly formatted.')
54 | hexStringToBytes(section, data, byteOffsets[i])
55 | }
56 |
57 | return new UUID(data)
58 | }
59 |
60 | static newRandomUuid(): UUID {
61 | const data = new Uint8Array(16)
62 | uuidv4({}, data)
63 | return new UUID(data)
64 | }
65 |
66 | static equals(uuid1: UUID, uuid2: UUID): boolean {
67 | return areArraysEqual(uuid1.asBytes(), uuid2.asBytes())
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/src/common/events/Event.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Event, getEventTime, isEventTime, isEvent } from './Event'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | suite('Event', () => {
25 |
26 | test('Event time generation produces sane values', () => {
27 | const nowMillis = Date.now() * 1000
28 | const eventTime = getEventTime()
29 |
30 | assert.isTrue(eventTime >= nowMillis, "Generated event time is in the past")
31 | })
32 |
33 | test('Event time verification works in both directions', () => {
34 | const eventTime = getEventTime()
35 | const fraction = 134123412342.13241234
36 | const negative = -23523452
37 | const zero = 0
38 |
39 | assert.isTrue(isEventTime(eventTime), "Generated event time identified as invalid")
40 | assert.isTrue(isEventTime(zero), "Zero value event time identified as invalid")
41 | assert.isFalse(isEventTime(fraction), "Fractional event time identified as valid")
42 | assert.isFalse(isEventTime(negative), "Negative event time identified as valid")
43 | })
44 |
45 | test('Event verification', () => {
46 | const event1: Event = {
47 | type: "Window",
48 | time: 264362
49 | }
50 |
51 | const event2 = {
52 | type: "",
53 | time: 1324125,
54 | extra: "heeyyyyyyyyyy"
55 | }
56 |
57 | const badEvent1 = {
58 | type: ""
59 | }
60 |
61 | const badEvent2 = {
62 | type: "",
63 | time: 1324125.435
64 | }
65 |
66 | const badEvent3 = {
67 | type: 4234
68 | }
69 |
70 | const badEvent4 = {
71 | extra: "heeyyyyyyyyyy"
72 | }
73 |
74 |
75 | assert.isTrue(isEvent(event1), "Valid event identified as invalid")
76 | assert.isTrue(isEvent(event2), "Valid event identified as invalid")
77 | assert.isFalse(isEvent(badEvent1), "Invalid event identified as valid")
78 | assert.isFalse(isEvent(badEvent2), "Invalid event identified as valid")
79 | assert.isFalse(isEvent(badEvent3), "Invalid event identified as valid")
80 | assert.isFalse(isEvent(badEvent4), "Invalid event identified as valid")
81 | })
82 |
83 | })
84 |
--------------------------------------------------------------------------------
/src/common/events/Event.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 |
21 | export interface Event {
22 | type: string
23 | time: number
24 | }
25 |
26 | export function isEvent(data: any): data is Event {
27 | const validType: boolean = 'type' in data && typeof data.type === 'string'
28 | const validTime: boolean = 'time' in data && typeof data.time === 'number' && isEventTime(data.time)
29 |
30 | return validType && validTime
31 | }
32 |
33 | export function isEventTime(num: number): boolean {
34 | return Number.isInteger(num) && num >= 0
35 | }
36 |
37 |
38 |
39 | let lastMillis: number = 0
40 | let tag: number = 0
41 | export function getEventTime(): number {
42 | const millis = getEpochMillis()
43 | if (millis !== lastMillis) {
44 | // reset the tag value whenever the measured time changes
45 | // random up to 900 so we don't end up near 1000 and roll over in the same millisecond
46 | lastMillis = millis
47 | tag = getRandomInt(0, 900)
48 | }
49 |
50 | return millis * 1000 + getTag()
51 | }
52 |
53 | function getEpochMillis(): number {
54 | // prefer to use the performance time api as it has better guarantees
55 | // monotonically increasing time.
56 | // Still can't rely on it for microsecond precision though according to docs
57 | if (typeof performance !== 'undefined' && typeof performance.timeOrigin !== 'undefined') {
58 | return Math.round(performance.timeOrigin + performance.now())
59 | } else {
60 | return Date.now()
61 | }
62 | }
63 |
64 | // This makes it more likely that two calls in the same millisecond
65 | // are still monotonically increasing
66 | function getTag(): number {
67 | tag = tag + 1
68 | if (tag >= 1000) {
69 | tag = 0
70 | }
71 | return tag
72 | }
73 |
74 | function getRandomInt(min: number, max: number) {
75 | min = Math.ceil(min);
76 | max = Math.floor(max);
77 | return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
78 | }
79 |
--------------------------------------------------------------------------------
/src/common/events/TextInputEvent.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Event } from './Event'
21 |
22 | export const textInputEventType = 'TextInput'
23 |
24 | export interface TextInputEvent extends Event {
25 | textHash: string
26 | textLength: number
27 | inputType: string
28 | windowLocationReference: number
29 | }
30 |
31 | export function createTextInputEvent(time: number, textHash: string, textLength: number, inputType: string, windowLocationReference: number): TextInputEvent {
32 | return {
33 | type: textInputEventType,
34 | time: time,
35 | textHash: textHash,
36 | textLength: textLength,
37 | inputType: inputType,
38 | windowLocationReference: windowLocationReference
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/common/events/WindowEvent.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { WindowEvent, isWindowEvent, createWindowEvent, normalizeWindowEvent } from './WindowEvent'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | suite('WindowEvent', () => {
25 |
26 | test('WindowEvent verification', () => {
27 | const event1: WindowEvent = createWindowEvent()
28 |
29 | const event2 = {
30 | type: "Window",
31 | time: 1324125,
32 | isTopLevelWindow: false,
33 | topLevelWindowReference: 0,
34 | extra: "heeyyyyyyyyyy"
35 | }
36 |
37 | const badEvent1 = {
38 | type: ""
39 | }
40 |
41 | const badEvent2 = {
42 | type: "",
43 | time: 1324125.435
44 | }
45 |
46 | const badEvent3 = {
47 | type: 4234
48 | }
49 |
50 | const badEvent4 = {
51 | extra: "heeyyyyyyyyyy"
52 | }
53 |
54 |
55 | assert.isTrue(isWindowEvent(event1), "Valid event identified as invalid")
56 | assert.isTrue(isWindowEvent(event2), "Valid event identified as invalid")
57 | assert.isFalse(isWindowEvent(badEvent1), "Invalid event identified as valid")
58 | assert.isFalse(isWindowEvent(badEvent2), "Invalid event identified as valid")
59 | assert.isFalse(isWindowEvent(badEvent3), "Invalid event identified as valid")
60 | assert.isFalse(isWindowEvent(badEvent4), "Invalid event identified as valid")
61 | })
62 |
63 | test('WindowEvent normalization', () => {
64 | const event = {
65 | type: "Window",
66 | time: 1324125,
67 | isTopLevelWindow: false,
68 | topLevelWindowReference: 0,
69 | extra: "heeyyyyyyyyyy"
70 | }
71 |
72 | assert.isTrue(isWindowEvent(event), "Valid event identified as invalid")
73 | assert.isTrue('extra' in event, "Test base event missing extra field")
74 |
75 | const normalizedEvent = normalizeWindowEvent(event)
76 |
77 | assert.isTrue(isWindowEvent(normalizedEvent), "Valid event identified as invalid")
78 | assert.isFalse('extra' in normalizedEvent, "Extra field present in normalized event")
79 | })
80 |
81 | })
82 |
--------------------------------------------------------------------------------
/src/common/events/WindowEvent.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { getEventTime, Event, isEvent, isEventTime } from './Event'
21 |
22 | export const windowEventType = 'Window'
23 |
24 | export interface WindowEvent extends Event {
25 | isTopLevelWindow: boolean
26 | topLevelWindowReference: number
27 | }
28 |
29 | export function createWindowEvent(): WindowEvent {
30 | return {
31 | type: windowEventType,
32 | time: getEventTime(),
33 | isTopLevelWindow: false,
34 | topLevelWindowReference: 0
35 | }
36 | }
37 |
38 | export function isWindowEvent(data: any): data is WindowEvent {
39 | const validEvent: boolean = isEvent(data) && data.type === windowEventType
40 |
41 | const validIsTopLevelWindow: boolean = 'isTopLevelWindow' in data && typeof data.isTopLevelWindow === 'boolean'
42 | const validTopLevelWindowReference: boolean = 'topLevelWindowReference' in data && typeof data.topLevelWindowReference === 'number' && isEventTime(data.topLevelWindowReference)
43 |
44 | return validEvent && validIsTopLevelWindow && validTopLevelWindowReference
45 | }
46 |
47 | export function normalizeWindowEvent(event: WindowEvent): WindowEvent {
48 | return {
49 | type: windowEventType,
50 | time: event.time,
51 | isTopLevelWindow: event.isTopLevelWindow,
52 | topLevelWindowReference: event.topLevelWindowReference,
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/common/events/WindowLocationEvent.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { WindowLocationEvent, createWindowLocationEvent, isWindowLocationEvent, normalizeWindowLocationEvent } from './WindowLocationEvent'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha'
23 | import { JSDOM } from 'jsdom'
24 |
25 | suite('WindowLocationEvent', () => {
26 |
27 | test('WindowLocationEvent verification', () => {
28 | const w = new JSDOM('', {
29 | url: "https://weaklayer.com:8443/stuff?hello=true#SectionTitle"
30 | }).window
31 |
32 | const windowRef = 1
33 | const event1: WindowLocationEvent = createWindowLocationEvent(windowRef, () => w.location)
34 |
35 | const event2 = {
36 | type: "Window",
37 | time: 1324125,
38 | }
39 |
40 | assert.isTrue(isWindowLocationEvent(event1), "Valid event identified as invalid")
41 | assert.isFalse(isWindowLocationEvent(event2), "Other event type identified as WindowLocation")
42 | })
43 |
44 |
45 | test('WindowLocationEvent normalization', () => {
46 | const w = new JSDOM('', {
47 | url: "https://weaklayer.com:8443/stuff?hello=true#SectionTitle"
48 | }).window
49 |
50 | const windowRef = 1
51 | const event: any = createWindowLocationEvent(windowRef, () => w.location)
52 | event.extra = "gsdfgfdshgsdfhsgfhdf"
53 |
54 | assert.isTrue(isWindowLocationEvent(event))
55 | assert.isTrue('extra' in event, "Test base event missing extra field")
56 |
57 | const normalizedEvent = normalizeWindowLocationEvent(event)
58 |
59 | assert.isTrue(isWindowLocationEvent(normalizedEvent), "Valid event identified as invalid")
60 | assert.isFalse('extra' in normalizedEvent, "Extra field present in normalized event")
61 | })
62 |
63 | test('Window with no explicit port set', () => {
64 | const w = new JSDOM('', {
65 | url: "https://weaklayer.com/stuff?hello=true#SectionTitle"
66 | }).window
67 |
68 | const windowRef = 1
69 | const event: WindowLocationEvent = createWindowLocationEvent(windowRef, () => w.location)
70 |
71 | assert.isFalse('port' in event && event.port !== undefined, "Port exists in event by default")
72 | })
73 | })
74 |
--------------------------------------------------------------------------------
/src/common/events/WindowLocationEvent.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { isEvent, isEventTime, Event, getEventTime } from './Event'
21 |
22 | export const windowLocationEventType = 'WindowLocation'
23 |
24 | export interface WindowLocationEvent extends Event {
25 | protocol: string
26 | hostname: string
27 | port?: number
28 | path: string
29 | search: string
30 | hash: string
31 | windowReference: number
32 | }
33 |
34 | export function isWindowLocationEvent(data: any): data is WindowLocationEvent {
35 | const validEvent: boolean = isEvent(data) && data.type === windowLocationEventType
36 | const validProtocol: boolean = 'protocol' in data && typeof data.protocol === 'string'
37 | const validHostname: boolean = 'hostname' in data && typeof data.hostname === 'string'
38 | const portPresent = 'port' in data && data.port !== undefined
39 | const validPort: boolean = !portPresent || (portPresent && typeof data.port === 'number' && data.port >= 0 && data.port <= 65535)
40 | const validPath: boolean = 'path' in data && typeof data.path === 'string'
41 | const validSearch: boolean = 'search' in data && typeof data.search === 'string'
42 | const validHash: boolean = 'hash' in data && typeof data.hash === 'string'
43 | const validWindowReference: boolean = 'windowReference' in data && typeof data.windowReference === 'number' && isEventTime(data.windowReference)
44 |
45 | return validEvent && validProtocol && validHostname && validPort && validPath && validSearch && validHash && validWindowReference
46 | }
47 |
48 | export function normalizeWindowLocationEvent(event: WindowLocationEvent): WindowLocationEvent {
49 | return {
50 | type: windowLocationEventType,
51 | time: event.time,
52 | protocol: event.protocol,
53 | hostname: event.hostname,
54 | port: event.port,
55 | path: event.path,
56 | search: event.search,
57 | hash: event.hash,
58 | windowReference: event.windowReference
59 | }
60 | }
61 |
62 |
63 | export function createWindowLocationEvent(windowReference: number, windowLocationSupplier: () => Location): WindowLocationEvent {
64 |
65 | const location: Location = windowLocationSupplier()
66 |
67 | const protocol: string = location.protocol.replace(/:$/, '') // trim the tailing colon from this api call
68 | const hostname: string = location.hostname
69 |
70 | let port: number | undefined
71 | const parsedPort: number = parseInt(location.port)
72 | if (!isNaN(parsedPort)) {
73 | // use the explicitly set port if there is one
74 | port = parsedPort
75 | }
76 |
77 | const path: string = location.pathname
78 | const search: string = location.search
79 | const hash: string = location.hash
80 |
81 | return {
82 | type: windowLocationEventType,
83 | time: getEventTime(),
84 | protocol: protocol,
85 | hostname: hostname,
86 | port: port,
87 | path: path,
88 | search: search,
89 | hash: hash,
90 | windowReference: windowReference
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/src/common/events/internal/TextCaptureEvent.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { TextCaptureEvent, createTextCaptureEvent, isTextCaptureEvent, normalizeTextCaptureEvent, textCaptureEventType } from './TextCaptureEvent'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha'
23 |
24 | suite('TextCaptureEvent', () => {
25 |
26 | test('TextCaptureEvent verification', () => {
27 | const event1: TextCaptureEvent = createTextCaptureEvent('hello', 'password', 22, 2, 5)
28 | assert.isTrue(isTextCaptureEvent(event1), "Valid event identified as invalid")
29 |
30 | const event2: TextCaptureEvent = {
31 | type: textCaptureEventType,
32 | time: 3,
33 | text: 'hello',
34 | inputType: 'password',
35 | windowReference: 100,
36 | elementReference: 3,
37 | windowLocationReference: 6
38 | }
39 | assert.isTrue(isTextCaptureEvent(event2), "Valid event identified as invalid")
40 | })
41 |
42 | test('TextCaptureEvent normalization', () => {
43 | const event: any = {
44 | type: textCaptureEventType,
45 | time: 3,
46 | text: '',
47 | inputType: 'password',
48 | windowReference: 100,
49 | elementReference: 3,
50 | windowLocationReference: 6,
51 | extra: "gsdfgfdshgsdfhsgfhdf"
52 | }
53 |
54 | assert.isTrue(isTextCaptureEvent(event))
55 | assert.isTrue('extra' in event, "Test base event missing extra field")
56 |
57 | const normalizedEvent = normalizeTextCaptureEvent(event)
58 |
59 | assert.isTrue(isTextCaptureEvent(normalizedEvent), "Valid event identified as invalid")
60 | assert.isFalse('extra' in normalizedEvent, "Extra field present in normalized event")
61 |
62 | })
63 |
64 | })
65 |
--------------------------------------------------------------------------------
/src/common/events/internal/TextCaptureEvent.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { isEvent, isEventTime, Event, getEventTime } from '../Event'
21 |
22 | export const textCaptureEventType = 'TextCapture'
23 |
24 | export interface TextCaptureEvent extends Event {
25 | text: string
26 | inputType: string
27 | windowReference: number
28 | windowLocationReference: number
29 | elementReference: number
30 | }
31 |
32 | export function isTextCaptureEvent(data: any): data is TextCaptureEvent {
33 | const validEvent: boolean = isEvent(data) && data.type === textCaptureEventType
34 |
35 | const validText: boolean = 'text' in data && typeof data.text === 'string'
36 | const validInputType: boolean = 'inputType' in data && typeof data.inputType === 'string'
37 |
38 | const validWindowReference: boolean = 'windowReference' in data && typeof data.windowReference === 'number' && isEventTime(data.windowReference)
39 | const validWindowLocationReference: boolean = 'windowLocationReference' in data && typeof data.windowLocationReference === 'number' && isEventTime(data.windowLocationReference)
40 | const validElementReference = 'elementReference' in data && typeof data.elementReference === 'number' && isEventTime(data.elementReference)
41 |
42 |
43 | return validEvent && validText && validInputType && validWindowReference && validWindowLocationReference && validElementReference
44 | }
45 |
46 | export function normalizeTextCaptureEvent(event: TextCaptureEvent): TextCaptureEvent {
47 | return {
48 | type: textCaptureEventType,
49 | time: event.time,
50 | text: event.text,
51 | inputType: event.inputType,
52 | windowReference: event.windowReference,
53 | windowLocationReference: event.windowLocationReference,
54 | elementReference: event.elementReference
55 | }
56 | }
57 |
58 | export function createTextCaptureEvent(text: string | undefined, inputType: string, windowReference: number, windowLocationReference: number, elementReference: number): TextCaptureEvent {
59 | const t = text || '' // Events with missing text somehow seem to happen on occasion
60 |
61 | return {
62 | type: textCaptureEventType,
63 | time: getEventTime(),
64 | text: t,
65 | inputType: inputType,
66 | windowReference: windowReference,
67 | windowLocationReference: windowLocationReference,
68 | elementReference: elementReference
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/common/utils/Assert.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from './Assert'
21 | import { assert as chaiAssert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | suite('Assert', () => {
25 |
26 | test('Test successful assert', () => {
27 | assert(true, "This test should finish fine")
28 | })
29 |
30 | test('Test failed assert', () => {
31 | let flag = false
32 | try {
33 | assert(false, "Flag was false")
34 | } catch (e) {
35 | chaiAssert.strictEqual(e.name, 'AssertionError', "Error with incorrect name thrown")
36 | flag = true
37 | }
38 |
39 | chaiAssert.isTrue(flag, "Assert failed to throw on failed assert")
40 | })
41 |
42 | })
43 |
--------------------------------------------------------------------------------
/src/common/utils/Assert.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | export class AssertionError extends Error {
21 |
22 | constructor(message: string) {
23 | super(message)
24 | this.name = 'AssertionError'
25 | }
26 |
27 | }
28 |
29 | export function assert(condition: boolean, message: string) {
30 | if (!condition) {
31 | throw new AssertionError(message)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/common/utils/ByteUtils.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { hexStringToBytes, areArraysEqual } from './ByteUtils'
21 | import { assert } from 'chai'
22 | import { test, suite } from 'mocha';
23 |
24 | suite('Byte Utils', () => {
25 |
26 | test('Hex string to byte conversion', () => {
27 | const hexString = '300aaacd'
28 | const expectedBytes = new Uint8Array([48, 10, 170, 205])
29 |
30 | const destinationArray = new Uint8Array(4)
31 | hexStringToBytes(hexString, destinationArray, 0)
32 |
33 | assert.deepStrictEqual(expectedBytes, destinationArray)
34 | })
35 |
36 | test('Byte array equality', () => {
37 | const array: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6])
38 | const equalArray: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6])
39 | const moreNumbersArray: Uint8Array = new Uint8Array([1, 2, 3, 4, 5, 6, 7])
40 | const differentNumbersArray: Uint8Array = new Uint8Array([1, 2, 3, 77, 5, 6])
41 |
42 | assert.isTrue(areArraysEqual(array, equalArray), "Equal arrays indentified as not equal")
43 | assert.isFalse(areArraysEqual(array, moreNumbersArray), "Not equal arrays identified as equal")
44 | assert.isFalse(areArraysEqual(array, differentNumbersArray), "Not equal arrays identified as equal")
45 | })
46 |
47 | })
48 |
--------------------------------------------------------------------------------
/src/common/utils/ByteUtils.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from './Assert'
21 |
22 | export function hexStringToBytes(hexString: string, dest: Uint8Array, offset: number) {
23 | const lowercaseHexString = hexString.toLowerCase()
24 |
25 | assert(lowercaseHexString.length % 2 === 0, 'Hex string must have an even number of characters to convert to bytes')
26 |
27 | for (let i = 0; i < lowercaseHexString.length; i = i + 2) {
28 | const char1 = lowercaseHexString.charCodeAt(i)
29 | const char2 = lowercaseHexString.charCodeAt(i + 1)
30 |
31 | assert(isLowerCaseHexChar(char1) && isLowerCaseHexChar(char2), 'Hex strings must only contain hexadecimal characters.')
32 |
33 | dest[offset + i / 2] = parseInt(String.fromCharCode(char1, char2), 16)
34 | }
35 | }
36 |
37 | function isLowerCaseHexChar(char: number): boolean {
38 | return ((48 <= char) && (char <= 57)) || ((97 <= char) && (char <= 102))
39 | }
40 |
41 | export function areArraysEqual(array1: Uint8Array, array2: Uint8Array): boolean {
42 | if (array1.length !== array2.length) {
43 | return false
44 | }
45 |
46 | for (let i = 0; i < array1.length; i++) {
47 | if (array1[i] !== array2[i]) {
48 | return false
49 | }
50 | }
51 |
52 | return true
53 | }
54 |
--------------------------------------------------------------------------------
/src/content/ContentHub.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { Event } from '../common/events/Event'
21 |
22 | export class ContentHub {
23 |
24 | private readonly eventPort: browser.runtime.Port
25 |
26 | constructor() {
27 | this.eventPort = browser.runtime.connect({ name: "EventPort" })
28 | }
29 |
30 | submitEvent(event: Event): void {
31 | this.eventPort.postMessage(event)
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/src/content/ElementRegistry.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { getEventTime } from "../common/events/Event"
21 |
22 | export class ElementRegistry {
23 |
24 | private readonly elementReferences: Map = new Map()
25 |
26 | getElementReference(element: EventTarget): number {
27 | let reference = this.elementReferences.get(element)
28 | if (reference) {
29 | return reference
30 | }
31 |
32 | reference = getEventTime()
33 | this.elementReferences.set(element, reference)
34 | return reference
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/content/WindowLocationEventGenerator.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { WindowLocationEventGenerator } from './WindowLocationEventGenerator'
21 | import { WindowLocationEvent } from '../common/events/WindowLocationEvent'
22 | import { assert } from 'chai'
23 | import { test, suite } from 'mocha';
24 | import { JSDOM } from 'jsdom'
25 |
26 | import { Semaphore } from '../common/concurrent/Semaphore'
27 |
28 |
29 | suite('WindowLocationEventGeneration', () => {
30 |
31 | test('Event generation on url change', async () => {
32 | const fakeDom = new JSDOM('', {
33 | url: "https://weaklayer.com:8443/stuff?hello=true#SectionTitle"
34 | })
35 |
36 | const semaphore1 = new Semaphore()
37 | let semaphore1set = false
38 | const semaphore2 = new Semaphore()
39 |
40 | let event1: WindowLocationEvent | undefined = undefined
41 | let event2: WindowLocationEvent | undefined = undefined
42 |
43 | const generator = new WindowLocationEventGenerator(1, () => fakeDom.window.location, (e) => {
44 | if (!semaphore1set) {
45 | event1 = e
46 | semaphore1set = true
47 | semaphore1.setSignal()
48 | } else {
49 | event2 = e
50 | semaphore2.setSignal()
51 | }
52 | }, 1)
53 |
54 | await semaphore1.getSignal()
55 | assert.isDefined(event1, "First event not set properly")
56 | const windowEvent1: WindowLocationEvent = event1 as unknown as WindowLocationEvent
57 | assert.strictEqual(windowEvent1.port, 8443, "First event port incorrect")
58 |
59 | fakeDom.reconfigure({
60 | url: "https://weaklayer.com:9443/stuff?hello=true#SectionTitle"
61 | })
62 |
63 | await semaphore2.getSignal()
64 | assert.isDefined(event2, "Second event not set properly")
65 | const windowEvent2: WindowLocationEvent = event2 as unknown as WindowLocationEvent
66 | assert.strictEqual(windowEvent2.port, 9443, "Second event port incorrect")
67 |
68 | // This is needed or the test won't stop because of the chained timers
69 | generator.stop()
70 | })
71 |
72 | })
73 |
--------------------------------------------------------------------------------
/src/content/WindowLocationEventGenerator.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { createWindowLocationEvent, WindowLocationEvent } from '../common/events/WindowLocationEvent'
21 |
22 | export class WindowLocationEventGenerator {
23 |
24 | private readonly windowReference: number
25 |
26 | private readonly locationSupplier: () => Location
27 |
28 | private readonly eventConsumer: (e: WindowLocationEvent) => void
29 |
30 | private readonly pollingInterval: number
31 |
32 | private lastLocation: string = ''
33 | private lastLocationReference: number = 0
34 |
35 | private continue = true
36 |
37 | constructor(windowReference: number, locationSupplier: () => Location, eventConsumer: (e: WindowLocationEvent) => void, pollingInterval: number = 100) {
38 | this.windowReference = windowReference
39 | this.locationSupplier = locationSupplier
40 | this.eventConsumer = eventConsumer
41 | this.pollingInterval = pollingInterval
42 |
43 | this.onTimer()
44 | setTimeout(() => this.onTimer(), this.pollingInterval)
45 | }
46 |
47 | private onTimer() {
48 | this.updateLocation()
49 |
50 | if (this.continue) {
51 | setTimeout(() => this.onTimer(), this.pollingInterval)
52 | }
53 | }
54 |
55 | private updateLocation() {
56 | const currentLocation = this.locationSupplier().href
57 |
58 | if (currentLocation !== this.lastLocation) {
59 | this.lastLocation = currentLocation
60 | const event = createWindowLocationEvent(this.windowReference, () => this.locationSupplier())
61 | this.lastLocationReference = event.time
62 | this.eventConsumer(event)
63 | }
64 | }
65 |
66 | getCurrentWindowLocationReference(): number {
67 | this.updateLocation()
68 | return this.lastLocationReference
69 | }
70 |
71 | stop(): void {
72 | this.continue = false
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/content/content.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { ContentHub } from './ContentHub'
21 | import { WindowEvent, createWindowEvent } from '../common/events/WindowEvent'
22 | import { WindowLocationEventGenerator } from './WindowLocationEventGenerator'
23 | import { TextInputEventManager } from './text/TextInputEventManager'
24 | import { ElementRegistry } from './ElementRegistry'
25 |
26 | // We hold onto this event here as most events in this window will link to it
27 | const windowEvent: WindowEvent = createWindowEvent()
28 | const contentHub = new ContentHub()
29 |
30 | contentHub.submitEvent(windowEvent)
31 |
32 | const windowLocationEventGenerator = new WindowLocationEventGenerator(windowEvent.time, () => window.location, (e) => contentHub.submitEvent(e))
33 |
34 | const elementRegistry = new ElementRegistry()
35 |
36 | const textInputEventManager = new TextInputEventManager(
37 | windowEvent.time,
38 | () => windowLocationEventGenerator.getCurrentWindowLocationReference(),
39 | (event) => contentHub.submitEvent(event),
40 | elementRegistry
41 | )
42 |
--------------------------------------------------------------------------------
/src/content/text/HTMLInputEventManager.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { ElementRegistry } from "../ElementRegistry"
21 |
22 | // Filter the input elements that don't take text
23 | const nonTextInputTypesArray = ['button', 'checkbox', 'color', 'file', 'image', 'radio', 'range', 'reset', 'submit']
24 | const nonTextInputTypes: Set = new Set()
25 | nonTextInputTypesArray.forEach(nonTextInputType => {
26 | nonTextInputTypes.add(nonTextInputType.toLowerCase())
27 | })
28 |
29 | export class HTMLInputEventManager {
30 |
31 | private readonly textConsumerFunc: (text: string, textType: string, targetReference: number) => void
32 |
33 | private readonly elementRegistry: ElementRegistry
34 |
35 | constructor(textConsumerFunc: (text: string, textType: string, targetReference: number) => void, elementRegistry: ElementRegistry) {
36 | this.textConsumerFunc = textConsumerFunc
37 | this.elementRegistry = elementRegistry
38 | }
39 |
40 | handleInputEvent(inputEvent: InputEvent) {
41 | if (!inputEvent.isTrusted) {
42 | return
43 | }
44 |
45 | const targetElement = inputEvent.target
46 | if (targetElement) {
47 | if ((targetElement instanceof HTMLInputElement && !nonTextInputTypes.has(targetElement.type.toLowerCase())) ||
48 | targetElement instanceof HTMLTextAreaElement) {
49 |
50 | const textInputElement = targetElement as HTMLInputElement | HTMLTextAreaElement
51 | this.textConsumerFunc(textInputElement.value, textInputElement.type, this.elementRegistry.getElementReference(textInputElement))
52 | }
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/src/content/text/TextChunkEventManager.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { getEventTime } from "../../common/events/Event"
21 |
22 | export class TextChunkEventManager {
23 |
24 | // Events that move around text chunks
25 | // Should be handled in their own right
26 | // Drags are especially noisy.
27 | // They get squelched in here.
28 |
29 | private readonly seenStrings: Set = new Set()
30 |
31 | private readonly textConsumerFunc: (text: string, textType: string, elementReference: number) => void
32 |
33 | constructor(textConsumerFunc: (text: string, textType: string, elementReference: number) => void) {
34 | this.textConsumerFunc = textConsumerFunc
35 | }
36 |
37 | handleDragEvent(event: DragEvent) {
38 | if (!event.isTrusted) {
39 | return
40 | }
41 |
42 | const dragText = event.dataTransfer?.getData("text")
43 | if (dragText) {
44 | if (event.type === 'drop') {
45 | this.handle(dragText, TextChunkEventManager.getTextType(event.target))
46 | } else {
47 | // We put unknown for the text type of drags (not drops)
48 | // The fact that text was dragged over a target doesn't indicate the type of text
49 | // Pasting / dropping into an element does
50 | this.handle(dragText, 'unknown')
51 | }
52 | }
53 | }
54 |
55 | handlePasteEvent(event: ClipboardEvent) {
56 | if (!event.isTrusted) {
57 | return
58 | }
59 |
60 | const clipboardText = event.clipboardData?.getData("text")
61 | if (clipboardText) {
62 | this.handle(clipboardText, TextChunkEventManager.getTextType(event.target))
63 | }
64 | }
65 |
66 | private handle(text: string, textType: string) {
67 | if (!this.seenStrings.has(text)) {
68 | this.seenStrings.add(text)
69 |
70 |
71 | // Also use new element reference because we don't want this capture to be correlated with anything else
72 | this.textConsumerFunc(text, textType, getEventTime())
73 | }
74 | }
75 |
76 | private static getTextType(targetElement: EventTarget | null): string {
77 |
78 | let textType = 'unknown'
79 |
80 | if (targetElement && (targetElement instanceof HTMLInputElement || targetElement instanceof HTMLTextAreaElement)) {
81 | textType = targetElement.type
82 | }
83 |
84 | return textType
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/content/text/TextInputEventManager.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { HTMLInputEventManager } from "./HTMLInputEventManager"
21 | import { TextCaptureEvent, createTextCaptureEvent } from "../../common/events/internal/TextCaptureEvent"
22 | import { ElementRegistry } from "../ElementRegistry"
23 | import { TextChunkEventManager } from "./TextChunkEventManager"
24 | import { VirtualElementManager } from "./composition/VirtualElementManager"
25 |
26 | export class TextInputEventManager {
27 |
28 | private readonly htmlInputEventManager: HTMLInputEventManager
29 |
30 | private readonly virtualElementManager: VirtualElementManager
31 |
32 | private readonly textChunkEventManager: TextChunkEventManager
33 |
34 | constructor(windowReference: number, windowLocationReferenceProducer: () => number, textCaptureEventConsumer: (e: TextCaptureEvent) => void, elementRegistry: ElementRegistry) {
35 |
36 | const consumeCapture = (text: string, type: string, elementReference: number) => {
37 | const e = createTextCaptureEvent(text, type, windowReference, windowLocationReferenceProducer(), elementReference)
38 | textCaptureEventConsumer(e)
39 | }
40 |
41 | this.htmlInputEventManager = new HTMLInputEventManager((text, type, reference) => consumeCapture(text, type, reference), elementRegistry)
42 | this.textChunkEventManager = new TextChunkEventManager((text, type, reference) => consumeCapture(text, type, reference))
43 | this.virtualElementManager = new VirtualElementManager(elementRegistry, (text, type, reference) => consumeCapture(text, type, reference))
44 |
45 | // Set up listeners for all events that could indicate text being inputted into the page
46 |
47 | // Input events. These indicate when the text content of HTML elements is worth a snapshot.
48 | window.addEventListener("input", (e) => {
49 | if (e instanceof InputEvent) {
50 | this.htmlInputEventManager.handleInputEvent(e)
51 | }
52 | }, { capture: true, once: false, passive: true })
53 |
54 | // Keyboard events. Should only need keydown.
55 | window.addEventListener("keydown", (e) => {
56 | if (e instanceof KeyboardEvent) {
57 | this.virtualElementManager.keyboardEvent(e)
58 | }
59 | }, { capture: true, once: false, passive: true })
60 |
61 | // clipboard events
62 | window.addEventListener("paste", (e) => {
63 | if (e instanceof ClipboardEvent) {
64 | this.virtualElementManager.clipboardEvent(e)
65 | this.textChunkEventManager.handlePasteEvent(e)
66 | }
67 | }, { capture: true, once: false, passive: true })
68 |
69 | // drag events
70 | window.addEventListener("drag", (e) => this.textChunkEventManager.handleDragEvent(e), { capture: true, once: false, passive: true })
71 | window.addEventListener("dragend", (e) => this.textChunkEventManager.handleDragEvent(e), { capture: true, once: false, passive: true })
72 | window.addEventListener("dragenter", (e) => this.textChunkEventManager.handleDragEvent(e), { capture: true, once: false, passive: true })
73 | window.addEventListener("dragstart", (e) => this.textChunkEventManager.handleDragEvent(e), { capture: true, once: false, passive: true })
74 | window.addEventListener("dragleave", (e) => this.textChunkEventManager.handleDragEvent(e), { capture: true, once: false, passive: true })
75 | window.addEventListener("dragover", (e) => this.textChunkEventManager.handleDragEvent(e), { capture: true, once: false, passive: true })
76 |
77 | // drop actually shows intention that the text is part of a larger composition
78 | // therefore handle in a virtual element as well
79 | window.addEventListener("drop", (e) => {
80 | this.textChunkEventManager.handleDragEvent(e)
81 | this.virtualElementManager.dragEvent(e)
82 | }, { capture: true, once: false, passive: true })
83 |
84 |
85 | }
86 |
87 | }
88 |
--------------------------------------------------------------------------------
/src/content/text/composition/VirtualElementFocus.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { getEventTime } from "../../../common/events/Event"
21 | import { ElementRegistry } from "../../ElementRegistry"
22 |
23 | export class VirtualElementFocus {
24 |
25 | private readonly focusAttentionIntervalMicros: number
26 |
27 | private readonly elementRegistry: ElementRegistry
28 |
29 | private lastFocusEventTime: number = 0
30 | private lastElementReference: number = 0
31 |
32 | constructor(elementRegistry: ElementRegistry, focusAttentionIntervalMicros: number = 5000000) {
33 | this.focusAttentionIntervalMicros = focusAttentionIntervalMicros
34 | this.elementRegistry = elementRegistry
35 | }
36 |
37 | hasFocusChanged(targetElement: EventTarget | null): boolean {
38 | let hasFocusChangedAnswer = false
39 |
40 | const elementReference = this.getElementReference(targetElement)
41 | const now = getEventTime()
42 |
43 | const diff = now - this.lastFocusEventTime
44 |
45 | if (diff > this.focusAttentionIntervalMicros || elementReference !== this.lastElementReference) {
46 | hasFocusChangedAnswer = true
47 | }
48 | this.lastFocusEventTime = now
49 | this.lastElementReference = elementReference
50 |
51 | return hasFocusChangedAnswer
52 | }
53 |
54 | private getElementReference(targetElement: EventTarget | null): number {
55 | let elementReference = 0
56 | if (targetElement) {
57 | elementReference = this.elementRegistry.getElementReference(targetElement)
58 | }
59 | return elementReference
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/src/content/text/composition/VirtualElementManager.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { VirtualTextAreaElement } from "./VirtualTextAreaElement"
21 | import { getEventTime } from "../../../common/events/Event"
22 | import { ElementRegistry } from "../../ElementRegistry"
23 | import { VirtualElementFocus } from "./VirtualElementFocus"
24 |
25 | export class VirtualElementManager {
26 | // This class contains the logic for deciding when to create new virtual elements
27 | // and deciding which virtual elements to apply composition events to.
28 | // Currently we apply every event to all virtual elements
29 |
30 | private readonly virtualElements: Array = new Array()
31 |
32 | private readonly virtualElementReferences: Map = new Map()
33 |
34 | private readonly virtualElementFocus: VirtualElementFocus
35 |
36 | private readonly textConsumerFunc: (text: string, textType: string, targetReference: number) => void
37 |
38 | constructor(elementRegistry: ElementRegistry, textConsumerFunc: (text: string, textType: string, targetReference: number) => void) {
39 | this.virtualElementFocus = new VirtualElementFocus(elementRegistry)
40 | this.textConsumerFunc = textConsumerFunc
41 | }
42 |
43 | keyboardEvent(event: KeyboardEvent) {
44 | if (event.isTrusted) {
45 | this.makeNewElement(event.target)
46 |
47 | for (let element of this.virtualElements) {
48 | element.keyboard(event)
49 | this.textConsumerFunc(element.value(), 'composite', this.getVirtualElementReference(element))
50 | }
51 | }
52 | }
53 |
54 | clipboardEvent(event: ClipboardEvent) {
55 | if (event.isTrusted) {
56 | this.makeNewElement(event.target)
57 |
58 | for (let element of this.virtualElements) {
59 | element.clipboard(event)
60 | this.textConsumerFunc(element.value(), 'composite', this.getVirtualElementReference(element))
61 | }
62 | }
63 | }
64 |
65 | dragEvent(event: DragEvent) {
66 | if (event.isTrusted) {
67 | this.makeNewElement(event.target)
68 |
69 | for (let element of this.virtualElements) {
70 | element.drag(event)
71 | this.textConsumerFunc(element.value(), 'composite', this.getVirtualElementReference(element))
72 | }
73 | }
74 | }
75 |
76 | private makeNewElement(target: EventTarget | null) {
77 | if (this.virtualElementFocus.hasFocusChanged(target)) {
78 | const newElem = new VirtualTextAreaElement()
79 | this.virtualElements.push(newElem)
80 | this.virtualElementReferences.set(newElem, getEventTime())
81 | }
82 | }
83 |
84 | private getVirtualElementReference(virtualElement: VirtualTextAreaElement): number {
85 | let reference = this.virtualElementReferences.get(virtualElement)
86 | if (!reference) {
87 | reference = getEventTime()
88 | this.virtualElementReferences.set(virtualElement, reference)
89 | }
90 | return reference
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/src/content/text/composition/VirtualTextAreaElement.spec.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | import { assert } from 'chai'
21 | import { test, suite } from 'mocha'
22 | import { VirtualTextAreaElement } from './VirtualTextAreaElement'
23 |
24 | suite('VirtualTExtAreaElement', () => {
25 |
26 | test('Constructs string with no edits', () => {
27 | const element = new VirtualTextAreaElement()
28 |
29 | const target: string = 'hello'
30 |
31 | element.keyboard({ type: 'keydown', key: 'h', ctrlKey: false } as KeyboardEvent)
32 | element.keyboard({ type: 'keydown', key: 'e', ctrlKey: false } as KeyboardEvent)
33 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
34 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
35 | element.keyboard({ type: 'keydown', key: 'o', ctrlKey: false } as KeyboardEvent)
36 |
37 | assert.strictEqual(element.value(), target)
38 | })
39 |
40 | test('Handles backspace', () => {
41 | const element = new VirtualTextAreaElement()
42 |
43 | const target: string = 'hllo'
44 |
45 | element.keyboard({ type: 'keydown', key: 'h', ctrlKey: false } as KeyboardEvent)
46 | element.keyboard({ type: 'keydown', key: 'e', ctrlKey: false } as KeyboardEvent)
47 | element.keyboard({ type: 'keydown', key: 'Backspace', ctrlKey: false } as KeyboardEvent)
48 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
49 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
50 | element.keyboard({ type: 'keydown', key: 'o', ctrlKey: false } as KeyboardEvent)
51 |
52 | assert.strictEqual(element.value(), target)
53 | })
54 |
55 |
56 | test('Handles cursor shifting', () => {
57 | const element = new VirtualTextAreaElement()
58 |
59 | const target: string = 'heoll!'
60 |
61 | element.keyboard({ type: 'keydown', key: 'h', ctrlKey: false } as KeyboardEvent)
62 | element.keyboard({ type: 'keydown', key: 'e', ctrlKey: false } as KeyboardEvent)
63 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
64 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
65 | element.keyboard({ type: 'keydown', key: 'ArrowLeft', ctrlKey: false } as KeyboardEvent)
66 | element.keyboard({ type: 'keydown', key: 'ArrowLeft', ctrlKey: false } as KeyboardEvent)
67 | element.keyboard({ type: 'keydown', key: 'o', ctrlKey: false } as KeyboardEvent)
68 | element.keyboard({ type: 'keydown', key: 'ArrowRight', ctrlKey: false } as KeyboardEvent)
69 | element.keyboard({ type: 'keydown', key: 'ArrowRight', ctrlKey: false } as KeyboardEvent)
70 | element.keyboard({ type: 'keydown', key: '!', ctrlKey: false } as KeyboardEvent)
71 |
72 | assert.strictEqual(element.value(), target)
73 | })
74 |
75 |
76 | test('Backspace near start and cursor moving', () => {
77 | const element = new VirtualTextAreaElement()
78 |
79 | const target: string = 'mo'
80 |
81 | element.keyboard({ type: 'keydown', key: 'h', ctrlKey: false } as KeyboardEvent)
82 | element.keyboard({ type: 'keydown', key: 'Backspace', ctrlKey: false } as KeyboardEvent)
83 | element.keyboard({ type: 'keydown', key: 'm', ctrlKey: false } as KeyboardEvent)
84 | element.keyboard({ type: 'keydown', key: 'l', ctrlKey: false } as KeyboardEvent)
85 | element.keyboard({ type: 'keydown', key: 'o', ctrlKey: false } as KeyboardEvent)
86 | element.keyboard({ type: 'keydown', key: 'ArrowLeft', ctrlKey: false } as KeyboardEvent)
87 | element.keyboard({ type: 'keydown', key: 'Backspace', ctrlKey: false } as KeyboardEvent)
88 |
89 | assert.strictEqual(element.value(), target)
90 | })
91 | })
92 |
--------------------------------------------------------------------------------
/src/content/text/composition/VirtualTextAreaElement.ts:
--------------------------------------------------------------------------------
1 | // SPDX-License-Identifier: AGPL-3.0-or-later
2 |
3 | // Copyright (C) 2020 Mitchell Wasson
4 |
5 | // This file is part of Weaklayer Sensor.
6 |
7 | // Weaklayer Sensor is free software: you can redistribute it and/or modify
8 | // it under the terms of the GNU Affero General Public License as published by
9 | // the Free Software Foundation, either version 3 of the License, or
10 | // (at your option) any later version.
11 |
12 | // This program is distributed in the hope that it will be useful,
13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | // GNU Affero General Public License for more details.
16 |
17 | // You should have received a copy of the GNU Affero General Public License
18 | // along with this program. If not, see .
19 |
20 | export class VirtualTextAreaElement {
21 |
22 | // Then captures of the content from this virtual element are sent to the background
23 | // and filtered / squelched in the same manner that html input element captures are
24 |
25 | private content: string = ''
26 |
27 | // cursor is the number of characters that precede the current position in the string (insert mode)
28 | private cursor: number = 0
29 |
30 | keyboard(event: KeyboardEvent) {
31 | if (event.type === 'keydown') { // only care for keydown events
32 | const keyValue: string = event.key
33 |
34 | const keyModified = event.ctrlKey || event.metaKey
35 |
36 | if (ignoreKeys.has(keyValue)) {
37 | return
38 | } else if (keyValue === 'ArrowLeft') {
39 | if (keyModified) {
40 | this.moveCursorStart()
41 | } else {
42 | this.moveCursor(-1)
43 | }
44 | } else if (keyValue === 'ArrowRight') {
45 | if (keyModified) {
46 | this.moveCursorEnd()
47 | } else {
48 | this.moveCursor(1)
49 | }
50 | } else if (keyValue === 'End') {
51 | this.moveCursorEnd()
52 | } else if (keyValue === 'Home') {
53 | this.moveCursorStart()
54 | } else if (keyValue === 'Backspace') {
55 | if (keyModified) {
56 | this.eraseAllBackward()
57 | } else {
58 | this.backspace()
59 | }
60 | } else if (keyValue === 'Delete' && !keyModified) {
61 | this.delete()
62 | } else if (keyValue === 'EraseEof') {
63 | this.eraseAllForward()
64 | } else if (!keyModified) {
65 | this.addText(event.key)
66 | }
67 | }
68 | }
69 |
70 | clipboard(event: ClipboardEvent) {
71 | if (event.type === 'paste') {
72 | const pasteText = event.clipboardData?.getData("text")
73 | if (pasteText) {
74 | this.addText(pasteText)
75 | }
76 | }
77 | }
78 |
79 | drag(event: DragEvent) {
80 | if (event.type === 'drop') {
81 | const dragText = event.dataTransfer?.getData("text")
82 | if (dragText) {
83 | this.addText(dragText)
84 | }
85 | }
86 | }
87 |
88 | value(): string {
89 | return this.content
90 | }
91 |
92 | private moveCursor(shift: number) {
93 | let newCursor = this.cursor + shift
94 |
95 | if (newCursor < 0) {
96 | newCursor = 0
97 | } else if (newCursor > this.content.length) {
98 | newCursor = this.content.length
99 | }
100 |
101 | this.cursor = newCursor
102 | }
103 |
104 | private moveCursorEnd() {
105 | this.cursor = this.content.length
106 | }
107 |
108 | private moveCursorStart() {
109 | this.cursor = 0
110 | }
111 |
112 | private backspace() {
113 | if (this.cursor === 0) {
114 | return // nothing to backspace since we are at the start
115 | } else {
116 | const start = this.content.slice(0, this.cursor - 1)
117 | const end = this.content.slice(this.cursor)
118 | this.content = start.concat(end)
119 | this.moveCursor(-1)
120 | }
121 | }
122 |
123 | private eraseAllBackward() {
124 | if (this.cursor === 0) {
125 | return // nothing to backspace since we are at the start
126 | } else {
127 | this.content = this.content.slice(this.cursor)
128 | this.moveCursorStart()
129 | }
130 | }
131 |
132 | private eraseAllForward() {
133 | if (this.cursor === this.content.length) {
134 | return // nothing to erase forward if we are at the end
135 | } else {
136 | this.content = this.content.slice(0, this.cursor)
137 | }
138 | // cursor stays the same since we are deleting forward
139 | }
140 |
141 | private delete() {
142 | if (this.cursor === this.content.length) {
143 | return // nothing to erase forward if we are at the end
144 | } else {
145 | const start = this.content.slice(0, this.cursor)
146 | const end = this.content.slice(this.cursor + 1)
147 | this.content = start.concat(end)
148 | }
149 | // cursor stays the same since we are deleting forward
150 | }
151 |
152 | private addText(text: string) {
153 | if (this.cursor === this.content.length) {
154 | this.content = this.content.concat(text)
155 | } else {
156 | const start = this.content.slice(0, this.cursor)
157 | const end = this.content.slice(this.cursor)
158 | this.content = start.concat(text, end)
159 | }
160 | this.moveCursor(text.length)
161 | }
162 | }
163 |
164 |
165 | const ignoreKeysArray = ['Dead', 'Unidentified', // special values
166 | 'Alt', 'AltGraph', 'CapsLock', 'Control', 'Fn', 'FnLock', 'Hyper', 'Meta', 'NumLock', 'ScrollLock', 'Shift', 'Super', 'Symbol', 'SymbolLock', // modifiers
167 | 'Tab', 'Enter', // Unapplicable whitespace - tab would generally change the focus element. enter would make stuff happen too
168 | 'ArrowDown', 'ArrowUp', 'PageDown', 'PageUp', // unapplicable navigators
169 | 'Clear', 'Copy', 'CrSel', 'Cut', 'ExSel', 'Paste', 'Redo', 'Undo', 'Insert', // unapplicable editors
170 | // TODO: incorporate the Insert key into the virtual text area element
171 | 'Accept', 'Again', 'Attn', 'Cancel', 'ContextMenu', 'Escape', 'Execute', 'Find', 'Finish', 'Help', 'Pause', 'Play', 'Props', 'Select', 'ZoomIn', 'ZoomOut', // unapplicable UI
172 | 'BrightnessDown', 'BrightnessUp', 'Eject', 'LogOff', 'Power', 'PowerOff', 'PrintScreen', 'Hibernate', 'Standby', 'WakeUp', // unapplicable device
173 | 'AllCandidates', 'Alphanumeric', 'CodeInput', 'Compose', 'Convert', 'FinalMode', 'GroupFirst', 'GroupLast', 'GroupNext', 'GroupPrevious', 'ModeChange', 'NextCandidate', 'NonConvert', 'PreviousCandidate', 'Process', 'SingleCandidate', // unapplicable IME and composition
174 | 'HangulMode', 'HanjaMode', 'JunjaMode', // unapplicable korean
175 | 'Eisu', 'Hankaku', 'Hiragana', 'HiraganaKatakana', 'KanaMode', 'KanjiMode', 'Katakana', 'Romaji', 'Zenkaku', 'ZenkakuHanaku', // unapplicable japanese
176 | 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'F13', 'F14', 'F15', 'F16', 'F17', 'F18', 'F19', 'F20', 'Soft1', 'Soft2', 'Soft3', 'Soft4', // unapplicable function
177 | 'AppSwitch', 'Call', 'Camera', 'CameraFocus', 'EndCall', 'GoBack', 'GoHome', 'HeadsetHook', 'LastNumberRedial', 'Notification', 'MannerMode', 'VoiceDial', // phone
178 | 'ChannelDown', 'ChannelUp', 'MediaFastForward', 'MediaPause', 'MediaPlay', 'MediaPlayPause', 'MediaRecord', 'MediaRewind', 'MediaStop', 'MediaTrackNext', 'MediaTrackPrevious', // media
179 | 'AudioBalanceLeft', 'AudioBalanceRight', 'AudioBassDown', 'AudioBassBoostDown', 'AudioBassBoostToggle', 'AudioBassBoostUp', 'AudioBassUp', 'AudioFaderFront', 'AudioFaderRear', 'AudioSurroundModeNext', 'AudioTrebleDown', 'AudioTrebleUp', 'AudioVolumeDown', 'AudioVolumeMute', 'AudioVolumeUp', 'MicrophoneToggle', 'MicrophoneVolumeDown', 'MicrophoneVolumeMute', 'MicrophoneVolumeUp', // audio
180 | 'TV', 'TV3DMode', 'TVAntennaCable', 'TVAudioDescription', 'TVAudioDescriptionMixDown', 'TVAudioDescriptionMixUp', 'TVContentsMenu', 'TVDataService', 'TVInput', 'TVInputComponent1', 'TVInputComponent2', 'TVInputComposite1', 'TVInputComposite2', 'TVInputHDMI1', 'TVInputHDMI2', 'TVInputHDMI3', 'TVInputHDMI4', 'TVInputVGA1', 'TVMediaContext', 'TVNetwork', 'TVNumberEntry', 'TVPower', 'TVRadioService', 'TVSatellite', 'TVSatelliteBS', 'TVSatelliteCS', 'TVSatelliteToggle', 'TVTerrestrialAnalog', 'TVTerrestrialDigital', 'TVTimer', // tv
181 | 'AVRInput', 'AVRPower', 'ColorF0Red', 'ColorF1Green', 'ColorF2Yellow', 'ColorF3Blue', 'ColorF4Grey', 'ColorF5Brown', 'ClosedCaptionToggle', 'Dimmer', 'DisplaySwap', 'DVR', 'Exit', 'FavoriteClear0', 'FavoriteClear1', 'FavoriteClear2', 'FavoriteClear3', 'FavoriteRecall0', 'FavoriteRecall1', 'FavoriteRecall2', 'FavoriteRecall3', 'FavoriteStore0', 'FavoriteStore1', 'FavoriteStore2', 'FavoriteStore3', 'Guide', 'GuideNextDay', 'GuidePreviousDay', 'Info', 'InstantReplay', 'Link', 'ListProgram', 'LiveContent', 'Lock', 'MediaApps', 'MediaAudioTrack', 'MediaLast', 'MediaSkipBackward', 'MediaSkipForward', 'MediaStepBackward', 'MediaStepForward', 'MediaTopMenu', 'NavigateIn', 'NavigateNext', 'NavigateOut', 'NavigatePrevious', 'NextFavoriteChannel', 'NextUserProfile', 'OnDemand', 'Pairing', 'PinPDown', 'PinPMove', 'PinPToggle', 'PinPUp', 'PlaySpeedDown', 'PlaySpeedReset', 'PlaySpeedUp', 'RandomToggle', 'RcLowBattery', 'RecordSpeedNext', 'RfBypass', 'ScanChannelsToggle', 'ScreenModeNext', 'Settings', 'SplitScreenToggle', 'STBInput', 'STBPower', 'Subtitle', 'Teletext', 'VideoModeNext', 'Wink', 'ZoomToggle', // media controller
182 | 'SpeechCorrectionList', 'SpeechInputToggle', // speech recognition
183 | 'Close', 'New', 'Open', 'Print', 'Save', 'SpellCheck', 'MailForward', 'MailReply', 'MailSend', // document
184 | 'LaunchCalculator', 'LaunchCalendar', 'LaunchContacts', 'LaunchMail', 'LaunchMediaPlayer', 'LaunchMusicPlayer', 'LaunchMyComputer', 'LaunchPhone', 'LaunchScreenSaver', 'LaunchSpreadsheet', 'LaunchWebBrowser', 'LaunchWebCam', 'LaunchWordProcessor', 'LaunchApplication1', 'LaunchApplication2', 'LaunchApplication3', 'LaunchApplication4', 'LaunchApplication5', 'LaunchApplication6', 'LaunchApplication7', 'LaunchApplication8', 'LaunchApplication9', 'LaunchApplication10', 'LaunchApplication11', 'LaunchApplication12', 'LaunchApplication13', 'LaunchApplication14', 'LaunchApplication15', 'LaunchApplication16', // application selector
185 | 'BrowserBack', 'BrowserFavorites', 'BrowserForward', 'BrowserHome', 'BrowserRefresh', 'BrowserSearch', 'BrowserStop', // browser control
186 | 'Key11', 'Key12', 'Separator' // num pad keys which are weird to handle. can look into these in the future
187 | ]
188 |
189 | const ignoreKeys: Set = new Set()
190 | ignoreKeysArray.forEach(ignoreKey => {
191 | ignoreKeys.add(ignoreKey)
192 | })
193 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "strict": true,
4 | "removeComments": true,
5 | "module": "commonjs",
6 | "target": "es6",
7 | "allowJs": false
8 | },
9 | "exclude": [
10 | "node_modules",
11 | "dist"
12 | ],
13 | "include": [
14 | "src"
15 | ]
16 | }
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const { CleanWebpackPlugin } = require('clean-webpack-plugin');
3 | const CopyWebpackPlugin = require('copy-webpack-plugin');
4 |
5 | module.exports = {
6 | mode: 'production',
7 | devtool: 'source-map',
8 | entry: {
9 | background: './src/background/background.ts',
10 | content: './src/content/content.ts'
11 | },
12 | module: {
13 | rules: [
14 | {
15 | test: /\.tsx?$/,
16 | use: [
17 | {
18 | loader: 'ts-loader',
19 | options: {
20 | configFile: 'tsconfig.json'
21 | }
22 | }
23 | ],
24 | exclude: /node_modules/
25 | },
26 | ],
27 | },
28 | plugins: [
29 | new CleanWebpackPlugin(),
30 | new CopyWebpackPlugin({
31 | patterns: [
32 | { from: 'LICENSE' },
33 | { from: 'node_modules/webextension-polyfill/dist/browser-polyfill.min.js' },
34 | { from: 'node_modules/webextension-polyfill/dist/browser-polyfill.min.js.map' },
35 | { from: 'icon16.png' },
36 | { from: 'icon48.png' },
37 | { from: 'icon128.png' }
38 | ]
39 | })
40 | ],
41 | resolve: {
42 | extensions: ['.tsx', '.ts', '.js']
43 | },
44 | output: {
45 | filename: '[name].js',
46 | path: path.resolve(__dirname, 'dist'),
47 | }
48 | };
49 |
--------------------------------------------------------------------------------