@gate-forge/plugin-protocol 0.1.0
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.
- package/LICENSE +202 -0
- package/README.md +187 -0
- package/dist/codes.d.ts +77 -0
- package/dist/codes.d.ts.map +1 -0
- package/dist/codes.js +115 -0
- package/dist/codes.js.map +1 -0
- package/dist/framing.d.ts +60 -0
- package/dist/framing.d.ts.map +1 -0
- package/dist/framing.js +153 -0
- package/dist/framing.js.map +1 -0
- package/dist/host.d.ts +61 -0
- package/dist/host.d.ts.map +1 -0
- package/dist/host.js +362 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +29 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +39 -0
- package/dist/index.js.map +1 -0
- package/dist/plugin.d.ts +44 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +133 -0
- package/dist/plugin.js.map +1 -0
- package/dist/schema.d.ts +176 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +142 -0
- package/dist/schema.js.map +1 -0
- package/package.json +41 -0
- package/python/gateforge_plugin/__init__.py +265 -0
- package/python/gateforge_plugin/__pycache__/__init__.cpython-312.pyc +0 -0
- package/python/gateforge_plugin/__pycache__/__init__.cpython-314.pyc +0 -0
- package/python/plugins/reference_detector.py +132 -0
|
@@ -0,0 +1,265 @@
|
|
|
1
|
+
"""GPP/3 client library for Gateforge plugins (Python, stdlib only).
|
|
2
|
+
|
|
3
|
+
Lineage: spikes/plugin-protocol host/_lib lineage, hardened per ADR 0002
|
|
4
|
+
D3 at protocolVersion 3 (GPP/3 signal transport per ADR 0003 D6). A
|
|
5
|
+
plugin calls :func:`serve` with its identity and a ``discover(paths)``
|
|
6
|
+
handler; this module performs the hello/ready handshake, validates host
|
|
7
|
+
frames (protocolVersion, seq order, digest), answers discover requests,
|
|
8
|
+
and completes the shutdown/bye handshake.
|
|
9
|
+
|
|
10
|
+
GPP/3 cutover: ``result`` payloads carry a mandatory
|
|
11
|
+
``classificationSignals`` array (taken from the handler's return value,
|
|
12
|
+
defaulting to an empty list for detectors without signal support).
|
|
13
|
+
GPP/2 peers fail closed at the handshake with ``E_PROTOCOL_VERSION``.
|
|
14
|
+
|
|
15
|
+
Digest rule (pin #5): ``digest = sha256(canonical({type, seq, payload}))``
|
|
16
|
+
over GF-canonical-JSON (UTF-8, recursively key-sorted, no whitespace,
|
|
17
|
+
integers plain) — byte-compatible with @gate-forge/core.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import hashlib
|
|
23
|
+
import json
|
|
24
|
+
import sys
|
|
25
|
+
|
|
26
|
+
PROTOCOL_VERSION = 3
|
|
27
|
+
REQUIRED_CAPABILITY = "discover"
|
|
28
|
+
|
|
29
|
+
_KNOWN_TYPES = ("hello", "ready", "discover", "result", "error", "shutdown", "bye")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class ProtocolError(Exception):
|
|
33
|
+
"""A fail-closed protocol violation carrying a GPP code and detail."""
|
|
34
|
+
|
|
35
|
+
def __init__(self, code: str, detail: str) -> None:
|
|
36
|
+
super().__init__(f"[{code}] {detail}")
|
|
37
|
+
self.code = code
|
|
38
|
+
self.detail = detail
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def canonical_json(value: object) -> str:
|
|
42
|
+
"""Serializes a JSON-representable value to GF-canonical-JSON (pin #1).
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
value: Any JSON value (str/int/bool/None/list/dict of JSON values).
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
str: Canonical JSON text — keys sorted recursively, no whitespace.
|
|
49
|
+
|
|
50
|
+
Raises:
|
|
51
|
+
TypeError: If the value is not JSON-representable.
|
|
52
|
+
"""
|
|
53
|
+
if value is None:
|
|
54
|
+
return "null"
|
|
55
|
+
if isinstance(value, str):
|
|
56
|
+
return json.dumps(value, ensure_ascii=False)
|
|
57
|
+
if isinstance(value, bool):
|
|
58
|
+
return "true" if value else "false"
|
|
59
|
+
if isinstance(value, int):
|
|
60
|
+
return str(value)
|
|
61
|
+
if isinstance(value, float):
|
|
62
|
+
if value != value or value in (float("inf"), float("-inf")):
|
|
63
|
+
raise TypeError(f"canonical_json: {value!r} has no canonical form")
|
|
64
|
+
return json.dumps(value)
|
|
65
|
+
if isinstance(value, list):
|
|
66
|
+
return "[" + ",".join(canonical_json(item) for item in value) + "]"
|
|
67
|
+
if isinstance(value, dict):
|
|
68
|
+
members = ",".join(
|
|
69
|
+
f"{json.dumps(key, ensure_ascii=False)}:{canonical_json(value[key])}"
|
|
70
|
+
for key in sorted(value)
|
|
71
|
+
)
|
|
72
|
+
return "{" + members + "}"
|
|
73
|
+
raise TypeError(f"canonical_json: unsupported type {type(value).__name__}")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def digest_of(type_: str, seq: int, payload: object) -> str:
|
|
77
|
+
"""Computes the per-message digest: sha256(canonical({type, seq, payload})).
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
type_: Message catalog name.
|
|
81
|
+
seq: Sender-side sequence number (1-based).
|
|
82
|
+
payload: Message payload (JSON value).
|
|
83
|
+
|
|
84
|
+
Returns:
|
|
85
|
+
str: Lowercase hex sha256 digest.
|
|
86
|
+
"""
|
|
87
|
+
return hashlib.sha256(
|
|
88
|
+
canonical_json({"type": type_, "seq": seq, "payload": payload}).encode("utf-8")
|
|
89
|
+
).hexdigest()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _send(
|
|
93
|
+
type_: str,
|
|
94
|
+
seq: int,
|
|
95
|
+
payload: object,
|
|
96
|
+
plugin_id: str,
|
|
97
|
+
plugin_version: str,
|
|
98
|
+
) -> None:
|
|
99
|
+
"""Writes one newline-terminated envelope line to stdout and flushes."""
|
|
100
|
+
frame = {
|
|
101
|
+
"protocolVersion": PROTOCOL_VERSION,
|
|
102
|
+
"pluginId": plugin_id,
|
|
103
|
+
"pluginVersion": plugin_version,
|
|
104
|
+
"type": type_,
|
|
105
|
+
"seq": seq,
|
|
106
|
+
"payload": payload,
|
|
107
|
+
"digest": digest_of(type_, seq, payload),
|
|
108
|
+
}
|
|
109
|
+
sys.stdout.write(json.dumps(frame, ensure_ascii=False, separators=(",", ":")) + "\n")
|
|
110
|
+
sys.stdout.flush()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _verify_host_frame(
|
|
114
|
+
frame: object,
|
|
115
|
+
expected_seq: int,
|
|
116
|
+
plugin_id: str,
|
|
117
|
+
plugin_version: str,
|
|
118
|
+
) -> dict:
|
|
119
|
+
"""Validates one host frame envelope; raises ProtocolError on violation.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
frame: Parsed JSON value of the host frame.
|
|
123
|
+
expected_seq: The next legal host seq (strictly sequential).
|
|
124
|
+
plugin_id: This plugin's declared id (must be echoed by the host).
|
|
125
|
+
plugin_version: This plugin's declared version (must be echoed).
|
|
126
|
+
|
|
127
|
+
Returns:
|
|
128
|
+
dict: The verified frame.
|
|
129
|
+
|
|
130
|
+
Raises:
|
|
131
|
+
ProtocolError: With the matching E_* code on any violation.
|
|
132
|
+
"""
|
|
133
|
+
where = f"host frame {expected_seq}"
|
|
134
|
+
if not isinstance(frame, dict):
|
|
135
|
+
raise ProtocolError("E_FRAME_JSON", f"{where}: valid JSON but not an object")
|
|
136
|
+
for field in ("protocolVersion", "pluginId", "pluginVersion", "type", "seq", "payload", "digest"):
|
|
137
|
+
if field not in frame:
|
|
138
|
+
raise ProtocolError("E_SCHEMA", f'{where}: required envelope field "{field}" is missing')
|
|
139
|
+
if frame["protocolVersion"] != PROTOCOL_VERSION:
|
|
140
|
+
raise ProtocolError(
|
|
141
|
+
"E_PROTOCOL_VERSION",
|
|
142
|
+
f"{where}: envelope protocolVersion={frame['protocolVersion']!r} but the plugin speaks {PROTOCOL_VERSION}",
|
|
143
|
+
)
|
|
144
|
+
if frame["pluginId"] != plugin_id or frame["pluginVersion"] != plugin_version:
|
|
145
|
+
raise ProtocolError(
|
|
146
|
+
"E_UNKNOWN_PLUGIN",
|
|
147
|
+
f"{where}: host echoed identity "
|
|
148
|
+
f"({frame['pluginId']!r}, {frame['pluginVersion']!r}) but this plugin is "
|
|
149
|
+
f"({plugin_id!r}, {plugin_version!r})",
|
|
150
|
+
)
|
|
151
|
+
if frame["type"] not in _KNOWN_TYPES:
|
|
152
|
+
raise ProtocolError(
|
|
153
|
+
"E_UNKNOWN_TYPE",
|
|
154
|
+
f"{where}: unknown message type {frame['type']!r}; known types: {sorted(_KNOWN_TYPES)}",
|
|
155
|
+
)
|
|
156
|
+
if frame["seq"] != expected_seq:
|
|
157
|
+
raise ProtocolError(
|
|
158
|
+
"E_SCHEMA",
|
|
159
|
+
f"{where} (type {frame['type']}): seq {frame['seq']!r} but expected {expected_seq}",
|
|
160
|
+
)
|
|
161
|
+
expected_digest = digest_of(frame["type"], frame["seq"], frame["payload"])
|
|
162
|
+
if frame["digest"] != expected_digest:
|
|
163
|
+
raise ProtocolError(
|
|
164
|
+
"E_SCHEMA",
|
|
165
|
+
f"{where} (type {frame['type']}): digest mismatch: expected {expected_digest}, got {frame['digest']}",
|
|
166
|
+
)
|
|
167
|
+
return frame
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def serve(
|
|
171
|
+
plugin_id: str,
|
|
172
|
+
plugin_version: str,
|
|
173
|
+
discover,
|
|
174
|
+
capabilities: tuple[str, ...] = (REQUIRED_CAPABILITY,),
|
|
175
|
+
) -> int:
|
|
176
|
+
"""Runs the GPP/3 serve loop over stdin/stdout until shutdown or EOF.
|
|
177
|
+
|
|
178
|
+
Args:
|
|
179
|
+
plugin_id: This plugin's identity, pinned by the host handshake.
|
|
180
|
+
plugin_version: This plugin's version, pinned by the host handshake.
|
|
181
|
+
discover: Callable ``discover(paths: list[str]) -> dict`` returning
|
|
182
|
+
``{"resources": [...], "unresolved": [...], "findings": [...],
|
|
183
|
+
"classificationSignals": [...]}`` (GPP/3; the signals array
|
|
184
|
+
defaults to ``[]`` for detectors without signal support).
|
|
185
|
+
Raise and the request is answered with an ``error`` frame.
|
|
186
|
+
capabilities: Declared capabilities (default: ``("discover",)``).
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
int: Process exit code (0 on a clean shutdown handshake).
|
|
190
|
+
"""
|
|
191
|
+
seq = 0
|
|
192
|
+
|
|
193
|
+
def next_seq() -> int:
|
|
194
|
+
nonlocal seq
|
|
195
|
+
seq += 1
|
|
196
|
+
return seq
|
|
197
|
+
|
|
198
|
+
_send("hello", next_seq(), {"capabilities": list(capabilities)}, plugin_id, plugin_version)
|
|
199
|
+
|
|
200
|
+
host_seq = 0 # the host has its own strictly sequential counter
|
|
201
|
+
|
|
202
|
+
for line in sys.stdin:
|
|
203
|
+
if not line.strip():
|
|
204
|
+
continue
|
|
205
|
+
try:
|
|
206
|
+
frame = json.loads(line)
|
|
207
|
+
except json.JSONDecodeError as error:
|
|
208
|
+
_fatal(plugin_id, plugin_version, next_seq(), "E_FRAME_JSON", f"host frame is not valid JSON ({error})")
|
|
209
|
+
frame = _verify_host_frame(frame, host_seq + 1, plugin_id, plugin_version)
|
|
210
|
+
host_seq += 1
|
|
211
|
+
type_ = frame["type"]
|
|
212
|
+
if type_ == "ready":
|
|
213
|
+
continue
|
|
214
|
+
if type_ == "discover":
|
|
215
|
+
request = frame["payload"]
|
|
216
|
+
request_id = request.get("requestId") if isinstance(request, dict) else None
|
|
217
|
+
paths = request.get("paths") if isinstance(request, dict) else None
|
|
218
|
+
if not isinstance(request_id, str) or not request_id or not isinstance(paths, list):
|
|
219
|
+
_fatal(
|
|
220
|
+
plugin_id,
|
|
221
|
+
plugin_version,
|
|
222
|
+
next_seq(),
|
|
223
|
+
"E_SCHEMA",
|
|
224
|
+
f"discover frame: invalid payload: {json.dumps(request)[:200]}",
|
|
225
|
+
)
|
|
226
|
+
try:
|
|
227
|
+
result = discover(list(paths))
|
|
228
|
+
payload = {
|
|
229
|
+
"requestId": request_id,
|
|
230
|
+
"resources": result.get("resources", []),
|
|
231
|
+
"unresolved": result.get("unresolved", []),
|
|
232
|
+
"findings": result.get("findings", []),
|
|
233
|
+
# GPP/3 (ADR 0003 D6): mandatory on every result;
|
|
234
|
+
# detectors without signal support send [].
|
|
235
|
+
"classificationSignals": result.get("classificationSignals", []),
|
|
236
|
+
}
|
|
237
|
+
# Optional coverage evidence (ADR 0003 D4): pass through
|
|
238
|
+
# the handler's reported scanned paths when provided.
|
|
239
|
+
scanned = result.get("scannedPaths")
|
|
240
|
+
if scanned is not None:
|
|
241
|
+
payload["scannedPaths"] = scanned
|
|
242
|
+
_send("result", next_seq(), payload, plugin_id, plugin_version)
|
|
243
|
+
except ProtocolError:
|
|
244
|
+
raise
|
|
245
|
+
except Exception as error: # request-scoped: session stays alive
|
|
246
|
+
_send(
|
|
247
|
+
"error",
|
|
248
|
+
next_seq(),
|
|
249
|
+
{"requestId": request_id, "code": "E_PLUGIN_INTERNAL", "message": str(error)},
|
|
250
|
+
plugin_id,
|
|
251
|
+
plugin_version,
|
|
252
|
+
)
|
|
253
|
+
elif type_ == "shutdown":
|
|
254
|
+
_send("bye", next_seq(), {}, plugin_id, plugin_version)
|
|
255
|
+
return 0
|
|
256
|
+
return 0
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _fatal(plugin_id: str, plugin_version: str, seq: int, code: str, detail: str) -> None:
|
|
260
|
+
"""Emits a session-fatal error frame (no requestId), then exits nonzero."""
|
|
261
|
+
try:
|
|
262
|
+
_send("error", seq + 1, {"code": code, "message": detail}, plugin_id, plugin_version)
|
|
263
|
+
except Exception:
|
|
264
|
+
pass
|
|
265
|
+
raise SystemExit(4)
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Reference GPP/3 detector: parses trivial `.gfx` route fixtures.
|
|
3
|
+
|
|
4
|
+
One `METHOD path` per line, `#` comments — the same fixture format and
|
|
5
|
+
algorithm as test/fixtures/plugins/_lib.mjs, so both reference plugins
|
|
6
|
+
must produce identical resources/findings AND classification-signal
|
|
7
|
+
documents for identical fixture bytes (determinism, plan invariant 7;
|
|
8
|
+
GPP/3 signal transport per ADR 0003 D6). Usage:
|
|
9
|
+
|
|
10
|
+
python3 reference_detector.py <fixture-root>
|
|
11
|
+
|
|
12
|
+
Usage is driven by the TS host tests: host spawns this script, handshakes,
|
|
13
|
+
discovers, and shuts it down.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import sys
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
|
|
21
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
22
|
+
|
|
23
|
+
from gateforge_plugin import ProtocolError, serve # noqa: E402
|
|
24
|
+
|
|
25
|
+
DETECTOR_VERSION = "1.0.0"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _scan(root: str, rel: str) -> tuple[list[dict], list[dict], list[dict]]:
|
|
29
|
+
"""Scans one .gfx fixture file into (resources, findings, signals).
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
root: Fixture root directory (plugin argv).
|
|
33
|
+
rel: Repo-root-relative path to scan; rejects absolute/`..` paths.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
tuple: (resources, DUPLICATE_ROUTE findings, exposure signals).
|
|
37
|
+
|
|
38
|
+
Raises:
|
|
39
|
+
ValueError: On a non-relative path or a malformed fixture line.
|
|
40
|
+
OSError: If the fixture file does not exist.
|
|
41
|
+
"""
|
|
42
|
+
if not rel or rel.startswith("/") or ".." in rel.split("/"):
|
|
43
|
+
raise ValueError(f"target must be a relative path under the fixture root, got {rel!r}")
|
|
44
|
+
text = (Path(root) / rel).read_text(encoding="utf-8")
|
|
45
|
+
resources: list[dict] = []
|
|
46
|
+
signals: list[dict] = []
|
|
47
|
+
seen: dict[str, list[dict]] = {}
|
|
48
|
+
for i, line_text in enumerate(text.split("\n")):
|
|
49
|
+
line = line_text.strip()
|
|
50
|
+
if not line or line.startswith("#"):
|
|
51
|
+
continue
|
|
52
|
+
space_at = line.find(" ")
|
|
53
|
+
if space_at <= 0:
|
|
54
|
+
raise ValueError(f"malformed fixture line {i + 1} in {rel}: {line_text!r}")
|
|
55
|
+
method = line[:space_at]
|
|
56
|
+
route_path = line[space_at + 1 :].strip()
|
|
57
|
+
location = {"file": rel, "line": i + 1, "col": 0}
|
|
58
|
+
resource_id = f"web.routes:{method} {route_path}"
|
|
59
|
+
resources.append(
|
|
60
|
+
{
|
|
61
|
+
"schemaVersion": 1,
|
|
62
|
+
"id": resource_id,
|
|
63
|
+
"kind": "http-route",
|
|
64
|
+
"source": rel,
|
|
65
|
+
"location": location,
|
|
66
|
+
"detectorVersion": DETECTOR_VERSION,
|
|
67
|
+
"attributes": {"method": method, "path": route_path},
|
|
68
|
+
}
|
|
69
|
+
)
|
|
70
|
+
signals.append(
|
|
71
|
+
{
|
|
72
|
+
"schemaVersion": 1,
|
|
73
|
+
"target": {"resourceId": resource_id},
|
|
74
|
+
"dimension": "exposure",
|
|
75
|
+
"assertion": "route",
|
|
76
|
+
"basis": "code-positive",
|
|
77
|
+
"source": "python-fixture-detector",
|
|
78
|
+
"location": location,
|
|
79
|
+
"detector": {"id": "python-fixture-detector", "version": DETECTOR_VERSION},
|
|
80
|
+
}
|
|
81
|
+
)
|
|
82
|
+
seen.setdefault(f"{method} {route_path}", []).append(location)
|
|
83
|
+
findings = [
|
|
84
|
+
{
|
|
85
|
+
"code": "DUPLICATE_ROUTE",
|
|
86
|
+
"detail": f"route '{key}' declared {len(locations)} times",
|
|
87
|
+
"locations": locations,
|
|
88
|
+
}
|
|
89
|
+
for key, locations in sorted(seen.items())
|
|
90
|
+
if len(locations) >= 2
|
|
91
|
+
]
|
|
92
|
+
return resources, findings, signals
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def discover(paths: list[str]) -> dict:
|
|
96
|
+
"""GPP/3 discover handler: scans each requested path in order.
|
|
97
|
+
|
|
98
|
+
Args:
|
|
99
|
+
paths: Repo-root-relative fixture paths from the discover request.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
dict: {"resources": [...], "unresolved": [], "findings": [...],
|
|
103
|
+
"classificationSignals": [...]}.
|
|
104
|
+
"""
|
|
105
|
+
resources: list[dict] = []
|
|
106
|
+
findings: list[dict] = []
|
|
107
|
+
signals: list[dict] = []
|
|
108
|
+
scanned: list[str] = []
|
|
109
|
+
for rel in paths:
|
|
110
|
+
file_resources, file_findings, file_signals = _scan(
|
|
111
|
+
sys.argv[1] if len(sys.argv) > 1 else ".", rel
|
|
112
|
+
)
|
|
113
|
+
resources.extend(file_resources)
|
|
114
|
+
findings.extend(file_findings)
|
|
115
|
+
signals.extend(file_signals)
|
|
116
|
+
scanned.append(rel)
|
|
117
|
+
return {
|
|
118
|
+
"resources": resources,
|
|
119
|
+
"unresolved": [],
|
|
120
|
+
"findings": findings,
|
|
121
|
+
"classificationSignals": signals,
|
|
122
|
+
"scannedPaths": scanned,
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
try:
|
|
128
|
+
raise SystemExit(serve("python-fixture-detector", DETECTOR_VERSION, discover))
|
|
129
|
+
except ProtocolError as error:
|
|
130
|
+
# Session-fatal: the frame was already emitted; exit nonzero.
|
|
131
|
+
print(f"reference_detector: {error}", file=sys.stderr)
|
|
132
|
+
raise SystemExit(4) from None
|