lookfirst 0.1.0__py3-none-any.whl

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.
Files changed (81) hide show
  1. lookfirst/__init__.py +16 -0
  2. lookfirst/__main__.py +3 -0
  3. lookfirst/cli.py +294 -0
  4. lookfirst/core/__init__.py +1 -0
  5. lookfirst/core/archive.py +220 -0
  6. lookfirst/core/config.py +28 -0
  7. lookfirst/core/errors.py +26 -0
  8. lookfirst/core/http.py +293 -0
  9. lookfirst/core/textsafe.py +65 -0
  10. lookfirst/core/urls.py +32 -0
  11. lookfirst/entry.py +23 -0
  12. lookfirst/hook.py +1074 -0
  13. lookfirst/hook_run.py +63 -0
  14. lookfirst/identity/__init__.py +1 -0
  15. lookfirst/identity/check.py +806 -0
  16. lookfirst/identity/github.py +190 -0
  17. lookfirst/identity/names.py +134 -0
  18. lookfirst/identity/official.py +97 -0
  19. lookfirst/identity/popular_index.py +214 -0
  20. lookfirst/identity/provenance.py +87 -0
  21. lookfirst/identity/readme_sim.py +64 -0
  22. lookfirst/mcp_server.py +117 -0
  23. lookfirst/pipeline.py +137 -0
  24. lookfirst/registry/__init__.py +2 -0
  25. lookfirst/registry/installers.py +53 -0
  26. lookfirst/registry/installers.yaml +85 -0
  27. lookfirst/registry/official.yaml +105 -0
  28. lookfirst/registry/popular.csv.gz +0 -0
  29. lookfirst/sandbox/Dockerfile +37 -0
  30. lookfirst/sandbox/__init__.py +10 -0
  31. lookfirst/sandbox/analyze.py +273 -0
  32. lookfirst/sandbox/command.py +97 -0
  33. lookfirst/sandbox/docker.py +135 -0
  34. lookfirst/sandbox/honeytokens.py +170 -0
  35. lookfirst/sandbox/image.py +63 -0
  36. lookfirst/sandbox/mitm_addon.py +120 -0
  37. lookfirst/sandbox/proxy.py +160 -0
  38. lookfirst/sandbox/runner.py +434 -0
  39. lookfirst/sandbox/trace_parse.py +229 -0
  40. lookfirst/sandbox/transfer.py +101 -0
  41. lookfirst/scanners/__init__.py +8 -0
  42. lookfirst/scanners/base.py +139 -0
  43. lookfirst/scanners/check.py +444 -0
  44. lookfirst/scanners/guarddog.py +151 -0
  45. lookfirst/scanners/lockfiles.py +194 -0
  46. lookfirst/scanners/osv.py +267 -0
  47. lookfirst/static/__init__.py +1 -0
  48. lookfirst/static/agent_configs.py +317 -0
  49. lookfirst/static/autorun.py +120 -0
  50. lookfirst/static/checks.py +51 -0
  51. lookfirst/static/code_rules.py +203 -0
  52. lookfirst/static/context.py +149 -0
  53. lookfirst/static/fetch.py +223 -0
  54. lookfirst/static/files.py +100 -0
  55. lookfirst/static/injection.py +329 -0
  56. lookfirst/static/install_paths.py +497 -0
  57. lookfirst/static/jsonc.py +50 -0
  58. lookfirst/static/model.py +122 -0
  59. lookfirst/static/readme.py +88 -0
  60. lookfirst/static/rules_catalog.py +632 -0
  61. lookfirst/static/shell_parse.py +325 -0
  62. lookfirst/static/shell_rules.py +1154 -0
  63. lookfirst/targets/__init__.py +1 -0
  64. lookfirst/targets/base.py +106 -0
  65. lookfirst/targets/github.py +160 -0
  66. lookfirst/targets/local.py +41 -0
  67. lookfirst/targets/models.py +53 -0
  68. lookfirst/targets/oneliner.py +27 -0
  69. lookfirst/targets/packages.py +354 -0
  70. lookfirst/verdict/__init__.py +1 -0
  71. lookfirst/verdict/describe.py +221 -0
  72. lookfirst/verdict/render_agent.py +478 -0
  73. lookfirst/verdict/render_markdown.py +219 -0
  74. lookfirst/verdict/render_terminal.py +181 -0
  75. lookfirst/verdict/schema.py +167 -0
  76. lookfirst/verdict/scoring.py +75 -0
  77. lookfirst-0.1.0.dist-info/METADATA +161 -0
  78. lookfirst-0.1.0.dist-info/RECORD +81 -0
  79. lookfirst-0.1.0.dist-info/WHEEL +4 -0
  80. lookfirst-0.1.0.dist-info/entry_points.txt +3 -0
  81. lookfirst-0.1.0.dist-info/licenses/LICENSE +202 -0
