Initial AMPG spec and Wownero prototype

This commit is contained in:
jwinterm
2026-07-05 19:29:00 -04:00
commit e01d35132f
24 changed files with 1899 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
"""Adaptive Multi-Protocol Gateway."""
__all__ = ["__version__"]
__version__ = "0.1.0"
+5
View File
@@ -0,0 +1,5 @@
from .cli import main
if __name__ == "__main__":
raise SystemExit(main())
+128
View File
@@ -0,0 +1,128 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import shutil
from .config import GatewayConfig, ProtocolConfig, SiteConfig
from .renderers import PrivacyRenderStats, render_privacy_html
IGNORED_DIRS = {".git", ".hg", ".svn", ".vscode", "__pycache__"}
IGNORED_SUFFIXES = (".bak", ".tmp", ".swp")
@dataclass(frozen=True)
class BuildResult:
site_id: str
protocol: str
renderer: str
output_root: Path
files_written: int
files_skipped: int = 0
privacy_stats: PrivacyRenderStats | None = None
def build_gateway(config: GatewayConfig) -> list[BuildResult]:
results: list[BuildResult] = []
for site in config.sites:
_validate_source(site)
for protocol in site.protocols.values():
if not protocol.enabled:
continue
results.append(build_protocol(site, protocol))
return results
def build_protocol(site: SiteConfig, protocol: ProtocolConfig) -> BuildResult:
output_root = site.outputs.root / protocol.name
_prepare_output_root(output_root)
if protocol.renderer == "clearnet":
return _copy_clearnet(site, protocol, output_root)
if protocol.renderer == "privacy-html":
return _render_privacy_html_tree(site, protocol, output_root)
raise ValueError(f"{site.id}/{protocol.name}: unsupported renderer {protocol.renderer!r}")
def _copy_clearnet(site: SiteConfig, protocol: ProtocolConfig, output_root: Path) -> BuildResult:
files_written = 0
for source_path in _iter_source_files(site.source.path):
target_path = output_root / source_path.relative_to(site.source.path)
target_path.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(source_path, target_path)
files_written += 1
return BuildResult(
site_id=site.id,
protocol=protocol.name,
renderer=protocol.renderer,
output_root=output_root,
files_written=files_written,
)
def _render_privacy_html_tree(
site: SiteConfig, protocol: ProtocolConfig, output_root: Path
) -> BuildResult:
files_written = 0
files_skipped = 0
stats = PrivacyRenderStats()
max_asset_bytes = int(protocol.options.get("max_asset_bytes", 1024 * 1024))
for source_path in _iter_source_files(site.source.path):
target_path = output_root / source_path.relative_to(site.source.path)
target_path.parent.mkdir(parents=True, exist_ok=True)
if source_path.suffix.lower() in {".html", ".htm"}:
html = source_path.read_text(encoding="utf-8", errors="replace")
rendered, file_stats = render_privacy_html(html)
target_path.write_text(rendered, encoding="utf-8")
stats = stats.add(file_stats)
elif source_path.suffix.lower() in {".js", ".map"}:
files_skipped += 1
continue
elif source_path.stat().st_size > max_asset_bytes:
files_skipped += 1
continue
else:
shutil.copy2(source_path, target_path)
files_written += 1
return BuildResult(
site_id=site.id,
protocol=protocol.name,
renderer=protocol.renderer,
output_root=output_root,
files_written=files_written,
files_skipped=files_skipped,
privacy_stats=stats,
)
def _iter_source_files(root: Path):
for path in sorted(root.rglob("*")):
if not path.is_file():
continue
rel_parts = path.relative_to(root).parts
if any(part in IGNORED_DIRS for part in rel_parts):
continue
if any(part.startswith(".") and part != ".well-known" for part in rel_parts):
continue
if path.name.endswith(IGNORED_SUFFIXES) or ".bak." in path.name:
continue
yield path
def _validate_source(site: SiteConfig) -> None:
if not site.source.path.exists():
raise FileNotFoundError(f"{site.id}: source path does not exist: {site.source.path}")
if not site.source.path.is_dir():
raise NotADirectoryError(f"{site.id}: source path is not a directory: {site.source.path}")
def _prepare_output_root(output_root: Path) -> None:
marker = output_root / ".ampg-output"
if output_root.exists() and any(output_root.iterdir()) and not marker.exists():
raise RuntimeError(
f"refusing to clean non-empty unmarked output directory: {output_root}"
)
if marker.exists():
shutil.rmtree(output_root)
output_root.mkdir(parents=True, exist_ok=True)
marker.write_text("generated by AMPG\n", encoding="utf-8")
+95
View File
@@ -0,0 +1,95 @@
from __future__ import annotations
import argparse
from pathlib import Path
import sys
from .build import build_gateway
from .config import load_config
from .docsgen import generate_docs
from .plan import plan_gateway
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(prog="ampg")
parser.add_argument(
"--config",
type=Path,
default=Path("gateway.toml"),
help="Path to gateway TOML config.",
)
subcommands = parser.add_subparsers(dest="command", required=True)
subcommands.add_parser("plan", help="Print a dry-run plan.")
subcommands.add_parser("build", help="Build enabled protocol outputs.")
docs_parser = subcommands.add_parser("docs", help="Generate or check generated docs.")
docs_subcommands = docs_parser.add_subparsers(dest="docs_command", required=True)
docs_generate = docs_subcommands.add_parser("generate", help="Generate docs from code.")
docs_generate.add_argument(
"--check",
action="store_true",
help="Fail if generated docs are stale instead of writing them.",
)
args = parser.parse_args(argv)
try:
if args.command == "docs":
return _cmd_docs(args)
config = load_config(args.config)
if args.command == "plan":
return _cmd_plan(config)
if args.command == "build":
return _cmd_build(config)
except Exception as exc: # noqa: BLE001 - CLI should print concise failures.
print(f"AMPG status=error message={exc}", file=sys.stderr)
return 1
return 1
def _cmd_plan(config) -> int:
for line in plan_gateway(config):
print(
"AMPG_PLAN "
f"site={line.site_id} "
f"protocol={line.protocol} "
f"renderer={line.renderer} "
f"output={line.output_root} "
f"daemon={line.daemon} "
f"policy={line.daemon_policy} "
f"action=\"{line.action}\""
)
return 0
def _cmd_build(config) -> int:
for result in build_gateway(config):
extra = ""
if result.privacy_stats is not None:
stats = result.privacy_stats
extra = (
f" removed_active_tags={stats.removed_active_tags}"
f" removed_event_handlers={stats.removed_event_handlers}"
f" removed_inline_styles={stats.removed_inline_styles}"
f" removed_remote_assets={stats.removed_remote_assets}"
)
print(
"AMPG_BUILD "
f"site={result.site_id} "
f"protocol={result.protocol} "
f"renderer={result.renderer} "
f"output={result.output_root} "
f"files={result.files_written}"
f" skipped={result.files_skipped}"
f"{extra}"
)
return 0
def _cmd_docs(args) -> int:
if args.docs_command == "generate":
changed = generate_docs(Path.cwd(), check=args.check)
changed_text = ",".join(str(path) for path in changed) if changed else "-"
mode = "check" if args.check else "write"
print(f"AMPG_DOCS status=ok mode={mode} changed={changed_text}")
return 0
return 1
+134
View File
@@ -0,0 +1,134 @@
from __future__ import annotations
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
import tomllib
DEFAULT_DAEMONS = {
"clearnet": "nginx",
"tor": "tor",
"i2p": "i2pd",
"gemini": "agate",
"reticulum": "rnsd",
}
DEFAULT_POLICIES = {
"clearnet": "adopt",
"tor": "auto",
"i2p": "auto",
"gemini": "auto",
"reticulum": "auto",
}
@dataclass(frozen=True)
class SourceConfig:
kind: str
path: Path
canonical_url: str | None = None
@dataclass(frozen=True)
class OutputConfig:
root: Path
@dataclass(frozen=True)
class ProtocolConfig:
name: str
enabled: bool
renderer: str
daemon: str
daemon_policy: str
options: dict[str, Any] = field(default_factory=dict)
@dataclass(frozen=True)
class SiteConfig:
id: str
domain: str
source: SourceConfig
outputs: OutputConfig
protocols: dict[str, ProtocolConfig]
@dataclass(frozen=True)
class GatewayConfig:
config_path: Path
sites: list[SiteConfig]
def load_config(path: Path) -> GatewayConfig:
config_path = path.resolve()
data = tomllib.loads(config_path.read_text(encoding="utf-8"))
sites = [_parse_site(raw_site, config_path.parent) for raw_site in data.get("site", [])]
if not sites:
raise ValueError("config must declare at least one [[site]]")
return GatewayConfig(config_path=config_path, sites=sites)
def _parse_site(raw_site: dict[str, Any], base_dir: Path) -> SiteConfig:
source = raw_site.get("source") or {}
outputs = raw_site.get("outputs") or {}
protocols = raw_site.get("protocols") or {}
site_id = _required_str(raw_site, "id")
domain = _required_str(raw_site, "domain")
source_kind = _required_str(source, "kind")
if source_kind != "static-html":
raise ValueError(f"{site_id}: unsupported source kind {source_kind!r}")
source_path = _resolve_path(base_dir, _required_str(source, "path"))
output_root = _resolve_path(base_dir, _required_str(outputs, "root"))
parsed_protocols = {
name: _parse_protocol(name, raw_protocol)
for name, raw_protocol in protocols.items()
if isinstance(raw_protocol, dict)
}
return SiteConfig(
id=site_id,
domain=domain,
source=SourceConfig(
kind=source_kind,
path=source_path,
canonical_url=source.get("canonical_url"),
),
outputs=OutputConfig(root=output_root),
protocols=parsed_protocols,
)
def _parse_protocol(name: str, raw_protocol: dict[str, Any]) -> ProtocolConfig:
enabled = bool(raw_protocol.get("enabled", False))
renderer = str(raw_protocol.get("renderer", name))
daemon = str(raw_protocol.get("daemon", DEFAULT_DAEMONS.get(name, name)))
policy = str(raw_protocol.get("daemon_policy", DEFAULT_POLICIES.get(name, "auto")))
options = dict(raw_protocol)
for key in ("enabled", "renderer", "daemon", "daemon_policy"):
options.pop(key, None)
return ProtocolConfig(
name=name,
enabled=enabled,
renderer=renderer,
daemon=daemon,
daemon_policy=policy,
options=options,
)
def _resolve_path(base_dir: Path, raw_path: str) -> Path:
path = Path(raw_path).expanduser()
if not path.is_absolute():
path = base_dir / path
return path.resolve()
def _required_str(data: dict[str, Any], key: str) -> str:
value = data.get(key)
if not isinstance(value, str) or not value:
raise ValueError(f"missing required string field {key!r}")
return value
+85
View File
@@ -0,0 +1,85 @@
from __future__ import annotations
from pathlib import Path
from .metadata import CONFIG_FIELDS, DAEMON_ADAPTERS, RENDER_PROFILES
GENERATED_DIR = Path("docs/generated")
def generate_docs(root: Path, *, check: bool = False) -> list[Path]:
docs = {
GENERATED_DIR / "config-schema.md": _config_schema_doc(),
GENERATED_DIR / "daemon-adapters.md": _daemon_adapters_doc(),
GENERATED_DIR / "render-profiles.md": _render_profiles_doc(),
}
changed: list[Path] = []
for rel_path, content in docs.items():
path = root / rel_path
if path.exists() and path.read_text(encoding="utf-8") == content:
continue
changed.append(rel_path)
if not check:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8")
if check and changed:
names = ", ".join(str(path) for path in changed)
raise RuntimeError(f"generated docs are stale: {names}")
return changed
def _header(title: str) -> str:
return (
f"# {title}\n\n"
"> Status: generated | Updated by `python3 -m ampg docs generate` | Applies to: AMPG\n\n"
"This file is generated from code. Do not edit it by hand.\n\n"
)
def _config_schema_doc() -> str:
rows = [
"| Section | Field | Type | Required | Default | Description |",
"| --- | --- | --- | --- | --- | --- |",
]
for field in CONFIG_FIELDS:
rows.append(
"| "
f"{field.section} | "
f"`{field.field}` | "
f"{field.kind} | "
f"{'yes' if field.required else 'no'} | "
f"{field.default or '-'} | "
f"{field.description} |"
)
return _header("Generated Config Schema") + "\n".join(rows) + "\n"
def _daemon_adapters_doc() -> str:
sections = [_header("Generated Daemon Adapters")]
for adapter in DAEMON_ADAPTERS:
sections.append(f"## {adapter.daemon}\n")
sections.append(f"- Protocols: {', '.join(adapter.protocols)}")
sections.append(f"- Default policy: `{adapter.default_policy}`")
sections.append(f"- Generated artifacts: {', '.join(adapter.generated_artifacts)}")
sections.append("")
sections.append("Notes:")
for note in adapter.notes:
sections.append(f"- {note}")
sections.append("")
return "\n".join(sections)
def _render_profiles_doc() -> str:
sections = [_header("Generated Render Profiles")]
for profile in RENDER_PROFILES:
sections.append(f"## {profile.name}\n")
sections.append(profile.summary)
sections.append("")
sections.append(f"- Output: {profile.output}")
sections.append("")
sections.append("Defaults:")
for default in profile.defaults:
sections.append(f"- {default}")
sections.append("")
return "\n".join(sections)
+152
View File
@@ -0,0 +1,152 @@
from __future__ import annotations
from dataclasses import dataclass
from .config import DEFAULT_DAEMONS, DEFAULT_POLICIES
from .renderers import ACTIVE_TAGS
@dataclass(frozen=True)
class ConfigField:
section: str
field: str
kind: str
required: bool
default: str
description: str
@dataclass(frozen=True)
class RenderProfile:
name: str
summary: str
output: str
defaults: tuple[str, ...]
@dataclass(frozen=True)
class DaemonAdapter:
daemon: str
protocols: tuple[str, ...]
default_policy: str
generated_artifacts: tuple[str, ...]
notes: tuple[str, ...]
CONFIG_FIELDS = (
ConfigField("site", "id", "string", True, "", "Stable site identifier used in output paths."),
ConfigField("site", "domain", "string", True, "", "Canonical public domain for the site."),
ConfigField("site.source", "kind", "enum", True, "static-html", "Source adapter kind."),
ConfigField("site.source", "path", "path", True, "", "Source tree path."),
ConfigField("site.source", "canonical_url", "url", False, "", "Canonical clearnet URL."),
ConfigField("site.outputs", "root", "path", True, "", "Generated output root."),
ConfigField(
"site.interactions",
"default_tier",
"enum",
False,
"static",
"Default interaction tier for routes.",
),
ConfigField(
"site.interactions",
"deny_routes",
"array<string>",
False,
"[]",
"Route patterns that must not be published.",
),
ConfigField(
"site.protocols.<name>",
"enabled",
"boolean",
False,
"false",
"Whether this protocol target is built and planned.",
),
ConfigField(
"site.protocols.<name>",
"renderer",
"enum",
False,
"<protocol>",
"Renderer profile to use for this protocol.",
),
ConfigField(
"site.protocols.<name>",
"daemon",
"enum",
False,
"protocol default",
"Ingress daemon adapter.",
),
ConfigField(
"site.protocols.<name>",
"daemon_policy",
"enum",
False,
"protocol default",
"Whether AMPG adopts, manages, or only renders config.",
),
)
RENDER_PROFILES = (
RenderProfile(
name="clearnet",
summary="High-fidelity static web output.",
output="HTML/CSS/JS/assets",
defaults=(
"Copies source files except hidden/editor/VCS clutter.",
"Keeps local JavaScript and rich media.",
"Writes only to AMPG-marked generated output roots.",
),
),
RenderProfile(
name="privacy-html",
summary="Static HTML for Tor and I2P.",
output="HTML/CSS/assets",
defaults=(
f"Removes active tags: {', '.join(sorted(ACTIVE_TAGS))}.",
"Removes inline event handlers such as onclick and onload.",
"Removes inline style attributes.",
"Skips JavaScript and source-map files.",
"Skips oversized assets above max_asset_bytes.",
"Removes remote src/poster/link asset references.",
),
),
)
DAEMON_ADAPTERS = (
DaemonAdapter(
daemon="nginx",
protocols=("clearnet", "tor", "i2p"),
default_policy=DEFAULT_POLICIES["clearnet"],
generated_artifacts=("server block snippets",),
notes=(
"Clearnet defaults to adopt because TLS and public vhost policy are operator-owned.",
"Tor/I2P HTTP targets can use loopback-only server blocks.",
),
),
DaemonAdapter(
daemon=DEFAULT_DAEMONS["tor"],
protocols=("tor",),
default_policy=DEFAULT_POLICIES["tor"],
generated_artifacts=("torrc hidden-service snippet",),
notes=(
"AMPG should preserve existing HiddenServiceDir material when adopting.",
"Managed hidden-service keys belong under AMPG state.",
),
),
DaemonAdapter(
daemon=DEFAULT_DAEMONS["i2p"],
protocols=("i2p",),
default_policy=DEFAULT_POLICIES["i2p"],
generated_artifacts=("i2pd server tunnel snippet",),
notes=(
"Web tunnels should use web-specific key files.",
"Existing RPC/P2P tunnel keys are not reused for web publishing.",
),
),
)
+49
View File
@@ -0,0 +1,49 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from .config import GatewayConfig
@dataclass(frozen=True)
class PlanLine:
site_id: str
protocol: str
renderer: str
output_root: Path
daemon: str
daemon_policy: str
action: str
def plan_gateway(config: GatewayConfig) -> list[PlanLine]:
lines: list[PlanLine] = []
for site in config.sites:
for protocol in site.protocols.values():
if not protocol.enabled:
continue
lines.append(
PlanLine(
site_id=site.id,
protocol=protocol.name,
renderer=protocol.renderer,
output_root=site.outputs.root / protocol.name,
daemon=protocol.daemon,
daemon_policy=protocol.daemon_policy,
action=_action_for_policy(protocol.daemon_policy),
)
)
return lines
def _action_for_policy(policy: str) -> str:
if policy == "external":
return "render outputs and config snippets only"
if policy == "adopt":
return "adopt existing daemon; fail if missing"
if policy == "manage":
return "create AMPG-owned daemon instance"
if policy == "auto":
return "adopt healthy daemon, otherwise manage AMPG-owned instance"
return "unknown policy; no apply support"
+175
View File
@@ -0,0 +1,175 @@
from __future__ import annotations
from dataclasses import dataclass
from html import escape
from html.parser import HTMLParser
VOID_ELEMENTS = {
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"link",
"meta",
"param",
"source",
"track",
"wbr",
}
ACTIVE_TAGS = {"script", "style"}
@dataclass(frozen=True)
class PrivacyRenderStats:
removed_active_tags: int = 0
removed_event_handlers: int = 0
removed_inline_styles: int = 0
removed_remote_assets: int = 0
def add(self, other: "PrivacyRenderStats") -> "PrivacyRenderStats":
return PrivacyRenderStats(
removed_active_tags=self.removed_active_tags + other.removed_active_tags,
removed_event_handlers=self.removed_event_handlers + other.removed_event_handlers,
removed_inline_styles=self.removed_inline_styles + other.removed_inline_styles,
removed_remote_assets=self.removed_remote_assets + other.removed_remote_assets,
)
class PrivacyHtmlRenderer(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=False)
self.parts: list[str] = []
self.skip_stack: list[str] = []
self.stats = PrivacyRenderStats()
def render(self, html: str) -> tuple[str, PrivacyRenderStats]:
self.feed(html)
self.close()
return "".join(self.parts), self.stats
def handle_decl(self, decl: str) -> None:
if not self.skip_stack:
self.parts.append(f"<!{decl}>")
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
if tag in ACTIVE_TAGS:
self.skip_stack.append(tag)
self.stats = PrivacyRenderStats(
removed_active_tags=self.stats.removed_active_tags + 1,
removed_event_handlers=self.stats.removed_event_handlers,
removed_inline_styles=self.stats.removed_inline_styles,
removed_remote_assets=self.stats.removed_remote_assets,
)
return
if self.skip_stack:
return
clean_attrs = self._clean_attrs(tag, attrs)
self.parts.append(f"<{tag}{_format_attrs(clean_attrs)}>")
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
tag = tag.lower()
if tag in ACTIVE_TAGS:
self.stats = PrivacyRenderStats(
removed_active_tags=self.stats.removed_active_tags + 1,
removed_event_handlers=self.stats.removed_event_handlers,
removed_inline_styles=self.stats.removed_inline_styles,
removed_remote_assets=self.stats.removed_remote_assets,
)
return
if self.skip_stack:
return
clean_attrs = self._clean_attrs(tag, attrs)
self.parts.append(f"<{tag}{_format_attrs(clean_attrs)}>")
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if self.skip_stack:
if self.skip_stack[-1] == tag:
self.skip_stack.pop()
return
if tag not in VOID_ELEMENTS:
self.parts.append(f"</{tag}>")
def handle_data(self, data: str) -> None:
if not self.skip_stack:
self.parts.append(data)
def handle_entityref(self, name: str) -> None:
if not self.skip_stack:
self.parts.append(f"&{name};")
def handle_charref(self, name: str) -> None:
if not self.skip_stack:
self.parts.append(f"&#{name};")
def handle_comment(self, data: str) -> None:
return
def _clean_attrs(
self, tag: str, attrs: list[tuple[str, str | None]]
) -> list[tuple[str, str | None]]:
clean: list[tuple[str, str | None]] = []
for name, value in attrs:
attr = name.lower()
if attr.startswith("on"):
self.stats = PrivacyRenderStats(
removed_active_tags=self.stats.removed_active_tags,
removed_event_handlers=self.stats.removed_event_handlers + 1,
removed_inline_styles=self.stats.removed_inline_styles,
removed_remote_assets=self.stats.removed_remote_assets,
)
continue
if attr == "style":
self.stats = PrivacyRenderStats(
removed_active_tags=self.stats.removed_active_tags,
removed_event_handlers=self.stats.removed_event_handlers,
removed_inline_styles=self.stats.removed_inline_styles + 1,
removed_remote_assets=self.stats.removed_remote_assets,
)
continue
if attr in {"src", "poster"} and value and _is_remote_url(value):
self.stats = PrivacyRenderStats(
removed_active_tags=self.stats.removed_active_tags,
removed_event_handlers=self.stats.removed_event_handlers,
removed_inline_styles=self.stats.removed_inline_styles,
removed_remote_assets=self.stats.removed_remote_assets + 1,
)
continue
if tag == "link" and attr == "href" and value and _is_remote_url(value):
self.stats = PrivacyRenderStats(
removed_active_tags=self.stats.removed_active_tags,
removed_event_handlers=self.stats.removed_event_handlers,
removed_inline_styles=self.stats.removed_inline_styles,
removed_remote_assets=self.stats.removed_remote_assets + 1,
)
continue
clean.append((name, value))
return clean
def render_privacy_html(html: str) -> tuple[str, PrivacyRenderStats]:
return PrivacyHtmlRenderer().render(html)
def _format_attrs(attrs: list[tuple[str, str | None]]) -> str:
if not attrs:
return ""
rendered = []
for name, value in attrs:
if value is None:
rendered.append(escape(name, quote=True))
else:
rendered.append(f'{escape(name, quote=True)}="{escape(value, quote=True)}"')
return " " + " ".join(rendered)
def _is_remote_url(value: str) -> bool:
lower = value.lower()
return lower.startswith("http://") or lower.startswith("https://") or lower.startswith("//")