feat(gen1): isolated opt-in simulator admin web interface
This commit is contained in:
1 parent
a520063837
commit
62b0ea3d69
18 files changed
+1417
-651
No files matched your search
@@ -968,6 +968,14 @@ jobs:
|
||||
dotnet run --project tools/ci/OglDynamicTextureRetentionRegression/OglDynamicTextureRetentionRegression.csproj --configuration Release
|
||||
|
||||
|
||||
- name: Verify isolated simulator admin web DLL and security contract
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/ci/verify_os_webinterface.py
|
||||
dotnet build addons/OSWebInterface/os_webinterface.csproj --configuration Release --no-restore
|
||||
dotnet run --project tools/ci/OSWebInterfaceSmoke/OSWebInterfaceSmoke.csproj --configuration Release
|
||||
|
||||
- name: Verify Generation 1 approved-viewer admission policy
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -990,653 +998,3 @@ jobs:
|
||||
|
||||
- name: Runtime smoke test World API
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
cd bin
|
||||
|
||||
dotnet Robust.dll -inifile Robust.NexVerseApi.Tests.ini > ../nexverse-api-smoke.log 2>&1 &
|
||||
ROBUST_PID=$!
|
||||
|
||||
cleanup() {
|
||||
kill "$ROBUST_PID" 2>/dev/null || true
|
||||
wait "$ROBUST_PID" 2>/dev/null || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
READY=0
|
||||
# Robust startup time varies on shared CI runners after full native builds.
|
||||
# Give the control plane 30 seconds while still failing immediately if the process exits.
|
||||
for i in $(seq 1 120); do
|
||||
if curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/health > /tmp/nexverse-health.json; then
|
||||
READY=1
|
||||
break
|
||||
fi
|
||||
|
||||
if ! kill -0 "$ROBUST_PID" 2>/dev/null; then
|
||||
echo "::error::Robust exited before World API became ready."
|
||||
cat ../nexverse-api-smoke.log
|
||||
exit 1
|
||||
fi
|
||||
|
||||
sleep 0.25
|
||||
done
|
||||
|
||||
if [ "$READY" -ne 1 ]; then
|
||||
echo "::error::World API did not become ready."
|
||||
cat ../nexverse-api-smoke.log
|
||||
exit 1
|
||||
fi
|
||||
|
||||
grep -F '"status": "ok"' /tmp/nexverse-health.json
|
||||
|
||||
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/version > /tmp/nexverse-version.json
|
||||
grep -F '"server_version": "OpenGenesisLINK Generation 1"' /tmp/nexverse-version.json
|
||||
grep -F '"generation": "Generation 1"' /tmp/nexverse-version.json
|
||||
grep -F '"release_channel": "dev"' /tmp/nexverse-version.json
|
||||
grep -F '"api_version": "v1"' /tmp/nexverse-version.json
|
||||
grep -F '"language": "de-DE"' /tmp/nexverse-version.json
|
||||
|
||||
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/openapi.json > /tmp/nexverse-openapi.json
|
||||
grep -F '"openapi": "3.1.0"' /tmp/nexverse-openapi.json
|
||||
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
|
||||
with open("/tmp/nexverse-openapi.json", "r", encoding="utf-8") as handle:
|
||||
doc = json.load(handle)
|
||||
|
||||
schemas = doc["components"]["schemas"]
|
||||
for required in (
|
||||
"Error",
|
||||
"Pagination",
|
||||
"User",
|
||||
"Region",
|
||||
"GridRegionPlacement",
|
||||
"GridCell",
|
||||
"GridLayoutResponse",
|
||||
"GridCellResponse",
|
||||
"GridPlacementValidationResponse",
|
||||
"NodeRegion",
|
||||
"Node",
|
||||
"NodeListResponse",
|
||||
"NodeResponse",
|
||||
"InventoryPermissions",
|
||||
"InventoryFolder",
|
||||
"InventoryItem",
|
||||
"InventoryTreeResponse",
|
||||
"InventoryFolderContentResponse",
|
||||
"InventoryItemResponse",
|
||||
"InventorySearchScan",
|
||||
"InventorySearchResponse",
|
||||
"InventoryItemCreateRequest",
|
||||
"InventoryItemCreateResponse",
|
||||
"InventoryLinkCreateRequest",
|
||||
"InventoryLinkCreateResponse",
|
||||
"InventoryItemCopyRequest",
|
||||
"InventoryItemCopyResponse",
|
||||
"InventoryRestoreRequest",
|
||||
"InventoryFolderRestoreResponse",
|
||||
"InventoryItemRestoreResponse",
|
||||
"Estate",
|
||||
"EstateListResponse",
|
||||
"EstateResponse",
|
||||
"EstatePolicies",
|
||||
"EstateManagement",
|
||||
"EstateCreateRequest",
|
||||
"EstateUpdateRequest",
|
||||
"EstateManagementResponse",
|
||||
"EstateRegionAssignmentResponse",
|
||||
"RegionCreateRequest",
|
||||
"RegionPlacementRequest",
|
||||
"RegionLifecycleRequest",
|
||||
"RegionOperation",
|
||||
"RegionMutationAcceptedResponse",
|
||||
"RegionOperationResponse",
|
||||
"UserCreateRequest",
|
||||
"UserCreateResponse",
|
||||
"ApiKey",
|
||||
"AuditEvent",
|
||||
):
|
||||
assert required in schemas, f"missing OpenAPI schema: {required}"
|
||||
|
||||
user_post = doc["paths"]["/api/v1/users"]["post"]
|
||||
assert user_post["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/UserCreateRequest"
|
||||
assert user_post["responses"]["201"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/UserCreateResponse"
|
||||
|
||||
user_schema = schemas["User"]
|
||||
for required in ("username", "display_name", "is_display_name_default"):
|
||||
assert required in user_schema["required"], f"User schema missing required display-name field: {required}"
|
||||
assert user_schema["properties"]["display_name"]["maxLength"] == 31
|
||||
assert user_schema["properties"]["display_name_changed"]["minimum"] == 0
|
||||
assert user_schema["properties"]["display_name_next_update"]["minimum"] == 0
|
||||
assert schemas["UserUpdateRequest"]["properties"]["display_name"]["maxLength"] == 31
|
||||
|
||||
estates_get = doc["paths"]["/api/v1/estates"]["get"]
|
||||
assert estates_get["x-nexverse-scope"] == "estates:read"
|
||||
assert estates_get["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateListResponse"
|
||||
assert {p["name"] for p in estates_get["parameters"]} == {"q", "owner_id", "limit", "offset"}
|
||||
assert schemas["Estate"]["required"] == ["estate_id", "name", "owner_id", "parent_estate_id", "region_count"]
|
||||
|
||||
estate_get = doc["paths"]["/api/v1/estates/{estateId}"]["get"]
|
||||
assert estate_get["x-nexverse-scope"] == "estates:read"
|
||||
assert estate_get["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateResponse"
|
||||
assert [p["name"] for p in estate_get["parameters"]] == ["estateId"]
|
||||
assert estate_get["parameters"][0]["in"] == "path" and estate_get["parameters"][0]["required"]
|
||||
|
||||
estate_post = doc["paths"]["/api/v1/estates"]["post"]
|
||||
assert estate_post["x-nexverse-scope"] == "estates:manage"
|
||||
assert estate_post["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateCreateRequest"
|
||||
assert estate_post["responses"]["201"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateManagementResponse"
|
||||
|
||||
estate_patch = doc["paths"]["/api/v1/estates/{estateId}"]["patch"]
|
||||
assert estate_patch["x-nexverse-scope"] == "estates:manage"
|
||||
assert estate_patch["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateUpdateRequest"
|
||||
assert estate_patch["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateManagementResponse"
|
||||
|
||||
estate_management = doc["paths"]["/api/v1/estates/{estateId}/management"]["get"]
|
||||
assert estate_management["x-nexverse-scope"] == "estates:manage"
|
||||
assert estate_management["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateManagementResponse"
|
||||
|
||||
estate_region_put = doc["paths"]["/api/v1/estates/{estateId}/regions/{regionId}"]["put"]
|
||||
assert estate_region_put["x-nexverse-scope"] == "estates:manage"
|
||||
assert estate_region_put["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/EstateRegionAssignmentResponse"
|
||||
assert [p["name"] for p in estate_region_put["parameters"]] == ["estateId", "regionId"]
|
||||
|
||||
assert schemas["EstateCreateRequest"]["required"] == ["name", "owner_id"]
|
||||
for prop in ("managers", "allowed_residents", "banned_residents", "allowed_groups"):
|
||||
assert schemas["EstateManagement"]["properties"][prop]["type"] == "array"
|
||||
assert schemas["EstatePolicies"]["properties"]["allow_voice"]["type"] == "boolean"
|
||||
|
||||
region_get = doc["paths"]["/api/v1/regions"]["get"]
|
||||
assert region_get["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionSearchResponse"
|
||||
|
||||
region_post = doc["paths"]["/api/v1/regions"]["post"]
|
||||
assert region_post["x-nexverse-scope"] == "regions:manage"
|
||||
assert region_post["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionCreateRequest"
|
||||
assert region_post["responses"]["202"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionMutationAcceptedResponse"
|
||||
|
||||
placement_patch = doc["paths"]["/api/v1/regions/{regionId}/placement"]["patch"]
|
||||
assert placement_patch["x-nexverse-scope"] == "regions:manage"
|
||||
assert placement_patch["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionPlacementRequest"
|
||||
assert placement_patch["responses"]["202"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionMutationAcceptedResponse"
|
||||
|
||||
lifecycle_post = doc["paths"]["/api/v1/regions/{regionId}/lifecycle"]["post"]
|
||||
assert lifecycle_post["x-nexverse-scope"] == "regions:manage"
|
||||
assert lifecycle_post["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionLifecycleRequest"
|
||||
assert lifecycle_post["responses"]["202"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionMutationAcceptedResponse"
|
||||
assert {p["name"] for p in lifecycle_post["parameters"]} == {"regionId", "Idempotency-Key"}
|
||||
assert schemas["RegionLifecycleRequest"]["properties"]["action"]["enum"] == ["start", "stop", "restart"]
|
||||
assert schemas["RegionOperation"]["properties"]["operation"]["enum"] == ["create", "move", "start", "stop", "restart"]
|
||||
|
||||
operation_get = doc["paths"]["/api/v1/region-operations/{operationId}"]["get"]
|
||||
assert operation_get["x-nexverse-scope"] == "regions:read"
|
||||
assert operation_get["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/RegionOperationResponse"
|
||||
|
||||
grid_layout = doc["paths"]["/api/v1/grid/layout"]["get"]
|
||||
assert grid_layout["x-nexverse-scope"] == "regions:read"
|
||||
assert grid_layout["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/GridLayoutResponse"
|
||||
assert {p["name"] for p in grid_layout["parameters"]} == {"min_x", "max_x", "min_y", "max_y"}
|
||||
assert all(p["schema"]["type"] == "integer" for p in grid_layout["parameters"])
|
||||
|
||||
grid_cell = doc["paths"]["/api/v1/grid/cells/{x}/{y}"]["get"]
|
||||
assert grid_cell["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/GridCellResponse"
|
||||
assert [p["name"] for p in grid_cell["parameters"]] == ["x", "y"]
|
||||
assert all(p["in"] == "path" and p["required"] for p in grid_cell["parameters"])
|
||||
|
||||
placement = doc["paths"]["/api/v1/grid/validate-placement"]["get"]
|
||||
assert placement["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/GridPlacementValidationResponse"
|
||||
assert {p["name"] for p in placement["parameters"]} == {"x", "y", "size_x", "size_y"}
|
||||
assert schemas["GridCell"]["properties"]["status"]["enum"] == ["free", "occupied", "reserved", "conflict"]
|
||||
assert schemas["GridRegionPlacement"]["properties"]["size_x"]["maximum"] == 4096
|
||||
for field in ("grid_x", "grid_y", "world_x", "world_y"):
|
||||
assert field in schemas["Region"]["required"], f"Region schema missing coordinate: {field}"
|
||||
assert schemas["Region"]["properties"][field]["type"] == "integer"
|
||||
assert "node_id" in schemas["GridRegionPlacement"]["properties"]
|
||||
assert "node_state" in schemas["GridRegionPlacement"]["properties"]
|
||||
assert schemas["Node"]["properties"]["managed_region_commands"]["type"] == "boolean"
|
||||
assert schemas["Node"]["properties"]["cross_region_object_messaging"]["type"] == "boolean"
|
||||
assert schemas["Node"]["properties"]["cross_owner_object_messaging"]["type"] == "boolean"
|
||||
assert schemas["Node"]["properties"]["object_messages_per_second"]["maximum"] == 200
|
||||
assert schemas["Node"]["properties"]["object_message_max_age_seconds"]["maximum"] == 300
|
||||
|
||||
nodes_get = doc["paths"]["/api/v1/nodes"]["get"]
|
||||
assert nodes_get["x-nexverse-scope"] == "simulators:read"
|
||||
assert nodes_get["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/NodeListResponse"
|
||||
node_get = doc["paths"]["/api/v1/nodes/{nodeId}"]["get"]
|
||||
assert node_get["x-nexverse-scope"] == "simulators:read"
|
||||
assert node_get["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/NodeResponse"
|
||||
assert [p["name"] for p in node_get["parameters"]] == ["nodeId"]
|
||||
assert node_get["parameters"][0]["in"] == "path" and node_get["parameters"][0]["required"]
|
||||
assert schemas["Node"]["properties"]["state"]["enum"] == ["online", "stale", "offline"]
|
||||
|
||||
inventory_search = doc["paths"]["/api/v1/inventory/search"]["get"]
|
||||
assert inventory_search["x-nexverse-scope"] == "inventory:read"
|
||||
assert [p["name"] for p in inventory_search["parameters"]] == ["owner_id", "q", "limit"]
|
||||
inventory_create = doc["paths"]["/api/v1/inventory/items"]["post"]
|
||||
assert inventory_create["x-nexverse-scope"] == "admin:*"
|
||||
assert inventory_create["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryItemCreateRequest"
|
||||
assert inventory_create["responses"]["201"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryItemCreateResponse"
|
||||
inventory_links = doc["paths"]["/api/v1/inventory/links"]["post"]
|
||||
assert inventory_links["x-nexverse-scope"] == "inventory:write"
|
||||
assert inventory_links["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryLinkCreateRequest"
|
||||
assert inventory_links["responses"]["201"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryLinkCreateResponse"
|
||||
assert schemas["InventorySearchResponse"]["properties"]["scan"]["$ref"] == "#/components/schemas/InventorySearchScan"
|
||||
assert schemas["InventoryItem"]["properties"]["permissions"]["$ref"] == "#/components/schemas/InventoryPermissions"
|
||||
inventory_copy = doc["paths"]["/api/v1/inventory/items/copy"]["post"]
|
||||
assert inventory_copy["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryItemCopyRequest"
|
||||
folder_restore = doc["paths"]["/api/v1/inventory/folders/{folderId}/restore"]["post"]
|
||||
assert folder_restore["requestBody"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryRestoreRequest"
|
||||
item_restore = doc["paths"]["/api/v1/inventory/items/{itemId}/restore"]["post"]
|
||||
assert item_restore["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == "#/components/schemas/InventoryItemRestoreResponse"
|
||||
for inventory_path in (
|
||||
"/api/v1/inventory/tree",
|
||||
"/api/v1/inventory/folders",
|
||||
"/api/v1/inventory/folders/{folderId}",
|
||||
"/api/v1/inventory/items",
|
||||
"/api/v1/inventory/items/{itemId}",
|
||||
"/api/v1/inventory/items/copy",
|
||||
"/api/v1/inventory/folders/{folderId}/restore",
|
||||
"/api/v1/inventory/items/{itemId}/restore",
|
||||
"/api/v1/inventory/links",
|
||||
"/api/v1/inventory/lost-and-found",
|
||||
"/api/v1/inventory/trash/empty",
|
||||
):
|
||||
assert inventory_path in doc["paths"], f"Inventory OpenAPI path missing: {inventory_path}"
|
||||
|
||||
for discovery_path in (
|
||||
"/api/v1/search",
|
||||
"/api/v1/places",
|
||||
"/api/v1/places/{placeId}",
|
||||
"/api/v1/events",
|
||||
"/api/v1/classifieds",
|
||||
"/api/v1/land-portal",
|
||||
"/api/v1/land-portal/owned",
|
||||
"/api/v1/destinations",
|
||||
"/api/v1/destinations/categories",
|
||||
"/api/v1/destinations/{destinationId}",
|
||||
"/api/v1/destinations/{destinationId}/visit",
|
||||
"/api/v1/destinations/{destinationId}/moderation",
|
||||
):
|
||||
assert discovery_path in doc["paths"], f"Discovery OpenAPI path missing: {discovery_path}"
|
||||
|
||||
assert doc["paths"]["/api/v1/search"]["get"]["security"] == []
|
||||
assert doc["paths"]["/api/v1/places"]["get"]["security"] == []
|
||||
assert doc["paths"]["/api/v1/places"]["post"]["x-nexverse-scope"] == "discovery:manage"
|
||||
assert doc["paths"]["/api/v1/destinations"]["post"]["x-nexverse-scope"] == "discovery:submit"
|
||||
assert doc["paths"]["/api/v1/destinations/{destinationId}/moderation"]["post"]["x-nexverse-scope"] == "discovery:manage"
|
||||
|
||||
assert doc["components"]["securitySchemes"]["apiKeyAuth"]["name"] == "X-NexVerse-Api-Key"
|
||||
assert doc["x_nexverse_idempotency"]["protected_operations"] == [
|
||||
"POST /api/v1/users",
|
||||
"POST /api/v1/regions",
|
||||
"PATCH /api/v1/regions/{regionId}/placement",
|
||||
"POST /api/v1/regions/{regionId}/lifecycle",
|
||||
]
|
||||
assert "/api/v1/docs" in doc["paths"]
|
||||
assert doc["x_nexverse_language"] == "de-DE"
|
||||
assert doc["x_nexverse_version_history"][0]["api_version"] == "v1"
|
||||
history = doc["x_nexverse_version_history"]
|
||||
assert [item["server_line"] for item in history[:9]] == [
|
||||
"0.9.4.0", "0.9.3.13", "0.9.3.12", "0.9.3.10", "0.9.3.8",
|
||||
"0.9.3.7", "0.9.3.6", "0.9.3.5", "0.9.3.4",
|
||||
]
|
||||
assert history[0]["status"] == "development"
|
||||
assert [item["status"] for item in history[:9]] == [
|
||||
"development", "release", "release", "release", "release",
|
||||
"completed", "completed", "completed", "release",
|
||||
]
|
||||
assert doc["x_nexverse_changelog"]
|
||||
assert doc["x_nexverse_changelog"][0]["version"] == "0.9.4.0"
|
||||
assert doc["x_nexverse_changelog"][0]["status"] == "development"
|
||||
assert "0.9.3.1 Dev" not in json.dumps(doc, ensure_ascii=False)
|
||||
assert "Resident and Hypergrid statistics dashboard" not in json.dumps(doc, ensure_ascii=False)
|
||||
assert "Legacy Cleanup and Platform Foundation" not in json.dumps(doc, ensure_ascii=False)
|
||||
display_change = next(
|
||||
item for item in doc["x_nexverse_changelog"]
|
||||
if item["title"] == "Persistente Display-Name-Grundlage"
|
||||
)
|
||||
assert display_change["status"] == "implemented"
|
||||
assert display_change["category"] == "identity"
|
||||
assert "/api/v1/users/{principalId}" in display_change["endpoints"]
|
||||
dev_start = next(item for item in doc["x_nexverse_changelog"] if item["title"] == "NexVerse 0.9.3.3 Dev gestartet")
|
||||
assert dev_start["status"] == "development"
|
||||
estate_change = next(item for item in doc["x_nexverse_changelog"] if item["title"] == "Estate-Verwaltung: Owner, Listen, Policies und Regionszuordnung")
|
||||
assert estate_change["status"] == "implemented"
|
||||
assert "/api/v1/estates" in estate_change["endpoints"]
|
||||
assert "/api/v1/estates/{estateId}" in estate_change["endpoints"]
|
||||
assert "/api/v1/estates/{estateId}/management" in estate_change["endpoints"]
|
||||
assert "/api/v1/estates/{estateId}/regions/{regionId}" in estate_change["endpoints"]
|
||||
|
||||
roadmap = doc["x_nexverse_roadmap"]
|
||||
assert roadmap["current_milestone"] == "0.9.4.0"
|
||||
assert roadmap["current_codename"] == "Generation 1"
|
||||
milestones = {item["version"]: item for item in roadmap["milestones"]}
|
||||
assert milestones["0.9.3.1"]["status"] == "released"
|
||||
assert milestones["0.9.3.2"]["status"] == "completed"
|
||||
assert milestones["0.9.3.2"]["checklist"] == {"completed": 36, "total": 36, "open": 0}
|
||||
assert milestones["0.9.3.3"]["status"] == "completed"
|
||||
assert milestones["0.9.3.4"]["status"] == "released"
|
||||
assert milestones["0.9.3.5"]["status"] == "completed"
|
||||
assert milestones["0.9.3.5"]["checklist"] == {"completed": 83, "total": 83, "open": 0}
|
||||
assert milestones["0.9.3.6"]["status"] == "completed"
|
||||
assert milestones["0.9.3.7"]["status"] == "completed"
|
||||
assert milestones["0.9.3.8"]["status"] == "released"
|
||||
assert milestones["0.9.3.9"]["status"] == "deferred"
|
||||
assert milestones["0.9.3.10"]["status"] == "released"
|
||||
assert milestones["0.9.3.12"]["status"] == "released"
|
||||
assert milestones["0.9.3.13"]["status"] == "released"
|
||||
assert milestones["0.9.4.0"]["status"] == "active"
|
||||
assert "Pathfinding 2.0" in milestones["0.9.3.10"]["summary"]
|
||||
assert "My Outfits 2.0" in milestones["0.9.3.10"]["summary"]
|
||||
|
||||
from pathlib import Path
|
||||
roadmap_text = Path("../doc/NexVerse/ROADMAP.md").read_text(encoding="utf-8")
|
||||
sections = {}
|
||||
current = None
|
||||
for line in roadmap_text.splitlines():
|
||||
if line.startswith("# Milestone "):
|
||||
current = line[len("# Milestone "):].strip()
|
||||
sections[current] = {"completed": 0, "total": 0}
|
||||
continue
|
||||
if current and (line.startswith("- [x]") or line.startswith("- [X]") or line.startswith("- [ ]")):
|
||||
sections[current]["total"] += 1
|
||||
if line.startswith("- [x]") or line.startswith("- [X]"):
|
||||
sections[current]["completed"] += 1
|
||||
|
||||
for source_name, api_version in (
|
||||
("0.9.3.1 — NEXJAST", "0.9.3.1"),
|
||||
("0.9.3.2", "0.9.3.2"),
|
||||
("0.9.3.3", "0.9.3.3"),
|
||||
("0.9.3.5", "0.9.3.5"),
|
||||
):
|
||||
published = milestones[api_version]["checklist"]
|
||||
parsed = sections[source_name]
|
||||
assert published["completed"] == parsed["completed"]
|
||||
assert published["total"] == parsed["total"]
|
||||
assert published["open"] == parsed["total"] - parsed["completed"]
|
||||
|
||||
stats_get = doc["paths"]["/api/v1/statistics/summary"]["get"]
|
||||
assert stats_get["x-nexverse-scope"] == "statistics:read"
|
||||
assert {} in stats_get["security"], "statistics aggregate mode must permit anonymous access"
|
||||
stats_schema = schemas["StatisticsSummaryResponse"]
|
||||
for required in ("detail_level", "protected_details"):
|
||||
assert required in stats_schema["required"], f"statistics schema missing required field: {required}"
|
||||
|
||||
assert doc["paths"]["/api/v1/users"]["post"]["x-nexverse-audience"] == ["admin"]
|
||||
assert doc["paths"]["/api/v1/nodes"]["get"]["x-nexverse-audience"] == ["admin", "service"]
|
||||
assert doc["paths"]["/api/v1/economy/balance"]["get"]["x-nexverse-audience"] == ["citizen", "admin", "service"]
|
||||
assert doc["paths"]["/api/v1/inventory/tree"]["get"]["x-nexverse-audience"] == ["citizen", "admin", "service"]
|
||||
# Real simulator Experience routes must appear in OpenAPI with
|
||||
# their method, service-only security and typed responses.
|
||||
for experience_path, methods in {
|
||||
"/api/v1/experiences/script/info": ("get",),
|
||||
"/api/v1/experiences/script/search": ("get",),
|
||||
"/api/v1/experiences/script/resolve": ("get",),
|
||||
"/api/v1/experiences/script/details": ("get",),
|
||||
"/api/v1/experiences/script/permission": ("get",),
|
||||
"/api/v1/experiences/script/location": ("get",),
|
||||
"/api/v1/experiences/script/kv": ("post",),
|
||||
"/api/v1/experiences/viewer/permissions": ("get", "put"),
|
||||
"/api/v1/experiences/viewer/group": ("get",),
|
||||
"/api/v1/experiences/viewer/manage": ("post", "put"),
|
||||
}.items():
|
||||
for method in methods:
|
||||
assert method in doc["paths"][experience_path], (experience_path, method)
|
||||
viewer = doc["paths"]["/api/v1/experiences/viewer/permissions"]
|
||||
assert viewer["put"]["x-nexverse-scope"] == "experiences:viewer:permissions"
|
||||
manager = doc["paths"]["/api/v1/experiences/viewer/manage"]
|
||||
for method, schema, result_code in (
|
||||
("post", "ExperienceViewerAcquireRequest", "201"),
|
||||
("put", "ExperienceViewerProfileRequest", "200"),
|
||||
):
|
||||
operation = manager[method]
|
||||
assert operation["x-nexverse-audience"] == ["service"]
|
||||
assert operation["x-nexverse-scope"] == "experiences:viewer:manage"
|
||||
assert operation["security"] == [{"apiKeyAuth": []}]
|
||||
assert operation["requestBody"]["content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/" + schema)
|
||||
assert operation["responses"][result_code]["content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/ExperienceViewerManageResponse")
|
||||
assert schemas["ExperienceViewerAcquireRequest"]["required"] == ["owner_id"]
|
||||
assert "experience_id" in schemas["ExperienceViewerProfileRequest"]["required"]
|
||||
assert viewer["put"]["x-nexverse-audience"] == ["service"]
|
||||
assert viewer["put"]["security"] == [{"apiKeyAuth": []}]
|
||||
assert viewer["put"]["requestBody"]["content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/ExperienceViewerDecisionRequest")
|
||||
assert viewer["get"]["responses"]["200"]["content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/ExperienceViewerPermissionReadResponse")
|
||||
assert {p["name"] for p in viewer["get"]["parameters"]} == {
|
||||
"resident_id", "experience_id"}
|
||||
assert "oneOf" in schemas["ExperienceViewerPermissionReadResponse"]
|
||||
assert doc["paths"]["/api/v1/experiences/script/kv"]["post"]["requestBody"][
|
||||
"content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/ExperienceKvRequest")
|
||||
assert doc["paths"]["/api/v1/experiences/script/info"]["get"]["responses"]["200"][
|
||||
"content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/ExperiencePublicInfoResponse")
|
||||
assert "check_original" in schemas["ExperienceKvRequest"]["properties"]
|
||||
assert doc["x_nexverse_version_history"][0]["status"] == "development"
|
||||
assert doc["x_nexverse_version_history"][0]["codename"] == "Generation 1"
|
||||
for path, required_methods in {
|
||||
"/api/v1/profiles/{principalId}/image": ("get",),
|
||||
"/api/v1/events/{eventId}": ("get", "patch", "delete"),
|
||||
"/api/v1/classifieds/{classifiedId}": ("get", "patch", "delete"),
|
||||
"/api/v1/groups/mine": ("get",),
|
||||
}.items():
|
||||
for method in required_methods:
|
||||
assert method in doc["paths"][path], (path, method)
|
||||
profile_image = doc["paths"]["/api/v1/profiles/{principalId}/image"]["get"]
|
||||
assert "image/png" in profile_image["responses"]["200"]["content"]
|
||||
assert profile_image["responses"]["200"]["content"]["image/png"]["schema"]["format"] == "binary"
|
||||
assert doc["paths"]["/api/v1/events/{eventId}"]["patch"]["x-nexverse-scope"] == "discovery:manage"
|
||||
assert doc["paths"]["/api/v1/groups/mine"]["get"]["x-nexverse-scope"] == "groups:read"
|
||||
assert doc["paths"]["/api/v1/events/{eventId}"]["patch"]["requestBody"][
|
||||
"content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/DiscoveryEventPatch")
|
||||
assert doc["paths"]["/api/v1/classifieds/{classifiedId}"]["patch"]["requestBody"][
|
||||
"content"]["application/json"]["schema"]["$ref"] == (
|
||||
"#/components/schemas/DiscoveryClassifiedPatch")
|
||||
assert "/api/v1/chatgpt-instructions.md" in doc["paths"]
|
||||
assert "/api/v1/chatgpt-buergerportal.md" in doc["paths"]
|
||||
assert "/api/v1/chatgpt-admin.md" in doc["paths"]
|
||||
assert "x-nexverse-ai-instruction" in doc["paths"]["/api/v1/users"]["post"]
|
||||
assert "x-nexverse-security-constraints" in doc["paths"]["/api/v1/users"]["post"]
|
||||
print("NexVerse OpenAPI 3.1 schema contract smoke: OK")
|
||||
PY
|
||||
|
||||
STATS_STATUS=$(curl --silent --max-time 2 -o /tmp/nexverse-statistics.json -w '%{http_code}' http://127.0.0.1:19090/api/v1/statistics/summary)
|
||||
test "$STATS_STATUS" = "503"
|
||||
grep -F '"error": "statistics_data_unavailable"' /tmp/nexverse-statistics.json
|
||||
if [ "$STATS_STATUS" = "404" ]; then
|
||||
echo "::error::Statistics route disappeared while privileged endpoints are disabled."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/docs > /tmp/nexverse-api-docs.html
|
||||
grep -F 'OpenGenesisLINK – Control Center' /tmp/nexverse-api-docs.html
|
||||
# Same-path POST must reach the dedicated auth handler, never return
|
||||
# the HTML login shell with a misleading HTTP 200. This synthetic
|
||||
# smoke runs in public-only mode, so real admin login is disabled.
|
||||
DOCS_LOGIN_STATUS="$(curl --silent --max-time 3 --output /tmp/ogl-docs-login.json --write-out '%{http_code}' \
|
||||
-X POST -H 'Content-Type: application/json' \
|
||||
--data '{"username":"ci-user","password":"not-a-real-password"}' \
|
||||
http://127.0.0.1:19090/api/v1/docs)"
|
||||
test "$DOCS_LOGIN_STATUS" = 503
|
||||
grep -F '"error":"admin_login_unavailable"' /tmp/ogl-docs-login.json
|
||||
# Full Control Center HTML must never be returned without a
|
||||
# server-verified local administrator token, regardless of UI scripts.
|
||||
DOCS_STATUS="$(curl --silent --output /tmp/ogl-docs-denied.txt --write-out '%{http_code}' --max-time 3 http://127.0.0.1:19090/api/v1/docs/panel)"
|
||||
test "$DOCS_STATUS" = 401
|
||||
if grep -F 'id="page-explorer"' /tmp/ogl-docs-denied.txt; then
|
||||
echo "::error::Protected OGL admin HTML was exposed anonymously"
|
||||
exit 1
|
||||
fi
|
||||
# The full dashboard is protected and cannot be downloaded anonymously.
|
||||
# Verify retained explorer/grid functions in its compiled HTML source.
|
||||
DOCS_SOURCE=../NexVerse/Server/Api/NexApiDocsPage.cs
|
||||
grep -F 'Was ist neu?' $DOCS_SOURCE
|
||||
grep -F 'OpenGenesisLINK Entwicklungsplan' $DOCS_SOURCE
|
||||
grep -F 'Was ist neu?' $DOCS_SOURCE
|
||||
grep -F 'OpenGenesisLINK Entwicklungsplan' $DOCS_SOURCE
|
||||
grep -F 'x_nexverse_changelog' $DOCS_SOURCE
|
||||
grep -F 'x_nexverse_roadmap' $DOCS_SOURCE
|
||||
grep -F '/api/v1/openapi.json' $DOCS_SOURCE
|
||||
grep -F 'ChatGPT / Portale' $DOCS_SOURCE
|
||||
grep -F '/api/v1/chatgpt-instructions.md' $DOCS_SOURCE
|
||||
grep -F '/api/v1/chatgpt-buergerportal.md' $DOCS_SOURCE
|
||||
grep -F '/api/v1/chatgpt-admin.md' $DOCS_SOURCE
|
||||
grep -F 'data-audience-target="citizen"' $DOCS_SOURCE
|
||||
grep -F 'data-endpoint-audience="admin"' $DOCS_SOURCE
|
||||
grep -F 'Interaktiver Grid-Planer' $DOCS_SOURCE
|
||||
grep -F '/api/v1/grid/layout' $DOCS_SOURCE
|
||||
grep -F '/api/v1/grid/validate-placement' $DOCS_SOURCE
|
||||
grep -F 'regions:read' $DOCS_SOURCE
|
||||
grep -F 'Simulator-Nodes' $DOCS_SOURCE
|
||||
grep -F '/api/v1/nodes' $DOCS_SOURCE
|
||||
grep -F 'simulators:read' $DOCS_SOURCE
|
||||
grep -F 'Region erstellen' $DOCS_SOURCE
|
||||
grep -F 'createGridRegion' $DOCS_SOURCE
|
||||
grep -F 'moveGridRegion' $DOCS_SOURCE
|
||||
grep -F 'gridRegionSearch' $DOCS_SOURCE
|
||||
grep -F 'jumpGridRegion' $DOCS_SOURCE
|
||||
grep -F 'startGridRegion' $DOCS_SOURCE
|
||||
grep -F 'stopGridRegion' $DOCS_SOURCE
|
||||
grep -F 'restartGridRegion' $DOCS_SOURCE
|
||||
grep -F 'loadGridEstates' $DOCS_SOURCE
|
||||
grep -F 'gridEstateOptions' $DOCS_SOURCE
|
||||
grep -F 'loadEstateManagement' $DOCS_SOURCE
|
||||
grep -F 'createEstateManagement' $DOCS_SOURCE
|
||||
grep -F 'updateEstateManagement' $DOCS_SOURCE
|
||||
grep -F 'assignEstateRegion' $DOCS_SOURCE
|
||||
grep -F 'estates:read' $DOCS_SOURCE
|
||||
grep -F 'estates:manage' $DOCS_SOURCE
|
||||
grep -F '/api/v1/estates' $DOCS_SOURCE
|
||||
grep -F '/api/v1/regions/' $DOCS_SOURCE
|
||||
grep -F '/lifecycle' $DOCS_SOURCE
|
||||
grep -F '/api/v1/region-operations/' $DOCS_SOURCE
|
||||
if grep -F 'localStorage' /tmp/nexverse-api-docs.html || grep -F 'localStorage' "$DOCS_SOURCE"; then
|
||||
echo "::error::API Control Center must not persist credentials in localStorage."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/chatgpt-instructions.md > /tmp/nexverse-chatgpt.md
|
||||
grep -F 'OpenGenesisLINK World API - ChatGPT Gesamtanweisung' /tmp/nexverse-chatgpt.md
|
||||
grep -F 'Buergerportal / Einwohner-Selbstbedienung' /tmp/nexverse-chatgpt.md
|
||||
grep -F '## Adminbereich' /tmp/nexverse-chatgpt.md
|
||||
grep -F '/api/v1/openapi.json' /tmp/nexverse-chatgpt.md
|
||||
grep -F 'experiences:viewer:permissions' /tmp/nexverse-chatgpt.md
|
||||
grep -F 'experiences:viewer:manage' /tmp/nexverse-chatgpt.md
|
||||
grep -F 'Script-/Service-Integrationen' /tmp/nexverse-chatgpt.md
|
||||
|
||||
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/chatgpt-buergerportal.md > /tmp/nexverse-chatgpt-citizen.md
|
||||
grep -F 'ChatGPT Anweisung Buergerportal' /tmp/nexverse-chatgpt-citizen.md
|
||||
grep -F 'admin:* gehoeren nicht in das Buergerportal' /tmp/nexverse-chatgpt-citizen.md
|
||||
grep -F 'Viewer-CAPS' /tmp/nexverse-chatgpt-citizen.md
|
||||
|
||||
curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/chatgpt-admin.md > /tmp/nexverse-chatgpt-admin.md
|
||||
grep -F 'ChatGPT Anweisung Adminbereich' /tmp/nexverse-chatgpt-admin.md
|
||||
grep -F 'Administrative Mutationen nur mit ausdruecklicher Benutzerabsicht' /tmp/nexverse-chatgpt-admin.md
|
||||
grep -F 'experiences:viewer:permissions' /tmp/nexverse-chatgpt-admin.md
|
||||
grep -F 'experiences:viewer:manage' /tmp/nexverse-chatgpt-admin.md
|
||||
|
||||
# Validate the actual server-generated Markdown, not merely source
|
||||
# markers: every documented full-index path must equal the running
|
||||
# server OpenAPI, and citizen/admin indexes must respect audiences.
|
||||
curl --silent --fail --max-time 5 \
|
||||
http://127.0.0.1:19090/api/v1/openapi.json \
|
||||
> /tmp/nexverse-chatgpt-openapi.json
|
||||
python3 "$GITHUB_WORKSPACE/tools/ci/verify_worldapi_chatgpt_runtime.py" \
|
||||
--openapi /tmp/nexverse-chatgpt-openapi.json \
|
||||
--all /tmp/nexverse-chatgpt.md \
|
||||
--citizen /tmp/nexverse-chatgpt-citizen.md \
|
||||
--admin /tmp/nexverse-chatgpt-admin.md
|
||||
|
||||
|
||||
ledger-db-matrix:
|
||||
name: NV dollar live database matrix
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
services:
|
||||
mariadb:
|
||||
image: mariadb:11.4
|
||||
env:
|
||||
MARIADB_ROOT_PASSWORD: ledgerroot
|
||||
MARIADB_DATABASE: ogl_ledger_ci
|
||||
MARIADB_USER: ledger
|
||||
MARIADB_PASSWORD: ledgerpass
|
||||
ports:
|
||||
- 3306
|
||||
options: >-
|
||||
--health-cmd="healthcheck.sh --connect --innodb_initialized"
|
||||
--health-interval=5s
|
||||
--health-timeout=5s
|
||||
--health-retries=24
|
||||
|
||||
postgres:
|
||||
image: postgres:16
|
||||
env:
|
||||
POSTGRES_DB: ogl_ledger_ci
|
||||
POSTGRES_USER: ledger
|
||||
POSTGRES_PASSWORD: ledgerpass
|
||||
ports:
|
||||
- 5432
|
||||
options: >-
|
||||
--health-cmd="pg_isready -U ledger -d ogl_ledger_ci"
|
||||
--health-interval=5s
|
||||
--health-timeout=5s
|
||||
--health-retries=24
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup .NET 10
|
||||
uses: actions/setup-dotnet@v4
|
||||
with:
|
||||
dotnet-version: '10.0.x'
|
||||
|
||||
- name: Verify bundled database providers
|
||||
shell: bash
|
||||
run: |
|
||||
test -f bin/MySql.Data.dll
|
||||
test -f bin/Npgsql.dll
|
||||
|
||||
- name: Run live NV dollar ledger matrix
|
||||
shell: bash
|
||||
env:
|
||||
NEX_LEDGER_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
|
||||
NEX_LEDGER_POSTGRESQL: "Host=127.0.0.1;Port=${{ job.services.postgres.ports[5432] }};Database=ogl_ledger_ci;Username=ledger;Password=ledgerpass;SSL Mode=Disable;"
|
||||
run: dotnet run --configuration Release --project tools/ci/NexLedgerSqlMatrixRegression/NexLedgerSqlMatrixRegression.csproj
|
||||
|
||||
- name: Run real MariaDB OGL profile feed deletion/retention race regression
|
||||
shell: bash
|
||||
env:
|
||||
NEX_FEED_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
|
||||
run: dotnet run --configuration Release --project tools/ci/OglProfileFeedMariaDbRegression/OglProfileFeedMariaDbRegression.csproj
|
||||
|
||||
- name: Run real MariaDB NexPortalIM archive regression
|
||||
shell: bash
|
||||
env:
|
||||
NEX_PORTAL_IM_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
|
||||
run: dotnet run --configuration Release --project tools/ci/NexPortalImMariaDbRegression/NexPortalImMariaDbRegression.csproj
|
||||
|
||||
- name: Run real MariaDB NPC owner direct-IM archive regression (R620)
|
||||
shell: bash
|
||||
env:
|
||||
NEX_NPC_CHAT_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
|
||||
run: dotnet run --configuration Release --project tools/ci/NexNpcChatStoreRegression/NexNpcChatStoreRegression.csproj
|
||||
|
||||
- name: Run real MariaDB NexGroups authorization and invitation regression
|
||||
shell: bash
|
||||
env:
|
||||
NEX_GROUPS_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
|
||||
run: |
|
||||
chmod +x runprebuild.sh
|
||||
./runprebuild.sh
|
||||
dotnet run --configuration Release --project tools/ci/NexGroupsSqlAuthorizationRegression/NexGroupsSqlAuthorizationRegression.csproj
|
||||
|
||||
- name: Run signed bearer HTTP NexGroups authorization regression
|
||||
shell: bash
|
||||
env:
|
||||
NEX_GROUPS_MARIADB: "Data Source=127.0.0.1;Port=${{ job.services.mariadb.ports[3306] }};Database=ogl_ledger_ci;User ID=ledger;Password=ledgerpass;Old Guids=true;SslMode=None;"
|
||||
run: dotnet run --configuration Release --project tools/ci/NexGroupsHttpRegression/NexGroupsHttpRegression.csproj
|
||||
@@ -134,12 +134,18 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenGenesisLINK.Addons.OGLW
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OpenGenesisLINK.Addons.OGLEnergy", "addons/OGLEnergy/OpenGenesisLINK.Addons.OGLEnergy.csproj", "{AF51F7E2-91D2-4801-AB77-F512A0430105}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "os_webinterface", "addons/OSWebInterface/os_webinterface.csproj", "{338B6E51-9969-4A9E-9E2C-E728A23A56A9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{338B6E51-9969-4A9E-9E2C-E728A23A56A9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{338B6E51-9969-4A9E-9E2C-E728A23A56A9}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{338B6E51-9969-4A9E-9E2C-E728A23A56A9}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{338B6E51-9969-4A9E-9E2C-E728A23A56A9}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{AF51F7E2-91D2-4801-AB77-F512A0430101}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{AF51F7E2-91D2-4801-AB77-F512A0430101}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{AF51F7E2-91D2-4801-AB77-F512A0430101}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Collections.Concurrent;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using log4net;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Framework;
|
||||
using OpenSim.Region.Framework.Scenes;
|
||||
using OpenSim.Services.Interfaces;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
internal sealed class AdminHttpServer : IDisposable
|
||||
{
|
||||
private sealed record Session(UUID Principal, string Name, string Csrf, DateTimeOffset Expires);
|
||||
private sealed class Attempt { public int Count; public DateTimeOffset Reset = DateTimeOffset.UtcNow.AddMinutes(5); }
|
||||
private sealed record LoginRequest(string Username, string Password);
|
||||
private sealed record RegionRequest(string RegionId);
|
||||
private sealed record UpdateRequest(string Sha);
|
||||
private sealed record ImportRequest(string RegionId);
|
||||
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(AdminHttpServer));
|
||||
private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
|
||||
private readonly ConcurrentDictionary<UUID, Scene> _scenes;
|
||||
private readonly ConcurrentDictionary<string, Session> _sessions = new();
|
||||
private readonly ConcurrentDictionary<string, Attempt> _attempts = new();
|
||||
private readonly HttpListener _listener = new();
|
||||
private readonly CancellationTokenSource _stop = new();
|
||||
private readonly AdminOperations _operations;
|
||||
private Task? _acceptTask;
|
||||
private readonly DateTimeOffset _started = DateTimeOffset.UtcNow;
|
||||
|
||||
public AdminHttpServer(ConcurrentDictionary<UUID, Scene> scenes, string storage, int port, int retention, List<(string Name, Uri Uri)> services)
|
||||
{
|
||||
_scenes = scenes;
|
||||
_operations = new AdminOperations(scenes, storage, retention, services);
|
||||
// Binding to any public interface is deliberately unsupported.
|
||||
_listener.Prefixes.Add($"http://127.0.0.1:{port}/");
|
||||
}
|
||||
|
||||
public void Start()
|
||||
{
|
||||
_listener.Start();
|
||||
_acceptTask = Task.Run(AcceptLoopAsync);
|
||||
}
|
||||
|
||||
private async Task AcceptLoopAsync()
|
||||
{
|
||||
while (!_stop.IsCancellationRequested)
|
||||
{
|
||||
HttpListenerContext context;
|
||||
try { context = await _listener.GetContextAsync(); }
|
||||
catch (Exception e) when (e is HttpListenerException or ObjectDisposedException) { break; }
|
||||
_ = Task.Run(() => DispatchAsync(context));
|
||||
}
|
||||
}
|
||||
|
||||
private static string Token() => Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant();
|
||||
|
||||
private static async Task<T?> ReadJsonAsync<T>(HttpListenerRequest req) where T : class
|
||||
{
|
||||
if (req.ContentLength64 > 16384 || req.ContentType is null ||
|
||||
!req.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
|
||||
return null;
|
||||
using var buffer = new MemoryStream();
|
||||
byte[] block = new byte[4096];
|
||||
int count;
|
||||
while ((count = await req.InputStream.ReadAsync(block)) > 0)
|
||||
{
|
||||
if (buffer.Length + count > 16384) return null;
|
||||
buffer.Write(block, 0, count);
|
||||
}
|
||||
try { return JsonSerializer.Deserialize<T>(buffer.ToArray(), JsonOptions); }
|
||||
catch (JsonException) { return null; }
|
||||
}
|
||||
|
||||
private static async Task SendAsync(HttpListenerResponse response, int code, object data)
|
||||
{
|
||||
response.StatusCode = code;
|
||||
response.ContentType = "application/json; charset=utf-8";
|
||||
byte[] payload = JsonSerializer.SerializeToUtf8Bytes(data, JsonOptions);
|
||||
response.ContentLength64 = payload.Length;
|
||||
await response.OutputStream.WriteAsync(payload);
|
||||
}
|
||||
|
||||
private static void SecurityHeaders(HttpListenerResponse r)
|
||||
{
|
||||
r.Headers["X-Content-Type-Options"] = "nosniff";
|
||||
r.Headers["Referrer-Policy"] = "no-referrer";
|
||||
r.Headers["X-Frame-Options"] = "DENY";
|
||||
r.Headers["Cache-Control"] = "no-store, private";
|
||||
r.Headers["Content-Security-Policy"] =
|
||||
"default-src 'none'; script-src 'self'; style-src 'self'; connect-src 'self'; img-src 'self' data:; base-uri 'none'; form-action 'self'; frame-ancestors 'none'";
|
||||
}
|
||||
|
||||
private static bool SameOrigin(HttpListenerRequest request)
|
||||
{
|
||||
// No CORS: browsers sending cross-site requests may not perform mutations.
|
||||
string origin = request.Headers["Origin"] ?? "";
|
||||
if (!string.IsNullOrEmpty(origin))
|
||||
{
|
||||
if (!Uri.TryCreate(origin, UriKind.Absolute, out Uri? parsed)) return false;
|
||||
string? host = request.Headers["Host"];
|
||||
if (string.IsNullOrWhiteSpace(host)) return false;
|
||||
return string.Equals(parsed.Authority, host, StringComparison.OrdinalIgnoreCase) &&
|
||||
(parsed.Scheme == "https" || parsed.Scheme == "http");
|
||||
}
|
||||
string fetchSite = request.Headers["Sec-Fetch-Site"] ?? "";
|
||||
return fetchSite is "" or "same-origin" or "none";
|
||||
}
|
||||
|
||||
private bool TrySession(HttpListenerRequest request, out Session? session)
|
||||
{
|
||||
session = null;
|
||||
string? id = request.Cookies["ogl_admin"]?.Value;
|
||||
if (id is null || !_sessions.TryGetValue(id, out Session? s)) return false;
|
||||
if (s.Expires <= DateTimeOffset.UtcNow)
|
||||
{
|
||||
_sessions.TryRemove(id, out _);
|
||||
return false;
|
||||
}
|
||||
// UserLevel can be revoked while a session is active. Revalidate on each action.
|
||||
Scene? scene = _scenes.Values.FirstOrDefault(v => v.UserAccountService is not null);
|
||||
if (scene is null) return false;
|
||||
try
|
||||
{
|
||||
UserAccount? account = scene.UserAccountService?.GetUserAccount(UUID.Zero, s.Principal);
|
||||
if (account is null || account.UserLevel <= 0 || !account.LoginAllowed) return false;
|
||||
}
|
||||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Account revalidation failed", e); return false; }
|
||||
session = s;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task LoginAsync(HttpListenerContext ctx)
|
||||
{
|
||||
var request = await ReadJsonAsync<LoginRequest>(ctx.Request);
|
||||
if (request is null || string.IsNullOrWhiteSpace(request.Username) ||
|
||||
string.IsNullOrEmpty(request.Password) || request.Username.Length > 120 ||
|
||||
request.Password.Length > 1024)
|
||||
{
|
||||
await SendAsync(ctx.Response, 400, new { error = "Ungültige Anmeldung" });
|
||||
return;
|
||||
}
|
||||
string key = request.Username.Trim().ToLowerInvariant();
|
||||
Attempt attempt = _attempts.GetOrAdd(key, _ => new Attempt());
|
||||
lock (attempt)
|
||||
{
|
||||
if (attempt.Reset <= DateTimeOffset.UtcNow) { attempt.Count = 0; attempt.Reset = DateTimeOffset.UtcNow.AddMinutes(5); }
|
||||
if (++attempt.Count > 8)
|
||||
{
|
||||
ctx.Response.StatusCode = 429;
|
||||
return;
|
||||
}
|
||||
}
|
||||
string[] split = request.Username.Replace('.', ' ').Split(' ', 2, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
|
||||
if (split.Length != 2)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||||
return;
|
||||
}
|
||||
|
||||
Scene? scene = _scenes.Values.FirstOrDefault(s => s.UserAccountService is not null && s.AuthenticationService is not null);
|
||||
if (scene is null)
|
||||
{
|
||||
await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienste nicht verfügbar" });
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
UserAccount? account = scene.UserAccountService.GetUserAccount(UUID.Zero, split[0], split[1]);
|
||||
if (account is null || !account.LoginAllowed)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||||
return;
|
||||
}
|
||||
// Same password transformation as the simulator login service.
|
||||
string hashed = Util.Md5Hash(request.Password);
|
||||
string token = scene.AuthenticationService.Authenticate(account.PrincipalID, hashed, 30);
|
||||
if (string.IsNullOrWhiteSpace(token) || !UUID.TryParse(token, out UUID secureSession) || secureSession == UUID.Zero)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Anmeldung fehlgeschlagen" });
|
||||
return;
|
||||
}
|
||||
try { scene.AuthenticationService.Release(account.PrincipalID, token); }
|
||||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] Token cleanup failed", e); }
|
||||
if (account.UserLevel <= 0)
|
||||
{
|
||||
await SendAsync(ctx.Response, 403, new { error = "Access Denied – Keine Berechtigung." });
|
||||
return;
|
||||
}
|
||||
lock (attempt) attempt.Count = 0;
|
||||
string sid = Token();
|
||||
var session = new Session(account.PrincipalID, account.Name, Token(), DateTimeOffset.UtcNow.AddHours(1));
|
||||
_sessions[sid] = session;
|
||||
bool secure = ctx.Request.IsSecureConnection ||
|
||||
string.Equals(ctx.Request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase);
|
||||
ctx.Response.AppendHeader("Set-Cookie", "ogl_admin=" + sid +
|
||||
"; Path=/; HttpOnly; SameSite=Strict; Max-Age=3600" + (secure ? "; Secure" : ""));
|
||||
await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf, expires = session.Expires });
|
||||
Log.Info("[OS WEBINTERFACE] Administrative session established");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Authentication service error", e);
|
||||
await SendAsync(ctx.Response, 503, new { error = "Authentifizierungsdienst nicht verfügbar" });
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task ServeResourceAsync(HttpListenerResponse response, string resource, string contentType)
|
||||
{
|
||||
using Stream? stream = typeof(AdminHttpServer).Assembly.GetManifestResourceStream(
|
||||
"os_webinterface.www." + resource);
|
||||
if (stream is null) { response.StatusCode = 404; return; }
|
||||
response.ContentType = contentType;
|
||||
response.ContentLength64 = stream.Length;
|
||||
await stream.CopyToAsync(response.OutputStream);
|
||||
}
|
||||
|
||||
private bool ValidateMutation(HttpListenerRequest request, Session session) =>
|
||||
SameOrigin(request) && string.Equals(request.Headers["X-OGL-CSRF"], session.Csrf, StringComparison.Ordinal);
|
||||
|
||||
private async Task DispatchAsync(HttpListenerContext ctx)
|
||||
{
|
||||
try
|
||||
{
|
||||
SecurityHeaders(ctx.Response);
|
||||
HttpListenerRequest request = ctx.Request;
|
||||
string route = request.Url?.AbsolutePath ?? "/";
|
||||
string method = request.HttpMethod;
|
||||
if (method == "GET" && route is "/" or "/index.html")
|
||||
{
|
||||
await ServeResourceAsync(ctx.Response, "index.html", "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/style.css")
|
||||
{
|
||||
await ServeResourceAsync(ctx.Response, "style.css", "text/css; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/app.js")
|
||||
{
|
||||
await ServeResourceAsync(ctx.Response, "app.js", "text/javascript; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/login")
|
||||
{
|
||||
if (!SameOrigin(request)) { await SendAsync(ctx.Response, 403, new { error = "Origin nicht erlaubt" }); return; }
|
||||
await LoginAsync(ctx); return;
|
||||
}
|
||||
if (!route.StartsWith("/api/", StringComparison.Ordinal))
|
||||
{
|
||||
await SendAsync(ctx.Response, 404, new { error = "Nicht gefunden" }); return;
|
||||
}
|
||||
if (!TrySession(request, out Session? session) || session is null)
|
||||
{
|
||||
await SendAsync(ctx.Response, 401, new { error = "Nicht angemeldet" }); return;
|
||||
}
|
||||
if (method != "GET" && !ValidateMutation(request, session))
|
||||
{
|
||||
await SendAsync(ctx.Response, 403, new { error = "CSRF/Origin-Prüfung fehlgeschlagen" }); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/logout")
|
||||
{
|
||||
string? sid = request.Cookies["ogl_admin"]?.Value;
|
||||
if (sid is not null) _sessions.TryRemove(sid, out _);
|
||||
ctx.Response.AppendHeader("Set-Cookie", "ogl_admin=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0");
|
||||
await SendAsync(ctx.Response, 200, new { ok = true }); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/me")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new { name = session.Name, csrf = session.Csrf }); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/overview")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new
|
||||
{
|
||||
started = _started,
|
||||
uptimeSeconds = (long)(DateTimeOffset.UtcNow - _started).TotalSeconds,
|
||||
memoryBytes = Environment.WorkingSet,
|
||||
gcBytes = GC.GetTotalMemory(false),
|
||||
regions = _operations.RegionSummary(),
|
||||
endpoints = _operations.PortSummary(),
|
||||
services = await _operations.ServiceSummaryAsync(_stop.Token)
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/logs")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new { content = _operations.LogTail() }); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/jobs")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, new { jobs = _operations.Jobs() }); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/regions/restart")
|
||||
{
|
||||
var payload = await ReadJsonAsync<RegionRequest>(request);
|
||||
if (payload is null || !_operations.Restart(payload.RegionId))
|
||||
await SendAsync(ctx.Response, 404, new { error = "Region nicht gefunden" });
|
||||
else await SendAsync(ctx.Response, 202, new { message = "Region-Neustart angefordert" });
|
||||
return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/oar/export")
|
||||
{
|
||||
var payload = await ReadJsonAsync<RegionRequest>(request);
|
||||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Region fehlt" }); return; }
|
||||
await SendAsync(ctx.Response, 202, _operations.Export(payload.RegionId)); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/oar/import")
|
||||
{
|
||||
string regionId = request.QueryString["region"] ?? "";
|
||||
if (request.ContentLength64 <= 0 || request.ContentLength64 > AdminOperations.MaxUploadBytes ||
|
||||
request.ContentType != "application/octet-stream")
|
||||
{
|
||||
await SendAsync(ctx.Response, 413, new { error = "Nur OAR-Dateien bis 2 GiB erlaubt" }); return;
|
||||
}
|
||||
var job = await _operations.ImportAsync(regionId, request.InputStream, request.ContentLength64, _stop.Token);
|
||||
await SendAsync(ctx.Response, 202, job); return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/oar/download")
|
||||
{
|
||||
string id = request.QueryString["id"] ?? "";
|
||||
string? file = _operations.ExportFile(id);
|
||||
if (file is null) { await SendAsync(ctx.Response, 404, new { error = "Archiv nicht verfügbar" }); return; }
|
||||
ctx.Response.ContentType = "application/octet-stream";
|
||||
ctx.Response.Headers["Content-Disposition"] = "attachment; filename=\"region-" + id + ".oar\"";
|
||||
using var input = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.Read);
|
||||
ctx.Response.ContentLength64 = input.Length;
|
||||
await input.CopyToAsync(ctx.Response.OutputStream);
|
||||
return;
|
||||
}
|
||||
if (method == "GET" && route == "/api/updates/check")
|
||||
{
|
||||
await SendAsync(ctx.Response, 200, await _operations.CheckGitAsync(_stop.Token)); return;
|
||||
}
|
||||
if (method == "POST" && route == "/api/updates/stage")
|
||||
{
|
||||
var payload = await ReadJsonAsync<UpdateRequest>(request);
|
||||
if (payload is null) { await SendAsync(ctx.Response, 400, new { error = "Commit fehlt" }); return; }
|
||||
await SendAsync(ctx.Response, 200, await _operations.StageUpdateAsync(payload.Sha, _stop.Token)); return;
|
||||
}
|
||||
await SendAsync(ctx.Response, 404, new { error = "Route nicht gefunden" });
|
||||
}
|
||||
catch (AdminOperations.OperationException e)
|
||||
{
|
||||
if (ctx.Response.OutputStream.CanWrite)
|
||||
await SendAsync(ctx.Response, e.Status, new { error = e.Message });
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Request failed", e);
|
||||
try { if (ctx.Response.OutputStream.CanWrite) await SendAsync(ctx.Response, 500, new { error = "Interner Fehler" }); } catch { }
|
||||
}
|
||||
finally { try { ctx.Response.Close(); } catch { } }
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stop.Cancel();
|
||||
try { _listener.Stop(); _listener.Close(); } catch { }
|
||||
_operations.Dispose();
|
||||
_sessions.Clear();
|
||||
_stop.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using log4net;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Region.Framework.Interfaces;
|
||||
using OpenSim.Region.Framework.Scenes;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>Privileged operations, scoped to scenes hosted by this ONE simulator.</summary>
|
||||
internal sealed class AdminOperations : IDisposable
|
||||
{
|
||||
public const long MaxUploadBytes = 2L * 1024 * 1024 * 1024;
|
||||
internal sealed class OperationException(int code, string message) : Exception(message)
|
||||
{
|
||||
public int Status { get; } = code;
|
||||
}
|
||||
private sealed class Job
|
||||
{
|
||||
public string Id = "";
|
||||
public string Region = "";
|
||||
public string Kind = "";
|
||||
public string State = "queued";
|
||||
public string Message = "";
|
||||
public DateTimeOffset Created = DateTimeOffset.UtcNow;
|
||||
public long Bytes;
|
||||
public long Total;
|
||||
public string File = "";
|
||||
}
|
||||
private readonly ConcurrentDictionary<UUID, Scene> _scenes;
|
||||
private readonly ConcurrentDictionary<string, Job> _jobs = new();
|
||||
private readonly ConcurrentDictionary<UUID, string> _busy = new();
|
||||
private readonly string _archiveDir;
|
||||
private readonly string _storage;
|
||||
private readonly int _retention;
|
||||
private readonly List<(string Name, Uri Uri)> _services;
|
||||
private readonly UpdateStager _updateStager;
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(AdminOperations));
|
||||
private static readonly HttpClient GitClient = CreateGitClient();
|
||||
|
||||
public AdminOperations(ConcurrentDictionary<UUID, Scene> scenes, string storage, int retention, List<(string Name, Uri Uri)> services)
|
||||
{
|
||||
_scenes = scenes;
|
||||
_storage = storage;
|
||||
_retention = retention;
|
||||
_services = services;
|
||||
_updateStager = new UpdateStager(storage, retention);
|
||||
_archiveDir = Path.Combine(storage, "archives");
|
||||
Directory.CreateDirectory(_archiveDir);
|
||||
}
|
||||
private static HttpClient CreateGitClient()
|
||||
{
|
||||
var h = new HttpClientHandler { AllowAutoRedirect = false };
|
||||
var client = new HttpClient(h) { Timeout = TimeSpan.FromSeconds(12) };
|
||||
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("OpenGenesisLINK-Admin", "0.1"));
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
return client;
|
||||
}
|
||||
|
||||
private Scene Region(string id)
|
||||
{
|
||||
if (!UUID.TryParse(id, out UUID uid) || !_scenes.TryGetValue(uid, out Scene? s))
|
||||
throw new OperationException(404, "Region nicht gefunden");
|
||||
return s;
|
||||
}
|
||||
private (Scene Scene, IRegionArchiverModule Archiver) GetArchiver(string id)
|
||||
{
|
||||
Scene scene = Region(id);
|
||||
var archive = scene.RequestModuleInterface<IRegionArchiverModule>();
|
||||
if (archive is null) throw new OperationException(503, "OAR-Modul in dieser Region nicht verfügbar");
|
||||
return (scene, archive);
|
||||
}
|
||||
private Job Begin(string id, string kind)
|
||||
{
|
||||
Scene scene = Region(id);
|
||||
string jobId = Guid.NewGuid().ToString("N");
|
||||
var job = new Job { Id = jobId, Region = scene.RegionInfo.RegionName, Kind = kind };
|
||||
if (!_busy.TryAdd(scene.RegionInfo.RegionID, jobId))
|
||||
throw new OperationException(409, "Diese Region führt bereits einen Archivauftrag aus");
|
||||
_jobs[jobId] = job;
|
||||
return job;
|
||||
}
|
||||
private void Complete(UUID regionId, Job job, string? error)
|
||||
{
|
||||
job.Message = error ?? "";
|
||||
job.State = string.IsNullOrWhiteSpace(error) ? "completed" : "failed";
|
||||
_busy.TryRemove(new KeyValuePair<UUID, string>(regionId, job.Id));
|
||||
}
|
||||
|
||||
public object[] RegionSummary()
|
||||
{
|
||||
return _scenes.Values.OrderBy(s => s.RegionInfo.RegionName).Select(s =>
|
||||
{
|
||||
var r = s.RegionInfo;
|
||||
return (object)new
|
||||
{
|
||||
id = r.RegionID.ToString(),
|
||||
name = r.RegionName,
|
||||
location = $"{r.RegionLocX}, {r.RegionLocY}",
|
||||
size = $"{r.RegionSizeX} × {r.RegionSizeY}",
|
||||
udpPort = r.InternalEndPoint?.Port,
|
||||
httpPort = r.HttpPort,
|
||||
serverUri = r.ServerURI,
|
||||
ready = s.Ready,
|
||||
agents = s.GetRootAgentCount(),
|
||||
scriptsEnabled = s.ScriptsEnabled,
|
||||
physicsEnabled = s.PhysicsEnabled
|
||||
};
|
||||
}).ToArray();
|
||||
}
|
||||
|
||||
public object[] PortSummary()
|
||||
{
|
||||
IPEndPoint[] udp;
|
||||
IPEndPoint[] tcp;
|
||||
try
|
||||
{
|
||||
udp = IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();
|
||||
tcp = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
|
||||
}
|
||||
catch { udp = []; tcp = []; }
|
||||
var rows = new List<object>();
|
||||
foreach (Scene s in _scenes.Values.OrderBy(v => v.RegionInfo.RegionName))
|
||||
{
|
||||
var r = s.RegionInfo;
|
||||
int udpPort = r.InternalEndPoint?.Port ?? 0;
|
||||
rows.Add(new
|
||||
{
|
||||
name = r.RegionName, protocol = "UDP", port = udpPort,
|
||||
local = udpPort > 0 && udp.Any(x => x.Port == udpPort),
|
||||
publicStatus = "Nicht extern geprüft – Router/NAT/Firewall unbekannt",
|
||||
hint = "Fritz!Box: UDP-Port an die lokale Simulator-IP weiterleiten"
|
||||
});
|
||||
int httpPort = (int)r.HttpPort;
|
||||
rows.Add(new
|
||||
{
|
||||
name = r.RegionName, protocol = "TCP", port = httpPort,
|
||||
local = httpPort > 0 && tcp.Any(x => x.Port == httpPort),
|
||||
publicStatus = "Nicht extern geprüft – Router/NAT/Firewall unbekannt",
|
||||
hint = "Fritz!Box: TCP-Port beziehungsweise HTTPS-Proxy prüfen"
|
||||
});
|
||||
}
|
||||
return rows.ToArray();
|
||||
}
|
||||
|
||||
public async Task<object[]> ServiceSummaryAsync(CancellationToken stop)
|
||||
{
|
||||
var checks = _services.Select(async item =>
|
||||
{
|
||||
bool reachable = false;
|
||||
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(stop);
|
||||
timeout.CancelAfter(TimeSpan.FromSeconds(2));
|
||||
try
|
||||
{
|
||||
using var client = new TcpClient();
|
||||
await client.ConnectAsync(item.Uri.Host, item.Uri.Port, timeout.Token);
|
||||
reachable = client.Connected;
|
||||
}
|
||||
catch (Exception) { }
|
||||
return (object)new
|
||||
{
|
||||
name = item.Name,
|
||||
host = item.Uri.Host,
|
||||
port = item.Uri.Port,
|
||||
protocol = item.Uri.Scheme.ToUpperInvariant() + "/TCP",
|
||||
reachable,
|
||||
detail = reachable ? "TCP-Verbindung erfolgreich – Dienstfunktion nicht geprüft" :
|
||||
"TCP nicht erreichbar: Dienst, DNS, Routing oder Firewall prüfen"
|
||||
};
|
||||
});
|
||||
return await Task.WhenAll(checks);
|
||||
}
|
||||
|
||||
public bool Restart(string id)
|
||||
{
|
||||
Scene s;
|
||||
try { s = Region(id); }
|
||||
catch (OperationException) { return false; }
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(500);
|
||||
try { s.RestartNow(); }
|
||||
catch (Exception e) { Log.Error("[OS WEBINTERFACE] Region restart failed", e); }
|
||||
});
|
||||
Log.Warn("[OS WEBINTERFACE] Region restart requested: " + s.RegionInfo.RegionName);
|
||||
return true;
|
||||
}
|
||||
|
||||
public string LogTail()
|
||||
{
|
||||
string path = Path.Combine(AppContext.BaseDirectory, "OpenSim.log");
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
string logs = Path.Combine(AppContext.BaseDirectory, "logs");
|
||||
if (Directory.Exists(logs))
|
||||
path = Directory.GetFiles(logs, "*.log")
|
||||
.OrderByDescending(File.GetLastWriteTimeUtc).FirstOrDefault() ?? "";
|
||||
}
|
||||
if (string.IsNullOrEmpty(path) || !File.Exists(path)) return "Keine OpenSim.log gefunden.";
|
||||
try
|
||||
{
|
||||
using var f = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
long size = Math.Min(f.Length, 100 * 1024);
|
||||
f.Seek(-size, SeekOrigin.End);
|
||||
using var reader = new StreamReader(f, Encoding.UTF8, true, 1024);
|
||||
string text = reader.ReadToEnd();
|
||||
return text.Length > 90_000 ? text[^90_000..] : text;
|
||||
}
|
||||
catch (IOException) { return "Logdatei vorübergehend nicht lesbar."; }
|
||||
}
|
||||
|
||||
public object[] Jobs() => _jobs.Values.OrderByDescending(x => x.Created).Take(30)
|
||||
.Select(x => (object)new
|
||||
{
|
||||
id = x.Id, region = x.Region, kind = x.Kind, state = x.State,
|
||||
message = x.Message, created = x.Created, bytes = x.Bytes, total = x.Total,
|
||||
download = x.Kind == "export" && x.State == "completed"
|
||||
}).ToArray();
|
||||
|
||||
public object Export(string regionId)
|
||||
{
|
||||
var (scene, archive) = GetArchiver(regionId);
|
||||
Job job = Begin(regionId, "export");
|
||||
job.File = Path.Combine(_archiveDir, job.Id + ".oar");
|
||||
EventManager.OarFileSaved? complete = null;
|
||||
complete = (requestId, message) =>
|
||||
{
|
||||
if (requestId != Guid.ParseExact(job.Id, "N")) return;
|
||||
scene.EventManager.OnOarFileSaved -= complete;
|
||||
if (string.IsNullOrWhiteSpace(message) && !File.Exists(job.File))
|
||||
message = "OAR-Datei wurde nicht erstellt";
|
||||
Complete(scene.RegionInfo.RegionID, job, message);
|
||||
if (job.State == "completed") job.Bytes = new FileInfo(job.File).Length;
|
||||
};
|
||||
scene.EventManager.OnOarFileSaved += complete;
|
||||
try
|
||||
{
|
||||
job.State = "saving";
|
||||
archive.ArchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary<string, object>());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
scene.EventManager.OnOarFileSaved -= complete;
|
||||
Complete(scene.RegionInfo.RegionID, job, e.Message);
|
||||
}
|
||||
return new { id = job.Id, state = job.State };
|
||||
}
|
||||
|
||||
public async Task<object> ImportAsync(string regionId, Stream source, long contentLength, CancellationToken stop)
|
||||
{
|
||||
var (scene, archive) = GetArchiver(regionId);
|
||||
Job job = Begin(regionId, "import");
|
||||
job.File = Path.Combine(_archiveDir, job.Id + ".upload");
|
||||
job.Total = contentLength;
|
||||
try
|
||||
{
|
||||
job.State = "uploading";
|
||||
using (var dst = new FileStream(job.File, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 * 1024, true))
|
||||
{
|
||||
byte[] buffer = new byte[64 * 1024];
|
||||
int read;
|
||||
while ((read = await source.ReadAsync(buffer, stop)) != 0)
|
||||
{
|
||||
job.Bytes += read;
|
||||
if (job.Bytes > contentLength || job.Bytes > MaxUploadBytes)
|
||||
throw new OperationException(413, "OAR Upload zu groß");
|
||||
await dst.WriteAsync(buffer.AsMemory(0, read), stop);
|
||||
}
|
||||
}
|
||||
if (job.Bytes != contentLength)
|
||||
throw new OperationException(400, "Unvollständiger OAR-Upload");
|
||||
|
||||
EventManager.OarFileLoaded? complete = null;
|
||||
complete = (requestId, loadedScenes, message) =>
|
||||
{
|
||||
if (requestId != Guid.ParseExact(job.Id, "N")) return;
|
||||
scene.EventManager.OnOarFileLoaded -= complete;
|
||||
Complete(scene.RegionInfo.RegionID, job, message);
|
||||
try { File.Delete(job.File); } catch { }
|
||||
};
|
||||
scene.EventManager.OnOarFileLoaded += complete;
|
||||
try
|
||||
{
|
||||
job.State = "importing";
|
||||
archive.DearchiveRegion(job.File, Guid.ParseExact(job.Id, "N"), new Dictionary<string, object>());
|
||||
}
|
||||
catch
|
||||
{
|
||||
scene.EventManager.OnOarFileLoaded -= complete;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Complete(scene.RegionInfo.RegionID, job, e.Message);
|
||||
try { File.Delete(job.File); } catch { }
|
||||
if (e is OperationException) throw;
|
||||
throw new OperationException(500, "OAR-Import fehlgeschlagen: " + e.Message);
|
||||
}
|
||||
Log.Warn("[OS WEBINTERFACE] OAR import initiated for " + scene.RegionInfo.RegionName);
|
||||
return new { id = job.Id, state = job.State };
|
||||
}
|
||||
|
||||
public string? ExportFile(string id)
|
||||
{
|
||||
if (!Guid.TryParseExact(id, "N", out _) ||
|
||||
!_jobs.TryGetValue(id, out Job? j) ||
|
||||
j.Kind != "export" || j.State != "completed")
|
||||
return null;
|
||||
string expected = Path.Combine(_archiveDir, id + ".oar");
|
||||
return j.File == expected && File.Exists(expected) ? expected : null;
|
||||
}
|
||||
|
||||
public async Task<object> CheckGitAsync(CancellationToken stop)
|
||||
{
|
||||
const string endpoint = "https://api.github.com/repos/opengenesislink/opengenesislinkserver/commits?sha=main&per_page=12";
|
||||
string? local = null;
|
||||
try { local = await GitShaAsync(stop); } catch { }
|
||||
try
|
||||
{
|
||||
using var response = await GitClient.GetAsync(endpoint, stop);
|
||||
response.EnsureSuccessStatusCode();
|
||||
using var document = JsonDocument.Parse(await response.Content.ReadAsStringAsync(stop));
|
||||
var entries = document.RootElement.EnumerateArray().Select(c => new
|
||||
{
|
||||
sha = c.GetProperty("sha").GetString(),
|
||||
title = (c.GetProperty("commit").GetProperty("message").GetString() ?? "").Split('\n')[0],
|
||||
date = c.GetProperty("commit").GetProperty("committer").GetProperty("date").GetString()
|
||||
}).ToArray();
|
||||
string? remote = entries.FirstOrDefault()?.sha;
|
||||
int? newCommitCount = null;
|
||||
if (local is not null && remote is not null && local != remote &&
|
||||
local.Length == 40 && local.All(Uri.IsHexDigit))
|
||||
{
|
||||
try
|
||||
{
|
||||
string compare = "https://api.github.com/repos/opengenesislink/opengenesislinkserver/compare/" +
|
||||
local + "..." + remote;
|
||||
using var compared = await GitClient.GetAsync(compare, stop);
|
||||
if (compared.IsSuccessStatusCode)
|
||||
{
|
||||
using var detail = JsonDocument.Parse(await compared.Content.ReadAsStringAsync(stop));
|
||||
newCommitCount = detail.RootElement.GetProperty("total_commits").GetInt32();
|
||||
entries = detail.RootElement.GetProperty("commits").EnumerateArray().Select(c => new
|
||||
{
|
||||
sha = c.GetProperty("sha").GetString(),
|
||||
title = (c.GetProperty("commit").GetProperty("message").GetString() ?? "").Split('\n')[0],
|
||||
date = c.GetProperty("commit").GetProperty("committer").GetProperty("date").GetString()
|
||||
}).ToArray();
|
||||
}
|
||||
}
|
||||
catch (Exception e) { Log.Warn("[OS WEBINTERFACE] GitHub compare unavailable", e); }
|
||||
}
|
||||
return new
|
||||
{
|
||||
local, remote, upToDate = local is not null && local == remote,
|
||||
newCommitCount, commits = entries,
|
||||
note = newCommitCount > entries.Length
|
||||
? "Es gibt weitere neue Commits; GitHub liefert in dieser Abfrage nur eine Teilmenge."
|
||||
: "Git-Commits sind Quellcode-Stände, keine geprüften Binär-Releases. Ein Update muss gebaut und vor Aktivierung getestet werden."
|
||||
};
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return new { local, error = "GitHub nicht erreichbar: " + e.GetType().Name };
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<string?> GitShaAsync(CancellationToken stop)
|
||||
{
|
||||
string? root = Directory.GetParent(AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar))?.FullName;
|
||||
if (root is null || !Directory.Exists(Path.Combine(root, ".git"))) return null;
|
||||
var start = new ProcessStartInfo("git")
|
||||
{
|
||||
WorkingDirectory = root, RedirectStandardOutput = true,
|
||||
RedirectStandardError = true, UseShellExecute = false
|
||||
};
|
||||
start.ArgumentList.Add("rev-parse");
|
||||
start.ArgumentList.Add("HEAD");
|
||||
using Process? p = Process.Start(start);
|
||||
if (p is null) return null;
|
||||
string output = (await p.StandardOutput.ReadToEndAsync(stop)).Trim();
|
||||
await p.WaitForExitAsync(stop);
|
||||
return p.ExitCode == 0 && output.Length == 40 ? output : null;
|
||||
}
|
||||
|
||||
public Task<object> StageUpdateAsync(string sha, CancellationToken stop) => _updateStager.StageAsync(sha, stop);
|
||||
|
||||
public void Dispose() { }
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Collections.Concurrent;
|
||||
using log4net;
|
||||
using Mono.Addins;
|
||||
using Nini.Config;
|
||||
using System.Collections.Generic;
|
||||
using OpenMetaverse;
|
||||
using OpenSim.Region.Framework.Interfaces;
|
||||
using OpenSim.Region.Framework.Scenes;
|
||||
|
||||
[assembly: Addin("OSWebInterface", Namespace = "OpenGenesisLINK", Version = "0.1.0")]
|
||||
[assembly: AddinDependency("::OpenSim.Region.Framework", OpenSim.VersionInfo.VersionNumber)]
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in, loopback-only simulator administration. The DLL is independent of OpenSim.dll.
|
||||
/// A separate TLS reverse proxy is REQUIRED before using it from another host.
|
||||
/// </summary>
|
||||
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OSWebInterface")]
|
||||
public sealed class OSWebInterfaceModule : ISharedRegionModule
|
||||
{
|
||||
private static readonly ILog Log = LogManager.GetLogger(typeof(OSWebInterfaceModule));
|
||||
private readonly ConcurrentDictionary<UUID, Scene> _scenes = new();
|
||||
private AdminHttpServer? _server;
|
||||
private bool _enabled;
|
||||
private int _port;
|
||||
private string _storage = "";
|
||||
|
||||
public string Name => "OSWebInterface";
|
||||
public Type? ReplaceableInterface => null;
|
||||
|
||||
public void Initialise(IConfigSource source)
|
||||
{
|
||||
IConfig? c = source?.Configs["OSWebInterface"];
|
||||
_enabled = c?.GetBoolean("Enabled", false) ?? false;
|
||||
if (!_enabled) return;
|
||||
_port = c?.GetInt("Port", 9847) ?? 9847;
|
||||
int retention = Math.Clamp(c?.GetInt("BackupRetention", 5) ?? 5, 1, 20);
|
||||
string folder = c?.GetString("DataDirectory", "os-webinterface-data") ?? "os-webinterface-data";
|
||||
if (_port < 1025 || _port > 65535 || Path.IsPathRooted(folder) ||
|
||||
folder.Contains("..", StringComparison.Ordinal) ||
|
||||
folder.Contains(':', StringComparison.Ordinal))
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Unsafe port or DataDirectory; module disabled.");
|
||||
_enabled = false;
|
||||
return;
|
||||
}
|
||||
_storage = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, folder));
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(_storage);
|
||||
var services = new List<(string Name, Uri Uri)>();
|
||||
foreach (var item in new (string Section, string Option)[]
|
||||
{
|
||||
("AssetService", "AssetServerURI"),
|
||||
("InventoryService", "InventoryServerURI"),
|
||||
("GridService", "GridServerURI"),
|
||||
("UserAccountService", "UserAccountServerURI"),
|
||||
("AuthenticationService", "AuthenticationServerURI"),
|
||||
("PresenceService", "PresenceServerURI"),
|
||||
("FriendsService", "FriendsServerURI"),
|
||||
("Hypergrid", "GatekeeperURI")
|
||||
})
|
||||
{
|
||||
string configured = source?.Configs[item.Section]?.GetString(item.Option, "") ?? "";
|
||||
if (Uri.TryCreate(configured, UriKind.Absolute, out Uri? endpoint) &&
|
||||
(endpoint.Scheme == Uri.UriSchemeHttp || endpoint.Scheme == Uri.UriSchemeHttps))
|
||||
services.Add((item.Section, endpoint));
|
||||
}
|
||||
_server = new AdminHttpServer(_scenes, _storage, _port, retention, services);
|
||||
_server.Start();
|
||||
Log.Info($"[OS WEBINTERFACE] Enabled on http://127.0.0.1:{_port}/ (loopback only). Configure an HTTPS reverse proxy for remote access.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Log.Error("[OS WEBINTERFACE] Failed to start; admin web disabled", e);
|
||||
_server?.Dispose();
|
||||
_server = null;
|
||||
_enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRegion(Scene scene)
|
||||
{
|
||||
if (_enabled) _scenes[scene.RegionInfo.RegionID] = scene;
|
||||
}
|
||||
|
||||
public void PostInitialise() { }
|
||||
|
||||
public void RegionLoaded(Scene scene) { }
|
||||
|
||||
public void RemoveRegion(Scene scene)
|
||||
{
|
||||
_scenes.TryRemove(scene.RegionInfo.RegionID, out _);
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
_enabled = false;
|
||||
_server?.Dispose();
|
||||
_server = null;
|
||||
_scenes.Clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.IO.Compression;
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
/// <summary>
|
||||
/// Safe download-only update stage: verifies advertised SHA, saves the GitHub
|
||||
/// source snapshot, and backs up configuration BEFORE any future installation.
|
||||
/// Does not execute downloaded source or replace running simulator assemblies.
|
||||
/// </summary>
|
||||
internal sealed class UpdateStager
|
||||
{
|
||||
private static readonly HttpClient GitHub = CreateClient();
|
||||
private readonly string _data;
|
||||
private readonly int _retention;
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
public const long MaxSnapshot = 256L * 1024 * 1024;
|
||||
|
||||
private static HttpClient CreateClient()
|
||||
{
|
||||
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false })
|
||||
{
|
||||
Timeout = TimeSpan.FromMinutes(5)
|
||||
};
|
||||
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("OpenGenesisLINK-UpdateStage", "0.1"));
|
||||
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json"));
|
||||
return client;
|
||||
}
|
||||
public UpdateStager(string data, int retention)
|
||||
{
|
||||
_data = data;
|
||||
_retention = retention;
|
||||
}
|
||||
|
||||
private static void PrivateDirectory(string dir)
|
||||
{
|
||||
Directory.CreateDirectory(dir);
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(dir, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
|
||||
}
|
||||
private static void PrivateFile(string file)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows())
|
||||
File.SetUnixFileMode(file, UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
private static bool Sha(string sha) =>
|
||||
sha.Length == 40 && sha.All(Uri.IsHexDigit);
|
||||
|
||||
private static async Task<HttpResponseMessage> RequestSnapshot(string sha, CancellationToken stop)
|
||||
{
|
||||
var first = await GitHub.GetAsync(
|
||||
"https://api.github.com/repos/opengenesislink/opengenesislinkserver/tarball/" + sha,
|
||||
HttpCompletionOption.ResponseHeadersRead, stop);
|
||||
if (first.StatusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Redirect or
|
||||
HttpStatusCode.RedirectMethod or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect)
|
||||
{
|
||||
Uri? target = first.Headers.Location;
|
||||
first.Dispose();
|
||||
if (target is null || target.Scheme != Uri.UriSchemeHttps ||
|
||||
!string.Equals(target.Host, "codeload.github.com", StringComparison.OrdinalIgnoreCase) ||
|
||||
!target.AbsolutePath.StartsWith("/opengenesislink/opengenesislinkserver/", StringComparison.Ordinal))
|
||||
throw new IOException("GitHub-Snapshot verweist auf eine unerwartete Adresse.");
|
||||
return await GitHub.GetAsync(target, HttpCompletionOption.ResponseHeadersRead, stop);
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
public async Task<object> StageAsync(string sha, CancellationToken stop)
|
||||
{
|
||||
if (!Sha(sha)) throw new AdminOperations.OperationException(400, "Ungültiger Commit SHA");
|
||||
if (OperatingSystem.IsWindows()) throw new AdminOperations.OperationException(501, "Windows-Update-Backup benötigt zuerst geprüfte NTFS-ACL-Berechtigungen; Update-Staging deaktiviert.");
|
||||
if (!_lock.Wait(0)) throw new AdminOperations.OperationException(409, "Ein Update-Download läuft bereits");
|
||||
try
|
||||
{
|
||||
using var latestResponse = await GitHub.GetAsync(
|
||||
"https://api.github.com/repos/opengenesislink/opengenesislinkserver/commits/main", stop);
|
||||
latestResponse.EnsureSuccessStatusCode();
|
||||
using var latestDocument = JsonDocument.Parse(await latestResponse.Content.ReadAsStringAsync(stop));
|
||||
string latest = latestDocument.RootElement.GetProperty("sha").GetString() ?? "";
|
||||
if (!string.Equals(latest, sha, StringComparison.OrdinalIgnoreCase))
|
||||
throw new AdminOperations.OperationException(409, "Commit ist nicht mehr die aktuelle main-Version. Bitte neu prüfen.");
|
||||
|
||||
string stage = Path.Combine(_data, "updates");
|
||||
string backups = Path.Combine(_data, "configuration-backups");
|
||||
PrivateDirectory(stage);
|
||||
PrivateDirectory(backups);
|
||||
string filename = Path.Combine(stage, sha.ToLowerInvariant() + ".tar.gz");
|
||||
if (File.Exists(filename))
|
||||
return new { state = "staged", sha, path = "updates/" + Path.GetFileName(filename), note = "Quellcode bereits heruntergeladen. Keine Binärdateien verändert." };
|
||||
|
||||
string tmp = filename + ".partial";
|
||||
try
|
||||
{
|
||||
using var response = await RequestSnapshot(sha, stop);
|
||||
response.EnsureSuccessStatusCode();
|
||||
if (response.Content.Headers.ContentLength > MaxSnapshot)
|
||||
throw new IOException("Quellcode-Snapshot überschreitet das Downloadlimit.");
|
||||
await using (var input = await response.Content.ReadAsStreamAsync(stop))
|
||||
await using (var output = new FileStream(tmp, FileMode.CreateNew, FileAccess.Write,
|
||||
FileShare.None, 128 * 1024, true))
|
||||
{
|
||||
byte[] buffer = new byte[128 * 1024];
|
||||
long copied = 0;
|
||||
int count;
|
||||
while ((count = await input.ReadAsync(buffer, stop)) > 0)
|
||||
{
|
||||
copied += count;
|
||||
if (copied > MaxSnapshot) throw new IOException("Quellcode-Snapshot zu groß");
|
||||
await output.WriteAsync(buffer.AsMemory(0, count), stop);
|
||||
}
|
||||
}
|
||||
PrivateFile(tmp);
|
||||
// Config and secret backup is local only, restricted to the service account.
|
||||
string stamp = DateTimeOffset.UtcNow.ToString("yyyyMMddTHHmmssfffZ");
|
||||
string backup = Path.Combine(backups, stamp + "-" + sha[..12] + ".zip");
|
||||
BackupConfigs(backup);
|
||||
File.Move(tmp, filename);
|
||||
PrivateFile(filename);
|
||||
Prune(backups);
|
||||
return new
|
||||
{
|
||||
state = "staged", sha, path = "updates/" + Path.GetFileName(filename),
|
||||
backup = "configuration-backups/" + Path.GetFileName(backup),
|
||||
note = "Quellcode heruntergeladen und Konfiguration gesichert. Noch KEIN Build, KEINE Installation und KEIN Neustart erfolgt."
|
||||
};
|
||||
}
|
||||
finally { try { if (File.Exists(tmp)) File.Delete(tmp); } catch { } }
|
||||
}
|
||||
catch (AdminOperations.OperationException) { throw; }
|
||||
catch (Exception e) { throw new AdminOperations.OperationException(502, "Update konnte nicht vorbereitet werden: " + e.Message); }
|
||||
finally { _lock.Release(); }
|
||||
}
|
||||
|
||||
private static void BackupConfigs(string backup)
|
||||
{
|
||||
string root = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar);
|
||||
// Never allow a backup root provided by the browser.
|
||||
string[] direct = ["OpenSim.ini", "OpenSimDefaults.ini", "nexverse.local.env"];
|
||||
string[] dirs = ["Regions", "config-include"];
|
||||
using var zip = new ZipArchive(File.Open(backup, FileMode.CreateNew), ZipArchiveMode.Create);
|
||||
PrivateFile(backup);
|
||||
foreach (string f in direct)
|
||||
{
|
||||
string path = Path.Combine(root, f);
|
||||
if (File.Exists(path) && (File.GetAttributes(path) & FileAttributes.ReparsePoint) == 0)
|
||||
zip.CreateEntryFromFile(path, f, CompressionLevel.Optimal);
|
||||
}
|
||||
foreach (string d in dirs)
|
||||
{
|
||||
string folder = Path.Combine(root, d);
|
||||
if (!Directory.Exists(folder)) continue;
|
||||
foreach (string f in Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
if ((File.GetAttributes(f) & FileAttributes.ReparsePoint) != 0) continue;
|
||||
string relative = Path.GetRelativePath(root, f);
|
||||
if (relative.EndsWith(".ini", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".pem", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".env", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".p12", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".pfx", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".key", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".crt", StringComparison.OrdinalIgnoreCase) ||
|
||||
relative.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
|
||||
zip.CreateEntryFromFile(f, relative.Replace('\\', '/'), CompressionLevel.Optimal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void Prune(string backupDir)
|
||||
{
|
||||
foreach (string old in Directory.EnumerateFiles(backupDir, "*.zip")
|
||||
.OrderByDescending(File.GetCreationTimeUtc).Skip(_retention))
|
||||
{
|
||||
if (Path.GetFileName(old).Length > 30)
|
||||
File.Delete(old);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<AssemblyName>os_webinterface</AssemblyName>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../OpenSim/Framework/OpenSim.Framework.csproj" />
|
||||
<ProjectReference Include="../../OpenSim/Region/Framework/OpenSim.Region.Framework.csproj" />
|
||||
<ProjectReference Include="../../OpenSim/Services/Interfaces/OpenSim.Services.Interfaces.csproj" />
|
||||
<Reference Include="Mono.Addins"><HintPath>../../bin/Mono.Addins.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="Nini"><HintPath>../../bin/Nini.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="OpenMetaverse"><HintPath>../../bin/OpenMetaverse.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="OpenMetaverseTypes"><HintPath>../../bin/OpenMetaverseTypes.dll</HintPath><Private>false</Private></Reference>
|
||||
<Reference Include="log4net"><HintPath>../../bin/log4net.dll</HintPath><Private>false</Private></Reference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="www/index.html" />
|
||||
<EmbeddedResource Include="www/app.js" />
|
||||
<EmbeddedResource Include="www/style.css" />
|
||||
</ItemGroup>
|
||||
<Target Name="CopyAddonToSimulatorBin" AfterTargets="Build" Condition="'$(DesignTimeBuild)' != 'true'">
|
||||
<Copy SourceFiles="$(TargetPath)" DestinationFiles="$(MSBuildThisFileDirectory)../../bin/$(TargetFileName)" SkipUnchangedFiles="true" />
|
||||
</Target>
|
||||
</Project>
|
||||
@@ -0,0 +1,62 @@
|
||||
"use strict";
|
||||
const $ = id => document.getElementById(id);
|
||||
let csrf="",overview=null,jobsTimer=null,modalAction=null,latestSha=null;
|
||||
const money = size => (size/(1024**2)).toFixed(1)+" MiB";
|
||||
const sleepTime = s => {const h=Math.floor(s/3600),m=Math.floor((s%3600)/60);return h+"h "+m+"m"};
|
||||
function notice(message, title="Hinweis", action=null) { $("modal-title").textContent=title; $("modal-message").textContent=message; $("modal").hidden=false; modalAction=action; $("modal-cancel").hidden=!action; }
|
||||
$("modal-ok").onclick=()=>{ $("modal").hidden=true; if(modalAction){const a=modalAction;modalAction=null;a();} };
|
||||
$("modal-cancel").onclick=()=>{$("modal").hidden=true;modalAction=null};
|
||||
async function api(path, options={}) {
|
||||
const headers = {...options.headers};
|
||||
if(options.method&&options.method!=="GET") headers["X-OGL-CSRF"]=csrf;
|
||||
const response=await fetch(path,{...options,headers,credentials:"same-origin",cache:"no-store"});
|
||||
const data=await response.json().catch(()=>({error:"Ungültige Serverantwort"}));
|
||||
if(!response.ok) throw new Error(data.error||"Serverfehler "+response.status);
|
||||
return data;
|
||||
}
|
||||
function jsonPost(path,obj){return api(path,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(obj)})}
|
||||
function row(...entries){const tr=document.createElement("tr");entries.forEach(e=>{const td=document.createElement("td");td.textContent=String(e??"–");tr.append(td)});return tr}
|
||||
function table(target,head,rows){const t=document.createElement("table"),thead=document.createElement("thead"),tbody=document.createElement("tbody");const th=document.createElement("tr");head.forEach(h=>{let x=document.createElement("th");x.textContent=h;th.append(x)});thead.append(th);rows.forEach(r=>tbody.append(r));t.append(thead,tbody);$(target).replaceChildren(t)}
|
||||
function statusCell(tr,status) {const td=tr.lastElementChild;td.replaceChildren();const span=document.createElement("span");span.className="status"+(status==="OK"?"":" bad");span.textContent=status;td.append(span)}
|
||||
function renderOverview(d) {
|
||||
overview=d; const regs=d.regions||[];
|
||||
$("num-regions").textContent=regs.length;
|
||||
$("num-avatars").textContent=regs.reduce((n,r)=>n+r.agents,0);
|
||||
$("num-memory").textContent=money(d.memoryBytes);
|
||||
$("num-uptime").textContent=sleepTime(d.uptimeSeconds);
|
||||
table("overview-regions",["Region","Koordinaten","Größe","Avatare","Status"],regs.map(r=>{const x=row(r.name,r.location,r.size,r.agents,r.ready?"OK":"Nicht bereit");statusCell(x,r.ready?"OK":"Fehler");return x}));
|
||||
table("services-table",["Dienst","Host","Port","Protokoll","Status"],(d.services||[]).map(v=>row(v.name,v.host,v.port,v.protocol,v.reachable?"Erreichbar":"Nicht erreichbar")));
|
||||
const wrapper=$("region-actions");wrapper.replaceChildren();
|
||||
regs.forEach(r=>{
|
||||
const c=document.createElement("article");c.className="region-card";
|
||||
const title=document.createElement("h3");title.textContent=r.name;
|
||||
const subtitle=document.createElement("p");subtitle.textContent="Region "+r.id;
|
||||
const inf=document.createElement("p");inf.textContent=r.location+" · "+r.size+" · "+r.agents+" Avatare · UDP "+r.udpPort+" · TCP "+r.httpPort;
|
||||
const btn=document.createElement("button");btn.className="danger";btn.textContent="Region neu starten";
|
||||
btn.onclick=()=>notice("Soll die Region „"+r.name+"“ tatsächlich neu gestartet werden? Aktive Bewohner werden unterbrochen.","Neustart bestätigen",async()=>{try{await jsonPost("/api/regions/restart",{regionId:r.id});notice("Regionsneustart wurde angefordert.");}catch(e){notice(e.message,"Fehler")}});
|
||||
c.append(title,subtitle,inf,btn);wrapper.append(c);
|
||||
});
|
||||
const sel=$("archive-region"),v=sel.value;sel.replaceChildren();
|
||||
regs.forEach(r=>{const o=document.createElement("option");o.value=r.id;o.textContent=r.name;sel.append(o)});if(regs.some(r=>r.id===v))sel.value=v;
|
||||
table("ports-table",["Region","Protokoll","Port","Lokaler Listener","Öffentlicher Zugang"],(d.endpoints||[]).map(p=>{const x=row(p.name,p.protocol,p.port,p.local?"OK":"Nicht aktiv",p.publicStatus);return x}));
|
||||
}
|
||||
async function refresh(){try{renderOverview(await api("/api/overview"));}catch(e){notice(e.message,"Verbindung fehlgeschlagen")}}
|
||||
async function loadJobs(){try{const data=await api("/api/jobs");const rows=(data.jobs||[]).map(j=>{const x=row(j.region,j.kind,j.state,j.total?(100*j.bytes/j.total).toFixed(0)+"%":"–",j.message||"–","");
|
||||
if(j.download){const a=document.createElement("a");a.href="/api/oar/download?id="+encodeURIComponent(j.id);a.textContent="OAR herunterladen";a.style.color="#69c7fb";x.lastElementChild.replaceChildren(a)}return x});
|
||||
table("job-table",["Region","Art","Status","Upload","Meldung","Download"],rows)}catch(e){notice(e.message,"Aufträge")}}
|
||||
async function loadLogs(){try{$("log-text").textContent=(await api("/api/logs")).content;}catch(e){$("log-text").textContent=e.message}}
|
||||
async function loadUpdates(){try{const d=await api("/api/updates/check");latestSha=d.remote||null;$("local-sha").textContent=d.local||"Kein lokaler Git-Checkout erkannt";$("remote-sha").textContent=d.remote||"–";$("version-note").textContent=(d.newCommitCount!=null?d.newCommitCount+" Commits seit deinem Stand. ":"")+(d.error||d.note||"");const box=$("commits");box.replaceChildren();(d.commits||[]).forEach(c=>{const x=document.createElement("article");x.className="commit";const b=document.createElement("b");b.textContent=c.title;const sm=document.createElement("small");sm.textContent=c.sha.slice(0,12)+" · "+new Date(c.date).toLocaleString("de-DE");x.append(b,sm);box.append(x)})}catch(e){notice(e.message,"GitHub")}}
|
||||
function showView(name){document.querySelectorAll(".view").forEach(v=>v.hidden=v.id!==name);document.querySelectorAll("nav a").forEach(v=>v.classList.toggle("active",v.dataset.view===name));const titles={overview:"Übersicht",regions:"Regionen & Aktionen",archives:"OAR-Archive",network:"Netzwerk & Ports",logs:"Simulator-Logs",updates:"Updates & GitHub"};$("page-title").textContent=titles[name]||"Übersicht";if(name==="logs")loadLogs();if(name==="archives")loadJobs();if(name==="updates")loadUpdates();}
|
||||
document.querySelectorAll("nav a").forEach(a=>a.onclick=e=>{e.preventDefault();showView(a.dataset.view)});
|
||||
$("login-form").onsubmit=async e=>{e.preventDefault();try{const d=await api("/api/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({username:$("username").value,password:$("password").value})});csrf=d.csrf;$("identity").textContent=d.name;$("login-view").hidden=true;$("dashboard").hidden=false;$("password").value="";await refresh();}catch(err){notice(err.message,err.message.includes("Access Denied")?"Access Denied":"Anmeldung fehlgeschlagen")}};
|
||||
$("refresh").onclick=refresh;
|
||||
$("logout").onclick=async()=>{try{await api("/api/logout",{method:"POST"})}finally{csrf="";$("dashboard").hidden=true;$("login-view").hidden=false}};
|
||||
$("oar-file").onchange=()=>{$("selected-file").textContent=$("oar-file").files[0]?.name||""};
|
||||
$("oar-export").onclick=async()=>{try{const d=await jsonPost("/api/oar/export",{regionId:$("archive-region").value});notice("OAR-Sicherung gestartet: "+d.id);await loadJobs()}catch(e){notice(e.message,"OAR Export")}};
|
||||
$("oar-import").onclick=()=>{const f=$("oar-file").files[0];if(!f){notice("Bitte zuerst eine .oar-Datei auswählen.");return;}if(f.size>2*1024**3){notice("Die Datei überschreitet 2 GiB.");return;}notice("ACHTUNG: OAR-Import kann alle Objekte und Gelände der gewählten Region überschreiben. Jetzt „"+f.name+"“ importieren?","OAR-Import bestätigen",async()=>{try{const d=await new Promise((resolve,reject)=>{const xhr=new XMLHttpRequest();xhr.open("POST","/api/oar/import?region="+encodeURIComponent($("archive-region").value));xhr.withCredentials=true;xhr.setRequestHeader("Content-Type","application/octet-stream");xhr.setRequestHeader("X-OGL-CSRF",csrf);xhr.upload.onprogress=e=>{if(e.lengthComputable)$("selected-file").textContent="Upload: "+Math.round(e.loaded*100/e.total)+"% ("+f.name+")";};xhr.onerror=()=>reject(new Error("Netzwerkfehler beim OAR Upload"));xhr.onload=()=>{let v;try{v=JSON.parse(xhr.responseText||"{}")}catch{v={error:"Ungültige Serverantwort"}}xhr.status>=200&&xhr.status<300?resolve(v):reject(new Error(v.error||"Upload fehlgeschlagen"))};xhr.send(f)});notice("Import angenommen: "+d.id+". Status im Auftragsbereich sichtbar.");await loadJobs()}catch(e){notice(e.message,"OAR Import")}})};
|
||||
$("update-stage").onclick=()=>{if(!latestSha){notice("Bitte zuerst GitHub prüfen.");return}notice("Commit "+latestSha.slice(0,12)+" herunterladen und vertrauliche Konfiguration lokal sichern? Es werden keine laufenden Programmdateien verändert.","Update vorbereiten",async()=>{try{const d=await jsonPost("/api/updates/stage",{sha:latestSha});notice(d.note+" Sicherung: "+d.backup,"Download abgeschlossen")}catch(e){notice(e.message,"Update fehlgeschlagen")}})};
|
||||
$("logs-refresh").onclick=loadLogs;$("updates-refresh").onclick=loadUpdates;$("jobs-refresh").onclick=loadJobs;
|
||||
async function bootstrap(){try{const d=await api("/api/me");csrf=d.csrf;$("identity").textContent=d.name;$("dashboard").hidden=false;$("login-view").hidden=true;await refresh()}catch{}}bootstrap();
|
||||
setInterval(()=>{if(!$("dashboard").hidden){refresh();if(!$("archives").hidden)loadJobs()}},30000);
|
||||
|
||||
setInterval(()=>{if(!$("dashboard").hidden&&!$("archives").hidden)loadJobs()},4000);
|
||||
@@ -0,0 +1,52 @@
|
||||
<!doctype html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark">
|
||||
<title>OpenGenesisLINK | Simulator Control</title>
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
<script src="/app.js" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="login-view" class="login-screen">
|
||||
<div class="login-panel">
|
||||
<div class="brand-mark">O<span>G</span>L</div>
|
||||
<p class="eyebrow">OPENGENESISLINK GENERATION 1</p>
|
||||
<h1>Simulator Control</h1>
|
||||
<p class="muted">Melde dich mit deinem Avatar-Konto an. Zugelassen sind Konten mit UserLevel größer als 0.</p>
|
||||
<form id="login-form">
|
||||
<label>Avatar-Name<input id="username" autocomplete="username" required placeholder="Vorname Nachname"></label>
|
||||
<label>Passwort<input id="password" type="password" autocomplete="current-password" required></label>
|
||||
<button type="submit" class="primary">Sicher anmelden</button>
|
||||
</form>
|
||||
<small class="muted">Zugang über den lokalen Simulator. Für externe Nutzung ist ein HTTPS-Reverse-Proxy erforderlich.</small>
|
||||
</div>
|
||||
</div>
|
||||
<div id="dashboard" hidden>
|
||||
<aside>
|
||||
<div class="side-brand"><div class="brand-mark small">O<span>G</span>L</div><div><strong>OpenGenesisLINK</strong><small>SIMULATOR CONTROL</small></div></div>
|
||||
<div class="side-label">INSTANZ</div>
|
||||
<nav><a href="#overview" data-view="overview" class="active">Übersicht</a><a href="#regions" data-view="regions">Regionen & Aktionen</a><a href="#archives" data-view="archives">OAR Sicherungen</a><a href="#network" data-view="network">Netzwerk & Ports</a><a href="#logs" data-view="logs">Live-Protokoll</a><a href="#updates" data-view="updates">Updates & GitHub</a></nav>
|
||||
<div class="side-footer"><span class="live-dot"></span> Simulator-Verwaltung lokal <p>Verbindung zu einem laufenden Simulatorprozess</p></div>
|
||||
</aside>
|
||||
<main>
|
||||
<header class="topbar"><div><span class="eyebrow">ADMINISTRATIONSZENTRALE</span><h2 id="page-title">Übersicht</h2></div><div class="top-right"><span id="identity" class="pill">Administrator</span><button id="refresh" class="ghost">Aktualisieren</button><button id="logout" class="ghost">Abmelden</button></div></header>
|
||||
<section id="overview" class="view">
|
||||
<div class="hero"><div><span class="eyebrow">SYSTEM CONTROL</span><h2>Deine virtuelle Infrastruktur.<br><em>Alles im Blick.</em></h2><p>Status, Regionen, Speicher und Dienste deiner Simulatorinstanz – zentral verwaltet.</p></div><div class="hero-ring"><span>OGL</span><small>GEN 1</small></div></div>
|
||||
<div class="stats">
|
||||
<article class="stat"><p>Geladene Regionen</p><strong id="num-regions">–</strong><small>in dieser Instanz</small></article>
|
||||
<article class="stat"><p>Avatare online</p><strong id="num-avatars">–</strong><small>Root-Avatare</small></article>
|
||||
<article class="stat"><p>Arbeitsspeicher</p><strong id="num-memory">–</strong><small>Simulator-Prozess</small></article>
|
||||
<article class="stat"><p>Instanz-Uptime</p><strong id="num-uptime">–</strong><small>seit Webmodul-Start</small></article>
|
||||
</div>
|
||||
<section class="panel"><div class="section-head"><div><h3>ROBUST & Grid-Dienste</h3><p>TCP-Erreichbarkeit der konfigurierten Service-Endpunkte</p></div></div><div id="services-table" class="table-wrap"></div></section><section class="panel"><div class="section-head"><div><h3>Regionen im Überblick</h3><p>Bereitschaft, aktuelle Besucher und Portkonfiguration</p></div></div><div id="overview-regions" class="table-wrap"></div></section>
|
||||
</section>
|
||||
<section id="regions" class="view" hidden><div class="section-head"><div><h3>Regionen & Aktionen</h3><p>Neustart ausschließlich für lokal geladene Regionen</p></div></div><div id="region-actions" class="cards"></div></section>
|
||||
<section id="archives" class="view" hidden><div class="section-head"><div><h3>OAR-Archive</h3><p>Lokaler Export, Download und Import mit Statusverfolgung. Ein Import verändert Regionsinhalt.</p></div></div><div class="panel"><label>Region auswählen<select id="archive-region"></select></label><div class="button-row"><button id="oar-export" class="primary">OAR-Sicherung erstellen</button><label for="oar-file" class="filelabel">OAR-Datei auswählen<input type="file" id="oar-file" accept=".oar,application/octet-stream" hidden></label><button id="oar-import" class="danger">Ausgewählte OAR importieren</button></div><div class="muted" id="selected-file"></div></div><section class="panel"><div class="section-head"><h3>Archivaufträge</h3><button class="ghost" id="jobs-refresh">Status abfragen</button></div><div id="job-table" class="table-wrap"></div></section></section>
|
||||
<section id="network" class="view" hidden><div class="section-head"><div><h3>Netzwerkdiagnose</h3><p>TCP-/UDP-Listener auf dem Simulatorhost und die konfigurierte Region-Ports</p></div></div><div class="panel notice">Lokale Listener sind keine Bestätigung der externen Erreichbarkeit: Fritz!Box-Portfreigaben, CGNAT und Firewall-Regeln müssen zusätzlich von außerhalb getestet werden.</div><div id="ports-table" class="table-wrap panel"></div></section>
|
||||
<section id="logs" class="view" hidden><div class="section-head"><div><h3>Simulator-Protokoll</h3><p>Letzte 90.000 Zeichen der aktiven Logdatei</p></div><button id="logs-refresh" class="ghost">Log aktualisieren</button></div><pre id="log-text" class="terminal">Lade Protokoll …</pre></section>
|
||||
<section id="updates" class="view" hidden><div class="section-head"><div><h3>GitHub & Versionskontrolle</h3><p>Commit-Stand des offiziellen OpenGenesisLINK-Repositorys</p></div><button id="updates-refresh" class="ghost">GitHub prüfen</button></div><div class="panel"><p>Installierter Commit</p><strong id="local-sha" class="mono">–</strong><p>Aktueller Main-Commit</p><strong id="remote-sha" class="mono">–</strong><div id="version-note" class="muted"></div><div class="button-row"><button class="primary" id="update-stage">Quellcode herunterladen & Konfiguration sichern</button></div></div><section class="panel"><h3>Letzte Änderungen</h3><div id="commits"></div></section><div class="panel notice">Dieser Schritt bereitet ein Update nur vor: GitHub-Quellcode herunterladen, lokale Konfiguration sicher sichern und alte Backups nach Retentionsregel entfernen. Der Build und die Aktivierung der Programmdateien sind ein separater, bewusst manueller Schritt. Kein automatischer Neustart.</div></section>
|
||||
</main>
|
||||
</div>
|
||||
<div id="modal" class="modal" hidden><div class="dialog" role="alertdialog" aria-modal="true" aria-labelledby="modal-title"><div class="modal-icon">!</div><h3 id="modal-title">Hinweis</h3><p id="modal-message"></p><div class="button-row"><button class="primary" id="modal-ok">Verstanden</button><button class="ghost" id="modal-cancel" hidden>Abbrechen</button></div></div></div>
|
||||
</body></html>
|
||||
@@ -0,0 +1 @@
|
||||
:root{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;background:#0b101b;color:#e9eef9;font-size:14px}*{box-sizing:border-box}body{margin:0;min-height:100vh}button,input,select{font:inherit}button{cursor:pointer;border-radius:10px;padding:10px 17px;border:1px solid #30415a;background:#161f32;color:#eef5ff}button:hover{filter:brightness(1.17)}button.primary{background:linear-gradient(120deg,#24b2ef,#087bdd);color:white;border:0;font-weight:700}button.danger{color:#ffb6b8;border-color:#92484d}button.ghost{background:#151e2d}.muted,p{color:#94a5bb}.eyebrow{letter-spacing:.22em;font-size:10px;color:#6cc9f2;font-weight:750}.brand-mark{width:64px;height:64px;display:grid;place-items:center;font-weight:900;letter-spacing:-.17em;padding-right:.15em;font-size:22px;background:linear-gradient(135deg,#17ade4,#6244bf);border-radius:18px;box-shadow:0 10px 34px #0788cc44}.brand-mark span{color:#b9eafe}.brand-mark.small{width:46px;height:46px;border-radius:14px;font-size:17px}h1{font-size:35px;margin:.6em 0 .25em}h2{font-size:30px;margin:6px 0 0;font-weight:750}h3{font-size:19px;margin:0 0 6px}.login-screen{min-height:100vh;display:grid;place-items:center;padding:25px;background:radial-gradient(ellipse at 70% 18%,#132d50 0,transparent 40%),radial-gradient(ellipse at 16% 82%,#19204c 0,transparent 48%),#0b101b}.login-panel{width:min(100%,460px);padding:46px;background:#151d2de8;border:1px solid #35425b;border-radius:24px;box-shadow:0 32px 120px #0006}.login-panel .muted{line-height:1.6}label{display:block;font-size:13px;color:#bccce1;font-weight:650;margin:18px 0}input,select{display:block;width:100%;background:#0d1523;border:1px solid #36455e;border-radius:9px;padding:13px;color:#ecf3fc;margin-top:8px;outline:0}input:focus,select:focus{border-color:#51bdf3}.login-panel .primary{width:100%;margin:12px 0 18px;padding:14px}small{font-size:11px}aside{position:fixed;inset:0 auto 0 0;width:255px;background:#111927;border-right:1px solid #27374b;padding:27px 16px;display:flex;flex-direction:column}.side-brand{display:flex;gap:12px;align-items:center;padding:0 9px 33px}.side-brand strong{font-size:14px}.side-brand small{display:block;color:#7b90a8;letter-spacing:.16em;font-size:9px;margin-top:4px}.side-label{font-size:10px;color:#67819f;letter-spacing:.18em;margin:0 12px 10px}nav{display:flex;flex-direction:column;gap:4px}nav a{text-decoration:none;color:#aabbd0;padding:14px 15px;border-radius:10px;font-weight:550}nav a.active,nav a:hover{background:#1a2c45;color:#65c8ff}nav a.active{box-shadow:inset 3px 0 #22a8f6}.side-footer{margin-top:auto;font-size:12px;border-top:1px solid #25344b;padding:18px 10px 0}.side-footer p{font-size:11px}.live-dot{width:8px;height:8px;border-radius:50%;background:#4cdb9b;display:inline-block;margin-right:8px;box-shadow:0 0 14px #42bb86}main{margin-left:255px;max-width:1600px;min-height:100vh;padding:28px 38px 70px}.topbar{display:flex;justify-content:space-between;align-items:center;gap:15px;padding-bottom:28px}.top-right{display:flex;align-items:center;gap:10px}.pill{padding:9px 13px;background:#1a283c;color:#8ad5fa;border:1px solid #2b4967;border-radius:30px;white-space:nowrap}.hero{display:flex;justify-content:space-between;align-items:center;background:radial-gradient(circle at 84% 50%,#24528b70,transparent 38%),linear-gradient(120deg,#172c48,#121c30);border:1px solid #2b4666;border-radius:21px;padding:35px 43px;min-height:250px}.hero h2{font-size:36px;line-height:1.18}.hero h2 em{font-style:normal;color:#49c1f8}.hero p{max-width:420px;line-height:1.55}.hero-ring{width:160px;height:160px;border:9px solid #2f6594;box-shadow:0 0 0 1px #50c6fa99,inset 0 0 40px #159deb33,0 0 55px #39b0e922;border-radius:50%;display:flex;flex-direction:column;justify-content:center;align-items:center}.hero-ring span{font-weight:900;font-size:43px;letter-spacing:-.1em}.hero-ring small{letter-spacing:.2em;color:#62caff}.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:16px;margin:24px 0}.stat,.panel,.region-card{border:1px solid #27364d;background:#151f30;border-radius:15px;padding:23px}.stat p{margin:0 0 12px;font-weight:650}.stat strong{font-size:30px;font-weight:800}.stat small{display:block;color:#6d87a5;margin-top:8px}.panel{margin:20px 0}.section-head{display:flex;justify-content:space-between;align-items:center;gap:15px;margin:9px 0 18px}.section-head p{font-size:12px;margin:5px 0}.table-wrap{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left}th{font-size:11px;text-transform:uppercase;letter-spacing:.08em;color:#8299b4;padding:14px;border-bottom:1px solid #2b3e55}td{padding:14px;border-bottom:1px solid #243348;color:#c9d6e7}td strong{color:#f4f7ff}.status{display:inline-block;border-radius:15px;padding:5px 9px;background:#273e49;color:#70dbb3;font-size:11px}.status.bad{background:#412b36;color:#ffacb4}.cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.region-card h3{font-size:20px}.region-card p{fonLine truncated
|
||||
@@ -581,3 +581,14 @@
|
||||
[Architecture]
|
||||
Include-Architecture = "config-include/GridHypergrid.ini"
|
||||
|
||||
|
||||
; ============================================================================
|
||||
; OpenGenesisLINK standalone Simulator Admin Interface (separate DLL).
|
||||
; Disabled by default. Listens only on 127.0.0.1; use a HTTPS reverse proxy
|
||||
; and firewall for access from another PC. Each simulator requires its own port.
|
||||
; On successful Avatar login UserLevel MUST be greater than 0.
|
||||
[OSWebInterface]
|
||||
Enabled = false
|
||||
Port = 9847
|
||||
DataDirectory = "os-webinterface-data"
|
||||
BackupRetention = 5
|
||||
@@ -464,3 +464,14 @@
|
||||
WebDavUsername = ""
|
||||
WebDavPasswordFile = ""
|
||||
MaximumArchiveMiB = 10240
|
||||
|
||||
; ============================================================================
|
||||
; OpenGenesisLINK standalone Simulator Admin Interface (separate DLL).
|
||||
; Disabled by default. Listens only on 127.0.0.1; use a HTTPS reverse proxy
|
||||
; and firewall for access from another PC. Each simulator requires its own port.
|
||||
; On successful Avatar login UserLevel MUST be greater than 0.
|
||||
[OSWebInterface]
|
||||
Enabled = false
|
||||
Port = 9847
|
||||
DataDirectory = "os-webinterface-data"
|
||||
BackupRetention = 5
|
||||
@@ -10,3 +10,4 @@ for addon in OGLWeather NexTraffic NexTransit NexSmartLight OGLEnergy; do
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
test -s bin/os_webinterface.dll || { echo "Missing simulator admin DLL: os_webinterface" >&2; exit 1; }
|
||||
@@ -0,0 +1,48 @@
|
||||
# OpenGenesisLINK Generation 1 – Simulator Control (os_webinterface.dll)
|
||||
|
||||
**Status:** Opt-in addon, developer preview. **Not enabled in production.**
|
||||
|
||||
## Independent DLL
|
||||
|
||||
os_webinterface.dll is a .NET 10 Mono.Addins ISharedRegionModule, loaded by the simulator's existing region-module manager. No additional web administration handlers are added to OpenSim.dll. Each simulator has its own panel and own port.
|
||||
|
||||
The HTTP listener binds ONLY to 127.0.0.1. For remote usage, configure an HTTPS reverse proxy with host firewall, certificate, forwarded Host header, and X-Forwarded-Proto set to https. Do not publish the raw HTTP port via a public Fritz!Box port forward.
|
||||
|
||||
## Configuration (simulator bin/OpenSim.ini)
|
||||
|
||||
[OSWebInterface]
|
||||
Enabled = true
|
||||
Port = 9847
|
||||
DataDirectory = "os-webinterface-data"
|
||||
BackupRetention = 5
|
||||
|
||||
Default Enabled=false; activating requires ONE planned simulator restart. Every simulator process must use a distinct port.
|
||||
|
||||
## Avatar authentication and authorization
|
||||
|
||||
Login with the local avatar first + last name (or First.Last) and its password. The simulator's native account and authentication services validate credentials. Only active avatars with UserLevel > 0 can log in. A valid avatar with UserLevel <= 0 receives HTTP 403: Access Denied – Keine Berechtigung.
|
||||
|
||||
Security: cryptographically random one-hour HttpOnly SameSite=Strict sessions; Secure cookies behind HTTPS; permissions revalidated on every request; CSRF and Origin checks for mutations; anti-bruteforce backoff; restrictive CSP. Passwords are never stored or echoed.
|
||||
|
||||
**UserLevel > 0 is full simulator administrative authority in this module.** Do not elevate untrusted accounts or publish the panel without strong TLS/firewall protection.
|
||||
|
||||
## Functionality
|
||||
|
||||
* Overview: Region ID/name, grid coordinates, size, readiness, root avatars, scripts/physics settings, RAM, uptime, UDP/TCP ports.
|
||||
* Region actions: restart a single local scene after explicit confirmation. Other simulator instances are not controlled by this DLL.
|
||||
* OAR: asynchronous export to a local archive, download, upload and import with job status and byte count (2 GiB limit). Existing OGL archive feature gates are enforced by the underlying archiver and NOT bypassed.
|
||||
* Logs: last 90,000 characters of OpenSim.log or the newest log inside the logs directory.
|
||||
* Services: probes configured ROBUST/Grid/Asset/Inventory/User/Authentication/Presence/Friends/Hypergrid endpoint TCP reachability (not application-level correctness).
|
||||
* Network: checks local TCP/UDP listeners. External reachability cannot be inferred from this alone: Fritz!Box, NAT/CGNAT, ISP inbound restrictions and firewall must be independently probed from outside the LAN.
|
||||
* Git: check current SHA and latest commit titles on official OpenGenesisLINK main.
|
||||
* Updates: explicitly download a pinned latest-GitHub source snapshot, create private ZIP backup of config including keyfiles, and rotate old backups. No automatic execution of GitHub source, no build and no binary replacement. A trusted build-and-rollback mechanism is required before one-click production activation. Manual restart alone does not install a staged source snapshot.
|
||||
|
||||
## Tests
|
||||
|
||||
python3 tools/ci/verify_os_webinterface.py
|
||||
dotnet build addons/OSWebInterface/os_webinterface.csproj -c Release
|
||||
dotnet build OpenSim.sln -c Release
|
||||
|
||||
Perform local Bomlitz acceptance before enabling on production, including valid/invalid UserLevel login, disposable-region restart, OAR roundtrip, HTTPS reverse proxy and external connectivity testing.
|
||||
|
||||
Note: Update snapshot staging is currently restricted to Linux due to required NTFS ACL enforcement for backups containing secrets on Windows. On Windows, the monitoring and admin functions remain available.
|
||||
+3
-1
@@ -37,13 +37,15 @@ case "$1" in
|
||||
addons/NexTransit/OpenGenesisLINK.Addons.NexTransit.csproj \
|
||||
addons/NexSmartLight/OpenGenesisLINK.Addons.NexSmartLight.csproj \
|
||||
addons/OGLWeather/OpenGenesisLINK.Addons.OGLWeather.csproj \
|
||||
addons/OGLEnergy/OpenGenesisLINK.Addons.OGLEnergy.csproj
|
||||
addons/OGLEnergy/OpenGenesisLINK.Addons.OGLEnergy.csproj \
|
||||
addons/OSWebInterface/os_webinterface.csproj
|
||||
printf '%s\n' \
|
||||
'#!/bin/sh' 'set -eu' \
|
||||
'dotnet build -c Release OpenSim.sln' \
|
||||
'for addon in NexTraffic NexTransit NexSmartLight OGLWeather OGLEnergy; do' \
|
||||
' test -s "bin/OpenGenesisLINK.Addons.${addon}.dll" || { echo "Missing city addon DLL: ${addon}" >&2; exit 1; }' \
|
||||
'done' \
|
||||
'test -s bin/os_webinterface.dll || { echo "Missing simulator admin DLL: os_webinterface" >&2; exit 1; }' \
|
||||
'bash addon-modules/OGLAssetService/build.sh Release' > compile.sh
|
||||
chmod +x compile.sh
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<OutputType>Exe</OutputType>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../../../addons/OSWebInterface/os_webinterface.csproj" />
|
||||
<Reference Include="Nini"><HintPath>../../../bin/Nini.dll</HintPath><Private>true</Private></Reference>
|
||||
<Reference Include="Mono.Addins"><HintPath>../../../bin/Mono.Addins.dll</HintPath><Private>true</Private></Reference>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,59 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using Nini.Config;
|
||||
using OpenGenesisLINK.Addons.OSWebInterface;
|
||||
|
||||
using var probe = new TcpListener(IPAddress.Loopback, 0);
|
||||
probe.Start();
|
||||
int port = ((IPEndPoint)probe.LocalEndpoint).Port;
|
||||
probe.Stop();
|
||||
|
||||
var config = new IniConfigSource();
|
||||
IConfig entry = config.Configs.Add("OSWebInterface");
|
||||
entry.Set("Enabled", "true");
|
||||
entry.Set("Port", port.ToString());
|
||||
entry.Set("DataDirectory", "os-webinterface-smoke-test");
|
||||
var module = new OSWebInterfaceModule();
|
||||
module.Initialise(config);
|
||||
try
|
||||
{
|
||||
using var client = new HttpClient(new HttpClientHandler { UseCookies = false }) {
|
||||
BaseAddress = new Uri($"http://127.0.0.1:{port}/"),
|
||||
Timeout = TimeSpan.FromSeconds(8)
|
||||
};
|
||||
var home = await client.GetAsync("/");
|
||||
if (home.StatusCode != HttpStatusCode.OK)
|
||||
throw new Exception("Index document status " + home.StatusCode);
|
||||
string html = await home.Content.ReadAsStringAsync();
|
||||
if (!html.Contains("Simulator Control")) throw new Exception("Index body missing");
|
||||
if (home.Headers.Contains("Access-Control-Allow-Origin"))
|
||||
throw new Exception("Unexpected CORS header");
|
||||
if (!home.Headers.Contains("Content-Security-Policy"))
|
||||
throw new Exception("CSP missing");
|
||||
foreach (string path in new[] { "/style.css", "/app.js" })
|
||||
{
|
||||
using var staticFile = await client.GetAsync(path);
|
||||
if (staticFile.StatusCode != HttpStatusCode.OK)
|
||||
throw new Exception("Static resource missing: " + path);
|
||||
}
|
||||
using var denied = await client.GetAsync("/api/overview");
|
||||
if (denied.StatusCode != HttpStatusCode.Unauthorized)
|
||||
throw new Exception("Unauthenticated overview not denied");
|
||||
using var forged = new HttpRequestMessage(HttpMethod.Post, "/api/login");
|
||||
forged.Headers.Add("Origin", "https://attacker.example");
|
||||
forged.Content = new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}",
|
||||
Encoding.UTF8, "application/json");
|
||||
using var rejected = await client.SendAsync(forged);
|
||||
if (rejected.StatusCode != HttpStatusCode.Forbidden)
|
||||
throw new Exception("Cross-origin login not denied");
|
||||
using var noBackends = await client.PostAsync("/api/login",
|
||||
new StringContent("{\"username\":\"Test User\",\"password\":\"123\"}", Encoding.UTF8,
|
||||
"application/json"));
|
||||
if (noBackends.StatusCode != HttpStatusCode.ServiceUnavailable)
|
||||
throw new Exception("Missing authentication service did not fail closed");
|
||||
Console.WriteLine("OSWebInterface HTTP smoke PASS: UI, static resources, CSP, 401, CSRF-origin and fail-closed login");
|
||||
}
|
||||
finally { module.Close(); }
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generation 1 simulator web interface static security/integration regression."""
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
def text(path):
|
||||
return (root / path).read_text(encoding="utf-8-sig")
|
||||
|
||||
project = text("addons/OSWebInterface/os_webinterface.csproj")
|
||||
module = text("addons/OSWebInterface/OSWebInterfaceModule.cs")
|
||||
http = text("addons/OSWebInterface/AdminHttpServer.cs")
|
||||
ops = text("addons/OSWebInterface/AdminOperations.cs")
|
||||
updates = text("addons/OSWebInterface/UpdateStager.cs")
|
||||
js = text("addons/OSWebInterface/www/app.js")
|
||||
ini_paths = ("bin/OpenSim.ini", "bin/OpenSim.ini.example")
|
||||
for ini in ini_paths:
|
||||
c = text(ini).split("[OSWebInterface]", 1)
|
||||
assert len(c) == 2 and "Enabled = false" in c[1], ini
|
||||
|
||||
for part in (
|
||||
"<AssemblyName>os_webinterface</AssemblyName>",
|
||||
"EmbeddedResource Include=\"www/index.html\"",
|
||||
"EmbeddedResource Include=\"www/app.js\"",
|
||||
"EmbeddedResource Include=\"www/style.css\"",
|
||||
):
|
||||
assert part in project, part
|
||||
for part in (
|
||||
'Id = "OSWebInterface"', "ISharedRegionModule",
|
||||
'GetBoolean("Enabled", false)',
|
||||
"http://127.0.0.1:", "Directory.CreateDirectory",
|
||||
"_server?.Dispose()",
|
||||
):
|
||||
assert part in module, part
|
||||
for part in (
|
||||
"GetUserAccount(UUID.Zero", "Authenticate(account.PrincipalID",
|
||||
"account.UserLevel <= 0", "!account.LoginAllowed",
|
||||
"Access Denied – Keine Berechtigung.",
|
||||
"HttpOnly; SameSite=Strict", "X-OGL-CSRF", "SameOrigin(",
|
||||
"Content-Security-Policy", "TrySession(request",
|
||||
'"/api/regions/restart"', '"/api/oar/import"', '"/api/oar/export"',
|
||||
'"/api/oar/download"', '"/api/updates/check"', '"/api/updates/stage"',
|
||||
):
|
||||
assert part in http, part
|
||||
for part in (
|
||||
"RestartNow()", "ArchiveRegion(", "DearchiveRegion(",
|
||||
"OnOarFileSaved", "OnOarFileLoaded", "GetActiveUdpListeners",
|
||||
"GetActiveTcpListeners", "publicStatus =",
|
||||
"MaxUploadBytes", "FileShare.ReadWrite", "CheckGitAsync(",
|
||||
):
|
||||
assert part in ops, part
|
||||
for part in (
|
||||
"PrivateFile", "File.SetUnixFileMode",
|
||||
"BackupConfigs(", "configuration-backups", "Prune(",
|
||||
"File.Move(tmp, filename)", "git", "latest",
|
||||
):
|
||||
assert part in updates, part
|
||||
assert "Process.Start(" not in updates, "Updater must never execute downloaded source."
|
||||
assert "innerHTML" not in js, "Client must avoid arbitrary HTML insertion."
|
||||
assert "textContent" in js
|
||||
|
||||
for p in ("OpenSim.sln", "runprebuild.sh", "compile.sh"):
|
||||
assert "os_webinterface" in text(p) or "OSWebInterface" in text(p), p
|
||||
assert "verify_os_webinterface.py" in text(".github/workflows/nexjast-ci.yml")
|
||||
print("OS webinterface: opt-in module, auth, CSRF, OAR, logs, ports, staging and build integration OK")
|
||||
Reference in new issue
Block a user