Let Cloudron turn on named admins, the ops token, and Umami after the image is built #118

Merged
an.di merged 3 commits from adilallo/fix/CR-394-rule-admin-ops-token-umami into main 2026-11-23 21:35:56 +00:00
9 changed files with 157 additions and 49 deletions

No files matched your search

+1
View File
@@ -61,6 +61,7 @@ NEXT_PUBLIC_ENABLE_BACKEND_SYNC=
# Optional Umami (self-hosted beside the app). Unset: no tracker script.
# Cookie-free / no-cookies is an Umami server setting.
# Read at request time on Cloudron, so `cloudron env set` does not need a rebuild.
# NEXT_PUBLIC_UMAMI_SRC=https://analytics.example.com/script.js
# NEXT_PUBLIC_UMAMI_WEBSITE_ID=
+24 -22
View File
@@ -1,7 +1,8 @@
import { Inter, Bricolage_Grotesque } from "next/font/google";
import type { Metadata, Viewport } from "next";
import type { ReactNode } from "react";
import { Suspense, type ReactNode } from "react";
import { headers } from "next/headers";
import { connection } from "next/server";
import Script from "next/script";
import messages from "../messages/en/index";
import { ASSETS, getAssetPath } from "../lib/assetUtils";
@@ -125,9 +126,22 @@ export async function generateMetadata(): Promise<Metadata> {
};
}
export default function RootLayout({ children }: { children: ReactNode }) {
async function UmamiScript() {
await connection();
const umami = umamiTracker();
if (!umami) return null;
return (
<Script
src={umami.src}
strategy="afterInteractive"
data-website-id={umami.websiteId}
data-do-not-track="true"
data-exclude-search="true"
/>
);
}
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en" className="font-sans">
<head>
@@ -150,26 +164,14 @@ export default function RootLayout({ children }: { children: ReactNode }) {
type="image/png"
/>
</head>
{umami ? (
<body className={`${inter.variable} ${bricolageGrotesque.variable}`}>
<Script
src={umami.src}
strategy="afterInteractive"
data-website-id={umami.websiteId}
data-do-not-track="true"
data-exclude-search="true"
/>
<div className="mx-auto flex min-h-screen w-full max-w-[1920px] flex-col">
{children}
</div>
</body>
) : (
<body className={`${inter.variable} ${bricolageGrotesque.variable}`}>
<div className="mx-auto flex min-h-screen w-full max-w-[1920px] flex-col">
{children}
</div>
</body>
)}
<body className={`${inter.variable} ${bricolageGrotesque.variable}`}>
<Suspense fallback={null}>
<UmamiScript />
</Suspense>
<div className="mx-auto flex min-h-screen w-full max-w-[1920px] flex-col">
{children}
</div>
</body>
</html>
);
}
+18 -3
View File
@@ -91,9 +91,15 @@ per-app in the manifest and provisioned at install time.
(`start.sh` chowns `/app/data` for the `node` user). When unset, upload
routes return `server_misconfigured`. See [CONTRIBUTING.md](../../CONTRIBUTING.md)
API table.
- `RULE_ADMIN_EMAILS` — comma-separated named admins. Required on staging
so `/rule-counts` exists and an admin read of a private Rule is logged.
- `OPS_PRUNE_TOKEN` — bearer token for `POST /api/ops/prune` and
`GET /api/ops/rule-counts`. Unset hides prune; together with an empty
admin list, `/api/ops/rule-counts` answers 404.
- `NEXT_PUBLIC_UMAMI_SRC` / `NEXT_PUBLIC_UMAMI_WEBSITE_ID` — optional
Umami tracker. Unset until the companion Umami app is installed.
Cookie-free mode is set on Umami, not here. See
Cookie-free mode is set on Umami, not here. The app reads these at
request time, so `cloudron env set` does not need a rebuild. See
[ops-runbook.md](ops-runbook.md) §9.3.
## 4. Platform settings
@@ -465,11 +471,15 @@ production env vars, and verify the vertical slice before apex cutover
SMTP_FROM="CommunityRule <hello@communityrule.info>" \
ENABLE_PRIVACY_POLICY=true \
NEXT_PUBLIC_ENABLE_BACKEND_SYNC=true \
UPLOAD_ROOT=/app/data/uploads
UPLOAD_ROOT=/app/data/uploads \
RULE_ADMIN_EMAILS="<named-admin-emails>" \
OPS_PRUNE_TOKEN="$(openssl rand -hex 32)"
```
Rotating `SESSION_SECRET` logs everyone out. `SMTP_FROM` must be an address
SES accepts on `communityrule.info` (platform mail addon is SES-relayed with
custom-from allowed — §3).
custom-from allowed — §3). Named admins can open private Rules and
`/rule-counts`; keep `OPS_PRUNE_TOKEN` in 1Password. Umami is a separate
app — [ops-runbook.md](ops-runbook.md) §9.3.
5. **Confirm the app is running** in the Cloudron dashboard (Logs tab). Look
for a clean `prisma migrate deploy` and Next.js listening on port 3000.
6. **Seed facet data (one-time per environment)** — templates + `MethodFacet`
@@ -501,6 +511,11 @@ steps below are still required.
resume works after re-login.
- [ ] **Upload (optional):** with `UPLOAD_ROOT` set, attach a community photo
in create flow and confirm it renders after publish.
- [ ] **Rule counts:** `GET /api/ops/rule-counts` is 401 logged out, 200
with `Authorization: Bearer $OPS_PRUNE_TOKEN` or a named-admin
session. `/rule-counts` is reachable after signing in as a named admin.
- [ ] **Umami:** homepage HTML includes the tracker (`data-website-id`).
The Umami site has cookies turned off.
**If something fails:**
+29 -11
View File
@@ -147,8 +147,15 @@ mount).
# optional — exercises magic-link request (check inbox manually):
EMAIL=you@example.com ./scripts/staging-smoke.sh staging.communityrule.info
# optional — require the Umami tracker, and check rule-counts with the bearer token:
EXPECT_UMAMI=1 OPS_PRUNE_TOKEN=... ./scripts/staging-smoke.sh staging.communityrule.info
```
Logged-out rule-counts may be 401 (route live) or 404 (hidden until
`RULE_ADMIN_EMAILS` or `OPS_PRUNE_TOKEN` is set). A missing Umami tag is
skipped unless `EXPECT_UMAMI=1`.
**Manual** (still required for full acceptance):
- Click a magic link → signed in → `GET /api/auth/session` returns a user.
@@ -250,10 +257,10 @@ persist across image updates unless changed:
| `ENABLE_PRIVACY_POLICY` | `true` on staging so `/privacy` is reachable. Unset in production until counsel has read the policy (404, no public links). |
| `NEXT_PUBLIC_ENABLE_BACKEND_SYNC` | `true` in staging/production — Postgres draft persistence. |
| `UPLOAD_ROOT` | `/app/data/uploads` on Cloudron — required for file uploads. |
| `OPS_PRUNE_TOKEN` | Bearer token for `POST /api/ops/prune`. Unset hides the route. Optional; the daily scheduler runs the prune inside the container without it. |
| `OPS_PRUNE_TOKEN` | Bearer token for `POST /api/ops/prune` and `GET /api/ops/rule-counts`. Unset hides prune. Optional for the daily scheduler, which runs prune inside the container without it. |
| `WORKSHOP_INQUIRY_PURGE_TOKEN` | Bearer token for `POST /api/workshop-inquiries/purge`. Unset hides that route. |
| `RULE_ADMIN_EMAILS` | Named admins. Comma-separated. Can open private Rules and `/rule-counts`. |
| `NEXT_PUBLIC_UMAMI_SRC` | Umami script URL. Unset: no tracker. Pair with `NEXT_PUBLIC_UMAMI_WEBSITE_ID`. |
| `RULE_ADMIN_EMAILS` | Named admins. Comma-separated. Can open private Rules and `/rule-counts`. Every admin read of a private Rule is logged. |
| `NEXT_PUBLIC_UMAMI_SRC` | Umami script URL. Unset: no tracker. Pair with `NEXT_PUBLIC_UMAMI_WEBSITE_ID`. Read at request time. |
| `NEXT_PUBLIC_UMAMI_WEBSITE_ID` | Umami website id for this hostname. |
Full detail: [`ops-backend-deploy.md` §3](ops-backend-deploy.md#3-environment-variables).
@@ -267,6 +274,8 @@ Full detail: [`ops-backend-deploy.md` §3](ops-backend-deploy.md#3-environment-v
| Container crash on start | Migration failure | App logs around `prisma migrate deploy`; fix forward with new migration |
| Magic link not sent | Mail addon, `SMTP_FROM`, or SES DNS | Cloudron mail logs (`CLOUDRON_MAIL_SMTP_*`); inbox/spam; SPF/DKIM for SES (§8.1) |
| Upload `server_misconfigured` | `UPLOAD_ROOT` unset | `cloudron env set --app <app> UPLOAD_ROOT=/app/data/uploads` |
| `/api/ops/rule-counts` is 404 | Neither `RULE_ADMIN_EMAILS` nor `OPS_PRUNE_TOKEN` is set | Set at least one. Strangers then get 401; a named admin or the bearer token gets 200. |
| No Umami script in the HTML | Tracker env unset, or cookies still on in Umami | Install Umami with `--no-sso` (§9.3), turn cookies off, set both `NEXT_PUBLIC_UMAMI_*` vars |
| No “Recommended” on method cards | Seed not run | §3.4 — `node prisma/seed.bundle.cjs` |
| Rate limit too aggressive after deploy | Expected per §6.1 | Single instance only; limits reset on container restart |
@@ -369,11 +378,19 @@ Sign-in mail failures log a request id, not the email address.
### 9.3 Umami (site counts)
Umami is a **second Cloudron app**, not this image. Install the Umami
Cloudron package (or Docker) on a hostname such as
`analytics.communityrule.info`. Create a website for this app’s public
origin. In Umami → website settings, **turn off cookies** (tracker
collects aggregate page views only).
Umami is a **second Cloudron app**, not this image. Install the store
package with Cloudron SSO off so logged-out visitors can load the
tracker:
```bash
cloudron install --appstore-id is.umami.cloudronapp \
--location analytics.communityrule.info --no-sso
```
Create a website for this app’s public origin (staging:
`https://staging.communityrule.info`). Umami 3’s tracker **sets no
cookies** by default; leave session replay off. Change the package
default admin password on first login. Copy the website id.
Then on this CommunityRule app:
@@ -384,9 +401,10 @@ cloudron env set --app staging.communityrule.info \
NEXT_PUBLIC_UMAMI_WEBSITE_ID=<website-id>
```
Unset both to ship no tracker. The snippet sets `data-do-not-track` and
`data-exclude-search` so query strings (share and export tokens) are not
sent to Umami.
The app reads those two names at request time. Unset both to ship no
tracker. The snippet sets `data-do-not-track` and `data-exclude-search`
so query strings (share and export tokens) are not sent to Umami. The
content security policy always allows `https://analytics.communityrule.info`.
### 9.4 Backups
+10 -2
View File
@@ -1,10 +1,18 @@
/**
* Optional Umami tracker. Unset env vars mean no script ships.
* Cookie-free mode is an Umami server setting, not this snippet.
*
* Values are read by key at request time so Cloudron `env set` works
* without rebuilding the image (`NEXT_PUBLIC_*` is otherwise inlined
* at `next build`).
*/
function readEnv(name: string): string {
return process.env[name]?.trim() ?? "";
}
export function umamiTracker(): { src: string; websiteId: string } | null {
const src = process.env.NEXT_PUBLIC_UMAMI_SRC?.trim() ?? "";
const websiteId = process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID?.trim() ?? "";
const src = readEnv("NEXT_PUBLIC_UMAMI_SRC");
const websiteId = readEnv("NEXT_PUBLIC_UMAMI_WEBSITE_ID");
if (!src || !websiteId) return null;
try {
const url = new URL(src);
+15 -11
View File
@@ -24,22 +24,26 @@ const svgrLoaderOptions = {
},
};
function umamiOrigin() {
/** Companion Umami app. Allowed even when the tracker is off so Cloudron can turn it on without a rebuild. */
const UMAMI_ORIGIN = "https://analytics.communityrule.info";
function umamiOrigins() {
const origins = new Set([UMAMI_ORIGIN]);
const src = process.env.NEXT_PUBLIC_UMAMI_SRC?.trim() ?? "";
if (!src) return "";
try {
return new URL(src).origin;
} catch {
return "";
if (src) {
try {
origins.add(new URL(src).origin);
} catch {
// ignore invalid tracker URLs
}
}
return [...origins].join(" ");
}
function contentSecurityPolicy() {
const umami = umamiOrigin();
const scriptSrc = umami
? `'self' 'unsafe-inline' ${umami}`
: `'self' 'unsafe-inline'`;
const connectSrc = umami ? `'self' ${umami}` : `'self'`;
const umami = umamiOrigins();
const scriptSrc = `'self' 'unsafe-inline' ${umami}`;
const connectSrc = `'self' ${umami}`;
return [
"default-src 'self'",
`script-src ${scriptSrc}`,
+44
View File
@@ -6,6 +6,8 @@
# ./scripts/staging-smoke.sh
# ./scripts/staging-smoke.sh communityrule.info
# EMAIL=you@example.com ./scripts/staging-smoke.sh staging.communityrule.info
# OPS_PRUNE_TOKEN=... ./scripts/staging-smoke.sh # also checks /api/ops/rule-counts with the bearer token
# EXPECT_UMAMI=1 ./scripts/staging-smoke.sh # fail if the homepage has no Umami tracker
#
# Manual follow-up (not automated here): click magic link in inbox, publish a rule,
# optional upload with UPLOAD_ROOT set.
@@ -67,6 +69,48 @@ check_json_contains 'templates seeded (non-empty)' '"slug":'
check_http "GET /api/rules" "$BASE/api/rules" "200"
check_json_contains 'rules list shape' '"rules":['
# 401: route is live and the caller is logged out.
# 404: hidden because neither RULE_ADMIN_EMAILS nor OPS_PRUNE_TOKEN is set.
# A supplied OPS_PRUNE_TOKEN means the route should exist, so 404 fails.
status="$(curl -sS -o /tmp/staging-smoke-body.$$ -w '%{http_code}' \
"$BASE/api/ops/rule-counts" || echo '000')"
if [ "$status" = "401" ]; then
pass "GET /api/ops/rule-counts (logged out) (HTTP 401)"
elif [ "$status" = "404" ] && [ -z "${OPS_PRUNE_TOKEN:-}" ]; then
printf 'SKIP GET /api/ops/rule-counts (logged out) (HTTP 404, hidden until RULE_ADMIN_EMAILS or OPS_PRUNE_TOKEN is set)\n'
else
fail "GET /api/ops/rule-counts (logged out) (expected HTTP 401, got $status)"
if [ -f "/tmp/staging-smoke-body.$$" ]; then
head -c 500 "/tmp/staging-smoke-body.$$" 1>&2 || true
printf '\n' 1>&2
fi
fi
if [ -n "${OPS_PRUNE_TOKEN:-}" ]; then
status="$(curl -sS -o /tmp/staging-smoke-body.$$ -w '%{http_code}' \
-H "Authorization: Bearer $OPS_PRUNE_TOKEN" \
"$BASE/api/ops/rule-counts" || echo '000')"
if [ "$status" = "200" ]; then
pass "GET /api/ops/rule-counts (ops token) (HTTP 200)"
check_json_contains 'rule-counts finished' '"finished":'
else
fail "GET /api/ops/rule-counts (ops token) (expected HTTP 200, got $status)"
head -c 500 "/tmp/staging-smoke-body.$$" 1>&2 || true
printf '\n' 1>&2
fi
else
printf 'SKIP GET /api/ops/rule-counts (ops token) (set OPS_PRUNE_TOKEN= to run)\n'
fi
check_http "GET / (homepage)" "$BASE/" "200"
if grep -Fq 'data-website-id' "/tmp/staging-smoke-body.$$" 2>/dev/null; then
pass "Umami tracker on homepage"
elif [ "${EXPECT_UMAMI:-}" = "1" ]; then
fail "Umami tracker on homepage (missing data-website-id)"
else
printf 'SKIP Umami tracker on homepage (optional; set EXPECT_UMAMI=1 to require data-website-id)\n'
fi
if [ -n "${EMAIL:-}" ]; then
status="$(curl -sS -o /tmp/staging-smoke-body.$$ -w '%{http_code}' \
-X POST "$BASE/api/auth/magic-link/request" \
+3
View File
@@ -12,6 +12,9 @@ describe("security headers", () => {
);
expect(byKey["Content-Security-Policy"]).toContain("default-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("script-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain(
"https://analytics.communityrule.info",
);
expect(byKey["Content-Security-Policy"]).toContain("style-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("font-src 'self'");
expect(byKey["Content-Security-Policy"]).toContain("img-src 'self'");
+13
View File
@@ -38,4 +38,17 @@ describe("umamiTracker", () => {
process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID = "site-1";
expect(umamiTracker()).toBeNull();
});
it("reads env at call time so Cloudron can set it after the image is built", () => {
delete process.env.NEXT_PUBLIC_UMAMI_SRC;
delete process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID;
expect(umamiTracker()).toBeNull();
process.env.NEXT_PUBLIC_UMAMI_SRC =
"https://analytics.communityrule.info/script.js";
process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID = "staging-site";
expect(umamiTracker()).toEqual({
src: "https://analytics.communityrule.info/script.js",
websiteId: "staging-site",
});
});
});