screen-relay 0.1.6__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.
- screen_relay-0.1.6/.gitignore +10 -0
- screen_relay-0.1.6/LICENSE +201 -0
- screen_relay-0.1.6/PKG-INFO +48 -0
- screen_relay-0.1.6/README.md +30 -0
- screen_relay-0.1.6/pyproject.toml +52 -0
- screen_relay-0.1.6/src/screen_relay/__init__.py +3 -0
- screen_relay-0.1.6/src/screen_relay/__main__.py +262 -0
- screen_relay-0.1.6/tests/test_cli.py +478 -0
|
@@ -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 2026 Vercel Inc.
|
|
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,48 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: screen-relay
|
|
3
|
+
Version: 0.1.6
|
|
4
|
+
Summary: Run the screen-relay CLI from Python tools such as uvx and pipx.
|
|
5
|
+
Project-URL: Homepage, https://screen-relay.dev
|
|
6
|
+
Project-URL: Documentation, https://screen-relay.dev/docs
|
|
7
|
+
Project-URL: Repository, https://github.com/vercel-labs/screen-relay
|
|
8
|
+
Project-URL: Changelog, https://github.com/vercel-labs/screen-relay/blob/main/CHANGELOG.md
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Operating System :: MacOS
|
|
13
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
14
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# screen-relay
|
|
20
|
+
|
|
21
|
+
Run the [screen-relay](https://screen-relay.dev) CLI from Python tools such as `uvx` and `pipx`.
|
|
22
|
+
|
|
23
|
+
This package is a launcher for the screen-relay npm package, not a Python port. On the first run of a version, it installs the matching npm package with `npm` into an isolated cache directory outside your working directory, then runs the CLI directly with `node`.
|
|
24
|
+
|
|
25
|
+
## Requirements
|
|
26
|
+
|
|
27
|
+
- Node.js 22 or newer, with `node` and `npm` on your `PATH`.
|
|
28
|
+
- Python 3.11 or newer.
|
|
29
|
+
- Network access the first time you run a version, so that `npm` can download it into the launcher cache.
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
uvx screen-relay install --yes # system packages and the engine build (first time only)
|
|
35
|
+
uvx screen-relay up -d # start a display, a desktop, and the engine
|
|
36
|
+
uvx screen-relay down
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
To keep `screen-relay` on your `PATH`, install the launcher as a tool:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
uv tool install screen-relay
|
|
43
|
+
screen-relay up -d
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Every argument goes to the npm CLI unchanged, and the command exits with the CLI's exit code. If `node` or `npm` is missing, the command prints an error and exits with code 1.
|
|
47
|
+
|
|
48
|
+
See the [screen-relay docs](https://screen-relay.dev/docs) for the commands, the Node SDK, and the HTTP and WebSocket API.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# screen-relay
|
|
2
|
+
|
|
3
|
+
Run the [screen-relay](https://screen-relay.dev) CLI from Python tools such as `uvx` and `pipx`.
|
|
4
|
+
|
|
5
|
+
This package is a launcher for the screen-relay npm package, not a Python port. On the first run of a version, it installs the matching npm package with `npm` into an isolated cache directory outside your working directory, then runs the CLI directly with `node`.
|
|
6
|
+
|
|
7
|
+
## Requirements
|
|
8
|
+
|
|
9
|
+
- Node.js 22 or newer, with `node` and `npm` on your `PATH`.
|
|
10
|
+
- Python 3.11 or newer.
|
|
11
|
+
- Network access the first time you run a version, so that `npm` can download it into the launcher cache.
|
|
12
|
+
|
|
13
|
+
## Usage
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
uvx screen-relay install --yes # system packages and the engine build (first time only)
|
|
17
|
+
uvx screen-relay up -d # start a display, a desktop, and the engine
|
|
18
|
+
uvx screen-relay down
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
To keep `screen-relay` on your `PATH`, install the launcher as a tool:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
uv tool install screen-relay
|
|
25
|
+
screen-relay up -d
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Every argument goes to the npm CLI unchanged, and the command exits with the CLI's exit code. If `node` or `npm` is missing, the command prints an error and exits with code 1.
|
|
29
|
+
|
|
30
|
+
See the [screen-relay docs](https://screen-relay.dev/docs) for the commands, the Node SDK, and the HTTP and WebSocket API.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27.0,<2"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "screen-relay"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Run the screen-relay CLI from Python tools such as uvx and pipx."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Environment :: Console",
|
|
15
|
+
"Operating System :: MacOS",
|
|
16
|
+
"Operating System :: Microsoft :: Windows",
|
|
17
|
+
"Operating System :: POSIX :: Linux",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://screen-relay.dev"
|
|
23
|
+
Documentation = "https://screen-relay.dev/docs"
|
|
24
|
+
Repository = "https://github.com/vercel-labs/screen-relay"
|
|
25
|
+
Changelog = "https://github.com/vercel-labs/screen-relay/blob/main/CHANGELOG.md"
|
|
26
|
+
|
|
27
|
+
[project.scripts]
|
|
28
|
+
screen-relay = "screen_relay.__main__:main"
|
|
29
|
+
|
|
30
|
+
[tool.hatch.version]
|
|
31
|
+
path = "src/screen_relay/__init__.py"
|
|
32
|
+
|
|
33
|
+
[tool.hatch.build.targets.sdist]
|
|
34
|
+
include = ["/src", "/tests", "/README.md", "/LICENSE", "/pyproject.toml"]
|
|
35
|
+
exclude = ["/**/__pycache__"]
|
|
36
|
+
|
|
37
|
+
[tool.hatch.build.targets.wheel]
|
|
38
|
+
packages = ["src/screen_relay"]
|
|
39
|
+
exclude = ["/**/__pycache__"]
|
|
40
|
+
|
|
41
|
+
[dependency-groups]
|
|
42
|
+
dev = ["ruff==0.17.6", "ty==1.1.0"]
|
|
43
|
+
|
|
44
|
+
[tool.ruff]
|
|
45
|
+
line-length = 100
|
|
46
|
+
target-version = "py311"
|
|
47
|
+
|
|
48
|
+
[tool.ruff.lint]
|
|
49
|
+
select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]
|
|
50
|
+
|
|
51
|
+
[tool.ty.environment]
|
|
52
|
+
python-version = "3.11"
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
"""Install the matching screen-relay npm package once and run its CLI with Node."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import shutil
|
|
5
|
+
import subprocess
|
|
6
|
+
import sys
|
|
7
|
+
import tempfile
|
|
8
|
+
from contextlib import suppress
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from screen_relay import __version__
|
|
12
|
+
|
|
13
|
+
MIN_NODE_MAJOR = 22
|
|
14
|
+
NPM_PACKAGE = f"screen-relay@{__version__}"
|
|
15
|
+
ENTRY_PATH = Path("node_modules") / "screen-relay" / "dist" / "cli" / "relay.mjs"
|
|
16
|
+
WINDOWS = os.name == "nt"
|
|
17
|
+
|
|
18
|
+
MISSING_NODE = (
|
|
19
|
+
"Error: screen-relay needs Node.js 22 or newer with node on your PATH. "
|
|
20
|
+
"Install Node.js 22 or newer, then run the command again."
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
MISSING_NPM = (
|
|
24
|
+
"Error: screen-relay needs npm on your PATH to install the CLI on first run. "
|
|
25
|
+
"Install Node.js 22 or newer, then run the command again."
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
MISSING_WINDOWS_NPM = (
|
|
29
|
+
"Error: screen-relay needs node.exe on your PATH with npm's npm-cli.js in "
|
|
30
|
+
"node_modules\\npm\\bin next to it, or an npm.exe on your PATH, to install "
|
|
31
|
+
"the CLI on first run. Install Node.js 22 or newer, then run the command again."
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def cache_dir() -> Path:
|
|
36
|
+
"""Return the versioned directory that holds the isolated npm CLI install."""
|
|
37
|
+
env_var = "LOCALAPPDATA" if WINDOWS else "XDG_CACHE_HOME"
|
|
38
|
+
configured = os.environ.get(env_var, "")
|
|
39
|
+
if configured and Path(configured).is_absolute():
|
|
40
|
+
base = Path(configured)
|
|
41
|
+
elif WINDOWS:
|
|
42
|
+
base = Path.home() / "AppData" / "Local"
|
|
43
|
+
else:
|
|
44
|
+
base = Path.home() / ".cache"
|
|
45
|
+
return base / "screen-relay" / "cli" / __version__
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def find_executable(name: str) -> Path | None:
|
|
49
|
+
"""Return the first executable ``name`` in an absolute PATH directory, ignoring cwd."""
|
|
50
|
+
for raw in os.environ.get("PATH", "").split(os.pathsep):
|
|
51
|
+
entry = raw.strip().strip('"') if WINDOWS else raw
|
|
52
|
+
if not entry:
|
|
53
|
+
continue
|
|
54
|
+
directory = Path(entry)
|
|
55
|
+
if not directory.is_absolute():
|
|
56
|
+
continue
|
|
57
|
+
candidate = directory / name
|
|
58
|
+
if candidate.is_file() and (WINDOWS or os.access(candidate, os.X_OK)):
|
|
59
|
+
return candidate
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def find_node() -> Path | None:
|
|
64
|
+
"""Return the Node.js executable from PATH, ignoring the working directory."""
|
|
65
|
+
return find_executable("node.exe" if WINDOWS else "node")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def find_npm(node: Path) -> list[str] | None:
|
|
69
|
+
"""Return argv to run npm without invoking cmd.exe or consulting the working directory."""
|
|
70
|
+
if WINDOWS:
|
|
71
|
+
script = node.parent / "node_modules" / "npm" / "bin" / "npm-cli.js"
|
|
72
|
+
if script.is_file():
|
|
73
|
+
return [str(node), str(script)]
|
|
74
|
+
npm_exe = find_executable("npm.exe")
|
|
75
|
+
if npm_exe is not None:
|
|
76
|
+
return [str(npm_exe)]
|
|
77
|
+
return None
|
|
78
|
+
npm = find_executable("npm")
|
|
79
|
+
return [str(npm)] if npm is not None else None
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def check_node_version(node: Path) -> bool:
|
|
83
|
+
"""Return False and print an error if ``node`` reports a version older than Node.js 22."""
|
|
84
|
+
try:
|
|
85
|
+
result = subprocess.run(
|
|
86
|
+
[str(node), "-v"],
|
|
87
|
+
stdin=subprocess.DEVNULL,
|
|
88
|
+
capture_output=True,
|
|
89
|
+
text=True,
|
|
90
|
+
timeout=10,
|
|
91
|
+
)
|
|
92
|
+
except (OSError, subprocess.SubprocessError):
|
|
93
|
+
return True
|
|
94
|
+
version = result.stdout.strip()
|
|
95
|
+
head = version[1:].split(".", 1)[0] if version.startswith("v") else ""
|
|
96
|
+
if result.returncode == 0 and head.isdigit() and int(head) < MIN_NODE_MAJOR:
|
|
97
|
+
print(
|
|
98
|
+
f"Error: screen-relay needs Node.js {MIN_NODE_MAJOR} or newer (found {version}). "
|
|
99
|
+
f"Install Node.js {MIN_NODE_MAJOR} or newer, then run the command again.",
|
|
100
|
+
file=sys.stderr,
|
|
101
|
+
)
|
|
102
|
+
return False
|
|
103
|
+
return True
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def install_command(npm: list[str], prefix: Path) -> list[str]:
|
|
107
|
+
"""Return the npm argv that installs the pinned screen-relay package into ``prefix``."""
|
|
108
|
+
return [
|
|
109
|
+
*npm,
|
|
110
|
+
"install",
|
|
111
|
+
"--prefix",
|
|
112
|
+
str(prefix),
|
|
113
|
+
"--no-global",
|
|
114
|
+
"--location=project",
|
|
115
|
+
"--no-dry-run",
|
|
116
|
+
"--no-package-lock-only",
|
|
117
|
+
"--ignore-scripts",
|
|
118
|
+
"--no-audit",
|
|
119
|
+
"--no-fund",
|
|
120
|
+
"--no-save",
|
|
121
|
+
"--no-package-lock",
|
|
122
|
+
NPM_PACKAGE,
|
|
123
|
+
]
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def verified_entry(root: Path) -> Path | None:
|
|
127
|
+
"""Return the installed CLI entrypoint under ``root`` if it exists inside ``root``."""
|
|
128
|
+
if root.is_symlink() or not root.is_dir():
|
|
129
|
+
return None
|
|
130
|
+
entry = root / ENTRY_PATH
|
|
131
|
+
if not entry.is_file():
|
|
132
|
+
return None
|
|
133
|
+
try:
|
|
134
|
+
if not entry.resolve().is_relative_to(root.resolve()):
|
|
135
|
+
return None
|
|
136
|
+
except OSError:
|
|
137
|
+
return None
|
|
138
|
+
return entry
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def replace_broken_target(scratch: Path, target: Path) -> tuple[Path | None, int]:
|
|
142
|
+
"""Replace an invalid preexisting ``target`` with ``scratch``, or return a concurrent winner."""
|
|
143
|
+
existing = verified_entry(target)
|
|
144
|
+
if existing is not None:
|
|
145
|
+
return existing, 0
|
|
146
|
+
stale: Path | None = None
|
|
147
|
+
try:
|
|
148
|
+
stale = Path(tempfile.mkdtemp(prefix=f".stale-{__version__}-", dir=target.parent))
|
|
149
|
+
with suppress(FileNotFoundError):
|
|
150
|
+
target.rename(stale / "entry")
|
|
151
|
+
scratch.rename(target)
|
|
152
|
+
except OSError as exc:
|
|
153
|
+
existing = verified_entry(target)
|
|
154
|
+
if existing is not None:
|
|
155
|
+
return existing, 0
|
|
156
|
+
print(f"Error: could not install {NPM_PACKAGE} into {target}: {exc}", file=sys.stderr)
|
|
157
|
+
return None, 1
|
|
158
|
+
finally:
|
|
159
|
+
if stale is not None:
|
|
160
|
+
shutil.rmtree(stale, ignore_errors=True)
|
|
161
|
+
return verified_entry(target), 0
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def ensure_cli(node: Path) -> tuple[Path | None, int]:
|
|
165
|
+
"""Ensure the pinned npm CLI is installed in the isolated cache and return its entrypoint."""
|
|
166
|
+
target = cache_dir()
|
|
167
|
+
existing = verified_entry(target)
|
|
168
|
+
if existing is not None:
|
|
169
|
+
return existing, 0
|
|
170
|
+
|
|
171
|
+
npm = find_npm(node)
|
|
172
|
+
if npm is None:
|
|
173
|
+
print(MISSING_WINDOWS_NPM if WINDOWS else MISSING_NPM, file=sys.stderr)
|
|
174
|
+
return None, 1
|
|
175
|
+
|
|
176
|
+
if not check_node_version(node):
|
|
177
|
+
return None, 1
|
|
178
|
+
|
|
179
|
+
try:
|
|
180
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
181
|
+
scratch = Path(tempfile.mkdtemp(prefix=f".install-{__version__}-", dir=target.parent))
|
|
182
|
+
except OSError as exc:
|
|
183
|
+
print(f"Error: could not create cache directory {target.parent}: {exc}", file=sys.stderr)
|
|
184
|
+
return None, 1
|
|
185
|
+
|
|
186
|
+
try:
|
|
187
|
+
env = {
|
|
188
|
+
k: v
|
|
189
|
+
for k, v in os.environ.items()
|
|
190
|
+
if k.lower() not in {"npm_config_workspace", "npm_config_workspaces"}
|
|
191
|
+
}
|
|
192
|
+
env["NPM_CONFIG_UPDATE_NOTIFIER"] = "false"
|
|
193
|
+
result = subprocess.run(
|
|
194
|
+
install_command(npm, scratch),
|
|
195
|
+
cwd=scratch,
|
|
196
|
+
env=env,
|
|
197
|
+
stdin=subprocess.DEVNULL,
|
|
198
|
+
capture_output=True,
|
|
199
|
+
text=True,
|
|
200
|
+
)
|
|
201
|
+
if result.returncode != 0:
|
|
202
|
+
detail = (result.stderr or result.stdout).strip()
|
|
203
|
+
if detail:
|
|
204
|
+
print(detail, file=sys.stderr)
|
|
205
|
+
return None, result.returncode
|
|
206
|
+
|
|
207
|
+
if verified_entry(scratch) is None:
|
|
208
|
+
print(f"Error: {NPM_PACKAGE} did not install {ENTRY_PATH}.", file=sys.stderr)
|
|
209
|
+
return None, 1
|
|
210
|
+
|
|
211
|
+
try:
|
|
212
|
+
scratch.rename(target)
|
|
213
|
+
except OSError:
|
|
214
|
+
entry, status = replace_broken_target(scratch, target)
|
|
215
|
+
if status != 0:
|
|
216
|
+
return None, status
|
|
217
|
+
if entry is None:
|
|
218
|
+
print(f"Error: {NPM_PACKAGE} did not install {ENTRY_PATH}.", file=sys.stderr)
|
|
219
|
+
return None, 1
|
|
220
|
+
return entry, 0
|
|
221
|
+
finally:
|
|
222
|
+
if scratch.exists():
|
|
223
|
+
shutil.rmtree(scratch, ignore_errors=True)
|
|
224
|
+
|
|
225
|
+
entry = verified_entry(target)
|
|
226
|
+
if entry is None:
|
|
227
|
+
print(f"Error: {NPM_PACKAGE} did not install {ENTRY_PATH}.", file=sys.stderr)
|
|
228
|
+
return None, 1
|
|
229
|
+
return entry, 0
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def main(argv: list[str] | None = None) -> int:
|
|
233
|
+
"""Run the pinned screen-relay CLI with ``argv`` and return its exit code."""
|
|
234
|
+
args = sys.argv[1:] if argv is None else argv
|
|
235
|
+
node = find_node()
|
|
236
|
+
if node is None:
|
|
237
|
+
print(MISSING_NODE, file=sys.stderr)
|
|
238
|
+
return 1
|
|
239
|
+
|
|
240
|
+
entry, status = ensure_cli(node)
|
|
241
|
+
if entry is None:
|
|
242
|
+
return status
|
|
243
|
+
|
|
244
|
+
cli_argv = [str(node), str(entry), *args]
|
|
245
|
+
if WINDOWS:
|
|
246
|
+
return run_child(cli_argv)
|
|
247
|
+
os.execv(str(node), cli_argv)
|
|
248
|
+
return 0
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def run_child(argv: list[str]) -> int:
|
|
252
|
+
"""Run ``argv`` as a child process and return its exit code once it exits."""
|
|
253
|
+
with subprocess.Popen(argv) as process:
|
|
254
|
+
while True:
|
|
255
|
+
try:
|
|
256
|
+
return process.wait()
|
|
257
|
+
except KeyboardInterrupt:
|
|
258
|
+
continue
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
if __name__ == "__main__":
|
|
262
|
+
sys.exit(main())
|
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Tests for the screen-relay Python launcher."""
|
|
2
|
+
|
|
3
|
+
import io
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import sys
|
|
9
|
+
import tempfile
|
|
10
|
+
import tomllib
|
|
11
|
+
import unittest
|
|
12
|
+
from contextlib import chdir, redirect_stderr
|
|
13
|
+
from importlib import import_module
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from unittest import mock
|
|
16
|
+
|
|
17
|
+
import screen_relay
|
|
18
|
+
from screen_relay import __main__ as cli
|
|
19
|
+
|
|
20
|
+
PINNED = f"screen-relay@{screen_relay.__version__}"
|
|
21
|
+
|
|
22
|
+
UNTRUSTED_TEXT = [
|
|
23
|
+
"hello & calc.exe",
|
|
24
|
+
'"quoted" & whoami',
|
|
25
|
+
"%PATH% !USERPROFILE!",
|
|
26
|
+
"a ^ b | c > d < e",
|
|
27
|
+
"it's (fine)",
|
|
28
|
+
"trailing backslash \\",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
FAKE_RELAY_CLI = """
|
|
32
|
+
import fs from "node:fs";
|
|
33
|
+
const payload = { argv: process.argv.slice(2), cwd: process.cwd() };
|
|
34
|
+
fs.writeFileSync(process.env.SCREEN_RELAY_TEST_RECORD, JSON.stringify(payload));
|
|
35
|
+
process.exit(7);
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def make_executable(path: Path, text: str = "") -> Path:
|
|
40
|
+
"""Create a file at ``path`` and mark it executable on POSIX."""
|
|
41
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
path.write_text(text)
|
|
43
|
+
if os.name != "nt":
|
|
44
|
+
path.chmod(0o755)
|
|
45
|
+
return path
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def windows_node(directory: Path, npm_cli: str | None = "") -> Path:
|
|
49
|
+
"""Lay out ``directory`` like a Windows Node.js install with an optional npm-cli.js."""
|
|
50
|
+
node = directory / "node.exe"
|
|
51
|
+
node.touch()
|
|
52
|
+
if npm_cli is not None:
|
|
53
|
+
bin_dir = directory / "node_modules" / "npm" / "bin"
|
|
54
|
+
bin_dir.mkdir(parents=True)
|
|
55
|
+
(bin_dir / "npm-cli.js").write_text(npm_cli)
|
|
56
|
+
return node
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def populate_cache(cache_root: Path, script: str = FAKE_RELAY_CLI) -> Path:
|
|
60
|
+
"""Pre-populate the isolated cache with a fake screen-relay CLI entrypoint."""
|
|
61
|
+
entry = cache_root / "screen-relay" / "cli" / screen_relay.__version__ / cli.ENTRY_PATH
|
|
62
|
+
entry.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
entry.write_text(script)
|
|
64
|
+
return entry
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class EntryPointTest(unittest.TestCase):
|
|
68
|
+
def test_the_declared_console_script_resolves_to_main(self) -> None:
|
|
69
|
+
project = tomllib.loads((Path(__file__).parent.parent / "pyproject.toml").read_text())
|
|
70
|
+
module, attribute = project["project"]["scripts"]["screen-relay"].split(":")
|
|
71
|
+
self.assertIs(getattr(import_module(module), attribute), cli.main)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class InstallCommandTest(unittest.TestCase):
|
|
75
|
+
def test_installs_pinned_package_without_scripts(self) -> None:
|
|
76
|
+
prefix = Path("/tmp/isolated")
|
|
77
|
+
self.assertEqual(
|
|
78
|
+
cli.install_command(["/usr/bin/npm"], prefix),
|
|
79
|
+
[
|
|
80
|
+
"/usr/bin/npm",
|
|
81
|
+
"install",
|
|
82
|
+
"--prefix",
|
|
83
|
+
str(prefix),
|
|
84
|
+
"--no-global",
|
|
85
|
+
"--location=project",
|
|
86
|
+
"--no-dry-run",
|
|
87
|
+
"--no-package-lock-only",
|
|
88
|
+
"--ignore-scripts",
|
|
89
|
+
"--no-audit",
|
|
90
|
+
"--no-fund",
|
|
91
|
+
"--no-save",
|
|
92
|
+
"--no-package-lock",
|
|
93
|
+
PINNED,
|
|
94
|
+
],
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
class MainTest(unittest.TestCase):
|
|
99
|
+
def setUp(self) -> None:
|
|
100
|
+
environ = mock.patch.dict(os.environ)
|
|
101
|
+
environ.start()
|
|
102
|
+
self.addCleanup(environ.stop)
|
|
103
|
+
|
|
104
|
+
def test_reports_missing_node(self) -> None:
|
|
105
|
+
stderr = io.StringIO()
|
|
106
|
+
with (
|
|
107
|
+
tempfile.TemporaryDirectory() as empty_dir,
|
|
108
|
+
mock.patch.dict(os.environ, {"PATH": empty_dir}),
|
|
109
|
+
redirect_stderr(stderr),
|
|
110
|
+
):
|
|
111
|
+
self.assertEqual(cli.main(["up"]), 1)
|
|
112
|
+
self.assertIn("Node.js 22", stderr.getvalue())
|
|
113
|
+
|
|
114
|
+
def test_reports_missing_npm_on_posix_cold_cache(self) -> None:
|
|
115
|
+
stderr = io.StringIO()
|
|
116
|
+
with (
|
|
117
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
118
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
119
|
+
):
|
|
120
|
+
make_executable(Path(bin_dir) / "node", "#!/bin/sh\n")
|
|
121
|
+
with (
|
|
122
|
+
mock.patch.object(cli, "WINDOWS", False),
|
|
123
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "XDG_CACHE_HOME": cache_root}),
|
|
124
|
+
redirect_stderr(stderr),
|
|
125
|
+
):
|
|
126
|
+
self.assertEqual(cli.main(["up"]), 1)
|
|
127
|
+
self.assertIn("needs npm", stderr.getvalue())
|
|
128
|
+
|
|
129
|
+
def test_warm_cache_runs_node_directly_without_npm(self) -> None:
|
|
130
|
+
with (
|
|
131
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
132
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
133
|
+
):
|
|
134
|
+
node = make_executable(Path(bin_dir) / "node", "#!/bin/sh\n")
|
|
135
|
+
entry = populate_cache(Path(cache_root))
|
|
136
|
+
with (
|
|
137
|
+
mock.patch.object(cli, "WINDOWS", False),
|
|
138
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "XDG_CACHE_HOME": cache_root}),
|
|
139
|
+
mock.patch.object(cli.os, "execv") as execv,
|
|
140
|
+
):
|
|
141
|
+
cli.main(["status", "--json"])
|
|
142
|
+
execv.assert_called_once_with(str(node), [str(node), str(entry), "status", "--json"])
|
|
143
|
+
|
|
144
|
+
def test_reads_sys_argv_by_default(self) -> None:
|
|
145
|
+
with (
|
|
146
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
147
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
148
|
+
):
|
|
149
|
+
node = make_executable(Path(bin_dir) / "node", "#!/bin/sh\n")
|
|
150
|
+
entry = populate_cache(Path(cache_root))
|
|
151
|
+
with (
|
|
152
|
+
mock.patch.object(cli, "WINDOWS", False),
|
|
153
|
+
mock.patch.object(cli.sys, "argv", ["screen-relay", "doctor"]),
|
|
154
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "XDG_CACHE_HOME": cache_root}),
|
|
155
|
+
mock.patch.object(cli.os, "execv") as execv,
|
|
156
|
+
):
|
|
157
|
+
cli.main()
|
|
158
|
+
execv.assert_called_once_with(str(node), [str(node), str(entry), "doctor"])
|
|
159
|
+
|
|
160
|
+
def test_runs_cached_cli_directly_with_node_on_windows(self) -> None:
|
|
161
|
+
process = mock.MagicMock()
|
|
162
|
+
process.__enter__.return_value = process
|
|
163
|
+
process.wait.return_value = 3
|
|
164
|
+
with (
|
|
165
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
166
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
167
|
+
):
|
|
168
|
+
node = windows_node(Path(bin_dir), npm_cli=None)
|
|
169
|
+
entry = populate_cache(Path(cache_root))
|
|
170
|
+
with (
|
|
171
|
+
mock.patch.object(cli, "WINDOWS", True),
|
|
172
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "LOCALAPPDATA": cache_root}),
|
|
173
|
+
mock.patch.object(cli.subprocess, "Popen", return_value=process) as popen,
|
|
174
|
+
):
|
|
175
|
+
self.assertEqual(cli.main(["type", *UNTRUSTED_TEXT]), 3)
|
|
176
|
+
popen.assert_called_once_with([str(node), str(entry), "type", *UNTRUSTED_TEXT])
|
|
177
|
+
|
|
178
|
+
def test_never_runs_a_batch_file_on_windows(self) -> None:
|
|
179
|
+
stderr = io.StringIO()
|
|
180
|
+
with (
|
|
181
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
182
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
183
|
+
):
|
|
184
|
+
directory = Path(bin_dir)
|
|
185
|
+
(directory / "node.cmd").touch()
|
|
186
|
+
(directory / "npm.cmd").touch()
|
|
187
|
+
with (
|
|
188
|
+
mock.patch.object(cli, "WINDOWS", True),
|
|
189
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "LOCALAPPDATA": cache_root}),
|
|
190
|
+
mock.patch.object(cli.subprocess, "Popen") as popen,
|
|
191
|
+
redirect_stderr(stderr),
|
|
192
|
+
):
|
|
193
|
+
self.assertEqual(cli.main(["type", "hello & calc.exe"]), 1)
|
|
194
|
+
popen.assert_not_called()
|
|
195
|
+
self.assertIn("Node.js 22", stderr.getvalue())
|
|
196
|
+
|
|
197
|
+
def test_reports_missing_npm_cli_on_windows(self) -> None:
|
|
198
|
+
stderr = io.StringIO()
|
|
199
|
+
with (
|
|
200
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
201
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
202
|
+
):
|
|
203
|
+
windows_node(Path(bin_dir), npm_cli=None)
|
|
204
|
+
with (
|
|
205
|
+
mock.patch.object(cli, "WINDOWS", True),
|
|
206
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "LOCALAPPDATA": cache_root}),
|
|
207
|
+
mock.patch.object(cli.subprocess, "Popen") as popen,
|
|
208
|
+
redirect_stderr(stderr),
|
|
209
|
+
):
|
|
210
|
+
self.assertEqual(cli.main(["up"]), 1)
|
|
211
|
+
popen.assert_not_called()
|
|
212
|
+
self.assertIn("npm-cli.js", stderr.getvalue())
|
|
213
|
+
|
|
214
|
+
def test_uses_an_npm_executable_beside_a_foreign_node_on_windows(self) -> None:
|
|
215
|
+
with tempfile.TemporaryDirectory() as name:
|
|
216
|
+
directory = Path(name)
|
|
217
|
+
node = directory / "node.exe"
|
|
218
|
+
npm = directory / "npm.exe"
|
|
219
|
+
node.touch()
|
|
220
|
+
npm.touch()
|
|
221
|
+
with (
|
|
222
|
+
mock.patch.object(cli, "WINDOWS", True),
|
|
223
|
+
mock.patch.dict(os.environ, {"PATH": name}),
|
|
224
|
+
):
|
|
225
|
+
self.assertEqual(cli.find_npm(node), [str(npm)])
|
|
226
|
+
|
|
227
|
+
def test_ignores_decoy_executables_in_working_directory(self) -> None:
|
|
228
|
+
with (
|
|
229
|
+
tempfile.TemporaryDirectory() as decoy_name,
|
|
230
|
+
tempfile.TemporaryDirectory() as real_name,
|
|
231
|
+
):
|
|
232
|
+
decoy = Path(decoy_name)
|
|
233
|
+
windows_node(decoy)
|
|
234
|
+
(decoy / "npm.exe").touch()
|
|
235
|
+
real = Path(real_name)
|
|
236
|
+
real_node = windows_node(real)
|
|
237
|
+
real_script = real / "node_modules" / "npm" / "bin" / "npm-cli.js"
|
|
238
|
+
with mock.patch.object(cli, "WINDOWS", True), chdir(decoy):
|
|
239
|
+
with mock.patch.dict(os.environ, {"PATH": os.pathsep.join(["", ".", "relative"])}):
|
|
240
|
+
self.assertIsNone(cli.find_node())
|
|
241
|
+
with mock.patch.dict(os.environ, {"PATH": os.pathsep.join(["", ".", real_name])}):
|
|
242
|
+
found_node = cli.find_node()
|
|
243
|
+
self.assertEqual(found_node, real_node)
|
|
244
|
+
assert found_node is not None
|
|
245
|
+
self.assertEqual(cli.find_npm(found_node), [str(real_node), str(real_script)])
|
|
246
|
+
|
|
247
|
+
def test_failed_install_leaves_no_partial_cache(self) -> None:
|
|
248
|
+
stderr = io.StringIO()
|
|
249
|
+
with (
|
|
250
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
251
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
252
|
+
):
|
|
253
|
+
node = make_executable(Path(bin_dir) / "node", "#!/bin/sh\n")
|
|
254
|
+
make_executable(Path(bin_dir) / "npm", "#!/bin/sh\n")
|
|
255
|
+
failed = subprocess.CompletedProcess([], 1, stdout="", stderr="registry down\n")
|
|
256
|
+
with (
|
|
257
|
+
mock.patch.object(cli, "WINDOWS", False),
|
|
258
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "XDG_CACHE_HOME": cache_root}),
|
|
259
|
+
mock.patch.object(cli.subprocess, "run", return_value=failed),
|
|
260
|
+
redirect_stderr(stderr),
|
|
261
|
+
):
|
|
262
|
+
entry, status = cli.ensure_cli(node)
|
|
263
|
+
self.assertIsNone(entry)
|
|
264
|
+
self.assertEqual(status, 1)
|
|
265
|
+
self.assertIn("registry down", stderr.getvalue())
|
|
266
|
+
cli_root = Path(cache_root) / "screen-relay" / "cli"
|
|
267
|
+
self.assertEqual(list(cli_root.iterdir()), [])
|
|
268
|
+
|
|
269
|
+
def test_recovers_from_preexisting_incomplete_cache_target(self) -> None:
|
|
270
|
+
for kind in ("broken_dir", "file"):
|
|
271
|
+
with (
|
|
272
|
+
self.subTest(kind=kind),
|
|
273
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
274
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
275
|
+
):
|
|
276
|
+
node = make_executable(Path(bin_dir) / "node", "#!/bin/sh\n")
|
|
277
|
+
make_executable(Path(bin_dir) / "npm", "#!/bin/sh\n")
|
|
278
|
+
target = Path(cache_root) / "screen-relay" / "cli" / screen_relay.__version__
|
|
279
|
+
if kind == "broken_dir":
|
|
280
|
+
(target / "junk").mkdir(parents=True)
|
|
281
|
+
(target / "junk" / "partial").write_text("broken")
|
|
282
|
+
else:
|
|
283
|
+
target.parent.mkdir(parents=True)
|
|
284
|
+
target.write_text("not a directory")
|
|
285
|
+
|
|
286
|
+
def fake_run(
|
|
287
|
+
argv: list[str],
|
|
288
|
+
**kwargs: object,
|
|
289
|
+
) -> subprocess.CompletedProcess[str]:
|
|
290
|
+
if argv[1:] == ["-v"]:
|
|
291
|
+
return subprocess.CompletedProcess(argv, 0, stdout="v24.0.0\n", stderr="")
|
|
292
|
+
prefix = Path(argv[argv.index("--prefix") + 1])
|
|
293
|
+
entry = prefix / cli.ENTRY_PATH
|
|
294
|
+
entry.parent.mkdir(parents=True, exist_ok=True)
|
|
295
|
+
entry.write_text(FAKE_RELAY_CLI)
|
|
296
|
+
return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")
|
|
297
|
+
|
|
298
|
+
with (
|
|
299
|
+
mock.patch.object(cli, "WINDOWS", False),
|
|
300
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "XDG_CACHE_HOME": cache_root}),
|
|
301
|
+
mock.patch.object(cli.subprocess, "run", side_effect=fake_run),
|
|
302
|
+
):
|
|
303
|
+
entry, status = cli.ensure_cli(node)
|
|
304
|
+
self.assertEqual(status, 0)
|
|
305
|
+
self.assertEqual(entry, target / cli.ENTRY_PATH)
|
|
306
|
+
self.assertEqual(
|
|
307
|
+
[p.name for p in target.parent.iterdir()], [screen_relay.__version__]
|
|
308
|
+
)
|
|
309
|
+
|
|
310
|
+
def test_rejects_node_older_than_22_on_cold_cache(self) -> None:
|
|
311
|
+
stderr = io.StringIO()
|
|
312
|
+
with (
|
|
313
|
+
tempfile.TemporaryDirectory() as bin_dir,
|
|
314
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
315
|
+
):
|
|
316
|
+
node = make_executable(Path(bin_dir) / "node", "#!/bin/sh\n")
|
|
317
|
+
make_executable(Path(bin_dir) / "npm", "#!/bin/sh\n")
|
|
318
|
+
old_node = subprocess.CompletedProcess([], 0, stdout="v20.18.0\n", stderr="")
|
|
319
|
+
with (
|
|
320
|
+
mock.patch.object(cli, "WINDOWS", False),
|
|
321
|
+
mock.patch.dict(os.environ, {"PATH": bin_dir, "XDG_CACHE_HOME": cache_root}),
|
|
322
|
+
mock.patch.object(cli.subprocess, "run", return_value=old_node) as run_mock,
|
|
323
|
+
redirect_stderr(stderr),
|
|
324
|
+
):
|
|
325
|
+
entry, status = cli.ensure_cli(node)
|
|
326
|
+
self.assertIsNone(entry)
|
|
327
|
+
self.assertEqual(status, 1)
|
|
328
|
+
self.assertIn("Node.js 22", stderr.getvalue())
|
|
329
|
+
self.assertIn("v20.18.0", stderr.getvalue())
|
|
330
|
+
run_mock.assert_called_once()
|
|
331
|
+
|
|
332
|
+
@unittest.skipIf(os.name == "nt", "POSIX symlink test")
|
|
333
|
+
def test_verified_entry_rejects_symlinked_cache_root(self) -> None:
|
|
334
|
+
with (
|
|
335
|
+
tempfile.TemporaryDirectory() as cache_root,
|
|
336
|
+
tempfile.TemporaryDirectory() as outside_dir,
|
|
337
|
+
):
|
|
338
|
+
outside = Path(outside_dir)
|
|
339
|
+
outside_entry = outside / cli.ENTRY_PATH
|
|
340
|
+
outside_entry.parent.mkdir(parents=True)
|
|
341
|
+
outside_entry.write_text(FAKE_RELAY_CLI)
|
|
342
|
+
target = Path(cache_root) / "screen-relay" / "cli" / screen_relay.__version__
|
|
343
|
+
target.parent.mkdir(parents=True)
|
|
344
|
+
target.symlink_to(outside)
|
|
345
|
+
self.assertIsNone(cli.verified_entry(target))
|
|
346
|
+
|
|
347
|
+
def test_waits_for_the_child_after_ctrl_c_on_windows(self) -> None:
|
|
348
|
+
process = mock.MagicMock()
|
|
349
|
+
process.__enter__.return_value = process
|
|
350
|
+
process.wait.side_effect = [KeyboardInterrupt, 130]
|
|
351
|
+
with mock.patch.object(cli.subprocess, "Popen", return_value=process):
|
|
352
|
+
self.assertEqual(cli.run_child(["node"]), 130)
|
|
353
|
+
self.assertEqual(process.wait.call_count, 2)
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
@unittest.skipUnless(shutil.which("node"), "needs Node.js")
|
|
357
|
+
class HostileCheckoutAndArgumentsTest(unittest.TestCase):
|
|
358
|
+
"""Runs real Node.js from a hostile checkout and checks isolation, cwd, and literal args."""
|
|
359
|
+
|
|
360
|
+
def setUp(self) -> None:
|
|
361
|
+
environ = mock.patch.dict(os.environ)
|
|
362
|
+
environ.start()
|
|
363
|
+
self.addCleanup(environ.stop)
|
|
364
|
+
|
|
365
|
+
def link_real_node(self, target: Path) -> Path:
|
|
366
|
+
real_node = shutil.which("node")
|
|
367
|
+
assert real_node is not None
|
|
368
|
+
if os.name == "nt":
|
|
369
|
+
shutil.copy(real_node, target)
|
|
370
|
+
else:
|
|
371
|
+
target.symlink_to(Path(real_node).resolve())
|
|
372
|
+
return target
|
|
373
|
+
|
|
374
|
+
def test_hostile_checkout_npmrc_is_never_executed_and_cwd_is_preserved(self) -> None:
|
|
375
|
+
with (
|
|
376
|
+
tempfile.TemporaryDirectory() as checkout_name,
|
|
377
|
+
tempfile.TemporaryDirectory() as cache_name,
|
|
378
|
+
tempfile.TemporaryDirectory() as bin_name,
|
|
379
|
+
):
|
|
380
|
+
checkout = Path(checkout_name)
|
|
381
|
+
cache_root = Path(cache_name)
|
|
382
|
+
bin_dir = Path(bin_name)
|
|
383
|
+
|
|
384
|
+
pwned = checkout / "pwned.txt"
|
|
385
|
+
evil_script = make_executable(
|
|
386
|
+
checkout / ("evil.cmd" if os.name == "nt" else "evil.sh"),
|
|
387
|
+
f"#!/bin/sh\necho pwned > {pwned}\nexit 99\n",
|
|
388
|
+
)
|
|
389
|
+
(checkout / "package.json").write_text('{"name":"screen-relay","version":"9.9.9"}\n')
|
|
390
|
+
(checkout / ".npmrc").write_text(
|
|
391
|
+
f"script-shell={evil_script}\nregistry=http://127.0.0.1:1/\n"
|
|
392
|
+
)
|
|
393
|
+
|
|
394
|
+
install_cwd_record = cache_root / "install-cwd.txt"
|
|
395
|
+
cli_record = checkout / "cli-record.json"
|
|
396
|
+
fake_npm_js = f"""
|
|
397
|
+
const fs = require("fs");
|
|
398
|
+
const path = require("path");
|
|
399
|
+
fs.writeFileSync({json.dumps(str(install_cwd_record))}, process.cwd());
|
|
400
|
+
const prefix = process.argv[process.argv.indexOf("--prefix") + 1];
|
|
401
|
+
const target = path.join(prefix, "node_modules", "screen-relay", "dist", "cli", "relay.mjs");
|
|
402
|
+
fs.mkdirSync(path.dirname(target), {{ recursive: true }});
|
|
403
|
+
fs.writeFileSync(target, {json.dumps(FAKE_RELAY_CLI)});
|
|
404
|
+
"""
|
|
405
|
+
if os.name == "nt":
|
|
406
|
+
self.link_real_node(bin_dir / "node.exe")
|
|
407
|
+
npm_bin = bin_dir / "node_modules" / "npm" / "bin"
|
|
408
|
+
npm_bin.mkdir(parents=True)
|
|
409
|
+
(npm_bin / "npm-cli.js").write_text(fake_npm_js)
|
|
410
|
+
cache_env = {"LOCALAPPDATA": cache_name}
|
|
411
|
+
else:
|
|
412
|
+
node_path = self.link_real_node(bin_dir / "node")
|
|
413
|
+
npm_js = bin_dir / "fake-npm.js"
|
|
414
|
+
npm_js.write_text(fake_npm_js)
|
|
415
|
+
make_executable(bin_dir / "npm", f'#!/bin/sh\nexec "{node_path}" "{npm_js}" "$@"\n')
|
|
416
|
+
cache_env = {"XDG_CACHE_HOME": cache_name}
|
|
417
|
+
|
|
418
|
+
path = os.pathsep.join(
|
|
419
|
+
entry for entry in (bin_name, os.environ.get("PATH", "")) if entry
|
|
420
|
+
)
|
|
421
|
+
env = {
|
|
422
|
+
**os.environ,
|
|
423
|
+
**cache_env,
|
|
424
|
+
"PATH": path,
|
|
425
|
+
"SCREEN_RELAY_TEST_RECORD": str(cli_record),
|
|
426
|
+
}
|
|
427
|
+
result = subprocess.run(
|
|
428
|
+
[sys.executable, "-m", "screen_relay", "type", *UNTRUSTED_TEXT],
|
|
429
|
+
cwd=checkout,
|
|
430
|
+
env=env,
|
|
431
|
+
capture_output=True,
|
|
432
|
+
text=True,
|
|
433
|
+
timeout=60,
|
|
434
|
+
)
|
|
435
|
+
|
|
436
|
+
self.assertEqual(result.returncode, 7, result.stderr)
|
|
437
|
+
self.assertEqual(result.stdout, "")
|
|
438
|
+
self.assertFalse(pwned.exists())
|
|
439
|
+
install_cwd = Path(install_cwd_record.read_text()).resolve()
|
|
440
|
+
self.assertNotEqual(install_cwd, checkout.resolve())
|
|
441
|
+
self.assertTrue(install_cwd.is_relative_to(cache_root.resolve()))
|
|
442
|
+
recorded = json.loads(cli_record.read_text())
|
|
443
|
+
self.assertEqual(recorded["argv"], ["type", *UNTRUSTED_TEXT])
|
|
444
|
+
self.assertEqual(Path(recorded["cwd"]).resolve(), checkout.resolve())
|
|
445
|
+
|
|
446
|
+
def test_windows_path_passes_untrusted_text_literally_to_node(self) -> None:
|
|
447
|
+
with (
|
|
448
|
+
tempfile.TemporaryDirectory() as bin_name,
|
|
449
|
+
tempfile.TemporaryDirectory() as cache_name,
|
|
450
|
+
):
|
|
451
|
+
bin_dir = Path(bin_name)
|
|
452
|
+
cache_root = Path(cache_name)
|
|
453
|
+
self.link_real_node(bin_dir / "node.exe")
|
|
454
|
+
populate_cache(cache_root)
|
|
455
|
+
recorded = bin_dir / "record.json"
|
|
456
|
+
path = os.pathsep.join(
|
|
457
|
+
entry for entry in (bin_name, os.environ.get("PATH", "")) if entry
|
|
458
|
+
)
|
|
459
|
+
for text in UNTRUSTED_TEXT:
|
|
460
|
+
with (
|
|
461
|
+
self.subTest(text=text),
|
|
462
|
+
mock.patch.object(cli, "WINDOWS", True),
|
|
463
|
+
mock.patch.dict(
|
|
464
|
+
os.environ,
|
|
465
|
+
{
|
|
466
|
+
"PATH": path,
|
|
467
|
+
"LOCALAPPDATA": cache_name,
|
|
468
|
+
"SCREEN_RELAY_TEST_RECORD": str(recorded),
|
|
469
|
+
},
|
|
470
|
+
),
|
|
471
|
+
):
|
|
472
|
+
code = cli.main(["type", text])
|
|
473
|
+
self.assertEqual(code, 7)
|
|
474
|
+
self.assertEqual(json.loads(recorded.read_text())["argv"], ["type", text])
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
if __name__ == "__main__":
|
|
478
|
+
unittest.main()
|