itqan-cli 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.
@@ -0,0 +1,91 @@
1
+ """API keys saved by `itqan login`, one per registry URL.
2
+
3
+ Keys live in ``<config dir>/credentials`` (JSON), readable only by the owner.
4
+ The config dir is ``$ITQAN_CONFIG_DIR``, else ``%APPDATA%\\itqan`` on Windows,
5
+ else ``$XDG_CONFIG_HOME/itqan`` or ``~/.config/itqan``. Keys are stored per
6
+ registry so a production key is never sent to a staging or local registry.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+ import sys
15
+ import tempfile
16
+
17
+ from itqan_cli.exceptions import ItqanCliError
18
+
19
+
20
+ class CredentialsError(ItqanCliError):
21
+ """The credentials file can't be read or written."""
22
+
23
+
24
+ def config_dir() -> Path:
25
+ if override := os.environ.get("ITQAN_CONFIG_DIR"):
26
+ return Path(override)
27
+ if sys.platform == "win32" and os.environ.get("APPDATA"):
28
+ return Path(os.environ["APPDATA"]) / "itqan"
29
+ base = os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config"
30
+ return Path(base) / "itqan"
31
+
32
+
33
+ def credentials_path() -> Path:
34
+ return config_dir() / "credentials"
35
+
36
+
37
+ def _registry_key(registry_url: str) -> str:
38
+ return registry_url.rstrip("/")
39
+
40
+
41
+ def _read() -> dict:
42
+ path = credentials_path()
43
+ if not path.exists():
44
+ return {}
45
+ try:
46
+ data = json.loads(path.read_text(encoding="utf-8"))
47
+ except (OSError, ValueError) as exc:
48
+ raise CredentialsError(f"Could not read {path}: {exc}") from exc
49
+ if not isinstance(data, dict) or not isinstance(data.get("registries", {}), dict):
50
+ raise CredentialsError(f"{path} is not a valid credentials file; delete it and run `itqan login` again.")
51
+ return data
52
+
53
+
54
+ def _write(data: dict) -> None:
55
+ """Replace the file atomically, created with owner-only permissions."""
56
+ path = credentials_path()
57
+ try:
58
+ path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
59
+ fd, tmp = tempfile.mkstemp(prefix=".credentials_", dir=path.parent) # mkstemp creates it 0600
60
+ try:
61
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
62
+ json.dump(data, f, indent=2)
63
+ os.replace(tmp, path)
64
+ except BaseException:
65
+ Path(tmp).unlink(missing_ok=True)
66
+ raise
67
+ except OSError as exc:
68
+ raise CredentialsError(f"Could not write {path}: {exc}") from exc
69
+
70
+
71
+ def load_api_key(registry_url: str) -> str | None:
72
+ """The key saved for ``registry_url``, or None."""
73
+ entry = _read().get("registries", {}).get(_registry_key(registry_url))
74
+ key = entry.get("api_key") if isinstance(entry, dict) else None
75
+ return key if isinstance(key, str) and key else None
76
+
77
+
78
+ def save_api_key(registry_url: str, api_key: str) -> Path:
79
+ data = _read()
80
+ data.setdefault("registries", {})[_registry_key(registry_url)] = {"api_key": api_key}
81
+ _write(data)
82
+ return credentials_path()
83
+
84
+
85
+ def delete_api_key(registry_url: str) -> bool:
86
+ """Forget the key for ``registry_url``; False when none was saved."""
87
+ data = _read()
88
+ if data.get("registries", {}).pop(_registry_key(registry_url), None) is None:
89
+ return False
90
+ _write(data)
91
+ return True
@@ -0,0 +1,220 @@
1
+ """Downloader and artifact materializer ensuring idempotency and atomic writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ import os
7
+ from pathlib import Path
8
+ import tempfile
9
+ import urllib.parse
10
+
11
+ import requests
12
+
13
+ from itqan_cli.client import ResolvedAssetPayload
14
+ from itqan_cli.exceptions import DownloadError
15
+
16
+ # The version marker filename is reserved — a download URL must never produce
17
+ # a basename matching this name, or it would silently overwrite version metadata.
18
+ _RESERVED_FILENAME = ".itqan_version"
19
+
20
+
21
+ def _validate_slug(slug: str) -> None:
22
+ """Reject slugs that could escape the assets directory via path traversal.
23
+
24
+ A valid slug is a single path component with no separators or traversal
25
+ sequences. Examples that are rejected: '../etc', 'foo/bar', 'a\\b'.
26
+
27
+ Why this matters: if asset.slug came from an untrusted source and contained
28
+ '../../../etc/passwd', the path join `assets_dir / slug` would resolve
29
+ outside the assets directory, allowing arbitrary file writes on the system.
30
+ """
31
+ if not slug or not slug.strip():
32
+ raise DownloadError("Asset slug cannot be empty.")
33
+ # Reject any separator or traversal component
34
+ forbidden = {"/", "\\", ".."}
35
+ for part in forbidden:
36
+ if part in slug:
37
+ raise DownloadError(
38
+ f"Asset slug '{slug}' contains forbidden path component '{part}'. "
39
+ "Slugs must be single safe path components."
40
+ )
41
+ # Path(slug).name must equal slug — catches edge cases like 'a/b' on Windows
42
+ if Path(slug).name != slug:
43
+ raise DownloadError(f"Asset slug '{slug}' is not a safe single path component.")
44
+
45
+
46
+ def _validate_download_url(url: str, slug: str) -> None:
47
+ """Reject non-HTTPS download URLs for non-loopback hosts.
48
+
49
+ Why this matters: downloading over HTTP exposes the artifact to
50
+ man-in-the-middle attacks — an attacker on the network could replace
51
+ the downloaded file with malicious content before it reaches the disk.
52
+ Loopback addresses (localhost, 127.x.x.x) are allowed for development.
53
+ """
54
+ parsed = urllib.parse.urlparse(url)
55
+ is_loopback = parsed.hostname in ("localhost", "127.0.0.1", "::1") or (
56
+ parsed.hostname is not None and parsed.hostname.startswith("127.")
57
+ )
58
+ if parsed.scheme == "http" and not is_loopback:
59
+ raise DownloadError(
60
+ f"Refusing to download asset '{slug}' over insecure HTTP from {url}. "
61
+ "Use HTTPS or a loopback address for development."
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True, slots=True)
66
+ class DownloadResult:
67
+ slug: str
68
+ version: str
69
+ target_path: Path
70
+ downloaded: bool
71
+ size_bytes: int
72
+
73
+
74
+ class AssetDownloader:
75
+ """Handles streaming download and atomic materialization of asset packages."""
76
+
77
+ def __init__(
78
+ self,
79
+ assets_dir: Path | str = "assets",
80
+ session: requests.Session | None = None,
81
+ timeout: float = 60.0,
82
+ ) -> None:
83
+ self.assets_dir = Path(assets_dir)
84
+ self.session = session or requests.Session()
85
+ self.timeout = timeout
86
+
87
+ def _determine_target_file(self, asset: ResolvedAssetPayload, target_dir: Path) -> Path:
88
+ """Derive filename from download_url or fall back to slug.pkg.
89
+
90
+ The reserved filename '.itqan_version' is rejected — if a URL's basename
91
+ collides with the version marker we use internally, it would silently
92
+ overwrite version metadata and break idempotency checks.
93
+ """
94
+ if asset.download_url:
95
+ parsed = urllib.parse.urlparse(asset.download_url)
96
+ filename = Path(parsed.path).name
97
+ if filename:
98
+ if filename == _RESERVED_FILENAME:
99
+ raise DownloadError(
100
+ f"Download URL for asset '{asset.slug}' has a reserved filename "
101
+ f"'{_RESERVED_FILENAME}'. This name is used internally by the CLI."
102
+ )
103
+ return target_dir / filename
104
+ return target_dir / f"{asset.slug}.pkg"
105
+
106
+ def materialize_asset(
107
+ self,
108
+ asset: ResolvedAssetPayload,
109
+ *,
110
+ force: bool = False,
111
+ ) -> DownloadResult:
112
+ """Materialize a single resolved asset into the assets/<entry name>/ folder.
113
+
114
+ The folder is named after the manifest entry, so two languages of one
115
+ asset (two entries) install side by side.
116
+
117
+ Ensures:
118
+ - Safety: slug is validated against path traversal before any I/O.
119
+ - Idempotency: skip if already present and non-empty.
120
+ - Atomicity: stream to temp file and rename upon success.
121
+ - Marker atomicity: version marker is staged as a temp file then
122
+ renamed — both the artifact and its marker are committed together
123
+ so a power loss between the two writes cannot leave a stale marker.
124
+ """
125
+ # --- Safety: validate slug before any path join ---
126
+ _validate_slug(asset.entry_name)
127
+
128
+ slug_dir = self.assets_dir / asset.entry_name
129
+ slug_dir.mkdir(parents=True, exist_ok=True)
130
+
131
+ target_file = self._determine_target_file(asset, slug_dir)
132
+
133
+ # Version marker file to ensure version integrity
134
+ version_marker = slug_dir / _RESERVED_FILENAME
135
+
136
+ # Idempotency check: if target file and matching version marker exist
137
+ if not force and target_file.is_file() and target_file.stat().st_size > 0:
138
+ if (
139
+ version_marker.is_file()
140
+ and version_marker.read_text(encoding="utf-8").strip() == asset.resolved_version
141
+ ):
142
+ return DownloadResult(
143
+ slug=asset.entry_name,
144
+ version=asset.resolved_version,
145
+ target_path=target_file,
146
+ downloaded=False,
147
+ size_bytes=target_file.stat().st_size,
148
+ )
149
+
150
+ if not asset.download_url:
151
+ raise DownloadError(
152
+ f"Asset '{asset.slug}' (version {asset.resolved_version}) has no download URL in the catalog."
153
+ )
154
+
155
+ # --- Security: validate download URL before connecting ---
156
+ _validate_download_url(asset.download_url, asset.slug)
157
+
158
+ # Download atomically to a temporary file in the same filesystem
159
+ temp_fd, temp_path_str = tempfile.mkstemp(
160
+ prefix=f"{asset.slug}_",
161
+ suffix=".tmp",
162
+ dir=slug_dir,
163
+ )
164
+ temp_file = Path(temp_path_str)
165
+
166
+ # Also stage the version marker as a temp file so both are committed
167
+ # in a single rename sequence — prevents a torn state if the process
168
+ # dies between writing the artifact and writing the marker.
169
+ marker_fd, marker_tmp_str = tempfile.mkstemp(
170
+ prefix=".itqan_version_",
171
+ suffix=".tmp",
172
+ dir=slug_dir,
173
+ )
174
+ # Close the marker fd immediately — we will re-open it for writing
175
+ # inside the try block. Keeping it open here would prevent deletion
176
+ # on Windows if an exception occurs before we reach the cleanup block.
177
+ os.close(marker_fd)
178
+ marker_tmp = Path(marker_tmp_str)
179
+
180
+ try:
181
+ with open(temp_fd, "wb") as f_out:
182
+ with self.session.get(asset.download_url, stream=True, timeout=self.timeout) as resp:
183
+ if resp.status_code != 200:
184
+ raise DownloadError(
185
+ f"Failed to download '{asset.slug}' from {asset.download_url}: HTTP {resp.status_code}"
186
+ )
187
+ for chunk in resp.iter_content(chunk_size=65536):
188
+ if chunk:
189
+ f_out.write(chunk)
190
+
191
+ # Write version string to the staged marker tmp file
192
+ marker_tmp.write_text(asset.resolved_version, encoding="utf-8")
193
+
194
+ # Atomically promote both: marker first, then artifact.
195
+ # os.replace() is atomic on POSIX and best-effort on Windows.
196
+ # If the artifact rename fails the marker is already in place, but
197
+ # the idempotency check requires BOTH to exist and match, so the
198
+ # next run will re-download correctly.
199
+ os.replace(marker_tmp, version_marker)
200
+ os.replace(temp_file, target_file)
201
+
202
+ return DownloadResult(
203
+ slug=asset.entry_name,
204
+ version=asset.resolved_version,
205
+ target_path=target_file,
206
+ downloaded=True,
207
+ size_bytes=target_file.stat().st_size,
208
+ )
209
+
210
+ except Exception as exc:
211
+ # Clean up temp files on failure — never leave partial artifacts
212
+ for tmp in (temp_file, marker_tmp):
213
+ try:
214
+ if tmp.exists():
215
+ tmp.unlink()
216
+ except OSError:
217
+ pass
218
+ if isinstance(exc, DownloadError):
219
+ raise
220
+ raise DownloadError(f"Error downloading asset '{asset.slug}': {exc}") from exc
@@ -0,0 +1,69 @@
1
+ """CLI exceptions adhering to docs/ASSET_MANIFEST.md error taxonomy."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class ItqanCliError(Exception):
7
+ """Base exception for all Itqan CLI errors."""
8
+
9
+ def __init__(self, message: str, *, exit_code: int = 1) -> None:
10
+ super().__init__(message)
11
+ self.message = message
12
+ self.exit_code = exit_code
13
+
14
+
15
+ class ManifestError(ItqanCliError):
16
+ """Base exception for manifest parsing/validation failures."""
17
+
18
+
19
+ class UnsupportedSchemaVersionError(ManifestError):
20
+ """schema_version is missing or not 1."""
21
+
22
+
23
+ class YamlProfileViolationError(ManifestError):
24
+ """YAML violates the strict profile (BOM, duplicate keys, multiple docs, etc.)."""
25
+
26
+
27
+ class ScalarShorthandEntryError(ManifestError):
28
+ """An entry under assets is a scalar instead of a mapping."""
29
+
30
+
31
+ class NonStringAssetKeyError(ManifestError):
32
+ """An asset key resolves to a non-string scalar (bool, int, float)."""
33
+
34
+
35
+ class UnknownFieldError(ManifestError):
36
+ """Any key outside the accepted schema."""
37
+
38
+
39
+ class MissingRequiredFieldError(ManifestError):
40
+ """An entry has no required 'version' field."""
41
+
42
+
43
+ class InvalidConstraintSyntaxError(ManifestError):
44
+ """Constraint string violates the SemVer grammar."""
45
+
46
+
47
+ class DuplicateAssetEntryError(ManifestError):
48
+ """Two entries name the same asset and language."""
49
+
50
+
51
+ class LockfileError(ItqanCliError):
52
+ """Base exception for lockfile operations."""
53
+
54
+
55
+ class LockfileStateError(LockfileError):
56
+ """Lockfile is in an unexpected or invalid state."""
57
+
58
+
59
+ class RegistryApiError(ItqanCliError):
60
+ """Error communicating with the Package Registry API."""
61
+
62
+ def __init__(self, message: str, *, status_code: int | None = None, error_name: str | None = None) -> None:
63
+ super().__init__(message)
64
+ self.status_code = status_code
65
+ self.error_name = error_name
66
+
67
+
68
+ class DownloadError(ItqanCliError):
69
+ """Error downloading or verifying an asset artifact."""
@@ -0,0 +1,118 @@
1
+ """Text of the starter itqan-assets.yaml written by `itqan init`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+
7
+ from itqan_cli.client import CatalogLanguage, CatalogPackage
8
+ from itqan_cli.semver import parse_semver
9
+
10
+ SAMPLE_COUNT = 3
11
+
12
+ _HEADER = """\
13
+ # Itqan assets manifest: the Quranic data this project uses.
14
+ # Spec: https://github.com/Itqan-community/cms-backend/blob/main/docs/ASSET_MANIFEST.md
15
+ #
16
+ # After editing, run `itqan install` to download the assets and write
17
+ # itqan-assets.lock. Commit both files.
18
+
19
+ schema_version: 1
20
+
21
+ # Folder the assets are downloaded into, relative to this file.
22
+ assets_dir: {assets_dir}
23
+
24
+ # Each entry is a name (the asset's slug, unless the entry sets `asset`) and a
25
+ # version range:
26
+ # "^1.2.0" any 1.x from 1.2.0 on "~1.2" any 1.2.x "1.2.0" exactly 1.2.0
27
+ #
28
+ # Languages: an entry installs the asset's source language. Add
29
+ # `language: <code>` to install another one. To install several languages of
30
+ # the same asset, give each its own entry and point it at the asset with
31
+ # `asset: <slug>`. Each language has its own version history.
32
+ assets:
33
+ """
34
+
35
+ _FALLBACK_ENTRIES = """\
36
+ # {reason} so these are examples: replace the slugs with real ones
37
+ # from the asset library at https://cms.itqan.dev, then uncomment.
38
+ #
39
+ # "tafsir-example":
40
+ # version: "^1.0.0"
41
+ #
42
+ # The same asset in English:
43
+ # "tafsir-example-en":
44
+ # asset: "tafsir-example"
45
+ # language: "en"
46
+ # version: "^1.0.0"
47
+ """
48
+
49
+
50
+ def _quote(value: str) -> str:
51
+ """YAML double-quoted scalar; slugs like `true` or `123` must stay strings."""
52
+ return json.dumps(value, ensure_ascii=False)
53
+
54
+
55
+ def _constraint(version: str) -> str:
56
+ """`^latest`, except a prerelease, which only an exact pin can select."""
57
+ semver = parse_semver(version)
58
+ return version if semver is not None and semver.prerelease is not None else f"^{version}"
59
+
60
+
61
+ def _describe(language: CatalogLanguage) -> str:
62
+ if not language.language: # an asset whose source language code was never set
63
+ return f"source ({language.latest_version})"
64
+ source = "source, " if language.is_source else ""
65
+ return f"{language.language} ({source}{language.latest_version})"
66
+
67
+
68
+ def entry_lines(
69
+ name: str, version: str, *, asset: str | None = None, language: str | None = None, indent: str = " "
70
+ ) -> list[str]:
71
+ """One manifest entry under `assets:`, constrained to ``^version``; ``indent``
72
+ is the entry key's indentation, and its fields go one level deeper."""
73
+ lines = [f"{indent}{_quote(name)}:"]
74
+ if asset is not None:
75
+ lines.append(f"{indent * 2}asset: {_quote(asset)}")
76
+ if language is not None:
77
+ lines.append(f"{indent * 2}language: {_quote(language)}")
78
+ lines.append(f"{indent * 2}version: {_quote(_constraint(version))}")
79
+ return lines
80
+
81
+
82
+ def render_header(assets_dir: str) -> str:
83
+ """The starter file up to and including `assets:`, with no entries."""
84
+ return _HEADER.format(assets_dir=_quote(assets_dir))
85
+
86
+
87
+ def pick_samples(packages: list[CatalogPackage], count: int = SAMPLE_COUNT) -> list[CatalogPackage]:
88
+ """Up to ``count`` packages, leading with one that has several languages so
89
+ the starter file shows a second-language entry."""
90
+ usable = [package for package in packages if package.languages]
91
+ multilingual = next((package for package in usable if len(package.languages) > 1), None)
92
+ ordered = ([multilingual] if multilingual else []) + [package for package in usable if package is not multilingual]
93
+ return ordered[:count]
94
+
95
+
96
+ def render_from_catalog(samples: list[CatalogPackage], assets_dir: str) -> str:
97
+ lines: list[str] = []
98
+ names: set[str] = set()
99
+ for package in samples:
100
+ if lines:
101
+ lines.append("")
102
+ name = " ".join(package.name.split()) # one line, even if the name has newlines
103
+ lines.append(f" # {name} — languages: {', '.join(_describe(lang) for lang in package.languages)}")
104
+ source = next((lang for lang in package.languages if lang.is_source), None)
105
+ first = source or package.languages[0]
106
+ lines += entry_lines(package.slug, first.latest_version, language=None if source else first.language)
107
+ names.add(package.slug)
108
+ other = next((lang for lang in package.languages if lang is not first), None)
109
+ entry_name = f"{package.slug}-{other.language}" if other else None
110
+ if other is not None and entry_name not in names:
111
+ lines.append(f" # The same asset in another language ({other.language}):")
112
+ lines += entry_lines(entry_name, other.latest_version, asset=package.slug, language=other.language)
113
+ names.add(entry_name)
114
+ return render_header(assets_dir) + "\n".join(lines) + "\n"
115
+
116
+
117
+ def render_fallback(assets_dir: str, reason: str) -> str:
118
+ return render_header(assets_dir) + _FALLBACK_ENTRIES.format(reason=reason)