refactor: trim v2 release hardening

This commit is contained in:
ajnart committed 2026-07-30 16:24:11 +02:00
1 parent 3cf1dc8341
commit 657704340c
79 files changed
+405 -3378

No files matched your search

-2
View File
@@ -6,8 +6,6 @@ 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=
+4 -24
View File
@@ -13,48 +13,28 @@ COPY packages/custom-widgets ./packages/custom-widgets
COPY packages/definitions ./packages/definitions
COPY packages/workshop ./packages/workshop
COPY tooling/typescript ./tooling/typescript
RUN pnpm config set store-dir /pnpm/store && pnpm install --filter @homarr/docs... --frozen-lockfile
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
FROM dependencies AS website
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
RUN CI=true SKIP_ENV_VALIDATION=true pnpm turbo build --filter=@homarr/docs
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
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
RUN chmod +x /usr/local/bin/workshop-entrypoint && mkdir -p /pb_data /pb_public && chown pocketbase:pocketbase /pb_data
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
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
ENV WORKSHOP_REQUIRE_PUBLIC_ORIGIN=true
COPY --from=website /app/workshop-public /pb_public
COPY --from=website /app/apps/docs/build /pb_public
COPY apps/workshop/pb_migrations /pb_migrations
COPY apps/workshop/pb_hooks /pb_hooks
RUN chown -R pocketbase:pocketbase /pb_hooks /pb_migrations /pb_public
+7
View File
@@ -0,0 +1,7 @@
.git
.next
.turbo
**/node_modules
**/pb_data
apps/docs/build
coverage
+2 -3
View File
@@ -69,8 +69,8 @@ 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.
documentation/site base. All three must be absolute HTTP(S) URLs. The old Docusaurus-only `WORKSHOP_URL` variable
remains a deprecated alias for one release.
## Optional GitHub OAuth
@@ -158,7 +158,6 @@ 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:
+2 -9
View File
@@ -10,17 +10,16 @@ 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_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
@@ -34,18 +33,12 @@ services:
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}"
-61
View File
@@ -1,72 +1,11 @@
#!/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}"
}
normalize_docs_base_url() {
value=$1
case "$value" in
/*) ;;
*)
echo "DOCS_BASE_URL must start with '/'" >&2
return 1
;;
esac
case "${value%/}/" in
*[!A-Za-z0-9._~/-]* | */./* | */../*)
echo "DOCS_BASE_URL must be a safe URL path without traversal" >&2
return 1
;;
esac
printf '/%s\n' "$(printf '%s' "$value" | sed 's#^/*##; s#/*$##')"
}
if [ "${1:-}" = "--validate-url" ]; then
normalize_http_url "${2:-URL}" "${3:-}"
exit
fi
if [ "${1:-}" = "--validate-docs-base-url" ]; then
normalize_docs_base_url "${2:-}"
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=$(normalize_docs_base_url "${DOCS_BASE_URL:-/}")
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:-*}" \
+1 -10
View File
@@ -3,26 +3,17 @@
onBootstrap((event) => {
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 }));
console.log(JSON.stringify({ event: "workshop_oauth_synchronized", enabled: configured }));
});
onRecordAuthWithOAuth2Request((event) => {
+4 -133
View File
@@ -3,67 +3,17 @@ 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
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
@@ -101,90 +51,11 @@ 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
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" \
printf 'y\n' | PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_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 fresh-migrated
stop_rollback_server
printf 'y\n' | PB_EXPOSE_PORT="$WORKSHOP_ROLLBACK_PORT" docker compose -p "$WORKSHOP_ROLLBACK_PROJECT" \
migrate down 1 --dir=/pb_data --migrationsDir=/pb_migrations
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_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 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
migrate up --dir=/pb_data --migrationsDir=/pb_migrations
-72
View File
@@ -1,72 +0,0 @@
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 },
});
const validateDocsBaseUrl = (value) =>
spawnSync("sh", [entrypoint, "--validate-docs-base-url", value], {
encoding: "utf8",
});
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]",
"http://[:1:2:3:4:5:6:7:8]",
"http://[1:2:3:4:5:6:7:8:]",
"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)}`);
}
for (const [value, expected] of [
["/", "/"],
["/docs/", "/docs"],
["/docs..preview", "/docs..preview"],
]) {
const result = validateDocsBaseUrl(value);
if (result.status !== 0 || result.stdout.trim() !== expected) {
throw new Error(`Expected valid DOCS_BASE_URL ${value}: ${result.stderr || result.stdout}`);
}
}
for (const value of ["docs", "/../docs", "/docs/../private", "/./docs", "/docs?preview=1"]) {
const result = validateDocsBaseUrl(value);
if (result.status === 0) throw new Error(`Expected invalid DOCS_BASE_URL to be rejected: ${JSON.stringify(value)}`);
}
console.log("Workshop runtime URL validation passed");
+10 -93
View File
@@ -9,78 +9,33 @@ if (typeof clientExport !== "string") throw new Error("Workshop client export is
await access(resolve("packages/workshop", clientExport));
const hook = await read("apps/workshop/pb_hooks/workshop.pb.js");
const dockerfile = await read("apps/workshop/Dockerfile");
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");
if (!hook.includes("require(`${__hooks}/workshop-utils.js`)")) {
throw new Error("Workshop handlers must load shared helpers inside their isolated PocketBase contexts");
}
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("validateAndNormalizeSubmission")) {
throw new Error("PocketBase must store Workshop submissions without interpreting their content");
}
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 (hook.includes("validateAndNormalizeSubmission") || hook.includes("workshop_submission_rejected")) {
throw new Error("PocketBase must not interpret or validate Workshop submission content");
}
for (const removedValidator of [
for (const artifact of [
"apps/workshop/pb_hooks/widget-validator.js",
"apps/workshop/pb_hooks/widget-validator.bundle.cjs",
"packages/workshop/src/pocketbase-validator.ts",
"scripts/build-workshop-validator.mjs",
]) {
let artifactExists = true;
try {
await access(resolve(removedValidator));
} catch (error) {
if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT") {
artifactExists = false;
} else {
await access(resolve(artifact))
.then(() => {
throw new Error(`Workshop validator artifact must stay removed: ${artifact}`);
})
.catch((error) => {
if (error instanceof Error && "code" in error && error.code === "ENOENT") return;
throw error;
}
}
if (artifactExists) throw new Error(`Workshop validator artifact must stay removed: ${removedValidator}`);
}
if (!dockerfile.includes("WORKSHOP_REQUIRE_PUBLIC_ORIGIN=true")) {
throw new Error("The production Workshop image must require an explicit public origin");
}
if (dockerfile.includes("widget-validator") || dockerfile.includes("build-workshop-validator")) {
throw new Error("The Workshop image must not build or copy a submission 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 [
@@ -96,44 +51,6 @@ for (const required of [
if (!migration.includes(required)) throw new Error(`Workshop rollback is missing state restoration: ${required}`);
}
for (const protectedField of [
"email:changed",
"displayName:changed",
"avatarUrl:changed",
"githubUsername:changed",
"githubProfileUrl:changed",
]) {
if (!migration.includes(protectedField)) {
throw new Error(`Workshop OAuth identity field remains caller-controlled: ${protectedField}`);
}
}
if (migration.includes("@request.body.avatar:changed")) {
throw new Error("Workshop access rules must not use the unsupported :changed modifier for file fields");
}
if (
!hook.includes('getUnsavedFiles("avatar")') ||
!hook.includes('original().getString("avatar")') ||
!hook.includes("Workshop avatars are managed by GitHub OAuth")
) {
throw new Error("Workshop avatar updates must be rejected by the user update request hook");
}
for (const protectedField of [
"title:changed",
"description:changed",
"content:changed",
"changelog:changed",
"screenshots:changed",
]) {
if (!migration.includes(protectedField)) {
throw new Error(`Workshop moderators can still rewrite submissions: ${protectedField}`);
}
}
for (const protectedField of ["category:changed", "explanation:changed"]) {
if (!migration.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");
-168
View File
@@ -1,168 +0,0 @@
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;
let userUpdateHook;
const ignoreHook = () => {};
vm.runInNewContext(hookSource, {
__hooks: "/pb_hooks",
console: { log: () => {} },
onBootstrap: ignoreHook,
onRecordAfterCreateSuccess: ignoreHook,
onRecordCreateRequest: ignoreHook,
onRecordDeleteRequest: ignoreHook,
onRecordUpdateRequest: (handler, collection) => {
if (collection === "users") userUpdateHook = handler;
},
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,
rejectRequest: (message) => {
throw new Error(message);
},
};
},
});
if (typeof oauthHook !== "function") throw new Error("Workshop OAuth request hook was not registered");
if (typeof userUpdateHook !== "function") throw new Error("Workshop user update 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");
}
let unchangedAvatarNextCalls = 0;
userUpdateHook({
next: () => {
unchangedAvatarNextCalls += 1;
},
record: {
getString: () => "provider-avatar.png",
getUnsavedFiles: () => [],
original: () => ({ getString: () => "provider-avatar.png" }),
},
});
if (unchangedAvatarNextCalls !== 1) {
throw new Error("User updates that leave the provider avatar unchanged must pass through");
}
for (const avatarChange of [
{
name: "upload",
current: "provider-avatar.png",
original: "provider-avatar.png",
unsavedFiles: [{ name: "forged-avatar.png" }],
},
{
name: "removal",
current: "",
original: "provider-avatar.png",
unsavedFiles: [],
},
]) {
let nextCalls = 0;
try {
userUpdateHook({
next: () => {
nextCalls += 1;
},
record: {
getString: () => avatarChange.current,
getUnsavedFiles: () => avatarChange.unsavedFiles,
original: () => ({ getString: () => avatarChange.original }),
},
});
throw new Error(`Workshop user avatar ${avatarChange.name} was accepted`);
} catch (error) {
if (!String(error).includes("managed by GitHub OAuth")) throw error;
}
if (nextCalls !== 0) throw new Error(`Rejected avatar ${avatarChange.name} continued the update request`);
}
console.log("Workshop OAuth hook contract passed");
@@ -1,261 +0,0 @@
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 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 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 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 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",
);
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}`);
}
await writeFile(snapshotPath, "{}", { 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}`,
);
}
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 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");
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/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");
assert.equal(users.passwordAuth?.enabled, true);
assert.equal(users.oauth2?.enabled, true);
assert.ok(users.oauth2?.providers?.some((provider) => provider.name === "github"));
await assertBaselineData();
await writeFile(snapshotPath, JSON.stringify({ users: userConfig(users) }), { 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");
await assertBaselineData();
console.log("Workshop full rollback state verified");
}
-111
View File
@@ -1,111 +0,0 @@
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, starts_single_colon, ends_single_colon, 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
starts_single_colon = substr(address, 1, 1) == ":" && substr(address, 1, 2) != "::"
ends_single_colon = substr(address, length(address), 1) == ":" && substr(address, length(address) - 1) != "::"
if (starts_single_colon || ends_single_colon) 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
}
}