harden v2 custom widgets and workshop

This commit is contained in:
ajnart committed 2026-07-28 14:12:14 +02:00
1 parent e8a2c87c2d
commit 723b46926a
194 files changed
+44862 -1265

No files matched your search

+14
View File
@@ -0,0 +1,14 @@
# Local PocketBase + Docusaurus development
PB_EXPOSE_PORT=8090
DOCS_EXPOSE_PORT=3003
PB_ALLOWED_ORIGINS=*
WORKSHOP_PUBLIC_ORIGIN=http://127.0.0.1:3003
HOMARR_WEBSITE_URL=http://127.0.0.1:3003
WORKSHOP_API_URL=http://127.0.0.1:8090
WORKSHOP_WEB_URL=http://127.0.0.1:3003/workshop
DOCS_BASE_URL=/
WORKSHOP_REQUIRE_OAUTH=false
# Optional local GitHub OAuth application.
# GITHUB_CLIENT_ID=
# GITHUB_CLIENT_SECRET=
+36 -5
View File
@@ -1,6 +1,6 @@
# syntax=docker/dockerfile:1.10
ARG POCKETBASE_IMAGE=ghcr.io/muchobien/pocketbase:0.39
ARG POCKETBASE_IMAGE=ghcr.io/muchobien/pocketbase:0.39.9@sha256:c0667fe6c5197ff226ff642120ab1ad870c3f2f27300940a61e5a7fa082b6816
FROM node:24.18.0-alpine AS dependencies
WORKDIR /app
@@ -13,26 +13,57 @@ COPY packages/custom-widgets ./packages/custom-widgets
COPY packages/definitions ./packages/definitions
COPY packages/workshop ./packages/workshop
COPY tooling/typescript ./tooling/typescript
RUN --mount=type=cache,id=workshop-pnpm-store,target=/pnpm/store pnpm config set store-dir /pnpm/store && pnpm install --filter @homarr/docs... --frozen-lockfile
RUN pnpm config set store-dir /pnpm/store && pnpm install --filter @homarr/docs... --frozen-lockfile
RUN pnpm build:workshop-validator
FROM dependencies AS website
RUN CI=true SKIP_ENV_VALIDATION=true pnpm turbo build --filter=@homarr/docs
ARG HOMARR_WEBSITE_URL=https://homarr.dev
ARG WORKSHOP_API_URL=https://homarr.dev
ARG WORKSHOP_WEB_URL=https://homarr.dev/workshop
ARG DOCS_BASE_URL=/
ENV HOMARR_WEBSITE_URL=$HOMARR_WEBSITE_URL
ENV WORKSHOP_API_URL=$WORKSHOP_API_URL
ENV WORKSHOP_WEB_URL=$WORKSHOP_WEB_URL
ENV DOCS_BASE_URL=$DOCS_BASE_URL
RUN CI=true SKIP_ENV_VALIDATION=true pnpm turbo build --filter=@homarr/docs \
&& mkdir -p /app/workshop-public \
&& docs_path="$(printf '%s' "$DOCS_BASE_URL" | sed 's#^/*##; s#/*$##')" \
&& if [ -z "$docs_path" ]; then \
cp -R /app/apps/docs/build/. /app/workshop-public/; \
else \
mkdir -p "/app/workshop-public/$docs_path" \
&& cp -R /app/apps/docs/build/. "/app/workshop-public/$docs_path/" \
&& cp /app/apps/docs/build/index.html /app/workshop-public/index.html; \
fi
FROM ${POCKETBASE_IMAGE} AS pocketbase-runtime
ENV PORT=8090
RUN addgroup -S pocketbase && adduser -S -G pocketbase pocketbase
COPY apps/workshop/entrypoint.sh /usr/local/bin/workshop-entrypoint
RUN chmod +x /usr/local/bin/workshop-entrypoint && mkdir -p /pb_data /pb_public && chown pocketbase:pocketbase /pb_data
COPY apps/workshop/workshop-url.awk /usr/local/lib/workshop-url.awk
RUN chmod 755 /usr/local/bin/workshop-entrypoint \
&& chmod 644 /usr/local/lib/workshop-url.awk \
&& mkdir -p /pb_data /pb_public \
&& chown pocketbase:pocketbase /pb_data /pb_public
ENTRYPOINT ["workshop-entrypoint"]
FROM pocketbase-runtime AS development
COPY --chown=pocketbase:pocketbase apps/workshop/pb_migrations /pb_migrations
COPY --chown=pocketbase:pocketbase apps/workshop/pb_hooks /pb_hooks
COPY --from=dependencies --chown=pocketbase:pocketbase \
/app/apps/workshop/pb_hooks/widget-validator.bundle.cjs \
/pb_hooks/widget-validator.bundle.cjs
EXPOSE 8090
HEALTHCHECK --interval=10s --timeout=5s --start-period=15s --retries=6 CMD wget -q --spider "http://127.0.0.1:${PORT}/api/health" || exit 1
FROM pocketbase-runtime AS production
COPY --from=website /app/apps/docs/build /pb_public
ENV WORKSHOP_REQUIRE_PUBLIC_ORIGIN=true
COPY --from=website /app/workshop-public /pb_public
COPY apps/workshop/pb_migrations /pb_migrations
COPY apps/workshop/pb_hooks /pb_hooks
COPY --from=dependencies \
/app/apps/workshop/pb_hooks/widget-validator.bundle.cjs \
/pb_hooks/widget-validator.bundle.cjs
RUN chown -R pocketbase:pocketbase /pb_hooks /pb_migrations /pb_public
EXPOSE 8090
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD wget -q --spider "http://127.0.0.1:${PORT}/api/health" || exit 1
-7
View File
@@ -1,7 +0,0 @@
.git
.next
.turbo
**/node_modules
**/pb_data
apps/docs/build
coverage
+129 -59
View File
@@ -1,105 +1,175 @@
# Homarr Workshop
Workshop is a small PocketBase service that serves the public documentation site and stores one Custom JSX v2 widget per submission.
Workshop is the public, community-driven PocketBase service behind the Workshop pages in Homarr's Docusaurus site. It
stores Custom JSX v2 widgets and Custom CSS submissions. Installation-time validation inside Homarr remains
authoritative: public content must be reviewed before it is installed.
The runtime image extends `ghcr.io/muchobien/pocketbase:0.39`; Homarr adds only the built documentation, PocketBase
collections, API rules, and its explicit serve arguments.
The runtime base is PocketBase 0.39.9 pinned by its multi-platform OCI digest in `apps/workshop/Dockerfile`. Update the
version and digest together, then run the Workshop integration and production-image smoke suites.
It intentionally has no approval queue, user bans, moderator roles, reusable widget connections, or remote control over
installed widgets. Submissions publish immediately. Authenticated users can vote, comment, and report; users with
`isAdmin` enabled can dismiss reports or delete any submission or comment.
The internal PocketBase field `users.isAdmin` means **Workshop moderator**. It does not grant Homarr administrator
access. Moderators can review private reports, dismiss reports, and remove submissions or comments.
## Local development
## Run the complete local stack
From the repository root:
```sh
pnpm docker:workshop
cp .env.example .env
pnpm install --frozen-lockfile
pnpm dev:workshop
```
Use `docker compose -f apps/workshop/docker-compose.yml logs -f workshop` for logs and
`docker compose -f apps/workshop/docker-compose.yml stop workshop` to stop it without deleting data.
This starts persistent PocketBase at `http://127.0.0.1:8090`, waits for health and required collections, and starts
Docusaurus at `http://127.0.0.1:3003`. Open:
Compose passes the selected port to PocketBase as `PORT`, so it listens on the same port inside and outside the
container. With the image directly, set both values: `docker run -e PORT=3003 -p 3003:3003 <workshop-image>`.
- PocketBase administration: `http://127.0.0.1:8090/_/`
- Workshop: `http://127.0.0.1:3003/workshop`
Open `http://127.0.0.1:18090/_/`, create the first PocketBase superuser, and configure GitHub OAuth on the `users` collection.
For direct Compose work, copy `apps/workshop/.env.example` to `apps/workshop/.env` and pass it explicitly with
`docker compose --env-file apps/workshop/.env -f apps/workshop/docker-compose.yml …`.
The `users.isAdmin` field defaults to `false`. Collection rules allow account creation only through OAuth without that
field and reject all regular-user attempts to change it. Appoint administrators out of band with a PocketBase
superuser or a deliberate SQLite update; there is no public role-management endpoint or hook.
Create the first PocketBase superuser in the administration UI, or use:
Users must sign in again after the role changes. Setting the value back to `false` removes Workshop administrator access.
```sh
docker compose -f apps/workshop/docker-compose.yml exec workshop \
pocketbase superuser create you@example.com 'replace-with-a-strong-password' --dir=/pb_data
```
The GitHub OAuth application needs one callback for the Workshop host:
Stopping `pnpm dev:workshop` stops PocketBase and Docusaurus without deleting
`homarr-workshop_pb_data`. To inspect or stop the service separately:
```sh
docker compose -f apps/workshop/docker-compose.yml logs -f workshop
docker compose -f apps/workshop/docker-compose.yml stop workshop
```
## Connect the Homarr application
Use the same URL contract in the repository-root `.env`, then restart Homarr:
```dotenv
HOMARR_WEBSITE_URL=http://127.0.0.1:3003
WORKSHOP_API_URL=http://127.0.0.1:8090
WORKSHOP_WEB_URL=http://127.0.0.1:3003/workshop
WORKSHOP_PUBLIC_ORIGIN=http://127.0.0.1:3003
PB_ALLOWED_ORIGINS=*
```
```sh
pnpm dev
```
`WORKSHOP_API_URL` controls API calls. `WORKSHOP_WEB_URL` controls links from Homarr. `HOMARR_WEBSITE_URL` is the
documentation/site base. All three must be absolute HTTP(S) URLs. `DOCS_BASE_URL` configures a Docusaurus path such as
`/docs-site/`. The old Docusaurus-only `WORKSHOP_URL` variable remains a deprecated alias for one release.
## Optional GitHub OAuth
Create a GitHub OAuth application with this callback:
```text
https://<workshop-host>/api/oauth2-redirect
```
Self-hosted Homarr origins do not need to be registered with GitHub. Keep `PB_ALLOWED_ORIGINS=*` (the default) so localhost and arbitrary self-hosted domains can open the central PocketBase OAuth popup. Set a restricted origin list only if it includes every Homarr origin that should use Workshop sign-in.
Set both credentials in `.env`:
Set `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET` in the repository-root `.env`. Set
`WORKSHOP_PUBLIC_ORIGIN=https://<workshop-host>` so notification emails link to the public Workshop. Configure the sender
and SMTP transport in PocketBase. PocketBase emails the submission author about new comments, emails every current
Workshop administrator about a new report, and emails the author after an administrator deletes their submission. Mail
failures are logged and never reject a comment, report, or deletion.
```dotenv
GITHUB_CLIENT_ID=...
GITHUB_CLIENT_SECRET=...
```
GitHub OAuth settings are synchronized from the environment on every PocketBase startup. Restart the Workshop after
rotating either credential; removing one or both values disables the provider instead of retaining stale credentials.
OAuth settings synchronize on every PocketBase startup. Restart after rotation. A production deployment must never
supply only one credential. `PB_ALLOWED_ORIGINS=*` is appropriate for the central community because arbitrary
self-hosted Homarr origins must open its OAuth popup; a restricted list must include every allowed browser origin.
Run the disposable service integration test from the repository root:
## Promote a Workshop moderator
Sign in once through GitHub so the user record exists. In the PocketBase administration UI, open the `users` collection
and set `isAdmin` to `true`. The user must sign in again. Set it back to `false` to remove moderator access.
Regular API rules cannot set this field. Never describe a Workshop moderator as a Homarr administrator: they are
separate roles in separate services.
## Validation and tests
The browser and shared client validate content with the canonical TypeScript schema. PocketBase independently validates
direct writes, owns schema and revision fields, and rejects stale compare-and-swap updates. Homarr validates the
downloaded content again before installation.
Run the disposable integration suite:
```sh
pnpm test:workshop
pnpm --filter @homarr/workshop typecheck
pnpm --filter @homarr/docs typecheck
```
The test uses a separate Compose project and deletes its named volume on exit. It never writes fixture users or admin
roles into the normal `homarr-workshop_pb_data` volume.
The integration suite uses a separate Compose project and deletes only its disposable volume.
The Workshop frontend validates submissions with `customWidgetImportSchema` from `@homarr/custom-widgets`, and Homarr
validates canonical content again before installation. PocketBase independently enforces publication invariants for
direct API requests, owns schema/revision fields, and rejects stale updates using the submitted expected revision.
The validated `$schema` is also stored as `widgetSchema` for listing compatibility badges; it must match the downloaded
manifest before Homarr enables installation.
PocketBase API rules enforce submission and comment ownership, one vote/report per user and submission, and
administrator-only moderation. Each new submission receives one real author-owned upvote. Reports are private to
administrators and are dismissed by changing their status. PocketBase cascade deletion removes related votes, comments,
and reports when a submission is deleted. Authors and administrators can mark a submission outdated without making it
un-installable.
## Backup and restore
## Production docs preview
Build the documentation and serve it from PocketBase using the same production image layout as the hosted Workshop:
PocketBase data lives in `/pb_data`. Stop writes and copy it into a new, empty host directory for each
filesystem-level backup:
```sh
pnpm docker:docs
docker compose -f apps/workshop/docker-compose.yml stop workshop
docker compose -f apps/workshop/docker-compose.yml cp workshop:/pb_data/. ./workshop-backup
docker compose -f apps/workshop/docker-compose.yml start workshop
```
Open `http://127.0.0.1:3003`. Set `DOCS_EXPOSE_PORT` to use another host port. PocketBase data persists in the
`homarr-workshop_pb_data` named volume.
Point a local Homarr checkout at it with:
Never copy a backup over a non-empty PocketBase volume: files created after the backup could survive and make the
restore inconsistent. For a development restore, first verify that the selected backup contains the database, then
empty the stopped volume before copying it:
```sh
WORKSHOP_API_URL=http://127.0.0.1:3003 pnpm dev
test -f ./workshop-backup/data.db
docker compose -f apps/workshop/docker-compose.yml stop workshop
docker compose -f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint sh workshop \
-c 'find /pb_data -mindepth 1 -maxdepth 1 -exec rm -rf {} +'
docker compose -f apps/workshop/docker-compose.yml cp ./workshop-backup/. workshop:/pb_data
docker compose -f apps/workshop/docker-compose.yml start workshop
curl --fail http://127.0.0.1:8090/api/health
curl --fail 'http://127.0.0.1:8090/api/collections/workshop_listings/records?perPage=1'
```
The production Homarr image reads the same variable when the container starts:
The cleanup command irreversibly empties the selected Compose volume, so confirm the backup path and preserve the
current volume separately before running it. After the HTTP checks, verify sign-in, reports, and a test installation.
Production backups must be versioned, access-controlled, restored into a clean staging volume, and validated before a
release.
## Production image and operations
The production target serves the built documentation from `/pb_public` and PocketBase from the same image. Required
production configuration:
```dotenv
HOMARR_WEBSITE_URL=https://homarr.dev
WORKSHOP_API_URL=https://homarr.dev
WORKSHOP_WEB_URL=https://homarr.dev/workshop
WORKSHOP_PUBLIC_ORIGIN=https://homarr.dev
PB_ALLOWED_ORIGINS=*
WORKSHOP_REQUIRE_OAUTH=true
```
Build and smoke-test the combined image locally:
```sh
docker run -p 7575:7575 -e WORKSHOP_API_URL=http://127.0.0.1:3003 <homarr-image>
docker compose -f apps/workshop/docker-compose.yml --profile docs up --build --detach docs
curl --fail http://127.0.0.1:3003/api/health
curl --fail http://127.0.0.1:3003/
curl --fail http://127.0.0.1:3003/workshop
docker compose -f apps/workshop/docker-compose.yml --profile docs stop docs
```
This command starts the profiled `docs` service from `apps/workshop/docker-compose.yml`. It does not start the development `workshop` service. Stop and remove the preview with:
```sh
docker compose -f apps/workshop/docker-compose.yml --profile docs rm --stop --force docs
```
Normal startup never deletes data. To intentionally recreate the local database, stop the stack first and then run:
Normal `up`, `start`, `stop`, and `down` operations retain the named volume. The following command is an intentional,
irreversible local reset:
```sh
docker compose -f apps/workshop/docker-compose.yml down --volumes
```
PocketBase data lives in `/pb_data`. Docker Compose persists it in the `pb_data` named volume for both the development Workshop service and the production documentation/Workshop service. The image serves the built Homarr documentation and Workshop UI from `/pb_public`.
At startup the container repairs ownership of existing data volumes, then runs PocketBase as its non-root user.
Never run the reset command against production. Release by immutable image digest, back up application and PocketBase
data first, rehearse restore and rollback in staging, and promote the exact tested digest. The Algolia recrawl workflow
remains manual until the external Homarr website host can dispatch it after promotion; publishing the image to GHCR does
not make that image live.
+15 -3
View File
@@ -10,15 +10,17 @@ services:
environment:
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
PORT: ${PB_EXPOSE_PORT:-8090}
HOMARR_WEBSITE_URL: ${HOMARR_WEBSITE_URL:-http://localhost:3003}
WORKSHOP_API_URL: ${WORKSHOP_API_URL:-http://localhost:8090}
WORKSHOP_WEB_URL: ${WORKSHOP_WEB_URL:-http://localhost:3003/workshop}
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
WORKSHOP_PUBLIC_ORIGIN: ${WORKSHOP_PUBLIC_ORIGIN:-http://localhost:8090}
WORKSHOP_REQUIRE_OAUTH: ${WORKSHOP_REQUIRE_OAUTH:-false}
WORKSHOP_PUBLIC_ORIGIN: ${WORKSHOP_PUBLIC_ORIGIN:-http://localhost:3003}
ports:
- "127.0.0.1:${PB_EXPOSE_PORT:-8090}:${PB_EXPOSE_PORT:-8090}"
volumes:
- pb_data:/pb_data
- ./pb_hooks:/pb_hooks:ro
- ./pb_migrations:/pb_migrations:ro
security_opt:
- no-new-privileges:true
@@ -29,11 +31,21 @@ services:
context: ../..
dockerfile: apps/workshop/Dockerfile
target: production
args:
HOMARR_WEBSITE_URL: ${HOMARR_WEBSITE_URL:-http://localhost:3003}
WORKSHOP_API_URL: ${WORKSHOP_API_URL:-http://localhost:3003}
WORKSHOP_WEB_URL: ${WORKSHOP_WEB_URL:-http://localhost:3003/workshop}
DOCS_BASE_URL: ${DOCS_BASE_URL:-/}
environment:
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
PORT: ${DOCS_EXPOSE_PORT:-3003}
HOMARR_WEBSITE_URL: ${HOMARR_WEBSITE_URL:-http://localhost:3003}
WORKSHOP_API_URL: ${WORKSHOP_API_URL:-http://localhost:3003}
WORKSHOP_WEB_URL: ${WORKSHOP_WEB_URL:-http://localhost:3003/workshop}
DOCS_BASE_URL: ${DOCS_BASE_URL:-/}
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
WORKSHOP_REQUIRE_OAUTH: ${WORKSHOP_REQUIRE_OAUTH:-false}
WORKSHOP_PUBLIC_ORIGIN: ${WORKSHOP_PUBLIC_ORIGIN:-http://localhost:3003}
ports:
- "127.0.0.1:${DOCS_EXPOSE_PORT:-3003}:${DOCS_EXPOSE_PORT:-3003}"
+52
View File
@@ -1,11 +1,63 @@
#!/bin/sh
set -eu
normalize_http_url() {
variable_name=$1
value=$2
printf '%s\n' "$value" | awk \
-v variable_name="$variable_name" \
-f "${WORKSHOP_URL_VALIDATOR_PATH:-/usr/local/lib/workshop-url.awk}"
}
if [ "${1:-}" = "--validate-url" ]; then
normalize_http_url "${2:-URL}" "${3:-}"
exit
fi
HOMARR_WEBSITE_URL=$(normalize_http_url HOMARR_WEBSITE_URL "${HOMARR_WEBSITE_URL:-https://homarr.dev}")
WORKSHOP_API_URL=$(normalize_http_url WORKSHOP_API_URL "${WORKSHOP_API_URL:-$HOMARR_WEBSITE_URL}")
WORKSHOP_WEB_URL=$(normalize_http_url WORKSHOP_WEB_URL "${WORKSHOP_WEB_URL:-$HOMARR_WEBSITE_URL/workshop}")
if [ "${WORKSHOP_REQUIRE_PUBLIC_ORIGIN:-false}" = "true" ] && [ -z "${WORKSHOP_PUBLIC_ORIGIN:-}" ]; then
echo "WORKSHOP_PUBLIC_ORIGIN must be set explicitly in production" >&2
exit 1
fi
if [ -n "${WORKSHOP_PUBLIC_ORIGIN:-}" ]; then
WORKSHOP_PUBLIC_ORIGIN=$(normalize_http_url WORKSHOP_PUBLIC_ORIGIN "$WORKSHOP_PUBLIC_ORIGIN")
fi
export HOMARR_WEBSITE_URL WORKSHOP_API_URL WORKSHOP_WEB_URL WORKSHOP_PUBLIC_ORIGIN
if [ "$(id -u)" -eq 0 ]; then
chown -R pocketbase:pocketbase /pb_data
exec su -p -s /bin/sh pocketbase -c 'exec /usr/local/bin/workshop-entrypoint'
fi
if [ -d /pb_public ]; then
docs_base_url=${DOCS_BASE_URL:-/}
case "$docs_base_url" in
/*) ;;
*)
echo "DOCS_BASE_URL must start with '/'" >&2
exit 1
;;
esac
case "$docs_base_url" in
*[!A-Za-z0-9._~/-]* | *".."*)
echo "DOCS_BASE_URL must be a safe URL path without traversal" >&2
exit 1
;;
esac
docs_base_url="/$(printf '%s' "$docs_base_url" | sed 's#^/*##; s#/*$##')"
runtime_directory="/pb_public${docs_base_url%/}"
mkdir -p "$runtime_directory"
cat >"$runtime_directory/workshop-runtime-config.js" <<EOF
globalThis.homarrRuntimeConfig = Object.freeze({
homarrWebsiteUrl: "$HOMARR_WEBSITE_URL",
workshopApiUrl: "$WORKSHOP_API_URL",
workshopWebUrl: "$WORKSHOP_WEB_URL"
});
EOF
fi
exec pocketbase serve \
--http="0.0.0.0:${PORT:-8090}" \
--origins="${PB_ALLOWED_ORIGINS:-*}" \
@@ -26,7 +26,7 @@
</tr>
<tr>
<td style="padding: 36px; color: #18181b; font-size: 15px; line-height: 1.65">
<p style="margin: 0 0 18px">A Workshop administrator removed your submission:</p>
<p style="margin: 0 0 18px">A Workshop moderator removed your submission:</p>
<div style="margin: 0 0 24px; padding: 16px 18px; border-left: 3px solid #dc2626; background: #fef2f2">
<strong>{{submissionTitle}}</strong>
</div>
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,11 @@
const { validatePocketBaseWidget } = require(`${__hooks}/widget-validator.bundle.cjs`);
const validateWidgetManifest = (content) => {
const result = validatePocketBaseWidget(content);
if (!result.success) {
throw new BadRequestError(result.error);
}
return result.content;
};
module.exports = { validateWidgetManifest };
+36 -29
View File
@@ -2,40 +2,12 @@ const CUSTOM_WIDGET_SCHEMA = "homarr-custom-widget-v2";
const CUSTOM_CSS_SCHEMA = "homarr-custom-css-v1";
const MAX_CSS_LENGTH = 16_384;
const MAX_CONTENT_LENGTH = 1_000_000;
const GITHUB_USERNAME_PATTERN = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/;
const rejectRequest = (message) => {
throw new BadRequestError(message);
};
const validateWidgetManifest = (content) => {
let widget;
try {
widget = JSON.parse(content);
} catch {
rejectRequest("Widget content must be valid JSON");
}
if (!widget || Array.isArray(widget) || typeof widget !== "object") rejectRequest("Widget must be a JSON object");
if (widget.$schema !== CUSTOM_WIDGET_SCHEMA) rejectRequest("Widget schema is not supported");
if (typeof widget.name !== "string" || !widget.name.trim() || widget.name.length > 100)
rejectRequest("Widget name is invalid");
if (!widget.sources || Array.isArray(widget.sources) || typeof widget.sources !== "object" || !widget.sources.default)
rejectRequest("Widget must define a default source");
if (Object.keys(widget.sources).length > 8) rejectRequest("Widget has too many sources");
for (const source of Object.values(widget.sources)) {
if (!source || Array.isArray(source) || typeof source !== "object") rejectRequest("Widget source is invalid");
if (typeof source.baseUrl !== "string" || !/^https?:\/\//.test(source.baseUrl))
rejectRequest("Widget source URL is invalid");
if (!["public", "private", "loopback"].includes(source.networkScope))
rejectRequest("Widget source network scope is invalid");
}
if (!widget.requests || Array.isArray(widget.requests) || typeof widget.requests !== "object")
rejectRequest("Widget requests are invalid");
if (!widget.options || Array.isArray(widget.options) || typeof widget.options !== "object")
rejectRequest("Widget options are invalid");
if (typeof widget.template !== "string" || !widget.template.trim()) rejectRequest("Widget template is invalid");
return JSON.stringify(widget);
};
const validateAndNormalizeSubmission = (record) => {
const type = record.getString("type");
const content = record.getString("content");
@@ -49,10 +21,44 @@ const validateAndNormalizeSubmission = (record) => {
return;
}
if (type !== "customWidget") rejectRequest("Submission type is invalid");
const { validateWidgetManifest } = require(`${__hooks}/widget-validator.js`);
record.set("content", validateWidgetManifest(content));
record.set("widgetSchema", CUSTOM_WIDGET_SCHEMA);
};
const normalizedIdentityText = (...values) => {
for (const value of values) {
if (typeof value !== "string") continue;
const normalized = value.replace(/[\u0000-\u001f\u007f]/g, "").trim();
if (normalized) return normalized;
}
return "";
};
const deriveGithubIdentity = (oauthUser, recordId) => {
const rawUser = oauthUser && typeof oauthUser.rawUser === "object" ? oauthUser.rawUser : {};
const candidateUsername = normalizedIdentityText(oauthUser && oauthUser.username, rawUser.login);
const githubUsername =
GITHUB_USERNAME_PATTERN.test(candidateUsername) && !candidateUsername.includes("--") ? candidateUsername : "";
const displayName =
normalizedIdentityText(oauthUser && oauthUser.name, rawUser.name, githubUsername, rawUser.login).slice(0, 100) ||
`GitHub user ${String(recordId || "").slice(0, 8)}`;
const candidateAvatarUrl = normalizedIdentityText(
oauthUser && oauthUser.avatarURL,
oauthUser && oauthUser.avatarUrl,
rawUser.avatar_url,
);
const avatarUrl =
candidateAvatarUrl.length <= 2_048 && /^https:\/\/[^"'\\\s]+$/i.test(candidateAvatarUrl) ? candidateAvatarUrl : "";
return {
displayName,
avatarUrl,
githubUsername,
githubProfileUrl: githubUsername ? `https://github.com/${githubUsername}` : "",
};
};
const escapeHtml = (value) =>
String(value)
.replaceAll("&", "&amp;")
@@ -80,6 +86,7 @@ const sendEmail = (app, recipientEmail, subject, text, html) => {
};
module.exports = {
deriveGithubIdentity,
emailTemplate,
escapeHtml,
rejectRequest,
+109 -10
View File
@@ -1,19 +1,77 @@
/// <reference path="../pb_data/types.d.ts" />
onBootstrap((event) => {
event.next();
const users = event.app.findCollectionByNameOrId("users");
const clientId = String($os.getenv("GITHUB_CLIENT_ID") || "").trim();
const clientSecret = String($os.getenv("GITHUB_CLIENT_SECRET") || "").trim();
const requireOAuth = ["1", "true", "yes", "on"].includes(
String($os.getenv("WORKSHOP_REQUIRE_OAUTH") || "")
.trim()
.toLowerCase(),
);
if (Boolean(clientId) !== Boolean(clientSecret)) {
console.log(JSON.stringify({ event: "workshop_oauth_configuration_rejected", reason: "partial_credentials" }));
throw new Error("GitHub OAuth requires both GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET");
}
const configured = Boolean(clientId && clientSecret);
if (requireOAuth && !configured) {
console.log(JSON.stringify({ event: "workshop_oauth_configuration_rejected", reason: "required_but_disabled" }));
throw new Error("GitHub OAuth is required but no credentials were configured");
}
event.next();
const users = event.app.findCollectionByNameOrId("users");
users.oauth2.enabled = configured;
users.oauth2.providers = configured ? [{ name: "github", clientId, clientSecret }] : [];
event.app.save(users);
console.log(JSON.stringify({ event: "workshop_oauth_synchronized", enabled: configured, required: requireOAuth }));
});
onRecordAuthWithOAuth2Request((event) => {
if (event.providerName !== "github" || !event.oauth2User) {
event.next();
return;
}
const { deriveGithubIdentity } = require(`${__hooks}/workshop-utils.js`);
const identity = deriveGithubIdentity(event.oauth2User, event.record ? event.record.id : event.oauth2User.id);
if (event.record) {
event.record.set("displayName", identity.displayName);
event.record.set("avatar", "");
event.record.set("avatarUrl", identity.avatarUrl);
event.record.set("githubUsername", identity.githubUsername);
event.record.set("githubProfileUrl", identity.githubProfileUrl);
event.app.save(event.record);
} else {
event.createData.displayName = identity.displayName;
event.createData.avatarUrl = identity.avatarUrl;
event.createData.githubUsername = identity.githubUsername;
event.createData.githubProfileUrl = identity.githubProfileUrl;
}
console.log(
JSON.stringify({
event: "workshop_oauth_identity_synchronized",
provider: "github",
recordId: event.record ? event.record.id : null,
newRecord: !event.record,
}),
);
event.next();
}, "users");
onRecordCreateRequest((event) => {
const { validateAndNormalizeSubmission } = require(`${__hooks}/workshop-utils.js`);
validateAndNormalizeSubmission(event.record);
try {
const { validateAndNormalizeSubmission } = require(`${__hooks}/workshop-utils.js`);
validateAndNormalizeSubmission(event.record);
} catch (error) {
console.log(
JSON.stringify({
event: "workshop_submission_rejected",
operation: "create",
type: event.record.getString("type"),
errorName: error && error.name ? error.name : "ValidationError",
}),
);
throw error;
}
event.record.set("revision", 1);
event.record.set("expectedRevision", 0);
event.record.set("changelog", "");
@@ -29,13 +87,49 @@ onRecordUpdateRequest((event) => {
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1) {
rejectRequest("Submission changed since it was read");
}
validateAndNormalizeSubmission(event.record);
try {
validateAndNormalizeSubmission(event.record);
} catch (error) {
console.log(
JSON.stringify({
event: "workshop_submission_rejected",
operation: "update",
submissionId: event.record.id,
type: event.record.getString("type"),
errorName: error && error.name ? error.name : "ValidationError",
}),
);
throw error;
}
event.record.set("expectedRevision", expectedRevision);
event.record.set("revision", currentRevision + 1);
event.next();
}, "submissions");
onRecordCreateRequest((event) => {
const auth = event.requestInfo().auth;
const reporter = event.record.getString("reporter");
const submission = event.record.getString("submission");
if (auth && auth.id === reporter) {
const dismissed = event.app.findRecordsByFilter(
"reports",
"reporter = {:reporter} && submission = {:submission} && status = 'dismissed'",
"",
1,
0,
{ reporter, submission },
);
if (dismissed.length > 0) {
event.app.delete(dismissed[0]);
console.log(
JSON.stringify({
event: "workshop_report_reopened",
reporterId: reporter,
submissionId: submission,
}),
);
}
}
event.record.set("status", "open");
event.next();
}, "reports");
@@ -62,6 +156,7 @@ onRecordAfterCreateSuccess((event) => {
const commenter = event.app.findRecordById("users", event.record.get("author"));
const recipientEmail = recipient.email();
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
const publicWorkshopUrl = ($os.getenv("WORKSHOP_WEB_URL") || `${publicOrigin}/workshop`).replace(/\/$/, "");
if (!recipientEmail || recipient.id === commenter.id || !publicOrigin) {
event.next();
@@ -71,7 +166,7 @@ onRecordAfterCreateSuccess((event) => {
const commenterName = commenter.getString("displayName") || "A community member";
const submissionTitle = submission.getString("title");
const rawExcerpt = event.record.getString("content").slice(0, 280);
const submissionUrl = `${publicOrigin}/workshop/${submission.id}/`;
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
const template = emailTemplate("comment-email.html")
.replaceAll("{{commenterName}}", escapeHtml(commenterName))
.replaceAll("{{submissionTitle}}", escapeHtml(submissionTitle))
@@ -97,6 +192,7 @@ onRecordAfterCreateSuccess((event) => {
const submission = event.app.findRecordById("submissions", event.record.get("submission"));
const reporter = event.app.findRecordById("users", event.record.get("reporter"));
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
const publicWorkshopUrl = ($os.getenv("WORKSHOP_WEB_URL") || `${publicOrigin}/workshop`).replace(/\/$/, "");
const admins = event.app.findRecordsByFilter("users", "isAdmin = true && email != ''", "", 100, 0);
if (!publicOrigin || admins.length === 0) {
@@ -108,8 +204,8 @@ onRecordAfterCreateSuccess((event) => {
const submissionTitle = submission.getString("title");
const category = event.record.getString("category");
const explanation = event.record.getString("explanation");
const adminUrl = `${publicOrigin}/workshop/admin`;
const submissionUrl = `${publicOrigin}/workshop/${submission.id}/`;
const adminUrl = `${publicWorkshopUrl}/admin`;
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
const template = emailTemplate("report-email.html")
.replaceAll("{{reporterName}}", escapeHtml(reporterName))
.replaceAll("{{submissionTitle}}", escapeHtml(submissionTitle))
@@ -155,12 +251,15 @@ onRecordDeleteRequest((event) => {
if (!recipientEmail) return;
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
const workshopUrl = publicOrigin ? `${publicOrigin}/workshop/` : "";
const workshopUrl = ($os.getenv("WORKSHOP_WEB_URL") || (publicOrigin ? `${publicOrigin}/workshop` : "")).replace(
/\/?$/,
"/",
);
const template = emailTemplate("submission-deleted-email.html").replaceAll(
"{{submissionTitle}}",
escapeHtml(submissionTitle),
);
const text = `A Workshop administrator removed your submission “${submissionTitle}”.${
const text = `A Workshop moderator removed your submission “${submissionTitle}”.${
workshopUrl ? `\n\nReturn to Workshop: ${workshopUrl}` : ""
}`;
@@ -1,6 +1,7 @@
/// <reference path="../pb_data/types.d.ts" />
const cloneJson = (value) => JSON.parse(JSON.stringify(value));
const cloneRule = (value) => (value === null ? null : String(value));
migrate(
(app) => {
@@ -31,11 +32,11 @@ migrate(
? {
passwordAuth: cloneJson(users.passwordAuth),
oauth2: cloneJson(users.oauth2),
listRule: users.listRule,
viewRule: users.viewRule,
createRule: users.createRule,
updateRule: users.updateRule,
deleteRule: users.deleteRule,
listRule: cloneRule(users.listRule),
viewRule: cloneRule(users.viewRule),
createRule: cloneRule(users.createRule),
updateRule: cloneRule(users.updateRule),
deleteRule: cloneRule(users.deleteRule),
}
: null,
addedUserFields: [],
@@ -286,6 +287,8 @@ migrate(
if (field) users.fields.removeById(field.id);
}
app.save(users);
} else {
app.delete(users);
}
app.delete(stateCollection);
},
@@ -0,0 +1,54 @@
/// <reference path="../pb_data/types.d.ts" />
const managedLabels = [
"submissions:create",
"submissions:update",
"submissions:delete",
"votes:create",
"votes:update",
"votes:delete",
"comments:create",
"comments:update",
"comments:delete",
"reports:create",
"reports:update",
"reports:delete",
"users:update",
];
const withoutManagedRules = (rules) => rules.filter((rule) => !managedLabels.includes(rule.label));
migrate(
(app) => {
const settings = app.settings();
settings.rateLimits.enabled = true;
settings.rateLimits.rules = [
...withoutManagedRules(settings.rateLimits.rules),
{ label: "submissions:create", audience: "@auth", duration: 60, maxRequests: 10 },
{ label: "submissions:update", audience: "@auth", duration: 60, maxRequests: 30 },
{ label: "submissions:delete", audience: "@auth", duration: 60, maxRequests: 10 },
{ label: "votes:create", audience: "@auth", duration: 10, maxRequests: 20 },
{ label: "votes:update", audience: "@auth", duration: 10, maxRequests: 20 },
{ label: "votes:delete", audience: "@auth", duration: 10, maxRequests: 20 },
{ label: "comments:create", audience: "@auth", duration: 60, maxRequests: 20 },
{ label: "comments:update", audience: "@auth", duration: 60, maxRequests: 20 },
{ label: "comments:delete", audience: "@auth", duration: 60, maxRequests: 20 },
{ label: "reports:create", audience: "@auth", duration: 60, maxRequests: 5 },
{ label: "reports:update", audience: "@auth", duration: 60, maxRequests: 30 },
{ label: "reports:delete", audience: "@auth", duration: 60, maxRequests: 30 },
{ label: "users:update", audience: "@auth", duration: 60, maxRequests: 20 },
];
app.save(settings);
},
(app) => {
const settings = app.settings();
settings.rateLimits.rules = [
...withoutManagedRules(settings.rateLimits.rules),
{ label: "submissions:create", audience: "@auth", duration: 60, maxRequests: 10 },
{ label: "votes:create", audience: "@auth", duration: 10, maxRequests: 20 },
{ label: "comments:create", audience: "@auth", duration: 60, maxRequests: 20 },
{ label: "reports:create", audience: "@auth", duration: 60, maxRequests: 5 },
];
app.save(settings);
},
);
@@ -0,0 +1,66 @@
/// <reference path="../pb_data/types.d.ts" />
const legacyUserUpdateRule = "id = @request.auth.id && @request.body.isAdmin:isset = false";
const legacySubmissionUpdateRule =
"(author = @request.auth.id || @request.auth.isAdmin = true) && @request.body.author:changed = false && @request.body.type:changed = false && @request.body.widgetSchema:changed = false";
const legacyReportUpdateRule =
"@request.auth.isAdmin = true && @request.body.reporter:changed = false && @request.body.submission:changed = false";
const identityFieldsUnchanged = [
"@request.body.email:changed = false",
"@request.body.displayName:changed = false",
"@request.body.avatar:changed = false",
"@request.body.avatarUrl:changed = false",
"@request.body.githubUsername:changed = false",
"@request.body.githubProfileUrl:changed = false",
].join(" && ");
const immutableSubmissionFields = [
"@request.body.author:changed = false",
"@request.body.type:changed = false",
"@request.body.widgetSchema:changed = false",
].join(" && ");
const moderatorSubmissionFieldsUnchanged = [
"@request.body.title:changed = false",
"@request.body.description:changed = false",
"@request.body.content:changed = false",
"@request.body.changelog:changed = false",
"@request.body.screenshots:changed = false",
].join(" && ");
migrate(
(app) => {
const users = app.findCollectionByNameOrId("users");
users.updateRule = `id = @request.auth.id && @request.body.isAdmin:isset = false && ${identityFieldsUnchanged}`;
app.save(users);
const submissions = app.findCollectionByNameOrId("submissions");
submissions.updateRule =
`(author = @request.auth.id && ${immutableSubmissionFields}) || ` +
`(@request.auth.isAdmin = true && author != @request.auth.id && ${immutableSubmissionFields} && ${moderatorSubmissionFieldsUnchanged})`;
app.save(submissions);
const reports = app.findCollectionByNameOrId("reports");
reports.updateRule =
"@request.auth.isAdmin = true && " +
"@request.body.reporter:changed = false && " +
"@request.body.submission:changed = false && " +
"@request.body.category:changed = false && " +
"@request.body.explanation:changed = false";
app.save(reports);
},
(app) => {
const users = app.findCollectionByNameOrId("users");
users.updateRule = legacyUserUpdateRule;
app.save(users);
const submissions = app.findCollectionByNameOrId("submissions");
submissions.updateRule = legacySubmissionUpdateRule;
app.save(submissions);
const reports = app.findCollectionByNameOrId("reports");
reports.updateRule = legacyReportUpdateRule;
app.save(reports);
},
);
+156 -4
View File
@@ -3,16 +3,68 @@ set -eu
WORKSHOP_TEST_PORT=${WORKSHOP_TEST_PORT:-18090}
WORKSHOP_TEST_PROJECT="homarr-workshop-test-$$"
WORKSHOP_ROLLBACK_PORT=${WORKSHOP_ROLLBACK_PORT:-$((WORKSHOP_TEST_PORT + 1))}
WORKSHOP_ROLLBACK_PROJECT="homarr-workshop-rollback-$$"
WORKSHOP_ROLLBACK_SNAPSHOT="/tmp/$WORKSHOP_ROLLBACK_PROJECT.json"
WORKSHOP_MIGRATION_COUNT=$(
node -e "const fs = require('node:fs'); console.log(fs.readdirSync('apps/workshop/pb_migrations').filter((name) => name.endsWith('.js')).length)"
)
ROLLBACK_CONTAINER=""
node apps/workshop/tests/workshop-contracts.mjs
node apps/workshop/tests/workshop-migration.mjs
node apps/workshop/tests/entrypoint-url.mjs
node apps/workshop/tests/workshop-identity.mjs
node apps/workshop/tests/workshop-oauth-hook.mjs
node scripts/build-workshop-validator.mjs
cleanup() {
if [ -n "$ROLLBACK_CONTAINER" ]; then
docker stop "$ROLLBACK_CONTAINER" >/dev/null 2>&1 || true
fi
docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml down --volumes --remove-orphans >/dev/null 2>&1 || true
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml down --volumes --remove-orphans >/dev/null 2>&1 || true
rm -f "$WORKSHOP_ROLLBACK_SNAPSHOT"
}
trap cleanup EXIT
wait_for_workshop() {
port=$1
for attempt in $(seq 1 60); do
if curl --fail --silent "http://127.0.0.1:$port/api/health" >/dev/null; then
return
fi
if [ "$attempt" -eq 60 ]; then
return 1
fi
sleep 1
done
}
start_rollback_server() {
ROLLBACK_CONTAINER=$(
PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm -d --service-ports --no-deps \
--entrypoint pocketbase workshop \
serve --http="0.0.0.0:$WORKSHOP_ROLLBACK_PORT" --origins="*" --dir=/pb_data \
--hooksDir=/tmp --migrationsDir=/tmp --publicDir=/pb_public --automigrate=false
)
wait_for_workshop "$WORKSHOP_ROLLBACK_PORT"
}
stop_rollback_server() {
docker stop "$ROLLBACK_CONTAINER" >/dev/null
ROLLBACK_CONTAINER=""
}
run_rollback_assertion() {
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_ROLLBACK_PORT" \
WORKSHOP_ROLLBACK_SNAPSHOT="$WORKSHOP_ROLLBACK_SNAPSHOT" \
node apps/workshop/tests/workshop-rollback.integration.mjs "$1"
}
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml up --build -d
@@ -34,6 +86,27 @@ docker compose -p "$WORKSHOP_TEST_PROJECT" -f apps/workshop/docker-compose.yml e
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_TEST_PORT" node apps/workshop/tests/workshop.integration.mjs
# PocketBase rate limits use the client IP as the counter key. Run the
# differential corpus in restart-separated shards so the adversarial coverage
# can grow without weakening the production write limits.
for corpus_shard in 0 1; do
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml restart workshop
for attempt in $(seq 1 60); do
if curl --fail --silent "http://127.0.0.1:$WORKSHOP_TEST_PORT/api/health" >/dev/null; then
break
fi
if [ "$attempt" -eq 60 ]; then
exit 1
fi
sleep 1
done
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_TEST_PORT" \
WORKSHOP_CORPUS_SHARD="$corpus_shard" WORKSHOP_CORPUS_SHARD_COUNT=2 pnpm exec tsx \
apps/workshop/tests/workshop-validator-corpus.mts
done
for client_id in workshop-test-client workshop-rotated-client; do
GITHUB_CLIENT_ID="$client_id" GITHUB_CLIENT_SECRET="workshop-test-secret" PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" \
docker compose -p "$WORKSHOP_TEST_PROJECT" -f apps/workshop/docker-compose.yml up -d --force-recreate workshop
@@ -50,11 +123,90 @@ for client_id in workshop-test-client workshop-rotated-client; do
node apps/workshop/tests/oauth-sync.integration.mjs
done
GITHUB_CLIENT_ID="workshop-partial-client" GITHUB_CLIENT_SECRET="" WORKSHOP_REQUIRE_OAUTH=false \
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml up -d --force-recreate workshop
partial_rejected=false
for attempt in $(seq 1 30); do
if PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml logs --no-color workshop | grep -q "partial_credentials"; then
partial_rejected=true
break
fi
sleep 1
done
if [ "$partial_rejected" != true ]; then
echo "Workshop accepted a partial GitHub OAuth configuration"
exit 1
fi
GITHUB_CLIENT_ID="" GITHUB_CLIENT_SECRET="" WORKSHOP_REQUIRE_OAUTH=true PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" \
docker compose -p "$WORKSHOP_TEST_PROJECT" -f apps/workshop/docker-compose.yml \
up -d --force-recreate workshop
required_rejected=false
for attempt in $(seq 1 30); do
if PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml logs --no-color workshop | grep -q "required_but_disabled"; then
required_rejected=true
break
fi
sleep 1
done
if [ "$required_rejected" != true ]; then
echo "Workshop started without OAuth while WORKSHOP_REQUIRE_OAUTH=true"
exit 1
fi
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
-f apps/workshop/docker-compose.yml stop workshop
printf 'y\n' | PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
WORKSHOP_IMAGE_ID=$(
docker compose -p "$WORKSHOP_TEST_PROJECT" -f apps/workshop/docker-compose.yml images -q workshop
)
docker image tag "$WORKSHOP_IMAGE_ID" "$WORKSHOP_ROLLBACK_PROJECT-workshop:latest"
PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm --no-deps --workdir /tmp --entrypoint pocketbase workshop \
superuser create workshop-rollback@example.invalid 'WorkshopRollback123!' --dir=/pb_data \
--hooksDir=/tmp --migrationsDir=/tmp --automigrate=false
start_rollback_server
run_rollback_assertion fresh-prepare
stop_rollback_server
PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint pocketbase workshop \
migrate down 1 --dir=/pb_data --migrationsDir=/pb_migrations
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
migrate up --dir=/pb_data --migrationsDir=/pb_migrations --hooksDir=/tmp --automigrate=false
start_rollback_server
run_rollback_assertion fresh-migrated
stop_rollback_server
printf 'y\n' | PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint pocketbase workshop \
migrate up --dir=/pb_data --migrationsDir=/pb_migrations
migrate down "$WORKSHOP_MIGRATION_COUNT" --dir=/pb_data --migrationsDir=/pb_migrations \
--hooksDir=/tmp --automigrate=false
start_rollback_server
run_rollback_assertion fresh-restored
run_rollback_assertion prepare
stop_rollback_server
PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint pocketbase workshop \
migrate up --dir=/pb_data --migrationsDir=/pb_migrations --hooksDir=/tmp --automigrate=false
start_rollback_server
run_rollback_assertion migrated
stop_rollback_server
printf 'y\n' | PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint pocketbase workshop \
migrate down "$WORKSHOP_MIGRATION_COUNT" --dir=/pb_data --migrationsDir=/pb_migrations \
--hooksDir=/tmp --automigrate=false
start_rollback_server
run_rollback_assertion restored
stop_rollback_server
PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
-f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint pocketbase workshop \
migrate up --dir=/pb_data --migrationsDir=/pb_migrations --hooksDir=/tmp --automigrate=false
start_rollback_server
run_rollback_assertion migrated
stop_rollback_server
+49
View File
@@ -0,0 +1,49 @@
import { spawnSync } from "node:child_process";
import { resolve } from "node:path";
const entrypoint = resolve("apps/workshop/entrypoint.sh");
const validator = resolve("apps/workshop/workshop-url.awk");
const validate = (value) =>
spawnSync("sh", [entrypoint, "--validate-url", "TEST_URL", value], {
encoding: "utf8",
env: { ...process.env, WORKSHOP_URL_VALIDATOR_PATH: validator },
});
for (const [value, expected] of [
["http://127.0.0.1:8090/", "http://127.0.0.1:8090"],
["https://example.com/docs/", "https://example.com/docs"],
["https://example.com:0/", "https://example.com:0"],
["https://[::1]:8090/workshop/", "https://[::1]:8090/workshop"],
]) {
const result = validate(value);
if (result.status !== 0 || result.stdout.trim() !== expected) {
throw new Error(`Expected valid runtime URL ${value}: ${result.stderr || result.stdout}`);
}
}
for (const value of [
"",
"http://",
"http:///docs",
"https://:",
"https://example.com:65536",
"https://::1",
"https://[:::1]",
"https://1.2.3.4.5",
"http://09.0.0.1",
"http://099.0.0.1",
"http://[::ffff:192.168.001.001]",
"http://[::ffff:192.168.1.01]",
"http://[fe80::1%25eth0]",
"https://user:password@example.com",
"https://example.com/workshop?token=secret",
"https://example.com/workshop#fragment",
"https://example.com/\tworkshop",
"https://example.com/\nworkshop",
]) {
const result = validate(value);
if (result.status === 0) throw new Error(`Expected invalid runtime URL to be rejected: ${JSON.stringify(value)}`);
}
console.log("Workshop runtime URL validation passed");
@@ -10,7 +10,13 @@ await access(resolve("packages/workshop", clientExport));
const hook = await read("apps/workshop/pb_hooks/workshop.pb.js");
const hookUtils = await read("apps/workshop/pb_hooks/workshop-utils.js");
const widgetValidator = await read("apps/workshop/pb_hooks/widget-validator.js");
const canonicalWidgetValidator = await read("packages/workshop/src/pocketbase-validator.ts");
const dockerfile = await read("apps/workshop/Dockerfile");
const schema = await read("packages/workshop/src/schema.ts");
const workshopApp = await read("apps/docs/src/components/workshop/WorkshopApp.tsx");
const workshopAdmin = await read("apps/docs/src/components/workshop/WorkshopAdmin.tsx");
const workshopDetail = await read("apps/docs/src/components/workshop/DetailPage.tsx");
const constantValue = (source, name) => {
const match = source.match(new RegExp(`(?:export )?const ${name} = ([\\d_]+)`));
if (!match?.[1]) throw new Error(`Workshop limit ${name} is missing or is not a numeric literal`);
@@ -28,24 +34,113 @@ if (!hook.includes("require(`${__hooks}/workshop-utils.js`)")) {
if (!hook.includes("onBootstrap") || !hook.includes("users.oauth2.providers = configured")) {
throw new Error("Workshop OAuth settings must be synchronized at every bootstrap");
}
if (!hook.includes("WORKSHOP_REQUIRE_OAUTH") || !hook.includes("partial_credentials")) {
throw new Error("Workshop OAuth bootstrap must reject partial and required-but-disabled configurations");
}
if (
!hook.includes("onRecordAuthWithOAuth2Request") ||
!hook.includes("deriveGithubIdentity") ||
!hook.includes("event.oauth2User") ||
hook.includes("event.oAuth2User") ||
!hook.includes("event.createData.displayName = identity.displayName") ||
!hook.includes('event.record.set("displayName", identity.displayName)') ||
!hook.includes("workshop_oauth_identity_synchronized")
) {
throw new Error("Workshop GitHub identity must be synchronized for first and returning OAuth logins");
}
if (!hook.includes("workshop_report_reopened") || !hook.includes("status = 'dismissed'")) {
throw new Error("Workshop must permit a fresh report after a previous report was dismissed");
}
if (
!widgetValidator.includes("widget-validator.bundle.cjs") ||
!canonicalWidgetValidator.includes("customWidgetDefinitionSchema.safeParse")
) {
throw new Error("Workshop direct writes must use the bundled canonical Custom Widget validator");
}
await access(resolve("apps/workshop/pb_hooks/widget-validator.bundle.cjs"));
if (!dockerfile.includes("WORKSHOP_REQUIRE_PUBLIC_ORIGIN=true")) {
throw new Error("The production Workshop image must require an explicit public origin");
}
if (!dockerfile.includes("COPY --from=dependencies") || !dockerfile.includes("widget-validator.bundle.cjs")) {
throw new Error("The production Workshop image must copy the freshly generated canonical validator");
}
if (hook.includes('findAllRecords("users")') || !hook.includes('findRecordsByFilter("users"')) {
throw new Error("Workshop report notifications must use a filtered, bounded administrator query");
}
if (!hook.includes("WORKSHOP_WEB_URL")) {
throw new Error("PocketBase-generated Workshop links must use the configured public web URL");
}
for (const [name, source] of [
["Workshop listing", workshopApp],
["Workshop moderation", workshopAdmin],
["Workshop detail", workshopDetail],
]) {
if (/<a\b[^>]*\bhref=["']\/workshop/u.test(source)) {
throw new Error(`${name} must use base-path-aware Docusaurus links`);
}
if (/window\.location(?:\.href)?\s*=\s*["']\/workshop/u.test(source)) {
throw new Error(`${name} must use a base-path-aware redirect`);
}
}
const migration = await read("apps/workshop/pb_migrations/1784240000_workshop_widgets.js");
for (const required of [
"workshop_migration_state",
"addedUserFields",
"cloneRule(users.listRule)",
"CREATE TRIGGER submissions_revision_cas",
"NEW.expectedRevision != OLD.revision",
"state.rateLimits.enabled",
"users.passwordAuth = state.users.passwordAuth",
"users.oauth2 = state.users.oauth2",
"app.delete(users)",
]) {
if (!migration.includes(required)) throw new Error(`Workshop rollback is missing state restoration: ${required}`);
}
const hardeningMigration = await read("apps/workshop/pb_migrations/1784240001_workshop_write_rate_limits.js");
for (const operation of ["create", "update", "delete"]) {
for (const collection of ["submissions", "votes", "comments", "reports"]) {
const label = `${collection}:${operation}`;
if (!hardeningMigration.includes(label)) throw new Error(`Workshop write rate limit is missing: ${label}`);
}
}
if (!hardeningMigration.includes("users:update")) throw new Error("Workshop user file updates must be rate limited");
const accessHardeningMigration = await read("apps/workshop/pb_migrations/1784240002_workshop_access_hardening.js");
for (const protectedField of [
"email:changed",
"displayName:changed",
"avatar:changed",
"avatarUrl:changed",
"githubUsername:changed",
"githubProfileUrl:changed",
]) {
if (!accessHardeningMigration.includes(protectedField)) {
throw new Error(`Workshop OAuth identity field remains caller-controlled: ${protectedField}`);
}
}
for (const protectedField of [
"title:changed",
"description:changed",
"content:changed",
"changelog:changed",
"screenshots:changed",
]) {
if (!accessHardeningMigration.includes(protectedField)) {
throw new Error(`Workshop moderators can still rewrite submissions: ${protectedField}`);
}
}
for (const protectedField of ["category:changed", "explanation:changed"]) {
if (!accessHardeningMigration.includes(protectedField)) {
throw new Error(`Workshop moderators can still rewrite reports: ${protectedField}`);
}
}
const workflow = await read(".github/workflows/workshop.yml");
if (/\n\s+paths:/u.test(workflow)) throw new Error("Workshop workflow must not filter out Docker build inputs");
if (!workflow.includes("DOCS_BASE_URL=/docs-site/") || !workflow.includes("workshop-base-path-smoke")) {
throw new Error("Workshop CI must exercise a non-root documentation deployment");
}
console.log("Workshop static contracts passed");
+63
View File
@@ -0,0 +1,63 @@
import { createRequire } from "node:module";
const require = createRequire(import.meta.url);
const { deriveGithubIdentity } = require("../pb_hooks/workshop-utils.js");
const identity = deriveGithubIdentity(
{
name: " Octo Cat ",
username: "octocat",
avatarURL: "https://avatars.githubusercontent.com/u/1?v=4",
rawUser: {},
},
"record123456",
);
if (
identity.displayName !== "Octo Cat" ||
identity.githubUsername !== "octocat" ||
identity.githubProfileUrl !== "https://github.com/octocat" ||
identity.avatarUrl !== "https://avatars.githubusercontent.com/u/1?v=4"
) {
throw new Error(`Trusted GitHub identity was not normalized: ${JSON.stringify(identity)}`);
}
const rawFallback = deriveGithubIdentity(
{
name: "",
username: "",
avatarURL: "",
rawUser: {
name: "\nRaw User\u0000",
login: "raw-user",
avatar_url: "https://avatars.githubusercontent.com/u/2",
},
},
"record123456",
);
if (
rawFallback.displayName !== "Raw User" ||
rawFallback.githubUsername !== "raw-user" ||
rawFallback.githubProfileUrl !== "https://github.com/raw-user"
) {
throw new Error(`Raw GitHub identity fallback was not normalized: ${JSON.stringify(rawFallback)}`);
}
const rejected = deriveGithubIdentity(
{
name: "\n",
username: "not/a/github-user",
avatarURL: "javascript:alert(1)",
rawUser: {},
},
"record123456",
);
if (
rejected.displayName !== "GitHub user record12" ||
rejected.githubUsername !== "" ||
rejected.githubProfileUrl !== "" ||
rejected.avatarUrl !== ""
) {
throw new Error(`Invalid provider identity fields were retained: ${JSON.stringify(rejected)}`);
}
console.log("Workshop OAuth identity normalization passed");
+11 -7
View File
@@ -50,7 +50,7 @@ class Record {
const original = {
passwordAuth: { enabled: true, identityFields: ["email"] },
oauth2: { enabled: true, providers: [{ name: "original", clientId: "before" }] },
oauth2: { enabled: true, providers: [{ name: "original", clientId: "before", clientSecret: "before-secret" }] },
rules: {
listRule: "original-list",
viewRule: "original-view",
@@ -157,13 +157,17 @@ rawQueries.length = 0;
settings.rateLimits = structuredClone(original.rateLimits);
migration.up(app);
const bootstrappedUsers = collections.get("users");
if (!bootstrappedUsers) throw new Error("Fresh migration did not create the users collection");
if (!collections.has("users")) throw new Error("Fresh migration did not create the users collection");
migration.down(app);
if (collections.get("users") !== bootstrappedUsers) {
throw new Error("Fresh rollback removed the users collection required by the bootstrap hook");
}
for (const name of ["workshop_migration_state", "workshop_listings", "reports", "comments", "votes", "submissions"]) {
for (const name of [
"users",
"workshop_migration_state",
"workshop_listings",
"reports",
"comments",
"votes",
"submissions",
]) {
if (collections.has(name)) throw new Error(`Fresh rollback left collection ${name}`);
}
if (JSON.stringify(settings.rateLimits) !== JSON.stringify(original.rateLimits)) {
+111
View File
@@ -0,0 +1,111 @@
import { createRequire } from "node:module";
import { readFile } from "node:fs/promises";
import vm from "node:vm";
const nodeRequire = createRequire(import.meta.url);
const workshopUtils = nodeRequire("../pb_hooks/workshop-utils.js");
const hookSource = await readFile("apps/workshop/pb_hooks/workshop.pb.js", "utf8");
let oauthHook;
const ignoreHook = () => {};
vm.runInNewContext(hookSource, {
__hooks: "/pb_hooks",
console: { log: () => {} },
onBootstrap: ignoreHook,
onRecordAfterCreateSuccess: ignoreHook,
onRecordCreateRequest: ignoreHook,
onRecordDeleteRequest: ignoreHook,
onRecordUpdateRequest: ignoreHook,
onRecordAuthWithOAuth2Request: (handler, collection) => {
if (collection !== "users") throw new Error(`OAuth hook targets unexpected collection: ${collection}`);
oauthHook = handler;
},
require: (specifier) => {
if (specifier !== "/pb_hooks/workshop-utils.js") {
throw new Error(`OAuth hook loaded unexpected dependency: ${specifier}`);
}
return workshopUtils;
},
});
if (typeof oauthHook !== "function") throw new Error("Workshop OAuth request hook was not registered");
const oauth2User = {
id: "provider-user-123",
name: "Octo Cat",
username: "octocat",
avatarURL: "https://avatars.githubusercontent.com/u/1?v=4",
rawUser: {},
};
const createData = {};
let createNextCalls = 0;
oauthHook({
app: { save: () => Promise.reject(new Error("New OAuth users must not be saved before PocketBase creates them")) },
createData,
next: () => {
createNextCalls += 1;
},
oauth2User,
providerName: "github",
record: null,
});
if (
createNextCalls !== 1 ||
createData.displayName !== "Octo Cat" ||
createData.avatarUrl !== "https://avatars.githubusercontent.com/u/1?v=4" ||
createData.githubUsername !== "octocat" ||
createData.githubProfileUrl !== "https://github.com/octocat"
) {
throw new Error(`First GitHub OAuth login did not synchronize trusted identity: ${JSON.stringify(createData)}`);
}
const returningValues = new Map();
const returningRecord = {
id: "returning-user-123",
set: (name, value) => returningValues.set(name, value),
};
let savedRecord;
let returningNextCalls = 0;
oauthHook({
app: {
save: (record) => {
savedRecord = record;
},
},
createData: {},
next: () => {
returningNextCalls += 1;
},
oauth2User,
providerName: "github",
record: returningRecord,
});
if (
savedRecord !== returningRecord ||
returningNextCalls !== 1 ||
returningValues.get("displayName") !== "Octo Cat" ||
returningValues.get("avatar") !== "" ||
returningValues.get("avatarUrl") !== "https://avatars.githubusercontent.com/u/1?v=4" ||
returningValues.get("githubUsername") !== "octocat" ||
returningValues.get("githubProfileUrl") !== "https://github.com/octocat"
) {
throw new Error("Returning GitHub OAuth login did not refresh trusted identity");
}
const ignoredCreateData = {};
let ignoredNextCalls = 0;
oauthHook({
app: {},
createData: ignoredCreateData,
next: () => {
ignoredNextCalls += 1;
},
oauth2User,
providerName: "oidc",
record: null,
});
if (ignoredNextCalls !== 1 || Object.keys(ignoredCreateData).length !== 0) {
throw new Error("Non-GitHub OAuth providers must pass through without GitHub identity synchronization");
}
console.log("Workshop OAuth hook contract passed");
@@ -0,0 +1,317 @@
import assert from "node:assert/strict";
import { readFile, writeFile } from "node:fs/promises";
const baseUrl = process.env.WORKSHOP_TEST_URL;
const snapshotPath = process.env.WORKSHOP_ROLLBACK_SNAPSHOT;
const phase = process.argv[2];
if (!baseUrl) throw new Error("WORKSHOP_TEST_URL is required");
if (!snapshotPath) throw new Error("WORKSHOP_ROLLBACK_SNAPSHOT is required");
if (!["fresh-prepare", "fresh-migrated", "fresh-restored", "prepare", "migrated", "restored"].includes(phase)) {
throw new Error("Unknown Workshop rollback test phase");
}
const superuser = {
email: "workshop-rollback@example.invalid",
password: "WorkshopRollback123!",
};
const baselineUser = {
email: "rollback-user@example.invalid",
password: "WorkshopRollbackUser123!",
note: "retained across the Workshop migration chain",
};
const baselineRateLimitLabel = "rollback_sentinel:create";
const workshopCollections = [
"workshop_migration_state",
"submissions",
"votes",
"comments",
"reports",
"workshop_listings",
];
const workshopUserFields = ["displayName", "avatarUrl", "avatar", "githubUsername", "githubProfileUrl", "isAdmin"];
const request = async (path, init = {}) => {
const response = await fetch(`${baseUrl}${path}`, {
...init,
headers: { "content-type": "application/json", ...init.headers },
});
const body = await response.json().catch(() => null);
if (!response.ok) throw new Error(`${response.status} ${path}: ${JSON.stringify(body)}`);
return body;
};
const auth = await request("/api/collections/_superusers/auth-with-password", {
method: "POST",
body: JSON.stringify({ identity: superuser.email, password: superuser.password }),
});
const rootHeaders = { authorization: `Bearer ${auth.token}` };
const collectionList = async () => {
const result = await request("/api/collections?perPage=200", { headers: rootHeaders });
return new Map(result.items.map((collection) => [collection.name, collection]));
};
const collection = (name) => request(`/api/collections/${name}`, { headers: rootHeaders });
const settings = () => request("/api/settings", { headers: rootHeaders });
const records = (name) =>
request(`/api/collections/${name}/records?perPage=200`, {
headers: rootHeaders,
});
const normalized = (value) => JSON.parse(JSON.stringify(value));
const publicOauthConfig = (oauth2) => {
const value = normalized(oauth2);
value.providers = value.providers?.map(({ clientSecret: _clientSecret, ...provider }) => provider);
return value;
};
const userConfig = (users) => ({
rules: {
listRule: users.listRule,
viewRule: users.viewRule,
createRule: users.createRule,
updateRule: users.updateRule,
deleteRule: users.deleteRule,
},
passwordAuth: normalized(users.passwordAuth),
oauth2: publicOauthConfig(users.oauth2),
fieldNames: users.fields.map((field) => field.name).toSorted(),
});
const readSnapshot = async () => JSON.parse(await readFile(snapshotPath, "utf8"));
const assertManagedRateLimits = (currentSettings) => {
assert.equal(currentSettings.rateLimits?.enabled, true, "Workshop migration did not enable rate limits");
const rateLimitLabels = new Set(currentSettings.rateLimits?.rules?.map((rule) => rule.label));
for (const operation of ["create", "update", "delete"]) {
for (const name of ["submissions", "votes", "comments", "reports"]) {
assert.ok(rateLimitLabels.has(`${name}:${operation}`), `Missing migrated rate limit ${name}:${operation}`);
}
}
assert.ok(rateLimitLabels.has("users:update"), "Missing migrated users:update rate limit");
return rateLimitLabels;
};
const assertBaselineData = async () => {
const userRecords = await records("users");
const retainedUser = userRecords.items.find((record) => record.email === baselineUser.email);
assert.equal(retainedUser?.baselineNote, baselineUser.note, "Baseline user data was not retained");
const sentinelRecords = await records("rollback_sentinel");
assert.equal(sentinelRecords.items.length, 1, "Unrelated baseline record count changed");
assert.equal(sentinelRecords.items[0]?.value, "keep-me", "Unrelated baseline data changed");
};
const assertMigrated = async () => {
const before = await readSnapshot();
const collections = await collectionList();
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(collections.has(name), `Migrated database is missing collection ${name}`);
}
const users = await collection("users");
assert.equal(users.passwordAuth?.enabled, false, "Workshop migration must disable password authentication");
assert.deepEqual(
publicOauthConfig(users.oauth2),
before.users.oauth2,
"Workshop migration changed existing OAuth settings",
);
for (const name of workshopUserFields) {
assert.ok(
users.fields.some((field) => field.name === name),
`Workshop user field ${name} is missing`,
);
}
assert.match(
users.updateRule ?? "",
/githubProfileUrl:changed = false/u,
"OAuth identity update rule is not hardened",
);
const currentSettings = await settings();
const rateLimitLabels = assertManagedRateLimits(currentSettings);
assert.ok(rateLimitLabels.has(baselineRateLimitLabel), "Workshop migration removed an unrelated rate-limit rule");
const stateRecords = await records("workshop_migration_state");
assert.equal(stateRecords.items.length, 1, "Workshop migration state snapshot is missing");
const migrationState = JSON.parse(stateRecords.items[0].snapshot);
assert.equal(migrationState.usersExisted, true, "Workshop migration did not recognize the existing users collection");
assert.deepEqual(migrationState.users.passwordAuth, before.users.passwordAuth);
assert.deepEqual(publicOauthConfig(migrationState.users.oauth2), before.users.oauth2);
assert.deepEqual(
{
listRule: migrationState.users.listRule,
viewRule: migrationState.users.viewRule,
createRule: migrationState.users.createRule,
updateRule: migrationState.users.updateRule,
deleteRule: migrationState.users.deleteRule,
},
before.users.rules,
"Workshop migration state did not snapshot the original user rules",
);
assert.equal(
migrationState.users.oauth2.providers.find((provider) => provider.name === "github")?.clientSecret,
"rollback-baseline-secret",
"Workshop migration state did not retain the OAuth secret required for rollback",
);
assert.deepEqual(migrationState.rateLimits, before.rateLimits);
await assertBaselineData();
};
if (phase === "fresh-prepare") {
let collections = await collectionList();
if (collections.has("users")) {
await request("/api/collections/users", { method: "DELETE", headers: rootHeaders });
collections = await collectionList();
}
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(!collections.has(name), `Fresh database unexpectedly contains collection ${name}`);
}
const currentSettings = await settings();
await writeFile(snapshotPath, JSON.stringify({ freshRateLimits: normalized(currentSettings.rateLimits) }), {
mode: 0o600,
});
console.log("Workshop fresh rollback baseline captured");
} else if (phase === "fresh-migrated") {
const collections = await collectionList();
for (const name of [...workshopCollections, "users"]) {
assert.ok(collections.has(name), `Fresh migration is missing collection ${name}`);
}
const users = await collection("users");
for (const name of workshopUserFields) {
assert.ok(
users.fields.some((field) => field.name === name),
`Fresh migration is missing user field ${name}`,
);
}
assertManagedRateLimits(await settings());
const stateRecords = await records("workshop_migration_state");
assert.equal(stateRecords.items.length, 1, "Fresh migration state snapshot is missing");
const migrationState = JSON.parse(stateRecords.items[0].snapshot);
assert.equal(migrationState.usersExisted, false, "Fresh migration incorrectly recorded an existing users collection");
assert.equal(migrationState.users, null, "Fresh migration retained nonexistent user settings");
console.log("Workshop fresh migration chain verified");
} else if (phase === "fresh-restored") {
const before = await readSnapshot();
const collections = await collectionList();
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(!collections.has(name), `Fresh rollback left collection ${name}`);
}
assert.ok(collections.has("_superusers"), "Fresh rollback removed PocketBase superuser data");
const currentSettings = await settings();
assert.deepEqual(
normalized(currentSettings.rateLimits),
before.freshRateLimits,
"Fresh rollback did not restore the original rate-limit settings",
);
console.log("Workshop fresh rollback state verified");
} else if (phase === "prepare") {
const collections = await collectionList();
for (const name of [...workshopCollections, "users", "rollback_sentinel"]) {
assert.ok(!collections.has(name), `Fresh rollback fixture unexpectedly contains collection ${name}`);
}
await request("/api/collections", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
type: "auth",
name: "users",
listRule: "@request.auth.id != ''",
viewRule: "id = @request.auth.id",
createRule: "@request.body.email != ''",
updateRule: "id = @request.auth.id",
deleteRule: "id = @request.auth.id",
passwordAuth: { enabled: true, identityFields: ["email"] },
oauth2: {
enabled: true,
providers: [
{
name: "github",
clientId: "rollback-baseline-client",
clientSecret: "rollback-baseline-secret",
},
],
},
fields: [{ type: "text", name: "baselineNote", max: 200 }],
}),
});
await request("/api/collections", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
type: "base",
name: "rollback_sentinel",
listRule: null,
viewRule: null,
createRule: null,
updateRule: null,
deleteRule: null,
fields: [{ type: "text", name: "value", required: true, max: 100 }],
}),
});
await request("/api/settings", {
method: "PATCH",
headers: rootHeaders,
body: JSON.stringify({
rateLimits: {
enabled: false,
rules: [{ label: baselineRateLimitLabel, audience: "", duration: 17, maxRequests: 23 }],
},
}),
});
await request("/api/collections/users/records", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
email: baselineUser.email,
emailVisibility: false,
verified: true,
password: baselineUser.password,
passwordConfirm: baselineUser.password,
baselineNote: baselineUser.note,
}),
});
await request("/api/collections/rollback_sentinel/records", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({ value: "keep-me" }),
});
const users = await collection("users");
const currentSettings = await settings();
assert.equal(users.passwordAuth?.enabled, true);
assert.equal(users.oauth2?.enabled, true);
assert.ok(users.oauth2?.providers?.some((provider) => provider.name === "github"));
assert.equal(currentSettings.rateLimits?.enabled, false);
assert.deepEqual(
currentSettings.rateLimits?.rules?.map((rule) => rule.label),
[baselineRateLimitLabel],
);
await assertBaselineData();
await writeFile(
snapshotPath,
JSON.stringify({ users: userConfig(users), rateLimits: normalized(currentSettings.rateLimits) }),
{ mode: 0o600 },
);
console.log("Workshop rollback baseline prepared");
} else if (phase === "migrated") {
await assertMigrated();
console.log("Workshop full migration chain verified");
} else {
const before = await readSnapshot();
const collections = await collectionList();
for (const name of workshopCollections) {
assert.ok(!collections.has(name), `Rollback left Workshop collection ${name}`);
}
for (const name of ["users", "rollback_sentinel"]) {
assert.ok(collections.has(name), `Rollback removed baseline collection ${name}`);
}
const users = await collection("users");
assert.deepEqual(userConfig(users), before.users, "Rollback did not restore user rules, fields, password, or OAuth");
const currentSettings = await settings();
assert.deepEqual(
normalized(currentSettings.rateLimits),
before.rateLimits,
"Rollback did not restore the original rate-limit settings",
);
await assertBaselineData();
console.log("Workshop full rollback state verified");
}
@@ -0,0 +1,332 @@
import { BUNDLED_CUSTOM_WIDGETS, customWidgetDefinitionSchema } from "@homarr/custom-widgets/core";
const baseUrl = process.env.WORKSHOP_TEST_URL ?? "http://127.0.0.1:18090";
const password = "WorkshopCorpus123!";
const shard = Number(process.env.WORKSHOP_CORPUS_SHARD ?? "0");
const shardCount = Number(process.env.WORKSHOP_CORPUS_SHARD_COUNT ?? "1");
if (!Number.isInteger(shard) || !Number.isInteger(shardCount) || shard < 0 || shardCount < 1 || shard >= shardCount) {
throw new Error("Validator corpus shard configuration is invalid");
}
const email = shardCount === 1 ? "workshop-corpus@example.invalid" : `workshop-corpus-${shard}@example.invalid`;
async function request(path: string, init: RequestInit = {}) {
const response = await fetch(`${baseUrl}${path}`, {
...init,
headers: { "content-type": "application/json", ...init.headers },
});
const body = (await response.json().catch(() => null)) as Record<string, unknown> | null;
return { response, body };
}
const root = await request("/api/collections/_superusers/auth-with-password", {
method: "POST",
body: JSON.stringify({ identity: "workshop-test@example.invalid", password: "WorkshopLocalTest123!" }),
});
if (!root.response.ok || typeof root.body?.token !== "string") throw new Error("Corpus superuser login failed");
const rootHeaders = { authorization: `Bearer ${root.body.token}` };
const createdUser = await request("/api/collections/users/records", {
method: "POST",
headers: rootHeaders,
body: JSON.stringify({
email,
emailVisibility: false,
verified: true,
password,
passwordConfirm: password,
displayName: "Validator Corpus",
}),
});
if (!createdUser.response.ok || typeof createdUser.body?.id !== "string") {
throw new Error(`Corpus user creation failed: ${JSON.stringify(createdUser.body)}`);
}
const userId = createdUser.body.id;
const signedIn = await request("/api/collections/users/auth-with-password", {
method: "POST",
body: JSON.stringify({ identity: email, password }),
});
if (!signedIn.response.ok || typeof signedIn.body?.token !== "string") throw new Error("Corpus user login failed");
const userHeaders = { authorization: `Bearer ${signedIn.body.token}` };
const bundled = BUNDLED_CUSTOM_WIDGETS.map(({ id, widget }) => ({
name: `bundled:${id}`,
widget: structuredClone(widget) as Record<string, unknown>,
}));
const base = structuredClone(bundled[0]?.widget);
if (!base) throw new Error("Bundled Custom Widget corpus is empty");
const asRecord = (value: unknown) => value as Record<string, unknown>;
const withMutation = (mutate: (widget: Record<string, unknown>) => void) => {
const widget = structuredClone(base) as Record<string, unknown>;
mutate(widget);
return widget;
};
bundled.push(
{
name: "source:valid-port-zero",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://example.com:0";
}),
},
{
name: "source:valid-trailing-dot",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://example.com.";
}),
},
{
name: "source:valid-idn",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://münich.example";
}),
},
{
name: "url:valid-ipv6-and-port",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://[2001:db8::1]:65535";
widget.iconUrl = "https://[2001:db8::1]:65535/icon.svg";
}),
},
{
name: "request:valid-harmless-key-metadata",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.path = "/api/status?key=status&auth=none";
requestDefinition.headers = {
Accept: "application/json",
"X-Api-Version": "2026-07",
"X-Feature-Key": "dashboard-layout",
};
}),
},
);
const adversarial = [
{
name: "manifest:unknown-secret-field",
widget: withMutation((widget) => {
widget.secrets = [{ value: "must-never-be-published" }];
}),
},
{
name: "source:embedded-credentials",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://user:password@example.com";
}),
},
{
name: "source:invalid-numeric-host",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://1.2.3.4.5";
}),
},
{
name: "source:invalid-numeric-leading-zero",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://09.0.0.1";
}),
},
{
name: "source:ambiguous-numeric-shorthand",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://127.1";
}),
},
{
name: "source:ambiguous-hexadecimal-ipv4",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://0x7f000001";
}),
},
{
name: "source:percent-encoded-host",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://%65xample.com";
}),
},
{
name: "source:backslash-normalization",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://example.com\\@attacker.invalid";
}),
},
{
name: "source:invalid-ipv6-zone",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://[fe80::1%25eth0]";
}),
},
{
name: "source:invalid-ipv6-embedded-ipv4",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "http://[::ffff:192.168.001.001]";
}),
},
{
name: "source:invalid-a-label",
widget: withMutation((widget) => {
asRecord(asRecord(widget.sources).default).baseUrl = "https://xn--a.example";
}),
},
{
name: "request:reserved-header",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.headers = { Authorization: "must-never-be-published" };
}),
},
{
name: "request:credential-in-body",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.body = { access_token: "must-never-be-published" };
}),
},
{
name: "request:credential-in-path-query",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.path = "/api/status?credential=Bearer-sk-secret-123456";
}),
},
{
name: "request:credential-in-custom-header",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.headers = { "X-Auth": "Bearer sk-secret-123456" };
}),
},
{
name: "request:common-token-in-header-value",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.headers = { "X-Service": "ghp_abcdefghijklmnopqrstuvwxyz123456" };
}),
},
{
name: "request:automatic-delete-query",
widget: withMutation((widget) => {
const requestDefinition = asRecord(Object.values(asRecord(widget.requests))[0]);
requestDefinition.kind = "query";
requestDefinition.trigger = "load";
requestDefinition.method = "DELETE";
}),
},
{
name: "icon:credential-query",
widget: withMutation((widget) => {
widget.iconUrl = "https://example.com/icon.png?clientSecret=must-never-be-published";
}),
},
{
name: "icon:unicode-mapped-numeric-host",
widget: withMutation((widget) => {
widget.iconUrl = "https://127.0.0.1/icon.png";
}),
},
{
name: "option:invalid-default",
widget: withMutation((widget) => {
asRecord(widget.options).invalid = { label: "Invalid", control: "number", default: "not-a-number" };
}),
},
{
name: "template:incompatible-request",
widget: withMutation((widget) => {
const requestId = Object.keys(asRecord(widget.requests))[0];
widget.template = `${String(widget.template)}<ActionButton requestId="${requestId}">Unsafe</ActionButton>`;
}),
},
{
name: "template:literal-credential",
widget: withMutation((widget) => {
widget.template = "<Text>Authorization: Bearer must-never-be-published</Text>";
}),
},
{
name: "template:blocked-script",
widget: withMutation((widget) => {
widget.template = "<script>unsafe()</script>";
}),
},
{
name: "template:unknown-component",
widget: withMutation((widget) => {
widget.template = "<DefinitelyNotAWidgetComponent />";
}),
},
{
name: "template:unknown-global",
widget: withMutation((widget) => {
widget.template = "<Text>{process.env.HOME}</Text>";
}),
},
];
let updateTargetId: string | undefined;
let updateTargetRevision = 0;
for (const [index, entry] of bundled.entries()) {
const canonicalAccepted = customWidgetDefinitionSchema.safeParse(entry.widget).success;
if (!canonicalAccepted) throw new Error(`Bundled widget failed canonical validation: ${entry.name}`);
const direct = updateTargetId
? await request(`/api/collections/submissions/records/${updateTargetId}`, {
method: "PATCH",
headers: userHeaders,
body: JSON.stringify({
title: `Corpus ${String(index + 1).padStart(2, "0")}`,
description: entry.name,
content: JSON.stringify(entry.widget),
expectedRevision: updateTargetRevision,
}),
})
: await request("/api/collections/submissions/records", {
method: "POST",
headers: userHeaders,
body: JSON.stringify({
type: "customWidget",
title: `Corpus ${String(index + 1).padStart(2, "0")}`,
description: entry.name,
widgetSchema: "caller-controlled",
content: JSON.stringify(entry.widget),
author: userId,
}),
});
if (!direct.response.ok || typeof direct.body?.id !== "string") {
throw new Error(
`PocketBase rejected bundled widget ${entry.name}: status=${direct.response.status}, body=${JSON.stringify(direct.body)}`,
);
}
updateTargetId ??= direct.body.id;
if (typeof direct.body.revision !== "number") throw new Error("Corpus response did not include a numeric revision");
updateTargetRevision = direct.body.revision;
}
if (!updateTargetId) throw new Error("Differential corpus did not create an update target");
const adversarialShard = adversarial.filter((_, index) => index % shardCount === shard);
for (const entry of adversarialShard) {
if (customWidgetDefinitionSchema.safeParse(entry.widget).success) {
throw new Error(`Adversarial corpus case passed canonical validation: ${entry.name}`);
}
const direct = await request(`/api/collections/submissions/records/${updateTargetId}`, {
method: "PATCH",
headers: userHeaders,
body: JSON.stringify({
content: JSON.stringify(entry.widget),
expectedRevision: updateTargetRevision,
}),
});
if (direct.response.status === 429) {
throw new Error(`Validator corpus was rate limited before checking ${entry.name}`);
}
if (direct.response.status !== 400) {
throw new Error(
`PocketBase accepted or mishandled invalid widget ${entry.name}: status=${direct.response.status}, body=${JSON.stringify(direct.body)}`,
);
}
}
console.log(
`Workshop validator differential corpus shard ${shard + 1}/${shardCount} passed (${bundled.length + adversarialShard.length} cases)`,
);
+87 -3
View File
@@ -34,6 +34,15 @@ for (const required of ["submissions", "votes", "comments", "reports", "workshop
for (const removed of ["workshop_admin_actions", "workshop_admins"]) {
if (collectionNames.has(removed)) throw new Error(`Removed Workshop collection still exists: ${removed}`);
}
const settings = await request("/api/settings", { headers: rootHeaders });
const rateLimitLabels = new Set(settings.rateLimits?.rules?.map((rule) => rule.label));
for (const operation of ["create", "update", "delete"]) {
for (const collection of ["submissions", "votes", "comments", "reports"]) {
const label = `${collection}:${operation}`;
if (!rateLimitLabels.has(label)) throw new Error(`Missing Workshop write rate limit: ${label}`);
}
}
if (!rateLimitLabels.has("users:update")) throw new Error("Workshop user/file updates are not rate limited");
// Production uses GitHub OAuth. Password auth is enabled only in this disposable database.
const usersCollection = await request("/api/collections/users", { headers: rootHeaders });
@@ -77,6 +86,29 @@ await expectStatus(
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ isAdmin: true }) },
404,
);
for (const [field, value] of [
["displayName", "Homarr Team"],
["avatarUrl", "https://example.invalid/forged-avatar.png"],
["githubUsername", "homarr-labs"],
["githubProfileUrl", "https://github.com/homarr-labs"],
]) {
await expectStatus(
`/api/collections/users/records/${author.id}`,
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ [field]: value }) },
404,
);
}
const unchangedAuthor = await request(`/api/collections/users/records/${author.id}`, {
headers: authorSession.headers,
});
if (
unchangedAuthor.displayName !== "Widget Author" ||
unchangedAuthor.avatarUrl ||
unchangedAuthor.githubUsername ||
unchangedAuthor.githubProfileUrl
) {
throw new Error("Workshop users can forge OAuth provider identity fields");
}
const visitorPassword = "WorkshopVisitor123!";
const visitor = await createUser("widget-visitor@example.invalid", "Widget Visitor", visitorPassword);
@@ -295,7 +327,7 @@ const report = await request("/api/collections/reports/records", {
await expectStatus(`/api/collections/reports/records/${report.id}`, { headers: visitorSession.headers }, 404);
await expectStatus("/api/collections/reports/records", { headers: visitorSession.headers }, 200);
const publicReports = await request("/api/collections/reports/records", { headers: visitorSession.headers });
if (publicReports.items.length !== 0) throw new Error("Report details must remain private to Workshop administrators");
if (publicReports.items.length !== 0) throw new Error("Report details must remain private to Workshop moderators");
await expectStatus(
`/api/collections/reports/records/${report.id}`,
{ method: "DELETE", headers: visitorSession.headers },
@@ -317,14 +349,45 @@ await expectStatus(
const reports = await request("/api/collections/reports/records", { headers: authorSession.headers });
if (reports.items.length !== 1 || reports.items[0].reporter !== visitor.id || reports.items[0].status !== "open") {
throw new Error("Workshop administrators must be able to review reports");
throw new Error("Workshop moderators must be able to review reports");
}
await expectStatus(
`/api/collections/reports/records/${report.id}`,
{
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({ category: "spam", explanation: "Moderator-authored replacement" }),
},
404,
);
const dismissedReport = await request(`/api/collections/reports/records/${report.id}`, {
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({ status: "dismissed" }),
});
if (dismissedReport.status !== "dismissed") throw new Error("Workshop administrators must be able to dismiss reports");
if (dismissedReport.status !== "dismissed") throw new Error("Workshop moderators must be able to dismiss reports");
const reopenedReport = await request("/api/collections/reports/records", {
method: "POST",
headers: visitorSession.headers,
body: JSON.stringify({
submission: submission.id,
reporter: visitor.id,
category: "malicious",
explanation: "The later submission revision now needs another review",
status: "dismissed",
}),
});
if (reopenedReport.status !== "open" || reopenedReport.id === report.id) {
throw new Error("A dismissed Workshop report must be replaceable with a fresh open report");
}
const reopenedReports = await request("/api/collections/reports/records", { headers: authorSession.headers });
if (
reopenedReports.items.length !== 1 ||
reopenedReports.items[0].id !== reopenedReport.id ||
reopenedReports.items[0].status !== "open"
) {
throw new Error("Re-reporting must replace only the reporter's dismissed report");
}
const visitorSubmission = await request("/api/collections/submissions/records", {
method: "POST",
@@ -340,6 +403,27 @@ const visitorSubmission = await request("/api/collections/submissions/records",
outdated: false,
}),
});
await expectStatus(
`/api/collections/submissions/records/${visitorSubmission.id}`,
{
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({
title: "Moderator-authored replacement",
content: JSON.stringify({ ...widget, name: "Moderator-authored replacement" }),
expectedRevision: 1,
}),
},
404,
);
const moderatedStatus = await request(`/api/collections/submissions/records/${visitorSubmission.id}`, {
method: "PATCH",
headers: authorSession.headers,
body: JSON.stringify({ outdated: true, expectedRevision: 1 }),
});
if (!moderatedStatus.outdated || moderatedStatus.revision !== 2) {
throw new Error("Workshop moderators must be limited to CAS-protected submission status changes");
}
await expectStatus(
`/api/collections/submissions/records/${visitorSubmission.id}`,
{ method: "DELETE", headers: authorSession.headers },
+108
View File
@@ -0,0 +1,108 @@
function reject(message) {
print variable_name " " message > "/dev/stderr"
failed = 1
exit 1
}
function valid_port(value, number) {
if (value !~ /^[0-9]+$/ || length(value) > 5) return 0
number = value + 0
return number >= 0 && number <= 65535
}
function valid_ipv4(value, parts, count, part_index) {
if (value !~ /^[0-9.]+$/) return 0
count = split(value, parts, ".")
if (count != 4) return 0
for (part_index = 1; part_index <= count; part_index++) {
if (length(parts[part_index]) > 1 && substr(parts[part_index], 1, 1) == "0") return 0
if (parts[part_index] == "" || parts[part_index] + 0 < 0 || parts[part_index] + 0 > 255) return 0
}
return 1
}
function valid_hostname(value, labels, count, label_index) {
if (value == "" || length(value) > 253 || value !~ /^[A-Za-z0-9._-]+$/) return 0
if (value ~ /^[0-9.]+$/) return valid_ipv4(value)
count = split(value, labels, ".")
for (label_index = 1; label_index <= count; label_index++) {
if (labels[label_index] == "" || length(labels[label_index]) > 63) return 0
if (labels[label_index] ~ /^-/ || labels[label_index] ~ /-$/) return 0
}
return 1
}
function valid_ipv6(value, percent, address, zone, collapsed, parts, count, groups, part_index) {
percent = index(value, "%")
if (percent) return 0
address = value
if (address !~ /:/ || address ~ /:::/ || address !~ /^[0-9A-Fa-f:.]+$/) return 0
collapsed = address
sub(/::/, "", collapsed)
if (collapsed ~ /::/) return 0
count = split(address, parts, ":")
groups = 0
for (part_index = 1; part_index <= count; part_index++) {
if (parts[part_index] == "") continue
if (parts[part_index] ~ /\./) {
if (part_index != count || !valid_ipv4(parts[part_index])) return 0
groups += 2
} else {
if (parts[part_index] !~ /^[0-9A-Fa-f]+$/ || length(parts[part_index]) > 4) return 0
groups++
}
}
return address ~ /::/ ? groups < 8 : groups == 8
}
{
if (NR != 1) reject("must be a single-line URL")
value = $0
if (value ~ /[[:cntrl:][:space:]]/ || index(value, "\"") || index(value, "\\")) {
reject("must not contain control characters, whitespace, quotes, or backslashes")
}
if (value !~ /^https?:\/\//) reject("must be an absolute HTTP(S) URL")
if (value ~ /[?#]/) reject("must not contain a query string or fragment")
rest = value
sub(/^https?:\/\//, "", rest)
slash = index(rest, "/")
authority = slash ? substr(rest, 1, slash - 1) : rest
if (authority == "") reject("must include a host")
if (authority ~ /@/) reject("must not contain credentials")
port = ""
if (authority ~ /^\[/) {
close_index = index(authority, "]")
if (!close_index) reject("contains an invalid IPv6 host")
host = substr(authority, 2, close_index - 2)
suffix = substr(authority, close_index + 1)
if (!valid_ipv6(host)) reject("contains an invalid IPv6 host")
if (suffix != "") {
if (suffix !~ /^:/) reject("contains an invalid host")
port = substr(suffix, 2)
}
} else {
host_with_port = authority
colon_count = gsub(/:/, ":", host_with_port)
if (colon_count > 1) reject("must wrap IPv6 hosts in brackets")
colon = index(authority, ":")
host = colon ? substr(authority, 1, colon - 1) : authority
port = colon ? substr(authority, colon + 1) : ""
if (!valid_hostname(host)) reject("contains an invalid host")
}
if (port != "" && !valid_port(port)) reject("contains an invalid port")
while (length(value) > 0 && substr(value, length(value), 1) == "/") {
value = substr(value, 1, length(value) - 1)
}
print value
}
END {
if (!failed && NR != 1) {
print variable_name " must be a single-line URL" > "/dev/stderr"
exit 1
}
}