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
 
 
 
 
 
 
 
 
 
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
"""Per-user plugin block storage + manifest validation.

Plugins are uploaded as `.zip` archives. Each archive must contain:

  - manifest.json — describes the block (kind, label, family, params, ...)
  - handler.py    — Python module exposing `run(inputs, params) -> dict`

Plugins live under ``/tmp/quda_plugins/<user_id>/<kind>/`` so they're
naturally scoped per browser (each browser tab gets its own
``user_id`` UUID stored in localStorage) and naturally garbage-
collected when the HF Space restarts (``/tmp`` is wiped). The user
can also explicitly delete plugins via the API.

This module is execution-free — it only validates and stores plugin
archives. The actual subprocess invocation lives in plugin_runner.py.
"""

from __future__ import annotations

import json
import logging
import re
import shutil
import zipfile
from pathlib import Path
from typing import Any, Literal

from pydantic import BaseModel, Field, ValidationError, field_validator

logger = logging.getLogger(__name__)

# ---- Configuration -----------------------------------------------------

PLUGIN_ROOT = Path("/tmp/quda_plugins")
MAX_PLUGINS_PER_USER = 5
MAX_ZIP_BYTES = 1 * 1024 * 1024  # 1 MB
MAX_FILES_IN_ZIP = 50
MAX_FILE_BYTES = 512 * 1024  # 512 KB per file inside the zip
# Allowed file extensions inside the zip. Keep narrow — plugins should
# be tiny Python modules, not data dumps.
ALLOWED_ZIP_EXTENSIONS = {".py", ".json", ".txt", ".md"}

# user_id must look like an identifier-ish token; constrains the
# directory structure we'll create on disk. Two flavours allowed:
#
#   * ``hf_<username>`` — server-derived from an authenticated session.
#     HF usernames are 1–39 chars matching [a-zA-Z0-9][a-zA-Z0-9_-]*,
#     so the prefixed form can be as short as 4 chars (hf_a).
#   * any other token of 8+ chars — the anon browser UUID generated by
#     frontend/src/lib/userId.ts.
#
# The hf_ prefix is reserved for server-derived ids and the route layer
# refuses to accept it on the query-parameter path (anon squat defense).
_USER_ID_RE = re.compile(r"^[a-zA-Z0-9_-]{4,64}$")
_KIND_RE = re.compile(r"^[a-z][a-z0-9_]{1,30}$")

# Reserved kinds collide with built-in NodeType — refuse to let a
# plugin shadow them.
RESERVED_KINDS = {
    "input_circuit",
    "ibm_backend",
    "fake_backend",
    "qucad",
    "qubound",
    "compvqc",
    "qshot",
    "fidelity",
    "output",
}

PluginFamily = Literal["source", "backend", "algorithm", "metric", "sink"]


# ---- Manifest schema ---------------------------------------------------

class PluginParamSpec(BaseModel):
    """One tunable parameter on the plugin's block. Mirrors the
    front-end NodeParamSpec format, with the same supported types."""

    key: str = Field(..., min_length=1, max_length=40)
    label: str = Field(..., min_length=1, max_length=80)
    type: Literal["number", "int", "select"]
    # number/int
    min: float | int | None = None
    max: float | int | None = None
    step: float | int | None = None
    displayPrecision: int | None = None
    # select
    options: list[dict[str, str]] | None = None
    # shared
    hint: str | None = Field(default=None, max_length=300)

    @field_validator("key")
    @classmethod
    def _key_format(cls, v: str) -> str:
        if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_]*", v):
            raise ValueError("param key must be a valid Python identifier")
        return v


