refactor(deploy): use Rust Server runtime contracts

This commit is contained in:
AAA committed 2026-10-30 22:32:59 -04:00
1 parent fcc0bb53bc
commit 1d86f22028
11 files changed
+92 -157

No files matched your search

-9
View File
@@ -1,9 +0,0 @@
#!/bin/bash
set -Eeuo pipefail
if [ "$#" -ne 0 ]; then
printf 'usage: %s\n' "$0" >&2
exit 2
fi
exec /opt/piik/current/piik-server --check-release
+9 -18
View File
@@ -1,21 +1,12 @@
# Point this domain directly at the server. See the self-hosting guide for HTTPS.
PUBLIC_BASE_URL=https://share.example.com
STUN_URLS=stun:share.example.com:3478
MAX_VIEWERS_PER_ROOM=20
# Empty means the site opens without a site password. Room access is separate.
SITE_ACCESS_PASSWORD=
# Optional for public sites: reclaim empty rooms after an hour, or earlier
# under room-code pressure. Unset/0 preserves room authority indefinitely.
# ROOM_EMPTY_TIMEOUT_SECONDS=3600
# Optional automatic media fallback: set BOTH values and allow UDP 7882.
# SFU_UDP_PORT=7882
# SFU_PUBLIC_IP=203.0.113.10
# Optional: require SFU for all rooms instead of P2P-first (requires SFU_UDP_PORT).
# SFU_ONLY=true
# Optional NAT survey: also allow UDP 3479 and 3480.
# NAT_PREDICTION_ENABLED=true
# Public HTTPS origin served by your reverse proxy.
PIIK_CHANNEL_WEB_ORIGIN=https://share.example.com
# Supply separate, private, stable keys. Keep this file outside version control.
PIIK_CHANNEL_OWNER_KEY=
PIIK_CHANNEL_INVITE_KEY=
# Optional advertised invitation origin; defaults to the Web origin.
# PIIK_CHANNEL_INVITATION_ORIGIN=https://share.example.com
# Optional WebRTC ICE server JSON; defaults to the shared public STUN choices.
# PIIK_CHANNEL_ICE_SERVERS=[{"urls":["stun:stun.cloudflare.com:3478"]}]
# To pin a release, replace latest with its vMAJOR.MINOR.PATCH tag.
# PIIK_IMAGE=ghcr.io/tntcrafthim/piik:latest
+5 -4
View File
@@ -1,9 +1,9 @@
FROM gcr.io/distroless/static-debian13:nonroot@sha256:e2e927ec666bae08560abb3c55d0659eceabb657f56b6782ab500a9fc7f555e3
FROM gcr.io/distroless/cc-debian13:nonroot@sha256:3ee00291cf386ec52a552e6a858d555debd74776eb4bfa53fa3df2cd6677515e
ARG PIIK_VERSION=development
ARG PIIK_REVISION
ARG PIIK_SERVER_SHA256
LABEL org.opencontainers.image.title="Piik Server" \
org.opencontainers.image.description="Private screen sharing with Web, signaling, STUN and optional media fallback." \
org.opencontainers.image.description="Private rooms with the shared Web UI and Rust media forwarding." \
org.opencontainers.image.source="https://github.com/TNTcraftHIM/Piik" \
org.opencontainers.image.licenses="MIT" \
org.opencontainers.image.version=$PIIK_VERSION \
@@ -12,7 +12,8 @@ LABEL org.opencontainers.image.title="Piik Server" \
WORKDIR /app
COPY --chmod=0555 piik-server /app/
COPY --chmod=0444 LICENSE THIRD-PARTY-NOTICES.txt REVISION /app/
ENV LISTEN_HOST=0.0.0.0 PIIK_LOG_DIR=/home/nonroot/logs ROOM_DATABASE_PATH=/home/nonroot/rooms.sqlite
COPY web/ /app/web/
ENV PIIK_CHANNEL_BIND_ADDRESS=0.0.0.0 PIIK_CHANNEL_PORT=8787 PIIK_CHANNEL_DATA_DIR=/home/nonroot
USER 65532:65532
EXPOSE 8787/tcp 3478/udp 3479/udp 3480/udp 7882/udp
EXPOSE 8787/tcp
ENTRYPOINT ["/app/piik-server"]
+5 -7
View File
@@ -10,15 +10,13 @@ services:
security_opt: [no-new-privileges:true]
env_file: .env
environment:
PIIK_ENV: production
LISTEN_HOST: 0.0.0.0
PIIK_CHANNEL_BIND_ADDRESS: 0.0.0.0
PIIK_CHANNEL_PORT: 8787
PIIK_CHANNEL_DATA_DIR: /home/nonroot
PIIK_CHANNEL_OWNER_KEY: ${PIIK_CHANNEL_OWNER_KEY:?Set a private stable owner key}
PIIK_CHANNEL_INVITE_KEY: ${PIIK_CHANNEL_INVITE_KEY:?Set a separate stable invitation key}
ports:
- "127.0.0.1:8787:8787/tcp"
- "3478:3478/udp"
# Auxiliary STUN and SFU listen only when enabled in .env.
- "3479:3479/udp"
- "3480:3480/udp"
- "7882:7882/udp"
volumes:
- piik-data:/home/nonroot
+1 -8
View File
@@ -1,5 +1,6 @@
# Run beside Piik; inject the same nonempty FRP_TOKEN into frpc and frps.
# See docs/operations/self-hosting.md for the public HTTPS proxy and frps setup.
# This forwards HTTP/WebSocket only; media uses the runtime's ICE paths.
serverAddr = "relay.example.com"
serverPort = 7000
auth.token = "{{ .Envs.FRP_TOKEN }}"
@@ -11,11 +12,3 @@ type = "tcp"
localIP = "127.0.0.1"
localPort = 8787
remotePort = 8787
[[proxies]]
name = "piik-sfu"
type = "udp"
localIP = "127.0.0.1"
# All three ports must match: localPort, remotePort, Piik's SFU_UDP_PORT.
localPort = 7882
remotePort = 7882
-21
View File
@@ -3,8 +3,6 @@ map $http_upgrade $piik_connection_upgrade {
'' close;
}
limit_req_zone $binary_remote_addr zone=piik_site_access:10m rate=5r/m;
server {
listen 80;
listen [::]:80;
@@ -39,25 +37,6 @@ server {
add_header X-Frame-Options "DENY" always;
add_header Permissions-Policy "camera=(self), microphone=(self), geolocation=()" always;
# Media uses /signal. Reject credential-bearing RTC query endpoints without
# persisting their query strings, including requests from already-open pages.
location ~ ^/rtc(?:/|$) {
access_log off;
error_log /dev/null crit;
return 404;
}
location = /api/site-access {
limit_req zone=piik_site_access burst=5 nodelay;
limit_req_status 429;
proxy_pass http://127.0.0.1:8787;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto https;
proxy_buffering off;
}
location / {
proxy_pass http://127.0.0.1:8787;
proxy_http_version 1.1;
+14 -20
View File
@@ -103,7 +103,7 @@ wait_for_health() {
local body=''
for _ in $(seq 1 120); do
body="$(curl -fsS --max-time 2 http://127.0.0.1:8787/healthz 2>/dev/null || true)"
if [ "$body" = '{"status":"ok"}' ]; then
if [ "$body" = 'piik-channel-prototype' ]; then
return 0
fi
sleep 0.25
@@ -165,7 +165,6 @@ for service in piik nginx; do
test "$(systemctl show "${service}.service" -p ActiveState --value)" = 'active'
test "$(systemctl show "${service}.service" -p NRestarts --value)" = '0'
done
# The first Go/embedded-media cutover owns its infrastructure recovery separately.
test -x "$old_release/piik-server"
old_pid="$(systemctl show piik.service -p MainPID --value)"
test "$old_pid" -gt 1
@@ -181,7 +180,7 @@ while IFS= read -r raw_entry; do
esac
case "$entry" in
/*|*\\*) printf 'invalid archive entry: %s\n' "$raw_entry" >&2; exit 41 ;;
LICENSE|REVISION|THIRD-PARTY-NOTICES.txt|piik-server) ;;
LICENSE|REVISION|THIRD-PARTY-NOTICES.txt|piik-server|web|web/*) ;;
*) printf 'unexpected archive entry: %s\n' "$raw_entry" >&2; exit 42 ;;
esac
done < <(tar -tzf "$artifact")
@@ -194,17 +193,20 @@ tar --no-same-owner --no-same-permissions -xzf "$artifact" -C "$stage"
tab=$'\t'
if [ -n "$(tail -c 1 "$manifest")" ]; then exit 61; fi
if grep -qEv "^[0-9a-f]{64}${tab}[0-9]+${tab}[^${tab}]*$" "$manifest"; then exit 62; fi
if grep -qEv "^[0-9a-f]{64}${tab}[0-9]+${tab}(LICENSE|REVISION|THIRD-PARTY-NOTICES\.txt|piik-server)$" "$manifest"; then exit 63; fi
if grep -qEv "^[0-9a-f]{64}${tab}[0-9]+${tab}(LICENSE|REVISION|THIRD-PARTY-NOTICES\.txt|piik-server|web/[A-Za-z0-9_./-]+)$" "$manifest"; then exit 63; fi
if [ -n "$(cut -f3 "$manifest" | sort | uniq -d)" ]; then exit 64; fi
if [ "$(wc -l < "$manifest")" -ne "$file_count" ]; then exit 65; fi
if [ -n "$(find "$stage" -type l)" ]; then exit 66; fi
if [ -n "$(find "$stage" -type f -printf '%D:%i\n' | sort | uniq -d)" ]; then exit 67; fi
if [ -n "$(find "$stage" ! -type f ! -type d ! -type l)" ]; then exit 68; fi
if [ "$(find "$stage" -type f | wc -l)" -ne "$file_count" ]; then exit 69; fi
if ! awk -F'\t' '{ printf "%s %s\n", $1, $3 }' "$manifest" | (cd "$stage" && sha256sum -c --strict --quiet -); then exit 70; fi
while IFS="$tab" read -r _ size path; do
case "/$path/" in
*'/../'*|*'/./'*|*'//'*) printf 'invalid manifest path: %s\n' "$path" >&2; exit 63 ;;
esac
test "$(stat -c '%s' "$stage/$path")" = "$size" || exit 70
done < "$manifest"
if ! awk -F'\t' '{ printf "%s %s\n", $1, $3 }' "$manifest" | (cd "$stage" && sha256sum -c --strict --quiet -); then exit 70; fi
if [ "$(cat "$stage/REVISION")" != "$revision" ]; then exit 71; fi
printf 'artifact_manifest=ok files=%s revision=%s\n' "$file_count" "$revision"
@@ -214,19 +216,11 @@ chmod 0755 "$stage/piik-server"
test -x "$stage/piik-server"
chmod 0644 "$stage/LICENSE" "$stage/REVISION" "$stage/THIRD-PARTY-NOTICES.txt"
# Runs as the service user under the manager (no sudo/polkit round trip) so a
# binary or environment file the service cannot use fails here, before cutover.
systemd-run \
--uid=piik \
--gid=piik \
--wait \
--collect \
--quiet \
--service-type=exec \
--property='EnvironmentFile=/etc/piik/piik.env' \
--property='Environment=PIIK_ENV=production' \
--property='RuntimeMaxSec=20s' \
"$stage/piik-server" --check-config
test -r "$stage/web/index.html"
test -r "$stage/web/$main_asset"
dependencies="$(ldd "$stage/piik-server")"
printf '%s\n' "$dependencies"
if grep -q 'not found' <<< "$dependencies"; then exit 72; fi
if [ -n "$(comm -12 <(find "$old_release" -type f -printf '%D:%i\n' | sort -u) <(find "$stage" -type f -printf '%D:%i\n' | sort -u))" ]; then
exit 80
@@ -266,8 +260,8 @@ test "$(readlink -f -- "$current")" = "$release"
pid="$(systemctl show piik.service -p MainPID --value)"
test "$pid" -gt 1
test "$(readlink -f "/proc/${pid}/cwd")" = "$release"
test "$(curl -fsS --max-time 5 http://127.0.0.1:8787/healthz)" = '{"status":"ok"}'
test "$(curl -fsS --max-time 8 "$public_origin/healthz")" = '{"status":"ok"}'
test "$(curl -fsS --max-time 5 http://127.0.0.1:8787/healthz)" = 'piik-channel-prototype'
test "$(curl -fsS --max-time 8 "$public_origin/healthz")" = 'piik-channel-prototype'
curl -fsS --max-time 5 http://127.0.0.1:8787/ | grep -Fq "$main_asset"
curl -fsS --max-time 8 "$public_origin/" | grep -Fq "$main_asset"
test "$(curl -sS -o /dev/null -w '%{http_code}' --max-time 8 "$public_origin/$main_asset")" = '200'
+4 -4
View File
@@ -1,5 +1,5 @@
[Unit]
Description=Piik web, signaling, STUN and SFU application
Description=Piik rooms, Web interface and media forwarding
After=network-online.target
Wants=network-online.target
@@ -8,8 +8,8 @@ Type=simple
User=piik
Group=piik
WorkingDirectory=/opt/piik/current
Environment=PIIK_ENV=production
Environment=ROOM_DATABASE_PATH=/var/lib/piik/rooms.sqlite
Environment=PIIK_CHANNEL_PORT=8787
Environment=PIIK_CHANNEL_DATA_DIR=/var/lib/piik
EnvironmentFile=/etc/piik/piik.env
ExecStart=/opt/piik/current/piik-server
Restart=on-failure
@@ -32,7 +32,7 @@ ProtectKernelLogs=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
# Pion uses Go's net.Interfaces, which queries Linux through NETLINK_ROUTE.
# Native interface discovery queries Linux through NETLINK_ROUTE.
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX AF_NETLINK
RestrictNamespaces=true
RestrictRealtime=true
+48 -65
View File
@@ -2,12 +2,12 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { randomBytes, randomUUID } from "node:crypto";
import { createSocket } from "node:dgram";
import { copyFileSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
import { generateKeyPairSync, randomUUID } from "node:crypto";
import { copyFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { fileURLToPath } from "node:url";
import WebSocket from "ws";
import { resetBuildWorkspace } from "./build-workspace.mjs";
import { checkWebSourceIdentity } from "./container-web-identity.mjs";
@@ -18,7 +18,11 @@ if (process.argv.length !== 4 || !image || !/^[0-9a-f]{40}$/.test(revision ?? ""
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const project = `piik-check-${randomUUID()}`;
const workspace = resetBuildWorkspace(root, "container-check", project);
const environment = { ...process.env, PIIK_IMAGE: image };
const origin = "https://share.example.com";
const ownerKey = randomUUID();
const inviteKey = randomUUID();
const environment = { ...process.env, PIIK_IMAGE: image,
PIIK_CHANNEL_OWNER_KEY: ownerKey, PIIK_CHANNEL_INVITE_KEY: inviteKey };
function docker(...args) {
return execFileSync("docker", args, {
cwd: workspace, env: environment, encoding: "utf8", timeout: 90_000,
@@ -37,47 +41,43 @@ async function until(check, label) {
} while (Date.now() < deadline);
throw new Error(`Container check timed out: ${label}`, { cause: failure });
}
async function request(path, options) {
const response = await fetch(`http://127.0.0.1:8787${path}`, {
...options, signal: AbortSignal.timeout(2_000),
});
async function request(path) {
const response = await fetch(`http://127.0.0.1:8787${path}`, { signal: AbortSignal.timeout(2_000) });
assert.ok(response.ok, `${path}: HTTP ${response.status}`);
return response;
}
async function expectServices(sfu, natPrediction) {
const capabilities = await (await request("/api/capabilities")).json();
// Capability metadata is extensible. This gate checks configured services,
// not the absence of other compatible capabilities.
assert.equal(capabilities.sfu, sfu);
assert.equal(capabilities.natPrediction, natPrediction);
}
async function binding(port) {
const socket = createSocket("udp4");
const packet = Buffer.alloc(20);
packet.writeUInt16BE(1); // RFC 8489 Binding Request, no attributes.
packet.writeUInt32BE(0x2112a442, 4);
randomBytes(12).copy(packet, 8);
async function rooms() {
const socket = new WebSocket("ws://127.0.0.1:8787/prototype/channel", { origin });
let timer;
try {
await new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`STUN ${port} timed out`)), 2_000);
const finish = (error) => { clearTimeout(timer); error ? reject(error) : resolve(); };
socket.once("error", finish);
socket.once("message", (reply) => {
try {
assert.ok(reply.length >= 20);
assert.equal(reply.readUInt16BE(0), 0x0101);
assert.deepEqual(reply.subarray(4, 20), packet.subarray(4, 20));
finish();
} catch (error) { finish(error); }
return await new Promise((resolve, reject) => {
timer = setTimeout(() => reject(new Error("Server rooms did not become available")), 10_000);
socket.once("error", reject);
socket.once("open", () => {
const publicKey = generateKeyPairSync("ed25519").publicKey.export({ format: "jwk" });
socket.send(JSON.stringify({ type: "join", name: "Container check", key: ownerKey,
signingKey: [...Buffer.from(publicKey.x, "base64url")] }));
});
socket.on("message", bytes => {
try {
const event = JSON.parse(bytes.toString());
assert.notEqual(event.type, "error", event.code);
if (!["welcome", "state"].includes(event.type)) return;
const { channel } = event.state;
if (channel.rooms.length === 3 && channel.rooms.every(room => room.available)) {
resolve({ channelId: channel.id, roomIds: channel.rooms.map(room => room.id).sort() });
}
} catch (error) { reject(error); }
});
socket.send(packet, port, "127.0.0.1", (error) => { if (error) finish(error); });
});
} finally { socket.close(); }
} finally { clearTimeout(timer); socket.terminate(); }
}
copyFileSync(join(root, "deploy/container/compose.yaml"), join(workspace, "compose.yaml"));
const sample = readFileSync(join(root, "deploy/container/.env.example"), "utf8");
writeFileSync(join(workspace, ".env"), sample);
writeFileSync(join(workspace, ".env"), sample
.replace(/^PIIK_CHANNEL_OWNER_KEY=$/m, `PIIK_CHANNEL_OWNER_KEY=${ownerKey}`)
.replace(/^PIIK_CHANNEL_INVITE_KEY=$/m, `PIIK_CHANNEL_INVITE_KEY=${inviteKey}`));
try {
const metadata = JSON.parse(docker("image", "inspect", image))[0];
assert.equal(metadata.Config.User, "65532:65532");
@@ -85,47 +85,30 @@ try {
assert.equal(metadata.Os, "linux");
assert.equal(metadata.Architecture, process.arch === "x64" ? "amd64" : process.arch);
assert.ok(["amd64", "arm64"].includes(metadata.Architecture));
assert.match(compose("run", "--rm", "--no-deps", "piik", "--check-config"), /config=ok/);
compose("config", "--quiet");
compose("up", "-d", "--pull", "never");
await until(async () => assert.deepEqual(await (await request("/healthz")).json(), { status: "ok" }), "ready");
await expectServices(false, false);
assert.equal((await (await request("/api/site-access")).json()).required, false);
await until(async () => assert.equal(await (await request("/healthz")).text(), "piik-channel-prototype"), "ready");
const html = await (await request("/")).text();
await checkWebSourceIdentity(html, revision, async asset => (await request(asset)).text());
await binding(3478);
const room = await (await request("/api/rooms", {
method: "POST", headers: { Origin: "https://share.example.com", "Content-Type": "application/json" },
body: JSON.stringify({ codeEntryPolicy: "open" }),
})).json();
assert.match(room.roomId, /^[1-9][0-9]{3}$/);
assert.ok(room.hostToken);
const initial = await rooms();
const container = JSON.parse(docker("inspect", compose("ps", "-q", "piik")))[0];
assert.equal(container.HostConfig.ReadonlyRootfs, true);
assert.ok(container.HostConfig.CapDrop.includes("ALL"));
assert.ok(container.HostConfig.SecurityOpt.some((value) => value.startsWith("no-new-privileges")));
assert.ok(container.HostConfig.SecurityOpt.some(value => value.startsWith("no-new-privileges")));
// Recreate with optional services on the same persistent room volume.
writeFileSync(join(workspace, ".env"), `${sample}\nSFU_UDP_PORT=7882\nSFU_PUBLIC_IP=127.0.0.1\nNAT_PREDICTION_ENABLED=true\nPIIK_DEBUG=server\n`);
compose("up", "-d", "--force-recreate", "--pull", "never");
await until(() => expectServices(true, true), "optional services");
await request(`/api/rooms/${room.roomId}/access`, {
method: "POST",
headers: { Origin: "https://share.example.com", Authorization: `Bearer ${room.hostToken}`, "Content-Type": "application/json" },
body: JSON.stringify({ action: "set-code-entry-policy", policy: "private" }),
});
for (const port of [3478, 3479, 3480]) await binding(port);
compose("kill", "--signal", "SIGUSR1", "piik");
const state = join(workspace, "state");
mkdirSync(state);
await until(() => {
compose("cp", "piik:/home/nonroot/.", state);
assert.ok(readdirSync(join(state, "logs")).some((name) => name.endsWith(".zip")));
}, "diagnostic export");
assert.equal(readFileSync(join(state, "rooms.sqlite")).subarray(0, 16).toString(), "SQLite format 3\0");
await until(async () => assert.equal(await (await request("/healthz")).text(), "piik-channel-prototype"), "restart");
assert.deepEqual(await rooms(), initial, "Recreated Server must reopen its persistent rooms");
compose("stop");
const stopped = JSON.parse(docker("inspect", compose("ps", "-aq", "piik")))[0];
assert.equal(stopped.State.ExitCode, 0, "SIGTERM must shut down cleanly");
process.stdout.write("Container checks passed: P2P, embedded services, room persistence, diagnostics and shutdown.\n");
const state = join(workspace, "state");
mkdirSync(state);
compose("cp", "piik:/home/nonroot/.", state);
for (const file of ["channel.sqlite", ...initial.roomIds.map(id => `rooms/${id}.sqlite`)]) {
assert.equal(readFileSync(join(state, file)).subarray(0, 16).toString(), "SQLite format 3\0");
}
process.stdout.write("Container checks passed: shared frontend, authenticated Native rooms, persistence and shutdown.\n");
} catch (error) {
try { process.stderr.write(`${compose("logs", "--no-color", "--tail", "60")}\n`); } catch { /* Startup may have failed. */ }
throw error;
-1
View File
@@ -54,7 +54,6 @@ cmd/piik-app/piik.ico
cmd/piik-app/piik_windows_amd64.syso
internal/server/webassets/dist/.gitkeep
deploy/release-server.sh
deploy/check-release.sh
docs/adr/0001-p2p-first-media-topology.md
docs/adr/0010-cross-platform-client-runtime.md
docs/research/agent-context-governance.md
+6
View File
@@ -20,6 +20,12 @@ eval "$(extract_function wait_for_health)"
eval "$(extract_function recover)"
eval "$(extract_function validate_artifact_names)"
# Readiness follows the Rust service's plaintext endpoint.
(
curl() { printf 'piik-channel-prototype'; }
wait_for_health
)
# Reject the other architecture before any deployment state is touched.
(
release_id='abcdef0'