Repository navigation
Expand file tree
/
Copy pathplugins.py
More file actions
1692 lines (1512 loc) · 69.3 KB
/
Copy pathplugins.py
File metadata and controls
1692 lines (1512 loc) · 69.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Local OpenBox plugin packages and hooks.
The plugin surface is frozen as API v1 (see docs/plugin-api.md): manifest
hooks, palette commands, a bounded library read, and a notification post.
Everything else is internal and may change.
"""
import hashlib
import json
import logging
import re
import shutil
import subprocess
import sys
import tempfile
import os
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import urlsplit
from archives import safe_zip_extract
from backend_io import atomic_write_text
from pkg.platform_compat import resolved_data_dir
# Capability declarations are additive on top of the frozen v1 hook set
# (ADR 0077). Each capability name maps to the hook a plugin must declare;
# the host refuses a capability whose hook is missing.
CAPABILITY_HOOKS = {
"storefront": "storefront",
"metadata": "metadata",
"media": "media",
"stats": "stats",
"emulator_settings": "emulator",
"discovery": "discovery",
}
CAPABILITY_HOOK_NAMES = frozenset(CAPABILITY_HOOKS.values())
# Hooks that receive the data bag, capability settings, and credentials.
PRIVILEGED_HOOK_NAMES = frozenset(CAPABILITY_HOOK_NAMES)
HOOKS = (
{"before_launch", "after_session", "library", "command", "library_source", "events"}
| set(PRIVILEGED_HOOK_NAMES)
)
# Per-hook wall-clock budgets. Legacy hooks keep the historical 5 s.
HOOK_TIMEOUTS = {
"storefront": 30,
"metadata": 15,
"media": 15,
"stats": 15,
"emulator": 10,
"discovery": 10,
"default": 5,
}
# Declared-permission whitelist for 1.14.0. A plugin that wants anything else
# is refused at manifest read time; grants never exceed declarations.
PERMISSIONS = frozenset({"network"})
PLUGIN_ID = re.compile(r"^[a-z0-9][a-z0-9._-]{1,63}$")
COMMAND_ID = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
PLUGIN_API_VERSION = 1
# Plugin API v2 is additive (ADR 0092). A v1 manifest keeps the v1 runner and the v1
# payload shapes; a v2 manifest is served by the JSON Lines runner.
PLUGIN_API_VERSIONS = (1, 2)
# The version the host advertises: the newest one it serves.
PLUGIN_API_VERSION_SUPPORTED = PLUGIN_API_VERSIONS[-1]
RUNNER = Path(__file__).with_name("plugin_runner.py")
RUNNER_V2 = Path(__file__).with_name("plugin_runner_v2.py")
# Events a v2 plugin may subscribe to. A manifest naming anything else is refused.
SUBSCRIPTIONS = frozenset({
"library.changed",
"library.progress",
"session.started",
"session.ended",
"game.launched",
})
LOGGER = logging.getLogger("openbox.plugins")
MAX_PLUGIN_PAYLOAD = 2 * 1024 * 1024
# A v2 plugin may return more than a v1 plugin, but the output is still capped (ADR 0092).
MAX_PLUGIN_OUTPUT_V2 = 4 * 1024 * 1024
MAX_COMMANDS = 32
MAX_LIBRARY_ENTRIES = 500
MAX_PLUGIN_DATA = 1024 * 1024
MAX_PLUGIN_DATA_KEY = 128
MAX_PLUGIN_DATA_DEPTH = 4
MAX_CREDENTIAL_KEYS = 128
MAX_CREDENTIAL_VALUE = 4096
MAX_CAPABILITY_NAME = 80
MAX_CAPABILITY_PLATFORM = 40
MAX_CAPABILITY_MEDIA_KINDS = 20
MAX_EMULATOR_CAPABILITIES = 8
MAX_MESSAGE_KEYS = 64
MAX_MESSAGE_TEXT = 500
MESSAGE_LOCALES = ("en", "es", "de", "fr", "pt")
NOTIFICATION_LEVELS = frozenset({"info", "success", "warning", "error"})
CAPABILITY_ID = PLUGIN_ID
EMULATOR_CAPABILITY_ID = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
MESSAGE_KEY = re.compile(r"^[a-z0-9._-]{1,64}$")
UNSANDBOXED_PLUGINS_ENV = "OPENBOX_ALLOW_UNSANDBOXED_PLUGINS"
def _capability_media_kinds():
"""Media kinds a metadata/media capability may declare.
Imported lazily: plugins.py is imported very early by web_app, and the
media field tables pull in state modules that must not import plugins.
"""
try:
from pkg.state.media_probe import MEDIA_PATH_FIELDS, MEDIA_TYPES_ALL
return frozenset(MEDIA_PATH_FIELDS) | frozenset(MEDIA_TYPES_ALL) | {"screenshots"}
except Exception: # an unavailable media module must not block manifests
return frozenset({
"cover", "background", "screenshots", "clear_logo", "fanart",
"banner", "icon", "box_back", "box_spine", "box_3d",
"title_screen", "cart_front", "cart_back", "disc", "advertisement",
"manual", "video", "music", "video_snap", "video_theme",
"video_trailer",
})
def sandbox_status():
"""Report the sandbox mode the host will use for plugin execution."""
if os.environ.get(UNSANDBOXED_PLUGINS_ENV) == "1":
return "disabled"
if not shutil.which("bwrap"):
return "unavailable"
try:
return "ready" if _sandbox_available() else "unavailable"
except (OSError, subprocess.SubprocessError, ValueError, TypeError):
# A mocked or broken subprocess layer must fail toward "unavailable"
# (skip the plugin) rather than break session bookkeeping.
return "unavailable"
def _clean_commands(raw, plugin_id):
if raw in (None, []):
return []
if not isinstance(raw, list) or len(raw) > MAX_COMMANDS:
raise ValueError("Plugin commands must be a bounded list.")
commands = []
seen = set()
for item in raw:
if not isinstance(item, dict):
raise ValueError("Plugin commands must be objects with id and label.")
command_id = str(item.get("id") or "").strip()
label = str(item.get("label") or "").strip()
if not COMMAND_ID.fullmatch(command_id) or not label:
raise ValueError("Plugin commands need a valid id and a label.")
if command_id in seen:
raise ValueError("Plugin command ids must be unique.")
seen.add(command_id)
commands.append({
"id": command_id,
"label": label[:80],
"description": str(item.get("description") or "")[:280],
"plugin_id": plugin_id,
"source": "manifest",
})
return commands
#: Top-level directories the sandbox already masks. The data directory is
#: usually under /home and therefore covered by accident rather than by
#: design; see _sandboxed_command.
SANDBOX_MASKED_PREFIXES = ("/home", "/tmp", "/run", "/mnt", "/media")
def _needs_data_dir_mask(data_posix: str) -> bool:
"""True when the data directory is not already hidden by a --tmpfs.
Kept as a pure function of a POSIX path string so the prefix rule can be
tested on any platform. ``Path.resolve()`` on Windows prepends a drive
letter, so a test that fed it "/srv/data" would be asserting about a path
that cannot exist on the host running the test.
"""
return not any(
data_posix == prefix or data_posix.startswith(prefix + "/")
for prefix in SANDBOX_MASKED_PREFIXES
)
def _sandboxed_command(package_root, entry, hook, *, share_net=False, api_version=1):
runner_name = "plugin_runner_v2.py" if api_version >= 2 else "plugin_runner.py"
"""Build a bubblewrap command with no user-home or network access.
``share_net`` re-shares the host network namespace and is only passed for
plugins the user explicitly granted the ``network`` permission. It must
come after ``--unshare-all``: bubblewrap applies namespace flags in
order, so a later ``--share-net`` clears the net bit ``--unshare-all``
set without touching the other namespaces.
"""
bubblewrap = shutil.which("bwrap")
if not bubblewrap:
return None
relative_entry = entry.relative_to(package_root)
command = [
bubblewrap,
"--die-with-parent",
"--new-session",
"--unshare-all",
]
if share_net:
command.append("--share-net")
# Mask the data directory explicitly.
#
# The five --tmpfs entries below only protect the data directory *by
# accident*: it normally lives under $HOME, and /home is masked. But
# OPENBOX_DATA_DIR is a documented, supported override, and
# default_data_dir() falls back to the process cwd when the home directory
# cannot be determined. Either way, a data directory outside those five
# paths stays readable through the --ro-bind of the whole filesystem --
# library.json, settings.json (which holds provider credentials) and the
# plugin state.
#
# Masking it by resolved path is free, because the plugin contract already
# gives a plugin everything it is entitled to on stdin: plugin_runner.py
# does json.load(sys.stdin) and plugins.py documents per-plugin settings as
# travelling in that payload. No legitimate plugin reads the data directory
# from disk, and this makes the documented guarantee true.
data_dir = resolved_data_dir().resolve()
command.extend([
"--ro-bind", "/", "/",
"--tmpfs", "/home",
"--tmpfs", "/tmp",
"--tmpfs", "/run",
"--tmpfs", "/mnt",
"--tmpfs", "/media",
"--proc", "/proc",
"--dev", "/dev",
])
# Only add the mask when the directory is not already covered by one of the
# tmpfs entries above; a redundant --tmpfs would needlessly hide it twice.
if _needs_data_dir_mask(data_dir.as_posix()):
command.extend(["--tmpfs", data_dir.as_posix()])
command.extend([
"--dir", "/opt/openbox",
"--dir", "/opt/openbox/plugin",
"--dir", "/opt/openbox/runner",
"--ro-bind", str(package_root), "/opt/openbox/plugin",
"--ro-bind", str(RUNNER.parent), "/opt/openbox/runner",
"--chdir", "/tmp",
sys.executable,
"-B",
f"/opt/openbox/runner/{runner_name}",
f"/opt/openbox/plugin/{relative_entry}",
*([] if api_version >= 2 else [hook]),
])
return command
def _sandbox_available():
"""Check whether this host can create the namespaces bubblewrap needs."""
command = shutil.which("bwrap")
if not command:
return False
probe = subprocess.run(
[command, "--die-with-parent", "--new-session", "--unshare-all", "--ro-bind", "/", "/", "/usr/bin/true"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,
check=False,
)
return probe.returncode == 0
def _plugin_command(package_root, entry, hook, *, trusted=False, share_net=False, api_version=1):
runner = RUNNER_V2 if api_version >= 2 else RUNNER
tail = [str(entry)] if api_version >= 2 else [str(entry), hook]
if os.environ.get(UNSANDBOXED_PLUGINS_ENV) == "1":
LOGGER.warning(
"Running plugin %s without an OS sandbox because %s=1",
package_root.name,
UNSANDBOXED_PLUGINS_ENV,
)
return [sys.executable, "-B", str(runner), *tail]
command = _sandboxed_command(package_root, entry, hook, share_net=share_net, api_version=api_version)
if command and _sandbox_available():
return command
if trusted:
# Sandbox unavailable (e.g. Windows) but the user explicitly trusted
# this exact package checksum: run unsandboxed, loudly.
LOGGER.warning(
"Running plugin %s without an OS sandbox: user-trusted package",
package_root.name,
)
return [sys.executable, "-B", str(runner), *tail]
LOGGER.warning(
"Skipping plugin %s because bubblewrap is unavailable; trust it in the Plugins manager to run it unsandboxed",
package_root.name,
)
return None
def state_file(directory):
return Path(directory) / "plugins-state.json"
def load_plugin_state(directory):
try:
data = json.loads(state_file(directory).read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except (OSError, json.JSONDecodeError):
return {}
def save_plugin_state(directory, state):
path = state_file(directory)
atomic_write_text(path, json.dumps(state, indent=2) + "\n")
# ---------------------------------------------------------------------------
# Plugins 2.0: trust (F1a), permissions (F1b), settings (F1c)
# ---------------------------------------------------------------------------
def _clean_permissions(raw):
"""Validate the manifest ``permissions`` declaration (whitelist)."""
if raw in (None, []):
return []
if not isinstance(raw, list) or not all(isinstance(item, str) for item in raw):
raise ValueError("Plugin permissions must be a list of strings.")
unknown = [item for item in raw if item not in PERMISSIONS]
if unknown:
raise ValueError(f"Plugin requests unknown permissions: {', '.join(sorted(unknown))}.")
return sorted(set(raw))
SETTING_TYPES = ("string", "number", "integer", "boolean")
def _clean_settings_schema(raw):
"""Validate the manifest ``settings`` JSON-Schema subset (structural)."""
if raw is None:
return None
if not isinstance(raw, dict):
raise ValueError("Plugin settings must be a JSON Schema object.")
if raw.get("type", "object") != "object":
raise ValueError("Plugin settings schema must be an object schema.")
properties = raw.get("properties", {})
if not isinstance(properties, dict):
raise ValueError("Plugin settings schema properties must be an object.")
for name, field in properties.items():
if not isinstance(field, dict):
raise ValueError(f"Plugin setting {name!r} must be an object.")
field_type = field.get("type", "string")
if field_type not in SETTING_TYPES:
raise ValueError(f"Plugin setting {name!r} has unsupported type {field_type!r}.")
enum = field.get("enum")
if enum is not None and (not isinstance(enum, list) or not enum):
raise ValueError(f"Plugin setting {name!r} enum must be a non-empty list.")
required = raw.get("required", [])
if not isinstance(required, list) or any(name not in properties for name in required):
raise ValueError("Plugin settings schema has an invalid required list.")
return {"type": "object", "properties": properties, "required": list(required)}
def _clean_messages(raw):
"""Validate the optional localized notification table."""
if raw is None:
return {}
if not isinstance(raw, dict) or len(raw) > MAX_MESSAGE_KEYS:
raise ValueError(f"Plugin messages must be an object with at most {MAX_MESSAGE_KEYS} keys.")
messages = {}
for key, translations in raw.items():
if not isinstance(key, str) or not MESSAGE_KEY.fullmatch(key):
raise ValueError(f"Plugin message key {key!r} is invalid.")
if not isinstance(translations, dict):
raise ValueError(f"Plugin message {key!r} must map locales to text.")
clean = {}
for locale, text in translations.items():
if locale not in MESSAGE_LOCALES:
# Forward compatible: a future locale is dropped, not fatal.
continue
if not isinstance(text, str):
raise ValueError(f"Plugin message {key!r} has a non-text {locale!r} translation.")
clean[locale] = text[:MAX_MESSAGE_TEXT]
messages[key] = clean
return messages
def _clean_optional_text(raw, label, maximum):
if raw in (None, ""):
return ""
if not isinstance(raw, str):
raise ValueError(f"Plugin {label} must be text.")
return raw.strip()[:maximum]
def _clean_homepage(raw):
if raw in (None, ""):
return ""
if not isinstance(raw, str):
raise ValueError("Plugin homepage must be a URL.")
value = raw.strip()
parts = urlsplit(value)
if len(value) > 300 or parts.scheme != "https" or not parts.netloc:
raise ValueError("Plugin homepage must be an HTTPS URL of at most 300 characters.")
return value
def _clean_capability_identity(name, value):
if not isinstance(value, dict):
raise ValueError(f"Plugin capability {name} must be an object.")
capability_id = value.get("id")
capability_name = value.get("name")
if not isinstance(capability_id, str) or not CAPABILITY_ID.fullmatch(capability_id):
raise ValueError(f"Plugin capability {name} needs a valid id.")
if not isinstance(capability_name, str) or not capability_name.strip():
raise ValueError(f"Plugin capability {name} needs a name.")
return capability_id, capability_name.strip()[:MAX_CAPABILITY_NAME]
def _clean_media_kinds(raw, name):
if raw is None:
return ["cover", "background"]
if not isinstance(raw, list) or len(raw) > MAX_CAPABILITY_MEDIA_KINDS:
raise ValueError(f"Plugin capability {name} media_kinds must be a bounded list.")
allowed = _capability_media_kinds()
kinds = []
for kind in raw:
if not isinstance(kind, str) or kind not in allowed:
raise ValueError(f"Plugin capability {name} declares an unknown media kind.")
if kind not in kinds:
kinds.append(kind)
return kinds
def _clean_emulator_capabilities(raw):
if not isinstance(raw, list) or len(raw) > MAX_EMULATOR_CAPABILITIES:
raise ValueError("Plugin emulator_settings must be a list of at most 8 emulators.")
emulators = []
seen = set()
for entry in raw:
if not isinstance(entry, dict):
raise ValueError("Plugin emulator_settings entries must be objects.")
emulator_id = entry.get("emulator_id")
if not isinstance(emulator_id, str) or not EMULATOR_CAPABILITY_ID.fullmatch(emulator_id):
raise ValueError("Plugin emulator_settings needs a valid emulator_id.")
if emulator_id in seen:
raise ValueError("Plugin emulator_settings ids must be unique.")
seen.add(emulator_id)
label = entry.get("label")
if label in (None, ""):
label = emulator_id
if not isinstance(label, str):
raise ValueError("Plugin emulator_settings label must be text.")
schema = _clean_settings_schema(entry.get("schema"))
if schema is None:
raise ValueError("Plugin emulator_settings requires a settings schema.")
scopes_raw = entry.get("scopes", ["global", "platform"])
if not isinstance(scopes_raw, list) or not set(scopes_raw) <= {"global", "platform"}:
raise ValueError("Plugin emulator_settings scopes must be global and/or platform.")
scopes = [scope for scope in ("global", "platform") if scope in scopes_raw]
if not scopes:
raise ValueError("Plugin emulator_settings needs at least one scope.")
emulators.append({
"emulator_id": emulator_id,
"label": label.strip()[:MAX_CAPABILITY_NAME],
"schema": schema,
"scopes": scopes,
})
return emulators
def _clean_capabilities(raw, plugin_id, hooks=None):
"""Validate the additive capability declarations.
A capability is only accepted when the plugin also declares its hook, so
a capability can never widen what the host is willing to invoke. When
``hooks`` is omitted every capability hook is treated as declared (used
by callers that validate shape only).
"""
if raw in (None, {}):
return {}
if not isinstance(raw, dict):
raise ValueError("Plugin capabilities must be an object.")
hooks = set(CAPABILITY_HOOK_NAMES if hooks is None else hooks)
capabilities = {}
seen_ids = set()
for name, hook in CAPABILITY_HOOKS.items():
if name not in raw:
continue
if hook not in hooks:
raise ValueError(f"Plugin capability {name} requires the {hook} hook.")
value = raw[name]
if name == "emulator_settings":
capabilities[name] = _clean_emulator_capabilities(value)
continue
capability_id, capability_name = _clean_capability_identity(name, value)
if capability_id in seen_ids:
raise ValueError(f"Plugin capability id {capability_id!r} is duplicated in {plugin_id}.")
seen_ids.add(capability_id)
capability = {"id": capability_id, "name": capability_name}
if name in ("storefront", "metadata"):
platform = value.get("platform", "")
if platform not in (None, "") and not isinstance(platform, str):
raise ValueError(f"Plugin {name} platform must be text.")
capability["platform"] = str(platform or "").strip()[:MAX_CAPABILITY_PLATFORM]
elif name == "media":
capability["media_kinds"] = _clean_media_kinds(value.get("media_kinds"), name)
capabilities[name] = capability
return capabilities
def _check_setting_value(name, field, value):
"""Type/range-check one setting value; return the cleaned value."""
field_type = field.get("type", "string")
if field_type == "string":
if not isinstance(value, str):
raise ValueError(f"Setting {name!r} must be a string.")
if "minLength" in field and len(value) < int(field["minLength"]):
raise ValueError(f"Setting {name!r} is too short.")
if "maxLength" in field and len(value) > int(field["maxLength"]):
raise ValueError(f"Setting {name!r} is too long.")
return value
if field_type == "boolean":
if not isinstance(value, bool):
raise ValueError(f"Setting {name!r} must be true or false.")
return value
if field_type == "integer":
if isinstance(value, bool) or not isinstance(value, int):
raise ValueError(f"Setting {name!r} must be a whole number.")
number = value
elif field_type == "number":
if isinstance(value, bool) or not isinstance(value, (int, float)):
raise ValueError(f"Setting {name!r} must be a number.")
number = value
else: # pragma: no cover - guarded by _clean_settings_schema
raise ValueError(f"Setting {name!r} has unsupported type {field_type!r}.")
if "minimum" in field and number < field["minimum"]:
raise ValueError(f"Setting {name!r} is below the minimum.")
if "maximum" in field and number > field["maximum"]:
raise ValueError(f"Setting {name!r} is above the maximum.")
return number
def validate_plugin_settings(schema, values):
"""Hand-rolled validator for the settings JSON-Schema subset.
Applies defaults, rejects unknown keys, and returns cleaned values.
The runtime is dependency-free, so this stays stdlib-only by design.
"""
schema = schema or {}
properties = schema.get("properties", {})
if not isinstance(values, dict):
raise ValueError("Plugin settings must be an object.")
unknown = sorted(name for name in values if name not in properties)
if unknown:
raise ValueError(f"Unknown plugin settings: {', '.join(unknown)}.")
cleaned = {}
for name, field in properties.items():
if name in values:
value = values[name]
elif "default" in field:
value = field["default"]
elif name in schema.get("required", []):
raise ValueError(f"Setting {name!r} is required.")
else:
continue
enum = field.get("enum")
if enum is not None and value not in enum:
raise ValueError(f"Setting {name!r} must be one of: {', '.join(str(item) for item in enum)}.")
cleaned[name] = _check_setting_value(name, field, value)
return cleaned
def _package_files(root):
return sorted(
(path for path in root.rglob("*") if path.is_file() and not path.is_symlink()),
key=lambda path: path.relative_to(root).as_posix(),
)
def _legacy_plugin_checksum(directory, plugin_id):
"""The digest grants recorded before the framing change used: raw contents, no file framing.
Only to tell a user that an old grant must be approved again. It never grants trust,
because it matches a package whose bytes were moved between files.
"""
root = Path(directory) / str(plugin_id)
digest = hashlib.sha256()
for path in _package_files(root):
digest.update(path.relative_to(root).as_posix().encode("utf-8") + b"\0")
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(65536), b""):
digest.update(chunk)
return digest.hexdigest()
def plugin_checksum(directory, plugin_id):
"""sha256 over the installed package (relative paths + contents).
Computed at trust-prompt time for manual installs; a mismatch against the
recorded checksum re-prompts, so updates cannot inherit old trust.
"""
root = Path(directory) / str(plugin_id)
digest = hashlib.sha256()
for path in _package_files(root):
# Frame each file as path NUL + sha256(content). Hashing raw content
# back to back left the content/next-path boundary ambiguous, so a
# package could move bytes between a file's tail and the next file
# name (e.g. into plugin.py) and keep the trusted checksum.
file_digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(65536), b""):
file_digest.update(chunk)
digest.update(path.relative_to(root).as_posix().encode("utf-8") + b"\0")
digest.update(file_digest.digest())
return digest.hexdigest()
def plugin_trust_status(directory, plugin_id):
"""Trust record for one plugin; trusted only when the checksum matches."""
root = Path(directory)
try:
checksum = plugin_checksum(root, plugin_id)
except OSError:
return {"trusted": False, "checksum": "", "checksum_matches": False, "granted_at": "", "retrust": False}
record = load_plugin_state(root).get("trust", {}).get(str(plugin_id))
record = record if isinstance(record, dict) else {}
checksum_matches = record.get("checksum") == checksum
# A grant from before the framing change is asked for again, never inherited.
retrust = False
if record.get("trusted") and not checksum_matches:
try:
retrust = record.get("checksum") == _legacy_plugin_checksum(root, plugin_id)
except OSError:
retrust = False
return {
"trusted": bool(record.get("trusted") and checksum_matches),
"checksum": checksum,
"checksum_matches": bool(checksum_matches),
"granted_at": str(record.get("granted_at") or ""),
"retrust": bool(retrust),
}
def set_plugin_trust(directory, plugin_id, trusted):
"""Grant or revoke unsandboxed-execution trust for one plugin.
Grants are bound to the package checksum at grant time: any update
changes the checksum and re-prompts. There is deliberately no
trust-everything switch (ADR 0056).
"""
root = Path(directory)
manifest = read_manifest(root / str(plugin_id))
state = load_plugin_state(root)
trust = state.setdefault("trust", {})
if trusted:
trust[manifest["id"]] = {
"trusted": True,
"checksum": plugin_checksum(root, manifest["id"]),
"granted_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
else:
trust.pop(manifest["id"], None)
save_plugin_state(root, state)
return bool(trusted)
def plugin_permission_grants(directory, plugin_id):
"""Permissions the user has granted this plugin (subset of its manifest)."""
state = load_plugin_state(Path(directory))
granted = (state.get("permissions") or {}).get(str(plugin_id), [])
return sorted({item for item in granted if item in PERMISSIONS})
def set_plugin_permissions(directory, plugin_id, permissions):
"""Record a user grant; requested permissions must be declared."""
root = Path(directory)
manifest = read_manifest(root / str(plugin_id))
wanted = {str(item) for item in (permissions or [])}
unknown = wanted - PERMISSIONS
if unknown:
raise ValueError(f"Unknown permissions: {', '.join(sorted(unknown))}.")
undeclared = wanted - set(manifest.get("permissions") or [])
if undeclared:
raise ValueError(f"Plugin does not declare permissions: {', '.join(sorted(undeclared))}.")
state = load_plugin_state(root)
grants = state.setdefault("permissions", {})
grants[manifest["id"]] = sorted(wanted)
save_plugin_state(root, state)
return sorted(wanted)
def plugin_settings_values(directory, manifest):
"""Stored setting values merged over schema defaults (validated)."""
schema = manifest.get("settings") or {}
state = load_plugin_state(Path(directory))
stored = (state.get("settings") or {}).get(manifest["id"], {})
if not isinstance(stored, dict):
stored = {}
try:
return validate_plugin_settings(schema, stored)
except ValueError:
# A schema update that invalidates stored values falls back to
# defaults rather than breaking the plugin.
return validate_plugin_settings(schema, {})
def get_plugin_settings(directory, plugin_id):
"""Return ``{"schema", "values"}`` for the Plugins dialog form."""
manifest = read_manifest(Path(directory) / str(plugin_id))
return {
"schema": manifest.get("settings") or {"type": "object", "properties": {}},
"values": plugin_settings_values(directory, manifest),
}
def set_plugin_settings(directory, plugin_id, values):
"""Validate and store per-plugin settings."""
root = Path(directory)
manifest = read_manifest(root / str(plugin_id))
cleaned = validate_plugin_settings(manifest.get("settings") or {}, values)
state = load_plugin_state(root)
settings = state.setdefault("settings", {})
settings[manifest["id"]] = cleaned
save_plugin_state(root, state)
return cleaned
def _secret_setting_names(manifest):
schema = manifest.get("settings") or {}
properties = schema.get("properties") if isinstance(schema, dict) else {}
if not isinstance(properties, dict):
return set()
return {
str(name) for name, field in properties.items()
if isinstance(field, dict) and field.get("format") == "password"
}
def plugin_settings_values_public(directory, manifest):
"""Stored settings minus password-format values (safe for hook payloads)."""
values = plugin_settings_values(directory, manifest)
secrets = _secret_setting_names(manifest)
return {name: value for name, value in values.items() if name not in secrets}
def get_plugin_settings_public(directory, plugin_id):
"""Schema plus redacted values for Settings > Plugins.
Password fields are never returned; ``secret_set`` tells the form whether
a value already exists without disclosing it.
"""
root = Path(directory)
manifest = read_manifest(root / str(plugin_id))
secrets = _secret_setting_names(manifest)
values = plugin_settings_values(directory, manifest)
return {
"schema": manifest.get("settings") or {"type": "object", "properties": {}},
"values": {name: value for name, value in values.items() if name not in secrets},
"secret_set": {name: bool(values.get(name)) for name in sorted(secrets)},
}
def _plugin_store_path(directory, folder, plugin_id):
plugin_id = str(plugin_id)
if not PLUGIN_ID.fullmatch(plugin_id):
raise ValueError("Plugin id is invalid.")
return Path(directory) / folder / f"{plugin_id}.json"
def _read_json_store(path, maximum):
try:
if path.stat().st_size > maximum:
return {}
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
return data if isinstance(data, dict) else {}
def _write_json_store(path, data):
path.parent.mkdir(parents=True, exist_ok=True)
try:
path.parent.chmod(0o700)
except OSError:
pass
atomic_write_text(path, json.dumps(data, indent=2, sort_keys=True) + "\n", mode=0o600)
def _json_depth(value):
"""Depth of a JSON value; raises ValueError for non-JSON data."""
if value is None or isinstance(value, (bool, int, float, str)):
if isinstance(value, float) and (value != value or value in (float("inf"), float("-inf"))):
raise ValueError("Plugin data must be finite JSON.")
return 0
if isinstance(value, list):
return 1 + max((_json_depth(item) for item in value), default=0)
if isinstance(value, dict):
for key, item in value.items():
if not isinstance(key, str) or not key or len(key) > MAX_PLUGIN_DATA_KEY:
raise ValueError("Plugin data keys must be short strings.")
_json_depth(item)
return 1 + max((_json_depth(item) for item in value.values()), default=0)
raise ValueError("Plugin data must be JSON serializable.")
def plugin_data_values(directory, plugin_id):
"""The plugin's bounded data bag (``{}`` when absent or malformed)."""
try:
path = _plugin_store_path(directory, "data", plugin_id)
except ValueError:
return {}
data = _read_json_store(path, MAX_PLUGIN_DATA)
try:
if data and _json_depth(data) > MAX_PLUGIN_DATA_DEPTH:
return {}
except ValueError:
return {}
return data
def set_plugin_data(directory, plugin_id, patch):
"""Shallow-merge a validated patch into the plugin data bag.
The whole merged bag must stay under 1 MiB and four levels deep; a patch
that breaks either bound raises ``ValueError`` and writes nothing.
"""
if not isinstance(patch, dict):
raise ValueError("Plugin data must be an object.")
cleaned = {}
for key, value in patch.items():
if not isinstance(key, str) or not key or len(key) > MAX_PLUGIN_DATA_KEY:
raise ValueError("Plugin data keys must be short strings.")
_json_depth(value)
cleaned[key] = value
merged = {**plugin_data_values(directory, plugin_id), **cleaned}
if _json_depth(merged) > MAX_PLUGIN_DATA_DEPTH:
raise ValueError("Plugin data is nested too deeply.")
encoded = json.dumps(merged, sort_keys=True)
if len(encoded.encode("utf-8")) > MAX_PLUGIN_DATA:
raise ValueError("Plugin data exceeds the 1 MiB limit.")
_write_json_store(_plugin_store_path(directory, "data", plugin_id), merged)
return merged
def plugin_credentials_values(directory, plugin_id):
"""Credential values for a capability hook (plain object, 0600 file)."""
try:
path = _plugin_store_path(directory, "credentials", plugin_id)
except ValueError:
return {}
raw = _read_json_store(path, MAX_PLUGIN_DATA)
values = {}
for key, value in raw.items():
if not isinstance(key, str) or not key or len(key) > MAX_PLUGIN_DATA_KEY:
continue
if isinstance(value, str) and len(value) <= MAX_CREDENTIAL_VALUE:
values[key] = value
return values
def set_plugin_credentials(directory, plugin_id, values, *, clear=None):
"""Merge credential values; an empty string or a clear entry deletes.
Returns the stored key names (never the values).
"""
if values is None:
values = {}
if not isinstance(values, dict):
raise ValueError("Plugin credentials must be an object.")
if clear is None:
clear = []
if not isinstance(clear, list) or any(not isinstance(item, str) for item in clear):
raise ValueError("Plugin credential clear list must be a list of names.")
existing = plugin_credentials_values(directory, plugin_id)
for key, value in values.items():
if not isinstance(key, str) or not key or len(key) > MAX_PLUGIN_DATA_KEY:
raise ValueError("Plugin credential names must be short strings.")
if value in ("", None):
existing.pop(key, None)
continue
if not isinstance(value, str) or len(value) > MAX_CREDENTIAL_VALUE:
raise ValueError("Plugin credential values must be strings of at most 4096 characters.")
existing[key] = value
for key in clear:
existing.pop(key, None)
if len(existing) > MAX_CREDENTIAL_KEYS:
raise ValueError("Plugins may store at most 128 credentials.")
path = _plugin_store_path(directory, "credentials", plugin_id)
if existing:
_write_json_store(path, existing)
else:
try:
path.unlink()
except FileNotFoundError:
pass
return sorted(existing)
def plugin_credentials_summary(directory, plugin_id):
"""Key names and presence flags for the UI; values are never returned."""
values = plugin_credentials_values(directory, plugin_id)
return {"keys": sorted(values), "set": {key: True for key in sorted(values)}}
def _resolve_hook_timeout(hook, timeout):
if timeout is not None:
return timeout
return HOOK_TIMEOUTS.get(hook, HOOK_TIMEOUTS["default"])
def _hook_payload(root, manifest, hook, payload):
"""Inject host data/credentials/settings into a hook payload."""
if not isinstance(payload, dict):
return payload
body = dict(payload)
body["plugin_data"] = plugin_data_values(root, manifest["id"])
capability = hook in PRIVILEGED_HOOK_NAMES
if manifest.get("settings"):
values = plugin_settings_values_public(root, manifest) if capability else plugin_settings_values(root, manifest)
if not capability:
# Password-format settings are credentials; legacy hooks never see them.
secrets = _secret_setting_names(manifest)
values = {key: value for key, value in values.items() if key not in secrets}
body["settings"] = values
if capability:
body["credentials"] = plugin_credentials_values(root, manifest["id"])
return body
def resolve_plugin_notification(manifest, notification, *, locale="en"):
"""Resolve a hook notification to ``{level, message}``.
Keys are looked up in the manifest message table for the active locale,
then English, then the key itself. Formatting failures fall back to the
raw template rather than dropping the notification.
"""
if isinstance(notification, str):
notification = {"message": notification}
if not isinstance(notification, dict):
raise ValueError("Plugin notification must be an object.")
level = notification.get("level", "info")
if level not in NOTIFICATION_LEVELS:
level = "info"
key = notification.get("key")
params = notification.get("params")
if not isinstance(params, dict):
params = {}
message = ""
if key not in (None, ""):
messages = manifest.get("messages") or {}
translations = messages.get(str(key)) if isinstance(messages, dict) else None
if isinstance(translations, dict):
template = translations.get(locale) or translations.get("en")
else:
template = None
if template is None:
template = str(key)[:MAX_MESSAGE_TEXT]
safe_params = {
str(name)[:64]: str(value)[:200]
for name, value in list(params.items())[:32]
}
try:
message = template.format(**safe_params)
except (KeyError, ValueError, IndexError):
message = template
if not message:
raw_message = notification.get("message")
message = raw_message if isinstance(raw_message, str) else ""
return {"level": level, "message": str(message)[:2000]}
def _active_locale():
try:
from openbox import load_state_readonly
state = load_state_readonly()
locale = state.get("settings", {}).get("locale") if isinstance(state, dict) else None
return str(locale or "en")[:5] or "en"
except Exception: # state is optional for notification localization
return "en"
def _persist_plugin_notification(plugin_id, event, resolved):
"""Store one plugin notification through the shared notification store."""
from notifications import add_notification
from openbox import update_state
def mutate(state):
add_notification(
state,
kind="plugin",
level=resolved["level"],
title=resolved["message"][:200],
body=resolved["message"],
source=plugin_id,
dedupe_key=f"plugin:{plugin_id}:{event}",
)
update_state(mutate)
def _service_state():
try:
from openbox import load_state_readonly
state = load_state_readonly()
if not isinstance(state, dict):
return {}
# Host services must see the same hidden/plugin-filtered games the UI
# sees, not raw persisted rows. A capability hook can run while the
# public payload itself is being built (discovery), so never recurse.