class PluginManifest(BaseModel):
    """User-facing plugin metadata. Stored as manifest.json inside the
    plugin zip, and surfaced via /api/plugins so the front-end can
    render the block tile and the param editor."""

    # max_length matches _KIND_RE's upper bound (1 leading lowercase
    # letter + up to 30 of the same charset = 31 max). Pydantic would
    # also catch a too-long value via the regex, but keeping the length
    # constraint in sync surfaces a clear length error before the
    # regex one.
    kind: str = Field(..., min_length=2, max_length=31)
    label: str = Field(..., min_length=1, max_length=40)
    family: PluginFamily
    tagline: str = Field(default="custom user block", max_length=80)
    description: str = Field(default="", max_length=400)
    color: str = Field(default="#6b7280")
    params: list[PluginParamSpec] = Field(default_factory=list)
    # Author can declare which keys their plugin writes back to ctx so
    # downstream blocks can pick them up.  Documentation only — the
    # plugin is free to write anything its handler returns.
    writes: list[str] = Field(default_factory=list)
    # Author info shown in the result card footer.  Optional.
    author: str | None = Field(default=None, max_length=80)

    @field_validator("kind")
    @classmethod
    def _kind_format(cls, v: str) -> str:
        if not _KIND_RE.fullmatch(v):
            raise ValueError(
                "kind must be lowercase letters/digits/underscores, starting "
                "with a letter, 2-31 chars"
            )
        if v in RESERVED_KINDS:
            raise ValueError(f"kind {v!r} collides with a built-in block")
        return v

    @field_validator("color")
    @classmethod
    def _color_format(cls, v: str) -> str:
        if not re.fullmatch(r"#[0-9a-fA-F]{6}", v):
            raise ValueError("color must be #rrggbb hex")
        return v

    @field_validator("params")
    @classmethod
    def _unique_param_keys(cls, v: list[PluginParamSpec]) -> list[PluginParamSpec]:
        keys = [p.key for p in v]
        if len(keys) != len(set(keys)):
            raise ValueError("param keys must be unique")
        if len(v) > 20:
            raise ValueError("at most 20 params per plugin")
        return v


# ---- Storage helpers ---------------------------------------------------

class PluginError(Exception):
    """Raised by upload/validation paths. Caller maps to HTTP 4xx."""


def validate_user_id(user_id: str) -> str:
    """Return user_id unchanged if it matches our format, else raise."""
    if not user_id or not _USER_ID_RE.fullmatch(user_id):
        raise PluginError("Invalid user_id format.")
    return user_id


def user_plugin_dir(user_id: str) -> Path:
    """Absolute path to ``/tmp/quda_plugins/<user_id>/``. Created
    on first access; never returns paths above PLUGIN_ROOT."""
    validate_user_id(user_id)
    d = PLUGIN_ROOT / user_id
    d.mkdir(parents=True, exist_ok=True)
    return d


def plugin_dir(user_id: str, kind: str) -> Path:
    if not _KIND_RE.fullmatch(kind):
        raise PluginError(f"Invalid plugin kind {kind!r}.")
    return user_plugin_dir(user_id) / kind


def list_user_plugins(user_id: str) -> list[PluginManifest]:
    """Return manifests of every plugin the user currently has installed."""
    base = user_plugin_dir(user_id)
    out: list[PluginManifest] = []
    for sub in sorted(base.iterdir()):
        if not sub.is_dir():
            continue
        manifest_path = sub / "manifest.json"
        if not manifest_path.exists():
            continue
        try:
            data = json.loads(manifest_path.read_text(encoding="utf-8"))
            out.append(PluginManifest.model_validate(data))
        except Exception as exc:
            logger.warning("Skipping broken plugin %s: %s", sub, exc)
            continue
    return out


def find_plugin(user_id: str, kind: str) -> tuple[PluginManifest, Path] | None:
    """Look up a single plugin by (user_id, kind). Returns the manifest
    plus the plugin's directory path (containing ``handler.py``), or
    ``None`` if not found."""
    d = plugin_dir(user_id, kind)
    manifest_path = d / "manifest.json"
    if not manifest_path.exists():
        return None
    try:
        manifest = PluginManifest.model_validate_json(
            manifest_path.read_text(encoding="utf-8")
        )
    except (ValidationError, json.JSONDecodeError) as exc:
        logger.warning("Plugin %s/%s has broken manifest: %s", user_id, kind, exc)
        return None
    return manifest, d


def delete_plugin(user_id: str, kind: str) -> bool:
    """Remove the given plugin from this user's namespace. Returns
    True if something was removed, False if it didn't exist.

    For authenticated users (hf_*), also removes the plugin from the
    HF Datasets backing store so it doesn't get re-hydrated next time."""
    d = plugin_dir(user_id, kind)
    existed_locally = d.exists()
    if existed_locally:
        shutil.rmtree(d, ignore_errors=True)
    # Mirror the removal to the dataset (no-op for anon users / off
    # deployments). Even if the local dir didn't exist, attempt the
    # remote delete in case the previous restart wiped /tmp without
    # giving the user a chance to re-list.
    from app.services import datasets_storage

    datasets_storage.remove_plugin(user_id, kind)
    return existed_locally


