Compare commits
31
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6db2f439b4 | ||
|
|
28603f2301 | ||
|
|
ee799dec98 | ||
|
|
0312767d75 | ||
|
|
46e8c15602 | ||
|
|
f1d6234800 | ||
|
|
a286f8abce | ||
|
|
d985a4c853 | ||
|
|
eb4e44a735 | ||
|
|
3bcde954fb | ||
|
|
328b2ce11a | ||
|
|
f4955bee9d | ||
|
|
570f2dda5a | ||
|
|
19709c2c75 | ||
|
|
f3f6dc8f7a | ||
|
|
0d7e6b52d2 | ||
|
|
2479cbbd0a | ||
|
|
c8d46ef2d9 | ||
|
|
ee65ff358c | ||
|
|
b207d17db8 | ||
|
|
92869d2683 | ||
|
|
d61b3e5978 | ||
|
|
1eeaf4d94f | ||
|
|
e9e9b5a97f | ||
|
|
350ab9f4e8 | ||
|
|
90a98a4306 | ||
|
|
53e15fdd69 | ||
|
|
a0ab22fbf3 | ||
|
|
52099c310d | ||
|
|
61a64cf339 | ||
|
|
afaccf79d1 |
@@ -25,3 +25,4 @@ npm-debug.log*
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
temp/
|
||||
|
||||
+56
-1
@@ -2,7 +2,62 @@
|
||||
|
||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||
|
||||
## Unreleased
|
||||
## events@2.3.1 - 2026-11-18
|
||||
|
||||
- Next.js 16.4.6 (security advisories for 16.2.0–16.4.4; Events wasn't exposed). Also brings
|
||||
`apps/events/package.json` up to the release (it was left at 2.2.0). Details in
|
||||
`apps/events/CHANGELOG.md`.
|
||||
|
||||
## agent@1.0.1 - 2026-11-18
|
||||
|
||||
- A `status` job on the central server is answered by the agent itself (its stats, frps and
|
||||
the agent version). It used to run `crosscode status`, which central servers don't have, and
|
||||
failed with `spawn /usr/local/bin/crosscode ENOENT`.
|
||||
|
||||
## events@2.3.0, contracts@1.3.0, agent@1.0.0 - 2026-11-17
|
||||
|
||||
Phase 1c (authenticator-app sign-in) and phase 1d (docs/AGENT-1.0-PLAN.md): installs, updates and
|
||||
uninstalls from the Hub (Hub 2.1.0) through the agent. Tested end to end on a VM (church server +
|
||||
central server + Hub, AGENT-1.0-PLAN §13 and EVENTS-2.2-PLAN §6).
|
||||
|
||||
### Events (2.3.0)
|
||||
|
||||
- Two-factor with an authenticator app, and recovery codes. The env template, the church export
|
||||
and registering by itself from `HUB_LICENCE_KEY` for installs from the Hub. Details in
|
||||
`apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts (1.3.0)
|
||||
|
||||
- `crosscode.agent-job/1` (fixed job types, strict arguments), `crosscode.agent-report/1`,
|
||||
`crosscode.script-report/1`, `crosscode.agent-stats/1`, the agent join / poll requests,
|
||||
`crosscode.env-template/1` and `crosscode.church-export/1`.
|
||||
- `@crosscode/contracts/signing`: Ed25519 jobs (over canonical JSON) and agent requests, config
|
||||
sealed to a server (X25519 + HKDF + AES-256-GCM), export encryption.
|
||||
|
||||
### Agent (1.0.0)
|
||||
|
||||
- `apps/agent`: polls the Hub, checks every job (pinned key, server, time window, replays, type,
|
||||
arguments) and runs the crosscode script for it; stats every minute; listens on nothing.
|
||||
Install script, systemd unit, self-update with automatic revert.
|
||||
|
||||
### crosscode script
|
||||
|
||||
- `--json` reports and `--config` on every command; `.env` files from each release's env template
|
||||
(appended to, never rewritten, on deploy); `install --frp` with Hub-given ports, a database on
|
||||
another server, and clean-up on failure; frpc.ini blocks; `restart`, `export`, `uninstall`, `purge`.
|
||||
- Fixed in the VM test: `adopt` applies a release's new migrations in the switch-over; a failed
|
||||
migration is marked rolled back so later deploys aren't blocked; frpc is restarted once when its
|
||||
admin lines are first added; a site's PM2 always runs under its own systemd unit (`pm2-<user>`),
|
||||
so restarting or updating the agent never stops a site; tags are fetched with `--force`.
|
||||
|
||||
## events@2.2.0, contracts@1.2.0 - 2026-11-17
|
||||
|
||||
### Events
|
||||
|
||||
- **Cross Events 2.2.0**, the first release from this repo (`apps/events`, ROADMAP-v3 phase 1b):
|
||||
moved in with its history, npm workspaces with one root lockfile, and the `crosscode` script
|
||||
(`deploy`, `status`, `install`, `adopt`) in `scripts/`. Also AI use shown in tokens instead of
|
||||
rand, and everything the backend serves under `/api`. Details in `apps/events/CHANGELOG.md`.
|
||||
|
||||
### Contracts
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Cross Code server agent
|
||||
|
||||
Runs on every server (docs/AGENT-1.0-PLAN.md). It polls Cross Code Hub every 30 seconds for
|
||||
signed jobs, runs the `crosscode` script for them, sends the results, and sends the server's
|
||||
stats every 60 seconds. **It listens on nothing**: no port, no URL; every request goes out to the Hub.
|
||||
|
||||
## Joining a server
|
||||
|
||||
Hub → Servers → **Add server** shows a command with a one-time token (valid an hour):
|
||||
|
||||
```bash
|
||||
curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
|
||||
| sudo bash -s -- --hub https://hub.crosscode.co.za --token <token>
|
||||
```
|
||||
|
||||
Add `--central` on the central (FastPanel) server: there the agent is read-only and only runs
|
||||
`check-ports` and `status`. The script installs Node 24 if needed, the agent in
|
||||
`/opt/crosscode/agent/releases/<version>` (with `current` pointing at it), the `crosscode` script in
|
||||
`/opt/crosscode/tools` (church servers), makes the server's two key pairs, joins, and starts
|
||||
`crosscode-agent.service`.
|
||||
|
||||
## On the server
|
||||
|
||||
| What | Where |
|
||||
|------|-------|
|
||||
| Config (Hub address, server id, the Hub's pinned job key) | `/etc/crosscode/agent.json` |
|
||||
| Private keys (never leave the server) | `/etc/crosscode/agent-ed25519.pem`, `agent-x25519.pem` |
|
||||
| Seen job ids (90 days), unsent reports, exports in progress | `/var/lib/crosscode-agent/` |
|
||||
| A job's opened config, only while it runs | `/run/crosscode-agent/` |
|
||||
| Logs | `journalctl -u crosscode-agent` |
|
||||
|
||||
## Security
|
||||
|
||||
- **Jobs are signed** by the Hub's job key (Ed25519, pinned when joining). The agent refuses a
|
||||
job that's unsigned, for another server, outside its time window, already seen, of an unknown
|
||||
type, or with an argument outside its schema. Refusals are reported to the Hub.
|
||||
- **Only the `crosscode` script runs**, with arguments built from the checked job (an array,
|
||||
never a shell). There's no "run this command" job.
|
||||
- **Config** (database admin, server settings) arrives sealed to this server's X25519 key. It's
|
||||
opened into a root-only file for the job and removed straight after.
|
||||
- **Log lines** sent with a report are filtered for passwords, tokens, keys and licence keys.
|
||||
- **Exports** are encrypted on the server with a new key; the key travels in the job's report
|
||||
so the Hub can email the download link, and the Hub doesn't store it.
|
||||
|
||||
## Updates
|
||||
|
||||
An `update-agent` job builds the new release next to the running one, switches `current`, and
|
||||
restarts. If the new agent hasn't polled the Hub within 150 seconds, `revert.sh` switches back.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
npm run build -w apps/agent # dist/cli.js: one file, everything bundled
|
||||
npm test -w apps/agent # the no-listening-socket test runs on Linux, after a build
|
||||
```
|
||||
@@ -0,0 +1,23 @@
|
||||
# The Cross Code server agent (docs/AGENT-1.0-PLAN.md §3). Root, because the crosscode script it
|
||||
# runs needs root (PostgreSQL, PM2 for each app user, frpc). It listens on nothing.
|
||||
[Unit]
|
||||
Description=Cross Code server agent
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/node /opt/crosscode/agent/current/apps/agent/dist/cli.js run
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
RuntimeDirectory=crosscode-agent
|
||||
RuntimeDirectoryMode=0700
|
||||
StateDirectory=crosscode-agent
|
||||
StateDirectoryMode=0700
|
||||
Environment=NODE_ENV=production
|
||||
# Logs: journalctl -u crosscode-agent
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env bash
|
||||
# Installs the Cross Code server agent and joins this server to the Hub
|
||||
# (docs/AGENT-1.0-PLAN.md §3). Hub → Servers → Add server shows the command, with a one-time token:
|
||||
#
|
||||
# curl -fsSL https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/apps/agent/deploy/install.sh \
|
||||
# | sudo bash -s -- --hub https://hub.crosscode.co.za --token <token> [--central]
|
||||
#
|
||||
# Church servers also get the crosscode script (/opt/crosscode/tools, linked as
|
||||
# /usr/local/bin/crosscode). The central server (--central) only gets the agent, which is
|
||||
# read-only there. Running it again updates nothing that's there already; use --force to join again.
|
||||
set -Eeuo pipefail
|
||||
|
||||
REPO="${CROSSCODE_REPO:-https://c-git.crosscode.co.za/joshua/crosscode-platform.git}"
|
||||
ROOT=/opt/crosscode/agent
|
||||
TOOLS=/opt/crosscode/tools
|
||||
HUB="" TOKEN="" MODE=church VERSION="" FORCE=""
|
||||
|
||||
die() { printf '!!> %s\n' "$*" >&2; exit 1; }
|
||||
step() { printf '==> %s\n' "$*"; }
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--hub) HUB="$2"; shift 2 ;;
|
||||
--token) TOKEN="$2"; shift 2 ;;
|
||||
--central) MODE=central; shift ;;
|
||||
--version) VERSION="$2"; shift 2 ;;
|
||||
--force) FORCE=--force; shift ;;
|
||||
*) die "Unknown option $1" ;;
|
||||
esac
|
||||
done
|
||||
[ "$(id -u)" = 0 ] || die "Run as root (sudo bash -s -- …)."
|
||||
[[ "$HUB" =~ ^https?:// ]] || die "--hub <url> is required."
|
||||
[[ "$TOKEN" =~ ^[A-Za-z0-9_-]{32,128}$ ]] || die "--token is required (Hub → Servers → Add server)."
|
||||
[ -z "$VERSION" ] || [[ "$VERSION" =~ ^agent@[0-9]+\.[0-9]+\.[0-9]+$ ]] || die "--version: expected agent@x.y.z."
|
||||
|
||||
step "System packages"
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -q
|
||||
apt-get install -y -q git curl ca-certificates
|
||||
if ! command -v node >/dev/null || [ "$(node -p 'process.versions.node.split(".")[0]')" -lt 24 ]; then
|
||||
step "Node.js 24"
|
||||
curl -fsSL https://deb.nodesource.com/setup_24.x | bash -
|
||||
apt-get install -y -q nodejs
|
||||
fi
|
||||
|
||||
if [ -z "$VERSION" ]; then
|
||||
VERSION="$(git ls-remote --tags --refs "$REPO" 'agent@*' | sed 's#.*refs/tags/##' | sort -t@ -k2 -V | tail -n 1)"
|
||||
[ -n "$VERSION" ] || die "No agent@x.y.z release yet."
|
||||
fi
|
||||
DIR="$ROOT/releases/${VERSION#agent@}"
|
||||
|
||||
step "Agent $VERSION in $DIR"
|
||||
mkdir -p "$ROOT/releases"
|
||||
chmod 755 /opt/crosscode "$ROOT" 2>/dev/null || true
|
||||
if [ ! -d "$DIR/.git" ]; then
|
||||
git clone --quiet --depth 1 --branch "$VERSION" "$REPO" "$DIR"
|
||||
fi
|
||||
(
|
||||
cd "$DIR"
|
||||
NODE_ENV=development npm ci --no-audit --no-fund --include=dev --include-workspace-root -w packages/contracts -w apps/agent
|
||||
npm run build -w packages/contracts
|
||||
npm run build -w apps/agent
|
||||
)
|
||||
[ "$(node "$DIR/apps/agent/dist/cli.js" version)" = "${VERSION#agent@}" ] || die "The build doesn't report $VERSION."
|
||||
ln -sfn "$DIR" "$ROOT/current"
|
||||
install -m 755 "$DIR/apps/agent/deploy/revert.sh" "$ROOT/revert.sh"
|
||||
|
||||
if [ "$MODE" = church ]; then
|
||||
step "The crosscode script ($TOOLS)"
|
||||
[ -d "$TOOLS/.git" ] || git clone --quiet "$REPO" "$TOOLS"
|
||||
ln -sfn "$TOOLS/scripts/crosscode" /usr/local/bin/crosscode
|
||||
fi
|
||||
|
||||
step "Joining the Hub ($HUB)"
|
||||
mkdir -p /etc/crosscode /var/lib/crosscode-agent
|
||||
chmod 700 /etc/crosscode /var/lib/crosscode-agent
|
||||
args=(join --hub "$HUB" --token "$TOKEN")
|
||||
[ "$MODE" = central ] && args+=(--central)
|
||||
[ -n "$FORCE" ] && args+=("$FORCE")
|
||||
if [ -f /etc/crosscode/agent.json ] && [ -z "$FORCE" ]; then
|
||||
echo " Already joined (/etc/crosscode/agent.json); keeping it."
|
||||
else
|
||||
node "$ROOT/current/apps/agent/dist/cli.js" "${args[@]}"
|
||||
fi
|
||||
|
||||
step "systemd"
|
||||
install -m 644 "$DIR/apps/agent/deploy/crosscode-agent.service" /etc/systemd/system/crosscode-agent.service
|
||||
systemctl daemon-reload
|
||||
systemctl enable --now crosscode-agent
|
||||
systemctl restart crosscode-agent
|
||||
step "Done: the server shows on Hub → Servers within a minute (journalctl -u crosscode-agent)."
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
# Started by a one-shot systemd timer after an agent update (src/update.ts). If the new agent
|
||||
# hasn't polled the Hub by now, update-pending.json is still there: switch back to the previous
|
||||
# release and restart. Copied to /opt/crosscode/agent/revert.sh by install.sh.
|
||||
set -euo pipefail
|
||||
ROOT=/opt/crosscode/agent
|
||||
PENDING=/var/lib/crosscode-agent/update-pending.json
|
||||
[ -f "$PENDING" ] || exit 0
|
||||
[ -L "$ROOT/previous" ] || { echo "crosscode-agent revert: no previous release" >&2; exit 1; }
|
||||
ln -sfn "$(readlink "$ROOT/previous")" "$ROOT/current.tmp"
|
||||
mv -T "$ROOT/current.tmp" "$ROOT/current"
|
||||
rm -f "$PENDING"
|
||||
systemctl restart crosscode-agent
|
||||
echo "crosscode-agent revert: the new agent didn't poll in time; back on $(readlink "$ROOT/current")" >&2
|
||||
@@ -0,0 +1,7 @@
|
||||
module.exports = {
|
||||
testEnvironment: "node",
|
||||
testMatch: ["<rootDir>/tests/**/*.test.ts"],
|
||||
transform: { "^.+\\.ts$": ["ts-jest", { tsconfig: { module: "commonjs", moduleResolution: "node", isolatedModules: true } }] },
|
||||
moduleFileExtensions: ["ts", "js", "json"],
|
||||
modulePathIgnorePatterns: ["<rootDir>/dist/"],
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
{
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.0.1",
|
||||
"private": true,
|
||||
"description": "The server agent: runs the crosscode script for signed jobs from Cross Code Hub, reports stats (docs/AGENT-1.0-PLAN.md)",
|
||||
"license": "UNLICENSED",
|
||||
"bin": { "crosscode-agent": "./dist/cli.js" },
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit",
|
||||
"test": "jest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"engines": { "node": ">=24" }
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* The central server (AGENT-1.0-PLAN §6): read-only checks of frps for `check-ports`. Nothing on
|
||||
* the central server is ever changed: no frps edits, no firewall, no FastPanel.
|
||||
*/
|
||||
|
||||
export interface FrpsSettings {
|
||||
proxyBindAddr: string | null;
|
||||
allowPorts: string | null;
|
||||
}
|
||||
|
||||
/** frps.ini's [common] proxy_bind_addr and allow_ports (null when not set or no file). */
|
||||
export function parseFrpsIni(text: string): FrpsSettings {
|
||||
let inCommon = false;
|
||||
const out: FrpsSettings = { proxyBindAddr: null, allowPorts: null };
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (/^\[.*\]$/.test(line)) { inCommon = line === "[common]"; continue; }
|
||||
if (!inCommon || line.startsWith("#") || line.startsWith(";")) continue;
|
||||
const m = /^([a-z_]+)\s*=\s*(.*)$/.exec(line);
|
||||
if (!m) continue;
|
||||
if (m[1] === "proxy_bind_addr") out.proxyBindAddr = m[2]!.trim() || null;
|
||||
if (m[1] === "allow_ports") out.allowPorts = m[2]!.trim() || null;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function readFrps(file = paths.frpsIni): FrpsSettings | null {
|
||||
try {
|
||||
return parseFrpsIni(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a port is inside allow_ports ("2000-3000,3001,4000-5000"); no allow_ports allows all. */
|
||||
export function portAllowed(port: number, allowPorts: string | null): boolean {
|
||||
if (!allowPorts) return true;
|
||||
return allowPorts.split(",").map((s) => s.trim()).filter(Boolean).some((range) => {
|
||||
const [a, b] = range.split("-").map((n) => Number(n.trim()));
|
||||
if (!Number.isFinite(a)) return false;
|
||||
return b === undefined ? port === a : Number.isFinite(b) && port >= a! && port <= b;
|
||||
});
|
||||
}
|
||||
|
||||
/** Listening TCP sockets from `ss -ltnH`: port → local addresses. */
|
||||
export function parseSs(text: string): Map<number, string[]> {
|
||||
const out = new Map<number, string[]>();
|
||||
for (const line of text.split("\n")) {
|
||||
const cols = line.trim().split(/\s+/);
|
||||
const local = cols[3];
|
||||
if (!local) continue;
|
||||
const i = local.lastIndexOf(":");
|
||||
const port = Number(local.slice(i + 1));
|
||||
const addr = local.slice(0, i).replace(/^\[|\]$/g, "").replace(/%.*$/, "");
|
||||
if (!Number.isFinite(port)) continue;
|
||||
out.set(port, [...(out.get(port) ?? []), addr]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const LOOPBACK = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
|
||||
|
||||
export interface PortCheck {
|
||||
port: number;
|
||||
allowed: boolean;
|
||||
listening: boolean;
|
||||
loopbackOnly: boolean;
|
||||
ok: boolean;
|
||||
}
|
||||
|
||||
export function checkPorts(ports: number[], frps: FrpsSettings | null, listening: Map<number, string[]>): { ports: PortCheck[]; proxyBindAddr: string | null; warnings: string[] } {
|
||||
const warnings: string[] = [];
|
||||
if (!frps) warnings.push(`No frps.ini at ${paths.frpsIni}.`);
|
||||
const bind = frps?.proxyBindAddr ?? null;
|
||||
if (frps && (!bind || !LOOPBACK.has(bind))) warnings.push(`proxy_bind_addr is ${bind ? `"${bind}"` : "not set"}: tunnels can be reached straight from the internet. Set proxy_bind_addr = 127.0.0.1 in frps.ini.`);
|
||||
const results = ports.map((port) => {
|
||||
const addrs = listening.get(port) ?? [];
|
||||
const allowed = portAllowed(port, frps?.allowPorts ?? null);
|
||||
const loopbackOnly = addrs.length > 0 && addrs.every((a) => LOOPBACK.has(a));
|
||||
return { port, allowed, listening: addrs.length > 0, loopbackOnly, ok: allowed && addrs.length > 0 && loopbackOnly };
|
||||
});
|
||||
for (const r of results) {
|
||||
if (!r.allowed) warnings.push(`Port ${r.port} isn't in allow_ports.`);
|
||||
else if (!r.listening) warnings.push(`Port ${r.port} isn't open in frps (is the church server's frpc connected?).`);
|
||||
else if (!r.loopbackOnly) warnings.push(`Port ${r.port} is open on more than 127.0.0.1.`);
|
||||
}
|
||||
return { ports: results, proxyBindAddr: bind, warnings };
|
||||
}
|
||||
|
||||
export function listeningNow(): Promise<Map<number, string[]>> {
|
||||
return new Promise((resolve) => {
|
||||
execFile("ss", ["-ltnH"], { timeout: 10_000 }, (err, stdout) => resolve(err ? new Map() : parseSs(String(stdout))));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { generateEd25519, generateX25519 } from "@crosscode/contracts/signing";
|
||||
import { configFile, ed25519File, loadConfig, saveConfig, writePrivate, x25519File } from "./config";
|
||||
import { hubClient, postUnsigned } from "./hub";
|
||||
import { Agent } from "./loop";
|
||||
import { AGENT_VERSION } from "./stats";
|
||||
|
||||
/**
|
||||
* crosscode-agent (AGENT-1.0-PLAN §3)
|
||||
* crosscode-agent join --hub https://hub.crosscode.co.za --token <one-time token> [--central]
|
||||
* crosscode-agent run what systemd runs (crosscode-agent.service)
|
||||
* crosscode-agent version
|
||||
*/
|
||||
|
||||
const USAGE = `crosscode-agent ${AGENT_VERSION}
|
||||
|
||||
crosscode-agent join --hub <url> --token <token> [--central] [--force]
|
||||
Join this server to the Hub with a one-time token (Hub → Servers → Add server).
|
||||
Makes the server's key pairs; the private keys never leave it.
|
||||
crosscode-agent run poll the Hub for jobs and send stats (run by systemd)
|
||||
crosscode-agent version
|
||||
`;
|
||||
|
||||
function flag(args: string[], name: string): string | undefined {
|
||||
const i = args.indexOf(name);
|
||||
return i >= 0 ? args[i + 1] : undefined;
|
||||
}
|
||||
|
||||
export async function join(args: string[]): Promise<void> {
|
||||
const hub = flag(args, "--hub");
|
||||
const token = flag(args, "--token");
|
||||
const mode: agent.AgentMode = args.includes("--central") ? "central" : "church";
|
||||
if (!hub || !/^https?:\/\//.test(hub)) throw new Error("--hub <url> is required (https://hub.crosscode.co.za).");
|
||||
if (!token) throw new Error("--token <token> is required (Hub → Servers → Add server).");
|
||||
if (fs.existsSync(configFile()) && !args.includes("--force")) {
|
||||
throw new Error(`This server has already joined (${configFile()}). Use --force to join again (the Hub then sees a new server).`);
|
||||
}
|
||||
const ed = generateEd25519();
|
||||
const x = generateX25519();
|
||||
const reply = agent.joinResponseSchema.parse(await postUnsigned(hub, "/api/agent/v1/join", {
|
||||
agentApiVersion: agent.AGENT_API_VERSION,
|
||||
token,
|
||||
mode,
|
||||
hostname: os.hostname().slice(0, 253),
|
||||
agentVersion: AGENT_VERSION,
|
||||
publicKeys: { ed25519: ed.publicKey, x25519: x.publicKey },
|
||||
}));
|
||||
writePrivate(ed25519File(), ed.privateKeyPem);
|
||||
writePrivate(x25519File(), x.privateKeyPem);
|
||||
saveConfig({ hubUrl: hub, serverId: reply.serverId, mode, hubJobKey: reply.hubJobKey, pollSeconds: reply.pollSeconds, statsSeconds: reply.statsSeconds, joinedAt: new Date().toISOString() });
|
||||
console.log(`Joined the Hub as ${reply.serverId} (${mode}). Start the agent: systemctl enable --now crosscode-agent`);
|
||||
}
|
||||
|
||||
export async function main(argv = process.argv.slice(2)): Promise<void> {
|
||||
const [command, ...args] = argv;
|
||||
switch (command) {
|
||||
case "version":
|
||||
case "--version":
|
||||
console.log(AGENT_VERSION);
|
||||
return;
|
||||
case "join":
|
||||
await join(args);
|
||||
return;
|
||||
case "run": {
|
||||
if (process.getuid && process.getuid() !== 0 && !process.env.CROSSCODE_AGENT_ALLOW_NON_ROOT) {
|
||||
throw new Error("Run the agent as root (it runs crosscode, which needs root).");
|
||||
}
|
||||
const { config, keys } = loadConfig();
|
||||
const a = new Agent({ config, keys, hub: hubClient(config, keys) });
|
||||
for (const sig of ["SIGTERM", "SIGINT"] as const) process.on(sig, () => { a.stop(); setTimeout(() => process.exit(0), 1000).unref(); });
|
||||
await a.start();
|
||||
return;
|
||||
}
|
||||
default:
|
||||
process.stdout.write(USAGE);
|
||||
if (command && command !== "help" && command !== "--help") process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((e) => {
|
||||
console.error(`crosscode-agent: ${(e as Error).message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
|
||||
/**
|
||||
* The `crosscode` arguments for a job (AGENT-1.0-PLAN §4): built from the checked arguments only,
|
||||
* as an array passed straight to the process (never through a shell). Jobs the agent handles
|
||||
* itself (update-agent, check-ports) have none.
|
||||
*
|
||||
* `--config <file>` is added by the runner when the job brings config; `--json` always.
|
||||
*/
|
||||
export function crosscodeArgs(job: agent.AgentJob, opts: { exportFile?: string } = {}): string[] | null {
|
||||
switch (job.type) {
|
||||
case "install": {
|
||||
const a = job.args;
|
||||
if (a.products.length !== 1 || a.products[0] !== "events") throw new Error("This agent can only install Events so far.");
|
||||
const domain = a.domains.events;
|
||||
const ports = a.ports.events;
|
||||
if (!domain || !ports) throw new Error("An Events install needs its domain and ports.");
|
||||
// The church's address: the Events domain without "events." (crosscode uses it for the
|
||||
// church.env ADDRESS; the domain itself goes in --events-domain).
|
||||
const address = domain.startsWith("events.") ? domain.slice("events.".length) : domain;
|
||||
const out = ["install", a.church, "--products", "events", "--domain", address, "--events-domain", domain,
|
||||
"--api-port", String(ports.api), "--web-port", String(ports.web), "--frp"];
|
||||
const v = a.versions?.events;
|
||||
if (v) out.push("--version", v);
|
||||
return out;
|
||||
}
|
||||
case "add-product":
|
||||
return ["add", job.args.church, job.args.product];
|
||||
case "deploy": {
|
||||
const out = ["deploy", job.args.church, ...job.args.products];
|
||||
for (const v of job.args.versions ?? []) out.push("--version", v);
|
||||
if (job.args.check) out.push("--check");
|
||||
return out;
|
||||
}
|
||||
case "adopt": {
|
||||
const out = ["adopt", job.args.church, "--events-dir", job.args.eventsDir];
|
||||
if (job.args.version) out.push("--version", job.args.version);
|
||||
if (job.args.address) out.push("--address", job.args.address);
|
||||
return out;
|
||||
}
|
||||
case "adopt-undo":
|
||||
return ["adopt", job.args.church, "--undo"];
|
||||
case "restart":
|
||||
return ["restart", job.args.church, ...(job.args.product ? [job.args.product] : [])];
|
||||
case "export":
|
||||
if (!opts.exportFile) throw new Error("export needs a file to write");
|
||||
return ["export", job.args.church, "--out", opts.exportFile];
|
||||
case "uninstall":
|
||||
return ["uninstall", job.args.church, "--confirm", job.args.church];
|
||||
case "purge":
|
||||
return ["purge", job.args.church, "--confirm", job.args.church];
|
||||
case "status":
|
||||
return ["status", ...(job.args.church ? [job.args.church] : []), "--no-fetch"];
|
||||
case "update-agent":
|
||||
case "check-ports":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { z } from "zod";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { publicKeyOf } from "@crosscode/contracts/signing";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/** /etc/crosscode/agent.json, written by `crosscode-agent join`. No secrets: the keys are files next to it. */
|
||||
export const agentConfigSchema = z.object({
|
||||
hubUrl: z.url({ protocol: /^https?$/ }),
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
mode: agent.agentModeSchema,
|
||||
/** The Hub's job-signing key, pinned when joining. */
|
||||
hubJobKey: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
|
||||
pollSeconds: z.int().min(5).max(600).default(30),
|
||||
statsSeconds: z.int().min(15).max(3600).default(60),
|
||||
joinedAt: z.string(),
|
||||
});
|
||||
export type AgentConfig = z.infer<typeof agentConfigSchema>;
|
||||
|
||||
export interface Keys {
|
||||
ed25519Pem: string;
|
||||
x25519Pem: string;
|
||||
}
|
||||
|
||||
export const configFile = () => path.join(paths.configDir, "agent.json");
|
||||
export const ed25519File = () => path.join(paths.configDir, "agent-ed25519.pem");
|
||||
export const x25519File = () => path.join(paths.configDir, "agent-x25519.pem");
|
||||
|
||||
/** Writes a file only root can read, atomically. */
|
||||
export function writePrivate(file: string, text: string): void {
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${file}.tmp-${process.pid}`;
|
||||
fs.writeFileSync(tmp, text, { mode: 0o600 });
|
||||
fs.renameSync(tmp, file);
|
||||
}
|
||||
|
||||
export function loadConfig(): { config: AgentConfig; keys: Keys } {
|
||||
const config = agentConfigSchema.parse(JSON.parse(fs.readFileSync(configFile(), "utf8")));
|
||||
const keys = { ed25519Pem: fs.readFileSync(ed25519File(), "utf8"), x25519Pem: fs.readFileSync(x25519File(), "utf8") };
|
||||
// A broken pair would sign requests the Hub can't check; better to stop at start.
|
||||
publicKeyOf(keys.ed25519Pem);
|
||||
publicKeyOf(keys.x25519Pem);
|
||||
return { config, keys };
|
||||
}
|
||||
|
||||
export function saveConfig(config: AgentConfig): void {
|
||||
writePrivate(configFile(), `${JSON.stringify(config, null, 2)}\n`);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import { signAgentRequest } from "@crosscode/contracts/signing";
|
||||
import type { AgentConfig, Keys } from "./config";
|
||||
|
||||
/**
|
||||
* Requests to the Hub. The agent only ever makes outgoing requests (it listens on nothing,
|
||||
* AGENT-1.0-PLAN §2 rule 1); every one after joining is signed with the server's Ed25519 key.
|
||||
*/
|
||||
|
||||
export class HubRequestError extends Error {
|
||||
constructor(message: string, readonly status: number, readonly code: string | null) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export type Fetch = typeof fetch;
|
||||
|
||||
export interface HubClient {
|
||||
post(path: string, body: unknown): Promise<unknown>;
|
||||
put(path: string, body: Uint8Array, contentType: string): Promise<unknown>;
|
||||
}
|
||||
|
||||
const TIMEOUT_MS = 30_000;
|
||||
const UPLOAD_TIMEOUT_MS = 10 * 60_000;
|
||||
|
||||
async function send(fetcher: Fetch, url: string, init: RequestInit, timeoutMs: number): Promise<unknown> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetcher(url, { ...init, signal: AbortSignal.timeout(timeoutMs) });
|
||||
} catch (e) {
|
||||
throw new HubRequestError(`The Hub can't be reached: ${(e as Error).message}`, 0, "HUB_UNREACHABLE");
|
||||
}
|
||||
if (res.status === 204) return null;
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await res.json();
|
||||
} catch {
|
||||
body = null;
|
||||
}
|
||||
if (!res.ok) {
|
||||
const b = (body ?? {}) as { message?: string; code?: string };
|
||||
throw new HubRequestError(b.message || `The Hub answered ${res.status}`, res.status, b.code ?? null);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/** An unsigned request (only `join`, where the one-time token is the proof). */
|
||||
export function postUnsigned(hubUrl: string, path: string, body: unknown, fetcher: Fetch = fetch): Promise<unknown> {
|
||||
return send(fetcher, `${hubUrl.replace(/\/$/, "")}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "user-agent": "crosscode-agent" },
|
||||
body: JSON.stringify(body),
|
||||
}, TIMEOUT_MS);
|
||||
}
|
||||
|
||||
export function hubClient(config: AgentConfig, keys: Keys, fetcher: Fetch = fetch): HubClient {
|
||||
const base = config.hubUrl.replace(/\/$/, "");
|
||||
const signed = (raw: string | Uint8Array) => signAgentRequest({ serverId: config.serverId, privateKeyPem: keys.ed25519Pem, rawBody: raw });
|
||||
return {
|
||||
post(path, body) {
|
||||
const raw = JSON.stringify(body);
|
||||
return send(fetcher, `${base}${path}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "user-agent": "crosscode-agent", ...signed(raw) },
|
||||
body: raw,
|
||||
}, TIMEOUT_MS);
|
||||
},
|
||||
put(path, body, contentType) {
|
||||
return send(fetcher, `${base}${path}`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": contentType, "user-agent": "crosscode-agent", ...signed(body) },
|
||||
body,
|
||||
}, UPLOAD_TIMEOUT_MS);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { encryptExport } from "@crosscode/contracts/signing";
|
||||
import { checkPorts, listeningNow, readFrps } from "./central";
|
||||
import { crosscodeArgs } from "./command";
|
||||
import type { AgentConfig, Keys } from "./config";
|
||||
import { type HubClient, HubRequestError } from "./hub";
|
||||
import { paths } from "./paths";
|
||||
import { runCrosscode, type RunResult } from "./runner";
|
||||
import { AGENT_VERSION, collectStats } from "./stats";
|
||||
import { confirmUpdate, updateAgent } from "./update";
|
||||
import { checkJob, SeenJobs } from "./verify";
|
||||
|
||||
/**
|
||||
* The agent's life: poll the Hub every 30 s for jobs due, send stats every 60 s, run one job at a
|
||||
* time and send each result. Reports that can't be sent are kept in an outbox and sent later, so
|
||||
* a Hub outage never loses a job's result. Nothing here listens: every request goes out.
|
||||
*/
|
||||
|
||||
const log = (...a: unknown[]) => console.log(new Date().toISOString(), ...a);
|
||||
|
||||
export interface AgentDeps {
|
||||
config: AgentConfig;
|
||||
keys: Keys;
|
||||
hub: HubClient;
|
||||
seen?: SeenJobs;
|
||||
/** For tests: replaces running crosscode and the stats. */
|
||||
run?: (args: string[], job: agent.AgentJob) => Promise<RunResult>;
|
||||
stats?: () => Promise<agent.AgentStats>;
|
||||
now?: () => Date;
|
||||
}
|
||||
|
||||
const outboxDir = () => path.join(paths.stateDir, "outbox");
|
||||
|
||||
function report(job: { id: string; type: agent.JobType }, serverId: string, r: Omit<RunResult, "log"> & { log?: string[] }): agent.AgentReport {
|
||||
return {
|
||||
schema: "crosscode.agent-report/1",
|
||||
jobId: job.id,
|
||||
serverId,
|
||||
type: job.type,
|
||||
status: r.status,
|
||||
startedAt: r.startedAt,
|
||||
finishedAt: r.finishedAt,
|
||||
steps: r.steps.slice(0, 200),
|
||||
result: r.result,
|
||||
...(r.message ? { message: r.message.slice(0, 2000) } : {}),
|
||||
log: (r.log ?? []).slice(-200),
|
||||
};
|
||||
}
|
||||
|
||||
export class Agent {
|
||||
private seen: SeenJobs;
|
||||
private stopped = false;
|
||||
private confirmed = false;
|
||||
private failures = 0;
|
||||
|
||||
constructor(private deps: AgentDeps) {
|
||||
this.seen = deps.seen ?? new SeenJobs();
|
||||
}
|
||||
|
||||
private now(): Date {
|
||||
return this.deps.now?.() ?? new Date();
|
||||
}
|
||||
|
||||
/** Sends a report, or keeps it in the outbox to send later. */
|
||||
async send(r: agent.AgentReport): Promise<void> {
|
||||
try {
|
||||
await this.deps.hub.post("/api/agent/v1/report", r);
|
||||
} catch (e) {
|
||||
log(`[report] ${r.jobId}: couldn't send (${(e as Error).message}); kept to send later.`);
|
||||
fs.mkdirSync(outboxDir(), { recursive: true, mode: 0o700 });
|
||||
fs.writeFileSync(path.join(outboxDir(), `${r.jobId}.json`), JSON.stringify(r), { mode: 0o600 });
|
||||
}
|
||||
}
|
||||
|
||||
async flushOutbox(): Promise<void> {
|
||||
let files: string[];
|
||||
try { files = fs.readdirSync(outboxDir()).filter((f) => f.endsWith(".json")); } catch { return; }
|
||||
for (const f of files) {
|
||||
const file = path.join(outboxDir(), f);
|
||||
try {
|
||||
await this.deps.hub.post("/api/agent/v1/report", JSON.parse(fs.readFileSync(file, "utf8")));
|
||||
fs.rmSync(file, { force: true });
|
||||
} catch (e) {
|
||||
// A report the Hub refuses outright (4xx) would never go: drop it rather than retry forever.
|
||||
if (e instanceof HubRequestError && e.status >= 400 && e.status < 500) fs.rmSync(file, { force: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One poll: fetch the jobs due and run them, one after the other. Returns the next delay (s). */
|
||||
async pollOnce(): Promise<number> {
|
||||
const { config } = this.deps;
|
||||
let reply: { jobs: unknown[]; pollSeconds: number };
|
||||
try {
|
||||
reply = agent.pollResponseSchema.parse(await this.deps.hub.post("/api/agent/v1/poll", {
|
||||
agentApiVersion: agent.AGENT_API_VERSION, agentVersion: AGENT_VERSION, mode: config.mode, runningJobId: null,
|
||||
}));
|
||||
} catch (e) {
|
||||
this.failures++;
|
||||
const delay = Math.min(300, config.pollSeconds * 2 ** Math.min(this.failures, 4));
|
||||
log(`[poll] ${(e as Error).message}; next try in ${delay}s.`);
|
||||
return delay;
|
||||
}
|
||||
this.failures = 0;
|
||||
if (!this.confirmed) {
|
||||
confirmUpdate();
|
||||
this.confirmed = true;
|
||||
}
|
||||
await this.flushOutbox();
|
||||
for (const raw of reply.jobs) {
|
||||
if (this.stopped) break;
|
||||
await this.handle(raw);
|
||||
}
|
||||
return reply.pollSeconds || config.pollSeconds;
|
||||
}
|
||||
|
||||
async handle(raw: unknown): Promise<void> {
|
||||
const { config } = this.deps;
|
||||
const verdict = checkJob(raw, config, this.seen, this.now());
|
||||
const at = this.now().toISOString();
|
||||
if (!verdict.ok) {
|
||||
log(`[job] ${verdict.id ?? "(no id)"} ${verdict.status}: ${verdict.message}`);
|
||||
if (verdict.id && verdict.type && !this.seen.has(verdict.id)) {
|
||||
this.seen.add(verdict.id);
|
||||
await this.send(report({ id: verdict.id, type: verdict.type }, config.serverId, { status: verdict.status, steps: [], result: {}, message: verdict.message, startedAt: at, finishedAt: at }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const job = verdict.job;
|
||||
// Seen before it runs, so a crash part-way can never run it twice.
|
||||
this.seen.add(job.id);
|
||||
log(`[job] ${job.id} ${job.type} ${JSON.stringify(job.args)}`);
|
||||
const result = await this.execute(job);
|
||||
log(`[job] ${job.id} ${result.status}${result.message ? `: ${result.message}` : ""}`);
|
||||
await this.send(report(job, config.serverId, result));
|
||||
if ((result as RunResult & { restart?: boolean }).restart) {
|
||||
log("[agent] Exiting so systemd starts the new version.");
|
||||
this.stopped = true;
|
||||
setTimeout(() => process.exit(0), 500);
|
||||
}
|
||||
}
|
||||
|
||||
private async execute(job: agent.AgentJob): Promise<RunResult & { restart?: boolean }> {
|
||||
const startedAt = this.now().toISOString();
|
||||
const limit = agent.JOB_TIME_LIMIT_MINUTES[job.type];
|
||||
try {
|
||||
switch (job.type) {
|
||||
case "update-agent": {
|
||||
const u = await updateAgent(job.args.version, AGENT_VERSION);
|
||||
return { status: u.status, steps: u.steps, result: u.result, message: u.message, log: [], startedAt, finishedAt: new Date().toISOString(), restart: u.restart };
|
||||
}
|
||||
case "check-ports": {
|
||||
const res = checkPorts(job.args.ports, readFrps(), await listeningNow());
|
||||
const ok = res.ports.every((p) => p.ok) && res.warnings.length === 0;
|
||||
return { status: ok ? "succeeded" : "failed", steps: [], result: res as unknown as Record<string, unknown>, message: res.warnings.join(" ") || undefined, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
case "export":
|
||||
return await this.runExport(job, limit);
|
||||
case "status":
|
||||
// The central server has no crosscode script (install.sh --central): its status is the
|
||||
// agent's own stats, with frps.
|
||||
if (this.deps.config.mode === "central") {
|
||||
const stats = await (this.deps.stats ?? (() => collectStats("central")))();
|
||||
const warning = stats.central && !stats.central.frpsRunning ? "frps isn't running." : undefined;
|
||||
return { status: "succeeded", steps: [], result: { stats } as unknown as Record<string, unknown>, message: warning, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
return await this.run(crosscodeArgs(job)!, job, limit);
|
||||
default: {
|
||||
const args = crosscodeArgs(job);
|
||||
if (!args) throw new Error(`No command for ${job.type}`);
|
||||
return await this.run(args, job, limit);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
return { status: "failed", steps: [], result: {}, message: (e as Error).message, log: [], startedAt, finishedAt: new Date().toISOString() };
|
||||
}
|
||||
}
|
||||
|
||||
private run(args: string[], job: agent.AgentJob, limit: number): Promise<RunResult> {
|
||||
if (this.deps.run) return this.deps.run(args, job);
|
||||
return runCrosscode({ args, sealedConfig: job.config ?? null, x25519Pem: this.deps.keys.x25519Pem, timeLimitMinutes: limit });
|
||||
}
|
||||
|
||||
/**
|
||||
* export: crosscode writes the ZIP, the agent encrypts it with a fresh key and uploads it. The
|
||||
* key goes to the Hub only in this job's report, so it can email the download link; the Hub
|
||||
* doesn't keep it (AGENT-1.0-PLAN §9).
|
||||
*/
|
||||
private async runExport(job: Extract<agent.AgentJob, { type: "export" }>, limit: number): Promise<RunResult> {
|
||||
const dir = path.join(paths.stateDir, "exports");
|
||||
fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const zip = path.join(dir, `${job.args.exportId}.zip`);
|
||||
fs.rmSync(zip, { force: true });
|
||||
try {
|
||||
const r = await this.run(crosscodeArgs(job, { exportFile: zip })!, job, limit);
|
||||
if (r.status !== "succeeded") return r;
|
||||
const { key, file } = encryptExport(fs.readFileSync(zip));
|
||||
await this.deps.hub.put(`/api/agent/v1/exports/${job.args.exportId}`, file, "application/octet-stream");
|
||||
return { ...r, result: { ...r.result, file: undefined, encryptedBytes: file.length, key } };
|
||||
} finally {
|
||||
fs.rmSync(zip, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async statsOnce(): Promise<void> {
|
||||
try {
|
||||
const stats = await (this.deps.stats ?? (() => collectStats(this.deps.config.mode)))();
|
||||
await this.deps.hub.post("/api/agent/v1/stats", stats);
|
||||
} catch (e) {
|
||||
log(`[stats] ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs until stopped: polls and stats on their own timers, never at the same time as a job. */
|
||||
async start(): Promise<void> {
|
||||
log(`[agent] ${AGENT_VERSION} (${this.deps.config.mode}) for ${this.deps.config.serverId}, Hub ${this.deps.config.hubUrl}`);
|
||||
let nextStats = 0;
|
||||
while (!this.stopped) {
|
||||
if (Date.now() >= nextStats) {
|
||||
await this.statsOnce();
|
||||
nextStats = Date.now() + this.deps.config.statsSeconds * 1000;
|
||||
}
|
||||
const delay = await this.pollOnce();
|
||||
await new Promise((r) => setTimeout(r, Math.max(5, Math.min(delay, this.deps.config.statsSeconds)) * 1000));
|
||||
}
|
||||
}
|
||||
|
||||
stop(): void {
|
||||
this.stopped = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
/**
|
||||
* Where the agent keeps things on a server (docs/AGENT-1.0-PLAN.md §3). Each can be moved with an
|
||||
* environment variable, which the tests use.
|
||||
*/
|
||||
const env = (name: string, fallback: string): string => process.env[name] || fallback;
|
||||
|
||||
export const paths = {
|
||||
/** agent.json and the two private keys, root only (mode 600). */
|
||||
get configDir() { return env("CROSSCODE_AGENT_CONFIG_DIR", "/etc/crosscode"); },
|
||||
/** Seen job ids (replay protection) and exports waiting to upload. */
|
||||
get stateDir() { return env("CROSSCODE_AGENT_STATE_DIR", "/var/lib/crosscode-agent"); },
|
||||
/** A job's opened config, only while the job runs (tmpfs). */
|
||||
get runDir() { return env("CROSSCODE_AGENT_RUN_DIR", "/run/crosscode-agent"); },
|
||||
/** The crosscode script (a checkout of the monorepo in /opt/crosscode/tools). */
|
||||
get crosscode() { return env("CROSSCODE_BIN", "/usr/local/bin/crosscode"); },
|
||||
/** Agent releases: releases/<version>/ (checkouts), current → the running one, previous. */
|
||||
get agentRoot() { return env("CROSSCODE_AGENT_ROOT", "/opt/crosscode/agent"); },
|
||||
/** frps.ini on the central server. */
|
||||
get frpsIni() { return env("CROSSCODE_FRPS_INI", "/etc/frp/frps.ini"); },
|
||||
/** The churches on a church server. */
|
||||
get sites() { return env("CROSSCODE_SITES", "/var/www/sites"); },
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Log lines are filtered for anything that looks like a secret before they leave the server
|
||||
* (AGENT-1.0-PLAN §4, rule 7). The crosscode script never prints .env values, but tools it runs
|
||||
* (npm, Prisma, git) might print a URL with a password or a token in an error.
|
||||
*/
|
||||
|
||||
const RULES: [RegExp, string][] = [
|
||||
// user:password@ in any URL (postgresql://, https://).
|
||||
[/([a-z][a-z0-9+.-]*:\/\/[^\s:/@]+:)[^\s@/]+@/gi, "$1***@"],
|
||||
// KEY=value and KEY: value for keys that hold secrets.
|
||||
[/\b([A-Z0-9_]*(SECRET|PASSWORD|PASSWD|TOKEN|API_KEY|PRIVATE_KEY|DSN|LICENCE_KEY|LICENSE_KEY)[A-Z0-9_]*)(\s*[=:]\s*)("[^"]*"|'[^']*'|\S+)/g, "$1$3***"],
|
||||
// Authorization headers and bearer tokens.
|
||||
[/\b(authorization\s*:\s*)(bearer|basic)\s+\S+/gi, "$1$2 ***"],
|
||||
[/\bbearer\s+[A-Za-z0-9._~+/=-]{16,}/gi, "Bearer ***"],
|
||||
// PEM blocks.
|
||||
[/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, "[private key]"],
|
||||
// Cross Code licence keys (CEH-7K2M-…).
|
||||
[/\b(CEH|CCA|CCW|CCP)-[A-Z0-9]{4}(-[A-Z0-9]{4}){3}\b/g, "$1-****"],
|
||||
// Long random-looking strings (hex or base64 of 32+ characters): likely keys or tokens.
|
||||
[/\b[A-Fa-f0-9]{40,}\b/g, "***"],
|
||||
[/\b[A-Za-z0-9+/_-]{48,}={0,2}/g, "***"],
|
||||
];
|
||||
|
||||
export function redact(line: string): string {
|
||||
let out = line;
|
||||
for (const [re, to] of RULES) out = out.replace(re, to);
|
||||
return out.length > 1000 ? `${out.slice(0, 997)}...` : out;
|
||||
}
|
||||
|
||||
/** Keeps the last `max` lines of output, redacted, without holding all of it in memory. */
|
||||
export class LogTail {
|
||||
private lines: string[] = [];
|
||||
private partial = "";
|
||||
constructor(private max = 200) {}
|
||||
push(chunk: string): void {
|
||||
const parts = (this.partial + chunk).split(/\r?\n/);
|
||||
this.partial = parts.pop() ?? "";
|
||||
for (const p of parts) this.add(p);
|
||||
}
|
||||
private add(line: string): void {
|
||||
this.lines.push(redact(line));
|
||||
if (this.lines.length > this.max) this.lines.shift();
|
||||
}
|
||||
end(): string[] {
|
||||
if (this.partial) {
|
||||
this.add(this.partial);
|
||||
this.partial = "";
|
||||
}
|
||||
return [...this.lines];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { openConfig } from "@crosscode/contracts/signing";
|
||||
import { paths } from "./paths";
|
||||
import { LogTail, redact } from "./redact";
|
||||
|
||||
/**
|
||||
* Runs `crosscode … --json` for a job: argument array (no shell), the job's config opened to a
|
||||
* file only root can read and removed as soon as the job ends, a time limit per type (the whole
|
||||
* process group is stopped past it), and the last 200 log lines, redacted.
|
||||
*/
|
||||
|
||||
export interface RunResult {
|
||||
status: agent.JobStatus;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
message?: string;
|
||||
log: string[];
|
||||
startedAt: string;
|
||||
finishedAt: string;
|
||||
}
|
||||
|
||||
export interface RunOptions {
|
||||
args: string[];
|
||||
sealedConfig?: agent.Sealed | null;
|
||||
x25519Pem: string;
|
||||
timeLimitMinutes: number;
|
||||
/** For tests. */
|
||||
bin?: string;
|
||||
}
|
||||
|
||||
const iso = (d = new Date()) => d.toISOString();
|
||||
|
||||
function writeConfig(sealed: agent.Sealed, x25519Pem: string): string {
|
||||
const opened = agent.jobConfigSchema.parse(openConfig(sealed, x25519Pem));
|
||||
fs.mkdirSync(paths.runDir, { recursive: true, mode: 0o700 });
|
||||
const file = path.join(paths.runDir, `config-${process.pid}-${Date.now()}.json`);
|
||||
fs.writeFileSync(file, JSON.stringify(opened), { mode: 0o600 });
|
||||
return file;
|
||||
}
|
||||
|
||||
export async function runCrosscode(opts: RunOptions): Promise<RunResult> {
|
||||
const startedAt = iso();
|
||||
let configFile: string | null = null;
|
||||
try {
|
||||
if (opts.sealedConfig) {
|
||||
try {
|
||||
configFile = writeConfig(opts.sealedConfig, opts.x25519Pem);
|
||||
} catch (e) {
|
||||
return { status: "refused", steps: [], result: {}, message: `The job's config couldn't be opened with this server's key: ${(e as Error).message}`, log: [], startedAt, finishedAt: iso() };
|
||||
}
|
||||
}
|
||||
const args = [...opts.args, "--json", ...(configFile ? ["--config", configFile] : [])];
|
||||
return await new Promise<RunResult>((resolve) => {
|
||||
const tail = new LogTail(200);
|
||||
let stdout = "";
|
||||
const child = spawn(opts.bin ?? paths.crosscode, args, {
|
||||
detached: true,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, CROSSCODE_NO_UPDATE: process.env.CROSSCODE_NO_UPDATE ?? "", LC_ALL: "C.UTF-8" },
|
||||
});
|
||||
let timedOut = false;
|
||||
const timer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
try { process.kill(-child.pid!, "SIGTERM"); } catch { /* already gone */ }
|
||||
setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { /* gone */ } }, 10_000).unref();
|
||||
}, opts.timeLimitMinutes * 60_000);
|
||||
child.stdout.setEncoding("utf8").on("data", (d: string) => { stdout += d; if (stdout.length > 5_000_000) stdout = stdout.slice(-1_000_000); });
|
||||
child.stderr.setEncoding("utf8").on("data", (d: string) => tail.push(d));
|
||||
child.on("error", (e) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ status: "failed", steps: [], result: {}, message: `crosscode couldn't be started: ${e.message}`, log: tail.end(), startedAt, finishedAt: iso() });
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
clearTimeout(timer);
|
||||
const log = tail.end();
|
||||
const report = parseReport(stdout);
|
||||
if (timedOut) {
|
||||
resolve({ status: "failed", steps: report?.steps ?? [], result: report?.result ?? {}, message: `Stopped after the time limit (${opts.timeLimitMinutes} minutes).`, log, startedAt, finishedAt: iso() });
|
||||
return;
|
||||
}
|
||||
if (!report) {
|
||||
resolve({ status: code === 0 ? "succeeded" : "failed", steps: [], result: {}, message: code === 0 ? undefined : `crosscode ended with code ${code} without a report.`, log, startedAt, finishedAt: iso() });
|
||||
return;
|
||||
}
|
||||
resolve({
|
||||
status: report.status,
|
||||
steps: report.steps,
|
||||
result: report.result,
|
||||
message: report.message ? redact(report.message) : undefined,
|
||||
log,
|
||||
startedAt: report.startedAt,
|
||||
finishedAt: report.finishedAt,
|
||||
});
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
if (configFile) fs.rmSync(configFile, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** The last line of stdout that's a valid script report. */
|
||||
export function parseReport(stdout: string): agent.ScriptReport | null {
|
||||
const lines = stdout.trim().split("\n").reverse();
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const parsed = agent.scriptReportSchema.safeParse(JSON.parse(line));
|
||||
if (parsed.success) return parsed.data;
|
||||
} catch {
|
||||
// not JSON
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import { execFile, execFileSync } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { readFrps } from "./central";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* The server's stats every 60 s (AGENT-1.0-PLAN §10, crosscode.agent-stats/1): RAM, CPU, disks,
|
||||
* uptime, versions, frpc, and each PM2 process with its church and product. Read from /proc and
|
||||
* the tools that are there; anything missing is null rather than an error.
|
||||
*/
|
||||
|
||||
export const AGENT_VERSION = "1.0.1";
|
||||
|
||||
function run(cmd: string, args: string[], timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 10_000_000 }, (err, stdout) => resolve(err ? null : String(stdout)));
|
||||
});
|
||||
}
|
||||
|
||||
export function parseMeminfo(text: string): agent.AgentStats["ram"] {
|
||||
const kb = (key: string) => Number(new RegExp(`^${key}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? 0) * 1024;
|
||||
const total = kb("MemTotal");
|
||||
const available = kb("MemAvailable");
|
||||
return { totalBytes: total, usedBytes: Math.max(0, total - available), availableBytes: available, swapTotalBytes: kb("SwapTotal"), swapUsedBytes: Math.max(0, kb("SwapTotal") - kb("SwapFree")) };
|
||||
}
|
||||
|
||||
/** CPU busy % between two /proc/stat readings. */
|
||||
export function cpuPercent(a: string, b: string): number {
|
||||
const parse = (t: string) => {
|
||||
const f = (/^cpu\s+(.+)$/m.exec(t)?.[1] ?? "").trim().split(/\s+/).map(Number);
|
||||
const idle = (f[3] ?? 0) + (f[4] ?? 0);
|
||||
return { idle, total: f.reduce((s, n) => s + (Number.isFinite(n) ? n : 0), 0) };
|
||||
};
|
||||
const x = parse(a), y = parse(b);
|
||||
const total = y.total - x.total;
|
||||
if (total <= 0) return 0;
|
||||
return Math.min(100, Math.max(0, Math.round(((total - (y.idle - x.idle)) / total) * 1000) / 10));
|
||||
}
|
||||
|
||||
async function disks(): Promise<agent.AgentStats["disks"]> {
|
||||
const out = await run("df", ["-P", "-B1", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs", "-x", "overlay"]);
|
||||
if (!out) return [];
|
||||
return out.trim().split("\n").slice(1).map((l) => l.trim().split(/\s+/)).filter((c) => c.length >= 6 && c[5]!.startsWith("/"))
|
||||
.slice(0, 30).map((c) => ({ mount: c[5]!, totalBytes: Number(c[1]), usedBytes: Number(c[2]), freeBytes: Number(c[3]) }));
|
||||
}
|
||||
|
||||
function osName(): string {
|
||||
try {
|
||||
const t = fs.readFileSync("/etc/os-release", "utf8");
|
||||
return /^PRETTY_NAME="?([^"\n]+)"?/m.exec(t)?.[1] ?? `${os.type()} ${os.release()}`;
|
||||
} catch {
|
||||
return `${os.type()} ${os.release()}`;
|
||||
}
|
||||
}
|
||||
|
||||
const versionIn = (text: string | null) => (text ? /(\d+\.\d+(\.\d+)?)/.exec(text)?.[1] ?? null : null);
|
||||
|
||||
/** church.env → { app user → [{ church, product, names }] }, read as data like the script does. */
|
||||
export function churchProcesses(sitesDir = paths.sites): Map<string, { church: string; product: agent.AgentStats["processes"][number]["product"]; names: string[] }[]> {
|
||||
const byUser = new Map<string, { church: string; product: "events" | "accounts" | "website" | "app"; names: string[] }[]>();
|
||||
let entries: string[];
|
||||
try { entries = fs.readdirSync(sitesDir); } catch { return byUser; }
|
||||
for (const church of entries) {
|
||||
if (!/^[a-z][a-z0-9-]{0,39}$/.test(church)) continue;
|
||||
let text: string;
|
||||
try { text = fs.readFileSync(path.join(sitesDir, church, "church.env"), "utf8"); } catch { continue; }
|
||||
const vars = new Map<string, string>();
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = /^([A-Z][A-Z0-9_]*)=("([^"]*)"|'([^']*)'|([^#\s]*))/.exec(line);
|
||||
if (m) vars.set(m[1]!, m[3] ?? m[4] ?? m[5] ?? "");
|
||||
}
|
||||
for (const product of ["accounts", "events", "website", "app"] as const) {
|
||||
const p = product.toUpperCase();
|
||||
const user = vars.get(`${p}_USER`);
|
||||
const names = (vars.get(`${p}_PM2`) ?? "").split(/\s+/).filter(Boolean);
|
||||
if (!user || !names.length || !/^[a-z_][a-z0-9_-]{0,31}$/.test(user)) continue;
|
||||
const list = byUser.get(user) ?? [];
|
||||
list.push({ church, product, names });
|
||||
byUser.set(user, list);
|
||||
}
|
||||
}
|
||||
return byUser;
|
||||
}
|
||||
|
||||
interface Pm2Proc { name?: string; monit?: { memory?: number; cpu?: number }; pm2_env?: { status?: string; restart_time?: number; pm_uptime?: number } }
|
||||
|
||||
function pm2Running(user: string): boolean {
|
||||
try {
|
||||
const home = execFileSync("getent", ["passwd", user], { encoding: "utf8" }).split(":")[5];
|
||||
const pid = Number(fs.readFileSync(`${home}/.pm2/pm2.pid`, "utf8").trim());
|
||||
if (!pid) return false;
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pm2Processes(): Promise<agent.AgentStats["processes"]> {
|
||||
const out: agent.AgentStats["processes"] = [];
|
||||
for (const [user, installs] of churchProcesses()) {
|
||||
// Only ask a daemon that's running: `pm2 jlist` would otherwise start an empty one inside this
|
||||
// agent's service, which dies with the agent (found in the VM test).
|
||||
if (!pm2Running(user)) continue;
|
||||
const json = await run("sudo", ["-n", "-u", user, "-H", "--", "pm2", "jlist"]);
|
||||
let list: Pm2Proc[];
|
||||
try { list = JSON.parse(json ?? "[]") as Pm2Proc[]; } catch { list = []; }
|
||||
for (const p of list) {
|
||||
const owner = installs.find((i) => i.names.includes(p.name ?? ""));
|
||||
out.push({
|
||||
name: String(p.name ?? "?").slice(0, 100),
|
||||
church: owner?.church ?? null,
|
||||
product: owner?.product ?? null,
|
||||
status: String(p.pm2_env?.status ?? "unknown").slice(0, 40),
|
||||
memoryBytes: Number(p.monit?.memory ?? 0),
|
||||
cpuPercent: Number(p.monit?.cpu ?? 0),
|
||||
restarts: Math.max(0, Math.trunc(Number(p.pm2_env?.restart_time ?? 0))),
|
||||
uptimeSeconds: p.pm2_env?.pm_uptime ? Math.max(0, (Date.now() - p.pm2_env.pm_uptime) / 1000) : 0,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out.slice(0, 200);
|
||||
}
|
||||
|
||||
/** A systemd unit is active; null when there's no systemctl. (is-active exits non-zero when inactive.) */
|
||||
function active(unit: string): Promise<boolean | null> {
|
||||
return new Promise((resolve) => {
|
||||
execFile("systemctl", ["is-active", unit], { timeout: 10_000 }, (err, stdout) => {
|
||||
if (err && (err as NodeJS.ErrnoException).code === "ENOENT") resolve(null);
|
||||
else resolve(String(stdout).trim() === "active");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function collectStats(mode: agent.AgentMode): Promise<agent.AgentStats> {
|
||||
const read = (f: string) => { try { return fs.readFileSync(f, "utf8"); } catch { return ""; } };
|
||||
const stat1 = read("/proc/stat");
|
||||
await new Promise((r) => setTimeout(r, 1000));
|
||||
const stat2 = read("/proc/stat");
|
||||
const [load1, load5, load15] = os.loadavg();
|
||||
const [diskList, postgres, frpc, processes, frpcRunning] = await Promise.all([
|
||||
disks(),
|
||||
run("psql", ["--version"]),
|
||||
run("frpc", ["-v"]),
|
||||
mode === "church" ? pm2Processes() : Promise.resolve([]),
|
||||
mode === "church" ? active("frpc") : Promise.resolve(null),
|
||||
]);
|
||||
const stats: agent.AgentStats = {
|
||||
schema: "crosscode.agent-stats/1",
|
||||
at: new Date().toISOString(),
|
||||
ram: parseMeminfo(read("/proc/meminfo")),
|
||||
cpu: { percent: cpuPercent(stat1, stat2), load1: load1 ?? 0, load5: load5 ?? 0, load15: load15 ?? 0, cores: Math.max(1, os.cpus().length) },
|
||||
disks: diskList,
|
||||
uptimeSeconds: os.uptime(),
|
||||
versions: { os: osName().slice(0, 200), node: process.versions.node, postgres: versionIn(postgres), frpc: versionIn(frpc), agent: AGENT_VERSION },
|
||||
frpcRunning,
|
||||
processes,
|
||||
};
|
||||
if (mode === "central") {
|
||||
const frps = readFrps();
|
||||
stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") };
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import type { agent } from "@crosscode/contracts";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* update-agent (AGENT-1.0-PLAN §3): the newest agent@x.y.z is checked out and built next to the
|
||||
* running copy, `current` is switched to it and the agent exits, so systemd starts the new one.
|
||||
* A one-shot systemd timer switches back to `previous` unless the new agent clears
|
||||
* update-pending.json by polling the Hub within 150 seconds.
|
||||
*
|
||||
* /opt/crosscode/agent/releases/<version>/ checkouts of the monorepo at agent@<version>
|
||||
* /opt/crosscode/agent/current, previous symlinks to releases
|
||||
* /opt/crosscode/agent/revert.sh written by the install script
|
||||
*/
|
||||
|
||||
const REPO = process.env.CROSSCODE_REPO || "https://c-git.crosscode.co.za/joshua/crosscode-platform.git";
|
||||
const CONFIRM_SECONDS = 150;
|
||||
|
||||
const pendingFile = () => path.join(paths.stateDir, "update-pending.json");
|
||||
|
||||
function exec(cmd: string, args: string[], cwd?: string, timeoutMs = 15 * 60_000): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cmd, args, { cwd, timeout: timeoutMs, maxBuffer: 20_000_000, env: { ...process.env, NODE_ENV: "development" } }, (err, stdout, stderr) => {
|
||||
if (err) reject(new Error(`${cmd} ${args.join(" ")}: ${String(stderr).trim().split("\n").slice(-3).join(" ") || err.message}`));
|
||||
else resolve(String(stdout));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface UpdateOutcome {
|
||||
status: agent.JobStatus;
|
||||
message: string;
|
||||
steps: agent.ReportStep[];
|
||||
result: Record<string, unknown>;
|
||||
/** Exit after reporting, so systemd starts the new version. */
|
||||
restart: boolean;
|
||||
}
|
||||
|
||||
export async function updateAgent(tag: string, currentVersion: string): Promise<UpdateOutcome> {
|
||||
const version = tag.replace(/^agent@/, "");
|
||||
const steps: agent.ReportStep[] = [];
|
||||
const step = async (name: string, fn: () => Promise<void>) => {
|
||||
const s: agent.ReportStep = { name, startedAt: new Date().toISOString(), finishedAt: null, outcome: "ok" };
|
||||
steps.push(s);
|
||||
try {
|
||||
await fn();
|
||||
} catch (e) {
|
||||
s.outcome = "failed";
|
||||
s.detail = (e as Error).message.slice(0, 2000);
|
||||
throw e;
|
||||
} finally {
|
||||
s.finishedAt = new Date().toISOString();
|
||||
}
|
||||
};
|
||||
if (version === currentVersion) return { status: "succeeded", message: `Already on ${tag}.`, steps, result: { version }, restart: false };
|
||||
|
||||
const root = paths.agentRoot;
|
||||
const dir = path.join(root, "releases", version);
|
||||
try {
|
||||
await step(`Checking out ${tag}`, async () => {
|
||||
if (!fs.existsSync(path.join(dir, ".git"))) {
|
||||
fs.mkdirSync(path.dirname(dir), { recursive: true });
|
||||
await exec("git", ["clone", "--quiet", "--depth", "1", "--branch", tag, REPO, dir]);
|
||||
}
|
||||
});
|
||||
await step("Installing and building", async () => {
|
||||
await exec("npm", ["ci", "--no-audit", "--no-fund", "--include=dev", "--include-workspace-root", "-w", "packages/contracts", "-w", "apps/agent"], dir);
|
||||
await exec("npm", ["run", "build", "-w", "packages/contracts"], dir);
|
||||
await exec("npm", ["run", "build", "-w", "apps/agent"], dir);
|
||||
});
|
||||
await step("Checking the new build", async () => {
|
||||
const out = await exec(process.execPath, [path.join(dir, "apps/agent/dist/cli.js"), "version"], dir, 30_000);
|
||||
if (out.trim() !== version) throw new Error(`The new build says it's ${out.trim()}, not ${version}.`);
|
||||
});
|
||||
await step("Switching over", async () => {
|
||||
const current = path.join(root, "current");
|
||||
const previous = path.join(root, "previous");
|
||||
const old = fs.readlinkSync(current);
|
||||
fs.writeFileSync(pendingFile(), JSON.stringify({ from: currentVersion, to: version, at: new Date().toISOString() }), { mode: 0o600 });
|
||||
replaceLink(previous, old);
|
||||
replaceLink(current, dir);
|
||||
// If the new agent doesn't poll within CONFIRM_SECONDS, revert.sh puts `previous` back.
|
||||
await exec("systemd-run", [`--on-active=${CONFIRM_SECONDS}`, `--unit=crosscode-agent-revert-${Date.now()}`, path.join(root, "revert.sh")]);
|
||||
});
|
||||
} catch (e) {
|
||||
return { status: "failed", message: `The agent wasn't updated: ${(e as Error).message}`, steps, result: { from: currentVersion, to: version }, restart: false };
|
||||
}
|
||||
return { status: "succeeded", message: `Switching to ${tag}; it confirms by polling within ${CONFIRM_SECONDS} seconds.`, steps, result: { from: currentVersion, to: version }, restart: true };
|
||||
}
|
||||
|
||||
function replaceLink(link: string, target: string): void {
|
||||
const tmp = `${link}.tmp-${process.pid}`;
|
||||
fs.rmSync(tmp, { force: true });
|
||||
fs.symlinkSync(target, tmp);
|
||||
fs.renameSync(tmp, link);
|
||||
}
|
||||
|
||||
/** Called after the first successful poll: this version works, so it stays. */
|
||||
export function confirmUpdate(): void {
|
||||
fs.rmSync(pendingFile(), { force: true });
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { verifyJob } from "@crosscode/contracts/signing";
|
||||
import type { AgentConfig } from "./config";
|
||||
import { paths } from "./paths";
|
||||
|
||||
/**
|
||||
* Whether to run a job (AGENT-1.0-PLAN §4). Checked in this order, and a job is refused at the
|
||||
* first check it fails:
|
||||
* 1. it's an object with an id and type the agent can report on,
|
||||
* 2. the signature verifies with the Hub key pinned when the server joined,
|
||||
* 3. it's for this server,
|
||||
* 4. it's within notBefore … expiresAt (an expired job is reported as `expired`, never run late),
|
||||
* 5. its id hasn't been seen in the last 90 days (replays),
|
||||
* 6. its type is one this agent runs (a central agent only runs check-ports, status, update-agent),
|
||||
* 7. every argument passes that type's schema (unknown arguments refused).
|
||||
*/
|
||||
|
||||
export type Verdict =
|
||||
| { ok: true; job: agent.AgentJob }
|
||||
| { ok: false; status: "refused" | "expired"; message: string; id: string | null; type: agent.JobType | null };
|
||||
|
||||
const SEEN_DAYS = 90;
|
||||
|
||||
/** Job ids already run or refused, with when (replay protection). */
|
||||
export class SeenJobs {
|
||||
private seen = new Map<string, number>();
|
||||
constructor(private file = path.join(paths.stateDir, "seen-jobs.json")) {
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(this.file, "utf8")) as Record<string, number>;
|
||||
for (const [id, at] of Object.entries(data)) this.seen.set(id, at);
|
||||
} catch {
|
||||
// First run, or an unreadable file: start empty (signatures and expiry still apply).
|
||||
}
|
||||
}
|
||||
has(id: string): boolean {
|
||||
return this.seen.has(id);
|
||||
}
|
||||
add(id: string, now = Date.now()): void {
|
||||
this.seen.set(id, now);
|
||||
const cutoff = now - SEEN_DAYS * 86_400_000;
|
||||
for (const [k, at] of this.seen) if (at < cutoff) this.seen.delete(k);
|
||||
fs.mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
|
||||
const tmp = `${this.file}.tmp-${process.pid}`;
|
||||
fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(this.seen)), { mode: 0o600 });
|
||||
fs.renameSync(tmp, this.file);
|
||||
}
|
||||
}
|
||||
|
||||
const typeOf = (v: unknown): agent.JobType | null => (agent.jobTypeSchema.safeParse(v).success ? (v as agent.JobType) : null);
|
||||
|
||||
export function checkJob(raw: unknown, config: AgentConfig, seen: SeenJobs, now = new Date()): Verdict {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { ok: false, status: "refused", message: "Not a job.", id: null, type: null };
|
||||
const j = raw as Record<string, unknown>;
|
||||
const id = typeof j.id === "string" && /^job_[A-Za-z0-9_-]{8,64}$/.test(j.id) ? j.id : null;
|
||||
const type = typeOf(j.type);
|
||||
const refuse = (message: string): Verdict => ({ ok: false, status: "refused", message, id, type });
|
||||
|
||||
if (!id) return refuse("The job has no valid id.");
|
||||
if (!verifyJob(j, config.hubJobKey)) return refuse("The signature doesn't match the Hub's key.");
|
||||
if (j.serverId !== config.serverId) return refuse(`The job is for ${String(j.serverId)}, not this server.`);
|
||||
const notBefore = Date.parse(String(j.notBefore));
|
||||
const expiresAt = Date.parse(String(j.expiresAt));
|
||||
if (!Number.isFinite(notBefore) || !Number.isFinite(expiresAt) || expiresAt <= notBefore) return refuse("The job's times aren't valid.");
|
||||
if (now.getTime() > expiresAt) return { ok: false, status: "expired", message: `The job expired at ${new Date(expiresAt).toISOString()}; it wasn't run.`, id, type };
|
||||
// A minute's leeway for clocks that differ a little.
|
||||
if (now.getTime() < notBefore - 60_000) return refuse(`The job isn't due until ${new Date(notBefore).toISOString()}.`);
|
||||
if (seen.has(id)) return refuse("This job was already received (a replay).");
|
||||
if (!type) return refuse(`Unknown job type ${JSON.stringify(j.type)}.`);
|
||||
if (config.mode === "central" && !agent.CENTRAL_JOB_TYPES.includes(type)) return refuse(`A central agent doesn't run ${type} jobs.`);
|
||||
const parsed = agent.agentJobSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
const issue = parsed.error.issues[0];
|
||||
return refuse(`The job's ${issue?.path.join(".") || "content"} isn't valid: ${issue?.message ?? "unknown problem"}.`);
|
||||
}
|
||||
return { ok: true, job: parsed.data };
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { crosscodeArgs } from "../src/command";
|
||||
import { job } from "./helpers";
|
||||
|
||||
const parsed = (over: Record<string, unknown>) => agent.agentJobSchema.parse(job(over));
|
||||
|
||||
describe("crosscode arguments for each job", () => {
|
||||
it("install: behind frp with the Hub's ports and the release", () => {
|
||||
expect(crosscodeArgs(parsed({
|
||||
type: "install",
|
||||
args: { church: "hope", products: ["events"], versions: { events: "events@2.4.1" }, domains: { events: "events.hope.co.za" }, ports: { events: { web: 20010, api: 20011 } } },
|
||||
}))).toEqual(["install", "hope", "--products", "events", "--domain", "hope.co.za", "--events-domain", "events.hope.co.za", "--api-port", "20011", "--web-port", "20010", "--frp", "--version", "events@2.4.1"]);
|
||||
});
|
||||
|
||||
it("deploy, adopt, restart, uninstall, purge, status", () => {
|
||||
expect(crosscodeArgs(parsed({}))).toEqual(["deploy", "hope", "events", "--version", "events@2.4.1"]);
|
||||
expect(crosscodeArgs(parsed({ args: { church: "hope", products: ["events"], check: true } }))).toEqual(["deploy", "hope", "events", "--check"]);
|
||||
expect(crosscodeArgs(parsed({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/hope-events", version: "events@2.2.0" } })))
|
||||
.toEqual(["adopt", "hope", "--events-dir", "/var/www/hope-events", "--version", "events@2.2.0"]);
|
||||
expect(crosscodeArgs(parsed({ type: "adopt-undo", args: { church: "hope" } }))).toEqual(["adopt", "hope", "--undo"]);
|
||||
expect(crosscodeArgs(parsed({ type: "restart", args: { church: "hope" } }))).toEqual(["restart", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "uninstall", args: { church: "hope" } }))).toEqual(["uninstall", "hope", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "purge", args: { church: "hope" } }))).toEqual(["purge", "hope", "--confirm", "hope"]);
|
||||
expect(crosscodeArgs(parsed({ type: "status", args: {} }))).toEqual(["status", "--no-fetch"]);
|
||||
});
|
||||
|
||||
it("export writes to the file the agent gives", () => {
|
||||
const j = parsed({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
|
||||
expect(crosscodeArgs(j, { exportFile: "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip" })).toEqual(["export", "hope", "--out", "/var/lib/crosscode-agent/exports/exp_abcdefgh.zip"]);
|
||||
});
|
||||
|
||||
it("the agent's own jobs run no crosscode command", () => {
|
||||
expect(crosscodeArgs(parsed({ type: "check-ports", args: { ports: [20010] } }))).toBeNull();
|
||||
expect(crosscodeArgs(parsed({ type: "update-agent", args: { version: "agent@1.0.1" } }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { generateEd25519, generateX25519, signJob } from "@crosscode/contracts/signing";
|
||||
import type { AgentConfig } from "../src/config";
|
||||
|
||||
export const hubKeys = generateEd25519();
|
||||
export const serverKeys = { ed25519: generateEd25519(), x25519: generateX25519() };
|
||||
|
||||
export const config: AgentConfig = {
|
||||
hubUrl: "https://hub.test",
|
||||
serverId: "srv_test00001",
|
||||
mode: "church",
|
||||
hubJobKey: hubKeys.publicKey,
|
||||
pollSeconds: 30,
|
||||
statsSeconds: 60,
|
||||
joinedAt: "2026-11-20T00:00:00.000Z",
|
||||
};
|
||||
|
||||
export const NOW = new Date("2026-11-20T12:05:00.000Z");
|
||||
|
||||
let n = 0;
|
||||
export function job(over: Record<string, unknown> = {}, key = hubKeys.privateKeyPem) {
|
||||
n++;
|
||||
return signJob({
|
||||
schema: "crosscode.agent-job/1",
|
||||
id: `job_test${String(n).padStart(6, "0")}`,
|
||||
serverId: config.serverId,
|
||||
type: "deploy",
|
||||
args: { church: "hope", products: ["events"], versions: ["events@2.4.1"] },
|
||||
config: null,
|
||||
notBefore: "2026-11-20T12:00:00.000Z",
|
||||
expiresAt: "2026-11-20T12:15:00.000Z",
|
||||
...over,
|
||||
}, key);
|
||||
}
|
||||
|
||||
/** A temporary state folder per test file. */
|
||||
export function tempState(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-test-"));
|
||||
process.env.CROSSCODE_AGENT_STATE_DIR = dir;
|
||||
process.env.CROSSCODE_AGENT_RUN_DIR = path.join(dir, "run");
|
||||
return dir;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { agent } from "@crosscode/contracts";
|
||||
import { decryptExport } from "@crosscode/contracts/signing";
|
||||
import { HubRequestError, type HubClient } from "../src/hub";
|
||||
import { Agent } from "../src/loop";
|
||||
import type { RunResult } from "../src/runner";
|
||||
import { SeenJobs } from "../src/verify";
|
||||
import { config, job, NOW, serverKeys, tempState } from "./helpers";
|
||||
|
||||
const state = tempState();
|
||||
|
||||
function fakeHub(jobs: unknown[]) {
|
||||
const posts: { path: string; body: unknown }[] = [];
|
||||
const puts: { path: string; body: Uint8Array }[] = [];
|
||||
let down = false;
|
||||
const hub: HubClient = {
|
||||
async post(p, body) {
|
||||
if (down) throw new HubRequestError("down", 0, "HUB_UNREACHABLE");
|
||||
posts.push({ path: p, body });
|
||||
if (p === "/api/agent/v1/poll") return { jobs: jobs.splice(0), pollSeconds: 30 };
|
||||
return null;
|
||||
},
|
||||
async put(p, body) {
|
||||
puts.push({ path: p, body });
|
||||
return null;
|
||||
},
|
||||
};
|
||||
return { hub, posts, puts, setDown: (v: boolean) => { down = v; } };
|
||||
}
|
||||
|
||||
const ok = (over: Partial<RunResult> = {}): RunResult => ({ status: "succeeded", steps: [{ name: "x", startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), outcome: "ok" }], result: {}, log: ["==> done"], startedAt: NOW.toISOString(), finishedAt: NOW.toISOString(), ...over });
|
||||
|
||||
type Run = (args: string[], job: agent.AgentJob) => Promise<RunResult>;
|
||||
|
||||
function make(jobs: unknown[], run: jest.Mock<ReturnType<Run>, Parameters<Run>> = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok())) {
|
||||
const h = fakeHub(jobs);
|
||||
const a = new Agent({ config, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, now: () => NOW });
|
||||
return { a, run, ...h };
|
||||
}
|
||||
|
||||
const reports = (posts: { path: string; body: unknown }[]) => posts.filter((p) => p.path === "/api/agent/v1/report").map((p) => p.body as agent.AgentReport);
|
||||
|
||||
describe("the agent loop", () => {
|
||||
it("runs a valid job once and reports it", async () => {
|
||||
const j = job();
|
||||
const { a, run, posts } = make([j, j]);
|
||||
await a.pollOnce();
|
||||
expect(run).toHaveBeenCalledTimes(1);
|
||||
expect(run.mock.calls[0]).toEqual([["deploy", "hope", "events", "--version", "events@2.4.1"], expect.objectContaining({ id: j.id })]);
|
||||
// The second copy is a replay: refused quietly (the first one's report already went).
|
||||
const rs = reports(posts);
|
||||
expect(rs.map((r) => [r.jobId, r.status])).toEqual([[j.id, "succeeded"]]);
|
||||
expect(agent.agentReportSchema.safeParse(rs[0]).success).toBe(true);
|
||||
});
|
||||
|
||||
it("reports refused and expired jobs without running them", async () => {
|
||||
const forged = { ...job(), signature: "A".repeat(86) };
|
||||
const late = job({ expiresAt: "2026-11-20T12:01:00.000Z", notBefore: "2026-11-20T11:00:00.000Z" });
|
||||
const { a, run, posts } = make([forged, late]);
|
||||
await a.pollOnce();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
expect(reports(posts).map((r) => r.status)).toEqual(["refused", "expired"]);
|
||||
});
|
||||
|
||||
it("keeps a report it can't send and sends it on the next poll", async () => {
|
||||
const j = job();
|
||||
let setDownLater: (v: boolean) => void = () => {};
|
||||
const { a, posts, setDown } = make([j], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { setDownLater(true); return ok(); }));
|
||||
setDownLater = setDown;
|
||||
await a.pollOnce();
|
||||
expect(reports(posts)).toEqual([]);
|
||||
expect(fs.readdirSync(path.join(state, "outbox"))).toContain(`${j.id}.json`);
|
||||
setDown(false);
|
||||
await a.pollOnce();
|
||||
expect(reports(posts).map((r) => r.jobId)).toEqual([j.id]);
|
||||
expect(fs.readdirSync(path.join(state, "outbox"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("backs off while the Hub is unreachable", async () => {
|
||||
const { a, setDown } = make([]);
|
||||
setDown(true);
|
||||
expect(await a.pollOnce()).toBe(60);
|
||||
expect(await a.pollOnce()).toBe(120);
|
||||
setDown(false);
|
||||
expect(await a.pollOnce()).toBe(30);
|
||||
});
|
||||
|
||||
it("export: encrypts the ZIP, uploads it, and only the report carries the key", async () => {
|
||||
const j = job({ type: "export", args: { church: "hope", exportId: "exp_abcdefgh" } });
|
||||
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async (args: string[]) => {
|
||||
fs.writeFileSync(args[3]!, "PK zip bytes");
|
||||
return ok({ result: { file: args[3], bytes: 12 } });
|
||||
});
|
||||
const { a, puts, posts } = make([j], run);
|
||||
await a.pollOnce();
|
||||
expect(puts).toHaveLength(1);
|
||||
expect(puts[0]!.path).toBe("/api/agent/v1/exports/exp_abcdefgh");
|
||||
const r = reports(posts)[0]!;
|
||||
expect(r.status).toBe("succeeded");
|
||||
const key = r.result.key as string;
|
||||
expect(decryptExport(puts[0]!.body, key).toString()).toBe("PK zip bytes");
|
||||
expect(Buffer.from(puts[0]!.body).includes(Buffer.from("PK zip"))).toBe(false);
|
||||
expect(fs.readdirSync(path.join(state, "exports"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("status on the central server: its own stats, without crosscode (which isn't installed there)", async () => {
|
||||
const h = fakeHub([job({ type: "status", args: {} })]);
|
||||
const run = jest.fn<ReturnType<Run>, Parameters<Run>>(async () => ok());
|
||||
const stats = { schema: "crosscode.agent-stats/1", central: { proxyBindAddr: "127.0.0.1", allowPorts: null, frpsRunning: true } } as unknown as agent.AgentStats;
|
||||
const a = new Agent({ config: { ...config, mode: "central" }, keys: { ed25519Pem: serverKeys.ed25519.privateKeyPem, x25519Pem: serverKeys.x25519.privateKeyPem }, hub: h.hub, seen: new SeenJobs(path.join(state, `seen-${Math.random()}.json`)), run, stats: async () => stats, now: () => NOW });
|
||||
await a.pollOnce();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
const r = reports(h.posts)[0]!;
|
||||
expect(r).toMatchObject({ type: "status", status: "succeeded", result: { stats } });
|
||||
expect(agent.agentReportSchema.safeParse(r).success).toBe(true);
|
||||
});
|
||||
|
||||
it("status on a church server runs crosscode status", async () => {
|
||||
const { a, run } = make([job({ type: "status", args: {} })]);
|
||||
await a.pollOnce();
|
||||
expect(run.mock.calls[0]![0]).toEqual(["status", "--no-fetch"]);
|
||||
});
|
||||
|
||||
it("a job that throws is reported as failed", async () => {
|
||||
const { a, posts } = make([job()], jest.fn<ReturnType<Run>, Parameters<Run>>(async () => { throw new Error("boom"); }));
|
||||
await a.pollOnce();
|
||||
expect(reports(posts)[0]).toMatchObject({ status: "failed", message: "boom" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { config, serverKeys } from "./helpers";
|
||||
|
||||
/**
|
||||
* AGENT-1.0-PLAN §2 rule 1: the agent listens on nothing. Starts the built agent (dist/cli.js)
|
||||
* against a fake Hub served by this test, lets it poll, then compares the agent's open sockets
|
||||
* with every listening TCP socket the kernel knows (/proc/net/tcp, tcp6). Linux only (the
|
||||
* servers); run `npm run build -w apps/agent` first.
|
||||
*/
|
||||
const cli = path.join(__dirname, "..", "dist", "cli.js");
|
||||
const linux = process.platform === "linux" && fs.existsSync(cli);
|
||||
const maybe = linux ? it : it.skip;
|
||||
|
||||
function listeningInodes(): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const f of ["/proc/net/tcp", "/proc/net/tcp6"]) {
|
||||
let text: string;
|
||||
try { text = fs.readFileSync(f, "utf8"); } catch { continue; }
|
||||
for (const line of text.split("\n").slice(1)) {
|
||||
const cols = line.trim().split(/\s+/);
|
||||
if (cols[3] === "0A") out.add(cols[9]!); // 0A = LISTEN
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function socketInodes(pid: number): Set<string> {
|
||||
const out = new Set<string>();
|
||||
for (const fd of fs.readdirSync(`/proc/${pid}/fd`)) {
|
||||
try {
|
||||
const m = /^socket:\[(\d+)\]$/.exec(fs.readlinkSync(`/proc/${pid}/fd/${fd}`));
|
||||
if (m) out.add(m[1]!);
|
||||
} catch { /* closed meanwhile */ }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe("the running agent", () => {
|
||||
maybe("has no listening socket", async () => {
|
||||
let polls = 0;
|
||||
const hub = http.createServer((req, res) => {
|
||||
if (req.url === "/api/agent/v1/poll") polls++;
|
||||
res.setHeader("content-type", "application/json");
|
||||
res.end(req.url === "/api/agent/v1/poll" ? JSON.stringify({ jobs: [], pollSeconds: 5 }) : "{}");
|
||||
});
|
||||
await new Promise<void>((r) => hub.listen(0, "127.0.0.1", r));
|
||||
const port = (hub.address() as { port: number }).port;
|
||||
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "agent-nolisten-"));
|
||||
fs.writeFileSync(path.join(dir, "agent.json"), JSON.stringify({ ...config, hubUrl: `http://127.0.0.1:${port}`, pollSeconds: 5, statsSeconds: 15 }));
|
||||
fs.writeFileSync(path.join(dir, "agent-ed25519.pem"), serverKeys.ed25519.privateKeyPem);
|
||||
fs.writeFileSync(path.join(dir, "agent-x25519.pem"), serverKeys.x25519.privateKeyPem);
|
||||
const child = spawn(process.execPath, [cli, "run"], {
|
||||
env: { ...process.env, CROSSCODE_AGENT_CONFIG_DIR: dir, CROSSCODE_AGENT_STATE_DIR: path.join(dir, "state"), CROSSCODE_AGENT_ALLOW_NON_ROOT: "1", CROSSCODE_SITES: path.join(dir, "sites") },
|
||||
stdio: "ignore",
|
||||
});
|
||||
try {
|
||||
for (let i = 0; i < 40 && polls === 0; i++) await new Promise((r) => setTimeout(r, 250));
|
||||
expect(polls).toBeGreaterThan(0);
|
||||
const listening = listeningInodes();
|
||||
const mine = [...socketInodes(child.pid!)].filter((inode) => listening.has(inode));
|
||||
expect(mine).toEqual([]);
|
||||
} finally {
|
||||
child.kill("SIGTERM");
|
||||
hub.close();
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
import { checkPorts, parseFrpsIni, parseSs, portAllowed } from "../src/central";
|
||||
import { LogTail, redact } from "../src/redact";
|
||||
import { churchProcesses, cpuPercent, parseMeminfo } from "../src/stats";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
describe("log lines are redacted before they leave the server", () => {
|
||||
it.each([
|
||||
["Error: connect postgresql://hope_events:Zx81kLmQ@localhost:5432/hope_events", "postgresql://hope_events:***@localhost"],
|
||||
["JWT_SECRET=abcdefghijklmnop", "JWT_SECRET=***"],
|
||||
['DB_PASSWORD: "hunter2 x"', "DB_PASSWORD: ***"],
|
||||
["Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.payload.sig", "Authorization: Bearer ***"],
|
||||
["licence CEH-7K2M-9QXA-P4RT-WD8C refused", "CEH-****"],
|
||||
["token a3f9c1d27b8e4f60a3f9c1d27b8e4f60a3f9c1d2", "token ***"],
|
||||
])("%s", (line, expected) => {
|
||||
const out = redact(line);
|
||||
expect(out).toContain(expected);
|
||||
});
|
||||
|
||||
it("keeps ordinary lines", () => {
|
||||
expect(redact("==> events: migrations")).toBe("==> events: migrations");
|
||||
});
|
||||
|
||||
it("keeps only the last lines", () => {
|
||||
const t = new LogTail(3);
|
||||
t.push("1\n2\n3\n4");
|
||||
t.push("\n5\n");
|
||||
expect(t.end()).toEqual(["3", "4", "5"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("central server checks", () => {
|
||||
const ini = "[common]\nbind_port = 7000\nproxy_bind_addr = 127.0.0.1\nallow_ports = 20000-29999,3000\n\n[web]\nproxy_bind_addr = 0.0.0.0\n";
|
||||
|
||||
it("reads [common] only", () => {
|
||||
expect(parseFrpsIni(ini)).toEqual({ proxyBindAddr: "127.0.0.1", allowPorts: "20000-29999,3000" });
|
||||
});
|
||||
|
||||
it("allow_ports ranges", () => {
|
||||
expect(portAllowed(20010, "20000-29999,3000")).toBe(true);
|
||||
expect(portAllowed(3000, "20000-29999,3000")).toBe(true);
|
||||
expect(portAllowed(5000, "20000-29999,3000")).toBe(false);
|
||||
expect(portAllowed(5000, null)).toBe(true);
|
||||
});
|
||||
|
||||
it("ports must be allowed, open and bound to 127.0.0.1 only", () => {
|
||||
const ss = "LISTEN 0 4096 127.0.0.1:20010 0.0.0.0:*\nLISTEN 0 4096 0.0.0.0:20011 0.0.0.0:*\nLISTEN 0 4096 [::1]:20012 [::]:*\n";
|
||||
const res = checkPorts([20010, 20011, 20012, 20013], parseFrpsIni(ini), parseSs(ss));
|
||||
expect(res.ports.map((p) => [p.port, p.ok])).toEqual([[20010, true], [20011, false], [20012, true], [20013, false]]);
|
||||
expect(res.warnings.join(" ")).toMatch(/20011 is open on more than 127.0.0.1/);
|
||||
expect(res.warnings.join(" ")).toMatch(/20013 isn't open/);
|
||||
});
|
||||
|
||||
it("warns when proxy_bind_addr is missing", () => {
|
||||
const res = checkPorts([20010], parseFrpsIni("[common]\nbind_port = 7000\n"), parseSs("LISTEN 0 1 127.0.0.1:20010 0.0.0.0:*"));
|
||||
expect(res.warnings.join(" ")).toMatch(/proxy_bind_addr is not set/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stats", () => {
|
||||
it("RAM from /proc/meminfo", () => {
|
||||
const r = parseMeminfo("MemTotal: 4000000 kB\nMemFree: 100 kB\nMemAvailable: 1000000 kB\nSwapTotal: 2000 kB\nSwapFree: 500 kB\n");
|
||||
expect(r).toEqual({ totalBytes: 4096000000, usedBytes: 3072000000, availableBytes: 1024000000, swapTotalBytes: 2048000, swapUsedBytes: 1536000 });
|
||||
});
|
||||
|
||||
it("CPU % between two readings", () => {
|
||||
expect(cpuPercent("cpu 100 0 100 700 100 0 0 0", "cpu 150 0 150 750 150 0 0 0")).toBe(50);
|
||||
});
|
||||
|
||||
it("PM2 processes are matched to churches through church.env", () => {
|
||||
const sites = fs.mkdtempSync(path.join(os.tmpdir(), "sites-"));
|
||||
fs.mkdirSync(path.join(sites, "hope"));
|
||||
fs.writeFileSync(path.join(sites, "hope", "church.env"), 'CHURCH=hope\nEVENTS_USER=cc-hope\nEVENTS_PM2="hope-events-backend hope-events-frontend"\n');
|
||||
fs.mkdirSync(path.join(sites, "Bad Name"));
|
||||
const map = churchProcesses(sites);
|
||||
expect([...map.entries()]).toEqual([["cc-hope", [{ church: "hope", product: "events", names: ["hope-events-backend", "hope-events-frontend"] }]]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import path from "node:path";
|
||||
import { generateEd25519 } from "@crosscode/contracts/signing";
|
||||
import { checkJob, SeenJobs } from "../src/verify";
|
||||
import { config, job, NOW, tempState } from "./helpers";
|
||||
|
||||
const dir = tempState();
|
||||
const fresh = () => new SeenJobs(path.join(dir, `seen-${Math.random()}.json`));
|
||||
|
||||
describe("checking a job (AGENT-1.0-PLAN §4)", () => {
|
||||
it("accepts a signed job for this server, in its window", () => {
|
||||
expect(checkJob(job(), config, fresh(), NOW)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("refuses a job signed with another key", () => {
|
||||
expect(checkJob(job({}, generateEd25519().privateKeyPem), config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused", message: expect.stringContaining("signature") });
|
||||
});
|
||||
|
||||
it("refuses a job whose content was changed after signing", () => {
|
||||
const j = job();
|
||||
expect(checkJob({ ...j, args: { ...j.args, church: "other" } }, config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused" });
|
||||
});
|
||||
|
||||
it("refuses a job for another server", () => {
|
||||
expect(checkJob(job({ serverId: "srv_other0001" }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("not this server") });
|
||||
});
|
||||
|
||||
it("reports an expired job as expired, and never runs it", () => {
|
||||
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T12:16:00.000Z"))).toMatchObject({ ok: false, status: "expired" });
|
||||
});
|
||||
|
||||
it("refuses a job that isn't due yet (beyond a minute of clock difference)", () => {
|
||||
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T11:58:00.000Z"))).toMatchObject({ ok: false, status: "refused" });
|
||||
expect(checkJob(job(), config, fresh(), new Date("2026-11-20T11:59:30.000Z"))).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("refuses a replayed job, also after a restart", () => {
|
||||
const file = path.join(dir, "seen-replay.json");
|
||||
const seen = new SeenJobs(file);
|
||||
const j = job();
|
||||
expect(checkJob(j, config, seen, NOW)).toMatchObject({ ok: true });
|
||||
seen.add(j.id);
|
||||
expect(checkJob(j, config, seen, NOW)).toMatchObject({ ok: false, message: expect.stringContaining("replay") });
|
||||
expect(checkJob(j, config, new SeenJobs(file), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("replay") });
|
||||
});
|
||||
|
||||
it("refuses an unknown type, and arguments with shell characters", () => {
|
||||
expect(checkJob(job({ type: "shell", args: { command: "id" } }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("Unknown job type") });
|
||||
expect(checkJob(job({ args: { church: "hope;reboot", products: ["events"] } }), config, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("isn't valid") });
|
||||
expect(checkJob(job({ type: "adopt", args: { church: "hope", eventsDir: "/var/www/$(id)" } }), config, fresh(), NOW)).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("a central agent only runs check-ports, status and update-agent", () => {
|
||||
const central = { ...config, mode: "central" as const };
|
||||
expect(checkJob(job(), central, fresh(), NOW)).toMatchObject({ ok: false, message: expect.stringContaining("central") });
|
||||
expect(checkJob(job({ type: "check-ports", args: { ports: [20010, 20011] } }), central, fresh(), NOW)).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("refuses things that aren't jobs", () => {
|
||||
for (const raw of [null, "job", [], { id: "nope" }]) expect(checkJob(raw, config, fresh(), NOW)).toMatchObject({ ok: false, status: "refused" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".",
|
||||
"types": ["node", "jest"],
|
||||
"declaration": false
|
||||
},
|
||||
"include": ["src", "tests", "tsup.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from "tsup";
|
||||
|
||||
// One self-contained file (contracts and zod bundled in), so a server needs no node_modules to run
|
||||
// the agent: /opt/crosscode/agent/current/apps/agent/dist/cli.js.
|
||||
export default defineConfig({
|
||||
entry: ["src/cli.ts"],
|
||||
format: ["cjs"],
|
||||
platform: "node",
|
||||
target: "node24",
|
||||
noExternal: [/.*/],
|
||||
clean: true,
|
||||
sourcemap: true,
|
||||
banner: { js: "#!/usr/bin/env node" },
|
||||
});
|
||||
@@ -5,11 +5,54 @@ All notable changes to this project are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project follows [Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
## [2.3.1] - 2026-11-18
|
||||
|
||||
### Security
|
||||
|
||||
- **Next.js 16.4.3 → 16.4.6** (and eslint-config-next), for two advisories about cached data leaking
|
||||
across root params in `use cache` / `unstable_cache` (affects 16.2.0–16.4.4). Events uses neither,
|
||||
so it wasn't exposed; `next build` now refuses affected versions, which stopped the 2.3.0 build.
|
||||
|
||||
## [2.3.0] - 2026-11-17
|
||||
|
||||
Authenticator-app sign-in and recovery codes (ROADMAP-v3 phase 1c), and what installs and
|
||||
updates from the Hub need (crosscode agent 1.0, Hub 2.1.0).
|
||||
|
||||
### Added
|
||||
|
||||
- **Two-factor with an authenticator app** (TOTP, RFC 6238) next to email and WhatsApp: Profile &
|
||||
Security → Two-factor → "An authenticator app" shows a QR code (drawn in the browser) and the key;
|
||||
the app's first code confirms it. Codes can't be used twice; nothing is sent, so there's no resend.
|
||||
The secret is stored encrypted (`User.totpSecret`).
|
||||
- **Recovery codes**: 10 single-use codes each time two-factor is turned on (any method), shown
|
||||
once with Download and Copy; one works at sign-in in place of any code ("Use a recovery code").
|
||||
A new set from Profile & Security (password needed). Using one, and making a new set, show in
|
||||
the account's activity.
|
||||
- **Admins see each account's method** in Users ("2FA: app / email / WhatsApp"); Reset 2FA also
|
||||
removes the app's secret and the recovery codes.
|
||||
- API (v2): `authenticator` in `/me/two-factor/enable` (answers with `secret` and `otpauthUrl`),
|
||||
`recoveryCodes` from `/me/two-factor/confirm`, `POST /me/two-factor/recovery-codes`;
|
||||
`twoFactorMethod` and `recoveryCodesLeft` on `/me`, `twoFactorMethod` on users.
|
||||
- Migration `20261118150000_authenticator_app`.
|
||||
- `env.template.json`: every `.env` variable with its layer, for installs and updates from the Hub.
|
||||
- `scripts/export-church.ts`: the church's data as `crosscode.church-export/1` (for `crosscode export`).
|
||||
- A site installed from the Hub registers by itself on first start when `HUB_LICENCE_KEY` is set
|
||||
(with `HUB_ADMIN_NAME` / `HUB_ADMIN_EMAIL` as its admin contact), retrying while the Hub is
|
||||
unreachable.
|
||||
|
||||
## [2.2.0] - 2026-11-17
|
||||
|
||||
Cross Events moves into the `crosscode-platform` monorepo (ROADMAP-v3 phase 1b,
|
||||
`docs/EVENTS-2.2-PLAN.md`). Existing installs move with `crosscode adopt`, not `deploy`.
|
||||
|
||||
### Changed
|
||||
|
||||
- **AI use is shown in tokens, not rand** (for 2.3.0; needs Hub 2.0.1 for the token figures). Site
|
||||
- **Moved into the monorepo** as `apps/events`, with its git history. The backend and frontend are
|
||||
npm workspaces with one root lockfile. Releases are tagged `events@x.y.z`; the older `v…` tags
|
||||
stay in the archived `hope-events` repo.
|
||||
- **The `crosscode` script** (`deploy`, `status`, `install`, `adopt`, in `scripts/` at the
|
||||
monorepo root) replaces `scripts/deploy.sh` and `scripts/install.sh`.
|
||||
- **AI use is shown in tokens, not rand** (needs Hub 2.0.1 for the token figures). Site
|
||||
settings → AI shows the percentage used, the input and output tokens used this month and an
|
||||
estimated allowance in tokens; the per-person, per-helper and per-day tables show tokens instead
|
||||
of cost. The 80% email names tokens instead of rand. The rand amounts the Hub sends are dropped
|
||||
@@ -20,6 +63,14 @@ and this project follows [Semantic Versioning](https://semver.org/).
|
||||
`inputTokens` / `outputTokens` instead of `chargedCents`.
|
||||
- `AiCall` keeps each call's tokens (migration `20261117120000_ai_tokens`). Calls from before it
|
||||
show 0 tokens.
|
||||
- **Everything the backend serves is under `/api`**, so the site and its API can share one
|
||||
address (`events.church.co.za`, no `events-api.` record) with a single proxy rule: `/api` →
|
||||
backend port, everything else → frontend port (DEPLOYMENT.md, "One address, one rule"). The
|
||||
status page is at `/api` (`/` redirects there), health at `/api/health`, the API reference at
|
||||
`/api/docs/v2` and uploaded files at `/api/uploads/…`. Stored paths stay `/uploads/…`; pictures,
|
||||
logos and attachments are given out as `/api/uploads/…`, and so are WhatsApp ticket PDFs.
|
||||
- The old paths keep working on the backend: `/health` and `/uploads/…` answer as before, and
|
||||
`/docs` and `/docs/v2` redirect to `/api/docs/v2`. A missing file under `/api/uploads` is 404.
|
||||
|
||||
## [2.1.1] - 2026-11-03
|
||||
|
||||
@@ -2274,4 +2325,4 @@ Run `npm run prisma:deploy` in the backend when deploying. This release adds a m
|
||||
[1.2.0]: https://git.crosscode.co.za/joshua/hope-events/compare/v1.1.0...v1.2.0
|
||||
[1.1.0]: https://git.crosscode.co.za/joshua/hope-events/compare/v1.0.1...v1.1.0
|
||||
[1.0.1]: https://git.crosscode.co.za/joshua/hope-events/compare/v1.0.0...v1.0.1
|
||||
[1.0.0]: https://git.crosscode.co.za/joshua/hope-events/releases/tag/v1.0.0
|
||||
[1.0.0]: https://git.crosscode.co.za/joshua/hope-events/releases/tag/v1.0.0
|
||||
|
||||
@@ -38,6 +38,27 @@ visitor ──http───▶ frps (vhost_http_port) ══tunnel══▶ frp
|
||||
On this server, nginx sends `/api`, `/uploads`, `/health` and `/docs` to the backend (port 5000)
|
||||
and everything else to the Next.js site (port 3000), the same as a normal install.
|
||||
|
||||
### One address, one rule (2.2.0 and later)
|
||||
|
||||
From 2.2.0 everything the backend serves is under **`/api`**: the API (`/api/v2`), the status page
|
||||
(`/api`), health (`/api/health`), the API reference (`/api/docs/v2`) and uploaded files
|
||||
(`/api/uploads/…`). So the site and its API share one address (`events.yourchurch.org`, no
|
||||
separate `events-api.` record), and a web server or panel such as FastPanel needs a single
|
||||
rule:
|
||||
|
||||
| Path | Goes to |
|
||||
|------|---------|
|
||||
| `/api` and everything under it | the backend, `http://127.0.0.1:5000` |
|
||||
| everything else | the frontend, `http://127.0.0.1:3000` |
|
||||
|
||||
Set `BACKEND_URL` (backend `.env`) and `NEXT_PUBLIC_API_URL` (frontend `.env.production`) to the
|
||||
same `https://` address as `FRONTEND_URL`, then rebuild the frontend. The old paths (`/health`,
|
||||
`/docs/v2`, `/uploads/…`) still answer on the backend's port, so a site with a separate API
|
||||
address keeps working unchanged. With only `/api` routed, links made before 2.2.0 that point at
|
||||
`https://<site>/uploads/…` stop working (they aren't stored that way, but could be in an old
|
||||
email); keep the four-path rule above if that matters. Pictures, logos and attachments are all
|
||||
given out as `/api/uploads/…` from 2.2.0.
|
||||
|
||||
## 2. Before you start
|
||||
|
||||
- Ubuntu 22.04 or 24.04 on this server, with `frpc` already installed and connected (it runs as
|
||||
@@ -264,7 +285,7 @@ setup). If the `[hope-events-https]` section fails to start, check `journalctl -
|
||||
|
||||
## 6. Finish in the browser
|
||||
|
||||
1. Open `https://events.yourchurch.org/health` — it should answer with the version.
|
||||
1. Open `https://events.yourchurch.org/api/health` (`/health` before 2.2.0) — it should answer with the version.
|
||||
2. Open `https://events.yourchurch.org/setup`: create the admin account.
|
||||
3. **Site settings → Licence**: enter the licence key to connect to the Hub. The site checks in
|
||||
every 15 minutes from then on (outgoing HTTPS to `events-hub.crosscode.co.za`, which frp
|
||||
|
||||
@@ -20,7 +20,7 @@ The backend provides a RESTful API for managing users, events, registrations, pa
|
||||
- Static uploads for event images
|
||||
|
||||
Documentation: see Backend API Documentation and Backend README for environment setup and endpoints.
|
||||
- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md
|
||||
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.2.0) — ./backend/API_DOCUMENTATION.md
|
||||
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||
- Backend README: ./backend/README.md
|
||||
|
||||
@@ -156,7 +156,7 @@ set names that match your PM2 apps (`pm2 ls`) and the port you use.
|
||||
|
||||
## Useful Links
|
||||
|
||||
- API reference: `/docs/v2` on the running backend (OpenAPI; admin token) — ./backend/API_DOCUMENTATION.md
|
||||
- API reference: `/api/docs/v2` on the running site (OpenAPI; admin token; `/docs/v2` before 2.2.0) — ./backend/API_DOCUMENTATION.md
|
||||
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||
- Backend README: ./backend/README.md
|
||||
- Frontend README: ./frontend/README.md
|
||||
|
||||
@@ -12,6 +12,31 @@ Write for church admins, not developers: no environment variables, endpoints or
|
||||
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||
-->
|
||||
|
||||
## 2.3.1
|
||||
|
||||
- **Maintenance update.** An update to the framework the site is built on, with its latest security
|
||||
fixes. Nothing changes in how you use Cross Events.
|
||||
|
||||
## 2.3.0
|
||||
|
||||
- **Sign in with an authenticator app.** Two-factor sign-in can now use an app on your phone
|
||||
(Google Authenticator, Microsoft Authenticator, 1Password and others) instead of a code by email
|
||||
or WhatsApp. It's the most secure option and works without signal. Set it up under Profile &
|
||||
Security.
|
||||
- **Recovery codes.** When you turn on two-factor you get 10 single-use recovery codes to keep
|
||||
somewhere safe: if you lose your phone, one of them lets you sign in.
|
||||
- **Admins can see how each person signs in**: the Users page shows whether each account uses an
|
||||
app, email or WhatsApp for its codes.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- **AI use is now shown in tokens.** Site settings → AI shows how much of this month's AI allowance
|
||||
your team has used, as input tokens (what's sent to the AI) and output tokens (its answers), with
|
||||
an estimate of the whole allowance. The tables of who used it and for what show tokens too.
|
||||
- **Behind the scenes:** Cross Events now lives alongside our other church products, so every
|
||||
product is updated the same way. Your site works as before, and your data and settings stay as
|
||||
they are.
|
||||
|
||||
## 2.1.1
|
||||
|
||||
- **Sending feedback forms and reminders no longer makes you wait.** "Send now" and "Remind" on the
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.1.1",
|
||||
"version": "2.3.1",
|
||||
"description": "Event Management System Backend",
|
||||
"main": "src/index.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
-- 2.3.0: tokens per AI call, which is what the site shows (the rand amount is the Hub's business).
|
||||
-- 2.2.0: tokens per AI call, which is what the site shows (the rand amount is the Hub's business).
|
||||
ALTER TABLE "AiCall" ADD COLUMN "inputTokens" INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE "AiCall" ADD COLUMN "outputTokens" INTEGER NOT NULL DEFAULT 0;
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
-- 2.3.0: two-factor with an authenticator app (TOTP), and recovery codes.
|
||||
ALTER TYPE "TwoFactorMethod" ADD VALUE 'authenticator';
|
||||
ALTER TABLE "User" ADD COLUMN "totpSecret" TEXT;
|
||||
ALTER TABLE "User" ADD COLUMN "totpLastStep" INTEGER;
|
||||
ALTER TABLE "TwoFactorChallenge" ADD COLUMN "pendingSecret" TEXT;
|
||||
CREATE TABLE "RecoveryCode" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"codeHash" TEXT NOT NULL,
|
||||
"usedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "RecoveryCode_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
CREATE UNIQUE INDEX "RecoveryCode_codeHash_key" ON "RecoveryCode"("codeHash");
|
||||
CREATE INDEX "RecoveryCode_userId_idx" ON "RecoveryCode"("userId");
|
||||
ALTER TABLE "RecoveryCode" ADD CONSTRAINT "RecoveryCode_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
ALTER TYPE "SecurityEventType" ADD VALUE 'recovery_code_used';
|
||||
ALTER TYPE "SecurityEventType" ADD VALUE 'recovery_codes_replaced';
|
||||
@@ -52,11 +52,16 @@ enum SecurityEventType {
|
||||
password_reset
|
||||
two_factor_enabled
|
||||
two_factor_disabled
|
||||
// 2.3.0: a recovery code signed in (the app or phone may be lost); a new set was made.
|
||||
recovery_code_used
|
||||
recovery_codes_replaced
|
||||
}
|
||||
|
||||
enum TwoFactorMethod {
|
||||
email
|
||||
whatsapp
|
||||
// 2.3.0: codes from an authenticator app (TOTP); nothing is sent.
|
||||
authenticator
|
||||
}
|
||||
|
||||
model User {
|
||||
@@ -75,6 +80,11 @@ model User {
|
||||
notificationPreference NotificationPreference @default(email)
|
||||
twoFactorEnabled Boolean @default(false)
|
||||
twoFactorMethod TwoFactorMethod?
|
||||
// 2.3.0: the authenticator app's secret (encrypted, utils/encryption.js) and the last 30-second
|
||||
// step a code was used for, so a code can't be used twice.
|
||||
totpSecret String?
|
||||
totpLastStep Int?
|
||||
recoveryCodes RecoveryCode[]
|
||||
// POPIA: opted in to "News & announcements" (marketing) bulk messages, per channel.
|
||||
// Event updates to registrants don't depend on these. History in CommunicationConsent.
|
||||
newsEmail Boolean @default(false)
|
||||
@@ -713,6 +723,8 @@ model TwoFactorChallenge {
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
purpose String // 'login' | 'enable'
|
||||
method TwoFactorMethod
|
||||
// 2.3.0: an authenticator app being set up: its secret (encrypted) until the first code confirms it.
|
||||
pendingSecret String?
|
||||
codeHash String
|
||||
attempts Int @default(0)
|
||||
lastSentAt DateTime @default(now())
|
||||
@@ -2342,9 +2354,9 @@ model AiCall {
|
||||
// ok, refused, incomplete, failed, cap_reached, unavailable
|
||||
outcome String
|
||||
// What the church was charged, in cents (fractions of a cent). Kept for the record; the site
|
||||
// shows tokens (2.3.0), and only the Hub shows rand.
|
||||
// shows tokens (2.2.0), and only the Hub shows rand.
|
||||
chargedCents Float @default(0)
|
||||
// Tokens the call used (2.3.0): input counts cached prompt tokens. 0 when the call failed.
|
||||
// Tokens the call used (2.2.0): input counts cached prompt tokens. 0 when the call failed.
|
||||
inputTokens Int @default(0)
|
||||
outputTokens Int @default(0)
|
||||
createdAt DateTime @default(now())
|
||||
@@ -2353,3 +2365,15 @@ model AiCall {
|
||||
@@index([createdAt])
|
||||
@@index([userId, createdAt])
|
||||
}
|
||||
|
||||
// 2.3.0: single-use codes for when the authenticator app (or phone) is lost. Only an HMAC is kept.
|
||||
model RecoveryCode {
|
||||
id String @id @default(uuid())
|
||||
userId String
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
codeHash String @unique
|
||||
usedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@index([userId])
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* Writes the church's data as crosscode.church-export/1 (src/services/churchExport.ts) into a
|
||||
* folder: export.json and README.txt. `crosscode export` runs it, copies public/uploads into the
|
||||
* folder's uploads/ and zips it. Run from backend/: npx tsx scripts/export-church.ts --out-dir <dir>
|
||||
*/
|
||||
import 'dotenv/config';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { buildExport, readExportInput } from '../src/services/churchExport';
|
||||
import { prisma } from '../src/v2/legacy';
|
||||
|
||||
const README = `Your church's data from Cross Events
|
||||
=====================================
|
||||
|
||||
export.json holds your events, people, registrations, payments, check-ins and volunteer
|
||||
rosters, in plain terms (crosscode.church-export/1). Records refer to each other with short
|
||||
references made for this file: "p12" is a person, "e3" an event, "t5" a ticket type and "r40"
|
||||
a registration. They mean nothing outside this file.
|
||||
|
||||
people everyone with an account: name, email, phone, role, what they agreed to
|
||||
events each event with its sessions and ticket types (prices in cents)
|
||||
registrations who registered for what, the people attending, their answers to the form
|
||||
payments amounts in cents, how and when they were paid, the provider's reference
|
||||
checkIns who was checked in to which event, and when
|
||||
rosters volunteer roles and who served
|
||||
settings the site's name, contact details and branding
|
||||
files uploaded files, in the uploads/ folder next to this file
|
||||
|
||||
Not included: passwords, security codes and logs about how the site ran.
|
||||
`;
|
||||
|
||||
function listFiles(dir: string, base = dir): { path: string; bytes: number }[] {
|
||||
if (!fs.existsSync(dir)) return [];
|
||||
return fs.readdirSync(dir, { withFileTypes: true }).flatMap(d => {
|
||||
const full = path.join(dir, d.name);
|
||||
if (d.isDirectory()) return d.name === 'tickets-temp' ? [] : listFiles(full, base);
|
||||
if (!d.isFile() || !/^[A-Za-z0-9._-]+$/.test(d.name)) return [];
|
||||
return [{ path: `uploads/${path.relative(base, full).split(path.sep).join('/')}`, bytes: fs.statSync(full).size }];
|
||||
});
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const i = process.argv.indexOf('--out-dir');
|
||||
const out = i > 0 ? process.argv[i + 1] : '';
|
||||
if (!out) throw new Error('Usage: export-church.ts --out-dir <dir>');
|
||||
fs.mkdirSync(out, { recursive: true });
|
||||
const { version } = require('../package.json') as { version: string };
|
||||
const data = buildExport(await readExportInput(version));
|
||||
data.files = listFiles(path.join(__dirname, '..', 'public', 'uploads'));
|
||||
fs.writeFileSync(path.join(out, 'export.json'), `${JSON.stringify(data, null, 2)}\n`);
|
||||
fs.writeFileSync(path.join(out, 'README.txt'), README);
|
||||
console.log(`export.json: ${data.people.length} people, ${data.events.length} events, ${data.registrations.length} registrations, ${data.files.length} files`);
|
||||
}
|
||||
|
||||
main()
|
||||
.catch(e => { console.error(`Export failed: ${(e as Error).message}`); process.exitCode = 1; })
|
||||
.finally(() => prisma.$disconnect().catch(() => {}));
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through
|
||||
* the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap, calls
|
||||
* Claude and meters the call. The site shows that use as tokens and a percentage (2.3.0); the cap's
|
||||
* Claude and meters the call. The site shows that use as tokens and a percentage (2.2.0); the cap's
|
||||
* rand amount stays on the Hub. This module:
|
||||
* - works out what the AI buttons do (`aiStatus`): hidden, working, or disabled until the
|
||||
* allowance renews — from the licence token first, then the Hub (cached for a minute);
|
||||
@@ -35,7 +35,7 @@ export type HelperName = (typeof HELPERS)[number];
|
||||
|
||||
/**
|
||||
* What the Hub says (§3b), as the site keeps it. The Hub also sends the allowance in rand
|
||||
* (`capCents`, `usedCents`); the site drops those (2.3.0): people see tokens and a percentage,
|
||||
* (`capCents`, `usedCents`); the site drops those (2.2.0): people see tokens and a percentage,
|
||||
* and only the Hub shows rand. The token fields are null from a Hub before 2.0.1.
|
||||
*/
|
||||
export type HubAiStatus = {
|
||||
|
||||
@@ -153,8 +153,12 @@ app.use((req, res, next) => {
|
||||
// Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js).
|
||||
app.use(require('./hub/readOnly').licenceReadOnly);
|
||||
|
||||
// Everything the backend serves is under /api (2.2.0), so the site and its API can share one
|
||||
// address: the web server sends /api to the backend and everything else to the frontend. The old
|
||||
// paths (/, /health, /docs/v2, /uploads) still work for sites with a separate API address.
|
||||
|
||||
// Health for monitoring (and the Hub): no secrets, no personal information.
|
||||
app.get('/health', async (req, res) => {
|
||||
app.get(['/api/health', '/health'], async (req, res) => {
|
||||
const report = require('./hub/report');
|
||||
let db = true;
|
||||
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
|
||||
@@ -174,11 +178,11 @@ app.use('/api/v2', linksRouter);
|
||||
app.use('/api/v2', require('./v2').v2Router());
|
||||
// Links in messages already sent: v1 addresses answer 308 with their v2 one.
|
||||
app.use(legacyLinkRedirects);
|
||||
app.use('/docs/v2', require('./v2').v2DocsRouter());
|
||||
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
||||
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
||||
app.use('/api', legacyV1Router);
|
||||
app.use('/api', v1Removed);
|
||||
app.use('/api/docs/v2', require('./v2').v2DocsRouter());
|
||||
app.get('/api/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||
// Before 2.2.0 the reference was at /docs/v2 (bookmarks, the old status page).
|
||||
app.use('/docs/v2', (req, res) => res.redirect(301, `/api${req.originalUrl}`));
|
||||
app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||
|
||||
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
||||
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
||||
@@ -187,12 +191,16 @@ warmCache().catch(() => {});
|
||||
// handlers. Serving them inline lets a compromised/malicious upload run script
|
||||
// in the site's origin if opened directly, so pin the safe response headers
|
||||
// (no inline execution, no MIME-sniffing to HTML/script) on every asset here.
|
||||
app.use('/uploads', express.static('public/uploads', {
|
||||
// Stored paths stay "/uploads/…"; they're given out as /api/uploads/… (v2/schemas.ts absoluteUrl).
|
||||
// /uploads still answers for links made before 2.2.0.
|
||||
const uploads = express.static('public/uploads', {
|
||||
setHeaders: (res) => {
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
},
|
||||
}));
|
||||
});
|
||||
app.use('/api/uploads', uploads, notFound); // a missing file is 404, not "API v1 removed"
|
||||
app.use('/uploads', uploads);
|
||||
|
||||
// ── Shared page helpers ────────────────────────────────────────────────────────
|
||||
|
||||
@@ -268,8 +276,9 @@ app.get('/favicon.ico', (req, res) => {
|
||||
res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico'));
|
||||
});
|
||||
|
||||
// ── Root route — status page ────────────────────────────────────────────────
|
||||
app.get('/', async (req, res) => {
|
||||
// ── Status page, at /api (2.2.0); / sends you there ─────────────────────────
|
||||
app.get('/', (req, res) => res.redirect(302, '/api'));
|
||||
app.get('/api', async (req, res) => {
|
||||
const mem = process.memoryUsage();
|
||||
const uptimeSec = process.uptime();
|
||||
const now = new Date().toISOString();
|
||||
@@ -335,15 +344,18 @@ app.get('/', async (req, res) => {
|
||||
</div>
|
||||
|
||||
<div class="note">
|
||||
API documentation (OpenAPI) is at <a href="/docs/v2">/docs/v2</a> — it needs an admin account token.
|
||||
API documentation (OpenAPI) is at <a href="/api/docs/v2">/api/docs/v2</a> — it needs an admin account token.
|
||||
</div>
|
||||
`);
|
||||
|
||||
res.send(html);
|
||||
});
|
||||
|
||||
// /docs: the v1 reference went with v1 in 2.0; the API is documented at /docs/v2 (OpenAPI).
|
||||
app.get('/docs', (req, res) => res.redirect(301, '/docs/v2'));
|
||||
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
||||
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
||||
// Mounted after everything else under /api, since v1Removed answers 410 for any other /api path.
|
||||
app.use('/api', legacyV1Router);
|
||||
app.use('/api', v1Removed);
|
||||
|
||||
// Error middleware
|
||||
app.use(notFound);
|
||||
@@ -384,7 +396,9 @@ app.listen(PORT, () => {
|
||||
// backup, temp cleanup) run on the pg-boss job queue — see src/jobs/index.js.
|
||||
require('./jobs').startJobs().catch(e => console.warn('[jobs] Not started:', e?.message || e));
|
||||
|
||||
// Check in with the Hub 30 s after starting, so the licence is fresh without waiting 15 minutes.
|
||||
// Installs made from the Hub register by themselves (HUB_LICENCE_KEY), then check in with the
|
||||
// Hub 30 s after starting, so the licence is fresh without waiting 15 minutes.
|
||||
require('./hub/client').connectFromEnv().catch(() => {});
|
||||
require('./hub/client').heartbeatSoon();
|
||||
|
||||
// Scheduled emails worker (polling)
|
||||
|
||||
@@ -45,9 +45,10 @@ function toAbsoluteUrl(req, url) {
|
||||
}
|
||||
return raw; // keep as-is if already absolute and not localhost
|
||||
}
|
||||
// Relative path like /uploads/... => prefix with request origin
|
||||
// Relative path like /uploads/... => prefix with request origin; uploads are served under
|
||||
// /api/uploads (2.2.0) so they reach the backend when the site and API share one address
|
||||
if (raw.startsWith('/')) {
|
||||
return `${req.protocol}://${req.get('host')}${raw}`;
|
||||
return `${req.protocol}://${req.get('host')}${raw.startsWith('/uploads/') ? `/api${raw}` : raw}`;
|
||||
}
|
||||
// Any other case, return as-is
|
||||
return raw;
|
||||
|
||||
@@ -11,6 +11,9 @@ const {
|
||||
resendChallenge,
|
||||
clearTrustedDevices,
|
||||
requiresTwoFactor,
|
||||
replaceRecoveryCodes,
|
||||
recoveryCodesLeft,
|
||||
clearTwoFactor,
|
||||
} = require('../utils/twoFactor');
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||
@@ -99,7 +102,7 @@ const startEnableTwoFactor = async (req, res) => {
|
||||
}
|
||||
if (!TWO_FACTOR_METHODS.includes(method)) {
|
||||
res.status(400);
|
||||
throw new Error('Choose email or WhatsApp for your verification codes');
|
||||
throw new Error('Choose email, WhatsApp or an authenticator app for your verification codes');
|
||||
}
|
||||
if (!(await availableMethods(user)).includes(method)) {
|
||||
res.status(400);
|
||||
@@ -109,7 +112,8 @@ const startEnableTwoFactor = async (req, res) => {
|
||||
}
|
||||
|
||||
// Unlike login, don't fall back to email here — the point of this step is to
|
||||
// prove the channel the user picked actually reaches them.
|
||||
// prove the channel the user picked actually reaches them. For an authenticator app the
|
||||
// answer carries the secret and its otpauth:// link (shown as a QR code) until confirmed.
|
||||
res.json(await createChallenge(user, 'enable', method, { allowFallback: false }));
|
||||
} catch (error) {
|
||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||
@@ -124,13 +128,20 @@ const confirmEnableTwoFactor = async (req, res) => {
|
||||
const { challengeId, code } = req.body || {};
|
||||
const challenge = await verifyChallenge(challengeId, code, 'enable', req.user.id);
|
||||
|
||||
// An authenticator app: the confirmed secret is kept (encrypted). Another method: any app is
|
||||
// forgotten. Either way a fresh set of recovery codes, shown once (2.3.0).
|
||||
await prisma.user.update({
|
||||
where: { id: req.user.id },
|
||||
data: { twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date() },
|
||||
data: {
|
||||
twoFactorEnabled: true, twoFactorMethod: challenge.method, updatedAt: new Date(),
|
||||
...(challenge.method === 'authenticator' ? { totpSecret: challenge.pendingSecret } : { totpSecret: null, totpLastStep: null }),
|
||||
},
|
||||
});
|
||||
await prisma.twoFactorChallenge.update({ where: { id: challenge.id }, data: { pendingSecret: null } }).catch(() => {});
|
||||
const recoveryCodes = await replaceRecoveryCodes(req.user.id);
|
||||
logSecurityEvent({ userId: req.user.id, type: 'two_factor_enabled', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
|
||||
|
||||
res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method });
|
||||
res.json({ twoFactorEnabled: true, twoFactorMethod: challenge.method, recoveryCodes });
|
||||
} catch (error) {
|
||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
@@ -157,7 +168,7 @@ const disableTwoFactor = async (req, res) => {
|
||||
|
||||
await prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: { twoFactorEnabled: false, twoFactorMethod: null, updatedAt: new Date() },
|
||||
data: { ...(await clearTwoFactor(user.id)), updatedAt: new Date() },
|
||||
});
|
||||
await clearTrustedDevices(user.id);
|
||||
if (user.twoFactorEnabled) {
|
||||
@@ -170,6 +181,27 @@ const disableTwoFactor = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// @desc A new set of recovery codes (the old ones stop working), shown once (2.3.0)
|
||||
// @route POST /api/v2/me/two-factor/recovery-codes
|
||||
// @access Private
|
||||
const replaceMyRecoveryCodes = async (req, res) => {
|
||||
try {
|
||||
const { password } = req.body || {};
|
||||
const user = await prisma.user.findUnique({ where: { id: req.user.id } });
|
||||
if (!user) { res.status(404); throw new Error('User not found'); }
|
||||
if (!user.twoFactorEnabled) { res.status(400); throw new Error('Turn on two-factor authentication first.'); }
|
||||
if (typeof password !== 'string' || !(await comparePassword(password, user.password))) {
|
||||
res.status(400);
|
||||
throw new Error('Incorrect password');
|
||||
}
|
||||
const recoveryCodes = await replaceRecoveryCodes(user.id);
|
||||
logSecurityEvent({ userId: user.id, type: 'recovery_codes_replaced', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
|
||||
res.json({ recoveryCodes });
|
||||
} catch (error) {
|
||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||
}
|
||||
};
|
||||
|
||||
// @desc Re-confirm the logged-in user's password without starting a new session
|
||||
// (the self-service kiosk uses this before letting the event be changed)
|
||||
// @route POST /api/users/verify-password
|
||||
@@ -220,7 +252,7 @@ const getUserProfile = async (req, res) => {
|
||||
const noticePromptPending = !req.impersonation && await require('../utils/privacyNotice').noticePromptPending({ noticeVersionAccepted });
|
||||
// Campus-scoped staff: the campuses they're limited to (null = every campus).
|
||||
const campusScope = (await require('../utils/campusScope').scopeFor(req))?.campusIds || null;
|
||||
res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope });
|
||||
res.json({ ...rest, twoFactorRequired: requiresTwoFactor(user), recoveryCodesLeft: user.twoFactorEnabled ? await recoveryCodesLeft(user.id) : 0, newsPromptPending: !newsAskedAt && !req.impersonation, noticePromptPending, campusScope });
|
||||
} else {
|
||||
res.status(404);
|
||||
throw new Error('User not found');
|
||||
@@ -253,7 +285,7 @@ const getUsers = async (req, res) => {
|
||||
|
||||
const select = {
|
||||
id: true, name: true, email: true, role: true,
|
||||
phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, createdAt: true, updatedAt: true, isActive: true
|
||||
phoneNumber: true, notificationPreference: true, twoFactorEnabled: true, twoFactorMethod: true, createdAt: true, updatedAt: true, isActive: true
|
||||
};
|
||||
|
||||
// Build filters
|
||||
@@ -406,8 +438,8 @@ const updateUser = async (req, res) => {
|
||||
// but never on — enabling requires the user to prove the channel themselves.
|
||||
const resetTwoFactor = twoFactorEnabled === false && user.twoFactorEnabled;
|
||||
if (resetTwoFactor) {
|
||||
data.twoFactorEnabled = false;
|
||||
data.twoFactorMethod = null;
|
||||
// The app's secret and the recovery codes go too (2.3.0).
|
||||
Object.assign(data, await clearTwoFactor(user.id));
|
||||
}
|
||||
|
||||
// Promoted to a role that requires 2FA without having it: end their sessions
|
||||
@@ -443,6 +475,7 @@ const updateUser = async (req, res) => {
|
||||
phoneNumber: true,
|
||||
notificationPreference: true,
|
||||
twoFactorEnabled: true,
|
||||
twoFactorMethod: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
isActive: true,
|
||||
@@ -820,6 +853,7 @@ module.exports = {
|
||||
startEnableTwoFactor,
|
||||
confirmEnableTwoFactor,
|
||||
disableTwoFactor,
|
||||
replaceMyRecoveryCodes,
|
||||
verifyPassword,
|
||||
getUserProfile,
|
||||
updateUserProfile,
|
||||
|
||||
@@ -216,4 +216,33 @@ function heartbeatSoon(delayMs = 30 * 1000) {
|
||||
soonTimer.unref?.();
|
||||
}
|
||||
|
||||
module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, signedPost, connect, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };
|
||||
/**
|
||||
* Installs made from the Hub (crosscode install, docs/AGENT-1.0-PLAN.md §7) have the licence key in
|
||||
* HUB_LICENCE_KEY: the site registers by itself on its first start, instead of in /setup. Does
|
||||
* nothing once registered, or without the key. Retries a few times (the Hub may be briefly
|
||||
* unreachable); a refused key is logged and left for /setup. Never throws.
|
||||
*/
|
||||
async function connectFromEnv({ attempts = 5, delayMs = 60 * 1000, sleep = ms => new Promise(r => setTimeout(r, ms).unref?.()) } = {}) {
|
||||
const key = String(process.env.HUB_LICENCE_KEY || '').trim();
|
||||
if (!key) return { connected: false, reason: 'no_key' };
|
||||
for (let i = 1; i <= attempts; i++) {
|
||||
try {
|
||||
const stored = await read(['hub_install_id']);
|
||||
if (stored.hub_install_id) return { connected: false, reason: 'already' };
|
||||
const name = String(process.env.HUB_ADMIN_NAME || '').trim() || null;
|
||||
const email = String(process.env.HUB_ADMIN_EMAIL || '').trim() || null;
|
||||
await connect(key, name || email ? { name, email } : null);
|
||||
console.log('[hub] Registered with the Hub using HUB_LICENCE_KEY.');
|
||||
return { connected: true };
|
||||
} catch (e) {
|
||||
const status = e?.statusCode || 0;
|
||||
console.warn(`[hub] Registering with HUB_LICENCE_KEY failed (attempt ${i} of ${attempts}):`, e?.message || e);
|
||||
// The Hub said no (unknown, revoked or in-use key): retrying won't help.
|
||||
if (status >= 400 && status < 500) return { connected: false, reason: e?.code || 'refused' };
|
||||
if (i < attempts) await sleep(delayMs);
|
||||
}
|
||||
}
|
||||
return { connected: false, reason: 'unreachable' };
|
||||
}
|
||||
|
||||
module.exports = { PROTOCOL_VERSION, HUB_KEYS, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };
|
||||
|
||||
@@ -16,7 +16,8 @@ const auth = require('../config/auth') as {
|
||||
};
|
||||
const twoFactor = require('../utils/twoFactor') as {
|
||||
createChallenge(user: any, purpose: string, method: string): Promise<{ challengeId: string; method: string; destination: string | null }>;
|
||||
verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string }>;
|
||||
verifyChallenge(challengeId: string, code: string, purpose: string): Promise<{ userId: string; method: string; usedRecoveryCode?: boolean }>;
|
||||
recoveryCodesLeft(userId: string): Promise<number>;
|
||||
issueTrustedDevice(userId: string, userAgent?: string): Promise<string>;
|
||||
isTrustedDevice(userId: string, deviceToken?: string): Promise<boolean>;
|
||||
clearTrustedDevices(userId: string): Promise<unknown>;
|
||||
@@ -279,6 +280,10 @@ export async function verifyLoginCode(input: { challengeId: string; code: string
|
||||
user = await prisma.user.update({ where: { id: user.id }, data: { twoFactorEnabled: true, twoFactorMethod: challenge.method as 'email' | 'whatsapp', updatedAt: new Date() }, select: LOGIN_USER_SELECT });
|
||||
logSecurityEvent({ userId: user.id, type: 'two_factor_enabled', ip: info.ip, userAgent: info.userAgent }).catch(() => {});
|
||||
}
|
||||
// 2.3.0: a recovery code was used instead (the app or phone may be lost): it's in the activity log.
|
||||
if (challenge.usedRecoveryCode) {
|
||||
logSecurityEvent({ userId: user.id, type: 'recovery_code_used', ip: info.ip, userAgent: info.userAgent }).catch(() => {});
|
||||
}
|
||||
const extra = input.rememberDevice === true ? { deviceToken: await twoFactor.issueTrustedDevice(user.id, info.userAgent) } : {};
|
||||
return completeLogin(user, info, extra);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
/**
|
||||
* The church's data when it leaves: crosscode.church-export/1 (packages/contracts,
|
||||
* docs/AGENT-1.0-PLAN.md §9). Plain terms and our own field names: no tables, Prisma models or
|
||||
* internal ids. Records point at each other with references made for the export (p1, e1, t1, r1)
|
||||
* that mean nothing outside the file. `crosscode export` runs scripts/export-church.ts, which
|
||||
* writes this as export.json next to the uploads.
|
||||
*
|
||||
* Not included: passwords, 2FA secrets, tokens, provider keys, audit and access logs (they're
|
||||
* about the site's running, not the church's data), and analytics.
|
||||
*/
|
||||
import { prisma } from '../v2/legacy';
|
||||
|
||||
type Row = Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any -- rows from Prisma
|
||||
|
||||
const iso = (d: unknown): string | null => (d instanceof Date ? d.toISOString() : d ? new Date(String(d)).toISOString() : null);
|
||||
const cents = (rand: unknown): number => Math.round(Number(rand || 0) * 100);
|
||||
|
||||
/** Hands out p1, p2 … for ids, in the order they're first seen. */
|
||||
class Refs {
|
||||
private map = new Map<string, string>();
|
||||
constructor(private prefix: string) {}
|
||||
of(id: string | null | undefined): string | null {
|
||||
if (!id) return null;
|
||||
let r = this.map.get(id);
|
||||
if (!r) {
|
||||
r = `${this.prefix}${this.map.size + 1}`;
|
||||
this.map.set(id, r);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
has(id: string | null | undefined): boolean {
|
||||
return !!id && this.map.has(id);
|
||||
}
|
||||
}
|
||||
|
||||
/** Settings worth giving back (never secrets: those are stored encrypted under other keys). */
|
||||
export const EXPORT_SETTING_KEYS = [
|
||||
'org_name', 'org_tagline', 'org_email', 'org_phone', 'org_address', 'org_website', 'brand_primary_color', 'logo_url', 'favicon_url',
|
||||
'app_name', 'timezone', 'currency', 'privacy_contact_email',
|
||||
];
|
||||
|
||||
export type ExportInput = {
|
||||
users: Row[]; events: Row[]; registrations: Row[]; payments: Row[]; usages: Row[]; slots: Row[]; roles: Row[];
|
||||
settings: Row[]; fields: Row[]; version: string;
|
||||
};
|
||||
|
||||
/** Builds the export from rows (kept separate from the database reads, so it can be tested). */
|
||||
export function buildExport(input: ExportInput, now = new Date()) {
|
||||
const people = new Refs('p');
|
||||
const events = new Refs('e');
|
||||
const tickets = new Refs('t');
|
||||
const regs = new Refs('r');
|
||||
const labels = new Map(input.fields.map(f => [f.id, String(f.label)]));
|
||||
const settings = Object.fromEntries(input.settings.filter(s => EXPORT_SETTING_KEYS.includes(s.key)).map(s => [s.key, String(s.value)]));
|
||||
|
||||
const out = {
|
||||
schema: 'crosscode.church-export/1' as const,
|
||||
exportedAt: now.toISOString(),
|
||||
product: 'events' as const,
|
||||
productVersion: input.version,
|
||||
church: { name: settings.org_name || 'Church', timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg' },
|
||||
people: input.users.map(u => ({
|
||||
ref: people.of(u.id)!,
|
||||
name: String(u.name || ''),
|
||||
email: u.email || null,
|
||||
phone: u.phoneNumber || null,
|
||||
role: String(u.role || 'user'),
|
||||
createdAt: iso(u.createdAt),
|
||||
consent: { email: typeof u.newsEmail === 'boolean' ? u.newsEmail : null, whatsapp: typeof u.newsWhatsApp === 'boolean' ? u.newsWhatsApp : null, privacyNoticeAcceptedAt: null },
|
||||
})),
|
||||
events: input.events.map(e => ({
|
||||
ref: events.of(e.id)!,
|
||||
title: String(e.title || ''),
|
||||
description: e.description || null,
|
||||
startsAt: iso(e.startDate),
|
||||
endsAt: iso(e.endDate),
|
||||
location: e.location || null,
|
||||
sessions: (e.sessions || []).map((s: Row) => ({ label: s.label || null, startsAt: iso(s.startsAt), endsAt: iso(s.endsAt) })),
|
||||
ticketTypes: (e.eventOptions || []).map((o: Row) => ({ ref: tickets.of(o.id)!, name: String(o.name || ''), priceCents: cents(o.price), currency: 'ZAR' })),
|
||||
capacity: null as number | null,
|
||||
published: !!e.isActive && !e.isHidden,
|
||||
})),
|
||||
registrations: input.registrations.filter(r => events.has(r.eventId)).map(r => ({
|
||||
ref: regs.of(r.id)!,
|
||||
eventRef: events.of(r.eventId)!,
|
||||
personRef: people.has(r.userId) ? people.of(r.userId) : null,
|
||||
status: String(r.status),
|
||||
createdAt: iso(r.createdAt),
|
||||
attendees: (r.attendees || []).map((a: Row) => ({
|
||||
name: String(a.name || ''),
|
||||
email: a.email || null,
|
||||
ticketTypeRef: tickets.has(a.eventOptionId) ? tickets.of(a.eventOptionId) : null,
|
||||
checkedInAt: iso(a.ticket?.usages?.[0]?.scannedAt),
|
||||
})),
|
||||
answers: (r.formResponses || []).flatMap((fr: Row) => (fr.answers || []).map((x: Row) => ({ question: labels.get(x.fieldId) || 'Question', answer: String(x.value ?? '') }))),
|
||||
})),
|
||||
payments: input.payments.map(p => ({
|
||||
registrationRef: regs.has(p.registrationId) ? regs.of(p.registrationId) : null,
|
||||
amountCents: cents(p.amount),
|
||||
currency: 'ZAR',
|
||||
method: String(p.method || 'unknown'),
|
||||
status: String(p.status || 'completed'),
|
||||
paidAt: iso(p.createdAt),
|
||||
reference: p.externalId || null,
|
||||
})),
|
||||
checkIns: input.usages.filter(u => events.has(u.ticket?.eventId)).map(u => ({
|
||||
eventRef: events.of(u.ticket.eventId)!,
|
||||
personRef: people.has(u.ticket?.holderUserId || u.ticket?.userId) ? people.of(u.ticket.holderUserId || u.ticket.userId) : null,
|
||||
name: u.ticket?.attendee?.name || null,
|
||||
at: iso(u.scannedAt),
|
||||
})),
|
||||
rosters: input.slots.map(s => {
|
||||
const role = input.roles.find(r => r.id === s.roleId);
|
||||
return {
|
||||
eventRef: role && events.has(role.eventId) ? events.of(role.eventId) : null,
|
||||
role: String(role?.name || 'Volunteer'),
|
||||
personRef: people.has(s.userId) ? people.of(s.userId) : null,
|
||||
startsAt: iso(role?.startsAt),
|
||||
endsAt: iso(role?.endsAt),
|
||||
};
|
||||
}),
|
||||
settings,
|
||||
files: [] as { path: string; bytes: number }[],
|
||||
};
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Reads everything the export needs. */
|
||||
export async function readExportInput(version: string): Promise<ExportInput> {
|
||||
const [users, events, registrations, payments, usages, slots, roles, settings, fields] = await Promise.all([
|
||||
prisma.user.findMany({ orderBy: { createdAt: 'asc' } }),
|
||||
prisma.event.findMany({ orderBy: { startDate: 'asc' }, include: { sessions: { orderBy: { order: 'asc' } }, eventOptions: true } }),
|
||||
prisma.registration.findMany({ orderBy: { createdAt: 'asc' }, include: { attendees: { orderBy: { order: 'asc' }, include: { ticket: { include: { usages: { orderBy: { scannedAt: 'asc' }, take: 1 } } } } }, formResponses: { include: { answers: true } } } }),
|
||||
prisma.payment.findMany({ orderBy: { createdAt: 'asc' } }),
|
||||
prisma.ticketUsage.findMany({ orderBy: { scannedAt: 'asc' }, include: { ticket: { include: { attendee: true } } } }),
|
||||
prisma.volunteerSlot.findMany(),
|
||||
prisma.servingRole.findMany(),
|
||||
prisma.appSetting.findMany(),
|
||||
prisma.eventFormField.findMany(),
|
||||
]);
|
||||
return { users, events, registrations, payments, usages, slots, roles, settings, fields, version } as ExportInput;
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
/**
|
||||
* Codes from an authenticator app (2.3.0; RFC 6238 TOTP: SHA-1, 6 digits, 30 seconds), the same
|
||||
* as Cross Code Hub's. `matchStep` says which 30-second step a code belongs to, so a code that was
|
||||
* used once is refused the second time (utils/twoFactor.js keeps the last step used).
|
||||
*/
|
||||
|
||||
const crypto = require('crypto');
|
||||
|
||||
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
||||
const STEP = 30;
|
||||
|
||||
function base32Encode(buf) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
let out = '';
|
||||
for (const byte of buf) {
|
||||
value = (value << 8) | byte;
|
||||
bits += 8;
|
||||
while (bits >= 5) {
|
||||
out += BASE32[(value >>> (bits - 5)) & 31];
|
||||
bits -= 5;
|
||||
}
|
||||
}
|
||||
if (bits > 0) out += BASE32[(value << (5 - bits)) & 31];
|
||||
return out;
|
||||
}
|
||||
|
||||
function base32Decode(str) {
|
||||
let bits = 0;
|
||||
let value = 0;
|
||||
const out = [];
|
||||
for (const ch of String(str).toUpperCase().replace(/=+$/, '')) {
|
||||
const idx = BASE32.indexOf(ch);
|
||||
if (idx === -1) continue;
|
||||
value = (value << 5) | idx;
|
||||
bits += 5;
|
||||
if (bits >= 8) {
|
||||
out.push((value >>> (bits - 8)) & 255);
|
||||
bits -= 8;
|
||||
}
|
||||
}
|
||||
return Buffer.from(out);
|
||||
}
|
||||
|
||||
/** A new secret: 20 random bytes, base32 (what the app stores). */
|
||||
function generateSecret() {
|
||||
return base32Encode(crypto.randomBytes(20));
|
||||
}
|
||||
|
||||
function codeAt(secret, counter) {
|
||||
const buf = Buffer.alloc(8);
|
||||
buf.writeBigUInt64BE(BigInt(counter));
|
||||
const hmac = crypto.createHmac('sha1', base32Decode(secret)).update(buf).digest();
|
||||
const offset = hmac[hmac.length - 1] & 0xf;
|
||||
const num = ((hmac[offset] & 0x7f) << 24) | (hmac[offset + 1] << 16) | (hmac[offset + 2] << 8) | hmac[offset + 3];
|
||||
return String(num % 1_000_000).padStart(6, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* The step `code` is right for (now, or one step either side for clock drift), or null. Steps at
|
||||
* or before `afterStep` don't count: that code was already used.
|
||||
*/
|
||||
function matchStep(secret, code, { now = Date.now(), afterStep = -1 } = {}) {
|
||||
const clean = String(code || '').replace(/\D/g, '');
|
||||
if (clean.length !== 6) return null;
|
||||
const counter = Math.floor(now / 1000 / STEP);
|
||||
for (const c of [counter - 1, counter, counter + 1]) {
|
||||
if (c <= afterStep) continue;
|
||||
if (crypto.timingSafeEqual(Buffer.from(codeAt(secret, c)), Buffer.from(clean))) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The otpauth:// link an authenticator app scans (as a QR code). */
|
||||
function otpauthUrl(secret, account, issuer) {
|
||||
const label = `${issuer}:${account}`;
|
||||
return `otpauth://totp/${encodeURIComponent(label)}?secret=${secret}&issuer=${encodeURIComponent(issuer)}&algorithm=SHA1&digits=6&period=${STEP}`;
|
||||
}
|
||||
|
||||
module.exports = { STEP, generateSecret, codeAt, matchStep, otpauthUrl, base32Encode, base32Decode };
|
||||
@@ -16,7 +16,9 @@ const RESEND_COOLDOWN_MS = 60 * 1000; // minimum gap between sends
|
||||
const CHALLENGE_MAX_AGE_MS = 30 * 60 * 1000; // after this, log in again rather than resend
|
||||
const TRUSTED_DEVICE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
|
||||
const METHODS = ['email', 'whatsapp'];
|
||||
// 2.3.0: 'authenticator' — codes from an app (TOTP, utils/totp.js); nothing is sent.
|
||||
const METHODS = ['email', 'whatsapp', 'authenticator'];
|
||||
const RECOVERY_CODE_COUNT = 10;
|
||||
|
||||
// Roles that must use two-factor authentication.
|
||||
const REQUIRED_ROLES = ['admin', 'supervisor'];
|
||||
@@ -67,9 +69,75 @@ async function availableMethods(user) {
|
||||
const methods = [];
|
||||
if (hasRealEmail(user)) methods.push('email');
|
||||
if (isValidZAPhone(user?.phoneNumber) && (await isConfigured())) methods.push('whatsapp');
|
||||
// An authenticator app needs nothing from the site, so it's always possible.
|
||||
methods.push('authenticator');
|
||||
return methods;
|
||||
}
|
||||
|
||||
// ─── Authenticator app (2.3.0) ───────────────────────────────────────────────
|
||||
|
||||
const totp = require('./totp');
|
||||
const { encrypt, decrypt } = require('./encryption');
|
||||
|
||||
/** A new secret for setting up an app, with the link and text to show (not saved yet). */
|
||||
function newAuthenticatorSecret(user) {
|
||||
const { getSettingSync } = require('./settingsCache');
|
||||
const issuer = getSettingSync('org_name', process.env.ORG_NAME || 'Cross Events');
|
||||
const secret = totp.generateSecret();
|
||||
return { secret, otpauthUrl: totp.otpauthUrl(secret, user.email, issuer) };
|
||||
}
|
||||
|
||||
// Recovery codes: xxxxx-xxxxx from an alphabet without look-alikes; stored as an HMAC.
|
||||
const RECOVERY_ALPHABET = 'abcdefghjkmnpqrstuvwxyz23456789';
|
||||
const normaliseRecovery = (code) => String(code || '').toLowerCase().replace(/[^a-z0-9]/g, '');
|
||||
const hashRecovery = (code) => hmac(`2fa-recovery:${normaliseRecovery(code)}`);
|
||||
const looksLikeRecoveryCode = (code) => normaliseRecovery(code).length === 10;
|
||||
|
||||
function randomRecoveryCode() {
|
||||
let s = '';
|
||||
for (let i = 0; i < 10; i++) s += RECOVERY_ALPHABET[crypto.randomInt(0, RECOVERY_ALPHABET.length)];
|
||||
return `${s.slice(0, 5)}-${s.slice(5)}`;
|
||||
}
|
||||
|
||||
/** A new set of recovery codes (the old ones stop working). Returns the codes to show once. */
|
||||
async function replaceRecoveryCodes(userId, db = prisma) {
|
||||
const codes = Array.from({ length: RECOVERY_CODE_COUNT }, randomRecoveryCode);
|
||||
await db.recoveryCode.deleteMany({ where: { userId } });
|
||||
await db.recoveryCode.createMany({ data: codes.map(c => ({ userId, codeHash: hashRecovery(c) })) });
|
||||
return codes;
|
||||
}
|
||||
|
||||
async function recoveryCodesLeft(userId) {
|
||||
return prisma.recoveryCode.count({ where: { userId, usedAt: null } });
|
||||
}
|
||||
|
||||
/** Uses a recovery code if it's one of this user's unused ones (single use, race-safe). */
|
||||
async function useRecoveryCode(userId, code) {
|
||||
if (!looksLikeRecoveryCode(code)) return false;
|
||||
const used = await prisma.recoveryCode.updateMany({ where: { userId, codeHash: hashRecovery(code), usedAt: null }, data: { usedAt: new Date() } });
|
||||
return used.count === 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks an app code against `secret` and records its step, so the same code can't be used again
|
||||
* (the update only succeeds if no later step was recorded meanwhile).
|
||||
*/
|
||||
async function useAuthenticatorCode(user, secret, code) {
|
||||
const step = totp.matchStep(secret, code, { afterStep: user.totpLastStep ?? -1 });
|
||||
if (step === null) return false;
|
||||
const saved = await prisma.user.updateMany({
|
||||
where: { id: user.id, OR: [{ totpLastStep: null }, { totpLastStep: { lt: step } }] },
|
||||
data: { totpLastStep: step },
|
||||
});
|
||||
return saved.count === 1;
|
||||
}
|
||||
|
||||
/** Turns 2FA off completely: the app's secret and the recovery codes go too. */
|
||||
async function clearTwoFactor(userId, db = prisma) {
|
||||
await db.recoveryCode.deleteMany({ where: { userId } });
|
||||
return { twoFactorEnabled: false, twoFactorMethod: null, totpSecret: null, totpLastStep: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this user's role must use two-factor authentication.
|
||||
* TWO_FACTOR_REQUIRED_ROLES=false turns the requirement off (break-glass).
|
||||
@@ -143,6 +211,20 @@ async function deliverCode(user, method, code, { allowFallback = true } = {}) {
|
||||
* purpose for this user is discarded, so only the newest code works.
|
||||
*/
|
||||
async function createChallenge(user, purpose, method, options) {
|
||||
if (method === 'authenticator') {
|
||||
// Nothing is sent: the code comes from the app. Setting it up carries the new secret,
|
||||
// encrypted, until the first code proves the app has it.
|
||||
const setup = purpose === 'enable' ? newAuthenticatorSecret(user) : null;
|
||||
// (Looked up here: the user passed in may be a selection that leaves the secret out.)
|
||||
if (purpose !== 'enable' && !(await prisma.user.findUnique({ where: { id: user.id }, select: { totpSecret: true } }))?.totpSecret) {
|
||||
throw fail('No authenticator app is set up for this account.', 400);
|
||||
}
|
||||
await prisma.twoFactorChallenge.deleteMany({ where: { userId: user.id, purpose } });
|
||||
const challenge = await prisma.twoFactorChallenge.create({
|
||||
data: { userId: user.id, purpose, method: 'authenticator', codeHash: '', pendingSecret: setup ? encrypt(setup.secret) : null, expiresAt: new Date(Date.now() + CODE_TTL_MS) },
|
||||
});
|
||||
return { challengeId: challenge.id, method: 'authenticator', destination: 'your authenticator app', ...(setup ? { secret: setup.secret, otpauthUrl: setup.otpauthUrl } : {}) };
|
||||
}
|
||||
const code = generateCode();
|
||||
const sent = await deliverCode(user, method, code, options);
|
||||
|
||||
@@ -185,9 +267,23 @@ async function verifyChallenge(challengeId, code, purpose, userId) {
|
||||
if (counted.count !== 1) throw invalid();
|
||||
|
||||
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
|
||||
if (!challenge || !safeEqual(challenge.codeHash, hashCode(submitted))) {
|
||||
let ok = false;
|
||||
let usedRecoveryCode = false;
|
||||
if (challenge?.method === 'authenticator') {
|
||||
const stored = purpose === 'enable' ? challenge.pendingSecret : challenge.user?.totpSecret;
|
||||
ok = !!stored && (await useAuthenticatorCode(challenge.user, decrypt(stored), submitted));
|
||||
} else if (challenge) {
|
||||
ok = safeEqual(challenge.codeHash, hashCode(submitted));
|
||||
}
|
||||
// At sign-in, a recovery code works in place of any code (2.3.0).
|
||||
if (!ok && challenge && purpose === 'login' && challenge.user?.twoFactorEnabled && (await useRecoveryCode(challenge.userId, code))) {
|
||||
ok = true;
|
||||
usedRecoveryCode = true;
|
||||
}
|
||||
if (!ok) {
|
||||
const left = challenge ? MAX_ATTEMPTS - challenge.attempts : 0;
|
||||
throw fail(left > 0 ? `Incorrect code. ${left} attempt${left === 1 ? '' : 's'} left.` : 'Too many incorrect attempts. Please request a new code.');
|
||||
const again = challenge?.method === 'authenticator' ? 'Please log in again.' : 'Please request a new code.';
|
||||
throw fail(left > 0 ? `Incorrect code. ${left} attempt${left === 1 ? '' : 's'} left.` : `Too many incorrect attempts. ${again}`);
|
||||
}
|
||||
|
||||
// Single use — if two requests race with the right code, only one wins.
|
||||
@@ -197,7 +293,7 @@ async function verifyChallenge(challengeId, code, purpose, userId) {
|
||||
});
|
||||
if (used.count !== 1) throw invalid();
|
||||
|
||||
return challenge;
|
||||
return { ...challenge, usedRecoveryCode };
|
||||
}
|
||||
|
||||
/** Replaces the code on an existing challenge and sends it again. */
|
||||
@@ -208,6 +304,7 @@ async function resendChallenge(challengeId, purpose, userId) {
|
||||
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
|
||||
if (!challenge || challenge.purpose !== purpose || challenge.usedAt || (userId && challenge.userId !== userId)) throw expired();
|
||||
if (Date.now() - challenge.createdAt.getTime() > CHALLENGE_MAX_AGE_MS) throw expired();
|
||||
if (challenge.method === 'authenticator') throw fail('Nothing is sent for an authenticator app: open the app for the current code, or use one of your recovery codes.');
|
||||
|
||||
const wait = RESEND_COOLDOWN_MS - (Date.now() - challenge.lastSentAt.getTime());
|
||||
if (wait > 0) throw fail(`Please wait ${Math.ceil(wait / 1000)} seconds before requesting another code.`, 429);
|
||||
@@ -264,6 +361,13 @@ async function clearTrustedDevices(userId) {
|
||||
|
||||
module.exports = {
|
||||
METHODS,
|
||||
RECOVERY_CODE_COUNT,
|
||||
replaceRecoveryCodes,
|
||||
recoveryCodesLeft,
|
||||
useRecoveryCode,
|
||||
useAuthenticatorCode,
|
||||
clearTwoFactor,
|
||||
newAuthenticatorSecret,
|
||||
REQUIRED_ROLES,
|
||||
requiresTwoFactor,
|
||||
enforcementMethod,
|
||||
|
||||
@@ -269,7 +269,7 @@ async function sendPdf(toPhone, localPdfPath, filename, caption) {
|
||||
`Set BACKEND_URL to your public backend URL (e.g. https://api.yourdomain.com) in your .env file.`
|
||||
);
|
||||
}
|
||||
const pdfUrl = `${backendUrl}/uploads/tickets-temp/${tempName}`;
|
||||
const pdfUrl = `${backendUrl}/api/uploads/tickets-temp/${tempName}`;
|
||||
|
||||
const { token, instanceId } = await getConfig();
|
||||
try {
|
||||
|
||||
@@ -51,6 +51,8 @@ export const user = obj({
|
||||
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
|
||||
isActive: optBool,
|
||||
notificationPreference: z.enum(['email', 'whatsapp', 'both']).nullish(),
|
||||
twoFactorEnabled: optBool,
|
||||
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullish().describe('How their sign-in codes come (2.3.0: authenticator = an app)'),
|
||||
homeCampusId: optStr,
|
||||
createdAt: optDate,
|
||||
});
|
||||
|
||||
@@ -43,7 +43,7 @@ export function v2Router(): Router {
|
||||
}
|
||||
|
||||
/**
|
||||
* /docs/v2: Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
||||
* /api/docs/v2 (2.2.0; /docs/v2 before, which now redirects): Swagger UI (served from swagger-ui-dist, nothing from a CDN). The page itself is
|
||||
* public; it asks for an admin token and uses it to load openapi.json and to try requests.
|
||||
*/
|
||||
export function v2DocsRouter(): Router {
|
||||
@@ -62,7 +62,7 @@ const DOCS_HTML = `<!doctype html>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Cross Events API v2</title>
|
||||
<link rel="stylesheet" href="/docs/v2/assets/swagger-ui.css">
|
||||
<link rel="stylesheet" href="/api/docs/v2/assets/swagger-ui.css">
|
||||
<style>
|
||||
body { margin: 0; font-family: system-ui, sans-serif; }
|
||||
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
||||
@@ -81,7 +81,7 @@ const DOCS_HTML = `<!doctype html>
|
||||
<p class="err" id="err" role="alert"></p>
|
||||
</main>
|
||||
<div id="ui"></div>
|
||||
<script src="/docs/v2/assets/swagger-ui-bundle.js"></script>
|
||||
<script src="/api/docs/v2/assets/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
(function () {
|
||||
var params = new URLSearchParams(location.search);
|
||||
|
||||
@@ -55,7 +55,7 @@ legacyV1Router.post('/privacy/unsubscribe/:token/one-click', express.urlencoded(
|
||||
/** Any other v1 address: gone since 2.0 (410, pointing at v2). /api/v2 misses fall through to 404. */
|
||||
export const v1Removed: RequestHandler = (req, res, next) => {
|
||||
if (req.path === '/v2' || req.path.startsWith('/v2/')) return next();
|
||||
res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /docs/v2.' });
|
||||
res.status(410).json({ code: 'API_V1_REMOVED', message: 'API v1 was removed in Cross Events 2.0. Use /api/v2 — it is described at /api/docs/v2.' });
|
||||
};
|
||||
|
||||
export const legacyLinkRedirects: RequestHandler = (req, res, next) => {
|
||||
|
||||
@@ -5,7 +5,7 @@ import { PATH_HELP, QUERY_HELP } from './docs';
|
||||
|
||||
/**
|
||||
* The OpenAPI 3.1 document for /api/v2, built from the route declarations (route.ts), so it is
|
||||
* always what the code does. Served at /api/v2/openapi.json, shown at /docs/v2.
|
||||
* always what the code does. Served at /api/v2/openapi.json, shown at /api/docs/v2.
|
||||
*/
|
||||
|
||||
type JsonSchema = Record<string, unknown>;
|
||||
|
||||
@@ -26,7 +26,7 @@ const toMe = (u: MeRow): z.input<typeof me> => ({
|
||||
});
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any -- the JS helpers below aren't typed yet */
|
||||
const { requiresTwoFactor } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean };
|
||||
const { requiresTwoFactor, recoveryCodesLeft } = require('../../utils/twoFactor') as { requiresTwoFactor(user: object): boolean; recoveryCodesLeft(userId: string): Promise<number> };
|
||||
const privacyNotice = require('../../utils/privacyNotice') as { noticePromptPending(u: { noticeVersionAccepted: unknown }): Promise<false | 'first' | 'updated'> };
|
||||
const campusScope = require('../../utils/campusScope') as { scopeFor(req: unknown): Promise<{ campusIds: string[] | null } | null> };
|
||||
|
||||
@@ -39,6 +39,8 @@ export const getMe = defineRoute({
|
||||
access: 'user',
|
||||
response: single(me.extend({
|
||||
twoFactorRequired: z.boolean().describe('Their role must use two-step sign-in'),
|
||||
twoFactorMethod: z.enum(['email', 'whatsapp', 'authenticator']).nullable().describe('How their codes come (2.3.0: authenticator = an app)'),
|
||||
recoveryCodesLeft: z.number().int().describe('Unused recovery codes (0 with two-step sign-in off)'),
|
||||
newsPromptPending: z.boolean(),
|
||||
noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]),
|
||||
campusScope: z.array(id).nullable(),
|
||||
@@ -54,6 +56,8 @@ export const getMe = defineRoute({
|
||||
data: {
|
||||
...toMe(u),
|
||||
twoFactorRequired: requiresTwoFactor(u),
|
||||
twoFactorMethod: u.twoFactorEnabled ? (u.twoFactorMethod ?? null) : null,
|
||||
recoveryCodesLeft: u.twoFactorEnabled ? await recoveryCodesLeft(u.id) : 0,
|
||||
newsPromptPending: !u.newsAskedAt && !impersonating,
|
||||
noticePromptPending: impersonating ? false as const : await privacyNotice.noticePromptPending({ noticeVersionAccepted: u.noticeVersionAccepted }),
|
||||
campusScope: (await campusScope.scopeFor(req))?.campusIds ?? null,
|
||||
|
||||
@@ -42,7 +42,7 @@ const SCOPE_LIST = 'scopeList (the handler filters by listWhere)';
|
||||
|
||||
// ─── Documented shapes (docs.ts) ─────────────────────────────────────────────
|
||||
|
||||
const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp']), destination: D.str.describe('Where the code went, partly hidden') });
|
||||
const challenge = D.obj({ challengeId: D.str, method: z.enum(['email', 'whatsapp', 'authenticator']), destination: D.str.describe('Where the code went, partly hidden') });
|
||||
const signedIn = D.obj({ message: D.optStr, id: D.str, name: D.str, email: D.str, role: D.str, token: D.str.describe('A new sign-in token') });
|
||||
const kind = z.enum(['update', 'news']).describe('update: about something they booked (always sent). news: needs their news consent');
|
||||
const attendeeFilter = D.obj({
|
||||
@@ -90,8 +90,9 @@ v1Route({ method: 'post', path: '/me/sessions/revoke', tag: 'Me', summary: 'Sign
|
||||
v1Route({ method: 'post', path: '/me/close', tag: 'Me', summary: 'Close my account', description: 'Needs the password. Personal details are removed; payment records stay, anonymised.', access: 'user', body: loose, documented: { body: D.obj({ password: D.str, deleteData: D.optBool.describe('Also ask for my personal information to be deleted') }), response: D.message }, v1: users.closeAccount });
|
||||
v1Route({ method: 'get', path: '/me/activity', tag: 'Me', summary: 'Recent sign-ins and changes to my account', access: 'user', documented: { response: z.array(D.obj({ id: D.str, type: D.str.describe('login, password_changed, two_factor_enabled…'), device: D.optStr, createdAt: D.date })) }, v1: users.getMyActivity });
|
||||
v1Route({ method: 'post', path: '/me/verify-password', tag: 'Me', summary: 'Check my password (before a sensitive change)', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.ok }, v1: users.verifyPassword });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp']), password: D.str }), response: challenge }, v1: users.startEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str }) }, v1: users.confirmEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/enable', tag: 'Me', summary: 'Start turning on two-step sign-in', description: 'Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app\x27s first code confirms it.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ method: z.enum(['email', 'whatsapp', 'authenticator']), password: D.str }), response: challenge.extend({ secret: D.optStr.describe('authenticator: the key to type in by hand'), otpauthUrl: D.optStr.describe('authenticator: show as a QR code') }) }, v1: users.startEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/confirm', tag: 'Me', summary: 'Confirm two-step sign-in with the code', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ challengeId: D.str, code: D.str }), response: D.obj({ twoFactorEnabled: z.literal(true), twoFactorMethod: D.str, recoveryCodes: z.array(D.str).describe('Shown once: single-use codes for when the app or phone is lost') }) }, v1: users.confirmEnableTwoFactor });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/recovery-codes', tag: 'Me', summary: 'A new set of recovery codes', description: 'Needs the password. The old codes stop working; the new ones are shown once.', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ recoveryCodes: z.array(D.str) }) }, v1: users.replaceMyRecoveryCodes });
|
||||
v1Route({ method: 'post', path: '/me/two-factor/disable', tag: 'Me', summary: 'Turn off two-step sign-in', access: 'user', middleware: [loginLimiter], body: loose, documented: { body: D.obj({ password: D.str }), response: D.obj({ twoFactorEnabled: z.literal(false), twoFactorMethod: z.null() }) }, v1: users.disableTwoFactor });
|
||||
v1Route({
|
||||
method: 'get', path: '/users/exists', tag: 'Accounts', summary: 'Is there an account with this email or phone?',
|
||||
|
||||
@@ -14,12 +14,20 @@ export function iso(d: Date | string | null | undefined): string | null {
|
||||
return d == null ? null : new Date(d).toISOString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a stored upload path is served: "/uploads/…" (as stored) → "/api/uploads/…" (2.2.0), so it
|
||||
* reaches the backend when the site and its API share one address. Anything else is unchanged.
|
||||
*/
|
||||
export function uploadPath(raw: string): string {
|
||||
return /^\/uploads\//.test(raw) ? `/api${raw}` : raw;
|
||||
}
|
||||
|
||||
/** A stored picture path ("/uploads/…") as an absolute URL on the host the request came to. */
|
||||
export function absoluteUrl(req: Request, url: string | null | undefined): string | null {
|
||||
const raw = String(url || '').trim();
|
||||
if (!raw) return null;
|
||||
if (/^https?:\/\//.test(raw)) return raw;
|
||||
return `${req.protocol}://${req.get('host')}${raw.startsWith('/') ? '' : '/'}${raw}`;
|
||||
return `${req.protocol}://${req.get('host')}${uploadPath(raw.startsWith('/') ? raw : `/${raw}`)}`;
|
||||
}
|
||||
|
||||
export const campusRef = z.object({ id, name: z.string(), slug: z.string() });
|
||||
|
||||
@@ -72,7 +72,7 @@ describe('status', () => {
|
||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: false });
|
||||
});
|
||||
|
||||
test('the Hub\'s rand amounts never leave the site (2.3.0); a Hub before 2.0.1 sends no tokens', async () => {
|
||||
test('the Hub\'s rand amounts never leave the site (2.2.0); a Hub before 2.0.1 sends no tokens', async () => {
|
||||
mockPost.mockResolvedValueOnce(hubStatus());
|
||||
const s = await aiStatus() as unknown as Record<string, unknown>;
|
||||
expect(s).not.toHaveProperty('capCents');
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
// The church's data when it leaves (crosscode.church-export/1): plain terms, export-only
|
||||
// references, no internal ids and no secrets.
|
||||
jest.mock('../src/config/db', () => ({}));
|
||||
|
||||
import { buildExport } from '../src/services/churchExport';
|
||||
|
||||
const d = (s: string) => new Date(s);
|
||||
const input = {
|
||||
version: '2.3.0',
|
||||
users: [
|
||||
{ id: 'u-uuid-1', name: 'Thandi', email: 't@x.org', phoneNumber: '+27821234567', role: 'admin', createdAt: d('2026-01-01T08:00:00Z'), newsEmail: true, newsWhatsApp: false, password: '$2b$hash', tokenVersion: 3 },
|
||||
{ id: 'u-uuid-2', name: 'Sipho', email: 's@x.org', phoneNumber: null, role: 'user', createdAt: d('2026-02-01T08:00:00Z'), newsEmail: false, newsWhatsApp: true },
|
||||
],
|
||||
events: [{
|
||||
id: 'ev-uuid-1', title: 'Camp', description: null, startDate: d('2026-12-04T16:00:00Z'), endDate: d('2026-12-06T12:00:00Z'), location: 'Camp X', isActive: true, isHidden: false,
|
||||
sessions: [{ id: 's-1', label: 'Friday', startsAt: d('2026-12-04T16:00:00Z'), endsAt: d('2026-12-04T21:00:00Z') }],
|
||||
eventOptions: [{ id: 'opt-uuid-1', name: 'Camper', price: 600 }],
|
||||
}],
|
||||
registrations: [{
|
||||
id: 'reg-uuid-1', eventId: 'ev-uuid-1', userId: 'u-uuid-2', status: 'paid', createdAt: d('2026-11-01T09:00:00Z'),
|
||||
attendees: [{ id: 'att-1', name: 'Sipho', email: 's@x.org', eventOptionId: 'opt-uuid-1', ticket: { usages: [{ scannedAt: d('2026-12-04T16:30:00Z') }] } }],
|
||||
formResponses: [{ answers: [{ fieldId: 'f-1', value: 'None' }] }],
|
||||
}],
|
||||
payments: [{ id: 'pay-1', registrationId: 'reg-uuid-1', amount: 600, method: 'card', status: 'completed', createdAt: d('2026-11-01T09:05:00Z'), externalId: 'YOCO-1' }],
|
||||
usages: [{ id: 'use-1', scannedAt: d('2026-12-04T16:30:00Z'), ticket: { eventId: 'ev-uuid-1', userId: 'u-uuid-2', holderUserId: null, attendee: { name: 'Sipho' } } }],
|
||||
slots: [{ id: 'slot-1', roleId: 'role-1', userId: 'u-uuid-1' }],
|
||||
roles: [{ id: 'role-1', eventId: 'ev-uuid-1', name: 'Kitchen', startsAt: null, endsAt: null }],
|
||||
settings: [{ key: 'org_name', value: 'Hope Church' }, { key: 'smtp_password', value: 'enc:secret' }, { key: 'hub_install_secret', value: 'x' }],
|
||||
fields: [{ id: 'f-1', label: 'Dietary needs' }],
|
||||
};
|
||||
|
||||
describe('church export', () => {
|
||||
const out = buildExport(input, new Date('2026-11-20T12:00:00Z'));
|
||||
|
||||
test('uses export-only references that link up', () => {
|
||||
expect(out.people.map(p => p.ref)).toEqual(['p1', 'p2']);
|
||||
expect(out.events[0]).toMatchObject({ ref: 'e1', ticketTypes: [{ ref: 't1', priceCents: 60000 }], published: true });
|
||||
expect(out.registrations[0]).toMatchObject({ ref: 'r1', eventRef: 'e1', personRef: 'p2', attendees: [{ ticketTypeRef: 't1', checkedInAt: '2026-12-04T16:30:00.000Z' }], answers: [{ question: 'Dietary needs', answer: 'None' }] });
|
||||
expect(out.payments[0]).toMatchObject({ registrationRef: 'r1', amountCents: 60000, reference: 'YOCO-1' });
|
||||
expect(out.checkIns[0]).toMatchObject({ eventRef: 'e1', personRef: 'p2', name: 'Sipho' });
|
||||
expect(out.rosters[0]).toMatchObject({ eventRef: 'e1', role: 'Kitchen', personRef: 'p1' });
|
||||
expect(out.church.name).toBe('Hope Church');
|
||||
});
|
||||
|
||||
test('has no internal ids and no secrets', () => {
|
||||
const text = JSON.stringify(out);
|
||||
for (const secret of ['uuid', '$2b$hash', 'enc:secret', 'hub_install_secret', 'smtp_password', 'tokenVersion', 'password']) expect(text).not.toContain(secret);
|
||||
const keys: string[] = [];
|
||||
const walk = (v: unknown): void => {
|
||||
if (Array.isArray(v)) v.forEach(walk);
|
||||
else if (v && typeof v === 'object') for (const [k, x] of Object.entries(v)) { keys.push(k); walk(x); }
|
||||
};
|
||||
walk(out);
|
||||
expect(keys.filter(k => /^(id|.*Id|uuid|_id)$/.test(k))).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
// Installs made from the Hub register by themselves with HUB_LICENCE_KEY (AGENT-1.0-PLAN §7).
|
||||
const mockSettings = new Map();
|
||||
jest.mock('../src/config/db', () => ({
|
||||
appSetting: {
|
||||
findMany: jest.fn(async ({ where }) => [...mockSettings].filter(([key]) => where.key.in.includes(key)).map(([key, value]) => ({ key, value }))),
|
||||
upsert: jest.fn(async ({ where, create }) => { mockSettings.set(where.key, create.value); }),
|
||||
deleteMany: jest.fn(async ({ where }) => { mockSettings.delete(where.key); }),
|
||||
},
|
||||
}));
|
||||
jest.mock('../src/hub/report', () => ({ APP_VERSION: '2.3.0', installInfo: async () => ({ name: 'Hope', url: 'https://events.hope.co.za', version: '2.3.0' }) }));
|
||||
jest.mock('../src/hub/publicKey', () => ({ hubPublicKey: () => 'pem' }));
|
||||
jest.mock('../src/hub/licence', () => ({ verifyToken: () => ({ installId: 'inst_1' }), clearLicenceCache: () => {} }));
|
||||
|
||||
const hub = require('../src/hub/client');
|
||||
|
||||
const reply = (status, body) => ({ ok: status < 400, status, json: async () => body });
|
||||
const noSleep = async () => {};
|
||||
|
||||
describe('registering with HUB_LICENCE_KEY', () => {
|
||||
let bodies;
|
||||
beforeEach(() => {
|
||||
mockSettings.clear();
|
||||
bodies = [];
|
||||
process.env.HUB_LICENCE_KEY = 'CEH-7K2M-9QXA-P4RT-WD8C';
|
||||
process.env.HUB_ADMIN_NAME = 'Jane Admin';
|
||||
process.env.HUB_ADMIN_EMAIL = 'jane@hope.co.za';
|
||||
global.fetch = jest.fn(async (_url, opts) => {
|
||||
bodies.push(JSON.parse(opts.body));
|
||||
return reply(201, { installId: 'inst_1', installSecret: 's3cret', licence: 'hel1.x.y', heartbeatIntervalMinutes: 15 });
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
delete global.fetch;
|
||||
delete process.env.HUB_LICENCE_KEY;
|
||||
delete process.env.HUB_ADMIN_NAME;
|
||||
delete process.env.HUB_ADMIN_EMAIL;
|
||||
});
|
||||
|
||||
test('registers once, with the admin contact, and stores the install', async () => {
|
||||
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: true });
|
||||
expect(bodies[0]).toMatchObject({ licenceKey: 'CEH-7K2M-9QXA-P4RT-WD8C', install: { adminContact: { name: 'Jane Admin', email: 'jane@hope.co.za' } } });
|
||||
expect(mockSettings.get('hub_install_id')).toBe('inst_1');
|
||||
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: false, reason: 'already' });
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('does nothing without the key', async () => {
|
||||
delete process.env.HUB_LICENCE_KEY;
|
||||
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: false, reason: 'no_key' });
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('a refused key isn\'t tried again; an unreachable Hub is', async () => {
|
||||
global.fetch = jest.fn(async () => reply(404, { code: 'LICENCE_NOT_FOUND', message: 'Unknown key' }));
|
||||
expect(await hub.connectFromEnv({ sleep: noSleep })).toEqual({ connected: false, reason: 'LICENCE_NOT_FOUND' });
|
||||
expect(global.fetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
global.fetch = jest.fn(async () => { throw new Error('ECONNREFUSED'); });
|
||||
expect(await hub.connectFromEnv({ attempts: 3, sleep: noSleep })).toEqual({ connected: false, reason: 'unreachable' });
|
||||
expect(global.fetch).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
// Two-factor with an authenticator app and recovery codes (2.3.0): setting it up, signing in with
|
||||
// the app's code (once only), recovery codes (single use), and turning it off.
|
||||
process.env.JWT_SECRET = 'test-secret';
|
||||
process.env.NODE_ENV = 'test';
|
||||
|
||||
function matches(row, where = {}) {
|
||||
return Object.entries(where).every(([key, cond]) => {
|
||||
if (key === 'OR') return cond.some(c => matches(row, c));
|
||||
const value = row[key];
|
||||
if (cond === null) return value == null;
|
||||
if (cond && typeof cond === 'object' && !(cond instanceof Date)) {
|
||||
if ('gt' in cond && !(value > cond.gt)) return false;
|
||||
if ('lt' in cond && !(value != null && value < cond.lt)) return false;
|
||||
return true;
|
||||
}
|
||||
return value === cond;
|
||||
});
|
||||
}
|
||||
|
||||
function model(defaults = () => ({})) {
|
||||
let rows = [];
|
||||
let seq = 0;
|
||||
const apply = (row, data) => { for (const [k, v] of Object.entries(data)) row[k] = v && typeof v === 'object' && 'increment' in v ? row[k] + v.increment : v; };
|
||||
return {
|
||||
rows: () => rows,
|
||||
reset: () => { rows = []; },
|
||||
create: async ({ data }) => { const r = { id: `id-${++seq}`, ...defaults(), ...data }; rows.push(r); return { ...r }; },
|
||||
createMany: async ({ data }) => { for (const d of data) rows.push({ id: `id-${++seq}`, ...defaults(), ...d }); return { count: data.length }; },
|
||||
findUnique: async ({ where, include, select }) => {
|
||||
const r = rows.find(x => matches(x, where));
|
||||
if (!r) return null;
|
||||
const out = { ...r };
|
||||
if (include?.user) out.user = { ...mockDb.user.rows().find(u => u.id === r.userId) };
|
||||
if (select) return Object.fromEntries(Object.keys(select).map(k => [k, r[k]]));
|
||||
return out;
|
||||
},
|
||||
update: async ({ where, data }) => { const r = rows.find(x => matches(x, where)); apply(r, data); return { ...r }; },
|
||||
updateMany: async ({ where, data }) => { const hit = rows.filter(x => matches(x, where)); hit.forEach(r => apply(r, data)); return { count: hit.length }; },
|
||||
deleteMany: async ({ where }) => { const before = rows.length; rows = rows.filter(x => !matches(x, where)); return { count: before - rows.length }; },
|
||||
count: async ({ where }) => rows.filter(x => matches(x, where)).length,
|
||||
};
|
||||
}
|
||||
|
||||
const mockDb = {
|
||||
user: model(),
|
||||
twoFactorChallenge: model(() => ({ attempts: 0, usedAt: null, lastSentAt: new Date(), createdAt: new Date(), pendingSecret: null })),
|
||||
recoveryCode: model(() => ({ usedAt: null, createdAt: new Date() })),
|
||||
trustedDevice: model(),
|
||||
};
|
||||
jest.mock('../src/config/db', () => mockDb);
|
||||
jest.mock('../src/utils/settingsCache', () => ({ getSettingSync: (_key, fallback) => fallback }));
|
||||
|
||||
const twoFactor = require('../src/utils/twoFactor');
|
||||
const totp = require('../src/utils/totp');
|
||||
const { decrypt } = require('../src/utils/encryption');
|
||||
|
||||
const STEP_MS = totp.STEP * 1000;
|
||||
const codeNow = (secret, offsetSteps = 0) => totp.codeAt(secret, Math.floor(Date.now() / STEP_MS) + offsetSteps);
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(mockDb)) m.reset();
|
||||
mockDb.user.rows().push({ id: 'u1', name: 'Jane', email: 'jane@example.com', role: 'admin', twoFactorEnabled: false, totpSecret: null, totpLastStep: null });
|
||||
});
|
||||
|
||||
async function setUpApp() {
|
||||
const user = mockDb.user.rows()[0];
|
||||
const ch = await twoFactor.createChallenge(user, 'enable', 'authenticator');
|
||||
return { ch, user };
|
||||
}
|
||||
|
||||
describe('setting up an authenticator app', () => {
|
||||
test('gives a secret and an otpauth link, keeps it only encrypted, and sends nothing', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
expect(ch).toMatchObject({ method: 'authenticator', destination: 'your authenticator app' });
|
||||
expect(ch.secret).toMatch(/^[A-Z2-7]{32}$/);
|
||||
expect(ch.otpauthUrl).toMatch(/^otpauth:\/\/totp\/.+secret=[A-Z2-7]{32}&issuer=/);
|
||||
const row = mockDb.twoFactorChallenge.rows()[0];
|
||||
expect(row.pendingSecret).not.toContain(ch.secret);
|
||||
expect(decrypt(row.pendingSecret)).toBe(ch.secret);
|
||||
});
|
||||
|
||||
test('the app\'s current code confirms it; a wrong code doesn\'t', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
await expect(twoFactor.verifyChallenge(ch.challengeId, '000000', 'enable', 'u1')).rejects.toThrow(/Incorrect code/);
|
||||
const ok = await twoFactor.verifyChallenge(ch.challengeId, codeNow(ch.secret), 'enable', 'u1');
|
||||
expect(ok.method).toBe('authenticator');
|
||||
expect(decrypt(ok.pendingSecret)).toBe(ch.secret);
|
||||
});
|
||||
|
||||
test('resend is refused: nothing is sent for an app', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
await expect(twoFactor.resendChallenge(ch.challengeId, 'enable', 'u1')).rejects.toThrow(/authenticator app/);
|
||||
});
|
||||
|
||||
test('it\'s always among the available methods', async () => {
|
||||
expect(await twoFactor.availableMethods({ email: 'x@guest.local', phoneNumber: null })).toEqual(['authenticator']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('signing in with the app', () => {
|
||||
let secret;
|
||||
beforeEach(async () => {
|
||||
const { ch } = await setUpApp();
|
||||
secret = ch.secret;
|
||||
Object.assign(mockDb.user.rows()[0], { twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: mockDb.twoFactorChallenge.rows()[0].pendingSecret });
|
||||
});
|
||||
|
||||
test('the current code works once; the same code again is refused', async () => {
|
||||
const user = mockDb.user.rows()[0];
|
||||
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
expect(a.secret).toBeUndefined();
|
||||
const code = codeNow(secret);
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, code, 'login')).resolves.toMatchObject({ usedRecoveryCode: false });
|
||||
const b = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(b.challengeId, code, 'login')).rejects.toThrow(/Incorrect code/);
|
||||
});
|
||||
|
||||
test('a code from the step before still works (clock drift); one from two steps back doesn\'t', async () => {
|
||||
const user = mockDb.user.rows()[0];
|
||||
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, codeNow(secret, -2), 'login')).rejects.toThrow(/Incorrect/);
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, codeNow(secret, -1), 'login')).resolves.toBeTruthy();
|
||||
});
|
||||
|
||||
test('no app set up: signing in with it is refused', async () => {
|
||||
mockDb.user.rows()[0].totpSecret = null;
|
||||
await expect(twoFactor.createChallenge(mockDb.user.rows()[0], 'login', 'authenticator')).rejects.toThrow(/No authenticator app/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('recovery codes', () => {
|
||||
test('ten codes, single use, accepted at sign-in in place of the app\'s code', async () => {
|
||||
const { ch } = await setUpApp();
|
||||
Object.assign(mockDb.user.rows()[0], { twoFactorEnabled: true, twoFactorMethod: 'authenticator', totpSecret: mockDb.twoFactorChallenge.rows()[0].pendingSecret });
|
||||
const codes = await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
expect(codes).toHaveLength(10);
|
||||
expect(new Set(codes).size).toBe(10);
|
||||
codes.forEach(c => expect(c).toMatch(/^[a-z2-9]{5}-[a-z2-9]{5}$/));
|
||||
expect(JSON.stringify(mockDb.recoveryCode.rows())).not.toContain(codes[0]);
|
||||
|
||||
const user = mockDb.user.rows()[0];
|
||||
const a = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(a.challengeId, codes[3].toUpperCase().replace('-', ' '), 'login')).resolves.toMatchObject({ usedRecoveryCode: true });
|
||||
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(9);
|
||||
const b = await twoFactor.createChallenge(user, 'login', 'authenticator');
|
||||
await expect(twoFactor.verifyChallenge(b.challengeId, codes[3], 'login')).rejects.toThrow(/Incorrect/);
|
||||
expect(ch).toBeTruthy();
|
||||
});
|
||||
|
||||
test('a new set replaces the old one', async () => {
|
||||
const first = await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
expect(await twoFactor.useRecoveryCode('u1', first[0])).toBe(false);
|
||||
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(10);
|
||||
});
|
||||
|
||||
test('turning 2FA off removes them and the app\'s secret', async () => {
|
||||
await twoFactor.replaceRecoveryCodes('u1', mockDb);
|
||||
const data = await twoFactor.clearTwoFactor('u1', mockDb);
|
||||
expect(data).toEqual({ twoFactorEnabled: false, twoFactorMethod: null, totpSecret: null, totpLastStep: null });
|
||||
expect(await twoFactor.recoveryCodesLeft('u1')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -117,15 +117,15 @@ afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
describe('availableMethods', () => {
|
||||
test('offers WhatsApp only with a valid phone and a configured gateway', async () => {
|
||||
expect(await availableMethods(USER)).toEqual(['email', 'whatsapp']);
|
||||
expect(await availableMethods(USER)).toEqual(['email', 'whatsapp', 'authenticator']);
|
||||
mockWhatsApp.configured = false;
|
||||
expect(await availableMethods(USER)).toEqual(['email']);
|
||||
expect(await availableMethods(USER)).toEqual(['email', 'authenticator']);
|
||||
mockWhatsApp.configured = true;
|
||||
expect(await availableMethods({ ...USER, phoneNumber: null })).toEqual(['email']);
|
||||
expect(await availableMethods({ ...USER, phoneNumber: null })).toEqual(['email', 'authenticator']);
|
||||
});
|
||||
|
||||
test('offers nothing by email for a guest placeholder address', async () => {
|
||||
expect(await availableMethods({ ...USER, email: 'x@guest.local' })).toEqual(['whatsapp']);
|
||||
expect(await availableMethods({ ...USER, email: 'x@guest.local' })).toEqual(['whatsapp', 'authenticator']);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ import { v2Router } from '../src/v2';
|
||||
import { ServiceError } from '../src/services/errors';
|
||||
import { routes } from '../src/v2/route';
|
||||
import { buildOpenApi } from '../src/v2/openapi';
|
||||
import { absoluteUrl, uploadPath } from '../src/v2/schemas';
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
@@ -129,7 +130,7 @@ describe('GET /api/v2/events', () => {
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.meta).toEqual({ page: 2, limit: 10, total: 31, pages: 4 });
|
||||
expect(res.body.data[0]).toMatchObject({ id: 'e1', startDate: '2026-12-04T16:00:00.000Z', series: { slug: 'camps' } });
|
||||
expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/uploads\/events\/camp\.jpg$/);
|
||||
expect(res.body.data[0].pictureUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/api\/uploads\/events\/camp\.jpg$/);
|
||||
const args = mockDb.event.findMany.mock.calls[0][0];
|
||||
expect(args).toMatchObject({ skip: 10, take: 10 });
|
||||
expect(args.where.AND).toEqual(expect.arrayContaining([{ isActive: true, isHidden: false, goLiveAt: { lte: expect.any(Date) } }, { title: { contains: 'camp', mode: 'insensitive' } }]));
|
||||
@@ -424,7 +425,7 @@ describe('events (staff)', () => {
|
||||
const res = await request(app).get('/api/v2/events/manage?past=true');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.data[0]).toMatchObject({ id: 'e1', isHidden: true, waitlistEnabled: true, startDate: '2026-12-04T16:00:00.000Z' });
|
||||
expect(res.body.data[0].picture).toMatch(/^http:\/\/.*\/uploads\/events\/c\.jpg$/);
|
||||
expect(res.body.data[0].picture).toMatch(/^http:\/\/[^/]+\/api\/uploads\/events\/c\.jpg$/);
|
||||
expect(mockEvents.listManagedEvents).toHaveBeenCalledWith({ includePast: true, includeInactive: false, excludeClosed: false, campus: undefined }, expect.objectContaining({ scope: null }));
|
||||
});
|
||||
|
||||
@@ -554,7 +555,16 @@ describe('sections, costs, image uploads', () => {
|
||||
mockImage.file = { filename: 'event-123.jpg' };
|
||||
const res = await request(app).post('/api/v2/uploads/event-image');
|
||||
expect(res.body.data.path).toBe('/uploads/events/event-123.jpg');
|
||||
expect(res.body.data.url).toMatch(/^http:\/\/.*\/uploads\/events\/event-123\.jpg$/);
|
||||
expect(res.body.data.url).toMatch(/^http:\/\/[^/]+\/api\/uploads\/events\/event-123\.jpg$/);
|
||||
});
|
||||
|
||||
test('stored uploads are given out under /api/uploads (2.2.0); other addresses are left alone', () => {
|
||||
expect(uploadPath('/uploads/branding/logo.png')).toBe('/api/uploads/branding/logo.png');
|
||||
expect(uploadPath('/api/uploads/x.png')).toBe('/api/uploads/x.png');
|
||||
expect(uploadPath('/images/x.png')).toBe('/images/x.png');
|
||||
const req = { protocol: 'https', get: () => 'events.church.co.za' } as unknown as Parameters<typeof absoluteUrl>[0];
|
||||
expect(absoluteUrl(req, 'uploads/events/a.jpg')).toBe('https://events.church.co.za/api/uploads/events/a.jpg');
|
||||
expect(absoluteUrl(req, 'https://cdn.example.org/uploads/a.jpg')).toBe('https://cdn.example.org/uploads/a.jpg');
|
||||
});
|
||||
|
||||
test('branding images are for admins once accounts exist', async () => {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# Handover — where things stand and how to carry on
|
||||
|
||||
Last updated: 2026-11-05, after **2.1.1** (deployed). **This file covers Cross Events only**
|
||||
Last updated: 2026-11-17, after **2.3.0** (released, tested on a VM, not deployed yet; servers
|
||||
still run 2.1.1 until they're adopted, see the root [ROLLOUT-1.0.md](../../../docs/ROLLOUT-1.0.md)).
|
||||
**This file covers Cross Events only**
|
||||
(what's been done, where the code lives, known gaps). **The plan for every product and where each
|
||||
phase stands are in the monorepo's root `docs/`** →
|
||||
[ROADMAP-v3.md](../../../docs/ROADMAP-v3.md),
|
||||
@@ -95,13 +97,13 @@ encrypted settings unreadable or break existing installs.
|
||||
## Next up
|
||||
|
||||
1. **Roadmap v3**, across every product: see `crosscode-platform/docs/HANDOVER.md` ("Where each
|
||||
phase stands", "Next up"). For Cross Events that means **2.2.0** (the move into the monorepo as
|
||||
`apps/events`, with the `crosscode` script; `crosscode-platform/docs/EVENTS-2.2-PLAN.md`), then
|
||||
**2.3.0** (authenticator app 2FA, `TwoFactorMethod` in `prisma/schema.prisma`) and **2.4.0**
|
||||
phase stands", "Next up"). **2.2.0** (the move into the monorepo) and **2.3.0** (authenticator
|
||||
app 2FA and recovery codes, plus what installs from the Hub need) are released (2026-11-17).
|
||||
Next for Cross Events is **rolling them out** (each install adopted from the Hub), then **2.4.0**
|
||||
(protocol v2, Linked products, the event feed).
|
||||
- **Deploying until 2.2.0:** `bash scripts/deploy.sh --check`, then
|
||||
`bash scripts/deploy.sh v<version>` on each server (installs ask through Request update as
|
||||
usual). From 2.2.0 on: `crosscode deploy <church> events`.
|
||||
- **Deploying:** installs still on 2.1.1 move with `adopt` (Hub → Servers → Installs → Link
|
||||
existing → Move onto the monorepo, or `crosscode adopt` by hand), never `deploy`. After that,
|
||||
updates are planned on the Hub (Updates), or `crosscode deploy <church> events` by hand.
|
||||
- **AI for a church:** set the licence's monthly AI cap above R0 on the Hub (Hub 1.6.0+); with
|
||||
no cap the buttons don't show.
|
||||
- Testing AI locally: run the Hub (`../events-hub`, port 5200), set Settings → AI there, give a
|
||||
@@ -119,6 +121,27 @@ encrypted settings unreadable or break existing installs.
|
||||
|
||||
Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026-10-28).
|
||||
|
||||
## Where two-factor lives (2.3.0)
|
||||
|
||||
- `backend/src/utils/twoFactor.js`: every method (email, WhatsApp, `authenticator`), challenges,
|
||||
recovery codes (10 per set, stored as HMACs, single use). `backend/src/utils/totp.js`: RFC 6238
|
||||
with a last-step check (`User.totpLastStep`), so a code can't be used twice.
|
||||
- **`totpSecret` never goes to the browser:** `LOGIN_USER_SELECT` doesn't include it (that selection
|
||||
is sent back on sign-in), so `createChallenge` reads it from the database itself.
|
||||
- Frontend: the profile page draws the QR code in the browser (a dynamic `import("qrcode")`);
|
||||
`LoginForm.tsx` has "Use a recovery code". Tests: `tests/twoFactorAuthenticator.test.js`.
|
||||
|
||||
## Where the Hub-install pieces live (2.3.0)
|
||||
|
||||
- `env.template.json` (copied to `scripts/products/events.env.template.json` at the monorepo root;
|
||||
keep them the same): every `.env` variable with its layer (`server`, `defaults`, `install`,
|
||||
`generated`). The Hub has its own copy (`events-hub/backend/src/utils/envTemplates/events.json`).
|
||||
A new variable goes in all three.
|
||||
- `backend/scripts/export-church.ts` (`src/services/churchExport.ts`): the church's data as
|
||||
`crosscode.church-export/1`, for `crosscode export` and uninstalls. No internal ids.
|
||||
- `backend/src/hub/client.js` `connectFromEnv()`: a site the Hub installed registers by itself on
|
||||
first start from `HUB_LICENCE_KEY`.
|
||||
|
||||
## Working on this repo
|
||||
|
||||
- **Release routine:** branch `feat/<name>` → commit → bump with
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { test, expect, seed, API } from "./fixtures";
|
||||
|
||||
// /api/v2 (1.51.0) against the real server and database: paged public events, the v2 error
|
||||
// shape, the signed-in person, and the OpenAPI reference at /docs/v2.
|
||||
// shape, the signed-in person, and the OpenAPI reference at /api/docs/v2.
|
||||
test.describe("API v2", () => {
|
||||
test("public events come a page at a time; errors have a code", async ({ request }) => {
|
||||
const res = await request.get(`${API}/api/v2/events?limit=2`);
|
||||
@@ -99,9 +99,11 @@ test.describe("API v2", () => {
|
||||
expect(ics.headers()["location"]).toBe(`/api/v2/events/${seed().events.conference}/calendar.ics`);
|
||||
const followed = await request.get(`${API}/api/events/${seed().events.conference}/ics`);
|
||||
expect(followed.headers()["content-type"]).toContain("text/calendar");
|
||||
// The old API reference sends people to the v2 one.
|
||||
// The old API reference addresses send people to the v2 one, under /api (2.2.0).
|
||||
const docs = await request.get(`${API}/docs`, { maxRedirects: 0 });
|
||||
expect(docs.headers()["location"]).toBe("/docs/v2");
|
||||
expect(docs.headers()["location"]).toBe("/api/docs/v2");
|
||||
const oldDocs = await request.get(`${API}/docs/v2?x=1`, { maxRedirects: 0 });
|
||||
expect(oldDocs.headers()["location"]).toBe("/api/docs/v2?x=1");
|
||||
});
|
||||
|
||||
test("staff list every event; supervisors create, change and admins deactivate", async ({ request }) => {
|
||||
@@ -339,11 +341,11 @@ test.describe("API v2", () => {
|
||||
expect((await request.get(`${API}/api/v2/admin/audit-log`, { headers: user })).status()).toBe(403);
|
||||
});
|
||||
|
||||
test("an admin can read the OpenAPI reference at /docs/v2", async ({ page, request }) => {
|
||||
test("an admin can read the OpenAPI reference at /api/docs/v2", async ({ page, request }) => {
|
||||
const headers = { Authorization: `Bearer ${seed().users.user.token}` };
|
||||
expect((await request.get(`${API}/api/v2/openapi.json`, { headers })).status()).toBe(403);
|
||||
|
||||
await page.goto(`${API}/docs/v2?token=${seed().users.admin.token}`);
|
||||
await page.goto(`${API}/api/docs/v2?token=${seed().users.admin.token}`);
|
||||
await expect(page.getByRole("heading", { name: /Cross Events API/ })).toBeVisible();
|
||||
// Sections start collapsed (there are hundreds of endpoints): open Events.
|
||||
await page.locator('h3.opblock-tag[data-tag="Events"]').click();
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
{
|
||||
"schema": "crosscode.env-template/1",
|
||||
"product": "events",
|
||||
"files": {
|
||||
"backend/.env": [
|
||||
{
|
||||
"name": "NODE_ENV",
|
||||
"layer": "generated",
|
||||
"required": true,
|
||||
"description": "production"
|
||||
},
|
||||
{
|
||||
"name": "PORT",
|
||||
"layer": "install",
|
||||
"from": "{apiPort}",
|
||||
"required": true,
|
||||
"description": "The backend's port (from the Hub's port list)"
|
||||
},
|
||||
{
|
||||
"name": "DATABASE_URL",
|
||||
"layer": "generated",
|
||||
"required": true,
|
||||
"description": "Made on the server with a new password; never leaves it"
|
||||
},
|
||||
{
|
||||
"name": "JWT_SECRET",
|
||||
"layer": "generated",
|
||||
"required": true,
|
||||
"description": "Also encrypts stored secrets: never change it"
|
||||
},
|
||||
{
|
||||
"name": "FRONTEND_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "APP_BASE_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "BACKEND_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true,
|
||||
"description": "The same address: the backend is under /api (2.2.0+)"
|
||||
},
|
||||
{
|
||||
"name": "TRUST_PROXY",
|
||||
"layer": "server",
|
||||
"required": true,
|
||||
"description": "Behind frp: loopback"
|
||||
},
|
||||
{
|
||||
"name": "APP_TIMEZONE",
|
||||
"layer": "install",
|
||||
"default": "Africa/Johannesburg"
|
||||
},
|
||||
{
|
||||
"name": "HUB_URL",
|
||||
"layer": "defaults",
|
||||
"default": "https://hub.crosscode.co.za"
|
||||
},
|
||||
{
|
||||
"name": "HUB_HEARTBEAT_ENABLED",
|
||||
"layer": "defaults",
|
||||
"default": "true"
|
||||
},
|
||||
{
|
||||
"name": "HUB_PUBLIC_KEY",
|
||||
"layer": "defaults",
|
||||
"description": "Only for a Hub other than hub.crosscode.co.za (staging, a test VM): its licence public key"
|
||||
},
|
||||
{
|
||||
"name": "HUB_LICENCE_KEY",
|
||||
"layer": "install",
|
||||
"description": "With it the site registers with the Hub by itself when it first starts"
|
||||
},
|
||||
{
|
||||
"name": "HUB_ADMIN_NAME",
|
||||
"layer": "install",
|
||||
"description": "The site admin, sent to the Hub on registering"
|
||||
},
|
||||
{
|
||||
"name": "HUB_ADMIN_EMAIL",
|
||||
"layer": "install"
|
||||
},
|
||||
{
|
||||
"name": "BACKUP_ENABLED",
|
||||
"layer": "defaults",
|
||||
"default": "true"
|
||||
},
|
||||
{
|
||||
"name": "DAILY_SUMMARY_ENABLED",
|
||||
"layer": "defaults",
|
||||
"default": "true"
|
||||
},
|
||||
{
|
||||
"name": "SENTRY_DSN",
|
||||
"layer": "defaults"
|
||||
}
|
||||
],
|
||||
"frontend/.env.production": [
|
||||
{
|
||||
"name": "NEXT_PUBLIC_API_URL",
|
||||
"layer": "install",
|
||||
"from": "https://{domain}",
|
||||
"required": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "2.1.1",
|
||||
"version": "2.3.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -36,7 +36,7 @@
|
||||
"date-fns": "^4.1.0",
|
||||
"idb": "^8.0.4",
|
||||
"lucide-react": "^0.536.0",
|
||||
"next": "^16.4.3",
|
||||
"next": "^16.4.6",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.3.1",
|
||||
"react-day-picker": "^9.8.1",
|
||||
@@ -55,7 +55,7 @@
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-next": "^16.4.3",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"openapi-typescript": "^7.13.0",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "3.4",
|
||||
|
||||
@@ -23,6 +23,7 @@ interface UserItem {
|
||||
phoneNumber?: string | null;
|
||||
notificationPreference?: string;
|
||||
twoFactorEnabled?: boolean;
|
||||
twoFactorMethod?: "email" | "whatsapp" | "authenticator" | null;
|
||||
isActive: boolean;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
@@ -34,6 +35,8 @@ type Role = typeof roleOptions[number];
|
||||
const notificationPreferenceOptions = ["email", "whatsapp", "both"] as const;
|
||||
|
||||
|
||||
const TWO_FACTOR_LABEL: Record<"email" | "whatsapp" | "authenticator", string> = { email: "email", whatsapp: "WhatsApp", authenticator: "app" };
|
||||
|
||||
export default function AdminUsersPage() {
|
||||
const { user, loading, token } = useAuth();
|
||||
const router = useRouter();
|
||||
@@ -418,6 +421,9 @@ export default function AdminUsersPage() {
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<RoleBadge role={u.role as RoleBadgeRole} />
|
||||
<div className="mt-1 text-xs text-gray-500" title="How their sign-in codes come">
|
||||
{u.twoFactorEnabled ? `2FA: ${TWO_FACTOR_LABEL[u.twoFactorMethod || "email"]}` : "No 2FA"}
|
||||
</div>
|
||||
</td>
|
||||
<td className="p-2">
|
||||
<span>{u.phoneNumber || ""}</span>
|
||||
|
||||
@@ -14,17 +14,19 @@ import { useCampuses } from "@/hooks/useCampuses";
|
||||
import { apiV2, apiV2Data } from "@/lib/apiV2";
|
||||
import { useStateSync } from "@/lib/hooks";
|
||||
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled"; device: string | null; createdAt: string };
|
||||
type ActivityEvent = { id: string; type: "login" | "password_changed" | "password_reset" | "two_factor_enabled" | "two_factor_disabled" | "recovery_code_used" | "recovery_codes_replaced"; device: string | null; createdAt: string };
|
||||
|
||||
const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | null) => string; icon: typeof LogIn }> = {
|
||||
login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn },
|
||||
password_changed: { label: () => "Password changed", icon: KeyRound },
|
||||
password_reset: { label: () => "Password reset via email link", icon: RotateCcw },
|
||||
two_factor_enabled: { label: () => "Two-factor authentication turned on", icon: ShieldCheck },
|
||||
recovery_code_used: { label: () => "Logged in with a recovery code", icon: ShieldAlert },
|
||||
recovery_codes_replaced: { label: () => "New recovery codes made", icon: ShieldCheck },
|
||||
two_factor_disabled: { label: () => "Two-factor authentication turned off", icon: ShieldOff },
|
||||
};
|
||||
|
||||
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp" };
|
||||
const TWO_FACTOR_METHOD_LABEL: Record<TwoFactorMethod, string> = { email: "email", whatsapp: "WhatsApp", authenticator: "an authenticator app" };
|
||||
|
||||
// Shared bits of the page (outside the component, so they aren't new components each render).
|
||||
const Alert = ({ msg }: { msg: { type: "ok" | "err"; text: string } }) => (
|
||||
@@ -185,12 +187,16 @@ export default function UserProfilePage() {
|
||||
// loaded once per page load, so it wouldn't reflect a change made here.
|
||||
const [tfEnabled, setTfEnabled] = useState(false);
|
||||
const [tfMethod, setTfMethod] = useState<TwoFactorMethod>("email");
|
||||
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change">("idle");
|
||||
const [tfStep, setTfStep] = useState<"idle" | "code" | "disable" | "change" | "recovery">("idle");
|
||||
const [tfPassword, setTfPassword] = useState("");
|
||||
const [tfCode, setTfCode] = useState("");
|
||||
const [tfChallenge, setTfChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||
const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||
const [tfBusy, setTfBusy] = useState(false);
|
||||
// 2.3.0: recovery codes just made (shown once), how many are left, and the setup QR code.
|
||||
const [tfRecovery, setTfRecovery] = useState<string[] | null>(null);
|
||||
const [tfRecoveryLeft, setTfRecoveryLeft] = useState(0);
|
||||
const [tfQr, setTfQr] = useState<{ url: string; image: string } | null>(null);
|
||||
|
||||
// WhatsApp codes need the number that's actually saved, not one still being typed.
|
||||
const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || "");
|
||||
@@ -201,9 +207,19 @@ export default function UserProfilePage() {
|
||||
if (user) {
|
||||
setTfEnabled(!!user.twoFactorEnabled);
|
||||
setTfMethod(user.twoFactorMethod || "email");
|
||||
setTfRecoveryLeft((user as { recoveryCodesLeft?: number }).recoveryCodesLeft ?? 0);
|
||||
}
|
||||
}, [user]);
|
||||
|
||||
// The setup QR code, drawn here from the otpauth:// link (the key never leaves the browser).
|
||||
useEffect(() => {
|
||||
const url = tfChallenge?.otpauthUrl;
|
||||
if (!url) return;
|
||||
let alive = true;
|
||||
import("qrcode").then(q => q.toDataURL(url, { margin: 1, width: 200 })).then(image => { if (alive) setTfQr({ url, image }); }).catch(() => {});
|
||||
return () => { alive = false; };
|
||||
}, [tfChallenge]);
|
||||
|
||||
const resetTwoFactorForm = () => {
|
||||
setTfStep("idle");
|
||||
setTfPassword("");
|
||||
@@ -241,12 +257,14 @@ export default function UserProfilePage() {
|
||||
const res = await (apiV2Data("post", "/me/two-factor/confirm", {
|
||||
authToken: token,
|
||||
body: { challengeId: tfChallenge.challengeId, code: tfCode },
|
||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod }>);
|
||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod; recoveryCodes?: string[] }>);
|
||||
const wasEnabled = tfEnabled;
|
||||
setTfEnabled(true);
|
||||
setTfMethod(res.twoFactorMethod);
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Codes will now be sent by ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
setTfRecovery(res.recoveryCodes ?? null);
|
||||
setTfRecoveryLeft(res.recoveryCodes?.length ?? 0);
|
||||
setTfMsg({ type: "ok", text: wasEnabled ? `Your codes now come from ${TWO_FACTOR_METHOD_LABEL[res.twoFactorMethod]}.` : "Two-factor authentication is on." });
|
||||
loadActivity();
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to verify the code." });
|
||||
@@ -255,6 +273,35 @@ export default function UserProfilePage() {
|
||||
}
|
||||
};
|
||||
|
||||
const newRecoveryCodes = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
setTfBusy(true);
|
||||
setTfMsg(null);
|
||||
try {
|
||||
const res = await (apiV2Data("post", "/me/two-factor/recovery-codes", { authToken: token, body: { password: tfPassword } }) as Promise<{ recoveryCodes: string[] }>);
|
||||
resetTwoFactorForm();
|
||||
setTfRecovery(res.recoveryCodes);
|
||||
setTfRecoveryLeft(res.recoveryCodes.length);
|
||||
loadActivity();
|
||||
} catch (e) {
|
||||
setTfMsg({ type: "err", text: errorMessage(e) || "Couldn't make new recovery codes." });
|
||||
} finally {
|
||||
setTfBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const downloadRecovery = () => {
|
||||
if (!tfRecovery) return;
|
||||
const text = `Recovery codes for ${user?.email || "your account"} (${window.location.host})\nEach works once, in place of a code, if you lose your phone or app.\n\n${tfRecovery.join("\n")}\n`;
|
||||
const url = URL.createObjectURL(new Blob([text], { type: "text/plain" }));
|
||||
const link = document.createElement("a");
|
||||
link.href = url;
|
||||
link.download = "recovery-codes.txt";
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const disableTwoFactor = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!token) return;
|
||||
@@ -266,6 +313,7 @@ export default function UserProfilePage() {
|
||||
body: { password: tfPassword },
|
||||
});
|
||||
setTfEnabled(false);
|
||||
setTfRecoveryLeft(0);
|
||||
resetTwoFactorForm();
|
||||
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
|
||||
loadActivity();
|
||||
@@ -424,9 +472,20 @@ export default function UserProfilePage() {
|
||||
|
||||
{tfStep === "code" && tfChallenge ? (
|
||||
<form onSubmit={confirmEnableTwoFactor} className="space-y-4">
|
||||
<p className="text-sm text-gray-500">
|
||||
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}
|
||||
</p>
|
||||
{tfChallenge.method === "authenticator" ? (
|
||||
<div className="space-y-3 text-sm text-gray-600">
|
||||
<p>Scan this with an authenticator app (Google Authenticator, Microsoft Authenticator, 1Password, Authy…), then enter the 6-digit code it shows.</p>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- a data: URL drawn in the browser */}
|
||||
{tfQr && tfQr.url === tfChallenge.otpauthUrl && <img src={tfQr.image} alt="QR code to add this account to an authenticator app" width={200} height={200} className="rounded border" />}
|
||||
{tfChallenge.secret && (
|
||||
<p className="text-xs">Can't scan it? Type this key into the app: <code className="select-all break-all rounded bg-gray-100 px-1 py-0.5 font-mono">{tfChallenge.secret.replace(/(.{4})/g, "$1 ").trim()}</code></p>
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-gray-500">
|
||||
We sent a 6-digit code to {tfChallenge.destination} by {TWO_FACTOR_METHOD_LABEL[tfChallenge.method]}. {tfEnabled ? "Enter it to switch your codes to this channel." : "Enter it to finish turning on two-factor authentication."}
|
||||
</p>
|
||||
)}
|
||||
<div>
|
||||
<label htmlFor="profile-verification-code" className="block text-sm font-medium text-gray-700 mb-1">Verification code</label>
|
||||
<input
|
||||
@@ -446,16 +505,32 @@ export default function UserProfilePage() {
|
||||
Cancel
|
||||
</button>
|
||||
<button type="submit" disabled={tfBusy || tfCode.length !== 6} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{tfBusy ? "Verifying…" : "Turn on two-factor"}
|
||||
{tfBusy ? "Verifying…" : tfEnabled ? "Switch" : "Turn on two-factor"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
) : tfEnabled && tfStep !== "change" ? (
|
||||
<>
|
||||
<p className="text-sm text-gray-500 mb-4">
|
||||
<span className="font-medium text-green-700">On.</span> When you log in we send a 6-digit code by{" "}
|
||||
{TWO_FACTOR_METHOD_LABEL[tfMethod]}. Devices you've chosen to trust skip the code for 30 days.
|
||||
<span className="font-medium text-green-700">On.</span>{" "}
|
||||
{tfMethod === "authenticator" ? "When you log in, enter the 6-digit code from your authenticator app." : <>When you log in we send a 6-digit code by {TWO_FACTOR_METHOD_LABEL[tfMethod]}.</>}{" "}
|
||||
Devices you've chosen to trust skip the code for 30 days.
|
||||
</p>
|
||||
<div className="mb-4 rounded-lg border border-gray-200 bg-gray-50 p-3 text-sm">
|
||||
<p className="text-gray-700"><span className="font-medium">Recovery codes:</span> {tfRecoveryLeft} of 10 left. Each works once in place of a code if you lose your phone or app.</p>
|
||||
{tfStep === "recovery" ? (
|
||||
<form onSubmit={newRecoveryCodes} className="mt-3 flex flex-wrap items-end gap-2">
|
||||
<div className="flex-1 min-w-[12rem]">
|
||||
<label htmlFor="profile-recovery-password" className="block text-xs font-medium text-gray-700 mb-1">Confirm with your password</label>
|
||||
<input id="profile-recovery-password" type="password" className={inputCls} value={tfPassword} onChange={e => setTfPassword(e.target.value)} required autoComplete="current-password" />
|
||||
</div>
|
||||
<button type="button" onClick={resetTwoFactorForm} className="px-3 py-2 rounded-lg bg-gray-100 text-sm font-medium hover:bg-gray-200">Cancel</button>
|
||||
<button type="submit" disabled={tfBusy || !tfPassword} className="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">{tfBusy ? "Making…" : "Make new codes"}</button>
|
||||
</form>
|
||||
) : (
|
||||
<button onClick={() => { setTfStep("recovery"); setTfPassword(""); setTfMsg(null); }} className="mt-2 text-sm text-brand-700 hover:underline">New recovery codes…</button>
|
||||
)}
|
||||
</div>
|
||||
{tfRequired ? (
|
||||
<>
|
||||
<p className="text-xs text-gray-500 mb-3">Required for your role, so it can't be turned off.</p>
|
||||
@@ -495,11 +570,12 @@ export default function UserProfilePage() {
|
||||
<p className="text-sm text-gray-500">
|
||||
{tfEnabled
|
||||
? "Choose where your login codes go. We'll send a code there first to check it reaches you."
|
||||
: "Add a second step to logging in: after your password, we send a 6-digit code that you need to enter."}
|
||||
: "Add a second step to logging in: after your password, a 6-digit code from an authenticator app, or one we send you."}
|
||||
</p>
|
||||
<div>
|
||||
<label htmlFor="profile-send-my-codes-by" className="block text-sm font-medium text-gray-700 mb-1">Send my codes by</label>
|
||||
<select id="profile-send-my-codes-by" className={inputCls} value={tfMethod} onChange={e => setTfMethod(e.target.value as TwoFactorMethod)}>
|
||||
<option value="authenticator">An authenticator app (most secure)</option>
|
||||
<option value="email">Email</option>
|
||||
{canWhatsAppCodes && <option value="whatsapp">WhatsApp</option>}
|
||||
</select>
|
||||
@@ -518,11 +594,23 @@ export default function UserProfilePage() {
|
||||
</button>
|
||||
)}
|
||||
<button type="submit" disabled={tfBusy || !tfPassword} className="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm font-medium hover:bg-brand-700 disabled:opacity-50">
|
||||
{tfBusy ? "Sending code…" : "Send verification code"}
|
||||
{tfBusy ? (tfMethod === "authenticator" ? "Preparing…" : "Sending code…") : tfMethod === "authenticator" ? "Set up the app" : "Send verification code"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
{tfRecovery && (
|
||||
<div className="mt-4 rounded-lg border border-amber-300 bg-amber-50 p-4 text-sm" role="region" aria-label="Your recovery codes">
|
||||
<p className="font-medium text-amber-900">Save your recovery codes now</p>
|
||||
<p className="mt-1 text-amber-900">Each works once, in place of a code, if you lose your phone or app. They won't be shown again.</p>
|
||||
<ul className="mt-3 grid grid-cols-2 gap-x-6 gap-y-1 font-mono text-sm sm:grid-cols-3">{tfRecovery.map(c => <li key={c}>{c}</li>)}</ul>
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<button type="button" onClick={downloadRecovery} className="px-3 py-2 rounded-lg bg-white border border-amber-300 text-sm font-medium hover:bg-amber-100">Download</button>
|
||||
<button type="button" onClick={() => navigator.clipboard?.writeText(tfRecovery.join("\n"))} className="px-3 py-2 rounded-lg bg-white border border-amber-300 text-sm font-medium hover:bg-amber-100">Copy</button>
|
||||
<button type="button" onClick={() => setTfRecovery(null)} className="px-3 py-2 rounded-lg bg-amber-600 text-white text-sm font-medium hover:bg-amber-700">I've saved them</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tfMsg && <Alert msg={tfMsg} />}
|
||||
</section>
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ export function LoginForm() {
|
||||
// Two-factor step — set once the password is accepted for an account with 2FA on.
|
||||
const [challenge, setChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||
const [code, setCode] = useState("");
|
||||
// 2.3.0: a recovery code instead of the 6-digit code (xxxxx-xxxxx, single use).
|
||||
const [useRecovery, setUseRecovery] = useState(false);
|
||||
const [rememberDevice, setRememberDevice] = useState(false);
|
||||
const [resendIn, setResendIn] = useState(0);
|
||||
|
||||
@@ -109,6 +111,7 @@ export function LoginForm() {
|
||||
const backToPassword = () => {
|
||||
setChallenge(null);
|
||||
setCode("");
|
||||
setUseRecovery(false);
|
||||
setPassword("");
|
||||
setError(null);
|
||||
};
|
||||
@@ -124,20 +127,24 @@ export function LoginForm() {
|
||||
</p>
|
||||
)}
|
||||
<p className="text-sm text-gray-600 mt-1">
|
||||
We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.
|
||||
{useRecovery
|
||||
? "Enter one of the recovery codes you saved when you turned on two-factor. Each works once."
|
||||
: challenge.method === "authenticator"
|
||||
? "Open your authenticator app and enter the 6-digit code it shows for this site."
|
||||
: <>We sent a 6-digit code to {challenge.destination} by {challenge.method === "whatsapp" ? "WhatsApp" : "email"}. It expires in 10 minutes.</>}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor="login-code" className="block text-sm font-medium mb-1">Verification code</label>
|
||||
<label htmlFor="login-code" className="block text-sm font-medium mb-1">{useRecovery ? "Recovery code" : "Verification code"}</label>
|
||||
<input
|
||||
id="login-code"
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
maxLength={6}
|
||||
inputMode={useRecovery ? "text" : "numeric"}
|
||||
autoComplete={useRecovery ? "off" : "one-time-code"}
|
||||
maxLength={useRecovery ? 11 : 6}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.replace(/\D/g, ""))}
|
||||
onChange={(e) => setCode(useRecovery ? e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "") : e.target.value.replace(/\D/g, ""))}
|
||||
className="w-full border rounded px-3 py-2 text-lg tracking-widest"
|
||||
autoFocus
|
||||
required
|
||||
@@ -158,7 +165,7 @@ export function LoginForm() {
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || code.length !== 6}
|
||||
disabled={loading || (useRecovery ? code.replace(/-/g, "").length !== 10 : code.length !== 6)}
|
||||
className="w-full bg-brand-600 hover:bg-brand-700 text-white rounded py-2 disabled:opacity-60"
|
||||
>
|
||||
{loading ? "Verifying..." : "Verify and log in"}
|
||||
@@ -168,14 +175,21 @@ export function LoginForm() {
|
||||
<button type="button" onClick={backToPassword} className="text-brand-600 hover:underline">
|
||||
Back to login
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={resendIn > 0}
|
||||
className="text-brand-600 hover:underline disabled:text-gray-400 disabled:no-underline"
|
||||
>
|
||||
{resendIn > 0 ? `Resend code in ${resendIn}s` : "Resend code"}
|
||||
</button>
|
||||
{!challenge.enrolling && (
|
||||
<button type="button" onClick={() => { setUseRecovery(!useRecovery); setCode(""); setError(null); }} className="text-brand-600 hover:underline">
|
||||
{useRecovery ? "Use a code instead" : "Use a recovery code"}
|
||||
</button>
|
||||
)}
|
||||
{challenge.method !== "authenticator" && !useRecovery && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResend}
|
||||
disabled={resendIn > 0}
|
||||
className="text-brand-600 hover:underline disabled:text-gray-400 disabled:no-underline"
|
||||
>
|
||||
{resendIn > 0 ? `Resend code in ${resendIn}s` : "Resend code"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { V2Result } from "@/lib/apiV2";
|
||||
|
||||
/**
|
||||
* AI helpers (2.0). The site calls AI through the Cross Events Hub, which keeps a monthly
|
||||
* allowance per licence, shown here as tokens and a percentage (2.3.0). One status per page load is shared by every AI button
|
||||
* allowance per licence, shown here as tokens and a percentage (2.2.0). One status per page load is shared by every AI button
|
||||
* (`useAiStatus`), and every helper call refreshes it — so the buttons disable straight after the
|
||||
* call that used up the allowance.
|
||||
*/
|
||||
|
||||
@@ -12950,6 +12950,28 @@
|
||||
"type": "boolean",
|
||||
"description": "Their role must use two-step sign-in"
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "How their codes come (2.3.0: authenticator = an app)"
|
||||
},
|
||||
"recoveryCodesLeft": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991,
|
||||
"description": "Unused recovery codes (0 with two-step sign-in off)"
|
||||
},
|
||||
"newsPromptPending": {
|
||||
"type": "boolean"
|
||||
},
|
||||
@@ -12995,6 +13017,8 @@
|
||||
"homeCampusId",
|
||||
"createdAt",
|
||||
"twoFactorRequired",
|
||||
"twoFactorMethod",
|
||||
"recoveryCodesLeft",
|
||||
"newsPromptPending",
|
||||
"noticePromptPending",
|
||||
"campusScope"
|
||||
@@ -47764,7 +47788,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
"destination": {
|
||||
@@ -48395,7 +48420,7 @@
|
||||
"Me"
|
||||
],
|
||||
"summary": "Start turning on two-step sign-in",
|
||||
"description": "Sends a code to confirm with.\n\n**Who:** Any signed-in person.",
|
||||
"description": "Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app's first code confirms it.\n\n**Who:** Any signed-in person.",
|
||||
"operationId": "postMeTwo-factorEnable",
|
||||
"security": [
|
||||
{
|
||||
@@ -48414,7 +48439,8 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
"password": {
|
||||
@@ -48448,12 +48474,27 @@
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp"
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
"destination": {
|
||||
"type": "string",
|
||||
"description": "Where the code went, partly hidden"
|
||||
},
|
||||
"secret": {
|
||||
"description": "authenticator: the key to type in by hand",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"otpauthUrl": {
|
||||
"description": "authenticator: show as a QR code",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
@@ -48549,11 +48590,107 @@
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"type": "string"
|
||||
},
|
||||
"recoveryCodes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"description": "Shown once: single-use codes for when the app or phone is lost"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"twoFactorEnabled",
|
||||
"twoFactorMethod"
|
||||
"twoFactorMethod",
|
||||
"recoveryCodes"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"data"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"400": {
|
||||
"description": "Validation failed (VALIDATION_FAILED)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"401": {
|
||||
"description": "Not signed in (UNAUTHENTICATED)",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"$ref": "#/components/schemas/Error"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/me/two-factor/recovery-codes": {
|
||||
"post": {
|
||||
"tags": [
|
||||
"Me"
|
||||
],
|
||||
"summary": "A new set of recovery codes",
|
||||
"description": "Needs the password. The old codes stop working; the new ones are shown once.\n\n**Who:** Any signed-in person.",
|
||||
"operationId": "postMeTwo-factorRecovery-codes",
|
||||
"security": [
|
||||
{
|
||||
"bearerAuth": []
|
||||
}
|
||||
],
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"password": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"password"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "OK",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"data": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"recoveryCodes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"recoveryCodes"
|
||||
],
|
||||
"additionalProperties": {}
|
||||
}
|
||||
@@ -48975,6 +49112,28 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"twoFactorEnabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"description": "How their sign-in codes come (2.3.0: authenticator = an app)",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homeCampusId": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -49148,6 +49307,28 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"twoFactorEnabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"description": "How their sign-in codes come (2.3.0: authenticator = an app)",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homeCampusId": {
|
||||
"type": [
|
||||
"string",
|
||||
@@ -49385,6 +49566,28 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"twoFactorEnabled": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"twoFactorMethod": {
|
||||
"description": "How their sign-in codes come (2.3.0: authenticator = an app)",
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"authenticator"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"homeCampusId": {
|
||||
"type": [
|
||||
"string",
|
||||
|
||||
+97
-4
@@ -4787,7 +4787,7 @@ export interface paths {
|
||||
put?: never;
|
||||
/**
|
||||
* Start turning on two-step sign-in
|
||||
* @description Sends a code to confirm with.
|
||||
* @description Sends a code to confirm with, or for `authenticator` (2.3.0) answers with `secret` and `otpauthUrl` to show as a QR code; the app's first code confirms it.
|
||||
*
|
||||
* **Who:** Any signed-in person.
|
||||
*/
|
||||
@@ -4818,6 +4818,28 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/two-factor/recovery-codes": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/**
|
||||
* A new set of recovery codes
|
||||
* @description Needs the password. The old codes stop working; the new ones are shown once.
|
||||
*
|
||||
* **Who:** Any signed-in person.
|
||||
*/
|
||||
post: operations["postMeTwo-factorRecovery-codes"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/me/two-factor/disable": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -12787,6 +12809,10 @@ export interface operations {
|
||||
createdAt: string;
|
||||
/** @description Their role must use two-step sign-in */
|
||||
twoFactorRequired: boolean;
|
||||
/** @description How their codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod: ("email" | "whatsapp" | "authenticator") | null;
|
||||
/** @description Unused recovery codes (0 with two-step sign-in off) */
|
||||
recoveryCodesLeft: number;
|
||||
newsPromptPending: boolean;
|
||||
noticePromptPending: false | ("first" | "updated");
|
||||
campusScope: string[] | null;
|
||||
@@ -28100,7 +28126,7 @@ export interface operations {
|
||||
data: {
|
||||
challengeId: string;
|
||||
/** @enum {string} */
|
||||
method: "email" | "whatsapp";
|
||||
method: "email" | "whatsapp" | "authenticator";
|
||||
/** @description Where the code went, partly hidden */
|
||||
destination: string;
|
||||
} & {
|
||||
@@ -28472,7 +28498,7 @@ export interface operations {
|
||||
content: {
|
||||
"application/json": {
|
||||
/** @enum {string} */
|
||||
method: "email" | "whatsapp";
|
||||
method: "email" | "whatsapp" | "authenticator";
|
||||
password: string;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
@@ -28490,9 +28516,13 @@ export interface operations {
|
||||
data: {
|
||||
challengeId: string;
|
||||
/** @enum {string} */
|
||||
method: "email" | "whatsapp";
|
||||
method: "email" | "whatsapp" | "authenticator";
|
||||
/** @description Where the code went, partly hidden */
|
||||
destination: string;
|
||||
/** @description authenticator: the key to type in by hand */
|
||||
secret?: string | null;
|
||||
/** @description authenticator: show as a QR code */
|
||||
otpauthUrl?: string | null;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
@@ -28548,6 +28578,60 @@ export interface operations {
|
||||
/** @constant */
|
||||
twoFactorEnabled: true;
|
||||
twoFactorMethod: string;
|
||||
/** @description Shown once: single-use codes for when the app or phone is lost */
|
||||
recoveryCodes: string[];
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
/** @description Validation failed (VALIDATION_FAILED) */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
/** @description Not signed in (UNAUTHENTICATED) */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["Error"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
"postMeTwo-factorRecovery-codes": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": {
|
||||
password: string;
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description OK */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": {
|
||||
data: {
|
||||
recoveryCodes: string[];
|
||||
} & {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
@@ -28738,6 +28822,9 @@ export interface operations {
|
||||
role: "admin" | "supervisor" | "staff" | "user";
|
||||
isActive?: boolean | null;
|
||||
notificationPreference?: ("email" | "whatsapp" | "both") | null;
|
||||
twoFactorEnabled?: boolean | null;
|
||||
/** @description How their sign-in codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null;
|
||||
homeCampusId?: string | null;
|
||||
createdAt?: string | null;
|
||||
} & {
|
||||
@@ -28810,6 +28897,9 @@ export interface operations {
|
||||
role: "admin" | "supervisor" | "staff" | "user";
|
||||
isActive?: boolean | null;
|
||||
notificationPreference?: ("email" | "whatsapp" | "both") | null;
|
||||
twoFactorEnabled?: boolean | null;
|
||||
/** @description How their sign-in codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null;
|
||||
homeCampusId?: string | null;
|
||||
createdAt?: string | null;
|
||||
/** @description Campuses they're limited to */
|
||||
@@ -28972,6 +29062,9 @@ export interface operations {
|
||||
role: "admin" | "supervisor" | "staff" | "user";
|
||||
isActive?: boolean | null;
|
||||
notificationPreference?: ("email" | "whatsapp" | "both") | null;
|
||||
twoFactorEnabled?: boolean | null;
|
||||
/** @description How their sign-in codes come (2.3.0: authenticator = an app) */
|
||||
twoFactorMethod?: ("email" | "whatsapp" | "authenticator") | null;
|
||||
homeCampusId?: string | null;
|
||||
createdAt?: string | null;
|
||||
} & {
|
||||
|
||||
@@ -72,7 +72,10 @@ export function resolveToApiOrigin(urlOrPath: string | null | undefined): string
|
||||
} catch {
|
||||
// fall through to relative handling
|
||||
}
|
||||
return API_BASE ? `${API_BASE}${raw}` : raw;
|
||||
// Stored uploads ("/uploads/…") are served under /api/uploads (2.2.0), so they reach the
|
||||
// backend when the site and its API share one address.
|
||||
const path = raw.startsWith("/uploads/") ? `/api${raw}` : raw;
|
||||
return API_BASE ? `${API_BASE}${path}` : path;
|
||||
}
|
||||
|
||||
// The parsed JSON body of a failed request — v1 sends `message` (some routes add a
|
||||
|
||||
@@ -26,7 +26,7 @@ export type AuthResponse = AuthUser & {
|
||||
deviceToken?: string;
|
||||
};
|
||||
|
||||
export type TwoFactorMethod = "email" | "whatsapp";
|
||||
export type TwoFactorMethod = "email" | "whatsapp" | "authenticator";
|
||||
|
||||
// What the login endpoint returns instead of a token when the account has 2FA on:
|
||||
// a code was sent to `destination` (masked) and must be exchanged for the token.
|
||||
@@ -37,6 +37,9 @@ export type TwoFactorChallenge = {
|
||||
destination: string;
|
||||
// The role requires 2FA and it wasn't on yet: verifying this code turns it on.
|
||||
enrolling?: boolean;
|
||||
// 2.3.0, setting up an authenticator app: the key and its otpauth:// link (shown as a QR code).
|
||||
secret?: string;
|
||||
otpauthUrl?: string;
|
||||
};
|
||||
|
||||
export function isTwoFactorChallenge(res: unknown): res is TwoFactorChallenge {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/events",
|
||||
"version": "2.1.1",
|
||||
"version": "2.3.1",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"dev:backend": "cd backend && npm run dev",
|
||||
|
||||
+47
-5
@@ -8,6 +8,10 @@ This replaces the old rule "the Hub never deploys" (decisions 10 and 23). The pa
|
||||
stays: **no site depends on the Hub to keep running**, and everything still goes through the
|
||||
`crosscode` script (EVENTS-2.2-PLAN §4), which keeps working by hand over SSH.
|
||||
|
||||
**Built, VM tested and released 2026-11-17** (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`; with
|
||||
`events@2.3.0`). Not rolled out yet: the steps are in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md). Where the
|
||||
build differs from this plan, see [Changes while building](#changes-while-building).
|
||||
|
||||
## Contents
|
||||
|
||||
1. [The shape](#1-the-shape)
|
||||
@@ -177,8 +181,9 @@ monorepo, listing every variable with its layer, whether it's required, and a de
|
||||
itself.
|
||||
- **URLs are checked before and after.** Before: the form checks that the domain's DNS points at
|
||||
the central server and warns if not (the install still runs). After Joshua marks the proxy done:
|
||||
the Hub checks `https://<domain>/` (frontend answers), `https://<domain>/health` (backend
|
||||
answers with the right version) and that `/health` reports the `FRONTEND_URL` it was given.
|
||||
the Hub checks `https://<domain>/` (frontend answers), `https://<domain>/api/health` (backend
|
||||
answers with the right version; `/health` before Events 2.2.0) and that it reports the
|
||||
`FRONTEND_URL` it was given.
|
||||
|
||||
**For Joshua to set per server before the first install:** the database settings and
|
||||
`TRUST_PROXY`. Behind frp the app sees every connection from frpc on `127.0.0.1`, and the
|
||||
@@ -375,7 +380,8 @@ Set up in FastPanel: events.hope.co.za (Hope Family Church, Cross Events)
|
||||
|
||||
1. Add the site events.hope.co.za.
|
||||
2. Proxy:
|
||||
/api, /uploads, /health, /docs → http://127.0.0.1:20011 (backend)
|
||||
/api → http://127.0.0.1:20011 (backend; Events 2.2.0+, older
|
||||
releases also need /uploads, /health, /docs)
|
||||
everything else → http://127.0.0.1:20010 (frontend)
|
||||
Pass the Host header and X-Forwarded-For / X-Forwarded-Proto: https.
|
||||
Allow uploads up to 25 MB.
|
||||
@@ -395,7 +401,7 @@ Central check: both ports are open in frps and only on 127.0.0.1.
|
||||
(lib/env.sh), ports given on the command line instead of picked.
|
||||
- `apps/events`: `env.template.json`, and the export (`crosscode export` calls a backend script
|
||||
that writes `crosscode.church-export/1`).
|
||||
- `packages/contracts` **1.2.0**: `crosscode.agent-job/1`, `crosscode.agent-report/1`,
|
||||
- `packages/contracts` **1.3.0** (1.2.0 went out with Events 2.2.0): `crosscode.agent-job/1`, `crosscode.agent-report/1`,
|
||||
`crosscode.agent-stats/1`, `crosscode.env-template/1`, `crosscode.church-export/1`.
|
||||
|
||||
**`events-hub` (Hub 2.1.0)**
|
||||
@@ -439,7 +445,7 @@ Central check: both ports are open in frps and only on 127.0.0.1.
|
||||
|
||||
## 14. Rolling it out
|
||||
|
||||
1. Contracts 1.2.0 → the `crosscode` script changes (with Events 2.2.0 out first) → agent 1.0.0
|
||||
1. Contracts 1.3.0 → the `crosscode` script changes (with Events 2.2.0 out first) → agent 1.0.0
|
||||
→ Hub 2.1.0, each released as usual (branch → merge → tag → push).
|
||||
2. On the central server: add `proxy_bind_addr = 127.0.0.1` to `frps.ini` if it's missing (check
|
||||
that each FastPanel site still answers), then join the central agent.
|
||||
@@ -451,6 +457,42 @@ Central check: both ports are open in frps and only on 127.0.0.1.
|
||||
5. Docs: CHANGELOGs, HANDOVER.md (1d done), `events-hub/deployment.md` (the job-signing key),
|
||||
a server how-to in `apps/agent/README.md`.
|
||||
|
||||
## Changes while building
|
||||
|
||||
Made on 2026-11-17, while building and in the VM test; none changes what Joshua or a church sees.
|
||||
|
||||
1. **Config encryption** is X25519 + HKDF-SHA256 + AES-256-GCM (`x25519-hkdf-sha256-aes-256-gcm`)
|
||||
instead of `x25519-xsalsa20-poly1305`: Node's built-in crypto has no XSalsa20, and this needs no
|
||||
extra library on the servers. Same guarantee: only the server's private key opens it.
|
||||
2. **Deployments, not new Install fields.** An `Install` row only exists once a site registers
|
||||
with its licence, so the Hub keeps a `Deployment` per product per server (short name, domain,
|
||||
ports, status), linked to its Install when the site registers. Installs made from the Hub
|
||||
register by themselves: `HUB_LICENCE_KEY` in their `.env` (Events, on first start).
|
||||
3. **The export key** goes to the Hub in the export job's report, so the Hub can email the link;
|
||||
it's used once and never stored (job rows keep the report without it). The Hub still can't read
|
||||
the stored file.
|
||||
4. **Jobs are signed when the agent picks them up**, not when they're planned, so a scheduled job
|
||||
carries the server configuration as it is at that moment.
|
||||
5. **Uninstall runs as a batch of two** (export, then uninstall), so the uninstall never runs if
|
||||
the export failed.
|
||||
6. **Install behind frp** doesn't use nginx on the church server: frpc tunnels the app's two ports
|
||||
straight to the central server (`crosscode install --frp`). The ports from the Hub are used for
|
||||
`local_port` and `remote_port`.
|
||||
7. **`crosscode install`** refuses a database or role that already exists, so it can never take
|
||||
over (or, on a failed install, drop) another site's database.
|
||||
8. **PM2 runs under its own systemd unit** (`pm2-<user>`) for every site user, set up by the
|
||||
`crosscode` script before any PM2 command. Found in the VM test: a PM2 daemon started from the
|
||||
agent's job belonged to the agent's service, so stopping or updating the agent stopped the
|
||||
sites. The agent's stats never start a PM2 daemon.
|
||||
9. **frpc is restarted once**, the first time its admin lines are added (a running frpc only reads
|
||||
them when it starts); later changes reload it. Every tunnel on that server drops for a few
|
||||
seconds that first time.
|
||||
10. **The VM test** (§13) also fixed: `adopt` applies a release's new migrations; a failed
|
||||
migration is marked rolled back so later deploys aren't blocked; the agent install builds with
|
||||
the root's tools; tags are fetched with `--force`; the Hub saves the servers settings, lets a
|
||||
failed or removed install's short name be used again, and links a Hub-installed site to its
|
||||
registration so banners reach it. The full list is in [HANDOVER.md](./HANDOVER.md).
|
||||
|
||||
## Decisions
|
||||
|
||||
Agreed with Joshua on 2026-11-12 (ROADMAP-v3 decisions 27–37):
|
||||
|
||||
@@ -252,6 +252,10 @@ database or its name.
|
||||
|
||||
## 6. Testing
|
||||
|
||||
**Done 2026-11-17** on a WSL Ubuntu 24.04 VM (steps 1–7 below; step 8 in the agent test). All
|
||||
pass after two fixes: `adopt` refused a release with new migrations (it now applies them in the
|
||||
switch-over), and a failed migration blocked later deploys (now marked rolled back).
|
||||
|
||||
- **Events, unchanged behaviour:** backend Jest, `tsc --noEmit`, frontend build and the
|
||||
Playwright e2e run, all from the monorepo. They should give the same counts as the 2.1.1
|
||||
baseline.
|
||||
|
||||
+54
-26
@@ -1,21 +1,21 @@
|
||||
# Handover — Cross Code, all products
|
||||
|
||||
Last updated: 2026-11-12. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
Last updated: 2026-11-17. **The plan is [ROADMAP-v3.md](./ROADMAP-v3.md)** (decided 2026-11-03,
|
||||
decisions table near the end). This file says where each phase stands and what comes next.
|
||||
Product-specific notes (where the code lives, known gaps) stay with each product: Cross Events'
|
||||
are in `hope-events/docs/HANDOVER.md` (`apps/events/docs/HANDOVER.md` from Events 2.2.0), and
|
||||
the Hub's are in `events-hub/docs/`.
|
||||
are in [`apps/events/docs/HANDOVER.md`](../apps/events/docs/HANDOVER.md), and the Hub's are in
|
||||
`events-hub/docs/` and `events-hub/deployment.md`.
|
||||
|
||||
The docs for every product are here in `docs/`: the roadmap, the Hub protocol
|
||||
([hub-protocol.md](./hub-protocol.md), with a copy in `events-hub`), this handover and the plans
|
||||
for each phase. They moved here from `hope-events/docs/` on 2026-11-05.
|
||||
([hub-protocol.md](./hub-protocol.md), with a copy in `events-hub`), this handover, the plans
|
||||
for each phase and the rollout checklist ([ROLLOUT-1.0.md](./ROLLOUT-1.0.md)).
|
||||
|
||||
## Repos
|
||||
|
||||
| Repo | What |
|
||||
|------|------|
|
||||
| `joshua/crosscode-platform` (this one) | Contracts, the apps (Accounts, Website, App, and Events from 2.2.0), shared packages, the `crosscode` script (from Events 2.2.0), the server agent (`apps/agent`, phase 1d), and these docs |
|
||||
| `joshua/hope-events` | Cross Events up to 2.1.x. Archived after the 2.2.0 move |
|
||||
| `joshua/crosscode-platform` (this one) | Contracts, the apps (Events from 2.2.0; Accounts, Website and App to come), shared packages, the `crosscode` script (`scripts/`), the server agent (`apps/agent`), and these docs |
|
||||
| `joshua/hope-events` | Cross Events up to 2.1.x. Frozen; archived once every install is adopted (EVENTS-2.2-PLAN §7) |
|
||||
| `joshua/events-hub` | Cross Code Hub. Its own server, its own `scripts/deploy.sh` |
|
||||
| `joshua/crosscode-site` | crosscode.co.za. Updated at the end of every phase that changes what it says (ROADMAP §9) |
|
||||
|
||||
@@ -23,26 +23,44 @@ for each phase. They moved here from `hope-events/docs/` on 2026-11-05.
|
||||
|
||||
| Phase | What | State |
|
||||
|-------|------|-------|
|
||||
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04 (`contracts@1.0.0`, `contracts@1.1.0`). Not published to a registry (decision 22): the Hub gets a packed release committed to its repo |
|
||||
| 1 | Hub 2.0.0 | **Released** 2026-11-05 (`events-hub` `v2.0.0`; `docs/HUB-2.0-PLAN.md` there). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first). crosscode-site's address prices are merged, **not deployed yet** |
|
||||
| 1b | Cross Events 2.2.0: moves here as `apps/events`, `crosscode` script | **In progress.** Planned in [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). **Steps 1–3 done 2026-11-12** (merged into `main`): history merged in under `apps/events` (from `hope-events` `e6c9670`), workspaces and one root lockfile with versions pinned to 2.1.1, same test results as 2.1.1 (711 backend tests, typecheck, both builds). **The `crosscode` script and `adopt` (§4–5) are written** (branch `feat/crosscode-script`, 2026-11-12; shellcheck and 47 bats tests pass, not yet run on a server). **Still to do:** VM testing (§6), the version bump and `events@2.2.0` tag, adopting each install, archiving `hope-events` (§7). Until then servers keep deploying from `hope-events` `v2.1.1`, and **Events work happens here** (`hope-events` is frozen; a hotfix there as 2.1.2 is cherry-picked into `apps/events`) |
|
||||
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | Not started (`TwoFactorMethod` enum in Events' `prisma/schema.prisma`) |
|
||||
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.2.0): server agent, installs / scheduled updates / uninstalls from the Hub, server stats | **Planned** 2026-11-12 in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) (ROADMAP decisions 27–37). Starts after 1b; can run alongside 1c |
|
||||
| 0 | contracts 1.0.0 / 1.1.0 | **Released** 2026-11-04. Not published to a registry (decision 22): the Hub gets a packed release committed to its repo (`backend/vendor/`) |
|
||||
| 1 | Hub 2.0.x | **Released** (`v2.0.0` 2026-11-05, `v2.0.1` AI tokens and `v2.0.2` refunds / voiding refunded invoices, 2026-11-17). **Not deployed yet:** `events-hub/deployment.md` → "Upgrading to 2.0" (run `check-hub2` first) |
|
||||
| 1b | Cross Events 2.2.0: moved here as `apps/events`, the `crosscode` script | **Released** 2026-11-17 (`events@2.2.0`, with AI use in tokens and the backend under `/api`). **VM tested 2026-11-17** (EVENTS-2.2-PLAN §6, all passing after fixes). **Not rolled out:** servers still run `hope-events` `v2.1.1` until each install is adopted |
|
||||
| 1c | Cross Events 2.3.0: authenticator app 2FA (TOTP + recovery codes) | **Released** 2026-11-17 (`events@2.3.0`). crosscode-site `v1.3.0` lists it (merged and tagged, **not deployed**) |
|
||||
| 1d | Agent 1.0.0 + Hub 2.1.0 (+ contracts 1.3.0) | **Released** 2026-11-17 (`agent@1.0.0`, `contracts@1.3.0`, Hub `v2.1.0`). **VM tested** end to end (AGENT-1.0-PLAN §13: joins, installs behind frp, scheduled / batch / missed updates, uninstall with export and purge, forged and replayed jobs). **Not rolled out** |
|
||||
| 2 | Cross Events 2.4.0: protocol v2, Linked products, event feed, `packages/seo` | Not started. Events keeps speaking protocol 1 until then |
|
||||
| 3–7 | Accounts 1.0.0 → Website 1.0.0 → Events 3.0.0 → App 1.0.0 → App 1.x | Not started |
|
||||
|
||||
## Next up
|
||||
|
||||
1. **Deploy Hub 2.0.0** and **crosscode-site** (the address prices). This finishes phase 1 and is
|
||||
needed before 2.2.0, because Hub 1.7 can't see `events@…` tags.
|
||||
2. **Cross Events 2.2.0**: [EVENTS-2.2-PLAN.md](./EVENTS-2.2-PLAN.md). Decided 2026-11-05:
|
||||
`adopt` builds next to the running install and switches over, and `adopt --undo` is built
|
||||
(ROADMAP decisions 25–26).
|
||||
3. **Agent 1.0.0 + Hub 2.1.0** (phase 1d): [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). Before the
|
||||
first install through it: check `proxy_bind_addr = 127.0.0.1` in `frps.ini` on the central
|
||||
server (worth doing now: without it, tunnel ports such as `:5000` may be reachable straight from
|
||||
the internet), and set each server's database settings and `TRUST_PROXY` in the Hub.
|
||||
4. **Cross Events 2.3.0** (authenticator app 2FA), then 2.4.0, as in ROADMAP §9.
|
||||
1. **Roll out**, in the order in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md): Hub 2.1.0 (make and back up
|
||||
the job-signing key first) → the central server's agent (check `proxy_bind_addr = 127.0.0.1`)
|
||||
→ each church server's agent → **adopt** the demo site, then each church (Link existing → Move
|
||||
onto the monorepo) → a throwaway New install to prove FASTPANEL, DNS and Let's Encrypt.
|
||||
2. **Deploy crosscode-site `v1.3.0`** (secure sign-in in the features and the brochure).
|
||||
3. **Archive `hope-events`** once every install reports 2.2.0 or later (EVENTS-2.2-PLAN §7).
|
||||
4. **Cross Events 2.4.0** (phase 2), as in ROADMAP §9.
|
||||
|
||||
## The VM test (2026-11-17)
|
||||
|
||||
Everything above was run on a WSL Ubuntu 24.04 VM before release: a church server, a "central"
|
||||
network namespace running frps with `proxy_bind_addr`, the Hub (`feat/servers-agent`) and local
|
||||
git mirrors standing in for c-git. It found nine bugs, all fixed with tests before tagging. None
|
||||
lost data, because each failed safely:
|
||||
|
||||
1. `adopt` refused a release with new migrations (it now applies them in the switch-over).
|
||||
2. A failed migration blocked every later deploy (Prisma P3009; now marked rolled back).
|
||||
3. The agent install skipped the root's build tools (`npm ci --include-workspace-root`).
|
||||
4. A failed install's short name couldn't be used again.
|
||||
5. The Hub didn't save the servers settings (install defaults, port range, central IP).
|
||||
6. frpc only reads its admin lines when it starts (restarted once the first time).
|
||||
7. **A site's PM2 belonged to the agent's service**, so stopping or updating the agent took down
|
||||
every site it had installed. PM2 now always runs under `pm2-<user>`.
|
||||
8. Update and closing banners never reached Hub-installed sites (registration now links them).
|
||||
9. A moved tag blocked a church's deploys (tags are fetched with `--force`).
|
||||
|
||||
Not covered by the VM: FASTPANEL, real DNS, Let's Encrypt. Hence the throwaway install in the
|
||||
rollout.
|
||||
|
||||
## Things to remember across phases
|
||||
|
||||
@@ -51,10 +69,20 @@ for each phase. They moved here from `hope-events/docs/` on 2026-11-05.
|
||||
`backend/src/utils/billing/tiers.js`) in the same phase, so the site and the Hub never disagree.
|
||||
- **A phase isn't done until crosscode-site matches it** (ROADMAP §9, "Updating crosscode-site").
|
||||
- Servers stay **PM2 + nginx** (no Docker), with one database per product per church, under
|
||||
`/var/www/sites/<church>/<product>`.
|
||||
`/var/www/sites/<church>/<product>`. Each site user's PM2 runs as a systemd unit,
|
||||
`pm2-<user>`; the `crosscode` script makes sure of it before any PM2 command.
|
||||
- **The agent pins the Hub's job key** when it joins. Back up `events-hub/backend/keys/` (licence
|
||||
and job keys); replacing the job key means every server joins again.
|
||||
- **A new `.env` variable** goes in three env templates: `apps/<product>/env.template.json`,
|
||||
`scripts/products/<product>.env.template.json` and the Hub's `envTemplates/<product>.json`.
|
||||
- **A new Events install never takes over an existing database**: moving an existing site is
|
||||
`adopt`, not a New install pointed at the old database.
|
||||
- **Prisma in the monorepo:** each app other than Events sets its own generator `output`, so
|
||||
hoisted clients don't overwrite each other (EVENTS-2.2-PLAN §2).
|
||||
- **AI for a church:** set the licence's monthly AI cap above R0 on the Hub; with no cap the
|
||||
buttons don't show (rules in Events' handover, "AI rules").
|
||||
- **Releasing:** branch → merge → tag (`<product>@<version>`) → push, with a CHANGELOG entry, and
|
||||
`npm run check` first. Pushes to c-git often fail authentication the first time; retry once.
|
||||
buttons don't show (rules in Events' handover, "AI rules"). Churches see tokens; only the Hub
|
||||
shows rand (markup 15% by default).
|
||||
- **Releasing:** branch → merge → tag (`<product>@<version>` here, `v<version>` in events-hub and
|
||||
crosscode-site) → push, with a CHANGELOG entry, and `npm run check` first. Pushes to c-git often
|
||||
fail authentication the first time; retry once. A push can also hang waiting on a login prompt
|
||||
after it has already gone through: check with `git ls-remote` before pushing again.
|
||||
|
||||
+5
-5
@@ -613,9 +613,9 @@ Planned in [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). In short:
|
||||
|-------|---------|------|----------------|
|
||||
| 0 | contracts 1.0.0 | `crosscode.event/1`, `crosscode.church/1`, `crosscode.identity/1`, Hub protocol v2: schemas, generated JSON Schema, docs, sample payloads, the monorepo set up. **Released 2026-11-04** | Everything else depends on them |
|
||||
| 1 | **Hub 2.0.0** | Cross Code Hub: products, licence per product, per-customer billing with bundles, protocol v2 (v1 still accepted), sibling discovery, AI usage per product, **releases per product with requirements** (§5), contracts as a committed file (§2). **Released 2026-11-05** (crosscode-site address prices merged) | Must exist before a second product is sold, and before Events releases come from the monorepo |
|
||||
| 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. No feature changes, so a problem is clearly the move | Before more products, so every product is released and deployed the same way from the start |
|
||||
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses | Independent and useful now; the Accounts migration later carries it over |
|
||||
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.2.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
|
||||
| 1b | **Cross Events 2.2.0** | **Moves into the monorepo** as `apps/events`, with its git history (merged in, not copied); its packages become workspaces; the **`crosscode` script** (`deploy`, `status`, `install`, `adopt`; §8) replaces `scripts/deploy.sh` and `scripts/install.sh`; every install moved with `crosscode adopt`; `hope-events` archived. Planned with no feature changes; two small ones were added on 2026-11-17 (decided by Joshua): **AI use shown in tokens**, never rand, outside the Hub (needs Hub 2.0.1), and **everything the backend serves under `/api`**, so a site and its API share one address and one proxy rule. **Tagged 2026-11-17, before the VM testing; VM tested the same day** | Before more products, so every product is released and deployed the same way from the start |
|
||||
| 1c | **Cross Events 2.3.0** | **Authenticator app 2FA** (TOTP) next to email and WhatsApp, with recovery codes; admins can see which method each staff account uses. **Released 2026-11-17** (`events@2.3.0`) | Independent and useful now; the Accounts migration later carries it over |
|
||||
| 1d | **Agent 1.0.0 + Hub 2.1.0** (contracts 1.3.0) | **Server agent** on every server (polls only, signed jobs, runs the `crosscode` script); Hub: Servers page with stats and alerts, server configuration, frp port list, New install with a choice of server, scheduled / emergency / batch updates with notice to the church, uninstall with an encrypted JSON export, emailed reports. [AGENT-1.0-PLAN.md](./AGENT-1.0-PLAN.md). **Released 2026-11-17** after the VM test; rollout in [ROLLOUT-1.0.md](./ROLLOUT-1.0.md) | Right after 1b (it runs the `crosscode` script), so every new church from then on is installed from the Hub. Can run alongside 1c |
|
||||
| 2 | **Cross Events 2.4.0** | Reports `product: "events"` (protocol v2), **Linked products**, the event feed (publish + show events from siblings), `packages/seo` (§11) with canonical links for imported events | Small; ready for when the Website exists |
|
||||
| 3 | **Accounts 1.0.0** | OIDC provider, sign-in, 2FA (email, WhatsApp, authenticator app), password reset, consent and notice, export / delete fan-out, admin, install script | The Website is built on it from day one |
|
||||
| 4 | **Church Website 1.0.0** | Public site with the **four templates** (§6), admin, simple events + feed, SEO (§11), Hope Family Church as the first church, then a second test church on a different template to prove it repeats | More churches need a website than an app; it also covers the "website only" case |
|
||||
@@ -636,8 +636,8 @@ At the end of each phase, update it in the same sitting and deploy it (its `DEPL
|
||||
|-------|--------------------------------|
|
||||
| 0 contracts | Nothing |
|
||||
| 1 Hub 2.0.0 | Bundle discounts (15% / 25%) and the address add-on (own domain R0 · Cross Code address R10 · domain included R25) in `src/data/pricing.mjs`, worded so it's clear the Website and App are still coming. Legal pages if billing terms change |
|
||||
| 1b Events 2.2.0 | Nothing (the move doesn't change what Cross Events does) |
|
||||
| 1c Events 2.3.0 | Authenticator app 2FA in the Cross Events feature list (`src/data/cross-events.mjs`) and the security / POPIA wording |
|
||||
| 1b Events 2.2.0 | The AI allowance in tokens instead of rand (`src/data/cross-events.mjs`, the brochure). Done in crosscode-site 1.2.0 |
|
||||
| 1c Events 2.3.0 | Authenticator app 2FA in the Cross Events feature list (`src/data/cross-events.mjs`) and the security / POPIA wording. |
|
||||
| 1d Agent 1.0.0 + Hub 2.1.0 | Nothing (it changes how installs are run, not what churches buy) |
|
||||
| 2 Events 2.4.0 | "Works with the Church Website and App" (event feed, Linked products) on the Cross Events page, as "coming" until those ship |
|
||||
| 3 Accounts 1.0.0 | "One sign-in for all your church's products" on the Products page. Accounts isn't sold, so no page or price of its own |
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# Rollout: Hub 2.1, the agent and Events 2.3 on the real servers
|
||||
|
||||
The order to move the live servers onto the agent, so that installs, updates and uninstalls are run
|
||||
from the Hub. Each step can be stopped after without leaving anything half done. Tested end to end
|
||||
on a VM (WSL: a church server, a central server with frps, the Hub) on 2026-11-17; the real servers
|
||||
add FASTPANEL, real DNS and Let's Encrypt, which the VM didn't have, so step 6 starts with a
|
||||
throwaway church.
|
||||
|
||||
Releases: `events@2.3.0`, `contracts@1.3.0`, `agent@1.0.0` (crosscode-platform), Hub `v2.1.0`,
|
||||
crosscode-site `v1.3.0`.
|
||||
|
||||
## Before you start
|
||||
|
||||
- [ ] A backup of the Hub's database and `backend/keys/` (the licence key).
|
||||
- [ ] A backup of each church's database (`pg_dump`) and `uploads/`. `adopt` and `deploy` take
|
||||
their own backups too, but keep one that's yours.
|
||||
- [ ] Know your frp port range (`allow_ports` in `frps.ini`) and which ports your hand-written
|
||||
tunnels use.
|
||||
|
||||
## 1. The Hub (2.1.0)
|
||||
|
||||
Follow `events-hub/deployment.md` → "Upgrading to 2.1":
|
||||
|
||||
- [ ] `npm run generate-keys -- --job` in `backend/`; back up `keys/hub-job-key.pem` with the
|
||||
licence key. **Agents pin this key when they join**: losing or replacing it means every server
|
||||
joins again.
|
||||
- [ ] `.env`: `HUB_JOB_SIGNING_KEY_FILE=./keys/hub-job-key.pem` and
|
||||
`HUB_PUBLIC_URL=https://hub.crosscode.co.za`.
|
||||
- [ ] `bash scripts/deploy.sh v2.1.0`.
|
||||
- [ ] Servers → Ports & defaults: the port range, the central server's IP, the install defaults.
|
||||
Mark every port a hand-written tunnel uses as taken.
|
||||
|
||||
## 2. The central server (frps)
|
||||
|
||||
- [ ] `frps.ini` has `proxy_bind_addr = 127.0.0.1` (tunnelled ports are then only reachable by
|
||||
nginx on that server). Restart frps and check every FASTPANEL site still answers.
|
||||
- [ ] Hub → Servers → Add server → **Central**; run the command it shows as root. It's read-only:
|
||||
it checks a new install's ports in frps and watches frps.
|
||||
- [ ] Within a minute the server shows on Servers with its stats.
|
||||
|
||||
## 3. Each church server
|
||||
|
||||
- [ ] Hub → Servers → Add server → **Church**; run the command as root. It installs Node tools,
|
||||
the agent (`/opt/crosscode/agent`) and the crosscode script (`/opt/crosscode/tools`, from
|
||||
main), and starts `crosscode-agent`. The agent listens on nothing.
|
||||
- [ ] On the server's page: its configuration. `TRUST_PROXY=loopback` behind frp; the database:
|
||||
`DB_HOST`/`DB_PORT`/`DB_ADMIN_URL` for a separate PostgreSQL, or nothing for the local one.
|
||||
- [ ] `systemctl status crosscode-agent` is active; the server's stats show on the Hub.
|
||||
- [ ] The first time the agent changes `frpc.ini` it adds the admin lines and **restarts frpc once**
|
||||
(every tunnel on that server drops for a few seconds). Do the first install on a quiet
|
||||
evening. Later changes only reload frpc.
|
||||
|
||||
## 4. Existing sites (the demo site and the churches): adopt, don't reinstall
|
||||
|
||||
Moving a site you already run onto the monorepo is `adopt`. It keeps the same database, uploads,
|
||||
`.env`, ports and nginx site; it only swaps the code and PM2 underneath, with a backup and an undo.
|
||||
|
||||
A New install can't take over an existing database: it refuses a database or role that already
|
||||
exists, so that it can never overwrite a church's data. "Install new and point it at the old
|
||||
database" would therefore stop at that check.
|
||||
|
||||
For each site:
|
||||
|
||||
- [ ] Servers → Installs → **Link existing**: the server, its folder name and its two ports.
|
||||
- [ ] **Move onto the monorepo** (an `adopt` job): planned at least 4 hours ahead; the church gets
|
||||
the email and banner. Start with the demo site.
|
||||
- [ ] After it: the site answers, `crosscode status` on the server shows it on `events@2.3.0`, its
|
||||
PM2 runs as `pm2-<user>` under systemd.
|
||||
- [ ] If something's wrong: the job's page has the log. `crosscode adopt <church> --undo` on the
|
||||
server puts the old install back (for 14 days).
|
||||
|
||||
## 5. Updates from then on
|
||||
|
||||
- [ ] Updates → pick installs and a version → a time at least 4 hours ahead (or an emergency
|
||||
update: 15 minutes, a reason and your 2FA code). A batch runs one church at a time and stops at
|
||||
the first failure; a failed update rolls back by itself.
|
||||
- [ ] An agent that's offline when a job is due doesn't run it late: the job is **missed** and
|
||||
you plan it again (the church gets a new notice).
|
||||
|
||||
## 6. New churches
|
||||
|
||||
- [ ] First, a throwaway church on a real server (a test domain): New install → the report email
|
||||
with the FASTPANEL steps → add the nginx site with its two ports → **Proxy done** → live.
|
||||
Uninstall it after (it exports first; check the download link works).
|
||||
- [ ] Then real churches the same way.
|
||||
|
||||
## 7. Decommissioning the old setup
|
||||
|
||||
Only after every site is adopted and has run on 2.3.0 for a while:
|
||||
|
||||
- [ ] Each adopted site keeps its old folder 14 days for `adopt --undo`. After that, `crosscode
|
||||
status` warns about it and shows the `rm -rf` to remove it; once removed, undo isn't possible.
|
||||
- [ ] The archived `hope-events` repo stays read-only (its `v…` tags are the history).
|
||||
- [ ] Old PM2 processes or cron jobs from the hand-run deploys: check `pm2 ls` for each site user
|
||||
shows only `<church>-events-backend` and `<church>-events-frontend`.
|
||||
|
||||
## If something goes wrong
|
||||
|
||||
| Symptom | Look at |
|
||||
|---|---|
|
||||
| A server doesn't show on the Hub | `journalctl -u crosscode-agent`; the server can reach `HUB_PUBLIC_URL` |
|
||||
| A job is refused by the agent | The job key changed (the server must join again) or the server's clock is off |
|
||||
| A new install's tunnels don't open | `journalctl -u frpc`; Hub → Jobs → the central `check-ports` job |
|
||||
| A site is down after an agent restart | `systemctl status pm2-<user>` (sites run under their own unit, not the agent's) |
|
||||
| An update failed | Hub → Jobs → its log; it rolled back. A failed migration is marked rolled back, so the next update isn't blocked |
|
||||
@@ -214,14 +214,14 @@ X-Hub-Install / X-Hub-Timestamp / X-Hub-Signature (as in §3)
|
||||
active (suspended, revoked, or past its grace days), or the Hub's AI isn't set up.
|
||||
- **`capReached: true`** — show the buttons **disabled** ("This month's AI allowance is used up — it
|
||||
renews on 1 December"). Reached means there isn't room left for even a small call.
|
||||
- **Churches see tokens, never rand** (Hub 2.0.1, Cross Events 2.3.0). `usedInputTokens` /
|
||||
- **Churches see tokens, never rand** (Hub 2.0.1, Cross Events 2.2.0). `usedInputTokens` /
|
||||
`usedOutputTokens` are this month's tokens over all the church's installs (input counts cached
|
||||
prompt tokens). `capInputTokens` / `capOutputTokens` are an **estimate** of the allowance: what half
|
||||
the cap buys as input and half as output, at the current model price, exchange rate and markup,
|
||||
rounded down to a thousand. `usedPercent` is exact (it's worked out in rand). Installs show the
|
||||
tokens and the percentage, and don't pass the cents on.
|
||||
- `capCents` / `usedCents` are cents (rand) as **charged** to the church, with fractions (a call costs
|
||||
a fraction of a cent), for the Hub and for installs before Cross Events 2.3.0. The month is South
|
||||
a fraction of a cent), for the Hub and for installs before Cross Events 2.2.0. The month is South
|
||||
African time; `renewsOn` is the 1st of the next month.
|
||||
|
||||
### A helper call
|
||||
|
||||
Generated
+70
-51
@@ -38,13 +38,28 @@
|
||||
"name": "@crosscode/accounts",
|
||||
"version": "0.0.0"
|
||||
},
|
||||
"apps/agent": {
|
||||
"name": "@crosscode/agent",
|
||||
"version": "1.0.1",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@crosscode/contracts": "*",
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"bin": {
|
||||
"crosscode-agent": "dist/cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=24"
|
||||
}
|
||||
},
|
||||
"apps/app": {
|
||||
"name": "@crosscode/app",
|
||||
"version": "0.0.0"
|
||||
},
|
||||
"apps/events/backend": {
|
||||
"name": "@crosscode/events-backend",
|
||||
"version": "2.1.1",
|
||||
"version": "2.3.1",
|
||||
"hasInstallScript": true,
|
||||
"dependencies": {
|
||||
"@cj-tech-master/excelts": "^10.2.0",
|
||||
@@ -91,7 +106,7 @@
|
||||
},
|
||||
"apps/events/frontend": {
|
||||
"name": "@crosscode/events-frontend",
|
||||
"version": "2.1.1",
|
||||
"version": "2.3.1",
|
||||
"dependencies": {
|
||||
"@dnd-kit/core": "^6.3.1",
|
||||
"@hookform/resolvers": "^5.2.1",
|
||||
@@ -119,7 +134,7 @@
|
||||
"date-fns": "^4.1.0",
|
||||
"idb": "^8.0.4",
|
||||
"lucide-react": "^0.536.0",
|
||||
"next": "^16.4.3",
|
||||
"next": "^16.4.6",
|
||||
"qrcode": "^1.5.4",
|
||||
"react": "^19.3.1",
|
||||
"react-day-picker": "^9.8.1",
|
||||
@@ -138,7 +153,7 @@
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"autoprefixer": "^10.4.21",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint-config-next": "^16.4.3",
|
||||
"eslint-config-next": "^16.4.6",
|
||||
"openapi-typescript": "^7.13.0",
|
||||
"postcss": "^8.5.6",
|
||||
"tailwindcss": "3.4",
|
||||
@@ -876,6 +891,10 @@
|
||||
"resolved": "apps/accounts",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/agent": {
|
||||
"resolved": "apps/agent",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@crosscode/app": {
|
||||
"resolved": "apps/app",
|
||||
"link": true
|
||||
@@ -2958,15 +2977,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/env": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.3.tgz",
|
||||
"integrity": "sha512-a7tz1QCcWWkwC/rPJcPMJk/UNRu9CFhDd3OHYE5hddbJrs8BqRTalxI6GlKCWEGzRLHN+S/B7a4PAHCtm25aBQ==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-16.4.6.tgz",
|
||||
"integrity": "sha512-SunBjJ6t+oBtecS3dTjdVuMhUogP5wD/vrGL5EVuQYM1iS4O5ilL51HkiJ3sPjMzRHiCChvr4dbaSJbR7F3lxA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@next/eslint-plugin-next": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.3.tgz",
|
||||
"integrity": "sha512-oxuC06wt/71h6ACYCV9GbKOfnf5a7VlRe/p80YHTut15TNgDEmynDnaq8t/xhy5rlvk7dhItIPs6H3rvIM4kyw==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.4.6.tgz",
|
||||
"integrity": "sha512-HdqERVOafOD8JaUSAkwf9aSu/1rsHlkN8C5GcXYBH3C/z1MxBhZFxB5rz/xqMMRiIj7r9tIv8OCLQ9JWUxCvWA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -3007,9 +3026,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-arm64": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.3.tgz",
|
||||
"integrity": "sha512-4yq5EXBt+VDtAZwTyfijaFp5D2C5oz3Ikw5a2kiX2K9nw72vrZX2q5UuAlkPtUMO1tQz6JTKpaKWjS7OOefTDQ==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.4.6.tgz",
|
||||
"integrity": "sha512-kJ4VVZkley17xKaJx72QN2IBqjrj7zenCQZaUF0l9ShS/1Mt2kW4+Z5KGG6vgr3L/J562xTOizVyM1iA/u5nlg==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -3023,9 +3042,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-darwin-x64": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.3.tgz",
|
||||
"integrity": "sha512-1Rvkn/LUhnEF8WxnRkOrqGhbwXui1bkWFxONKIbN+r7C+9KHDSZ+iUoj4CzymVMWUyZIyx9szcb9+kbKhD500A==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.4.6.tgz",
|
||||
"integrity": "sha512-eIPGZIqC+8JKaeZmvnCANJQF4xWkkHqSnAAajtFxgwDMAOnCgxNvP52SeWZ41PyVwoe+Le/NQuZSaQ8j7YshSA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -3039,9 +3058,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.3.tgz",
|
||||
"integrity": "sha512-dCKpXErGg3abUM6t5JTJV/ottVBTStJB5lRJTbgdUdQaQ+jNHiK56Hsc0YAEg/rinSh42hYG3HWiYmEMdilnxg==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.4.6.tgz",
|
||||
"integrity": "sha512-9nI6O8vvczH2D9ZNdMGqb/3NuT15T9ksOZnAmx9/gjF2cOi74+xxyf1Hk96uIMfm14c9y6wHeBq6SH8g6udvcA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -3058,9 +3077,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-arm64-musl": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.3.tgz",
|
||||
"integrity": "sha512-WwYbhWkhYBvBtib1K4W0kL8MW2snBD2A5b3SN4vPpqalZbZs5+bQ1yzAdepVoOqrFfEW3dmREy4Zs1MrWcrFbw==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.4.6.tgz",
|
||||
"integrity": "sha512-7/qPhTxDp2ScluOJOhLuhWmlA17o1yZ0SIgpISBCpBxXgtnK4+KGywBpFkfLPiU1rnSM1faFGzYkH6i7JdTrqA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -3077,9 +3096,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-gnu": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.3.tgz",
|
||||
"integrity": "sha512-QymWvfUwDEC5/lpJOsxX5VAbyoR2D13+2Jsjz4be7gT4LPqEgdpkeLIR/HFfCLgKzoMhpJbp6I/JnogyNZHcaA==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.4.6.tgz",
|
||||
"integrity": "sha512-oOpbNa8XOW1qCGd9VvzC4fbkkRxEls7/WI6tz+YHC0xRA7KpV1U7DrAnCPjzVyOk/karzWEepCOcTIDmwK8FwQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -3096,9 +3115,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-linux-x64-musl": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.3.tgz",
|
||||
"integrity": "sha512-Vmjd9D7DpA4Vv3cUlr82QWgJD/BQZmns801vtC5VWHg6jCIA4a5vMKpQnfrM2pyCrp2eV0ENdUg4PlN3bAc2Yw==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.4.6.tgz",
|
||||
"integrity": "sha512-aM8CZ+OR2EwXaAYw7KGkW2GDmNDsLBIRe1MMRZCJPTdw/xhTD0IMUVO4sf3KqrzuRouGzwwLZn34+gFeVXiUQA==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -3115,9 +3134,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.3.tgz",
|
||||
"integrity": "sha512-lG1pPdPLk7gTyGb00n5JIMLdBJgjb+UEhSdZvFbhUMg0DyC6z4B7RnpSKF9VCd4imkLObVbXOFA0kFCpw7yFow==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.4.6.tgz",
|
||||
"integrity": "sha512-U0p7/tEtqvHX2crhd841CDwKtp5CFkKXVjOhmfccR3Pvp64sj8KBwRqsvltqLOwVBbj0NtkxwXSDpEHYGbxeXQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
@@ -3131,9 +3150,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@next/swc-win32-x64-msvc": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.3.tgz",
|
||||
"integrity": "sha512-NmQC9RkJdnPXRaMxtkCzobB3teVjqF33oSOnwDfi+XYGWWYpt+xlGK3mtktSKLbdjwaWbJu2OkkMiRFGUUncKg==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.4.6.tgz",
|
||||
"integrity": "sha512-3ZG15/5WIdlTQsIEvc9sPTTSL5XFrlLklIKmfF4fwsDnoAhu6NcBDXsk3mbGxNyo6aVLEGex+fHCv2MahY7a9g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
@@ -10867,13 +10886,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-config-next": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.3.tgz",
|
||||
"integrity": "sha512-j9IqBma6abp800frdUURaizYMgXOK+jNGyq6CsYcM9AxpSJs5D/TgMNGeAmRUilZvA7g9V1Tr71gNg9/SVTuMQ==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.4.6.tgz",
|
||||
"integrity": "sha512-IBGGrVf9E6pL0NGL0hmeicVGeSyv1VEzIWq6IecDqkw+YFByhEtDJS9u1r6s6a1VxK6rssh69KyNFQUgfaacqw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@next/eslint-plugin-next": "16.4.3",
|
||||
"@next/eslint-plugin-next": "16.4.6",
|
||||
"eslint-import-resolver-node": "^0.3.6",
|
||||
"eslint-import-resolver-typescript": "^3.5.2",
|
||||
"eslint-plugin-import": "^2.32.0",
|
||||
@@ -14838,12 +14857,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/next": {
|
||||
"version": "16.4.3",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.4.3.tgz",
|
||||
"integrity": "sha512-OqxKTGi9u80FydydsMNYNjnuje9Au+kvHlt2GZ//ftdpDHm1dxKqAaENoOOTX5wKzn+9vaKUNIfZeyZUuLhCnA==",
|
||||
"version": "16.4.6",
|
||||
"resolved": "https://registry.npmjs.org/next/-/next-16.4.6.tgz",
|
||||
"integrity": "sha512-QZJiYhaZLJMo2KpkQGQIwvmd79WVsAWeYIU554a8d7zArS3si/IRy3lBNV/rtYhE70oLwdLYhPAXLPx8HwcwtA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@next/env": "16.4.3",
|
||||
"@next/env": "16.4.6",
|
||||
"@swc/helpers": "0.5.23",
|
||||
"baseline-browser-mapping": "^2.9.19",
|
||||
"caniuse-lite": "^1.0.30001579",
|
||||
@@ -14857,14 +14876,14 @@
|
||||
"node": ">=20.9.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@next/swc-darwin-arm64": "16.4.3",
|
||||
"@next/swc-darwin-x64": "16.4.3",
|
||||
"@next/swc-linux-arm64-gnu": "16.4.3",
|
||||
"@next/swc-linux-arm64-musl": "16.4.3",
|
||||
"@next/swc-linux-x64-gnu": "16.4.3",
|
||||
"@next/swc-linux-x64-musl": "16.4.3",
|
||||
"@next/swc-win32-arm64-msvc": "16.4.3",
|
||||
"@next/swc-win32-x64-msvc": "16.4.3",
|
||||
"@next/swc-darwin-arm64": "16.4.6",
|
||||
"@next/swc-darwin-x64": "16.4.6",
|
||||
"@next/swc-linux-arm64-gnu": "16.4.6",
|
||||
"@next/swc-linux-arm64-musl": "16.4.6",
|
||||
"@next/swc-linux-x64-gnu": "16.4.6",
|
||||
"@next/swc-linux-x64-musl": "16.4.6",
|
||||
"@next/swc-win32-arm64-msvc": "16.4.6",
|
||||
"@next/swc-win32-x64-msvc": "16.4.6",
|
||||
"sharp": "^0.35.5"
|
||||
},
|
||||
"peerDependencies": {
|
||||
@@ -19633,7 +19652,7 @@
|
||||
},
|
||||
"packages/contracts": {
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.1.0",
|
||||
"version": "1.3.0",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"zod": "^4.6.7"
|
||||
|
||||
+3
-3
@@ -16,7 +16,7 @@
|
||||
"test:scripts": "bats scripts/tests",
|
||||
"typecheck": "npm run typecheck --workspaces --if-present",
|
||||
"lint": "eslint .",
|
||||
"lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh",
|
||||
"lint:scripts": "shellcheck -x scripts/crosscode scripts/products/events.sh scripts/lib/report.sh scripts/lib/env.sh scripts/lib/frpc.sh scripts/lib/manage.sh apps/agent/deploy/install.sh apps/agent/deploy/revert.sh",
|
||||
"check": "npm run lint && npm run lint:scripts && npm run typecheck && npm test && npm run test:scripts && npm run build"
|
||||
},
|
||||
"engines": {
|
||||
@@ -69,8 +69,8 @@
|
||||
"@radix-ui/react-toast": "1.2.23",
|
||||
"@radix-ui/react-tooltip": "1.2.16",
|
||||
"autoprefixer": "10.5.4",
|
||||
"eslint-config-next": "16.4.3",
|
||||
"next": "16.4.3",
|
||||
"eslint-config-next": "16.4.6",
|
||||
"next": "16.4.6",
|
||||
"postcss": "8.5.26",
|
||||
"react-hook-form": "7.86.0",
|
||||
"tailwind-merge": "3.6.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@crosscode/contracts",
|
||||
"version": "1.1.0",
|
||||
"version": "1.3.0",
|
||||
"description": "The shared JSON formats used by every Cross Code product: zod schemas, JSON Schema, TypeScript types and sample payloads",
|
||||
"license": "UNLICENSED",
|
||||
"type": "commonjs",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"schema": "crosscode.church-export/1",
|
||||
"exportedAt": "2026-11-20T12:00:00.000Z",
|
||||
"product": "events",
|
||||
"productVersion": "2.3.0",
|
||||
"church": { "name": "Grace Demo Church", "timezone": "Africa/Johannesburg" },
|
||||
"people": [
|
||||
{
|
||||
"ref": "p1",
|
||||
"name": "Thandi Example",
|
||||
"email": "thandi@example.org",
|
||||
"phone": "+27821234567",
|
||||
"role": "admin",
|
||||
"createdAt": "2026-01-10T08:00:00.000Z",
|
||||
"consent": { "email": true, "whatsapp": false, "privacyNoticeAcceptedAt": "2026-01-10T08:00:00.000Z" }
|
||||
}
|
||||
],
|
||||
"events": [
|
||||
{
|
||||
"ref": "e1",
|
||||
"title": "Youth Camp",
|
||||
"description": "A weekend away.",
|
||||
"startsAt": "2026-12-04T16:00:00.000Z",
|
||||
"endsAt": "2026-12-06T12:00:00.000Z",
|
||||
"location": "Camp Example",
|
||||
"sessions": [{ "label": "Friday", "startsAt": "2026-12-04T16:00:00.000Z", "endsAt": "2026-12-04T21:00:00.000Z" }],
|
||||
"ticketTypes": [{ "ref": "t1", "name": "Camper", "priceCents": 60000, "currency": "ZAR" }],
|
||||
"capacity": 80,
|
||||
"published": true
|
||||
}
|
||||
],
|
||||
"registrations": [
|
||||
{
|
||||
"ref": "r1",
|
||||
"eventRef": "e1",
|
||||
"personRef": "p1",
|
||||
"status": "confirmed",
|
||||
"createdAt": "2026-11-01T09:00:00.000Z",
|
||||
"attendees": [{ "name": "Thandi Example", "email": "thandi@example.org", "ticketTypeRef": "t1", "checkedInAt": null }],
|
||||
"answers": [{ "question": "Dietary needs", "answer": "None" }]
|
||||
}
|
||||
],
|
||||
"payments": [
|
||||
{ "registrationRef": "r1", "amountCents": 60000, "currency": "ZAR", "method": "card", "status": "paid", "paidAt": "2026-11-01T09:05:00.000Z", "reference": "YOCO-123" }
|
||||
],
|
||||
"checkIns": [],
|
||||
"rosters": [{ "eventRef": "e1", "role": "Kitchen", "personRef": "p1", "startsAt": null, "endsAt": null }],
|
||||
"settings": { "org_name": "Grace Demo Church" },
|
||||
"files": [{ "path": "uploads/events/camp.jpg", "bytes": 120400 }]
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-job-config.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"server": {
|
||||
"default": {},
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z][A-Z0-9_]*$"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"maxLength": 4000
|
||||
}
|
||||
},
|
||||
"defaults": {
|
||||
"default": {},
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z][A-Z0-9_]*$"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"maxLength": 4000
|
||||
}
|
||||
},
|
||||
"install": {
|
||||
"default": {},
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z][A-Z0-9_]*$"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"maxLength": 4000
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"additionalProperties": false
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,55 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-join-request.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agentApiVersion": {
|
||||
"type": "number",
|
||||
"const": 1
|
||||
},
|
||||
"token": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{32,128}$"
|
||||
},
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"church",
|
||||
"central"
|
||||
]
|
||||
},
|
||||
"hostname": {
|
||||
"type": "string",
|
||||
"maxLength": 253
|
||||
},
|
||||
"agentVersion": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"publicKeys": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ed25519": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{43}$"
|
||||
},
|
||||
"x25519": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{43}$"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ed25519",
|
||||
"x25519"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agentApiVersion",
|
||||
"token",
|
||||
"mode",
|
||||
"hostname",
|
||||
"agentVersion",
|
||||
"publicKeys"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-join-response.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"serverId": {
|
||||
"type": "string",
|
||||
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"hubJobKey": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z0-9_-]{43}$"
|
||||
},
|
||||
"pollSeconds": {
|
||||
"type": "integer",
|
||||
"minimum": 5,
|
||||
"maximum": 600
|
||||
},
|
||||
"statsSeconds": {
|
||||
"type": "integer",
|
||||
"minimum": 15,
|
||||
"maximum": 3600
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"serverId",
|
||||
"hubJobKey",
|
||||
"pollSeconds",
|
||||
"statsSeconds"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-poll-request.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agentApiVersion": {
|
||||
"type": "number",
|
||||
"const": 1
|
||||
},
|
||||
"agentVersion": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"mode": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"church",
|
||||
"central"
|
||||
]
|
||||
},
|
||||
"runningJobId": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agentApiVersion",
|
||||
"agentVersion",
|
||||
"mode",
|
||||
"runningJobId"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-poll-response.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"jobs": {
|
||||
"maxItems": 10,
|
||||
"type": "array",
|
||||
"items": {}
|
||||
},
|
||||
"pollSeconds": {
|
||||
"type": "integer",
|
||||
"minimum": 5,
|
||||
"maximum": 600
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"jobs",
|
||||
"pollSeconds"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-report.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.agent-report/1"
|
||||
},
|
||||
"jobId": {
|
||||
"type": "string",
|
||||
"pattern": "^job_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"serverId": {
|
||||
"type": "string",
|
||||
"pattern": "^srv_[A-Za-z0-9_-]{8,64}$"
|
||||
},
|
||||
"type": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"install",
|
||||
"add-product",
|
||||
"deploy",
|
||||
"adopt",
|
||||
"adopt-undo",
|
||||
"restart",
|
||||
"export",
|
||||
"uninstall",
|
||||
"purge",
|
||||
"update-agent",
|
||||
"check-ports",
|
||||
"status"
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"succeeded",
|
||||
"failed",
|
||||
"rolled-back",
|
||||
"refused",
|
||||
"expired"
|
||||
]
|
||||
},
|
||||
"startedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"finishedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"steps": {
|
||||
"maxItems": 200,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
"startedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"finishedAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"outcome": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ok",
|
||||
"failed",
|
||||
"skipped",
|
||||
"rolled-back"
|
||||
]
|
||||
},
|
||||
"detail": {
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"startedAt",
|
||||
"finishedAt",
|
||||
"outcome"
|
||||
]
|
||||
}
|
||||
},
|
||||
"result": {
|
||||
"default": {},
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string"
|
||||
},
|
||||
"additionalProperties": {}
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
},
|
||||
"log": {
|
||||
"maxItems": 200,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"maxLength": 1000
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"jobId",
|
||||
"serverId",
|
||||
"type",
|
||||
"status",
|
||||
"startedAt",
|
||||
"finishedAt",
|
||||
"steps",
|
||||
"log"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,296 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/agent-stats.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.agent-stats/1"
|
||||
},
|
||||
"at": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"ram": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"totalBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"usedBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"availableBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"swapTotalBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"swapUsedBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"totalBytes",
|
||||
"usedBytes",
|
||||
"availableBytes",
|
||||
"swapTotalBytes",
|
||||
"swapUsedBytes"
|
||||
]
|
||||
},
|
||||
"cpu": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"percent": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 100
|
||||
},
|
||||
"load1": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"load5": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"load15": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"cores": {
|
||||
"type": "integer",
|
||||
"exclusiveMinimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"percent",
|
||||
"load1",
|
||||
"load5",
|
||||
"load15",
|
||||
"cores"
|
||||
]
|
||||
},
|
||||
"disks": {
|
||||
"maxItems": 30,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"mount": {
|
||||
"type": "string",
|
||||
"maxLength": 255
|
||||
},
|
||||
"totalBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"usedBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"freeBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"mount",
|
||||
"totalBytes",
|
||||
"usedBytes",
|
||||
"freeBytes"
|
||||
]
|
||||
}
|
||||
},
|
||||
"uptimeSeconds": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"versions": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"os": {
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
"node": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"postgres": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"frpc": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"agent": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"os",
|
||||
"node",
|
||||
"postgres",
|
||||
"frpc",
|
||||
"agent"
|
||||
]
|
||||
},
|
||||
"frpcRunning": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"processes": {
|
||||
"maxItems": 200,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
"church": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9-]{1,30}$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"product": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"memoryBytes": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"cpuPercent": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
},
|
||||
"restarts": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"uptimeSeconds": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"church",
|
||||
"product",
|
||||
"status",
|
||||
"memoryBytes",
|
||||
"cpuPercent",
|
||||
"restarts",
|
||||
"uptimeSeconds"
|
||||
]
|
||||
}
|
||||
},
|
||||
"central": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"proxyBindAddr": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"allowPorts": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"frpsRunning": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"proxyBindAddr",
|
||||
"allowPorts",
|
||||
"frpsRunning"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"at",
|
||||
"ram",
|
||||
"cpu",
|
||||
"disks",
|
||||
"uptimeSeconds",
|
||||
"versions",
|
||||
"frpcRunning",
|
||||
"processes"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,676 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/church-export.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.church-export/1"
|
||||
},
|
||||
"exportedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"product": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
"productVersion": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"church": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
"timezone": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^[A-Za-z_]+(\\/[A-Za-z0-9_+-]+){0,2}$|^UTC$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"timezone"
|
||||
]
|
||||
},
|
||||
"people": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ref": {
|
||||
"type": "string",
|
||||
"pattern": "^p[0-9]+$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"phone": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"createdAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"consent": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"email": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"whatsapp": {
|
||||
"type": [
|
||||
"boolean",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"privacyNoticeAcceptedAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"email",
|
||||
"whatsapp",
|
||||
"privacyNoticeAcceptedAt"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ref",
|
||||
"name",
|
||||
"email",
|
||||
"phone",
|
||||
"role",
|
||||
"createdAt",
|
||||
"consent"
|
||||
]
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ref": {
|
||||
"type": "string",
|
||||
"pattern": "^e[0-9]+$"
|
||||
},
|
||||
"title": {
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
"description": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 20000
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"startsAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"endsAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"location": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"sessions": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"label": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"startsAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"endsAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"label",
|
||||
"startsAt",
|
||||
"endsAt"
|
||||
]
|
||||
}
|
||||
},
|
||||
"ticketTypes": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ref": {
|
||||
"type": "string",
|
||||
"pattern": "^t[0-9]+$"
|
||||
},
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
"priceCents": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"currency": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 3
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ref",
|
||||
"name",
|
||||
"priceCents",
|
||||
"currency"
|
||||
]
|
||||
}
|
||||
},
|
||||
"capacity": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"published": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ref",
|
||||
"title",
|
||||
"description",
|
||||
"startsAt",
|
||||
"endsAt",
|
||||
"location",
|
||||
"sessions",
|
||||
"ticketTypes",
|
||||
"capacity",
|
||||
"published"
|
||||
]
|
||||
}
|
||||
},
|
||||
"registrations": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"ref": {
|
||||
"type": "string",
|
||||
"pattern": "^r[0-9]+$"
|
||||
},
|
||||
"eventRef": {
|
||||
"type": "string",
|
||||
"pattern": "^e[0-9]+$"
|
||||
},
|
||||
"personRef": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^p[0-9]+$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"createdAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"attendees": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
"email": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 254
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"ticketTypeRef": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^t[0-9]+$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"checkedInAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"email",
|
||||
"ticketTypeRef",
|
||||
"checkedInAt"
|
||||
]
|
||||
}
|
||||
},
|
||||
"answers": {
|
||||
"default": [],
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"question": {
|
||||
"type": "string",
|
||||
"maxLength": 500
|
||||
},
|
||||
"answer": {
|
||||
"type": "string",
|
||||
"maxLength": 5000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"question",
|
||||
"answer"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"ref",
|
||||
"eventRef",
|
||||
"personRef",
|
||||
"status",
|
||||
"createdAt",
|
||||
"attendees"
|
||||
]
|
||||
}
|
||||
},
|
||||
"payments": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"registrationRef": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^r[0-9]+$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"amountCents": {
|
||||
"type": "integer",
|
||||
"minimum": -9007199254740991,
|
||||
"maximum": 9007199254740991
|
||||
},
|
||||
"currency": {
|
||||
"type": "string",
|
||||
"minLength": 3,
|
||||
"maxLength": 3
|
||||
},
|
||||
"method": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"status": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
},
|
||||
"paidAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"reference": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"registrationRef",
|
||||
"amountCents",
|
||||
"currency",
|
||||
"method",
|
||||
"status",
|
||||
"paidAt",
|
||||
"reference"
|
||||
]
|
||||
}
|
||||
},
|
||||
"checkIns": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"eventRef": {
|
||||
"type": "string",
|
||||
"pattern": "^e[0-9]+$"
|
||||
},
|
||||
"personRef": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^p[0-9]+$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"name": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"maxLength": 300
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"at": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"eventRef",
|
||||
"personRef",
|
||||
"name",
|
||||
"at"
|
||||
]
|
||||
}
|
||||
},
|
||||
"rosters": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"eventRef": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^e[0-9]+$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"role": {
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
"personRef": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"pattern": "^p[0-9]+$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"startsAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"endsAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"eventRef",
|
||||
"role",
|
||||
"personRef",
|
||||
"startsAt",
|
||||
"endsAt"
|
||||
]
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"maxLength": 100
|
||||
},
|
||||
"additionalProperties": {
|
||||
"type": "string",
|
||||
"maxLength": 5000
|
||||
}
|
||||
},
|
||||
"files": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"path": {
|
||||
"type": "string",
|
||||
"pattern": "^uploads\\/[A-Za-z0-9._/-]+$"
|
||||
},
|
||||
"bytes": {
|
||||
"type": "integer",
|
||||
"minimum": 0,
|
||||
"maximum": 9007199254740991
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"path",
|
||||
"bytes"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"exportedAt",
|
||||
"product",
|
||||
"productVersion",
|
||||
"church",
|
||||
"people",
|
||||
"events",
|
||||
"registrations",
|
||||
"payments",
|
||||
"checkIns",
|
||||
"rosters",
|
||||
"settings",
|
||||
"files"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/env-template.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.env-template/1"
|
||||
},
|
||||
"product": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"events",
|
||||
"website",
|
||||
"app",
|
||||
"accounts"
|
||||
]
|
||||
},
|
||||
"files": {
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z0-9._/-]+$"
|
||||
},
|
||||
"additionalProperties": {
|
||||
"minItems": 1,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"pattern": "^[A-Z][A-Z0-9_]*$"
|
||||
},
|
||||
"layer": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"server",
|
||||
"defaults",
|
||||
"install",
|
||||
"generated"
|
||||
]
|
||||
},
|
||||
"required": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"default": {
|
||||
"type": "string",
|
||||
"maxLength": 4000
|
||||
},
|
||||
"from": {
|
||||
"type": "string",
|
||||
"maxLength": 400
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"maxLength": 400
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"layer"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"schema",
|
||||
"product",
|
||||
"files"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
{
|
||||
"$id": "https://c-git.crosscode.co.za/joshua/crosscode-platform/raw/branch/main/packages/contracts/schemas/script-report.json",
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"succeeded",
|
||||
"failed",
|
||||
"rolled-back",
|
||||
"refused",
|
||||
"expired"
|
||||
]
|
||||
},
|
||||
"startedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"finishedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"steps": {
|
||||
"maxItems": 200,
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"name": {
|
||||
"type": "string",
|
||||
"maxLength": 200
|
||||
},
|
||||
"startedAt": {
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
"finishedAt": {
|
||||
"anyOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"format": "date-time",
|
||||
"pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z))$"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"outcome": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"ok",
|
||||
"failed",
|
||||
"skipped",
|
||||
"rolled-back"
|
||||
]
|
||||
},
|
||||
"detail": {
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"name",
|
||||
"startedAt",
|
||||
"finishedAt",
|
||||
"outcome"
|
||||
]
|
||||
}
|
||||
},
|
||||
"result": {
|
||||
"default": {},
|
||||
"type": "object",
|
||||
"propertyNames": {
|
||||
"type": "string"
|
||||
},
|
||||
"additionalProperties": {}
|
||||
},
|
||||
"message": {
|
||||
"type": "string",
|
||||
"maxLength": 2000
|
||||
},
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"const": "crosscode.script-report/1"
|
||||
},
|
||||
"command": {
|
||||
"type": "string",
|
||||
"maxLength": 40
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"status",
|
||||
"startedAt",
|
||||
"finishedAt",
|
||||
"steps",
|
||||
"schema",
|
||||
"command"
|
||||
]
|
||||
}
|
||||
@@ -41,6 +41,17 @@ function contracts(c) {
|
||||
"hub-ai-complete-response": c.hub.aiCompleteResponseSchema,
|
||||
"hub-error": c.hub.hubErrorSchema,
|
||||
"health": c.hub.healthSchema,
|
||||
"agent-job": c.agent.agentJobSchema,
|
||||
"agent-report": c.agent.agentReportSchema,
|
||||
"script-report": c.agent.scriptReportSchema,
|
||||
"agent-stats": c.agent.agentStatsSchema,
|
||||
"agent-join-request": c.agent.joinRequestSchema,
|
||||
"agent-join-response": c.agent.joinResponseSchema,
|
||||
"agent-poll-request": c.agent.pollRequestSchema,
|
||||
"agent-poll-response": c.agent.pollResponseSchema,
|
||||
"agent-job-config": c.agent.jobConfigSchema,
|
||||
"env-template": c.agent.envTemplateSchema,
|
||||
"church-export": c.churchExportSchema,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, productSchema } from "./common";
|
||||
|
||||
/**
|
||||
* The server agent (docs/AGENT-1.0-PLAN.md, ROADMAP-v3 phase 1d): what the Hub and the agent on
|
||||
* each server send each other. The agent only polls (it listens on nothing), runs only the
|
||||
* `crosscode` script, and only for jobs of the fixed types below, signed by the Hub.
|
||||
*
|
||||
* Signing and encryption (Node only) are in `@crosscode/contracts/signing`:
|
||||
* - jobs: Ed25519 by the Hub over `canonicalJson(job without "signature")`;
|
||||
* - agent → Hub requests: Ed25519 by the agent over `timestamp + "." + rawBody` ({@link AGENT_HEADERS});
|
||||
* - the job's `config`: sealed to the server's X25519 key (X25519 + HKDF-SHA256 + AES-256-GCM).
|
||||
*/
|
||||
|
||||
export const AGENT_API_VERSION = 1;
|
||||
|
||||
/** Headers on every agent → Hub request (after joining). */
|
||||
export const AGENT_HEADERS = {
|
||||
server: "x-crosscode-server",
|
||||
timestamp: "x-crosscode-timestamp",
|
||||
signature: "x-crosscode-signature",
|
||||
} as const;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Building blocks
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** A church's short name: folders, PM2 names, database names, tunnel names (`hope`, `cross-roads`). */
|
||||
export const shortNameSchema = z.string().regex(/^[a-z][a-z0-9-]{1,30}$/, "Expected a short name: a-z, 0-9 and -, starting with a letter");
|
||||
|
||||
/** A release tag, `<product>@x.y.z` (no prereleases: jobs only install releases). */
|
||||
export const releaseTagSchema = z.string().regex(/^(accounts|events|website|app)@\d+\.\d+\.\d+$/, "Expected <product>@x.y.z");
|
||||
|
||||
/** An agent release tag, `agent@x.y.z`. */
|
||||
export const agentTagSchema = z.string().regex(/^agent@\d+\.\d+\.\d+$/, "Expected agent@x.y.z");
|
||||
|
||||
/** A host name (no scheme, no path): `events.hope.co.za`. */
|
||||
export const domainSchema = z.string().max(253).regex(/^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,}$/, "Expected a domain like events.hope.co.za");
|
||||
|
||||
/** A TCP port the Hub hands out (frp tunnels use the same number on both ends). */
|
||||
export const portSchema = z.int().min(1024).max(65535);
|
||||
|
||||
/** An absolute path on the server without `..`, spaces or shell characters. */
|
||||
export const serverPathSchema = z.string().max(255).regex(/^\/(?!.*\/\.\.?(\/|$))[A-Za-z0-9._/-]+$/, "Expected an absolute path");
|
||||
|
||||
export const productPortsSchema = z.object({ web: portSchema, api: portSchema }).refine((p) => p.web !== p.api, "web and api must differ");
|
||||
export type ProductPorts = z.infer<typeof productPortsSchema>;
|
||||
|
||||
export const AGENT_MODES = ["church", "central"] as const;
|
||||
export const agentModeSchema = z.enum(AGENT_MODES);
|
||||
export type AgentMode = z.infer<typeof agentModeSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Jobs (crosscode.agent-job/1)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** Each job type and the arguments it takes. Unknown keys are refused, not stripped. */
|
||||
export const jobArgsSchemas = {
|
||||
/** `crosscode install <church> --products … --frp --json` */
|
||||
install: z.strictObject({
|
||||
church: shortNameSchema,
|
||||
products: z.array(productSchema).min(1).max(4),
|
||||
/** Per product: the release (default: the latest). */
|
||||
versions: z.partialRecord(productSchema, releaseTagSchema).optional(),
|
||||
/** Per product: where it's served. */
|
||||
domains: z.partialRecord(productSchema, domainSchema),
|
||||
/** Per product: the ports from the Hub's port list. */
|
||||
ports: z.partialRecord(productSchema, productPortsSchema),
|
||||
}),
|
||||
/** `crosscode add <church> <product>` (from phase 3). */
|
||||
"add-product": z.strictObject({ church: shortNameSchema, product: productSchema, version: releaseTagSchema.optional(), domain: domainSchema, ports: productPortsSchema }),
|
||||
/** `crosscode deploy <church> [products] [--version …] --json` */
|
||||
deploy: z.strictObject({
|
||||
church: shortNameSchema,
|
||||
products: z.array(productSchema).min(1).max(4),
|
||||
versions: z.array(releaseTagSchema).max(4).optional(),
|
||||
check: z.boolean().optional(),
|
||||
}),
|
||||
/** `crosscode adopt <church> --events-dir <dir> [--version …] [--address …] --json` */
|
||||
adopt: z.strictObject({ church: shortNameSchema, eventsDir: serverPathSchema, version: releaseTagSchema.optional(), address: domainSchema.optional() }),
|
||||
"adopt-undo": z.strictObject({ church: shortNameSchema }),
|
||||
/** `crosscode restart <church> [product] --json` (PM2 reload) */
|
||||
restart: z.strictObject({ church: shortNameSchema, product: productSchema.optional() }),
|
||||
/** `crosscode export <church> --out <zip> --json`; the agent encrypts the ZIP and uploads it under `exportId`. */
|
||||
export: z.strictObject({ church: shortNameSchema, exportId: z.string().regex(/^exp_[A-Za-z0-9_-]{8,64}$/) }),
|
||||
/** `crosscode uninstall <church> --json` */
|
||||
uninstall: z.strictObject({ church: shortNameSchema }),
|
||||
/** `crosscode purge <church> --json` (deletes what uninstall kept for 30 days) */
|
||||
purge: z.strictObject({ church: shortNameSchema }),
|
||||
/** The agent updates itself to that tag. */
|
||||
"update-agent": z.strictObject({ version: agentTagSchema }),
|
||||
/** Central server only: are these ports allowed, open and bound to 127.0.0.1? */
|
||||
"check-ports": z.strictObject({ ports: z.array(portSchema).min(1).max(50) }),
|
||||
/** `crosscode status [<church>] --json` */
|
||||
status: z.strictObject({ church: shortNameSchema.optional() }),
|
||||
} as const;
|
||||
|
||||
export type JobType = keyof typeof jobArgsSchemas;
|
||||
export const JOB_TYPES = Object.keys(jobArgsSchemas) as JobType[];
|
||||
export const jobTypeSchema = z.enum(JOB_TYPES as [JobType, ...JobType[]]);
|
||||
export type JobArgs<T extends JobType> = z.infer<(typeof jobArgsSchemas)[T]>;
|
||||
|
||||
/** The only jobs a central agent runs (§3). */
|
||||
export const CENTRAL_JOB_TYPES: readonly JobType[] = ["check-ports", "status", "update-agent"];
|
||||
|
||||
/** Time limits per job type, in minutes (§3). A job past it is stopped and reported as failed. */
|
||||
export const JOB_TIME_LIMIT_MINUTES: Record<JobType, number> = {
|
||||
install: 30, "add-product": 30, deploy: 20, adopt: 30, "adopt-undo": 15, restart: 5, export: 20,
|
||||
uninstall: 20, purge: 10, "update-agent": 15, "check-ports": 2, status: 3,
|
||||
};
|
||||
|
||||
/** Config sealed to the server's X25519 key (`sealConfig` in `@crosscode/contracts/signing`). */
|
||||
export const sealedSchema = z.strictObject({
|
||||
alg: z.literal("x25519-hkdf-sha256-aes-256-gcm"),
|
||||
/** The sender's one-time X25519 public key, base64url (raw 32 bytes). */
|
||||
epk: z.string().regex(/^[A-Za-z0-9_-]{43}$/),
|
||||
/** 12-byte nonce, base64url. */
|
||||
iv: z.string().regex(/^[A-Za-z0-9_-]{16}$/),
|
||||
/** Ciphertext with the 16-byte GCM tag appended, base64url. */
|
||||
ciphertext: z.string().regex(/^[A-Za-z0-9_-]+$/).max(200_000),
|
||||
});
|
||||
export type Sealed = z.infer<typeof sealedSchema>;
|
||||
|
||||
/**
|
||||
* What a job's sealed `config` holds once opened (§5): `.env` values by layer, each keyed by the
|
||||
* variable name. `generated` values are never sent: the server makes them.
|
||||
*/
|
||||
export const jobConfigSchema = z.strictObject({
|
||||
server: z.record(z.string().regex(/^[A-Z][A-Z0-9_]*$/), z.string().max(4000)).default({}),
|
||||
defaults: z.record(z.string().regex(/^[A-Z][A-Z0-9_]*$/), z.string().max(4000)).default({}),
|
||||
/** Per product: the install's own values (URLs, timezone, licence key, PORT). */
|
||||
install: z.partialRecord(productSchema, z.record(z.string().regex(/^[A-Z][A-Z0-9_]*$/), z.string().max(4000))).default({}),
|
||||
});
|
||||
export type JobConfig = z.infer<typeof jobConfigSchema>;
|
||||
|
||||
const jobBase = {
|
||||
schema: z.literal("crosscode.agent-job/1"),
|
||||
id: z.string().regex(/^job_[A-Za-z0-9_-]{8,64}$/),
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
config: sealedSchema.nullable().optional(),
|
||||
notBefore: dateTimeSchema,
|
||||
expiresAt: dateTimeSchema,
|
||||
/** Ed25519 over `canonicalJson(job without "signature")`, base64url. */
|
||||
signature: z.string().regex(/^[A-Za-z0-9_-]{86}$/),
|
||||
};
|
||||
|
||||
function jobOf<T extends JobType>(type: T) {
|
||||
return z.strictObject({ ...jobBase, type: z.literal(type), args: jobArgsSchemas[type] });
|
||||
}
|
||||
|
||||
export const agentJobSchema = z.discriminatedUnion("type", [
|
||||
jobOf("install"), jobOf("add-product"), jobOf("deploy"), jobOf("adopt"), jobOf("adopt-undo"), jobOf("restart"),
|
||||
jobOf("export"), jobOf("uninstall"), jobOf("purge"), jobOf("update-agent"), jobOf("check-ports"), jobOf("status"),
|
||||
]);
|
||||
export type AgentJob = z.infer<typeof agentJobSchema>;
|
||||
export type UnsignedAgentJob = Omit<AgentJob, "signature">;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Reports (crosscode.agent-report/1)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
export const JOB_STATUSES = ["succeeded", "failed", "rolled-back", "refused", "expired"] as const;
|
||||
export const jobStatusSchema = z.enum(JOB_STATUSES);
|
||||
export type JobStatus = z.infer<typeof jobStatusSchema>;
|
||||
|
||||
export const reportStepSchema = z.object({
|
||||
name: z.string().max(200),
|
||||
startedAt: dateTimeSchema,
|
||||
finishedAt: dateTimeSchema.nullable(),
|
||||
outcome: z.enum(["ok", "failed", "skipped", "rolled-back"]),
|
||||
detail: z.string().max(2000).optional(),
|
||||
});
|
||||
export type ReportStep = z.infer<typeof reportStepSchema>;
|
||||
|
||||
/**
|
||||
* A job's result. The `crosscode … --json` output is the report without `jobId`, `serverId` and
|
||||
* `log`; the agent adds those (the log's last 200 lines, filtered for secrets) and signs the request.
|
||||
*/
|
||||
export const agentReportSchema = z.object({
|
||||
schema: z.literal("crosscode.agent-report/1"),
|
||||
jobId: z.string().regex(/^job_[A-Za-z0-9_-]{8,64}$/),
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
type: jobTypeSchema,
|
||||
status: jobStatusSchema,
|
||||
startedAt: dateTimeSchema,
|
||||
finishedAt: dateTimeSchema,
|
||||
steps: z.array(reportStepSchema).max(200),
|
||||
/** What the command found or did, by type (versions, ports, the export's size …). */
|
||||
result: z.record(z.string(), z.unknown()).default({}),
|
||||
/** Why a job was refused or failed, in a sentence. */
|
||||
message: z.string().max(2000).optional(),
|
||||
log: z.array(z.string().max(1000)).max(200),
|
||||
});
|
||||
export type AgentReport = z.infer<typeof agentReportSchema>;
|
||||
|
||||
/** What `crosscode … --json` prints: the report's own part. */
|
||||
export const scriptReportSchema = agentReportSchema.omit({ schema: true, jobId: true, serverId: true, type: true, log: true }).extend({
|
||||
schema: z.literal("crosscode.script-report/1"),
|
||||
command: z.string().max(40),
|
||||
});
|
||||
export type ScriptReport = z.infer<typeof scriptReportSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Stats (crosscode.agent-stats/1), every 60 s
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const bytes = z.number().nonnegative();
|
||||
|
||||
export const processStatSchema = z.object({
|
||||
name: z.string().max(100),
|
||||
church: shortNameSchema.nullable(),
|
||||
product: productSchema.nullable(),
|
||||
status: z.string().max(40),
|
||||
memoryBytes: bytes,
|
||||
cpuPercent: z.number().nonnegative(),
|
||||
restarts: z.int().nonnegative(),
|
||||
uptimeSeconds: z.number().nonnegative(),
|
||||
});
|
||||
|
||||
export const centralStatSchema = z.object({
|
||||
/** `proxy_bind_addr` in frps.ini, null when it isn't set (tunnels then open on every address). */
|
||||
proxyBindAddr: z.string().max(100).nullable(),
|
||||
/** `allow_ports` in frps.ini as written, e.g. `20000-29999`. */
|
||||
allowPorts: z.string().max(2000).nullable(),
|
||||
frpsRunning: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
export const agentStatsSchema = z.object({
|
||||
schema: z.literal("crosscode.agent-stats/1"),
|
||||
at: dateTimeSchema,
|
||||
ram: z.object({ totalBytes: bytes, usedBytes: bytes, availableBytes: bytes, swapTotalBytes: bytes, swapUsedBytes: bytes }),
|
||||
cpu: z.object({ percent: z.number().min(0).max(100), load1: z.number().nonnegative(), load5: z.number().nonnegative(), load15: z.number().nonnegative(), cores: z.int().positive() }),
|
||||
disks: z.array(z.object({ mount: z.string().max(255), totalBytes: bytes, usedBytes: bytes, freeBytes: bytes })).max(30),
|
||||
uptimeSeconds: z.number().nonnegative(),
|
||||
versions: z.object({ os: z.string().max(200), node: z.string().max(40), postgres: z.string().max(40).nullable(), frpc: z.string().max(40).nullable(), agent: z.string().max(40) }),
|
||||
frpcRunning: z.boolean().nullable(),
|
||||
processes: z.array(processStatSchema).max(200),
|
||||
central: centralStatSchema.nullable().optional(),
|
||||
});
|
||||
export type AgentStats = z.infer<typeof agentStatsSchema>;
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Agent API (/api/agent/v1/*)
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const base64urlKey = z.string().regex(/^[A-Za-z0-9_-]{43}$/, "Expected a raw 32-byte key, base64url");
|
||||
|
||||
/** POST /api/agent/v1/join (unsigned: the one-time token is the proof). */
|
||||
export const joinRequestSchema = z.object({
|
||||
agentApiVersion: z.literal(AGENT_API_VERSION),
|
||||
token: z.string().regex(/^[A-Za-z0-9_-]{32,128}$/),
|
||||
mode: agentModeSchema,
|
||||
hostname: z.string().max(253),
|
||||
agentVersion: z.string().max(40),
|
||||
/** The agent's Ed25519 key (signs its requests) and X25519 key (receives config). */
|
||||
publicKeys: z.object({ ed25519: base64urlKey, x25519: base64urlKey }),
|
||||
});
|
||||
export const joinResponseSchema = z.object({
|
||||
serverId: z.string().regex(/^srv_[A-Za-z0-9_-]{8,64}$/),
|
||||
/** The Hub's job-signing Ed25519 key, pinned by the agent. */
|
||||
hubJobKey: base64urlKey,
|
||||
pollSeconds: z.int().min(5).max(600),
|
||||
statsSeconds: z.int().min(15).max(3600),
|
||||
});
|
||||
|
||||
/** POST /api/agent/v1/poll (signed). */
|
||||
export const pollRequestSchema = z.object({
|
||||
agentApiVersion: z.literal(AGENT_API_VERSION),
|
||||
agentVersion: z.string().max(40),
|
||||
mode: agentModeSchema,
|
||||
/** The job being run now, if any (the Hub won't hand out another). */
|
||||
runningJobId: z.string().regex(/^job_[A-Za-z0-9_-]{8,64}$/).nullable(),
|
||||
});
|
||||
export const pollResponseSchema = z.object({
|
||||
jobs: z.array(z.unknown()).max(10), // each checked with agentJobSchema and the signature by the agent
|
||||
pollSeconds: z.int().min(5).max(600),
|
||||
});
|
||||
|
||||
/** POST /api/agent/v1/stats (signed): an {@link agentStatsSchema} body. → 204 */
|
||||
/** POST /api/agent/v1/report (signed): an {@link agentReportSchema} body. → 204 */
|
||||
/** PUT /api/agent/v1/exports/:exportId (signed): the encrypted ZIP, `application/octet-stream`. → 204 */
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Env template (crosscode.env-template/1): apps/<product>/env.template.json
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
export const ENV_LAYERS = ["server", "defaults", "install", "generated"] as const;
|
||||
export const envLayerSchema = z.enum(ENV_LAYERS);
|
||||
|
||||
export const envVariableSchema = z.object({
|
||||
name: z.string().regex(/^[A-Z][A-Z0-9_]*$/),
|
||||
layer: envLayerSchema,
|
||||
required: z.boolean().default(false),
|
||||
/** Used when no layer gives a value. */
|
||||
default: z.string().max(4000).optional(),
|
||||
/** Built from the install's values: `https://{domain}`, `{apiPort}`. */
|
||||
from: z.string().max(400).optional(),
|
||||
description: z.string().max(400).optional(),
|
||||
});
|
||||
export type EnvVariable = z.infer<typeof envVariableSchema>;
|
||||
|
||||
export const envTemplateSchema = z.object({
|
||||
schema: z.literal("crosscode.env-template/1"),
|
||||
product: productSchema,
|
||||
/** Relative to the product's folder (`apps/<product>`): `backend/.env`, `frontend/.env.production`. */
|
||||
files: z.record(z.string().regex(/^[a-z0-9._/-]+$/), z.array(envVariableSchema).min(1)),
|
||||
});
|
||||
export type EnvTemplate = z.infer<typeof envTemplateSchema>;
|
||||
|
||||
/** The variables a layer must provide for a template, that it doesn't (the Hub's check before a job). */
|
||||
export function missingRequired(template: EnvTemplate, layer: "server" | "defaults", values: Record<string, string | undefined>): string[] {
|
||||
const missing: string[] = [];
|
||||
for (const vars of Object.values(template.files)) {
|
||||
for (const v of vars) {
|
||||
if (v.layer !== layer || !v.required || v.default !== undefined) continue;
|
||||
if (!values[v.name] || !String(values[v.name]).trim()) missing.push(v.name);
|
||||
}
|
||||
}
|
||||
return [...new Set(missing)];
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
/**
|
||||
* Canonical JSON for signatures: object keys sorted (by UTF-16 code units, as JavaScript sorts),
|
||||
* no whitespace, `undefined` properties left out. Arrays keep their order. Only plain JSON values
|
||||
* (no Dates, Maps or functions: convert them first).
|
||||
*/
|
||||
export function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value === "boolean" || typeof value === "string") return JSON.stringify(value);
|
||||
if (typeof value === "number") {
|
||||
if (!Number.isFinite(value)) throw new Error("canonicalJson: numbers must be finite");
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (Array.isArray(value)) return `[${value.map((v) => (v === undefined ? "null" : canonicalJson(v))).join(",")}]`;
|
||||
if (typeof value === "object") {
|
||||
const proto = Object.getPrototypeOf(value) as unknown;
|
||||
if (proto !== Object.prototype && proto !== null) throw new Error("canonicalJson: only plain objects");
|
||||
const obj = value as Record<string, unknown>;
|
||||
const entries = Object.keys(obj)
|
||||
.filter((k) => obj[k] !== undefined)
|
||||
.sort()
|
||||
.map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`);
|
||||
return `{${entries.join(",")}}`;
|
||||
}
|
||||
throw new Error(`canonicalJson: can't encode a ${typeof value}`);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { z } from "zod";
|
||||
import { dateTimeSchema, productSchema, timezoneSchema } from "./common";
|
||||
|
||||
/**
|
||||
* crosscode.church-export/1: a church's data when it leaves (docs/AGENT-1.0-PLAN.md §9). Written
|
||||
* for people, in plain terms with our own field names: no database tables, Prisma models or
|
||||
* internal ids. Records point at each other with references made for the export (`p12`, `e3`,
|
||||
* `r40`), which mean nothing outside the file.
|
||||
*
|
||||
* Shipped as a ZIP: `export.json` (this), `uploads/` (the files in `files`) and `README.txt`.
|
||||
*/
|
||||
|
||||
const ref = (prefix: string) => z.string().regex(new RegExp(`^${prefix}[0-9]+$`));
|
||||
const text = (max = 20000) => z.string().max(max);
|
||||
const when = dateTimeSchema.nullable();
|
||||
const cents = z.int();
|
||||
|
||||
export const exportPersonSchema = z.object({
|
||||
ref: ref("p"),
|
||||
name: text(300),
|
||||
email: text(254).nullable(),
|
||||
phone: text(40).nullable(),
|
||||
role: text(40),
|
||||
createdAt: when,
|
||||
consent: z.object({ email: z.boolean().nullable(), whatsapp: z.boolean().nullable(), privacyNoticeAcceptedAt: when }),
|
||||
});
|
||||
|
||||
export const exportEventSchema = z.object({
|
||||
ref: ref("e"),
|
||||
title: text(500),
|
||||
description: text().nullable(),
|
||||
startsAt: when,
|
||||
endsAt: when,
|
||||
location: text(500).nullable(),
|
||||
sessions: z.array(z.object({ label: text(300).nullable(), startsAt: when, endsAt: when })),
|
||||
ticketTypes: z.array(z.object({ ref: ref("t"), name: text(300), priceCents: cents, currency: z.string().length(3) })),
|
||||
capacity: z.int().nullable(),
|
||||
published: z.boolean(),
|
||||
});
|
||||
|
||||
export const exportRegistrationSchema = z.object({
|
||||
ref: ref("r"),
|
||||
eventRef: ref("e"),
|
||||
personRef: ref("p").nullable(),
|
||||
status: text(40),
|
||||
createdAt: when,
|
||||
attendees: z.array(z.object({ name: text(300), email: text(254).nullable(), ticketTypeRef: ref("t").nullable(), checkedInAt: when })),
|
||||
answers: z.array(z.object({ question: text(500), answer: text(5000) })).default([]),
|
||||
});
|
||||
|
||||
export const exportPaymentSchema = z.object({
|
||||
registrationRef: ref("r").nullable(),
|
||||
amountCents: cents,
|
||||
currency: z.string().length(3),
|
||||
method: text(40),
|
||||
status: text(40),
|
||||
paidAt: when,
|
||||
reference: text(200).nullable(),
|
||||
});
|
||||
|
||||
export const exportCheckInSchema = z.object({ eventRef: ref("e"), personRef: ref("p").nullable(), name: text(300).nullable(), at: when });
|
||||
|
||||
export const exportRosterSchema = z.object({ eventRef: ref("e").nullable(), role: text(200), personRef: ref("p").nullable(), startsAt: when, endsAt: when });
|
||||
|
||||
export const churchExportSchema = z.object({
|
||||
schema: z.literal("crosscode.church-export/1"),
|
||||
exportedAt: dateTimeSchema,
|
||||
product: productSchema,
|
||||
productVersion: z.string().max(40),
|
||||
church: z.object({ name: text(300), timezone: timezoneSchema.nullable() }),
|
||||
people: z.array(exportPersonSchema),
|
||||
events: z.array(exportEventSchema),
|
||||
registrations: z.array(exportRegistrationSchema),
|
||||
payments: z.array(exportPaymentSchema),
|
||||
checkIns: z.array(exportCheckInSchema),
|
||||
rosters: z.array(exportRosterSchema),
|
||||
/** The site's own settings that matter to a church (name, contact, branding), never secrets. */
|
||||
settings: z.record(z.string().max(100), z.string().max(5000)),
|
||||
/** Uploaded files in the ZIP's `uploads/` folder. */
|
||||
files: z.array(z.object({ path: z.string().regex(/^uploads\/[A-Za-z0-9._/-]+$/), bytes: z.int().nonnegative() })),
|
||||
});
|
||||
export type ChurchExport = z.infer<typeof churchExportSchema>;
|
||||
|
||||
/** Keys that look like internal ids anywhere in an export (the export test fails on any). */
|
||||
export const INTERNAL_ID_KEYS = /^(id|.*Id|uuid|_id)$/;
|
||||
@@ -9,3 +9,6 @@ export * from "./church";
|
||||
export * from "./identity";
|
||||
export * from "./return-to";
|
||||
export * as hub from "./hub";
|
||||
export * as agent from "./agent";
|
||||
export * from "./church-export";
|
||||
export { canonicalJson } from "./canonical";
|
||||
|
||||
@@ -1,4 +1,22 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
import {
|
||||
createCipheriv,
|
||||
createDecipheriv,
|
||||
createHmac,
|
||||
createPrivateKey,
|
||||
createPublicKey,
|
||||
diffieHellman,
|
||||
generateKeyPairSync,
|
||||
hkdfSync,
|
||||
randomBytes,
|
||||
sign as edSign,
|
||||
timingSafeEqual,
|
||||
verify as edVerify,
|
||||
type KeyObject,
|
||||
} from "node:crypto";
|
||||
import { AGENT_HEADERS, type Sealed } from "./agent";
|
||||
import { canonicalJson } from "./canonical";
|
||||
|
||||
export { canonicalJson } from "./canonical";
|
||||
|
||||
/**
|
||||
* Signed requests between Cross Code installs (Node only: `@crosscode/contracts/signing`).
|
||||
@@ -74,3 +92,145 @@ export function verify(opts: { secret: string; timestamp: unknown; signature: un
|
||||
const given = Buffer.from(signature, "hex");
|
||||
return timingSafeEqual(expected, given) ? { ok: true } : { ok: false, code: "BAD_SIGNATURE" };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Server agent (docs/AGENT-1.0-PLAN.md §3–4): Ed25519 signatures, sealed config, export files.
|
||||
// Keys travel as raw 32-byte base64url strings; private keys stay on their machine as PKCS#8 PEM.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const b64u = (buf: Uint8Array): string => Buffer.from(buf).toString("base64url");
|
||||
const unb64u = (s: string): Buffer => Buffer.from(s, "base64url");
|
||||
const bytesOf = (data: RawBody): Buffer => (typeof data === "string" ? Buffer.from(data) : Buffer.from(data));
|
||||
|
||||
export interface KeyPair {
|
||||
/** Raw 32-byte public key, base64url. */
|
||||
publicKey: string;
|
||||
/** PKCS#8 PEM. Never leaves the machine that made it. */
|
||||
privateKeyPem: string;
|
||||
}
|
||||
|
||||
function rawPublic(key: KeyObject): string {
|
||||
const jwk = key.export({ format: "jwk" });
|
||||
if (!jwk.x) throw new Error("Not an OKP key");
|
||||
return jwk.x;
|
||||
}
|
||||
|
||||
export function generateEd25519(): KeyPair {
|
||||
const { publicKey, privateKey } = generateKeyPairSync("ed25519");
|
||||
return { publicKey: rawPublic(publicKey), privateKeyPem: privateKey.export({ format: "pem", type: "pkcs8" }).toString() };
|
||||
}
|
||||
|
||||
export function generateX25519(): KeyPair {
|
||||
const { publicKey, privateKey } = generateKeyPairSync("x25519");
|
||||
return { publicKey: rawPublic(publicKey), privateKeyPem: privateKey.export({ format: "pem", type: "pkcs8" }).toString() };
|
||||
}
|
||||
|
||||
/** The raw public key of a PKCS#8 private key (to check a configured key pair matches). */
|
||||
export function publicKeyOf(privateKeyPem: string): string {
|
||||
return rawPublic(createPublicKey(createPrivateKey(privateKeyPem)));
|
||||
}
|
||||
|
||||
const okpPublic = (crv: "Ed25519" | "X25519", x: string): KeyObject => createPublicKey({ key: { kty: "OKP", crv, x }, format: "jwk" });
|
||||
|
||||
/** Ed25519 signature of some bytes, base64url (86 characters). */
|
||||
export function ed25519Sign(privateKeyPem: string, data: RawBody): string {
|
||||
return b64u(edSign(null, bytesOf(data), createPrivateKey(privateKeyPem)));
|
||||
}
|
||||
|
||||
export function ed25519Verify(publicKey: string, data: RawBody, signature: unknown): boolean {
|
||||
if (typeof signature !== "string" || !/^[A-Za-z0-9_-]{86}$/.test(signature)) return false;
|
||||
try {
|
||||
return edVerify(null, bytesOf(data), okpPublic("Ed25519", publicKey), unb64u(signature));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The bytes a job's signature covers: the job without `signature`, as canonical JSON. */
|
||||
export function jobSigningInput(job: Record<string, unknown>): string {
|
||||
const rest = { ...job };
|
||||
delete rest.signature;
|
||||
return canonicalJson(rest);
|
||||
}
|
||||
|
||||
/** The Hub signs a job (with its job-signing key, not the licence key). */
|
||||
export function signJob<T extends Record<string, unknown>>(job: T, hubPrivateKeyPem: string): T & { signature: string } {
|
||||
return { ...job, signature: ed25519Sign(hubPrivateKeyPem, jobSigningInput(job)) };
|
||||
}
|
||||
|
||||
/** The agent checks a job against the Hub key it pinned when it joined. */
|
||||
export function verifyJob(job: Record<string, unknown>, hubPublicKey: string): boolean {
|
||||
return ed25519Verify(hubPublicKey, jobSigningInput(job), job.signature);
|
||||
}
|
||||
|
||||
/** Headers for an agent → Hub request. `now` is for tests. */
|
||||
export function signAgentRequest(opts: { serverId: string; privateKeyPem: string; rawBody: RawBody; now?: Date }): Record<string, string> {
|
||||
const timestamp = (opts.now ?? new Date()).toISOString();
|
||||
return {
|
||||
[AGENT_HEADERS.server]: opts.serverId,
|
||||
[AGENT_HEADERS.timestamp]: timestamp,
|
||||
[AGENT_HEADERS.signature]: ed25519Sign(opts.privateKeyPem, Buffer.concat([Buffer.from(`${timestamp}.`), bytesOf(opts.rawBody)])),
|
||||
};
|
||||
}
|
||||
|
||||
/** The Hub checks an agent request against the key the server joined with. */
|
||||
export function verifyAgentRequest(opts: { publicKey: string; timestamp: unknown; signature: unknown; rawBody: RawBody; now?: Date; maxSkewMs?: number }): VerifyResult {
|
||||
if (typeof opts.timestamp !== "string") return { ok: false, code: "BAD_SIGNATURE" };
|
||||
const sentAt = Date.parse(opts.timestamp);
|
||||
const now = (opts.now ?? new Date()).getTime();
|
||||
if (!Number.isFinite(sentAt) || Math.abs(now - sentAt) > (opts.maxSkewMs ?? MAX_CLOCK_SKEW_MS)) return { ok: false, code: "STALE_REQUEST" };
|
||||
return ed25519Verify(opts.publicKey, Buffer.concat([Buffer.from(`${opts.timestamp}.`), bytesOf(opts.rawBody)]), opts.signature)
|
||||
? { ok: true }
|
||||
: { ok: false, code: "BAD_SIGNATURE" };
|
||||
}
|
||||
|
||||
const SEAL_INFO = Buffer.from("crosscode.agent-config/1");
|
||||
|
||||
function sealKey(shared: Buffer, epk: string, recipient: string): Buffer {
|
||||
return Buffer.from(hkdfSync("sha256", shared, Buffer.concat([unb64u(epk), unb64u(recipient)]), SEAL_INFO, 32));
|
||||
}
|
||||
|
||||
/** Seal a JSON value to a server's X25519 key: only that server can open it. */
|
||||
export function sealConfig(value: unknown, recipientX25519: string): Sealed {
|
||||
const eph = generateKeyPairSync("x25519");
|
||||
const epk = rawPublic(eph.publicKey);
|
||||
const shared = diffieHellman({ privateKey: eph.privateKey, publicKey: okpPublic("X25519", recipientX25519) });
|
||||
const key = sealKey(shared, epk, recipientX25519);
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
const data = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final(), cipher.getAuthTag()]);
|
||||
return { alg: "x25519-hkdf-sha256-aes-256-gcm", epk, iv: b64u(iv), ciphertext: b64u(data) };
|
||||
}
|
||||
|
||||
/** Open a sealed value with the server's X25519 private key. Throws if it was changed or isn't for this key. */
|
||||
export function openConfig(sealed: Sealed, x25519PrivateKeyPem: string): unknown {
|
||||
const priv = createPrivateKey(x25519PrivateKeyPem);
|
||||
const recipient = rawPublic(createPublicKey(priv));
|
||||
const shared = diffieHellman({ privateKey: priv, publicKey: okpPublic("X25519", sealed.epk) });
|
||||
const key = sealKey(shared, sealed.epk, recipient);
|
||||
const data = unb64u(sealed.ciphertext);
|
||||
if (data.length < 17) throw new Error("Sealed data is too short");
|
||||
const decipher = createDecipheriv("aes-256-gcm", key, unb64u(sealed.iv));
|
||||
decipher.setAuthTag(data.subarray(data.length - 16));
|
||||
const plain = Buffer.concat([decipher.update(data.subarray(0, data.length - 16)), decipher.final()]);
|
||||
return JSON.parse(plain.toString("utf8")) as unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* An export ZIP encrypted with a fresh random key (§9): `iv (12) ‖ ciphertext ‖ tag (16)`,
|
||||
* AES-256-GCM, which the browser decrypts with WebCrypto. The key only goes in the link's `#…`.
|
||||
*/
|
||||
export function encryptExport(zip: Uint8Array): { key: string; file: Buffer } {
|
||||
const key = randomBytes(32);
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
const file = Buffer.concat([iv, cipher.update(zip), cipher.final(), cipher.getAuthTag()]);
|
||||
return { key: b64u(key), file };
|
||||
}
|
||||
|
||||
export function decryptExport(file: Uint8Array, key: string): Buffer {
|
||||
const buf = Buffer.from(file);
|
||||
const decipher = createDecipheriv("aes-256-gcm", unb64u(key), buf.subarray(0, 12));
|
||||
decipher.setAuthTag(buf.subarray(buf.length - 16));
|
||||
return Buffer.concat([decipher.update(buf.subarray(12, buf.length - 16)), decipher.final()]);
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user