#!/usr/bin/env node // End-to-end governance simulation against the LIVE deployment. // // RADAR_PASSWORD=... node scripts/e2e/governance-sim.mjs // // Env: API_URL (default https://api.occupymedia.cc), MASTODON_URL // (default https://social.occupymedia.cc), RADAR_EMAIL, RADAR_PASSWORD // (Mastodon web sign-in, used only to click "Authorize" in the real OAuth // consent flow), RADAR_TOKEN (else read over ssh), REPORT // (default /tmp/opencode/workers/GOV-SIM-REPORT.md). // // All created data is prefixed "e2e-gov-". Re-runnable: existing users, // memberships and the Mastodon connection are reused. import { execFileSync } from "node:child_process"; import { mkdirSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; const API = (process.env.API_URL ?? "https://api.occupymedia.cc").replace(/\/$/, ""); const MASTO = (process.env.MASTODON_URL ?? "https://social.occupymedia.cc").replace(/\/$/, ""); const REPORT = process.env.REPORT ?? "/tmp/opencode/workers/GOV-SIM-REPORT.md"; const PASSWORD = "GovSim!2026x"; const RUN = new Date().toISOString().replace(/[-:]/g, "").slice(0, 15); const TAG = "acampada26s"; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const log = (...a) => console.log(`[${new Date().toISOString().slice(11, 19)}]`, ...a); // --------------------------------------------------------------------------- // Report bookkeeping // --------------------------------------------------------------------------- const calls = []; // per-section API call log const sections = []; const gaps = []; const deviations = []; let current = null; function section(name, meta = {}) { current = { name, ...meta, calls: [], checks: [], notes: [] }; sections.push(current); return current; } function check(label, expected, actual, body) { const pass = JSON.stringify(expected) === JSON.stringify(actual); current.checks.push({ label, expected, actual, pass, ...(pass ? {} : { body }) }); log(`${pass ? "PASS" : "FAIL"} ${current.name} — ${label}: expected ${JSON.stringify(expected)} got ${JSON.stringify(actual)}`); return pass; } const note = (text) => { current?.notes.push(text); log(` note: ${text}`); }; const gap = (text) => { if (!gaps.includes(text)) gaps.push(text); }; // --------------------------------------------------------------------------- // HTTP helpers // --------------------------------------------------------------------------- function summarize(body) { if (body === undefined || body === null) return ""; const keys = ["username", "workspaceName", "role", "provider", "instanceUrl", "draftId", "kind", "ballot", "connectionId", "scope", "accountId"]; const out = {}; for (const k of keys) if (body[k] !== undefined) out[k] = body[k]; if (body.rule) out.rule = body.rule; if (body.policy) out.policy = body.policy; if (body.post) out.post = { text: String(body.post.text).slice(0, 40) + "…", providerMetadata: body.post.providerMetadata }; return JSON.stringify(out); } async function api(method, path, opts = {}) { const r = await apiOnce(method, path, opts); // Membership/role writes bump the workspace authorization epoch: re-mint // the caller's session once and retry. if (r.status === 401 && /epoch stale/.test(JSON.stringify(r.data)) && opts.as && ctx.workspaceId) { const key = opts.as === "owner" ? "owner" : opts.as.replace(/^e2e-gov-/, ""); const name = key === "owner" ? "e2e-gov-owner" : `e2e-gov-${key}`; ctx.tokens[key] = (await apiOnce("POST", "/auth/login", { body: { username: name, password: PASSWORD, workspaceId: ctx.workspaceId }, as: name })).data.token; return apiOnce(method, path, { ...opts, token: ctx.tokens[key] }); } if ((opts.ok ?? true) && r.status >= 400) { const err = new Error(`${method} ${path} -> ${r.status}: ${JSON.stringify(r.data).slice(0, 500)}`); err.status = r.status; err.data = r.data; throw err; } return r; } async function apiOnce(method, path, { token, body, as } = {}) { const res = await fetch(`${API}${path}`, { method, headers: { ...(body === undefined ? {} : { "content-type": "application/json" }), ...(token ? { authorization: `Bearer ${token}` } : {}) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), redirect: "manual", }); const text = await res.text(); let data; try { data = text ? JSON.parse(text) : null; } catch { data = text; } const entry = { method, path, as, status: res.status, req: summarize(body) }; (current ? current.calls : calls).push(entry); return { status: res.status, data, headers: res.headers }; } function radarToken() { if (process.env.RADAR_TOKEN) return process.env.RADAR_TOKEN.trim(); return execFileSync("ssh", ["-i", `${process.env.HOME}/.ssh/devserver`, "root@192.168.13.22", "pct exec 150 -- cat /root/.occ-mastodon/radar_token"], { stdio: ["ignore", "pipe", "ignore"] }).toString().trim(); } async function masto(token, path) { const res = await fetch(`${MASTO}${path}`, { headers: { authorization: `Bearer ${token}` } }); if (!res.ok) throw new Error(`mastodon ${path} -> ${res.status}`); return res.json(); } // Minimal cookie jar for the Mastodon web consent flow. class Jar { constructor() { this.c = new Map(); } take(res) { for (const line of res.headers.getSetCookie?.() ?? []) { const [pair] = line.split(";"); const i = pair.indexOf("="); this.c.set(pair.slice(0, i).trim(), pair.slice(i + 1).trim()); } } header() { return [...this.c].map(([k, v]) => `${k}=${v}`).join("; "); } } const hidden = (html) => Object.fromEntries([...html.matchAll(/]*>/g)].map((m) => m[0]) .filter((t) => /type=["']hidden["']/.test(t)) .map((t) => [t.match(/name=["']([^"']+)["']/)?.[1], (t.match(/value=["']([^"']*)["']/)?.[1] ?? "").replace(/&/g, "&")]) .filter(([k]) => k)); // --------------------------------------------------------------------------- // Identity helpers // --------------------------------------------------------------------------- async function registerOrLogin(username, displayName, workspaceName) { const body = { username, password: PASSWORD, displayName, ...(workspaceName ? { workspaceName } : {}) }; const reg = await api("POST", "/auth/register", { body, ok: false, as: username }); if (reg.status < 300) return { ...reg.data, reused: false }; if (reg.status !== 409) throw new Error(`register ${username}: ${reg.status} ${JSON.stringify(reg.data)}`); const login = await api("POST", "/auth/login", { body: { username, password: PASSWORD }, as: username }); return { ...login.data, reused: true }; } async function loginTo(username, workspaceId) { return (await api("POST", "/auth/login", { body: { username, password: PASSWORD, workspaceId }, as: username })).data; } const wsOf = (me) => me?.workspace?.id ?? me?.workspaceId ?? me?.activeWorkspace?.id; const uidOf = (me) => me?.user?.id ?? me?.userId ?? me?.id; // --------------------------------------------------------------------------- // Main // --------------------------------------------------------------------------- const ctx = { users: {}, tokens: {} }; async function setup() { section("Setup: identities, membership, roles"); const owner = await registerOrLogin("e2e-gov-owner", "GovSim Owner", "GovSim Collective"); ctx.workspaceId = wsOf(owner.me); ctx.ownerId = uidOf(owner.me); ctx.tokens.owner = owner.token; note(`owner ${owner.reused ? "reused (login)" : "registered"}; workspace ${ctx.workspaceId}; me keys: ${Object.keys(owner.me ?? {}).join(",")}`); if (!ctx.workspaceId) throw new Error(`cannot find workspaceId in me: ${JSON.stringify(owner.me)}`); const members = async () => (await api("GET", "/team/members", { token: ctx.tokens.owner, as: "owner" })).data; let roster = await members(); const list = Array.isArray(roster) ? roster : roster.members ?? []; note(`member row keys: ${Object.keys(list[0] ?? {}).join(",")}`); let link = null; for (let i = 1; i <= 9; i++) { const name = `e2e-gov-u${i}`; const solo = await registerOrLogin(name, `GovSim U${i}`); const uid = uidOf(solo.me); ctx.users[`u${i}`] = { name, id: uid }; const already = list.find((m) => (m.userId ?? m.user_id ?? m.user?.id) === uid || m.username === name); if (!already) { link ??= (await api("POST", "/team/invite-links", { token: ctx.tokens.owner, as: "owner", body: { role: "Editor", expiresInHours: 1, maxUses: 9 } })).data; const claim = await api("POST", `/invites/${encodeURIComponent(link.token)}/claim`, { token: solo.token, as: name, body: {}, ok: false }); if (claim.status >= 300 && claim.status !== 409) throw new Error(`claim ${name}: ${claim.status} ${JSON.stringify(claim.data)}`); } ctx.tokens[`u${i}`] = (await loginTo(name, ctx.workspaceId)).token; } roster = await members(); const all = Array.isArray(roster) ? roster : roster.members ?? []; const find = (u) => all.find((m) => (m.userId ?? m.user_id ?? m.user?.id) === u.id || m.username === u.name); for (const k of ["u1", "u2", "u3"]) { const m = find(ctx.users[k]); if (!m) throw new Error(`${k} not a member after claim`); if (m.role !== "Admin") await api("PATCH", `/team/members/${m.id ?? m.membershipId}/role`, { token: ctx.tokens.owner, as: "owner", body: { role: "Admin" } }); } // Role changes bump the membership epoch: re-mint sessions. for (let i = 1; i <= 9; i++) ctx.tokens[`u${i}`] = (await loginTo(`e2e-gov-u${i}`, ctx.workspaceId)).token; ctx.tokens.owner = (await loginTo("e2e-gov-owner", ctx.workspaceId)).token; const finalRoster = await members(); const fr = Array.isArray(finalRoster) ? finalRoster : finalRoster.members ?? []; const roles = Object.fromEntries(Object.entries(ctx.users).map(([k, u]) => [k, find.call(null, u) && fr.find((m) => (m.userId ?? m.user_id ?? m.user?.id) === u.id || m.username === u.name)?.role])); check("u1..u3 Admin, u4..u9 Editor (chatgov.vote via migration 024)", { u1: "Admin", u2: "Admin", u3: "Admin", u4: "Editor", u5: "Editor", u6: "Editor", u7: "Editor", u8: "Editor", u9: "Editor" }, roles, fr); check("active member count (owner + 9)", 10, fr.filter((m) => (m.status ?? "active") === "active").length, fr); } async function connectMastodon() { section("Setup: Mastodon connection (OAuth authorization-code flow)"); const existing = (await api("GET", "/connections", { token: ctx.tokens.owner, as: "owner" })).data; const conns = Array.isArray(existing) ? existing : existing.connections ?? []; note(`connection row keys: ${Object.keys(conns[0] ?? {}).join(",")}`); const live = conns.find((c) => c.provider === "mastodon" && !c.disconnectedAt && !c.disconnected_at); if (live) { ctx.connectionId = live.id; note(`reusing mastodon connection ${live.id}`); return; } gap("No route accepts a pre-issued Mastodon access_token (POST /connections only has /authorize → OAuth consent → /connections/callback, plus telegram/bot-token). The sim drives the real consent flow as radar instead."); const auth = await api("POST", "/connections/authorize", { token: ctx.tokens.owner, as: "owner", body: { provider: "mastodon", instanceUrl: MASTO } }); const apiJar = new Jar(); apiJar.take({ headers: auth.headers }); const redirectUrl = auth.data.redirectUrl; if (!process.env.RADAR_PASSWORD) throw new Error("RADAR_PASSWORD is required to approve the OAuth consent as radar"); const jar = new Jar(); const get = async (url) => { const r = await fetch(url, { headers: { cookie: jar.header() }, redirect: "manual" }); jar.take(r); return r; }; const post = async (url, form) => { const r = await fetch(url, { method: "POST", headers: { cookie: jar.header(), "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form), redirect: "manual" }); jar.take(r); return r; }; const signIn = await (await get(`${MASTO}/auth/sign_in`)).text(); const csrf = signIn.match(/name="csrf-token" content="([^"]+)"/)?.[1] ?? hidden(signIn).authenticity_token; const s = await post(`${MASTO}/auth/sign_in`, { authenticity_token: csrf, "user[email]": process.env.RADAR_EMAIL ?? "radar@occupymedia.cc", "user[password]": process.env.RADAR_PASSWORD }); current.calls.push({ method: "POST", path: `${MASTO}/auth/sign_in`, status: s.status, req: "radar web sign-in" }); if (s.status !== 302 && s.status !== 303) throw new Error(`mastodon sign-in failed: ${s.status}`); let r = await get(redirectUrl); current.calls.push({ method: "GET", path: `${MASTO}/oauth/authorize`, status: r.status, req: "consent page" }); let callback = r.headers.get("location"); if (r.status === 200) { const html = await r.text(); const form = html.split(/