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

+8
View File
@@ -0,0 +1,8 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
language: "en-US"
reviews:
auto_review:
enabled: true
drafts: false
base_branches:
- "v2"
-1
View File
@@ -17,7 +17,6 @@ coverage
dev
.build
e2e
apps/docs
apps/nextjs/.next
.env
.env.*
+26 -3
View File
@@ -61,9 +61,32 @@ TURBO_TELEMETRY_DISABLED=1
# Enable mock integration
UNSAFE_ENABLE_MOCK_INTEGRATION=true
# Public Workshop API origin used by Homarr's Workshop browser. The default is https://homarr.dev.
# This is read when the server starts, including in the production Docker image.
# WORKSHOP_API_URL=http://127.0.0.1:3003
# Public URL contract. Values must be absolute HTTP(S) URLs without credentials,
# query strings, or fragments. Trailing slashes are normalized at startup.
HOMARR_WEBSITE_URL=https://homarr.dev
# PocketBase API used by Homarr and by the standalone documentation site.
# Defaults to HOMARR_WEBSITE_URL.
# WORKSHOP_API_URL=https://homarr.dev
# Public Workshop page opened from Homarr. Defaults to HOMARR_WEBSITE_URL/workshop.
# WORKSHOP_WEB_URL=https://homarr.dev/workshop
# Emergency switches preserve stored data. They are enabled by default.
CUSTOM_WIDGETS_ENABLED=true
WORKSHOP_ENABLED=true
# Documentation and PocketBase deployment settings.
# DOCS_BASE_URL=/
# WORKSHOP_PUBLIC_ORIGIN=https://homarr.dev
# PB_ALLOWED_ORIGINS=*
# WORKSHOP_REQUIRE_OAUTH=false
# Local Workshop stack (pnpm dev:workshop):
# 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
# Optional: GITHUB_CLIENT_ID=
# Optional: GITHUB_CLIENT_SECRET=
# Enable demo mode (seeds a demo user "demo"/"demo", a sample board and a mock integration)
# DEMO_MODE=true
+1 -1
View File
@@ -23,7 +23,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_APPROVE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }}
app-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }}
permission-pull-requests: write # required to approve pull request
- name: Install GitHub CLI
+158 -27
View File
@@ -47,6 +47,24 @@ env:
PREVIEW_IMAGE: ghcr.io/homarr-labs/homarr-test
jobs:
formatting:
name: Formatting
if: github.event_name != 'pull_request_target' && (github.event_name != 'workflow_dispatch' || inputs.operation != 'cleanup')
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
if: "!env.ACT"
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || '' }}
- name: Setup
uses: ./tooling/github/setup
- name: Check formatting
run: pnpm format
fast-gate:
name: Fast gate
if: github.event_name != 'pull_request_target' && (github.event_name != 'workflow_dispatch' || inputs.operation != 'cleanup')
@@ -89,6 +107,9 @@ jobs:
- name: Validate workspace configuration
run: pnpm lint:ws
- name: Validate GitHub Actions
run: pnpm check:actions
- name: Validate Custom Widget architecture
run: pnpm check:custom-widgets
@@ -100,12 +121,63 @@ jobs:
pnpm --filter nextjs build
pnpm check:custom-widget-bundle
unit:
name: Full unit suite
if: github.event_name != 'pull_request_target' && (github.event_name != 'workflow_dispatch' || inputs.operation != 'cleanup')
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
if: "!env.ACT"
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || '' }}
- name: Setup
uses: ./tooling/github/setup
- name: Copy environment defaults
run: cp .env.example .env
- name: Run unit tests
run: pnpm test
migration-matrix:
name: Database migrations (${{ matrix.database }})
if: github.event_name != 'pull_request_target' && (github.event_name != 'workflow_dispatch' || inputs.operation != 'cleanup')
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
include:
- database: SQLite
test_file: packages/db/test/sqlite-migration.spec.ts
- database: MySQL
test_file: packages/db/test/mysql-migration.spec.ts
- database: PostgreSQL
test_file: packages/db/test/postgresql-migration.spec.ts
steps:
- uses: actions/checkout@v7
if: "!env.ACT"
with:
persist-credentials: false
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || '' }}
- name: Setup
uses: ./tooling/github/setup
- name: Copy environment defaults
run: cp .env.example .env
- name: Run ${{ matrix.database }} migration tests
env:
MIGRATION_TEST_FILE: ${{ matrix.test_file }}
run: pnpm exec vitest run --project db-node "$MIGRATION_TEST_FILE"
container:
name: Container and E2E
needs: fast-gate
needs: [formatting, fast-gate, unit, migration-matrix]
if: |
github.event_name == 'merge_group' ||
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
@@ -238,11 +310,12 @@ jobs:
run: echo "Act validated the publication path; external GHCR writes are disabled locally."
preview-arm64:
name: Build arm64 preview image
needs: fast-gate
name: Arm64 image
needs: [formatting, fast-gate, unit, migration-matrix]
if: |
(
(github.event_name == 'pull_request' && github.event.pull_request.draft == false && github.event.pull_request.head.repo.full_name == github.repository) ||
github.event_name == 'merge_group' ||
(github.event_name == 'pull_request' && github.event.pull_request.draft == false) ||
(github.event_name == 'workflow_dispatch' && inputs.operation == 'publish')
)
runs-on: ubuntu-24.04-arm
@@ -260,7 +333,12 @@ jobs:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.ref || '' }}
- name: Log in to GHCR
if: "!env.ACT"
if: |
!env.ACT &&
(
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event_name == 'workflow_dispatch' && inputs.operation == 'publish')
)
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
@@ -273,7 +351,12 @@ jobs:
- name: Build and push arm64 preview image by digest
id: preview-build
if: "!env.ACT"
if: |
!env.ACT &&
(
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) ||
(github.event_name == 'workflow_dispatch' && inputs.operation == 'publish')
)
uses: docker/build-push-action@v7
with:
context: .
@@ -288,6 +371,27 @@ jobs:
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
TURBO_REMOTE_CACHE_SIGNATURE_KEY=${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }}
- name: Build arm64 image without publication
if: |
!env.ACT &&
(
github.event_name == 'merge_group' ||
(github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name != github.repository)
)
uses: docker/build-push-action@v7
with:
context: .
network: host
platforms: linux/arm64
outputs: type=cacheonly
cache-from: type=gha,scope=homarr-linux-arm64
cache-to: type=gha,scope=homarr-linux-arm64,mode=max
secrets: |
TURBO_API=${{ secrets.TURBO_API }}
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
TURBO_REMOTE_CACHE_SIGNATURE_KEY=${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }}
publish-preview:
name: Publish multi-platform preview image
needs: [container, preview-arm64]
@@ -318,6 +422,7 @@ jobs:
uses: docker/setup-buildx-action@v4
- name: Verify PR head before publication
id: publication-preflight
if: github.event_name == 'pull_request'
uses: actions/github-script@v8
env:
@@ -330,15 +435,21 @@ jobs:
pull_number: context.payload.pull_request.number,
});
if (pull.state !== "open") {
core.setFailed(`PR #${pull.number} is ${pull.state}; refusing to publish its preview.`);
core.notice(`PR #${pull.number} is ${pull.state}; preview publication is no longer needed.`);
core.setOutput("publish", "false");
return;
}
if (pull.head.sha !== process.env.EXPECTED_HEAD_SHA) {
core.setFailed(`PR #${pull.number} moved from ${process.env.EXPECTED_HEAD_SHA} to ${pull.head.sha}.`);
core.notice(`PR #${pull.number} moved to ${pull.head.sha}; a newer run owns preview publication.`);
core.setOutput("publish", "false");
return;
}
core.setOutput("publish", "true");
- name: Publish preview manifest
if: "!env.ACT"
if: |
!env.ACT &&
(github.event_name != 'pull_request' || steps.publication-preflight.outputs.publish == 'true')
env:
AMD64_DIGEST: ${{ needs.container.outputs.digest }}
ARM64_DIGEST: ${{ needs.preview-arm64.outputs.digest }}
@@ -348,7 +459,9 @@ jobs:
"${PREVIEW_IMAGE}@${ARM64_DIGEST}"
- name: Verify preview manifest platforms
if: "!env.ACT"
if: |
!env.ACT &&
(github.event_name != 'pull_request' || steps.publication-preflight.outputs.publish == 'true')
run: |
image="${PREVIEW_IMAGE}:${PREVIEW_TAG}"
manifest="$(docker buildx imagetools inspect "$image" --raw)"
@@ -383,24 +496,42 @@ jobs:
const packageName = "homarr-test";
const org = context.repo.owner;
const tag = process.env.IMAGE_TAG;
const versions = await github.paginate(
github.rest.packages.getAllPackageVersionsForPackageOwnedByOrg,
{ package_type: "container", package_name: packageName, org, per_page: 100 },
);
const target = versions.find((version) =>
version.metadata?.container?.tags?.includes(tag),
);
if (!target) {
core.info(`No package version found with tag "${tag}"`);
return;
const attempts = context.eventName === "pull_request_target" ? 7 : 1;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
let versions;
try {
versions = await github.paginate(
github.rest.packages.getAllPackageVersionsForPackageOwnedByOrg,
{ package_type: "container", package_name: packageName, org, per_page: 100 },
);
} catch (error) {
if (error.status === 404) {
core.info(`Package "${packageName}" does not exist; cleanup is already complete.`);
return;
}
throw error;
}
const targets = versions.filter((version) =>
version.metadata?.container?.tags?.includes(tag),
);
if (targets.length > 0) {
for (const target of targets) {
await github.rest.packages.deletePackageVersionForOrg({
package_type: "container",
package_name: packageName,
org,
package_version_id: target.id,
});
core.info(`Deleted package version ${target.id} (${tag})`);
}
return;
}
if (attempt < attempts) {
core.info(`No "${tag}" version found yet; retrying cleanup after publication settles.`);
await new Promise((resolve) => setTimeout(resolve, 5_000));
}
}
await github.rest.packages.deletePackageVersionForOrg({
package_type: "container",
package_name: packageName,
org,
package_version_id: target.id,
});
core.info(`Deleted package version ${target.id} (${tag})`);
core.info(`No package version found with tag "${tag}"; cleanup is already complete.`);
- name: Show Act cleanup result
if: env.ACT
@@ -22,7 +22,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.CROWDIN_APP_PRIVATE_KEY }}
client-id: ${{ secrets.CROWDIN_APP_ID }}
app-id: ${{ secrets.CROWDIN_APP_ID }}
permission-contents: write # required to commit to crowdin branch
permission-pull-requests: write # required to create pull request
@@ -52,7 +52,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_APPROVE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }}
app-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }}
permission-pull-requests: write
- name: Approve PR
env:
@@ -64,7 +64,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_MERGE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
app-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # write to beta branch (due to merge)
permission-pull-requests: write # merge pull request
- id: automerge
@@ -54,7 +54,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_MERGE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
app-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # required to commit package.json & changelog changes, merge them to dev / next and publish the release
- uses: actions/checkout@v7
@@ -246,7 +246,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_MERGE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
app-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # required to publish the release
- name: Log in to the Container registry
+109 -31
View File
@@ -1,56 +1,134 @@
name: "[Deployment] Documentation"
name: "[Publish] Documentation and Workshop"
on:
push:
branches: ["dev"]
branches: ["v2"]
paths:
- "apps/docs/**"
- "packages/definitions/src/docs/**"
- "apps/workshop/**"
- "packages/custom-widgets/**"
- "packages/workshop/**"
- "packages/definitions/**"
- "tooling/typescript/**"
- "patches/**"
- "package.json"
- "pnpm-lock.yaml"
- "pnpm-workspace.yaml"
- "turbo.json"
- ".dockerignore"
- ".github/workflows/deployment-docs.yml"
workflow_dispatch:
permissions:
contents: read
pages: write
packages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: false
group: workshop-image-${{ github.ref }}
cancel-in-progress: true
env:
SKIP_ENV_VALIDATION: true
REGISTRY: ghcr.io
IMAGE_NAME: ghcr.io/homarr-labs/homarr-workshop
TURBO_API: ${{ secrets.TURBO_API }}
TURBO_TEAM: ${{ secrets.TURBO_TEAM }}
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_REMOTE_CACHE_SIGNATURE_KEY: ${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }}
jobs:
build:
publish:
name: Publish immutable multi-platform image
runs-on: ubuntu-latest
timeout-minutes: 10
timeout-minutes: 45
outputs:
digest: ${{ steps.build.outputs.digest }}
steps:
- uses: actions/checkout@v7
- name: Setup
uses: ./tooling/github/setup
- name: Build docs
run: pnpm turbo build --filter=@homarr/docs
env:
CI: "true"
- name: Setup Pages
uses: actions/configure-pages@v6
- name: Upload pages artifact
uses: actions/upload-pages-artifact@v5
with:
path: "apps/docs/build"
deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v5
- name: Set up QEMU
uses: docker/setup-qemu-action@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v4
- name: Log in to GHCR
uses: docker/login-action@v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and publish by immutable commit tag
id: build
uses: docker/build-push-action@v7
with:
context: .
file: apps/workshop/Dockerfile
target: production
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ env.IMAGE_NAME }}:sha-${{ github.sha }}
labels: |
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
org.opencontainers.image.revision=${{ github.sha }}
provenance: mode=max
sbom: true
cache-from: type=gha,scope=workshop-production
cache-to: type=gha,scope=workshop-production,mode=max
secrets: |
TURBO_API=${{ secrets.TURBO_API }}
TURBO_TEAM=${{ secrets.TURBO_TEAM }}
TURBO_TOKEN=${{ secrets.TURBO_TOKEN }}
TURBO_REMOTE_CACHE_SIGNATURE_KEY=${{ secrets.TURBO_REMOTE_CACHE_SIGNATURE_KEY }}
- name: Smoke-test the published digest
env:
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
run: |
manifest="$(docker buildx imagetools inspect "${IMAGE_NAME}@${IMAGE_DIGEST}" --raw)"
for architecture in amd64 arm64; do
jq --exit-status --arg architecture "$architecture" \
'any(.manifests[]; .platform.os == "linux" and .platform.architecture == $architecture)' \
<<<"$manifest" >/dev/null
done
docker run --detach --name workshop-smoke --platform linux/amd64 \
--publish 127.0.0.1:18090:8090 \
--env HOMARR_WEBSITE_URL=http://127.0.0.1:18090 \
--env WORKSHOP_API_URL=http://127.0.0.1:18090 \
--env WORKSHOP_WEB_URL=http://127.0.0.1:18090/workshop \
--env WORKSHOP_PUBLIC_ORIGIN=http://127.0.0.1:18090 \
--env WORKSHOP_REQUIRE_OAUTH=false \
"${IMAGE_NAME}@${IMAGE_DIGEST}"
for attempt in $(seq 1 60); do
if curl --fail --silent http://127.0.0.1:18090/api/health >/dev/null; then
break
fi
if [ "$attempt" -eq 60 ]; then
docker logs workshop-smoke
exit 1
fi
sleep 1
done
curl --fail --silent --show-error http://127.0.0.1:18090/ >/dev/null
curl --location --fail --silent --show-error http://127.0.0.1:18090/workshop >/dev/null
curl --fail --silent --show-error \
'http://127.0.0.1:18090/api/collections/workshop_listings/records?page=1&perPage=1' >/dev/null
curl --fail --silent --show-error http://127.0.0.1:18090/workshop-runtime-config.js \
| grep --fixed-strings 'workshopApiUrl: "http://127.0.0.1:18090"'
- name: Stop smoke container
if: always()
run: docker rm --force workshop-smoke >/dev/null 2>&1 || true
- name: Record immutable promotion input
env:
IMAGE_DIGEST: ${{ steps.build.outputs.digest }}
run: |
{
echo "### Workshop image candidate"
echo
echo "\`${IMAGE_NAME}@${IMAGE_DIGEST}\`"
echo
echo "This workflow publishes but does not deploy. Promote this exact digest only after staging acceptance and rollback rehearsal."
} >>"$GITHUB_STEP_SUMMARY"
@@ -55,7 +55,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_APPROVE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }}
app-id: ${{ secrets.RENOVATE_APPROVE_APP_ID }}
permission-pull-requests: write
- name: Approve PR
env:
@@ -67,7 +67,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_MERGE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
app-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # write to main branch (due to merge)
permission-pull-requests: write # merge pull request
- id: automerge
+4 -10
View File
@@ -1,10 +1,9 @@
name: "[Docs] Algolia Recrawl"
# Automatic recrawls are intentionally disabled until the external homarr.dev
# host can dispatch this workflow after promoting an immutable Workshop image.
# Publishing an image to GHCR does not make its documentation live.
on:
workflow_run:
workflows: ["[Deployment] Documentation"]
types: [completed]
branches: [dev]
workflow_dispatch:
permissions:
@@ -12,11 +11,6 @@ permissions:
jobs:
recrawl:
if: >-
${{
(github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event != 'pull_request')
|| github.event_name == 'workflow_dispatch'
}}
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
@@ -43,7 +37,7 @@ jobs:
ALGOLIA_CRAWLER_USER_ID: ${{ secrets.ALGOLIA_CRAWLER_USER_ID }}
ALGOLIA_CRAWLER_API_KEY: ${{ secrets.ALGOLIA_CRAWLER_API_KEY }}
- name: Wait for GitHub Pages to serve the new deployment
- name: Allow the promoted documentation host to settle
run: sleep 60
- name: Trigger Algolia DocSearch recrawl
+1 -34
View File
@@ -5,39 +5,6 @@ on:
types: [released]
jobs:
trigger-docs-release:
name: Trigger Documentation Release
runs-on: ubuntu-latest
timeout-minutes: 2
steps:
- name: Obtain token
id: obtainToken
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.HOMARR_DOCS_RELEASE_APP_PRIVATE_KEY }}
client-id: ${{ vars.HOMARR_DOCS_RELEASE_APP_ID }}
owner: homarr-labs
repositories: |
documentation
permission-contents: write # required to dispatch repository workflow
- name: Trigger documentation release
env:
GITHUB_TOKEN: ${{ steps.obtainToken.outputs.token }}
SOURCE_TAG: ${{ github.event.release.tag_name }}
run: |
curl -X POST \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github+json" \
https://api.github.com/repos/homarr-labs/documentation/dispatches \
-d @- <<EOF
{
"event_type": "trigger-release",
"client_payload": {
"tag": "${SOURCE_TAG}"
}
}
EOF
update-bug-report-template:
name: Update Bug Report Template
runs-on: ubuntu-latest
@@ -48,7 +15,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.RENOVATE_MERGE_PRIVATE_KEY }}
client-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
app-id: ${{ secrets.RENOVATE_MERGE_APP_ID }}
permission-contents: write # required to commit to branch
permission-pull-requests: write # required to create pr & enable automerge
- name: Checkout code
+1 -1
View File
@@ -24,7 +24,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.HOMARR_UPDATE_CONTRIBUTORS_PRIVATE_KEY }}
client-id: ${{ vars.HOMARR_UPDATE_CONTRIBUTORS_APP_ID }}
app-id: ${{ vars.HOMARR_UPDATE_CONTRIBUTORS_APP_ID }}
permission-contents: write # required to commit to branch
permission-pull-requests: write # required to create pr & enable automerge
@@ -24,7 +24,7 @@ jobs:
uses: actions/create-github-app-token@v3
with:
private-key: ${{ secrets.HOMARR_UPDATE_CONTRIBUTORS_PRIVATE_KEY }}
client-id: ${{ vars.HOMARR_UPDATE_CONTRIBUTORS_APP_ID }}
app-id: ${{ vars.HOMARR_UPDATE_CONTRIBUTORS_APP_ID }}
permission-contents: write # required to commit to branch
permission-pull-requests: write # required to create pr & enable automerge
- name: Checkout code
+44 -1
View File
@@ -2,6 +2,7 @@ name: Workshop
on:
pull_request:
merge_group:
push:
branches: [dev, v2]
@@ -10,8 +11,9 @@ permissions:
jobs:
validate:
name: Workshop integration
runs-on: ubuntu-24.04
timeout-minutes: 30
timeout-minutes: 45
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v6
@@ -24,5 +26,46 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm --filter @homarr/workshop typecheck
- run: pnpm --filter @homarr/docs typecheck
- run: pnpm build:workshop-validator
- run: git diff --exit-code -- apps/workshop/pb_hooks/widget-validator.bundle.cjs
- run: pnpm test:workshop
- run: docker build --target production -f apps/workshop/Dockerfile .
- name: Build and smoke-test a non-root documentation deployment
run: |
docker build \
--build-arg DOCS_BASE_URL=/docs-site/ \
--tag homarr-workshop:base-path-smoke \
--target production \
--file apps/workshop/Dockerfile \
.
docker run --detach --name workshop-base-path-smoke \
--publish 127.0.0.1:18093:8090 \
--env DOCS_BASE_URL=/docs-site/ \
--env HOMARR_WEBSITE_URL=http://127.0.0.1:18093 \
--env WORKSHOP_API_URL=http://127.0.0.1:18093 \
--env WORKSHOP_WEB_URL=http://127.0.0.1:18093/docs-site/workshop \
--env WORKSHOP_PUBLIC_ORIGIN=http://127.0.0.1:18093 \
--env WORKSHOP_REQUIRE_OAUTH=false \
homarr-workshop:base-path-smoke
for attempt in $(seq 1 60); do
if curl --fail --silent http://127.0.0.1:18093/api/health >/dev/null; then
break
fi
if [ "$attempt" -eq 60 ]; then
docker logs workshop-base-path-smoke
exit 1
fi
sleep 1
done
curl --fail --silent --show-error http://127.0.0.1:18093/docs-site/ \
| grep --fixed-strings '/docs-site/assets/'
curl --location --fail --silent --show-error http://127.0.0.1:18093/docs-site/workshop/ \
| grep --fixed-strings '/docs-site/workshop/'
curl --fail --silent --show-error \
http://127.0.0.1:18093/docs-site/workshop-runtime-config.js \
| grep --fixed-strings 'workshopWebUrl: "http://127.0.0.1:18093/docs-site/workshop"'
curl --fail --silent --show-error \
'http://127.0.0.1:18093/api/collections/workshop_listings/records?page=1&perPage=1' >/dev/null
- name: Stop non-root documentation smoke container
if: always()
run: docker rm --force workshop-base-path-smoke >/dev/null 2>&1 || true
+1 -1
View File
@@ -37,7 +37,7 @@ RUN --mount=type=secret,id=TURBO_API,env=TURBO_API \
--mount=type=secret,id=TURBO_TEAM,env=TURBO_TEAM \
--mount=type=secret,id=TURBO_TOKEN,env=TURBO_TOKEN \
--mount=type=secret,id=TURBO_REMOTE_CACHE_SIGNATURE_KEY,env=TURBO_REMOTE_CACHE_SIGNATURE_KEY \
TURBO_PLATFORM="${TARGETPLATFORM:-linux/amd64}" pnpm build
TURBO_PLATFORM="${TARGETPLATFORM:-linux/amd64}" pnpm turbo build --filter='!@homarr/docs'
FROM base AS runner
WORKDIR /app
+92
View File
@@ -0,0 +1,92 @@
# Homarr development
This repository contains the Homarr application, task and WebSocket services, the Docusaurus documentation site, and
the PocketBase-backed Community Workshop.
## Prerequisites
- Node.js 24.18 or newer
- Corepack with pnpm 11.11
- Docker with Docker Compose
- Git
Enable the repository's pnpm version and install dependencies:
```sh
corepack enable
corepack install
pnpm install --frozen-lockfile
```
## Run Homarr locally
Copy the environment template and choose a writable absolute SQLite path:
```sh
cp .env.example .env
```
Keep the development infrastructure running in the first terminal:
```sh
pnpm docker:dev
```
Then apply migrations and start Homarr in a second terminal:
```sh
pnpm db:migration:sqlite:run
pnpm dev
```
Homarr is available at `http://127.0.0.1:3000`. The foreground infrastructure command starts Redis and the optional
database services from `development/development.docker-compose.yml`; stop it with Ctrl+C after stopping Homarr.
## Run PocketBase and documentation locally
The integrated command starts persistent PocketBase on port 8090, waits for its health endpoint and Workshop
collections, then starts Docusaurus on port 3003:
```sh
pnpm dev:workshop
```
Open the PocketBase administration UI at `http://127.0.0.1:8090/_/` to create the first superuser. Open the Workshop at
`http://127.0.0.1:3003/workshop`.
To run Homarr against this local stack, set these values in `.env` and restart `pnpm dev`:
```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
```
Stopping `pnpm dev:workshop` stops the services but retains the `homarr-workshop_pb_data` volume. See
[`apps/workshop/README.md`](apps/workshop/README.md) for OAuth, moderator access, logs, backup, restore, and intentional
reset instructions.
## Common checks
```sh
pnpm format
pnpm lint
pnpm typecheck
pnpm test
pnpm test:workshop
pnpm turbo build --filter=@homarr/docs
```
Use `pnpm format:fix` and `pnpm lint:fix` to apply mechanical fixes. User-facing code changes must include the matching
documentation under `apps/docs/docs/`.
## Repository map
- `apps/nextjs` — main Homarr web application
- `apps/tasks` — scheduled task runner and API
- `apps/websocket` — WebSocket server
- `apps/docs` — Docusaurus documentation and public Workshop UI
- `apps/workshop` — PocketBase image, migrations, hooks, and integration tests
- `packages` — shared application, API, database, UI, widget, and integration packages
- `development` — local Docker infrastructure
- `e2e` — end-to-end tests
+8 -2
View File
@@ -21,8 +21,14 @@ pnpm dev:docs
# Or from within this directory
pnpm dev
# PocketBase on 8090 plus docs on 3003
pnpm dev:workshop
```
The standalone docs use `WORKSHOP_API_URL` for PocketBase, `HOMARR_WEBSITE_URL` for the public site origin, and
`DOCS_BASE_URL` for the deployment path. The old `WORKSHOP_URL` name is a deprecated one-release alias.
## Build
```bash
@@ -40,7 +46,7 @@ Uses oxlint and oxfmt (same as the rest of the monorepo):
```bash
pnpm lint # oxlint
pnpm format # oxfmt (check)
pnpm format -- --write # oxfmt (fix)
pnpm format:fix # oxfmt (fix)
```
## Typecheck
@@ -93,7 +99,7 @@ pnpm verify:search
| Layer | Technology |
| -------------- | ------------------------------------------- |
| Site generator | Docusaurus 3 (`@docusaurus/preset-classic`) |
| Styling | Tailwind CSS 3 + Docusaurus Infima |
| Styling | Tailwind CSS 4 + Docusaurus Infima |
| Icons | `@tabler/icons-react` |
| Diagrams | Mermaid (`@docusaurus/theme-mermaid`) |
| Search | Algolia DocSearch |
@@ -8,62 +8,102 @@ tags:
sidebar_position: 1
---
## Setting up your development environment
This guide will help you set up your development environment to start contributing to homarr.
## Set up your development environment
### Prerequisites
- **Node.js (lts)**: You can download it from the [official website](https://nodejs.org/).
- **pnpm (latest)**: You can install it by running `npm install -g pnpm`.
- **Git**: You can download it from the [official website](https://git-scm.com/).
- **Docker or Docker Desktop**: You can download it from the [official website](https://www.docker.com/).
- **A GitHub account**: You can create one on the [official website](https://github.com/).
- Node.js 24.18 or newer
- Corepack and pnpm 11.11
- Git
- Docker with Docker Compose
### Setting up the project
The versions in the root `package.json` are the supported baseline. Let Corepack select the repository version instead
of installing an unrelated global pnpm:
1. Fork the repository by clicking on the "Fork" button on the top right corner of the repository page.
```sh
corepack enable
corepack install
pnpm install --frozen-lockfile
```
![Fork button](./img/fork.png)
### Run the Homarr application
2. Clone the repository to your local machine with `git clone`. You can find the url to use by clicking on the "Code" button on the top right corner of your forks repository page.
1. Copy `.env.example` to `.env`.
2. Set `DB_URL` to an absolute writable SQLite file path.
3. Keep Redis and the optional local databases running in one terminal.
4. Apply migrations and start Next.js in another terminal.
![Clone button](./img/clone.png)
```sh
cp .env.example .env
```
3. Change directory to the project folder with `cd homarr`.
Terminal 1:
4. Install the dependencies with `pnpm install`.
```sh
pnpm docker:dev
```
5. Start redis by running `pnpm run docker:dev`. This will run a docker-compose file with a redis service.
Terminal 2:
6. Copy the `.env.example` file to `.env` and replace `DB_URL` with the full path you want to use for the sqlite database file. For example `DB_URL='C:\\Dev\\homarr\\packages\\db\\db.sqlite'`
```sh
pnpm db:migration:sqlite:run
pnpm dev
```
7. Run the migrations to create the sqlite db file with `pnpm run db:migration:sqlite:run`.
The infrastructure command remains in the foreground. Open `http://127.0.0.1:3000`; the first user created through
Homarr becomes the instance administrator.
8. Start the development server with `pnpm dev` and wait for a message that says `✓ Ready in 10.7s`
### Run PocketBase and documentation
9. Open your browser and navigate to [http://localhost:3000](http://localhost:3000). (Loading the page might take up to 2 minutes the first time)
Use the integrated local Workshop command in a second terminal:
### Useful npm scripts
```sh
pnpm dev:workshop
```
#### During development
It starts persistent PocketBase on port 8090, waits for health and the required collections, then starts Docusaurus on
port 3003. It also propagates shutdown without deleting the PocketBase volume.
- `pnpm dev`: Start the development server.
- `pnpm cli`: Run cli commands.
- `pnpm db:migration:sqlite:run`: Run the migrations to create or update the sqlite db file.
- `pnpm db:migration:sqlite:generate`: Generate a new migration file for the sqlite db. Also works with `mysql`.
- `pnpm db:studio`: Open a visual studio for the database.
- `pnpm package:new`: Create a new package in the monorepo.
Open `http://127.0.0.1:8090/_/` and create the first PocketBase superuser. The Workshop UI is available at
`http://127.0.0.1:3003/workshop`.
#### Checking code quality
Point Homarr at the local services with:
- `pnpm lint`: Run the linter to check for code quality issues.
- `pnpm format:fix`: Run the formatter to fix code style issues.
- `pnpm test`: Run the tests. You can also use `pnpm test:ui` to get a UI for the tests.
- `pnpm typecheck`: Run the typescript type checker.
```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
```
#### Building the project
Restart `pnpm dev` after changing `.env`. GitHub OAuth is optional locally. See
[`apps/workshop/README.md`](https://github.com/homarr-labs/homarr/blob/HEAD/apps/workshop/README.md) for OAuth,
Workshop moderator promotion, logs, tests, backup, restore, stopping, and intentional volume reset.
- `pnpm build`: Build the project for production.
- `docker build -t homarr .`: Build a docker image for the project.
- `docker run -p 7575:7575 -e SECRET_ENCRYPTION_KEY='your_64_character_hex_string' homarr:latest`: Run the created docker image.
### URL and base-path testing
Docusaurus reads `HOMARR_WEBSITE_URL`, `WORKSHOP_API_URL`, `WORKSHOP_WEB_URL`, and `DOCS_BASE_URL` at startup/build.
Homarr renders its public URL values into the page at server startup, so Docker overrides do not rely on
`NEXT_PUBLIC_*` build variables. Test a separate API origin and non-root documentation path before release:
```sh
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/docs-site/workshop \
DOCS_BASE_URL=/docs-site/ \
pnpm dev:docs
```
### Useful commands
- `pnpm dev` — Next.js on port 3000.
- `pnpm dev:docs` — Docusaurus only on port 3003.
- `pnpm dev:workshop` — persistent PocketBase plus Docusaurus.
- `pnpm cli` — Homarr operations CLI.
- `pnpm db:migration:sqlite:run` — create or update a SQLite database.
- `pnpm db:studio` — inspect the database.
- `pnpm format` / `pnpm format:fix` — check or apply oxfmt.
- `pnpm lint` / `pnpm lint:fix` — check or apply oxlint.
- `pnpm typecheck` — typecheck all workspaces.
- `pnpm test` — unit and contract suites.
- `pnpm test:workshop` — disposable Workshop integration suite.
- `pnpm build` — production monorepo build.
@@ -25,13 +25,18 @@ This is especially useful for [docker secrets](https://docs.docker.com/engine/sw
Using the `PUID` and `PGID` will require you to set the correct permissions on the mounted volumes and if used the docker socket. See more in the [Running as a different user](/docs/advanced/running-as-different-user) documentation.
:::
| Environment Variable | Description | Possible values | Default |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ------- |
| `PUID` | User ID to run the container as | Any valid user ID | `0` |
| `PGID` | Group ID to run the container as | Any valid group ID | `0` |
| `LOG_LEVEL` | Log level to use | `debug` / `info` / `warn` / `error` | `info` |
| `NO_EXTERNAL_CONNECTION` | Disables some requests that need internet connection | `true` or `false` | `false` |
| `ENABLE_DNS_CACHING` | Enables dns caching. Enabled by default, but if you experience issues with IPv6 or static IPs, see [#4006](https://github.com/homarr-labs/homarr/issues/4006) or disable this flag | `true` or `false` | `true` |
| Environment Variable | Description | Possible values | Default |
| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- | ----------------------------- |
| `PUID` | User ID to run the container as | Any valid user ID | `0` |
| `PGID` | Group ID to run the container as | Any valid group ID | `0` |
| `LOG_LEVEL` | Log level to use | `debug` / `info` / `warn` / `error` | `info` |
| `NO_EXTERNAL_CONNECTION` | Disables some requests that need internet connection | `true` or `false` | `false` |
| `ENABLE_DNS_CACHING` | Enables dns caching. Enabled by default, but if you experience issues with IPv6 or static IPs, see [#4006](https://github.com/homarr-labs/homarr/issues/4006) or disable this flag | `true` or `false` | `true` |
| `HOMARR_WEBSITE_URL` | Main Homarr documentation/site base used by runtime links. Must be an absolute HTTP(S) URL. | HTTP(S) URL | `https://homarr.dev` |
| `WORKSHOP_API_URL` | PocketBase API used by Homarr and standalone documentation. | HTTP(S) URL | `HOMARR_WEBSITE_URL` |
| `WORKSHOP_WEB_URL` | Public Workshop page opened from Homarr. | HTTP(S) URL | `HOMARR_WEBSITE_URL/workshop` |
| `CUSTOM_WIDGETS_ENABLED` | Emergency switch. `false` preserves definitions and placements but blocks Custom Widget authoring and execution. | `true` or `false` | `true` |
| `WORKSHOP_ENABLED` | Emergency switch. `false` hides and blocks Workshop operations without disabling installed widgets. | `true` or `false` | `true` |
## Authentication
@@ -105,7 +110,14 @@ External redis is currently not supported with Proxmox Community Scripts
The advanced deployments environment variables should only be used if you know what you are doing.
:::
| Environment Variable | Description |
| ------------------------ | --------------------------------------------------------------------------------------------------------------- |
| `DB_MIGRATIONS_DISABLED` | Disable db migrations. For example for helm charts |
| `WORKSHOP_API_URL` | Runtime public origin of the separate Workshop PocketBase service. Homarr uses `https://homarr.dev` by default. |
| Environment Variable | Description |
| ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `DB_MIGRATIONS_DISABLED` | Disable db migrations. For example for helm charts. |
| `DOCS_BASE_URL` | Docusaurus deployment path. It must start with `/` and is normalized with a trailing slash. Default: `/`. |
| `WORKSHOP_PUBLIC_ORIGIN` | Origin used in PocketBase-generated links and email. It must be set explicitly in production. |
| `PB_ALLOWED_ORIGINS` | Browser origins accepted by PocketBase. The central public community defaults to `*` so self-hosted Homarr instances can use OAuth. |
| `WORKSHOP_REQUIRE_OAUTH` | Fail Workshop production readiness when GitHub OAuth is disabled. Both GitHub OAuth credentials are always required together. |
All public URL variables reject non-HTTP protocols, embedded credentials, query strings, and fragments, and normalize
trailing slashes at startup. The Docusaurus-only `WORKSHOP_URL` name is accepted as a deprecated alias for
`WORKSHOP_API_URL` for one release. `WORKSHOP_API_URL` takes precedence.
@@ -4,6 +4,9 @@ An external agent creates one widget at a time with the Homarr MCP server. The a
Homarr does not create widget packs or drafts for multiple widgets.
The MCP API key must belong to a Homarr administrator. Non-administrator keys do not list Custom Widget tools, prompts,
or resources. The same administrator requirement applies to the matching HTTP authoring endpoints.
<a className="button button--primary" href="https://www.skills.sh/homarr-labs/homarr/homarr-custom-widget">
View the Custom Widget Skill on skills.sh
</a>
@@ -67,7 +70,10 @@ These interfaces do not return an archive URL or archive hash.
12. Update the saved definition if the final verification finds a problem.
13. Repeat the procedure for the next widget.
Each source-configuration URL applies to one definition or preview and one source. The user confirms the server URL, network scope, and required credential fields directly in Homarr. The agent receives only request status and never receives plaintext credentials. Preview-scoped values expire with that preview; definition-scoped values persist.
Each source-configuration URL applies to one definition or preview and one source. It is short-lived, single-use, and
can only be opened and completed by an authenticated Homarr administrator. The administrator confirms the server URL,
network scope, and required credential fields directly in Homarr. The agent receives only request status and never
receives plaintext credentials. Preview-scoped values expire with that preview; definition-scoped values persist.
Agents can install existing widgets without regenerating them:
@@ -38,7 +38,8 @@ Bounded regex literals are supported for string matching, splitting, search, and
- `SubFetch` runs a manual query with its `params`. Set `triggerContent` to a card or image to make that content the accessible click and keyboard trigger instead of showing the default load button.
- `ActionButton` and `ToggleSwitch` run actions.
- `RefreshButton` renders a compact, accessible icon control that refreshes load queries.
- `RefreshButton` renders a compact, accessible icon control that refreshes load queries for authenticated viewers. It
is disabled for anonymous public-board viewers because refreshing invalidates shared server cache state.
- `Icon`/`TablerIcon` resolves installed safe icons.
Always include responsive loading, empty, error, and success states. Runtime failures remain inside the widget tile.
@@ -49,6 +49,21 @@ interface HomarrCustomWidgetV2 {
The browser renders JSX. Homarr's server executes named requests, applies board permissions and network protections, and injects credentials. The browser never receives source credentials.
## Permissions
Custom Widget management is an administrator-only surface. Only a Homarr administrator can create, import, migrate,
preview, publish, install, configure, or write secrets, including through HTTP authoring resources or MCP. An API key
only lists Custom Widget MCP tools, prompts, and resources when its owner is an administrator.
Adding or configuring a Custom Widget placement requires both administrator access and permission to modify that
board. A non-administrator with board-modify access can move, resize, change presentation settings, or remove an
existing placement, but cannot add one, change its definition, refresh interval, or Custom Widget options. Duplicating
a board that contains Custom Widgets also requires an administrator.
Once an administrator has placed a widget, ordinary board permissions apply to rendering and requests. Authorized
non-administrators can use it on private boards, and queries can render for anonymous viewers on public boards.
Mutations remain authenticated and enforce each request's view, modify, or full permission.
## Authoring paths
- [Create a Custom Widget](./authoring) visually or with one copied AI prompt.
@@ -60,9 +75,23 @@ The browser renders JSX. Homarr's server executes named requests, applies board
The workbench keeps one continuous layout with visual source, request, and option editors. Advanced raw JSON remains available for experts and AI paste. Invalid values stay inline and disable both preview and Save/Create until they are corrected.
Exports, imports, Workshop, MCP, and storage all validate the same schema. Widgets saved in the legacy format remain visible with a **Migration required** badge after upgrading. Use **Copy migration prompt**, give the redacted prompt to an LLM, then import its v2 JSON from that widget's action menu. Homarr keeps the legacy record until the replacement validates and is confirmed; credentials are never included in the prompt.
Exports, imports, Workshop, MCP, and storage all validate the same schema. Widgets saved in the v1 format remain
visible to administrators with a **Migration required** badge after upgrading. Use **Copy migration prompt**, give the
redacted prompt to an LLM, then import its v2 JSON from that widget's action menu. The prompt keeps safe request
metadata but deliberately omits the v1 display configuration because legacy free-text and JSX can contain hard-coded
credentials. Add a credential-free description of the widget's visible layout and behavior when sending the prompt.
When adding widgets while editing a board, the Custom Widgets section always includes **Install from Workshop**. The Workshop and API source review open above the widget picker without closing it. After import, the new definition appears in the picker. Its tile waits for the board to be saved before server requests run and loads automatically after a successful save; no page reload is required.
Homarr keeps the original v1 definition and encrypted secret as a compatibility backup even after the validated v2
replacement is created. The v2 record uses the same stable ID and takes precedence. The archived v1 copy stays hidden
while the replacement exists; deleting the v2 record surfaces the v1 entry as migration-required again. Automatic
legacy deletion is intentionally unavailable during v2 stabilization. Credentials are never included in prompts,
logs, or exports.
For administrators adding widgets while editing a board, the Custom Widgets section includes **Install from
Workshop**. Non-administrators do not see the Custom Widget picker or Workshop actions. The Workshop and API source
review open above the widget picker without closing it. After import, the new definition appears in the picker. Its tile
waits for the board to be saved before server requests run and loads automatically after a successful save; no page
reload is required.
## Import and Workshop
@@ -70,10 +99,26 @@ Import review shows origins, authentication modes, network scopes, methods, acti
For example, installing **Tautulli Activity** asks for both the user's Tautulli URL and API key. A stable public source such as PokéAPI keeps its published URL without creating unnecessary setup work.
Workshop publishes technically valid widgets immediately; users can vote or report them, and administrators can delete submissions. Publishers should replace personal private-network hosts with a clear service placeholder before publishing.
Workshop publishes technically valid widgets immediately; users can vote or report them, and Workshop moderators can
delete submissions. Community moderation is separate from Homarr administration and is not a security boundary.
Publishers should replace personal private-network hosts with a clear service placeholder before publishing. Homarr
performs definitive validation again at install time.
Connected agents can search, inspect, and install Workshop widgets with `customWidget_workshopSearch`, `customWidget_workshopGet`, and `customWidget_workshopInstall`. After installation they can set a source URL and credentials with `customWidget_sourceConfigure`, or create a secure user-facing setup URL with `customWidget_configurationRequestUser`. Secret values are never returned through MCP.
These tools are only exposed to API keys owned by Homarr administrators. Opening and completing a source-configuration
URL also requires the same authenticated administrator; the URL is short-lived, single-use, and redacted.
## Reliability and rollback
Custom Widget response caches and action invalidation use shared Redis state, so multiple Homarr replicas see the same
versioned cache generation. Deployments must point every replica at the same Redis service.
Set `CUSTOM_WIDGETS_ENABLED=false` to stop authoring and runtime execution while preserving definitions, secrets, board
placements, and v1 backups. Re-enable it after correcting the incident. Before upgrading, back up the database and
`SECRET_ENCRYPTION_KEY`; a v1 binary can still read preserved v1 tables during application rollback. Widgets created
only in v2 may be unavailable to the rolled-back binary, but do not replace the v1 backup.
## Bundled examples
Homarr seeds five disabled examples without credentials and never overwrites an edited seed. They use the same public contract. The Tautulli example is the highest-scoring widget preserved from Homarr's AI authoring evaluation:
@@ -12,7 +12,9 @@ Requests are keyed by ID. `source`, `kind`, `method`, `trigger`, `auth`, and `pe
The request `path` is appended to the source `baseUrl`, including a base path such as `/api/v2`.
GET, POST, PUT, PATCH, and DELETE work for queries and actions. Kind—not method—controls behavior. Load queries run automatically, manual queries run through `SubFetch`, and actions run only from `ActionButton` or `ToggleSwitch`.
GET, POST, PUT, and PATCH work for queries and actions. DELETE is restricted to actions so it can never run while a
board loads. Kind controls the remaining behavior: load queries run automatically, manual queries run through
`SubFetch`, and actions run only from `ActionButton` or `ToggleSwitch`.
Bind values directly where they are used:
@@ -40,3 +42,12 @@ Paths and query-string values must resolve to text, numbers, or booleans. JSON b
Every request uses Homarr's existing server executor: same-origin source enforcement, network scope, DNS and redirect validation, SSRF protection, board permissions, rate and request limits, body and response limits, timeouts, and encrypted credential injection. Static headers cannot override credentials, cookies, routing, proxy, forwarding, or hop-by-hop headers.
Queries default to view permission and actions to modify. DELETE always requires full permission and confirmation. Actions are never cached, retried, or run on load.
Management and runtime are intentionally separate. A Homarr administrator with board-modify permission places and
configures the widget. After placement, query and action authorization follows the request's board permission. Public
boards may execute queries for anonymous viewers, but mutations stay authenticated. This includes shared-cache
invalidation: `RefreshButton` is disabled for anonymous viewers, while ordinary scheduled query rendering remains
available.
Responses use bounded, versioned shared-Redis cache keys. Action invalidation advances the shared version so every
Homarr replica stops serving the previous response without scanning or deleting a key prefix.
@@ -4,7 +4,15 @@
The definition does not exist. If it was deleted, remove the unavailable tile from the board.
If the Custom Widgets page shows the definition with a **Migration required** badge, open its action menu and select **Copy migration prompt**. Give that redacted prompt to an LLM, then import the resulting v2 JSON from the same menu. Homarr keeps the legacy definition until the replacement validates and you confirm the migration.
If the Custom Widgets page shows the definition with a **Migration required** badge, an administrator can open its
action menu and select **Copy migration prompt**. Give that redacted prompt to an LLM, then import the resulting v2 JSON
from the same menu. Because arbitrary v1 display text or JSX may contain credentials, the prompt omits that display
configuration; describe the old widget's visible layout and behavior without including secrets. Other viewers see
**Contact an administrator** instead of a migration link.
Homarr keeps the v1 definition and encrypted secret after migration. The validated v2 replacement uses the same ID and
takes precedence; the archived v1 record reappears if the v2 replacement is deleted. There is no v1 permanent-delete
action during the v2 stabilization period.
Otherwise, install or create a Custom JSX v2 definition.
@@ -34,6 +42,15 @@ An invalid definition disables widget preview and Save/Create. The Data, Options
The Diagnostics tab shows the current schema errors.
## Feature unavailable
If every Custom Widget reports that the feature is unavailable, check `CUSTOM_WIDGETS_ENABLED`. Setting it to `false`
is an emergency stop that preserves definitions, secrets, legacy backups, and board placements while blocking authoring
and execution.
If Workshop alone is unavailable, check `WORKSHOP_ENABLED` and `WORKSHOP_API_URL`. Disabling Workshop does not disable
widgets that are already installed.
## Correct request errors
Check the API source network scope. Check the base URL and credentials.
@@ -44,6 +61,9 @@ For “invalid placeholder,” use `{option:name}` or `{param:name}`. Load queri
The journal shows the method, request ID, path template, status, and duration.
In a multi-instance deployment, all Homarr replicas must share Redis. Versioned cache invalidation is distributed
through Redis; replicas connected to different Redis databases can serve stale query responses after an action.
## Correct a Mantine prop warning
`UNKNOWN_MANTINE_PROP` is a warning. Homarr passes the prop to Mantine.
@@ -57,3 +77,10 @@ Use safe widget options, temporary inputs, or named requests instead.
The widget option definitions changed and the saved values are invalid. Open the item settings.
Correct the marked configuration values. Homarr does not infer widget option migrations.
## Roll back safely
Before an application upgrade, back up the database and preserve the exact `SECRET_ENCRYPTION_KEY`. The v2 schema keeps
the physical v1 definition and secret tables readable by a v1 binary. Roll back the application without running
manual cleanup, verify legacy widgets, and restore the database backup if the migration itself must be reversed.
PocketBase Workshop data is a separate backup and restore operation.
+16 -2
View File
@@ -92,6 +92,10 @@ MCP supports two authentication methods:
API key authentication is simpler and recommended for most setups. The API key inherits the permissions of the user who created it. Tools that require higher privileges will return permission errors if the key lacks access.
Custom Widget and Workshop authoring are different: their tools, prompts, and resources are exposed only when the API
key owner is a Homarr administrator. Non-administrator keys cannot discover or invoke those capabilities. Creating an
API key never elevates the owner.
## Testing the Connection
Verify your MCP endpoint is working:
@@ -168,6 +172,9 @@ The tools table on the MCP tab is dynamically generated - it always reflects the
An agent creates one `homarr-custom-widget-v2` definition at a time. Start with the native prompt `homarr-custom-widget-author`.
The API key owner must be a Homarr administrator. The same rule applies to management, import, migration, preview,
secrets, publication, Workshop installation, and the HTTP authoring resources.
Then, read the live schema and component resources. These resources describe the installed Mantine components.
1. Call `customWidget_getAuthoringPrompt` and `customWidget_schema`.
@@ -194,7 +201,8 @@ Discovery resources:
- `homarr://custom-widgets/examples/{name}`
- `homarr://custom-widgets/skill`
An HTTP-only harness can use the matching `/api/custom-widgets/authoring-prompt`, `/schema`, `/components`, and `/skill` endpoints instead of MCP resource URIs.
An authenticated administrator can use the matching `/api/custom-widgets/authoring-prompt`, `/schema`, `/components`,
and `/skill` endpoints instead of MCP resource URIs. These endpoints are not public schema downloads.
The Custom Widget tools are:
@@ -219,7 +227,13 @@ The Custom Widget tools are:
- `customWidget_getAuthoringPrompt`
- `customWidget_getSkill`
The `custom-widget-manage` permission permits authoring. A direct credential write also requires the `custom-widget-secret-write` permission.
Custom Widget permissions are not assignable group capabilities. Administrator status is required for the complete
authoring surface. A source-configuration URL is short-lived and single-use, requires the same logged-in administrator
to open and complete it, and never returns plaintext credentials to the agent.
Adding a `customApi` item through `board_addItem`, changing its definition or options, and duplicating a board that
contains one also require an administrator with board-modify access. Existing placements continue to render and run
authorized requests according to normal board permissions.
Homarr applies its request security controls during request execution. These controls include SSRF, DNS, redirect, size, timeout, rate, and permission controls.
@@ -177,6 +177,11 @@ Currently, the following permissions are available:
- **Full integration access**: Allow members to manage, use and interact with any integration
- **Administrator**: Members with this permission have full access to all features and settings
Custom Widget authoring, import, migration, preview, secrets, Workshop access, and placement configuration are reserved
for administrators and are not separate assignable group permissions. Board modifiers can still move, resize, change
presentation settings, or remove an existing Custom Widget placement, and board viewers can use placed widgets as
allowed by each request.
When you changed permissions, you must confirm your changes by clicking the banner at the bottom:
![](./img/changing-group-permissions.png)
+42 -10
View File
@@ -17,9 +17,14 @@ The [Community Workshop](pathname:///workshop) is where Homarr users share and d
**custom CSS themes** and **custom widgets**. You can browse submissions, upvote the ones
you like, report abuse, and install entries directly into your own Homarr instance.
The central `homarr.dev` Workshop is a public community. Browsing it on the website is public. Browsing, installing,
publishing, or importing Workshop content **inside a Homarr instance is restricted to Homarr administrators**.
:::warning
The workshop contains community-made content. Widgets may contain unwanted or malicious content and it is your duty to check & verify safety of the content. While we try to remove malicious content as best as we can, we take no responsibility. Always review the widget JSON and all CSS before installing it on your instance and take frequent backups as prevention measures.
The Workshop contains community-made content. Moderation is not a security boundary. Always review widget capabilities,
network origins, actions, and CSS before installing. Homarr's installation-time validator is definitive and can reject
content that the public service accepted earlier. Back up your instance before installing untrusted content.
:::
@@ -29,12 +34,12 @@ The workshop contains community-made content. Widgets may contain unwanted or ma
- Sign in with **GitHub** to upvote/downvote, submit your own creations, or report a submission.
- Each submission shows its title, description, linked GitHub author, revision, optional screenshots, comments, and full content. Widget pages also summarize API sources, actions, options, network access, and required credentials before installation.
- A new submission receives one real upvote owned by its author. Votes remain unique per user and submission.
- Report details and reporter identities are visible only to Workshop administrators. Reported submissions are highlighted in the administration page, where each open report can be dismissed or the submission can be deleted. Reports do not automatically remove a submission.
- Report details and reporter identities are visible only to Workshop moderators. Reported submissions are highlighted in the moderation page, where each open report can be dismissed or the submission can be deleted. Reports do not automatically remove a submission.
- The manual **Outdated** badge warns visitors that a submission may need an update.
## Comments
Comments are publicly readable and appear in chronological conversation bubbles with the author's avatar and GitHub profile. Signed-in users can post; authors can edit or delete their own comments, and Workshop administrators can delete any comment. Failed posts keep the text you typed. When SMTP and `WORKSHOP_PUBLIC_ORIGIN` are configured, the submission author receives one email for a comment from another user. Self-comments, edits, and deletions do not send mail.
Comments are publicly readable and appear in chronological conversation bubbles with the author's avatar and GitHub profile. Signed-in users can post; authors can edit or delete their own comments, and Workshop moderators can delete any comment. Failed posts keep the text you typed. When SMTP and `WORKSHOP_PUBLIC_ORIGIN` are configured, the submission author receives one email for a comment from another user. Self-comments, edits, and deletions do not send mail.
## Submitting
@@ -49,7 +54,14 @@ Comments are publicly readable and appear in chronological conversation bubbles
Submissions are published immediately. Reported entries are reviewed and may be removed.
Authors can edit a submission later to publish a new revision. The edit form can keep or remove existing screenshots and add new PNG, JPG, or WebP images without changing the Workshop URL.
When SMTP and `WORKSHOP_PUBLIC_ORIGIN` are configured, every current Workshop administrator receives an email when a report is submitted. If an administrator deletes the reported submission, its author receives a separate removal email. Author self-deletion does not send a moderation email.
When SMTP and `WORKSHOP_PUBLIC_ORIGIN` are configured, every current Workshop moderator receives an email when a report is submitted. If a moderator deletes the reported submission, its author receives a separate removal email. Author self-deletion does not send a moderation email.
:::info Separate roles
A Workshop moderator is a user with PocketBase's internal `isAdmin` field. This role moderates the central community
and is unrelated to a Homarr instance administrator.
:::
## Submission guidelines
@@ -61,9 +73,9 @@ that primarily promotes unrelated products or services.
You can install workshop entries without leaving Homarr:
- **Custom widgets** — go to **Manage → Custom Widgets**, or use **Install from Workshop** in the
- **Custom widgets (Homarr administrators only)** — go to **Manage → Custom Widgets**, or use **Install from Workshop** in the
board widget picker. Pick an entry, review its capabilities, and enter any required local secrets before import.
- **Custom CSS** — open a board's **Settings → Custom CSS**, click **Install from Workshop**, and
- **Custom CSS from Workshop (Homarr administrators only)** — open a board's **Settings → Custom CSS**, click **Install from Workshop**, and
pick a theme to load it into the editor before saving.
Alternatively, open a submission in the Workshop and use **Download widget JSON** or **Copy CSS**. The submission page shows the matching manual installation steps before the source code.
@@ -74,13 +86,33 @@ Custom Widget imports detect required bearer, basic, header, or query credential
Workshop is powered by [PocketBase](https://pocketbase.io). The production image compiles the current Docusaurus site and serves it together with the API from one origin. The deployment lives in `apps/workshop/` with a Dockerfile, Compose configuration, version-controlled migrations, hooks, a smoke test, and ACT-local workflow instructions.
Run `pnpm docker:workshop` for the PocketBase development service or `pnpm docker:docs` for the built documentation and Workshop site. Both use `apps/workshop/docker-compose.yml` and the persistent `pb_data` volume. Normal start and stop commands retain data; `docker compose -f apps/workshop/docker-compose.yml down --volumes` intentionally recreates the database.
Run `pnpm dev:workshop` for the recommended local stack: persistent PocketBase on port 8090 and Docusaurus on port 3003. The command waits for health and collections and preserves the `pb_data` volume on shutdown. `pnpm docker:docs`
builds the combined production layout. Normal start and stop commands retain data; `down --volumes` is an intentional,
irreversible development reset.
Because Workshop is still unreleased, reset an older development volume if it predates the current schema and comments report that their collection context is missing. No compatibility migrations are maintained for these pre-release databases.
GitHub needs only the central callback `https://<workshop-host>/api/oauth2-redirect`. Keep PocketBase origins unrestricted
unless every self-hosted Homarr caller is explicitly listed. Configure both `GITHUB_CLIENT_ID` and
`GITHUB_CLIENT_SECRET`; supplying only one is a startup error. Production also requires
`WORKSHOP_PUBLIC_ORIGIN`. Configure SMTP for comment, report, and removal notices.
GitHub needs only the central callback `https://<workshop-host>/api/oauth2-redirect`. Keep PocketBase origins unrestricted unless every self-hosted Homarr caller is explicitly listed. Configure `GITHUB_CLIENT_ID`, `GITHUB_CLIENT_SECRET`, `WORKSHOP_PUBLIC_ORIGIN`, and PocketBase SMTP settings for authentication, comment email, report alerts, and submission-removal notices.
The public URL contract is:
Homarr instances use the server-side `WORKSHOP_API_URL` variable to reach the central API. The Docusaurus site uses `WORKSHOP_URL` when its development server runs separately; the combined production image always uses its own origin. Restart the corresponding process after changing either value because both are read at startup.
| Variable | Purpose | Default |
| ------------------------ | ------------------------------------------------- | ----------------------------- |
| `HOMARR_WEBSITE_URL` | Documentation/site base used by Homarr links | `https://homarr.dev` |
| `WORKSHOP_API_URL` | PocketBase API used by Homarr and standalone docs | `HOMARR_WEBSITE_URL` |
| `WORKSHOP_WEB_URL` | Public Workshop page linked from Homarr | `HOMARR_WEBSITE_URL/workshop` |
| `DOCS_BASE_URL` | Docusaurus deployment path | `/` |
| `WORKSHOP_PUBLIC_ORIGIN` | PocketBase-generated links and email | Required in production |
| `PB_ALLOWED_ORIGINS` | PocketBase browser origins | `*` for the central community |
The deprecated docs-only `WORKSHOP_URL` alias remains for one release; `WORKSHOP_API_URL` takes precedence. Homarr
server-renders runtime values for the browser, and the combined image writes a public runtime config at container
startup. Restart services after changes.
Back up application and PocketBase data before deployment. Publish the combined image by immutable digest, test the
exact digest in staging, rehearse application rollback and PocketBase restore, then promote that same digest. The
`WORKSHOP_ENABLED=false` switch disables Homarr's Workshop entry points without affecting installed widgets.
## Client architecture
+2 -1
View File
@@ -38,7 +38,8 @@ Enable the definition before you use it. The definition must also be available t
Each named request declares its minimum board permission. This permission does not depend on the HTTP method.
Queries and actions can use GET, POST, PUT, PATCH, or DELETE. The `kind` value controls runtime behavior.
Queries and actions can use GET, POST, PUT, or PATCH. DELETE is valid only for actions so it can never run
automatically while a board loads. The `kind` value controls the remaining runtime behavior.
A DELETE request requires full board permission and confirmation. An anonymous viewer cannot run an action.
+18 -3
View File
@@ -1,20 +1,35 @@
import type * as Preset from "@docusaurus/preset-classic";
import type { Config } from "@docusaurus/types";
import { themes as prismThemes } from "prism-react-renderer";
import { normalizeDocsBaseUrl, resolveHomarrUrlConfig } from "@homarr/workshop/schema";
const a11yEmoji = require("@fec/remark-a11y-emoji");
const deprecatedWorkshopUrl = process.env.WORKSHOP_URL;
if (deprecatedWorkshopUrl && !process.env.WORKSHOP_API_URL) {
console.warn("WORKSHOP_URL is deprecated; use WORKSHOP_API_URL instead.");
}
const publicUrls = resolveHomarrUrlConfig({
homarrWebsiteUrl: process.env.HOMARR_WEBSITE_URL,
workshopApiUrl: process.env.WORKSHOP_API_URL ?? deprecatedWorkshopUrl,
workshopWebUrl: process.env.WORKSHOP_WEB_URL,
});
const docsBaseUrl = normalizeDocsBaseUrl(process.env.DOCS_BASE_URL);
const config: Config = {
title: "Homarr documentation",
tagline: "A simple yet powerful dashboard for your server.",
url: "https://homarr.dev",
baseUrl: "/",
url: publicUrls.homarrWebsiteUrl,
baseUrl: docsBaseUrl,
trailingSlash: undefined,
favicon: "img/logo.png",
organizationName: "homarr-labs",
projectName: "homarr",
customFields: {
workshopUrl: process.env.WORKSHOP_URL ?? "",
workshopUrl: publicUrls.workshopApiUrl,
workshopWebUrl: publicUrls.workshopWebUrl,
},
scripts: [{ src: `${docsBaseUrl}workshop-runtime-config.js` }],
i18n: {
defaultLocale: "en",
locales: ["en"],
@@ -2,8 +2,11 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import BrowserOnly from "@docusaurus/BrowserOnly";
import Link from "@docusaurus/Link";
import { useLocation } from "@docusaurus/router";
import useBaseUrl from "@docusaurus/useBaseUrl";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import Layout from "@theme/Layout";
import { getRuntimeWorkshopApiUrl } from "@site/src/lib/runtime-config";
import {
IconArrowBigDown,
IconArrowBigUp,
@@ -176,6 +179,7 @@ const WidgetSafetySummary = ({ widget }: { widget: HomarrCustomWidgetV2 }) => {
const MarketplaceDetail = ({ workshopUrl }: { workshopUrl: string }) => {
const location = useLocation();
const workshopHomeUrl = useBaseUrl("/workshop/");
const submissionId = parseSubmissionId(location.pathname);
const backend = useMemo(() => getWorkshopBackend(workshopUrl), [workshopUrl]);
@@ -325,7 +329,7 @@ const MarketplaceDetail = ({ workshopUrl }: { workshopUrl: string }) => {
if (!submission) return;
try {
await backend.delete(submission.id);
window.location.href = "/workshop/";
window.location.href = workshopHomeUrl;
} catch (caught) {
setError(errorMessage(caught, "Failed to delete submission"));
}
@@ -335,7 +339,7 @@ const MarketplaceDetail = ({ workshopUrl }: { workshopUrl: string }) => {
if (!submission) return;
try {
const updated = await backend.toggleOutdated(submission.id, !submission.outdated);
setSubmission({ ...submission, outdated: updated.outdated });
setSubmission(updated);
setError(null);
toast.success(updated.outdated ? "Submission marked as outdated" : "Submission marked as current");
} catch (caught) {
@@ -453,7 +457,7 @@ const MarketplaceDetail = ({ workshopUrl }: { workshopUrl: string }) => {
setReportOpen(false);
setReportExplanation("");
setError(null);
toast.success("Report submitted", { description: "A Workshop administrator can now review it." });
toast.success("Report submitted", { description: "A Workshop moderator can now review it." });
} catch (caught) {
setReportError(errorMessage(caught, "Failed to submit report"));
} finally {
@@ -863,7 +867,7 @@ const MarketplaceDetail = ({ workshopUrl }: { workshopUrl: string }) => {
<DialogHeader>
<DialogTitle>Report submission</DialogTitle>
<DialogDescription>
Only Workshop administrators can review report details and reporter identities.
Only Workshop moderators can review report details and reporter identities.
</DialogDescription>
</DialogHeader>
{reportError && (
@@ -1023,7 +1027,7 @@ export default function MarketplaceDetailPage() {
<BrowserOnly fallback={<DetailSkeleton />}>
{() => (
<WorkshopErrorBoundary>
<MarketplaceDetail workshopUrl={configuredWorkshopUrl || window.location.origin} />
<MarketplaceDetail workshopUrl={getRuntimeWorkshopApiUrl(configuredWorkshopUrl)} />
</WorkshopErrorBoundary>
)}
</BrowserOnly>
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "@docusaurus/Link";
import {
IconBrandGithub,
IconExternalLink,
@@ -52,7 +53,7 @@ export function WorkshopAdmin({ workshopUrl }: { workshopUrl?: string }) {
setSubmissions(nextSubmissions);
setError("");
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Unable to load Workshop administration");
setError(cause instanceof Error ? cause.message : "Unable to load Workshop moderation");
} finally {
setLoading(false);
}
@@ -118,13 +119,13 @@ export function WorkshopAdmin({ workshopUrl }: { workshopUrl?: string }) {
<IconShield size={18} />
<span className="text-sm font-medium">Restricted area</span>
</div>
<h1 className="text-3xl font-semibold tracking-tight">Workshop administration</h1>
<h1 className="text-3xl font-semibold tracking-tight">Workshop moderation</h1>
<p className="mt-2 max-w-2xl text-sm text-muted-foreground">
Review reports and remove unsafe or outdated submissions. PocketBase rules enforce every action.
</p>
</div>
<div className="flex flex-wrap gap-2">
<Button variant="outline" nativeButton={false} render={<a href="/workshop" aria-label="Back to Workshop" />}>
<Button variant="outline" nativeButton={false} render={<Link to="/workshop" aria-label="Back to Workshop" />}>
Back to Workshop
</Button>
{!user && (
@@ -145,14 +146,14 @@ export function WorkshopAdmin({ workshopUrl }: { workshopUrl?: string }) {
{user && !user.isAdmin && (
<Alert variant="destructive" className="mb-5">
<IconShield />
<AlertTitle>Administrator access required</AlertTitle>
<AlertTitle>Workshop moderator access required</AlertTitle>
<AlertDescription>This GitHub account cannot access Workshop moderation.</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive" className="mb-5">
<IconFlag />
<AlertTitle>Workshop administration failed</AlertTitle>
<AlertTitle>Workshop moderation failed</AlertTitle>
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
@@ -265,7 +266,7 @@ export function WorkshopAdmin({ workshopUrl }: { workshopUrl?: string }) {
variant="outline"
size="sm"
nativeButton={false}
render={<a href={`/workshop/${submission.id}`} aria-label={`Inspect ${submission.title}`} />}
render={<Link to={`/workshop/${submission.id}`} aria-label={`Inspect ${submission.title}`} />}
>
<IconExternalLink size={14} /> Inspect submission
</Button>
@@ -1,4 +1,5 @@
import React, { useMemo, useState } from "react";
import Link from "@docusaurus/Link";
import {
IconAlertCircle,
IconArrowBigDown,
@@ -323,7 +324,7 @@ const SubmissionCard = ({ submission, backend, userVote, onVote }: SubmissionCar
return (
<Card className="relative flex h-full min-w-0 w-full flex-col">
<a href={`/workshop/${submission.id}/`} className="block shrink-0">
<Link to={`/workshop/${submission.id}/`} className="block shrink-0">
{hasScreenshots ? (
<div className="relative">
<Badge
@@ -340,13 +341,13 @@ const SubmissionCard = ({ submission, backend, userVote, onVote }: SubmissionCar
<TypeIcon size={32} className="text-muted-foreground/20" />
</div>
)}
</a>
</Link>
<CardHeader className="flex flex-col gap-2 sm:grid">
<div className="flex items-center gap-2">
<a href={`/workshop/${submission.id}/`} className="min-w-0 hover:underline" title={submission.title}>
<Link to={`/workshop/${submission.id}/`} className="min-w-0 hover:underline" title={submission.title}>
<CardTitle className="truncate">{submission.title}</CardTitle>
</a>
</Link>
{!hasScreenshots && (
<Badge variant="secondary" className="shrink-0 gap-1.5 px-2">
<span className={cn("size-2 rounded-full", typeDotColors[submission.type])} />
@@ -423,7 +424,7 @@ const SubmissionCard = ({ submission, backend, userVote, onVote }: SubmissionCar
className="h-10 sm:h-7"
size="sm"
nativeButton={false}
render={<a href={`/workshop/${submission.id}/`} aria-label={`View ${submission.title} details`} />}
render={<Link to={`/workshop/${submission.id}/`} aria-label={`View ${submission.title} details`} />}
>
<IconEye size={14} /> View details
</Button>
+21
View File
@@ -0,0 +1,21 @@
interface HomarrRuntimeConfig {
homarrWebsiteUrl?: string;
workshopApiUrl?: string;
workshopWebUrl?: string;
}
declare global {
interface Window {
homarrRuntimeConfig?: Readonly<HomarrRuntimeConfig>;
}
}
export const getRuntimeWorkshopApiUrl = (configuredUrl: string): string => {
if (typeof window === "undefined") return configuredUrl;
return window.homarrRuntimeConfig?.workshopApiUrl || configuredUrl || window.location.origin;
};
export const getRuntimeWorkshopWebUrl = (configuredUrl: string): string => {
if (typeof window === "undefined") return configuredUrl;
return window.homarrRuntimeConfig?.workshopWebUrl || configuredUrl || `${window.location.origin}/workshop`;
};
+3 -2
View File
@@ -3,13 +3,14 @@ import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import Layout from "@theme/Layout";
import { WorkshopAdmin } from "@site/src/components/workshop/WorkshopAdmin";
import { getRuntimeWorkshopApiUrl } from "@site/src/lib/runtime-config";
export default function WorkshopAdminRoute() {
const { siteConfig } = useDocusaurusContext();
const workshopUrl = (siteConfig.customFields?.workshopUrl as string | undefined) ?? "";
return (
<Layout title="Workshop administration" noFooter>
<WorkshopAdmin workshopUrl={workshopUrl} />
<Layout title="Workshop moderation" noFooter>
<WorkshopAdmin workshopUrl={getRuntimeWorkshopApiUrl(workshopUrl)} />
</Layout>
);
}
+2 -1
View File
@@ -5,6 +5,7 @@ import Layout from "@theme/Layout";
import { WorkshopApp, WorkshopListingFallback } from "@site/src/components/workshop/WorkshopApp";
import { WorkshopErrorBoundary } from "@site/src/components/workshop/WorkshopErrorBoundary";
import { getRuntimeWorkshopApiUrl } from "@site/src/lib/runtime-config";
export default function WorkshopPage() {
const { siteConfig } = useDocusaurusContext();
@@ -16,7 +17,7 @@ export default function WorkshopPage() {
<BrowserOnly fallback={<WorkshopListingFallback />}>
{() => (
<WorkshopErrorBoundary>
<WorkshopApp workshopUrl={configuredWorkshopUrl || window.location.origin} />
<WorkshopApp workshopUrl={getRuntimeWorkshopApiUrl(configuredWorkshopUrl)} />
</WorkshopErrorBoundary>
)}
</BrowserOnly>
+1
View File
@@ -0,0 +1 @@
globalThis.homarrRuntimeConfig = Object.freeze({});
+31 -17
View File
@@ -1,28 +1,42 @@
# Create T3 App
# Homarr web application
This is a [T3 Stack](https://create.t3.gg/) project bootstrapped with `create-t3-app`.
This workspace contains Homarr's Next.js application. It consumes the shared API, authentication, database, board,
widget, translation, and UI packages from this monorepo.
## What's next? How do I make an app with this?
Run commands from the repository root:
We try to keep this project as simple as possible, so you can start with just the scaffolding we set up for you, and add additional things later when they become necessary.
```sh
pnpm install --frozen-lockfile
cp .env.example .env
```
If you are not familiar with the different technologies used in this project, please refer to the respective docs. If you still are in the wind, please join our [Discord](https://t3.gg/discord) and ask for help.
Keep infrastructure running in the first terminal:
- [Next.js](https://nextjs.org)
- [NextAuth.js](https://next-auth.js.org)
- [Drizzle](https://orm.drizzle.team)
- [Tailwind CSS](https://tailwindcss.com)
- [tRPC](https://trpc.io)
```sh
pnpm docker:dev
```
## Learn More
Apply migrations and start the application in a second terminal:
To learn more about the [T3 Stack](https://create.t3.gg/), take a look at the following resources:
```sh
pnpm db:migration:sqlite:run
pnpm dev
```
- [Documentation](https://create.t3.gg/)
- [Learn the T3 Stack](https://create.t3.gg/en/faq#what-learning-resources-are-currently-available) — Check out these awesome tutorials
The app listens on `http://127.0.0.1:3000`. Configure an absolute writable `DB_URL`, `AUTH_SECRET`, and
`SECRET_ENCRYPTION_KEY` in `.env` before first startup.
You can check out the [create-t3-app GitHub repository](https://github.com/t3-oss/create-t3-app) — your feedback and contributions are welcome!
To test Custom Widgets against a local Community Workshop, run `pnpm dev:workshop` in another terminal and set:
## How do I deploy this?
```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
```
Follow our deployment guides for [Vercel](https://create.t3.gg/en/deployment/vercel) and [Docker](https://create.t3.gg/en/deployment/docker) for more information.
Server-rendered runtime configuration exposes those URLs to the browser, so changing a production container's
environment does not require rebuilding the Next.js bundle.
See the repository [`README.md`](../../README.md) for validation commands and
[`apps/docs/docs/advanced/development/getting-started.mdx`](../docs/docs/advanced/development/getting-started.mdx) for
the full contributor setup.
@@ -9,6 +9,7 @@ import "~/styles/prismjs.scss";
import { IconInfoCircle } from "@tabler/icons-react";
import { useForm } from "@homarr/form";
import { useSession } from "@homarr/auth/client";
import { useI18n, useScopedI18n } from "@homarr/translation/client";
import { WorkshopCssImportButton } from "~/components/workshop/workshop-css-import-button";
@@ -22,6 +23,8 @@ interface Props {
}
export const CustomCssSettingsContent = ({ board }: Props) => {
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const t = useI18n();
const customCssT = useScopedI18n("board.field.customCss");
const { mutate: savePartialSettings, isPending } = useSavePartialSettingsMutation(board);
@@ -48,7 +51,7 @@ export const CustomCssSettingsContent = ({ board }: Props) => {
</Alert>
<Group justify="space-between">
<WorkshopCssImportButton onImport={(css) => form.setFieldValue("customCss", css)} />
{isAdmin ? <WorkshopCssImportButton onImport={(css) => form.setFieldValue("customCss", css)} /> : <span />}
<Button type="submit" loading={isPending}>
{t("common.action.saveChanges")}
</Button>
@@ -1,5 +1,10 @@
import type { Metadata } from "next";
import { redirect } from "next/navigation";
import { auth } from "@homarr/auth/next";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
import { CustomWidgetConfigurationEntry } from "./configuration-entry";
export const metadata: Metadata = {
@@ -8,6 +13,9 @@ export const metadata: Metadata = {
};
export default async function CustomWidgetConfigurationPage({ params }: { params: Promise<{ token: string }> }) {
const session = await auth();
if (!session?.user.permissions.includes("admin")) redirect(session ? "/" : "/auth/login");
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const { token } = await params;
return <CustomWidgetConfigurationEntry token={token} />;
}
+12 -3
View File
@@ -24,7 +24,7 @@ import { SettingsProvider } from "@homarr/settings";
import { SpotlightProvider } from "@homarr/spotlight";
import type { SupportedLanguage } from "@homarr/translation";
import { isLocaleRTL, isLocaleSupported } from "@homarr/translation";
import { WORKSHOP_API_URL } from "@homarr/workshop/schema";
import { resolveHomarrUrlConfig } from "@homarr/workshop/schema";
import { Analytics } from "~/components/layout/analytics";
import { CrowdinLiveTranslation } from "~/components/layout/crowdin-live-translation";
@@ -54,7 +54,7 @@ export const generateMetadata = async (): Promise<Metadata> => ({
title: "Homarr Dashboard",
description:
"A self-hosted dashboard for the *arr stack and your entire homelab. Integrates with 50+ services, real-time widgets, no config files.",
url: "https://homarr.dev",
url: env.HOMARR_WEBSITE_URL,
siteName: "Homarr",
},
icons: {
@@ -89,6 +89,11 @@ export default async function Layout(props: {
const serverSettings = await getServerSettingsAsync(db);
const colorScheme = await getCurrentColorSchemeAsync();
const direction = isLocaleRTL((await props.params).locale) ? "rtl" : "ltr";
const publicUrls = resolveHomarrUrlConfig({
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
workshopApiUrl: env.WORKSHOP_API_URL,
workshopWebUrl: env.WORKSHOP_WEB_URL,
});
const StackedProvider = composeWrappers([
(innerProps) => {
@@ -141,7 +146,11 @@ export default async function Layout(props: {
suppressHydrationWarning
>
<head>
<meta name="homarr-workshop-api-url" content={env.WORKSHOP_API_URL ?? WORKSHOP_API_URL} />
<meta name="homarr-website-url" content={publicUrls.homarrWebsiteUrl} />
<meta name="homarr-workshop-api-url" content={publicUrls.workshopApiUrl} />
<meta name="homarr-workshop-web-url" content={publicUrls.workshopWebUrl} />
<meta name="homarr-custom-widgets-enabled" content={String(env.CUSTOM_WIDGETS_ENABLED !== false)} />
<meta name="homarr-workshop-enabled" content={String(env.WORKSHOP_ENABLED !== false)} />
<SearchEngineOptimization />
<CrowdinLiveTranslation locale={locale} />
</head>
@@ -23,6 +23,7 @@ import { useScopedI18n } from "@homarr/translation/client";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { WorkshopPublishModal } from "~/components/workshop/workshop-publish-modal";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
const iconProps = { size: 16, stroke: 1.5 };
@@ -36,9 +37,9 @@ interface WidgetRef {
export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
const t = useScopedI18n("customWidget");
const workshopEnabled = useRuntimeFeature("workshop");
const { openConfirmModal } = useConfirmModal();
const deleteMutation = clientApi.customWidget.delete.useMutation();
const deleteLegacyMutation = clientApi.customWidget.deleteLegacy.useMutation();
const duplicateMutation = clientApi.customWidget.duplicate.useMutation();
const utils = clientApi.useUtils();
const [publishOpened, publishControls] = useDisclosure(false);
@@ -146,10 +147,6 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
showErrorNotification({ title: t("action.delete"), message: t("notification.deleteError") });
},
};
if (widget.migrationRequired) {
deleteLegacyMutation.mutate({ id: widget.id }, callbacks);
return;
}
deleteMutation.mutate({ id: widget.id }, callbacks);
},
});
@@ -176,9 +173,11 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
<Menu.Item onClick={() => void handleExport()} leftSection={<IconDownload {...iconProps} />}>
{t("action.export")}
</Menu.Item>
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
{workshopEnabled && (
<Menu.Item onClick={publishControls.open} leftSection={<IconBuildingStore {...iconProps} />}>
{t("action.publishWorkshop")}
</Menu.Item>
)}
<Menu.Divider />
</>
)}
@@ -196,17 +195,21 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
<Menu.Divider />
</>
)}
<Menu.Item
color="red"
leftSection={<IconTrash {...iconProps} />}
onClick={handleDelete}
disabled={deleteMutation.isPending || deleteLegacyMutation.isPending}
>
{t("action.delete")}
</Menu.Item>
{!widget.migrationRequired && (
<Menu.Item
color="red"
leftSection={<IconTrash {...iconProps} />}
onClick={handleDelete}
disabled={deleteMutation.isPending}
>
{t("action.delete")}
</Menu.Item>
)}
</Menu.Dropdown>
</Menu>
{widget.valid && <WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />}
{widget.valid && workshopEnabled && (
<WorkshopPublishModal opened={publishOpened} onClose={publishControls.close} widget={widget} />
)}
{widget.migrationRequired && (
<>
<input
@@ -5,7 +5,9 @@ import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { catchTrpcNotFound } from "~/errors/trpc-catch-error";
import { env } from "~/env";
import { CustomWidgetBetaBanner } from "../../_beta-banner";
import { CustomWidgetForm } from "../../_custom-widget-form";
import { FormErrorBoundary } from "../../_form-error-boundary";
@@ -16,9 +18,10 @@ interface EditCustomWidgetPageProps {
export default async function EditCustomWidgetPage(props: EditCustomWidgetPageProps) {
const session = await auth();
if (!session || !session.user.permissions.includes("custom-widget-manage")) {
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const params = await props.params;
const definition = await api.customWidget.get({ id: params.id }).catch(catchTrpcNotFound);
@@ -5,15 +5,18 @@ import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server";
import { DynamicBreadcrumb } from "~/components/navigation/dynamic-breadcrumb";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
import { CustomWidgetBetaBanner } from "../_beta-banner";
import { CustomWidgetForm } from "../_custom-widget-form";
import { FormErrorBoundary } from "../_form-error-boundary";
export default async function NewCustomWidgetPage() {
const session = await auth();
if (!session || !session.user.permissions.includes("custom-widget-manage")) {
if (!session || !session.user.permissions.includes("admin")) {
redirect("/manage/custom-widgets");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const t = await getScopedI18n("customWidget");
@@ -9,6 +9,8 @@ import { Link } from "@homarr/ui";
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
import { MobileAffixButton } from "~/components/manage/mobile-affix-button";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
import { CustomWidgetBetaBanner } from "./_beta-banner";
import { WorkshopInstallButton } from "~/components/workshop/workshop-install-button";
import { ImportCustomWidgetButton } from "./_import-custom-widget-button";
@@ -17,9 +19,10 @@ import { CustomWidgetList } from "./_custom-widget-list";
export default async function CustomWidgetsPage() {
const session = await auth();
if (!session || !session.user.permissions.includes("custom-widget-manage")) {
if (!session || !session.user.permissions.includes("admin")) {
redirect(session ? "/" : "/auth/login");
}
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const definitions = await api.customWidget.list();
const t = await getScopedI18n("customWidget");
@@ -5,9 +5,13 @@ import { api } from "@homarr/api/server";
import { auth } from "@homarr/auth/next";
import CustomJsxDisplay from "@homarr/widgets/custom-api/custom-jsx-display";
import { CustomWidgetsUnavailable } from "~/components/custom-widgets/custom-widgets-unavailable";
import { env } from "~/env";
export default async function CustomWidgetPreviewPage({ params }: { params: Promise<{ id: string }> }) {
const session = await auth();
if (!session?.user.permissions.includes("custom-widget-manage")) redirect("/");
if (!session?.user.permissions.includes("admin")) redirect("/");
if (env.CUSTOM_WIDGETS_ENABLED === false) return <CustomWidgetsUnavailable />;
const { id } = await params;
const preview = await api.customWidget.previewGet({ sessionId: id }).catch(() => null);
if (!preview) notFound();
@@ -41,6 +41,7 @@ import type { NavigationLink } from "~/components/layout/navigation";
import { MainNavigation } from "~/components/layout/navigation";
import { ClientShell } from "~/components/layout/shell";
import { ManageTourProvider } from "~/components/onboarding/manage-tour";
import { env as nextEnv } from "~/env";
export default async function ManageLayout({ children }: PropsWithChildren) {
const t = await getScopedI18n("management.navbar");
@@ -79,13 +80,16 @@ export default async function ManageLayout({ children }: PropsWithChildren) {
icon: IconApi,
href: "/manage/custom-widgets",
label: t("items.customWidgets"),
hidden: !session?.user.permissions.includes("custom-widget-manage"),
hidden: nextEnv.CUSTOM_WIDGETS_ENABLED === false || !session?.user.permissions.includes("admin"),
},
{
icon: IconBuildingStore,
href: "/manage/workshop",
label: t("items.workshop"),
hidden: !session?.user.permissions.includes("custom-widget-manage"),
hidden:
nextEnv.CUSTOM_WIDGETS_ENABLED === false ||
nextEnv.WORKSHOP_ENABLED === false ||
!session?.user.permissions.includes("admin"),
},
{
icon: IconSearch,
@@ -1,17 +1,42 @@
import { redirect } from "next/navigation";
import { Button } from "@mantine/core";
import { IconExternalLink } from "@tabler/icons-react";
import { auth } from "@homarr/auth/next";
import { getScopedI18n } from "@homarr/translation/server";
import { resolveHomarrUrlConfig } from "@homarr/workshop/schema";
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
import { WorkshopInstaller } from "~/components/workshop/workshop-installer";
import { env } from "~/env";
export default async function WorkshopPage() {
const session = await auth();
if (!session?.user.permissions.includes("custom-widget-manage")) redirect(session ? "/" : "/auth/login");
if (!session?.user.permissions.includes("admin")) redirect(session ? "/" : "/auth/login");
if (env.CUSTOM_WIDGETS_ENABLED === false || env.WORKSHOP_ENABLED === false) redirect("/");
const t = await getScopedI18n("workshop");
const { workshopWebUrl } = resolveHomarrUrlConfig({
homarrWebsiteUrl: env.HOMARR_WEBSITE_URL,
workshopApiUrl: env.WORKSHOP_API_URL,
workshopWebUrl: env.WORKSHOP_WEB_URL,
});
return (
<ManagePageLayout title={t("title")} size="xl">
<ManagePageLayout
title={t("title")}
size="xl"
primaryAction={
<Button
component="a"
href={workshopWebUrl}
target="_blank"
rel="noopener noreferrer"
variant="default"
leftSection={<IconExternalLink size={16} />}
>
{t("openCommunity")}
</Button>
}
>
<WorkshopInstaller />
</ManagePageLayout>
);
+2 -2
View File
@@ -5,7 +5,7 @@ import { createOpenApiFetchHandler } from "trpc-to-openapi";
import { createTRPCContext } from "@homarr/api";
import { openApiRouter } from "@homarr/api/open-api";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
@@ -14,7 +14,7 @@ const logger = createLogger({ module: "trpcOpenApiRoute" });
const handlerAsync = async (req: NextRequest) => {
const apiKeyHeaderValue = req.headers.get(API_KEY_HEADER_NAME);
const ipAddress = ipAddressFromHeaders(req.headers);
const ipAddress = rateLimitAddressFromHeaders(req.headers);
const { ua } = userAgent(req);
logger.info(
@@ -0,0 +1,40 @@
// @vitest-environment node
import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
auth: vi.fn(),
env: { CUSTOM_WIDGETS_ENABLED: true },
}));
vi.mock("@homarr/auth/next", () => ({ auth: mocks.auth }));
vi.mock("~/env", () => ({ env: mocks.env }));
import { requireCustomWidgetAdmin } from "./admin";
beforeEach(() => {
mocks.env.CUSTOM_WIDGETS_ENABLED = true;
mocks.auth.mockResolvedValue({ user: { permissions: ["admin"] } });
});
describe("Custom Widget HTTP resource access", () => {
test("allows authenticated administrators", async () => {
await expect(requireCustomWidgetAdmin()).resolves.toBeNull();
});
test.each([
["anonymous users", null],
["authenticated non-admins", { user: { permissions: ["board-modify-all"] } }],
])("denies %s", async (_label, session) => {
mocks.auth.mockResolvedValue(session);
const response = await requireCustomWidgetAdmin();
expect(response?.status).toBe(403);
});
test("returns an unavailable response when the emergency switch is off", async () => {
mocks.env.CUSTOM_WIDGETS_ENABLED = false;
const response = await requireCustomWidgetAdmin();
expect(response?.status).toBe(503);
await expect(response?.json()).resolves.toMatchObject({ error: expect.stringContaining("temporarily disabled") });
});
});
@@ -0,0 +1,19 @@
import { NextResponse } from "next/server";
import { auth } from "@homarr/auth/next";
import { env } from "~/env";
export const requireCustomWidgetAdmin = async (): Promise<NextResponse | null> => {
const session = await auth();
if (!session?.user.permissions.includes("admin")) {
return NextResponse.json({ error: "Administrator access is required." }, { status: 403 });
}
if (env.CUSTOM_WIDGETS_ENABLED === false) {
return NextResponse.json(
{ error: "Custom Widgets are temporarily disabled by the server administrator." },
{ status: 503 },
);
}
return null;
};
@@ -2,9 +2,11 @@ import { NextResponse } from "next/server";
import { CUSTOM_WIDGET_MCP_AUTHORING_PROMPT } from "@homarr/custom-widgets/authoring-prompt";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json({
version: 2,
prompt: CUSTOM_WIDGET_MCP_AUTHORING_PROMPT,
@@ -2,8 +2,10 @@ import { NextResponse } from "next/server";
import { getCustomWidgetComponentCatalog } from "@homarr/custom-widgets/authoring-resources";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json(getCustomWidgetComponentCatalog());
}
@@ -6,16 +6,17 @@ import {
completeCustomWidgetConfigurationRequest,
configurePreviewSessionSource,
getCustomWidgetConfigurationRequest,
invalidateCustomWidgetResponseCache,
parseStoredCustomWidgetDefinition,
releaseCustomWidgetConfigurationRequest,
serializeCustomWidgetDefinition,
} from "@homarr/api/custom-widget-configuration";
import { encryptSecret } from "@homarr/common/server";
import { invalidateCustomWidgetResponseCache } from "@homarr/custom-widgets/server";
import { customWidgetSourceSchema, hasSameCustomWidgetSourceAuthentication } from "@homarr/custom-widgets/core";
import { and, db, eq, handleTransactionsAsync } from "@homarr/db";
import { customWidgetDefinitions, customWidgetSecrets } from "@homarr/db/schema";
import { requireCustomWidgetAdmin } from "../../admin";
import { readConfigurationRequestBody } from "../body";
interface RouteContext {
@@ -23,6 +24,8 @@ interface RouteContext {
}
export async function GET(_request: NextRequest, context: RouteContext) {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
const { token } = await context.params;
const request = await getCustomWidgetConfigurationRequest(token);
if (!request)
@@ -41,6 +44,8 @@ export async function GET(_request: NextRequest, context: RouteContext) {
}
export async function POST(request: NextRequest, context: RouteContext) {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
const { token } = await context.params;
const pending = await getCustomWidgetConfigurationRequest(token);
if (!pending || pending.status !== "pending") {
@@ -92,7 +97,7 @@ export async function POST(request: NextRequest, context: RouteContext) {
sourceResult.data,
secrets,
);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
await invalidateCustomWidgetResponseCache([`custom-jsx:preview:${claimed.target.id}:`]);
} else {
const definition = await db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, claimed.target.id),
@@ -2,8 +2,10 @@ import { NextResponse } from "next/server";
import { getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json(getCustomWidgetJsonSchema());
}
@@ -2,8 +2,10 @@ import { NextResponse } from "next/server";
import { getCustomWidgetSkill } from "@homarr/custom-widgets/authoring-resources";
export const dynamic = "force-static";
import { requireCustomWidgetAdmin } from "../admin";
export function GET() {
export async function GET() {
const denied = await requireCustomWidgetAdmin();
if (denied) return denied;
return NextResponse.json(getCustomWidgetSkill());
}
@@ -4,6 +4,10 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
const mocks = vi.hoisted(() => ({
authenticate: vi.fn(),
rateLimitAddress: vi.fn(() => "127.0.0.1"),
toolProcedure: vi.fn(),
loggerWarn: vi.fn(),
env: { CUSTOM_WIDGETS_ENABLED: true, WORKSHOP_ENABLED: true },
buildPrompt: vi.fn((request?: string, documentationUrl?: string) =>
[`Request: ${request ?? ""}`, `Documentation: ${documentationUrl ?? ""}`].join("\n"),
),
@@ -13,16 +17,16 @@ const mocks = vi.hoisted(() => ({
vi.mock("next/server", () => ({ userAgent: () => ({ ua: "MCP route test" }) }));
vi.mock("@homarr/api/mcp", () => ({
createTRPCContext: vi.fn(() => ({})),
mcpRouter: { createCaller: vi.fn(() => ({})) },
mcpRouter: { createCaller: vi.fn(() => ({ board: { getAllBoards: mocks.toolProcedure } })) },
}));
vi.mock("@homarr/auth/api-key", () => ({
API_KEY_HEADER_NAME: "ApiKey",
getSessionFromApiKeyAsync: mocks.authenticate,
}));
vi.mock("@homarr/common", () => ({ extractBaseUrlFromHeaders: () => "http://localhost" }));
vi.mock("@homarr/common/server", () => ({ ipAddressFromHeaders: () => "127.0.0.1" }));
vi.mock("@homarr/common/server", () => ({ rateLimitAddressFromHeaders: mocks.rateLimitAddress }));
vi.mock("@homarr/core/infrastructure/logs", () => ({
createLogger: () => ({ info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
createLogger: () => ({ info: vi.fn(), warn: mocks.loggerWarn, error: vi.fn() }),
}));
vi.mock("@homarr/custom-widgets/authoring-prompt", () => ({ buildCustomWidgetMcpPrompt: mocks.buildPrompt }));
vi.mock("@homarr/custom-widgets/authoring-resources", () => ({
@@ -35,8 +39,30 @@ vi.mock("@homarr/custom-widgets/core", () => ({
getCustomWidgetJsonSchema: () => ({ type: "object", title: "Custom Widget" }),
}));
vi.mock("@homarr/db", () => ({ db: {} }));
vi.mock("~/env", () => ({ env: mocks.env }));
vi.mock("~/versions/package-reader", () => ({ getPackageVersion: () => "test-version" }));
vi.mock("../_extract-tools", () => ({ extractMcpTools: () => [] }));
vi.mock("../_extract-tools", () => ({
extractMcpTools: () => [
{
name: "board_getAllBoards",
description: "List boards",
pathInRouter: ["board", "getAllBoards"],
inputSchema: { type: "object", properties: {} },
},
{
name: "customWidget_list",
description: "List Custom Widgets",
pathInRouter: ["customWidget", "list"],
inputSchema: { type: "object", properties: {} },
},
{
name: "customWidget_workshopSearch",
description: "Search Workshop",
pathInRouter: ["customWidget", "workshopSearch"],
inputSchema: { type: "object", properties: {} },
},
],
}));
import { POST } from "./route";
@@ -48,9 +74,16 @@ interface JsonRpcResponse {
}
beforeEach(() => {
mocks.authenticate.mockResolvedValue({ user: { id: "user-1" } });
mocks.authenticate.mockResolvedValue({ user: { id: "user-1", permissions: ["admin"] } });
mocks.env.CUSTOM_WIDGETS_ENABLED = true;
mocks.env.WORKSHOP_ENABLED = true;
mocks.buildPrompt.mockClear();
mocks.getComponent.mockClear();
mocks.rateLimitAddress.mockClear();
mocks.rateLimitAddress.mockReturnValue("127.0.0.1");
mocks.toolProcedure.mockReset();
mocks.toolProcedure.mockResolvedValue([]);
mocks.loggerWarn.mockClear();
});
async function callMcp(method: string, params: Record<string, unknown> = {}, id = 1) {
@@ -60,6 +93,8 @@ async function callMcp(method: string, params: Record<string, unknown> = {}, id
Accept: "application/json, text/event-stream",
ApiKey: "key.secret",
"Content-Type": "application/json",
"X-Forwarded-For": "198.51.100.10",
"X-Real-IP": "127.0.0.1",
},
body: JSON.stringify({ jsonrpc: "2.0", id, method, params }),
});
@@ -91,6 +126,7 @@ describe("authenticated MCP prompt protocol", () => {
serverInfo: { name: "homarr", version: "test-version" },
});
expect(mocks.authenticate).toHaveBeenCalledWith({}, "key.secret", "127.0.0.1", "MCP route test");
expect(mocks.rateLimitAddress).toHaveBeenCalledWith(expect.any(Headers));
});
test("lists and interpolates the custom-widget authoring prompt", async () => {
@@ -178,6 +214,55 @@ describe("authenticated MCP resource protocol", () => {
});
});
describe("non-admin MCP discovery", () => {
test("does not list or expose Custom Widget tools, prompts or resources", async () => {
mocks.authenticate.mockResolvedValue({ user: { id: "user-1", permissions: ["board-view-all"] } });
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
]);
const prompts = await callMcp("prompts/list");
expect(prompts.body.result).toEqual({ prompts: [] });
const resources = await callMcp("resources/list");
expect(resources.body.result).toEqual({ resources: [] });
const templates = await callMcp("resources/templates/list");
expect(templates.body.result).toEqual({ resourceTemplates: [] });
const prompt = await callMcp("prompts/get", { name: "homarr-custom-widget-author" });
expect(prompt.body.result).toBeUndefined();
expect(prompt.body.error).toBeDefined();
const resource = await callMcp("resources/read", { uri: "homarr://custom-widgets/schema" });
expect(resource.body.result).toBeUndefined();
expect(resource.body.error).toBeDefined();
});
});
describe("MCP emergency switches", () => {
test("removes Custom Widget authoring discovery when Custom Widgets are disabled", async () => {
mocks.env.CUSTOM_WIDGETS_ENABLED = false;
expect((await callMcp("prompts/list")).body.result).toEqual({ prompts: [] });
expect((await callMcp("resources/list")).body.result).toEqual({ resources: [] });
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
]);
});
test("removes only Workshop tools when Workshop is disabled", async () => {
mocks.env.WORKSHOP_ENABLED = false;
const tools = await callMcp("tools/list");
expect(((tools.body.result?.tools ?? []) as Array<{ name: string }>).map(({ name }) => name)).toEqual([
"board_getAllBoards",
"customWidget_list",
]);
});
});
describe("MCP protocol errors", () => {
test.each([
["prompts/get", { name: "unknown" }],
@@ -193,4 +278,23 @@ describe("MCP protocol errors", () => {
expect(body.result).toBeUndefined();
expect(body.error).toEqual(expect.objectContaining({ code: -32603, message: expect.any(String) }));
});
test("does not log sensitive tool error messages", async () => {
const failure = Object.assign(new Error("request to https://user:secret@example.test/private failed"), {
code: "BAD_GATEWAY",
});
mocks.toolProcedure.mockRejectedValue(failure);
const { body } = await callMcp("tools/call", { name: "board_getAllBoards", arguments: {} });
expect(JSON.stringify(body)).not.toContain("user:secret");
expect(mocks.loggerWarn).toHaveBeenCalledWith("MCP tool execution failed", {
tool: "board_getAllBoards",
errorName: "Error",
errorCode: "BAD_GATEWAY",
});
const metadata = mocks.loggerWarn.mock.calls.at(-1)?.[1] as Record<string, unknown>;
expect(metadata).not.toHaveProperty("error");
expect(metadata).not.toHaveProperty("message");
});
});
@@ -16,7 +16,7 @@ import {
import { createTRPCContext, mcpRouter } from "@homarr/api/mcp";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { extractBaseUrlFromHeaders } from "@homarr/common";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { buildCustomWidgetMcpPrompt } from "@homarr/custom-widgets/authoring-prompt";
import {
@@ -27,6 +27,7 @@ import {
import { customJsxExamples, getCustomWidgetJsonSchema } from "@homarr/custom-widgets/core";
import { db } from "@homarr/db";
import { env } from "~/env";
import { getPackageVersion } from "~/versions/package-reader";
import { extractMcpTools } from "../_extract-tools";
@@ -85,7 +86,12 @@ function clearAuthFailures(ip: string | null) {
authFailures.delete(ip ?? "unknown");
}
const callerStorage = new AsyncLocalStorage<ReturnType<typeof mcpRouter.createCaller>>();
interface McpCallerContext {
caller: ReturnType<typeof mcpRouter.createCaller>;
isAdmin: boolean;
}
const callerStorage = new AsyncLocalStorage<McpCallerContext>();
const emptyObjectSchema = {
type: "object" as const,
@@ -113,6 +119,23 @@ function getTools() {
return toolsCache;
}
function getVisibleTools() {
const tools = getTools();
if (!isCustomWidgetMcpEnabled()) {
return tools.filter((tool) => !tool.name.startsWith("customWidget_"));
}
return env.WORKSHOP_ENABLED === false
? tools.filter((tool) => !tool.name.startsWith("customWidget_workshop"))
: tools;
}
function requireCustomWidgetMcpAdmin() {
if (!isCustomWidgetMcpEnabled()) throw new Error("Resource not found");
}
const isCustomWidgetMcpEnabled = () =>
Boolean(callerStorage.getStore()?.isAdmin) && env.CUSTOM_WIDGETS_ENABLED !== false;
const SAFE_ERROR_MESSAGES: Record<string, string> = {
UNAUTHORIZED: "You do not have permission to perform this action",
FORBIDDEN: "Access denied",
@@ -184,19 +207,22 @@ If \`hasUseAccess\` is false, the API key owner lacks permission for that integr
const mcpHandler = createMcpHandler(
(server) => {
server.server.setRequestHandler(ListPromptsRequestSchema, () => ({
prompts: [
{
name: "homarr-custom-widget-author",
description: "Author and iterate on one Homarr Custom JSX v2 widget.",
arguments: [
{ name: "request", description: "The widget the user wants.", required: false },
{ name: "documentationUrl", description: "External API documentation URL.", required: false },
],
},
],
prompts: isCustomWidgetMcpEnabled()
? [
{
name: "homarr-custom-widget-author",
description: "Author and iterate on one Homarr Custom JSX v2 widget.",
arguments: [
{ name: "request", description: "The widget the user wants.", required: false },
{ name: "documentationUrl", description: "External API documentation URL.", required: false },
],
},
]
: [],
}));
server.server.setRequestHandler(GetPromptRequestSchema, (request) => {
requireCustomWidgetMcpAdmin();
if (request.params.name !== "homarr-custom-widget-author") throw new Error("Prompt not found");
return {
description: "Current Homarr Custom Widget authoring workflow.",
@@ -216,36 +242,49 @@ const mcpHandler = createMcpHandler(
});
server.server.setRequestHandler(ListResourcesRequestSchema, () => ({
resources: [
{ uri: "homarr://custom-widgets/schema", name: "Custom Widget schema", mimeType: "application/schema+json" },
{ uri: "homarr://custom-widgets/components", name: "Custom Widget components", mimeType: "application/json" },
{ uri: "homarr://custom-widgets/skill", name: "Custom Widget skill", mimeType: "text/markdown" },
...customJsxExamples.map((example) => ({
uri: `homarr://custom-widgets/examples/${example.id}`,
name: `Custom Widget example: ${example.title}`,
mimeType: "application/json",
})),
],
resources: isCustomWidgetMcpEnabled()
? [
{
uri: "homarr://custom-widgets/schema",
name: "Custom Widget schema",
mimeType: "application/schema+json",
},
{
uri: "homarr://custom-widgets/components",
name: "Custom Widget components",
mimeType: "application/json",
},
{ uri: "homarr://custom-widgets/skill", name: "Custom Widget skill", mimeType: "text/markdown" },
...customJsxExamples.map((example) => ({
uri: `homarr://custom-widgets/examples/${example.id}`,
name: `Custom Widget example: ${example.title}`,
mimeType: "application/json",
})),
]
: [],
}));
server.server.setRequestHandler(ListResourceTemplatesRequestSchema, () => ({
resourceTemplates: [
{
uriTemplate: "homarr://custom-widgets/components/{name}",
name: "Custom Widget component",
description: "Metadata for one installed Custom Widget component.",
mimeType: "application/json",
},
{
uriTemplate: "homarr://custom-widgets/examples/{name}",
name: "Custom Widget example",
description: "One canonical Custom Widget example.",
mimeType: "application/json",
},
],
resourceTemplates: isCustomWidgetMcpEnabled()
? [
{
uriTemplate: "homarr://custom-widgets/components/{name}",
name: "Custom Widget component",
description: "Metadata for one installed Custom Widget component.",
mimeType: "application/json",
},
{
uriTemplate: "homarr://custom-widgets/examples/{name}",
name: "Custom Widget example",
description: "One canonical Custom Widget example.",
mimeType: "application/json",
},
]
: [],
}));
server.server.setRequestHandler(ReadResourceRequestSchema, (request) => {
requireCustomWidgetMcpAdmin();
const { uri } = request.params;
let text: string;
let mimeType = "application/json";
@@ -271,12 +310,12 @@ const mcpHandler = createMcpHandler(
});
server.server.setRequestHandler(ListToolsRequestSchema, () => ({
tools: getTools(),
tools: getVisibleTools(),
}));
server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const tools = getTools();
const tools = getVisibleTools();
const tool = tools.find((t) => t.name === name);
if (!tool) {
@@ -286,8 +325,8 @@ const mcpHandler = createMcpHandler(
};
}
const caller = callerStorage.getStore();
if (!caller) {
const callerContext = callerStorage.getStore();
if (!callerContext) {
return {
content: [{ type: "text" as const, text: "Authentication context not available" }],
isError: true,
@@ -295,7 +334,7 @@ const mcpHandler = createMcpHandler(
}
try {
const procedure = tool.pathInRouter.reduce<any>((acc, part) => acc?.[part], caller);
const procedure = tool.pathInRouter.reduce<any>((acc, part) => acc?.[part], callerContext.caller);
if (typeof procedure !== "function") {
return {
content: [{ type: "text" as const, text: `Tool "${name}" is not callable` }],
@@ -311,7 +350,9 @@ const mcpHandler = createMcpHandler(
const message = sanitizeErrorMessage(error);
logger.warn("MCP tool execution failed", {
tool: name,
error: error instanceof Error ? error.message : String(error),
errorName: error instanceof Error ? error.name : "UnknownError",
errorCode:
error instanceof Error && "code" in error && typeof error.code === "string" ? error.code : undefined,
});
return {
content: [{ type: "text" as const, text: JSON.stringify({ error: message }) }],
@@ -353,7 +394,7 @@ function jsonErrorResponse(status: number, body: Record<string, string>, extraHe
const handler = async (req: NextRequest) => {
const apiKeyValue = extractApiKeyValue(req);
const ipAddress = ipAddressFromHeaders(req.headers);
const ipAddress = rateLimitAddressFromHeaders(req.headers);
const { ua } = userAgent(req);
if (!checkAuthRateLimit(ipAddress)) {
@@ -398,7 +439,9 @@ const handler = async (req: NextRequest) => {
const ctx = createTRPCContext({ session, headers: req.headers });
const caller = mcpRouter.createCaller(ctx);
return callerStorage.run(caller, () => mcpHandler(req as unknown as Request));
return callerStorage.run({ caller, isAdmin: session.user.permissions.includes("admin") }, () =>
mcpHandler(req as unknown as Request),
);
};
export { handler as GET, handler as POST, handler as DELETE };
+2 -2
View File
@@ -5,7 +5,7 @@ import { appRouter, createTRPCContext } from "@homarr/api";
import { trpcPath } from "@homarr/api/shared";
import { API_KEY_HEADER_NAME, getSessionFromApiKeyAsync } from "@homarr/auth/api-key";
import { auth } from "@homarr/auth/next";
import { ipAddressFromHeaders } from "@homarr/common/server";
import { rateLimitAddressFromHeaders } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db } from "@homarr/db";
@@ -34,7 +34,7 @@ export function OPTIONS() {
const handler = auth(async (req) => {
// Try API key auth first, fall back to session cookie
const apiKeyHeader = req.headers.get(API_KEY_HEADER_NAME);
const ipAddress = ipAddressFromHeaders(req.headers);
const ipAddress = rateLimitAddressFromHeaders(req.headers);
const { ua } = userAgent(req);
@@ -30,6 +30,8 @@ export const BoardItemMenu = (props: BoardItemMenuProps) => {
};
const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuProps) => {
const { data: session } = useSession();
const canDuplicate = item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
const refResetErrorBoundaryOnNextRender = useRef(false);
const tItem = useScopedI18n("item");
const t = useI18n();
@@ -135,9 +137,11 @@ const BoardItemMenuInner = ({ offset, item, resetErrorBoundary }: BoardItemMenuP
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Item leftSection={<IconCopy size={16} />} onClick={() => duplicateItem({ itemId: item.id })}>
{tItem("action.duplicate")}
</Menu.Item>
{canDuplicate && (
<Menu.Item leftSection={<IconCopy size={16} />} onClick={() => duplicateItem({ itemId: item.id })}>
{tItem("action.duplicate")}
</Menu.Item>
)}
<Menu.Divider />
<Menu.Label c="red.6">{t("common.dangerZone")}</Menu.Label>
<Menu.Item c="red.6" leftSection={<IconTrash size={16} />} onClick={openRemoveModal}>
@@ -3,6 +3,7 @@ import { Avatar, Box, Button, Card, Center, Divider, Group, Image, Stack, Text,
import { IconApi } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { createId, objectEntries } from "@homarr/common";
import { getIconUrl, getIntegrationName } from "@homarr/definitions";
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
@@ -15,15 +16,23 @@ import { reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/wid
import { WidgetEditModal } from "@homarr/widgets/modals";
import { WorkshopInstallButton } from "~/components/workshop/workshop-install-button";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
import { useItemActions } from "./item-actions";
export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, innerProps }) => {
const { data: session } = useSession();
const isAdmin = session?.user.permissions.includes("admin") ?? false;
const customWidgetsEnabled = useRuntimeFeature("custom-widgets");
const workshopEnabled = useRuntimeFeature("workshop");
const [search, setSearch] = useState("");
const t = useI18n();
const { createItem, updateItemOptions, updateItemAdvancedOptions, updateItemIntegrations } = useItemActions();
const { openModal: openEditModal } = useModalAction(WidgetEditModal);
const { data: integrationData } = clientApi.integration.all.useQuery();
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery({ boardId: innerProps.boardId });
const { data: customWidgetDefs } = clientApi.customWidget.available.useQuery(
{ boardId: innerProps.boardId },
{ enabled: isAdmin && customWidgetsEnabled },
);
const settings = useSettings();
const availableKinds = useMemo(() => new Set((integrationData ?? []).map((i) => i.kind)), [integrationData]);
@@ -160,61 +169,67 @@ export const ItemSelectModal = createModal<{ boardId: string }>(({ actions, inne
/>
))}
<Divider
label={t("customWidget.page.list.title")}
labelPosition="center"
my="sm"
style={{ gridColumn: "1 / -1" }}
/>
{filteredCustomWidgets.map((def) => (
<Card
key={def.id}
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden", "--_hover-opacity": "0" }}
onMouseEnter={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "1")}
onMouseLeave={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "0")}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
{def.iconUrl ? (
<Image src={def.iconUrl} w={22} h={22} fit="contain" style={{ flexShrink: 0, marginTop: 2 }} />
) : (
<IconApi size={22} style={{ flexShrink: 0, marginTop: 2 }} />
)}
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
{def.name}
</Text>
</Group>
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{def.description ?? ""}
</Text>
</Stack>
<Box
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
style={{
opacity: "var(--_hover-opacity)",
transition: "opacity 150ms ease",
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={() => handleAddCustomWidget(def)} variant="light" size="xs" fullWidth>
{t("item.create.addToBoard")}
</Button>
</Box>
</Card>
))}
{isAdmin && customWidgetsEnabled && (
<>
<Divider
label={t("customWidget.page.list.title")}
labelPosition="center"
my="sm"
style={{ gridColumn: "1 / -1" }}
/>
{filteredCustomWidgets.map((def) => (
<Card
key={def.id}
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden", "--_hover-opacity": "0" }}
onMouseEnter={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "1")}
onMouseLeave={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "0")}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
{def.iconUrl ? (
<Image src={def.iconUrl} w={22} h={22} fit="contain" style={{ flexShrink: 0, marginTop: 2 }} />
) : (
<IconApi size={22} style={{ flexShrink: 0, marginTop: 2 }} />
)}
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
{def.name}
</Text>
</Group>
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{def.description ?? ""}
</Text>
</Stack>
<Box
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
style={{
opacity: "var(--_hover-opacity)",
transition: "opacity 150ms ease",
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={() => handleAddCustomWidget(def)} variant="light" size="xs" fullWidth>
{t("item.create.addToBoard")}
</Button>
</Box>
</Card>
))}
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
{workshopEnabled && (
<Box style={{ gridColumn: "1 / -1" }}>
<WorkshopInstallButton fullWidth>{t("workshop.installDialog")}</WorkshopInstallButton>
</Box>
)}
</>
)}
{filteredItems.length === 0 && filteredCustomWidgets.length === 0 && (
{filteredItems.length === 0 && (!isAdmin || !customWidgetsEnabled || filteredCustomWidgets.length === 0) && (
<Center p="xl">
<Text c="dimmed">{t("common.noResults")}</Text>
</Center>
@@ -49,6 +49,7 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
const t = useI18n();
const settings = useSettings();
const isRightClickEnabled = settings.enableRightClickOnWidgets;
const canConfigureWidget = item.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
const { openModal } = useModalAction(WidgetEditModal);
const { openModal: openMoveModal } = useModalAction(ItemMoveModal);
const { openConfirmModal } = useConfirmModal();
@@ -76,9 +77,10 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
type OptionDef = { type: string; skipContextMenu?: boolean };
const toggleOptions = useMemo(() => {
if (!canConfigureWidget) return [];
const rawOptions = currentDefinition.createOptions(settings) as unknown as Record<string, OptionDef>;
return Object.entries(rawOptions).filter(([, def]) => def.type === "switch" && !def.skipContextMenu);
}, [currentDefinition, settings]);
}, [canConfigureWidget, currentDefinition, settings]);
const widgetContextActions = useMemo(() => {
const def = currentDefinition as Record<string, unknown>;
@@ -227,13 +229,15 @@ export const WidgetContextMenu = ({ item, widgetStateRef, children }: WidgetCont
>
{tItem("action.moveResize")}
</Menu.Item>
<Menu.Item
closeMenuOnClick
leftSection={<IconCopy size={16} />}
onClick={() => duplicateItem({ itemId: item.id })}
>
{tItem("action.duplicate")}
</Menu.Item>
{canConfigureWidget && (
<Menu.Item
closeMenuOnClick
leftSection={<IconCopy size={16} />}
onClick={() => duplicateItem({ itemId: item.id })}
>
{tItem("action.duplicate")}
</Menu.Item>
)}
</>
)}
@@ -0,0 +1,16 @@
import { Alert, Container } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { getScopedI18n } from "@homarr/translation/server";
export async function CustomWidgetsUnavailable() {
const t = await getScopedI18n("customWidget.page.disabled");
return (
<Container size="sm" py="xl">
<Alert color="yellow" icon={<IconAlertTriangle size={18} />} title={t("title")}>
{t("message")}
</Alert>
</Container>
);
}
@@ -5,10 +5,14 @@ import { Button, Modal } from "@mantine/core";
import { IconDownload } from "@tabler/icons-react";
import { WorkshopBrowser } from "./workshop-browser";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
export function WorkshopCssImportButton({ onImport }: { onImport(css: string): void }) {
const workshopEnabled = useRuntimeFeature("workshop");
const [opened, setOpened] = useState(false);
if (!workshopEnabled) return null;
return (
<>
<Button type="button" variant="light" leftSection={<IconDownload size={16} />} onClick={() => setOpened(true)}>
@@ -9,6 +9,7 @@ import type { HomarrCustomWidgetV2 } from "@homarr/custom-widgets/core";
import { useScopedI18n } from "@homarr/translation/client";
import { CustomWidgetImportDialog } from "~/components/custom-widgets/custom-widget-import-dialog";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
import { WorkshopBrowser } from "./workshop-browser";
interface WorkshopInstallButtonProps {
@@ -17,6 +18,7 @@ interface WorkshopInstallButtonProps {
}
export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallButtonProps = {}) {
const workshopEnabled = useRuntimeFeature("workshop");
const t = useScopedI18n("workshop");
const stack = useModalsStack(["workshop", "review"]);
const [pendingWidget, setPendingWidget] = useState<HomarrCustomWidgetV2 | null>(null);
@@ -27,6 +29,8 @@ export function WorkshopInstallButton({ children, fullWidth }: WorkshopInstallBu
setPendingWidget(null);
};
if (!workshopEnabled) return null;
return (
<>
<Button
@@ -10,6 +10,7 @@ import type { WorkshopUser } from "@homarr/workshop/schema";
import { useScopedI18n } from "@homarr/translation/client";
import { createWorkshopClient } from "./workshop-client";
import { useRuntimeFeature } from "~/hooks/use-runtime-feature";
import {
getPrivateWorkshopSourceNames,
publishWorkshopDefinition,
@@ -25,6 +26,7 @@ export function WorkshopPublishModal({
onClose(): void;
widget: { id: string; name: string };
}) {
const workshopEnabled = useRuntimeFeature("workshop");
const t = useScopedI18n("workshop");
const client = useMemo(createWorkshopClient, []);
const [user, setUser] = useState<WorkshopUser | null>(null);
@@ -35,15 +37,16 @@ export function WorkshopPublishModal({
const [error, setError] = useState<string | null>(null);
const [published, setPublished] = useState(false);
const [sourceUrlsReviewed, setSourceUrlsReviewed] = useState(false);
const definition = clientApi.customWidget.export.useQuery({ id: widget.id }, { enabled: opened });
const definition = clientApi.customWidget.export.useQuery({ id: widget.id }, { enabled: opened && workshopEnabled });
const privateSourceNames = getPrivateWorkshopSourceNames(definition.data);
const definitionFingerprint = definition.data ? serializeWorkshopDefinition(definition.data) : null;
useEffect(() => {
if (!workshopEnabled) return;
const unsubscribe = client.subscribeToAuth(setUser);
void client.refreshAuth().then(setUser);
return unsubscribe;
}, [client]);
}, [client, workshopEnabled]);
useEffect(() => {
if (!opened) return;
setTitle(widget.name);
@@ -86,6 +89,8 @@ export function WorkshopPublishModal({
}
};
if (!workshopEnabled) return null;
return (
<Modal opened={opened} onClose={onClose} title={t("publish.title")} size="lg">
<Stack>
+19 -1
View File
@@ -1,13 +1,31 @@
import { z } from "zod/v4";
import { createBooleanSchema, createEnv } from "@homarr/core/infrastructure/env";
import { normalizeHttpUrl } from "@homarr/workshop/schema";
const publicHttpUrl = (variableName: string) =>
z.string().transform((value, context) => {
try {
return normalizeHttpUrl(value, variableName);
} catch (error) {
context.addIssue({
code: "custom",
message: error instanceof Error ? error.message : `${variableName} is invalid`,
});
return z.NEVER;
}
});
export const env = createEnv({
server: {
UNSAFE_ENABLE_MOCK_INTEGRATION: createBooleanSchema(false),
DEMO_MODE: createBooleanSchema(false),
DEMO_READ_ONLY: createBooleanSchema(true),
WORKSHOP_API_URL: z.string().url().optional(),
CUSTOM_WIDGETS_ENABLED: createBooleanSchema(true),
WORKSHOP_ENABLED: createBooleanSchema(true),
HOMARR_WEBSITE_URL: publicHttpUrl("HOMARR_WEBSITE_URL").default("https://homarr.dev"),
WORKSHOP_API_URL: publicHttpUrl("WORKSHOP_API_URL").optional(),
WORKSHOP_WEB_URL: publicHttpUrl("WORKSHOP_WEB_URL").optional(),
},
experimental__runtimeEnv: process.env,
});
@@ -0,0 +1,12 @@
"use client";
import { useSyncExternalStore } from "react";
const subscribe = () => () => undefined;
export const useRuntimeFeature = (feature: "custom-widgets" | "workshop") =>
useSyncExternalStore(
subscribe,
() => document.querySelector<HTMLMetaElement>(`meta[name="homarr-${feature}-enabled"]`)?.content !== "false",
() => true,
);
+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
}
}
+372 -21
View File
@@ -1,8 +1,20 @@
import { createServer } from "node:http";
import { chromium, expect } from "@playwright/test";
import type { Browser } from "@playwright/test";
import { stringify as stringifySuperJson } from "superjson";
import type { StartedTestContainer } from "testcontainers";
import { describe, test } from "vitest";
import { eq } from "@homarr/db";
import {
customWidgetDefinitions,
customWidgetSecrets,
legacyCustomWidgetDefinitions,
legacyCustomWidgetSecrets,
} from "@homarr/db/schema";
import type { HomarrCustomWidgetV2Input } from "@homarr/custom-widgets/core";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import type { MockApiServer } from "./shared/mock-api-server";
@@ -13,6 +25,153 @@ const adminCredentials = { username: "admin", password: "Comp(exP4sswOrd" };
const initialTemplate =
"<Stack><Title order={4}>{data.status?.title}</Title><Badge>{data.status?.status}</Badge></Stack>";
const updatedTemplate = "<Stack><Text fw={700}>{data.status?.title}</Text><Text>{data.status?.value}</Text></Stack>";
const workshopWidgetName = "Workshop E2E widget";
const legacyWidgetName = "Legacy E2E Widget";
const legacyWidgetId = "legacy-e2e-widget";
interface WorkshopMockServer {
url: string;
close(): Promise<void>;
}
const startWorkshopMockServerAsync = async (widget: HomarrCustomWidgetV2Input): Promise<WorkshopMockServer> => {
const submissionId = "e2eworkshop0001";
const timestamp = "2026-07-28T10:00:00.000Z";
const listing = {
id: submissionId,
collectionId: "workshop-listings",
collectionName: "workshop_listings",
type: "customWidget",
title: workshopWidgetName,
description: "Installed from the Workshop and rendered on a Homarr board.",
widgetSchema: "homarr-custom-widget-v2",
screenshots: [],
author: "e2e-author",
authorName: "E2E Workshop author",
authorAvatar: "",
authorAvatarUrl: "",
authorGithubUsername: "",
authorGithubProfileUrl: "",
score: 1,
upvotes: 1,
downvotes: 0,
commentCount: 0,
reportCount: 0,
revision: 1,
changelog: "Initial E2E submission",
outdated: false,
created: timestamp,
updated: timestamp,
};
const submission = {
id: submissionId,
collectionId: "submissions",
collectionName: "submissions",
type: listing.type,
title: listing.title,
description: listing.description,
widgetSchema: listing.widgetSchema,
content: JSON.stringify(widget),
revision: listing.revision,
changelog: listing.changelog,
outdated: listing.outdated,
screenshots: listing.screenshots,
author: listing.author,
created: timestamp,
updated: timestamp,
};
const server = createServer((request, response) => {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "*");
response.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
response.setHeader("Access-Control-Allow-Private-Network", "true");
response.setHeader("Content-Type", "application/json");
if (request.method === "OPTIONS") {
response.writeHead(204);
response.end();
return;
}
const pathname = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
if (request.method === "GET" && pathname === "/api/collections/workshop_listings/records") {
response.end(
JSON.stringify({
page: 1,
perPage: 24,
totalItems: 1,
totalPages: 1,
items: [listing],
}),
);
return;
}
if (request.method === "GET" && pathname === `/api/collections/workshop_listings/records/${submissionId}`) {
response.end(JSON.stringify(listing));
return;
}
if (request.method === "GET" && pathname === `/api/collections/submissions/records/${submissionId}`) {
response.end(JSON.stringify(submission));
return;
}
response.writeHead(404);
response.end(JSON.stringify({ code: 404, message: "Not found.", data: {} }));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.off("error", reject);
resolve();
});
});
const address = server.address();
if (!address || typeof address === "string") throw new Error("Workshop mock server did not bind to a TCP port");
return {
url: `http://127.0.0.1:${address.port}`,
close: () =>
new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
server.closeAllConnections();
}),
};
};
const loginAsAdmin = async (browser: Browser, baseUrl: string, clipboard = false) => {
const context = await browser.newContext({
permissions: clipboard ? ["clipboard-read", "clipboard-write"] : [],
});
const page = await context.newPage();
await page.goto(`${baseUrl}/auth/login`);
await page.waitForLoadState("networkidle");
await page.getByLabel("Username").fill(adminCredentials.username);
await page.locator("#password").fill(adminCredentials.password);
await page.locator("button[type='submit']").click();
await page.waitForURL(baseUrl, { timeout: 15_000 });
return page;
};
const addCustomWidgetToBoard = async (
page: Awaited<ReturnType<typeof loginAsAdmin>>,
baseUrl: string,
name: string,
) => {
await page.goto(baseUrl);
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("button", { name: "New item", exact: true }).click();
await page.getByRole("menuitem", { name: "New item", exact: true }).click();
const picker = page.getByRole("dialog").last();
const customWidgetCard = picker.getByText(name, { exact: true }).locator("xpath=../../..");
await customWidgetCard.hover();
await customWidgetCard.getByRole("button", { name: "Add to board" }).click();
const addDialog = page.getByRole("dialog").last();
await expect(addDialog.getByText(name, { exact: true })).toBeVisible();
await addDialog.getByRole("button", { name: "Save changes", exact: true }).click();
await page.getByRole("button", { name: "Save", exact: true }).click();
};
describe("Custom JSX v2 workbench", () => {
test("creates, previews, edits, and immediately adds a widget to a board", async () => {
@@ -30,14 +189,7 @@ describe("Custom JSX v2 workbench", () => {
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
browser = await chromium.launch();
const page = await browser.newPage();
await page.goto(`${baseUrl}/auth/login`);
await page.waitForLoadState("networkidle");
await page.getByLabel("Username").fill(adminCredentials.username);
await page.locator("#password").fill(adminCredentials.password);
await page.locator("button[type='submit']").click();
await page.waitForURL(baseUrl, { timeout: 15_000 });
const page = await loginAsAdmin(browser, baseUrl);
await page.goto(`${baseUrl}/manage/custom-widgets/new`);
await page.locator('input[data-path="name"]:visible').fill("E2E Custom JSX v2");
@@ -74,24 +226,223 @@ describe("Custom JSX v2 workbench", () => {
await page.getByRole("button", { name: "Save", exact: true }).last().click();
await expect(page.getByText('Widget "E2E Custom JSX v2" updated successfully.')).toBeVisible({ timeout: 15_000 });
await page.goto(baseUrl);
await page.getByRole("button", { name: "Edit", exact: true }).click();
await page.getByRole("button", { name: "New item", exact: true }).click();
await page.getByRole("menuitem", { name: "New item", exact: true }).click();
const picker = page.getByRole("dialog").last();
const customWidgetCard = picker.getByText("E2E Custom JSX v2", { exact: true }).locator("xpath=../../..");
await customWidgetCard.hover();
await customWidgetCard.getByRole("button", { name: "Add to board" }).click();
const addDialog = page.getByRole("dialog").last();
await expect(addDialog.getByText("E2E Custom JSX v2")).toBeVisible();
await addDialog.getByRole("button", { name: "Save changes", exact: true }).click();
await addCustomWidgetToBoard(page, baseUrl, "E2E Custom JSX v2");
await expect(page.getByText("Widget definition not found")).not.toBeVisible();
await page.getByRole("button", { name: "Save", exact: true }).click();
await expect(page.getByText("E2E Widget")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("42")).toBeVisible({ timeout: 15_000 });
} finally {
await Promise.allSettled([browser?.close(), homarrContainer?.stop(), mockApi?.close()]);
}
}, 180_000);
test("installs a Workshop widget, places it on a board, and renders its query", async () => {
let mockApi: MockApiServer | undefined;
let workshopMock: WorkshopMockServer | undefined;
let homarrContainer: StartedTestContainer | undefined;
let browser: Browser | undefined;
try {
mockApi = await startMockApiServerAsync({ title: "Workshop query result", status: "online", value: 73 });
const workshopWidget = {
$schema: "homarr-custom-widget-v2",
name: workshopWidgetName,
description: "A Workshop installation exercised by the integrated E2E suite.",
sources: {
default: {
name: "E2E API",
baseUrl: mockApi.url,
networkScope: "private",
auth: "none",
},
},
requests: { status: { path: "/status" } },
options: {},
template: updatedTemplate,
} satisfies HomarrCustomWidgetV2Input;
workshopMock = await startWorkshopMockServerAsync(workshopWidget);
const { db, localMountPath } = await createSqliteDbFileAsync();
await seedAdminUserAsync(db, adminCredentials);
homarrContainer = await createHomarrContainer({
environment: {
AUTH_PROVIDERS: "credentials",
WORKSHOP_API_URL: workshopMock.url,
},
mounts: { "/appdata": localMountPath },
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
browser = await chromium.launch();
const page = await loginAsAdmin(browser, baseUrl);
await page.goto(`${baseUrl}/manage/workshop`);
await expect(page.getByText(workshopWidgetName, { exact: true })).toBeVisible({ timeout: 15_000 });
await page.getByRole("button", { name: "Inspect widget" }).click();
const workshopDialog = page.getByRole("dialog", { name: workshopWidgetName });
await expect(
workshopDialog.getByText("Installed from the Workshop and rendered on a Homarr board."),
).toBeVisible();
await workshopDialog.getByRole("button", { name: "Install widget" }).click();
const importDialog = page.getByRole("dialog", { name: "Review custom widget import" });
await importDialog
.getByRole("checkbox", {
name: "I confirm that this server URL is correct for my Homarr installation",
})
.check();
await importDialog.getByRole("button", { name: "Import widget" }).click();
await expect(page.getByText("Widget imported successfully.")).toBeVisible({ timeout: 15_000 });
await page.waitForURL("**/manage/custom-widgets/edit/**", { timeout: 15_000 });
await addCustomWidgetToBoard(page, baseUrl, workshopWidgetName);
await expect(page.getByText("Widget definition not found")).not.toBeVisible();
await expect(page.getByText("Workshop query result")).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("73")).toBeVisible({ timeout: 15_000 });
} finally {
await Promise.allSettled([browser?.close(), homarrContainer?.stop(), workshopMock?.close(), mockApi?.close()]);
}
}, 180_000);
test("migrates a redacted preserved v1 widget and resurfaces it when the v2 replacement is deleted", async () => {
let homarrContainer: StartedTestContainer | undefined;
let browser: Browser | undefined;
const encryptedValue = "preserved.ciphertext" as `${string}.${string}`;
const migratedWidget = {
$schema: "homarr-custom-widget-v2",
name: legacyWidgetName,
description: "Validated v2 replacement for the preserved legacy widget.",
sources: {
default: {
name: "Legacy API",
baseUrl: "https://legacy-api.homarr.dev/api",
networkScope: "public",
auth: { type: "apiKeyHeader", name: "X-E2E-Key" },
},
},
requests: { status: { path: "/status" } },
options: {},
template: "<Stack><Text>{data.status?.value}</Text></Stack>",
} satisfies HomarrCustomWidgetV2Input;
try {
const { db, localMountPath } = await createSqliteDbFileAsync();
const { userId } = await seedAdminUserAsync(db, adminCredentials);
await db.insert(legacyCustomWidgetDefinitions).values({
id: legacyWidgetId,
name: legacyWidgetName,
description: "Preserved v1 fixture",
url: "https://legacy-user:super-secret@legacy-api.homarr.dev/api/status?token=token-value#fragment",
authType: "apiKeyHeader",
headerName: "X-E2E-Key",
method: "POST",
requestBody: JSON.stringify({ password: "nested-secret", filters: ["private-filter"] }),
displayType: "singleValue",
displayConfig: stringifySuperJson({ type: "singleValue", jsonPath: "$.value" }),
enabled: true,
creatorId: userId,
});
await db.insert(legacyCustomWidgetSecrets).values({
definitionId: legacyWidgetId,
kind: "apiKey",
encryptedValue,
updatedAt: new Date(0),
});
homarrContainer = await createHomarrContainer({
environment: { AUTH_PROVIDERS: "credentials" },
mounts: { "/appdata": localMountPath },
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
browser = await chromium.launch();
const page = await loginAsAdmin(browser, baseUrl, true);
await page.goto(`${baseUrl}/manage/custom-widgets`);
const legacyCard = page
.getByText(legacyWidgetName, { exact: true })
.locator("xpath=ancestor::*[contains(@class, 'mantine-Card-root')]");
await expect(legacyCard.getByText("Migration required", { exact: true })).toBeVisible();
await legacyCard.getByRole("button", { name: "Actions" }).click();
await page.getByRole("menuitem", { name: "Copy LLM migration prompt" }).click();
await expect(page.getByText(/A redacted migration prompt was copied/u)).toBeVisible({ timeout: 15_000 });
const prompt = await page.evaluate(() => navigator.clipboard.readText());
expect(prompt).toContain("[REDACTED]");
expect(prompt).not.toContain("legacy-user");
expect(prompt).not.toContain("super-secret");
expect(prompt).not.toContain("token-value");
expect(prompt).not.toContain("nested-secret");
expect(prompt).not.toContain("private-filter");
await legacyCard.getByRole("button", { name: "Actions" }).click();
await page.getByLabel("Import migrated v2 JSON").setInputFiles({
name: "legacy-widget-v2.json",
mimeType: "application/json",
buffer: Buffer.from(JSON.stringify(migratedWidget)),
});
const migrationDialog = page.getByRole("dialog", { name: "Review migrated v2 replacement" });
await migrationDialog.getByRole("button", { name: "Confirm v2 replacement" }).click();
await expect(
page.getByText("Legacy widget migrated successfully. Existing board placements now use the v2 definition."),
).toBeVisible({ timeout: 15_000 });
expect(
await db.query.legacyCustomWidgetDefinitions.findFirst({
where: eq(legacyCustomWidgetDefinitions.id, legacyWidgetId),
}),
).toMatchObject({ id: legacyWidgetId, name: legacyWidgetName });
expect(
await db.query.legacyCustomWidgetSecrets.findFirst({
where: eq(legacyCustomWidgetSecrets.definitionId, legacyWidgetId),
}),
).toMatchObject({ definitionId: legacyWidgetId, encryptedValue });
expect(
await db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, legacyWidgetId),
}),
).toMatchObject({ id: legacyWidgetId, name: legacyWidgetName });
expect(
await db.query.customWidgetSecrets.findFirst({
where: eq(customWidgetSecrets.definitionId, legacyWidgetId),
}),
).toMatchObject({
definitionId: legacyWidgetId,
sourceId: "default",
kind: "apiKey",
encryptedValue,
});
await page.reload();
const migratedCard = page
.getByText(legacyWidgetName, { exact: true })
.locator("xpath=ancestor::*[contains(@class, 'mantine-Card-root')]");
await expect(migratedCard.getByText("Migration required", { exact: true })).not.toBeVisible();
await migratedCard.getByRole("button", { name: "Actions" }).click();
await page.getByRole("menuitem", { name: "Delete Custom Widget" }).click();
const deleteDialog = page.getByRole("dialog", { name: "Delete Custom Widget" });
await deleteDialog.getByRole("button", { name: "Confirm", exact: true }).click();
await expect(page.getByText(`Widget "${legacyWidgetName}" deleted.`)).toBeVisible({ timeout: 15_000 });
expect(
await db.query.customWidgetDefinitions.findFirst({
where: eq(customWidgetDefinitions.id, legacyWidgetId),
}),
).toBeUndefined();
expect(
await db.query.legacyCustomWidgetDefinitions.findFirst({
where: eq(legacyCustomWidgetDefinitions.id, legacyWidgetId),
}),
).toMatchObject({ id: legacyWidgetId, name: legacyWidgetName });
expect(
await db.query.legacyCustomWidgetSecrets.findFirst({
where: eq(legacyCustomWidgetSecrets.definitionId, legacyWidgetId),
}),
).toMatchObject({ definitionId: legacyWidgetId, encryptedValue });
await page.reload();
const resurfacedLegacyCard = page
.getByText(legacyWidgetName, { exact: true })
.locator("xpath=ancestor::*[contains(@class, 'mantine-Card-root')]");
await expect(resurfacedLegacyCard.getByText("Migration required", { exact: true })).toBeVisible();
} finally {
await Promise.allSettled([browser?.close(), homarrContainer?.stop()]);
}
}, 180_000);
});
+4 -1
View File
@@ -8,6 +8,7 @@
"clean:workspaces": "turbo clean",
"check:custom-widgets": "pnpm --filter @homarr/custom-widgets check:architecture",
"check:custom-widget-bundle": "node ./scripts/check-custom-widget-bundle.mjs",
"check:actions": "bash ./scripts/ci/check-actions.sh",
"check:openapi": "tsx ./scripts/check-openapi-schema.mts",
"ci:act:all": "bash scripts/ci/act.sh all",
"ci:act:cleanup": "bash scripts/ci/act.sh cleanup",
@@ -24,6 +25,8 @@
"db:studio": "pnpm -F db studio",
"dev": "pnpm -F nextjs dev",
"dev:docs": "pnpm -F @homarr/docs dev",
"dev:workshop": "node ./scripts/dev-workshop.mjs",
"build:workshop-validator": "pnpm --filter @homarr/workshop build:pocketbase-validator",
"docker:docs": "docker compose -f apps/workshop/docker-compose.yml up --build docs",
"docker:workshop": "docker compose -f apps/workshop/docker-compose.yml up --build workshop",
"docker:dev": "docker compose -f ./development/development.docker-compose.yml up",
@@ -31,7 +34,7 @@
"format:fix": "turbo format --continue",
"lint": "turbo lint --continue",
"lint:fix": "turbo lint --continue -- --fix",
"lint:ws": "pnpm dlx sherif@latest",
"lint:ws": "pnpm dlx sherif@1.13.0",
"release": "semantic-release",
"scripts:update-bug-report-template": "tsx ./scripts/update-bug-report-template.mts",
"scripts:update-readme-integrations": "tsx ./scripts/update-integration-list.mts",
+1
View File
@@ -63,6 +63,7 @@
},
"devDependencies": {
"@homarr/tsconfig": "workspace:^0.1.0",
"ioredis": "catalog:",
"typescript": "catalog:"
}
}
@@ -1,5 +1,6 @@
export * from "./router/custom-widget/configuration-requests";
export { configurePreviewSessionSource } from "./router/custom-widget/preview-sessions";
export { invalidateCustomWidgetResponseCache } from "./router/custom-widget/request-executor";
export {
parseStoredCustomWidgetDefinition,
serializeCustomWidgetDefinition,
@@ -0,0 +1,4 @@
export function useProcessLocalCustomWidgetState(runtime: { CI?: string; NODE_ENV?: string } = process.env): boolean {
if (runtime.NODE_ENV === "production") return false;
return runtime.NODE_ENV === "test" || runtime.CI === "true";
}
+22
View File
@@ -1,16 +1,38 @@
import { z } from "zod/v4";
import { createBooleanSchema, createEnv } from "@homarr/core/infrastructure/env";
import { normalizeHttpUrl } from "@homarr/workshop/schema";
const publicHttpUrl = (variableName: string) =>
z.string().transform((value, context) => {
try {
return normalizeHttpUrl(value, variableName);
} catch (error) {
context.addIssue({
code: "custom",
message: error instanceof Error ? error.message : `${variableName} is invalid`,
});
return z.NEVER;
}
});
export const env = createEnv({
server: {
KUBERNETES_SERVICE_ACCOUNT_NAME: z.string().optional(),
DEMO_MODE: createBooleanSchema(false),
DEMO_READ_ONLY: createBooleanSchema(true),
CUSTOM_WIDGETS_ENABLED: createBooleanSchema(true),
WORKSHOP_ENABLED: createBooleanSchema(true),
HOMARR_WEBSITE_URL: publicHttpUrl("HOMARR_WEBSITE_URL").default("https://homarr.dev"),
WORKSHOP_API_URL: publicHttpUrl("WORKSHOP_API_URL").optional(),
},
runtimeEnv: {
KUBERNETES_SERVICE_ACCOUNT_NAME: process.env.KUBERNETES_SERVICE_ACCOUNT_NAME,
DEMO_MODE: process.env.DEMO_MODE,
DEMO_READ_ONLY: process.env.DEMO_READ_ONLY,
CUSTOM_WIDGETS_ENABLED: process.env.CUSTOM_WIDGETS_ENABLED,
WORKSHOP_ENABLED: process.env.WORKSHOP_ENABLED,
HOMARR_WEBSITE_URL: process.env.HOMARR_WEBSITE_URL,
WORKSHOP_API_URL: process.env.WORKSHOP_API_URL,
},
});
+22
View File
@@ -59,8 +59,13 @@ import { zodUnionFromArray } from "@homarr/validation/enums";
import type { BoardItemAdvancedOptions } from "@homarr/validation/shared";
import { sectionSchema, sharedItemSchema } from "@homarr/validation/shared";
import { env } from "../env";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure, publicProcedure } from "../trpc";
import { throwIfActionForbiddenAsync } from "./board/board-access";
import {
throwIfCustomWidgetBoardDuplicationForbidden,
throwIfCustomWidgetPlacementChangeForbidden,
} from "./board/custom-widget-placement-access";
import { generateResponsiveGridFor } from "./board/grid-algorithm";
export const boardRouter = createTRPCRouter({
@@ -372,6 +377,11 @@ export const boardRouter = createTRPCRouter({
}
const { sections: boardSections, items: boardItems, layouts: boardLayouts, ...boardProps } = board;
throwIfCustomWidgetBoardDuplicationForbidden(
ctx.session.user.permissions.includes("admin"),
env.CUSTOM_WIDGETS_ENABLED !== false,
boardItems,
);
const newBoardId = createId();
@@ -855,6 +865,12 @@ export const boardRouter = createTRPCRouter({
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
const dbBoard = await getFullBoardWithWhereAsync(ctx.db, eq(boards.id, input.id), ctx.session.user.id);
throwIfCustomWidgetPlacementChangeForbidden({
isAdmin: ctx.session.user.permissions.includes("admin"),
customWidgetsEnabled: env.CUSTOM_WIDGETS_ENABLED !== false,
submittedItems: input.items,
storedItems: dbBoard.items,
});
await handleTransactionsAsync(ctx.db, {
async handleAsync(db, schema) {
@@ -1440,6 +1456,12 @@ export const boardRouter = createTRPCRouter({
.output(z.object({ itemId: z.string() }))
.mutation(async ({ ctx, input }) => {
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.boardId), "modify");
throwIfCustomWidgetPlacementChangeForbidden({
isAdmin: ctx.session.user.permissions.includes("admin"),
customWidgetsEnabled: env.CUSTOM_WIDGETS_ENABLED !== false,
submittedItems: [{ id: "", kind: input.kind, options: input.options }],
storedItems: [],
});
if (input.integrationIds.length > 0) {
const existing = await ctx.db.query.integrations.findMany({
@@ -0,0 +1,96 @@
import { isDeepStrictEqual } from "node:util";
import { TRPCError } from "@trpc/server";
interface BoardPlacement {
id: string;
kind: string;
options: Record<string, unknown>;
}
interface CustomWidgetPlacementGuardInput {
isAdmin: boolean;
customWidgetsEnabled: boolean;
submittedItems: readonly BoardPlacement[];
storedItems: readonly BoardPlacement[];
}
const throwAdminRequired = () => {
throw new TRPCError({
code: "FORBIDDEN",
message: "Only administrators can add or configure Custom Widgets",
});
};
const throwFeatureDisabled = () => {
throw new TRPCError({
code: "SERVICE_UNAVAILABLE",
message: "Custom Widgets are temporarily disabled by the server administrator",
});
};
const assertAuthoringAllowed = (isAdmin: boolean, customWidgetsEnabled: boolean) => {
if (!customWidgetsEnabled) throwFeatureDisabled();
if (!isAdmin) throwAdminRequired();
};
/**
* Protects the security-sensitive part of Custom Widget placements while
* leaving ordinary board operations (layout, presentation and removal) to the
* existing board permission checks.
*/
export const throwIfCustomWidgetPlacementChangeForbidden = ({
isAdmin,
customWidgetsEnabled,
submittedItems,
storedItems,
}: CustomWidgetPlacementGuardInput) => {
const storedById = new Map(storedItems.map((item) => [item.id, item]));
for (const submitted of submittedItems) {
const stored = storedById.get(submitted.id);
if (!stored) {
if (submitted.kind === "customApi") assertAuthoringAllowed(isAdmin, customWidgetsEnabled);
continue;
}
const wasCustomWidget = stored.kind === "customApi";
const isCustomWidget = submitted.kind === "customApi";
if (wasCustomWidget !== isCustomWidget) {
if (isCustomWidget) assertAuthoringAllowed(isAdmin, customWidgetsEnabled);
else if (!isAdmin) throwAdminRequired();
continue;
}
if (
wasCustomWidget &&
!isDeepStrictEqual(normalizeCustomWidgetOptions(submitted.options), normalizeCustomWidgetOptions(stored.options))
) {
assertAuthoringAllowed(isAdmin, customWidgetsEnabled);
}
}
};
export const throwIfCustomWidgetBoardDuplicationForbidden = (
isAdmin: boolean,
customWidgetsEnabled: boolean,
items: readonly Pick<BoardPlacement, "kind">[],
) => {
if (items.some((item) => item.kind === "customApi")) assertAuthoringAllowed(isAdmin, customWidgetsEnabled);
};
function normalizeCustomWidgetOptions(options: Record<string, unknown>) {
return {
...options,
configuration:
options.configuration !== null &&
typeof options.configuration === "object" &&
!Array.isArray(options.configuration)
? options.configuration
: {},
configurationVersion:
typeof options.configurationVersion === "number" && Number.isInteger(options.configurationVersion)
? options.configurationVersion
: 1,
refreshInterval: typeof options.refreshInterval === "number" ? options.refreshInterval : 30,
};
}
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more