lookfirst/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """lookfirst: check code from strangers before you or your AI agent runs it."""
2
+
3
+
4
+ def __getattr__(name: str) -> str:
5
+ # The version is looked up only when asked for: importlib.metadata takes about 28 ms
6
+ # to import, and the hook's fast path never needs it.
7
+ if name == "__version__":
8
+ from importlib.metadata import PackageNotFoundError, version
9
+
10
+ try:
11
+ value = version("lookfirst")
12
+ except PackageNotFoundError: # running from a source tree that isn't installed
13
+ value = "0.0.0+unknown"
14
+ globals()["__version__"] = value
15
+ return value
16
+ raise AttributeError(f"module 'lookfirst' has no attribute {name!r}")
lookfirst/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from lookfirst.entry import main
2
+
3
+ raise SystemExit(main())
lookfirst/cli.py ADDED
@@ -0,0 +1,294 @@
1
+ """The `lookfirst` command.
2
+
3
+ Exit codes: 0 Looks OK, 10 Caution, 20 Don't run, 1 error. Usage mistakes
4
+ exit 1 too, not the usual 2, because Claude Code reads exit 2 from a hook
5
+ as "block this command".
6
+ """
7
+
8
+ import os
9
+ import sys
10
+ from collections.abc import Sequence
11
+ from enum import StrEnum
12
+ from pathlib import Path
13
+ from typing import Annotated
14
+
15
+ import typer
16
+ from rich.text import Text
17
+
18
+ from lookfirst import __version__
19
+ from lookfirst.core.errors import LookfirstError
20
+ from lookfirst.core.textsafe import visible
21
+ from lookfirst.pipeline import run_check
22
+ from lookfirst.sandbox.runner import DEFAULT_TIMEOUT, SandboxOptions
23
+ from lookfirst.verdict.render_markdown import render_markdown
24
+ from lookfirst.verdict.render_terminal import make_console, render_terminal
25
+
26
+ EXIT_ERROR = 1
27
+ _USAGE_ERROR = 2 # what typer uses for a usage mistake
28
+
29
+ app = typer.Typer(
30
+ name="lookfirst",
31
+ add_completion=False,
32
+ no_args_is_help=True,
33
+ pretty_exceptions_enable=False,
34
+ help=(
35
+ "Check a GitHub repo, shell one-liner or package before you or your AI agent runs it. "
36
+ "lookfirst lowers risk; it doesn't guarantee safety."
37
+ ),
38
+ )
39
+
40
+
41
+ class Network(StrEnum):
42
+ sinkhole = "sinkhole"
43
+ passthrough = "passthrough"
44
+ offline = "offline"
45
+
46
+
47
+ class Arch(StrEnum):
48
+ arm64 = "arm64"
49
+ amd64 = "amd64"
50
+
51
+
52
+ sandbox_app = typer.Typer(
53
+ name="sandbox",
54
+ no_args_is_help=True,
55
+ help="The Docker sandbox that --sandbox runs installs in.",
56
+ )
57
+ app.add_typer(sandbox_app)
58
+
59
+
60
+ def _show_version(value: bool) -> None:
61
+ if value:
62
+ typer.echo(f"lookfirst {__version__}")
63
+ raise typer.Exit()
64
+
65
+
66
+ @app.callback()
67
+ def _root(
68
+ version: Annotated[
69
+ bool,
70
+ typer.Option(
71
+ "--version", callback=_show_version, is_eager=True, help="Show the version and exit."
72
+ ),
73
+ ] = False,
74
+ ) -> None:
75
+ """Check a GitHub repo, shell one-liner or package before you or your AI agent runs it."""
76
+
77
+
78
+ def print_error(message: str, hint: str | None = None) -> None:
79
+ console = make_console(stderr=True)
80
+ console.print(Text.assemble(("lookfirst: ", "bold red"), visible(message)))
81
+ if hint:
82
+ console.print(Text(visible(hint, keep_newlines=True), style="dim"))
83
+
84
+
85
+ @app.command()
86
+ def check(
87
+ target: Annotated[
88
+ str,
89
+ typer.Argument(
90
+ help=(
91
+ "What to check: a GitHub URL or owner/repo (optionally @branch, tag or commit), "
92
+ 'a folder, a quoted shell command such as "curl ... | bash", '
93
+ "npm:<name> or pypi:<name>."
94
+ ),
95
+ show_default=False,
96
+ ),
97
+ ],
98
+ sandbox: Annotated[
99
+ bool,
100
+ typer.Option(
101
+ "--sandbox",
102
+ help="Also run the install in a throwaway Docker sandbox and watch what it does.",
103
+ ),
104
+ ] = False,
105
+ cmd: Annotated[
106
+ str | None,
107
+ typer.Option(
108
+ "--cmd",
109
+ metavar="COMMAND",
110
+ help="With --sandbox: the install command to run, instead of lookfirst's guess.",
111
+ ),
112
+ ] = None,
113
+ network: Annotated[
114
+ Network,
115
+ typer.Option(
116
+ "--network",
117
+ case_sensitive=False,
118
+ help=(
119
+ "With --sandbox: sinkhole (the default) records every request and lets only "
120
+ "package registries and the project's own sites through; passthrough lets "
121
+ "everything through; offline has no network at all."
122
+ ),
123
+ ),
124
+ ] = Network.sinkhole,
125
+ arch: Annotated[
126
+ Arch | None,
127
+ typer.Option(
128
+ "--arch",
129
+ case_sensitive=False,
130
+ help=(
131
+ "With --sandbox: arm64 or amd64. The default is this computer's own; amd64 on "
132
+ "Apple Silicon runs under emulation."
133
+ ),
134
+ ),
135
+ ] = None,
136
+ timeout: Annotated[
137
+ int,
138
+ typer.Option(
139
+ "--timeout",
140
+ min=10,
141
+ max=1800,
142
+ metavar="SECONDS",
143
+ help="With --sandbox: stop the dry run after this many seconds.",
144
+ ),
145
+ ] = DEFAULT_TIMEOUT,
146
+ json_output: Annotated[bool, typer.Option("--json", help="Print the report as JSON.")] = False,
147
+ report_file: Annotated[
148
+ Path | None,
149
+ typer.Option(
150
+ "--report",
151
+ metavar="FILE",
152
+ help="Also save the report as Markdown to FILE.",
153
+ dir_okay=False,
154
+ ),
155
+ ] = None,
156
+ ) -> None:
157
+ """Check a target before you run it. Nothing from the target is ever run on this computer."""
158
+ status = make_console(stderr=True)
159
+ options = SandboxOptions(
160
+ command=cmd, network=network.value, arch=arch.value if arch else None, timeout=timeout
161
+ )
162
+ if sandbox:
163
+ minutes = f"{timeout // 60} minutes" if timeout >= 120 else f"{timeout} seconds"
164
+ status.print(Text(f"Running the install in the sandbox (up to {minutes})...", style="dim"))
165
+ try:
166
+ report = run_check(
167
+ target,
168
+ sandbox=sandbox,
169
+ sandbox_options=options,
170
+ on_sandbox_build=lambda: status.print(
171
+ Text("Building the sandbox image (first time only, about a minute)...", style="dim")
172
+ ),
173
+ )
174
+ except LookfirstError as exc:
175
+ print_error(exc.message, exc.hint)
176
+ raise typer.Exit(EXIT_ERROR) from None
177
+
178
+ if report_file is not None:
179
+ try:
180
+ report_file.write_text(render_markdown(report), encoding="utf-8")
181
+ except OSError as exc:
182
+ print_error(f"Couldn't save the report to {report_file}: {exc.strerror or exc}.")
183
+ raise typer.Exit(EXIT_ERROR) from None
184
+
185
+ if json_output:
186
+ sys.stdout.write(report.model_dump_json(indent=2) + "\n")
187
+ else:
188
+ render_terminal(report, make_console())
189
+ raise typer.Exit(report.exit_code)
190
+
191
+
192
+ @app.command("update-index")
193
+ def update_index() -> None:
194
+ """Refresh lookfirst's list of popular repos from GitHub. Needs a GitHub token."""
195
+ from lookfirst.core.http import github_token, make_client
196
+ from lookfirst.identity import popular_index
197
+
198
+ token = github_token()
199
+ if not token:
200
+ print_error(
201
+ "Updating the list of popular repos needs a GitHub token.",
202
+ "Set GITHUB_TOKEN, or sign in with `gh auth login`, then try again.",
203
+ )
204
+ raise typer.Exit(EXIT_ERROR)
205
+ console = make_console(stderr=True)
206
+ console.print(
207
+ "Searching GitHub for the most-starred and fastest-rising repos (about 3 minutes)..."
208
+ )
209
+ try:
210
+ with make_client(token=token) as client:
211
+ data = popular_index.build(client)
212
+ except LookfirstError as exc:
213
+ print_error(exc.message, exc.hint)
214
+ raise typer.Exit(EXIT_ERROR) from None
215
+ path = popular_index.save_to_cache(data)
216
+ console.print(f"Saved {len(popular_index.load_index()):,} popular repos to {path}.")
217
+
218
+
219
+ @app.command("mcp")
220
+ def mcp() -> None:
221
+ """Run lookfirst as an MCP server over stdio, so a coding agent can call it."""
222
+ from lookfirst.mcp_server import main as mcp_main
223
+
224
+ mcp_main()
225
+
226
+
227
+ @app.command("hook", context_settings={"allow_extra_args": True, "ignore_unknown_options": True})
228
+ def hook() -> None:
229
+ """Claude Code's PreToolUse hook for the Bash tool. Reads the hook's JSON on stdin."""
230
+ # `lookfirst hook` normally never gets here: lookfirst/entry.py hands it off before
231
+ # Typer loads, to keep it fast. This is for --help and for running cli.py directly.
232
+ from lookfirst.hook import main as hook_main
233
+
234
+ raise typer.Exit(hook_main(()))
235
+
236
+
237
+ @sandbox_app.command("build")
238
+ def sandbox_build(
239
+ arch: Annotated[
240
+ Arch | None,
241
+ typer.Option(
242
+ "--arch", case_sensitive=False, help="arm64 or amd64 (default: this computer's)."
243
+ ),
244
+ ] = None,
245
+ ) -> None:
246
+ """Build the sandbox image and fetch the recording proxy, so --sandbox starts quickly."""
247
+ from lookfirst.sandbox import image
248
+ from lookfirst.sandbox.docker import DockerError, find_docker
249
+
250
+ docker = find_docker()
251
+ engine = docker.engine() if docker else None
252
+ if docker is None or engine is None:
253
+ print_error(
254
+ "Docker isn't installed or isn't running.",
255
+ "Install OrbStack or Docker Desktop and start it, then try again.",
256
+ )
257
+ raise typer.Exit(EXIT_ERROR)
258
+ chosen = arch.value if arch else engine[1]
259
+ console = make_console(stderr=True)
260
+ console.print(Text(f"Building the {chosen} sandbox image (about a minute)...", style="dim"))
261
+ try:
262
+ built = image.ensure_sandbox_image(docker, chosen)
263
+ image.ensure_proxy_image(docker)
264
+ except DockerError as exc:
265
+ print_error(f"The sandbox image couldn't be built: {exc}")
266
+ raise typer.Exit(EXIT_ERROR) from None
267
+ console.print(f"Ready: {image.sandbox_tag(chosen)} ({built[:19]}), and the recording proxy.")
268
+
269
+
270
+ def main(argv: Sequence[str] | None = None) -> int:
271
+ """Run the CLI and return its exit code."""
272
+ command = typer.main.get_command(app)
273
+ try:
274
+ command.main(
275
+ args=list(argv) if argv is not None else None,
276
+ prog_name="lookfirst",
277
+ standalone_mode=True,
278
+ )
279
+ except SystemExit as exc:
280
+ code = exc.code
281
+ if code is None:
282
+ return 0
283
+ if isinstance(code, int):
284
+ return EXIT_ERROR if code == _USAGE_ERROR else code
285
+ return EXIT_ERROR
286
+ except Exception as exc:
287
+ if os.environ.get("LOOKFIRST_DEBUG"):
288
+ raise
289
+ print_error(
290
+ f"Something went wrong inside lookfirst ({type(exc).__name__}). This is a bug.",
291
+ "Run again with LOOKFIRST_DEBUG=1 to see the details.",
292
+ )
293
+ return EXIT_ERROR
294
+ return 0
@@ -0,0 +1 @@
1
+ """Shared building blocks: errors, limits, HTTP, archives and safe text."""
@@ -0,0 +1,220 @@
1
+ """Unpack a downloaded archive without trusting it.
2
+
3
+ Only regular files and folders are written. Links, devices and entries that
4
+ would land outside the destination are skipped and recorded in the manifest,
5
+ so later checks can report them. Nothing unpacked is ever executable: files
6
+ are written 0644 and each file's original permissions are kept as data.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import stat
14
+ import tarfile
15
+ import zipfile
16
+ from dataclasses import dataclass, field
17
+ from pathlib import Path, PurePosixPath
18
+ from typing import IO, Literal
19
+
20
+ from lookfirst.core.config import DEFAULT_LIMITS, MB, Limits
21
+ from lookfirst.core.errors import UnsafeArchiveError
22
+
23
+ FILE_MODE = 0o644
24
+ _CHUNK = 1024 * 1024
25
+ _DRIVE = re.compile(r"^[A-Za-z]:$")
26
+ _MAX_NAME_IN_MANIFEST = 300
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class ArchiveFile:
31
+ path: str # relative POSIX path inside the archive
32
+ size: int
33
+ mode: int # permission bits recorded in the archive (not applied on disk)
34
+
35
+ @property
36
+ def executable(self) -> bool:
37
+ return bool(self.mode & 0o111)
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class ArchiveLink:
42
+ path: str
43
+ target: str
44
+ kind: Literal["symlink", "hardlink"]
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class SkippedEntry:
49
+ path: str
50
+ reason: str
51
+
52
+
53
+ @dataclass
54
+ class ArchiveManifest:
55
+ files: list[ArchiveFile] = field(default_factory=list)
56
+ links: list[ArchiveLink] = field(default_factory=list)
57
+ skipped: list[SkippedEntry] = field(default_factory=list)
58
+ total_bytes: int = 0
59
+ root: str = "" # the single top-level folder, if everything was inside one
60
+ _entries: int = field(default=0, repr=False)
61
+ _by_casefold: dict[str, str] = field(default_factory=dict, repr=False)
62
+ _file_index: dict[str, int] = field(default_factory=dict, repr=False)
63
+
64
+ def skip(self, name: str, reason: str) -> None:
65
+ self.skipped.append(SkippedEntry(name[:_MAX_NAME_IN_MANIFEST], reason))
66
+
67
+
68
+ def safe_relpath(name: str) -> str | None:
69
+ """Return a clean relative POSIX path for an archive entry, or None if it's unsafe."""
70
+ if not name or "\x00" in name:
71
+ return None
72
+ if name.startswith("/"):
73
+ return None
74
+ parts = [p for p in PurePosixPath(name).parts if p not in ("", ".")]
75
+ if not parts or ".." in parts or _DRIVE.match(parts[0]):
76
+ return None
77
+ return "/".join(parts)
78
+
79
+
80
+ def unpack(archive: Path, dest: Path, *, limits: Limits = DEFAULT_LIMITS) -> ArchiveManifest:
81
+ """Unpack a zip, tar, tar.gz or other compressed tar into dest."""
82
+ dest.mkdir(parents=True, exist_ok=True)
83
+ if zipfile.is_zipfile(archive):
84
+ manifest = _unpack_zip(archive, dest, limits)
85
+ elif _is_tar(archive):
86
+ manifest = _unpack_tar(archive, dest, limits)
87
+ else:
88
+ raise UnsafeArchiveError(
89
+ "The download isn't a zip or tar archive, so lookfirst can't read it."
90
+ )
91
+ manifest.root = _single_root(manifest)
92
+ return manifest
93
+
94
+
95
+ def _is_tar(archive: Path) -> bool:
96
+ try:
97
+ return tarfile.is_tarfile(archive)
98
+ except (OSError, tarfile.TarError, EOFError):
99
+ return False
100
+
101
+
102
+ def _count(manifest: ArchiveManifest, limits: Limits) -> None:
103
+ manifest._entries += 1
104
+ if manifest._entries > limits.max_entries:
105
+ raise UnsafeArchiveError(
106
+ f"The archive has more than {limits.max_entries:,} entries, "
107
+ "so lookfirst stopped unpacking it."
108
+ )
109
+
110
+
111
+ def _make_dir(dest: Path, rel: str, manifest: ArchiveManifest) -> None:
112
+ try:
113
+ dest.joinpath(*rel.split("/")).mkdir(parents=True, exist_ok=True)
114
+ except OSError:
115
+ manifest.skip(rel, "clashes with a file of the same name")
116
+
117
+
118
+ def _write_file(
119
+ dest: Path, rel: str, source: IO[bytes], mode: int, manifest: ArchiveManifest, limits: Limits
120
+ ) -> None:
121
+ other = manifest._by_casefold.get(rel.casefold())
122
+ if other is not None and other != rel:
123
+ # On a Mac's default disk these two names would be the same file.
124
+ manifest.skip(rel, f"name differs from {other[:_MAX_NAME_IN_MANIFEST]} only in letter case")
125
+ return
126
+ target = dest.joinpath(*rel.split("/"))
127
+ try:
128
+ target.parent.mkdir(parents=True, exist_ok=True)
129
+ fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_TRUNC | os.O_NOFOLLOW, FILE_MODE)
130
+ except OSError:
131
+ manifest.skip(rel, "clashes with a folder or file of the same name")
132
+ return
133
+ size = 0
134
+ with os.fdopen(fd, "wb") as out:
135
+ while chunk := source.read(_CHUNK):
136
+ size += len(chunk)
137
+ manifest.total_bytes += len(chunk)
138
+ if manifest.total_bytes > limits.max_unpacked_bytes:
139
+ raise UnsafeArchiveError(
140
+ f"The archive unpacks to more than {limits.max_unpacked_bytes // MB} MB, "
141
+ "so lookfirst stopped unpacking it."
142
+ )
143
+ out.write(chunk)
144
+ entry = ArchiveFile(path=rel, size=size, mode=mode & 0o7777)
145
+ manifest._by_casefold[rel.casefold()] = rel
146
+ if rel in manifest._file_index: # the same name twice: the later copy wins, as with tar
147
+ manifest.files[manifest._file_index[rel]] = entry
148
+ else:
149
+ manifest._file_index[rel] = len(manifest.files)
150
+ manifest.files.append(entry)
151
+
152
+
153
+ def _unpack_tar(archive: Path, dest: Path, limits: Limits) -> ArchiveManifest:
154
+ manifest = ArchiveManifest()
155
+ try:
156
+ with tarfile.open(archive, mode="r:*") as tar:
157
+ for member in tar:
158
+ _count(manifest, limits)
159
+ rel = safe_relpath(member.name)
160
+ if rel is None:
161
+ manifest.skip(member.name, "path points outside the archive's folder")
162
+ elif member.issym():
163
+ manifest.links.append(ArchiveLink(rel, member.linkname, "symlink"))
164
+ elif member.islnk():
165
+ manifest.links.append(ArchiveLink(rel, member.linkname, "hardlink"))
166
+ elif member.isdir():
167
+ _make_dir(dest, rel, manifest)
168
+ elif not member.isfile():
169
+ manifest.skip(rel, "not a regular file (a device, pipe or other special file)")
170
+ else:
171
+ source = tar.extractfile(member)
172
+ if source is None:
173
+ manifest.skip(rel, "couldn't be read from the archive")
174
+ continue
175
+ with source:
176
+ _write_file(dest, rel, source, member.mode, manifest, limits)
177
+ except (tarfile.TarError, EOFError, OSError) as exc:
178
+ raise UnsafeArchiveError(
179
+ "The archive is damaged or in a format lookfirst can't read."
180
+ ) from exc
181
+ return manifest
182
+
183
+
184
+ def _unpack_zip(archive: Path, dest: Path, limits: Limits) -> ArchiveManifest:
185
+ manifest = ArchiveManifest()
186
+ try:
187
+ with zipfile.ZipFile(archive) as zf:
188
+ for info in zf.infolist():
189
+ _count(manifest, limits)
190
+ # Zip files made on Windows may use backslashes as folder separators.
191
+ rel = safe_relpath(info.filename.replace("\\", "/"))
192
+ unix_mode = (info.external_attr >> 16) & 0xFFFF
193
+ if rel is None:
194
+ manifest.skip(info.filename, "path points outside the archive's folder")
195
+ elif stat.S_ISLNK(unix_mode):
196
+ with zf.open(info) as source:
197
+ link_target = source.read(4096).decode("utf-8", "replace")
198
+ manifest.links.append(ArchiveLink(rel, link_target, "symlink"))
199
+ elif info.is_dir():
200
+ _make_dir(dest, rel, manifest)
201
+ elif info.flag_bits & 0x1:
202
+ manifest.skip(rel, "encrypted, so it can't be read")
203
+ elif stat.S_IFMT(unix_mode) not in (0, stat.S_IFREG):
204
+ manifest.skip(rel, "not a regular file (a device, pipe or other special file)")
205
+ else:
206
+ with zf.open(info) as source:
207
+ _write_file(dest, rel, source, unix_mode or FILE_MODE, manifest, limits)
208
+ except (zipfile.BadZipFile, NotImplementedError, RuntimeError, EOFError, OSError) as exc:
209
+ raise UnsafeArchiveError(
210
+ "The archive is damaged or in a format lookfirst can't read."
211
+ ) from exc
212
+ return manifest
213
+
214
+
215
+ def _single_root(manifest: ArchiveManifest) -> str:
216
+ tops = {f.path.split("/", 1)[0] for f in manifest.files if "/" in f.path}
217
+ loose = [f for f in manifest.files if "/" not in f.path]
218
+ if len(tops) == 1 and not loose:
219
+ return tops.pop()
220
+ return ""
@@ -0,0 +1,28 @@
1
+ """Limits that keep a hostile target from filling the disk or memory, and where lookfirst
2
+ keeps its cache."""
3
+
4
+ import os
5
+ from dataclasses import dataclass
6
+ from pathlib import Path
7
+
8
+ MB = 1024 * 1024
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Limits:
13
+ max_download_bytes: int = 200 * MB
14
+ max_json_bytes: int = 20 * MB
15
+ max_unpacked_bytes: int = 1024 * MB
16
+ max_entries: int = 50_000
17
+ http_timeout_s: float = 30.0
18
+ max_redirects: int = 5
19
+
20
+
21
+ DEFAULT_LIMITS = Limits()
22
+
23
+
24
+ def cache_dir() -> Path:
25
+ """Where lookfirst caches GitHub answers and the popular-repos list.
26
+ Set LOOKFIRST_CACHE_DIR to move it."""
27
+ override = os.environ.get("LOOKFIRST_CACHE_DIR")
28
+ return Path(override).expanduser() if override else Path.home() / ".cache" / "lookfirst"
@@ -0,0 +1,26 @@
1
+ """Errors that lookfirst can explain to the user in plain English."""
2
+
3
+
4
+ class LookfirstError(Exception):
5
+ """A problem with a plain-English message, and optionally a hint for what to do."""
6
+
7
+ def __init__(self, message: str, *, hint: str | None = None) -> None:
8
+ super().__init__(message)
9
+ self.message = message
10
+ self.hint = hint
11
+
12
+
13
+ class TargetError(LookfirstError):
14
+ """We couldn't understand or find the target."""
15
+
16
+
17
+ class FetchError(LookfirstError):
18
+ """We couldn't download the target or its details."""
19
+
20
+
21
+ class UnsafeArchiveError(LookfirstError):
22
+ """An archive was too big or too damaged to unpack safely."""
23
+
24
+
25
+ class CouldntCheckError(LookfirstError):
26
+ """The main thing to check couldn't be read, so no verdict would mean anything."""