Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
78dd903b2d | ||
|
|
716d47242a | ||
|
|
8a930d07c6 | ||
|
|
390b80e56e | ||
|
|
4952e2cb0f | ||
|
|
9d585c94aa | ||
|
|
0cc72aaaad | ||
|
|
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 | ||
|
|
38ebce24ab | ||
|
|
e8853cf0c8 | ||
|
|
c442fe0d42 | ||
|
|
f174285711 |
@@ -25,3 +25,4 @@ npm-debug.log*
|
|||||||
# OS
|
# OS
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
temp/
|
||||||
|
|||||||
+88
-1
@@ -2,7 +2,94 @@
|
|||||||
|
|
||||||
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …).
|
||||||
|
|
||||||
## Unreleased
|
## events@2.4.0, contracts@1.4.0 - unreleased
|
||||||
|
|
||||||
|
Phase 2 (docs/EVENTS-2.4-PLAN.md): protocol v2, Linked products, the event feed and
|
||||||
|
`packages/seo`. With Hub 2.2.0 (events-hub). Not tagged yet: the e2e run and the VM test come first.
|
||||||
|
|
||||||
|
### Events (2.4.0)
|
||||||
|
|
||||||
|
- Protocol v2 with the site's own Ed25519 key, Settings → Linked products with Connect, the public
|
||||||
|
event feed (`/api/feed/v1/events`) and `event.changed`, and events from linked products on the
|
||||||
|
public pages. Details in `apps/events/CHANGELOG.md`.
|
||||||
|
|
||||||
|
### Contracts (1.4.0)
|
||||||
|
|
||||||
|
- `crosscode.link/1` (`link.connect`, `link.connected`, `link.disconnect`) with `signLink` /
|
||||||
|
`verifyLink`, PEM helpers, link secrets and nonces; `LINK_PATHS`, `FEED_PATHS`.
|
||||||
|
- The v2 heartbeat can carry `publicKey`; the reply's `publicKeyStatus` (`saved` / `matches` /
|
||||||
|
`mismatch`).
|
||||||
|
- `typesVersions` for `@crosscode/contracts/signing` (older `moduleResolution`).
|
||||||
|
|
||||||
|
### packages/seo (new)
|
||||||
|
|
||||||
|
- `eventJsonLd`, `churchJsonLd`, `canonicalUrl`, `pageMeta`, `jsonLdString` (ROADMAP-v3 §11).
|
||||||
|
|
||||||
|
### Scripts
|
||||||
|
|
||||||
|
- `crosscode` (Events): installs and builds the shared packages Events uses before it.
|
||||||
|
|
||||||
|
## 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
|
||||||
|
|
||||||
|
- AI status (Hub protocol §3b): optional `usedInputTokens`, `usedOutputTokens`, `capInputTokens`,
|
||||||
|
`capOutputTokens` (Hub 2.0.1). Churches see tokens; the cents stay for the Hub and older installs.
|
||||||
|
|
||||||
### Docs
|
### Docs
|
||||||
|
|
||||||
|
|||||||
@@ -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" },
|
||||||
|
});
|
||||||
+108
-2
@@ -5,7 +5,113 @@ 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/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||||
and this project follows [Semantic Versioning](https://semver.org/).
|
and this project follows [Semantic Versioning](https://semver.org/).
|
||||||
|
|
||||||
## [Unreleased]
|
## [2.4.0] - unreleased
|
||||||
|
|
||||||
|
Protocol v2, Linked products, the event feed and `packages/seo` (ROADMAP-v3 phase 2,
|
||||||
|
docs/EVENTS-2.4-PLAN.md). Needs Hub 2.2.0 for the move to protocol v2 (against an older Hub it keeps
|
||||||
|
working on v1 and Linked products stays empty). contracts 1.4.0.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **Protocol v2** (`src/hub/client.js`): register and heartbeat send `product: "events"`; the site
|
||||||
|
makes an Ed25519 key pair once (`src/links/store.ts`, `hub_private_key` encrypted) and sends its
|
||||||
|
public key on the heartbeat until the Hub answers `publicKeyStatus: saved | matches`. Installs
|
||||||
|
registered with v1 move over without their licence key. The reply's `linkedProducts` is cached
|
||||||
|
(`hub_linked_products`). A Hub that refuses a v2 body gets the same heartbeat as v1, and v1 is
|
||||||
|
used for a day (`hub_v1_until`), so the licence always refreshes. Update requests and AI calls
|
||||||
|
stay v1.
|
||||||
|
- **Linked products** (Site settings → Linked products; `/api/v2/linked-products`): the church's
|
||||||
|
other products from the Hub, **Connect** / **Disconnect** (`crosscode.link/1` over
|
||||||
|
`POST /api/links/v1/connect` and `/disconnect`, both directions, Ed25519-signed and checked
|
||||||
|
against the Hub-listed key, replays refused via `LinkNonce`), per-link **Show events from** and
|
||||||
|
the site's **Publish my events** (`feed_publish`). Audit log: `product_link_connected`,
|
||||||
|
`product_link_disconnected`, `feed_publish_toggled`, `feed_show_toggled`.
|
||||||
|
- **The event feed** `GET /api/feed/v1/events?updatedSince=` (`crosscode.event-feed/1`, public, no
|
||||||
|
personal information) built from `FeedEntry` (`src/feed/entries.ts`): going live, closing and
|
||||||
|
selling out are changes even though no `Event` row changes; deactivated events go in `deleted`;
|
||||||
|
ended events drop out after 30 days without a tombstone. Refreshed by the `feed` job (every 5
|
||||||
|
minutes), a few seconds after writes to events, tickets and registrations (`config/db.js`), and
|
||||||
|
before answering when older than a minute. Changes are announced with `event.changed`
|
||||||
|
(`LINK_HEADERS`, one retry after a minute; the 15-minute poll catches the rest).
|
||||||
|
- **Showing linked products' events** (`src/feed/sync.ts`, `ImportedEvent`): fetched every 15
|
||||||
|
minutes (`feed-sync`) and on a valid `POST /api/feed/v1/changed` (`feed-sync-link` task); only
|
||||||
|
events whose origin matches the link; the last good copy stays when a source is down. Shown on
|
||||||
|
/events, the home page and campus pages, each with its page `/events/linked/<product>/<id>`
|
||||||
|
(markdown with HTML off, canonical link to the origin, no JSON-LD, not in the sitemap).
|
||||||
|
`/api/v2/linked-events`.
|
||||||
|
- **`@crosscode/seo`** (`packages/seo`): the event page's JSON-LD now comes from
|
||||||
|
`crosscode.event/1` (`crosscodeEvent` and `priceRangeCents` on `/events/:id/full`);
|
||||||
|
`frontend/src/lib/eventSchema.ts` is gone. The price range now covers main tickets only (an add-on
|
||||||
|
used to set the lowest price).
|
||||||
|
- Readiness: "Events from linked products are up to date".
|
||||||
|
- `FEED_JOBS_ENABLED` (default `true`). Migration `20261120120000_linked_products`.
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
- **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
|
||||||
|
on arrival, so they never reach a browser. With a Hub before 2.0.1 only the percentage shows.
|
||||||
|
- **API (v2):** `GET /api/v2/ai/status` (and the `status` in every AI reply and in `/ai/usage`) no
|
||||||
|
longer has `capCents` / `usedCents`; it has `usedInputTokens`, `usedOutputTokens`,
|
||||||
|
`capInputTokens`, `capOutputTokens` (null from an older Hub). `/ai/usage` rows have
|
||||||
|
`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
|
## [2.1.1] - 2026-11-03
|
||||||
|
|
||||||
@@ -2260,4 +2366,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.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.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.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)
|
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.
|
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
|
## 2. Before you start
|
||||||
|
|
||||||
- Ubuntu 22.04 or 24.04 on this server, with `frpc` already installed and connected (it runs as
|
- 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
|
## 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.
|
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
|
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
|
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
|
- Static uploads for event images
|
||||||
|
|
||||||
Documentation: see Backend API Documentation and Backend README for environment setup and endpoints.
|
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
|
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||||
- Backend README: ./backend/README.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
|
## 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
|
- Moving to 2.0 (v1 API removed): ./MIGRATING-TO-2.md
|
||||||
- Backend README: ./backend/README.md
|
- Backend README: ./backend/README.md
|
||||||
- Frontend README: ./frontend/README.md
|
- Frontend README: ./frontend/README.md
|
||||||
|
|||||||
@@ -119,7 +119,9 @@ Managed in the Payments tab (through `/api/v2/payments/providers/settings` and `
|
|||||||
| `VOLUNTEER_JOBS_ENABLED` (env) | `true` | The `volunteers` job (every 15 minutes) that sends volunteer reminders the day before a shift. |
|
| `VOLUNTEER_JOBS_ENABLED` (env) | `true` | The `volunteers` job (every 15 minutes) that sends volunteer reminders the day before a shift. |
|
||||||
| `WEBHOOKS_JOBS_ENABLED` (env) | `true` | The `webhooks` job (every minute): sends deliveries that are due (retries), picks up sends cut off by a restart, deletes deliveries older than 30 days. New events are sent straight away without it. |
|
| `WEBHOOKS_JOBS_ENABLED` (env) | `true` | The `webhooks` job (every minute): sends deliveries that are due (retries), picks up sends cut off by a restart, deletes deliveries older than 30 days. New events are sent straight away without it. |
|
||||||
| `WEBHOOKS_ENABLED` (env) | `true` | `false` stops noticing events for outbound webhooks altogether (nothing new is queued). |
|
| `WEBHOOKS_ENABLED` (env) | `true` | `false` stops noticing events for outbound webhooks altogether (nothing new is queued). |
|
||||||
| `WEBHOOKS_ALLOW_PRIVATE` (env) | `false` | `true` lets webhook endpoints use http and private or local addresses — for local testing only (the e2e tests set it). |
|
| `WEBHOOKS_ALLOW_PRIVATE` (env) | `false` | `true` lets webhook endpoints and linked products use http and private or local addresses — for local testing only (the e2e tests set it). |
|
||||||
|
| `FEED_JOBS_ENABLED` (env) | `true` | The `feed` job (every 5 minutes: publishes what changed in the event feed, e.g. an event going live or selling out, and tells linked products) and `feed-sync` (every 15 minutes: fetches events from the linked products shown here). Off: the feed is still rebuilt when it's asked for. |
|
||||||
|
| `feed_publish` | `true` | Settings → Linked products → **Publish my events**: the public event feed (`/api/feed/v1/events`) for the church's other products. |
|
||||||
| `SERIES_JOBS_ENABLED` (env) | `true` | The `series` job (every 15 minutes) that emails a series' followers once when a new event in it goes live (News & announcements: only people opted in to news). |
|
| `SERIES_JOBS_ENABLED` (env) | `true` | The `series` job (every 15 minutes) that emails a series' followers once when a new event in it goes live (News & announcements: only people opted in to news). |
|
||||||
| `RETENTION_JOBS_ENABLED` (env) | `true` | The nightly 03:30 `retention` job. Off means nothing expires automatically. |
|
| `RETENTION_JOBS_ENABLED` (env) | `true` | The nightly 03:30 `retention` job. Off means nothing expires automatically. |
|
||||||
| `wawp_webhook_last_seen` | — | Set when WAWP's webhook arrives with the right secret; the readiness page uses it to check WhatsApp STOP is set up. |
|
| `wawp_webhook_last_seen` | — | Set when WAWP's webhook arrives with the right secret; the readiness page uses it to check WhatsApp STOP is set up. |
|
||||||
|
|||||||
@@ -12,6 +12,41 @@ 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".
|
developer log is CHANGELOG.md. A tagged version without a section here shows "No details given".
|
||||||
-->
|
-->
|
||||||
|
|
||||||
|
## 2.4.0
|
||||||
|
|
||||||
|
- **Ready for the Church Website and App.** When your church has them, your events can show on
|
||||||
|
them and theirs here, with registration and payments still in Cross Events. Nothing changes until
|
||||||
|
you have them: Site settings → Linked products then lists them, with a Connect button.
|
||||||
|
- **Publish my events** (on by default) shares your public events with your connected products,
|
||||||
|
exactly as they appear on your events page. Hidden events and anyone's details are never shared.
|
||||||
|
- **Better search results for your events**: Google gets each event's real dates, place and the
|
||||||
|
price range of its main tickets, from the same data every Cross Code product uses.
|
||||||
|
|
||||||
|
## 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
|
## 2.1.1
|
||||||
|
|
||||||
- **Sending feedback forms and reminders no longer makes you wait.** "Send now" and "Remind" on the
|
- **Sending feedback forms and reminders no longer makes you wait.** "Send now" and "Remind" on the
|
||||||
|
|||||||
@@ -80,8 +80,10 @@ VOLUNTEER_JOBS_ENABLED=true
|
|||||||
SERIES_JOBS_ENABLED=true
|
SERIES_JOBS_ENABLED=true
|
||||||
WEBHOOKS_JOBS_ENABLED=true
|
WEBHOOKS_JOBS_ENABLED=true
|
||||||
WEBHOOKS_ENABLED=true
|
WEBHOOKS_ENABLED=true
|
||||||
# Local testing only: lets webhook endpoints be http:// or on a private network
|
# Local testing only: lets webhook endpoints and linked products be http:// or on a private network
|
||||||
WEBHOOKS_ALLOW_PRIVATE=false
|
WEBHOOKS_ALLOW_PRIVATE=false
|
||||||
|
# Linked products (2.4.0): publish the event feed every 5 minutes, fetch linked products' events every 15
|
||||||
|
FEED_JOBS_ENABLED=true
|
||||||
# Privacy (POPIA): daily 08:00 reminder to admins of data requests due within a week
|
# Privacy (POPIA): daily 08:00 reminder to admins of data requests due within a week
|
||||||
PRIVACY_JOBS_ENABLED=true
|
PRIVACY_JOBS_ENABLED=true
|
||||||
# Privacy (POPIA): nightly 03:30 retention job (Admin → Privacy → Retention). Note: inactive
|
# Privacy (POPIA): nightly 03:30 retention job (Admin → Privacy → Retention). Note: inactive
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@crosscode/events-backend",
|
"name": "@crosscode/events-backend",
|
||||||
"version": "2.1.1",
|
"version": "2.3.1",
|
||||||
"description": "Event Management System Backend",
|
"description": "Event Management System Backend",
|
||||||
"main": "src/index.js",
|
"main": "src/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -22,6 +22,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@cj-tech-master/excelts": "^10.2.0",
|
"@cj-tech-master/excelts": "^10.2.0",
|
||||||
|
"@crosscode/contracts": "*",
|
||||||
"@node-rs/argon2": "^2.2.2",
|
"@node-rs/argon2": "^2.2.2",
|
||||||
"@prisma/adapter-pg": "^7.10.1",
|
"@prisma/adapter-pg": "^7.10.1",
|
||||||
"@prisma/client": "^7.10.1",
|
"@prisma/client": "^7.10.1",
|
||||||
@@ -48,6 +49,7 @@
|
|||||||
"zod": "^4.6.7"
|
"zod": "^4.6.7"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@crosscode/seo": "*",
|
||||||
"@types/express": "^5.0.6",
|
"@types/express": "^5.0.6",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/jsonwebtoken": "^9.0.10",
|
"@types/jsonwebtoken": "^9.0.10",
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
-- 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';
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
-- 2.4.0: linked products and the event feed (docs/EVENTS-2.4-PLAN.md).
|
||||||
|
ALTER TYPE "AdminAuditAction" ADD VALUE 'product_link_connected';
|
||||||
|
ALTER TYPE "AdminAuditAction" ADD VALUE 'product_link_disconnected';
|
||||||
|
ALTER TYPE "AdminAuditAction" ADD VALUE 'feed_publish_toggled';
|
||||||
|
ALTER TYPE "AdminAuditAction" ADD VALUE 'feed_show_toggled';
|
||||||
|
|
||||||
|
CREATE TABLE "ProductLink" (
|
||||||
|
"installId" TEXT NOT NULL,
|
||||||
|
"product" TEXT NOT NULL,
|
||||||
|
"url" TEXT NOT NULL,
|
||||||
|
"publicKey" TEXT NOT NULL,
|
||||||
|
"secret" TEXT NOT NULL,
|
||||||
|
"connectedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"connectedById" TEXT,
|
||||||
|
"showEvents" BOOLEAN NOT NULL DEFAULT false,
|
||||||
|
"lastSyncAt" TIMESTAMP(3),
|
||||||
|
"lastSyncError" TEXT,
|
||||||
|
"lastGoodAt" TIMESTAMP(3),
|
||||||
|
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
CONSTRAINT "ProductLink_pkey" PRIMARY KEY ("installId")
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE "LinkNonce" (
|
||||||
|
"nonce" TEXT NOT NULL,
|
||||||
|
"seenAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
CONSTRAINT "LinkNonce_pkey" PRIMARY KEY ("nonce")
|
||||||
|
);
|
||||||
|
CREATE INDEX "LinkNonce_seenAt_idx" ON "LinkNonce"("seenAt");
|
||||||
|
|
||||||
|
CREATE TABLE "FeedEntry" (
|
||||||
|
"eventId" TEXT NOT NULL,
|
||||||
|
"hash" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"changedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"removedAt" TIMESTAMP(3),
|
||||||
|
CONSTRAINT "FeedEntry_pkey" PRIMARY KEY ("eventId")
|
||||||
|
);
|
||||||
|
CREATE INDEX "FeedEntry_changedAt_idx" ON "FeedEntry"("changedAt");
|
||||||
|
CREATE INDEX "FeedEntry_removedAt_idx" ON "FeedEntry"("removedAt");
|
||||||
|
|
||||||
|
CREATE TABLE "ImportedEvent" (
|
||||||
|
"key" TEXT NOT NULL,
|
||||||
|
"linkId" TEXT NOT NULL,
|
||||||
|
"payload" JSONB NOT NULL,
|
||||||
|
"startsAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"endsAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
"campusSlug" TEXT,
|
||||||
|
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||||
|
CONSTRAINT "ImportedEvent_pkey" PRIMARY KEY ("key")
|
||||||
|
);
|
||||||
|
CREATE INDEX "ImportedEvent_linkId_idx" ON "ImportedEvent"("linkId");
|
||||||
|
CREATE INDEX "ImportedEvent_endsAt_idx" ON "ImportedEvent"("endsAt");
|
||||||
|
ALTER TABLE "ImportedEvent" ADD CONSTRAINT "ImportedEvent_linkId_fkey" FOREIGN KEY ("linkId") REFERENCES "ProductLink"("installId") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||||
@@ -52,11 +52,16 @@ enum SecurityEventType {
|
|||||||
password_reset
|
password_reset
|
||||||
two_factor_enabled
|
two_factor_enabled
|
||||||
two_factor_disabled
|
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 {
|
enum TwoFactorMethod {
|
||||||
email
|
email
|
||||||
whatsapp
|
whatsapp
|
||||||
|
// 2.3.0: codes from an authenticator app (TOTP); nothing is sent.
|
||||||
|
authenticator
|
||||||
}
|
}
|
||||||
|
|
||||||
model User {
|
model User {
|
||||||
@@ -75,6 +80,11 @@ model User {
|
|||||||
notificationPreference NotificationPreference @default(email)
|
notificationPreference NotificationPreference @default(email)
|
||||||
twoFactorEnabled Boolean @default(false)
|
twoFactorEnabled Boolean @default(false)
|
||||||
twoFactorMethod TwoFactorMethod?
|
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.
|
// POPIA: opted in to "News & announcements" (marketing) bulk messages, per channel.
|
||||||
// Event updates to registrants don't depend on these. History in CommunicationConsent.
|
// Event updates to registrants don't depend on these. History in CommunicationConsent.
|
||||||
newsEmail Boolean @default(false)
|
newsEmail Boolean @default(false)
|
||||||
@@ -713,6 +723,8 @@ model TwoFactorChallenge {
|
|||||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||||
purpose String // 'login' | 'enable'
|
purpose String // 'login' | 'enable'
|
||||||
method TwoFactorMethod
|
method TwoFactorMethod
|
||||||
|
// 2.3.0: an authenticator app being set up: its secret (encrypted) until the first code confirms it.
|
||||||
|
pendingSecret String?
|
||||||
codeHash String
|
codeHash String
|
||||||
attempts Int @default(0)
|
attempts Int @default(0)
|
||||||
lastSentAt DateTime @default(now())
|
lastSentAt DateTime @default(now())
|
||||||
@@ -835,6 +847,10 @@ enum AdminAuditAction {
|
|||||||
webhook_endpoint_changed
|
webhook_endpoint_changed
|
||||||
registrations_bulk
|
registrations_bulk
|
||||||
ai_settings_changed
|
ai_settings_changed
|
||||||
|
product_link_connected
|
||||||
|
product_link_disconnected
|
||||||
|
feed_publish_toggled
|
||||||
|
feed_show_toggled
|
||||||
}
|
}
|
||||||
|
|
||||||
// Append-only audit trail for admin/supervisor-initiated actions with money or
|
// Append-only audit trail for admin/supervisor-initiated actions with money or
|
||||||
@@ -2341,11 +2357,88 @@ model AiCall {
|
|||||||
helper String
|
helper String
|
||||||
// ok, refused, incomplete, failed, cap_reached, unavailable
|
// ok, refused, incomplete, failed, cap_reached, unavailable
|
||||||
outcome String
|
outcome String
|
||||||
// What the church was charged, in cents (fractions of a cent).
|
// What the church was charged, in cents (fractions of a cent). Kept for the record; the site
|
||||||
|
// shows tokens (2.2.0), and only the Hub shows rand.
|
||||||
chargedCents Float @default(0)
|
chargedCents Float @default(0)
|
||||||
|
// 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())
|
createdAt DateTime @default(now())
|
||||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||||
|
|
||||||
@@index([createdAt])
|
@@index([createdAt])
|
||||||
@@index([userId, 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])
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md) ─────────────────────
|
||||||
|
|
||||||
|
// A link to one of the church's other products (Settings → Linked products → Connect): the
|
||||||
|
// shared secret signs the calls between the two (the event.changed webhook). The sibling's key
|
||||||
|
// is the one the Hub listed when it was connected.
|
||||||
|
model ProductLink {
|
||||||
|
installId String @id // the sibling's Hub install id
|
||||||
|
product String // website | app | accounts
|
||||||
|
url String
|
||||||
|
publicKey String
|
||||||
|
secret String // encrypted (utils/encryption)
|
||||||
|
connectedAt DateTime
|
||||||
|
connectedById String? // a user here; null when the sibling connected
|
||||||
|
// "Show events from this product" (off by default).
|
||||||
|
showEvents Boolean @default(false)
|
||||||
|
lastSyncAt DateTime?
|
||||||
|
lastSyncError String?
|
||||||
|
lastGoodAt DateTime?
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
updatedAt DateTime @updatedAt
|
||||||
|
|
||||||
|
importedEvents ImportedEvent[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nonces of link messages already accepted (crosscode.link/1), so one can't be replayed. Kept
|
||||||
|
// an hour: a message older than five minutes is refused anyway.
|
||||||
|
model LinkNonce {
|
||||||
|
nonce String @id
|
||||||
|
seenAt DateTime @default(now())
|
||||||
|
|
||||||
|
@@index([seenAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
// What the feed last published for each event (feed/entries.ts): changedAt moves only when what
|
||||||
|
// a sibling sees changes, so ?updatedSince= also catches going live, closing and selling out.
|
||||||
|
model FeedEntry {
|
||||||
|
eventId String @id
|
||||||
|
hash String
|
||||||
|
payload Json
|
||||||
|
changedAt DateTime
|
||||||
|
removedAt DateTime? // stopped being public: listed in `deleted`
|
||||||
|
|
||||||
|
@@index([changedAt])
|
||||||
|
@@index([removedAt])
|
||||||
|
}
|
||||||
|
|
||||||
|
// An event from a linked product's feed: a read-only copy, never published again.
|
||||||
|
model ImportedEvent {
|
||||||
|
key String @id // eventKey(): "<product>:<id>"
|
||||||
|
linkId String
|
||||||
|
link ProductLink @relation(fields: [linkId], references: [installId], onDelete: Cascade)
|
||||||
|
payload Json // the crosscode.event/1 as received
|
||||||
|
startsAt DateTime
|
||||||
|
endsAt DateTime
|
||||||
|
campusSlug String?
|
||||||
|
updatedAt DateTime
|
||||||
|
|
||||||
|
@@index([linkId])
|
||||||
|
@@index([endsAt])
|
||||||
|
}
|
||||||
|
|||||||
@@ -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,8 @@
|
|||||||
/**
|
/**
|
||||||
* AI helpers (2.0, roadmap §15). The site never holds a Claude API key: every call goes through
|
* 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 in rand,
|
* the Cross Events Hub (docs/hub-protocol.md §3b), which checks the licence's monthly cap, calls
|
||||||
* calls Claude and meters the call. This module:
|
* 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
|
* - 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);
|
* allowance renews — from the licence token first, then the Hub (cached for a minute);
|
||||||
* - runs one helper call (`runHelper`), with this site's own switches per helper and an optional
|
* - runs one helper call (`runHelper`), with this site's own switches per helper and an optional
|
||||||
@@ -32,8 +33,16 @@ const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(en
|
|||||||
export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const;
|
export const HELPERS = ['draft_event', 'summarise_report', 'draft_message', 'summarise_feedback', 'improve_text'] as const;
|
||||||
export type HelperName = (typeof HELPERS)[number];
|
export type HelperName = (typeof HELPERS)[number];
|
||||||
|
|
||||||
/** What the Hub says (§3b). Cents are charged rand, with fractions. */
|
/**
|
||||||
export type HubAiStatus = { enabled: boolean; capReached: boolean; capCents: number; usedCents: number; usedPercent: number; renewsOn: string | null };
|
* 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.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 = {
|
||||||
|
enabled: boolean; capReached: boolean; usedPercent: number; renewsOn: string | null;
|
||||||
|
usedInputTokens: number | null; usedOutputTokens: number | null;
|
||||||
|
capInputTokens: number | null; capOutputTokens: number | null;
|
||||||
|
};
|
||||||
/** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */
|
/** What the buttons need: the Hub's answer, whether it could be reached, and this site's switches. */
|
||||||
export type AiStatus = HubAiStatus & { available: boolean; helpers: Record<HelperName, boolean> };
|
export type AiStatus = HubAiStatus & { available: boolean; helpers: Record<HelperName, boolean> };
|
||||||
|
|
||||||
@@ -44,7 +53,28 @@ const STATUS_TTL_MS = 60 * 1000;
|
|||||||
const CALL_TIMEOUT_MS = 90 * 1000;
|
const CALL_TIMEOUT_MS = 90 * 1000;
|
||||||
const KEEP_CALLS_DAYS = 400;
|
const KEEP_CALLS_DAYS = 400;
|
||||||
|
|
||||||
const OFF: HubAiStatus = { enabled: false, capReached: false, capCents: 0, usedCents: 0, usedPercent: 0, renewsOn: null };
|
const OFF: HubAiStatus = { enabled: false, capReached: false, usedPercent: 0, renewsOn: null, usedInputTokens: null, usedOutputTokens: null, capInputTokens: null, capOutputTokens: null };
|
||||||
|
|
||||||
|
const tokens = (n: unknown): number | null => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.round(n) : null);
|
||||||
|
|
||||||
|
/** The Hub's status without its rand amounts. */
|
||||||
|
function fromHub(v: Record<string, unknown>): HubAiStatus {
|
||||||
|
return {
|
||||||
|
enabled: v.enabled === true,
|
||||||
|
capReached: v.capReached === true,
|
||||||
|
usedPercent: typeof v.usedPercent === 'number' ? v.usedPercent : 0,
|
||||||
|
renewsOn: typeof v.renewsOn === 'string' ? v.renewsOn : null,
|
||||||
|
usedInputTokens: tokens(v.usedInputTokens), usedOutputTokens: tokens(v.usedOutputTokens),
|
||||||
|
capInputTokens: tokens(v.capInputTokens), capOutputTokens: tokens(v.capOutputTokens),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "1.2M", "450K", "800": tokens for people. */
|
||||||
|
export function tokenText(n: number): string {
|
||||||
|
if (n >= 1e6) return `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1).replace(/\.0$/, '')}M`;
|
||||||
|
if (n >= 1e3) return `${Math.round(n / 1e3)}K`;
|
||||||
|
return String(n);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── This site's settings ─────────────────────────────────────────────────────
|
// ─── This site's settings ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -78,8 +108,8 @@ let cached: { at: number; value: HubAiStatus; available: boolean } | null = null
|
|||||||
|
|
||||||
/** Keep what the Hub just said (every AI reply and error carries it). */
|
/** Keep what the Hub just said (every AI reply and error carries it). */
|
||||||
function remember(value: unknown, available = true): void {
|
function remember(value: unknown, available = true): void {
|
||||||
const v = value as Partial<HubAiStatus> | null;
|
const v = value as Record<string, unknown> | null;
|
||||||
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: { ...OFF, ...v } as HubAiStatus, available };
|
if (v && typeof v.enabled === 'boolean') cached = { at: Date.now(), value: fromHub(v), available };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearAiStatusCache(): void {
|
export function clearAiStatusCache(): void {
|
||||||
@@ -185,7 +215,10 @@ async function warnAt80(status: HubAiStatus): Promise<void> {
|
|||||||
if (!email.isSmtpConfigured()) return;
|
if (!email.isSmtpConfigured()) return;
|
||||||
const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } });
|
const admins = await prisma.user.findMany({ where: { role: 'admin', isActive: true }, select: { email: true } });
|
||||||
const when = renewsText(status.renewsOn);
|
const when = renewsText(status.renewsOn);
|
||||||
const text = `This site has used ${status.usedPercent}% of this month's AI allowance (R${(status.usedCents / 100).toFixed(2)} of R${(status.capCents / 100).toFixed(2)}). The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`;
|
const used = status.usedInputTokens != null && status.usedOutputTokens != null
|
||||||
|
? ` (${tokenText(status.usedInputTokens)} input and ${tokenText(status.usedOutputTokens)} output tokens)`
|
||||||
|
: '';
|
||||||
|
const text = `This site has used ${status.usedPercent}% of this month's AI allowance${used}. The AI buttons stop working when it runs out, until it renews on ${when}. Site settings → AI shows who used it and for what.`;
|
||||||
for (const a of admins) {
|
for (const a of admins) {
|
||||||
await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`<p>${text}</p>`) })
|
await email.sendMail({ to: a.email, subject: `AI allowance ${status.usedPercent}% used`, text, html: email.emailWrapper(`<p>${text}</p>`) })
|
||||||
.catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message));
|
.catch(e => console.warn('[ai] 80% warning email failed:', (e as Error).message));
|
||||||
@@ -210,9 +243,13 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
|||||||
|
|
||||||
let outcome = 'ok';
|
let outcome = 'ok';
|
||||||
let chargedCents = 0;
|
let chargedCents = 0;
|
||||||
|
let inputTokens = 0;
|
||||||
|
let outputTokens = 0;
|
||||||
try {
|
try {
|
||||||
const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS });
|
const reply = await hub.signedPost('/api/installs/ai/complete', { protocolVersion: hub.PROTOCOL_VERSION, helper, ...req }, { timeoutMs: CALL_TIMEOUT_MS });
|
||||||
chargedCents = Number(reply.chargedCents) || 0;
|
chargedCents = Number(reply.chargedCents) || 0;
|
||||||
|
inputTokens = tokens(reply.usage?.inputTokens) ?? 0;
|
||||||
|
outputTokens = tokens(reply.usage?.outputTokens) ?? 0;
|
||||||
remember(reply.status);
|
remember(reply.status);
|
||||||
await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message));
|
await warnAt80(reply.status).catch(e => console.warn('[ai] 80% check failed:', (e as Error).message));
|
||||||
return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } };
|
return { output: reply.output, status: { ...(cached?.value || OFF), available: true, helpers: status.helpers } };
|
||||||
@@ -223,7 +260,7 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
|||||||
if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false);
|
if ((e as { code?: string }).code === 'HUB_UNREACHABLE') remember(cached?.value || { ...OFF, enabled: true }, false);
|
||||||
throw mapped.error;
|
throw mapped.error;
|
||||||
} finally {
|
} finally {
|
||||||
await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message));
|
await prisma.aiCall.create({ data: { userId, helper, outcome, chargedCents, inputTokens, outputTokens } }).catch(err => console.warn('[ai] could not log the call:', (err as Error).message));
|
||||||
await pruneOldCalls();
|
await pruneOldCalls();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -234,27 +271,30 @@ export async function runHelper(helper: HelperName, userId: string, req: HelperR
|
|||||||
export async function usageThisMonth(now = new Date()) {
|
export async function usageThisMonth(now = new Date()) {
|
||||||
const sast = new Date(now.getTime() + 2 * 3600 * 1000);
|
const sast = new Date(now.getTime() + 2 * 3600 * 1000);
|
||||||
const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000);
|
const from = new Date(Date.UTC(sast.getUTCFullYear(), sast.getUTCMonth(), 1) - 2 * 3600 * 1000);
|
||||||
const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, chargedCents: true, createdAt: true } });
|
const calls = await prisma.aiCall.findMany({ where: { createdAt: { gte: from } }, select: { userId: true, helper: true, outcome: true, inputTokens: true, outputTokens: true, createdAt: true } });
|
||||||
const add = (m: Map<string, { uses: number; chargedCents: number }>, key: string, cents: number) => {
|
type Use = { uses: number; inputTokens: number; outputTokens: number };
|
||||||
const v = m.get(key) || { uses: 0, chargedCents: 0 };
|
const add = (m: Map<string, Use>, key: string, c: { inputTokens: number; outputTokens: number }) => {
|
||||||
|
const v = m.get(key) || { uses: 0, inputTokens: 0, outputTokens: 0 };
|
||||||
v.uses++;
|
v.uses++;
|
||||||
v.chargedCents += cents;
|
v.inputTokens += c.inputTokens;
|
||||||
|
v.outputTokens += c.outputTokens;
|
||||||
m.set(key, v);
|
m.set(key, v);
|
||||||
};
|
};
|
||||||
const byPerson = new Map<string, { uses: number; chargedCents: number }>();
|
const byPerson = new Map<string, Use>();
|
||||||
const byHelper = new Map<string, { uses: number; chargedCents: number }>();
|
const byHelper = new Map<string, Use>();
|
||||||
const byDay = new Map<string, { uses: number; chargedCents: number }>();
|
const byDay = new Map<string, Use>();
|
||||||
for (const c of calls) {
|
for (const c of calls) {
|
||||||
if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue;
|
if (c.outcome === 'cap_reached' || c.outcome === 'unavailable') continue;
|
||||||
add(byPerson, c.userId || '', c.chargedCents);
|
add(byPerson, c.userId || '', c);
|
||||||
add(byHelper, c.helper, c.chargedCents);
|
add(byHelper, c.helper, c);
|
||||||
add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c.chargedCents);
|
add(byDay, new Date(c.createdAt.getTime() + 2 * 3600 * 1000).toISOString().slice(0, 10), c);
|
||||||
}
|
}
|
||||||
const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } });
|
const people = await prisma.user.findMany({ where: { id: { in: [...byPerson.keys()].filter(Boolean) } }, select: { id: true, name: true } });
|
||||||
const names = new Map(people.map(p => [p.id, p.name]));
|
const names = new Map(people.map(p => [p.id, p.name]));
|
||||||
|
const most = (a: Use, b: Use) => (b.inputTokens + b.outputTokens) - (a.inputTokens + a.outputTokens) || b.uses - a.uses;
|
||||||
return {
|
return {
|
||||||
people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort((a, b) => b.chargedCents - a.chargedCents),
|
people: [...byPerson.entries()].map(([id, v]) => ({ userId: id || null, name: id ? names.get(id) || 'Unknown' : 'Removed account', ...v })).sort(most),
|
||||||
helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort((a, b) => b.chargedCents - a.chargedCents),
|
helpers: [...byHelper.entries()].map(([helper, v]) => ({ helper, ...v })).sort(most),
|
||||||
days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)),
|
days: [...byDay.entries()].map(([day, v]) => ({ day, ...v })).sort((a, b) => a.day.localeCompare(b.day)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -135,6 +135,9 @@ const webhookRoutes = require('./routes/webhookRoutes');
|
|||||||
// Mount webhook routes BEFORE JSON body parser to avoid double-reading the stream
|
// Mount webhook routes BEFORE JSON body parser to avoid double-reading the stream
|
||||||
app.use('/api/webhooks', webhookRoutes);
|
app.use('/api/webhooks', webhookRoutes);
|
||||||
app.use('/api/v2/webhooks', webhooksRouter);
|
app.use('/api/v2/webhooks', webhooksRouter);
|
||||||
|
// The church's other products (2.4.0): the event feed, event.changed and Connect
|
||||||
|
// (/api/feed/v1, /api/links/v1; src/links/routes.ts). Its own parsers (raw for the webhook).
|
||||||
|
app.use('/api', require('./links/routes').crossProductRouter());
|
||||||
|
|
||||||
// Apply JSON body parser for all non-webhook routes
|
// Apply JSON body parser for all non-webhook routes
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
@@ -153,8 +156,12 @@ app.use((req, res, next) => {
|
|||||||
// Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js).
|
// Licence suspended, revoked or missing: no new or edited events, registrations or payments (src/hub/readOnly.js).
|
||||||
app.use(require('./hub/readOnly').licenceReadOnly);
|
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.
|
// 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');
|
const report = require('./hub/report');
|
||||||
let db = true;
|
let db = true;
|
||||||
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
|
try { await prisma.$queryRaw`SELECT 1`; } catch { db = false; }
|
||||||
@@ -174,11 +181,11 @@ app.use('/api/v2', linksRouter);
|
|||||||
app.use('/api/v2', require('./v2').v2Router());
|
app.use('/api/v2', require('./v2').v2Router());
|
||||||
// Links in messages already sent: v1 addresses answer 308 with their v2 one.
|
// Links in messages already sent: v1 addresses answer 308 with their v2 one.
|
||||||
app.use(legacyLinkRedirects);
|
app.use(legacyLinkRedirects);
|
||||||
app.use('/docs/v2', require('./v2').v2DocsRouter());
|
app.use('/api/docs/v2', require('./v2').v2DocsRouter());
|
||||||
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
app.get('/api/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||||
// address) and links in messages already sent (308s above, a mail app's one-click POST here).
|
// Before 2.2.0 the reference was at /docs/v2 (bookmarks, the old status page).
|
||||||
app.use('/api', legacyV1Router);
|
app.use('/docs/v2', (req, res) => res.redirect(301, `/api${req.originalUrl}`));
|
||||||
app.use('/api', v1Removed);
|
app.get('/docs', (req, res) => res.redirect(301, '/api/docs/v2'));
|
||||||
|
|
||||||
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
// Pre-warm the settings cache so synchronous helpers have DB values from startup
|
||||||
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
const { getSettingSync, warmCache } = require('./utils/settingsCache');
|
||||||
@@ -187,12 +194,16 @@ warmCache().catch(() => {});
|
|||||||
// handlers. Serving them inline lets a compromised/malicious upload run script
|
// 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
|
// 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.
|
// (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) => {
|
setHeaders: (res) => {
|
||||||
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
res.setHeader('Content-Security-Policy', "default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
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 ────────────────────────────────────────────────────────
|
// ── Shared page helpers ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@@ -268,8 +279,9 @@ app.get('/favicon.ico', (req, res) => {
|
|||||||
res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico'));
|
res.sendFile(path.join(__dirname, '..', 'src', 'favicon.ico'));
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Root route — status page ────────────────────────────────────────────────
|
// ── Status page, at /api (2.2.0); / sends you there ─────────────────────────
|
||||||
app.get('/', async (req, res) => {
|
app.get('/', (req, res) => res.redirect(302, '/api'));
|
||||||
|
app.get('/api', async (req, res) => {
|
||||||
const mem = process.memoryUsage();
|
const mem = process.memoryUsage();
|
||||||
const uptimeSec = process.uptime();
|
const uptimeSec = process.uptime();
|
||||||
const now = new Date().toISOString();
|
const now = new Date().toISOString();
|
||||||
@@ -335,15 +347,18 @@ app.get('/', async (req, res) => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="note">
|
<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>
|
</div>
|
||||||
`);
|
`);
|
||||||
|
|
||||||
res.send(html);
|
res.send(html);
|
||||||
});
|
});
|
||||||
|
|
||||||
// /docs: the v1 reference went with v1 in 2.0; the API is documented at /docs/v2 (OpenAPI).
|
// v1 (/api/…) was removed in 2.0. Still answered: provider webhooks (above, and WAWP's old
|
||||||
app.get('/docs', (req, res) => res.redirect(301, '/docs/v2'));
|
// 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
|
// Error middleware
|
||||||
app.use(notFound);
|
app.use(notFound);
|
||||||
@@ -384,7 +399,9 @@ app.listen(PORT, () => {
|
|||||||
// backup, temp cleanup) run on the pg-boss job queue — see src/jobs/index.js.
|
// 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));
|
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();
|
require('./hub/client').heartbeatSoon();
|
||||||
|
|
||||||
// Scheduled emails worker (polling)
|
// Scheduled emails worker (polling)
|
||||||
|
|||||||
@@ -87,8 +87,33 @@ function withWebhooks(base) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The event feed (2.4.0, src/feed/entries.ts): a write to anything a linked product would see
|
||||||
|
* (an event, its tickets, sessions, series or campus, or a registration that can fill it up)
|
||||||
|
* refreshes the feed a few seconds later. Only starts a timer; never affects the write.
|
||||||
|
*/
|
||||||
|
const FEED_MODELS = new Set(['Event', 'EventOption', 'OptionVariant', 'EarlyBirdTier', 'EventSession', 'EventSeries', 'Campus', 'Registration', 'RegistrationOption', 'WaitlistEntry']);
|
||||||
|
const WRITES = new Set(['create', 'createMany', 'createManyAndReturn', 'update', 'updateMany', 'updateManyAndReturn', 'upsert', 'delete', 'deleteMany']);
|
||||||
|
|
||||||
|
function withFeed(client) {
|
||||||
|
const touched = () => {
|
||||||
|
try { require('../feed/entries').changedSoon(); } catch (e) { console.warn('[feed] changedSoon:', e?.message || e); }
|
||||||
|
};
|
||||||
|
return client.$extends({
|
||||||
|
query: {
|
||||||
|
$allModels: {
|
||||||
|
async $allOperations({ model, operation, args, query }) {
|
||||||
|
const result = await query(args);
|
||||||
|
if (FEED_MODELS.has(model) && WRITES.has(operation)) touched();
|
||||||
|
return result;
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function createPrismaClient() {
|
function createPrismaClient() {
|
||||||
return withWebhooks(createBaseClient());
|
return withFeed(withWebhooks(createBaseClient()));
|
||||||
}
|
}
|
||||||
|
|
||||||
const prisma = createPrismaClient();
|
const prisma = createPrismaClient();
|
||||||
|
|||||||
@@ -45,9 +45,10 @@ function toAbsoluteUrl(req, url) {
|
|||||||
}
|
}
|
||||||
return raw; // keep as-is if already absolute and not localhost
|
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('/')) {
|
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
|
// Any other case, return as-is
|
||||||
return raw;
|
return raw;
|
||||||
|
|||||||
@@ -11,6 +11,9 @@ const {
|
|||||||
resendChallenge,
|
resendChallenge,
|
||||||
clearTrustedDevices,
|
clearTrustedDevices,
|
||||||
requiresTwoFactor,
|
requiresTwoFactor,
|
||||||
|
replaceRecoveryCodes,
|
||||||
|
recoveryCodesLeft,
|
||||||
|
clearTwoFactor,
|
||||||
} = require('../utils/twoFactor');
|
} = require('../utils/twoFactor');
|
||||||
|
|
||||||
// ─── Helpers ────────────────────────────────────────────────────────────────
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
||||||
@@ -99,7 +102,7 @@ const startEnableTwoFactor = async (req, res) => {
|
|||||||
}
|
}
|
||||||
if (!TWO_FACTOR_METHODS.includes(method)) {
|
if (!TWO_FACTOR_METHODS.includes(method)) {
|
||||||
res.status(400);
|
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)) {
|
if (!(await availableMethods(user)).includes(method)) {
|
||||||
res.status(400);
|
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
|
// 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 }));
|
res.json(await createChallenge(user, 'enable', method, { allowFallback: false }));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(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 { challengeId, code } = req.body || {};
|
||||||
const challenge = await verifyChallenge(challengeId, code, 'enable', req.user.id);
|
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({
|
await prisma.user.update({
|
||||||
where: { id: req.user.id },
|
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(() => {});
|
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) {
|
} catch (error) {
|
||||||
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
res.status(errorStatus(error, res)).json({ message: safeErrorMessage(error) });
|
||||||
}
|
}
|
||||||
@@ -157,7 +168,7 @@ const disableTwoFactor = async (req, res) => {
|
|||||||
|
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
where: { id: user.id },
|
where: { id: user.id },
|
||||||
data: { twoFactorEnabled: false, twoFactorMethod: null, updatedAt: new Date() },
|
data: { ...(await clearTwoFactor(user.id)), updatedAt: new Date() },
|
||||||
});
|
});
|
||||||
await clearTrustedDevices(user.id);
|
await clearTrustedDevices(user.id);
|
||||||
if (user.twoFactorEnabled) {
|
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
|
// @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)
|
// (the self-service kiosk uses this before letting the event be changed)
|
||||||
// @route POST /api/users/verify-password
|
// @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 });
|
const noticePromptPending = !req.impersonation && await require('../utils/privacyNotice').noticePromptPending({ noticeVersionAccepted });
|
||||||
// Campus-scoped staff: the campuses they're limited to (null = every campus).
|
// Campus-scoped staff: the campuses they're limited to (null = every campus).
|
||||||
const campusScope = (await require('../utils/campusScope').scopeFor(req))?.campusIds || null;
|
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 {
|
} else {
|
||||||
res.status(404);
|
res.status(404);
|
||||||
throw new Error('User not found');
|
throw new Error('User not found');
|
||||||
@@ -253,7 +285,7 @@ const getUsers = async (req, res) => {
|
|||||||
|
|
||||||
const select = {
|
const select = {
|
||||||
id: true, name: true, email: true, role: true,
|
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
|
// Build filters
|
||||||
@@ -406,8 +438,8 @@ const updateUser = async (req, res) => {
|
|||||||
// but never on — enabling requires the user to prove the channel themselves.
|
// but never on — enabling requires the user to prove the channel themselves.
|
||||||
const resetTwoFactor = twoFactorEnabled === false && user.twoFactorEnabled;
|
const resetTwoFactor = twoFactorEnabled === false && user.twoFactorEnabled;
|
||||||
if (resetTwoFactor) {
|
if (resetTwoFactor) {
|
||||||
data.twoFactorEnabled = false;
|
// The app's secret and the recovery codes go too (2.3.0).
|
||||||
data.twoFactorMethod = null;
|
Object.assign(data, await clearTwoFactor(user.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Promoted to a role that requires 2FA without having it: end their sessions
|
// Promoted to a role that requires 2FA without having it: end their sessions
|
||||||
@@ -443,6 +475,7 @@ const updateUser = async (req, res) => {
|
|||||||
phoneNumber: true,
|
phoneNumber: true,
|
||||||
notificationPreference: true,
|
notificationPreference: true,
|
||||||
twoFactorEnabled: true,
|
twoFactorEnabled: true,
|
||||||
|
twoFactorMethod: true,
|
||||||
createdAt: true,
|
createdAt: true,
|
||||||
updatedAt: true,
|
updatedAt: true,
|
||||||
isActive: true,
|
isActive: true,
|
||||||
@@ -820,6 +853,7 @@ module.exports = {
|
|||||||
startEnableTwoFactor,
|
startEnableTwoFactor,
|
||||||
confirmEnableTwoFactor,
|
confirmEnableTwoFactor,
|
||||||
disableTwoFactor,
|
disableTwoFactor,
|
||||||
|
replaceMyRecoveryCodes,
|
||||||
verifyPassword,
|
verifyPassword,
|
||||||
getUserProfile,
|
getUserProfile,
|
||||||
updateUserProfile,
|
updateUserProfile,
|
||||||
|
|||||||
@@ -0,0 +1,244 @@
|
|||||||
|
/**
|
||||||
|
* An event as `crosscode.event/1` (docs/EVENTS-2.4-PLAN.md §3): what the feed publishes and what
|
||||||
|
* the event page's JSON-LD is built from (@crosscode/seo).
|
||||||
|
*
|
||||||
|
* `buildCrosscodeEvent` is pure (the event, what's left of each ticket and the site's details in,
|
||||||
|
* the payload out) so it can be tested without a database; `loadForFeed` reads what it needs.
|
||||||
|
*
|
||||||
|
* Never in here: the event's contact person, kids check-in and volunteer tickets, staff prices,
|
||||||
|
* the attendee form. Only what the public event page already shows.
|
||||||
|
*/
|
||||||
|
import type { CrosscodeEvent } from '@crosscode/contracts';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS utils */
|
||||||
|
const sessionsUtil = require('../utils/sessions') as {
|
||||||
|
activeSessions<S extends { cancelledAt?: Date | string | null; startsAt: Date | string }>(sessions: S[]): S[];
|
||||||
|
registrationClosesAt(event: object, sessions: object[]): Date;
|
||||||
|
isPickOption(event: object, option: object): boolean;
|
||||||
|
};
|
||||||
|
const { publicOptions } = require('../utils/volunteers') as { publicOptions<O>(event: object): O[] };
|
||||||
|
const { getEffectiveUnitPrice } = require('../utils/pricing') as { getEffectiveUnitPrice(option: object, ref: Date | null, at: Date): number };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
export type FeedContext = {
|
||||||
|
/** This install's Hub id (origin.installId). */
|
||||||
|
installId: string;
|
||||||
|
/** The site's address, without a trailing slash. */
|
||||||
|
baseUrl: string;
|
||||||
|
timezone: string;
|
||||||
|
/** Campuses switched on (otherwise every event is for the whole church). */
|
||||||
|
campusesOn: boolean;
|
||||||
|
now: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FeedOption = {
|
||||||
|
id: string;
|
||||||
|
price: number;
|
||||||
|
isMainTicket: boolean;
|
||||||
|
stockLimit: number;
|
||||||
|
sessionMode?: string;
|
||||||
|
earlyBirdTiers?: { deadline: Date | string; price: number; order?: number | null }[];
|
||||||
|
variants?: { price: number | null }[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type FeedEventRow = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
description: string | null;
|
||||||
|
startDate: Date;
|
||||||
|
endDate: Date;
|
||||||
|
goLiveAt: Date | null;
|
||||||
|
registrationDeadline: Date | null;
|
||||||
|
picture: string | null;
|
||||||
|
location: string | null;
|
||||||
|
requiresRegistration: boolean;
|
||||||
|
waitlistEnabled: boolean;
|
||||||
|
scheduleType: string;
|
||||||
|
attendanceMode: string;
|
||||||
|
lateJoinEnabled: boolean;
|
||||||
|
lateJoinUntilSessionId: string | null;
|
||||||
|
kidsOptionId?: string | null;
|
||||||
|
volunteerOptionId?: string | null;
|
||||||
|
campus: { slug: string; name: string } | null;
|
||||||
|
series: { id: string; name: string } | null;
|
||||||
|
sessions: { id: string; label: string | null; startsAt: Date; endsAt: Date; location: string | null; cancelledAt: Date | null }[];
|
||||||
|
eventOptions: FeedOption[];
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Places left per option (`null` = no limit). Missing options count as unlimited. */
|
||||||
|
export type Availability = Map<string, number | null>;
|
||||||
|
|
||||||
|
export type BuiltEvent = {
|
||||||
|
event: CrosscodeEvent;
|
||||||
|
/** The event's own lowest and highest current prices, for its JSON-LD (`null` when free). */
|
||||||
|
priceRangeCents: { lowCents: number; highCents: number } | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const cut = (s: string | null | undefined, max: number): string | null => {
|
||||||
|
const t = String(s ?? '').trim();
|
||||||
|
return t ? (t.length > max ? `${t.slice(0, max - 1)}…` : t) : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** "/uploads/…" (as stored) → an absolute address on the site, served under /api (2.2.0). */
|
||||||
|
export function absolute(baseUrl: string, raw: string | null | undefined): string | null {
|
||||||
|
const v = String(raw ?? '').trim();
|
||||||
|
if (!v) return null;
|
||||||
|
if (/^https?:\/\//i.test(v)) return v;
|
||||||
|
const path = v.startsWith('/') ? v : `/${v}`;
|
||||||
|
return `${baseUrl}${/^\/uploads\//.test(path) ? `/api${path}` : path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plain text as markdown that reads the same: markdown characters escaped, line breaks kept
|
||||||
|
* (Events descriptions are plain text shown with their line breaks).
|
||||||
|
*/
|
||||||
|
export function plainToMarkdown(text: string | null | undefined): string | null {
|
||||||
|
const t = String(text ?? '').replace(/\r\n?/g, '\n').trim();
|
||||||
|
if (!t) return null;
|
||||||
|
const lines = t.split('\n').map((line) => line
|
||||||
|
.replace(/[\\`*_[\]<>|~]/g, (c) => `\\${c}`)
|
||||||
|
// A line that would start a heading, a list, a quote or a numbered list.
|
||||||
|
.replace(/^(\s*)([#>+-])/, '$1\\$2')
|
||||||
|
.replace(/^(\s*\d+)([.)])(\s)/, '$1\\$2$3'));
|
||||||
|
// A hard break between lines of the same paragraph (two spaces), blank lines stay paragraphs.
|
||||||
|
return lines.map((l, i) => (i < lines.length - 1 && l.trim() && lines[i + 1]!.trim() ? `${l} ` : l)).join('\n').slice(0, 20000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Today's price of each ticket (early-bird when one is open, else each variant's or the base price), in rand. */
|
||||||
|
function currentPrices(options: FeedOption[], now: Date): number[] {
|
||||||
|
const prices: number[] = [];
|
||||||
|
for (const o of options) {
|
||||||
|
if (o.variants && o.variants.length > 0) {
|
||||||
|
for (const v of o.variants) prices.push(v.price ?? o.price);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
prices.push(getEffectiveUnitPrice(o, null, now));
|
||||||
|
}
|
||||||
|
return prices.filter((p) => Number.isFinite(p) && p >= 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
function registration(row: FeedEventRow, options: FeedOption[], available: Availability, ctx: FeedContext, pageUrl: string): CrosscodeEvent['registration'] {
|
||||||
|
const closes = sessionsUtil.registrationClosesAt(row, row.sessions);
|
||||||
|
const closesAt = closes && Number.isFinite(closes.getTime()) ? closes.toISOString() : null;
|
||||||
|
if (!row.requiresRegistration) {
|
||||||
|
// Contact-only events: no tickets; the description says how to take part.
|
||||||
|
return { mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null };
|
||||||
|
}
|
||||||
|
const main = options.filter((o) => o.isMainTicket);
|
||||||
|
const priced = main.length > 0 ? main : options;
|
||||||
|
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
|
||||||
|
const low = prices.length > 0 ? Math.min(...prices) : 0;
|
||||||
|
|
||||||
|
let status: CrosscodeEvent['registration']['status'] = 'open';
|
||||||
|
if (row.goLiveAt && ctx.now < row.goLiveAt) status = 'not_open';
|
||||||
|
else if (closesAt && ctx.now >= new Date(closesAt)) status = 'closed';
|
||||||
|
else if (main.length > 0 && main.every((o) => o.stockLimit > 0 && (available.get(o.id) ?? 1) <= 0)) status = row.waitlistEnabled ? 'waitlist' : 'full';
|
||||||
|
|
||||||
|
return {
|
||||||
|
mode: 'origin',
|
||||||
|
url: pageUrl,
|
||||||
|
status,
|
||||||
|
opensAt: row.goLiveAt && ctx.now < row.goLiveAt ? row.goLiveAt.toISOString() : null,
|
||||||
|
closesAt,
|
||||||
|
priceFrom: low > 0 ? { amountCents: low, currency: 'ZAR' } : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildCrosscodeEvent(row: FeedEventRow, available: Availability, ctx: FeedContext): BuiltEvent {
|
||||||
|
const pageUrl = `${ctx.baseUrl}/events/${row.id}`;
|
||||||
|
const options = publicOptions<FeedOption>(row);
|
||||||
|
const live = sessionsUtil.activeSessions(row.sessions);
|
||||||
|
const multi = row.scheduleType === 'sessions' && row.sessions.length > 0;
|
||||||
|
// startsAt / endsAt are the first start and last end of the sessions that still run.
|
||||||
|
const startsAt = multi && live.length > 0 ? live[0]!.startsAt : row.startDate;
|
||||||
|
const endsAt = multi && live.length > 0 ? live.reduce((m, s) => (s.endsAt > m ? s.endsAt : m), live[0]!.endsAt) : row.endDate;
|
||||||
|
const place = cut(row.location, 200);
|
||||||
|
const online = place && /^https?:\/\//i.test(place) ? place : null;
|
||||||
|
|
||||||
|
const reg = registration(row, options, available, ctx, pageUrl);
|
||||||
|
const priced = options.filter((o) => o.isMainTicket).length > 0 ? options.filter((o) => o.isMainTicket) : options;
|
||||||
|
const prices = currentPrices(priced, ctx.now).map((p) => Math.round(p * 100));
|
||||||
|
const priceRangeCents = row.requiresRegistration && prices.some((p) => p > 0) ? { lowCents: Math.min(...prices), highCents: Math.max(...prices) } : null;
|
||||||
|
|
||||||
|
const event: CrosscodeEvent = {
|
||||||
|
schema: 'crosscode.event/1',
|
||||||
|
id: row.id,
|
||||||
|
origin: { product: 'events', installId: ctx.installId, url: pageUrl },
|
||||||
|
status: 'published',
|
||||||
|
// The feed puts the time it last changed here (feed/entries.ts).
|
||||||
|
updatedAt: ctx.now.toISOString(),
|
||||||
|
title: cut(row.title, 200) ?? 'Event',
|
||||||
|
summary: null,
|
||||||
|
description: plainToMarkdown(row.description),
|
||||||
|
imageUrl: absolute(ctx.baseUrl, row.picture),
|
||||||
|
timezone: ctx.timezone,
|
||||||
|
startsAt: new Date(startsAt).toISOString(),
|
||||||
|
endsAt: new Date(endsAt).toISOString(),
|
||||||
|
allDay: false,
|
||||||
|
sessions: multi
|
||||||
|
? [...row.sessions]
|
||||||
|
.sort((a, b) => new Date(a.startsAt).getTime() - new Date(b.startsAt).getTime())
|
||||||
|
.slice(0, 500)
|
||||||
|
.map((s) => ({
|
||||||
|
id: s.id,
|
||||||
|
label: cut(s.label, 200),
|
||||||
|
startsAt: new Date(s.startsAt).toISOString(),
|
||||||
|
endsAt: new Date(s.endsAt).toISOString(),
|
||||||
|
location: cut(s.location, 300),
|
||||||
|
cancelled: !!s.cancelledAt,
|
||||||
|
}))
|
||||||
|
: [],
|
||||||
|
location: place ? (online ? { name: null, address: null, onlineUrl: online } : { name: place, address: null, onlineUrl: null }) : null,
|
||||||
|
campus: ctx.campusesOn && row.campus ? { slug: row.campus.slug, name: cut(row.campus.name, 200) ?? row.campus.slug } : null,
|
||||||
|
series: row.series ? { id: row.series.id, name: cut(row.series.name, 200) ?? 'Series' } : null,
|
||||||
|
tags: [],
|
||||||
|
registration: reg,
|
||||||
|
};
|
||||||
|
return { event, priceRangeCents };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What `loadForFeed` selects (and the e2e/unit fixtures build). */
|
||||||
|
export const FEED_EVENT_SELECT = {
|
||||||
|
id: true, title: true, description: true, startDate: true, endDate: true, goLiveAt: true, registrationDeadline: true,
|
||||||
|
picture: true, location: true, requiresRegistration: true, waitlistEnabled: true, scheduleType: true, attendanceMode: true,
|
||||||
|
lateJoinEnabled: true, lateJoinUntilSessionId: true, kidsOptionId: true, volunteerOptionId: true, updatedAt: true,
|
||||||
|
campus: { select: { slug: true, name: true } },
|
||||||
|
series: { select: { id: true, name: true } },
|
||||||
|
sessions: { select: { id: true, label: true, startsAt: true, endsAt: true, location: true, cancelledAt: true } },
|
||||||
|
eventOptions: { select: { id: true, price: true, isMainTicket: true, stockLimit: true, sessionMode: true, earlyBirdTiers: true, variants: { select: { price: true } } } },
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Places left on each limited main ticket. "Pick sessions" tickets have places per session; they
|
||||||
|
* count as sold out only when every session that still runs is.
|
||||||
|
*/
|
||||||
|
export async function availabilityFor(row: FeedEventRow): Promise<Availability> {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
|
const { takenCount } = require('../utils/stock') as { takenCount(where: object): Promise<number> };
|
||||||
|
const out: Availability = new Map();
|
||||||
|
for (const o of publicOptions<FeedOption>(row)) {
|
||||||
|
if (!o.isMainTicket || !(o.stockLimit > 0)) continue;
|
||||||
|
if (sessionsUtil.isPickOption(row, o)) {
|
||||||
|
let left = 0;
|
||||||
|
for (const s of sessionsUtil.activeSessions(row.sessions)) left += Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id, sessionId: s.id }));
|
||||||
|
out.set(o.id, left);
|
||||||
|
} else {
|
||||||
|
out.set(o.id, Math.max(0, o.stockLimit - await takenCount({ eventOptionId: o.id })));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One event as `crosscode.event/1`, for its own page's JSON-LD (whether or not it's public: a
|
||||||
|
* hidden event's page is reachable by its link). `null` when there's no such event.
|
||||||
|
*/
|
||||||
|
export async function crosscodeEventFor(eventId: string, now = new Date()): Promise<BuiltEvent | null> {
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { feedContext } = require('./context') as typeof import('./context');
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
const row = (await prisma.event.findUnique({ where: { id: eventId }, select: FEED_EVENT_SELECT })) as FeedEventRow | null;
|
||||||
|
if (!row) return null;
|
||||||
|
return buildCrosscodeEvent(row, await availabilityFor(row), await feedContext(now));
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* What every part of the feed and of Linked products needs to know about this site: its Hub id,
|
||||||
|
* its address, its timezone and whether campuses and publishing are on.
|
||||||
|
*/
|
||||||
|
import type { FeedContext } from './build';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { getSetting } = require('../utils/settingsCache') as { getSetting(key: string, fallback?: string): Promise<string> };
|
||||||
|
const { campusesEnabled } = require('../utils/campuses') as { campusesEnabled(): Promise<boolean> };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
/** Setting: "Publish my events" (on unless set to "false"). */
|
||||||
|
export const PUBLISH_KEY = 'feed_publish';
|
||||||
|
|
||||||
|
export async function publishOn(): Promise<boolean> {
|
||||||
|
return String(await getSetting(PUBLISH_KEY, 'true')).toLowerCase() !== 'false';
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The site's address, as it tells the Hub (hub/report.js installInfo). */
|
||||||
|
export async function siteUrl(): Promise<string> {
|
||||||
|
const url = await getSetting('app_base_url', process.env.FRONTEND_URL || '');
|
||||||
|
return String(url || process.env.FRONTEND_URL || '').split(',')[0]!.trim().replace(/\/+$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function hubInstallId(): Promise<string | null> {
|
||||||
|
const row = await prisma.appSetting.findUnique({ where: { key: 'hub_install_id' } });
|
||||||
|
return row?.value || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Placeholder id for a site not connected to the Hub (its JSON-LD still works; it has no feed). */
|
||||||
|
export const NO_INSTALL_ID = '00000000-0000-4000-8000-000000000000';
|
||||||
|
|
||||||
|
export async function feedContext(now = new Date()): Promise<FeedContext & { connected: boolean }> {
|
||||||
|
const [installId, baseUrl, campusesOn] = await Promise.all([hubInstallId(), siteUrl(), campusesEnabled().catch(() => false)]);
|
||||||
|
return {
|
||||||
|
installId: installId || NO_INSTALL_ID,
|
||||||
|
connected: !!installId,
|
||||||
|
baseUrl,
|
||||||
|
timezone: process.env.APP_TIMEZONE || 'Africa/Johannesburg',
|
||||||
|
campusesOn,
|
||||||
|
now,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
/**
|
||||||
|
* The published feed (docs/EVENTS-2.4-PLAN.md §3): `FeedEntry` holds what was last published for
|
||||||
|
* each event, so `?updatedSince=` is right even when an event changes without its row changing
|
||||||
|
* (it goes live, registration closes, it sells out) and when it stops being public (Events never
|
||||||
|
* deletes an event, it deactivates it).
|
||||||
|
*
|
||||||
|
* `refreshFeed` builds every event that is public and ended at most 30 days ago, and moves an
|
||||||
|
* entry's `changedAt` only when its payload changed. Run by the `feed` job (every 5 minutes),
|
||||||
|
* shortly after any change to events, tickets or registrations (`changedSoon`), and before the
|
||||||
|
* feed is served when the last run is more than a minute old.
|
||||||
|
*/
|
||||||
|
import crypto from 'crypto';
|
||||||
|
import { canonicalJson, eventSchema, EVENT_FEED_SCHEMA, type CrosscodeEvent, type EventFeed } from '@crosscode/contracts';
|
||||||
|
import { availabilityFor, buildCrosscodeEvent, FEED_EVENT_SELECT, type FeedEventRow } from './build';
|
||||||
|
import { feedContext } from './context';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { publicEventWhere } = require('../utils/series') as { publicEventWhere(now: Date): object };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
const DAY = 24 * 60 * 60 * 1000;
|
||||||
|
/** Ended events stay in a full fetch this long. */
|
||||||
|
export const ENDED_KEEP_DAYS = 30;
|
||||||
|
/** Entries of events that stopped being public are kept (as `deleted`) this long. */
|
||||||
|
export const REMOVED_KEEP_DAYS = 90;
|
||||||
|
|
||||||
|
/** The hash of what a sibling sees (without `updatedAt`, which is the entry's `changedAt`). */
|
||||||
|
export function payloadHash(event: CrosscodeEvent): string {
|
||||||
|
const { updatedAt: _ignored, ...rest } = event;
|
||||||
|
return crypto.createHash('sha256').update(canonicalJson(rest)).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RefreshResult = { changed: string[]; removed: string[]; skipped: { id: string; reason: string }[] };
|
||||||
|
|
||||||
|
let lastRefreshAt = 0;
|
||||||
|
let running: Promise<RefreshResult> | null = null;
|
||||||
|
|
||||||
|
export async function refreshFeed(now = new Date(), db = prisma): Promise<RefreshResult> {
|
||||||
|
const ctx = await feedContext(now);
|
||||||
|
const result: RefreshResult = { changed: [], removed: [], skipped: [] };
|
||||||
|
// Without a Hub install id there's no origin to publish under.
|
||||||
|
if (!ctx.connected) return result;
|
||||||
|
|
||||||
|
const rows = (await db.event.findMany({
|
||||||
|
where: { AND: [publicEventWhere(now), { endDate: { gte: new Date(now.getTime() - ENDED_KEEP_DAYS * DAY) } }] },
|
||||||
|
select: FEED_EVENT_SELECT,
|
||||||
|
})) as FeedEventRow[];
|
||||||
|
const entries: { eventId: string; hash: string; removedAt: Date | null }[] = await db.feedEntry.findMany({ select: { eventId: true, hash: true, removedAt: true } });
|
||||||
|
const byId = new Map(entries.map((e) => [e.eventId, e]));
|
||||||
|
const current = new Set<string>();
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const built = buildCrosscodeEvent(row, await availabilityFor(row), ctx);
|
||||||
|
const check = eventSchema.safeParse(built.event);
|
||||||
|
if (!check.success) {
|
||||||
|
// Never publish something the contract refuses; the next change may fix it.
|
||||||
|
result.skipped.push({ id: row.id, reason: check.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ') });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
current.add(row.id);
|
||||||
|
const hash = payloadHash(built.event);
|
||||||
|
const prev = byId.get(row.id);
|
||||||
|
if (prev && prev.hash === hash && !prev.removedAt) continue;
|
||||||
|
await db.feedEntry.upsert({
|
||||||
|
where: { eventId: row.id },
|
||||||
|
create: { eventId: row.id, hash, payload: built.event, changedAt: now, removedAt: null },
|
||||||
|
update: { hash, payload: built.event, changedAt: now, removedAt: null },
|
||||||
|
});
|
||||||
|
result.changed.push(row.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Entries no longer built: an event that stopped being public goes into `deleted`; one that
|
||||||
|
// only ended long enough ago drops out quietly (siblings keep their copy).
|
||||||
|
const gone = entries.filter((e) => !e.removedAt && !current.has(e.eventId)).map((e) => e.eventId);
|
||||||
|
if (gone.length > 0) {
|
||||||
|
const stillPublic = new Set<string>(
|
||||||
|
(await db.event.findMany({ where: { AND: [{ id: { in: gone } }, publicEventWhere(now)] }, select: { id: true } })).map((e: { id: string }) => e.id),
|
||||||
|
);
|
||||||
|
const skipped = new Set(result.skipped.map((s) => s.id));
|
||||||
|
for (const id of gone) {
|
||||||
|
if (skipped.has(id)) continue;
|
||||||
|
if (stillPublic.has(id)) await db.feedEntry.delete({ where: { eventId: id } });
|
||||||
|
else {
|
||||||
|
await db.feedEntry.update({ where: { eventId: id }, data: { removedAt: now } });
|
||||||
|
result.removed.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await db.feedEntry.deleteMany({ where: { removedAt: { lt: new Date(now.getTime() - REMOVED_KEEP_DAYS * DAY) } } });
|
||||||
|
// Wall-clock time of the run (not `now`, which tests and catch-up runs may set).
|
||||||
|
lastRefreshAt = Date.now();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One refresh at a time in this process; the job, `changedSoon` and the feed share it. */
|
||||||
|
export function refreshOnce(now = new Date()): Promise<RefreshResult> {
|
||||||
|
if (!running) running = refreshFeed(now).finally(() => { running = null; });
|
||||||
|
return running;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function lastRefresh(): number {
|
||||||
|
return lastRefreshAt;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The feed answer (`crosscode.event-feed/1`). */
|
||||||
|
export async function feedResponse(updatedSince: Date | null, now = new Date(), db = prisma): Promise<EventFeed> {
|
||||||
|
const live = await db.feedEntry.findMany({
|
||||||
|
where: { removedAt: null, ...(updatedSince ? { changedAt: { gt: updatedSince } } : {}) },
|
||||||
|
orderBy: { changedAt: 'asc' },
|
||||||
|
});
|
||||||
|
const deleted = updatedSince
|
||||||
|
? await db.feedEntry.findMany({ where: { removedAt: { gt: updatedSince } }, orderBy: { removedAt: 'asc' }, select: { eventId: true, removedAt: true } })
|
||||||
|
: [];
|
||||||
|
return {
|
||||||
|
schema: EVENT_FEED_SCHEMA,
|
||||||
|
generatedAt: now.toISOString(),
|
||||||
|
events: live.map((e: { payload: CrosscodeEvent; changedAt: Date }) => ({ ...e.payload, updatedAt: e.changedAt.toISOString() })),
|
||||||
|
deleted: deleted.map((d: { eventId: string; removedAt: Date }) => ({ id: d.eventId, deletedAt: d.removedAt.toISOString() })),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── After a change ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
let timer: NodeJS.Timeout | null = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Something that can change the feed was written (config/db.js): refresh a few seconds later
|
||||||
|
* (one refresh for a burst of writes) and tell connected siblings. Never throws.
|
||||||
|
*/
|
||||||
|
export function changedSoon(delayMs = 5000): void {
|
||||||
|
if (timer) return;
|
||||||
|
timer = setTimeout(() => {
|
||||||
|
timer = null;
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||||
|
(require('./notify') as typeof import('./notify')).refreshAndNotify().catch((e: unknown) => console.warn('[feed] refresh failed:', (e as Error)?.message || e));
|
||||||
|
}, delayMs);
|
||||||
|
timer.unref?.();
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
/**
|
||||||
|
* Telling connected siblings the feed changed (`event.changed`, signed with each link's secret),
|
||||||
|
* so they fetch straight away instead of at their next 15-minute poll. One try, and one more a
|
||||||
|
* minute later; after that the poll catches up, so a sibling that's down misses nothing.
|
||||||
|
*/
|
||||||
|
import { EVENT_FEED_SCHEMA, FEED_PATHS, type EventChanged } from '@crosscode/contracts';
|
||||||
|
import { LINK_HEADERS, signedHeaders } from '@crosscode/contracts/signing';
|
||||||
|
import { hubInstallId, publishOn } from './context';
|
||||||
|
import { refreshOnce, type RefreshResult } from './entries';
|
||||||
|
import { callSibling, siblingUrl } from '../links/http';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
const RETRY_MS = 60 * 1000;
|
||||||
|
|
||||||
|
type LinkRow = { installId: string; url: string; secret: string };
|
||||||
|
|
||||||
|
export async function sendChanged(link: LinkRow, eventIds: string[], senderId: string, now = new Date()): Promise<void> {
|
||||||
|
const body: EventChanged = { schema: EVENT_FEED_SCHEMA, type: 'event.changed', occurredAt: now.toISOString(), eventIds: eventIds.slice(0, 100) };
|
||||||
|
const raw = JSON.stringify(body);
|
||||||
|
const headers = signedHeaders(LINK_HEADERS, { senderId, secret: decrypt(link.secret), rawBody: raw });
|
||||||
|
await callSibling(await siblingUrl(link.url, FEED_PATHS.changed), { method: 'POST', body: raw, headers });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tells every connected sibling; failures are retried once, then left to the sibling's poll. */
|
||||||
|
export async function notifyLinks(eventIds: string[]): Promise<{ told: number; failed: number }> {
|
||||||
|
if (eventIds.length === 0 || !(await publishOn())) return { told: 0, failed: 0 };
|
||||||
|
const senderId = await hubInstallId();
|
||||||
|
if (!senderId) return { told: 0, failed: 0 };
|
||||||
|
const links: LinkRow[] = await prisma.productLink.findMany({ select: { installId: true, url: true, secret: true } });
|
||||||
|
let told = 0;
|
||||||
|
let failed = 0;
|
||||||
|
await Promise.all(links.map(async (link) => {
|
||||||
|
try {
|
||||||
|
await sendChanged(link, eventIds, senderId);
|
||||||
|
told++;
|
||||||
|
} catch (e) {
|
||||||
|
failed++;
|
||||||
|
console.warn(`[feed] event.changed to ${link.url} failed, trying once more in a minute:`, (e as Error)?.message || e);
|
||||||
|
setTimeout(() => {
|
||||||
|
sendChanged(link, eventIds, senderId).catch((err) => console.warn(`[feed] event.changed to ${link.url} failed again (its poll will catch up):`, (err as Error)?.message || err));
|
||||||
|
}, RETRY_MS).unref?.();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
return { told, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `feed` job: refresh what's published and tell siblings what changed. */
|
||||||
|
export async function refreshAndNotify(now = new Date()): Promise<RefreshResult & { told: number }> {
|
||||||
|
const result = await refreshOnce(now);
|
||||||
|
const { told } = await notifyLinks([...result.changed, ...result.removed]);
|
||||||
|
return { ...result, told };
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* Showing events from linked products (docs/EVENTS-2.4-PLAN.md §4): each link with "Show events
|
||||||
|
* from this product" on is fetched every 15 minutes (`feed-sync` job) and straight away on a
|
||||||
|
* valid `event.changed` (`feed-sync-link` task). Its events are kept as read-only copies
|
||||||
|
* (`ImportedEvent`), keyed by origin product + id, and never published again.
|
||||||
|
*
|
||||||
|
* - The last good copy stays: a failed fetch only records the error.
|
||||||
|
* - One bad event is skipped and logged (parseEventFeed); it never holds up the rest.
|
||||||
|
* - Only events that really come from that sibling are taken (origin.installId and product
|
||||||
|
* must match the link), so one product can't put words in another's mouth.
|
||||||
|
*/
|
||||||
|
import { eventKey, FEED_PATHS, parseEventFeed, type CrosscodeEvent } from '@crosscode/contracts';
|
||||||
|
import { callSibling, siblingUrl } from '../links/http';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
/** Fetch from a little before the last good fetch, so an event saved during it isn't missed. */
|
||||||
|
const OVERLAP_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
type Link = { installId: string; product: string; url: string; showEvents: boolean; lastGoodAt: Date | null };
|
||||||
|
|
||||||
|
export type SyncResult = { installId: string; ok: boolean; imported?: number; deleted?: number; rejected?: number; skipped?: number; error?: string };
|
||||||
|
|
||||||
|
export async function syncLink(link: Link, now = new Date()): Promise<SyncResult> {
|
||||||
|
if (!link.showEvents) return { installId: link.installId, ok: true, imported: 0, deleted: 0 };
|
||||||
|
const since = link.lastGoodAt ? new Date(link.lastGoodAt.getTime() - OVERLAP_MS) : null;
|
||||||
|
try {
|
||||||
|
const url = await siblingUrl(link.url, FEED_PATHS.events, since ? { updatedSince: since.toISOString() } : {});
|
||||||
|
const parsed = parseEventFeed(await callSibling(url, { method: 'GET' }));
|
||||||
|
if (!parsed.ok) throw new Error(`The feed isn't a crosscode.event-feed/1: ${parsed.error.issues.slice(0, 3).map((i) => `${i.path.join('.')} ${i.message}`).join('; ')}`);
|
||||||
|
const { feed, rejected } = parsed;
|
||||||
|
for (const r of rejected) console.warn(`[feed] skipped an event from ${link.url} (${r.id ?? `#${r.index}`}):`, r.issues.slice(0, 3).map((i) => `${i.path.join('.')} ${i.message}`).join('; '));
|
||||||
|
|
||||||
|
const theirs = feed.events.filter((e) => e.origin.installId === link.installId && e.origin.product === link.product);
|
||||||
|
const skipped = feed.events.length - theirs.length;
|
||||||
|
for (const e of theirs) await upsert(link.installId, e);
|
||||||
|
const deletedKeys = feed.deleted.map((d) => `${link.product}:${d.id}`);
|
||||||
|
let deleted = deletedKeys.length ? (await prisma.importedEvent.deleteMany({ where: { linkId: link.installId, key: { in: deletedKeys } } })).count : 0;
|
||||||
|
// A full fetch is the whole list: anything not in it is gone (or ended a while ago).
|
||||||
|
if (!since) deleted += (await prisma.importedEvent.deleteMany({ where: { linkId: link.installId, key: { notIn: theirs.map(eventKey) } } })).count;
|
||||||
|
|
||||||
|
await prisma.productLink.update({
|
||||||
|
where: { installId: link.installId },
|
||||||
|
data: { lastSyncAt: now, lastGoodAt: new Date(feed.generatedAt), lastSyncError: rejected.length ? `${rejected.length} event(s) skipped: they don't fit crosscode.event/1` : null },
|
||||||
|
});
|
||||||
|
return { installId: link.installId, ok: true, imported: theirs.length, deleted, rejected: rejected.length, skipped };
|
||||||
|
} catch (e) {
|
||||||
|
const error = String((e as Error)?.message || e).slice(0, 500);
|
||||||
|
await prisma.productLink.update({ where: { installId: link.installId }, data: { lastSyncAt: now, lastSyncError: error } }).catch(() => {});
|
||||||
|
return { installId: link.installId, ok: false, error };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function upsert(linkId: string, e: CrosscodeEvent) {
|
||||||
|
const data = { linkId, payload: e, startsAt: new Date(e.startsAt), endsAt: new Date(e.endsAt), campusSlug: e.campus?.slug ?? null, updatedAt: new Date(e.updatedAt) };
|
||||||
|
await prisma.importedEvent.upsert({ where: { key: eventKey(e) }, create: { key: eventKey(e), ...data }, update: data });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `feed-sync` job: every link that shows events, one after another (one failing never stops the rest). */
|
||||||
|
export async function syncAll(now = new Date()): Promise<{ links: number; failed: number }> {
|
||||||
|
const links: Link[] = await prisma.productLink.findMany({ where: { showEvents: true } });
|
||||||
|
let failed = 0;
|
||||||
|
for (const link of links) if (!(await syncLink(link, now)).ok) failed++;
|
||||||
|
return { links: links.length, failed };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The `feed-sync-link` task (after an `event.changed`). */
|
||||||
|
export async function syncOne(installId: string): Promise<SyncResult | { skipped: string }> {
|
||||||
|
const link: Link | null = await prisma.productLink.findUnique({ where: { installId } });
|
||||||
|
if (!link) return { skipped: 'no such link' };
|
||||||
|
return syncLink(link);
|
||||||
|
}
|
||||||
@@ -6,8 +6,18 @@
|
|||||||
* hub_last_heartbeat_at, hub_last_error, hub_latest_version,
|
* hub_last_heartbeat_at, hub_last_error, hub_latest_version,
|
||||||
* hub_releases, hub_notices (JSON from the last heartbeat: what's new, provider's notices),
|
* hub_releases, hub_notices (JSON from the last heartbeat: what's new, provider's notices),
|
||||||
* hub_update_requested_at, hub_update_requested_version,
|
* hub_update_requested_at, hub_update_requested_version,
|
||||||
* hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub).
|
* hub_update_snoozed_version ("Not now" for that version; set here, not by the Hub),
|
||||||
|
* hub_v1_until (the Hub refused protocol v2: speak v1 until then; 2.4.0),
|
||||||
|
* and this site's key pair and the Hub's list of the church's other products (links/store.ts).
|
||||||
* These keys are kept out of the generic settings endpoints (settingsController).
|
* These keys are kept out of the generic settings endpoints (settingsController).
|
||||||
|
*
|
||||||
|
* Protocol (2.4.0, docs/EVENTS-2.4-PLAN.md §1): register and heartbeat speak **v2**
|
||||||
|
* (`product: "events"`, this site's public key, the church's other products in the reply). An
|
||||||
|
* install that registered with v1 moves over by sending its key on the heartbeat (Hub 2.2.0
|
||||||
|
* saves it), so nobody needs the licence key again. If the Hub refuses a v2 body (a Hub before
|
||||||
|
* 2.0, or a body the Hub's contract doesn't accept), the same heartbeat goes again as v1 and v1
|
||||||
|
* is used for a day: the licence must keep refreshing whatever happens. Update requests and AI
|
||||||
|
* calls stay v1, which every Hub accepts.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const crypto = require('crypto');
|
const crypto = require('crypto');
|
||||||
@@ -15,10 +25,16 @@ const prisma = require('../config/db');
|
|||||||
const { encrypt, decrypt } = require('../utils/encryption');
|
const { encrypt, decrypt } = require('../utils/encryption');
|
||||||
const { verifyToken, clearLicenceCache } = require('./licence');
|
const { verifyToken, clearLicenceCache } = require('./licence');
|
||||||
const report = require('./report');
|
const report = require('./report');
|
||||||
|
const { hub } = require('@crosscode/contracts');
|
||||||
|
const store = require('../links/store');
|
||||||
|
|
||||||
|
/** Update requests and AI calls (as in v1; the Hub answers both versions). */
|
||||||
const PROTOCOL_VERSION = 1;
|
const PROTOCOL_VERSION = 1;
|
||||||
|
/** Register and heartbeat (2.4.0). */
|
||||||
|
const HEARTBEAT_PROTOCOL = 2;
|
||||||
|
const V1_FALLBACK_MS = 24 * 60 * 60 * 1000;
|
||||||
const TIMEOUT_MS = 15000;
|
const TIMEOUT_MS = 15000;
|
||||||
const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version'];
|
const HUB_KEYS = ['hub_install_id', 'hub_install_secret', 'hub_licence', 'hub_last_heartbeat_at', 'hub_last_error', 'hub_latest_version', 'hub_update_requested_at', 'hub_update_requested_version', 'hub_releases', 'hub_notices', 'hub_update_snoozed_version', 'hub_v1_until', ...store.KEY_SETTINGS];
|
||||||
|
|
||||||
function hubUrl() {
|
function hubUrl() {
|
||||||
return String(process.env.HUB_URL || 'https://events-hub.crosscode.co.za').replace(/\/$/, '');
|
return String(process.env.HUB_URL || 'https://events-hub.crosscode.co.za').replace(/\/$/, '');
|
||||||
@@ -100,11 +116,26 @@ async function connect(licenceKey, adminContact) {
|
|||||||
if (!/^https?:\/\//.test(install.url)) {
|
if (!/^https?:\/\//.test(install.url)) {
|
||||||
throw new HubError('Set the site\'s web address first (FRONTEND_URL on the server, or Site settings → Organisation).', 'NO_SITE_URL', 400);
|
throw new HubError('Set the site\'s web address first (FRONTEND_URL on the server, or Site settings → Organisation).', 'NO_SITE_URL', 400);
|
||||||
}
|
}
|
||||||
const data = await post('/api/installs/register', {
|
const v1Body = {
|
||||||
protocolVersion: PROTOCOL_VERSION,
|
protocolVersion: PROTOCOL_VERSION,
|
||||||
licenceKey: String(licenceKey || '').trim(),
|
licenceKey: String(licenceKey || '').trim(),
|
||||||
install: { ...install, adminContact: adminContact ? { name: adminContact.name || null, email: adminContact.email || null } : null },
|
install: { ...install, adminContact: adminContact ? { name: adminContact.name || null, email: adminContact.email || null } : null },
|
||||||
});
|
};
|
||||||
|
// v2 (2.4.0): the product and this site's public key, so the church's other products can link.
|
||||||
|
// Anything wrong with the key (or a Hub that only speaks v1) registers with v1 instead.
|
||||||
|
const publicKeyPem = await ownPublicKey();
|
||||||
|
const v2Body = { ...v1Body, protocolVersion: HEARTBEAT_PROTOCOL, licenceKey: v1Body.licenceKey.toUpperCase(), product: 'events', install: { ...v1Body.install, publicKey: publicKeyPem } };
|
||||||
|
const v2 = !!publicKeyPem && !(await v1Only()) && hub.registerRequestSchema.safeParse(v2Body).success;
|
||||||
|
let data;
|
||||||
|
let sentV2 = v2;
|
||||||
|
try {
|
||||||
|
data = await post('/api/installs/register', v2 ? v2Body : v1Body);
|
||||||
|
} catch (e) {
|
||||||
|
if (!v2 || !refusedV2(e)) throw e;
|
||||||
|
await useV1ForADay();
|
||||||
|
sentV2 = false;
|
||||||
|
data = await post('/api/installs/register', v1Body);
|
||||||
|
}
|
||||||
const claims = verifyToken(data.licence);
|
const claims = verifyToken(data.licence);
|
||||||
if (!claims || claims.installId !== data.installId) {
|
if (!claims || claims.installId !== data.installId) {
|
||||||
throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL pointing at the right Hub?', 'BAD_LICENCE', 502);
|
throw new HubError('The Hub answered with a licence this install can\'t verify. Is HUB_URL pointing at the right Hub?', 'BAD_LICENCE', 502);
|
||||||
@@ -118,16 +149,106 @@ async function connect(licenceKey, adminContact) {
|
|||||||
hub_latest_version: data.latestVersion || null,
|
hub_latest_version: data.latestVersion || null,
|
||||||
...fromHub(data),
|
...fromHub(data),
|
||||||
});
|
});
|
||||||
|
if (sentV2) {
|
||||||
|
try {
|
||||||
|
await store.saveLinkedProducts(data.linkedProducts);
|
||||||
|
// Registered with the key, so the Hub has it.
|
||||||
|
await store.setPublicKeyStatus('matches');
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[hub] Could not save the linked products:', e?.message || e);
|
||||||
|
}
|
||||||
|
}
|
||||||
return claims;
|
return claims;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** This site's public key, or null when it can't be made or read (then v1 is used). */
|
||||||
|
async function ownPublicKey() {
|
||||||
|
try {
|
||||||
|
return (await store.keyPair()).publicKeyPem;
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[hub] No key pair for protocol v2, using v1:', e?.message || e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether the Hub refused a v2 body (too old for v2, or a contract it doesn't accept): retry as v1. */
|
||||||
|
function refusedV2(e) {
|
||||||
|
return e instanceof HubError && e.statusCode === 400 && ['UNSUPPORTED_PROTOCOL', 'INVALID_REQUEST'].includes(e.code);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function v1Only() {
|
||||||
|
const until = (await read(['hub_v1_until'])).hub_v1_until;
|
||||||
|
return !!until && new Date(until).getTime() > Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function useV1ForADay() {
|
||||||
|
await save({ hub_v1_until: new Date(Date.now() + V1_FALLBACK_MS).toISOString() });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The health as protocol v2 wants it: every field there (a part that couldn't be read is
|
||||||
|
* reported as nothing wrong rather than left out).
|
||||||
|
*/
|
||||||
|
function v2Health(h) {
|
||||||
|
return {
|
||||||
|
...h,
|
||||||
|
jobs: h.jobs || { mode: 'unknown', failedLast24h: 0 },
|
||||||
|
pendingMigrations: Number.isInteger(h.pendingMigrations) ? h.pendingMigrations : 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The heartbeat body: v2 when it fits the contract (with the public key until the Hub has it),
|
||||||
|
* otherwise v1. Returns { body, v2 }.
|
||||||
|
*/
|
||||||
|
async function heartbeatBody() {
|
||||||
|
const health = await report.health();
|
||||||
|
const stats = await report.stats();
|
||||||
|
const v1 = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health, stats };
|
||||||
|
if (await v1Only()) return { body: v1, v2: false };
|
||||||
|
const publicKeyPem = await ownPublicKey();
|
||||||
|
if (!publicKeyPem) return { body: v1, v2: false };
|
||||||
|
const status = await store.publicKeyStatus().catch(() => null);
|
||||||
|
const v2 = {
|
||||||
|
protocolVersion: HEARTBEAT_PROTOCOL,
|
||||||
|
product: 'events',
|
||||||
|
version: report.APP_VERSION,
|
||||||
|
health: v2Health(health),
|
||||||
|
stats,
|
||||||
|
...(status === 'saved' || status === 'matches' ? {} : { publicKey: publicKeyPem }),
|
||||||
|
};
|
||||||
|
const check = hub.heartbeatRequestSchema.safeParse(v2);
|
||||||
|
if (!check.success) {
|
||||||
|
console.warn('[hub] The v2 heartbeat doesn\'t fit the contract, sending v1:', check.error.issues.slice(0, 3).map(i => `${i.path.join('.')} ${i.message}`).join('; '));
|
||||||
|
return { body: v1, v2: false };
|
||||||
|
}
|
||||||
|
return { body: v2, v2: true };
|
||||||
|
}
|
||||||
|
|
||||||
/** Send a heartbeat (the `hub-heartbeat` job). Skips quietly when not connected. */
|
/** Send a heartbeat (the `hub-heartbeat` job). Skips quietly when not connected. */
|
||||||
async function heartbeat() {
|
async function heartbeat() {
|
||||||
const s = await read(['hub_install_id', 'hub_install_secret']);
|
const s = await read(['hub_install_id', 'hub_install_secret']);
|
||||||
if (!s.hub_install_id || !s.hub_install_secret) return { skipped: 'not connected' };
|
if (!s.hub_install_id || !s.hub_install_secret) return { skipped: 'not connected' };
|
||||||
const body = { protocolVersion: PROTOCOL_VERSION, version: report.APP_VERSION, health: await report.health(), stats: await report.stats() };
|
let { body, v2 } = await heartbeatBody();
|
||||||
try {
|
try {
|
||||||
const data = await signedPost('/api/installs/heartbeat', body);
|
let data;
|
||||||
|
try {
|
||||||
|
data = await signedPost('/api/installs/heartbeat', body);
|
||||||
|
} catch (e) {
|
||||||
|
if (!v2 || !refusedV2(e)) throw e;
|
||||||
|
console.warn(`[hub] The Hub refused a v2 heartbeat (${e.code}: ${e.message}); using v1 for a day.`);
|
||||||
|
await useV1ForADay();
|
||||||
|
({ body, v2 } = await heartbeatBody());
|
||||||
|
data = await signedPost('/api/installs/heartbeat', body);
|
||||||
|
}
|
||||||
|
if (v2) {
|
||||||
|
try {
|
||||||
|
await store.saveLinkedProducts(data.linkedProducts);
|
||||||
|
if (typeof data.publicKeyStatus === 'string') await store.setPublicKeyStatus(data.publicKeyStatus);
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('[hub] Could not save the linked products:', e?.message || e);
|
||||||
|
}
|
||||||
|
}
|
||||||
const claims = verifyToken(data.licence);
|
const claims = verifyToken(data.licence);
|
||||||
await save({
|
await save({
|
||||||
// Keep the old token if the new one doesn't check out (never accept an unverified one).
|
// Keep the old token if the new one doesn't check out (never accept an unverified one).
|
||||||
@@ -137,7 +258,7 @@ async function heartbeat() {
|
|||||||
hub_latest_version: data.latestVersion || null,
|
hub_latest_version: data.latestVersion || null,
|
||||||
...fromHub(data),
|
...fromHub(data),
|
||||||
});
|
});
|
||||||
return { ok: true, status: claims?.status || null };
|
return { ok: true, status: claims?.status || null, protocol: v2 ? 2 : 1 };
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
await save({ hub_last_error: `${new Date().toISOString()} ${e.code || ''} ${e.message}`.slice(0, 500) });
|
await save({ hub_last_error: `${new Date().toISOString()} ${e.code || ''} ${e.message}`.slice(0, 500) });
|
||||||
// The Hub doesn't know this install any more (licence released): drop the connection and the
|
// The Hub doesn't know this install any more (licence released): drop the connection and the
|
||||||
@@ -216,4 +337,33 @@ function heartbeatSoon(delayMs = 30 * 1000) {
|
|||||||
soonTimer.unref?.();
|
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, HEARTBEAT_PROTOCOL, HUB_KEYS, heartbeatBody, hubUrl, HubError, signedPost, connect, connectFromEnv, heartbeat, heartbeatSoon, requestUpdate, cancelUpdateRequest, snoozeUpdate };
|
||||||
|
|||||||
@@ -75,6 +75,14 @@ const JOBS = [
|
|||||||
name: 'hub-heartbeat', label: 'Cross Events Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED',
|
name: 'hub-heartbeat', label: 'Cross Events Hub: heartbeat and licence refresh', cron: '*/15 * * * *', env: 'HUB_HEARTBEAT_ENABLED',
|
||||||
run: () => require('../hub/client').heartbeat(),
|
run: () => require('../hub/client').heartbeat(),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'feed', label: 'Event feed: publish changes (going live, closing, selling out) and tell linked products', cron: '*/5 * * * *', env: 'FEED_JOBS_ENABLED',
|
||||||
|
run: () => require('../feed/notify').refreshAndNotify(new Date()),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'feed-sync', label: 'Linked products: fetch events from the products shown here', cron: '*/15 * * * *', env: 'FEED_JOBS_ENABLED',
|
||||||
|
run: () => require('../feed/sync').syncAll(new Date()),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
name: 'retention', label: 'Retention: delete or anonymise personal information past its retention period', cron: '30 3 * * *', env: 'RETENTION_JOBS_ENABLED',
|
name: 'retention', label: 'Retention: delete or anonymise personal information past its retention period', cron: '30 3 * * *', env: 'RETENTION_JOBS_ENABLED',
|
||||||
run: () => require('../utils/retention').runRetention(new Date()),
|
run: () => require('../utils/retention').runRetention(new Date()),
|
||||||
@@ -147,6 +155,8 @@ function isNoop(value) {
|
|||||||
*/
|
*/
|
||||||
const TASKS = {
|
const TASKS = {
|
||||||
'feedback-send': (data) => require('../utils/feedback').runFeedbackTask(data),
|
'feedback-send': (data) => require('../utils/feedback').runFeedbackTask(data),
|
||||||
|
// A linked product said its events changed (event.changed): fetch its feed now.
|
||||||
|
'feed-sync-link': (data) => require('../feed/sync').syncOne(String(data.installId || '')),
|
||||||
};
|
};
|
||||||
|
|
||||||
async function runTask(name, data) {
|
async function runTask(name, data) {
|
||||||
|
|||||||
@@ -0,0 +1,186 @@
|
|||||||
|
/**
|
||||||
|
* Connect and Disconnect (`crosscode.link/1`, docs/EVENTS-2.4-PLAN.md §2).
|
||||||
|
*
|
||||||
|
* Trust comes from the Hub's list on both sides: a message is accepted only from an install in
|
||||||
|
* this site's own cached `linkedProducts` (same church), signed with the key the Hub listed for
|
||||||
|
* it. The Hub isn't called while connecting. Both sides then hold the same secret, which signs the
|
||||||
|
* calls between them (the `event.changed` webhook).
|
||||||
|
*/
|
||||||
|
import {
|
||||||
|
LINK_PATHS,
|
||||||
|
LINK_SCHEMA,
|
||||||
|
linkConnectedSchema,
|
||||||
|
linkConnectSchema,
|
||||||
|
linkDisconnectSchema,
|
||||||
|
type LinkConnect,
|
||||||
|
type LinkConnected,
|
||||||
|
type LinkDisconnect,
|
||||||
|
type hub,
|
||||||
|
} from '@crosscode/contracts';
|
||||||
|
import { newLinkNonce, newLinkSecret, signLink, verifyLink } from '@crosscode/contracts/signing';
|
||||||
|
import { hubInstallId, siteUrl } from '../feed/context';
|
||||||
|
import { callSibling, LinkCallError, siblingUrl } from './http';
|
||||||
|
import { keyPair, listedProduct } from './store';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { encrypt } = require('../utils/encryption') as { encrypt(v: string): string };
|
||||||
|
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
export class LinkError extends Error {
|
||||||
|
constructor(message: string, public code: string, public status = 400) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const NONCE_KEEP_MS = 60 * 60 * 1000;
|
||||||
|
|
||||||
|
type Self = { installId: string; url: string; privateKeyPem: string };
|
||||||
|
|
||||||
|
async function self(): Promise<Self> {
|
||||||
|
const installId = await hubInstallId();
|
||||||
|
if (!installId) throw new LinkError('This site isn\'t connected to the Hub, so it can\'t link to other products yet.', 'LINKS_UNAVAILABLE', 503);
|
||||||
|
const url = await siteUrl();
|
||||||
|
if (!/^https?:\/\//.test(url)) throw new LinkError('Set the site\'s web address first (Site settings → Organisation).', 'LINKS_UNAVAILABLE', 503);
|
||||||
|
const { privateKeyPem } = await keyPair();
|
||||||
|
return { installId, url, privateKeyPem };
|
||||||
|
}
|
||||||
|
|
||||||
|
const party = (s: Self) => ({ product: 'events' as const, installId: s.installId, url: s.url });
|
||||||
|
|
||||||
|
/** Records a nonce; false when it was seen before (a replay). Old nonces are cleaned up. */
|
||||||
|
async function firstUse(nonce: string, now: Date): Promise<boolean> {
|
||||||
|
await prisma.linkNonce.deleteMany({ where: { seenAt: { lt: new Date(now.getTime() - NONCE_KEEP_MS) } } }).catch(() => {});
|
||||||
|
try {
|
||||||
|
await prisma.linkNonce.create({ data: { nonce, seenAt: now } });
|
||||||
|
return true;
|
||||||
|
} catch (e) {
|
||||||
|
if ((e as { code?: string })?.code === 'P2002') return false;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function audit(action: string, link: { installId: string; product: string }, actor: { id: string; role: string } | null, ip: string | null, metadata: object = {}) {
|
||||||
|
await logAdminAction({
|
||||||
|
actorId: actor?.id ?? null,
|
||||||
|
actorRole: actor?.role ?? 'linked_product',
|
||||||
|
action,
|
||||||
|
targetType: 'product_link',
|
||||||
|
targetId: link.installId,
|
||||||
|
metadata: { product: link.product, ...metadata },
|
||||||
|
ip,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveLink(sibling: hub.LinkedProduct, secret: string, connectedById: string | null, now: Date) {
|
||||||
|
const data = { product: sibling.product, url: sibling.url, publicKey: sibling.publicKey, secret: encrypt(secret), connectedAt: now, connectedById, lastSyncError: null };
|
||||||
|
return prisma.productLink.upsert({ where: { installId: sibling.installId }, create: { installId: sibling.installId, ...data }, update: data });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── This site connects (an admin clicked Connect) ─────────────────────────────
|
||||||
|
|
||||||
|
export async function connectTo(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()) {
|
||||||
|
const sibling = await listedProduct(installId);
|
||||||
|
if (!sibling) throw new LinkError('That product isn\'t in the list the Hub gave this site. Wait for the next Hub heartbeat (up to 15 minutes).', 'NOT_LINKED', 404);
|
||||||
|
const me = await self();
|
||||||
|
const secret = newLinkSecret();
|
||||||
|
const message = signLink<Omit<LinkConnect, 'signature'>>({
|
||||||
|
schema: LINK_SCHEMA,
|
||||||
|
type: 'link.connect',
|
||||||
|
from: party(me),
|
||||||
|
to: { installId: sibling.installId },
|
||||||
|
secret,
|
||||||
|
issuedAt: now.toISOString(),
|
||||||
|
nonce: newLinkNonce(),
|
||||||
|
}, me.privateKeyPem);
|
||||||
|
|
||||||
|
let reply: unknown;
|
||||||
|
try {
|
||||||
|
reply = await callSibling(await siblingUrl(sibling.url, LINK_PATHS.connect), { method: 'POST', body: JSON.stringify(message) });
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof LinkCallError) throw new LinkError(`${sibling.url} refused to connect: ${e.message}`, e.code, 502);
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
const parsed = linkConnectedSchema.safeParse(reply);
|
||||||
|
if (!parsed.success) throw new LinkError(`${sibling.url} answered in a way this site doesn't understand.`, 'BAD_REPLY', 502);
|
||||||
|
const r: LinkConnected = parsed.data;
|
||||||
|
const check = verifyLink(r as unknown as Record<string, unknown>, sibling.publicKey, { now: new Date() });
|
||||||
|
if (!check.ok || r.inReplyTo !== message.nonce || r.from.installId !== sibling.installId || r.to.installId !== me.installId) {
|
||||||
|
throw new LinkError(`${sibling.url}'s answer isn't signed with the key the Hub listed for it.`, 'BAD_SIGNATURE', 502);
|
||||||
|
}
|
||||||
|
const link = await saveLink(sibling, secret, actor.id, now);
|
||||||
|
await audit('product_link_connected', link, actor, ip, { by: 'this_site' });
|
||||||
|
return link;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── A sibling connects to this site ───────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Answers `POST /api/links/v1/connect`. Throws LinkError (with the code the sibling is told). */
|
||||||
|
export async function acceptConnect(body: unknown, ip: string | null, now = new Date()): Promise<LinkConnected> {
|
||||||
|
const parsed = linkConnectSchema.safeParse(body);
|
||||||
|
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 connect message.', 'INVALID_REQUEST', 400);
|
||||||
|
const m = parsed.data;
|
||||||
|
const me = await self();
|
||||||
|
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||||
|
const sibling = await listedProduct(m.from.installId);
|
||||||
|
if (!sibling || sibling.product !== m.from.product) {
|
||||||
|
throw new LinkError('This site doesn\'t know that install yet: the Hub lists the church\'s products in its next heartbeat (up to 15 minutes).', 'NOT_LINKED', 403);
|
||||||
|
}
|
||||||
|
const check = verifyLink(m as unknown as Record<string, unknown>, sibling.publicKey, { now });
|
||||||
|
if (!check.ok) throw new LinkError(check.code === 'STALE_REQUEST' ? 'The message is too old, or a clock is wrong.' : 'The signature doesn\'t match the key the Hub listed.', check.code, 401);
|
||||||
|
if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||||
|
|
||||||
|
const link = await saveLink(sibling, m.secret, null, now);
|
||||||
|
await audit('product_link_connected', link, null, ip, { by: 'sibling' });
|
||||||
|
return signLink<Omit<LinkConnected, 'signature'>>({
|
||||||
|
schema: LINK_SCHEMA,
|
||||||
|
type: 'link.connected',
|
||||||
|
from: party(me),
|
||||||
|
to: { installId: sibling.installId },
|
||||||
|
inReplyTo: m.nonce,
|
||||||
|
issuedAt: new Date().toISOString(),
|
||||||
|
nonce: newLinkNonce(),
|
||||||
|
}, me.privateKeyPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Disconnect ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** This site ends a link. The local link goes even if the sibling can't be reached. */
|
||||||
|
export async function disconnectFrom(installId: string, actor: { id: string; role: string }, ip: string | null, now = new Date()): Promise<{ siblingTold: boolean; message: string | null }> {
|
||||||
|
const link = await prisma.productLink.findUnique({ where: { installId } });
|
||||||
|
if (!link) throw new LinkError('That product isn\'t connected.', 'NOT_LINKED', 404);
|
||||||
|
let siblingTold = false;
|
||||||
|
let problem: string | null = null;
|
||||||
|
try {
|
||||||
|
const me = await self();
|
||||||
|
const message = signLink<Omit<LinkDisconnect, 'signature'>>({
|
||||||
|
schema: LINK_SCHEMA, type: 'link.disconnect', from: party(me), to: { installId }, issuedAt: now.toISOString(), nonce: newLinkNonce(),
|
||||||
|
}, me.privateKeyPem);
|
||||||
|
await callSibling(await siblingUrl(link.url, LINK_PATHS.disconnect), { method: 'POST', body: JSON.stringify(message) });
|
||||||
|
siblingTold = true;
|
||||||
|
} catch (e) {
|
||||||
|
problem = (e as Error).message;
|
||||||
|
}
|
||||||
|
// Its imported events go with it (ImportedEvent cascades).
|
||||||
|
await prisma.productLink.delete({ where: { installId } });
|
||||||
|
await audit('product_link_disconnected', link, actor, ip, { by: 'this_site', siblingTold });
|
||||||
|
return { siblingTold, message: problem };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Answers `POST /api/links/v1/disconnect`, checked against the key saved when the link was made. */
|
||||||
|
export async function acceptDisconnect(body: unknown, ip: string | null, now = new Date()): Promise<void> {
|
||||||
|
const parsed = linkDisconnectSchema.safeParse(body);
|
||||||
|
if (!parsed.success) throw new LinkError('That isn\'t a crosscode.link/1 disconnect message.', 'INVALID_REQUEST', 400);
|
||||||
|
const m = parsed.data;
|
||||||
|
const me = await self();
|
||||||
|
if (m.to.installId !== me.installId) throw new LinkError('That message is for another install.', 'WRONG_INSTALL', 400);
|
||||||
|
const link = await prisma.productLink.findUnique({ where: { installId: m.from.installId } });
|
||||||
|
// Already gone: nothing to do, and nothing to tell (the sibling just wants it ended).
|
||||||
|
if (!link) return;
|
||||||
|
const check = verifyLink(m as unknown as Record<string, unknown>, link.publicKey, { now });
|
||||||
|
if (!check.ok) throw new LinkError('The signature doesn\'t match this link.', check.code, 401);
|
||||||
|
if (!(await firstUse(m.nonce, now))) throw new LinkError('That message was already used.', 'REPLAYED', 409);
|
||||||
|
await prisma.productLink.delete({ where: { installId: link.installId } });
|
||||||
|
await audit('product_link_disconnected', link, null, ip, { by: 'sibling' });
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
/**
|
||||||
|
* Calls to a linked product: only to a public https address the Hub listed (the same rule as
|
||||||
|
* outbound webhooks, utils/webhooks.js: private addresses refused unless WEBHOOKS_ALLOW_PRIVATE
|
||||||
|
* is set for local testing), redirects not followed, a timeout, and a size limit on the answer.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const { assertPublicHost } = require('../utils/webhooks') as { assertPublicHost(hostname: string): Promise<void> };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
export const TIMEOUT_MS = 15000;
|
||||||
|
const MAX_BYTES = 5 * 1024 * 1024;
|
||||||
|
|
||||||
|
export class LinkCallError extends Error {
|
||||||
|
constructor(message: string, public code: string, public status = 502, public data: unknown = null) {
|
||||||
|
super(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const allowHttp = () => String(process.env.WEBHOOKS_ALLOW_PRIVATE || '').toLowerCase() === 'true';
|
||||||
|
|
||||||
|
/** The address of `path` on a sibling, after checking where it points. */
|
||||||
|
export async function siblingUrl(base: string, path: string, query: Record<string, string> = {}): Promise<URL> {
|
||||||
|
let url: URL;
|
||||||
|
try {
|
||||||
|
url = new URL(path, base.endsWith('/') ? base : `${base}/`);
|
||||||
|
} catch {
|
||||||
|
throw new LinkCallError(`${base} isn't a web address`, 'BAD_ADDRESS', 400);
|
||||||
|
}
|
||||||
|
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && allowHttp())) throw new LinkCallError(`${base} doesn't use https`, 'BAD_ADDRESS', 400);
|
||||||
|
for (const [k, v] of Object.entries(query)) url.searchParams.set(k, v);
|
||||||
|
try {
|
||||||
|
await assertPublicHost(url.hostname);
|
||||||
|
} catch (e) {
|
||||||
|
throw new LinkCallError((e as Error).message, 'PRIVATE_ADDRESS', 400);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readLimited(res: Response): Promise<string> {
|
||||||
|
const length = Number(res.headers.get('content-length') || 0);
|
||||||
|
if (length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||||
|
const text = await res.text();
|
||||||
|
if (text.length > MAX_BYTES) throw new LinkCallError('The answer is too large', 'TOO_LARGE');
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A JSON request to a sibling. Throws LinkCallError with the sibling's own message and code on a 4xx/5xx. */
|
||||||
|
export async function callSibling(url: URL, init: { method: 'GET' | 'POST'; body?: string; headers?: Record<string, string> }): Promise<unknown> {
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await fetch(url, {
|
||||||
|
method: init.method,
|
||||||
|
headers: { Accept: 'application/json', ...(init.body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...init.headers },
|
||||||
|
body: init.body,
|
||||||
|
redirect: 'manual',
|
||||||
|
signal: AbortSignal.timeout(TIMEOUT_MS),
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
throw new LinkCallError(`${url.host} could not be reached: ${(e as Error)?.message || e}`, 'UNREACHABLE');
|
||||||
|
}
|
||||||
|
if (res.status >= 300 && res.status < 400) throw new LinkCallError(`${url.host} answered with a redirect`, 'REDIRECTED');
|
||||||
|
const text = await readLimited(res);
|
||||||
|
let data: unknown = null;
|
||||||
|
try {
|
||||||
|
data = text ? JSON.parse(text) : null;
|
||||||
|
} catch {
|
||||||
|
if (res.ok) throw new LinkCallError(`${url.host} didn't answer with JSON`, 'NOT_JSON');
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
const d = (data && typeof data === 'object' ? data : {}) as { message?: string; code?: string; error?: { message?: string; code?: string } };
|
||||||
|
throw new LinkCallError(d.message || d.error?.message || `${url.host} answered ${res.status}`, d.code || d.error?.code || `HTTP_${res.status}`, res.status >= 500 ? 502 : res.status, data);
|
||||||
|
}
|
||||||
|
return data;
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
/**
|
||||||
|
* The endpoints the church's other products call (docs/EVENTS-2.4-PLAN.md §2–4). Contracts
|
||||||
|
* between products, so outside /api/v2, with errors as `{ message, code }`:
|
||||||
|
*
|
||||||
|
* GET /api/feed/v1/events?updatedSince= crosscode.event-feed/1 (public; "Publish my events")
|
||||||
|
* POST /api/feed/v1/changed event.changed from a linked product (LINK_HEADERS)
|
||||||
|
* POST /api/links/v1/connect crosscode.link/1 link.connect → link.connected
|
||||||
|
* POST /api/links/v1/disconnect crosscode.link/1 link.disconnect → link.disconnected
|
||||||
|
*
|
||||||
|
* Mounted before the app's JSON parser: the webhook is verified on its raw bytes.
|
||||||
|
*/
|
||||||
|
import express, { type Request, type Response, type Router } from 'express';
|
||||||
|
import rateLimit from 'express-rate-limit';
|
||||||
|
import { eventChangedSchema, FEED_PATHS, LINK_PATHS, LINK_SCHEMA } from '@crosscode/contracts';
|
||||||
|
import { LINK_HEADERS, verify } from '@crosscode/contracts/signing';
|
||||||
|
import { hubInstallId, publishOn } from '../feed/context';
|
||||||
|
import { feedResponse, lastRefresh, refreshOnce } from '../feed/entries';
|
||||||
|
import { acceptConnect, acceptDisconnect, LinkError } from './connect';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
|
||||||
|
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: Request): string | null };
|
||||||
|
const { enqueueTask } = require('../jobs') as { enqueueTask(name: string, data: object): Promise<unknown> };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
/** The feed is rebuilt before answering when the last refresh is older than this. */
|
||||||
|
const FRESH_MS = 60 * 1000;
|
||||||
|
|
||||||
|
const fail = (res: Response, status: number, code: string, message: string) => res.status(status).json({ message, code });
|
||||||
|
|
||||||
|
function sendError(res: Response, e: unknown) {
|
||||||
|
if (e instanceof LinkError) return fail(res, e.status, e.code, e.message);
|
||||||
|
console.error('[links]', e);
|
||||||
|
return fail(res, 500, 'SERVER_ERROR', 'Something went wrong.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const limiter = (max: number) => rateLimit({ windowMs: 5 * 60 * 1000, max, standardHeaders: true, legacyHeaders: false, message: { message: 'Too many requests, please try again later.', code: 'RATE_LIMITED' } });
|
||||||
|
|
||||||
|
export function crossProductRouter(): Router {
|
||||||
|
const router = express.Router();
|
||||||
|
const json = express.json({ limit: '16kb' });
|
||||||
|
|
||||||
|
router.get(FEED_PATHS.events.replace(/^\/api/, ''), limiter(300), async (req, res) => {
|
||||||
|
try {
|
||||||
|
if (!(await publishOn())) return fail(res, 404, 'FEED_OFF', 'This site doesn\'t publish its events (Settings → Linked products).');
|
||||||
|
if (!(await hubInstallId())) return fail(res, 503, 'FEED_UNAVAILABLE', 'This site isn\'t connected to the Hub yet, so it has no feed.');
|
||||||
|
const raw = typeof req.query.updatedSince === 'string' ? req.query.updatedSince : null;
|
||||||
|
const since = raw ? new Date(raw) : null;
|
||||||
|
if (raw && (!since || !Number.isFinite(since.getTime()))) return fail(res, 400, 'INVALID_REQUEST', 'updatedSince must be an ISO 8601 date and time.');
|
||||||
|
if (Date.now() - lastRefresh() > FRESH_MS) await refreshOnce();
|
||||||
|
res.set('Cache-Control', 'no-store');
|
||||||
|
return res.json(await feedResponse(since));
|
||||||
|
} catch (e) {
|
||||||
|
return sendError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post(FEED_PATHS.changed.replace(/^\/api/, ''), limiter(300), express.raw({ type: () => true, limit: '16kb' }), async (req, res) => {
|
||||||
|
try {
|
||||||
|
const sender = String(req.get(LINK_HEADERS.sender) || '');
|
||||||
|
const link = sender ? await prisma.productLink.findUnique({ where: { installId: sender } }) : null;
|
||||||
|
if (!link) return fail(res, 404, 'NOT_LINKED', 'This site has no link with that install.');
|
||||||
|
const rawBody: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
|
||||||
|
const check = verify({ secret: decrypt(link.secret), timestamp: req.get(LINK_HEADERS.timestamp), signature: req.get(LINK_HEADERS.signature), rawBody });
|
||||||
|
if (!check.ok) return fail(res, 401, check.code, 'The signature doesn\'t match this link.');
|
||||||
|
let body: unknown;
|
||||||
|
try { body = JSON.parse(rawBody.toString('utf8')); } catch { body = null; }
|
||||||
|
if (!eventChangedSchema.safeParse(body).success) return fail(res, 400, 'INVALID_REQUEST', 'That isn\'t an event.changed message.');
|
||||||
|
if (link.showEvents) await enqueueTask('feed-sync-link', { installId: link.installId });
|
||||||
|
return res.status(202).json({ accepted: true, fetching: link.showEvents });
|
||||||
|
} catch (e) {
|
||||||
|
return sendError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post(LINK_PATHS.connect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
|
||||||
|
try {
|
||||||
|
return res.json(await acceptConnect(req.body, getClientIp(req)));
|
||||||
|
} catch (e) {
|
||||||
|
return sendError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post(LINK_PATHS.disconnect.replace(/^\/api/, ''), limiter(30), json, async (req, res) => {
|
||||||
|
try {
|
||||||
|
await acceptDisconnect(req.body, getClientIp(req));
|
||||||
|
return res.json({ schema: LINK_SCHEMA, type: 'link.disconnected' });
|
||||||
|
} catch (e) {
|
||||||
|
return sendError(res, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// A body that isn't JSON (express.json's own error) answers in the same shape.
|
||||||
|
router.use((err: { type?: string; status?: number }, _req: Request, res: Response, next: (e?: unknown) => void) => {
|
||||||
|
if (err?.type === 'entity.parse.failed' || err?.type === 'entity.too.large') return fail(res, err.status || 400, 'INVALID_REQUEST', 'The body must be JSON (16 kB at most).');
|
||||||
|
return next(err);
|
||||||
|
});
|
||||||
|
return router;
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
/**
|
||||||
|
* This site's Ed25519 key pair and the church's other products as the Hub last listed them
|
||||||
|
* (docs/EVENTS-2.4-PLAN.md §1–2). Kept in AppSetting, out of the generic settings endpoints
|
||||||
|
* (hub/client.js HUB_KEYS):
|
||||||
|
* hub_private_key (encrypted PKCS#8 PEM), hub_public_key (SPKI PEM), hub_public_key_status
|
||||||
|
* (the Hub's last publicKeyStatus), hub_linked_products (JSON, from the last heartbeat).
|
||||||
|
* The key pair is made once and never changed: the Hub keeps the first key it saw, and every
|
||||||
|
* linked product checks this site's messages against it.
|
||||||
|
*/
|
||||||
|
import { hub } from '@crosscode/contracts';
|
||||||
|
import { ed25519PublicToPem, generateEd25519 } from '@crosscode/contracts/signing';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../config/db');
|
||||||
|
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
type LinkedProduct = hub.LinkedProduct;
|
||||||
|
|
||||||
|
export const KEY_SETTINGS = ['hub_private_key', 'hub_public_key', 'hub_public_key_status', 'hub_linked_products'] as const;
|
||||||
|
|
||||||
|
async function read(key: string): Promise<string | null> {
|
||||||
|
const row = await prisma.appSetting.findUnique({ where: { key } });
|
||||||
|
return row?.value ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function write(key: string, value: string | null): Promise<void> {
|
||||||
|
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
|
||||||
|
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
|
||||||
|
}
|
||||||
|
|
||||||
|
let made: Promise<{ publicKeyPem: string; privateKeyPem: string }> | null = null;
|
||||||
|
|
||||||
|
/** This site's key pair, made the first time it's needed. */
|
||||||
|
export function keyPair(): Promise<{ publicKeyPem: string; privateKeyPem: string }> {
|
||||||
|
if (!made) {
|
||||||
|
made = (async () => {
|
||||||
|
const [priv, pub] = await Promise.all([read('hub_private_key'), read('hub_public_key')]);
|
||||||
|
if (priv && pub) return { privateKeyPem: decrypt(priv), publicKeyPem: pub };
|
||||||
|
const pair = generateEd25519();
|
||||||
|
const publicKeyPem = ed25519PublicToPem(pair.publicKey);
|
||||||
|
await write('hub_private_key', encrypt(pair.privateKeyPem));
|
||||||
|
await write('hub_public_key', publicKeyPem);
|
||||||
|
return { privateKeyPem: pair.privateKeyPem, publicKeyPem };
|
||||||
|
})().catch((e) => {
|
||||||
|
made = null;
|
||||||
|
throw e;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return made;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** For tests. */
|
||||||
|
export function forgetKeyPair(): void {
|
||||||
|
made = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `saved` / `matches` / `mismatch` from the Hub, or null (not sent yet, or a Hub before 2.2.0). */
|
||||||
|
export async function publicKeyStatus(): Promise<string | null> {
|
||||||
|
return read('hub_public_key_status');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setPublicKeyStatus(status: string | null): Promise<void> {
|
||||||
|
await write('hub_public_key_status', status);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The church's other installs as the Hub last listed them (an empty list if it never did). */
|
||||||
|
export async function linkedProducts(): Promise<LinkedProduct[]> {
|
||||||
|
const raw = await read('hub_linked_products');
|
||||||
|
if (!raw) return [];
|
||||||
|
try {
|
||||||
|
const list = JSON.parse(raw);
|
||||||
|
return Array.isArray(list) ? list.filter((l) => hub.linkedProductSchema.safeParse(l).success) : [];
|
||||||
|
} catch {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saves the list from a v2 heartbeat or register reply. Entries that don't fit the contract are left out. */
|
||||||
|
export async function saveLinkedProducts(list: unknown): Promise<LinkedProduct[]> {
|
||||||
|
if (!Array.isArray(list)) return linkedProducts();
|
||||||
|
const clean = list.map((l) => hub.linkedProductSchema.safeParse(l)).filter((r) => r.success).map((r) => r.data as LinkedProduct).slice(0, 10);
|
||||||
|
await write('hub_linked_products', JSON.stringify(clean));
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listedProduct(installId: string): Promise<LinkedProduct | null> {
|
||||||
|
return (await linkedProducts()).find((l) => l.installId === installId) ?? null;
|
||||||
|
}
|
||||||
@@ -16,7 +16,8 @@ const auth = require('../config/auth') as {
|
|||||||
};
|
};
|
||||||
const twoFactor = require('../utils/twoFactor') as {
|
const twoFactor = require('../utils/twoFactor') as {
|
||||||
createChallenge(user: any, purpose: string, method: string): Promise<{ challengeId: string; method: string; destination: string | null }>;
|
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>;
|
issueTrustedDevice(userId: string, userAgent?: string): Promise<string>;
|
||||||
isTrustedDevice(userId: string, deviceToken?: string): Promise<boolean>;
|
isTrustedDevice(userId: string, deviceToken?: string): Promise<boolean>;
|
||||||
clearTrustedDevices(userId: string): Promise<unknown>;
|
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 });
|
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(() => {});
|
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) } : {};
|
const extra = input.rememberDevice === true ? { deviceToken: await twoFactor.issueTrustedDevice(user.id, info.userAgent) } : {};
|
||||||
return completeLogin(user, info, extra);
|
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;
|
||||||
|
}
|
||||||
@@ -91,6 +91,13 @@ async function readiness(now = new Date(), db = prisma) {
|
|||||||
lastBackup ? `Last backup ${new Date(lastBackup).toLocaleString('en-ZA')}` : 'No backups found on this server.',
|
lastBackup ? `Last backup ${new Date(lastBackup).toLocaleString('en-ZA')}` : 'No backups found on this server.',
|
||||||
'/dashboard/admin/settings?tab=backups');
|
'/dashboard/admin/settings?tab=backups');
|
||||||
|
|
||||||
|
// Linked products (2.4.0): a product whose events are shown here, but that hasn't answered for a day.
|
||||||
|
const shown = await (db.productLink?.findMany({ where: { showEvents: true }, select: { url: true, lastGoodAt: true, lastSyncError: true, connectedAt: true } }) ?? Promise.resolve([])).catch(() => []);
|
||||||
|
const stale = shown.filter(l => l.lastSyncError && now - new Date(l.lastGoodAt || l.connectedAt) > DAY);
|
||||||
|
add('linked_sync', 'Events from linked products are up to date', stale.length === 0,
|
||||||
|
stale.length ? `Not fetched for over a day: ${stale.map(l => l.url).join(', ')}. Their last events keep showing.` : `${shown.length} product${shown.length === 1 ? '' : 's'} fetched in the last day`,
|
||||||
|
'/dashboard/admin/settings?tab=linked', shown.length > 0);
|
||||||
|
|
||||||
const applicable = checks.filter(c => c.applies);
|
const applicable = checks.filter(c => c.applies);
|
||||||
const passed = applicable.filter(c => c.ok).length;
|
const passed = applicable.filter(c => c.ok).length;
|
||||||
return { score: applicable.length ? Math.round((passed / applicable.length) * 100) : 0, passed, total: applicable.length, checks };
|
return { score: applicable.length ? Math.round((passed / applicable.length) * 100) : 0, passed, total: applicable.length, checks };
|
||||||
|
|||||||
@@ -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 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 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.
|
// Roles that must use two-factor authentication.
|
||||||
const REQUIRED_ROLES = ['admin', 'supervisor'];
|
const REQUIRED_ROLES = ['admin', 'supervisor'];
|
||||||
@@ -67,9 +69,75 @@ async function availableMethods(user) {
|
|||||||
const methods = [];
|
const methods = [];
|
||||||
if (hasRealEmail(user)) methods.push('email');
|
if (hasRealEmail(user)) methods.push('email');
|
||||||
if (isValidZAPhone(user?.phoneNumber) && (await isConfigured())) methods.push('whatsapp');
|
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;
|
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.
|
* True when this user's role must use two-factor authentication.
|
||||||
* TWO_FACTOR_REQUIRED_ROLES=false turns the requirement off (break-glass).
|
* 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.
|
* purpose for this user is discarded, so only the newest code works.
|
||||||
*/
|
*/
|
||||||
async function createChallenge(user, purpose, method, options) {
|
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 code = generateCode();
|
||||||
const sent = await deliverCode(user, method, code, options);
|
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();
|
if (counted.count !== 1) throw invalid();
|
||||||
|
|
||||||
const challenge = await prisma.twoFactorChallenge.findUnique({ where: { id: challengeId }, include: { user: true } });
|
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;
|
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.
|
// 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();
|
if (used.count !== 1) throw invalid();
|
||||||
|
|
||||||
return challenge;
|
return { ...challenge, usedRecoveryCode };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Replaces the code on an existing challenge and sends it again. */
|
/** 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 } });
|
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 (!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 (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());
|
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);
|
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 = {
|
module.exports = {
|
||||||
METHODS,
|
METHODS,
|
||||||
|
RECOVERY_CODE_COUNT,
|
||||||
|
replaceRecoveryCodes,
|
||||||
|
recoveryCodesLeft,
|
||||||
|
useRecoveryCode,
|
||||||
|
useAuthenticatorCode,
|
||||||
|
clearTwoFactor,
|
||||||
|
newAuthenticatorSecret,
|
||||||
REQUIRED_ROLES,
|
REQUIRED_ROLES,
|
||||||
requiresTwoFactor,
|
requiresTwoFactor,
|
||||||
enforcementMethod,
|
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.`
|
`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();
|
const { token, instanceId } = await getConfig();
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ export const user = obj({
|
|||||||
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
|
role: z.enum(['admin', 'supervisor', 'staff', 'user']),
|
||||||
isActive: optBool,
|
isActive: optBool,
|
||||||
notificationPreference: z.enum(['email', 'whatsapp', 'both']).nullish(),
|
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,
|
homeCampusId: optStr,
|
||||||
createdAt: optDate,
|
createdAt: optDate,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import './resources/checkin';
|
|||||||
import './resources/auth';
|
import './resources/auth';
|
||||||
import './resources/ai';
|
import './resources/ai';
|
||||||
import './resources/feedback';
|
import './resources/feedback';
|
||||||
|
import './resources/linkedProducts';
|
||||||
|
|
||||||
const pkg = require('../../package.json') as { version: string };
|
const pkg = require('../../package.json') as { version: string };
|
||||||
|
|
||||||
@@ -43,7 +44,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.
|
* public; it asks for an admin token and uses it to load openapi.json and to try requests.
|
||||||
*/
|
*/
|
||||||
export function v2DocsRouter(): Router {
|
export function v2DocsRouter(): Router {
|
||||||
@@ -62,7 +63,7 @@ const DOCS_HTML = `<!doctype html>
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>Cross Events API v2</title>
|
<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>
|
<style>
|
||||||
body { margin: 0; font-family: system-ui, sans-serif; }
|
body { margin: 0; font-family: system-ui, sans-serif; }
|
||||||
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
#login { max-width: 40rem; margin: 3rem auto; padding: 0 1rem; }
|
||||||
@@ -81,7 +82,7 @@ const DOCS_HTML = `<!doctype html>
|
|||||||
<p class="err" id="err" role="alert"></p>
|
<p class="err" id="err" role="alert"></p>
|
||||||
</main>
|
</main>
|
||||||
<div id="ui"></div>
|
<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>
|
<script>
|
||||||
(function () {
|
(function () {
|
||||||
var params = new URLSearchParams(location.search);
|
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. */
|
/** 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) => {
|
export const v1Removed: RequestHandler = (req, res, next) => {
|
||||||
if (req.path === '/v2' || req.path.startsWith('/v2/')) return 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) => {
|
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
|
* 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>;
|
type JsonSchema = Record<string, unknown>;
|
||||||
|
|||||||
@@ -21,9 +21,11 @@ const status = z.object({
|
|||||||
enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'),
|
enabled: z.boolean().describe('false: hide the AI buttons (the licence has no AI, or the site isn\'t connected to the Hub)'),
|
||||||
capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'),
|
capReached: z.boolean().describe('true: show the buttons disabled until `renewsOn`'),
|
||||||
available: z.boolean().describe('false: the Hub couldn\'t be reached just now'),
|
available: z.boolean().describe('false: the Hub couldn\'t be reached just now'),
|
||||||
capCents: z.number().describe('The monthly allowance, in cents'),
|
usedPercent: z.number().describe('How much of this month\'s allowance is used (0–100)'),
|
||||||
usedCents: z.number().describe('Used this month, in cents (fractions of a cent)'),
|
usedInputTokens: z.number().int().nullable().describe('Input tokens used this month by all the church\'s products (null from a Hub before 2.0.1)'),
|
||||||
usedPercent: z.number(),
|
usedOutputTokens: z.number().int().nullable().describe('Output tokens used this month'),
|
||||||
|
capInputTokens: z.number().int().nullable().describe('About how many input tokens the monthly allowance holds, if half of it went on input (an estimate: cached prompts cost less)'),
|
||||||
|
capOutputTokens: z.number().int().nullable().describe('About how many output tokens the allowance holds, if half of it went on output'),
|
||||||
renewsOn: z.string().nullable().describe('YYYY-MM-DD'),
|
renewsOn: z.string().nullable().describe('YYYY-MM-DD'),
|
||||||
helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'),
|
helpers: helperFlags.describe('Each helper switched on or off in Site settings → AI'),
|
||||||
});
|
});
|
||||||
@@ -33,7 +35,7 @@ const settings = z.object({
|
|||||||
dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'),
|
dailyLimitPerPerson: z.number().int().min(0).max(1000).describe('0 = no limit'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const use = z.object({ uses: z.number().int(), chargedCents: z.number() });
|
const use = z.object({ uses: z.number().int(), inputTokens: z.number().int(), outputTokens: z.number().int() });
|
||||||
|
|
||||||
export const getAiStatus = defineRoute({
|
export const getAiStatus = defineRoute({
|
||||||
method: 'get',
|
method: 'get',
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { single } from '../paging';
|
|||||||
import { absoluteUrl, id, idParams, isoDate } from '../schemas';
|
import { absoluteUrl, id, idParams, isoDate } from '../schemas';
|
||||||
import * as details from '../../services/eventDetails';
|
import * as details from '../../services/eventDetails';
|
||||||
import { managedEvent } from './eventsManage';
|
import { managedEvent } from './eventsManage';
|
||||||
|
import { crosscodeEventFor } from '../../feed/build';
|
||||||
|
|
||||||
/* eslint-disable @typescript-eslint/no-explicit-any -- stored records are passed through */
|
/* eslint-disable @typescript-eslint/no-explicit-any -- stored records are passed through */
|
||||||
const campusScope = require('../../utils/campusScope') as {
|
const campusScope = require('../../utils/campusScope') as {
|
||||||
@@ -35,9 +36,15 @@ export const full = defineRoute({
|
|||||||
response: single(managedEvent.extend({
|
response: single(managedEvent.extend({
|
||||||
form: z.looseObject({ id, isRequired: z.boolean(), fields: z.array(z.looseObject({ id, type: z.string(), label: z.string() })) }).nullable(),
|
form: z.looseObject({ id, isRequired: z.boolean(), fields: z.array(z.looseObject({ id, type: z.string(), label: z.string() })) }).nullable(),
|
||||||
attachments: z.array(z.looseObject({ id, originalName: z.string(), url: z.string().nullable() })),
|
attachments: z.array(z.looseObject({ id, originalName: z.string(), url: z.string().nullable() })),
|
||||||
|
crosscodeEvent: z.looseObject({ schema: z.literal('crosscode.event/1'), id }).nullable()
|
||||||
|
.describe('The event as crosscode.event/1 (2.4.0), what its page builds its schema.org JSON-LD from (@crosscode/seo). The same shape the event feed publishes.'),
|
||||||
|
priceRangeCents: z.object({ lowCents: z.number().int(), highCents: z.number().int() }).nullable()
|
||||||
|
.describe('The lowest and highest current ticket prices in cents, for the JSON-LD price range (null when free)'),
|
||||||
})),
|
})),
|
||||||
async handler({ params, user, req }) {
|
async handler({ params, user, req }) {
|
||||||
return { data: plain(await details.getEventDetail(params.id, await viewerOf(req, user), urlOf(req))) };
|
const detail = plain(await details.getEventDetail(params.id, await viewerOf(req, user), urlOf(req)));
|
||||||
|
const built = await crosscodeEventFor(params.id).catch(() => null);
|
||||||
|
return { data: { ...detail, crosscodeEvent: built?.event ?? null, priceRangeCents: built?.priceRangeCents ?? null } };
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,277 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { defineRoute } from '../route';
|
||||||
|
import { ApiError, notFound } from '../errors';
|
||||||
|
import { single } from '../paging';
|
||||||
|
import { iso, isoDate } from '../schemas';
|
||||||
|
import { connectTo, disconnectFrom, LinkError } from '../../links/connect';
|
||||||
|
import { linkedProducts, publicKeyStatus } from '../../links/store';
|
||||||
|
import { hubInstallId, PUBLISH_KEY, publishOn } from '../../feed/context';
|
||||||
|
import { syncLink } from '../../feed/sync';
|
||||||
|
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
|
||||||
|
const prisma = require('../../config/db');
|
||||||
|
const { invalidate } = require('../../utils/settingsCache') as { invalidate(key?: string): void };
|
||||||
|
const { logAdminAction } = require('../../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
|
||||||
|
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string | null };
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings → Linked products (2.4.0, docs/EVENTS-2.4-PLAN.md §2, §4, §6): the church's other
|
||||||
|
* products as the Hub lists them, Connect / Disconnect, "Show events from" per product and
|
||||||
|
* "Publish my events" for this site. And, for the public pages, the events imported from them.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const PRODUCT_NAMES: Record<string, string> = { events: 'Cross Events', website: 'Church Website', app: 'Church App', accounts: 'Accounts' };
|
||||||
|
/** Products that publish events (Accounts has none). */
|
||||||
|
const EVENT_PRODUCTS = new Set(['website', 'app']);
|
||||||
|
|
||||||
|
const installParams = z.object({ installId: z.uuid().describe("The product's Hub install id") });
|
||||||
|
|
||||||
|
function asApiError(e: unknown): never {
|
||||||
|
if (e instanceof LinkError) {
|
||||||
|
const code = e.status === 404 ? 'NOT_FOUND' : e.status === 503 || e.status === 502 ? 'UNAVAILABLE' : e.status === 409 ? 'CONFLICT' : 'VALIDATION_FAILED';
|
||||||
|
throw new ApiError(code, e.message);
|
||||||
|
}
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkState = z.object({
|
||||||
|
connectedAt: isoDate,
|
||||||
|
connectedBy: z.string().nullable().describe('Who pressed Connect here; null when the other product connected'),
|
||||||
|
showEvents: z.boolean(),
|
||||||
|
lastSyncAt: isoDate.nullable(),
|
||||||
|
lastGoodAt: isoDate.nullable().describe('When its events were last fetched successfully'),
|
||||||
|
lastSyncError: z.string().nullable(),
|
||||||
|
importedEvents: z.number().int(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const productRow = z.object({
|
||||||
|
installId: z.string(),
|
||||||
|
product: z.string(),
|
||||||
|
name: z.string(),
|
||||||
|
url: z.string(),
|
||||||
|
listed: z.boolean().describe('In the list the Hub last gave (false: connected before, no longer listed)'),
|
||||||
|
publishesEvents: z.boolean(),
|
||||||
|
link: linkState.nullable().describe('null = not connected'),
|
||||||
|
});
|
||||||
|
|
||||||
|
type LinkRow = {
|
||||||
|
installId: string; product: string; url: string; connectedAt: Date; connectedById: string | null; showEvents: boolean;
|
||||||
|
lastSyncAt: Date | null; lastGoodAt: Date | null; lastSyncError: string | null; _count: { importedEvents: number };
|
||||||
|
};
|
||||||
|
|
||||||
|
async function overview() {
|
||||||
|
const [listed, links, installId, publish, keyStatus] = await Promise.all([
|
||||||
|
linkedProducts(),
|
||||||
|
prisma.productLink.findMany({ include: { _count: { select: { importedEvents: true } } } }) as Promise<LinkRow[]>,
|
||||||
|
hubInstallId(),
|
||||||
|
publishOn(),
|
||||||
|
publicKeyStatus(),
|
||||||
|
]);
|
||||||
|
const people = new Map<string, string>(
|
||||||
|
(await prisma.user.findMany({ where: { id: { in: links.map((l) => l.connectedById).filter(Boolean) as string[] } }, select: { id: true, name: true } }))
|
||||||
|
.map((u: { id: string; name: string }) => [u.id, u.name]),
|
||||||
|
);
|
||||||
|
const byId = new Map(links.map((l) => [l.installId, l]));
|
||||||
|
const ids = [...new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)])];
|
||||||
|
const products = ids.map((id) => {
|
||||||
|
const hubRow = listed.find((l) => l.installId === id);
|
||||||
|
const link = byId.get(id);
|
||||||
|
const product = hubRow?.product ?? link!.product;
|
||||||
|
return {
|
||||||
|
installId: id,
|
||||||
|
product,
|
||||||
|
name: PRODUCT_NAMES[product] ?? product,
|
||||||
|
url: hubRow?.url ?? link!.url,
|
||||||
|
listed: !!hubRow,
|
||||||
|
publishesEvents: EVENT_PRODUCTS.has(product),
|
||||||
|
link: link ? {
|
||||||
|
connectedAt: iso(link.connectedAt),
|
||||||
|
connectedBy: link.connectedById ? people.get(link.connectedById) ?? 'A deleted account' : null,
|
||||||
|
showEvents: link.showEvents,
|
||||||
|
lastSyncAt: iso(link.lastSyncAt),
|
||||||
|
lastGoodAt: iso(link.lastGoodAt),
|
||||||
|
lastSyncError: link.lastSyncError,
|
||||||
|
importedEvents: link._count.importedEvents,
|
||||||
|
} : null,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
hubConnected: !!installId,
|
||||||
|
// "saved" / "matches": the Hub has this site's key, so the others can link to it.
|
||||||
|
keyKnownToHub: keyStatus === 'saved' || keyStatus === 'matches',
|
||||||
|
keyMismatch: keyStatus === 'mismatch',
|
||||||
|
publishEvents: publish,
|
||||||
|
products,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const overviewSchema = z.object({
|
||||||
|
hubConnected: z.boolean(),
|
||||||
|
keyKnownToHub: z.boolean().describe("The Hub has this site's public key (sent with the heartbeat), so the church's other products are told about it"),
|
||||||
|
keyMismatch: z.boolean().describe('The Hub has a different key for this site (ask the provider to clear it)'),
|
||||||
|
publishEvents: z.boolean(),
|
||||||
|
products: z.array(productRow),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getLinkedProducts = defineRoute({
|
||||||
|
method: 'get',
|
||||||
|
path: '/linked-products',
|
||||||
|
tag: 'Linked products',
|
||||||
|
summary: "The church's other products",
|
||||||
|
description: 'As the Hub last listed them (with each heartbeat), with whether each is connected and its events shown here.',
|
||||||
|
access: 'admin',
|
||||||
|
response: single(overviewSchema),
|
||||||
|
async handler() {
|
||||||
|
return { data: await overview() };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateFeedSettings = defineRoute({
|
||||||
|
method: 'put',
|
||||||
|
path: '/linked-products/settings',
|
||||||
|
tag: 'Linked products',
|
||||||
|
summary: 'Publish my events (on or off)',
|
||||||
|
description: 'Whether this site publishes its public events for the church\'s other products (GET /api/feed/v1/events).',
|
||||||
|
access: 'admin',
|
||||||
|
body: z.object({ publishEvents: z.boolean() }),
|
||||||
|
response: single(overviewSchema),
|
||||||
|
async handler({ body, user, req }) {
|
||||||
|
await prisma.appSetting.upsert({ where: { key: PUBLISH_KEY }, update: { value: String(body.publishEvents) }, create: { key: PUBLISH_KEY, value: String(body.publishEvents) } });
|
||||||
|
invalidate(PUBLISH_KEY);
|
||||||
|
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'feed_publish_toggled', targetType: 'setting', targetId: PUBLISH_KEY, metadata: { publishEvents: body.publishEvents }, ip: getClientIp(req) });
|
||||||
|
return { data: await overview() };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const connect = defineRoute({
|
||||||
|
method: 'post',
|
||||||
|
path: '/linked-products/:installId/connect',
|
||||||
|
tag: 'Linked products',
|
||||||
|
summary: 'Connect to one of the church\'s products',
|
||||||
|
description: 'Sets up a signed link with it (crosscode.link/1). Both products must be in each other\'s list from the Hub. Connecting again replaces the link\'s secret.',
|
||||||
|
access: 'admin',
|
||||||
|
params: installParams,
|
||||||
|
response: single(overviewSchema),
|
||||||
|
async handler({ params, user, req }) {
|
||||||
|
await connectTo(params.installId, { id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError);
|
||||||
|
return { data: await overview() };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const disconnect = defineRoute({
|
||||||
|
method: 'post',
|
||||||
|
path: '/linked-products/:installId/disconnect',
|
||||||
|
tag: 'Linked products',
|
||||||
|
summary: 'Disconnect a product',
|
||||||
|
description: 'Ends the link on both sides (the other product is told when it can be reached) and removes its events from this site.',
|
||||||
|
access: 'admin',
|
||||||
|
params: installParams,
|
||||||
|
response: single(overviewSchema.extend({ otherSideTold: z.boolean(), problem: z.string().nullable() })),
|
||||||
|
async handler({ params, user, req }) {
|
||||||
|
const r = await disconnectFrom(params.installId, { id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError);
|
||||||
|
return { data: { ...(await overview()), otherSideTold: r.siblingTold, problem: r.message } };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const updateLink = defineRoute({
|
||||||
|
method: 'put',
|
||||||
|
path: '/linked-products/:installId',
|
||||||
|
tag: 'Linked products',
|
||||||
|
summary: 'Show events from a connected product (on or off)',
|
||||||
|
description: 'On: its events are fetched now and every 15 minutes, and shown on the public pages. Off: they are removed from this site.',
|
||||||
|
access: 'admin',
|
||||||
|
params: installParams,
|
||||||
|
body: z.object({ showEvents: z.boolean() }),
|
||||||
|
response: single(overviewSchema),
|
||||||
|
async handler({ params, body, user, req }) {
|
||||||
|
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
|
||||||
|
if (!link) throw notFound('That connected product');
|
||||||
|
if (body.showEvents && !EVENT_PRODUCTS.has(link.product)) throw new ApiError('VALIDATION_FAILED', `${PRODUCT_NAMES[link.product] ?? link.product} has no events to show.`);
|
||||||
|
const updated = await prisma.productLink.update({ where: { installId: link.installId }, data: { showEvents: body.showEvents, ...(body.showEvents ? {} : { lastGoodAt: null }) } });
|
||||||
|
if (body.showEvents) await syncLink(updated);
|
||||||
|
else await prisma.importedEvent.deleteMany({ where: { linkId: link.installId } });
|
||||||
|
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'feed_show_toggled', targetType: 'product_link', targetId: link.installId, metadata: { product: link.product, showEvents: body.showEvents }, ip: getClientIp(req) });
|
||||||
|
return { data: await overview() };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const syncNow = defineRoute({
|
||||||
|
method: 'post',
|
||||||
|
path: '/linked-products/:installId/sync',
|
||||||
|
tag: 'Linked products',
|
||||||
|
summary: 'Fetch a product\'s events now',
|
||||||
|
access: 'admin',
|
||||||
|
params: installParams,
|
||||||
|
response: single(overviewSchema),
|
||||||
|
async handler({ params }) {
|
||||||
|
const link = await prisma.productLink.findUnique({ where: { installId: params.installId } });
|
||||||
|
if (!link) throw notFound('That connected product');
|
||||||
|
await syncLink(link);
|
||||||
|
return { data: await overview() };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Public: events from linked products ─────────────────────────────────────
|
||||||
|
|
||||||
|
const crosscodeEvent = z.looseObject({
|
||||||
|
schema: z.literal('crosscode.event/1'),
|
||||||
|
id: z.string(),
|
||||||
|
title: z.string(),
|
||||||
|
startsAt: isoDate,
|
||||||
|
endsAt: isoDate,
|
||||||
|
}).describe('The event as crosscode.event/1, as the other product published it');
|
||||||
|
|
||||||
|
const linkedEvent = z.object({
|
||||||
|
key: z.string().describe('"<product>:<id>", unique across products'),
|
||||||
|
product: z.string(),
|
||||||
|
productName: z.string(),
|
||||||
|
event: crosscodeEvent,
|
||||||
|
});
|
||||||
|
|
||||||
|
type ImportedRow = { key: string; payload: { origin: { product: string } } & Record<string, unknown>; campusSlug: string | null };
|
||||||
|
|
||||||
|
const toLinked = (r: ImportedRow) => ({ key: r.key, product: r.payload.origin.product, productName: PRODUCT_NAMES[r.payload.origin.product] ?? r.payload.origin.product, event: r.payload as unknown as z.input<typeof crosscodeEvent> });
|
||||||
|
|
||||||
|
export const listLinkedEvents = defineRoute({
|
||||||
|
method: 'get',
|
||||||
|
path: '/linked-events',
|
||||||
|
tag: 'Events',
|
||||||
|
summary: "Upcoming events from the church's other products",
|
||||||
|
description: 'Read-only copies of the events of connected products shown here (Settings → Linked products), soonest first. Each links back to its own page.',
|
||||||
|
access: 'public',
|
||||||
|
query: z.object({
|
||||||
|
campus: z.string().max(64).optional().describe("A campus slug (its events, church-wide ones and ones for a campus this site doesn't have), or 'all' for church-wide only"),
|
||||||
|
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||||
|
}),
|
||||||
|
response: single(z.array(linkedEvent)),
|
||||||
|
async handler({ query }) {
|
||||||
|
const now = new Date();
|
||||||
|
const rows: ImportedRow[] = await prisma.importedEvent.findMany({
|
||||||
|
where: { endsAt: { gte: now }, link: { showEvents: true } },
|
||||||
|
orderBy: [{ startsAt: 'asc' }, { key: 'asc' }],
|
||||||
|
take: 300,
|
||||||
|
});
|
||||||
|
let list = rows;
|
||||||
|
if (query.campus) {
|
||||||
|
const ours = new Set<string>((await prisma.campus.findMany({ select: { slug: true } })).map((c: { slug: string }) => c.slug));
|
||||||
|
list = rows.filter((r) => !r.campusSlug || !ours.has(r.campusSlug) || (query.campus !== 'all' && r.campusSlug === query.campus));
|
||||||
|
}
|
||||||
|
return { data: list.slice(0, query.limit).map(toLinked) };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getLinkedEvent = defineRoute({
|
||||||
|
method: 'get',
|
||||||
|
path: '/linked-events/:product/:id',
|
||||||
|
tag: 'Events',
|
||||||
|
summary: "One event from another of the church's products",
|
||||||
|
access: 'public',
|
||||||
|
params: z.object({ product: z.enum(['website', 'app']).describe('The product the event comes from'), id: z.uuid().describe("The event's id in that product") }),
|
||||||
|
response: single(linkedEvent.extend({ lastSyncedAt: isoDate.nullable().describe('When the copy was last refreshed from its product') })),
|
||||||
|
async handler({ params }) {
|
||||||
|
const row = await prisma.importedEvent.findFirst({ where: { key: `${params.product}:${params.id}`, link: { showEvents: true } }, include: { link: { select: { lastGoodAt: true } } } });
|
||||||
|
if (!row) throw notFound('That event');
|
||||||
|
return { data: { ...toLinked(row), lastSyncedAt: iso(row.link.lastGoodAt) } };
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -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 */
|
/* 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 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> };
|
const campusScope = require('../../utils/campusScope') as { scopeFor(req: unknown): Promise<{ campusIds: string[] | null } | null> };
|
||||||
|
|
||||||
@@ -39,6 +39,8 @@ export const getMe = defineRoute({
|
|||||||
access: 'user',
|
access: 'user',
|
||||||
response: single(me.extend({
|
response: single(me.extend({
|
||||||
twoFactorRequired: z.boolean().describe('Their role must use two-step sign-in'),
|
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(),
|
newsPromptPending: z.boolean(),
|
||||||
noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]),
|
noticePromptPending: z.union([z.literal(false), z.enum(['first', 'updated'])]),
|
||||||
campusScope: z.array(id).nullable(),
|
campusScope: z.array(id).nullable(),
|
||||||
@@ -54,6 +56,8 @@ export const getMe = defineRoute({
|
|||||||
data: {
|
data: {
|
||||||
...toMe(u),
|
...toMe(u),
|
||||||
twoFactorRequired: requiresTwoFactor(u),
|
twoFactorRequired: requiresTwoFactor(u),
|
||||||
|
twoFactorMethod: u.twoFactorEnabled ? (u.twoFactorMethod ?? null) : null,
|
||||||
|
recoveryCodesLeft: u.twoFactorEnabled ? await recoveryCodesLeft(u.id) : 0,
|
||||||
newsPromptPending: !u.newsAskedAt && !impersonating,
|
newsPromptPending: !u.newsAskedAt && !impersonating,
|
||||||
noticePromptPending: impersonating ? false as const : await privacyNotice.noticePromptPending({ noticeVersionAccepted: u.noticeVersionAccepted }),
|
noticePromptPending: impersonating ? false as const : await privacyNotice.noticePromptPending({ noticeVersionAccepted: u.noticeVersionAccepted }),
|
||||||
campusScope: (await campusScope.scopeFor(req))?.campusIds ?? null,
|
campusScope: (await campusScope.scopeFor(req))?.campusIds ?? null,
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ const SCOPE_LIST = 'scopeList (the handler filters by listWhere)';
|
|||||||
|
|
||||||
// ─── Documented shapes (docs.ts) ─────────────────────────────────────────────
|
// ─── 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 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 kind = z.enum(['update', 'news']).describe('update: about something they booked (always sent). news: needs their news consent');
|
||||||
const attendeeFilter = D.obj({
|
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: '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: '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/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/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 }) }, v1: users.confirmEnableTwoFactor });
|
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: '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({
|
v1Route({
|
||||||
method: 'get', path: '/users/exists', tag: 'Accounts', summary: 'Is there an account with this email or phone?',
|
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();
|
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. */
|
/** 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 {
|
export function absoluteUrl(req: Request, url: string | null | undefined): string | null {
|
||||||
const raw = String(url || '').trim();
|
const raw = String(url || '').trim();
|
||||||
if (!raw) return null;
|
if (!raw) return null;
|
||||||
if (/^https?:\/\//.test(raw)) return raw;
|
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() });
|
export const campusRef = z.object({ id, name: z.string(), slug: z.string() });
|
||||||
|
|||||||
@@ -28,9 +28,12 @@ const mockMail = jest.fn(async (_m: unknown) => undefined);
|
|||||||
jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true }));
|
jest.mock('../src/utils/email', () => ({ sendMail: (m: unknown) => mockMail(m), emailWrapper: (s: string) => s, isSmtpConfigured: () => true }));
|
||||||
jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) }));
|
jest.mock('../src/utils/adminAudit', () => ({ logAdminAction: jest.fn(async () => undefined) }));
|
||||||
|
|
||||||
import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, _internal } from '../src/ai';
|
import { aiStatus, runHelper, saveAiSettings, clearAiStatusCache, tokenText, _internal } from '../src/ai';
|
||||||
|
|
||||||
const hubStatus = (over = {}) => ({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01', ...over });
|
const hubStatus = (over = {}) => ({
|
||||||
|
enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01',
|
||||||
|
usedInputTokens: 40000, usedOutputTokens: 9000, capInputTokens: 1785000, capOutputTokens: 357000, ...over,
|
||||||
|
});
|
||||||
const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 };
|
const req = { system: 'Write a friendly message.', input: 'Bring a sleeping bag.', maxTokens: 500 };
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
@@ -55,7 +58,7 @@ describe('status', () => {
|
|||||||
|
|
||||||
test('asks the Hub and caches its answer for a minute', async () => {
|
test('asks the Hub and caches its answer for a minute', async () => {
|
||||||
mockPost.mockResolvedValue(hubStatus());
|
mockPost.mockResolvedValue(hubStatus());
|
||||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedCents: 100, helpers: { draft_event: true } });
|
expect(await aiStatus()).toMatchObject({ enabled: true, available: true, usedInputTokens: 40000, capOutputTokens: 357000, helpers: { draft_event: true } });
|
||||||
await aiStatus();
|
await aiStatus();
|
||||||
expect(mockPost).toHaveBeenCalledTimes(1);
|
expect(mockPost).toHaveBeenCalledTimes(1);
|
||||||
expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 });
|
expect(mockPost).toHaveBeenCalledWith('/api/installs/ai/status', { protocolVersion: 1 });
|
||||||
@@ -68,16 +71,32 @@ describe('status', () => {
|
|||||||
mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502));
|
mockPost.mockRejectedValueOnce(new MockHubError('down', 'HUB_UNREACHABLE', 502));
|
||||||
expect(await aiStatus()).toMatchObject({ enabled: true, available: false });
|
expect(await aiStatus()).toMatchObject({ enabled: true, available: false });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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');
|
||||||
|
expect(s).not.toHaveProperty('usedCents');
|
||||||
|
clearAiStatusCache();
|
||||||
|
mockPost.mockResolvedValueOnce({ enabled: true, capReached: false, capCents: 5000, usedCents: 100, usedPercent: 2, renewsOn: '2026-12-01' });
|
||||||
|
expect(await aiStatus()).toMatchObject({ usedPercent: 2, usedInputTokens: null, capInputTokens: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tokens for people', () => {
|
||||||
|
expect(['800', '45K', '1.2M', '2M', '12M']).toEqual([800, 45000, 1200000, 2000000, 12300000].map(tokenText));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('running a helper', () => {
|
describe('running a helper', () => {
|
||||||
test('sends the request to the Hub, logs the call, returns the answer', async () => {
|
test('sends the request to the Hub, logs the call, returns the answer', async () => {
|
||||||
mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({ output: 'Hi all!', chargedCents: 0.31, status: hubStatus({ usedCents: 100.31 }) });
|
mockPost.mockResolvedValueOnce(hubStatus()).mockResolvedValueOnce({
|
||||||
|
output: 'Hi all!', usage: { inputTokens: 1840, outputTokens: 420 }, chargedCents: 0.31, status: hubStatus({ usedInputTokens: 41840, usedOutputTokens: 9420 }),
|
||||||
|
});
|
||||||
const r = await runHelper('draft_message', 'u1', req);
|
const r = await runHelper('draft_message', 'u1', req);
|
||||||
expect(r.output).toBe('Hi all!');
|
expect(r.output).toBe('Hi all!');
|
||||||
expect(r.status.usedCents).toBe(100.31);
|
expect(r.status).toMatchObject({ usedInputTokens: 41840, usedOutputTokens: 9420 });
|
||||||
expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 });
|
expect(mockPost).toHaveBeenLastCalledWith('/api/installs/ai/complete', { protocolVersion: 1, helper: 'draft_message', ...req }, { timeoutMs: 90000 });
|
||||||
expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31 }]);
|
expect(mockCalls).toEqual([{ userId: 'u1', helper: 'draft_message', outcome: 'ok', chargedCents: 0.31, inputTokens: 1840, outputTokens: 420 }]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('a helper switched off, or the cap reached, never reaches the Hub', async () => {
|
test('a helper switched off, or the cap reached, never reaches the Hub', async () => {
|
||||||
@@ -102,7 +121,7 @@ describe('running a helper', () => {
|
|||||||
.mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) }));
|
.mockRejectedValueOnce(new MockHubError('used up', 'AI_CAP_REACHED', 402, { code: 'AI_CAP_REACHED', status: hubStatus({ capReached: true }) }));
|
||||||
await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') });
|
await expect(runHelper('draft_message', 'u1', req)).rejects.toMatchObject({ reason: 'AI_CAP_REACHED', message: expect.stringContaining('1 December') });
|
||||||
expect((await aiStatus()).capReached).toBe(true);
|
expect((await aiStatus()).capReached).toBe(true);
|
||||||
expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0 });
|
expect(mockCalls[0]).toMatchObject({ outcome: 'cap_reached', chargedCents: 0, inputTokens: 0, outputTokens: 0 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('admins are emailed once a month at 80%', async () => {
|
test('admins are emailed once a month at 80%', async () => {
|
||||||
@@ -112,6 +131,9 @@ describe('running a helper', () => {
|
|||||||
await runHelper('draft_message', 'u1', req);
|
await runHelper('draft_message', 'u1', req);
|
||||||
expect(mockMail).toHaveBeenCalledTimes(1);
|
expect(mockMail).toHaveBeenCalledTimes(1);
|
||||||
expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]);
|
expect(mockMail.mock.calls[0]).toEqual([expect.objectContaining({ to: 'admin@test.local', subject: 'AI allowance 81% used' })]);
|
||||||
|
const text = (mockMail.mock.calls[0] as unknown as [{ text: string }])[0].text;
|
||||||
|
expect(text).toContain('40K input and 9K output tokens');
|
||||||
|
expect(text).not.toMatch(/R\d/);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ import {
|
|||||||
draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer,
|
draftEvent, summariseReport, draftMessage, improveText, type EventDraftAnswer,
|
||||||
} from '../src/ai/helpers';
|
} from '../src/ai/helpers';
|
||||||
|
|
||||||
const status = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: {} };
|
const status = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: {} };
|
||||||
const now = new Date('2026-10-30T08:00:00Z');
|
const now = new Date('2026-10-30T08:00:00Z');
|
||||||
|
|
||||||
beforeEach(() => mockRun.mockReset());
|
beforeEach(() => mockRun.mockReset());
|
||||||
|
|||||||
@@ -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,63 @@
|
|||||||
|
// 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 }))),
|
||||||
|
findUnique: jest.fn(async ({ where }) => (mockSettings.has(where.key) ? { key: where.key, value: mockSettings.get(where.key) } : null)),
|
||||||
|
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,520 @@
|
|||||||
|
// 2.4.0 (docs/EVENTS-2.4-PLAN.md §8): the event feed, Linked products / Connect, showing events
|
||||||
|
// from linked products, and the v2 heartbeat. In-memory database (tests/support/fakeFeedDb.js).
|
||||||
|
jest.mock('../src/config/db', () => require('./support/fakeFeedDb'));
|
||||||
|
jest.mock('../src/utils/settingsCache', () => {
|
||||||
|
const db = require('./support/fakeFeedDb');
|
||||||
|
return {
|
||||||
|
getSetting: async (key, fallback = '') => (db.t.appSetting.get(key)?.value ?? fallback),
|
||||||
|
getSettingSync: () => '',
|
||||||
|
invalidate: () => {},
|
||||||
|
warmCache: async () => {},
|
||||||
|
ENCRYPTED_KEYS: new Set(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const mockSold = new Map();
|
||||||
|
jest.mock('../src/utils/stock', () => ({ takenCount: async ({ eventOptionId, sessionId }) => mockSold.get(sessionId ? `${eventOptionId}:${sessionId}` : eventOptionId) || 0 }));
|
||||||
|
const mockTasks = [];
|
||||||
|
jest.mock('../src/jobs', () => ({ enqueueTask: async (name, data) => { mockTasks.push([name, data]); return { queued: true }; } }));
|
||||||
|
|
||||||
|
process.env.WEBHOOKS_ALLOW_PRIVATE = 'true';
|
||||||
|
process.env.FRONTEND_URL = 'https://events.hope.test';
|
||||||
|
process.env.JWT_SECRET = 'a-test-secret-that-is-long-enough-for-the-encryption';
|
||||||
|
|
||||||
|
const express = require('express');
|
||||||
|
const request = require('supertest');
|
||||||
|
const { eventSchema, eventFeedSchema, linkConnectSchema, hub: hubContract } = require('@crosscode/contracts');
|
||||||
|
const signing = require('@crosscode/contracts/signing');
|
||||||
|
const db = require('./support/fakeFeedDb');
|
||||||
|
const path = require('path');
|
||||||
|
const SAMPLES = path.join(path.dirname(require.resolve('@crosscode/contracts/package.json')), 'samples');
|
||||||
|
const contractSample = (name) => JSON.parse(require('fs').readFileSync(path.join(SAMPLES, name), 'utf8'));
|
||||||
|
const { encrypt } = require('../src/utils/encryption');
|
||||||
|
const { buildCrosscodeEvent, plainToMarkdown, absolute } = require('../src/feed/build');
|
||||||
|
const { refreshFeed, feedResponse } = require('../src/feed/entries');
|
||||||
|
const { syncLink } = require('../src/feed/sync');
|
||||||
|
const connect = require('../src/links/connect');
|
||||||
|
const store = require('../src/links/store');
|
||||||
|
const { crossProductRouter } = require('../src/links/routes');
|
||||||
|
|
||||||
|
const EVENTS_ID = '9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c';
|
||||||
|
const WEBSITE_ID = '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02';
|
||||||
|
const WEBSITE_URL = 'https://www.hope.test';
|
||||||
|
const NOW = new Date('2026-11-20T10:00:00.000Z');
|
||||||
|
const DAY = 24 * 3600e3;
|
||||||
|
|
||||||
|
const ctx = (over = {}) => ({ installId: EVENTS_ID, baseUrl: 'https://events.hope.test', timezone: 'Africa/Johannesburg', campusesOn: false, now: NOW, ...over });
|
||||||
|
|
||||||
|
let n = 0;
|
||||||
|
const uuid = () => `00000000-0000-4000-8000-${String(++n).padStart(12, '0')}`;
|
||||||
|
|
||||||
|
function eventRow(over = {}) {
|
||||||
|
const id = over.id || uuid();
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
title: 'Youth Camp',
|
||||||
|
description: 'Three days away.\nBring a *sleeping bag*.',
|
||||||
|
startDate: new Date(NOW.getTime() + 30 * DAY),
|
||||||
|
endDate: new Date(NOW.getTime() + 32 * DAY),
|
||||||
|
goLiveAt: new Date(NOW.getTime() - DAY),
|
||||||
|
registrationDeadline: null,
|
||||||
|
picture: '/uploads/camp.jpg',
|
||||||
|
location: 'Camp Wartburg',
|
||||||
|
requiresRegistration: true,
|
||||||
|
waitlistEnabled: false,
|
||||||
|
scheduleType: 'single',
|
||||||
|
attendanceMode: 'whole',
|
||||||
|
lateJoinEnabled: false,
|
||||||
|
lateJoinUntilSessionId: null,
|
||||||
|
kidsOptionId: null,
|
||||||
|
volunteerOptionId: null,
|
||||||
|
isActive: true,
|
||||||
|
isHidden: false,
|
||||||
|
campus: null,
|
||||||
|
series: null,
|
||||||
|
sessions: [],
|
||||||
|
eventOptions: [
|
||||||
|
{ id: `${id}-adult`, price: 450, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
|
||||||
|
{ id: `${id}-child`, price: 300, isMainTicket: true, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
|
||||||
|
{ id: `${id}-tshirt`, price: 120, isMainTicket: false, stockLimit: 0, sessionMode: 'all', earlyBirdTiers: [], variants: [] },
|
||||||
|
],
|
||||||
|
...over,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const keys = { events: signing.generateEd25519(), website: signing.generateEd25519() };
|
||||||
|
const pem = (k) => signing.ed25519PublicToPem(k.publicKey);
|
||||||
|
|
||||||
|
async function setUpSite({ linked = true } = {}) {
|
||||||
|
db.reset();
|
||||||
|
store.forgetKeyPair();
|
||||||
|
db.t.appSetting.set('hub_install_id', { key: 'hub_install_id', value: EVENTS_ID });
|
||||||
|
db.t.appSetting.set('hub_private_key', { key: 'hub_private_key', value: encrypt(keys.events.privateKeyPem) });
|
||||||
|
db.t.appSetting.set('hub_public_key', { key: 'hub_public_key', value: pem(keys.events) });
|
||||||
|
if (linked) await store.saveLinkedProducts([{ product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: pem(keys.website) }]);
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
mockSold.clear();
|
||||||
|
mockTasks.length = 0;
|
||||||
|
await setUpSite();
|
||||||
|
delete global.fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Building crosscode.event/1 ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('crosscode.event/1 from an event', () => {
|
||||||
|
test('a ticketed event passes the contract, with the lowest main ticket as the price', () => {
|
||||||
|
const { event, priceRangeCents } = buildCrosscodeEvent(eventRow(), new Map(), ctx());
|
||||||
|
expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]);
|
||||||
|
expect(event.origin).toEqual({ product: 'events', installId: EVENTS_ID, url: `https://events.hope.test/events/${event.id}` });
|
||||||
|
expect(event.registration).toMatchObject({ mode: 'origin', status: 'open', priceFrom: { amountCents: 30000, currency: 'ZAR' } });
|
||||||
|
expect(priceRangeCents).toEqual({ lowCents: 30000, highCents: 45000 });
|
||||||
|
expect(event.imageUrl).toBe('https://events.hope.test/api/uploads/camp.jpg');
|
||||||
|
expect(event.location).toEqual({ name: 'Camp Wartburg', address: null, onlineUrl: null });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never carries the contact person, kids or volunteer tickets', () => {
|
||||||
|
const row = eventRow({ contactName: 'Jane', contactPhone: '082', contactEmail: 'jane@x.co.za' });
|
||||||
|
row.kidsOptionId = row.eventOptions[1].id;
|
||||||
|
row.eventOptions[1].price = 0;
|
||||||
|
const json = JSON.stringify(buildCrosscodeEvent(row, new Map(), ctx()).event);
|
||||||
|
expect(json).not.toMatch(/Jane|082|jane@/);
|
||||||
|
expect(buildCrosscodeEvent(row, new Map(), ctx()).event.registration.priceFrom).toEqual({ amountCents: 45000, currency: 'ZAR' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
['not_open', { goLiveAt: new Date(NOW.getTime() + DAY) }, new Map()],
|
||||||
|
['closed', { registrationDeadline: new Date(NOW.getTime() - 3600e3) }, new Map()],
|
||||||
|
])('registration %s', (status, over, avail) => {
|
||||||
|
expect(buildCrosscodeEvent(eventRow(over), avail, ctx()).event.registration.status).toBe(status);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('full when every main ticket is limited and sold out; waitlist when it has one', () => {
|
||||||
|
const row = eventRow();
|
||||||
|
row.eventOptions[0].stockLimit = 10;
|
||||||
|
row.eventOptions[1].stockLimit = 5;
|
||||||
|
const soldOut = new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 0]]);
|
||||||
|
expect(buildCrosscodeEvent(row, soldOut, ctx()).event.registration.status).toBe('full');
|
||||||
|
expect(buildCrosscodeEvent({ ...row, waitlistEnabled: true }, soldOut, ctx()).event.registration.status).toBe('waitlist');
|
||||||
|
// One main ticket still has places: open.
|
||||||
|
expect(buildCrosscodeEvent(row, new Map([[row.eventOptions[0].id, 0], [row.eventOptions[1].id, 2]]), ctx()).event.registration.status).toBe('open');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('contact-only and free events', () => {
|
||||||
|
expect(buildCrosscodeEvent(eventRow({ requiresRegistration: false }), new Map(), ctx()).event.registration).toEqual({ mode: 'contact', url: null, status: 'open', opensAt: null, closesAt: null, priceFrom: null });
|
||||||
|
const free = eventRow();
|
||||||
|
for (const o of free.eventOptions) o.price = 0;
|
||||||
|
const built = buildCrosscodeEvent(free, new Map(), ctx());
|
||||||
|
expect(built.event.registration.priceFrom).toBeNull();
|
||||||
|
expect(built.priceRangeCents).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a multi-day event: sessions, and start/end from the sessions that still run', () => {
|
||||||
|
const s = (d, cancelled = false) => ({ id: uuid(), label: `Week ${d}`, startsAt: new Date(NOW.getTime() + d * 7 * DAY), endsAt: new Date(NOW.getTime() + d * 7 * DAY + 2 * 3600e3), location: null, cancelledAt: cancelled ? NOW : null });
|
||||||
|
const sessions = [s(1), s(2), s(3, true)];
|
||||||
|
const { event } = buildCrosscodeEvent(eventRow({ scheduleType: 'sessions', sessions }), new Map(), ctx());
|
||||||
|
expect(eventSchema.safeParse(event).error?.issues ?? []).toEqual([]);
|
||||||
|
expect(event.sessions).toHaveLength(3);
|
||||||
|
expect(event.endsAt).toBe(sessions[1].endsAt.toISOString());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an online event, and the campus only while campuses are on', () => {
|
||||||
|
const row = eventRow({ location: 'https://youtube.com/live/abc', campus: { slug: 'meyerton', name: 'Meyerton' } });
|
||||||
|
expect(buildCrosscodeEvent(row, new Map(), ctx()).event).toMatchObject({ location: { onlineUrl: 'https://youtube.com/live/abc' }, campus: null });
|
||||||
|
expect(buildCrosscodeEvent(row, new Map(), ctx({ campusesOn: true })).event.campus).toEqual({ slug: 'meyerton', name: 'Meyerton' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('plain text descriptions read the same as markdown', () => {
|
||||||
|
expect(plainToMarkdown('Bring a *sleeping bag*\n- not a list\n1. not numbered\n\n# not a heading')).toBe('Bring a \\*sleeping bag\\* \n\\- not a list \n1\\. not numbered\n\n\\# not a heading');
|
||||||
|
expect(plainToMarkdown(' ')).toBeNull();
|
||||||
|
expect(absolute('https://e.test', 'https://cdn.test/x.jpg')).toBe('https://cdn.test/x.jpg');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── The published feed ───────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('the feed', () => {
|
||||||
|
const put = (row) => db.t.event.set(row.id, row);
|
||||||
|
|
||||||
|
test('publishes public events, and updatedSince returns exactly what changed', async () => {
|
||||||
|
const a = eventRow();
|
||||||
|
const hidden = eventRow({ isHidden: true });
|
||||||
|
const later = eventRow({ goLiveAt: new Date(NOW.getTime() + 2 * 3600e3) });
|
||||||
|
[a, hidden, later].forEach(put);
|
||||||
|
|
||||||
|
const first = await refreshFeed(NOW);
|
||||||
|
expect(first.changed).toEqual([a.id]);
|
||||||
|
const full = await feedResponse(null, NOW);
|
||||||
|
expect(eventFeedSchema.safeParse(full).success).toBe(true);
|
||||||
|
expect(full.events.map((e) => e.id)).toEqual([a.id]);
|
||||||
|
|
||||||
|
// Nothing changed: nothing new since.
|
||||||
|
const t1 = new Date(NOW.getTime() + 60e3);
|
||||||
|
expect((await refreshFeed(t1)).changed).toEqual([]);
|
||||||
|
expect((await feedResponse(NOW, t1)).events).toEqual([]);
|
||||||
|
|
||||||
|
// Going live changes no Event row, but shows up.
|
||||||
|
const t2 = new Date(NOW.getTime() + 3 * 3600e3);
|
||||||
|
expect((await refreshFeed(t2)).changed).toEqual([later.id]);
|
||||||
|
expect((await feedResponse(t1, t2)).events.map((e) => e.id)).toEqual([later.id]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('selling out is a change; deactivating puts the event in deleted', async () => {
|
||||||
|
const a = eventRow();
|
||||||
|
a.eventOptions[0].stockLimit = 2;
|
||||||
|
a.eventOptions[1].stockLimit = 2;
|
||||||
|
put(a);
|
||||||
|
await refreshFeed(NOW);
|
||||||
|
|
||||||
|
mockSold.set(a.eventOptions[0].id, 2);
|
||||||
|
mockSold.set(a.eventOptions[1].id, 2);
|
||||||
|
const t1 = new Date(NOW.getTime() + 60e3);
|
||||||
|
expect((await refreshFeed(t1)).changed).toEqual([a.id]);
|
||||||
|
const after = await feedResponse(NOW, t1);
|
||||||
|
expect(after.events[0].registration.status).toBe('full');
|
||||||
|
expect(after.events[0].updatedAt).toBe(t1.toISOString());
|
||||||
|
|
||||||
|
put({ ...a, isActive: false });
|
||||||
|
const t2 = new Date(NOW.getTime() + 120e3);
|
||||||
|
expect((await refreshFeed(t2)).removed).toEqual([a.id]);
|
||||||
|
const gone = await feedResponse(t1, t2);
|
||||||
|
expect(gone.events).toEqual([]);
|
||||||
|
expect(gone.deleted).toEqual([{ id: a.id, deletedAt: t2.toISOString() }]);
|
||||||
|
// A full fetch no longer lists it.
|
||||||
|
expect((await feedResponse(null, t2)).events).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('an event that ended a month ago drops out quietly (not deleted)', async () => {
|
||||||
|
const a = eventRow({ startDate: new Date(NOW.getTime() - 2 * DAY), endDate: new Date(NOW.getTime() - DAY) });
|
||||||
|
put(a);
|
||||||
|
await refreshFeed(NOW);
|
||||||
|
const later = new Date(NOW.getTime() + 31 * DAY);
|
||||||
|
const r = await refreshFeed(later);
|
||||||
|
expect(r.removed).toEqual([]);
|
||||||
|
expect((await feedResponse(NOW, later)).deleted).toEqual([]);
|
||||||
|
expect(db.t.feedEntry.has(a.id)).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('without a Hub install id there is no feed', async () => {
|
||||||
|
db.t.appSetting.delete('hub_install_id');
|
||||||
|
put(eventRow());
|
||||||
|
expect(await refreshFeed(NOW)).toEqual({ changed: [], removed: [], skipped: [] });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Connect ──────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function connectMessage(over = {}, key = keys.website) {
|
||||||
|
return signing.signLink({
|
||||||
|
schema: 'crosscode.link/1',
|
||||||
|
type: 'link.connect',
|
||||||
|
from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL },
|
||||||
|
to: { installId: EVENTS_ID },
|
||||||
|
secret: signing.newLinkSecret(),
|
||||||
|
issuedAt: new Date().toISOString(),
|
||||||
|
nonce: signing.newLinkNonce(),
|
||||||
|
...over,
|
||||||
|
}, key.privateKeyPem);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Connect from a linked product', () => {
|
||||||
|
test('a listed product connects; the reply is signed with this site\'s key and echoes the nonce', async () => {
|
||||||
|
const m = connectMessage();
|
||||||
|
const reply = await connect.acceptConnect(m, '1.2.3.4');
|
||||||
|
expect(signing.verifyLink(reply, pem(keys.events))).toEqual({ ok: true });
|
||||||
|
expect(reply).toMatchObject({ type: 'link.connected', inReplyTo: m.nonce, to: { installId: WEBSITE_ID }, from: { product: 'events', installId: EVENTS_ID } });
|
||||||
|
const link = db.t.productLink.get(WEBSITE_ID);
|
||||||
|
expect(link).toMatchObject({ product: 'website', url: WEBSITE_URL, connectedById: null });
|
||||||
|
expect(db.t.audit.map((a) => a.action)).toEqual(['product_link_connected']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
['not listed by the Hub', async () => { await store.saveLinkedProducts([]); return connectMessage(); }, 'NOT_LINKED'],
|
||||||
|
['signed with another key', async () => connectMessage({}, signing.generateEd25519()), 'BAD_SIGNATURE'],
|
||||||
|
['too old', async () => connectMessage({ issuedAt: new Date(Date.now() - 10 * 60e3).toISOString() }), 'STALE_REQUEST'],
|
||||||
|
['for another install', async () => connectMessage({ to: { installId: WEBSITE_ID } }), 'WRONG_INSTALL'],
|
||||||
|
['claiming another product', async () => connectMessage({ from: { product: 'app', installId: WEBSITE_ID, url: WEBSITE_URL } }), 'NOT_LINKED'],
|
||||||
|
['not a link message', async () => ({ hello: 'world' }), 'INVALID_REQUEST'],
|
||||||
|
])('refused when %s', async (_name, make, code) => {
|
||||||
|
await expect(connect.acceptConnect(await make(), null)).rejects.toMatchObject({ code });
|
||||||
|
expect(db.t.productLink.size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a replayed message is refused', async () => {
|
||||||
|
const m = connectMessage();
|
||||||
|
await connect.acceptConnect(m, null);
|
||||||
|
await expect(connect.acceptConnect(m, null)).rejects.toMatchObject({ code: 'REPLAYED' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('disconnect from the sibling removes the link and its events; a forged one doesn\'t', async () => {
|
||||||
|
await connect.acceptConnect(connectMessage(), null);
|
||||||
|
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
|
||||||
|
const msg = (key) => signing.signLink({ schema: 'crosscode.link/1', type: 'link.disconnect', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce() }, key.privateKeyPem);
|
||||||
|
await expect(connect.acceptDisconnect(msg(signing.generateEd25519()), null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' });
|
||||||
|
await connect.acceptDisconnect(msg(keys.website), null);
|
||||||
|
expect(db.t.productLink.size).toBe(0);
|
||||||
|
expect(db.t.importedEvent.size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Connect from this site', () => {
|
||||||
|
const admin = { id: 'admin-1', role: 'admin' };
|
||||||
|
|
||||||
|
function siblingAnswers(make) {
|
||||||
|
global.fetch = jest.fn(async (url, init) => {
|
||||||
|
const body = JSON.parse(init.body);
|
||||||
|
expect(String(url)).toBe(`${WEBSITE_URL}/api/links/v1/connect`);
|
||||||
|
expect(linkConnectSchema.safeParse(body).success).toBe(true);
|
||||||
|
expect(signing.verifyLink(body, pem(keys.events))).toEqual({ ok: true });
|
||||||
|
const reply = make(body);
|
||||||
|
return new Response(JSON.stringify(reply.body), { status: reply.status || 200, headers: { 'content-type': 'application/json' } });
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const goodReply = (body, key = keys.website, over = {}) => ({
|
||||||
|
body: signing.signLink({ schema: 'crosscode.link/1', type: 'link.connected', from: { product: 'website', installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID }, inReplyTo: body.nonce, issuedAt: new Date().toISOString(), nonce: signing.newLinkNonce(), ...over }, key.privateKeyPem),
|
||||||
|
});
|
||||||
|
|
||||||
|
test('connects when the sibling answers, signed with its listed key', async () => {
|
||||||
|
let sentSecret;
|
||||||
|
siblingAnswers((body) => { sentSecret = body.secret; return goodReply(body); });
|
||||||
|
await connect.connectTo(WEBSITE_ID, admin, null);
|
||||||
|
const link = db.t.productLink.get(WEBSITE_ID);
|
||||||
|
expect(link.connectedById).toBe('admin-1');
|
||||||
|
expect(require('../src/utils/encryption').decrypt(link.secret)).toBe(sentSecret);
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
['signed with another key', (body) => goodReply(body, signing.generateEd25519())],
|
||||||
|
['for another message', (body) => goodReply(body, keys.website, { inReplyTo: signing.newLinkNonce() })],
|
||||||
|
])('refuses an answer %s', async (_name, make) => {
|
||||||
|
siblingAnswers(make);
|
||||||
|
await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'BAD_SIGNATURE' });
|
||||||
|
expect(db.t.productLink.size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('passes on the sibling\'s refusal', async () => {
|
||||||
|
siblingAnswers(() => ({ status: 403, body: { message: 'Not linked yet', code: 'NOT_LINKED' } }));
|
||||||
|
await expect(connect.connectTo(WEBSITE_ID, admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('only to a product the Hub listed', async () => {
|
||||||
|
await expect(connect.connectTo('3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09', admin, null)).rejects.toMatchObject({ code: 'NOT_LINKED' });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Showing events from a linked product ──────────────────────────────────────
|
||||||
|
|
||||||
|
describe('events from a linked product', () => {
|
||||||
|
const sample = () => contractSample('event-simple.json');
|
||||||
|
const linkRow = () => ({ installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('s'), connectedAt: NOW, connectedById: null, showEvents: true, lastSyncAt: null, lastGoodAt: null, lastSyncError: null });
|
||||||
|
const feedOf = (events, deleted = []) => ({ schema: 'crosscode.event-feed/1', generatedAt: NOW.toISOString(), events, deleted });
|
||||||
|
const answer = (body, status = 200) => { global.fetch = jest.fn(async () => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } })); };
|
||||||
|
|
||||||
|
test('imports its events, skips a bad one and one that claims another origin', async () => {
|
||||||
|
db.t.productLink.set(WEBSITE_ID, linkRow());
|
||||||
|
const good = sample();
|
||||||
|
const bad = { ...sample(), id: 'not-a-uuid' };
|
||||||
|
const spoofed = { ...sample(), id: uuid(), origin: { ...sample().origin, installId: EVENTS_ID } };
|
||||||
|
answer(feedOf([good, bad, spoofed]));
|
||||||
|
const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||||
|
expect(r).toMatchObject({ ok: true, imported: 1, rejected: 1, skipped: 1 });
|
||||||
|
expect([...db.t.importedEvent.keys()]).toEqual([`website:${good.id}`]);
|
||||||
|
expect(String(global.fetch.mock.calls[0][0])).toBe(`${WEBSITE_URL}/api/feed/v1/events`);
|
||||||
|
expect(db.t.productLink.get(WEBSITE_ID).lastGoodAt.toISOString()).toBe(NOW.toISOString());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a source that is down keeps its last events and shows the error', async () => {
|
||||||
|
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
|
||||||
|
db.t.importedEvent.set('website:x', { key: 'website:x', linkId: WEBSITE_ID });
|
||||||
|
global.fetch = jest.fn(async () => { throw new Error('ECONNREFUSED'); });
|
||||||
|
const r = await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||||
|
expect(r.ok).toBe(false);
|
||||||
|
expect(db.t.importedEvent.size).toBe(1);
|
||||||
|
expect(db.t.productLink.get(WEBSITE_ID).lastSyncError).toMatch(/could not be reached/);
|
||||||
|
// It fetched what changed since a little before the last good fetch.
|
||||||
|
expect(String(global.fetch.mock.calls[0][0])).toContain('updatedSince=');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deleted events go; never re-published in this site\'s own feed', async () => {
|
||||||
|
db.t.productLink.set(WEBSITE_ID, { ...linkRow(), lastGoodAt: NOW });
|
||||||
|
const e = sample();
|
||||||
|
answer(feedOf([e]));
|
||||||
|
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||||
|
answer(feedOf([], [{ id: e.id, deletedAt: NOW.toISOString() }]));
|
||||||
|
await syncLink(db.t.productLink.get(WEBSITE_ID), NOW);
|
||||||
|
expect(db.t.importedEvent.size).toBe(0);
|
||||||
|
// The feed is built from this site's own events only.
|
||||||
|
db.t.importedEvent.set('website:y', { key: 'website:y', linkId: WEBSITE_ID, payload: e });
|
||||||
|
await refreshFeed(NOW);
|
||||||
|
expect((await feedResponse(null, NOW)).events).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── The endpoints other products call ─────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('/api/feed/v1 and /api/links/v1', () => {
|
||||||
|
const app = () => express().use('/api', crossProductRouter());
|
||||||
|
|
||||||
|
test('the feed: on by default, 404 when publishing is off, 400 for a bad updatedSince', async () => {
|
||||||
|
// The route works on the real clock.
|
||||||
|
const now = Date.now();
|
||||||
|
db.t.event.set('e', eventRow({ id: uuid(), goLiveAt: new Date(now - DAY), startDate: new Date(now + 10 * DAY), endDate: new Date(now + 11 * DAY) }));
|
||||||
|
await refreshFeed(new Date());
|
||||||
|
const res = await request(app()).get('/api/feed/v1/events');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(eventFeedSchema.safeParse(res.body).success).toBe(true);
|
||||||
|
expect(res.body.events).toHaveLength(1);
|
||||||
|
expect((await request(app()).get('/api/feed/v1/events?updatedSince=yesterday')).body.code).toBe('INVALID_REQUEST');
|
||||||
|
db.t.appSetting.set('feed_publish', { key: 'feed_publish', value: 'false' });
|
||||||
|
expect((await request(app()).get('/api/feed/v1/events')).status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('event.changed: checked with the link\'s secret, then a fetch is queued', async () => {
|
||||||
|
db.t.productLink.set(WEBSITE_ID, { installId: WEBSITE_ID, product: 'website', url: WEBSITE_URL, publicKey: pem(keys.website), secret: encrypt('link-secret'), connectedAt: NOW, showEvents: true });
|
||||||
|
const body = JSON.stringify({ schema: 'crosscode.event-feed/1', type: 'event.changed', occurredAt: new Date().toISOString(), eventIds: [uuid()] });
|
||||||
|
const send = (secret, sender = WEBSITE_ID) => request(app()).post('/api/feed/v1/changed').set('Content-Type', 'application/json')
|
||||||
|
.set(signing.signedHeaders(signing.LINK_HEADERS, { senderId: sender, secret, rawBody: body })).send(body);
|
||||||
|
expect((await send('wrong')).status).toBe(401);
|
||||||
|
expect((await send('link-secret', '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e09')).status).toBe(404);
|
||||||
|
const ok = await send('link-secret');
|
||||||
|
expect(ok.status).toBe(202);
|
||||||
|
expect(mockTasks).toEqual([['feed-sync-link', { installId: WEBSITE_ID }]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('connect over HTTP, and errors as { message, code }', async () => {
|
||||||
|
const res = await request(app()).post('/api/links/v1/connect').send(connectMessage());
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(res.body.type).toBe('link.connected');
|
||||||
|
const bad = await request(app()).post('/api/links/v1/connect').send(connectMessage({}, signing.generateEd25519()));
|
||||||
|
expect(bad.status).toBe(401);
|
||||||
|
expect(bad.body).toEqual({ message: expect.any(String), code: 'BAD_SIGNATURE' });
|
||||||
|
const notJson = await request(app()).post('/api/links/v1/connect').set('Content-Type', 'application/json').send('{oops');
|
||||||
|
expect(notJson.body.code).toBe('INVALID_REQUEST');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── The v2 heartbeat ─────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe('protocol v2 heartbeat', () => {
|
||||||
|
const report = require('../src/hub/report');
|
||||||
|
const sampleHb = contractSample('hub-heartbeat-events.json');
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.spyOn(report, 'health').mockResolvedValue({ ...sampleHb.health, jobs: null, pendingMigrations: null });
|
||||||
|
jest.spyOn(report, 'stats').mockResolvedValue(sampleHb.stats);
|
||||||
|
});
|
||||||
|
afterEach(() => jest.restoreAllMocks());
|
||||||
|
|
||||||
|
test('fits the contract (gaps in health filled), with the public key until the Hub has it', async () => {
|
||||||
|
const client = require('../src/hub/client');
|
||||||
|
const { body, v2 } = await client.heartbeatBody();
|
||||||
|
expect(v2).toBe(true);
|
||||||
|
expect(hubContract.heartbeatRequestSchema.safeParse(body).error?.issues ?? []).toEqual([]);
|
||||||
|
expect(body.publicKey).toBe(pem(keys.events));
|
||||||
|
await store.setPublicKeyStatus('saved');
|
||||||
|
expect((await client.heartbeatBody()).body).not.toHaveProperty('publicKey');
|
||||||
|
await store.setPublicKeyStatus('mismatch');
|
||||||
|
expect((await client.heartbeatBody()).body.publicKey).toBe(pem(keys.events));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a Hub that refuses v2 gets the same heartbeat as v1, and v1 for a day', async () => {
|
||||||
|
const client = require('../src/hub/client');
|
||||||
|
db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') });
|
||||||
|
const sent = [];
|
||||||
|
global.fetch = jest.fn(async (_url, init) => {
|
||||||
|
const b = JSON.parse(init.body);
|
||||||
|
sent.push(b.protocolVersion);
|
||||||
|
if (b.protocolVersion === 2) return new Response(JSON.stringify({ message: 'Protocol 2 is not supported', code: 'UNSUPPORTED_PROTOCOL' }), { status: 400 });
|
||||||
|
return new Response(JSON.stringify({ licence: 'x', latestVersion: null }), { status: 200 });
|
||||||
|
});
|
||||||
|
const r = await client.heartbeat();
|
||||||
|
expect(r).toMatchObject({ ok: true, protocol: 1 });
|
||||||
|
expect(sent).toEqual([2, 1]);
|
||||||
|
await client.heartbeat();
|
||||||
|
expect(sent).toEqual([2, 1, 1]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('saves the church\'s other products from the reply', async () => {
|
||||||
|
const client = require('../src/hub/client');
|
||||||
|
db.t.appSetting.set('hub_install_secret', { key: 'hub_install_secret', value: encrypt('install-secret') });
|
||||||
|
const listed = [{ product: 'app', installId: '3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e04', url: 'https://app.hope.test', publicKey: pem(keys.website) }, { product: 'bogus' }];
|
||||||
|
global.fetch = jest.fn(async () => new Response(JSON.stringify({ licence: 'x', latestVersion: null, linkedProducts: listed, publicKeyStatus: 'saved' }), { status: 200 }));
|
||||||
|
await client.heartbeat();
|
||||||
|
expect((await store.linkedProducts()).map((l) => l.product)).toEqual(['app']);
|
||||||
|
expect(await store.publicKeyStatus()).toBe('saved');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── The event page's JSON-LD (@crosscode/seo, replacing frontend/src/lib/eventSchema.ts) ──
|
||||||
|
|
||||||
|
describe('event JSON-LD from crosscode.event/1', () => {
|
||||||
|
test('matches what the event page sent before 2.4.0, with the price range from main tickets only', () => {
|
||||||
|
const { eventJsonLd } = require('@crosscode/seo');
|
||||||
|
const row = eventRow({ id: '00000000-0000-4000-8000-0000000000aa' });
|
||||||
|
const built = buildCrosscodeEvent(row, new Map(), ctx());
|
||||||
|
// As the page calls it (events/[id]/page.tsx).
|
||||||
|
const ld = eventJsonLd({ ...built.event, description: row.description }, {
|
||||||
|
pageUrl: `https://events.hope.test/events/${row.id}`,
|
||||||
|
organizer: { name: 'Hope Family Church', url: 'https://events.hope.test' },
|
||||||
|
priceRange: built.priceRangeCents,
|
||||||
|
offerUrl: `https://events.hope.test/register/${row.id}`,
|
||||||
|
validFrom: row.goLiveAt.toISOString(),
|
||||||
|
});
|
||||||
|
expect(ld).toEqual({
|
||||||
|
'@context': 'https://schema.org',
|
||||||
|
'@type': 'Event',
|
||||||
|
name: 'Youth Camp',
|
||||||
|
description: row.description,
|
||||||
|
startDate: row.startDate.toISOString(),
|
||||||
|
endDate: row.endDate.toISOString(),
|
||||||
|
eventStatus: 'https://schema.org/EventScheduled',
|
||||||
|
eventAttendanceMode: 'https://schema.org/OfflineEventAttendanceMode',
|
||||||
|
location: { '@type': 'Place', name: 'Camp Wartburg', address: 'Camp Wartburg' },
|
||||||
|
image: ['https://events.hope.test/api/uploads/camp.jpg'],
|
||||||
|
url: `https://events.hope.test/events/${row.id}`,
|
||||||
|
organizer: { '@type': 'Organization', name: 'Hope Family Church', url: 'https://events.hope.test' },
|
||||||
|
// Before 2.4.0 the add-on T-shirt (R120) made this 120.00–450.00.
|
||||||
|
offers: { '@type': 'AggregateOffer', lowPrice: '300.00', highPrice: '450.00', priceCurrency: 'ZAR', availability: 'https://schema.org/InStock', url: `https://events.hope.test/register/${row.id}`, validFrom: row.goLiveAt.toISOString() },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
// An in-memory stand-in for the Prisma client, with just what the feed and Linked products use
|
||||||
|
// (src/feed, src/links, src/v2/resources/linkedProducts.ts). Where clauses are matched generically
|
||||||
|
// (AND, equality, in / notIn, gt / gte / lt / lte, not, nested relation filters on `link`).
|
||||||
|
|
||||||
|
const t = { appSetting: new Map(), productLink: new Map(), linkNonce: new Map(), importedEvent: new Map(), feedEntry: new Map(), event: new Map(), campus: [], user: [], audit: [] };
|
||||||
|
|
||||||
|
// Rows keep their Dates; JSON columns (payload) keep their strings, as Prisma gives them back.
|
||||||
|
const clone = (v) => (v === undefined ? v : structuredClone(v));
|
||||||
|
const val = (v) => (v instanceof Date ? v.getTime() : v);
|
||||||
|
|
||||||
|
function matchValue(actual, cond) {
|
||||||
|
if (cond !== null && typeof cond === 'object' && !(cond instanceof Date) && !Array.isArray(cond)) {
|
||||||
|
return Object.entries(cond).every(([op, x]) => {
|
||||||
|
switch (op) {
|
||||||
|
case 'in': return x.includes(actual);
|
||||||
|
case 'notIn': return !x.includes(actual);
|
||||||
|
case 'gt': return actual != null && val(actual) > val(x);
|
||||||
|
case 'gte': return actual != null && val(actual) >= val(x);
|
||||||
|
case 'lt': return actual != null && val(actual) < val(x);
|
||||||
|
case 'lte': return actual != null && val(actual) <= val(x);
|
||||||
|
case 'not': return x === null ? actual != null : !matchValue(actual, x);
|
||||||
|
default: throw new Error(`fakeFeedDb: no operator ${op}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return val(actual) === val(cond);
|
||||||
|
}
|
||||||
|
|
||||||
|
function matches(row, where = {}) {
|
||||||
|
return Object.entries(where || {}).every(([k, cond]) => {
|
||||||
|
if (k === 'AND') return cond.every((w) => matches(row, w));
|
||||||
|
if (k === 'link') return matches(t.productLink.get(row.linkId) || {}, cond.is || cond);
|
||||||
|
return matchValue(row[k], cond);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const pick = (row, select) => (select ? Object.fromEntries(Object.keys(select).filter((k) => select[k]).map((k) => [k, row[k]])) : row);
|
||||||
|
|
||||||
|
function sortBy(rows, orderBy) {
|
||||||
|
const list = Array.isArray(orderBy) ? orderBy : orderBy ? [orderBy] : [];
|
||||||
|
return [...rows].sort((a, b) => {
|
||||||
|
for (const o of list) {
|
||||||
|
const [k, dir] = Object.entries(o)[0];
|
||||||
|
const d = val(a[k]) < val(b[k]) ? -1 : val(a[k]) > val(b[k]) ? 1 : 0;
|
||||||
|
if (d) return dir === 'desc' ? -d : d;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function table(name, idKey, { include } = {}) {
|
||||||
|
const m = t[name];
|
||||||
|
const withIncludes = (row, inc) => {
|
||||||
|
if (!inc) return row;
|
||||||
|
const out = { ...row };
|
||||||
|
if (inc._count) out._count = { importedEvents: [...t.importedEvent.values()].filter((e) => e.linkId === row.installId).length };
|
||||||
|
if (inc.link) out.link = { ...t.productLink.get(row.linkId) };
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
findUnique: jest.fn(async ({ where, select }) => { const r = m.get(where[idKey]); return r ? pick(clone(r), select) : null; }),
|
||||||
|
findFirst: jest.fn(async ({ where, include: inc } = {}) => { const r = [...m.values()].find((x) => matches(x, where)); return r ? withIncludes(clone(r), inc) : null; }),
|
||||||
|
findMany: jest.fn(async ({ where, select, include: inc, orderBy, take } = {}) => sortBy([...m.values()].filter((x) => matches(x, where)), orderBy).slice(0, take ?? Infinity).map((r) => withIncludes(pick(clone(r), select), inc))),
|
||||||
|
create: jest.fn(async ({ data }) => {
|
||||||
|
if (m.has(data[idKey])) throw Object.assign(new Error('Unique constraint failed'), { code: 'P2002' });
|
||||||
|
m.set(data[idKey], clone(data));
|
||||||
|
return clone(data);
|
||||||
|
}),
|
||||||
|
upsert: jest.fn(async ({ where, create, update }) => {
|
||||||
|
const prev = m.get(where[idKey]);
|
||||||
|
const row = prev ? { ...prev, ...update } : { ...create };
|
||||||
|
m.set(where[idKey], clone(row));
|
||||||
|
return clone(row);
|
||||||
|
}),
|
||||||
|
update: jest.fn(async ({ where, data }) => {
|
||||||
|
const prev = m.get(where[idKey]);
|
||||||
|
if (!prev) throw Object.assign(new Error('Record to update not found'), { code: 'P2025' });
|
||||||
|
const row = { ...prev, ...data };
|
||||||
|
m.set(where[idKey], clone(row));
|
||||||
|
return clone(row);
|
||||||
|
}),
|
||||||
|
delete: jest.fn(async ({ where }) => {
|
||||||
|
const prev = m.get(where[idKey]);
|
||||||
|
if (!prev) throw Object.assign(new Error('Record to delete does not exist'), { code: 'P2025' });
|
||||||
|
m.delete(where[idKey]);
|
||||||
|
if (name === 'productLink') for (const [k, e] of t.importedEvent) if (e.linkId === where[idKey]) t.importedEvent.delete(k);
|
||||||
|
return prev;
|
||||||
|
}),
|
||||||
|
deleteMany: jest.fn(async ({ where } = {}) => {
|
||||||
|
let count = 0;
|
||||||
|
for (const [k, r] of m) if (matches(r, where)) { m.delete(k); count++; }
|
||||||
|
return { count };
|
||||||
|
}),
|
||||||
|
...include,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const db = {
|
||||||
|
t,
|
||||||
|
appSetting: table('appSetting', 'key'),
|
||||||
|
productLink: table('productLink', 'installId'),
|
||||||
|
linkNonce: table('linkNonce', 'nonce'),
|
||||||
|
importedEvent: table('importedEvent', 'key'),
|
||||||
|
feedEntry: table('feedEntry', 'eventId'),
|
||||||
|
event: table('event', 'id'),
|
||||||
|
campus: { findMany: jest.fn(async () => t.campus.map((c) => ({ ...c }))) },
|
||||||
|
user: { findMany: jest.fn(async ({ where }) => t.user.filter((u) => matches(u, where))) },
|
||||||
|
adminAuditLog: { create: jest.fn(async ({ data }) => { t.audit.push(data); return data; }) },
|
||||||
|
reset() {
|
||||||
|
for (const k of ['appSetting', 'productLink', 'linkNonce', 'importedEvent', 'feedEntry', 'event']) t[k].clear();
|
||||||
|
t.campus.length = 0; t.user.length = 0; t.audit.length = 0;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = db;
|
||||||
@@ -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', () => {
|
describe('availableMethods', () => {
|
||||||
test('offers WhatsApp only with a valid phone and a configured gateway', async () => {
|
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;
|
mockWhatsApp.configured = false;
|
||||||
expect(await availableMethods(USER)).toEqual(['email']);
|
expect(await availableMethods(USER)).toEqual(['email', 'authenticator']);
|
||||||
mockWhatsApp.configured = true;
|
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 () => {
|
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 { ServiceError } from '../src/services/errors';
|
||||||
import { routes } from '../src/v2/route';
|
import { routes } from '../src/v2/route';
|
||||||
import { buildOpenApi } from '../src/v2/openapi';
|
import { buildOpenApi } from '../src/v2/openapi';
|
||||||
|
import { absoluteUrl, uploadPath } from '../src/v2/schemas';
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
app.use(express.json());
|
app.use(express.json());
|
||||||
@@ -129,7 +130,7 @@ describe('GET /api/v2/events', () => {
|
|||||||
expect(res.status).toBe(200);
|
expect(res.status).toBe(200);
|
||||||
expect(res.body.meta).toEqual({ page: 2, limit: 10, total: 31, pages: 4 });
|
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]).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];
|
const args = mockDb.event.findMany.mock.calls[0][0];
|
||||||
expect(args).toMatchObject({ skip: 10, take: 10 });
|
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' } }]));
|
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');
|
const res = await request(app).get('/api/v2/events/manage?past=true');
|
||||||
expect(res.status).toBe(200);
|
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]).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 }));
|
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' };
|
mockImage.file = { filename: 'event-123.jpg' };
|
||||||
const res = await request(app).post('/api/v2/uploads/event-image');
|
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.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 () => {
|
test('branding images are for admins once accounts exist', async () => {
|
||||||
@@ -683,7 +693,7 @@ describe('money (v1 handlers behind v2 routes)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('AI helpers (2.0)', () => {
|
describe('AI helpers (2.0)', () => {
|
||||||
const st = { enabled: true, capReached: false, available: true, capCents: 5000, usedCents: 1, usedPercent: 0, renewsOn: '2026-12-01', helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } };
|
const st = { enabled: true, capReached: false, available: true, usedPercent: 0, renewsOn: '2026-12-01', usedInputTokens: 1000, usedOutputTokens: 200, capInputTokens: 1785000, capOutputTokens: 357000, helpers: { draft_event: true, summarise_report: true, draft_message: true, summarise_feedback: true, improve_text: true } };
|
||||||
|
|
||||||
test('supervisors only', async () => {
|
test('supervisors only', async () => {
|
||||||
signedIn = { id: 's1', role: 'staff' };
|
signedIn = { id: 's1', role: 'staff' };
|
||||||
|
|||||||
@@ -1,12 +1,16 @@
|
|||||||
# Handover — where things stand and how to carry on
|
# 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-18, after **2.3.1** (Next.js 16.4.6 for security advisories, on top of 2.3.0;
|
||||||
|
released, 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
|
(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/`** →
|
phase stands are in the monorepo's root `docs/`** →
|
||||||
[ROADMAP-v3.md](../../../docs/ROADMAP-v3.md),
|
[ROADMAP-v3.md](../../../docs/ROADMAP-v3.md),
|
||||||
[HANDOVER.md](../../../docs/HANDOVER.md) (all products) and
|
[HANDOVER.md](../../../docs/HANDOVER.md) (all products) and
|
||||||
[EVENTS-2.2-PLAN.md](../../../docs/EVENTS-2.2-PLAN.md) (the next Events release:
|
[EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md) (the next Events release: protocol v2,
|
||||||
the move into the monorepo). The Hub protocol is there too ([hub-protocol.md](../../../docs/hub-protocol.md)). How Cross
|
Linked products, the event feed and `packages/seo`; the move into the monorepo was
|
||||||
|
[EVENTS-2.2-PLAN.md](../../../docs/EVENTS-2.2-PLAN.md)). The Hub protocol is there too ([hub-protocol.md](../../../docs/hub-protocol.md)). How Cross
|
||||||
Events got to 2.x is in [ROADMAP-v2.md](./ROADMAP-v2.md); the round before that in
|
Events got to 2.x is in [ROADMAP-v2.md](./ROADMAP-v2.md); the round before that in
|
||||||
[FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md).
|
[FEATURES-ROUND-1.md](./FEATURES-ROUND-1.md).
|
||||||
|
|
||||||
@@ -95,13 +99,14 @@ encrypted settings unreadable or break existing installs.
|
|||||||
## Next up
|
## Next up
|
||||||
|
|
||||||
1. **Roadmap v3**, across every product: see `crosscode-platform/docs/HANDOVER.md` ("Where each
|
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
|
phase stands", "Next up"). **2.2.0** (the move into the monorepo) and **2.3.0** (authenticator
|
||||||
`apps/events`, with the `crosscode` script; `crosscode-platform/docs/EVENTS-2.2-PLAN.md`), then
|
app 2FA and recovery codes, plus what installs from the Hub need) are released (2026-11-17;
|
||||||
**2.3.0** (authenticator app 2FA, `TwoFactorMethod` in `prisma/schema.prisma`) and **2.4.0**
|
**2.3.1** with Next.js 16.4.6 on 2026-11-18). Next for Cross Events is **rolling them out**
|
||||||
(protocol v2, Linked products, the event feed).
|
(each install adopted from the Hub, on 2.3.1), then **2.4.0** (protocol v2, Linked products,
|
||||||
- **Deploying until 2.2.0:** `bash scripts/deploy.sh --check`, then
|
the event feed), planned in [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md).
|
||||||
`bash scripts/deploy.sh v<version>` on each server (installs ask through Request update as
|
- **Deploying:** installs still on 2.1.1 move with `adopt` (Hub → Servers → Installs → Link
|
||||||
usual). From 2.2.0 on: `crosscode deploy <church> events`.
|
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
|
- **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.
|
no cap the buttons don't show.
|
||||||
- Testing AI locally: run the Hub (`../events-hub`, port 5200), set Settings → AI there, give a
|
- Testing AI locally: run the Hub (`../events-hub`, port 5200), set Settings → AI there, give a
|
||||||
@@ -119,6 +124,47 @@ encrypted settings unreadable or break existing installs.
|
|||||||
|
|
||||||
Languages (Afrikaans, §10) and Wallet passes (§7) are removed from scope (2026-10-28).
|
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`.
|
||||||
|
|
||||||
|
## Where Linked products and the feed live (2.4.0)
|
||||||
|
|
||||||
|
Plan and reasons: the root [EVENTS-2.4-PLAN.md](../../../docs/EVENTS-2.4-PLAN.md).
|
||||||
|
|
||||||
|
- **Protocol v2**: `backend/src/hub/client.js` (`heartbeatBody`, the v1 fallback `hub_v1_until`).
|
||||||
|
The key pair and the Hub's list of the church's products: `backend/src/links/store.ts`.
|
||||||
|
- **Connect** (`crosscode.link/1`): `backend/src/links/connect.ts` (both directions),
|
||||||
|
`links/http.ts` (calls to siblings: public addresses only, like webhooks), `links/routes.ts`
|
||||||
|
(`/api/feed/v1/*`, `/api/links/v1/*`, mounted in `app.js` before the JSON parser).
|
||||||
|
- **The feed**: `backend/src/feed/build.ts` (an Event as `crosscode.event/1`, also for the event
|
||||||
|
page's JSON-LD), `feed/entries.ts` (`FeedEntry`, refresh, `changedSoon` from `config/db.js`),
|
||||||
|
`feed/notify.ts` (`event.changed`), `feed/sync.ts` (fetching linked products' events into
|
||||||
|
`ImportedEvent`). Jobs `feed`, `feed-sync`; task `feed-sync-link`.
|
||||||
|
- **Screens**: `frontend/src/components/admin/LinkedProductsTab.tsx` (Site settings → Linked
|
||||||
|
products), `components/events/LinkedEventCard.tsx`, `lib/linkedEvents.ts`,
|
||||||
|
`app/events/linked/[product]/[id]/page.tsx`. API: `backend/src/v2/resources/linkedProducts.ts`.
|
||||||
|
- **Tests**: `backend/tests/linkedProducts.test.js` (in-memory database:
|
||||||
|
`tests/support/fakeFeedDb.js`), `e2e/linked-products.spec.ts` (a fake Church Website on
|
||||||
|
localhost:5198).
|
||||||
|
|
||||||
## Working on this repo
|
## Working on this repo
|
||||||
|
|
||||||
- **Release routine:** branch `feat/<name>` → commit → bump with
|
- **Release routine:** branch `feat/<name>` → commit → bump with
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { test, expect, seed, API } from "./fixtures";
|
import { test, expect, seed, API } from "./fixtures";
|
||||||
|
|
||||||
// /api/v2 (1.51.0) against the real server and database: paged public events, the v2 error
|
// /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.describe("API v2", () => {
|
||||||
test("public events come a page at a time; errors have a code", async ({ request }) => {
|
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`);
|
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`);
|
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`);
|
const followed = await request.get(`${API}/api/events/${seed().events.conference}/ics`);
|
||||||
expect(followed.headers()["content-type"]).toContain("text/calendar");
|
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 });
|
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 }) => {
|
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);
|
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}` };
|
const headers = { Authorization: `Bearer ${seed().users.user.token}` };
|
||||||
expect((await request.get(`${API}/api/v2/openapi.json`, { headers })).status()).toBe(403);
|
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();
|
await expect(page.getByRole("heading", { name: /Cross Events API/ })).toBeVisible();
|
||||||
// Sections start collapsed (there are hundreds of endpoints): open Events.
|
// Sections start collapsed (there are hundreds of endpoints): open Events.
|
||||||
await page.locator('h3.opblock-tag[data-tag="Events"]').click();
|
await page.locator('h3.opblock-tag[data-tag="Events"]').click();
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
import http from "http";
|
||||||
|
import path from "path";
|
||||||
|
import crypto from "crypto";
|
||||||
|
import { test, expect, loginAs, seed, API } from "./fixtures";
|
||||||
|
|
||||||
|
// Linked products and the event feed (2.4.0, docs/EVENTS-2.4-PLAN.md §8). A fake Church Website
|
||||||
|
// runs on localhost: the test tells the site the Hub listed it (as a heartbeat would), an admin
|
||||||
|
// connects it and shows its events, and its event appears on /events with its own page whose
|
||||||
|
// canonical link points back to the website. Also: this site's own feed, and its event JSON-LD.
|
||||||
|
/* eslint-disable @typescript-eslint/no-require-imports -- the backend's own modules, as prepare-db.js uses them */
|
||||||
|
const backend = path.join(__dirname, "..", "backend");
|
||||||
|
const { Client } = require(require.resolve("pg", { paths: [backend] }));
|
||||||
|
const { e2eDatabaseUrl } = require("./support/db-url");
|
||||||
|
const signing = require(require.resolve("@crosscode/contracts/signing", { paths: [backend] }));
|
||||||
|
const { eventFeedSchema } = require(require.resolve("@crosscode/contracts", { paths: [backend] }));
|
||||||
|
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||||
|
|
||||||
|
const WEBSITE_PORT = 5198;
|
||||||
|
const WEBSITE_URL = `http://localhost:${WEBSITE_PORT}`;
|
||||||
|
const WEBSITE_ID = "3b0f6a52-6c1e-4b7a-9d0e-2f1a8c4b7e02";
|
||||||
|
const EVENTS_ID = "9a4c2f1e-7b3d-4e5a-8c6f-0d1e2f3a4b5c";
|
||||||
|
const EVENT_ID = "6e5d4c3b-2a19-4807-b6f5-e4d3c2b1a090";
|
||||||
|
const websiteKey = signing.generateEd25519();
|
||||||
|
const websitePem = signing.ed25519PublicToPem(websiteKey.publicKey);
|
||||||
|
|
||||||
|
async function sql<T = Record<string, unknown>>(text: string, values: unknown[] = []): Promise<T[]> {
|
||||||
|
const client = new Client({ connectionString: e2eDatabaseUrl() });
|
||||||
|
await client.connect();
|
||||||
|
try {
|
||||||
|
return (await client.query(text, values)).rows as T[];
|
||||||
|
} finally {
|
||||||
|
await client.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const setSetting = (key: string, value: string) =>
|
||||||
|
sql(`INSERT INTO "AppSetting" (key, value, "updatedAt") VALUES ($1, $2, now()) ON CONFLICT (key) DO UPDATE SET value = $2, "updatedAt" = now()`, [key, value]);
|
||||||
|
|
||||||
|
function websiteEvent() {
|
||||||
|
const starts = new Date(Date.now() + 10 * 24 * 3600e3);
|
||||||
|
return {
|
||||||
|
schema: "crosscode.event/1",
|
||||||
|
id: EVENT_ID,
|
||||||
|
origin: { product: "website", installId: WEBSITE_ID, url: `${WEBSITE_URL}/events/carols-by-candlelight` },
|
||||||
|
status: "published",
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
title: "Carols by Candlelight",
|
||||||
|
summary: null,
|
||||||
|
description: "Bring a **blanket** and the family.\n\n<script>alert(1)</script>No booking needed.",
|
||||||
|
imageUrl: null,
|
||||||
|
timezone: "Africa/Johannesburg",
|
||||||
|
startsAt: starts.toISOString(),
|
||||||
|
endsAt: new Date(starts.getTime() + 2 * 3600e3).toISOString(),
|
||||||
|
allDay: false,
|
||||||
|
sessions: [],
|
||||||
|
location: { name: "Church lawn", address: null, onlineUrl: null },
|
||||||
|
campus: null,
|
||||||
|
series: null,
|
||||||
|
tags: ["christmas"],
|
||||||
|
registration: { mode: "contact", url: null, status: "open", opensAt: null, closesAt: null, priceFrom: null },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test.describe.serial("linked products and the event feed", () => {
|
||||||
|
let server: http.Server;
|
||||||
|
const connects: Record<string, unknown>[] = [];
|
||||||
|
|
||||||
|
test.beforeAll(async () => {
|
||||||
|
server = http.createServer((req, res) => {
|
||||||
|
let body = "";
|
||||||
|
req.on("data", c => { body += c; });
|
||||||
|
req.on("end", async () => {
|
||||||
|
const send = (status: number, json: unknown) => res.writeHead(status, { "Content-Type": "application/json" }).end(JSON.stringify(json));
|
||||||
|
if (req.method === "POST" && req.url === "/api/links/v1/connect") {
|
||||||
|
const m = JSON.parse(body);
|
||||||
|
connects.push(m);
|
||||||
|
// The website checks Cross Events' message with the key the Hub listed for it.
|
||||||
|
const [row] = await sql<{ value: string }>(`SELECT value FROM "AppSetting" WHERE key = 'hub_public_key'`);
|
||||||
|
if (!row || !signing.verifyLink(m, row.value).ok) return send(401, { message: "Bad signature", code: "BAD_SIGNATURE" });
|
||||||
|
return send(200, signing.signLink({
|
||||||
|
schema: "crosscode.link/1", type: "link.connected",
|
||||||
|
from: { product: "website", installId: WEBSITE_ID, url: WEBSITE_URL }, to: { installId: EVENTS_ID },
|
||||||
|
inReplyTo: m.nonce, issuedAt: new Date().toISOString(), nonce: crypto.randomBytes(18).toString("base64url"),
|
||||||
|
}, websiteKey.privateKeyPem));
|
||||||
|
}
|
||||||
|
if (req.method === "GET" && req.url?.startsWith("/api/feed/v1/events")) {
|
||||||
|
return send(200, { schema: "crosscode.event-feed/1", generatedAt: new Date().toISOString(), events: [websiteEvent()], deleted: [] });
|
||||||
|
}
|
||||||
|
if (req.method === "POST" && req.url === "/api/links/v1/disconnect") return send(200, { schema: "crosscode.link/1", type: "link.disconnected" });
|
||||||
|
return send(404, { message: "Not here", code: "NOT_FOUND" });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
await new Promise<void>(resolve => server.listen(WEBSITE_PORT, resolve));
|
||||||
|
// What a v2 heartbeat would have stored: this site's Hub id and the church's other products.
|
||||||
|
await setSetting("hub_install_id", EVENTS_ID);
|
||||||
|
await setSetting("hub_linked_products", JSON.stringify([{ product: "website", installId: WEBSITE_ID, url: WEBSITE_URL, publicKey: websitePem }]));
|
||||||
|
});
|
||||||
|
|
||||||
|
test.afterAll(async () => {
|
||||||
|
await sql(`DELETE FROM "ProductLink"`);
|
||||||
|
await sql(`DELETE FROM "FeedEntry"`);
|
||||||
|
await sql(`DELETE FROM "AppSetting" WHERE key IN ('hub_install_id', 'hub_linked_products', 'feed_publish')`);
|
||||||
|
await new Promise(resolve => server.close(resolve));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an admin connects the Church Website and shows its events", async ({ page }) => {
|
||||||
|
await loginAs(page, "admin");
|
||||||
|
await page.goto("/dashboard/admin/settings?tab=linked");
|
||||||
|
const row = page.getByTestId("linked-website");
|
||||||
|
await expect(row).toContainText("Church Website");
|
||||||
|
await expect(row).toContainText("Not connected");
|
||||||
|
await row.getByRole("button", { name: "Connect" }).click();
|
||||||
|
await expect(page.getByRole("status")).toContainText("Connected to Church Website.");
|
||||||
|
expect(connects).toHaveLength(1);
|
||||||
|
expect(connects[0]).toMatchObject({ type: "link.connect", from: { product: "events", installId: EVENTS_ID }, to: { installId: WEBSITE_ID } });
|
||||||
|
|
||||||
|
await row.getByLabel(/Show events from Church Website/).check();
|
||||||
|
await expect(page.getByRole("status")).toContainText("events are fetched");
|
||||||
|
await expect(row).toContainText("1 event");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("its event is on /events, with its own page pointing back to the website", async ({ page }) => {
|
||||||
|
await page.goto("/events");
|
||||||
|
const card = page.getByTestId("linked-event-card").filter({ hasText: "Carols by Candlelight" });
|
||||||
|
await expect(card).toContainText("From the Church Website");
|
||||||
|
await card.getByRole("link", { name: "View details" }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(new RegExp(`/events/linked/website/${EVENT_ID}$`));
|
||||||
|
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Carols by Candlelight");
|
||||||
|
await expect(page.locator('link[rel="canonical"]')).toHaveAttribute("href", `${WEBSITE_URL}/events/carols-by-candlelight`);
|
||||||
|
await expect(page.locator("strong", { hasText: "blanket" })).toBeVisible();
|
||||||
|
// HTML in the description is dropped, never run.
|
||||||
|
expect(await page.locator("main script").count()).toBe(0);
|
||||||
|
expect(await page.locator('script[type="application/ld+json"]').count()).toBe(0);
|
||||||
|
|
||||||
|
const sitemap = await (await page.request.get("/sitemap.xml")).text();
|
||||||
|
expect(sitemap).not.toContain("/events/linked/");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("this site's own feed and event JSON-LD", async ({ page, request }) => {
|
||||||
|
const res = await request.get(`${API}/api/feed/v1/events`);
|
||||||
|
expect(res.status()).toBe(200);
|
||||||
|
const feed = await res.json();
|
||||||
|
expect(eventFeedSchema.safeParse(feed).success).toBe(true);
|
||||||
|
const ids = feed.events.map((e: { id: string }) => e.id);
|
||||||
|
expect(ids).toContain(seed().events.free);
|
||||||
|
expect(ids).not.toContain(EVENT_ID);
|
||||||
|
expect(JSON.stringify(feed)).not.toMatch(/@e2e\.test/);
|
||||||
|
|
||||||
|
await page.goto(`/events/${seed().events.free}`);
|
||||||
|
const ld = JSON.parse(await page.locator('script[type="application/ld+json"]').innerText());
|
||||||
|
expect(ld).toMatchObject({ "@context": "https://schema.org", "@type": "Event", url: expect.stringContaining(`/events/${seed().events.free}`) });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("disconnecting removes its events", async ({ page }) => {
|
||||||
|
await loginAs(page, "admin");
|
||||||
|
await page.goto("/dashboard/admin/settings?tab=linked");
|
||||||
|
page.once("dialog", d => d.accept());
|
||||||
|
await page.getByTestId("linked-website").getByRole("button", { name: "Disconnect" }).click();
|
||||||
|
await expect(page.getByRole("status")).toContainText("Disconnected from Church Website.");
|
||||||
|
await page.goto("/events");
|
||||||
|
await expect(page.getByTestId("linked-event-card")).toHaveCount(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -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",
|
"name": "@crosscode/events-frontend",
|
||||||
"version": "2.1.1",
|
"version": "2.3.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
@@ -10,6 +10,8 @@
|
|||||||
"api:types": "openapi-typescript src/lib/api-v2/openapi.json -o src/lib/api-v2/schema.d.ts"
|
"api:types": "openapi-typescript src/lib/api-v2/openapi.json -o src/lib/api-v2/schema.d.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@crosscode/contracts": "*",
|
||||||
|
"@crosscode/seo": "*",
|
||||||
"@dnd-kit/core": "^6.3.1",
|
"@dnd-kit/core": "^6.3.1",
|
||||||
"@hookform/resolvers": "^5.2.1",
|
"@hookform/resolvers": "^5.2.1",
|
||||||
"@radix-ui/react-accordion": "^1.2.11",
|
"@radix-ui/react-accordion": "^1.2.11",
|
||||||
@@ -36,12 +38,13 @@
|
|||||||
"date-fns": "^4.1.0",
|
"date-fns": "^4.1.0",
|
||||||
"idb": "^8.0.4",
|
"idb": "^8.0.4",
|
||||||
"lucide-react": "^0.536.0",
|
"lucide-react": "^0.536.0",
|
||||||
"next": "^16.4.3",
|
"next": "^16.4.6",
|
||||||
"qrcode": "^1.5.4",
|
"qrcode": "^1.5.4",
|
||||||
"react": "^19.3.1",
|
"react": "^19.3.1",
|
||||||
"react-day-picker": "^9.8.1",
|
"react-day-picker": "^9.8.1",
|
||||||
"react-dom": "^19.3.1",
|
"react-dom": "^19.3.1",
|
||||||
"react-hook-form": "^7.62.0",
|
"react-hook-form": "^7.62.0",
|
||||||
|
"react-markdown": "^10.1.0",
|
||||||
"react-webcam": "^7.2.0",
|
"react-webcam": "^7.2.0",
|
||||||
"tailwind-merge": "^3.3.1",
|
"tailwind-merge": "^3.3.1",
|
||||||
"tailwindcss-animate": "^1.0.7",
|
"tailwindcss-animate": "^1.0.7",
|
||||||
@@ -55,7 +58,7 @@
|
|||||||
"@types/react-dom": "^19.3.0",
|
"@types/react-dom": "^19.3.0",
|
||||||
"autoprefixer": "^10.4.21",
|
"autoprefixer": "^10.4.21",
|
||||||
"eslint": "^10.13.0",
|
"eslint": "^10.13.0",
|
||||||
"eslint-config-next": "^16.4.3",
|
"eslint-config-next": "^16.4.6",
|
||||||
"openapi-typescript": "^7.13.0",
|
"openapi-typescript": "^7.13.0",
|
||||||
"postcss": "^8.5.6",
|
"postcss": "^8.5.6",
|
||||||
"tailwindcss": "3.4",
|
"tailwindcss": "3.4",
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import { notFound } from "next/navigation";
|
|||||||
import { Navbar } from "@/components/layout/Navbar";
|
import { Navbar } from "@/components/layout/Navbar";
|
||||||
import { Footer } from "@/components/layout/Footer";
|
import { Footer } from "@/components/layout/Footer";
|
||||||
import { EventCard } from "@/components/events/EventCard";
|
import { EventCard } from "@/components/events/EventCard";
|
||||||
|
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
|
||||||
|
import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents";
|
||||||
import { ApiImage } from "@/components/shared/ApiImage";
|
import { ApiImage } from "@/components/shared/ApiImage";
|
||||||
import { apiFetchListForPrerender, ApiError } from "@/lib/api";
|
import { apiFetchListForPrerender, ApiError } from "@/lib/api";
|
||||||
import { mapsSearchUrl } from "@/lib/maps";
|
import { mapsSearchUrl } from "@/lib/maps";
|
||||||
@@ -42,13 +44,17 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
|
|||||||
const campus = await loadCampus(slug);
|
const campus = await loadCampus(slug);
|
||||||
if (!campus) notFound();
|
if (!campus) notFound();
|
||||||
|
|
||||||
const events = await apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } });
|
const [events, linked] = await Promise.all([
|
||||||
|
apiFetchListForPrerender<Event>(`/api/v2/event-listing?campus=${encodeURIComponent(campus.slug)}`, { nextOptions: { next: { revalidate } } }),
|
||||||
|
fetchLinkedEvents(campus.slug),
|
||||||
|
]);
|
||||||
// A server component renders once per request (or revalidation): this is that render's time.
|
// A server component renders once per request (or revalidation): this is that render's time.
|
||||||
// eslint-disable-next-line react-hooks/purity
|
// eslint-disable-next-line react-hooks/purity
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const upcoming = (events || [])
|
const upcoming = (events || [])
|
||||||
.filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now)
|
.filter(e => e.cashupStatus !== "closed" && new Date(e.endDate || e.startDate).getTime() > now)
|
||||||
.sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
|
.sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
|
||||||
|
const items = mergeByStart(upcoming, linked, e => e.nextSession?.startsAt || e.startDate);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex flex-col">
|
<div className="min-h-screen flex flex-col">
|
||||||
@@ -79,14 +85,16 @@ export default async function CampusPage({ params }: { params: Promise<{ slug: s
|
|||||||
|
|
||||||
<h2 className="text-xl font-semibold text-gray-900 mb-1">Upcoming events</h2>
|
<h2 className="text-xl font-semibold text-gray-900 mb-1">Upcoming events</h2>
|
||||||
<p className="text-sm text-gray-500 mb-6">Events at {campus.name}, and church-wide events for every campus.</p>
|
<p className="text-sm text-gray-500 mb-6">Events at {campus.name}, and church-wide events for every campus.</p>
|
||||||
{upcoming.length === 0 ? (
|
{items.length === 0 ? (
|
||||||
<div className="text-center py-16 border rounded-xl bg-gray-50">
|
<div className="text-center py-16 border rounded-xl bg-gray-50">
|
||||||
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
||||||
<p className="text-gray-500 text-sm">No upcoming events at {campus.name} right now — check back soon.</p>
|
<p className="text-gray-500 text-sm">No upcoming events at {campus.name} right now — check back soon.</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
||||||
{upcoming.map(event => <EventCard key={event.id} event={event} />)}
|
{items.map(item => item.kind === "own"
|
||||||
|
? <EventCard key={item.event.id} event={item.event} />
|
||||||
|
: <LinkedEventCard key={item.event.key} item={item.event} />)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import { ApiError, resolveToApiOrigin } from "@/lib/api";
|
|||||||
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
|
import { apiV2Raw, apiV2Data } from "@/lib/apiV2";
|
||||||
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
import { useSiteSettings } from "@/contexts/SiteSettingsContext";
|
||||||
import { useDismissingState } from "@/hooks/useDismissingState";
|
import { useDismissingState } from "@/hooks/useDismissingState";
|
||||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles } from "lucide-react";
|
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, CreditCard, DatabaseBackup, Timer, KeyRound, MapPinned, type LucideIcon, Webhook, Sparkles, Link2 } from "lucide-react";
|
||||||
import { ColorPickerField } from "@/components/admin/ColorPickerField";
|
import { ColorPickerField } from "@/components/admin/ColorPickerField";
|
||||||
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
|
import { BrandingPreviewPanel } from "@/components/admin/BrandingPreviewPanel";
|
||||||
import { BackupsTab } from "@/components/admin/BackupsTab";
|
import { BackupsTab } from "@/components/admin/BackupsTab";
|
||||||
@@ -17,6 +17,7 @@ import { PaymentsTab } from "@/components/admin/PaymentsTab";
|
|||||||
import { LicenceTab } from "@/components/admin/LicenceTab";
|
import { LicenceTab } from "@/components/admin/LicenceTab";
|
||||||
import { WebhooksTab } from "@/components/admin/WebhooksTab";
|
import { WebhooksTab } from "@/components/admin/WebhooksTab";
|
||||||
import { AiTab } from "@/components/admin/AiTab";
|
import { AiTab } from "@/components/admin/AiTab";
|
||||||
|
import { LinkedProductsTab } from "@/components/admin/LinkedProductsTab";
|
||||||
import { CampusesTab } from "@/components/admin/CampusesTab";
|
import { CampusesTab } from "@/components/admin/CampusesTab";
|
||||||
import { extractDominantColors } from "@/lib/extractColors";
|
import { extractDominantColors } from "@/lib/extractColors";
|
||||||
import { mapsSearchUrl } from "@/lib/maps";
|
import { mapsSearchUrl } from "@/lib/maps";
|
||||||
@@ -25,7 +26,7 @@ import { BackLink } from "@/components/shared/BackLink";
|
|||||||
import { uploadImage } from "@/lib/eventSetup";
|
import { uploadImage } from "@/lib/eventSetup";
|
||||||
import { useExternalEffect } from "@/lib/hooks";
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "backups" | "jobs" | "licence" | "ai";
|
type TabId = "organisation" | "campuses" | "branding" | "notifications" | "email" | "legal" | "whatsapp" | "payments" | "webhooks" | "linked" | "backups" | "jobs" | "licence" | "ai";
|
||||||
|
|
||||||
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
||||||
{ id: "organisation", label: "Organisation", icon: Building2 },
|
{ id: "organisation", label: "Organisation", icon: Building2 },
|
||||||
@@ -37,6 +38,7 @@ const TABS: { id: TabId; label: string; icon: LucideIcon }[] = [
|
|||||||
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
|
{ id: "whatsapp", label: "WhatsApp", icon: MessageCircle },
|
||||||
{ id: "payments", label: "Payments", icon: CreditCard },
|
{ id: "payments", label: "Payments", icon: CreditCard },
|
||||||
{ id: "webhooks", label: "Webhooks", icon: Webhook },
|
{ id: "webhooks", label: "Webhooks", icon: Webhook },
|
||||||
|
{ id: "linked", label: "Linked products", icon: Link2 },
|
||||||
{ id: "backups", label: "Backups", icon: DatabaseBackup },
|
{ id: "backups", label: "Backups", icon: DatabaseBackup },
|
||||||
{ id: "jobs", label: "Background jobs", icon: Timer },
|
{ id: "jobs", label: "Background jobs", icon: Timer },
|
||||||
{ id: "licence", label: "Licence", icon: KeyRound },
|
{ id: "licence", label: "Licence", icon: KeyRound },
|
||||||
@@ -718,6 +720,7 @@ function SiteSettingsPageInner() {
|
|||||||
{/* ── Backups ───────────────────────────────────────────────────────── */}
|
{/* ── Backups ───────────────────────────────────────────────────────── */}
|
||||||
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
|
{activeTab === "backups" && <BackupsTab active={activeTab === "backups"} />}
|
||||||
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
|
{activeTab === "webhooks" && <WebhooksTab active={activeTab === "webhooks"} />}
|
||||||
|
{activeTab === "linked" && <LinkedProductsTab active={activeTab === "linked"} />}
|
||||||
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
|
{activeTab === "jobs" && <JobsTab active={activeTab === "jobs"} />}
|
||||||
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
|
{activeTab === "licence" && <LicenceTab active={activeTab === "licence"} />}
|
||||||
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
|
{activeTab === "ai" && <AiTab active={activeTab === "ai"} />}
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ interface UserItem {
|
|||||||
phoneNumber?: string | null;
|
phoneNumber?: string | null;
|
||||||
notificationPreference?: string;
|
notificationPreference?: string;
|
||||||
twoFactorEnabled?: boolean;
|
twoFactorEnabled?: boolean;
|
||||||
|
twoFactorMethod?: "email" | "whatsapp" | "authenticator" | null;
|
||||||
isActive: boolean;
|
isActive: boolean;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
@@ -34,6 +35,8 @@ type Role = typeof roleOptions[number];
|
|||||||
const notificationPreferenceOptions = ["email", "whatsapp", "both"] as const;
|
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() {
|
export default function AdminUsersPage() {
|
||||||
const { user, loading, token } = useAuth();
|
const { user, loading, token } = useAuth();
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
@@ -418,6 +421,9 @@ export default function AdminUsersPage() {
|
|||||||
</td>
|
</td>
|
||||||
<td className="p-2">
|
<td className="p-2">
|
||||||
<RoleBadge role={u.role as RoleBadgeRole} />
|
<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>
|
||||||
<td className="p-2">
|
<td className="p-2">
|
||||||
<span>{u.phoneNumber || ""}</span>
|
<span>{u.phoneNumber || ""}</span>
|
||||||
|
|||||||
@@ -14,17 +14,19 @@ import { useCampuses } from "@/hooks/useCampuses";
|
|||||||
import { apiV2, apiV2Data } from "@/lib/apiV2";
|
import { apiV2, apiV2Data } from "@/lib/apiV2";
|
||||||
import { useStateSync } from "@/lib/hooks";
|
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 }> = {
|
const ACTIVITY_META: Record<ActivityEvent["type"], { label: (device: string | null) => string; icon: typeof LogIn }> = {
|
||||||
login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn },
|
login: { label: d => `Logged in${d ? ` from ${d}` : ""}`, icon: LogIn },
|
||||||
password_changed: { label: () => "Password changed", icon: KeyRound },
|
password_changed: { label: () => "Password changed", icon: KeyRound },
|
||||||
password_reset: { label: () => "Password reset via email link", icon: RotateCcw },
|
password_reset: { label: () => "Password reset via email link", icon: RotateCcw },
|
||||||
two_factor_enabled: { label: () => "Two-factor authentication turned on", icon: ShieldCheck },
|
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 },
|
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).
|
// 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 } }) => (
|
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.
|
// loaded once per page load, so it wouldn't reflect a change made here.
|
||||||
const [tfEnabled, setTfEnabled] = useState(false);
|
const [tfEnabled, setTfEnabled] = useState(false);
|
||||||
const [tfMethod, setTfMethod] = useState<TwoFactorMethod>("email");
|
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 [tfPassword, setTfPassword] = useState("");
|
||||||
const [tfCode, setTfCode] = useState("");
|
const [tfCode, setTfCode] = useState("");
|
||||||
const [tfChallenge, setTfChallenge] = useState<TwoFactorChallenge | null>(null);
|
const [tfChallenge, setTfChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||||
const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
const [tfMsg, setTfMsg] = useDismissingState<{ type: "ok" | "err"; text: string } | null>(null);
|
||||||
const [tfBusy, setTfBusy] = useState(false);
|
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.
|
// WhatsApp codes need the number that's actually saved, not one still being typed.
|
||||||
const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || "");
|
const canWhatsAppCodes = isValidZAPhone(user?.phoneNumber || "");
|
||||||
@@ -201,9 +207,19 @@ export default function UserProfilePage() {
|
|||||||
if (user) {
|
if (user) {
|
||||||
setTfEnabled(!!user.twoFactorEnabled);
|
setTfEnabled(!!user.twoFactorEnabled);
|
||||||
setTfMethod(user.twoFactorMethod || "email");
|
setTfMethod(user.twoFactorMethod || "email");
|
||||||
|
setTfRecoveryLeft((user as { recoveryCodesLeft?: number }).recoveryCodesLeft ?? 0);
|
||||||
}
|
}
|
||||||
}, [user]);
|
}, [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 = () => {
|
const resetTwoFactorForm = () => {
|
||||||
setTfStep("idle");
|
setTfStep("idle");
|
||||||
setTfPassword("");
|
setTfPassword("");
|
||||||
@@ -241,12 +257,14 @@ export default function UserProfilePage() {
|
|||||||
const res = await (apiV2Data("post", "/me/two-factor/confirm", {
|
const res = await (apiV2Data("post", "/me/two-factor/confirm", {
|
||||||
authToken: token,
|
authToken: token,
|
||||||
body: { challengeId: tfChallenge.challengeId, code: tfCode },
|
body: { challengeId: tfChallenge.challengeId, code: tfCode },
|
||||||
}) as Promise<{ twoFactorMethod: TwoFactorMethod }>);
|
}) as Promise<{ twoFactorMethod: TwoFactorMethod; recoveryCodes?: string[] }>);
|
||||||
const wasEnabled = tfEnabled;
|
const wasEnabled = tfEnabled;
|
||||||
setTfEnabled(true);
|
setTfEnabled(true);
|
||||||
setTfMethod(res.twoFactorMethod);
|
setTfMethod(res.twoFactorMethod);
|
||||||
resetTwoFactorForm();
|
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();
|
loadActivity();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setTfMsg({ type: "err", text: errorMessage(e) || "Failed to verify the code." });
|
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) => {
|
const disableTwoFactor = async (e: React.FormEvent) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!token) return;
|
if (!token) return;
|
||||||
@@ -266,6 +313,7 @@ export default function UserProfilePage() {
|
|||||||
body: { password: tfPassword },
|
body: { password: tfPassword },
|
||||||
});
|
});
|
||||||
setTfEnabled(false);
|
setTfEnabled(false);
|
||||||
|
setTfRecoveryLeft(0);
|
||||||
resetTwoFactorForm();
|
resetTwoFactorForm();
|
||||||
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
|
setTfMsg({ type: "ok", text: "Two-factor authentication is off." });
|
||||||
loadActivity();
|
loadActivity();
|
||||||
@@ -424,9 +472,20 @@ export default function UserProfilePage() {
|
|||||||
|
|
||||||
{tfStep === "code" && tfChallenge ? (
|
{tfStep === "code" && tfChallenge ? (
|
||||||
<form onSubmit={confirmEnableTwoFactor} className="space-y-4">
|
<form onSubmit={confirmEnableTwoFactor} className="space-y-4">
|
||||||
<p className="text-sm text-gray-500">
|
{tfChallenge.method === "authenticator" ? (
|
||||||
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."}
|
<div className="space-y-3 text-sm text-gray-600">
|
||||||
</p>
|
<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>
|
<div>
|
||||||
<label htmlFor="profile-verification-code" className="block text-sm font-medium text-gray-700 mb-1">Verification code</label>
|
<label htmlFor="profile-verification-code" className="block text-sm font-medium text-gray-700 mb-1">Verification code</label>
|
||||||
<input
|
<input
|
||||||
@@ -446,16 +505,32 @@ export default function UserProfilePage() {
|
|||||||
Cancel
|
Cancel
|
||||||
</button>
|
</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">
|
<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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
) : tfEnabled && tfStep !== "change" ? (
|
) : tfEnabled && tfStep !== "change" ? (
|
||||||
<>
|
<>
|
||||||
<p className="text-sm text-gray-500 mb-4">
|
<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{" "}
|
<span className="font-medium text-green-700">On.</span>{" "}
|
||||||
{TWO_FACTOR_METHOD_LABEL[tfMethod]}. Devices you've chosen to trust skip the code for 30 days.
|
{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>
|
</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 ? (
|
{tfRequired ? (
|
||||||
<>
|
<>
|
||||||
<p className="text-xs text-gray-500 mb-3">Required for your role, so it can't be turned off.</p>
|
<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">
|
<p className="text-sm text-gray-500">
|
||||||
{tfEnabled
|
{tfEnabled
|
||||||
? "Choose where your login codes go. We'll send a code there first to check it reaches you."
|
? "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>
|
</p>
|
||||||
<div>
|
<div>
|
||||||
<label htmlFor="profile-send-my-codes-by" className="block text-sm font-medium text-gray-700 mb-1">Send my codes by</label>
|
<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)}>
|
<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>
|
<option value="email">Email</option>
|
||||||
{canWhatsAppCodes && <option value="whatsapp">WhatsApp</option>}
|
{canWhatsAppCodes && <option value="whatsapp">WhatsApp</option>}
|
||||||
</select>
|
</select>
|
||||||
@@ -518,11 +594,23 @@ export default function UserProfilePage() {
|
|||||||
</button>
|
</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">
|
<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>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</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} />}
|
{tfMsg && <Alert msg={tfMsg} />}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,9 @@ type Event = {
|
|||||||
attendanceMode?: "whole" | "pick";
|
attendanceMode?: "whole" | "pick";
|
||||||
sessions?: EventSession[];
|
sessions?: EventSession[];
|
||||||
registrationClosesAt?: string;
|
registrationClosesAt?: string;
|
||||||
|
// 2.4.0: the event as crosscode.event/1, what its schema.org JSON-LD is built from (@crosscode/seo).
|
||||||
|
crosscodeEvent?: CrosscodeEvent | null;
|
||||||
|
priceRangeCents?: { lowCents: number; highCents: number } | null;
|
||||||
lateJoin?: LateJoinInfo | null;
|
lateJoin?: LateJoinInfo | null;
|
||||||
series?: EventSeriesRef | null;
|
series?: EventSeriesRef | null;
|
||||||
nextInSeries?: NextInSeries | null;
|
nextInSeries?: NextInSeries | null;
|
||||||
@@ -69,7 +72,8 @@ import { isPickOption, latePrice, registrationClosesAt, scheduleSummary } from "
|
|||||||
import { SessionSchedule } from "@/components/events/SessionSchedule";
|
import { SessionSchedule } from "@/components/events/SessionSchedule";
|
||||||
import { appUrl, appName } from "@/lib/siteConfig";
|
import { appUrl, appName } from "@/lib/siteConfig";
|
||||||
import { getServerSettings } from "@/lib/serverSettings";
|
import { getServerSettings } from "@/lib/serverSettings";
|
||||||
import { eventJsonLd, jsonLdString } from "@/lib/eventSchema";
|
import { eventJsonLd, jsonLdString } from "@crosscode/seo";
|
||||||
|
import type { CrosscodeEvent } from "@crosscode/contracts";
|
||||||
|
|
||||||
// Tiered low-stock threshold: larger events use a smaller percentage.
|
// Tiered low-stock threshold: larger events use a smaller percentage.
|
||||||
// Math.round avoids Math.ceil inflating the threshold (e.g. ceil(1.5)=2 made
|
// Math.round avoids Math.ceil inflating the threshold (e.g. ceil(1.5)=2 made
|
||||||
@@ -188,16 +192,21 @@ export default async function EventDetailPage({ params }: { params: Promise<{ id
|
|||||||
|
|
||||||
const settings = await getServerSettings();
|
const settings = await getServerSettings();
|
||||||
const siteUrl = appUrl.replace(/\/$/, "");
|
const siteUrl = appUrl.replace(/\/$/, "");
|
||||||
const jsonLd = eventJsonLd(event, {
|
// schema.org Event (Google's event results), from the same crosscode.event/1 the feed publishes.
|
||||||
pageUrl: `${siteUrl}/events/${event.id}`,
|
// The description goes in as the plain text it is (the feed's copy is escaped for markdown).
|
||||||
imageUrl: event.picture ? resolveToApiOrigin(event.picture) : null,
|
const jsonLd = event.crosscodeEvent
|
||||||
organizerName: settings.org_name || appName,
|
? eventJsonLd({ ...event.crosscodeEvent, description: event.description || null }, {
|
||||||
siteUrl,
|
pageUrl: `${siteUrl}/events/${event.id}`,
|
||||||
});
|
organizer: { name: settings.org_name || appName, url: siteUrl },
|
||||||
|
priceRange: event.priceRangeCents ?? undefined,
|
||||||
|
offerUrl: `${siteUrl}/register/${event.id}`,
|
||||||
|
validFrom: event.goLiveAt || null,
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex flex-col">
|
<div className="min-h-screen flex flex-col">
|
||||||
<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(jsonLd) }} />
|
{jsonLd && <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: jsonLdString(jsonLd) }} />}
|
||||||
<Navbar />
|
<Navbar />
|
||||||
<main className="flex-1 py-8 px-4 max-w-6xl mx-auto w-full">
|
<main className="flex-1 py-8 px-4 max-w-6xl mx-auto w-full">
|
||||||
<FunnelTracker eventId={event.id} stage="view" />
|
<FunnelTracker eventId={event.id} stage="view" />
|
||||||
|
|||||||
@@ -0,0 +1,121 @@
|
|||||||
|
import { Metadata } from "next";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
import ReactMarkdown from "react-markdown";
|
||||||
|
import { ArrowLeft, Calendar, ExternalLink, MapPin, Video } from "lucide-react";
|
||||||
|
import { Navbar } from "@/components/layout/Navbar";
|
||||||
|
import { Footer } from "@/components/layout/Footer";
|
||||||
|
import { ApiImage } from "@/components/shared/ApiImage";
|
||||||
|
import { ApiError } from "@/lib/api";
|
||||||
|
import { apiV2Data } from "@/lib/apiV2";
|
||||||
|
import { formatDateTimeRange } from "@/lib/date";
|
||||||
|
import { fromLabel, type LinkedEvent } from "@/lib/linkedEvents";
|
||||||
|
|
||||||
|
export const revalidate = 60;
|
||||||
|
|
||||||
|
type Linked = LinkedEvent & { lastSyncedAt: string | null };
|
||||||
|
type Params = { params: Promise<{ product: string; id: string }> };
|
||||||
|
|
||||||
|
async function load(product: string, id: string): Promise<Linked | null> {
|
||||||
|
if (product !== "website" && product !== "app") return null;
|
||||||
|
try {
|
||||||
|
return (await apiV2Data("get", "/linked-events/{product}/{id}", { params: { product, id }, nextOptions: { next: { revalidate } } })) as unknown as Linked;
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof ApiError && (e.status === 404 || e.status === 400)) return null;
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The description's first paragraph as plain text, for the meta description. */
|
||||||
|
const plain = (md: string | null) => (md || "").split(/\n\s*\n/)[0]!.replace(/\\([\\`*_[\]<>|~#+.!()-])/g, "$1").replace(/[*_`]/g, "").trim().slice(0, 200);
|
||||||
|
|
||||||
|
export async function generateMetadata({ params }: Params): Promise<Metadata> {
|
||||||
|
const { product, id } = await params;
|
||||||
|
const item = await load(product, id);
|
||||||
|
if (!item) return {};
|
||||||
|
const e = item.event;
|
||||||
|
const description = e.summary || plain(e.description) || `${e.title} — ${formatDateTimeRange(e.startsAt, e.endsAt)}`;
|
||||||
|
return {
|
||||||
|
title: e.title,
|
||||||
|
description,
|
||||||
|
// A copy: search engines are pointed at the event's own page, so they see one event, not two
|
||||||
|
// (ROADMAP-v3 §11, "Imported events"). It isn't in this site's sitemap either.
|
||||||
|
alternates: { canonical: e.origin.url },
|
||||||
|
openGraph: { title: e.title, description, type: "website", url: e.origin.url, ...(e.imageUrl ? { images: [{ url: e.imageUrl }] } : {}) },
|
||||||
|
twitter: { card: "summary_large_image", title: e.title, description, ...(e.imageUrl ? { images: [e.imageUrl] } : {}) },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An event from another of the church's products (2.4.0): shown read-only, with the way to take
|
||||||
|
* part at the product it comes from. No schema.org JSON-LD here; its own page carries it.
|
||||||
|
*/
|
||||||
|
export default async function LinkedEventPage({ params }: Params) {
|
||||||
|
const { product, id } = await params;
|
||||||
|
const item = await load(product, id);
|
||||||
|
if (!item) notFound();
|
||||||
|
const e = item.event;
|
||||||
|
const r = e.registration;
|
||||||
|
const live = e.sessions.filter(s => !s.cancelled);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex flex-col">
|
||||||
|
<Navbar />
|
||||||
|
<main className="flex-1 py-8 px-4 max-w-4xl mx-auto w-full">
|
||||||
|
<Link href="/events" className="inline-flex items-center gap-1 text-sm text-gray-500 hover:text-gray-700 mb-4">
|
||||||
|
<ArrowLeft className="w-4 h-4" /> All events
|
||||||
|
</Link>
|
||||||
|
{e.imageUrl && <ApiImage src={e.imageUrl} alt={e.title} className="w-full max-h-96 object-cover rounded-2xl mb-6" />}
|
||||||
|
<p className="text-xs font-medium uppercase tracking-wide text-brand-700">{fromLabel(item)}</p>
|
||||||
|
<h1 className="text-3xl font-bold text-gray-900 mt-1">{e.title}</h1>
|
||||||
|
{e.status === "cancelled" && <p className="mt-2 inline-block rounded-full bg-red-50 px-3 py-1 text-sm font-medium text-red-700">Cancelled</p>}
|
||||||
|
|
||||||
|
<div className="mt-4 space-y-2 text-gray-700">
|
||||||
|
<p className="flex items-center gap-2"><Calendar className="w-4 h-4 shrink-0 text-gray-400" /> {formatDateTimeRange(e.startsAt, e.endsAt)}</p>
|
||||||
|
{(e.location?.name || e.location?.address) && (
|
||||||
|
<p className="flex items-center gap-2"><MapPin className="w-4 h-4 shrink-0 text-gray-400" /> {[e.location?.name, e.location?.address].filter(Boolean).join(", ")}</p>
|
||||||
|
)}
|
||||||
|
{e.location?.onlineUrl && (
|
||||||
|
<p className="flex items-center gap-2"><Video className="w-4 h-4 shrink-0 text-gray-400" /> <a href={e.location.onlineUrl} rel="noopener nofollow" className="text-brand-700 underline">Join online</a></p>
|
||||||
|
)}
|
||||||
|
{e.campus && <p className="text-sm text-gray-500">{e.campus.name}</p>}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{live.length > 1 && (
|
||||||
|
<div className="mt-6">
|
||||||
|
<h2 className="font-semibold text-gray-900 mb-2">Dates</h2>
|
||||||
|
<ul className="space-y-1 text-sm text-gray-700">
|
||||||
|
{live.map(s => <li key={s.id}>{s.label ? `${s.label}: ` : ""}{formatDateTimeRange(s.startsAt, s.endsAt)}{s.location ? ` · ${s.location}` : ""}</li>)}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{e.description && (
|
||||||
|
<div className="prose prose-sm max-w-none mt-6 text-gray-700">
|
||||||
|
{/* Markdown with HTML switched off (crosscode.event/1): raw HTML is dropped, links open as plain links. */}
|
||||||
|
<ReactMarkdown skipHtml components={{ a: ({ href, children }) => <a href={href} rel="noopener nofollow ugc" className="text-brand-700 underline">{children}</a> }}>
|
||||||
|
{e.description}
|
||||||
|
</ReactMarkdown>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="mt-8 rounded-xl border p-4 bg-gray-50">
|
||||||
|
{(r.mode === "origin" || r.mode === "external") && r.url ? (
|
||||||
|
<a href={r.url} rel="noopener" className="inline-flex items-center gap-2 rounded-lg bg-brand-600 px-5 py-2.5 text-white font-medium hover:bg-brand-700">
|
||||||
|
Register <ExternalLink className="w-4 h-4" aria-hidden />
|
||||||
|
</a>
|
||||||
|
) : r.mode === "contact" ? (
|
||||||
|
<p className="text-sm text-gray-700">No booking here: see the details above for how to take part.</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-gray-700">No booking needed.</p>
|
||||||
|
)}
|
||||||
|
<p className="mt-3 text-sm text-gray-600">
|
||||||
|
This event is run through the {item.productName}.{" "}
|
||||||
|
<a href={e.origin.url} rel="noopener" className="text-brand-700 underline">See it there</a> for the latest details.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
<Footer />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ import { Navbar } from "@/components/layout/Navbar";
|
|||||||
import { Footer } from "@/components/layout/Footer";
|
import { Footer } from "@/components/layout/Footer";
|
||||||
import { EventsGrid } from "@/components/events/EventsGrid";
|
import { EventsGrid } from "@/components/events/EventsGrid";
|
||||||
import { apiFetchListForPrerender } from "@/lib/api";
|
import { apiFetchListForPrerender } from "@/lib/api";
|
||||||
|
import { fetchLinkedEvents } from "@/lib/linkedEvents";
|
||||||
import { Calendar } from "lucide-react";
|
import { Calendar } from "lucide-react";
|
||||||
|
|
||||||
export const revalidate = 60;
|
export const revalidate = 60;
|
||||||
@@ -32,7 +33,10 @@ type Event = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export default async function EventsPage() {
|
export default async function EventsPage() {
|
||||||
const events = await apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } });
|
const [events, linked] = await Promise.all([
|
||||||
|
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
|
||||||
|
fetchLinkedEvents(),
|
||||||
|
]);
|
||||||
// A server component renders once per request (or revalidation): this is that render's time.
|
// A server component renders once per request (or revalidation): this is that render's time.
|
||||||
// eslint-disable-next-line react-hooks/purity
|
// eslint-disable-next-line react-hooks/purity
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -53,10 +57,10 @@ export default async function EventsPage() {
|
|||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900">All Events</h1>
|
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900">All Events</h1>
|
||||||
<p className="text-sm text-gray-500">{sorted.length} upcoming event{sorted.length === 1 ? "" : "s"}</p>
|
<p className="text-sm text-gray-500">{sorted.length + linked.length} upcoming event{sorted.length + linked.length === 1 ? "" : "s"}</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<EventsGrid events={sorted} />
|
<EventsGrid events={sorted} linked={linked} />
|
||||||
</main>
|
</main>
|
||||||
<Footer />
|
<Footer />
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { EventCard } from "@/components/events/EventCard";
|
import { EventCard } from "@/components/events/EventCard";
|
||||||
|
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
|
||||||
|
import { fetchLinkedEvents, mergeByStart } from "@/lib/linkedEvents";
|
||||||
import { Navbar } from "@/components/layout/Navbar";
|
import { Navbar } from "@/components/layout/Navbar";
|
||||||
import { Footer } from "@/components/layout/Footer";
|
import { Footer } from "@/components/layout/Footer";
|
||||||
import { JoinUsButton } from "@/components/home/JoinUsButton";
|
import { JoinUsButton } from "@/components/home/JoinUsButton";
|
||||||
@@ -48,9 +50,10 @@ async function getOrgName(): Promise<string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export default async function HomePage() {
|
export default async function HomePage() {
|
||||||
const [events, displayName] = await Promise.all([
|
const [events, displayName, linked] = await Promise.all([
|
||||||
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
|
apiFetchListForPrerender<Event>("/api/v2/event-listing", { nextOptions: { next: { revalidate: 60 } } }),
|
||||||
getOrgName(),
|
getOrgName(),
|
||||||
|
fetchLinkedEvents(),
|
||||||
]);
|
]);
|
||||||
// A server component renders once per request (or revalidation): this is that render's time.
|
// A server component renders once per request (or revalidation): this is that render's time.
|
||||||
// eslint-disable-next-line react-hooks/purity
|
// eslint-disable-next-line react-hooks/purity
|
||||||
@@ -60,6 +63,8 @@ export default async function HomePage() {
|
|||||||
return !isNaN(t) && t > now;
|
return !isNaN(t) && t > now;
|
||||||
});
|
});
|
||||||
const sorted = [...upcoming].sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
|
const sorted = [...upcoming].sort((a, b) => new Date(a.nextSession?.startsAt || a.startDate).getTime() - new Date(b.nextSession?.startsAt || b.startDate).getTime());
|
||||||
|
// With events from the church's other products (Linked products), by date.
|
||||||
|
const items = mergeByStart(sorted, linked, e => e.nextSession?.startsAt || e.startDate);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex flex-col">
|
<div className="min-h-screen flex flex-col">
|
||||||
@@ -72,10 +77,10 @@ export default async function HomePage() {
|
|||||||
<div className="absolute -bottom-24 -left-24 w-96 h-96 rounded-full bg-brand-100/40 blur-3xl" />
|
<div className="absolute -bottom-24 -left-24 w-96 h-96 rounded-full bg-brand-100/40 blur-3xl" />
|
||||||
</div>
|
</div>
|
||||||
<div className="relative max-w-2xl mx-auto px-4">
|
<div className="relative max-w-2xl mx-auto px-4">
|
||||||
{sorted.length > 0 && (
|
{items.length > 0 && (
|
||||||
<div className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full bg-white border border-brand-200 text-brand-700 shadow-sm mb-5">
|
<div className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-full bg-white border border-brand-200 text-brand-700 shadow-sm mb-5">
|
||||||
<CalendarCheck className="w-3.5 h-3.5" />
|
<CalendarCheck className="w-3.5 h-3.5" />
|
||||||
{sorted.length} upcoming event{sorted.length === 1 ? "" : "s"}
|
{items.length} upcoming event{items.length === 1 ? "" : "s"}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<h1 className="text-4xl sm:text-5xl font-bold mb-4 text-gray-900">Welcome to {displayName}</h1>
|
<h1 className="text-4xl sm:text-5xl font-bold mb-4 text-gray-900">Welcome to {displayName}</h1>
|
||||||
@@ -98,16 +103,16 @@ export default async function HomePage() {
|
|||||||
<ArrowRight className="w-3.5 h-3.5" />
|
<ArrowRight className="w-3.5 h-3.5" />
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
{sorted.length === 0 ? (
|
{items.length === 0 ? (
|
||||||
<div className="text-center py-12 border rounded-xl bg-gray-50">
|
<div className="text-center py-12 border rounded-xl bg-gray-50">
|
||||||
<CalendarCheck className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
<CalendarCheck className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
||||||
<p className="text-gray-500 text-sm">No upcoming events right now — check back soon.</p>
|
<p className="text-gray-500 text-sm">No upcoming events right now — check back soon.</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
||||||
{sorted.slice(0, 3).map(event => (
|
{items.slice(0, 3).map(item => item.kind === "own"
|
||||||
<EventCard key={event.id} event={event} />
|
? <EventCard key={item.event.id} event={item.event} />
|
||||||
))}
|
: <LinkedEventCard key={item.event.key} item={item.event} />)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<div className="text-center mt-8 sm:hidden">
|
<div className="text-center mt-8 sm:hidden">
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import React, { useEffect, useState } from "react";
|
|||||||
import { Sparkles } from "lucide-react";
|
import { Sparkles } from "lucide-react";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { apiV2, type V2Result } from "@/lib/apiV2";
|
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||||
import { loadAiStatus, renewsText } from "@/lib/ai";
|
import { loadAiStatus, renewsText, tokenText } from "@/lib/ai";
|
||||||
import { errorMessage } from "@/lib/utils";
|
import { errorMessage } from "@/lib/utils";
|
||||||
|
|
||||||
type Usage = V2Result<"/ai/usage", "get">["data"];
|
type Usage = V2Result<"/ai/usage", "get">["data"];
|
||||||
@@ -18,8 +18,8 @@ const HELPERS: { key: Helper; label: string; where: string }[] = [
|
|||||||
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
|
{ key: "improve_text", label: "Improve this text", where: "Event descriptions, the banner, message boxes" },
|
||||||
];
|
];
|
||||||
|
|
||||||
// Fractions of a cent add up: show R0.0123 below a rand.
|
/** "12K in · 3K out" for a row of use. */
|
||||||
const money = (cents: number) => (cents > 0 && cents < 100 ? `R${(cents / 100).toFixed(4)}` : `R${(cents / 100).toFixed(2)}`);
|
const inOut = (u: { inputTokens: number; outputTokens: number }) => `${tokenText(u.inputTokens)} in · ${tokenText(u.outputTokens)} out`;
|
||||||
|
|
||||||
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
|
/** Site settings → AI: the monthly allowance, who used it for what, and a switch per helper. */
|
||||||
export function AiTab({ active }: { active: boolean }) {
|
export function AiTab({ active }: { active: boolean }) {
|
||||||
@@ -53,7 +53,10 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
|
|
||||||
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
if (!usage) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||||
const s = usage.status;
|
const s = usage.status;
|
||||||
const maxDay = Math.max(0.0001, ...usage.days.map(d => d.chargedCents));
|
const dayTokens = (d: { inputTokens: number; outputTokens: number }) => d.inputTokens + d.outputTokens;
|
||||||
|
const maxDay = Math.max(1, ...usage.days.map(dayTokens));
|
||||||
|
const hasTokens = s.usedInputTokens != null && s.usedOutputTokens != null;
|
||||||
|
const hasCap = s.capInputTokens != null && s.capOutputTokens != null && s.capInputTokens > 0;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@@ -72,14 +75,23 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
<div className="rounded-lg border p-4">
|
<div className="rounded-lg border p-4">
|
||||||
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||||
<span className="text-sm font-medium">This month</span>
|
<span className="text-sm font-medium">This month</span>
|
||||||
<span className="text-sm text-gray-600">{money(s.usedCents)} of {money(s.capCents)} · renews on {renewsText(s.renewsOn)}</span>
|
<span className="text-sm text-gray-600">{s.usedPercent}% used · renews on {renewsText(s.renewsOn)}</span>
|
||||||
</div>
|
</div>
|
||||||
|
{hasTokens && (
|
||||||
|
<p className="mt-1 text-sm text-gray-700">
|
||||||
|
{tokenText(s.usedInputTokens!)} input and {tokenText(s.usedOutputTokens!)} output tokens used
|
||||||
|
{hasCap && <> of about {tokenText(s.capInputTokens!)} input and {tokenText(s.capOutputTokens!)} output</>}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
|
<div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-gray-100" role="progressbar" aria-label="AI allowance used" aria-valuenow={s.usedPercent} aria-valuemin={0} aria-valuemax={100}>
|
||||||
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
|
<div className={`h-full ${s.usedPercent >= 80 ? "bg-amber-500" : "bg-violet-500"}`} style={{ width: `${s.usedPercent}%` }} />
|
||||||
</div>
|
</div>
|
||||||
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
|
{s.capReached && <p className="mt-2 text-sm text-amber-800">The allowance is used up: the AI buttons are disabled until {renewsText(s.renewsOn)}, or until your provider raises it.</p>}
|
||||||
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.</p>}
|
{!s.available && <p className="mt-2 text-sm text-amber-800">The provider's Hub can't be reached right now, so AI is unavailable. Everything else works as usual.</p>}
|
||||||
<p className="mt-2 text-xs text-gray-500">Admins get an email when 80% is used.</p>
|
<p className="mt-2 text-xs text-gray-500">
|
||||||
|
Admins get an email when 80% is used.
|
||||||
|
{hasCap && " The allowance in tokens is an estimate: it's what you'd get if half went on input (what's sent) and half on output (the answers). Repeated instructions are cached and cost less, so most sites get more input than this."}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
@@ -114,8 +126,8 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
<h3 className="mb-2 font-medium">By person this month</h3>
|
<h3 className="mb-2 font-medium">By person this month</h3>
|
||||||
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
|
{usage.people.length === 0 ? <p className="text-sm text-gray-500">Nobody has used AI yet this month.</p> : (
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Person</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
|
||||||
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{money(p.chargedCents)}</td></tr>)}</tbody>
|
<tbody>{usage.people.map(p => <tr key={p.userId || "removed"} className="border-t"><td className="py-1">{p.name}</td><td>{p.uses}</td><td className="text-right">{inOut(p)}</td></tr>)}</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -123,16 +135,16 @@ export function AiTab({ active }: { active: boolean }) {
|
|||||||
<h3 className="mb-2 font-medium">By helper this month</h3>
|
<h3 className="mb-2 font-medium">By helper this month</h3>
|
||||||
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
|
{usage.helpers.length === 0 ? <p className="text-sm text-gray-500">—</p> : (
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Cost</th></tr></thead>
|
<thead><tr className="text-left text-xs text-gray-500"><th className="py-1">Helper</th><th>Uses</th><th className="text-right">Tokens</th></tr></thead>
|
||||||
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{money(h.chargedCents)}</td></tr>)}</tbody>
|
<tbody>{usage.helpers.map(h => <tr key={h.helper} className="border-t"><td className="py-1">{HELPERS.find(x => x.key === h.helper)?.label || h.helper}</td><td>{h.uses}</td><td className="text-right">{inOut(h)}</td></tr>)}</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{usage.days.length > 0 && (
|
{usage.days.length > 0 && (
|
||||||
<div className="md:col-span-2">
|
<div className="md:col-span-2">
|
||||||
<h3 className="mb-2 font-medium">Per day</h3>
|
<h3 className="mb-2 font-medium">Per day</h3>
|
||||||
<div className="flex h-20 items-end gap-1" aria-label="AI cost per day this month">
|
<div className="flex h-20 items-end gap-1" aria-label="AI tokens per day this month">
|
||||||
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${money(d.chargedCents)}`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (d.chargedCents / maxDay) * 100)}%` }} />)}
|
{usage.days.map(d => <div key={d.day} title={`${d.day}: ${d.uses} uses, ${inOut(d)} tokens`} className="flex-1 rounded-t bg-violet-300" style={{ height: `${Math.max(4, (dayTokens(d) / maxDay) * 100)}%` }} />)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,167 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { useEffect, useState } from "react";
|
||||||
|
import { Link2, RefreshCw } from "lucide-react";
|
||||||
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
|
import { apiV2, type V2Result } from "@/lib/apiV2";
|
||||||
|
import { errorMessage } from "@/lib/utils";
|
||||||
|
|
||||||
|
type Overview = V2Result<"/linked-products", "get">["data"];
|
||||||
|
type Product = Overview["products"][number];
|
||||||
|
|
||||||
|
const when = (iso: string | null) =>
|
||||||
|
iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }) : "never";
|
||||||
|
|
||||||
|
/** "2 hours ago", for "last synced". */
|
||||||
|
function ago(iso: string | null): string {
|
||||||
|
if (!iso) return "never";
|
||||||
|
const mins = Math.round((Date.now() - new Date(iso).getTime()) / 60000);
|
||||||
|
if (mins < 1) return "just now";
|
||||||
|
if (mins < 60) return `${mins} minute${mins === 1 ? "" : "s"} ago`;
|
||||||
|
const hours = Math.round(mins / 60);
|
||||||
|
if (hours < 48) return `${hours} hour${hours === 1 ? "" : "s"} ago`;
|
||||||
|
return `${Math.round(hours / 24)} days ago`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Site settings → Linked products (2.4.0): the church's other Cross Code products (as the Hub
|
||||||
|
* lists them), Connect / Disconnect, "Show events from" each, and "Publish my events".
|
||||||
|
*/
|
||||||
|
export function LinkedProductsTab({ active }: { active: boolean }) {
|
||||||
|
const { token } = useAuth();
|
||||||
|
const [data, setData] = useState<Overview | null>(null);
|
||||||
|
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!active || !token) return;
|
||||||
|
let alive = true;
|
||||||
|
apiV2("get", "/linked-products", { authToken: token })
|
||||||
|
.then(({ data: d }) => { if (alive) setData(d); })
|
||||||
|
.catch(e => { if (alive) setMsg({ ok: false, text: errorMessage(e) || "Could not load linked products." }); });
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [active, token]);
|
||||||
|
|
||||||
|
const run = async (key: string, call: () => Promise<{ data: Overview }>, ok: string | ((d: Overview) => string)) => {
|
||||||
|
setBusy(key);
|
||||||
|
setMsg(null);
|
||||||
|
try {
|
||||||
|
const { data: d } = await call();
|
||||||
|
setData(d);
|
||||||
|
setMsg({ ok: true, text: typeof ok === "function" ? ok(d) : ok });
|
||||||
|
} catch (e) {
|
||||||
|
setMsg({ ok: false, text: errorMessage(e) || "That didn't work." });
|
||||||
|
}
|
||||||
|
setBusy(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!token) return null;
|
||||||
|
if (!data) return msg ? <p className="text-sm text-red-700">{msg.text}</p> : <p className="text-sm text-gray-500">Loading…</p>;
|
||||||
|
const auth = { authToken: token };
|
||||||
|
|
||||||
|
const connect = (p: Product) => run(`c:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/connect", { ...auth, params: { installId: p.installId } }), `Connected to ${p.name}.`);
|
||||||
|
const disconnect = (p: Product) => {
|
||||||
|
if (!window.confirm(`Disconnect ${p.name}? Its events stop showing here, and this site's events stop showing there.`)) return;
|
||||||
|
run(`d:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/disconnect", { ...auth, params: { installId: p.installId } }) as Promise<{ data: Overview & { otherSideTold: boolean; problem: string | null } }>,
|
||||||
|
(d) => {
|
||||||
|
const r = d as Overview & { otherSideTold?: boolean; problem?: string | null };
|
||||||
|
return r.otherSideTold ? `Disconnected from ${p.name}.` : `Disconnected here. ${p.name} couldn't be told (${r.problem || "not reachable"}); disconnect it there too.`;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const showEvents = (p: Product, on: boolean) => run(`s:${p.installId}`, () => apiV2("put", "/linked-products/{installId}", { ...auth, params: { installId: p.installId }, body: { showEvents: on } }),
|
||||||
|
on ? `${p.name}'s events are fetched and shown on your events pages.` : `${p.name}'s events are no longer shown here.`);
|
||||||
|
const syncNow = (p: Product) => run(`y:${p.installId}`, () => apiV2("post", "/linked-products/{installId}/sync", { ...auth, params: { installId: p.installId } }), "Fetched.");
|
||||||
|
const publish = (on: boolean) => run("publish", () => apiV2("put", "/linked-products/settings", { ...auth, body: { publishEvents: on } }),
|
||||||
|
on ? "Your events are published for your other products." : "Your events are no longer published.");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-6">
|
||||||
|
<div>
|
||||||
|
<h2 className="flex items-center gap-2 text-lg font-semibold"><Link2 className="h-5 w-5 text-brand-600" aria-hidden /> Linked products</h2>
|
||||||
|
<p className="mt-1 text-sm text-gray-600">
|
||||||
|
Your church's other Cross Code products, such as the Church Website and Church App. Connect them to show your events there, and theirs here.
|
||||||
|
Registrations and payments always stay in Cross Events.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{msg && <p role="status" className={`text-sm ${msg.ok ? "text-green-700" : "text-red-700"}`}>{msg.text}</p>}
|
||||||
|
|
||||||
|
{!data.hubConnected && (
|
||||||
|
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">This site isn't connected to the Hub yet (Settings → Licence), so it doesn't know your other products.</div>
|
||||||
|
)}
|
||||||
|
{data.hubConnected && data.keyMismatch && (
|
||||||
|
<div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
|
||||||
|
The Hub has a different key for this site, so your other products can't check that messages really come from it. This happens after a server is rebuilt: ask your provider to clear the site's key on the Hub.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="rounded-lg border p-4">
|
||||||
|
<label className="flex items-start gap-3">
|
||||||
|
<input type="checkbox" className="mt-1" checked={data.publishEvents} disabled={busy === "publish"} onChange={e => publish(e.target.checked)} />
|
||||||
|
<span>
|
||||||
|
<span className="text-sm font-medium">Publish my events</span>
|
||||||
|
<span className="block text-sm text-gray-600">Your public events, as they appear on your events page, for your connected products to show. Never anyone's details.</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{data.hubConnected && data.products.length === 0 && (
|
||||||
|
<div className="rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">
|
||||||
|
Your church has no other Cross Code products yet. When it has (for example the{" "}
|
||||||
|
<a href="https://crosscode.co.za" className="text-brand-700 underline" target="_blank" rel="noopener noreferrer">Church Website</a>), it shows here within 15 minutes.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{data.products.length > 0 && (
|
||||||
|
<ul className="space-y-3">
|
||||||
|
{data.products.map(p => (
|
||||||
|
<li key={p.installId} className="rounded-lg border p-4" data-testid={`linked-${p.product}`}>
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<div className="font-medium">{p.name}</div>
|
||||||
|
<a href={p.url} target="_blank" rel="noopener noreferrer" className="text-sm text-brand-700 underline">{p.url.replace(/^https?:\/\//, "")}</a>
|
||||||
|
<div className="mt-1 text-sm text-gray-600">
|
||||||
|
{p.link
|
||||||
|
? <>Connected {when(p.link.connectedAt)}{p.link.connectedBy ? ` by ${p.link.connectedBy}` : ` by ${p.name}`}</>
|
||||||
|
: "Not connected"}
|
||||||
|
{!p.listed && <span className="ml-1 text-amber-800">· no longer listed by the Hub</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex gap-2">
|
||||||
|
{p.link ? (
|
||||||
|
<button type="button" className="rounded-lg border px-3 py-1.5 text-sm hover:bg-gray-50 disabled:opacity-50" disabled={!!busy} onClick={() => disconnect(p)}>Disconnect</button>
|
||||||
|
) : (
|
||||||
|
<button type="button" className="rounded-lg bg-brand-600 px-3 py-1.5 text-sm text-white hover:bg-brand-700 disabled:opacity-50" disabled={!!busy || !p.listed} onClick={() => connect(p)}>
|
||||||
|
{busy === `c:${p.installId}` ? "Connecting…" : "Connect"}
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{p.link && p.publishesEvents && (
|
||||||
|
<div className="mt-3 border-t pt-3">
|
||||||
|
<label className="flex items-start gap-3">
|
||||||
|
<input type="checkbox" className="mt-1" checked={p.link.showEvents} disabled={!!busy} onChange={e => showEvents(p, e.target.checked)} />
|
||||||
|
<span>
|
||||||
|
<span className="text-sm font-medium">Show events from {p.name}</span>
|
||||||
|
<span className="block text-sm text-gray-600">Its events appear on your events pages, marked as coming from it, with a link to their page there.</span>
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
{p.link.showEvents && (
|
||||||
|
<div className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-gray-600">
|
||||||
|
<span>{p.link.importedEvents} event{p.link.importedEvents === 1 ? "" : "s"} · last synced {ago(p.link.lastGoodAt)}</span>
|
||||||
|
<button type="button" className="inline-flex items-center gap-1 text-brand-700 underline disabled:opacity-50" disabled={!!busy} onClick={() => syncNow(p)}>
|
||||||
|
<RefreshCw className="h-3.5 w-3.5" aria-hidden /> Fetch now
|
||||||
|
</button>
|
||||||
|
{p.link.lastSyncError && <span className="w-full text-amber-800">Last try ({ago(p.link.lastSyncAt)}): {p.link.lastSyncError}. The events from the last good fetch keep showing.</span>}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -27,6 +27,8 @@ export function LoginForm() {
|
|||||||
// Two-factor step — set once the password is accepted for an account with 2FA on.
|
// Two-factor step — set once the password is accepted for an account with 2FA on.
|
||||||
const [challenge, setChallenge] = useState<TwoFactorChallenge | null>(null);
|
const [challenge, setChallenge] = useState<TwoFactorChallenge | null>(null);
|
||||||
const [code, setCode] = useState("");
|
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 [rememberDevice, setRememberDevice] = useState(false);
|
||||||
const [resendIn, setResendIn] = useState(0);
|
const [resendIn, setResendIn] = useState(0);
|
||||||
|
|
||||||
@@ -109,6 +111,7 @@ export function LoginForm() {
|
|||||||
const backToPassword = () => {
|
const backToPassword = () => {
|
||||||
setChallenge(null);
|
setChallenge(null);
|
||||||
setCode("");
|
setCode("");
|
||||||
|
setUseRecovery(false);
|
||||||
setPassword("");
|
setPassword("");
|
||||||
setError(null);
|
setError(null);
|
||||||
};
|
};
|
||||||
@@ -124,20 +127,24 @@ export function LoginForm() {
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
<p className="text-sm text-gray-600 mt-1">
|
<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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<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
|
<input
|
||||||
id="login-code"
|
id="login-code"
|
||||||
type="text"
|
type="text"
|
||||||
inputMode="numeric"
|
inputMode={useRecovery ? "text" : "numeric"}
|
||||||
autoComplete="one-time-code"
|
autoComplete={useRecovery ? "off" : "one-time-code"}
|
||||||
maxLength={6}
|
maxLength={useRecovery ? 11 : 6}
|
||||||
value={code}
|
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"
|
className="w-full border rounded px-3 py-2 text-lg tracking-widest"
|
||||||
autoFocus
|
autoFocus
|
||||||
required
|
required
|
||||||
@@ -158,7 +165,7 @@ export function LoginForm() {
|
|||||||
|
|
||||||
<button
|
<button
|
||||||
type="submit"
|
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"
|
className="w-full bg-brand-600 hover:bg-brand-700 text-white rounded py-2 disabled:opacity-60"
|
||||||
>
|
>
|
||||||
{loading ? "Verifying..." : "Verify and log in"}
|
{loading ? "Verifying..." : "Verify and log in"}
|
||||||
@@ -168,14 +175,21 @@ export function LoginForm() {
|
|||||||
<button type="button" onClick={backToPassword} className="text-brand-600 hover:underline">
|
<button type="button" onClick={backToPassword} className="text-brand-600 hover:underline">
|
||||||
Back to login
|
Back to login
|
||||||
</button>
|
</button>
|
||||||
<button
|
{!challenge.enrolling && (
|
||||||
type="button"
|
<button type="button" onClick={() => { setUseRecovery(!useRecovery); setCode(""); setError(null); }} className="text-brand-600 hover:underline">
|
||||||
onClick={onResend}
|
{useRecovery ? "Use a code instead" : "Use a recovery code"}
|
||||||
disabled={resendIn > 0}
|
</button>
|
||||||
className="text-brand-600 hover:underline disabled:text-gray-400 disabled:no-underline"
|
)}
|
||||||
>
|
{challenge.method !== "authenticator" && !useRecovery && (
|
||||||
{resendIn > 0 ? `Resend code in ${resendIn}s` : "Resend code"}
|
<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>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -3,12 +3,14 @@
|
|||||||
import React, { useState } from "react";
|
import React, { useState } from "react";
|
||||||
import { CalendarX } from "lucide-react";
|
import { CalendarX } from "lucide-react";
|
||||||
import { EventCard } from "@/components/events/EventCard";
|
import { EventCard } from "@/components/events/EventCard";
|
||||||
|
import { LinkedEventCard } from "@/components/events/LinkedEventCard";
|
||||||
|
import { mergeByStart, type LinkedEvent } from "@/lib/linkedEvents";
|
||||||
import { CampusFilter } from "@/components/shared/CampusFilter";
|
import { CampusFilter } from "@/components/shared/CampusFilter";
|
||||||
import { useCampuses } from "@/hooks/useCampuses";
|
import { useCampuses } from "@/hooks/useCampuses";
|
||||||
import { useAuth } from "@/hooks/useAuth";
|
import { useAuth } from "@/hooks/useAuth";
|
||||||
import { useExternalEffect } from "@/lib/hooks";
|
import { useExternalEffect } from "@/lib/hooks";
|
||||||
|
|
||||||
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null };
|
type GridEvent = React.ComponentProps<typeof EventCard>["event"] & { campusId?: string | null; nextSession?: { startsAt: string } | null };
|
||||||
|
|
||||||
// The visitor's campus choice, kept in this browser (like the cookie choice).
|
// The visitor's campus choice, kept in this browser (like the cookie choice).
|
||||||
const STORAGE_KEY = "hope_events_campus";
|
const STORAGE_KEY = "hope_events_campus";
|
||||||
@@ -23,8 +25,10 @@ function store(value: string) {
|
|||||||
/**
|
/**
|
||||||
* The public events grid with a campus filter (while campuses are on). A campus shows its own
|
* The public events grid with a campus filter (while campuses are on). A campus shows its own
|
||||||
* events plus church-wide ones. Starts on the visitor's last choice, else their home campus.
|
* events plus church-wide ones. Starts on the visitor's last choice, else their home campus.
|
||||||
|
* Events from linked products (2.4.0) are mixed in by date; a campus also shows linked events for
|
||||||
|
* no campus or for a campus this site doesn't have.
|
||||||
*/
|
*/
|
||||||
export function EventsGrid({ events }: { events: GridEvent[] }) {
|
export function EventsGrid({ events, linked = [] }: { events: GridEvent[]; linked?: LinkedEvent[] }) {
|
||||||
const { enabled, campuses } = useCampuses();
|
const { enabled, campuses } = useCampuses();
|
||||||
const { user } = useAuth();
|
const { user } = useAuth();
|
||||||
const [campus, setCampus] = useState("");
|
const [campus, setCampus] = useState("");
|
||||||
@@ -39,20 +43,28 @@ export function EventsGrid({ events }: { events: GridEvent[] }) {
|
|||||||
|
|
||||||
const choose = (value: string) => { setCampus(value); store(value); };
|
const choose = (value: string) => { setCampus(value); store(value); };
|
||||||
const shown = enabled && campus ? events.filter(e => !e.campusId || e.campusId === campus) : events;
|
const shown = enabled && campus ? events.filter(e => !e.campusId || e.campusId === campus) : events;
|
||||||
|
const chosenSlug = campuses.find(c => c.id === campus)?.slug;
|
||||||
|
const slugs = new Set(campuses.map(c => c.slug));
|
||||||
|
const shownLinked = enabled && campus
|
||||||
|
? linked.filter(l => !l.event.campus || !slugs.has(l.event.campus.slug) || l.event.campus.slug === chosenSlug)
|
||||||
|
: linked;
|
||||||
|
const items = mergeByStart(shown, shownLinked, e => e.nextSession?.startsAt || e.startDate);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
<CampusFilter value={campus} onChange={choose} id="events-campus" />
|
<CampusFilter value={campus} onChange={choose} id="events-campus" />
|
||||||
</div>
|
</div>
|
||||||
{shown.length === 0 ? (
|
{items.length === 0 ? (
|
||||||
<div className="text-center py-16 border rounded-xl bg-gray-50">
|
<div className="text-center py-16 border rounded-xl bg-gray-50">
|
||||||
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
<CalendarX className="w-8 h-8 text-gray-300 mx-auto mb-2" />
|
||||||
<p className="text-gray-500 text-sm">{events.length ? "No events at this campus right now — try another campus." : "No events available right now — check back soon."}</p>
|
<p className="text-gray-500 text-sm">{events.length + linked.length ? "No events at this campus right now — try another campus." : "No events available right now — check back soon."}</p>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
<div className="grid gap-6 md:grid-cols-3 sm:grid-cols-2">
|
||||||
{shown.map(event => <EventCard key={event.id} event={event} />)}
|
{items.map(item => item.kind === "own"
|
||||||
|
? <EventCard key={item.event.id} event={item.event} />
|
||||||
|
: <LinkedEventCard key={item.event.key} item={item.event} />)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { Calendar, ExternalLink, MapPin } from "lucide-react";
|
||||||
|
import { ApiImage } from "@/components/shared/ApiImage";
|
||||||
|
import { formatDateTimeRange } from "@/lib/date";
|
||||||
|
import { fromLabel, linkedEventPath, type LinkedEvent } from "@/lib/linkedEvents";
|
||||||
|
|
||||||
|
/** The first paragraph of a markdown description as plain text, for a card. */
|
||||||
|
function teaser(e: LinkedEvent["event"]): string {
|
||||||
|
const text = e.summary || (e.description || "").split(/\n\s*\n/)[0] || "";
|
||||||
|
return text.replace(/\\([\\`*_[\]<>|~#+.!()-])/g, "$1").replace(/[*_`]/g, "").trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A card for an event from another of the church's products (Website, App): like EventCard, with
|
||||||
|
* a "From the Church Website" label. Details open its page here; registering happens where it comes from.
|
||||||
|
*/
|
||||||
|
export function LinkedEventCard({ item }: { item: LinkedEvent }) {
|
||||||
|
const e = item.event;
|
||||||
|
const r = e.registration;
|
||||||
|
const place = e.location?.name || e.location?.address || (e.location?.onlineUrl ? "Online" : null);
|
||||||
|
const action = r.mode === "origin" ? "Register" : r.mode === "external" ? "Register" : null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="relative border rounded-xl overflow-hidden shadow-sm hover:shadow-md hover:border-brand-200 transition" data-testid="linked-event-card">
|
||||||
|
<a href={linkedEventPath(item)} className="block">
|
||||||
|
{e.imageUrl ? (
|
||||||
|
<ApiImage src={e.imageUrl} alt={e.title} className="h-48 w-full object-cover" />
|
||||||
|
) : (
|
||||||
|
<div className="h-48 w-full bg-brand-50 flex items-center justify-center">
|
||||||
|
<Calendar className="w-10 h-10 text-brand-200" />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="p-4">
|
||||||
|
<p className="text-xs font-medium uppercase tracking-wide text-brand-700">{fromLabel(item)}</p>
|
||||||
|
<h3 className="text-lg font-semibold hover:underline">{e.title}</h3>
|
||||||
|
{e.campus && <p className="text-xs text-gray-500 mt-0.5">{e.campus.name}</p>}
|
||||||
|
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-1">
|
||||||
|
<Calendar className="w-3.5 h-3.5 shrink-0" />
|
||||||
|
{formatDateTimeRange(e.startsAt, e.endsAt)}
|
||||||
|
</p>
|
||||||
|
{place && (
|
||||||
|
<p className="text-sm text-gray-500 flex items-center gap-1.5 mt-1">
|
||||||
|
<MapPin className="w-3.5 h-3.5 shrink-0" />
|
||||||
|
<span className="truncate">{place}</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="text-sm text-gray-600 mt-2 line-clamp-2">{teaser(e)}</p>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
<div className="px-4 pb-4 flex gap-2">
|
||||||
|
<a href={linkedEventPath(item)} className="flex-1 text-center text-sm text-gray-700 border rounded-lg py-2 hover:bg-gray-50 transition-colors">
|
||||||
|
View details
|
||||||
|
</a>
|
||||||
|
{action && r.url && (
|
||||||
|
<a href={r.url} rel="noopener" className="flex-1 inline-flex items-center justify-center gap-1 text-center text-sm text-white bg-brand-600 rounded-lg py-2 hover:bg-brand-700 transition-colors">
|
||||||
|
{action} <ExternalLink className="w-3.5 h-3.5" aria-hidden />
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send, BookOpen } from "lucide-react";
|
import { Building2, Palette, Bell, Mail, Scale, MessageCircle, LayoutDashboard, Timer, Play, CreditCard, ArrowUpDown, KeyRound, ArrowUpCircle, MapPinned, Archive, Users, BellOff, Megaphone, Webhook, Send, BookOpen, Link2 } from "lucide-react";
|
||||||
import { GuideItem } from "@/components/shared/GuideItem";
|
import { GuideItem } from "@/components/shared/GuideItem";
|
||||||
import type { HelpContent } from "./types";
|
import type { HelpContent } from "./types";
|
||||||
|
|
||||||
@@ -174,6 +174,27 @@ export const siteSettingsHelpContent: HelpContent = {
|
|||||||
</div>
|
</div>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
key: "linked",
|
||||||
|
label: "Linked products",
|
||||||
|
icon: Link2,
|
||||||
|
content: (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<p>Your church's other Cross Code products, such as the Church Website and the Church App. The Hub lists them here by itself (within 15 minutes of a new one being set up).</p>
|
||||||
|
<div className="space-y-4">
|
||||||
|
<GuideItem icon={Link2} title="Connect" tone="brand">
|
||||||
|
"Connect" sets up a secure link with that product, so your events can show there and theirs here. Either side can connect or disconnect; the other side shows who did it.
|
||||||
|
</GuideItem>
|
||||||
|
<GuideItem icon={Megaphone} title="Publish my events" tone="green">
|
||||||
|
On by default: your connected products can show your public events, as they appear on your events page, with a link back here to register. Hidden events, people's details and children's details are never shared. Registrations and payments always stay in Cross Events.
|
||||||
|
</GuideItem>
|
||||||
|
<GuideItem icon={Send} title="Show events from a product" tone="gray">
|
||||||
|
Tick it to show that product's events on your events pages, marked as coming from it. They're fetched every 15 minutes (straight away when they change), and can only be changed where they come from. If that product can't be reached, its last events keep showing and this tab says when it last synced.
|
||||||
|
</GuideItem>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
{
|
{
|
||||||
key: "jobs",
|
key: "jobs",
|
||||||
label: "Background jobs",
|
label: "Background jobs",
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user