astrbot_plugin_private_comp.../p4_capabilities.py

154 行
5.3 KiB
Python

# -*- coding: utf-8 -*-
"""Strict, non-executing capability parsing for P4 management commands.
This module deliberately contains no AstrBot integration, persistence, owner
lookup, or state transition. It only recognizes a complete, unambiguous
command payload and returns the capability metadata needed by a later security
gate. A prefix match is never sufficient to bypass confinement handling.
The registry is immutable and P4-A remains shadow/advisory only. Callers must
still apply the P3 gates, resolve the stable target, verify owner authority,
write an audit event, and decide whether any later phase permits execution.
"""
from __future__ import annotations
from dataclasses import dataclass
import re
from types import MappingProxyType
from typing import Callable, Mapping
# Keep this grammar in lockstep with p4_affinity_confinement._EVENT_ID_RE.
# Unlike that internal normalization helper, this command parser never strips
# input: leading, trailing, or token-separating whitespace means no match.
_SAFE_EVENT_ID = r"[A-Za-z0-9][A-Za-z0-9_.:@/+-]{0,127}"
_PERSON_ID = r"person_[0-9a-f]{24}"
_P0_IDENTITY_KEY = r"ops-origin-v1:[0-9a-f]{64}"
_TARGET = rf"(?:{_PERSON_ID}|{_P0_IDENTITY_KEY})"
PERSON_ID_RE = re.compile(rf"{_PERSON_ID}\Z")
P0_IDENTITY_KEY_RE = re.compile(rf"{_P0_IDENTITY_KEY}\Z")
SAFE_EVENT_ID_RE = re.compile(rf"{_SAFE_EVENT_ID}\Z")
_RELEASE_RE = re.compile(rf"/放出 (?P<target>{_TARGET})\Z")
_MISJUDGMENT_RE = re.compile(
rf"/误判 (?P<target>{_TARGET})(?: (?P<event_id>{_SAFE_EVENT_ID}))?\Z"
)
@dataclass(frozen=True)
class Capability:
"""One exact, non-executing command capability.
``parser`` is intentionally exact: it receives the entire raw payload and
returns ``None`` unless every byte belongs to the command grammar.
"""
capability_id: str
parser: Callable[[str], tuple[str, str | None] | None]
group: str
tool: str
sensitivity: str
requires_owner_authorization: bool
self_service_allowed: bool
execution_mode: str
@dataclass(frozen=True)
class ParsedP4ManagementCommand:
"""A syntactically valid management intent, never an authorization result."""
capability_id: str
target: str
target_kind: str
event_id: str | None
group: str
tool: str
sensitivity: str
requires_owner_authorization: bool
self_service_allowed: bool
execution_mode: str
def _parse_release(payload: str) -> tuple[str, str | None] | None:
match = _RELEASE_RE.fullmatch(payload)
if match is None:
return None
return match.group("target"), None
def _parse_misjudgment(payload: str) -> tuple[str, str | None] | None:
match = _MISJUDGMENT_RE.fullmatch(payload)
if match is None:
return None
return match.group("target"), match.group("event_id")
# A tuple of frozen records makes command registration static. The companion
# runtime may consult this metadata later, but cannot use it as an authority
# decision or a live-effect switch during P4-A.
P4_CAPABILITY_REGISTRY: tuple[Capability, ...] = (
Capability(
capability_id="p4.owner_release",
parser=_parse_release,
group="p4_affinity_confinement",
tool="owner_release",
sensitivity="owner_only_confinement_exemption",
requires_owner_authorization=True,
self_service_allowed=False,
execution_mode="shadow_advisory_only",
),
Capability(
capability_id="p4.owner_misjudgment",
parser=_parse_misjudgment,
group="p4_affinity_confinement",
tool="owner_misjudgment",
sensitivity="owner_only_ledger_reversal",
requires_owner_authorization=True,
self_service_allowed=False,
execution_mode="shadow_advisory_only",
),
)
P4_CAPABILITY_BY_ID: Mapping[str, Capability] = MappingProxyType(
{capability.capability_id: capability for capability in P4_CAPABILITY_REGISTRY}
)
def parse_p4_management_command(payload: object) -> ParsedP4ManagementCommand | None:
"""Return a management intent only for a complete pure command payload.
The function intentionally performs no trimming, Unicode normalization,
nickname lookup, identity resolution, owner check, audit write, or state
transition. In particular, ``/放出`` or ``/误判`` prefixes surrounded by
prose do not match and therefore cannot receive command exemptions.
"""
if not isinstance(payload, str):
return None
for capability in P4_CAPABILITY_REGISTRY:
parsed = capability.parser(payload)
if parsed is None:
continue
target, event_id = parsed
target_kind = "person_id" if PERSON_ID_RE.fullmatch(target) else "p0_identity_key"
return ParsedP4ManagementCommand(
capability_id=capability.capability_id,
target=target,
target_kind=target_kind,
event_id=event_id,
group=capability.group,
tool=capability.tool,
sensitivity=capability.sensitivity,
requires_owner_authorization=capability.requires_owner_authorization,
self_service_allowed=capability.self_service_allowed,
execution_mode=capability.execution_mode,
)
return None
def is_exact_p4_management_command(payload: object) -> bool:
"""Whether ``payload`` is a complete registered P4 command, not an authorization."""
return parse_p4_management_command(payload) is not None