sudoo-plugin-sdk 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,26 @@
1
+ """The Sudoo.sh plugin SDK: manifest types, plugin interfaces, a test harness and the `sudoo-plugin` command.
2
+
3
+ from sudoo_plugin_sdk import SudooPlugin, PluginContext, Theme
4
+ from sudoo_plugin_sdk.plugins import NotificationChannel, Notification
5
+ from sudoo_plugin_sdk.testing import make_context
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+
10
+ from sudoo_plugin_sdk.context import Caller, PluginContext, PluginSettings, ServiceError, Services
11
+ from sudoo_plugin_sdk.manifest import Manifest, load_manifest
12
+ from sudoo_plugin_sdk.plugins.base import SudooPlugin
13
+ from sudoo_plugin_sdk.theme import Theme
14
+
15
+ __all__ = [
16
+ "Caller",
17
+ "Manifest",
18
+ "PluginContext",
19
+ "PluginSettings",
20
+ "ServiceError",
21
+ "Services",
22
+ "SudooPlugin",
23
+ "Theme",
24
+ "__version__",
25
+ "load_manifest",
26
+ ]
@@ -0,0 +1,3 @@
1
+ from sudoo_plugin_sdk.cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,282 @@
1
+ """The `sudoo-plugin` command.
2
+
3
+ sudoo-plugin new <type> <id> a new plugin project from the built-in templates
4
+ sudoo-plugin validate [path] the hub's automated checks, locally
5
+ sudoo-plugin test [path] the plugin's tests against a fake panel
6
+ sudoo-plugin pack [path] dist/<id>-<version>.sudoo, byte for byte reproducible; prints its SHA-256
7
+ sudoo-plugin verify <package> check the hub's Ed25519 signature of a package
8
+ sudoo-plugin publish [path|package] upload to the hub's developer endpoint (SUDOO_DEVELOPER_TOKEN)
9
+ sudoo-plugin schema the manifest's JSON Schema
10
+ sudoo-plugin types plugin types, entry-point groups and the permissions they need
11
+
12
+ Exit status: 0 success, 1 a check or command failed, 2 wrong usage.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import contextlib
19
+ import json
20
+ import sys
21
+ from collections.abc import Iterator, Sequence
22
+ from pathlib import Path
23
+
24
+ from sudoo_plugin_sdk import __version__
25
+ from sudoo_plugin_sdk.groups import GROUPS
26
+ from sudoo_plugin_sdk.manifest import PERMISSION_DESCRIPTIONS, PLUGIN_TYPES, json_schema
27
+ from sudoo_plugin_sdk.package import EXTENSION, PackError, pack, read_manifest
28
+ from sudoo_plugin_sdk.publish import PublishError, changelog_entry, publish
29
+ from sudoo_plugin_sdk.scaffold import ScaffoldError, names_for, scaffold
30
+ from sudoo_plugin_sdk.signing import load_public_key, sha256_of, verify_package
31
+ from sudoo_plugin_sdk.validate import Report, validate
32
+
33
+
34
+ def _say(text: str = "") -> None:
35
+ sys.stdout.write(text + "\n")
36
+
37
+
38
+ def _fail(text: str) -> int:
39
+ sys.stderr.write(text + "\n")
40
+ return 1
41
+
42
+
43
+ def _print_report(report: Report, strict: bool) -> bool:
44
+ for message in report.errors:
45
+ _say(f"error {message}")
46
+ for message in report.warnings:
47
+ _say(f"warning {message}")
48
+ ok = report.ok and not (strict and report.warnings)
49
+ if report.manifest is not None:
50
+ state = "valid" if ok else "not valid"
51
+ _say(f"{report.manifest.id} {report.manifest.version}: {state} "
52
+ f"({len(report.errors)} errors, {len(report.warnings)} warnings)") # fmt: skip
53
+ return ok
54
+
55
+
56
+ # --------------------------------------------------------------------------- commands
57
+
58
+
59
+ def cmd_new(args: argparse.Namespace) -> int:
60
+ try:
61
+ target = Path(args.dir) if args.dir else Path.cwd() / names_for(args.id).entry
62
+ scaffold(args.type, args.id, target, author=args.author)
63
+ except ScaffoldError as error:
64
+ return _fail(str(error))
65
+ _say(f"Created {target}")
66
+ _say(f" cd {target}\n uv sync\n uv run sudoo-plugin validate && uv run sudoo-plugin test")
67
+ return 0
68
+
69
+
70
+ def cmd_validate(args: argparse.Namespace) -> int:
71
+ report = validate(Path(args.path), import_code=not args.no_import)
72
+ return 0 if _print_report(report, args.strict) else 1
73
+
74
+
75
+ @contextlib.contextmanager
76
+ def _on_path(folder: Path) -> Iterator[None]:
77
+ sys.path.insert(0, str(folder))
78
+ try:
79
+ yield
80
+ finally:
81
+ with contextlib.suppress(ValueError):
82
+ sys.path.remove(str(folder))
83
+
84
+
85
+ def cmd_test(args: argparse.Namespace) -> int:
86
+ project = Path(args.path).resolve()
87
+ report = validate(project, import_code=True)
88
+ if not _print_report(report, strict=False):
89
+ return 1
90
+ try:
91
+ import pytest
92
+ except ImportError:
93
+ return _fail("pytest is not installed: install sudoo-plugin-sdk[test] (uv add --dev 'sudoo-plugin-sdk[test]').")
94
+ tests = project / "tests"
95
+ if not tests.is_dir():
96
+ return _fail(f"{tests} does not exist.")
97
+ with _on_path(project / "src"):
98
+ code = pytest.main(
99
+ [
100
+ "--rootdir",
101
+ str(project),
102
+ "-W",
103
+ "ignore::pytest.PytestAssertRewriteWarning",
104
+ str(tests),
105
+ *args.pytest_args,
106
+ ]
107
+ )
108
+ return 0 if int(code) == 0 else 1
109
+
110
+
111
+ def cmd_pack(args: argparse.Namespace) -> int:
112
+ project = Path(args.path).resolve()
113
+ report = validate(project, import_code=not args.no_import)
114
+ if not _print_report(report, args.strict) or report.manifest is None:
115
+ return _fail("Not packed: fix the errors above.")
116
+ try:
117
+ packed = pack(project, report.manifest, Path(args.out) if args.out else None, compress=args.compress)
118
+ except PackError as error:
119
+ return _fail(f"Not packed:\n{error}")
120
+ _say(f"Packed {packed.path} ({packed.files} files, {packed.size} bytes)")
121
+ _say(f"sha256 {packed.sha256}")
122
+ return 0
123
+
124
+
125
+ def cmd_verify(args: argparse.Namespace) -> int:
126
+ package = Path(args.package)
127
+ try:
128
+ key_source = Path(args.public_key)
129
+ key_data = key_source.read_bytes() if key_source.is_file() else args.public_key.encode()
130
+ public_key = load_public_key(key_data)
131
+ except (OSError, ValueError) as error:
132
+ return _fail(f"The public key cannot be read: {error}")
133
+ if args.signature:
134
+ signature = args.signature
135
+ else:
136
+ signature_file = Path(args.signature_file) if args.signature_file else Path(str(package) + ".sig")
137
+ try:
138
+ signature = signature_file.read_text(encoding="utf-8").strip()
139
+ except OSError:
140
+ return _fail(f"No signature: give --signature or put it in {signature_file}.")
141
+ try:
142
+ manifest = read_manifest(package)
143
+ except (OSError, ValueError) as error:
144
+ return _fail(str(error))
145
+ sha256 = sha256_of(package)
146
+ if not verify_package(public_key, manifest.id, manifest.version, package, signature, args.sha256):
147
+ return _fail(f"NOT VERIFIED: the signature does not match {manifest.id} {manifest.version} (sha256 {sha256}).")
148
+ _say(f"Verified: {manifest.id} {manifest.version}, sha256 {sha256}")
149
+ return 0
150
+
151
+
152
+ def cmd_publish(args: argparse.Namespace) -> int:
153
+ target = Path(args.path).resolve()
154
+ if target.is_dir():
155
+ project = target
156
+ report = validate(project, import_code=not args.no_import)
157
+ if not _print_report(report, strict=False) or report.manifest is None:
158
+ return _fail("Not published: fix the errors above.")
159
+ try:
160
+ package = pack(project, report.manifest).path
161
+ except PackError as error:
162
+ return _fail(f"Not published:\n{error}")
163
+ version = report.manifest.version
164
+ else:
165
+ package = target
166
+ # dist/<id>-<version>.sudoo: the project (and its CHANGELOG.md) is usually the folder above dist/
167
+ project = next(
168
+ (p for p in (target.parent, target.parent.parent) if (p / "CHANGELOG.md").is_file()), target.parent
169
+ )
170
+ if package.suffix != EXTENSION:
171
+ return _fail(f"{package} is not a {EXTENSION} package or a plugin folder.")
172
+ try:
173
+ version = read_manifest(package).version
174
+ except (OSError, ValueError) as error:
175
+ return _fail(str(error))
176
+ if args.changelog_file:
177
+ changelog = Path(args.changelog_file).read_text(encoding="utf-8")
178
+ elif args.changelog:
179
+ changelog = args.changelog
180
+ else:
181
+ changelog = changelog_entry(project, version) or ""
182
+ if not changelog:
183
+ return _fail(f"No changelog: add a '## {version}' section to CHANGELOG.md, or give --changelog.")
184
+ try:
185
+ result = publish(package, changelog, hub=args.hub, dry_run=args.dry_run)
186
+ except PublishError as error:
187
+ return _fail(str(error))
188
+ if args.dry_run:
189
+ _say(f"Dry run: would send {package.name} ({result.size} bytes, sha256 {result.sha256})")
190
+ _say(f" as {result.plugin_id} {result.version} to {result.url}/api/v1/developer/plugins")
191
+ _say(" changelog:\n " + "\n ".join(changelog.strip().splitlines()))
192
+ return 0
193
+ data = (result.response or {}).get("data", {})
194
+ _say(f"Submitted {result.plugin_id} {result.version} ({'new plugin' if result.new_plugin else 'new version'})")
195
+ _say(f" state: {data.get('status', 'submitted')}, sha256 {result.sha256}")
196
+ for check in data.get("checks", []):
197
+ _say(f" {check.get('status', ''):8} {check.get('name', '')}: {check.get('message', '')}")
198
+ _say("Follow the review on developers.sudoo.sh.")
199
+ return 0 if data.get("status") != "changes_requested" else 1
200
+
201
+
202
+ def cmd_schema(_: argparse.Namespace) -> int:
203
+ _say(json.dumps(json_schema(), indent=2))
204
+ return 0
205
+
206
+
207
+ def cmd_types(_: argparse.Namespace) -> int:
208
+ for group in GROUPS:
209
+ state = "available" if group.available else "planned"
210
+ needs = ", ".join(sorted(group.needs)) or "-"
211
+ _say(f"{group.type:17} {group.name:24} {group.interface:20} {state:9} needs: {needs}")
212
+ _say("\nPermissions:")
213
+ for key, text in PERMISSION_DESCRIPTIONS.items():
214
+ _say(f" {key:17} {text}")
215
+ return 0
216
+
217
+
218
+ def parser() -> argparse.ArgumentParser:
219
+ root = argparse.ArgumentParser(prog="sudoo-plugin", description="Build plugins for Sudoo.sh.")
220
+ root.add_argument("--version", action="version", version=f"sudoo-plugin {__version__}")
221
+ commands = root.add_subparsers(dest="command", required=True, metavar="command")
222
+
223
+ new = commands.add_parser("new", help="create a plugin project")
224
+ new.add_argument("type", choices=PLUGIN_TYPES, metavar="type", help="plugin type: " + ", ".join(PLUGIN_TYPES))
225
+ new.add_argument("id", help="plugin id, reverse domain: com.example.midnight-theme")
226
+ new.add_argument("--dir", help="folder to create (default: the id's last part)")
227
+ new.add_argument("--author", default="Your name", help="author name for the manifest and licence")
228
+ new.set_defaults(run=cmd_new)
229
+
230
+ check = commands.add_parser("validate", help="run the hub's automated checks locally")
231
+ check.add_argument("path", nargs="?", default=".")
232
+ check.add_argument("--no-import", action="store_true", help="do not import the plugin's code")
233
+ check.add_argument("--strict", action="store_true", help="fail on warnings too")
234
+ check.set_defaults(run=cmd_validate)
235
+
236
+ test = commands.add_parser("test", help="run the plugin's tests against a fake panel")
237
+ test.add_argument("path", nargs="?", default=".")
238
+ test.add_argument("pytest_args", nargs=argparse.REMAINDER, help="passed to pytest (after --)")
239
+ test.set_defaults(run=cmd_test)
240
+
241
+ build = commands.add_parser("pack", help="build the .sudoo package")
242
+ build.add_argument("path", nargs="?", default=".")
243
+ build.add_argument("--out", help="folder for the package (default: dist/)")
244
+ build.add_argument(
245
+ "--compress", action="store_true", help="deflate entries (smaller; same zlib needed to reproduce)"
246
+ )
247
+ build.add_argument("--no-import", action="store_true", help="do not import the plugin's code while checking")
248
+ build.add_argument("--strict", action="store_true", help="fail on warnings too")
249
+ build.set_defaults(run=cmd_pack)
250
+
251
+ verify = commands.add_parser("verify", help="check a package's Ed25519 signature")
252
+ verify.add_argument("package")
253
+ verify.add_argument("--public-key", required=True, help="PEM file, or base64url of the 32-byte key")
254
+ verify.add_argument("--signature", help="base64url signature (default: read <package>.sig)")
255
+ verify.add_argument("--signature-file", help="file holding the signature")
256
+ verify.add_argument("--sha256", help="the SHA-256 the catalogue lists; must match too")
257
+ verify.set_defaults(run=cmd_verify)
258
+
259
+ send = commands.add_parser("publish", help="upload to the hub (token in SUDOO_DEVELOPER_TOKEN)")
260
+ send.add_argument("path", nargs="?", default=".", help="plugin folder (packed first) or a .sudoo package")
261
+ send.add_argument("--changelog", help="what changed (default: this version's section of CHANGELOG.md)")
262
+ send.add_argument("--changelog-file", help="file with what changed")
263
+ send.add_argument("--hub", help="hub address (default: SUDOO_HUB_URL or https://hub.sudoo.sh)")
264
+ send.add_argument("--dry-run", action="store_true", help="check and show what would be sent; send nothing")
265
+ send.add_argument("--no-import", action="store_true", help="do not import the plugin's code while checking")
266
+ send.set_defaults(run=cmd_publish)
267
+
268
+ commands.add_parser("schema", help="print the manifest's JSON Schema").set_defaults(run=cmd_schema)
269
+ commands.add_parser("types", help="list plugin types and permissions").set_defaults(run=cmd_types)
270
+ return root
271
+
272
+
273
+ def main(argv: Sequence[str] | None = None) -> int:
274
+ args = parser().parse_args(argv)
275
+ if getattr(args, "pytest_args", None) and args.pytest_args[0] == "--":
276
+ args.pytest_args = args.pytest_args[1:]
277
+ result: int = args.run(args)
278
+ return result
279
+
280
+
281
+ if __name__ == "__main__":
282
+ raise SystemExit(main())
@@ -0,0 +1,276 @@
1
+ """What the panel gives every plugin: its settings, the core services, a logger, a data folder and its own records.
2
+
3
+ The panel creates each plugin class once, with a `PluginContext` (dependency injection: a plugin never reads the
4
+ environment, imports Flask or reaches into the panel's modules). Everything a plugin may do to the panel goes through
5
+ `context.services`, the stable service layer the panel's own routes use, so a plugin gets exactly the checks, audit
6
+ entries and quotas the web app gets.
7
+
8
+ The service signatures below follow ROADMAP section 11 ("Core service layer"). They are versioned with this SDK
9
+ (`sdk_version` in manifest.json): a breaking change is a new major SDK version.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import builtins
15
+ import logging
16
+ from collections.abc import Callable, Iterator, Mapping
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+ from typing import Any, Literal, Protocol, runtime_checkable
20
+
21
+ Resource = dict[str, Any]
22
+ """A plain dictionary, the same shape as the panel's API resources (never passwords)."""
23
+
24
+ Via = Literal["session", "token", "mcp", "plugin"]
25
+
26
+
27
+ @dataclass(frozen=True, slots=True)
28
+ class Caller:
29
+ """Who asks the services to do something. The core builds it for people signed in to the web app; an
30
+ `api_access` plugin builds it for tokens; a plugin acting on its own behalf uses `PluginContext.caller`."""
31
+
32
+ name: str # "sam", "api:CI pipeline", "mcp:Sam's laptop", "plugin:com.example.backup"
33
+ permissions: frozenset[str]
34
+ via: Via = "session"
35
+ token_id: str | None = None
36
+ ip: str = ""
37
+ request_id: str = ""
38
+
39
+ def can(self, permission: str) -> bool:
40
+ return permission in self.permissions
41
+
42
+
43
+ class ServiceError(Exception):
44
+ """The only exception a service raises. The panel turns it into RFC 9457 problem details for the API, and the
45
+ MCP plugin into a tool error."""
46
+
47
+ def __init__(self, status: int, title: str, detail: str = "") -> None:
48
+ super().__init__(f"{status} {title}" + (f": {detail}" if detail else ""))
49
+ self.status = status
50
+ self.title = title
51
+ self.detail = detail
52
+
53
+
54
+ # --------------------------------------------------------------------------- services
55
+
56
+
57
+ @runtime_checkable
58
+ class InstanceService(Protocol):
59
+ def list(self, caller: Caller, limit: int = 50, offset: int = 0) -> list[Resource]: ...
60
+ def get(self, caller: Caller, name: str) -> Resource: ...
61
+ def plan(
62
+ self, caller: Caller, repo: str, branch: str, name: str | None = None, from_backup: str | None = None
63
+ ) -> Resource: ...
64
+ def quota(self, caller: Caller) -> Resource: ...
65
+ def create(self, caller: Caller, fields: Mapping[str, Any]) -> Resource: ...
66
+ def change(self, caller: Caller, name: str, fields: Mapping[str, Any]) -> Resource: ...
67
+ def run(self, caller: Caller, name: str, action: str, fields: Mapping[str, Any] | None = None) -> Resource: ...
68
+ def delete(self, caller: Caller, name: str, confirm: str) -> Resource: ...
69
+ def credentials(self, caller: Caller, name: str) -> Resource: ...
70
+ def logs(self, caller: Caller, name: str, lines: int = 200) -> builtins.list[str]: ...
71
+
72
+
73
+ @runtime_checkable
74
+ class JobService(Protocol):
75
+ def list(self, caller: Caller, instance: str | None = None, limit: int = 50, offset: int = 0) -> list[Resource]: ...
76
+ def get(self, caller: Caller, job_id: str, include_log: bool = False) -> Resource: ...
77
+ def log(self, caller: Caller, job_id: str, offset: int = 0) -> Resource: ...
78
+ def wait(self, caller: Caller, job_id: str, timeout: float = 60.0) -> Resource: ...
79
+
80
+
81
+ @runtime_checkable
82
+ class BackupService(Protocol):
83
+ def list(self, caller: Caller, instance: str | None = None, version: str | None = None) -> list[Resource]: ...
84
+ def compatible(self, caller: Caller, file: str, version: str) -> bool: ...
85
+ def delete(self, caller: Caller, file: str) -> None: ...
86
+
87
+
88
+ @runtime_checkable
89
+ class VersionService(Protocol):
90
+ def list(self, caller: Caller) -> list[Resource]: ...
91
+
92
+
93
+ @runtime_checkable
94
+ class DocsService(Protocol):
95
+ def list(self, caller: Caller) -> list[Resource]: ...
96
+ def get(self, caller: Caller, path: str) -> Resource: ...
97
+
98
+
99
+ @runtime_checkable
100
+ class ServerService(Protocol):
101
+ def figures(self, caller: Caller) -> Resource: ...
102
+
103
+
104
+ Event = dict[str, Any]
105
+ """{"kind": "instance.created", "data": {...}}: instance, job and backup events, presented as API resources."""
106
+
107
+ Unsubscribe = Callable[[], None]
108
+
109
+
110
+ @runtime_checkable
111
+ class EventService(Protocol):
112
+ def subscribe(self, kinds: list[str], callback: Callable[[Event], None]) -> Unsubscribe: ...
113
+
114
+
115
+ @dataclass(frozen=True, slots=True)
116
+ class RouteInfo:
117
+ method: str
118
+ path: str
119
+ permission: str | None
120
+ summary: str = ""
121
+
122
+
123
+ @runtime_checkable
124
+ class RouteService(Protocol):
125
+ def list(self) -> list[RouteInfo]: ...
126
+
127
+
128
+ @runtime_checkable
129
+ class Services(Protocol):
130
+ """`sudoo.services`: what the core offers plugins. Every call checks the caller's permission and writes the
131
+ audit entry itself."""
132
+
133
+ @property
134
+ def instances(self) -> InstanceService: ...
135
+ @property
136
+ def jobs(self) -> JobService: ...
137
+ @property
138
+ def backups(self) -> BackupService: ...
139
+ @property
140
+ def versions(self) -> VersionService: ...
141
+ @property
142
+ def docs(self) -> DocsService: ...
143
+ @property
144
+ def server(self) -> ServerService: ...
145
+ @property
146
+ def events(self) -> EventService: ...
147
+ @property
148
+ def routes(self) -> RouteService: ...
149
+
150
+
151
+ # --------------------------------------------------------------------------- the plugin's own things
152
+
153
+ Document = dict[str, Any]
154
+
155
+
156
+ @runtime_checkable
157
+ class PluginStorage(Protocol):
158
+ """The plugin's own records (permissions `storage.read` / `storage.write`), kept by the panel's storage and
159
+ separate from every other plugin's. Collections are names the plugin chooses."""
160
+
161
+ def get(self, collection: str, key: str) -> Document | None: ...
162
+ def all(self, collection: str) -> dict[str, Document]: ...
163
+ def put(self, collection: str, key: str, document: Document) -> None: ...
164
+ def delete(self, collection: str, key: str) -> bool: ...
165
+ def change(
166
+ self, collection: str, key: str, fn: Callable[[Document | None], Document | None]
167
+ ) -> Document | None: ...
168
+
169
+
170
+ @runtime_checkable
171
+ class Secrets(Protocol):
172
+ """The panel's encrypted vault (permission `secrets`), one namespace per plugin."""
173
+
174
+ def get(self, name: str) -> str | None: ...
175
+ def put(self, name: str, value: str) -> None: ...
176
+ def delete(self, name: str) -> bool: ...
177
+
178
+
179
+ @runtime_checkable
180
+ class Mail(Protocol):
181
+ """The panel's mailer (permission `mail.send`)."""
182
+
183
+ @property
184
+ def ready(self) -> bool: ...
185
+ def send(self, to: str, subject: str, text: str, html: str | None = None) -> None: ...
186
+
187
+
188
+ class PluginSettings(Mapping[str, Any]):
189
+ """The values of the settings the manifest declares, as the administrator set them on the Settings page
190
+ (defaults otherwise). Read-only for the plugin; secrets are plain strings here and never logged by the panel."""
191
+
192
+ def __init__(self, values: Mapping[str, Any] | None = None) -> None:
193
+ self._values = dict(values or {})
194
+
195
+ def __getitem__(self, key: str) -> Any:
196
+ return self._values[key]
197
+
198
+ def __iter__(self) -> Iterator[str]:
199
+ return iter(self._values)
200
+
201
+ def __len__(self) -> int:
202
+ return len(self._values)
203
+
204
+ def __repr__(self) -> str:
205
+ return f"PluginSettings({sorted(self._values)})" # keys only: values may be secrets
206
+
207
+ def string(self, key: str, default: str = "") -> str:
208
+ value = self._values.get(key, default)
209
+ return default if value is None else str(value)
210
+
211
+ def integer(self, key: str, default: int = 0) -> int:
212
+ value = self._values.get(key, default)
213
+ if isinstance(value, bool) or not isinstance(value, int):
214
+ raise ValueError(f"The setting {key} must be a whole number.")
215
+ return value
216
+
217
+ def number(self, key: str, default: float = 0.0) -> float:
218
+ value = self._values.get(key, default)
219
+ if isinstance(value, bool) or not isinstance(value, int | float):
220
+ raise ValueError(f"The setting {key} must be a number.")
221
+ return float(value)
222
+
223
+ def boolean(self, key: str, default: bool = False) -> bool:
224
+ value = self._values.get(key, default)
225
+ if not isinstance(value, bool):
226
+ raise ValueError(f"The setting {key} must be true or false.")
227
+ return value
228
+
229
+
230
+ # What each plugin permission lets the plugin's own Caller do in the services (the panel's role permissions).
231
+ PLUGIN_GRANTS: dict[str, frozenset[str]] = {
232
+ "instances.read": frozenset({"instances.view", "instances.logs"}),
233
+ "instances.write": frozenset(
234
+ {"instances.view", "instances.create", "instances.update", "instances.operate", "instances.restore",
235
+ "instances.delete", "backups.manage"}
236
+ ),
237
+ "accounts.read": frozenset({"accounts.view"}),
238
+ "settings.read": frozenset({"settings.view"}),
239
+ "settings.write": frozenset({"settings.view", "settings.manage"}),
240
+ } # fmt: skip
241
+
242
+
243
+ def granted(permissions: frozenset[str]) -> frozenset[str]:
244
+ """The panel permissions a plugin's own Caller has, from the plugin permissions it was granted."""
245
+ result: set[str] = set()
246
+ for permission in permissions:
247
+ result |= PLUGIN_GRANTS.get(permission, frozenset())
248
+ return frozenset(result)
249
+
250
+
251
+ @dataclass(frozen=True)
252
+ class PluginContext:
253
+ """Everything the panel hands a plugin when it creates it."""
254
+
255
+ plugin_id: str
256
+ version: str
257
+ settings: PluginSettings
258
+ services: Services
259
+ logger: logging.Logger
260
+ data_dir: Path # a folder only this plugin writes to; kept across updates, removed on uninstall
261
+ permissions: frozenset[str] = field(default_factory=frozenset) # granted at install (the manifest's list)
262
+ storage: PluginStorage | None = None # with storage.read / storage.write
263
+ secrets: Secrets | None = None # with secrets
264
+ mail: Mail | None = None # with mail.send
265
+ sudoo_version: str = "2.0.0"
266
+
267
+ @property
268
+ def caller(self) -> Caller:
269
+ """The Caller for things the plugin does on its own (a background task, an instance hook): limited to what
270
+ the permissions granted at install allow (PLUGIN_GRANTS), audited as plugin:<id>."""
271
+ return Caller(name=f"plugin:{self.plugin_id}", permissions=granted(self.permissions), via="plugin")
272
+
273
+ def require(self, permission: str) -> None:
274
+ """Raise PermissionError when the plugin was not granted `permission`; call before using a capability."""
275
+ if permission not in self.permissions:
276
+ raise PermissionError(f"{self.plugin_id} was not granted the permission {permission}.")
@@ -0,0 +1,84 @@
1
+ """Entry-point groups: where the panel looks for each kind of plugin, and what each kind usually needs.
2
+
3
+ A manifest's `type` names one kind of plugin; its `entry_points` must then include that kind's group. Eight groups
4
+ exist in the panel today; the others are planned for the plugin manager of Sudoo.sh 2.0 and their interfaces may
5
+ still change before SDK 1.0.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+
12
+ from sudoo_plugin_sdk.manifest import PLUGIN_TYPES
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Group:
17
+ type: str # the manifest `type`
18
+ name: str # the entry-point group
19
+ interface: str # the class or Protocol in this SDK
20
+ available: bool # True: the panel loads it today; False: planned
21
+ needs: frozenset[str] = frozenset() # permissions a plugin of this group cannot work without
22
+ usually: frozenset[str] = frozenset() # permissions most plugins of this group ask for (a hint, not a rule)
23
+ description: str = ""
24
+
25
+
26
+ GROUPS: tuple[Group, ...] = (
27
+ Group("auth", "sudoo.auth", "Authenticator", True, usually=frozenset({"network.outbound"}),
28
+ description="Checks a user name and password (LDAP, a company directory)"),
29
+ Group("second_factor", "sudoo.second_factors", "SecondFactor", True,
30
+ description="Proves it is really that person after the password (SMS, hardware keys)"),
31
+ Group("mailer", "sudoo.mailers", "Mailer", True, usually=frozenset({"network.outbound"}),
32
+ description="Sends the panel's e-mail (SMTP, an e-mail service's API)"),
33
+ Group("exposure", "sudoo.exposure", "Exposure", True, usually=frozenset({"docker", "network.outbound"}),
34
+ description="Turns a local port into an address people can open (tunnels, reverse proxies)"),
35
+ Group("update_trigger", "sudoo.update_triggers", "UpdateTrigger", True, usually=frozenset({"network.inbound"}),
36
+ description="Tells the panel that an instance has new code (webhooks, polling)"),
37
+ Group("addon_source", "sudoo.addon_sources", "AddonSource", True,
38
+ usually=frozenset({"filesystem.read", "network.outbound"}),
39
+ description="Provides the Odoo Enterprise add-ons of each version"),
40
+ Group("storage", "sudoo.storage", "Storage", True, description="Keeps the panel's own data (another database)"),
41
+ Group("rate_limiter", "sudoo.rate_limiters", "RateLimiter", True,
42
+ description="Keeps request counts (shared between panels)"),
43
+ Group("backup", "sudoo.backups", "BackupDestination", False, needs=frozenset({"network.outbound"}),
44
+ usually=frozenset({"instances.read"}), description="Stores backups elsewhere (S3, SFTP)"),
45
+ Group("notification", "sudoo.notifications", "NotificationChannel", False,
46
+ usually=frozenset({"network.outbound"}), description="Sends alerts to a channel (Slack, Discord, SMS)"),
47
+ Group("instance_hook", "sudoo.instance_hooks", "InstanceHook", False, needs=frozenset({"instances.read"}),
48
+ description="Runs when an instance is created, started, stopped or deleted"),
49
+ Group("dashboard_widget", "sudoo.dashboard_widgets", "DashboardWidget", False,
50
+ description="Adds a card to the dashboard"),
51
+ Group("web_page", "sudoo.web_pages", "WebPage", False, description="Adds a page to the web app"),
52
+ Group("background_task", "sudoo.background_tasks", "BackgroundTask", False,
53
+ description="Runs recurring work in the background"),
54
+ Group("theme", "sudoo.themes", "Theme", False, description="Changes the panel's colours, logo and e-mail accent"),
55
+ Group("api", "sudoo.api_access", "ApiAccess", False, needs=frozenset({"network.inbound"}),
56
+ description="Authenticates callers that are not the browser app (API tokens)"),
57
+ Group("mcp", "sudoo.mcp", "McpServer", False, needs=frozenset({"network.inbound"}),
58
+ description="Serves the panel's operations to Model Context Protocol clients"),
59
+ Group("extension", "sudoo.extensions", "Extension", False, description="Anything else"),
60
+ ) # fmt: skip
61
+
62
+ # Groups a plugin may register beside its main one, without a `type` of their own.
63
+ EXTRA_GROUPS: dict[str, Group] = {
64
+ "sudoo.api_blueprints": Group(
65
+ "extension",
66
+ "sudoo.api_blueprints",
67
+ "ApiRoutes",
68
+ False,
69
+ needs=frozenset({"network.inbound"}),
70
+ description="Adds endpoints under /api/v1/plugins/<id>/",
71
+ ),
72
+ }
73
+
74
+ BY_TYPE: dict[str, Group] = {group.type: group for group in GROUPS}
75
+ BY_NAME: dict[str, Group] = {group.name: group for group in GROUPS} | EXTRA_GROUPS
76
+
77
+ assert set(BY_TYPE) == set(PLUGIN_TYPES) # noqa: S101 - every manifest type has a group
78
+
79
+ # A theme is data: colours, a logo and an e-mail accent. It never needs a permission.
80
+ THEME_PERMISSIONS: frozenset[str] = frozenset()
81
+
82
+
83
+ def group_of(plugin_type: str) -> Group:
84
+ return BY_TYPE[plugin_type]