# ---- Upload + validation -----------------------------------------------

def install_plugin_zip(
    user_id: str,
    zip_bytes: bytes,
    *,
    _skip_dataset_sync: bool = False,
) -> PluginManifest:
    """Validate and install a plugin .zip for the given user. Raises
    :class:`PluginError` with a human-readable message if anything
    goes wrong; the caller maps to HTTP 400.

    ``_skip_dataset_sync`` is an internal flag used by hydration to
    avoid re-uploading a plugin we just downloaded from the dataset.
    Always omit it from external callers."""
    validate_user_id(user_id)

    # Hard size cap up front.
    if len(zip_bytes) > MAX_ZIP_BYTES:
        raise PluginError(
            f"Zip is {len(zip_bytes)} bytes; max allowed is {MAX_ZIP_BYTES}."
        )

    # Per-user plugin count cap. Reject before extracting anything.
    existing = list_user_plugins(user_id)
    if len(existing) >= MAX_PLUGINS_PER_USER:
        raise PluginError(
            f"You already have {len(existing)} plugins (max "
            f"{MAX_PLUGINS_PER_USER}). Delete one before uploading a new one."
        )

    # Parse the zip.
    import io
    try:
        zf = zipfile.ZipFile(io.BytesIO(zip_bytes))
    except zipfile.BadZipFile:
        raise PluginError("Not a valid zip file.") from None

    # Inspect entries before extracting. We refuse paths with .. or
    # leading /, refuse non-allowed extensions, refuse over-large files
    # or too many entries.
    members = zf.infolist()
    if len(members) > MAX_FILES_IN_ZIP:
        raise PluginError(
            f"Zip has {len(members)} files; max allowed is {MAX_FILES_IN_ZIP}."
        )
    manifest_member = None
    handler_member = None
    for m in members:
        # Reject any path that tries to escape the destination.
        if m.is_dir():
            continue
        name = m.filename
        # Defence-in-depth: reject path-traversal in multiple flavours.
        # On Linux the .. check below is sufficient, but we also reject
        # backslash separators (Windows-style) and leading dots so a
        # crafted zip can't end up writing to unexpected paths if this
        # codebase is ever deployed on another OS.
        if (
            name.startswith("/")
            or name.startswith("\\")
            or "\\" in name
            or ".." in Path(name).parts
            or Path(name).is_absolute()
        ):
            raise PluginError(f"Suspicious zip entry path: {name!r}.")
        # Reject extensions outside the allowlist.
        ext = Path(name).suffix.lower()
        if ext not in ALLOWED_ZIP_EXTENSIONS:
            raise PluginError(
                f"File {name!r} has disallowed extension {ext!r}. Allowed: "
                + ", ".join(sorted(ALLOWED_ZIP_EXTENSIONS))
            )
        if m.file_size > MAX_FILE_BYTES:
            raise PluginError(
                f"File {name!r} is {m.file_size} bytes; max per-file is {MAX_FILE_BYTES}."
            )
        # Capture the required files.  Some zips put everything at the
        # top level; some nest under a single folder. Accept either by
        # matching the basename.
        base = Path(name).name
        if base == "manifest.json":
            manifest_member = m
        elif base == "handler.py":
            handler_member = m

    if manifest_member is None:
        raise PluginError("Zip is missing manifest.json at the top level.")
    if handler_member is None:
        raise PluginError("Zip is missing handler.py at the top level.")

    # Parse + validate the manifest before writing anything to disk.
    try:
        manifest_raw = zf.read(manifest_member).decode("utf-8")
    except UnicodeDecodeError:
        raise PluginError("manifest.json is not valid UTF-8.") from None
    try:
        manifest_data = json.loads(manifest_raw)
    except json.JSONDecodeError:
        raise PluginError(
            "manifest.json is not valid JSON. Check for missing commas, "
            "trailing commas, or unquoted keys."
        ) from None
    try:
        manifest = PluginManifest.model_validate(manifest_data)
    except ValidationError as exc:
        # Pull the first error message to keep the UX friendly.
        first = exc.errors()[0]
        path = ".".join(str(p) for p in first.get("loc", []))
        msg = first.get("msg", "validation failed")
        raise PluginError(f"manifest.{path}: {msg}") from None

    # Refuse if this user already has a plugin with the same kind.
    target_dir = plugin_dir(user_id, manifest.kind)
    if target_dir.exists():
        raise PluginError(
            f"You already have a plugin with kind={manifest.kind!r}. "
            "Delete it first or use a different kind."
        )

    # All checks passed — extract into a flat layout: <plugin_dir>/
    # contains manifest.json + handler.py + any extras directly.
    target_dir.mkdir(parents=True, exist_ok=False)
    try:
        # Write manifest.json (already validated).
        (target_dir / "manifest.json").write_text(manifest_raw, encoding="utf-8")
        # Extract every other allowed file. Use the basename so a
        # nested-in-folder zip and a flat zip end up identical on disk.
        seen = set()
        for m in members:
            if m.is_dir():
                continue
            base = Path(m.filename).name
            if base == "manifest.json":
                continue
            if base in seen:
                raise PluginError(
                    f"Duplicate file basename {base!r} in zip; flatten the layout."
                )
            seen.add(base)
            dest = target_dir / base
            with zf.open(m) as src, open(dest, "wb") as dst:
                # Copy in chunks so we don't load huge files in memory.
                while True:
                    chunk = src.read(64 * 1024)
                    if not chunk:
                        break
                    dst.write(chunk)
    except Exception:
        # Roll back on partial extraction so the user isn't stuck with
        # a corrupted plugin.
        shutil.rmtree(target_dir, ignore_errors=True)
        raise

    logger.info("Installed plugin %s/%s", user_id, manifest.kind)

    # Re-uploading a plugin with the same kind+params would otherwise
    # hit stale cache entries pinned to the previous code. Invalidate
    # every prefix-cache entry whose prefix included this kind.
    try:
        from app.services.workflow_service import invalidate_step_cache_for_node_type
        n_evicted = invalidate_step_cache_for_node_type(manifest.kind)
        if n_evicted:
            logger.info(
                "Evicted %d step-cache entries for plugin kind %r after re-install",
                n_evicted, manifest.kind,
            )
    except Exception:
        # Cache invalidation is best-effort; don't fail an install for it.
        logger.exception("Plugin cache invalidation failed (non-fatal)")

    # Mirror to the HF Datasets backing store so authenticated users'
    # plugins survive container restarts. No-op for anon users.
    if not _skip_dataset_sync:
        from app.services import datasets_storage

        datasets_storage.push_plugin(user_id, manifest.kind, zip_bytes)

    return manifest


