ovos-network-log 0.1.0a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ # Run the tests and build the wheel on every push; check that the wheel's
2
+ # start-up hook (ovos_network_log.pth) logs a request in a fresh environment;
3
+ # publish to PyPI when a version tag is pushed (vX.Y.Z, matching __version__).
4
+ # Publishing uses PyPI's trusted publishing (no token): the PyPI project must
5
+ # name this repo, this workflow and the "pypi" environment as its publisher.
6
+ name: Build and publish
7
+
8
+ on:
9
+ push:
10
+ branches: [main]
11
+ tags: ["v*"]
12
+ pull_request:
13
+ workflow_dispatch:
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ build:
20
+ runs-on: ubuntu-latest
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: "3.12"
26
+ - name: Tests
27
+ run: |
28
+ pip install -q -e ".[test]"
29
+ pytest -q tests
30
+ - name: Build
31
+ run: |
32
+ pip install -q build
33
+ python -m build
34
+ - name: The start-up hook works from the wheel
35
+ run: |
36
+ unzip -l dist/*.whl | grep -q "ovos_network_log.pth"
37
+ python -m venv /tmp/fresh
38
+ /tmp/fresh/bin/pip install -q dist/*.whl
39
+ OVOS_NETWORK_LOG=1 OVOS_NETWORK_LOG_BUS=0 OVOS_NETWORK_LOG_FILE=/tmp/net.jsonl \
40
+ /tmp/fresh/bin/python -c "
41
+ import urllib.request, urllib.error
42
+ try: urllib.request.urlopen('https://example.com/a/path?q=x', timeout=20).read()
43
+ except urllib.error.HTTPError: pass # a 404 is an answer too
44
+ "
45
+ cat /tmp/net.jsonl
46
+ grep -q '"host": "example.com"' /tmp/net.jsonl
47
+ ! grep -q "a/path" /tmp/net.jsonl
48
+ # not an OVOS program, not forced on: nothing logged
49
+ OVOS_NETWORK_LOG_BUS=0 OVOS_NETWORK_LOG_FILE=/tmp/none.jsonl \
50
+ /tmp/fresh/bin/python -c "import urllib.request; urllib.request.urlopen('https://example.com', timeout=20).read()"
51
+ test ! -e /tmp/none.jsonl
52
+ - uses: actions/upload-artifact@v4
53
+ with:
54
+ name: dist
55
+ path: dist
56
+
57
+ publish:
58
+ if: startsWith(github.ref, 'refs/tags/v')
59
+ needs: build
60
+ runs-on: ubuntu-latest
61
+ environment: pypi
62
+ permissions:
63
+ id-token: write
64
+ steps:
65
+ - uses: actions/download-artifact@v4
66
+ with:
67
+ name: dist
68
+ path: dist
69
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,4 @@
1
+ dist/
2
+ __pycache__/
3
+ *.egg-info/
4
+ .pytest_cache/
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,96 @@
1
+ Metadata-Version: 2.5
2
+ Name: ovos-network-log
3
+ Version: 0.1.0a1
4
+ Summary: A network log for OpenVoiceOS: every request OVOS and its skills make – when, where, who asked – for ovos-skill-guardian and you to read
5
+ Project-URL: Homepage, https://github.com/emkay-voice/ovos-network-log
6
+ Project-URL: Format, https://github.com/emkay-voice/emkay/blob/main/docs/network-log.md
7
+ Project-URL: Guardian, https://github.com/emkay-voice/ovos-skill-guardian
8
+ Author: Andreas Lorensen
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: emkay,log,network,openvoiceos,ovos,privacy
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Requires-Python: >=3.9
16
+ Provides-Extra: bus
17
+ Requires-Dist: ovos-bus-client; extra == 'bus'
18
+ Provides-Extra: test
19
+ Requires-Dist: pytest; extra == 'test'
20
+ Requires-Dist: requests; extra == 'test'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # ovos-network-log
24
+
25
+ A network log for [OpenVoiceOS](https://openvoiceos.org): every request OVOS
26
+ and its skills and plugins make – when, to which host, who asked – so what the
27
+ assistant sends out is something you can look at, not just a promise.
28
+
29
+ It writes the same log [Emkay](https://emkay.ai) keeps in the browser, in the
30
+ same format, so [ovos-skill-guardian](https://github.com/emkay-voice/ovos-skill-guardian)
31
+ can answer *"what did you send out today?"* and *"what just happened?"* on any
32
+ OpenVoiceOS device too.
33
+
34
+ ```
35
+ pip install ovos-network-log # in the same environment as OVOS
36
+ pip install ovos-network-log[bus] # … and send each request on the messagebus
37
+ ```
38
+
39
+ Restart OVOS' services, and the log starts.
40
+
41
+ ## What is logged
42
+
43
+ For each request: when, the host, the method, the status, the size of the
44
+ answer, which package asked (from the call stack: `ovos-skill-wikipedia`,
45
+ `ovos-tts-plugin-server` … or `ovos` for OVOS itself) and the service in words.
46
+ **Never the path, the query or the body**: some services carry what you said
47
+ in the address, and the log must not become the thing it is there to show.
48
+
49
+ ```json
50
+ {"t": 1794863530091, "host": "stt.openvoiceos.pt", "method": "POST", "status": 200, "bytes": 52, "who": "ovos-stt-plugin-server", "kind": "stt", "service": "speech recognition (OpenVoiceOS server)"}
51
+ ```
52
+
53
+ The format: [docs/network-log.md in Emkay](https://github.com/emkay-voice/emkay/blob/main/docs/network-log.md).
54
+ Requests to this machine itself (`localhost`, `127.0.0.1` – the messagebus,
55
+ for instance) are not "sent out" and are left out. A request that never got an
56
+ answer (offline, refused) is logged with status `0`.
57
+
58
+ ## How
59
+
60
+ The package puts a small `ovos_network_log.pth` file next to the installed
61
+ packages. Python reads `.pth` files when it starts – it is how editable
62
+ installs and coverage hook in – and this one imports
63
+ `ovos_network_log._startup`, which switches the log on **only in OVOS' own
64
+ programs** (`ovos-core`, `ovos-audio`, `ovos-dinkum-listener`, `ovos-phal`,
65
+ `ovos-gui-service`, `hivemind-…` – anything named `ovos-…`, `mycroft-…`,
66
+ `hivemind-…` or `neon-…`). `pip` or your own scripts in the same environment
67
+ are left alone.
68
+
69
+ It wraps Python's `http.client`, which `urllib`, `urllib3` and `requests` –
70
+ what nearly all of OpenVoiceOS uses – go through. Requests made with `httpx`
71
+ or `aiohttp` are not seen (yet).
72
+
73
+ ## Where it goes
74
+
75
+ - **The file** `~/.local/state/emkay/network.jsonl`, one JSON object per line
76
+ (`OVOS_NETWORK_LOG_FILE` changes it). Entries older than seven days are
77
+ dropped when a service starts.
78
+ - **The messagebus**, as `ovos.network.request` with the entry as its data,
79
+ with the `bus` extra (`ovos-bus-client`). ovos-skill-guardian listens for it.
80
+ That matters with **Docker** ([ovos-docker](https://github.com/OpenVoiceOS/ovos-docker)),
81
+ where each OVOS service is a container with its own file system: install the
82
+ package in each image you want logged (the skills container makes most of
83
+ the requests), and the bus brings the entries to Guardian wherever it runs.
84
+ `OVOS_NETWORK_LOG_BUS=0` turns this off.
85
+
86
+ ## Settings (environment variables)
87
+
88
+ | | |
89
+ |---|---|
90
+ | `OVOS_NETWORK_LOG` | `1`: log in this process whatever it is; `0`: never |
91
+ | `OVOS_NETWORK_LOG_FILE` | where the log file is |
92
+ | `OVOS_NETWORK_LOG_BUS` | `0`: don't send entries on the messagebus |
93
+
94
+ ## License
95
+
96
+ Apache-2.0
@@ -0,0 +1,74 @@
1
+ # ovos-network-log
2
+
3
+ A network log for [OpenVoiceOS](https://openvoiceos.org): every request OVOS
4
+ and its skills and plugins make – when, to which host, who asked – so what the
5
+ assistant sends out is something you can look at, not just a promise.
6
+
7
+ It writes the same log [Emkay](https://emkay.ai) keeps in the browser, in the
8
+ same format, so [ovos-skill-guardian](https://github.com/emkay-voice/ovos-skill-guardian)
9
+ can answer *"what did you send out today?"* and *"what just happened?"* on any
10
+ OpenVoiceOS device too.
11
+
12
+ ```
13
+ pip install ovos-network-log # in the same environment as OVOS
14
+ pip install ovos-network-log[bus] # … and send each request on the messagebus
15
+ ```
16
+
17
+ Restart OVOS' services, and the log starts.
18
+
19
+ ## What is logged
20
+
21
+ For each request: when, the host, the method, the status, the size of the
22
+ answer, which package asked (from the call stack: `ovos-skill-wikipedia`,
23
+ `ovos-tts-plugin-server` … or `ovos` for OVOS itself) and the service in words.
24
+ **Never the path, the query or the body**: some services carry what you said
25
+ in the address, and the log must not become the thing it is there to show.
26
+
27
+ ```json
28
+ {"t": 1794863530091, "host": "stt.openvoiceos.pt", "method": "POST", "status": 200, "bytes": 52, "who": "ovos-stt-plugin-server", "kind": "stt", "service": "speech recognition (OpenVoiceOS server)"}
29
+ ```
30
+
31
+ The format: [docs/network-log.md in Emkay](https://github.com/emkay-voice/emkay/blob/main/docs/network-log.md).
32
+ Requests to this machine itself (`localhost`, `127.0.0.1` – the messagebus,
33
+ for instance) are not "sent out" and are left out. A request that never got an
34
+ answer (offline, refused) is logged with status `0`.
35
+
36
+ ## How
37
+
38
+ The package puts a small `ovos_network_log.pth` file next to the installed
39
+ packages. Python reads `.pth` files when it starts – it is how editable
40
+ installs and coverage hook in – and this one imports
41
+ `ovos_network_log._startup`, which switches the log on **only in OVOS' own
42
+ programs** (`ovos-core`, `ovos-audio`, `ovos-dinkum-listener`, `ovos-phal`,
43
+ `ovos-gui-service`, `hivemind-…` – anything named `ovos-…`, `mycroft-…`,
44
+ `hivemind-…` or `neon-…`). `pip` or your own scripts in the same environment
45
+ are left alone.
46
+
47
+ It wraps Python's `http.client`, which `urllib`, `urllib3` and `requests` –
48
+ what nearly all of OpenVoiceOS uses – go through. Requests made with `httpx`
49
+ or `aiohttp` are not seen (yet).
50
+
51
+ ## Where it goes
52
+
53
+ - **The file** `~/.local/state/emkay/network.jsonl`, one JSON object per line
54
+ (`OVOS_NETWORK_LOG_FILE` changes it). Entries older than seven days are
55
+ dropped when a service starts.
56
+ - **The messagebus**, as `ovos.network.request` with the entry as its data,
57
+ with the `bus` extra (`ovos-bus-client`). ovos-skill-guardian listens for it.
58
+ That matters with **Docker** ([ovos-docker](https://github.com/OpenVoiceOS/ovos-docker)),
59
+ where each OVOS service is a container with its own file system: install the
60
+ package in each image you want logged (the skills container makes most of
61
+ the requests), and the bus brings the entries to Guardian wherever it runs.
62
+ `OVOS_NETWORK_LOG_BUS=0` turns this off.
63
+
64
+ ## Settings (environment variables)
65
+
66
+ | | |
67
+ |---|---|
68
+ | `OVOS_NETWORK_LOG` | `1`: log in this process whatever it is; `0`: never |
69
+ | `OVOS_NETWORK_LOG_FILE` | where the log file is |
70
+ | `OVOS_NETWORK_LOG_BUS` | `0`: don't send entries on the messagebus |
71
+
72
+ ## License
73
+
74
+ Apache-2.0
@@ -0,0 +1,254 @@
1
+ """A network log for OpenVoiceOS: what the assistant sent out, and who asked.
2
+
3
+ Installed next to OVOS (pip install ovos-network-log), it logs every HTTP
4
+ request an OVOS service makes – ovos-core and its skills, the listener, the
5
+ audio service, PHAL – in the format Emkay keeps and
6
+ ovos-skill-guardian reads ("what did you send out today?", "what just
7
+ happened?"):
8
+
9
+ {"t": 1794863530091, "host": "stt.openvoiceos.pt", "method": "POST",
10
+ "status": 200, "bytes": 52, "who": "ovos-stt-plugin-server",
11
+ "kind": "stt", "service": "speech recognition (OpenVoiceOS server)"}
12
+
13
+ when, the host, the method, the status, the size of the answer, which
14
+ package asked (from the call stack) and the service in words. Never the
15
+ path, the query or the body: some services carry what you said in the
16
+ address, and the log must not become the thing it is there to show.
17
+ https://github.com/emkay-voice/emkay/blob/main/docs/network-log.md
18
+
19
+ How: a .pth file (ovos_network_log.pth) that Python reads at start-up in
20
+ every process of this environment imports ovos_network_log._startup, which
21
+ switches the log on in OVOS' own processes only (ovos-core, ovos-audio,
22
+ ovos-dinkum-listener, ovos-phal …; OVOS_NETWORK_LOG=1 forces it on,
23
+ =0 off). It wraps http.client – under urllib, urllib3 and requests, which
24
+ nearly all of OVOS uses. Requests made with httpx or aiohttp are not seen.
25
+
26
+ Where: each entry is appended to ~/.local/state/emkay/network.jsonl
27
+ (OVOS_NETWORK_LOG_FILE changes it) and, unless OVOS_NETWORK_LOG_BUS=0, sent
28
+ on the messagebus as ovos.network.request – so a skill in another process or
29
+ container hears it too (in Docker, where each OVOS service has its own file
30
+ system, install the package in each image; the bus is what they share).
31
+ Entries older than seven days are dropped when a service starts.
32
+ """
33
+ import json
34
+ import os
35
+ import re
36
+ import sys
37
+ import threading
38
+ import time
39
+ from functools import lru_cache
40
+
41
+ __version__ = "0.1.0a1"
42
+
43
+ DEFAULT_FILE = "~/.local/state/emkay/network.jsonl"
44
+ BUS_MESSAGE = "ovos.network.request"
45
+ KEEP_DAYS = 7
46
+
47
+ #: OVOS' own processes, by the program's name: the log is on in these
48
+ OVOS_PROGRAMS = re.compile(r"^(ovos|mycroft|hivemind|neon)[-_]")
49
+
50
+ #: known services, by host: (pattern, kind, words) – the same as Emkay's
51
+ #: web/netlog.js; `kind` is a fixed id that ovos-skill-guardian translates
52
+ SERVICES = [
53
+ (r"(^|\.)stt\.openvoiceos\.pt$|(^|\.)stt\.smartgic\.io$", "stt", "speech recognition (OpenVoiceOS server)"),
54
+ (r"(^|\.)tts\.openvoiceos\.pt$|(^|\.)tts\.smartgic\.io$", "tts", "voice (OpenVoiceOS server)"),
55
+ (r"nllb|translat", "translate", "translation (OpenVoiceOS server)"),
56
+ (r"(^|\.)wikipedia\.org$|(^|\.)wikimedia\.org$|(^|\.)wikidata\.org$", "wikipedia", "Wikipedia"),
57
+ (r"(^|\.)huggingface\.co$|(^|\.)hf\.co$|xethub", "models", "model downloads (Hugging Face)"),
58
+ (r"(^|\.)store\.emkay\.ai$", "store", "Emkay skill store"),
59
+ (r"(^|\.)pypi\.org$|(^|\.)pythonhosted\.org$", "packages", "package installs (PyPI)"),
60
+ (r"(^|\.)githubusercontent\.com$|(^|\.)github\.com$", "github", "GitHub"),
61
+ (r"(^|\.)open-meteo\.com$|weather", "weather", "weather"),
62
+ (r"radio-browser|somafm|(^|\.)dr\.dk$|stream", "radio", "radio and news"),
63
+ ]
64
+ _SERVICES = [(re.compile(p), k, w) for p, k, w in SERVICES]
65
+
66
+ #: hosts that are this machine: not "sent out"
67
+ LOCAL = re.compile(r"^(localhost|127\.|\[?::1\]?|0\.0\.0\.0)")
68
+
69
+ #: packages on the way to the network that are not the one asking
70
+ MACHINERY = {
71
+ "requests", "urllib3", "httpx", "httpcore", "certifi", "charset_normalizer", "idna",
72
+ "ovos_network_log", "ovos_utils", "ovos_bus_client", "ovos_workshop", "ovos_plugin_manager",
73
+ "ovos_config", "ovos_core", "concurrent", "contextlib", "functools", "threading", "importlib",
74
+ }
75
+
76
+
77
+ def service(host: str):
78
+ """(kind, words) for a host: a known service, or the host itself."""
79
+ name = host.split(":")[0].lower()
80
+ for pattern, kind, words in _SERVICES:
81
+ if pattern.search(name):
82
+ return kind, words
83
+ return "other", host
84
+
85
+
86
+ @lru_cache(maxsize=None)
87
+ def _distribution(top: str) -> str:
88
+ name = top
89
+ try:
90
+ from importlib.metadata import packages_distributions
91
+ name = (packages_distributions().get(top) or [top])[0]
92
+ except Exception:
93
+ pass
94
+ return re.sub(r"[-_.]+", "-", name).lower()
95
+
96
+
97
+ def caller(depth: int = 2) -> str:
98
+ """The package making the current call (its pip name), or "ovos" for OVOS itself."""
99
+ stdlib = getattr(sys, "stdlib_module_names", ())
100
+ frame = sys._getframe(depth)
101
+ while frame:
102
+ top = (frame.f_globals.get("__name__") or "").split(".")[0]
103
+ if top and top not in MACHINERY and top not in stdlib and top != "__main__":
104
+ return _distribution(top)
105
+ frame = frame.f_back
106
+ return "ovos"
107
+
108
+
109
+ def log_file() -> str:
110
+ return os.path.expanduser(os.environ.get("OVOS_NETWORK_LOG_FILE") or DEFAULT_FILE)
111
+
112
+
113
+ _lock = threading.Lock()
114
+
115
+
116
+ def write(entry: dict, path: str = None):
117
+ """Append one entry to the log file (one short line: an append is atomic)."""
118
+ path = path or log_file()
119
+ line = json.dumps(entry, ensure_ascii=False) + "\n"
120
+ with _lock:
121
+ os.makedirs(os.path.dirname(path), exist_ok=True)
122
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
123
+ try:
124
+ os.write(fd, line.encode("utf-8"))
125
+ finally:
126
+ os.close(fd)
127
+
128
+
129
+ def prune(path: str = None, days: int = KEEP_DAYS):
130
+ """Drop the entries older than `days` (when a service starts)."""
131
+ path = path or log_file()
132
+ try:
133
+ with open(path, encoding="utf-8") as f:
134
+ lines = f.readlines()
135
+ except OSError:
136
+ return
137
+ since = (time.time() - days * 86400) * 1000
138
+ keep = []
139
+ for line in lines:
140
+ try:
141
+ if json.loads(line).get("t", 0) >= since:
142
+ keep.append(line)
143
+ except ValueError:
144
+ pass
145
+ if len(keep) != len(lines):
146
+ with _lock:
147
+ tmp = path + ".tmp"
148
+ with open(tmp, "w", encoding="utf-8") as f:
149
+ f.writelines(keep)
150
+ os.replace(tmp, path)
151
+
152
+
153
+ # -- the bus -------------------------------------------------------------------
154
+
155
+ _queue = []
156
+ _wake = threading.Event()
157
+ _bus_thread = None
158
+
159
+
160
+ def _bus_sender():
161
+ """Send queued entries on the messagebus from a thread of its own, so a
162
+ request never waits for the bus. The bus client talks over a websocket,
163
+ not http.client, so it is not logged itself."""
164
+ client = None
165
+ while True:
166
+ _wake.wait(5)
167
+ _wake.clear()
168
+ if not _queue:
169
+ continue
170
+ try:
171
+ if client is None:
172
+ from ovos_bus_client import MessageBusClient
173
+ client = MessageBusClient()
174
+ client.run_in_thread()
175
+ client.connected_event.wait(5)
176
+ from ovos_bus_client.message import Message
177
+ while _queue:
178
+ client.emit(Message(BUS_MESSAGE, _queue.pop(0)))
179
+ except Exception:
180
+ time.sleep(10) # no bus yet (still starting): later
181
+
182
+
183
+ def send_on_bus(entry: dict):
184
+ global _bus_thread
185
+ _queue.append(entry)
186
+ del _queue[:-500] # never more than this waiting
187
+ if _bus_thread is None:
188
+ _bus_thread = threading.Thread(target=_bus_sender, name="ovos-network-log", daemon=True)
189
+ _bus_thread.start()
190
+ _wake.set()
191
+
192
+
193
+ # -- the hook ------------------------------------------------------------------
194
+
195
+ def record(host: str, method: str, status: int, size, who: str):
196
+ """Log one request; None for this machine's own addresses."""
197
+ if not host or LOCAL.match(host):
198
+ return None
199
+ kind, words = service(host)
200
+ entry = {"t": int(time.time() * 1000), "host": host, "method": method or "GET", "status": status,
201
+ "bytes": size, "who": who, "kind": kind, "service": words}
202
+ try:
203
+ write(entry)
204
+ except OSError:
205
+ pass
206
+ if os.environ.get("OVOS_NETWORK_LOG_BUS", "1") != "0":
207
+ send_on_bus(entry)
208
+ return entry
209
+
210
+
211
+ def install():
212
+ """Wrap http.client so every request this process makes is logged. Once."""
213
+ import http.client as hc
214
+ if getattr(hc.HTTPConnection.getresponse, "_ovos_network_log", False):
215
+ return
216
+ plain_request, plain_getresponse = hc.HTTPConnection.request, hc.HTTPConnection.getresponse
217
+
218
+ def _host(conn):
219
+ default = 443 if isinstance(conn, getattr(hc, "HTTPSConnection", ())) else 80
220
+ host = getattr(conn, "_tunnel_host", None) or conn.host
221
+ port = getattr(conn, "_tunnel_port", None) or conn.port
222
+ return host if not port or port == default else f"{host}:{port}"
223
+
224
+ def request(self, method, url, *args, **kwargs):
225
+ self._ovos_net = (method, caller(2))
226
+ try:
227
+ return plain_request(self, method, url, *args, **kwargs)
228
+ except Exception: # refused, offline, no name: it never got an answer
229
+ record(_host(self), method, 0, None, self._ovos_net[1])
230
+ raise
231
+
232
+ def getresponse(self, *args, **kwargs):
233
+ method, who = getattr(self, "_ovos_net", ("GET", "ovos"))
234
+ try:
235
+ resp = plain_getresponse(self, *args, **kwargs)
236
+ except Exception:
237
+ record(_host(self), method, 0, None, who)
238
+ raise
239
+ size = resp.getheader("Content-Length")
240
+ record(_host(self), method, resp.status, int(size) if size and size.isdigit() else None, who)
241
+ return resp
242
+
243
+ getresponse._ovos_network_log = True
244
+ hc.HTTPConnection.request = request
245
+ hc.HTTPConnection.getresponse = getresponse
246
+
247
+
248
+ def wanted() -> bool:
249
+ """Is this one of OVOS' own processes (or forced on/off)?"""
250
+ forced = os.environ.get("OVOS_NETWORK_LOG")
251
+ if forced in ("0", "1"):
252
+ return forced == "1"
253
+ program = os.path.basename(sys.argv[0] if sys.argv and sys.argv[0] else "")
254
+ return bool(OVOS_PROGRAMS.match(program))
@@ -0,0 +1,10 @@
1
+ """Run at Python's start-up by ovos_network_log.pth, in every process of this
2
+ environment: switches the network log on in OVOS' own processes. It must
3
+ never break a start-up, so anything that goes wrong is left alone."""
4
+ try:
5
+ from ovos_network_log import install, prune, wanted
6
+ if wanted():
7
+ install()
8
+ prune()
9
+ except Exception: # pragma: no cover
10
+ pass
@@ -0,0 +1 @@
1
+ import ovos_network_log._startup
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "ovos-network-log"
7
+ dynamic = ["version"]
8
+ description = "A network log for OpenVoiceOS: every request OVOS and its skills make – when, where, who asked – for ovos-skill-guardian and you to read"
9
+ readme = "README.md"
10
+ license = {text = "Apache-2.0"}
11
+ authors = [{name = "Andreas Lorensen"}]
12
+ requires-python = ">=3.9"
13
+ keywords = ["ovos", "openvoiceos", "privacy", "network", "log", "emkay"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "License :: OSI Approved :: Apache Software License",
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+ dependencies = []
20
+
21
+ [project.optional-dependencies]
22
+ bus = ["ovos-bus-client"]
23
+ test = ["pytest", "requests"]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/emkay-voice/ovos-network-log"
27
+ Format = "https://github.com/emkay-voice/emkay/blob/main/docs/network-log.md"
28
+ Guardian = "https://github.com/emkay-voice/ovos-skill-guardian"
29
+
30
+ [tool.hatch.version]
31
+ path = "ovos_network_log/__init__.py"
32
+
33
+ [tool.hatch.build.targets.wheel]
34
+ packages = ["ovos_network_log"]
35
+
36
+ # the start-up hook goes next to the packages, where Python reads .pth files
37
+ [tool.hatch.build.targets.wheel.force-include]
38
+ "ovos_network_log.pth" = "ovos_network_log.pth"
@@ -0,0 +1,106 @@
1
+ """The network log: requests through http.client (urllib, requests) are written as
2
+ Emkay's network log lines, with who asked and the service, never the path."""
3
+ import http.server
4
+ import json
5
+ import threading
6
+ import time
7
+ import urllib.request
8
+
9
+ import pytest
10
+
11
+ import ovos_network_log as nl
12
+
13
+
14
+ @pytest.fixture
15
+ def log(tmp_path, monkeypatch):
16
+ path = tmp_path / "network.jsonl"
17
+ monkeypatch.setenv("OVOS_NETWORK_LOG_FILE", str(path))
18
+ monkeypatch.setenv("OVOS_NETWORK_LOG_BUS", "0")
19
+ # this machine's addresses are left out; for the test, a local server must count
20
+ monkeypatch.setattr(nl, "LOCAL", __import__("re").compile(r"^$never"))
21
+ nl.install()
22
+ return path
23
+
24
+
25
+ @pytest.fixture
26
+ def server():
27
+ class Handler(http.server.BaseHTTPRequestHandler):
28
+ def do_GET(self):
29
+ body = b"hello"
30
+ self.send_response(200)
31
+ self.send_header("Content-Length", str(len(body)))
32
+ self.end_headers()
33
+ self.wfile.write(body)
34
+
35
+ def log_message(self, *a):
36
+ pass
37
+ srv = http.server.HTTPServer(("127.0.0.1", 0), Handler)
38
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
39
+ yield f"127.0.0.1:{srv.server_address[1]}"
40
+ srv.shutdown()
41
+
42
+
43
+ def entries(path):
44
+ return [json.loads(line) for line in path.read_text().splitlines()]
45
+
46
+
47
+ def test_a_request_is_logged_without_its_path(log, server):
48
+ urllib.request.urlopen(f"http://{server}/secret/what-you-said?q=hello").read()
49
+ [e] = entries(log)
50
+ assert e["host"] == server and e["method"] == "GET" and e["status"] == 200 and e["bytes"] == 5
51
+ assert e["kind"] == "other" and e["service"] == server
52
+ assert "secret" not in json.dumps(e) and "hello" not in json.dumps(e)
53
+ assert abs(e["t"] / 1000 - time.time()) < 5
54
+
55
+
56
+ def test_requests_is_seen_too(log, server):
57
+ requests = pytest.importorskip("requests")
58
+ requests.get(f"http://{server}/x", timeout=5)
59
+ assert entries(log)[-1]["host"] == server
60
+
61
+
62
+ def test_a_refused_request_is_logged_with_status_0(log):
63
+ with pytest.raises(OSError):
64
+ urllib.request.urlopen("http://127.0.0.1:9/", timeout=2)
65
+ e = entries(log)[-1]
66
+ assert e["status"] == 0 and e["host"] == "127.0.0.1:9"
67
+
68
+
69
+ def test_this_machine_is_not_sent_out(tmp_path, monkeypatch):
70
+ monkeypatch.setenv("OVOS_NETWORK_LOG_FILE", str(tmp_path / "n.jsonl"))
71
+ monkeypatch.setenv("OVOS_NETWORK_LOG_BUS", "0")
72
+ assert nl.record("localhost:8181", "GET", 200, 1, "ovos") is None
73
+ assert nl.record("127.0.0.1", "GET", 200, 1, "ovos") is None
74
+ assert not (tmp_path / "n.jsonl").exists()
75
+
76
+
77
+ def test_known_services():
78
+ assert nl.service("stt.openvoiceos.pt") == ("stt", "speech recognition (OpenVoiceOS server)")
79
+ assert nl.service("da.wikipedia.org")[0] == "wikipedia"
80
+ assert nl.service("air-quality-api.open-meteo.com")[0] == "weather"
81
+ assert nl.service("example.com") == ("other", "example.com")
82
+
83
+
84
+ def test_who_asked():
85
+ assert nl.caller(1) in ("tests", "test-network-log", "ovos")
86
+
87
+
88
+ def test_only_ovos_programs(monkeypatch):
89
+ monkeypatch.delenv("OVOS_NETWORK_LOG", raising=False)
90
+ for program, on in (("/usr/bin/ovos-core", True), ("ovos-audio", True), ("mycroft-skills", True),
91
+ ("/usr/bin/pip", False), ("python3", False)):
92
+ monkeypatch.setattr("sys.argv", [program])
93
+ assert nl.wanted() is on, program
94
+ monkeypatch.setenv("OVOS_NETWORK_LOG", "1")
95
+ assert nl.wanted()
96
+ monkeypatch.setenv("OVOS_NETWORK_LOG", "0")
97
+ monkeypatch.setattr("sys.argv", ["ovos-core"])
98
+ assert not nl.wanted()
99
+
100
+
101
+ def test_old_entries_are_pruned(tmp_path):
102
+ path = tmp_path / "n.jsonl"
103
+ now = int(time.time() * 1000)
104
+ path.write_text(json.dumps({"t": now - 9 * 86400 * 1000}) + "\n" + json.dumps({"t": now}) + "\n")
105
+ nl.prune(str(path))
106
+ assert [e["t"] for e in entries(path)] == [now]