M3 plugin platform: frontend host, reference plugins, UI kit + docs
Completes M3 (SPEC §11 + §12 acceptance) on top of the backend platform (4e077f1).
Frontend host (§11.3):
- src/plugins/: manifest loader, runtime ESM bundle loader (framework-agnostic
mount contract), PluginSlot, PluginPage (app.page at /p/*), plugin context
(scoped api/events/i18n), capabilities hook. Wired slots into ThreadView
(message.actions/message.banner), MailLayout sidebar (sidebar.section + page nav)
and Settings→Accounts (settings.page); ws.ts fans out core + plugin.* events.
- plugin-ui.css: theme-aware .wm-* classes so bundles don't re-derive inline styles.
SDK additions:
- CurrentUserId + require_csrf (plugin-router auth), messages.envelope/header,
actions.set_flags/trash, sdk.enqueue.
Reference plugins (plugins/, installed via webmail.plugins entry points):
- hello: skeleton page-plugin (app.page + plg_hello_note w/ RLS + cron job) —
install→run→uninstall --drop-data leaves zero residue.
- labels: message.actions + sidebar.section slots, KV only, zero core diffs.
- filters: message.new hook -> match (subject/from/to) -> Mark read / Pin / Delete
(delete = move thread to Trash via the core path).
docs/plugins.md: full authoring guide + a complete "Unsubscribe button" worked
example (the §12 "writable from docs alone" bar).
Also: conftest resets the arq pool between tests (loop-bound global, like engine/redis).
Gates: backend ruff + mypy --strict (107) + full suite 337; frontend tsc + eslint
+ vitest (11) + vite build.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Rcj3TpydMTzTSmU7kunzf8
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
"""Message read + flag helpers exposed to plugins via the SDK (SPEC §11).
|
||||
|
||||
Plugins like ``filters`` need to inspect a newly-arrived message and flag it.
|
||||
Both operations are user-scoped: a plugin can only read/act on the given user's
|
||||
own message (the same app-level ``user_id`` scoping core uses — core tables have
|
||||
no RLS). Flagging mirrors the core action path: update the DB, enqueue the IMAP
|
||||
push, and publish ``flags.changed`` so the UI updates.
|
||||
|
||||
(Only flag actions are exposed for now; a ``move`` action would follow the same
|
||||
wrap-the-core-path pattern.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from collections.abc import Iterable
|
||||
from email import message_from_bytes
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from app.db import session_scope
|
||||
from app.events import get_event_bus
|
||||
from app.indexer import blobstore
|
||||
from app.models import Message
|
||||
|
||||
|
||||
class PluginMessages:
|
||||
"""Read-only, user-scoped view of a message's matchable fields."""
|
||||
|
||||
async def header(self, user_id: uuid.UUID, message_id: uuid.UUID, name: str) -> str | None:
|
||||
"""Return a raw header (e.g. ``List-Unsubscribe``) from the user's message,
|
||||
or None if the message/header/blob is missing. Parses the stored RFC822."""
|
||||
async with session_scope() as session:
|
||||
msg = await session.scalar(
|
||||
select(Message).where(Message.id == message_id, Message.user_id == user_id)
|
||||
)
|
||||
if msg is None or not msg.blob_sha256:
|
||||
return None
|
||||
sha = msg.blob_sha256
|
||||
try:
|
||||
raw = blobstore.load(user_id, sha)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
return message_from_bytes(raw).get(name)
|
||||
|
||||
async def envelope(self, user_id: uuid.UUID, message_id: uuid.UUID) -> dict[str, Any] | None:
|
||||
async with session_scope() as session:
|
||||
msg = await session.scalar(
|
||||
select(Message).where(Message.id == message_id, Message.user_id == user_id)
|
||||
)
|
||||
if msg is None:
|
||||
return None
|
||||
sender = msg.from_addr[0] if msg.from_addr else {}
|
||||
return {
|
||||
"message_id": str(msg.id),
|
||||
"subject": msg.subject or "",
|
||||
"from_email": (sender.get("email") or "").lower(),
|
||||
"from_name": sender.get("name") or "",
|
||||
# Full recipient list (multi-account setups match on "to").
|
||||
"to": [
|
||||
{"email": (a.get("email") or "").lower(), "name": a.get("name") or ""}
|
||||
for a in msg.to_addr
|
||||
],
|
||||
"flags": list(msg.flags),
|
||||
}
|
||||
|
||||
|
||||
class PluginActions:
|
||||
"""User-scoped actions a plugin can take on a message."""
|
||||
|
||||
async def set_flags(
|
||||
self,
|
||||
user_id: uuid.UUID,
|
||||
message_id: uuid.UUID,
|
||||
*,
|
||||
add: Iterable[str] = (),
|
||||
remove: Iterable[str] = (),
|
||||
) -> bool:
|
||||
"""Add/remove IMAP flags on the user's message (mirrors the core path).
|
||||
|
||||
Only user-settable flags survive (\\Seen/\\Flagged/\\Answered). Returns
|
||||
False if nothing owned matches or nothing would change."""
|
||||
from app.queue import enqueue_job
|
||||
from app.sync.actions import apply_flags_to_messages, sanitize_flags
|
||||
|
||||
add_f, remove_f = sanitize_flags(add), sanitize_flags(remove)
|
||||
if not add_f and not remove_f:
|
||||
return False
|
||||
async with session_scope() as session:
|
||||
msg = await session.scalar(
|
||||
select(Message).where(Message.id == message_id, Message.user_id == user_id)
|
||||
)
|
||||
if msg is None:
|
||||
return False
|
||||
await apply_flags_to_messages(session, [msg], add_f, remove_f)
|
||||
flags = list(msg.flags)
|
||||
await enqueue_job("push_flags_job", str(message_id), sorted(add_f), sorted(remove_f))
|
||||
await get_event_bus().publish(
|
||||
"flags.changed",
|
||||
{"user_id": str(user_id), "message_id": str(message_id), "flags": flags},
|
||||
)
|
||||
return True
|
||||
|
||||
async def trash(self, user_id: uuid.UUID, message_id: uuid.UUID) -> bool:
|
||||
"""Move the message's thread to Trash — the same path as the UI Delete
|
||||
(move_thread_to_folder_job handles the IMAP move, restore state, folder
|
||||
creation and events). Returns False if the message isn't the user's."""
|
||||
from app.queue import enqueue_job
|
||||
|
||||
async with session_scope() as session:
|
||||
msg = await session.scalar(
|
||||
select(Message).where(Message.id == message_id, Message.user_id == user_id)
|
||||
)
|
||||
if msg is None or msg.thread_id is None:
|
||||
return False
|
||||
thread_id = msg.thread_id
|
||||
await enqueue_job("move_thread_to_folder_job", str(thread_id), "trash")
|
||||
return True
|
||||
@@ -15,15 +15,19 @@ from __future__ import annotations
|
||||
import uuid
|
||||
from contextlib import AbstractAsyncContextManager
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
from typing import Annotated, Any
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.accounts.ssrf import guarded_get
|
||||
from app.config import Settings, get_settings
|
||||
from app.events import get_event_bus
|
||||
from app.identity.deps import current_user, require_csrf
|
||||
from app.indexer import blobstore
|
||||
from app.models import User
|
||||
from app.outbox import service as outbox_service
|
||||
from app.plugins.actions import PluginActions, PluginMessages
|
||||
from app.plugins.db import plugin_session
|
||||
from app.plugins.kv import PluginKvStore
|
||||
from app.plugins.types import (
|
||||
@@ -39,6 +43,7 @@ from app.plugins.types import (
|
||||
from app.queue import enqueue_job
|
||||
|
||||
__all__ = [
|
||||
"CurrentUserId",
|
||||
"Hook",
|
||||
"JobFunc",
|
||||
"JobSpec",
|
||||
@@ -49,10 +54,21 @@ __all__ = [
|
||||
"Slot",
|
||||
"UiManifest",
|
||||
"blobstore",
|
||||
"require_csrf",
|
||||
"sdk",
|
||||
]
|
||||
|
||||
|
||||
async def _current_user_id(user: Annotated[User, Depends(current_user)]) -> uuid.UUID:
|
||||
return user.id
|
||||
|
||||
|
||||
# Auth for plugin routers (plugins must not import app.identity directly, SPEC §11):
|
||||
# `CurrentUserId` resolves the authenticated user's id; `require_csrf` guards mutating
|
||||
# routes. Use with the RLS-scoped `sdk(name).session(user_id)`.
|
||||
CurrentUserId = Annotated[uuid.UUID, Depends(_current_user_id)]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PluginSdk:
|
||||
"""A lightweight facade over shared services, scoped to one plugin.
|
||||
@@ -105,6 +121,17 @@ class PluginSdk:
|
||||
"""Draft/send helpers (``upsert_draft``, ``create_outbox``, …)."""
|
||||
return outbox_service
|
||||
|
||||
# --- messages -----------------------------------------------------------
|
||||
@property
|
||||
def messages(self) -> PluginMessages:
|
||||
"""Read a user's message envelope (subject/sender/flags) for matching."""
|
||||
return PluginMessages()
|
||||
|
||||
@property
|
||||
def actions(self) -> PluginActions:
|
||||
"""User-scoped message actions (``set_flags``) — e.g. for filter rules."""
|
||||
return PluginActions()
|
||||
|
||||
# --- outbound HTTP ------------------------------------------------------
|
||||
async def http_get(self, url: str) -> str | None:
|
||||
"""GET ``url`` through the §10.6 SSRF guard (blocks private IPs/oversize)."""
|
||||
|
||||
Reference in New Issue
Block a user