chore: snapshot workshop v2 rewrite
This commit is contained in:
34 files changed
+876
-910
No files matched your search
@@ -1,9 +1,12 @@
|
||||
# syntax=docker/dockerfile:1.10
|
||||
|
||||
FROM node:24.18.0-alpine AS website
|
||||
FROM node:24.18.0-alpine AS dependencies
|
||||
WORKDIR /app
|
||||
ENV COREPACK_HOME=/corepack
|
||||
|
||||
RUN corepack enable pnpm
|
||||
RUN mkdir -p /corepack && \
|
||||
corepack enable pnpm && \
|
||||
corepack install --global pnpm@11.10.0
|
||||
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
|
||||
COPY patches ./patches
|
||||
RUN --mount=type=cache,id=workshop-pnpm-store,target=/pnpm/store \
|
||||
@@ -17,8 +20,11 @@ COPY packages/validation ./packages/validation
|
||||
COPY packages/workshop ./packages/workshop
|
||||
COPY tooling/typescript ./tooling/typescript
|
||||
RUN --mount=type=cache,id=workshop-pnpm-store,target=/pnpm/store \
|
||||
pnpm install --recursive --offline --frozen-lockfile && \
|
||||
CI=true SKIP_ENV_VALIDATION=true pnpm turbo build --filter=@homarr/docs
|
||||
pnpm install --recursive --offline --frozen-lockfile
|
||||
|
||||
FROM dependencies AS website
|
||||
|
||||
RUN CI=true SKIP_ENV_VALIDATION=true pnpm turbo build --filter=@homarr/docs
|
||||
|
||||
FROM alpine:3.22 AS pocketbase
|
||||
|
||||
@@ -39,7 +45,20 @@ RUN case "${TARGETARCH}" in \
|
||||
cd /tmp && grep " ${ARCHIVE}$" checksums.txt | sha256sum -c - && \
|
||||
unzip "/tmp/${ARCHIVE}" pocketbase -d /out
|
||||
|
||||
FROM alpine:3.22
|
||||
FROM alpine:3.22 AS development
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata
|
||||
COPY --from=pocketbase /out/pocketbase /usr/local/bin/pocketbase
|
||||
COPY apps/workshop/entrypoint.dev.sh /usr/local/bin/workshop-dev-entrypoint
|
||||
COPY apps/workshop/dev-public /pb_public
|
||||
RUN chmod +x /usr/local/bin/workshop-dev-entrypoint && \
|
||||
mkdir -p /pb_data /pb_hooks /pb_migrations
|
||||
|
||||
EXPOSE 8090
|
||||
HEALTHCHECK --interval=10s --timeout=5s --start-period=15s --retries=6 CMD wget -q --spider http://127.0.0.1:8090/api/health || exit 1
|
||||
ENTRYPOINT ["workshop-dev-entrypoint"]
|
||||
|
||||
FROM alpine:3.22 AS production
|
||||
|
||||
RUN apk add --no-cache ca-certificates tzdata && addgroup -S pocketbase && adduser -S -G pocketbase pocketbase
|
||||
COPY --from=pocketbase /out/pocketbase /usr/local/bin/pocketbase
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
!patches/**
|
||||
!apps/docs/**
|
||||
!apps/workshop/entrypoint.sh
|
||||
!apps/workshop/entrypoint.dev.sh
|
||||
!apps/workshop/dev-public/**
|
||||
!apps/workshop/pb_hooks/**
|
||||
!apps/workshop/pb_migrations/**
|
||||
!packages/definitions/**
|
||||
|
||||
+64
-40
@@ -1,50 +1,74 @@
|
||||
# Homarr Workshop service
|
||||
|
||||
The Workshop image serves the compiled Homarr documentation and the PocketBase community API from one origin: `https://homarr.dev`. It is not a per-instance Homarr service. Local deployment is for development and integration testing.
|
||||
Workshop combines the public Docusaurus experience with a PocketBase community API. Development keeps the two processes separate; the production image serves both from one origin.
|
||||
|
||||
## Local startup
|
||||
## Development
|
||||
|
||||
1. Copy the repository-root `.env.example` to `.env` and create a GitHub OAuth app.
|
||||
2. Set its callback URL to `http://localhost:<PB_EXPOSE_PORT>/api/oauth2-redirect` (port `8090` by default).
|
||||
3. Set `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `PB_SUPERUSER_EMAIL`, and `PB_SUPERUSER_PASSWORD`.
|
||||
4. Run `pnpm dev:workshop` from the repository root. It builds the single Workshop image, starts it, and removes obsolete Compose containers.
|
||||
|
||||
Open the Workshop at `http://localhost:<PB_EXPOSE_PORT>/workshop`. The API is at `/api` on the same origin and the emergency PocketBase dashboard is at `/_/` (port `8090` by default). `0.0.0.0` in PocketBase's server log is its container bind address, not a browser URL. Day-to-day moderation belongs in `/workshop/admin`, not the PocketBase dashboard.
|
||||
|
||||
All Workshop configuration is read from the repository-root `.env`; there is no app-specific environment file. If port 8090 is unavailable, set `PB_EXPOSE_PORT` there. `pnpm dev:workshop:website` remains available for Docusaurus HMR and connects to the local container through `WORKSHOP_API_URL`.
|
||||
|
||||
The multi-stage image builds Docusaurus, downloads the official PocketBase `0.39.6` release, verifies it against that release's `checksums.txt`, and copies the versioned migrations, hooks, and static website into the runtime image.
|
||||
|
||||
GitHub OAuth configuration is synchronized from the environment on every boot, including for an existing development volume. `PB_ALLOWED_ORIGINS` defaults to `*` because arbitrary self-hosted Homarr origins consume the central API. PocketBase authenticates writes with bearer tokens and does not use cookies; CORS is not an authorization boundary.
|
||||
|
||||
## Roles and account states
|
||||
|
||||
- `member`: publish, update/delete owned submissions, vote, and report.
|
||||
- `moderator`: report queue, submission removal, posting bans, and account disable/restore.
|
||||
- `admin`: moderator actions plus role changes.
|
||||
- `posting_banned`: cannot create or update submissions; can browse, vote, and report.
|
||||
- `disabled`: cannot authenticate or write.
|
||||
|
||||
Bootstrap the first admin through the PocketBase dashboard by changing a GitHub-authenticated user's role. All later staff actions use the restricted Workshop back office and are recorded in `moderation_actions`.
|
||||
|
||||
## Backup and restore
|
||||
|
||||
PocketBase stores records and uploads in `/pb_data`. Stop writes or stop the container, then archive the named volume:
|
||||
From the repository root, run:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env --file apps/workshop/docker-compose.yml stop workshop
|
||||
docker run --rm -v homarr-workshop_workshop_data:/data -v "$PWD":/backup alpine tar czf /backup/workshop-backup.tgz -C /data .
|
||||
docker compose --env-file .env --file apps/workshop/docker-compose.yml start workshop
|
||||
pnpm dev:workshop
|
||||
```
|
||||
|
||||
Restore only into the same PocketBase version after preserving the current volume. Extract the archive into an empty `workshop_data` volume, start the service, and verify `/api/health`, collection migrations, a listing request, and an authenticated write.
|
||||
This starts:
|
||||
|
||||
## Production checklist
|
||||
- PocketBase in Docker with `--dev` at `http://localhost:8090`;
|
||||
- the PocketBase dashboard at `http://localhost:8090/_/`;
|
||||
- `@homarr/workshop` in watch mode on the host;
|
||||
- Docusaurus with HMR at `http://localhost:3003/workshop`.
|
||||
|
||||
- Run `ghcr.io/homarr-labs/workshop:dev` behind the `homarr.dev` TLS endpoint; the image owns both the website and `/api`.
|
||||
- Terminate TLS at the reverse proxy and forward the real client IP.
|
||||
- Keep superuser credentials outside Compose and rotate them after bootstrap.
|
||||
- Restrict the dashboard path to operators; GitHub users never need it.
|
||||
- Review the versioned default rate limits for OAuth, submissions, votes, reports, moderation, and general API traffic against production load before launch.
|
||||
- Back up `/pb_data` before every PocketBase or migration upgrade and test restore regularly.
|
||||
- Monitor health, authentication failures, 429/5xx responses, moderation actions, disk use, and backup age.
|
||||
PocketBase data is bind-mounted at `apps/workshop/pb_data/`. The directory is gitignored and survives container rebuilds. Hooks and migrations are mounted read-only and PocketBase reloads them in development mode.
|
||||
|
||||
No users, superusers, OAuth providers, or submissions are seeded. Create the first superuser manually in the PocketBase dashboard, configure GitHub OAuth on the `users` collection, and use `http://localhost:8090/api/oauth2-redirect` as the local callback URL. OAuth account creation is handled by PocketBase directly. Promote moderators and administrators by creating a `workshop_staff` record for the user; that record is the authorization source of truth.
|
||||
|
||||
Optional ports and CORS behavior are configured only in the repository-root `.env`:
|
||||
|
||||
```dotenv
|
||||
PB_EXPOSE_PORT=8090
|
||||
WORKSHOP_WEB_PORT=3003
|
||||
PB_ALLOWED_ORIGINS=*
|
||||
```
|
||||
|
||||
## Production-like preview
|
||||
|
||||
Run the exact combined image shape used for deployment:
|
||||
|
||||
```sh
|
||||
pnpm preview:workshop
|
||||
```
|
||||
|
||||
The multi-stage image builds Docusaurus, verifies and installs PocketBase `0.39.6`, copies the hooks and migrations, and serves everything from `http://localhost:8090`:
|
||||
|
||||
- website: `http://localhost:8090/workshop`;
|
||||
- API: `http://localhost:8090/api`;
|
||||
- dashboard: `http://localhost:8090/_/`.
|
||||
|
||||
The preview reuses `apps/workshop/pb_data/`, so OAuth configuration and local records remain available when switching between development and preview. `--remove-orphans` replaces the previous service shape without deleting data.
|
||||
|
||||
## Reset local data
|
||||
|
||||
Resetting is always explicit:
|
||||
|
||||
```sh
|
||||
pnpm reset:workshop
|
||||
```
|
||||
|
||||
The command asks for confirmation, stops both service variants, and clears `apps/workshop/pb_data/`. For automation, use `pnpm reset:workshop -- --force`.
|
||||
|
||||
Authentication failures for an old email are requests made by the PocketBase dashboard against the persisted database; Workshop startup never attempts to authenticate or seed that account.
|
||||
|
||||
## Build and validation
|
||||
|
||||
`pnpm build` builds both `@homarr/workshop` and Docusaurus as part of the monorepo build. The production image can be validated locally with:
|
||||
|
||||
```sh
|
||||
pnpm test:workshop-preview
|
||||
```
|
||||
|
||||
The test uses a temporary database, builds and starts the production image, checks the website, API, service worker, and migrated collections, then removes all test state. The dedicated Workshop CI workflow runs this test only when Workshop-related sources or build inputs change; it does not publish an image.
|
||||
|
||||
## Operations
|
||||
|
||||
The live service uses the production target behind the `homarr.dev` TLS proxy. PocketBase superuser access is bootstrap/emergency access only; normal moderation belongs in `/workshop/admin`.
|
||||
|
||||
Back up `/pb_data` before PocketBase or schema upgrades. It contains records, uploads, OAuth settings, and credentials. Production must also restrict `/_/`, monitor health and authentication failures, and validate backup restoration regularly.
|
||||
@@ -0,0 +1,10 @@
|
||||
self.addEventListener("install", () => self.skipWaiting());
|
||||
|
||||
self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(
|
||||
Promise.all([
|
||||
caches.keys().then((keys) => Promise.all(keys.map((key) => caches.delete(key)))),
|
||||
self.registration.unregister(),
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
name: homarr-workshop
|
||||
|
||||
services:
|
||||
workshop:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: apps/workshop/Dockerfile
|
||||
target: production
|
||||
args:
|
||||
POCKETBASE_VERSION: 0.39.6
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
|
||||
ports:
|
||||
- "127.0.0.1:${PB_EXPOSE_PORT:-8090}:8090"
|
||||
volumes:
|
||||
- ${WORKSHOP_DATA_DIR:-./pb_data}:/pb_data
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
@@ -5,23 +5,17 @@ services:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: apps/workshop/Dockerfile
|
||||
target: development
|
||||
args:
|
||||
POCKETBASE_VERSION: 0.39.6
|
||||
image: homarr/workshop:0.39.6
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
|
||||
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
|
||||
PB_SUPERUSER_EMAIL: ${PB_SUPERUSER_EMAIL:-}
|
||||
PB_SUPERUSER_PASSWORD: ${PB_SUPERUSER_PASSWORD:-}
|
||||
PB_PUBLIC_URL: ${PB_PUBLIC_URL:-http://localhost:${PB_EXPOSE_PORT:-8090}}
|
||||
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
|
||||
ports:
|
||||
- "127.0.0.1:${PB_EXPOSE_PORT:-8090}:8090"
|
||||
volumes:
|
||||
- workshop_data:/pb_data
|
||||
- ${WORKSHOP_DATA_DIR:-./pb_data}:/pb_data
|
||||
- ./pb_hooks:/pb_hooks:ro
|
||||
- ./pb_migrations:/pb_migrations:ro
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
|
||||
volumes:
|
||||
workshop_data:
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
echo "Workshop development API: http://localhost:8090/api"
|
||||
echo "PocketBase dashboard: http://localhost:8090/_/"
|
||||
|
||||
exec pocketbase serve \
|
||||
--dev \
|
||||
--automigrate=false \
|
||||
--http=0.0.0.0:8090 \
|
||||
--origins="${PB_ALLOWED_ORIGINS:-*}" \
|
||||
--dir=/pb_data \
|
||||
--hooksDir=/pb_hooks \
|
||||
--migrationsDir=/pb_migrations \
|
||||
--publicDir=/pb_public \
|
||||
--indexFallback=true
|
||||
@@ -1,12 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
if [ -n "${PB_SUPERUSER_EMAIL:-}" ] && [ -n "${PB_SUPERUSER_PASSWORD:-}" ]; then
|
||||
pocketbase superuser upsert "${PB_SUPERUSER_EMAIL}" "${PB_SUPERUSER_PASSWORD}" --dir=/pb_data
|
||||
fi
|
||||
|
||||
echo "Workshop: ${PB_PUBLIC_URL:-http://localhost:8090}/workshop"
|
||||
echo "Workshop API: ${PB_PUBLIC_URL:-http://localhost:8090}/api"
|
||||
echo "Workshop is listening on port 8090"
|
||||
echo "Workshop API is available at /api"
|
||||
|
||||
exec pocketbase serve \
|
||||
--http=0.0.0.0:8090 \
|
||||
|
||||
@@ -20,12 +20,10 @@ function fail(ErrorType, _code, message) {
|
||||
throw new ErrorType(message);
|
||||
}
|
||||
|
||||
function requireWritableAccount(app, auth, posting) {
|
||||
function requireWritableAccount(app, auth) {
|
||||
if (!auth) fail(UnauthorizedError, "authentication_required", "Authentication is required");
|
||||
const account = app.findRecordById("users", auth.id);
|
||||
if (account.getString("state") === "disabled") fail(ForbiddenError, "account_disabled", "Account is disabled");
|
||||
if (posting && account.getString("state") === "posting_banned")
|
||||
fail(ForbiddenError, "posting_banned", "Account cannot publish submissions");
|
||||
return account;
|
||||
}
|
||||
|
||||
@@ -78,10 +76,31 @@ function snapshot(record) {
|
||||
}
|
||||
|
||||
function requireStaff(app, auth) {
|
||||
const account = requireWritableAccount(app, auth, false);
|
||||
const role = account.getString("role");
|
||||
if (role !== "moderator" && role !== "admin") fail(ForbiddenError, "forbidden", "Staff access is required");
|
||||
return role;
|
||||
requireWritableAccount(app, auth);
|
||||
let staff;
|
||||
try {
|
||||
staff = app.findFirstRecordByFilter("workshop_staff", "user = {:user}", { user: auth.id });
|
||||
} catch {
|
||||
fail(ForbiddenError, "forbidden", "Staff access is required");
|
||||
}
|
||||
return staff.getString("role");
|
||||
}
|
||||
|
||||
function setStaffRole(app, user, role) {
|
||||
let staff = null;
|
||||
try {
|
||||
staff = app.findFirstRecordByFilter("workshop_staff", "user = {:user}", { user: user.id });
|
||||
} catch {
|
||||
// Members do not have a staff record.
|
||||
}
|
||||
if (role === "member") {
|
||||
if (staff) app.delete(staff);
|
||||
return;
|
||||
}
|
||||
if (!staff) staff = new Record(app.findCollectionByNameOrId("workshop_staff"));
|
||||
staff.set("user", user.id);
|
||||
staff.set("role", role);
|
||||
app.save(staff);
|
||||
}
|
||||
|
||||
function body(e) {
|
||||
@@ -104,4 +123,13 @@ function audit(app, actor, action, targetType, targetId, reason, targetSnapshot)
|
||||
app.save(record);
|
||||
}
|
||||
|
||||
module.exports = { audit, body, fail, requireStaff, requireWritableAccount, snapshot, validateSubmission };
|
||||
module.exports = {
|
||||
audit,
|
||||
body,
|
||||
fail,
|
||||
requireStaff,
|
||||
requireWritableAccount,
|
||||
setStaffRole,
|
||||
snapshot,
|
||||
validateSubmission,
|
||||
};
|
||||
@@ -1,42 +1,5 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
onBootstrap((e) => {
|
||||
e.next();
|
||||
const users = e.app.findCollectionByNameOrId("users");
|
||||
const clientId = $os.getenv("GITHUB_CLIENT_ID");
|
||||
const clientSecret = $os.getenv("GITHUB_CLIENT_SECRET");
|
||||
users.oauth2.enabled = Boolean(clientId && clientSecret);
|
||||
users.oauth2.providers = clientId && clientSecret ? [{ name: "github", clientId, clientSecret }] : [];
|
||||
e.app.save(users);
|
||||
});
|
||||
|
||||
onRecordAuthWithOAuth2Request((e) => {
|
||||
const utils = require(`${__hooks}/workshop-utils.js`);
|
||||
if (e.record && e.record.getString("state") === "disabled")
|
||||
utils.fail(ForbiddenError, "account_disabled", "Account is disabled");
|
||||
if (e.isNewRecord) {
|
||||
e.createData.displayName = e.oAuth2User.name || e.oAuth2User.username || "Community member";
|
||||
e.createData.avatarUrl = e.oAuth2User.avatarUrl || "";
|
||||
e.createData.role = "member";
|
||||
e.createData.state = "active";
|
||||
}
|
||||
e.next();
|
||||
}, "users");
|
||||
|
||||
onRecordAuthRequest((e) => {
|
||||
const utils = require(`${__hooks}/workshop-utils.js`);
|
||||
if (e.record.getString("state") === "disabled") utils.fail(ForbiddenError, "account_disabled", "Account is disabled");
|
||||
e.next();
|
||||
}, "users");
|
||||
|
||||
onRecordUpdateRequest((e) => {
|
||||
const original = e.app.findRecordById("users", e.record.id);
|
||||
e.record.set("role", original.get("role"));
|
||||
e.record.set("state", original.get("state"));
|
||||
e.record.set("moderationReason", original.get("moderationReason"));
|
||||
e.next();
|
||||
}, "users");
|
||||
|
||||
onRecordCreateRequest((e) => {
|
||||
const utils = require(`${__hooks}/workshop-utils.js`);
|
||||
const account = utils.requireWritableAccount(e.app, e.auth, true);
|
||||
@@ -116,8 +79,7 @@ routerAdd(
|
||||
const utils = require(`${__hooks}/workshop-utils.js`);
|
||||
const actorRole = utils.requireStaff(e.app, e.auth);
|
||||
const data = utils.body(e);
|
||||
if (!["active", "posting_banned", "disabled"].includes(data.state))
|
||||
throw new BadRequestError("Invalid account state");
|
||||
if (!["active", "disabled"].includes(data.state)) throw new BadRequestError("Invalid account state");
|
||||
const id = e.request.pathValue("id");
|
||||
if (id === e.auth.id) throw new BadRequestError("You cannot moderate your own account");
|
||||
e.app.runInTransaction((tx) => {
|
||||
@@ -149,6 +111,7 @@ routerAdd(
|
||||
const previous = utils.snapshot(target);
|
||||
target.set("role", data.role);
|
||||
tx.save(target);
|
||||
utils.setStaffRole(tx, target, data.role);
|
||||
utils.audit(tx, e.auth, "set_role", "user", id, data.reason, previous);
|
||||
});
|
||||
return e.json(200, { success: true });
|
||||
|
||||
@@ -13,7 +13,8 @@ migrate(
|
||||
}
|
||||
users.listRule = "@request.auth.role = 'moderator' || @request.auth.role = 'admin'";
|
||||
users.viewRule = "id = @request.auth.id || @request.auth.role = 'moderator' || @request.auth.role = 'admin'";
|
||||
users.updateRule = "id = @request.auth.id && @request.auth.state != 'disabled'";
|
||||
users.updateRule =
|
||||
"id = @request.auth.id && @request.auth.state != 'disabled' && @request.body.role:changed = false && @request.body.state:changed = false && @request.body.moderationReason:changed = false";
|
||||
users.deleteRule = null;
|
||||
users.passwordAuth = { enabled: false };
|
||||
// PocketBase creates a default users auth collection on first boot, so
|
||||
@@ -26,20 +27,35 @@ migrate(
|
||||
name: "state",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
values: ["active", "posting_banned", "disabled"],
|
||||
values: ["active", "disabled"],
|
||||
}),
|
||||
new TextField({ name: "moderationReason", max: 1000 }),
|
||||
);
|
||||
const githubClientId = $os.getenv("GITHUB_CLIENT_ID");
|
||||
const githubClientSecret = $os.getenv("GITHUB_CLIENT_SECRET");
|
||||
users.oauth2.enabled = Boolean(githubClientId && githubClientSecret);
|
||||
users.oauth2.providers =
|
||||
githubClientId && githubClientSecret
|
||||
? [{ name: "github", clientId: githubClientId, clientSecret: githubClientSecret }]
|
||||
: [];
|
||||
app.save(users);
|
||||
|
||||
const staffRule = "@request.auth.role = 'moderator' || @request.auth.role = 'admin'";
|
||||
const workshopStaff = new Collection({
|
||||
type: "base",
|
||||
name: "workshop_staff",
|
||||
listRule: "user = @request.auth.id",
|
||||
viewRule: "user = @request.auth.id",
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [
|
||||
{ type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
|
||||
{ type: "select", name: "role", required: true, maxSelect: 1, values: ["moderator", "admin"] },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
workshopStaff.addIndex("idx_workshop_staff_user", true, "user", "");
|
||||
app.save(workshopStaff);
|
||||
|
||||
const staffRule = "@collection.workshop_staff.user ?= @request.auth.id";
|
||||
users.listRule = staffRule;
|
||||
users.viewRule = `id = @request.auth.id || ${staffRule}`;
|
||||
app.save(users);
|
||||
|
||||
const writableRule = "@request.auth.id != '' && @request.auth.state != 'disabled'";
|
||||
const authorRule = "author = @request.auth.id && @request.auth.state = 'active'";
|
||||
|
||||
@@ -241,7 +257,14 @@ migrate(
|
||||
(app) => {
|
||||
// PocketBase creates the users auth collection before this migration. Keep
|
||||
// it intact on rollback so reverting Workshop can never delete accounts.
|
||||
for (const name of ["workshop_listings", "moderation_actions", "reports", "votes", "submissions"]) {
|
||||
for (const name of [
|
||||
"workshop_listings",
|
||||
"moderation_actions",
|
||||
"reports",
|
||||
"votes",
|
||||
"submissions",
|
||||
"workshop_staff",
|
||||
]) {
|
||||
try {
|
||||
app.delete(app.findCollectionByNameOrId(name));
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
const state = users.fields.getByName("state");
|
||||
if (state) state.values = ["active", "disabled"];
|
||||
|
||||
let staff;
|
||||
try {
|
||||
staff = app.findCollectionByNameOrId("workshop_staff");
|
||||
} catch {
|
||||
staff = new Collection({
|
||||
type: "base",
|
||||
name: "workshop_staff",
|
||||
listRule: "user = @request.auth.id",
|
||||
viewRule: "user = @request.auth.id",
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [
|
||||
{
|
||||
type: "relation",
|
||||
name: "user",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
collectionId: users.id,
|
||||
cascadeDelete: true,
|
||||
},
|
||||
{ type: "select", name: "role", required: true, maxSelect: 1, values: ["moderator", "admin"] },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
staff.addIndex("idx_workshop_staff_user", true, "user", "");
|
||||
app.save(staff);
|
||||
}
|
||||
|
||||
for (const user of app.findRecordsByFilter("users", "role = 'moderator' || role = 'admin'", "", 0, 0)) {
|
||||
if (!user) continue;
|
||||
let record;
|
||||
try {
|
||||
record = app.findFirstRecordByFilter("workshop_staff", "user = {:user}", { user: user.id });
|
||||
} catch {
|
||||
record = new Record(staff);
|
||||
record.set("user", user.id);
|
||||
}
|
||||
record.set("role", user.getString("role"));
|
||||
app.save(record);
|
||||
}
|
||||
|
||||
const staffRule = "@collection.workshop_staff.user ?= @request.auth.id";
|
||||
users.listRule = staffRule;
|
||||
users.viewRule = `id = @request.auth.id || ${staffRule}`;
|
||||
users.updateRule =
|
||||
"id = @request.auth.id && @request.auth.state != 'disabled' && @request.body.role:changed = false && @request.body.state:changed = false && @request.body.moderationReason:changed = false";
|
||||
app.save(users);
|
||||
},
|
||||
(app) => {
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
users.listRule = "@request.auth.role = 'moderator' || @request.auth.role = 'admin'";
|
||||
users.viewRule = "id = @request.auth.id || @request.auth.role = 'moderator' || @request.auth.role = 'admin'";
|
||||
users.updateRule = "id = @request.auth.id && @request.auth.state != 'disabled'";
|
||||
const state = users.fields.getByName("state");
|
||||
if (state) state.values = ["active", "posting_banned", "disabled"];
|
||||
app.save(users);
|
||||
try {
|
||||
app.delete(app.findCollectionByNameOrId("workshop_staff"));
|
||||
} catch {
|
||||
// Already removed.
|
||||
}
|
||||
},
|
||||
);
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
data_dir="${WORKSHOP_DATA_DIR:-apps/workshop/pb_data}"
|
||||
|
||||
if [ "${1:-}" != "--force" ]; then
|
||||
printf "Delete the local Workshop database at %s? [y/N] " "$data_dir"
|
||||
read -r answer
|
||||
case "$answer" in
|
||||
y|Y|yes|YES) ;;
|
||||
*) echo "Reset cancelled"; exit 0 ;;
|
||||
esac
|
||||
fi
|
||||
|
||||
docker compose --env-file .env --file apps/workshop/docker-compose.yml down --remove-orphans >/dev/null 2>&1 || true
|
||||
docker compose --env-file .env --file apps/workshop/docker-compose.preview.yml down --remove-orphans >/dev/null 2>&1 || true
|
||||
|
||||
mkdir -p "$data_dir"
|
||||
docker run --rm --volume "$(cd "$data_dir" && pwd):/data" alpine:3.22 sh -c 'rm -rf /data/.[!.]* /data/..?* /data/*'
|
||||
echo "Workshop database reset"
|
||||
@@ -5,24 +5,49 @@ project="homarr-workshop-integration"
|
||||
port="${WORKSHOP_TEST_PORT:-18091}"
|
||||
email="integration@homarr.test"
|
||||
password="${WORKSHOP_TEST_PASSWORD:-WorkshopIntegrationPassword123!}"
|
||||
data_dir="$(mktemp -d)"
|
||||
|
||||
cleanup() {
|
||||
PB_EXPOSE_PORT="$port" docker compose --env-file .env.example --file apps/workshop/docker-compose.yml --project-name "$project" down --volumes >/dev/null 2>&1 || true
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose --env-file .env.example --file apps/workshop/docker-compose.yml --project-name "$project" down --remove-orphans >/dev/null 2>&1 || true
|
||||
docker run --rm --volume "$data_dir:/data" alpine:3.22 sh -c 'rm -rf /data/.[!.]* /data/..?* /data/*' >/dev/null 2>&1 || true
|
||||
rmdir "$data_dir" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
cleanup
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose --env-file .env.example --file apps/workshop/docker-compose.yml --project-name "$project" down --remove-orphans >/dev/null 2>&1 || true
|
||||
|
||||
PB_EXPOSE_PORT="$port" \
|
||||
PB_SUPERUSER_EMAIL="$email" \
|
||||
PB_SUPERUSER_PASSWORD="$password" \
|
||||
GITHUB_CLIENT_ID="integration-client" \
|
||||
GITHUB_CLIENT_SECRET="integration-secret" \
|
||||
docker compose --env-file .env.example --file apps/workshop/docker-compose.yml --project-name "$project" up --detach --build --wait
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose \
|
||||
--env-file .env.example \
|
||||
--file apps/workshop/docker-compose.yml \
|
||||
--project-name "$project" \
|
||||
up --detach --build --wait
|
||||
|
||||
WORKSHOP_DATA_DIR="$data_dir" docker compose \
|
||||
--env-file .env.example \
|
||||
--file apps/workshop/docker-compose.yml \
|
||||
--project-name "$project" \
|
||||
exec --no-TTY workshop pocketbase superuser upsert "$email" "$password" --dir=/pb_data
|
||||
|
||||
if ! WORKSHOP_TEST_URL="http://127.0.0.1:$port" \
|
||||
WORKSHOP_TEST_SUPERUSER_EMAIL="$email" \
|
||||
WORKSHOP_TEST_SUPERUSER_PASSWORD="$password" \
|
||||
node apps/workshop/tests/workshop.integration.mjs; then
|
||||
docker compose --env-file .env.example --file apps/workshop/docker-compose.yml --project-name "$project" logs --no-color workshop
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose --env-file .env.example --file apps/workshop/docker-compose.yml --project-name "$project" logs --no-color workshop
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose \
|
||||
--env-file .env.example \
|
||||
--file apps/workshop/docker-compose.yml \
|
||||
--project-name "$project" \
|
||||
restart workshop >/dev/null
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose \
|
||||
--env-file .env.example \
|
||||
--file apps/workshop/docker-compose.yml \
|
||||
--project-name "$project" \
|
||||
up --detach --wait >/dev/null
|
||||
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$port" \
|
||||
WORKSHOP_TEST_SUPERUSER_EMAIL="$email" \
|
||||
WORKSHOP_TEST_SUPERUSER_PASSWORD="$password" \
|
||||
WORKSHOP_VERIFY_CONFIGURATION_ONLY=true \
|
||||
node apps/workshop/tests/workshop.integration.mjs
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
project="homarr-workshop-preview-test"
|
||||
port="${WORKSHOP_PREVIEW_TEST_PORT:-18092}"
|
||||
email="preview@homarr.test"
|
||||
password="${WORKSHOP_PREVIEW_TEST_PASSWORD:-WorkshopPreviewPassword123!}"
|
||||
data_dir="$(mktemp -d)"
|
||||
base_url="http://127.0.0.1:$port"
|
||||
|
||||
cleanup() {
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose --env-file .env.example --file apps/workshop/docker-compose.preview.yml --project-name "$project" down --remove-orphans >/dev/null 2>&1 || true
|
||||
docker run --rm --volume "$data_dir:/data" alpine:3.22 sh -c 'rm -rf /data/.[!.]* /data/..?* /data/*' >/dev/null 2>&1 || true
|
||||
rmdir "$data_dir" >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose --env-file .env.example --file apps/workshop/docker-compose.preview.yml --project-name "$project" down --remove-orphans >/dev/null 2>&1 || true
|
||||
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose \
|
||||
--env-file .env.example \
|
||||
--file apps/workshop/docker-compose.preview.yml \
|
||||
--project-name "$project" \
|
||||
up --detach --build --wait
|
||||
|
||||
curl --fail --silent --show-error "$base_url/api/health" >/dev/null
|
||||
curl --fail --silent --show-error --location "$base_url/workshop" >/dev/null
|
||||
curl --fail --silent --show-error "$base_url/workshop-sw.js" >/dev/null
|
||||
|
||||
PB_EXPOSE_PORT="$port" WORKSHOP_DATA_DIR="$data_dir" docker compose \
|
||||
--env-file .env.example \
|
||||
--file apps/workshop/docker-compose.preview.yml \
|
||||
--project-name "$project" \
|
||||
exec --no-TTY workshop pocketbase superuser upsert "$email" "$password" --dir=/pb_data >/dev/null
|
||||
|
||||
token="$(curl --fail --silent --show-error \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data "{\"identity\":\"$email\",\"password\":\"$password\"}" \
|
||||
"$base_url/api/collections/_superusers/auth-with-password" | jq --raw-output '.token')"
|
||||
|
||||
collections="$(curl --fail --silent --show-error \
|
||||
--header "Authorization: $token" \
|
||||
"$base_url/api/collections?perPage=200")"
|
||||
|
||||
for collection in users submissions votes reports moderation_actions workshop_listings; do
|
||||
echo "$collections" | jq --exit-status --arg name "$collection" '.items | any(.name == $name)' >/dev/null || {
|
||||
echo "Missing Workshop collection: $collection" >&2
|
||||
exit 1
|
||||
}
|
||||
done
|
||||
|
||||
echo "Workshop production preview passed"
|
||||
@@ -5,18 +5,32 @@ import PocketBase, { ClientResponseError } from "pocketbase";
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL;
|
||||
const superuserEmail = process.env.WORKSHOP_TEST_SUPERUSER_EMAIL;
|
||||
const superuserPassword = process.env.WORKSHOP_TEST_SUPERUSER_PASSWORD;
|
||||
const verifyConfigurationOnly = process.env.WORKSHOP_VERIFY_CONFIGURATION_ONLY === "true";
|
||||
assert(baseUrl && superuserEmail && superuserPassword, "Workshop integration test environment is incomplete");
|
||||
|
||||
const root = new PocketBase(baseUrl);
|
||||
await root.collection("_superusers").authWithPassword(superuserEmail, superuserPassword);
|
||||
if (!verifyConfigurationOnly) {
|
||||
await root.collections.update("users", {
|
||||
oauth2: {
|
||||
enabled: true,
|
||||
providers: [{ name: "github", clientId: "integration-client", clientSecret: "integration-secret" }],
|
||||
},
|
||||
});
|
||||
}
|
||||
const authMethods = await root.collection("users").listAuthMethods();
|
||||
assert.equal(authMethods.oauth2.enabled, true, "GitHub OAuth must be configured from the runtime environment");
|
||||
assert.equal(authMethods.oauth2.enabled, true, "GitHub OAuth must retain its persisted PocketBase configuration");
|
||||
assert.equal(authMethods.password.enabled, false, "password authentication must remain disabled");
|
||||
assert.deepEqual(
|
||||
authMethods.oauth2.providers.map((provider) => provider.name),
|
||||
["github"],
|
||||
);
|
||||
|
||||
if (verifyConfigurationOnly) {
|
||||
console.log("Workshop PocketBase configuration persisted across restart");
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const createUser = async (name, role = "member", state = "active") => {
|
||||
const password = `Workshop${name}Password123!`;
|
||||
return root.collection("users").create({
|
||||
@@ -37,28 +51,29 @@ const expectStatus = async (operation, status) => {
|
||||
|
||||
const memberRecord = await createUser("Member");
|
||||
const secondMemberRecord = await createUser("SecondMember");
|
||||
const bannedRecord = await createUser("Banned", "member", "posting_banned");
|
||||
const disabledRecord = await createUser("Disabled");
|
||||
const moderatorRecord = await createUser("Moderator", "moderator");
|
||||
const adminRecord = await createUser("Admin", "admin");
|
||||
await root.collection("workshop_staff").create({ user: moderatorRecord.id, role: "moderator" });
|
||||
await root.collection("workshop_staff").create({ user: adminRecord.id, role: "admin" });
|
||||
|
||||
const member = await root.collection("users").impersonate(memberRecord.id, 3600);
|
||||
const secondMember = await root.collection("users").impersonate(secondMemberRecord.id, 3600);
|
||||
const banned = await root.collection("users").impersonate(bannedRecord.id, 3600);
|
||||
const disabled = await root.collection("users").impersonate(disabledRecord.id, 3600);
|
||||
const moderator = await root.collection("users").impersonate(moderatorRecord.id, 3600);
|
||||
const admin = await root.collection("users").impersonate(adminRecord.id, 3600);
|
||||
|
||||
assert.equal((await member.collection("users").getList()).totalItems, 0, "members must not list Workshop accounts");
|
||||
|
||||
const forgedMember = await member.collection("users").update(memberRecord.id, {
|
||||
role: "admin",
|
||||
state: "posting_banned",
|
||||
moderationReason: "self escalation",
|
||||
});
|
||||
assert.equal(forgedMember.role, "member", "members must not change their own role");
|
||||
assert.equal(forgedMember.state, "active", "members must not change their own account state");
|
||||
assert.equal(forgedMember.moderationReason, "", "members must not change protected moderation fields");
|
||||
await expectStatus(
|
||||
() =>
|
||||
member.collection("users").update(memberRecord.id, {
|
||||
role: "admin",
|
||||
state: "disabled",
|
||||
moderationReason: "self escalation",
|
||||
}),
|
||||
[403, 404],
|
||||
);
|
||||
|
||||
await admin.send(`/api/workshop/moderation/users/${disabledRecord.id}/state`, {
|
||||
method: "POST",
|
||||
@@ -89,10 +104,6 @@ assert.equal(submission.authorName, "Member", "server must snapshot the authenti
|
||||
assert.equal(submission.revision, 1, "server must own the initial revision");
|
||||
assert.equal(submission.schemaVersion, "homarr-custom-widget-v2", "server must own schemaVersion");
|
||||
|
||||
await expectStatus(
|
||||
() => banned.collection("submissions").create({ type: "css", title: "Blocked theme", content: "body {}" }),
|
||||
403,
|
||||
);
|
||||
await expectStatus(() => disabled.collection("votes").create({ submission: submission.id, value: 1 }), [400, 403]);
|
||||
await expectStatus(
|
||||
() =>
|
||||
@@ -127,7 +138,7 @@ await expectStatus(
|
||||
() =>
|
||||
member.send(`/api/workshop/moderation/users/${secondMemberRecord.id}/state`, {
|
||||
method: "POST",
|
||||
body: { state: "posting_banned", reason: "No permission" },
|
||||
body: { state: "disabled", reason: "No permission" },
|
||||
}),
|
||||
403,
|
||||
);
|
||||
@@ -153,6 +164,10 @@ await admin.send(`/api/workshop/moderation/users/${secondMemberRecord.id}/role`,
|
||||
body: { role: "moderator", reason: "Integration promotion" },
|
||||
});
|
||||
assert.equal((await root.collection("users").getOne(secondMemberRecord.id)).role, "moderator");
|
||||
assert.equal(
|
||||
(await root.collection("workshop_staff").getFirstListItem(`user = '${secondMemberRecord.id}'`)).role,
|
||||
"moderator",
|
||||
);
|
||||
|
||||
await moderator.send(`/api/workshop/moderation/reports/${report.id}/resolve`, {
|
||||
method: "POST",
|
||||
|
||||
Reference in new issue
Block a user