qodalis-cli-server-plugin-portal 1.0.0b29__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,18 @@
1
+ """Qodalis CLI portal plugin — the prebuilt portal site
2
+ (``@qodalis/cli-server-portal``) at one mount, with ``portal.json``: the
3
+ guides of the docs plugin and the API reference of the public-api plugin."""
4
+
5
+ from __future__ import annotations
6
+
7
+ #: The package's icon on the admin dashboard's plugins page (``CliInstalledPlugin.icon``).
8
+ __plugin_icon__ = "🧭"
9
+
10
+ from .cli_portal_builder import DEFAULT_PATH, CliPortalBuilder, CliPortalPlugin
11
+ from .site_resolver import resolve_site_dir
12
+
13
+ __all__ = [
14
+ "CliPortalBuilder",
15
+ "CliPortalPlugin",
16
+ "DEFAULT_PATH",
17
+ "resolve_site_dir",
18
+ ]
@@ -0,0 +1,286 @@
1
+ """Fluent builder for the portal plugin.
2
+
3
+ Usage::
4
+
5
+ portal = (
6
+ CliPortalBuilder()
7
+ .set_name("RateBell API")
8
+ .add_footer_link("Terms", "https://ratebell.app/terms")
9
+ .add_section(docs_plugin)
10
+ .add_section(public_api_plugin)
11
+ .build()
12
+ )
13
+ result.mount_plugin(portal)
14
+
15
+ The portal answers only its own paths under the mount (the site's pages,
16
+ ``portal.json``, ``assets/<file>``, ``favicon.svg``; GET and HEAD), so even at
17
+ ``/`` it never shadows the host's routes.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import html
23
+ import logging
24
+ import os
25
+ import re
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Callable, Optional
28
+
29
+ from fastapi import APIRouter, Request
30
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
31
+ from fastapi.routing import APIRoute
32
+ from starlette.routing import Match
33
+
34
+ from .options import (
35
+ validate_footer_links,
36
+ validate_logo,
37
+ validate_name,
38
+ validate_path,
39
+ validate_theme,
40
+ )
41
+ from .site_resolver import resolve_site_dir
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ DEFAULT_PATH = "/qcli/portal"
46
+ DEFAULT_NAME = "Documentation"
47
+ SITE_NOT_FOUND = "[qcli] portal site not found; the portal is not served"
48
+ INVALID_PATH_BASE = "invalid path base"
49
+ SECTION_KINDS = ("docs", "api")
50
+ BASE_TAG = '<base href="/" />'
51
+ _NO_CACHE = {"Cache-Control": "no-cache"}
52
+ JSON_TYPE = "application/json; charset=utf-8"
53
+ _IMMUTABLE = {"Cache-Control": "public, max-age=31536000, immutable"}
54
+ _ASSET_NAME = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9._-]*$")
55
+ _METHODS = ("GET", "HEAD")
56
+
57
+
58
+ class _PortalRoute(APIRoute):
59
+ """A route that matches GET and HEAD only, and (for files) only when the
60
+ file exists, so anything else falls through to the host's routes and
61
+ the framework's 404."""
62
+
63
+ #: ``(path_params) -> bool``: whether the route serves this request.
64
+ serves: Optional[Callable[[dict[str, Any]], bool]] = None
65
+
66
+ def matches(self, scope: Any) -> tuple[Match, dict[str, Any]]:
67
+ match, child = super().matches(scope)
68
+ if match == Match.NONE:
69
+ return match, child
70
+ if scope.get("method") not in _METHODS:
71
+ return Match.NONE, {}
72
+ serves = type(self).serves
73
+ if serves is not None and not serves(child.get("path_params", {})):
74
+ return Match.NONE, {}
75
+ return match, child
76
+
77
+
78
+ def _route_class(serves: Callable[[dict[str, Any]], bool] | None = None) -> type[_PortalRoute]:
79
+ # A class per condition: include_router re-creates routes from their class.
80
+ return type("PortalRoute", (_PortalRoute,), {"serves": staticmethod(serves) if serves else None})
81
+
82
+
83
+ def _path_base(request: Request) -> str | None:
84
+ """The app's root path, or ``None`` when it could make a URL leave the
85
+ host: ``//`` or ``/\\``, or whitespace / control characters (browsers drop
86
+ them, so ``/<tab>/evil`` becomes ``//evil``)."""
87
+ root = request.scope.get("root_path", "") or ""
88
+ if root.startswith("//") or root.startswith("/\\") or any(c.isspace() or ord(c) < 0x20 or 0x7F <= ord(c) <= 0x9F for c in root):
89
+ return None
90
+ return root.rstrip("/")
91
+
92
+
93
+ @dataclass
94
+ class CliPortalPlugin:
95
+ """The built portal plugin: mount it with ``CliServerResult.mount_plugin``."""
96
+
97
+ #: The mount (``/`` allowed).
98
+ prefix: str
99
+ router: APIRouter
100
+ #: ``portal.json`` without a path base.
101
+ document: dict[str, Any]
102
+ #: The site's directory, ``None`` when no site was found (nothing served).
103
+ site_dir: Optional[str] = None
104
+ #: Host routes: never counted among the CLI's routes.
105
+ cli_routes: bool = False
106
+ #: Served without sign-in (GET and HEAD), also under ``/api/`` on a
107
+ #: protected server; under them the portal answers every path itself.
108
+ #: Empty at ``/`` (never under ``/api/``) and without a site.
109
+ public_paths: list[str] = field(default_factory=list)
110
+ _index: Optional[str] = field(default=None, repr=False)
111
+
112
+ def portal_json(self, root: str) -> dict[str, Any]:
113
+ doc = dict(self.document)
114
+ if doc.get("docs"):
115
+ doc["docs"] = {**doc["docs"], "pages": root + doc["docs"]["pages"]}
116
+ if doc.get("api"):
117
+ api = doc["api"]
118
+ doc["api"] = {**api, "openapi": root + api["openapi"], "swagger": root + api["swagger"]}
119
+ return doc
120
+
121
+ def index_html(self, root: str) -> str:
122
+ mount = "" if self.prefix == "/" else self.prefix
123
+ href = html.escape(f"{root}{mount}/", quote=True)
124
+ return (self._index or "").replace(BASE_TAG, f'<base href="{href}" />', 1)
125
+
126
+
127
+ class CliPortalBuilder:
128
+ """Fluent builder for the portal plugin. Everything is checked by
129
+ :meth:`build` (``ValueError``)."""
130
+
131
+ def __init__(self) -> None:
132
+ self._path: Any = DEFAULT_PATH
133
+ self._name: Any = DEFAULT_NAME
134
+ self._logo: Any = None
135
+ self._theme: Any = None
136
+ self._links: list[tuple[Any, Any]] = []
137
+ self._sections: list[Any] = []
138
+ self._site_dir: str | None = None
139
+
140
+ def set_path(self, path: str) -> CliPortalBuilder:
141
+ """The mount (default ``/qcli/portal``; ``/`` allowed)."""
142
+ self._path = path
143
+ return self
144
+
145
+ def set_name(self, name: str) -> CliPortalBuilder:
146
+ """The portal's name (default ``Documentation``): 1-80 characters."""
147
+ self._name = name
148
+ return self
149
+
150
+ def set_logo_url(self, url: str | None) -> CliPortalBuilder:
151
+ """An http(s) URL, a root-relative path or a base64 ``data:image`` URL."""
152
+ self._logo = url
153
+ return self
154
+
155
+ def set_theme(self, theme: dict[str, Any] | None) -> CliPortalBuilder:
156
+ """``{"mode": "dark" | "light" | "system", "dark": {...}, "light":
157
+ {...}}`` with the dashboard's colour tokens (camelCase or
158
+ snake_case); the mode defaults to ``system``."""
159
+ self._theme = theme
160
+ return self
161
+
162
+ def add_footer_link(self, label: str, url: str) -> CliPortalBuilder:
163
+ """A footer link (at most 20): an http(s) URL or a root-relative path."""
164
+ self._links.append((label, url))
165
+ return self
166
+
167
+ def add_section(self, plugin: Any) -> CliPortalBuilder:
168
+ """Show a plugin's section: the docs plugin (guides) or the public-api
169
+ plugin (API reference); a ``portal_section`` dict works too."""
170
+ self._sections.append(getattr(plugin, "portal_section", plugin))
171
+ return self
172
+
173
+ def set_site_dir(self, path: str | None) -> CliPortalBuilder:
174
+ """Serve the site from this directory only (no other location is
175
+ tried); by default it is found as described in the README."""
176
+ self._site_dir = path
177
+ return self
178
+
179
+ def build(self) -> CliPortalPlugin:
180
+ path = validate_path(self._path)
181
+ document: dict[str, Any] = {
182
+ "name": validate_name(self._name),
183
+ "logo": validate_logo(self._logo),
184
+ "theme": validate_theme(self._theme),
185
+ "footerLinks": validate_footer_links(self._links),
186
+ "docs": None,
187
+ "api": None,
188
+ }
189
+ seen: set[str] = set()
190
+ for section in self._sections:
191
+ kind = section.get("kind") if isinstance(section, dict) else None
192
+ if kind not in SECTION_KINDS:
193
+ raise ValueError(f"invalid portal section: {kind}")
194
+ if kind in seen:
195
+ raise ValueError(f"portal section already registered: {kind}")
196
+ seen.add(kind)
197
+ base = section["base_path"]
198
+ if kind == "docs":
199
+ document["docs"] = {"title": section["title"], "pages": f"{base}/pages"}
200
+ else:
201
+ document["api"] = {
202
+ "title": section["title"], "openapi": f"{base}/openapi.json", "swagger": f"{base}/swagger",
203
+ }
204
+
205
+ site_dir = resolve_site_dir(self._site_dir)
206
+ plugin = CliPortalPlugin(prefix=path, router=APIRouter(), document=document, site_dir=site_dir)
207
+ if site_dir is None:
208
+ # Nothing is served, portal.json included.
209
+ logger.warning(SITE_NOT_FOUND)
210
+ return plugin
211
+ with open(os.path.join(site_dir, "index.html"), encoding="utf-8") as handle:
212
+ plugin._index = handle.read()
213
+ plugin.router = _router(plugin, site_dir)
214
+ if path != "/":
215
+ plugin.public_paths = [
216
+ path, f"{path}/", f"{path}/portal.json", f"{path}/favicon.svg", f"{path}/assets/*",
217
+ f"{path}/guides/*", f"{path}/reference", f"{path}/reference/*",
218
+ ]
219
+ return plugin
220
+
221
+
222
+ def _router(plugin: CliPortalPlugin, site_dir: str) -> APIRouter:
223
+ router = APIRouter()
224
+ assets_dir = os.path.join(site_dir, "assets")
225
+ favicon = os.path.join(site_dir, "favicon.svg")
226
+
227
+ def asset_exists(params: dict[str, Any]) -> bool:
228
+ name = params.get("file")
229
+ return (
230
+ isinstance(name, str)
231
+ and bool(_ASSET_NAME.match(name))
232
+ and os.path.isfile(os.path.join(assets_dir, name))
233
+ )
234
+
235
+ async def index(request: Request) -> Response:
236
+ root = _path_base(request)
237
+ if root is None:
238
+ return JSONResponse({"error": INVALID_PATH_BASE}, status_code=400, media_type=JSON_TYPE)
239
+ return HTMLResponse(plugin.index_html(root), headers=_NO_CACHE)
240
+
241
+ async def portal_json(request: Request) -> Response:
242
+ root = _path_base(request)
243
+ if root is None:
244
+ return JSONResponse({"error": INVALID_PATH_BASE}, status_code=400, media_type=JSON_TYPE)
245
+ return JSONResponse(plugin.portal_json(root), headers=_NO_CACHE, media_type=JSON_TYPE)
246
+
247
+ # At "/" a missing file falls through to the host's routes. Elsewhere the
248
+ # portal answers every path under its public prefixes itself, so a path
249
+ # served without sign-in never reaches a host route.
250
+ owns_prefixes = plugin.prefix != "/"
251
+
252
+ async def not_found() -> Response:
253
+ return JSONResponse({"error": "not found"}, status_code=404, media_type=JSON_TYPE)
254
+
255
+ async def asset(file: str) -> Response:
256
+ if not asset_exists({"file": file}):
257
+ return await not_found()
258
+ return FileResponse(os.path.join(assets_dir, file), headers=_IMMUTABLE)
259
+
260
+ async def favicon_svg() -> Response:
261
+ if not os.path.isfile(favicon):
262
+ return await not_found()
263
+ return FileResponse(favicon, media_type="image/svg+xml")
264
+
265
+ plain = _route_class()
266
+
267
+ def add(path: str, endpoint: Any, route_class: type[_PortalRoute] = plain) -> None:
268
+ router.add_api_route(
269
+ path, endpoint, methods=list(_METHODS), include_in_schema=False, route_class_override=route_class,
270
+ )
271
+
272
+ # The mount itself ("" under the prefix); at "/" the "/" route covers it.
273
+ if plugin.prefix != "/":
274
+ add("", index)
275
+ for page in ("/", "/guides/{slug}", "/reference", "/reference/{tag}"):
276
+ add(page, index)
277
+ add("/portal.json", portal_json)
278
+ if owns_prefixes:
279
+ add("/assets/{file}", asset)
280
+ add("/favicon.svg", favicon_svg)
281
+ for under in ("/assets", "/guides", "/reference"):
282
+ add(under + "/{rest:path}", not_found)
283
+ else:
284
+ add("/assets/{file}", asset, _route_class(asset_exists))
285
+ add("/favicon.svg", favicon_svg, _route_class(lambda _: os.path.isfile(favicon)))
286
+ return router
@@ -0,0 +1,152 @@
1
+ """Validation of the portal's options (contract C8), with the admin plugin's
2
+ rules for names, logos and colours (the colour patterns are those of
3
+ ``qodalis_cli_admin.services.admin_theme``)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ from collections.abc import Mapping
9
+ from typing import Any
10
+ from urllib.parse import urlparse
11
+
12
+ #: The dashboard's colour tokens (``theme.json``), the same on every server.
13
+ THEME_TOKENS: tuple[str, ...] = (
14
+ "primary", "primaryHover", "onPrimary", "accent", "background", "backgroundAccent", "sidebar",
15
+ "surface", "popover", "control", "controlHover", "border", "overlay", "heading", "text", "muted",
16
+ "subtle", "success", "warning", "error", "info",
17
+ )
18
+ THEME_MODES: tuple[str, ...] = ("dark", "light", "system")
19
+ MAX_NAME = 80
20
+ MAX_LOGO = 200_000
21
+ MAX_FOOTER_LINKS = 20
22
+ MAX_COLOR_LENGTH = 100
23
+
24
+ NAME_TEXT = "portal name must be 1-80 characters without control characters"
25
+ LOGO_TEXT = "portal logo must be an http(s) URL, a root-relative path or a data:image URL"
26
+
27
+ _CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
28
+ _DATA_IMAGE = re.compile(
29
+ r"^data:image/(?:png|jpeg|gif|webp|svg\+xml|x-icon|vnd\.microsoft\.icon);base64,[A-Za-z0-9+/]+={0,2}$"
30
+ )
31
+ # A hex colour, a colour function with plain numeric arguments, or a named
32
+ # colour: nothing that can end the declaration (; { } quotes) or load anything.
33
+ _COLOR_PATTERNS = (
34
+ re.compile(r"^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$", re.IGNORECASE),
35
+ re.compile(r"^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z.,%+\-\s/]*\)$", re.IGNORECASE),
36
+ re.compile(r"^[a-z]{3,30}$", re.IGNORECASE),
37
+ )
38
+ _SNAKE_TO_TOKEN = {re.sub(r"[A-Z]", lambda m: "_" + m.group(0).lower(), t): t for t in THEME_TOKENS}
39
+
40
+
41
+ # Case-insensitive: a mount must not hold CLI routes in any spelling.
42
+ _CLI_PATH = re.compile(r"^/(api|ws)/(v\d+/)?(qcli|cli)(/|$)", re.IGNORECASE)
43
+ _CLI_PARENT = re.compile(r"^/(api|ws)(/v\d+)?$", re.IGNORECASE)
44
+
45
+
46
+ def _holds_cli_routes(path: str) -> bool:
47
+ """``/api``, ``/ws``, ``/api/v1`` or a path under a CLI route."""
48
+ return bool(_CLI_PARENT.match(path) or _CLI_PATH.match(path + "/"))
49
+
50
+
51
+ def validate_path(path: Any) -> str:
52
+ """The mount: starts with ``/``, no trailing ``/`` except ``/`` itself;
53
+ nothing that could leave a URL or an HTML attribute (``//``, ``\\``,
54
+ whitespace, ``?``, ``#``, quotes, ``<``, ``>``)."""
55
+ if (
56
+ not isinstance(path, str)
57
+ or not path.startswith("/")
58
+ or (path != "/" and path.endswith("/"))
59
+ or "//" in path
60
+ or any(c.isspace() or ord(c) < 0x20 or c in "?#\\\"'<>" for c in path)
61
+ or _holds_cli_routes(path)
62
+ ):
63
+ raise ValueError(f"invalid portal path: {path}")
64
+ return path
65
+
66
+
67
+ def validate_name(name: Any) -> str:
68
+ if not isinstance(name, str) or not 1 <= len(name) <= MAX_NAME or _CONTROL.search(name):
69
+ raise ValueError(NAME_TEXT)
70
+ return name
71
+
72
+
73
+ def _is_root_relative(value: str) -> bool:
74
+ return (
75
+ value.startswith("/")
76
+ and not re.match(r"^/[/\\]", value)
77
+ and not re.search(r"[\s\x00-\x1f\x7f]", value)
78
+ )
79
+
80
+
81
+ def _is_http_url(value: str) -> bool:
82
+ if re.search(r"[\s\x00-\x1f\x7f]", value):
83
+ return False
84
+ parsed = urlparse(value)
85
+ return parsed.scheme in ("http", "https") and bool(parsed.hostname)
86
+
87
+
88
+ def validate_logo(logo: Any) -> str | None:
89
+ if logo is None:
90
+ return None
91
+ if (
92
+ not isinstance(logo, str)
93
+ or not logo
94
+ or len(logo) > MAX_LOGO
95
+ or not (_DATA_IMAGE.match(logo) or _is_root_relative(logo) or _is_http_url(logo))
96
+ ):
97
+ raise ValueError(LOGO_TEXT)
98
+ return logo
99
+
100
+
101
+ def is_color(value: Any) -> bool:
102
+ if not isinstance(value, str):
103
+ return False
104
+ v = value.strip()
105
+ return 0 < len(v) <= MAX_COLOR_LENGTH and any(p.fullmatch(v) for p in _COLOR_PATTERNS)
106
+
107
+
108
+ def _colors(colors: Any, scheme: str) -> dict[str, str]:
109
+ if colors is None:
110
+ return {}
111
+ if not isinstance(colors, Mapping):
112
+ raise ValueError(f"invalid portal colour {scheme}: {colors}")
113
+ result: dict[str, str] = {}
114
+ for key, value in colors.items():
115
+ token = key if key in THEME_TOKENS else _SNAKE_TO_TOKEN.get(key)
116
+ if value is None and token is not None:
117
+ continue
118
+ if token is None or not is_color(value):
119
+ raise ValueError(f"invalid portal colour {scheme}.{key}: {value}")
120
+ result[token] = value.strip()
121
+ return result
122
+
123
+
124
+ def validate_theme(theme: Mapping[str, Any] | None) -> dict[str, Any]:
125
+ """``{"mode", "dark", "light"}`` with only the set colours; the mode
126
+ defaults to ``system``."""
127
+ theme = theme or {}
128
+ if not isinstance(theme, Mapping):
129
+ raise ValueError(f"invalid portal theme mode: {theme}")
130
+ mode = theme.get("mode") or "system"
131
+ if mode not in THEME_MODES:
132
+ raise ValueError(f"invalid portal theme mode: {mode}")
133
+ return {"mode": mode, "dark": _colors(theme.get("dark"), "dark"), "light": _colors(theme.get("light"), "light")}
134
+
135
+
136
+ def validate_footer_links(links: list[tuple[Any, Any]]) -> list[dict[str, str]]:
137
+ """At most 20 links; ``label`` 1-80 characters, ``url`` http(s) or
138
+ root-relative. The error names the offending (or the 21st) link."""
139
+ result: list[dict[str, str]] = []
140
+ for index, (label, url) in enumerate(links):
141
+ valid = (
142
+ index < MAX_FOOTER_LINKS
143
+ and isinstance(label, str)
144
+ and 1 <= len(label) <= MAX_NAME
145
+ and not _CONTROL.search(label)
146
+ and isinstance(url, str)
147
+ and (_is_root_relative(url) or _is_http_url(url))
148
+ )
149
+ if not valid:
150
+ raise ValueError(f"invalid portal footer link: {label}")
151
+ result.append({"label": label, "url": url})
152
+ return result