postcrm-plugin-sdk 0.1.3__tar.gz

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,33 @@
1
+ PostCRM Plugin SDK License
2
+
3
+ Copyright (c) 2026 PostLTD. All rights reserved.
4
+
5
+ This license applies to the PostCRM Plugin SDK published by PostLTD: the
6
+ @postcrm/plugin-sdk-ui npm package and the postcrm-plugin-sdk Python package,
7
+ including their source code, documentation and build artifacts (the "SDK").
8
+
9
+ 1. Grant of use. PostLTD grants you a non-exclusive, royalty-free right to
10
+ use, copy, modify and compile the SDK solely to develop, build, test and
11
+ run plugins for the PostCRM platform.
12
+
13
+ 2. Restrictions. You may not:
14
+ a) sell, resell, sublicense or otherwise make the SDK available as a
15
+ standalone product, or as part of a product whose primary value is the
16
+ SDK itself;
17
+ b) publish, distribute or repackage the SDK (including modified copies) to
18
+ any public or private package registry, marketplace or repository as an
19
+ independent product;
20
+ c) remove or alter this license or any copyright notice.
21
+
22
+ 3. Plugins. Plugins that you develop using the SDK are your own work and may be
23
+ distributed under terms of your choice, provided that they do not contain or
24
+ redistribute the SDK itself.
25
+
26
+ 4. No warranty. THE SDK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
29
+ EVENT SHALL POSTLTD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY
30
+ ARISING FROM THE USE OF THE SDK.
31
+
32
+ 5. Termination. This license terminates automatically if you breach any of its
33
+ terms.
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.3
2
+ Name: postcrm-plugin-sdk
3
+ Version: 0.1.3
4
+ Summary: PostCRM plugin SDK (Python)
5
+ License: PostCRM Plugin SDK License
6
+
7
+ Copyright (c) 2026 PostLTD. All rights reserved.
8
+
9
+ This license applies to the PostCRM Plugin SDK published by PostLTD: the
10
+ @postcrm/plugin-sdk-ui npm package and the postcrm-plugin-sdk Python package,
11
+ including their source code, documentation and build artifacts (the "SDK").
12
+
13
+ 1. Grant of use. PostLTD grants you a non-exclusive, royalty-free right to
14
+ use, copy, modify and compile the SDK solely to develop, build, test and
15
+ run plugins for the PostCRM platform.
16
+
17
+ 2. Restrictions. You may not:
18
+ a) sell, resell, sublicense or otherwise make the SDK available as a
19
+ standalone product, or as part of a product whose primary value is the
20
+ SDK itself;
21
+ b) publish, distribute or repackage the SDK (including modified copies) to
22
+ any public or private package registry, marketplace or repository as an
23
+ independent product;
24
+ c) remove or alter this license or any copyright notice.
25
+
26
+ 3. Plugins. Plugins that you develop using the SDK are your own work and may be
27
+ distributed under terms of your choice, provided that they do not contain or
28
+ redistribute the SDK itself.
29
+
30
+ 4. No warranty. THE SDK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
33
+ EVENT SHALL POSTLTD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY
34
+ ARISING FROM THE USE OF THE SDK.
35
+
36
+ 5. Termination. This license terminates automatically if you breach any of its
37
+ terms.
38
+ Keywords: postcrm,plugin,sdk,fastapi
39
+ Author: PostCRM
40
+ Requires-Python: >=3.12,<4.0
41
+ Classifier: Framework :: FastAPI
42
+ Classifier: License :: Other/Proprietary License
43
+ Classifier: Programming Language :: Python :: 3
44
+ Classifier: Programming Language :: Python :: 3.12
45
+ Classifier: Programming Language :: Python :: 3.13
46
+ Requires-Dist: cryptography (>=43.0,<44.0)
47
+ Requires-Dist: fastapi (>=0.110.3)
48
+ Requires-Dist: httpx (>=0.28.1,<0.29.0)
49
+ Requires-Dist: pydantic (>=2.0)
50
+ Requires-Dist: uvicorn (>=0.30.1,<0.31.0)
51
+ Description-Content-Type: text/markdown
52
+
53
+ # postcrm-plugin-sdk
54
+
55
+ Python SDK для backend-части плагинов PostCRM. Пакет публикуется в публичный
56
+ PyPI.
57
+
58
+ ## Установка
59
+
60
+ ```bash
61
+ pip install postcrm-plugin-sdk
62
+ ```
63
+
64
+ Токен и дополнительный index-url не нужны. Для установки без registry
65
+ используйте git+https или wheel/sdist из релиза репозитория.
66
+
67
+ ## create_app
68
+
69
+ ```python
70
+ from fastapi import APIRouter
71
+ from postcrm_plugin_sdk import create_app
72
+
73
+ router = APIRouter()
74
+
75
+
76
+ @router.get("/hello")
77
+ async def hello() -> dict[str, str]:
78
+ return {"message": "hello"}
79
+
80
+
81
+ app = create_app(router=router)
82
+ ```
83
+
84
+ ## Context
85
+
86
+ ```python
87
+ from fastapi import Depends
88
+ from postcrm_plugin_sdk import PluginContext, get_plugin_context
89
+
90
+
91
+ @router.get("/account")
92
+ async def account(context: PluginContext = Depends(get_plugin_context)):
93
+ return {"accountId": context.account_id}
94
+ ```
95
+
96
+ Context приходит от runner-а, проверяется по HMAC и сроку действия. Плагин не
97
+ получает JWT пользователя или секрет подписи.
98
+
99
+ ## CrmClient
100
+
101
+ ```python
102
+ from postcrm_plugin_sdk import CrmClient
103
+
104
+ items = await CrmClient(context).inquiry_read(limit=10)
105
+ ```
106
+
107
+ Клиент выполняет только разрешенные manifest-ом curated capabilities.
108
+
109
+ ## ExternalHTTP
110
+
111
+ ```python
112
+ from postcrm_plugin_sdk import ExternalHTTP
113
+
114
+ data = await ExternalHTTP(context).request("GET", "https://api.example.com/data")
115
+ ```
116
+
117
+ Запрос идет через runner egress proxy с проверкой allowlist.
118
+
119
+ ## Sandbox
120
+
121
+ Sandbox-orchestrator в пакет не входит: hardened runtime поставляется
122
+ отдельным сервисом.
123
+
124
+ ## Лицензия
125
+
126
+ Пакет распространяется по PostCRM Plugin SDK License (см. `LICENSE` в
127
+ пакете): SDK разрешено использовать только для разработки, сборки и запуска
128
+ плагинов PostCRM.
129
+
@@ -0,0 +1,76 @@
1
+ # postcrm-plugin-sdk
2
+
3
+ Python SDK для backend-части плагинов PostCRM. Пакет публикуется в публичный
4
+ PyPI.
5
+
6
+ ## Установка
7
+
8
+ ```bash
9
+ pip install postcrm-plugin-sdk
10
+ ```
11
+
12
+ Токен и дополнительный index-url не нужны. Для установки без registry
13
+ используйте git+https или wheel/sdist из релиза репозитория.
14
+
15
+ ## create_app
16
+
17
+ ```python
18
+ from fastapi import APIRouter
19
+ from postcrm_plugin_sdk import create_app
20
+
21
+ router = APIRouter()
22
+
23
+
24
+ @router.get("/hello")
25
+ async def hello() -> dict[str, str]:
26
+ return {"message": "hello"}
27
+
28
+
29
+ app = create_app(router=router)
30
+ ```
31
+
32
+ ## Context
33
+
34
+ ```python
35
+ from fastapi import Depends
36
+ from postcrm_plugin_sdk import PluginContext, get_plugin_context
37
+
38
+
39
+ @router.get("/account")
40
+ async def account(context: PluginContext = Depends(get_plugin_context)):
41
+ return {"accountId": context.account_id}
42
+ ```
43
+
44
+ Context приходит от runner-а, проверяется по HMAC и сроку действия. Плагин не
45
+ получает JWT пользователя или секрет подписи.
46
+
47
+ ## CrmClient
48
+
49
+ ```python
50
+ from postcrm_plugin_sdk import CrmClient
51
+
52
+ items = await CrmClient(context).inquiry_read(limit=10)
53
+ ```
54
+
55
+ Клиент выполняет только разрешенные manifest-ом curated capabilities.
56
+
57
+ ## ExternalHTTP
58
+
59
+ ```python
60
+ from postcrm_plugin_sdk import ExternalHTTP
61
+
62
+ data = await ExternalHTTP(context).request("GET", "https://api.example.com/data")
63
+ ```
64
+
65
+ Запрос идет через runner egress proxy с проверкой allowlist.
66
+
67
+ ## Sandbox
68
+
69
+ Sandbox-orchestrator в пакет не входит: hardened runtime поставляется
70
+ отдельным сервисом.
71
+
72
+ ## Лицензия
73
+
74
+ Пакет распространяется по PostCRM Plugin SDK License (см. `LICENSE` в
75
+ пакете): SDK разрешено использовать только для разработки, сборки и запуска
76
+ плагинов PostCRM.
@@ -0,0 +1,29 @@
1
+ """Python SDK плагинов PostCRM."""
2
+
3
+ from postcrm_plugin_sdk.app import create_app, get_plugin_context, require_capability
4
+ from postcrm_plugin_sdk.context import (
5
+ ContextError,
6
+ PluginContext,
7
+ parse_context,
8
+ plugin_database_dsn,
9
+ resolve_secret,
10
+ sign_context,
11
+ )
12
+ from postcrm_plugin_sdk.curated import CrmClient, CuratedError, ExternalHTTP
13
+ from postcrm_plugin_sdk.errors import PluginAPIError
14
+
15
+ __all__ = [
16
+ "ContextError",
17
+ "CrmClient",
18
+ "CuratedError",
19
+ "ExternalHTTP",
20
+ "PluginAPIError",
21
+ "PluginContext",
22
+ "create_app",
23
+ "get_plugin_context",
24
+ "parse_context",
25
+ "plugin_database_dsn",
26
+ "resolve_secret",
27
+ "require_capability",
28
+ "sign_context",
29
+ ]
@@ -0,0 +1,107 @@
1
+ """FastAPI-фабрика plugin worker-а."""
2
+
3
+ from collections.abc import Awaitable, Callable
4
+ from typing import Any
5
+
6
+ from fastapi import APIRouter, Depends, FastAPI, Request
7
+ from fastapi.responses import JSONResponse
8
+
9
+ from postcrm_plugin_sdk.context import ContextError, PluginContext, parse_context
10
+ from postcrm_plugin_sdk.errors import PluginAPIError, plugin_api_error_handler
11
+
12
+ PLUGIN_ID_ENV = "PLUGIN_ID"
13
+ PLUGIN_VERSION_ENV = "PLUGIN_VERSION"
14
+
15
+
16
+ def get_plugin_context(request: Request) -> PluginContext:
17
+ """Возвращает проверенный context запроса.
18
+
19
+ :param request: Request - Запрос.
20
+
21
+ :return: PluginContext - Контекст.
22
+ """
23
+ context = getattr(request.state, "plugin_context", None)
24
+ if context is None:
25
+ raise PluginAPIError("PLUGIN_FORBIDDEN", 403)
26
+ return context
27
+
28
+
29
+ def require_capability(capability: str) -> Callable[[PluginContext], PluginContext]:
30
+ """Создаёт dependency обязательной capability.
31
+
32
+ :param capability: str - Capability.
33
+
34
+ :return: Callable - Dependency.
35
+ """
36
+
37
+ def checker(context: PluginContext = Depends(get_plugin_context)) -> PluginContext:
38
+ try:
39
+ context.require(capability)
40
+ except ContextError as error:
41
+ raise PluginAPIError(error.code, 403) from error
42
+ return context
43
+
44
+ return checker
45
+
46
+
47
+ def create_app(
48
+ *,
49
+ plugin_id: str | None = None,
50
+ version: str | None = None,
51
+ sdk_major: int = 1,
52
+ router: APIRouter | None = None,
53
+ on_startup: Callable[[], Awaitable[None]] | None = None,
54
+ on_shutdown: Callable[[], Awaitable[None]] | None = None,
55
+ ) -> FastAPI:
56
+ """Создаёт ASGI-приложение плагина.
57
+
58
+ :param plugin_id: str | None - ID плагина (по умолчанию env).
59
+ :param version: str | None - Версия (по умолчанию env).
60
+ :param sdk_major: int - Major версия SDK.
61
+ :param router: APIRouter | None - Пользовательские routes.
62
+ :param on_startup: Callable | None - Async startup hook.
63
+ :param on_shutdown: Callable | None - Async shutdown hook.
64
+
65
+ :return: FastAPI - Приложение.
66
+ """
67
+ import os
68
+
69
+ identifier = plugin_id or os.environ.get(PLUGIN_ID_ENV, "unknown")
70
+ plugin_version = version or os.environ.get(PLUGIN_VERSION_ENV, "0.0.0")
71
+
72
+ app = FastAPI(title=f"PostCRM plugin {identifier}", docs_url=None, redoc_url=None, openapi_url=None)
73
+ app.add_exception_handler(PluginAPIError, plugin_api_error_handler) # pyright: ignore[reportArgumentType]
74
+
75
+ @app.middleware("http")
76
+ async def context_middleware(request: Request, call_next: Callable[[Request], Awaitable[Any]]):
77
+ if request.url.path in {"/healthz", "/readyz"}:
78
+ return await call_next(request)
79
+ try:
80
+ request.state.plugin_context = parse_context(dict(request.headers))
81
+ except ContextError as error:
82
+ return JSONResponse(status_code=403, content={"code": error.code})
83
+ return await call_next(request)
84
+
85
+ @app.get("/healthz")
86
+ async def healthz() -> dict[str, Any]:
87
+ """Readiness для runner-а."""
88
+ return {
89
+ "plugin_id": identifier,
90
+ "version": plugin_version,
91
+ "sdk_major": sdk_major,
92
+ "ready": True,
93
+ }
94
+
95
+ @app.get("/readyz")
96
+ async def readyz() -> dict[str, Any]:
97
+ """Псевдоним healthz."""
98
+ return await healthz()
99
+
100
+ if router is not None:
101
+ app.include_router(router)
102
+
103
+ if on_startup is not None:
104
+ app.router.on_startup.append(on_startup)
105
+ if on_shutdown is not None:
106
+ app.router.on_shutdown.append(on_shutdown)
107
+ return app
@@ -0,0 +1,203 @@
1
+ """Проверенный короткоживущий context плагина."""
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import os
7
+ import time
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+
11
+ CONTEXT_HEADER = "x-postcrm-plugin-context"
12
+ SIGNATURE_HEADER = "x-postcrm-plugin-context-signature"
13
+
14
+
15
+ class ContextError(RuntimeError):
16
+ """Context отсутствует, просрочен или подпись неверна."""
17
+
18
+ def __init__(self, code: str = "PLUGIN_FORBIDDEN") -> None:
19
+ super().__init__(code)
20
+ self.code = code
21
+
22
+
23
+ def canonical_context(context: dict[str, Any]) -> bytes:
24
+ """Формирует канонический JSON контекста.
25
+
26
+ :param context: dict - Контекст.
27
+
28
+ :return: bytes - Стабильное представление.
29
+ """
30
+ return json.dumps(context, sort_keys=True, separators=(",", ":")).encode("utf-8")
31
+
32
+
33
+ def sign_context(context: dict[str, Any], secret: str) -> str:
34
+ """Подписывает контекст HMAC-SHA256.
35
+
36
+ :param context: dict - Контекст.
37
+ :param secret: str - Секрет.
38
+
39
+ :return: str - Hex-подпись.
40
+ """
41
+ return hmac.new(secret.encode("utf-8"), canonical_context(context), hashlib.sha256).hexdigest()
42
+
43
+
44
+ @dataclass
45
+ class PluginContext:
46
+ """Контекст запроса, доступный коду плагина.
47
+
48
+ Плагин не получает JWT, cookies, DB DSN или management token. Все поля
49
+ приходят из подписанного runner/core контекста.
50
+ """
51
+
52
+ request_id: str
53
+ plugin_id: str
54
+ version: str
55
+ installation_id: int
56
+ account_id: int
57
+ user_id: int
58
+ role: str
59
+ capabilities: list[str] = field(default_factory=list[str])
60
+ sdk_major: int = 1
61
+ issued_at: int = 0
62
+ expires_at: int = 0
63
+ surface: str | None = None
64
+ settings: dict[str, Any] = field(default_factory=dict[str, Any])
65
+ secret_refs: dict[str, str] = field(default_factory=dict[str, str])
66
+ request_handle: str = ""
67
+ raw: dict[str, Any] = field(default_factory=dict[str, Any])
68
+
69
+ @classmethod
70
+ def from_dict(cls, data: dict[str, Any]) -> "PluginContext":
71
+ """Создаёт контекст из проверенного dict.
72
+
73
+ :param data: dict - Проверенный контекст.
74
+
75
+ :return: PluginContext - Модель.
76
+ """
77
+ return cls(
78
+ request_id=str(data.get("request_id", "")),
79
+ plugin_id=str(data.get("plugin_id", "")),
80
+ version=str(data.get("version", "")),
81
+ installation_id=int(data.get("installation_id", 0) or 0),
82
+ account_id=int(data.get("account_id", 0) or 0),
83
+ user_id=int(data.get("user_id", 0) or 0),
84
+ role=str(data.get("role", "")),
85
+ capabilities=[str(item) for item in data.get("capabilities", [])],
86
+ sdk_major=int(data.get("sdk_major", 1) or 1),
87
+ issued_at=int(data.get("issued_at", 0) or 0),
88
+ expires_at=int(data.get("expires_at", 0) or 0),
89
+ surface=str(data["surface"]) if data.get("surface") else None,
90
+ settings=dict(data.get("settings", {})) if isinstance(data.get("settings"), dict) else {},
91
+ secret_refs={str(key): str(value) for key, value in (data.get("secret_refs", {}) or {}).items()}
92
+ if isinstance(data.get("secret_refs"), dict)
93
+ else {},
94
+ request_handle=str(data.get("request_handle", "")),
95
+ raw=data,
96
+ )
97
+
98
+ def require(self, capability: str) -> None:
99
+ """Проверяет выданную capability.
100
+
101
+ :raises ContextError: Если capability не выдана.
102
+ """
103
+ if capability not in self.capabilities:
104
+ raise ContextError("PLUGIN_FORBIDDEN")
105
+
106
+ def worker_headers(self) -> dict[str, str]:
107
+ """Формирует заголовки worker -> runner.
108
+
109
+ Handle выдан runner-ом на время текущего запроса и не позволяет
110
+ подделать account/user/role. Секрет подписи worker-у недоступен.
111
+
112
+ :return: dict[str, str] - Заголовок handle.
113
+ """
114
+ return {"X-PostCRM-Request-Handle": self.request_handle}
115
+
116
+
117
+ def parse_context(headers: dict[str, str], *, secret: str | None = None) -> PluginContext:
118
+ """Разбирает context, доставленный runner-ом по private UDS.
119
+
120
+ Worker не владеет HMAC-секретом: доверие основано на приватном сокете,
121
+ правах uid и короткоживущем request handle. ``secret`` оставлен для
122
+ обратной совместимости и не используется.
123
+
124
+ :param headers: dict[str, str] - HTTP-заголовки (case-insensitive).
125
+ :param secret: str | None - Не используется.
126
+
127
+ :return: PluginContext - Проверенный контекст.
128
+
129
+ :raises ContextError: Если context отсутствует или просрочен.
130
+ """
131
+ lowered = {key.lower(): value for key, value in headers.items()}
132
+ raw_context = lowered.get(CONTEXT_HEADER)
133
+ handle = lowered.get("x-postcrm-request-handle", "")
134
+ allow_unsigned = os.environ.get("PLUGIN_SDK_ALLOW_UNSIGNED", "false").lower() == "true"
135
+ if not raw_context:
136
+ if allow_unsigned:
137
+ return PluginContext(
138
+ request_id="dev",
139
+ plugin_id=os.environ.get("PLUGIN_ID", "dev"),
140
+ version=os.environ.get("PLUGIN_VERSION", "0.0.0"),
141
+ installation_id=0,
142
+ account_id=0,
143
+ user_id=0,
144
+ role="SYSTEM",
145
+ sdk_major=1,
146
+ issued_at=int(time.time()),
147
+ expires_at=int(time.time()) + 60,
148
+ )
149
+ raise ContextError()
150
+ try:
151
+ data = json.loads(raw_context)
152
+ except json.JSONDecodeError as error:
153
+ raise ContextError() from error
154
+ if not isinstance(data, dict):
155
+ raise ContextError()
156
+ # Context приходит по private UDS от runner-а. Worker не владеет секретом
157
+ # подписи, поэтому доверяет источнику сокета, а не собственному вычислению
158
+ # HMAC. Handle обязателен для последующих worker -> runner вызовов.
159
+ if handle:
160
+ data["request_handle"] = handle
161
+ expires_at = int(data.get("expires_at", 0) or 0)
162
+ if expires_at and expires_at < int(time.time()):
163
+ raise ContextError()
164
+ return PluginContext.from_dict(data)
165
+
166
+
167
+ async def resolve_secret(reference: str, context: "PluginContext | None" = None) -> str:
168
+ """Разрешает logical secret reference через runner broker.
169
+
170
+ Значения не хранятся в context и не попадают в plugin package.
171
+
172
+ :param reference: str - secret:// или docker:// ссылка.
173
+
174
+ :return: str - Значение секрета.
175
+ """
176
+ import os
177
+
178
+ import httpx
179
+
180
+ handle = context.request_handle if context is not None else os.environ.get("PLUGIN_REQUEST_HANDLE", "")
181
+ if not handle:
182
+ raise ContextError("PLUGIN_FORBIDDEN")
183
+ runner_url = os.environ.get("PLUGIN_RUNNER_WORKER_URL", "http://127.0.0.1:8090").rstrip("/")
184
+ async with httpx.AsyncClient(timeout=httpx.Timeout(10.0)) as client:
185
+ response = await client.post(
186
+ f"{runner_url}/worker/secrets/resolve",
187
+ headers={"X-PostCRM-Request-Handle": handle},
188
+ json={"ref": reference},
189
+ )
190
+ if response.status_code >= 400:
191
+ raise ContextError("PLUGIN_FORBIDDEN")
192
+ return str(response.json().get("value", ""))
193
+
194
+
195
+ def plugin_database_dsn() -> str | None:
196
+ """Возвращает DSN только к plugin-owned schema.
197
+
198
+ Общий DSN CRM worker-у не передается; значение выставляется runner-ом
199
+ из per-plugin runtime role.
200
+
201
+ :return: str | None - DSN или None, если database.own не включен.
202
+ """
203
+ return os.environ.get("PLUGIN_DB_DSN") or None
@@ -0,0 +1,113 @@
1
+ """Клиент curated CRM capabilities через host-mediated runner."""
2
+
3
+ import os
4
+ from typing import Any
5
+
6
+ import httpx
7
+
8
+ from postcrm_plugin_sdk.context import PluginContext
9
+
10
+
11
+ class CuratedError(RuntimeError):
12
+ """Capability недоступна или вернула ошибку."""
13
+
14
+ def __init__(self, code: str, message: str = "") -> None:
15
+ super().__init__(message or code)
16
+ self.code = code
17
+ self.message = message or code
18
+
19
+
20
+ class CrmClient:
21
+ """Узкий клиент разрешенных CRM-операций.
22
+
23
+ Worker не знает core URL/DSN/JWT: запрос идет в runner, который
24
+ проверяет подпись и пересылает его в core с management token.
25
+ """
26
+
27
+ def __init__(self, context: PluginContext, *, runner_url: str | None = None) -> None:
28
+ self.context = context
29
+ self.runner_url = (runner_url or os.environ.get("PLUGIN_RUNNER_WORKER_URL", "http://127.0.0.1:8090")).rstrip(
30
+ "/"
31
+ )
32
+
33
+ async def execute(self, capability: str, payload: dict[str, Any]) -> dict[str, Any]:
34
+ """Выполняет capability.
35
+
36
+ :param capability: str - Имя capability.
37
+ :param payload: dict - Параметры.
38
+
39
+ :return: dict - Результат.
40
+ """
41
+ self.context.require(capability)
42
+ headers = {"Content-Type": "application/json", **self.context.worker_headers()}
43
+ async with httpx.AsyncClient(timeout=httpx.Timeout(20.0)) as client:
44
+ response = await client.post(
45
+ f"{self.runner_url}/worker/capabilities/{capability}",
46
+ headers=headers,
47
+ json={"capability": capability, "payload": payload},
48
+ )
49
+ if response.status_code >= 400:
50
+ data = response.json() if response.content else {}
51
+ raise CuratedError(str(data.get("code", "PLUGIN_FORBIDDEN")), str(data.get("message", "")))
52
+ return response.json()
53
+
54
+ async def inquiry_read(self, **payload: Any) -> dict[str, Any]:
55
+ """Читает заявки аккаунта."""
56
+ return await self.execute("crm.inquiry.read", payload)
57
+
58
+ async def interaction_read(self, **payload: Any) -> dict[str, Any]:
59
+ """Читает обращения аккаунта."""
60
+ return await self.execute("crm.interaction.read", payload)
61
+
62
+ async def user_read_basic(self, **payload: Any) -> dict[str, Any]:
63
+ """Читает базовые профили пользователей аккаунта."""
64
+ return await self.execute("crm.user.read_basic", payload)
65
+
66
+ async def notification_create(self, **payload: Any) -> dict[str, Any]:
67
+ """Создаёт уведомление пользователю аккаунта."""
68
+ return await self.execute("crm.notification.create", payload)
69
+
70
+
71
+ class ExternalHTTP:
72
+ """Управляемый внешний HTTP через runner egress proxy."""
73
+
74
+ def __init__(self, context: PluginContext, *, runner_url: str | None = None) -> None:
75
+ self.context = context
76
+ self.runner_url = (runner_url or os.environ.get("PLUGIN_RUNNER_WORKER_URL", "http://127.0.0.1:8090")).rstrip(
77
+ "/"
78
+ )
79
+ self.allowed_origins = [
80
+ origin for origin in os.environ.get("PLUGIN_EGRESS_ORIGINS", "").split(",") if origin.strip()
81
+ ]
82
+
83
+ async def request(
84
+ self,
85
+ method: str,
86
+ url: str,
87
+ *,
88
+ headers: dict[str, str] | None = None,
89
+ body: str = "",
90
+ ) -> dict[str, Any]:
91
+ """Выполняет внешний запрос через allowlist.
92
+
93
+ :return: dict - Ответ `{status, headers, body}`.
94
+ """
95
+ request_headers = {"Content-Type": "application/json", **self.context.worker_headers()}
96
+ async with httpx.AsyncClient(timeout=httpx.Timeout(20.0)) as client:
97
+ response = await client.post(
98
+ f"{self.runner_url}/worker/egress",
99
+ headers=request_headers,
100
+ json={
101
+ "plugin_id": self.context.plugin_id,
102
+ "account_id": self.context.account_id,
103
+ "url": url,
104
+ "method": method,
105
+ "headers": headers or {},
106
+ "body": body,
107
+ "allowed_origins": self.allowed_origins,
108
+ },
109
+ )
110
+ if response.status_code >= 400:
111
+ data = response.json() if response.content else {}
112
+ raise CuratedError(str(data.get("code", "PLUGIN_EGRESS_DENIED")))
113
+ return response.json()
@@ -0,0 +1,28 @@
1
+ """Стабильные ошибки plugin API."""
2
+
3
+ from fastapi import Request
4
+ from fastapi.responses import JSONResponse
5
+
6
+
7
+ class PluginAPIError(Exception):
8
+ """Ошибка с machine-readable кодом для host UI."""
9
+
10
+ def __init__(self, code: str, status_code: int = 400, message: str = "") -> None:
11
+ super().__init__(message or code)
12
+ self.code = code
13
+ self.status_code = status_code
14
+ self.message = message
15
+
16
+
17
+ async def plugin_api_error_handler(_request: Request, error: PluginAPIError) -> JSONResponse:
18
+ """Преобразует ошибку плагина в стабильный JSON.
19
+
20
+ :param _request: Request - Запрос.
21
+ :param error: PluginAPIError - Ошибка.
22
+
23
+ :return: JSONResponse - Ответ.
24
+ """
25
+ payload = {"code": error.code}
26
+ if error.message:
27
+ payload["message"] = error.message
28
+ return JSONResponse(status_code=error.status_code, content=payload)
@@ -0,0 +1,219 @@
1
+ """Сборка, checksums, SBOM и подпись `.postcrm-plugin`."""
2
+
3
+ import base64
4
+ import hashlib
5
+ import json
6
+ import zipfile
7
+ from pathlib import Path
8
+ from typing import Any
9
+
10
+ from cryptography.hazmat.primitives import serialization
11
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
12
+
13
+ NON_HASHED_FILES = {"checksums.json", "signature.sig", "signature.json"}
14
+ FORBIDDEN_SOURCE_PARTS = {
15
+ ".git",
16
+ ".env",
17
+ ".venv",
18
+ "node_modules",
19
+ "__pycache__",
20
+ "dist",
21
+ }
22
+ FORBIDDEN_SOURCE_SUFFIXES = {".pem", ".key", ".p12", ".pfx"}
23
+
24
+
25
+ class PackageError(ValueError):
26
+ """Ошибка сборки пакета."""
27
+
28
+
29
+ def canonical_signing_payload(*, plugin_id: str, version: str, package_hash: str) -> bytes:
30
+ """Канонический payload подписи.
31
+
32
+ :return: bytes - JSON.
33
+ """
34
+ return json.dumps(
35
+ {"pluginId": plugin_id, "version": version, "packageHash": package_hash},
36
+ sort_keys=True,
37
+ separators=(",", ":"),
38
+ ).encode("utf-8")
39
+
40
+
41
+ def canonical_hash(files: dict[str, bytes]) -> str:
42
+ """Canonical hash содержимого пакета.
43
+
44
+ :param files: dict[str, bytes] - Файлы.
45
+
46
+ :return: str - SHA-256.
47
+ """
48
+ digest = hashlib.sha256()
49
+ for path in sorted(files):
50
+ if path in NON_HASHED_FILES:
51
+ continue
52
+ digest.update(path.encode("utf-8"))
53
+ digest.update(b"\0")
54
+ digest.update(hashlib.sha256(files[path]).digest())
55
+ digest.update(b"\0")
56
+ return digest.hexdigest()
57
+
58
+
59
+ def build_checksums(files: dict[str, bytes]) -> dict[str, str]:
60
+ """Формирует checksums.json.
61
+
62
+ :param files: dict[str, bytes] - Файлы без checksums/signature.
63
+
64
+ :return: dict[str, str] - Хэши файлов и packageHash.
65
+ """
66
+ checksums = {
67
+ path: hashlib.sha256(content).hexdigest() for path, content in files.items() if path not in NON_HASHED_FILES
68
+ }
69
+ checksums["packageHash"] = canonical_hash(files)
70
+ return checksums
71
+
72
+
73
+ def load_private_key(path: str | Path) -> Ed25519PrivateKey:
74
+ """Загружает Ed25519 private key из PEM.
75
+
76
+ :param path: str | Path - Путь.
77
+
78
+ :return: Ed25519PrivateKey - Ключ.
79
+ """
80
+ key = serialization.load_pem_private_key(Path(path).read_bytes(), password=None)
81
+ if not isinstance(key, Ed25519PrivateKey):
82
+ raise PackageError("Ожидается Ed25519 private key")
83
+ return key
84
+
85
+
86
+ def generate_keypair(private_path: str | Path, public_path: str | Path) -> None:
87
+ """Создаёт Ed25519 keypair для издателя.
88
+
89
+ :param private_path: str | Path - Путь private key.
90
+ :param public_path: str | Path - Путь public key.
91
+ """
92
+ private_key = Ed25519PrivateKey.generate()
93
+ private_file = Path(private_path)
94
+ private_file.write_bytes(
95
+ private_key.private_bytes(
96
+ encoding=serialization.Encoding.PEM,
97
+ format=serialization.PrivateFormat.PKCS8,
98
+ encryption_algorithm=serialization.NoEncryption(),
99
+ )
100
+ )
101
+ private_file.chmod(0o600)
102
+ Path(public_path).write_bytes(
103
+ private_key.public_key().public_bytes(
104
+ encoding=serialization.Encoding.PEM,
105
+ format=serialization.PublicFormat.SubjectPublicKeyInfo,
106
+ )
107
+ )
108
+
109
+
110
+ def generate_sbom(*, name: str, version: str, components: list[dict[str, Any]] | None = None) -> dict[str, Any]:
111
+ """Формирует минимальный SBOM.
112
+
113
+ :param name: str - Имя пакета.
114
+ :param version: str - Версия.
115
+ :param components: list | None - Компоненты.
116
+
117
+ :return: dict - SBOM.
118
+ """
119
+ return {
120
+ "bomFormat": "CycloneDX",
121
+ "specVersion": "1.5",
122
+ "version": 1,
123
+ "metadata": {"component": {"type": "application", "name": name, "version": version}},
124
+ "components": components or [],
125
+ }
126
+
127
+
128
+ def build_package(
129
+ *,
130
+ source_dir: str | Path,
131
+ output: str | Path,
132
+ private_key_path: str | Path,
133
+ key_id: str,
134
+ sbom_components: list[dict[str, Any]] | None = None,
135
+ ) -> Path:
136
+ """Собирает подписанный `.postcrm-plugin`.
137
+
138
+ :param source_dir: str | Path - Каталог с manifest.json и frontend/backend.
139
+ :param output: str | Path - Путь архива.
140
+ :param private_key_path: str | Path - Ed25519 private key.
141
+ :param key_id: str - ID ключа.
142
+ :param sbom_components: list | None - Компоненты SBOM.
143
+
144
+ :return: Path - Созданный архив.
145
+ """
146
+ source = Path(source_dir)
147
+ manifest_path = source / "manifest.json"
148
+ if not manifest_path.is_file():
149
+ raise PackageError("manifest.json не найден")
150
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
151
+ plugin_id = str(manifest.get("id", ""))
152
+ version = str(manifest.get("version", ""))
153
+ files: dict[str, bytes] = {}
154
+ for path in sorted(source.rglob("*")):
155
+ if not path.is_file():
156
+ continue
157
+ relative = path.relative_to(source).as_posix()
158
+ parts = set(relative.split("/"))
159
+ if parts & FORBIDDEN_SOURCE_PARTS or path.suffix.lower() in FORBIDDEN_SOURCE_SUFFIXES:
160
+ continue
161
+ if relative in {"sbom.json", "checksums.json", "signature.sig", "signature.json"}:
162
+ continue
163
+ files[relative] = path.read_bytes()
164
+
165
+ files["sbom.json"] = json.dumps(
166
+ generate_sbom(name=plugin_id, version=version, components=sbom_components),
167
+ ensure_ascii=False,
168
+ indent=2,
169
+ ).encode("utf-8")
170
+ checksums = build_checksums(files)
171
+ files["checksums.json"] = json.dumps(checksums, sort_keys=True, indent=2).encode("utf-8")
172
+ package_hash = checksums["packageHash"]
173
+ signature = load_private_key(private_key_path).sign(
174
+ canonical_signing_payload(plugin_id=plugin_id, version=version, package_hash=package_hash)
175
+ )
176
+ files["signature.sig"] = base64.b64encode(signature)
177
+ files["signature.json"] = json.dumps({"keyId": key_id}, sort_keys=True).encode("utf-8")
178
+
179
+ target = Path(output)
180
+ target.parent.mkdir(parents=True, exist_ok=True)
181
+ with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED) as archive:
182
+ for path, content in sorted(files.items()):
183
+ archive.writestr(path, content)
184
+ return target
185
+
186
+
187
+ def inspect_package(data: bytes) -> dict[str, Any]:
188
+ """Проверяет базовую структуру пакета без core-специфичной политики.
189
+
190
+ :param data: bytes - Архив.
191
+
192
+ :return: dict - `{"manifest", "packageHash", "files"}`.
193
+ """
194
+ import io
195
+
196
+ try:
197
+ archive = zipfile.ZipFile(io.BytesIO(data))
198
+ except zipfile.BadZipFile as error:
199
+ raise PackageError("invalid zip") from error
200
+ files = {info.filename: archive.read(info) for info in archive.infolist() if not info.is_dir()}
201
+ for path in files:
202
+ if path.startswith("/") or ".." in path.split("/") or "\\" in path:
203
+ raise PackageError(f"unsafe path: {path}")
204
+ if "manifest.json" not in files or "checksums.json" not in files:
205
+ raise PackageError("manifest.json/checksums.json отсутствуют")
206
+ checksums = json.loads(files["checksums.json"])
207
+ package_hash = canonical_hash(files)
208
+ if checksums.get("packageHash") != package_hash:
209
+ raise PackageError("packageHash mismatch")
210
+ for path, content in files.items():
211
+ if path in NON_HASHED_FILES:
212
+ continue
213
+ if checksums.get(path) != hashlib.sha256(content).hexdigest():
214
+ raise PackageError(f"checksum mismatch: {path}")
215
+ return {
216
+ "manifest": json.loads(files["manifest.json"]),
217
+ "packageHash": package_hash,
218
+ "files": sorted(files),
219
+ }
@@ -0,0 +1,53 @@
1
+ [project]
2
+ name = "postcrm-plugin-sdk"
3
+ version = "0.1.3"
4
+ description = "PostCRM plugin SDK (Python)"
5
+ authors = [{ name = "PostCRM" }]
6
+ license = { file = "LICENSE" }
7
+ readme = "README.md"
8
+ keywords = ["postcrm", "plugin", "sdk", "fastapi"]
9
+ dynamic = ["dependencies", "requires-python", "classifiers"]
10
+
11
+ [tool.poetry]
12
+ packages = [{ include = "postcrm_plugin_sdk" }]
13
+ include = ["LICENSE", "README.md"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3.12",
16
+ "Framework :: FastAPI",
17
+ ]
18
+
19
+ [tool.poetry.dependencies]
20
+ python = "^3.12"
21
+ fastapi = ">=0.110.3"
22
+ httpx = "^0.28.1"
23
+ pydantic = ">=2.0"
24
+ cryptography = "^43.0"
25
+ uvicorn = "^0.30.1"
26
+
27
+ [tool.poetry.group.dev.dependencies]
28
+ pytest = "^8.2.2"
29
+ pytest-asyncio = "^0.23.0"
30
+ ruff = "0.12.8"
31
+ black = "^26.3.1"
32
+ pyright = "^1.1.408"
33
+
34
+ [tool.ruff]
35
+ line-length = 120
36
+ target-version = "py312"
37
+
38
+ [tool.black]
39
+ line-length = 120
40
+ target-version = ["py312"]
41
+
42
+ [tool.pytest.ini_options]
43
+ asyncio_mode = "auto"
44
+ pythonpath = ["."]
45
+
46
+ [tool.pyright]
47
+ include = ["postcrm_plugin_sdk"]
48
+ pythonVersion = "3.12"
49
+ typeCheckingMode = "basic"
50
+
51
+ [build-system]
52
+ requires = ["poetry-core"]
53
+ build-backend = "poetry.core.masonry.api"