def hydrate_from_dataset_if_needed(user_id: str) -> int:
    """For authenticated users on a freshly-restarted Space, pull any
    plugins from the HF Datasets backing store that aren't yet on
    /tmp. Idempotent + cheap when there's nothing to hydrate.

    Anon users always no-op (no persistent backing store)."""
    from app.services import auth_service, datasets_storage

    if not auth_service.is_hf_user_id(user_id):
        return 0
    user_dir = user_plugin_dir(user_id)
    return datasets_storage.hydrate_into_tmp(
        user_id, user_dir, install_plugin_zip
    )


def get_plugin_handler_path(user_id: str, kind: str) -> Path | None:
    """Resolve to the handler.py for a (user, kind) plugin, or None."""
    d = plugin_dir(user_id, kind)
    handler = d / "handler.py"
    if not handler.exists():
        return None
    return handler


# ---- Helper exposed to the frontend ------------------------------------

def manifest_to_frontend(m: PluginManifest) -> dict[str, Any]:
    """Shape the manifest into the JSON the front-end expects (mirrors
    the NodeSpec fields in frontend/src/lib/nodeCatalog.ts)."""
    return {
        "kind": m.kind,
        "label": m.label,
        "family": m.family,
        "tagline": m.tagline,
        "description": m.description,
        "color": m.color,
        "params": [p.model_dump(exclude_none=True) for p in m.params],
        "writes": m.writes,
        "author": m.author,
        "is_plugin": True,
    }