feat!: release v2 (#6545)
Co-authored-by: Artur <145776561+arturict@users.noreply.github.com> Co-authored-by: arturict <arturict@users.noreply.github.com> Co-authored-by: Thomas <thomas@ajnart.fr> Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com> Co-authored-by: Danura30082 <danura30082+github@gmail.com> Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com> Co-authored-by: ajnart <thomas@ajnart.fr> Co-authored-by: ajnart <thomas@ajnart.dev> Co-authored-by: chenjun <chenjun@foxmail.com> Co-authored-by: Wikibear <wikibear@users.noreply.github.com> Co-authored-by: Bergasha <bergasha@gmail.com> Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com> Co-authored-by: Lucas Araujo <lucas.lra@gmail.com> Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com> Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social> Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com> Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com> Co-authored-by: thrawnx <tight.bulb9384@fastmail.com> Co-authored-by: Chris <58918656+nordada@users.noreply.github.com> Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com> Co-authored-by: Yanis <naamaneyanis@gmail.com> Co-authored-by: Wikibear <me@sej.de> Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386
-139176
No files matched your search
@@ -0,0 +1,20 @@
|
||||
# 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
|
||||
|
||||
# Optional Homarr provider. The upstream key stays only in the Workshop server.
|
||||
# OPENROUTER_API_KEY=
|
||||
HOMARR_AI_DAILY_REQUEST_LIMIT=50
|
||||
HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT=10000
|
||||
# HOMARR_AI_OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
||||
# HOMARR_AI_OPENROUTER_MODEL=
|
||||
# HOMARR_AI_ALLOW_INSECURE_UPSTREAM=false
|
||||
|
||||
# Optional local GitHub OAuth application.
|
||||
# GITHUB_CLIENT_ID=
|
||||
# GITHUB_CLIENT_SECRET=
|
||||
@@ -0,0 +1,19 @@
|
||||
WORKSHOP_IMAGE=ghcr.io/homarr-labs/workshop:v2
|
||||
WORKSHOP_EXPOSE_PORT=8090
|
||||
|
||||
HOMARR_WEBSITE_URL=https://v2.preview.homarr.dev
|
||||
WORKSHOP_API_URL=https://v2.preview.homarr.dev
|
||||
WORKSHOP_WEB_URL=https://v2.preview.homarr.dev/workshop
|
||||
WORKSHOP_PUBLIC_ORIGIN=https://v2.preview.homarr.dev
|
||||
PB_ALLOWED_ORIGINS=*
|
||||
|
||||
# Set this secret in the deployment environment to enable the Homarr provider.
|
||||
# OPENROUTER_API_KEY=
|
||||
HOMARR_AI_DAILY_REQUEST_LIMIT=50
|
||||
HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT=10000
|
||||
# HOMARR_AI_OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
|
||||
# HOMARR_AI_OPENROUTER_MODEL=
|
||||
|
||||
# Optional GitHub OAuth application for the preview hostname.
|
||||
# GITHUB_CLIENT_ID=
|
||||
# GITHUB_CLIENT_SECRET=
|
||||
@@ -0,0 +1 @@
|
||||
pb_data/
|
||||
@@ -0,0 +1,74 @@
|
||||
# syntax=docker/dockerfile:1.10
|
||||
|
||||
ARG POCKETBASE_IMAGE=ghcr.io/muchobien/pocketbase:0.39.9@sha256:c0667fe6c5197ff226ff642120ab1ad870c3f2f27300940a61e5a7fa082b6816
|
||||
|
||||
FROM golang:1.25.7-alpine AS pocketbase-builder
|
||||
WORKDIR /src
|
||||
COPY apps/workshop/go.mod apps/workshop/go.sum ./
|
||||
RUN --mount=type=cache,id=workshop-go-mod,target=/go/pkg/mod go mod download
|
||||
COPY apps/workshop/*.go ./
|
||||
RUN --mount=type=cache,id=workshop-go-mod,target=/go/pkg/mod \
|
||||
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/pocketbase .
|
||||
|
||||
FROM pocketbase-builder AS pocketbase-test
|
||||
RUN --mount=type=cache,id=workshop-go-mod,target=/go/pkg/mod go test ./...
|
||||
|
||||
FROM node:24.18.0-alpine AS dependencies
|
||||
WORKDIR /app
|
||||
ENV COREPACK_HOME=/corepack
|
||||
RUN mkdir -p /corepack && corepack enable pnpm && corepack install --global pnpm@11.15.1
|
||||
COPY pnpm-lock.yaml pnpm-workspace.yaml package.json turbo.json ./
|
||||
COPY patches ./patches
|
||||
COPY apps/docs ./apps/docs
|
||||
COPY tools/motion-reel/three ./tools/motion-reel/three
|
||||
COPY packages/common ./packages/common
|
||||
COPY packages/core ./packages/core
|
||||
COPY packages/custom-widgets ./packages/custom-widgets
|
||||
COPY packages/definitions ./packages/definitions
|
||||
COPY packages/db ./packages/db
|
||||
COPY packages/server-settings ./packages/server-settings
|
||||
COPY packages/settings ./packages/settings
|
||||
COPY packages/translation ./packages/translation
|
||||
COPY packages/ui ./packages/ui
|
||||
COPY packages/validation ./packages/validation
|
||||
COPY packages/workshop ./packages/workshop
|
||||
COPY tooling/typescript ./tooling/typescript
|
||||
RUN --mount=type=cache,id=workshop-pnpm-store,target=/pnpm/store pnpm config set store-dir /pnpm/store && pnpm install --filter @homarr/docs... --frozen-lockfile
|
||||
|
||||
FROM dependencies AS website
|
||||
ARG KAPA_WEBSITE_ID=1e4656f4-abeb-4343-bbae-1d8626f52378
|
||||
ENV KAPA_WEBSITE_ID=$KAPA_WEBSITE_ID
|
||||
ARG HOMARR_WEBSITE_URL=https://homarr.dev
|
||||
ARG WORKSHOP_API_URL=https://homarr.dev
|
||||
ARG WORKSHOP_WEB_URL=https://homarr.dev/workshop
|
||||
ENV HOMARR_WEBSITE_URL=$HOMARR_WEBSITE_URL
|
||||
ENV WORKSHOP_API_URL=$WORKSHOP_API_URL
|
||||
ENV WORKSHOP_WEB_URL=$WORKSHOP_WEB_URL
|
||||
RUN CI=true SKIP_ENV_VALIDATION=true pnpm --filter @homarr/docs build
|
||||
|
||||
FROM ${POCKETBASE_IMAGE} AS pocketbase-runtime
|
||||
ENV PORT=8090
|
||||
COPY --from=pocketbase-builder /out/pocketbase /usr/local/bin/pocketbase
|
||||
RUN addgroup -S pocketbase && adduser -S -G pocketbase pocketbase
|
||||
COPY apps/workshop/entrypoint.sh /usr/local/bin/workshop-entrypoint
|
||||
RUN chmod 755 /usr/local/bin/workshop-entrypoint && mkdir -p /pb_data /pb_public && chown pocketbase:pocketbase /pb_data /pb_public
|
||||
VOLUME ["/pb_data"]
|
||||
ENTRYPOINT ["workshop-entrypoint"]
|
||||
|
||||
FROM pocketbase-runtime AS development
|
||||
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
|
||||
ARG HOMARR_WEBSITE_URL=https://homarr.dev
|
||||
ARG WORKSHOP_API_URL=https://homarr.dev
|
||||
ARG WORKSHOP_WEB_URL=https://homarr.dev/workshop
|
||||
ENV HOMARR_WEBSITE_URL=$HOMARR_WEBSITE_URL
|
||||
ENV WORKSHOP_API_URL=$WORKSHOP_API_URL
|
||||
ENV WORKSHOP_WEB_URL=$WORKSHOP_WEB_URL
|
||||
COPY --from=website /app/apps/docs/out /pb_public
|
||||
COPY apps/workshop/pb_migrations /pb_migrations
|
||||
COPY apps/workshop/pb_hooks /pb_hooks
|
||||
RUN chown -R pocketbase:pocketbase /pb_hooks /pb_migrations /pb_public
|
||||
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
|
||||
@@ -0,0 +1,8 @@
|
||||
.git
|
||||
**/.next
|
||||
**/.source
|
||||
**/.turbo
|
||||
**/node_modules
|
||||
**/pb_data
|
||||
apps/docs/out
|
||||
coverage
|
||||
@@ -0,0 +1,106 @@
|
||||
# Homarr Workshop
|
||||
|
||||
Workshop is the PocketBase service behind the community pages in Homarr's documentation site. It stores Custom JSX v2
|
||||
widgets and Custom CSS submissions. Homarr validates community content again before installation.
|
||||
|
||||
The PocketBase version and multi-platform image digest are pinned in `apps/workshop/Dockerfile`; update and validate
|
||||
them together.
|
||||
|
||||
## Run locally
|
||||
|
||||
From the repository root:
|
||||
|
||||
```sh
|
||||
cp apps/workshop/.env.example apps/workshop/.env
|
||||
pnpm install --frozen-lockfile
|
||||
docker compose --env-file apps/workshop/.env -f apps/workshop/docker-compose.yml up --build workshop
|
||||
```
|
||||
|
||||
Start the documentation site in another terminal:
|
||||
|
||||
```sh
|
||||
WORKSHOP_API_URL=http://127.0.0.1:8090 pnpm dev:docs
|
||||
```
|
||||
|
||||
Open PocketBase administration at `http://127.0.0.1:8090/_/` and Workshop at
|
||||
`http://127.0.0.1:3003/workshop`. Create the first PocketBase superuser in the administration UI or run:
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
Useful service commands:
|
||||
|
||||
```sh
|
||||
docker compose -f apps/workshop/docker-compose.yml logs -f workshop
|
||||
docker compose -f apps/workshop/docker-compose.yml stop workshop
|
||||
```
|
||||
|
||||
## Connect Homarr
|
||||
|
||||
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=*
|
||||
```
|
||||
|
||||
`WORKSHOP_API_URL` controls API calls, `WORKSHOP_WEB_URL` controls links from Homarr, and
|
||||
`HOMARR_WEBSITE_URL` is the documentation-site base. All three must be absolute HTTP(S) URLs.
|
||||
|
||||
## OAuth and moderators
|
||||
|
||||
For optional GitHub OAuth, set both `GITHUB_CLIENT_ID` and `GITHUB_CLIENT_SECRET`. The callback is:
|
||||
|
||||
```text
|
||||
https://<workshop-host>/api/oauth2-redirect
|
||||
```
|
||||
|
||||
After a user signs in, a PocketBase superuser can promote them by setting `users.isAdmin` to `true`. This grants
|
||||
Workshop moderation only; it does not grant Homarr administrator access. The user must sign in again after the change.
|
||||
|
||||
The public community uses `PB_ALLOWED_ORIGINS=*` because self-hosted Homarr instances can run on any origin. Private
|
||||
deployments can use an explicit comma-separated allowlist.
|
||||
|
||||
## Validate changes
|
||||
|
||||
Run the focused Workshop checks:
|
||||
|
||||
```sh
|
||||
pnpm test:workshop
|
||||
pnpm --filter @homarr/workshop typecheck
|
||||
pnpm --filter @homarr/docs typecheck
|
||||
```
|
||||
|
||||
The integration suite uses a disposable Compose project. `pnpm test:workshop-image` additionally builds and smoke-tests
|
||||
the combined production image. The production image smoke also runs in PR CI on native amd64 and arm64 runners, including data persistence and backup restore. The broader integration suite remains available manually. Workshop CI validates Compose configuration and publishes images only on release branches. The main Fast gate owns workspace typechecking.
|
||||
|
||||
To smoke-test an already built candidate without rebuilding:
|
||||
|
||||
```sh
|
||||
WORKSHOP_IMAGE_TEST_IMAGE=homarr-workshop:candidate pnpm test:workshop-image
|
||||
```
|
||||
|
||||
## Data safety
|
||||
|
||||
PocketBase data lives in `/pb_data`. Normal start, stop, and down operations retain the named volume. Back up the
|
||||
database before migrations or image promotion, and test restores in a separate empty volume.
|
||||
|
||||
The v2 branch consolidates the unreleased Workshop migrations. Volumes that ran an earlier v2 migration chain are
|
||||
unsupported and must be backed up and recreated. The following command permanently removes the local Workshop volume:
|
||||
|
||||
```sh
|
||||
docker compose -f apps/workshop/docker-compose.yml down --volumes
|
||||
```
|
||||
|
||||
Never run that reset against production.
|
||||
|
||||
## Production
|
||||
|
||||
The production image serves the documentation site and PocketBase from one origin. See the
|
||||
[Workshop operator guide](../docs/docs/advanced/development/workshop-operator.mdx) for environment variables, proxying, staging, backups,
|
||||
and promotion. Publish by immutable digest, validate that exact digest in staging, then promote it.
|
||||
@@ -0,0 +1,30 @@
|
||||
name: homarr-workshop-staging
|
||||
|
||||
services:
|
||||
workshop:
|
||||
image: ${WORKSHOP_IMAGE:-ghcr.io/homarr-labs/workshop:v2}
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
HOMARR_WEBSITE_URL: ${HOMARR_WEBSITE_URL:?Set HOMARR_WEBSITE_URL in the Workshop environment file}
|
||||
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
|
||||
PORT: 8090
|
||||
WORKSHOP_API_URL: ${WORKSHOP_API_URL:?Set WORKSHOP_API_URL in the Workshop environment file}
|
||||
WORKSHOP_PUBLIC_ORIGIN: ${WORKSHOP_PUBLIC_ORIGIN:?Set WORKSHOP_PUBLIC_ORIGIN in the Workshop environment file}
|
||||
WORKSHOP_WEB_URL: ${WORKSHOP_WEB_URL:?Set WORKSHOP_WEB_URL in the Workshop environment file}
|
||||
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
|
||||
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
|
||||
HOMARR_AI_DAILY_REQUEST_LIMIT: ${HOMARR_AI_DAILY_REQUEST_LIMIT:-50}
|
||||
HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT: ${HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT:-10000}
|
||||
HOMARR_AI_OPENROUTER_BASE_URL: ${HOMARR_AI_OPENROUTER_BASE_URL:-https://openrouter.ai/api/v1}
|
||||
HOMARR_AI_OPENROUTER_MODEL: ${HOMARR_AI_OPENROUTER_MODEL:-openai/gpt-6-luna}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
ports:
|
||||
- "127.0.0.1:${WORKSHOP_EXPOSE_PORT:-8090}:8090"
|
||||
volumes:
|
||||
- pb_data:/pb_data
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
stop_grace_period: 30s
|
||||
|
||||
volumes:
|
||||
pb_data:
|
||||
@@ -0,0 +1,81 @@
|
||||
name: homarr-workshop
|
||||
|
||||
services:
|
||||
assistant-upstream:
|
||||
profiles:
|
||||
- test
|
||||
image: node:24.18.0-alpine
|
||||
command: ["node", "/mock/openrouter-mock.mjs"]
|
||||
environment:
|
||||
PORT: 18091
|
||||
EXPECTED_MODEL: mock/team-selected-model
|
||||
volumes:
|
||||
- ./tests/openrouter-mock.mjs:/mock/openrouter-mock.mjs:ro
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
|
||||
workshop:
|
||||
build:
|
||||
context: ../..
|
||||
dockerfile: apps/workshop/Dockerfile
|
||||
target: development
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
HOMARR_WEBSITE_URL: ${HOMARR_WEBSITE_URL:-http://localhost:3003}
|
||||
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
|
||||
PORT: ${PB_EXPOSE_PORT:-8090}
|
||||
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:-}
|
||||
HOMARR_AI_DAILY_REQUEST_LIMIT: ${HOMARR_AI_DAILY_REQUEST_LIMIT:-50}
|
||||
HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT: ${HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT:-10000}
|
||||
HOMARR_AI_OPENROUTER_BASE_URL: ${HOMARR_AI_OPENROUTER_BASE_URL:-https://openrouter.ai/api/v1}
|
||||
HOMARR_AI_OPENROUTER_MODEL: ${HOMARR_AI_OPENROUTER_MODEL:-openai/gpt-6-luna}
|
||||
HOMARR_AI_ALLOW_INSECURE_UPSTREAM: ${HOMARR_AI_ALLOW_INSECURE_UPSTREAM:-false}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
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
|
||||
|
||||
docs:
|
||||
profiles:
|
||||
- docs
|
||||
build:
|
||||
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}
|
||||
environment:
|
||||
HOMARR_WEBSITE_URL: ${HOMARR_WEBSITE_URL:-http://localhost:3003}
|
||||
PB_ALLOWED_ORIGINS: ${PB_ALLOWED_ORIGINS:-*}
|
||||
PORT: ${DOCS_EXPOSE_PORT:-3003}
|
||||
WORKSHOP_API_URL: ${WORKSHOP_API_URL:-http://localhost:3003}
|
||||
WORKSHOP_WEB_URL: ${WORKSHOP_WEB_URL:-http://localhost:3003/workshop}
|
||||
GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-}
|
||||
GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-}
|
||||
HOMARR_AI_DAILY_REQUEST_LIMIT: ${HOMARR_AI_DAILY_REQUEST_LIMIT:-50}
|
||||
HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT: ${HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT:-10000}
|
||||
HOMARR_AI_OPENROUTER_BASE_URL: ${HOMARR_AI_OPENROUTER_BASE_URL:-https://openrouter.ai/api/v1}
|
||||
HOMARR_AI_OPENROUTER_MODEL: ${HOMARR_AI_OPENROUTER_MODEL:-openai/gpt-6-luna}
|
||||
HOMARR_AI_ALLOW_INSECURE_UPSTREAM: ${HOMARR_AI_ALLOW_INSECURE_UPSTREAM:-false}
|
||||
OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}
|
||||
WORKSHOP_PUBLIC_ORIGIN: ${WORKSHOP_PUBLIC_ORIGIN:-http://localhost:3003}
|
||||
ports:
|
||||
- "127.0.0.1:${DOCS_EXPOSE_PORT:-3003}:${DOCS_EXPOSE_PORT:-3003}"
|
||||
volumes:
|
||||
- pb_data:/pb_data
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
|
||||
volumes:
|
||||
pb_data:
|
||||
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
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
|
||||
|
||||
HOMARR_WEBSITE_URL=${HOMARR_WEBSITE_URL:-https://homarr.dev}
|
||||
WORKSHOP_API_URL=${WORKSHOP_API_URL:-$HOMARR_WEBSITE_URL}
|
||||
WORKSHOP_WEB_URL=${WORKSHOP_WEB_URL:-$HOMARR_WEBSITE_URL/workshop}
|
||||
|
||||
encode_runtime_value() {
|
||||
printf '%s' "$1" | base64 | tr -d '\n'
|
||||
}
|
||||
|
||||
cat >/pb_public/workshop-runtime-config.js <<EOF
|
||||
const decodeRuntimeValue = (value) =>
|
||||
new TextDecoder().decode(Uint8Array.from(atob(value), (character) => character.charCodeAt(0)));
|
||||
globalThis.homarrRuntimeConfig = Object.freeze({
|
||||
homarrWebsiteUrl: decodeRuntimeValue("$(encode_runtime_value "$HOMARR_WEBSITE_URL")"),
|
||||
workshopApiUrl: decodeRuntimeValue("$(encode_runtime_value "$WORKSHOP_API_URL")"),
|
||||
workshopWebUrl: decodeRuntimeValue("$(encode_runtime_value "$WORKSHOP_WEB_URL")")
|
||||
});
|
||||
EOF
|
||||
|
||||
exec pocketbase serve \
|
||||
--http="0.0.0.0:${PORT:-8090}" \
|
||||
--origins="${PB_ALLOWED_ORIGINS:-*}" \
|
||||
--dir=/pb_data \
|
||||
--hooksDir=/pb_hooks \
|
||||
--migrationsDir=/pb_migrations \
|
||||
--publicDir=/pb_public \
|
||||
--indexFallback=false
|
||||
@@ -0,0 +1,47 @@
|
||||
module github.com/homarr-labs/homarr/apps/workshop
|
||||
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/pocketbase/dbx v1.12.0
|
||||
github.com/pocketbase/pocketbase v0.39.9
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
|
||||
github.com/disintegration/imaging v1.6.2 // indirect
|
||||
github.com/dlclark/regexp2/v2 v2.5.2 // indirect
|
||||
github.com/domodwyer/mailyak/v3 v3.6.2 // indirect
|
||||
github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217 // indirect
|
||||
github.com/dop251/goja v0.0.0-20260722130236-0768e0998ac0 // indirect
|
||||
github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14 // indirect
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/fatih/color v1.19.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.10.1 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
|
||||
github.com/ganigeorgiev/fexpr v0.6.0 // indirect
|
||||
github.com/go-sourcemap/sourcemap v2.1.4+incompatible // indirect
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 // indirect
|
||||
github.com/google/pprof v0.0.0-20260709232956-b9395ee17fa0 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-isatty v0.0.23 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/pocketbase/ozzo-validation/v4 v4.3.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/spf13/cobra v1.10.2 // indirect
|
||||
github.com/spf13/pflag v1.0.10 // indirect
|
||||
golang.org/x/crypto v0.54.0 // indirect
|
||||
golang.org/x/image v0.44.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/oauth2 v0.36.0 // indirect
|
||||
golang.org/x/sync v0.22.0 // indirect
|
||||
golang.org/x/sys v0.47.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
modernc.org/libc v1.74.1 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
modernc.org/sqlite v1.54.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,143 @@
|
||||
github.com/Masterminds/semver/v3 v3.5.0 h1:kQceYJfbupGfZOKZQg0kou0DgAKhzDg2NZPAwZ/2OOE=
|
||||
github.com/Masterminds/semver/v3 v3.5.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=
|
||||
github.com/asaskevich/govalidator v0.0.0-20200108200545-475eaeb16496/go.mod h1:oGkLhpf+kjZl6xBf758TQhh5XrAeiJv/7FRz/2spLIg=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/disintegration/imaging v1.6.2 h1:w1LecBlG2Lnp8B3jk5zSuNqd7b4DXhcjwek1ei82L+c=
|
||||
github.com/disintegration/imaging v1.6.2/go.mod h1:44/5580QXChDfwIclfc/PCwrr44amcmDAg8hxG0Ewe4=
|
||||
github.com/dlclark/regexp2/v2 v2.5.2 h1:HAsucWRhsqcDzl6Ua9aR8JwYOTzrZyPrF0/FNxJVAI0=
|
||||
github.com/dlclark/regexp2/v2 v2.5.2/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU=
|
||||
github.com/domodwyer/mailyak/v3 v3.6.2 h1:x3tGMsyFhTCaxp6ycgR0FE/bu5QiNp+hetUuCOBXMn8=
|
||||
github.com/domodwyer/mailyak/v3 v3.6.2/go.mod h1:lOm/u9CyCVWHeaAmHIdF4RiKVxKUT/H5XX10lIKAL6c=
|
||||
github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217 h1:16iT9CBDOniJwFGPI41MbUDfEk74hFaKTqudrX8kenY=
|
||||
github.com/dop251/base64dec v0.0.0-20231022112746-c6c9f9a96217/go.mod h1:eIb+f24U+eWQCIsj9D/ah+MD9UP+wdxuqzsdLD+mhGM=
|
||||
github.com/dop251/goja v0.0.0-20260722130236-0768e0998ac0 h1:1JJPIzrFPTNEHCFkIDhKV2CHBklTA/7VHJp9sVB8Em0=
|
||||
github.com/dop251/goja v0.0.0-20260722130236-0768e0998ac0/go.mod h1:LiIEzozrcvNXorsG/3+ypGqdTUAqZryhzSsqi0oU/Qg=
|
||||
github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14 h1:3U8dTgyNBhEQ/GVw0jZW5q+93Zw2gAZPRWhJ9TwV3rM=
|
||||
github.com/dop251/goja_nodejs v0.0.0-20260212111938-1f56ff5bcf14/go.mod h1:Tb7Xxye4LX7cT3i8YLvmPMGCV92IOi4CDZvm/V8ylc0=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/fatih/color v1.19.0 h1:Zp3PiM21/9Ld6FzSKyL5c/BULoe/ONr9KlbYVOfG8+w=
|
||||
github.com/fatih/color v1.19.0/go.mod h1:zNk67I0ZUT1bEGsSGyCZYZNrHuTkJJB+r6Q9VuMi0LE=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho=
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13 h1:46nXokslUBsAJE/wMsp5gtO500a4F3Nkz9Ufpk2AcUM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.13/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s=
|
||||
github.com/ganigeorgiev/fexpr v0.6.0 h1:Fza3O/QMBKEudUvxV862qe6GjxM60GJjjKytdp+VQus=
|
||||
github.com/ganigeorgiev/fexpr v0.6.0/go.mod h1:RyGiGqmeXhEQ6+mlGdnUleLHgtzzu/VGO2WtJkF5drE=
|
||||
github.com/go-sourcemap/sourcemap v2.1.4+incompatible h1:a+iTbH5auLKxaNwQFg0B+TCYl6lbukKPc7b5x0n1s6Q=
|
||||
github.com/go-sourcemap/sourcemap v2.1.4+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg=
|
||||
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM=
|
||||
github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY=
|
||||
github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
|
||||
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/google/pprof v0.0.0-20260709232956-b9395ee17fa0 h1:du0WGc8xSKq/++e0cglxhS/mXVqsR7+c7jLEi5Vqduw=
|
||||
github.com/google/pprof v0.0.0-20260709232956-b9395ee17fa0/go.mod h1:MxpfABSjhmINe3F1It9d+8exIHFvUqtLIRCdOGNXqiI=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY=
|
||||
github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.23 h1:cYwCQTQf3HB6xUC+BtyCLZNr7IzbOmoZbmssVNzSyiQ=
|
||||
github.com/mattn/go-isatty v0.0.23/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A=
|
||||
github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
|
||||
github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pocketbase/dbx v1.12.0 h1:/oLErM+A0b4xI0PWTGPqSDVjzix48PqI/bng2l0PzoA=
|
||||
github.com/pocketbase/dbx v1.12.0/go.mod h1:xXRCIAKTHMgUCyCKZm55pUOdvFziJjQfXaWKhu2vhMs=
|
||||
github.com/pocketbase/ozzo-validation/v4 v4.3.0 h1:uKBDVma7bZqgR2a6AwE+k9hkuDFfiZMpBHQdZ1z3iQs=
|
||||
github.com/pocketbase/ozzo-validation/v4 v4.3.0/go.mod h1:6XNjSTw/Jb2F8LOkKO3oyzIWExbrGiYoS4uVxVwz90g=
|
||||
github.com/pocketbase/pocketbase v0.39.9 h1:zmrvbWJwBlb+iXst02uD6zNqNpiyG86KtlOJjd+Bhx4=
|
||||
github.com/pocketbase/pocketbase v0.39.9/go.mod h1:6l4ZFFa8kNkxLSumxzVm+DtczfUz86Wqow0bQYiXEkQ=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||
golang.org/x/image v0.44.0 h1:+tDekMZED9+LrtB3G5xzRggpVh9CARjZqROla3R3R+I=
|
||||
golang.org/x/image v0.44.0/go.mod h1:V8K3KE9KKKE+pLpQDOeN18w9oacNSvy1tDOirTu4xtY=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
|
||||
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM=
|
||||
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
|
||||
modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
|
||||
modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
|
||||
modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
|
||||
modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
|
||||
modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
|
||||
modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
|
||||
modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
|
||||
modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.54.0 h1:JCxR4qwkJvOaqAoYcgDoO25Nc+ROg6EJ2LfBVzdrgog=
|
||||
modernc.org/sqlite v1.54.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,759 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/pocketbase/dbx"
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
)
|
||||
|
||||
const (
|
||||
homarrProviderModelID = "homarr/model"
|
||||
homarrProviderModelName = "Homarr model"
|
||||
defaultOpenRouterModelID = "openai/gpt-6-luna"
|
||||
lunaOpenRouterModelID = "openai/gpt-5.6-luna"
|
||||
maxChatInputTokens = 256 * 1024
|
||||
maxChatOutputTokens = 32 * 1024
|
||||
defaultDailyLimit = 50
|
||||
defaultGlobalDailyLimit = 10_000
|
||||
// The Homarr composer permits five 1 MB images, which expand to about 6.7 MB as
|
||||
// base64. Keep the authenticated transport bounded without confusing bytes with
|
||||
// model tokens; validate textual and image content separately below.
|
||||
maxChatRequestBytes = 12_000_000
|
||||
// One UTF-8 byte can represent a complete token. Keep the byte guard conservative
|
||||
// so accepted requests cannot exceed the advertised context before reaching the model.
|
||||
maxChatTextBytes = maxChatInputTokens
|
||||
maxChatImageDataBytes = 1_400_000
|
||||
maxChatImages = 5
|
||||
maxChatMessages = 512
|
||||
maxChatResponseBytes = 8 << 20
|
||||
maxWebSearchResults = 5
|
||||
maxWebSearchUses = 3
|
||||
maxWebSearchTotal = 10
|
||||
maxWebSearchCharacters = 2500
|
||||
webSearchContextSize = "low"
|
||||
maxUserInFlight = 2
|
||||
maxGlobalInFlight = 100
|
||||
openRouterDefaultURL = "https://openrouter.ai/api/v1"
|
||||
openRouterReferer = "https://homarr.dev"
|
||||
openRouterTitle = "Homarr AI Assistant"
|
||||
providerRequestTimeout = 5 * time.Minute
|
||||
)
|
||||
|
||||
var (
|
||||
errProviderResponseTooLarge = errors.New("provider response is too large")
|
||||
errInvalidProviderResponse = errors.New("invalid provider response")
|
||||
errInvalidTools = errors.New("invalid request tools")
|
||||
errUnsupportedTool = errors.New("unsupported request tool")
|
||||
errTooManyImages = errors.New("too many images or image too large")
|
||||
errRemoteImage = errors.New("remote image not allowed")
|
||||
errInputTooLarge = errors.New("request exceeds model input limit")
|
||||
)
|
||||
|
||||
var clientControlledRoutingFields = []string{
|
||||
"models", "provider", "route", "plugins", "transforms", "extra_body", "extra_headers",
|
||||
}
|
||||
|
||||
var clientControlledCostFields = []string{
|
||||
"audio", "modalities", "logprobs", "top_logprobs", "prediction", "service_tier",
|
||||
}
|
||||
|
||||
type homarrProvider struct {
|
||||
apiKey string
|
||||
baseURL string
|
||||
modelID string
|
||||
dailyLimit int
|
||||
globalDailyLimit int
|
||||
httpClient *http.Client
|
||||
now func() time.Time
|
||||
inFlightMutex sync.Mutex
|
||||
inFlightByUser map[string]int
|
||||
globalInFlight int
|
||||
}
|
||||
|
||||
type quotaSnapshot struct {
|
||||
Limit int `json:"limit"`
|
||||
Used int `json:"used"`
|
||||
Remaining int `json:"remaining"`
|
||||
ResetsAt time.Time `json:"resetsAt"`
|
||||
}
|
||||
|
||||
type providerRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []providerMessage `json:"messages"`
|
||||
Stream bool `json:"stream"`
|
||||
}
|
||||
|
||||
type providerMessage struct {
|
||||
Role string `json:"role"`
|
||||
}
|
||||
|
||||
type quotaExceededError struct {
|
||||
Snapshot quotaSnapshot
|
||||
}
|
||||
|
||||
func (err *quotaExceededError) Error() string { return "daily Homarr provider allowance exhausted" }
|
||||
|
||||
func registerHomarrProvider(app *pocketbase.PocketBase) {
|
||||
provider, err := newHomarrProviderFromEnv()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
app.OnServe().BindFunc(func(event *core.ServeEvent) error {
|
||||
group := event.Router.Group("/api/ai")
|
||||
group.GET("/v1/models", provider.models)
|
||||
group.GET("/usage", provider.usage).
|
||||
Bind(apis.RequireAuth("users")).
|
||||
Unbind(apis.DefaultActivityLoggerMiddlewareId)
|
||||
group.POST("/v1/chat/completions", provider.chat).
|
||||
Bind(apis.RequireAuth("users"), apis.BodyLimit(maxChatRequestBytes)).
|
||||
Unbind(apis.DefaultActivityLoggerMiddlewareId)
|
||||
return event.Next()
|
||||
})
|
||||
}
|
||||
|
||||
func newHomarrProviderFromEnv() (*homarrProvider, error) {
|
||||
baseURL := strings.TrimRight(strings.TrimSpace(os.Getenv("HOMARR_AI_OPENROUTER_BASE_URL")), "/")
|
||||
if baseURL == "" {
|
||||
baseURL = openRouterDefaultURL
|
||||
}
|
||||
parsedURL, err := url.Parse(baseURL)
|
||||
if err != nil || parsedURL.Host == "" || (parsedURL.Scheme != "https" && parsedURL.Scheme != "http") ||
|
||||
parsedURL.User != nil || parsedURL.RawQuery != "" || parsedURL.Fragment != "" {
|
||||
return nil, errors.New("HOMARR_AI_OPENROUTER_BASE_URL must be an absolute HTTP(S) URL without credentials, a query, or a fragment")
|
||||
}
|
||||
if parsedURL.Scheme != "https" && strings.TrimSpace(os.Getenv("HOMARR_AI_ALLOW_INSECURE_UPSTREAM")) != "true" {
|
||||
return nil, errors.New("HOMARR_AI_OPENROUTER_BASE_URL must use HTTPS unless HOMARR_AI_ALLOW_INSECURE_UPSTREAM=true")
|
||||
}
|
||||
|
||||
modelID := strings.TrimSpace(os.Getenv("HOMARR_AI_OPENROUTER_MODEL"))
|
||||
if modelID == "" {
|
||||
modelID = defaultOpenRouterModelID
|
||||
}
|
||||
if len(modelID) > 256 || strings.IndexFunc(modelID, func(value rune) bool {
|
||||
return unicode.IsSpace(value) || unicode.IsControl(value)
|
||||
}) >= 0 {
|
||||
return nil, errors.New("HOMARR_AI_OPENROUTER_MODEL must be a non-empty model identifier of at most 256 characters")
|
||||
}
|
||||
|
||||
dailyLimit := defaultDailyLimit
|
||||
if rawLimit := strings.TrimSpace(os.Getenv("HOMARR_AI_DAILY_REQUEST_LIMIT")); rawLimit != "" {
|
||||
value, parseErr := strconv.Atoi(rawLimit)
|
||||
if parseErr != nil || value < 1 || value > 100_000 {
|
||||
return nil, errors.New("HOMARR_AI_DAILY_REQUEST_LIMIT must be an integer between 1 and 100000")
|
||||
}
|
||||
dailyLimit = value
|
||||
}
|
||||
globalDailyLimit := defaultGlobalDailyLimit
|
||||
if rawLimit := strings.TrimSpace(os.Getenv("HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT")); rawLimit != "" {
|
||||
value, parseErr := strconv.Atoi(rawLimit)
|
||||
if parseErr != nil || value < 1 || value > 10_000_000 {
|
||||
return nil, errors.New("HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT must be an integer between 1 and 10000000")
|
||||
}
|
||||
globalDailyLimit = value
|
||||
}
|
||||
|
||||
return &homarrProvider{
|
||||
apiKey: strings.TrimSpace(os.Getenv("OPENROUTER_API_KEY")),
|
||||
baseURL: baseURL,
|
||||
modelID: modelID,
|
||||
dailyLimit: dailyLimit,
|
||||
globalDailyLimit: globalDailyLimit,
|
||||
httpClient: &http.Client{
|
||||
Timeout: providerRequestTimeout,
|
||||
CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
},
|
||||
},
|
||||
now: time.Now,
|
||||
inFlightByUser: make(map[string]int),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) models(event *core.RequestEvent) error {
|
||||
if provider.apiKey == "" {
|
||||
return event.JSON(http.StatusServiceUnavailable, openAIError("The Homarr provider is not configured."))
|
||||
}
|
||||
return event.JSON(http.StatusOK, map[string]any{
|
||||
"object": "list",
|
||||
"data": []map[string]any{{
|
||||
"id": homarrProviderModelID,
|
||||
"object": "model",
|
||||
"name": homarrProviderModelName,
|
||||
"description": "The tool-capable model selected by the Homarr team.",
|
||||
"owned_by": "homarr",
|
||||
"context_length": maxChatInputTokens,
|
||||
"supported_parameters": []string{
|
||||
"tools", "tool_choice", "reasoning", "include_reasoning", "structured_outputs",
|
||||
},
|
||||
"architecture": map[string]any{
|
||||
"input_modalities": []string{"text", "image"},
|
||||
"output_modalities": []string{"text"},
|
||||
},
|
||||
}},
|
||||
})
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) usage(event *core.RequestEvent) error {
|
||||
snapshot, err := provider.quota(event.App, event.Auth)
|
||||
if err != nil {
|
||||
return event.InternalServerError("The Homarr provider allowance could not be loaded.", nil)
|
||||
}
|
||||
return event.JSON(http.StatusOK, snapshot)
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) chat(event *core.RequestEvent) error {
|
||||
if provider.apiKey == "" {
|
||||
return event.JSON(http.StatusServiceUnavailable, openAIError("The Homarr provider is not configured."))
|
||||
}
|
||||
if !provider.acquireRequest(event.Auth.Id) {
|
||||
return event.JSON(http.StatusTooManyRequests, openAIError("Too many Homarr provider requests are already running."))
|
||||
}
|
||||
defer provider.releaseRequest(event.Auth.Id)
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(event.Request.Body, maxChatRequestBytes+1))
|
||||
if err != nil || len(body) > maxChatRequestBytes {
|
||||
return event.JSON(http.StatusRequestEntityTooLarge, openAIError("The request is too large."))
|
||||
}
|
||||
|
||||
var requestBody providerRequest
|
||||
if err := json.Unmarshal(body, &requestBody); err != nil || len(requestBody.Messages) == 0 {
|
||||
return event.JSON(http.StatusBadRequest, openAIError("The request body is not valid OpenAI chat JSON."))
|
||||
}
|
||||
if len(requestBody.Messages) > maxChatMessages {
|
||||
return event.JSON(http.StatusBadRequest, openAIError("The request contains too many messages."))
|
||||
}
|
||||
if requestBody.Model != homarrProviderModelID {
|
||||
return event.JSON(http.StatusBadRequest, openAIError("The Homarr provider offers only the Homarr model."))
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return event.JSON(http.StatusBadRequest, openAIError("The request body is not valid OpenAI chat JSON."))
|
||||
}
|
||||
if err := validateProviderInput(payload); err != nil {
|
||||
message := "The request exceeds the Homarr model input limit."
|
||||
if errors.Is(err, errTooManyImages) {
|
||||
message = "The request contains too many images or an image that is too large."
|
||||
} else if errors.Is(err, errRemoteImage) {
|
||||
message = "Remote image URLs are not supported. Upload the image to Homarr instead."
|
||||
}
|
||||
return event.JSON(http.StatusRequestEntityTooLarge, openAIError(message))
|
||||
}
|
||||
if err := sanitizeProviderPayload(payload, provider.modelID); err != nil {
|
||||
message := "The request contains an unsupported tool."
|
||||
if errors.Is(err, errInvalidTools) {
|
||||
message = "The request tools are not valid."
|
||||
}
|
||||
return event.JSON(http.StatusBadRequest, openAIError(message))
|
||||
}
|
||||
upstreamBody, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return event.JSON(http.StatusBadRequest, openAIError("The request body could not be prepared."))
|
||||
}
|
||||
|
||||
upstreamRequest, err := http.NewRequestWithContext(
|
||||
event.Request.Context(),
|
||||
http.MethodPost,
|
||||
provider.baseURL+"/chat/completions",
|
||||
bytes.NewReader(upstreamBody),
|
||||
)
|
||||
if err != nil {
|
||||
return event.JSON(http.StatusInternalServerError, openAIError("The Homarr provider request could not be prepared."))
|
||||
}
|
||||
snapshot, err := provider.startRequest(event.App, event.Auth)
|
||||
if err != nil {
|
||||
var quotaErr *quotaExceededError
|
||||
if errors.As(err, "aErr) {
|
||||
event.Response.Header().Set("X-Homarr-Quota-Limit", strconv.Itoa(quotaErr.Snapshot.Limit))
|
||||
event.Response.Header().Set("X-Homarr-Quota-Remaining", "0")
|
||||
event.Response.Header().Set("X-Homarr-Quota-Reset", quotaErr.Snapshot.ResetsAt.Format(time.RFC3339))
|
||||
return event.JSON(http.StatusTooManyRequests, openAIError("Your daily Homarr provider allowance is exhausted."))
|
||||
}
|
||||
return event.JSON(http.StatusInternalServerError, openAIError("The Homarr provider request could not be started."))
|
||||
}
|
||||
upstreamRequest.Header.Set("Authorization", "Bearer "+provider.apiKey)
|
||||
upstreamRequest.Header.Set("Content-Type", "application/json")
|
||||
upstreamRequest.Header.Set("Accept", "text/event-stream, application/json")
|
||||
upstreamRequest.Header.Set("HTTP-Referer", openRouterReferer)
|
||||
upstreamRequest.Header.Set("X-OpenRouter-Title", openRouterTitle)
|
||||
upstreamRequest.Header.Set("X-OpenRouter-Metadata", "enabled")
|
||||
|
||||
upstreamResponse, err := provider.httpClient.Do(upstreamRequest)
|
||||
if err != nil {
|
||||
return event.JSON(http.StatusBadGateway, openAIError("The model endpoint could not be reached."))
|
||||
}
|
||||
defer func() { _ = upstreamResponse.Body.Close() }()
|
||||
|
||||
event.Response.Header().Set("Cache-Control", "no-store")
|
||||
event.Response.Header().Set("X-Accel-Buffering", "no")
|
||||
event.Response.Header().Set("X-Homarr-Quota-Limit", strconv.Itoa(snapshot.Limit))
|
||||
event.Response.Header().Set("X-Homarr-Quota-Remaining", strconv.Itoa(snapshot.Remaining))
|
||||
event.Response.Header().Set("X-Homarr-Quota-Reset", snapshot.ResetsAt.Format(time.RFC3339))
|
||||
if requestID := upstreamResponse.Header.Get("X-Request-Id"); requestID != "" {
|
||||
event.Response.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
|
||||
contentType := upstreamResponse.Header.Get("Content-Type")
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
if upstreamResponse.StatusCode < 200 || upstreamResponse.StatusCode >= 300 {
|
||||
message := upstreamErrorMessage(upstreamResponse.Body, upstreamResponse.StatusCode, provider.apiKey)
|
||||
return event.JSON(safeUpstreamStatus(upstreamResponse.StatusCode), map[string]any{
|
||||
"error": map[string]any{"message": message, "type": "homarr_provider_upstream_error"},
|
||||
})
|
||||
}
|
||||
|
||||
if requestBody.Stream {
|
||||
event.Response.Header().Set("Content-Type", contentType)
|
||||
event.Response.WriteHeader(upstreamResponse.StatusCode)
|
||||
if _, streamErr := copyAliasedSSE(flushingWriter{event.Response}, upstreamResponse.Body, maxChatResponseBytes); streamErr != nil {
|
||||
_, _ = io.WriteString(flushingWriter{event.Response}, streamErrorFrame())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
responseBody, readErr := readBoundedBody(upstreamResponse.Body, maxChatResponseBytes)
|
||||
if readErr != nil {
|
||||
return event.JSON(http.StatusBadGateway, openAIError("The model endpoint returned an invalid response."))
|
||||
}
|
||||
responseBody, readErr = aliasCompletionBody(responseBody)
|
||||
if readErr != nil {
|
||||
return event.JSON(http.StatusBadGateway, openAIError("The model endpoint returned an invalid response."))
|
||||
}
|
||||
return event.Blob(upstreamResponse.StatusCode, contentType, responseBody)
|
||||
}
|
||||
|
||||
var upstreamCredentialPattern = regexp.MustCompile(`(?i)\b(?:bearer\s+[^\s"<>]+|sk-[a-z0-9_-]+|eyJ[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+)`)
|
||||
|
||||
// Forward only a bounded structured message, never provider metadata, request
|
||||
// headers, raw HTML, or a body that may contain the original conversation.
|
||||
func upstreamErrorMessage(body io.Reader, status int, apiKey string) string {
|
||||
prefix := "Upstream model service returned HTTP " + strconv.Itoa(status) + "."
|
||||
data, err := io.ReadAll(io.LimitReader(body, 16*1024+1))
|
||||
if err != nil || len(data) > 16*1024 {
|
||||
return prefix + " No readable error details were returned."
|
||||
}
|
||||
var payload struct {
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
if json.Unmarshal(data, &payload) != nil {
|
||||
return prefix + " The response was not a structured JSON error."
|
||||
}
|
||||
message := payload.Error.Message
|
||||
if message == "" {
|
||||
message = payload.Message
|
||||
}
|
||||
if apiKey != "" {
|
||||
message = strings.ReplaceAll(message, apiKey, "[REDACTED]")
|
||||
}
|
||||
message = upstreamCredentialPattern.ReplaceAllString(message, "[REDACTED]")
|
||||
message = strings.Join(strings.Fields(message), " ")
|
||||
if message == "" {
|
||||
return prefix + " No error message was returned."
|
||||
}
|
||||
// URLs can embed credentials or sensitive query strings. Keep only their origin/path.
|
||||
words := strings.Split(message, " ")
|
||||
for index, word := range words {
|
||||
if strings.Contains(word, "://") {
|
||||
words[index] = "[URL omitted]"
|
||||
}
|
||||
}
|
||||
message = strings.Join(words, " ")
|
||||
runes := []rune(message)
|
||||
if len(runes) > 1000 {
|
||||
message = string(runes[:1000]) + "…"
|
||||
}
|
||||
return prefix + " " + message
|
||||
}
|
||||
|
||||
func streamErrorFrame() string {
|
||||
payload, _ := json.Marshal(map[string]any{
|
||||
"error": map[string]any{
|
||||
"message": "The model endpoint returned an invalid response.",
|
||||
"type": "homarr_provider_error",
|
||||
},
|
||||
})
|
||||
return "data: " + string(payload) + "\n\ndata: [DONE]\n\n"
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) acquireRequest(userID string) bool {
|
||||
provider.inFlightMutex.Lock()
|
||||
defer provider.inFlightMutex.Unlock()
|
||||
if provider.globalInFlight >= maxGlobalInFlight || provider.inFlightByUser[userID] >= maxUserInFlight {
|
||||
return false
|
||||
}
|
||||
provider.globalInFlight++
|
||||
provider.inFlightByUser[userID]++
|
||||
return true
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) releaseRequest(userID string) {
|
||||
provider.inFlightMutex.Lock()
|
||||
defer provider.inFlightMutex.Unlock()
|
||||
provider.globalInFlight--
|
||||
provider.inFlightByUser[userID]--
|
||||
if provider.inFlightByUser[userID] == 0 {
|
||||
delete(provider.inFlightByUser, userID)
|
||||
}
|
||||
}
|
||||
|
||||
func safeUpstreamStatus(status int) int {
|
||||
if status == http.StatusUnauthorized || status == http.StatusForbidden {
|
||||
return http.StatusBadGateway
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func sanitizeProviderPayload(payload map[string]any, upstreamModelID string) error {
|
||||
for _, field := range clientControlledRoutingFields {
|
||||
delete(payload, field)
|
||||
}
|
||||
for _, field := range clientControlledCostFields {
|
||||
delete(payload, field)
|
||||
}
|
||||
delete(payload, "max_completion_tokens")
|
||||
delete(payload, "max_tokens")
|
||||
delete(payload, "metadata")
|
||||
delete(payload, "user")
|
||||
if reasoning, ok := payload["reasoning"].(map[string]any); ok {
|
||||
delete(reasoning, "max_tokens")
|
||||
}
|
||||
|
||||
if rawTools, exists := payload["tools"]; exists {
|
||||
tools, ok := rawTools.([]any)
|
||||
if !ok {
|
||||
return errInvalidTools
|
||||
}
|
||||
sanitizedTools := make([]any, 0, len(tools))
|
||||
webSearchAdded := false
|
||||
for _, rawTool := range tools {
|
||||
tool, ok := rawTool.(map[string]any)
|
||||
if !ok {
|
||||
return errUnsupportedTool
|
||||
}
|
||||
switch tool["type"] {
|
||||
case "function":
|
||||
sanitizedTools = append(sanitizedTools, tool)
|
||||
case "openrouter:web_search":
|
||||
if !webSearchAdded {
|
||||
sanitizedTools = append(sanitizedTools, map[string]any{
|
||||
"type": "openrouter:web_search",
|
||||
"parameters": map[string]any{
|
||||
"max_results": maxWebSearchResults,
|
||||
"max_uses": maxWebSearchUses,
|
||||
"max_total_results": maxWebSearchTotal,
|
||||
"max_characters": maxWebSearchCharacters,
|
||||
"search_context_size": webSearchContextSize,
|
||||
},
|
||||
})
|
||||
webSearchAdded = true
|
||||
}
|
||||
default:
|
||||
return errUnsupportedTool
|
||||
}
|
||||
}
|
||||
payload["tools"] = sanitizedTools
|
||||
}
|
||||
|
||||
payload["model"] = upstreamModelID
|
||||
payload["max_completion_tokens"] = maxChatOutputTokens
|
||||
payload["n"] = 1
|
||||
payload["parallel_tool_calls"] = false
|
||||
payload["usage"] = map[string]any{"include": true}
|
||||
delete(payload, "stream_options")
|
||||
if payload["stream"] == true {
|
||||
payload["stream_options"] = map[string]any{"include_usage": true}
|
||||
}
|
||||
// BYOK-only billing also requires disabling shared capacity on the OpenRouter key.
|
||||
// Retention and data collection policies are managed by OpenRouter guardrails.
|
||||
providerPreferences := map[string]any{
|
||||
"allow_fallbacks": false,
|
||||
}
|
||||
if upstreamModelID == defaultOpenRouterModelID {
|
||||
delete(payload, "reasoning_effort")
|
||||
delete(payload, "include_reasoning")
|
||||
delete(payload, "temperature")
|
||||
delete(payload, "top_p")
|
||||
payload["reasoning"] = map[string]any{"effort": "max", "exclude": false}
|
||||
} else if upstreamModelID == lunaOpenRouterModelID {
|
||||
delete(payload, "reasoning")
|
||||
payload["reasoning_effort"] = "high"
|
||||
}
|
||||
payload["provider"] = providerPreferences
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateProviderInput(payload map[string]any) error {
|
||||
textBytes := 0
|
||||
imageCount := 0
|
||||
var walk func(any) error
|
||||
walk = func(value any) error {
|
||||
switch typed := value.(type) {
|
||||
case string:
|
||||
if strings.HasPrefix(typed, "data:image/") {
|
||||
imageCount++
|
||||
if imageCount > maxChatImages || len(typed) > maxChatImageDataBytes {
|
||||
return errTooManyImages
|
||||
}
|
||||
return nil
|
||||
}
|
||||
textBytes += len(typed)
|
||||
if textBytes > maxChatTextBytes {
|
||||
return errInputTooLarge
|
||||
}
|
||||
case []any:
|
||||
for _, item := range typed {
|
||||
if err := walk(item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case map[string]any:
|
||||
if typed["type"] == "image_url" {
|
||||
image, ok := typed["image_url"].(map[string]any)
|
||||
imageURL, urlOK := image["url"].(string)
|
||||
if !ok || !urlOK || !strings.HasPrefix(imageURL, "data:image/") {
|
||||
return errRemoteImage
|
||||
}
|
||||
imageCount++
|
||||
if imageCount > maxChatImages || len(imageURL) > maxChatImageDataBytes {
|
||||
return errTooManyImages
|
||||
}
|
||||
}
|
||||
for key, item := range typed {
|
||||
if typed["type"] == "image_url" && key == "image_url" {
|
||||
continue
|
||||
}
|
||||
textBytes += len(key)
|
||||
if textBytes > maxChatTextBytes {
|
||||
return errInputTooLarge
|
||||
}
|
||||
if err := walk(item); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return walk(payload)
|
||||
}
|
||||
|
||||
func aliasCompletionBody(body []byte) ([]byte, error) {
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
return nil, errInvalidProviderResponse
|
||||
}
|
||||
payload["model"] = homarrProviderModelID
|
||||
aliased, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return nil, errInvalidProviderResponse
|
||||
}
|
||||
return aliased, nil
|
||||
}
|
||||
|
||||
func copyAliasedSSE(writer io.Writer, reader io.Reader, limit int64) (int64, error) {
|
||||
buffered := bufio.NewReader(io.LimitReader(reader, limit+1))
|
||||
var written int64
|
||||
var read int64
|
||||
for {
|
||||
line, err := buffered.ReadString('\n')
|
||||
read += int64(len(line))
|
||||
if read > limit {
|
||||
return written, errProviderResponseTooLarge
|
||||
}
|
||||
if strings.HasPrefix(line, "data: ") && strings.TrimSpace(strings.TrimPrefix(line, "data: ")) != "[DONE]" {
|
||||
payload := strings.TrimSpace(strings.TrimPrefix(line, "data: "))
|
||||
aliased, aliasErr := aliasCompletionBody([]byte(payload))
|
||||
if aliasErr != nil {
|
||||
return written, aliasErr
|
||||
}
|
||||
line = "data: " + string(aliased) + "\n"
|
||||
}
|
||||
if written+int64(len(line)) > limit {
|
||||
return written, errProviderResponseTooLarge
|
||||
}
|
||||
count, writeErr := io.WriteString(writer, line)
|
||||
written += int64(count)
|
||||
if writeErr != nil {
|
||||
return written, writeErr
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
return written, nil
|
||||
}
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func copyBounded(writer io.Writer, reader io.Reader, limit int64) (int64, error) {
|
||||
written, err := io.Copy(writer, io.LimitReader(reader, limit))
|
||||
if err != nil {
|
||||
return written, err
|
||||
}
|
||||
var extra [1]byte
|
||||
read, err := reader.Read(extra[:])
|
||||
if read > 0 {
|
||||
return written, errProviderResponseTooLarge
|
||||
}
|
||||
if err != nil && !errors.Is(err, io.EOF) {
|
||||
return written, err
|
||||
}
|
||||
return written, nil
|
||||
}
|
||||
|
||||
func readBoundedBody(reader io.Reader, limit int64) ([]byte, error) {
|
||||
body, err := io.ReadAll(io.LimitReader(reader, limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(body)) > limit {
|
||||
return nil, errProviderResponseTooLarge
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) quota(app core.App, user *core.Record) (quotaSnapshot, error) {
|
||||
now := provider.now().UTC()
|
||||
var snapshot quotaSnapshot
|
||||
err := app.RunInTransaction(func(txApp core.App) error {
|
||||
quota, current, quotaChanged, err := provider.loadQuota(txApp, user, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
globalQuota, globalRemaining, globalQuotaChanged, err := provider.loadGlobalQuota(txApp, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current.Remaining = min(current.Remaining, globalRemaining)
|
||||
snapshot = current
|
||||
if globalQuotaChanged {
|
||||
if err := txApp.Save(globalQuota); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if quotaChanged {
|
||||
return txApp.Save(quota)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return snapshot, err
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) loadGlobalQuota(app core.App, now time.Time) (*core.Record, int, bool, error) {
|
||||
quota, err := app.FindFirstRecordByFilter("assistant_global_quota", "key = 'default'")
|
||||
if err != nil {
|
||||
return nil, 0, false, err
|
||||
}
|
||||
changed := false
|
||||
if quota.GetString("day") != now.Format(time.DateOnly) {
|
||||
quota.Set("day", now.Format(time.DateOnly))
|
||||
quota.Set("used", 0)
|
||||
changed = true
|
||||
}
|
||||
return quota, max(0, provider.globalDailyLimit-quota.GetInt("used")), changed, nil
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) loadQuota(
|
||||
app core.App,
|
||||
user *core.Record,
|
||||
now time.Time,
|
||||
) (*core.Record, quotaSnapshot, bool, error) {
|
||||
day := now.Format(time.DateOnly)
|
||||
quota, err := app.FindFirstRecordByFilter(
|
||||
"assistant_quotas",
|
||||
"user = {:user} && day = {:day}",
|
||||
dbx.Params{"user": user.Id, "day": day},
|
||||
)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, quotaSnapshot{}, false, err
|
||||
}
|
||||
changed := false
|
||||
if quota == nil {
|
||||
collection, err := app.FindCollectionByNameOrId("assistant_quotas")
|
||||
if err != nil {
|
||||
return nil, quotaSnapshot{}, false, err
|
||||
}
|
||||
quota = core.NewRecord(collection)
|
||||
quota.Set("user", user.Id)
|
||||
quota.Set("day", day)
|
||||
quota.Set("used", 0)
|
||||
changed = true
|
||||
}
|
||||
limit := provider.dailyLimit
|
||||
used := quota.GetInt("used")
|
||||
return quota, quotaSnapshot{
|
||||
Limit: limit,
|
||||
Used: used,
|
||||
Remaining: max(0, limit-used),
|
||||
ResetsAt: time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, time.UTC),
|
||||
}, changed, nil
|
||||
}
|
||||
|
||||
func (provider *homarrProvider) startRequest(
|
||||
app core.App,
|
||||
user *core.Record,
|
||||
) (quotaSnapshot, error) {
|
||||
var snapshot quotaSnapshot
|
||||
err := app.RunInTransaction(func(txApp core.App) error {
|
||||
now := provider.now().UTC()
|
||||
quota, current, _, err := provider.loadQuota(txApp, user, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
globalQuota, globalRemaining, _, err := provider.loadGlobalQuota(txApp, now)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if current.Remaining < 1 || globalRemaining < 1 {
|
||||
return "aExceededError{Snapshot: current}
|
||||
}
|
||||
current.Used++
|
||||
current.Remaining = max(0, current.Limit-current.Used)
|
||||
quota.Set("used", current.Used)
|
||||
globalQuota.Set("used", globalQuota.GetInt("used")+1)
|
||||
snapshot = current
|
||||
if err := txApp.Save(globalQuota); err != nil {
|
||||
return err
|
||||
}
|
||||
return txApp.Save(quota)
|
||||
})
|
||||
return snapshot, err
|
||||
}
|
||||
|
||||
func openAIError(message string) map[string]any {
|
||||
return map[string]any{"error": map[string]any{"message": message, "type": "homarr_provider_error"}}
|
||||
}
|
||||
|
||||
type flushingWriter struct {
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
func (writer flushingWriter) Write(chunk []byte) (int, error) {
|
||||
written, err := writer.ResponseWriter.Write(chunk)
|
||||
if flusher, ok := writer.ResponseWriter.(http.Flusher); ok {
|
||||
flusher.Flush()
|
||||
}
|
||||
return written, err
|
||||
}
|
||||
@@ -0,0 +1,377 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUpstreamErrorMessage(t *testing.T) {
|
||||
for _, tt := range []struct{ name, body, key, want string }{
|
||||
{"routing", `{"error":{"message":"No endpoints found matching your data policy"}}`, "", "Upstream model service returned HTTP 404. No endpoints found matching your data policy"},
|
||||
{"proxy", `{"message":"Route not found"}`, "", "Upstream model service returned HTTP 404. Route not found"},
|
||||
{"redaction", `{"error":{"message":"opaque-private-key Bearer abc123 sk-or-v1-example https://user:pass@example.com/?key=secret"},"metadata":{"secret":"must not appear"}}`, "opaque-private-key", "Upstream model service returned HTTP 404. [REDACTED] [REDACTED] [REDACTED] [URL omitted]"},
|
||||
{"html", `<html>private upstream page</html>`, "", "Upstream model service returned HTTP 404. The response was not a structured JSON error."},
|
||||
{"empty", `{}`, "", "Upstream model service returned HTTP 404. No error message was returned."},
|
||||
{"oversized", strings.Repeat("x", 16*1024+1), "", "Upstream model service returned HTTP 404. No readable error details were returned."},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := upstreamErrorMessage(strings.NewReader(tt.body), 404, tt.key); got != tt.want {
|
||||
t.Fatalf("got %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
message := upstreamErrorMessage(strings.NewReader(`{"error":{"message":"`+strings.Repeat("é", 2000)+`"}}`), 404, "")
|
||||
if len([]rune(message)) > 1100 {
|
||||
t.Fatal("upstream message was not bounded")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeProviderPayload(t *testing.T) {
|
||||
payload := map[string]any{
|
||||
"model": homarrProviderModelID,
|
||||
"models": []string{"attacker/model"},
|
||||
"provider": map[string]any{"order": []string{"attacker"}},
|
||||
"route": "fallback",
|
||||
"plugins": []string{"web"},
|
||||
"transforms": []string{"middle-out"},
|
||||
"max_tokens": 1_000_000,
|
||||
"max_completion_tokens": 1_000_000,
|
||||
"n": 100,
|
||||
"parallel_tool_calls": true,
|
||||
"extra_body": map[string]any{"provider": map[string]any{"order": []string{"attacker"}}},
|
||||
"extra_headers": map[string]any{"Authorization": "Bearer attacker"},
|
||||
"metadata": map[string]any{"user": "private-user-id"},
|
||||
"audio": map[string]any{"format": "wav"},
|
||||
"modalities": []string{"text", "audio"},
|
||||
"logprobs": true,
|
||||
"top_logprobs": 20,
|
||||
"prediction": map[string]any{"content": strings.Repeat("x", 100)},
|
||||
"service_tier": "priority",
|
||||
"reasoning": map[string]any{"effort": "high", "max_tokens": 1_000_000},
|
||||
"user": "private-user-id",
|
||||
"tools": []any{
|
||||
map[string]any{"type": "function", "function": map[string]any{"name": "board_list"}},
|
||||
map[string]any{
|
||||
"type": "openrouter:web_search",
|
||||
"parameters": map[string]any{"max_results": 1000, "max_uses": 1000},
|
||||
},
|
||||
map[string]any{"type": "openrouter:web_search"},
|
||||
},
|
||||
"messages": []any{map[string]any{"role": "user", "content": "hello"}},
|
||||
}
|
||||
if err := sanitizeProviderPayload(payload, "mock/team-selected-model"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, field := range clientControlledRoutingFields {
|
||||
if field == "provider" {
|
||||
continue
|
||||
}
|
||||
if _, exists := payload[field]; exists {
|
||||
t.Fatalf("client-controlled routing field %q was forwarded", field)
|
||||
}
|
||||
}
|
||||
for _, field := range clientControlledCostFields {
|
||||
if _, exists := payload[field]; exists {
|
||||
t.Fatalf("client-controlled cost field %q was forwarded", field)
|
||||
}
|
||||
}
|
||||
if payload["model"] != "mock/team-selected-model" {
|
||||
t.Fatalf("unexpected upstream model: %v", payload["model"])
|
||||
}
|
||||
if payload["max_completion_tokens"] != maxChatOutputTokens || payload["n"] != 1 || payload["parallel_tool_calls"] != false {
|
||||
t.Fatalf("unsafe generation controls were forwarded: %#v", payload)
|
||||
}
|
||||
if _, exists := payload["max_tokens"]; exists {
|
||||
t.Fatal("deprecated client max_tokens was forwarded")
|
||||
}
|
||||
if _, exists := payload["user"]; exists {
|
||||
t.Fatal("client user identifier was forwarded")
|
||||
}
|
||||
if _, exists := payload["metadata"]; exists {
|
||||
t.Fatal("client metadata was forwarded")
|
||||
}
|
||||
reasoning := payload["reasoning"].(map[string]any)
|
||||
if _, exists := reasoning["max_tokens"]; exists || reasoning["effort"] != "high" {
|
||||
t.Fatalf("reasoning budget was not bounded safely: %#v", reasoning)
|
||||
}
|
||||
tools := payload["tools"].([]any)
|
||||
if len(tools) != 2 {
|
||||
t.Fatalf("unexpected sanitized tool count: %d", len(tools))
|
||||
}
|
||||
webSearch := tools[1].(map[string]any)
|
||||
parameters := webSearch["parameters"].(map[string]any)
|
||||
if parameters["max_results"] != maxWebSearchResults ||
|
||||
parameters["max_uses"] != maxWebSearchUses ||
|
||||
parameters["max_total_results"] != maxWebSearchTotal ||
|
||||
parameters["max_characters"] != maxWebSearchCharacters ||
|
||||
parameters["search_context_size"] != webSearchContextSize {
|
||||
t.Fatalf("web search limits were not enforced: %#v", parameters)
|
||||
}
|
||||
usage, err := json.Marshal(payload["usage"])
|
||||
if err != nil || string(usage) != `{"include":true}` {
|
||||
t.Fatalf("unexpected usage options: %s, %v", usage, err)
|
||||
}
|
||||
privacy := payload["provider"].(map[string]any)
|
||||
for _, field := range []string{"zdr", "data_collection"} {
|
||||
if _, exists := privacy[field]; exists {
|
||||
t.Fatalf("privacy policy must be left to OpenRouter guardrails: %#v", privacy)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeProviderPayloadPinsDefaultModelQuality(t *testing.T) {
|
||||
payload := map[string]any{
|
||||
"reasoning_effort": "none",
|
||||
"reasoning": map[string]any{"effort": "low", "enabled": false, "exclude": true},
|
||||
"include_reasoning": false,
|
||||
"temperature": 0.3,
|
||||
"top_p": 0.5,
|
||||
"provider": map[string]any{"only": []string{"azure"}, "allow_fallbacks": true, "zdr": true, "data_collection": "allow"},
|
||||
"stream": true,
|
||||
"stream_options": map[string]any{"include_usage": false},
|
||||
}
|
||||
if err := sanitizeProviderPayload(payload, defaultOpenRouterModelID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if payload["model"] != "openai/gpt-6-luna" {
|
||||
t.Fatalf("unexpected default model: %#v", payload["model"])
|
||||
}
|
||||
reasoning := payload["reasoning"].(map[string]any)
|
||||
if reasoning["effort"] != "max" || reasoning["exclude"] != false {
|
||||
t.Fatalf("default model did not use visible max reasoning: %#v", reasoning)
|
||||
}
|
||||
for _, field := range []string{"reasoning_effort", "include_reasoning", "temperature", "top_p"} {
|
||||
if _, exists := payload[field]; exists {
|
||||
t.Fatalf("conflicting or unsupported field %q was forwarded", field)
|
||||
}
|
||||
}
|
||||
if payload["stream_options"].(map[string]any)["include_usage"] != true {
|
||||
t.Fatal("streamed token usage must be included")
|
||||
}
|
||||
preferences := payload["provider"].(map[string]any)
|
||||
if _, exists := preferences["only"]; exists {
|
||||
t.Fatalf("provider allowlists must not restrict eligible endpoints: %#v", preferences)
|
||||
}
|
||||
if preferences["allow_fallbacks"] != false {
|
||||
t.Fatalf("default model must not fall back to another provider: %#v", preferences)
|
||||
}
|
||||
for _, field := range []string{"zdr", "data_collection"} {
|
||||
if _, exists := preferences[field]; exists {
|
||||
t.Fatalf("client privacy overrides must not be forwarded: %#v", preferences)
|
||||
}
|
||||
}
|
||||
for _, field := range []string{"order", "quantizations"} {
|
||||
if _, exists := preferences[field]; exists {
|
||||
t.Fatalf("obsolete DeepInfra routing field %q was forwarded", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeProviderPayloadPinsLunaReasoning(t *testing.T) {
|
||||
payload := map[string]any{
|
||||
"reasoning": map[string]any{"effort": "xhigh"},
|
||||
"reasoning_effort": "xhigh",
|
||||
}
|
||||
if err := sanitizeProviderPayload(payload, lunaOpenRouterModelID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if _, exists := payload["reasoning"]; exists {
|
||||
t.Fatal("Luna must use the top-level reasoning_effort field")
|
||||
}
|
||||
if payload["reasoning_effort"] != "high" {
|
||||
t.Fatalf("Luna did not use high reasoning: %#v", payload["reasoning_effort"])
|
||||
}
|
||||
preferences := payload["provider"].(map[string]any)
|
||||
if _, exists := preferences["order"]; exists {
|
||||
t.Fatalf("Luna must not inherit DeepInfra routing: %#v", preferences)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeProviderPayloadRejectsUnsupportedServerTools(t *testing.T) {
|
||||
payload := map[string]any{"tools": []any{map[string]any{"type": "openrouter:computer"}}}
|
||||
if err := sanitizeProviderPayload(payload, "mock/team-selected-model"); err == nil {
|
||||
t.Fatal("expected unsupported server tool to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeUpstreamStatus(t *testing.T) {
|
||||
for _, status := range []int{401, 403} {
|
||||
if actual := safeUpstreamStatus(status); actual != 502 {
|
||||
t.Fatalf("expected upstream %d to become 502, got %d", status, actual)
|
||||
}
|
||||
}
|
||||
if actual := safeUpstreamStatus(429); actual != 429 {
|
||||
t.Fatalf("expected upstream 429 to be preserved, got %d", actual)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProviderInput(t *testing.T) {
|
||||
payload := map[string]any{
|
||||
"messages": []any{map[string]any{
|
||||
"role": "user",
|
||||
"content": []any{map[string]any{
|
||||
"type": "image_url",
|
||||
"image_url": map[string]any{"url": "data:image/png;base64," + strings.Repeat("a", 1_300_000)},
|
||||
}},
|
||||
}},
|
||||
}
|
||||
if err := validateProviderInput(payload); err != nil {
|
||||
t.Fatalf("expected a supported Homarr image request, got %v", err)
|
||||
}
|
||||
payload["messages"] = []any{map[string]any{"role": "user", "content": strings.Repeat("x", maxChatTextBytes-100)}}
|
||||
if err := validateProviderInput(payload); err != nil {
|
||||
t.Fatalf("expected text at the conservative context boundary to be accepted, got %v", err)
|
||||
}
|
||||
payload["messages"] = []any{map[string]any{"role": "user", "content": strings.Repeat("x", maxChatTextBytes+1)}}
|
||||
if err := validateProviderInput(payload); !errors.Is(err, errInputTooLarge) {
|
||||
t.Fatalf("expected oversized text input to be rejected, got %v", err)
|
||||
}
|
||||
payload["messages"] = []any{map[string]any{
|
||||
"role": "user",
|
||||
"content": []any{map[string]any{
|
||||
"type": "image_url",
|
||||
"image_url": map[string]any{"url": "data:image/png;base64," + strings.Repeat("a", maxChatImageDataBytes)},
|
||||
}},
|
||||
}}
|
||||
if err := validateProviderInput(payload); !errors.Is(err, errTooManyImages) {
|
||||
t.Fatalf("expected oversized image input to be rejected, got %v", err)
|
||||
}
|
||||
payload["messages"] = []any{map[string]any{
|
||||
"role": "user",
|
||||
"content": []any{map[string]any{
|
||||
"type": "image_url",
|
||||
"image_url": map[string]any{"url": "https://attacker.example/expensive-image.png"},
|
||||
}},
|
||||
}}
|
||||
if err := validateProviderInput(payload); !errors.Is(err, errRemoteImage) {
|
||||
t.Fatalf("expected a remote image URL to be rejected, got %v", err)
|
||||
}
|
||||
payload["messages"] = []any{map[string]any{
|
||||
"role": "user",
|
||||
"content": []any{
|
||||
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,YQ=="}},
|
||||
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,YQ=="}},
|
||||
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,YQ=="}},
|
||||
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,YQ=="}},
|
||||
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,YQ=="}},
|
||||
},
|
||||
}}
|
||||
if err := validateProviderInput(payload); err != nil {
|
||||
t.Fatalf("expected five uploaded images to be accepted, got %v", err)
|
||||
}
|
||||
payload["messages"].([]any)[0].(map[string]any)["content"] = append(
|
||||
payload["messages"].([]any)[0].(map[string]any)["content"].([]any),
|
||||
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,YQ=="}},
|
||||
)
|
||||
if err := validateProviderInput(payload); !errors.Is(err, errTooManyImages) {
|
||||
t.Fatalf("expected six uploaded images to be rejected, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderInFlightLimits(t *testing.T) {
|
||||
provider := &homarrProvider{inFlightByUser: make(map[string]int)}
|
||||
if !provider.acquireRequest("one") {
|
||||
t.Fatal("expected the first user request to be admitted")
|
||||
}
|
||||
if !provider.acquireRequest("one") {
|
||||
t.Fatal("expected the second user request to be admitted")
|
||||
}
|
||||
if provider.acquireRequest("one") {
|
||||
t.Fatal("expected the third user request to be rejected")
|
||||
}
|
||||
provider.releaseRequest("one")
|
||||
provider.releaseRequest("one")
|
||||
for index := range maxGlobalInFlight {
|
||||
if !provider.acquireRequest(string(rune(index + 1))) {
|
||||
t.Fatalf("expected global request %d to be admitted", index)
|
||||
}
|
||||
}
|
||||
if provider.acquireRequest("overflow") {
|
||||
t.Fatal("expected the global in-flight limit to reject overflow")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompletionModelAlias(t *testing.T) {
|
||||
body, err := aliasCompletionBody([]byte(`{"id":"one","model":"private/model","choices":[]}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(body), "private/model") || !strings.Contains(string(body), `"model":"homarr/model"`) {
|
||||
t.Fatalf("private upstream model leaked in JSON: %s", body)
|
||||
}
|
||||
var stream strings.Builder
|
||||
_, err = copyAliasedSSE(
|
||||
&stream,
|
||||
strings.NewReader("data: {\"id\":\"one\",\"model\":\"private/model\",\"choices\":[]}\n\ndata: [DONE]\n\n"),
|
||||
1024,
|
||||
)
|
||||
if err != nil || strings.Contains(stream.String(), "private/model") ||
|
||||
!strings.Contains(stream.String(), `"model":"homarr/model"`) {
|
||||
t.Fatalf("private upstream model leaked in SSE: %s, %v", stream.String(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderEnvironment(t *testing.T) {
|
||||
t.Setenv("OPENROUTER_API_KEY", "test-key")
|
||||
t.Setenv("HOMARR_AI_OPENROUTER_BASE_URL", "https://router.example/v1/")
|
||||
t.Setenv("HOMARR_AI_OPENROUTER_MODEL", "mock/team-selected-model")
|
||||
t.Setenv("HOMARR_AI_DAILY_REQUEST_LIMIT", "75")
|
||||
t.Setenv("HOMARR_AI_GLOBAL_DAILY_REQUEST_LIMIT", "900")
|
||||
provider, err := newHomarrProviderFromEnv()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if provider.apiKey != "test-key" || provider.baseURL != "https://router.example/v1" ||
|
||||
provider.modelID != "mock/team-selected-model" || provider.dailyLimit != 75 || provider.globalDailyLimit != 900 {
|
||||
t.Fatalf("unexpected provider config: %#v", provider)
|
||||
}
|
||||
|
||||
t.Setenv("HOMARR_AI_DAILY_REQUEST_LIMIT", "0")
|
||||
if _, err := newHomarrProviderFromEnv(); err == nil {
|
||||
t.Fatal("expected invalid daily limit to fail")
|
||||
}
|
||||
|
||||
t.Setenv("HOMARR_AI_DAILY_REQUEST_LIMIT", "50")
|
||||
for _, unsafeURL := range []string{
|
||||
"https://user:password@router.example/v1",
|
||||
"https://router.example/v1?key=secret",
|
||||
"https://router.example/v1#fragment",
|
||||
} {
|
||||
t.Setenv("HOMARR_AI_OPENROUTER_BASE_URL", unsafeURL)
|
||||
if _, err := newHomarrProviderFromEnv(); err == nil {
|
||||
t.Fatalf("expected unsafe upstream URL %q to fail", unsafeURL)
|
||||
}
|
||||
}
|
||||
t.Setenv("HOMARR_AI_OPENROUTER_BASE_URL", "http://router.example/v1")
|
||||
if _, err := newHomarrProviderFromEnv(); err == nil {
|
||||
t.Fatal("expected an insecure upstream to fail without an explicit development opt-in")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadBoundedBody(t *testing.T) {
|
||||
body, err := readBoundedBody(strings.NewReader("1234"), 4)
|
||||
if err != nil || string(body) != "1234" {
|
||||
t.Fatalf("unexpected bounded body: %q, %v", body, err)
|
||||
}
|
||||
if _, err := readBoundedBody(strings.NewReader("12345"), 4); err != errProviderResponseTooLarge {
|
||||
t.Fatalf("expected response size error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyBounded(t *testing.T) {
|
||||
var target strings.Builder
|
||||
written, err := copyBounded(&target, strings.NewReader("1234"), 4)
|
||||
if err != nil || written != 4 || target.String() != "1234" {
|
||||
t.Fatalf("unexpected bounded copy: %q, %d, %v", target.String(), written, err)
|
||||
}
|
||||
|
||||
target.Reset()
|
||||
written, err = copyBounded(&target, strings.NewReader("12345"), 4)
|
||||
if err != errProviderResponseTooLarge || written != 4 || target.String() != "1234" {
|
||||
t.Fatalf("expected bounded copy failure, got %q, %d, %v", target.String(), written, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"compress/gzip"
|
||||
"errors"
|
||||
"io/fs"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/pocketbase/pocketbase"
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/plugins/jsvm"
|
||||
"github.com/pocketbase/pocketbase/plugins/migratecmd"
|
||||
"github.com/pocketbase/pocketbase/tools/hook"
|
||||
"github.com/pocketbase/pocketbase/tools/osutils"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
func main() {
|
||||
app := pocketbase.New()
|
||||
|
||||
var hooksDir string
|
||||
app.RootCmd.PersistentFlags().StringVar(&hooksDir, "hooksDir", "", "the directory with the JS app hooks")
|
||||
|
||||
var hooksWatch bool
|
||||
app.RootCmd.PersistentFlags().BoolVar(&hooksWatch, "hooksWatch", true, "auto restart on JS hook changes")
|
||||
|
||||
var hooksPool int
|
||||
app.RootCmd.PersistentFlags().IntVar(&hooksPool, "hooksPool", 15, "the number of prewarmed JS runtimes")
|
||||
|
||||
var migrationsDir string
|
||||
app.RootCmd.PersistentFlags().StringVar(&migrationsDir, "migrationsDir", "", "the directory with JS migrations")
|
||||
|
||||
var automigrate bool
|
||||
app.RootCmd.PersistentFlags().BoolVar(&automigrate, "automigrate", true, "enable automatic migrations")
|
||||
|
||||
var publicDir string
|
||||
app.RootCmd.PersistentFlags().StringVar(&publicDir, "publicDir", defaultPublicDir(), "the static files directory")
|
||||
|
||||
var indexFallback bool
|
||||
app.RootCmd.PersistentFlags().BoolVar(&indexFallback, "indexFallback", false, "serve index.html for missing paths")
|
||||
|
||||
_ = app.RootCmd.ParseFlags(os.Args[1:])
|
||||
|
||||
jsvm.MustRegister(app, jsvm.Config{
|
||||
MigrationsDir: migrationsDir,
|
||||
HooksDir: hooksDir,
|
||||
HooksWatch: hooksWatch,
|
||||
HooksPoolSize: hooksPool,
|
||||
})
|
||||
migratecmd.MustRegister(app, app.RootCmd, migratecmd.Config{
|
||||
TemplateLang: migratecmd.TemplateLangJS,
|
||||
Automigrate: automigrate,
|
||||
Dir: migrationsDir,
|
||||
})
|
||||
|
||||
registerHomarrProvider(app)
|
||||
app.OnServe().Bind(&hook.Handler[*core.ServeEvent]{
|
||||
Func: func(event *core.ServeEvent) error {
|
||||
if !event.Router.HasRoute(http.MethodGet, "/{path...}") {
|
||||
event.Router.GET("/{path...}", staticWebsite(os.DirFS(publicDir), indexFallback)).Bind(
|
||||
staticCompression(),
|
||||
)
|
||||
}
|
||||
return event.Next()
|
||||
},
|
||||
Priority: 999,
|
||||
})
|
||||
|
||||
if err := app.Start(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func staticCompression() *hook.Handler[*core.RequestEvent] {
|
||||
compression := apis.GzipWithConfig(apis.GzipConfig{Level: gzip.BestSpeed, MinLength: 1024})
|
||||
compress := compression.Func
|
||||
compression.Func = func(event *core.RequestEvent) error {
|
||||
// A compressed 206 response no longer matches its Content-Range and cannot be cached as a video range.
|
||||
if event.Request.Header.Get("Range") != "" || isCompressedAsset(event.Request.URL.Path) {
|
||||
return event.Next()
|
||||
}
|
||||
// PocketBase's middleware matches "gzip" without checking its quality value.
|
||||
// Respect clients that explicitly refuse it before delegating compression.
|
||||
for _, encoding := range strings.Split(event.Request.Header.Get("Accept-Encoding"), ",") {
|
||||
name, parameters, _ := strings.Cut(encoding, ";")
|
||||
if !strings.EqualFold(strings.TrimSpace(name), "gzip") {
|
||||
continue
|
||||
}
|
||||
for _, parameter := range strings.Split(parameters, ";") {
|
||||
key, value, found := strings.Cut(parameter, "=")
|
||||
if !found || !strings.EqualFold(strings.TrimSpace(key), "q") {
|
||||
continue
|
||||
}
|
||||
quality, err := strconv.ParseFloat(strings.TrimSpace(value), 64)
|
||||
if err != nil || quality <= 0 {
|
||||
event.Response.Header().Add("Vary", "Accept-Encoding")
|
||||
return event.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
return compress(event)
|
||||
}
|
||||
return compression
|
||||
}
|
||||
|
||||
func isCompressedAsset(path string) bool {
|
||||
switch strings.ToLower(filepath.Ext(path)) {
|
||||
case ".avif", ".gif", ".ico", ".jpeg", ".jpg", ".mp4", ".png", ".webm", ".webp", ".woff", ".woff2":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func staticWebsite(fsys fs.FS, indexFallback bool) func(*core.RequestEvent) error {
|
||||
serve := apis.Static(fsys, indexFallback)
|
||||
return func(event *core.RequestEvent) error {
|
||||
event.Response.Header().Set("Cache-Control", staticCacheControl(event.Request.URL.Path))
|
||||
if event.Request.URL.RawQuery != "" {
|
||||
// PocketBase's canonical file/directory redirects omit the request query.
|
||||
event.Response = &staticRedirectResponse{event.Response, event.Request.URL.RawQuery}
|
||||
}
|
||||
err := serve(event)
|
||||
if err != nil {
|
||||
event.Response.Header().Set("Cache-Control", "no-store")
|
||||
}
|
||||
if !errors.Is(err, router.ErrFileNotFound) || strings.HasPrefix(event.Request.URL.Path, "/api/") {
|
||||
return err
|
||||
}
|
||||
page, readErr := fs.ReadFile(fsys, "404.html")
|
||||
if readErr != nil {
|
||||
return err
|
||||
}
|
||||
event.Response.Header().Set("Cache-Control", "no-store")
|
||||
return event.HTML(http.StatusNotFound, string(page))
|
||||
}
|
||||
}
|
||||
|
||||
func staticCacheControl(path string) string {
|
||||
if path == "/workshop-runtime-config.js" {
|
||||
return "no-store"
|
||||
}
|
||||
for _, prefix := range []string{"/workshop", "/marketplace"} {
|
||||
if path == prefix || strings.HasPrefix(path, prefix+"/") {
|
||||
return "no-store"
|
||||
}
|
||||
}
|
||||
if strings.HasPrefix(path, "/_next/static/") {
|
||||
return "public, max-age=31536000, immutable"
|
||||
}
|
||||
for _, prefix := range []string{"/img/", "/media/", "/videos/", "/data/", "/custom-widgets/"} {
|
||||
if strings.HasPrefix(path, prefix) {
|
||||
return "public, max-age=600, s-maxage=86400"
|
||||
}
|
||||
}
|
||||
switch strings.ToLower(filepath.Ext(path)) {
|
||||
case ".avif", ".gif", ".ico", ".jpeg", ".jpg", ".mp4", ".png", ".svg", ".ttf", ".webm", ".webp", ".woff", ".woff2":
|
||||
return "public, max-age=600, s-maxage=86400"
|
||||
default:
|
||||
return "public, max-age=60, s-maxage=300"
|
||||
}
|
||||
}
|
||||
|
||||
type staticRedirectResponse struct {
|
||||
http.ResponseWriter
|
||||
query string
|
||||
}
|
||||
|
||||
func (response *staticRedirectResponse) WriteHeader(status int) {
|
||||
if location := response.Header().Get("Location"); status == http.StatusMovedPermanently && location != "" {
|
||||
response.Header().Set("Location", location+"?"+response.query)
|
||||
}
|
||||
response.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func defaultPublicDir() string {
|
||||
if osutils.IsProbablyGoRun() {
|
||||
return "./pb_public"
|
||||
}
|
||||
return filepath.Join(os.Args[0], "../pb_public")
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>New Comment on Homarr Workshop</title>
|
||||
</head>
|
||||
<body style="margin: 0; padding: 0; background-color: #f4f4f4; font-family: Helvetica, Arial, sans-serif">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color: #f4f4f4">
|
||||
<tr>
|
||||
<td align="center" style="padding: 50px 20px">
|
||||
<table
|
||||
role="presentation"
|
||||
width="600"
|
||||
cellpadding="0"
|
||||
cellspacing="0"
|
||||
style="width: 600px; max-width: 100%; background-color: #ffffff; border: 1px solid #000000"
|
||||
>
|
||||
<!-- Header -->
|
||||
<tr>
|
||||
<td align="center" style="background-color: #000000; padding: 36px 20px">
|
||||
<a href="https://homarr.dev" target="_blank" style="text-decoration: none">
|
||||
<img
|
||||
src="https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/homarr-wordmark-light.png"
|
||||
alt="Homarr"
|
||||
width="170"
|
||||
style="display: block; width: 170px; height: auto; border: 0; margin: 0 auto"
|
||||
/>
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Body -->
|
||||
<tr>
|
||||
<td style="padding: 45px 40px; color: #000000; font-size: 15px; line-height: 1.7">
|
||||
<p style="margin: 0 0 18px 0">Hi there,</p>
|
||||
<p style="margin: 0 0 18px 0">
|
||||
<strong>{{commenterName}}</strong> left a comment on your submission
|
||||
<strong>{{submissionTitle}}</strong>:
|
||||
</p>
|
||||
<blockquote
|
||||
style="
|
||||
margin: 0 0 24px 0;
|
||||
padding: 16px 20px;
|
||||
border-left: 3px solid #000000;
|
||||
background-color: #f9f9f9;
|
||||
color: #555555;
|
||||
"
|
||||
>
|
||||
{{commentExcerpt}}
|
||||
</blockquote>
|
||||
|
||||
<!-- CTA button -->
|
||||
<table role="presentation" cellpadding="0" cellspacing="0">
|
||||
<tr>
|
||||
<td align="center" style="background-color: #000000">
|
||||
<a
|
||||
href="{{submissionUrl}}"
|
||||
target="_blank"
|
||||
style="
|
||||
display: inline-block;
|
||||
padding: 12px 28px;
|
||||
color: #ffffff;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
letter-spacing: 0.5px;
|
||||
"
|
||||
>
|
||||
VIEW THE COMMENT
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<!-- Divider -->
|
||||
<tr>
|
||||
<td style="border-top: 1px solid #000000"></td>
|
||||
</tr>
|
||||
|
||||
<!-- Footer -->
|
||||
<tr>
|
||||
<td align="center" style="padding: 24px 20px; color: #000000; font-size: 12px">
|
||||
<a href="https://homarr.dev" target="_blank" style="color: #000000; text-decoration: underline"
|
||||
>homarr.dev</a
|
||||
>
|
||||
· Homarr — 2026
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,64 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Workshop report</title>
|
||||
</head>
|
||||
<body style="margin: 0; padding: 0; background: #f4f4f4; font-family: Helvetica, Arial, sans-serif">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background: #f4f4f4">
|
||||
<tr>
|
||||
<td align="center" style="padding: 50px 20px">
|
||||
<table
|
||||
role="presentation"
|
||||
width="600"
|
||||
cellpadding="0"
|
||||
cellspacing="0"
|
||||
style="width: 600px; max-width: 100%; background: #ffffff; border: 1px solid #dc2626"
|
||||
>
|
||||
<tr>
|
||||
<td style="background: #991b1b; padding: 28px 36px; color: #ffffff">
|
||||
<div style="font-size: 12px; font-weight: bold; letter-spacing: 1px; text-transform: uppercase">
|
||||
Moderation alert
|
||||
</div>
|
||||
<div style="margin-top: 8px; font-size: 22px; font-weight: bold">
|
||||
A Workshop submission was reported
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 36px; color: #18181b; font-size: 15px; line-height: 1.65">
|
||||
<p style="margin: 0 0 18px">
|
||||
<strong>{{reporterName}}</strong> reported <a href="{{submissionUrl}}">{{submissionTitle}}</a>.
|
||||
</p>
|
||||
<p
|
||||
style="margin: 0 0 8px; font-size: 12px; font-weight: bold; text-transform: uppercase; color: #991b1b"
|
||||
>
|
||||
{{category}}
|
||||
</p>
|
||||
<blockquote
|
||||
style="margin: 0 0 26px; padding: 16px 18px; border-left: 3px solid #dc2626; background: #fef2f2"
|
||||
>
|
||||
{{explanation}}
|
||||
</blockquote>
|
||||
<a
|
||||
href="{{adminUrl}}"
|
||||
style="
|
||||
display: inline-block;
|
||||
padding: 12px 20px;
|
||||
background: #991b1b;
|
||||
color: #ffffff;
|
||||
font-weight: bold;
|
||||
text-decoration: none;
|
||||
"
|
||||
>
|
||||
REVIEW REPORT
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,44 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Workshop submission removed</title>
|
||||
</head>
|
||||
<body style="margin: 0; padding: 0; background: #f4f4f4; font-family: Helvetica, Arial, sans-serif">
|
||||
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background: #f4f4f4">
|
||||
<tr>
|
||||
<td align="center" style="padding: 50px 20px">
|
||||
<table
|
||||
role="presentation"
|
||||
width="600"
|
||||
cellpadding="0"
|
||||
cellspacing="0"
|
||||
style="width: 600px; max-width: 100%; background: #ffffff; border: 1px solid #27272a"
|
||||
>
|
||||
<tr>
|
||||
<td style="background: #18181b; padding: 28px 36px; color: #ffffff">
|
||||
<div style="font-size: 12px; font-weight: bold; letter-spacing: 1px; text-transform: uppercase">
|
||||
Homarr Workshop
|
||||
</div>
|
||||
<div style="margin-top: 8px; font-size: 22px; font-weight: bold">Your submission was removed</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 36px; color: #18181b; font-size: 15px; line-height: 1.65">
|
||||
<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>
|
||||
<p style="margin: 0">
|
||||
The submission is no longer available in Workshop. Widgets or CSS already installed by users are not
|
||||
removed from their Homarr instances.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,68 @@
|
||||
const rejectRequest = (message) => {
|
||||
throw new BadRequestError(message);
|
||||
};
|
||||
|
||||
const escapeHtml = (value) =>
|
||||
String(value)
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
|
||||
const renderWorkshopSocialHtml = (html, metadata) => {
|
||||
const title = escapeHtml(metadata.title);
|
||||
const description = escapeHtml(metadata.description);
|
||||
const url = escapeHtml(metadata.url);
|
||||
const image = escapeHtml(metadata.image);
|
||||
const imageAlt = escapeHtml(`${metadata.submissionTitle} preview`);
|
||||
const section = escapeHtml(metadata.section);
|
||||
const tags = [
|
||||
`<title>${title}</title>`,
|
||||
`<meta name="description" content="${description}">`,
|
||||
`<link rel="canonical" href="${url}">`,
|
||||
`<meta property="og:type" content="article">`,
|
||||
`<meta property="og:site_name" content="Homarr Workshop">`,
|
||||
`<meta property="og:title" content="${title}">`,
|
||||
`<meta property="og:description" content="${description}">`,
|
||||
`<meta property="og:url" content="${url}">`,
|
||||
`<meta property="article:section" content="${section}">`,
|
||||
`<meta name="twitter:card" content="summary_large_image">`,
|
||||
`<meta name="twitter:title" content="${title}">`,
|
||||
`<meta name="twitter:description" content="${description}">`,
|
||||
`<meta property="og:image" content="${image}">`,
|
||||
`<meta property="og:image:alt" content="${imageAlt}">`,
|
||||
`<meta name="twitter:image" content="${image}">`,
|
||||
`<meta name="twitter:image:alt" content="${imageAlt}">`,
|
||||
].join("\n");
|
||||
const replaceableTags =
|
||||
/<title\b[^>]*>[\s\S]*?<\/title>|<meta\b[^>]*(?:name|property)=["'](?:robots|description|og:(?:title|description|url|image|image:alt|type|site_name)|twitter:(?:card|title|description|image|image:alt)|article:section)["'][^>]*>|<link\b[^>]*rel=["']canonical["'][^>]*>/gi;
|
||||
|
||||
return html.replace(replaceableTags, "").replace("<head>", `<head>\n${tags}`);
|
||||
};
|
||||
|
||||
const emailTemplate = (filename) => {
|
||||
const hooksPath = $os.getenv("WORKSHOP_PB_HOOKS_DIR") || __hooks;
|
||||
return $os.readFile($filepath.join(hooksPath, filename));
|
||||
};
|
||||
|
||||
const sendEmail = (app, recipientEmail, subject, text, html) => {
|
||||
const sender = app.settings().meta;
|
||||
app.newMailClient().send(
|
||||
new MailerMessage({
|
||||
from: { address: sender.senderAddress, name: sender.senderName },
|
||||
to: [{ address: recipientEmail }],
|
||||
subject,
|
||||
text,
|
||||
html,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
emailTemplate,
|
||||
escapeHtml,
|
||||
rejectRequest,
|
||||
renderWorkshopSocialHtml,
|
||||
sendEmail,
|
||||
};
|
||||
@@ -0,0 +1,263 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
onBootstrap((event) => {
|
||||
const clientId = String($os.getenv("GITHUB_CLIENT_ID") || "").trim();
|
||||
const clientSecret = String($os.getenv("GITHUB_CLIENT_SECRET") || "").trim();
|
||||
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);
|
||||
event.next();
|
||||
const users = event.app.findCollectionByNameOrId("users");
|
||||
users.oauth2.enabled = configured;
|
||||
users.oauth2.mappedFields = { id: "", name: "", username: "name", avatarURL: "" };
|
||||
users.oauth2.providers = configured ? [{ name: "github", clientId, clientSecret }] : [];
|
||||
event.app.save(users);
|
||||
console.log(JSON.stringify({ event: "workshop_oauth_synchronized", enabled: configured }));
|
||||
});
|
||||
|
||||
const workshopDetailPage = (event) => {
|
||||
const id = event.request.pathValue("id");
|
||||
if (id === "admin") return event.fileFS($os.dirFS("/pb_public"), "workshop/admin/index.html");
|
||||
|
||||
const indexHtml = toString($os.readFile("/pb_public/404.html"));
|
||||
const remoteApiUrl = String($os.getenv("WORKSHOP_REMOTE_API_URL") || "")
|
||||
.replace(/\/$/, "")
|
||||
.replace(/\/api$/, "");
|
||||
try {
|
||||
const { renderWorkshopSocialHtml } = require(`${__hooks}/workshop-utils.js`);
|
||||
let submission;
|
||||
if (remoteApiUrl) {
|
||||
const response = $http.send({
|
||||
url: `${remoteApiUrl}/api/collections/workshop_listings/records/${encodeURIComponent(id)}`,
|
||||
timeout: 5,
|
||||
});
|
||||
if (response.statusCode === 404) return event.html(404, indexHtml);
|
||||
if (response.statusCode !== 200) return event.html(503, indexHtml);
|
||||
submission = response.json;
|
||||
} else {
|
||||
const record = event.app.findRecordById("submissions", id);
|
||||
submission = {
|
||||
id: record.id,
|
||||
type: record.getString("type"),
|
||||
title: record.getString("title"),
|
||||
description: record.getString("description"),
|
||||
screenshots: record.getStringSlice("screenshots"),
|
||||
};
|
||||
}
|
||||
const type = submission.type;
|
||||
const section = type === "customCss" ? "Custom CSS" : "Custom widget";
|
||||
const submissionTitle = submission.title;
|
||||
const title = `${submissionTitle} · Homarr Workshop`;
|
||||
const description = `${section} for Homarr. ${submission.description}`.trim();
|
||||
const workshopUrl = $os.getenv("WORKSHOP_WEB_URL").replace(/\/$/, "");
|
||||
const apiUrl = remoteApiUrl || $os.getenv("WORKSHOP_API_URL").replace(/\/$/, "");
|
||||
const websiteUrl = $os.getenv("HOMARR_WEBSITE_URL").replace(/\/$/, "");
|
||||
const screenshot = submission.screenshots[0];
|
||||
const image = screenshot
|
||||
? `${apiUrl}/api/files/submissions/${submission.id}/${encodeURIComponent(screenshot)}`
|
||||
: `${websiteUrl}/img/logo.png`;
|
||||
|
||||
return event.html(
|
||||
200,
|
||||
renderWorkshopSocialHtml(indexHtml, {
|
||||
title,
|
||||
description,
|
||||
url: `${workshopUrl}/${submission.id}`,
|
||||
image,
|
||||
section,
|
||||
submissionTitle,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
return event.html(remoteApiUrl ? 503 : 404, indexHtml);
|
||||
}
|
||||
};
|
||||
|
||||
routerAdd("GET", "/workshop/{id}", workshopDetailPage);
|
||||
routerAdd("GET", "/workshop/{id}/{$}", workshopDetailPage);
|
||||
|
||||
onRecordCreateRequest((event) => {
|
||||
event.record.set("revision", 1);
|
||||
event.record.set("expectedRevision", 0);
|
||||
event.record.set("changelog", "");
|
||||
event.record.set("outdated", false);
|
||||
event.next();
|
||||
}, "submissions");
|
||||
|
||||
onRecordUpdateRequest((event) => {
|
||||
const { rejectRequest } = require(`${__hooks}/workshop-utils.js`);
|
||||
const original = event.record.original();
|
||||
const currentRevision = original.getInt("revision");
|
||||
const expectedRevision = event.record.getInt("expectedRevision");
|
||||
if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 1) {
|
||||
rejectRequest("Submission changed since it was read");
|
||||
}
|
||||
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");
|
||||
|
||||
onRecordAfterCreateSuccess((event) => {
|
||||
try {
|
||||
const votes = event.app.findCollectionByNameOrId("votes");
|
||||
const vote = new Record(votes);
|
||||
vote.set("submission", event.record.id);
|
||||
vote.set("user", event.record.get("author"));
|
||||
vote.set("value", 1);
|
||||
event.app.save(vote);
|
||||
} catch (error) {
|
||||
console.log(`Workshop initial upvote failed for ${event.record.id}: ${error}`);
|
||||
}
|
||||
event.next();
|
||||
}, "submissions");
|
||||
|
||||
onRecordAfterCreateSuccess((event) => {
|
||||
try {
|
||||
const { emailTemplate, escapeHtml, sendEmail } = require(`${__hooks}/workshop-utils.js`);
|
||||
const submission = event.app.findRecordById("submissions", event.record.get("submission"));
|
||||
const recipient = event.app.findRecordById("users", submission.get("author"));
|
||||
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();
|
||||
return;
|
||||
}
|
||||
|
||||
const commenterName = commenter.getString("name") || "A community member";
|
||||
const submissionTitle = submission.getString("title");
|
||||
const rawExcerpt = event.record.getString("content").slice(0, 280);
|
||||
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
|
||||
const template = emailTemplate("comment-email.html")
|
||||
.replaceAll("{{commenterName}}", escapeHtml(commenterName))
|
||||
.replaceAll("{{submissionTitle}}", escapeHtml(submissionTitle))
|
||||
.replaceAll("{{commentExcerpt}}", escapeHtml(rawExcerpt))
|
||||
.replaceAll("{{submissionUrl}}", escapeHtml(submissionUrl));
|
||||
|
||||
sendEmail(
|
||||
event.app,
|
||||
recipientEmail,
|
||||
`${commenterName} commented on ${submissionTitle}`,
|
||||
`${commenterName} commented on “${submissionTitle}”:\n\n${rawExcerpt}\n\n${submissionUrl}`,
|
||||
template,
|
||||
);
|
||||
} catch (error) {
|
||||
console.log(`Workshop comment email failed for ${event.record.id}: ${error}`);
|
||||
}
|
||||
event.next();
|
||||
}, "comments");
|
||||
|
||||
onRecordAfterCreateSuccess((event) => {
|
||||
try {
|
||||
const { emailTemplate, escapeHtml, sendEmail } = require(`${__hooks}/workshop-utils.js`);
|
||||
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) {
|
||||
event.next();
|
||||
return;
|
||||
}
|
||||
|
||||
const reporterName = reporter.getString("name") || "A community member";
|
||||
const submissionTitle = submission.getString("title");
|
||||
const category = event.record.getString("category");
|
||||
const explanation = event.record.getString("explanation");
|
||||
const adminUrl = `${publicWorkshopUrl}/admin`;
|
||||
const submissionUrl = `${publicWorkshopUrl}/${submission.id}/`;
|
||||
const template = emailTemplate("report-email.html")
|
||||
.replaceAll("{{reporterName}}", escapeHtml(reporterName))
|
||||
.replaceAll("{{submissionTitle}}", escapeHtml(submissionTitle))
|
||||
.replaceAll("{{category}}", escapeHtml(category))
|
||||
.replaceAll("{{explanation}}", escapeHtml(explanation))
|
||||
.replaceAll("{{adminUrl}}", escapeHtml(adminUrl))
|
||||
.replaceAll("{{submissionUrl}}", escapeHtml(submissionUrl));
|
||||
|
||||
for (const admin of admins) {
|
||||
try {
|
||||
sendEmail(
|
||||
event.app,
|
||||
admin.email(),
|
||||
`Workshop report: ${submissionTitle}`,
|
||||
`${reporterName} reported “${submissionTitle}” for ${category}.\n\n${explanation}\n\nReview: ${adminUrl}`,
|
||||
template,
|
||||
);
|
||||
} catch (error) {
|
||||
console.log(`Workshop report email failed for admin ${admin.id}: ${error}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`Workshop report email failed for ${event.record.id}: ${error}`);
|
||||
}
|
||||
event.next();
|
||||
}, "reports");
|
||||
|
||||
onRecordDeleteRequest((event) => {
|
||||
const { emailTemplate, escapeHtml, sendEmail } = require(`${__hooks}/workshop-utils.js`);
|
||||
const submissionId = event.record.id;
|
||||
const submissionTitle = event.record.getString("title");
|
||||
const authorId = event.record.get("author");
|
||||
const actor = event.requestInfo().auth;
|
||||
const notifyAuthor = actor && actor.getBool("isAdmin") && actor.id !== authorId;
|
||||
|
||||
event.next();
|
||||
|
||||
if (!notifyAuthor) return;
|
||||
|
||||
try {
|
||||
const author = event.app.findRecordById("users", authorId);
|
||||
const recipientEmail = author.email();
|
||||
if (!recipientEmail) return;
|
||||
|
||||
const publicOrigin = $os.getenv("WORKSHOP_PUBLIC_ORIGIN").replace(/\/$/, "");
|
||||
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 moderator removed your submission “${submissionTitle}”.${
|
||||
workshopUrl ? `\n\nReturn to Workshop: ${workshopUrl}` : ""
|
||||
}`;
|
||||
|
||||
sendEmail(event.app, recipientEmail, `Your Workshop submission was removed`, text, template);
|
||||
} catch (error) {
|
||||
console.log(`Workshop deletion email failed for ${submissionId}: ${error}`);
|
||||
}
|
||||
}, "submissions");
|
||||
@@ -0,0 +1,286 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
const cloneJson = (value) => JSON.parse(JSON.stringify(value));
|
||||
const cloneRule = (value) => (value === null ? null : String(value));
|
||||
const adminRule = "@request.auth.isAdmin = true";
|
||||
const identityFieldsUnchanged = ["@request.body.email:changed = false", "@request.body.name: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) => {
|
||||
let usersExisted = true;
|
||||
let users;
|
||||
try {
|
||||
users = app.findCollectionByNameOrId("users");
|
||||
} catch {
|
||||
usersExisted = false;
|
||||
users = new Collection({ type: "auth", name: "users" });
|
||||
}
|
||||
|
||||
const stateCollection = new Collection({
|
||||
type: "base",
|
||||
name: "workshop_migration_state",
|
||||
listRule: null,
|
||||
viewRule: null,
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [{ type: "text", name: "snapshot", required: true, max: 1_000_000 }],
|
||||
});
|
||||
app.save(stateCollection);
|
||||
const state = {
|
||||
usersExisted,
|
||||
users: usersExisted
|
||||
? {
|
||||
passwordAuth: cloneJson(users.passwordAuth),
|
||||
oauth2: cloneJson(users.oauth2),
|
||||
listRule: cloneRule(users.listRule),
|
||||
viewRule: cloneRule(users.viewRule),
|
||||
createRule: cloneRule(users.createRule),
|
||||
updateRule: cloneRule(users.updateRule),
|
||||
deleteRule: cloneRule(users.deleteRule),
|
||||
}
|
||||
: null,
|
||||
addedUserFields: [],
|
||||
};
|
||||
const addUserField = (field) => {
|
||||
if (users.fields.getByName(field.name)) return;
|
||||
users.fields.add(field);
|
||||
state.addedUserFields.push(field.name);
|
||||
};
|
||||
|
||||
users.passwordAuth = { enabled: false };
|
||||
addUserField(new TextField({ name: "name", required: true, min: 1, max: 39 }));
|
||||
addUserField(new BoolField({ name: "isAdmin" }));
|
||||
|
||||
users.listRule = "";
|
||||
users.viewRule = "";
|
||||
users.createRule = '@request.context = "oauth2" && @request.body.isAdmin:isset = false';
|
||||
users.updateRule = `id = @request.auth.id && @request.body.isAdmin:isset = false && ${identityFieldsUnchanged}`;
|
||||
users.deleteRule = null;
|
||||
app.save(users);
|
||||
const stateRecord = new Record(stateCollection);
|
||||
stateRecord.set("snapshot", JSON.stringify(state));
|
||||
app.save(stateRecord);
|
||||
|
||||
const submissions = new Collection({
|
||||
type: "base",
|
||||
name: "submissions",
|
||||
listRule: "",
|
||||
viewRule: "",
|
||||
createRule: "@request.auth.id != '' && @request.body.author = @request.auth.id",
|
||||
updateRule:
|
||||
`(author = @request.auth.id && ${immutableSubmissionFields}) || ` +
|
||||
`(${adminRule} && author != @request.auth.id && ${immutableSubmissionFields} && ${moderatorSubmissionFieldsUnchanged})`,
|
||||
deleteRule: `author = @request.auth.id || ${adminRule}`,
|
||||
fields: [
|
||||
{ type: "select", name: "type", required: true, maxSelect: 1, values: ["customWidget", "customCss"] },
|
||||
{ type: "text", name: "title", required: true, min: 3, max: 100 },
|
||||
{ type: "text", name: "description", max: 2000 },
|
||||
{ type: "text", name: "widgetSchema", required: true, min: 1, max: 100 },
|
||||
{ type: "text", name: "content", required: true, max: 1000000 },
|
||||
{ type: "number", name: "revision", required: true, onlyInt: true, min: 1 },
|
||||
{ type: "number", name: "expectedRevision", onlyInt: true, min: 0 },
|
||||
{ type: "text", name: "changelog", max: 2000 },
|
||||
{ type: "bool", name: "outdated" },
|
||||
{
|
||||
type: "file",
|
||||
name: "screenshots",
|
||||
maxSelect: 5,
|
||||
maxSize: 5242880,
|
||||
mimeTypes: ["image/png", "image/jpeg", "image/webp"],
|
||||
thumbs: ["480x320", "960x640"],
|
||||
},
|
||||
{ type: "relation", name: "author", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
submissions.addIndex("idx_submissions_author", false, "author", "");
|
||||
submissions.addIndex("idx_submissions_created", false, "created", "");
|
||||
app.save(submissions);
|
||||
app
|
||||
.db()
|
||||
.newQuery(
|
||||
`CREATE TRIGGER submissions_revision_cas
|
||||
BEFORE UPDATE ON submissions
|
||||
FOR EACH ROW
|
||||
WHEN NEW.expectedRevision != OLD.revision OR NEW.revision != OLD.revision + 1
|
||||
BEGIN
|
||||
SELECT RAISE(ABORT, 'submission revision compare-and-swap failed');
|
||||
END`,
|
||||
)
|
||||
.execute();
|
||||
|
||||
const votes = new Collection({
|
||||
type: "base",
|
||||
name: "votes",
|
||||
listRule: "user = @request.auth.id",
|
||||
viewRule: "user = @request.auth.id",
|
||||
createRule:
|
||||
"@request.auth.id != '' && @request.body.user = @request.auth.id && (@request.body.value = 1 || @request.body.value = -1)",
|
||||
updateRule:
|
||||
"user = @request.auth.id && @request.body.user:changed = false && @request.body.submission:changed = false && (@request.body.value = 1 || @request.body.value = -1)",
|
||||
deleteRule: "user = @request.auth.id",
|
||||
fields: [
|
||||
{
|
||||
type: "relation",
|
||||
name: "submission",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
collectionId: submissions.id,
|
||||
cascadeDelete: true,
|
||||
},
|
||||
{ type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
|
||||
{ type: "number", name: "value", required: true, onlyInt: true, min: -1, max: 1 },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
votes.addIndex("idx_votes_user_submission", true, "user, submission", "");
|
||||
votes.addIndex("idx_votes_submission", false, "submission", "");
|
||||
app.save(votes);
|
||||
|
||||
const comments = new Collection({
|
||||
type: "base",
|
||||
name: "comments",
|
||||
listRule: "",
|
||||
viewRule: "",
|
||||
createRule: "@request.auth.id != '' && @request.body.author = @request.auth.id",
|
||||
updateRule:
|
||||
"author = @request.auth.id && @request.body.author:changed = false && @request.body.submission:changed = false",
|
||||
deleteRule: `author = @request.auth.id || ${adminRule}`,
|
||||
fields: [
|
||||
{
|
||||
type: "relation",
|
||||
name: "submission",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
collectionId: submissions.id,
|
||||
cascadeDelete: true,
|
||||
},
|
||||
{ type: "relation", name: "author", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
|
||||
{ type: "text", name: "content", required: true, min: 1, max: 2000 },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
comments.addIndex("idx_comments_submission", false, "submission", "");
|
||||
app.save(comments);
|
||||
|
||||
const reports = new Collection({
|
||||
type: "base",
|
||||
name: "reports",
|
||||
listRule: adminRule,
|
||||
viewRule: adminRule,
|
||||
createRule: "@request.auth.id != '' && @request.body.reporter = @request.auth.id",
|
||||
updateRule:
|
||||
`${adminRule} && ` +
|
||||
"@request.body.reporter:changed = false && " +
|
||||
"@request.body.submission:changed = false && " +
|
||||
"@request.body.category:changed = false && " +
|
||||
"@request.body.explanation:changed = false",
|
||||
deleteRule: adminRule,
|
||||
fields: [
|
||||
{
|
||||
type: "relation",
|
||||
name: "submission",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
collectionId: submissions.id,
|
||||
cascadeDelete: true,
|
||||
},
|
||||
{
|
||||
type: "relation",
|
||||
name: "reporter",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
collectionId: users.id,
|
||||
cascadeDelete: true,
|
||||
},
|
||||
{
|
||||
type: "select",
|
||||
name: "category",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
values: ["outdated", "malicious", "spam", "copyright", "inappropriate", "other"],
|
||||
},
|
||||
{ type: "text", name: "explanation", required: true, min: 3, max: 1000 },
|
||||
{ type: "select", name: "status", required: true, maxSelect: 1, values: ["open", "dismissed"] },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
reports.addIndex("idx_reports_reporter_submission", true, "reporter, submission", "");
|
||||
reports.addIndex("idx_reports_created", false, "created", "");
|
||||
app.save(reports);
|
||||
|
||||
const listings = new Collection({
|
||||
type: "view",
|
||||
name: "workshop_listings",
|
||||
listRule: "",
|
||||
viewRule: "",
|
||||
viewQuery: `
|
||||
SELECT s.id, s.type, s.title, s.description, s.widgetSchema, s.screenshots, s.author,
|
||||
u.name AS authorName,
|
||||
s.revision, s.changelog, s.outdated, s.created, s.updated,
|
||||
COALESCE((SELECT COUNT(*) FROM votes v WHERE v.submission = s.id AND v.value = 1), 0) AS upvotes,
|
||||
COALESCE((SELECT COUNT(*) FROM votes v WHERE v.submission = s.id AND v.value = -1), 0) AS downvotes,
|
||||
COALESCE((SELECT SUM(v.value) FROM votes v WHERE v.submission = s.id), 0) AS score,
|
||||
COALESCE((SELECT COUNT(*) FROM comments c WHERE c.submission = s.id), 0) AS commentCount,
|
||||
COALESCE((SELECT COUNT(*) FROM reports r WHERE r.submission = s.id AND r.status = 'open'), 0) AS reportCount
|
||||
FROM submissions s
|
||||
JOIN users u ON u.id = s.author
|
||||
`,
|
||||
});
|
||||
app.save(listings);
|
||||
},
|
||||
(app) => {
|
||||
let stateCollection;
|
||||
let stateRecord;
|
||||
try {
|
||||
stateCollection = app.findCollectionByNameOrId("workshop_migration_state");
|
||||
stateRecord = app.findFirstRecordByFilter(stateCollection.id, "");
|
||||
} catch {
|
||||
throw new Error("Workshop migration cannot be rolled back safely because its state snapshot is missing");
|
||||
}
|
||||
const state = JSON.parse(stateRecord.getString("snapshot"));
|
||||
for (const name of ["workshop_listings", "reports", "comments", "votes", "submissions"]) {
|
||||
try {
|
||||
app.delete(app.findCollectionByNameOrId(name));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
if (state.usersExisted) {
|
||||
users.passwordAuth = state.users.passwordAuth;
|
||||
users.oauth2 = state.users.oauth2;
|
||||
users.listRule = state.users.listRule;
|
||||
users.viewRule = state.users.viewRule;
|
||||
users.createRule = state.users.createRule;
|
||||
users.updateRule = state.users.updateRule;
|
||||
users.deleteRule = state.users.deleteRule;
|
||||
for (const name of state.addedUserFields) {
|
||||
const field = users.fields.getByName(name);
|
||||
if (field) users.fields.removeById(field.id);
|
||||
}
|
||||
app.save(users);
|
||||
} else {
|
||||
app.delete(users);
|
||||
}
|
||||
app.delete(stateCollection);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
const reportReaderRule = "@request.auth.id != '' && (author = @request.auth.id || @request.auth.isAdmin = true)";
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const summaries = new Collection({
|
||||
type: "view",
|
||||
name: "workshop_report_summaries",
|
||||
listRule: reportReaderRule,
|
||||
viewRule: reportReaderRule,
|
||||
viewQuery: `
|
||||
SELECT r.id, r.submission, s.author, r.category, r.explanation, r.created
|
||||
FROM reports r
|
||||
INNER JOIN submissions s ON s.id = r.submission
|
||||
WHERE r.status = 'open'
|
||||
`,
|
||||
});
|
||||
app.save(summaries);
|
||||
},
|
||||
(app) => {
|
||||
app.delete(app.findCollectionByNameOrId("workshop_report_summaries"));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,61 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const users = app.findCollectionByNameOrId("users");
|
||||
const quotas = new Collection({
|
||||
type: "base",
|
||||
name: "assistant_quotas",
|
||||
listRule: null,
|
||||
viewRule: null,
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [
|
||||
{
|
||||
type: "relation",
|
||||
name: "user",
|
||||
required: true,
|
||||
maxSelect: 1,
|
||||
collectionId: users.id,
|
||||
cascadeDelete: true,
|
||||
},
|
||||
{ type: "text", name: "day", required: true, min: 10, max: 10 },
|
||||
{ type: "number", name: "used", onlyInt: true, min: 0 },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
quotas.addIndex("idx_assistant_quotas_user", true, "user", "");
|
||||
app.save(quotas);
|
||||
|
||||
const globalQuota = new Collection({
|
||||
type: "base",
|
||||
name: "assistant_global_quota",
|
||||
listRule: null,
|
||||
viewRule: null,
|
||||
createRule: null,
|
||||
updateRule: null,
|
||||
deleteRule: null,
|
||||
fields: [
|
||||
{ type: "text", name: "key", required: true, min: 1, max: 32 },
|
||||
{ type: "text", name: "day", required: true, min: 10, max: 10 },
|
||||
{ type: "number", name: "used", onlyInt: true, min: 0 },
|
||||
{ type: "autodate", name: "created", onCreate: true },
|
||||
{ type: "autodate", name: "updated", onCreate: true, onUpdate: true },
|
||||
],
|
||||
});
|
||||
globalQuota.addIndex("idx_assistant_global_quota_key", true, "key", "");
|
||||
app.save(globalQuota);
|
||||
|
||||
const globalRecord = new Record(globalQuota);
|
||||
globalRecord.set("key", "default");
|
||||
globalRecord.set("day", "1970-01-01");
|
||||
globalRecord.set("used", 0);
|
||||
app.save(globalRecord);
|
||||
},
|
||||
(app) => {
|
||||
app.delete(app.findCollectionByNameOrId("assistant_global_quota"));
|
||||
app.delete(app.findCollectionByNameOrId("assistant_quotas"));
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,36 @@
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
migrate(
|
||||
(app) => {
|
||||
const quotas = app.findCollectionByNameOrId("assistant_quotas");
|
||||
quotas.removeIndex("idx_assistant_quotas_user");
|
||||
quotas.addIndex("idx_assistant_quotas_user_day", true, "user, day", "");
|
||||
app.save(quotas);
|
||||
},
|
||||
(app) => {
|
||||
const quotas = app.findCollectionByNameOrId("assistant_quotas");
|
||||
quotas.removeIndex("idx_assistant_quotas_user_day");
|
||||
|
||||
// The previous schema can keep only one record per user. Retain the latest UTC day when rolling back.
|
||||
app
|
||||
.db()
|
||||
.newQuery(`
|
||||
DELETE FROM assistant_quotas
|
||||
WHERE id NOT IN (
|
||||
SELECT (
|
||||
SELECT candidate.id
|
||||
FROM assistant_quotas candidate
|
||||
WHERE candidate.user = quota_user.user
|
||||
ORDER BY candidate.day DESC, candidate.created DESC, candidate.id DESC
|
||||
LIMIT 1
|
||||
)
|
||||
FROM assistant_quotas quota_user
|
||||
GROUP BY quota_user.user
|
||||
)
|
||||
`)
|
||||
.execute();
|
||||
|
||||
quotas.addIndex("idx_assistant_quotas_user", true, "user", "");
|
||||
app.save(quotas);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
|
||||
cd "$repo_dir"
|
||||
|
||||
preview_name=${DOCS_PREVIEW_NAME:-homarr-docs-static-preview}
|
||||
preview_host=${DOCS_PREVIEW_HOST:-127.0.0.1}
|
||||
preview_port=${DOCS_PREVIEW_PORT:-8093}
|
||||
preview_image=homarr-workshop:docs-static-preview
|
||||
preview_url="http://$preview_host:$preview_port"
|
||||
api_url=${WORKSHOP_API_URL:-$preview_url}
|
||||
api_url=${api_url%/}
|
||||
api_url=${api_url%/api}
|
||||
remote_api_url=${WORKSHOP_REMOTE_API_URL:-${WORKSHOP_API_URL:-}}
|
||||
remote_api_url=${remote_api_url%/}
|
||||
remote_api_url=${remote_api_url%/api}
|
||||
|
||||
if [ ! -f apps/docs/out/404.html ]; then
|
||||
echo 'Build the docs first: pnpm --filter @homarr/docs build' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
docker build --target development -f apps/workshop/Dockerfile -t "$preview_image" .
|
||||
docker run --detach --rm --name "$preview_name" \
|
||||
--user "$(id -u):$(id -g)" \
|
||||
--publish "$preview_host:$preview_port:8090" \
|
||||
--mount "type=bind,src=$repo_dir/apps/docs/out,dst=/pb_public" \
|
||||
--mount "type=bind,src=$repo_dir/apps/workshop/pb_hooks,dst=/pb_hooks,readonly" \
|
||||
--mount "type=bind,src=$repo_dir/apps/workshop/pb_migrations,dst=/pb_migrations,readonly" \
|
||||
--tmpfs "/pb_data:uid=$(id -u),gid=$(id -g)" \
|
||||
--env "HOMARR_WEBSITE_URL=$preview_url" \
|
||||
--env "WORKSHOP_API_URL=$api_url" \
|
||||
--env "WORKSHOP_REMOTE_API_URL=$remote_api_url" \
|
||||
--env "WORKSHOP_WEB_URL=$preview_url/workshop" \
|
||||
"$preview_image"
|
||||
|
||||
attempt=0
|
||||
until docker exec "$preview_name" wget -q --spider http://127.0.0.1:8090/api/health >/dev/null 2>&1; do
|
||||
attempt=$((attempt + 1))
|
||||
if [ "$attempt" -ge 30 ]; then
|
||||
echo "Preview did not become healthy. Inspect it with: docker logs $preview_name" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
printf 'Static docs: %s/docs/\nWorkshop API: %s\nStop: docker stop %s\n' "$preview_url" "$api_url" "$preview_name"
|
||||
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"github.com/pocketbase/pocketbase/apis"
|
||||
"github.com/pocketbase/pocketbase/core"
|
||||
"github.com/pocketbase/pocketbase/tools/router"
|
||||
)
|
||||
|
||||
func TestStaticWebsite(t *testing.T) {
|
||||
files := fstest.MapFS{
|
||||
"index.html": {Data: []byte("Home")},
|
||||
"404.html": {Data: []byte("Page not found")},
|
||||
"api/search": {Data: []byte(`{"type":"advanced"}`)},
|
||||
"llms.txt": {Data: []byte("# Docs")},
|
||||
"docs/index.html": {Data: []byte("Documentation")},
|
||||
}
|
||||
for _, scenario := range []struct {
|
||||
path string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"/docs/missing", http.StatusNotFound, "Page not found"},
|
||||
{"/api/search?q=board", http.StatusOK, `{"type":"advanced"}`},
|
||||
{"/llms.txt", http.StatusOK, "# Docs"},
|
||||
} {
|
||||
t.Run(scenario.path, func(t *testing.T) {
|
||||
event := new(core.RequestEvent)
|
||||
event.Request = httptest.NewRequest(http.MethodGet, scenario.path, nil)
|
||||
event.Request.SetPathValue(apis.StaticWildcardParam, strings.TrimPrefix(event.Request.URL.Path, "/"))
|
||||
response := httptest.NewRecorder()
|
||||
event.Response = response
|
||||
if err := staticWebsite(files, false)(event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != scenario.status || response.Body.String() != scenario.body {
|
||||
t.Fatalf("got %d %q", response.Code, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
event := new(core.RequestEvent)
|
||||
event.Request = httptest.NewRequest(http.MethodGet, "/api/missing", nil)
|
||||
event.Request.SetPathValue(apis.StaticWildcardParam, "api/missing")
|
||||
event.Response = httptest.NewRecorder()
|
||||
if err := staticWebsite(files, false)(event); !errors.Is(err, router.ErrFileNotFound) {
|
||||
t.Fatalf("missing API should retain API error, got %v", err)
|
||||
}
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
event := new(core.RequestEvent)
|
||||
event.Request = httptest.NewRequest(method, "/docs?example=1", nil)
|
||||
event.Request.SetPathValue(apis.StaticWildcardParam, "docs")
|
||||
response := httptest.NewRecorder()
|
||||
event.Response = response
|
||||
if err := staticWebsite(files, false)(event); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusMovedPermanently || response.Header().Get("Location") != "/docs/?example=1" {
|
||||
t.Fatalf("%s redirect lost query: %d %s", method, response.Code, response.Header().Get("Location"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
WORKSHOP_IMAGE_TEST_PORT=${WORKSHOP_IMAGE_TEST_PORT:-18091}
|
||||
WORKSHOP_IMAGE_TEST_NAME="homarr-workshop-image-test-$$"
|
||||
WORKSHOP_IMAGE_TEST_RESTORED_NAME="homarr-workshop-image-restored-$$"
|
||||
WORKSHOP_IMAGE_TEST_TAG=${WORKSHOP_IMAGE_TEST_IMAGE:-homarr-workshop:test-$$}
|
||||
WORKSHOP_IMAGE_TEST_VOLUME="homarr-workshop-image-test-$$"
|
||||
WORKSHOP_IMAGE_TEST_RESTORE_VOLUME="homarr-workshop-image-restore-$$"
|
||||
WORKSHOP_IMAGE_TEST_BACKUP_DIR=$(mktemp -d)
|
||||
WORKSHOP_IMAGE_TEST_BACKUP="$WORKSHOP_IMAGE_TEST_BACKUP_DIR/pb-data.tar"
|
||||
TEST_WEBSITE_URL=https://docs.example.invalid
|
||||
TEST_API_URL=https://api.example.invalid
|
||||
TEST_WORKSHOP_URL=https://workshop.example.invalid
|
||||
|
||||
cleanup() {
|
||||
docker rm --force "$WORKSHOP_IMAGE_TEST_NAME" "$WORKSHOP_IMAGE_TEST_RESTORED_NAME" >/dev/null 2>&1 || true
|
||||
docker volume rm "$WORKSHOP_IMAGE_TEST_VOLUME" "$WORKSHOP_IMAGE_TEST_RESTORE_VOLUME" >/dev/null 2>&1 || true
|
||||
rm -rf "$WORKSHOP_IMAGE_TEST_BACKUP_DIR"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
verify_persisted_data() {
|
||||
WORKSHOP_TEST_URL="$1" node --input-type=module -e '
|
||||
import assert from "node:assert/strict";
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL;
|
||||
const response = await fetch(`${baseUrl}/api/collections/_superusers/auth-with-password`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ identity: "workshop-image@example.invalid", password: "WorkshopImageTest123!" }),
|
||||
});
|
||||
assert.equal(response.status, 200, "superuser must survive restart or restore");
|
||||
const { token } = await response.json();
|
||||
const headers = { authorization: `Bearer ${token}` };
|
||||
const usersResponse = await fetch(`${baseUrl}/api/collections/users/records?perPage=200`, { headers });
|
||||
assert.equal(usersResponse.status, 200);
|
||||
const users = await usersResponse.json();
|
||||
const author = users.items.find((user) => user.email === "social-author@example.invalid");
|
||||
assert.ok(author, "user must survive restart or restore");
|
||||
const submissionsResponse = await fetch(`${baseUrl}/api/collections/submissions/records?perPage=200`, { headers });
|
||||
assert.equal(submissionsResponse.status, 200);
|
||||
const submissions = await submissionsResponse.json();
|
||||
const submission = submissions.items.find((item) => item.title === "Ocean <Glow>");
|
||||
assert.ok(submission, "submission must survive restart or restore");
|
||||
assert.equal(submission.author, author.id, "submission author must survive restart or restore");
|
||||
assert.equal(submission.content, "body { color: white; }", "submission content must survive restart or restore");
|
||||
assert.equal(submission.screenshots.length, 1, "screenshot reference must survive restart or restore");
|
||||
const screenshot = encodeURIComponent(submission.screenshots[0]);
|
||||
const screenshotResponse = await fetch(`${baseUrl}/api/files/submissions/${submission.id}/${screenshot}`, { headers });
|
||||
assert.equal(screenshotResponse.status, 200, "screenshot file must survive restart or restore");
|
||||
const expectedScreenshot = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
assert.deepEqual(Buffer.from(await screenshotResponse.arrayBuffer()), expectedScreenshot, "screenshot bytes must survive restart or restore");
|
||||
'
|
||||
}
|
||||
|
||||
docker volume create "$WORKSHOP_IMAGE_TEST_VOLUME" >/dev/null
|
||||
docker volume create "$WORKSHOP_IMAGE_TEST_RESTORE_VOLUME" >/dev/null
|
||||
|
||||
if [ -z "${WORKSHOP_IMAGE_TEST_IMAGE:-}" ]; then
|
||||
docker build --target production -f apps/workshop/Dockerfile -t "$WORKSHOP_IMAGE_TEST_TAG" .
|
||||
fi
|
||||
docker run --detach --name "$WORKSHOP_IMAGE_TEST_NAME" \
|
||||
--publish "127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT:8090" \
|
||||
--mount "type=volume,source=$WORKSHOP_IMAGE_TEST_VOLUME,target=/pb_data" \
|
||||
--env HOMARR_WEBSITE_URL="$TEST_WEBSITE_URL" \
|
||||
--env WORKSHOP_API_URL="$TEST_API_URL" \
|
||||
--env WORKSHOP_WEB_URL="$TEST_WORKSHOP_URL" \
|
||||
--env WORKSHOP_PUBLIC_ORIGIN="$TEST_API_URL" \
|
||||
--env PB_ALLOWED_ORIGINS='*' \
|
||||
"$WORKSHOP_IMAGE_TEST_TAG" >/dev/null
|
||||
|
||||
for attempt in $(seq 1 60); do
|
||||
if curl --fail --silent "http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT/api/health" >/dev/null; then
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -eq 60 ]; then
|
||||
docker logs "$WORKSHOP_IMAGE_TEST_NAME"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT" \
|
||||
EXPECTED_HOMARR_WEBSITE_URL="$TEST_WEBSITE_URL" \
|
||||
EXPECTED_WORKSHOP_API_URL="$TEST_API_URL" \
|
||||
EXPECTED_WORKSHOP_WEB_URL="$TEST_WORKSHOP_URL" \
|
||||
node apps/workshop/tests/runtime-config.integration.mjs
|
||||
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT" \
|
||||
node apps/workshop/tests/static-export.integration.mjs
|
||||
|
||||
docker exec "$WORKSHOP_IMAGE_TEST_NAME" pocketbase superuser create \
|
||||
workshop-image@example.invalid 'WorkshopImageTest123!' --dir=/pb_data
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT" \
|
||||
EXPECTED_HOMARR_WEBSITE_URL="$TEST_WEBSITE_URL" \
|
||||
EXPECTED_WORKSHOP_API_URL="$TEST_API_URL" \
|
||||
EXPECTED_WORKSHOP_WEB_URL="$TEST_WORKSHOP_URL" \
|
||||
node apps/workshop/tests/workshop-social-metadata.integration.mjs
|
||||
|
||||
curl --fail --location --silent "http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT/workshop" >/dev/null
|
||||
curl --fail --silent \
|
||||
"http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT/api/collections/workshop_listings/records?perPage=1" >/dev/null
|
||||
curl --fail --silent --dump-header - --output /dev/null \
|
||||
--header 'Origin: https://homarr.example' \
|
||||
"http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT/api/collections/workshop_listings/records?perPage=1" \
|
||||
| tr -d '\r' \
|
||||
| grep -qi '^Access-Control-Allow-Origin: \*$'
|
||||
|
||||
docker stop "$WORKSHOP_IMAGE_TEST_NAME" >/dev/null
|
||||
mkdir -p "$WORKSHOP_IMAGE_TEST_BACKUP_DIR/data"
|
||||
docker cp "$WORKSHOP_IMAGE_TEST_NAME:/pb_data/." "$WORKSHOP_IMAGE_TEST_BACKUP_DIR/data"
|
||||
test -s "$WORKSHOP_IMAGE_TEST_BACKUP_DIR/data/data.db"
|
||||
tar -C "$WORKSHOP_IMAGE_TEST_BACKUP_DIR/data" -cf "$WORKSHOP_IMAGE_TEST_BACKUP" .
|
||||
docker rm "$WORKSHOP_IMAGE_TEST_NAME" >/dev/null
|
||||
|
||||
docker run --detach --name "$WORKSHOP_IMAGE_TEST_NAME" \
|
||||
--publish "127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT:8090" \
|
||||
--mount "type=volume,source=$WORKSHOP_IMAGE_TEST_VOLUME,target=/pb_data" \
|
||||
--env HOMARR_WEBSITE_URL="$TEST_WEBSITE_URL" \
|
||||
--env WORKSHOP_API_URL="$TEST_API_URL" \
|
||||
--env WORKSHOP_WEB_URL="$TEST_WORKSHOP_URL" \
|
||||
--env WORKSHOP_PUBLIC_ORIGIN="$TEST_API_URL" \
|
||||
--env PB_ALLOWED_ORIGINS='*' \
|
||||
"$WORKSHOP_IMAGE_TEST_TAG" >/dev/null
|
||||
|
||||
for attempt in $(seq 1 60); do
|
||||
if curl --fail --silent "http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT/api/health" >/dev/null; then
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -eq 60 ]; then
|
||||
docker logs "$WORKSHOP_IMAGE_TEST_NAME"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
verify_persisted_data "http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT"
|
||||
echo "Workshop named-volume persistence passed"
|
||||
|
||||
docker stop "$WORKSHOP_IMAGE_TEST_NAME" >/dev/null
|
||||
docker rm "$WORKSHOP_IMAGE_TEST_NAME" >/dev/null
|
||||
docker run --rm \
|
||||
--mount "type=volume,source=$WORKSHOP_IMAGE_TEST_RESTORE_VOLUME,target=/pb_data" \
|
||||
--mount "type=bind,source=$WORKSHOP_IMAGE_TEST_BACKUP,target=/tmp/pb-data.tar,readonly" \
|
||||
--entrypoint sh \
|
||||
"$WORKSHOP_IMAGE_TEST_TAG" \
|
||||
-c 'tar -C /pb_data -xf /tmp/pb-data.tar'
|
||||
|
||||
docker run --detach --name "$WORKSHOP_IMAGE_TEST_RESTORED_NAME" \
|
||||
--publish "127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT:8090" \
|
||||
--mount "type=volume,source=$WORKSHOP_IMAGE_TEST_RESTORE_VOLUME,target=/pb_data" \
|
||||
--env HOMARR_WEBSITE_URL="$TEST_WEBSITE_URL" \
|
||||
--env WORKSHOP_API_URL="$TEST_API_URL" \
|
||||
--env WORKSHOP_WEB_URL="$TEST_WORKSHOP_URL" \
|
||||
--env WORKSHOP_PUBLIC_ORIGIN="$TEST_API_URL" \
|
||||
--env PB_ALLOWED_ORIGINS='*' \
|
||||
"$WORKSHOP_IMAGE_TEST_TAG" >/dev/null
|
||||
|
||||
for attempt in $(seq 1 60); do
|
||||
if curl --fail --silent "http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT/api/health" >/dev/null; then
|
||||
break
|
||||
fi
|
||||
if [ "$attempt" -eq 60 ]; then
|
||||
docker logs "$WORKSHOP_IMAGE_TEST_RESTORED_NAME"
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
verify_persisted_data "http://127.0.0.1:$WORKSHOP_IMAGE_TEST_PORT"
|
||||
echo "Workshop backup restore passed"
|
||||
|
||||
echo "Workshop production image passed"
|
||||
@@ -0,0 +1,92 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
WORKSHOP_TEST_PORT=${WORKSHOP_TEST_PORT:-18090}
|
||||
WORKSHOP_TEST_PROJECT="homarr-workshop-test-$$"
|
||||
export HOMARR_AI_OPENROUTER_BASE_URL=http://assistant-upstream:18091/api/v1
|
||||
export HOMARR_AI_OPENROUTER_MODEL=mock/team-selected-model
|
||||
export HOMARR_AI_ALLOW_INSECURE_UPSTREAM=true
|
||||
export OPENROUTER_API_KEY=workshop-test-openrouter-key
|
||||
|
||||
docker build --target pocketbase-test -f apps/workshop/Dockerfile .
|
||||
node apps/workshop/tests/workshop-contracts.mjs
|
||||
node apps/workshop/tests/workshop-migration.mjs
|
||||
|
||||
cleanup() {
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose --profile test -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml down --volumes --remove-orphans >/dev/null 2>&1 || true
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
HOMARR_WEBSITE_URL=https://preview.example.invalid \
|
||||
WORKSHOP_API_URL=https://api.preview.example.invalid \
|
||||
WORKSHOP_WEB_URL=https://preview.example.invalid/workshop \
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose --profile test -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml up --build -d
|
||||
|
||||
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
|
||||
PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml logs --no-color workshop
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_TEST_PORT" \
|
||||
EXPECTED_HOMARR_WEBSITE_URL=https://preview.example.invalid \
|
||||
EXPECTED_WORKSHOP_API_URL=https://api.preview.example.invalid \
|
||||
EXPECTED_WORKSHOP_WEB_URL=https://preview.example.invalid/workshop \
|
||||
node apps/workshop/tests/runtime-config.integration.mjs
|
||||
|
||||
docker compose -p "$WORKSHOP_TEST_PROJECT" -f apps/workshop/docker-compose.yml exec -T workshop \
|
||||
pocketbase superuser create \
|
||||
workshop-test@example.invalid 'WorkshopLocalTest123!' --dir=/pb_data
|
||||
|
||||
WORKSHOP_TEST_URL="http://127.0.0.1:$WORKSHOP_TEST_PORT" node apps/workshop/tests/workshop.integration.mjs
|
||||
|
||||
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
|
||||
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" EXPECTED_GITHUB_CLIENT_ID="$client_id" \
|
||||
node apps/workshop/tests/oauth-sync.integration.mjs
|
||||
done
|
||||
|
||||
OPENROUTER_API_KEY="" PB_EXPOSE_PORT="$WORKSHOP_TEST_PORT" docker compose -p "$WORKSHOP_TEST_PROJECT" \
|
||||
-f apps/workshop/docker-compose.yml up -d --force-recreate 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
|
||||
models_status=$(curl --silent --output /dev/null --write-out '%{http_code}' \
|
||||
"http://127.0.0.1:$WORKSHOP_TEST_PORT/api/ai/v1/models")
|
||||
if [ "$models_status" != "503" ]; then
|
||||
echo "Expected an unconfigured Homarr provider to return 503, received $models_status"
|
||||
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" \
|
||||
-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" \
|
||||
-f apps/workshop/docker-compose.yml run --rm --no-deps --entrypoint pocketbase workshop \
|
||||
migrate up --dir=/pb_data --migrationsDir=/pb_migrations
|
||||
@@ -0,0 +1,35 @@
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL ?? "http://127.0.0.1:18090";
|
||||
const expectedClientId = process.env.EXPECTED_GITHUB_CLIENT_ID;
|
||||
if (!expectedClientId) throw new Error("EXPECTED_GITHUB_CLIENT_ID is required");
|
||||
|
||||
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 root = await request("/api/collections/_superusers/auth-with-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ identity: "workshop-test@example.invalid", password: "WorkshopLocalTest123!" }),
|
||||
});
|
||||
const users = await request("/api/collections/users", {
|
||||
headers: { authorization: `Bearer ${root.token}` },
|
||||
});
|
||||
const github = users.oauth2?.providers?.find((provider) => provider.name === "github");
|
||||
if (!users.oauth2?.enabled || github?.clientId !== expectedClientId) {
|
||||
throw new Error(`GitHub OAuth was not synchronized for ${expectedClientId}`);
|
||||
}
|
||||
if (
|
||||
users.oauth2?.mappedFields?.username !== "name" ||
|
||||
users.oauth2?.mappedFields?.id ||
|
||||
users.oauth2?.mappedFields?.name ||
|
||||
users.oauth2?.mappedFields?.avatarURL
|
||||
) {
|
||||
throw new Error(`GitHub OAuth field mapping was not synchronized: ${JSON.stringify(users.oauth2?.mappedFields)}`);
|
||||
}
|
||||
|
||||
console.log(`Workshop OAuth synchronization passed for ${expectedClientId}`);
|
||||
@@ -0,0 +1,52 @@
|
||||
const enabled = process.env.HOMARR_AI_LIVE_SMOKE === "1";
|
||||
if (!enabled)
|
||||
throw new Error("Set HOMARR_AI_LIVE_SMOKE=1 to acknowledge that this check consumes a real provider request");
|
||||
|
||||
const baseUrl = process.env.WORKSHOP_LIVE_TEST_URL?.replace(/\/+$/u, "");
|
||||
const token = process.env.WORKSHOP_LIVE_TEST_TOKEN;
|
||||
if (!baseUrl || !token) {
|
||||
throw new Error("WORKSHOP_LIVE_TEST_URL and WORKSHOP_LIVE_TEST_TOKEN are required");
|
||||
}
|
||||
|
||||
const requestJson = async (path, init = {}) => {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
...init,
|
||||
headers: { "content-type": "application/json", authorization: `Bearer ${token}`, ...init.headers },
|
||||
signal: AbortSignal.timeout(60_000),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(`${response.status} ${path}: ${JSON.stringify(body)}`);
|
||||
return { body, headers: response.headers };
|
||||
};
|
||||
|
||||
const { body: models } = await requestJson("/api/ai/v1/models");
|
||||
if (models.data?.length !== 1 || models.data[0]?.id !== "homarr/model") {
|
||||
throw new Error("The live Workshop endpoint did not advertise the stable Homarr model");
|
||||
}
|
||||
|
||||
const { body: before } = await requestJson("/api/ai/usage");
|
||||
if (before.remaining < 1) throw new Error("The live test user has no remaining Homarr provider allowance");
|
||||
|
||||
const { body: completion, headers } = await requestJson("/api/ai/v1/chat/completions", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "Reply with exactly OK." }],
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
if (
|
||||
completion.model !== "homarr/model" ||
|
||||
typeof completion.choices?.[0]?.message?.content !== "string" ||
|
||||
completion.choices[0].message.content.length === 0 ||
|
||||
headers.get("x-homarr-quota-remaining") === null
|
||||
) {
|
||||
throw new Error("The live Homarr provider did not return an OpenAI-compatible completion with quota headers");
|
||||
}
|
||||
|
||||
const { body: after } = await requestJson("/api/ai/usage");
|
||||
if (after.used < before.used + 1 || after.remaining >= before.remaining) {
|
||||
throw new Error("The live completion was not charged to the authenticated Workshop user");
|
||||
}
|
||||
|
||||
process.stdout.write("Live Homarr provider smoke test passed\n");
|
||||
@@ -0,0 +1,210 @@
|
||||
import { createServer } from "node:http";
|
||||
|
||||
const port = Number(process.env.PORT ?? 18091);
|
||||
const expectedModel = process.env.EXPECTED_MODEL ?? "mock/team-selected-model";
|
||||
const expectedApiKey = process.env.EXPECTED_API_KEY ?? "workshop-test-openrouter-key";
|
||||
|
||||
const json = (response, status, body) => {
|
||||
response.writeHead(status, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify(body));
|
||||
};
|
||||
|
||||
const server = createServer(async (request, response) => {
|
||||
if (request.method === "GET" && request.url === "/health") {
|
||||
json(response, 200, { ok: true });
|
||||
return;
|
||||
}
|
||||
if (request.method !== "POST" || request.url !== "/api/v1/chat/completions") {
|
||||
json(response, 404, { error: { message: "Not found" } });
|
||||
return;
|
||||
}
|
||||
if (request.headers.authorization !== `Bearer ${expectedApiKey}`) {
|
||||
json(response, 401, { error: { message: "Invalid upstream credentials" } });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
request.headers["http-referer"] !== "https://homarr.dev" ||
|
||||
request.headers["x-openrouter-title"] !== "Homarr AI Assistant" ||
|
||||
request.headers["x-openrouter-metadata"] !== "enabled"
|
||||
) {
|
||||
json(response, 400, { error: { message: "Homarr upstream attribution headers are missing or spoofed" } });
|
||||
return;
|
||||
}
|
||||
|
||||
const chunks = [];
|
||||
for await (const chunk of request) chunks.push(chunk);
|
||||
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
||||
if (body.model !== expectedModel) {
|
||||
json(response, 400, { error: { message: "Unexpected upstream model" } });
|
||||
return;
|
||||
}
|
||||
if (body.max_completion_tokens !== 32_768 || body.n !== 1 || body.parallel_tool_calls !== false) {
|
||||
json(response, 400, { error: { message: "Unsafe generation controls reached the upstream" } });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
"max_tokens" in body ||
|
||||
"user" in body ||
|
||||
"metadata" in body ||
|
||||
"extra_body" in body ||
|
||||
"extra_headers" in body ||
|
||||
"max_tokens" in (body.reasoning ?? {})
|
||||
) {
|
||||
json(response, 400, { error: { message: "Private or unbounded request fields reached the upstream" } });
|
||||
return;
|
||||
}
|
||||
const forbiddenCostField = ["audio", "modalities", "logprobs", "top_logprobs", "prediction", "service_tier"].find(
|
||||
(field) => field in body,
|
||||
);
|
||||
if (forbiddenCostField) {
|
||||
json(response, 400, { error: { message: `Client cost field was forwarded: ${forbiddenCostField}` } });
|
||||
return;
|
||||
}
|
||||
const forbiddenRoutingField = ["models", "route", "plugins", "transforms"].find((field) => field in body);
|
||||
if (forbiddenRoutingField) {
|
||||
json(response, 400, { error: { message: `Client routing field was forwarded: ${forbiddenRoutingField}` } });
|
||||
return;
|
||||
}
|
||||
if (body.provider?.zdr !== true || body.provider?.data_collection !== "deny") {
|
||||
json(response, 400, { error: { message: "Required upstream privacy controls are missing" } });
|
||||
return;
|
||||
}
|
||||
const webSearchTools = body.tools?.filter((tool) => tool.type === "openrouter:web_search") ?? [];
|
||||
if (
|
||||
webSearchTools.length > 1 ||
|
||||
webSearchTools.some(
|
||||
(tool) =>
|
||||
tool.parameters?.max_results !== 5 ||
|
||||
tool.parameters?.max_uses !== 3 ||
|
||||
tool.parameters?.max_total_results !== 10 ||
|
||||
tool.parameters?.max_characters !== 2500 ||
|
||||
tool.parameters?.search_context_size !== "low",
|
||||
)
|
||||
) {
|
||||
json(response, 400, { error: { message: "Unbounded web search controls reached the upstream" } });
|
||||
return;
|
||||
}
|
||||
if (body.messages?.some((message) => message.content === "upstream failure")) {
|
||||
json(response, 503, { error: { message: "Simulated upstream failure" } });
|
||||
return;
|
||||
}
|
||||
if (body.messages?.some((message) => message.content === "malformed stream")) {
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
response.end('data: {"model":\n\n');
|
||||
return;
|
||||
}
|
||||
if (body.messages?.some((message) => message.content === "in-flight probe")) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 500));
|
||||
}
|
||||
|
||||
const wantsToolCall = body.messages?.some((message) => message.content === "inspect my dashboard");
|
||||
if (wantsToolCall && !body.tools?.some((tool) => tool.type === "function" && tool.function?.name === "board_list")) {
|
||||
json(response, 400, { error: { message: "The authenticated function tool was not forwarded" } });
|
||||
return;
|
||||
}
|
||||
|
||||
const completion = {
|
||||
id: "gen-workshop-test",
|
||||
object: "chat.completion",
|
||||
model: body.model,
|
||||
choices: [
|
||||
wantsToolCall
|
||||
? {
|
||||
index: 0,
|
||||
message: {
|
||||
role: "assistant",
|
||||
content: null,
|
||||
tool_calls: [
|
||||
{
|
||||
id: "call-board-list",
|
||||
type: "function",
|
||||
function: { name: "board_list", arguments: "{}" },
|
||||
},
|
||||
],
|
||||
},
|
||||
finish_reason: "tool_calls",
|
||||
}
|
||||
: {
|
||||
index: 0,
|
||||
message: { role: "assistant", content: "Hello from the Homarr provider" },
|
||||
finish_reason: "stop",
|
||||
},
|
||||
],
|
||||
usage: { prompt_tokens: 12, completion_tokens: 7, total_tokens: 19, cost: 0.00041 },
|
||||
};
|
||||
if (!body.stream) {
|
||||
json(response, 200, completion);
|
||||
return;
|
||||
}
|
||||
|
||||
response.writeHead(200, {
|
||||
"content-type": "text/event-stream",
|
||||
"cache-control": "no-cache",
|
||||
"x-request-id": "mock-openrouter-request",
|
||||
});
|
||||
if (wantsToolCall) {
|
||||
response.write(
|
||||
`data: ${JSON.stringify({
|
||||
id: completion.id,
|
||||
object: "chat.completion.chunk",
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: {
|
||||
role: "assistant",
|
||||
tool_calls: [
|
||||
{
|
||||
index: 0,
|
||||
id: "call-board-list",
|
||||
type: "function",
|
||||
function: { name: "board_list", arguments: "{" },
|
||||
},
|
||||
],
|
||||
},
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
})}\n\n`,
|
||||
);
|
||||
response.write(
|
||||
`data: ${JSON.stringify({
|
||||
id: completion.id,
|
||||
object: "chat.completion.chunk",
|
||||
model: body.model,
|
||||
choices: [
|
||||
{
|
||||
index: 0,
|
||||
delta: { tool_calls: [{ index: 0, function: { arguments: "}" } }] },
|
||||
finish_reason: "tool_calls",
|
||||
},
|
||||
],
|
||||
usage: completion.usage,
|
||||
})}\n\n`,
|
||||
);
|
||||
response.end("data: [DONE]\n\n");
|
||||
return;
|
||||
}
|
||||
response.write(
|
||||
`data: ${JSON.stringify({
|
||||
id: completion.id,
|
||||
object: "chat.completion.chunk",
|
||||
model: body.model,
|
||||
choices: [{ index: 0, delta: { role: "assistant", content: "Hello from " }, finish_reason: null }],
|
||||
})}\n\n`,
|
||||
);
|
||||
setTimeout(() => {
|
||||
response.write(
|
||||
`data: ${JSON.stringify({
|
||||
id: completion.id,
|
||||
object: "chat.completion.chunk",
|
||||
model: body.model,
|
||||
choices: [{ index: 0, delta: { content: "the Homarr provider" }, finish_reason: "stop" }],
|
||||
usage: completion.usage,
|
||||
})}\n\n`,
|
||||
);
|
||||
response.end("data: [DONE]\n\n");
|
||||
}, 150);
|
||||
});
|
||||
|
||||
server.listen(port, "0.0.0.0");
|
||||
@@ -0,0 +1,28 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL;
|
||||
const remoteUrl = process.env.WORKSHOP_REMOTE_API_URL?.replace(/\/$/, "").replace(/\/api$/, "");
|
||||
assert.ok(baseUrl && remoteUrl, "WORKSHOP_TEST_URL and WORKSHOP_REMOTE_API_URL are required");
|
||||
const response = await fetch(`${remoteUrl}/api/collections/workshop_listings/records?perPage=100`);
|
||||
assert.equal(response.status, 200);
|
||||
const { items } = await response.json();
|
||||
assert.ok(items.length > 0, "Remote backend must contain public listings");
|
||||
const escapeHtml = (value) =>
|
||||
value
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
for (const item of items) {
|
||||
const page = await fetch(`${baseUrl}/workshop/${item.id}/`);
|
||||
assert.equal(page.status, 200, item.title);
|
||||
const html = await page.text();
|
||||
assert.ok(html.includes(`<title>${escapeHtml(item.title)} · Homarr Workshop</title>`), item.title);
|
||||
assert.ok(!html.includes('name="robots" content="noindex"'), item.title);
|
||||
}
|
||||
const missing = await fetch(`${baseUrl}/workshop/nonexistentitem/`);
|
||||
assert.equal(missing.status, 404);
|
||||
console.log(
|
||||
`Remote Workshop verified: ${items.length} direct item pages with HTTP 200 and metadata; missing item 404.`,
|
||||
);
|
||||
@@ -0,0 +1,24 @@
|
||||
import vm from "node:vm";
|
||||
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL;
|
||||
if (!baseUrl) throw new Error("WORKSHOP_TEST_URL is required");
|
||||
|
||||
const response = await fetch(`${baseUrl}/workshop-runtime-config.js`);
|
||||
if (!response.ok) throw new Error(`Runtime configuration returned ${response.status}`);
|
||||
|
||||
const context = { TextDecoder, Uint8Array, atob };
|
||||
context.globalThis = context;
|
||||
vm.runInNewContext(await response.text(), context);
|
||||
|
||||
const actual = JSON.parse(JSON.stringify(context.homarrRuntimeConfig));
|
||||
const expected = {
|
||||
homarrWebsiteUrl: process.env.EXPECTED_HOMARR_WEBSITE_URL,
|
||||
workshopApiUrl: process.env.EXPECTED_WORKSHOP_API_URL,
|
||||
workshopWebUrl: process.env.EXPECTED_WORKSHOP_WEB_URL,
|
||||
};
|
||||
|
||||
if (JSON.stringify(actual) !== JSON.stringify(expected)) {
|
||||
throw new Error(`Unexpected Workshop runtime configuration: ${JSON.stringify(actual)}`);
|
||||
}
|
||||
|
||||
console.log("Workshop runtime configuration passed");
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL;
|
||||
if (!baseUrl) throw new Error("WORKSHOP_TEST_URL is required");
|
||||
|
||||
const indexResponse = await fetch(`${baseUrl}/api/search?q=board`);
|
||||
assert.equal(indexResponse.status, 200, "PocketBase must serve the static search index under /api/search");
|
||||
assert.equal((await indexResponse.json()).type, "advanced");
|
||||
|
||||
const compressedIndex = await fetch(`${baseUrl}/api/search`, { headers: { "Accept-Encoding": "gzip" } });
|
||||
assert.equal(compressedIndex.headers.get("content-encoding"), "gzip", "large static indexes must be compressed");
|
||||
assert.match(compressedIndex.headers.get("vary"), /Accept-Encoding/i);
|
||||
const plainIndex = await fetch(`${baseUrl}/api/search`, { headers: { "Accept-Encoding": "identity" } });
|
||||
assert.equal(plainIndex.headers.get("content-encoding"), null);
|
||||
const indexText = await plainIndex.text();
|
||||
assert.equal(await compressedIndex.text(), indexText, "compression must preserve the exported index");
|
||||
const declinedIndex = await fetch(`${baseUrl}/api/search`, { headers: { "Accept-Encoding": "br, gzip; q=0" } });
|
||||
assert.equal(declinedIndex.headers.get("content-encoding"), null, "an explicitly refused encoding must not be used");
|
||||
assert.equal(await declinedIndex.text(), indexText);
|
||||
|
||||
for (const path of ["/llms.txt", "/llms-full.txt", "/llms.mdx/docs/content.md"]) {
|
||||
const response = await fetch(`${baseUrl}${path}`);
|
||||
assert.equal(response.status, 200, path);
|
||||
assert.match(await response.text(), /^# /, `${path} must serve Markdown rather than the homepage`);
|
||||
}
|
||||
|
||||
const missing = await fetch(`${baseUrl}/docs/this-page-does-not-exist`);
|
||||
assert.equal(missing.status, 404);
|
||||
const missingHtml = await missing.text();
|
||||
// The shared static 404 shell waits for hydration to distinguish missing pages
|
||||
// from dynamic Workshop detail routes without flashing a false not-found state.
|
||||
assert.match(missingHtml, /aria-label="Loading submission"/);
|
||||
assert.match(missingHtml, /name="robots" content="noindex"/);
|
||||
|
||||
const missingApi = await fetch(`${baseUrl}/api/this-endpoint-does-not-exist`);
|
||||
assert.equal(missingApi.status, 404);
|
||||
assert.match(missingApi.headers.get("content-type"), /application\/json/);
|
||||
await missingApi.arrayBuffer();
|
||||
|
||||
const admin = await fetch(`${baseUrl}/workshop/admin/`);
|
||||
assert.equal(admin.status, 200);
|
||||
assert.match(await admin.text(), /Workshop moderation/);
|
||||
|
||||
const missingItem = await fetch(`${baseUrl}/workshop/nonexistentitem`);
|
||||
assert.equal(missingItem.status, 404);
|
||||
assert.match(await missingItem.text(), /name="robots" content="noindex"/);
|
||||
|
||||
for (const method of ["GET", "HEAD"]) {
|
||||
const headers = { "Accept-Encoding": "gzip" };
|
||||
const redirect = await fetch(`${baseUrl}/docs?example=1`, { method, headers, redirect: "manual" });
|
||||
assert.equal(redirect.status, 301);
|
||||
assert.equal(redirect.headers.get("location"), "/docs/?example=1");
|
||||
await redirect.arrayBuffer();
|
||||
const page = await fetch(`${baseUrl}/docs/`, { method, headers });
|
||||
assert.equal(page.status, 200);
|
||||
await page.arrayBuffer();
|
||||
}
|
||||
|
||||
console.log("PocketBase static export routes passed");
|
||||
@@ -0,0 +1,32 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import vm from "node:vm";
|
||||
|
||||
const read = (path) => readFile(path, "utf8");
|
||||
|
||||
const hookUtilsModule = { exports: {} };
|
||||
vm.runInNewContext(await read("apps/workshop/pb_hooks/workshop-utils.js"), { module: hookUtilsModule });
|
||||
const socialHtml = hookUtilsModule.exports.renderWorkshopSocialHtml(
|
||||
'<html><head><title data-rh="true">Homarr documentation</title><meta name="robots" content="noindex"/><meta data-rh="true" property="og:title" content="Homarr documentation"><meta data-rh="true" name="description" content="Generic"><link data-rh="true" rel="canonical" href="https://homarr.dev/"></head></html>',
|
||||
{
|
||||
title: "Ocean <Glow> · Homarr Workshop",
|
||||
description: "Custom CSS for Homarr. Calm & readable.",
|
||||
url: "https://preview.example/workshop/abc",
|
||||
image: "https://preview.example/api/files/submissions/abc/preview.png",
|
||||
section: "Custom CSS",
|
||||
submissionTitle: "Ocean <Glow>",
|
||||
},
|
||||
);
|
||||
for (const expected of [
|
||||
"<title>Ocean <Glow> · Homarr Workshop</title>",
|
||||
'property="og:description" content="Custom CSS for Homarr. Calm & readable."',
|
||||
'rel="canonical" href="https://preview.example/workshop/abc"',
|
||||
'property="og:image" content="https://preview.example/api/files/submissions/abc/preview.png"',
|
||||
'name="twitter:card" content="summary_large_image"',
|
||||
'property="article:section" content="Custom CSS"',
|
||||
]) {
|
||||
if (!socialHtml.includes(expected)) throw new Error(`Workshop social metadata is missing: ${expected}`);
|
||||
}
|
||||
if (socialHtml.includes("Homarr documentation")) throw new Error("Workshop social metadata must replace generic tags");
|
||||
if (socialHtml.includes("noindex")) throw new Error("Published Workshop details must not inherit the 404 noindex tag");
|
||||
|
||||
console.log("Workshop social metadata rendering passed");
|
||||
@@ -0,0 +1,166 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import vm from "node:vm";
|
||||
|
||||
// oxlint-disable-next-line typescript/no-extraneous-class -- Mirrors the PocketBase Field constructor API.
|
||||
class Field {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.id = `field-${options.name}`;
|
||||
}
|
||||
}
|
||||
|
||||
class Fields {
|
||||
constructor(fields = []) {
|
||||
this.values = fields.map((field) => (field instanceof Field ? field : new Field(field)));
|
||||
}
|
||||
getByName(name) {
|
||||
return this.values.find((field) => field.name === name);
|
||||
}
|
||||
add(field) {
|
||||
this.values.push(field);
|
||||
}
|
||||
removeById(id) {
|
||||
this.values = this.values.filter((field) => field.id !== id);
|
||||
}
|
||||
}
|
||||
|
||||
class Collection {
|
||||
constructor(options) {
|
||||
Object.assign(this, options);
|
||||
this.id = options.id ?? options.name;
|
||||
this.fields = new Fields(options.fields);
|
||||
}
|
||||
addIndex() {}
|
||||
}
|
||||
|
||||
let recordId = 0;
|
||||
class Record {
|
||||
constructor(collection) {
|
||||
this.collection = collection;
|
||||
this.id = `record-${++recordId}`;
|
||||
this.data = new Map();
|
||||
}
|
||||
set(name, value) {
|
||||
this.data.set(name, value);
|
||||
}
|
||||
getString(name) {
|
||||
return String(this.data.get(name) ?? "");
|
||||
}
|
||||
}
|
||||
|
||||
const original = {
|
||||
passwordAuth: { enabled: true, identityFields: ["email"] },
|
||||
oauth2: { enabled: true, providers: [{ name: "original", clientId: "before", clientSecret: "before-secret" }] },
|
||||
rules: {
|
||||
listRule: "original-list",
|
||||
viewRule: "original-view",
|
||||
createRule: "original-create",
|
||||
updateRule: "original-update",
|
||||
deleteRule: "original-delete",
|
||||
},
|
||||
};
|
||||
const users = new Collection({ type: "auth", name: "users", fields: [{ type: "text", name: "existing" }] });
|
||||
users.passwordAuth = structuredClone(original.passwordAuth);
|
||||
users.oauth2 = structuredClone(original.oauth2);
|
||||
Object.assign(users, original.rules);
|
||||
const collections = new Map([[users.id, users]]);
|
||||
const records = new Map();
|
||||
const rawQueries = [];
|
||||
const app = {
|
||||
db() {
|
||||
return {
|
||||
newQuery(sql) {
|
||||
return {
|
||||
execute() {
|
||||
rawQueries.push(sql);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
findCollectionByNameOrId(name) {
|
||||
const collection = collections.get(name);
|
||||
if (!collection) throw new Error(`Missing collection ${name}`);
|
||||
return collection;
|
||||
},
|
||||
findFirstRecordByFilter(collectionId) {
|
||||
const record = records.get(collectionId)?.[0];
|
||||
if (!record) throw new Error(`Missing state record ${collectionId}`);
|
||||
return record;
|
||||
},
|
||||
save(value) {
|
||||
if (value instanceof Collection) collections.set(value.id, value);
|
||||
else if (value instanceof Record)
|
||||
records.set(value.collection.id, [...(records.get(value.collection.id) ?? []), value]);
|
||||
},
|
||||
delete(collection) {
|
||||
collections.delete(collection.id);
|
||||
records.delete(collection.id);
|
||||
},
|
||||
};
|
||||
|
||||
let migration;
|
||||
const sandbox = {
|
||||
Collection,
|
||||
Record,
|
||||
TextField: Field,
|
||||
URLField: Field,
|
||||
FileField: Field,
|
||||
BoolField: Field,
|
||||
console,
|
||||
migrate: (up, down) => {
|
||||
migration = { up, down };
|
||||
},
|
||||
};
|
||||
const source = await readFile("apps/workshop/pb_migrations/1784240000_workshop_widgets.js", "utf8");
|
||||
vm.runInNewContext(source, sandbox);
|
||||
if (!migration) throw new Error("Workshop migration did not register");
|
||||
|
||||
migration.up(app);
|
||||
if (!collections.has("workshop_migration_state")) {
|
||||
throw new Error("Workshop migration did not capture state before applying changes");
|
||||
}
|
||||
if (
|
||||
!rawQueries.some(
|
||||
(query) =>
|
||||
query.includes("CREATE TRIGGER submissions_revision_cas") &&
|
||||
query.includes("NEW.expectedRevision != OLD.revision"),
|
||||
)
|
||||
) {
|
||||
throw new Error("Workshop migration did not install the atomic submission revision guard");
|
||||
}
|
||||
migration.down(app);
|
||||
|
||||
if (JSON.stringify(users.passwordAuth) !== JSON.stringify(original.passwordAuth))
|
||||
throw new Error("Password authentication was not restored");
|
||||
if (JSON.stringify(users.oauth2) !== JSON.stringify(original.oauth2))
|
||||
throw new Error("OAuth settings were not restored");
|
||||
for (const [name, value] of Object.entries(original.rules)) {
|
||||
if (users[name] !== value) throw new Error(`User rule ${name} was not restored`);
|
||||
}
|
||||
if (users.fields.values.map((field) => field.name).join(",") !== "existing")
|
||||
throw new Error("Workshop user fields were not removed on rollback");
|
||||
for (const name of ["workshop_migration_state", "workshop_listings", "reports", "comments", "votes", "submissions"]) {
|
||||
if (collections.has(name)) throw new Error(`Rollback left collection ${name}`);
|
||||
}
|
||||
|
||||
collections.clear();
|
||||
records.clear();
|
||||
rawQueries.length = 0;
|
||||
|
||||
migration.up(app);
|
||||
if (!collections.has("users")) throw new Error("Fresh migration did not create the users collection");
|
||||
migration.down(app);
|
||||
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}`);
|
||||
}
|
||||
|
||||
console.log("Workshop migration up/down restoration passed");
|
||||
@@ -0,0 +1,73 @@
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL ?? "http://127.0.0.1:18091";
|
||||
const publicWebsiteUrl = process.env.EXPECTED_HOMARR_WEBSITE_URL ?? "https://docs.example.invalid";
|
||||
const publicWorkshopUrl = process.env.EXPECTED_WORKSHOP_WEB_URL ?? "https://workshop.example.invalid";
|
||||
const publicApiUrl = process.env.EXPECTED_WORKSHOP_API_URL ?? "https://api.example.invalid";
|
||||
|
||||
const request = async (path, init = {}) => {
|
||||
const response = await fetch(`${baseUrl}${path}`, init);
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok) throw new Error(`${response.status} ${path}: ${JSON.stringify(body)}`);
|
||||
return body;
|
||||
};
|
||||
|
||||
const root = await request("/api/collections/_superusers/auth-with-password", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ identity: "workshop-image@example.invalid", password: "WorkshopImageTest123!" }),
|
||||
});
|
||||
const headers = { authorization: `Bearer ${root.token}` };
|
||||
const author = await request("/api/collections/users/records", {
|
||||
method: "POST",
|
||||
headers: { ...headers, "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
email: "social-author@example.invalid",
|
||||
password: "WorkshopSocialTest123!",
|
||||
passwordConfirm: "WorkshopSocialTest123!",
|
||||
name: "social-author",
|
||||
}),
|
||||
});
|
||||
const png = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
const data = new FormData();
|
||||
data.set("type", "customCss");
|
||||
data.set("title", "Ocean <Glow>");
|
||||
data.set("description", "Calm & readable.");
|
||||
data.set("widgetSchema", "homarr-custom-css-v1");
|
||||
data.set("content", "body { color: white; }");
|
||||
data.set("author", author.id);
|
||||
data.set("screenshots", new File([png], "preview.png", { type: "image/png" }));
|
||||
const submission = await request("/api/collections/submissions/records", { method: "POST", headers, body: data });
|
||||
const screenshot = encodeURIComponent(submission.screenshots[0]);
|
||||
const html = await fetch(`${baseUrl}/workshop/${submission.id}`).then((response) => response.text());
|
||||
|
||||
for (const expected of [
|
||||
"<title>Ocean <Glow> · Homarr Workshop</title>",
|
||||
'property="og:description" content="Custom CSS for Homarr. Calm & readable."',
|
||||
`rel="canonical" href="${publicWorkshopUrl}/${submission.id}"`,
|
||||
`property="og:image" content="${publicApiUrl}/api/files/submissions/${submission.id}/${screenshot}"`,
|
||||
'name="twitter:card" content="summary_large_image"',
|
||||
'property="article:section" content="Custom CSS"',
|
||||
]) {
|
||||
if (!html.includes(expected)) throw new Error(`Rendered Workshop page is missing social metadata: ${expected}`);
|
||||
}
|
||||
|
||||
const noScreenshotData = new FormData();
|
||||
noScreenshotData.set("type", "customCss");
|
||||
noScreenshotData.set("title", "No preview image");
|
||||
noScreenshotData.set("description", "Uses the Homarr logo.");
|
||||
noScreenshotData.set("widgetSchema", "homarr-custom-css-v1");
|
||||
noScreenshotData.set("content", "body { color: white; }");
|
||||
noScreenshotData.set("author", author.id);
|
||||
const noScreenshot = await request("/api/collections/submissions/records", {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: noScreenshotData,
|
||||
});
|
||||
const noScreenshotHtml = await fetch(`${baseUrl}/workshop/${noScreenshot.id}`).then((response) => response.text());
|
||||
if (!noScreenshotHtml.includes(`property="og:image" content="${publicWebsiteUrl}/img/logo.png"`)) {
|
||||
throw new Error("Workshop social metadata must use the website origin for the fallback logo");
|
||||
}
|
||||
|
||||
console.log("Workshop social metadata integration passed");
|
||||
@@ -0,0 +1,819 @@
|
||||
const baseUrl = process.env.WORKSHOP_TEST_URL ?? "http://127.0.0.1:18090";
|
||||
|
||||
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 expectStatus = async (path, init, expected) => {
|
||||
const response = await fetch(`${baseUrl}${path}`, {
|
||||
...init,
|
||||
headers: { "content-type": "application/json", ...init.headers },
|
||||
});
|
||||
if (response.status !== expected) {
|
||||
const body = await response.text();
|
||||
throw new Error(`Expected ${expected} for ${path}, received ${response.status}: ${body}`);
|
||||
}
|
||||
};
|
||||
|
||||
const root = await request("/api/collections/_superusers/auth-with-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ identity: "workshop-test@example.invalid", password: "WorkshopLocalTest123!" }),
|
||||
});
|
||||
const rootHeaders = { authorization: `Bearer ${root.token}` };
|
||||
const collections = await request("/api/collections?perPage=200", { headers: rootHeaders });
|
||||
const collectionNames = new Set(collections.items.map((collection) => collection.name));
|
||||
for (const required of [
|
||||
"submissions",
|
||||
"votes",
|
||||
"comments",
|
||||
"reports",
|
||||
"workshop_listings",
|
||||
"workshop_report_summaries",
|
||||
"assistant_quotas",
|
||||
"assistant_global_quota",
|
||||
]) {
|
||||
if (!collectionNames.has(required)) throw new Error(`Missing Workshop collection: ${required}`);
|
||||
}
|
||||
for (const removed of ["workshop_admin_actions", "workshop_admins", "assistant_requests", "assistant_activity"]) {
|
||||
if (collectionNames.has(removed)) throw new Error(`Removed Workshop collection still exists: ${removed}`);
|
||||
}
|
||||
|
||||
// Production uses GitHub OAuth. Password auth is enabled only in this disposable database.
|
||||
const usersCollection = await request("/api/collections/users", { headers: rootHeaders });
|
||||
if (usersCollection.createRule !== '@request.context = "oauth2" && @request.body.isAdmin:isset = false') {
|
||||
throw new Error("User creation must be limited to OAuth without administrator fields");
|
||||
}
|
||||
await request("/api/collections/users", {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({ ...usersCollection, passwordAuth: { enabled: true, identityFields: ["email"] } }),
|
||||
});
|
||||
|
||||
const createUser = async (email, name, password, extra = {}) =>
|
||||
request("/api/collections/users/records", {
|
||||
method: "POST",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({
|
||||
email,
|
||||
emailVisibility: false,
|
||||
verified: true,
|
||||
password,
|
||||
passwordConfirm: password,
|
||||
name,
|
||||
...extra,
|
||||
}),
|
||||
});
|
||||
|
||||
const signIn = async (email, password) => {
|
||||
const auth = await request("/api/collections/users/auth-with-password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ identity: email, password }),
|
||||
});
|
||||
return { auth, headers: { authorization: `Bearer ${auth.token}` } };
|
||||
};
|
||||
|
||||
const authorPassword = "WorkshopAuthor123!";
|
||||
const author = await createUser("widget-author@example.invalid", "widget-author", authorPassword);
|
||||
const authorSession = await signIn(author.email, authorPassword);
|
||||
await expectStatus(
|
||||
`/api/collections/users/records/${author.id}`,
|
||||
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ isAdmin: true }) },
|
||||
404,
|
||||
);
|
||||
await expectStatus(
|
||||
`/api/collections/users/records/${author.id}`,
|
||||
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ name: "homarr-labs" }) },
|
||||
404,
|
||||
);
|
||||
const unchangedAuthor = await request(`/api/collections/users/records/${author.id}`, {
|
||||
headers: authorSession.headers,
|
||||
});
|
||||
if (unchangedAuthor.name !== "widget-author") {
|
||||
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);
|
||||
const visitorSession = await signIn(visitor.email, visitorPassword);
|
||||
const concurrencyPassword = "WorkshopConcurrency123!";
|
||||
const concurrencyUser = await createUser(
|
||||
"provider-concurrency@example.invalid",
|
||||
"provider-concurrency",
|
||||
concurrencyPassword,
|
||||
);
|
||||
const concurrencySession = await signIn(concurrencyUser.email, concurrencyPassword);
|
||||
|
||||
const modelList = await request("/api/ai/v1/models");
|
||||
if (
|
||||
modelList.object !== "list" ||
|
||||
modelList.data.length !== 1 ||
|
||||
modelList.data[0].id !== "homarr/model" ||
|
||||
modelList.data[0].context_length !== 256 * 1024
|
||||
) {
|
||||
throw new Error("The Homarr provider must advertise exactly one model");
|
||||
}
|
||||
await expectStatus("/api/ai/usage", {}, 401);
|
||||
await expectStatus(
|
||||
"/api/ai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "unauthenticated" }],
|
||||
}),
|
||||
},
|
||||
401,
|
||||
);
|
||||
await expectStatus(
|
||||
"/api/ai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: { authorization: "Bearer forged-workshop-user-token" },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "forged identity" }],
|
||||
}),
|
||||
},
|
||||
401,
|
||||
);
|
||||
|
||||
const inFlightProbe = () =>
|
||||
fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...concurrencySession.headers },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "in-flight probe" }],
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
const inFlightResponses = await Promise.all([inFlightProbe(), inFlightProbe(), inFlightProbe()]);
|
||||
if (
|
||||
inFlightResponses
|
||||
.map((response) => response.status)
|
||||
.toSorted()
|
||||
.join(",") !== "200,200,429"
|
||||
) {
|
||||
throw new Error("The per-user in-flight request limit was not enforced");
|
||||
}
|
||||
const concurrencyUsage = await request("/api/ai/usage", { headers: concurrencySession.headers });
|
||||
if (concurrencyUsage.used !== 2) {
|
||||
throw new Error(`Rejected in-flight requests must not consume allowance: ${JSON.stringify(concurrencyUsage)}`);
|
||||
}
|
||||
|
||||
const initialUsage = await request("/api/ai/usage", { headers: authorSession.headers });
|
||||
const initialReset = new Date(initialUsage.resetsAt);
|
||||
if (
|
||||
initialUsage.limit !== 50 ||
|
||||
initialUsage.used !== 0 ||
|
||||
initialUsage.remaining !== 50 ||
|
||||
initialReset.getUTCHours() !== 0 ||
|
||||
initialReset <= new Date()
|
||||
) {
|
||||
throw new Error(`Unexpected initial Homarr provider allowance: ${JSON.stringify(initialUsage)}`);
|
||||
}
|
||||
const forgedDateUsage = await request("/api/ai/usage", {
|
||||
headers: { ...authorSession.headers, date: "Thu, 01 Jan 2099 00:00:00 GMT" },
|
||||
});
|
||||
if (forgedDateUsage.resetsAt !== initialUsage.resetsAt || forgedDateUsage.remaining !== initialUsage.remaining) {
|
||||
throw new Error(`A client-controlled date changed the server allowance: ${JSON.stringify(forgedDateUsage)}`);
|
||||
}
|
||||
|
||||
await expectStatus(
|
||||
"/api/ai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [
|
||||
{ role: "user", content: "too many tools" },
|
||||
...Array.from({ length: 1000 }, (_, index) => ({
|
||||
role: "tool",
|
||||
tool_call_id: `tool-${index}`,
|
||||
content: "{}",
|
||||
})),
|
||||
],
|
||||
}),
|
||||
},
|
||||
400,
|
||||
);
|
||||
|
||||
await expectStatus(
|
||||
"/api/ai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "x".repeat(256 * 1024 + 1) }],
|
||||
}),
|
||||
},
|
||||
413,
|
||||
);
|
||||
await expectStatus(
|
||||
"/api/ai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "image_url", image_url: { url: "https://attacker.example/tracker.png" } }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
413,
|
||||
);
|
||||
const usageAfterRejectedRequest = await request("/api/ai/usage", { headers: authorSession.headers });
|
||||
if (usageAfterRejectedRequest.used !== 0) {
|
||||
throw new Error("A rejected oversized request-unit batch consumed allowance");
|
||||
}
|
||||
|
||||
await expectStatus(
|
||||
"/api/ai/v1/chat/completions",
|
||||
{
|
||||
method: "POST",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({ model: "another-model", messages: [{ role: "user", content: "hello" }] }),
|
||||
},
|
||||
400,
|
||||
);
|
||||
|
||||
const streamStartedAt = performance.now();
|
||||
const streamResponse = await fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...authorSession.headers },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "hello" }],
|
||||
stream: true,
|
||||
}),
|
||||
});
|
||||
if (!streamResponse.ok || streamResponse.headers.get("x-homarr-quota-remaining") !== "49") {
|
||||
throw new Error(`Streaming provider request failed: ${streamResponse.status}`);
|
||||
}
|
||||
const streamReader = streamResponse.body.getReader();
|
||||
const firstChunk = await streamReader.read();
|
||||
const firstChunkAt = performance.now();
|
||||
let streamText = new TextDecoder().decode(firstChunk.value ?? new Uint8Array());
|
||||
while (true) {
|
||||
const chunk = await streamReader.read();
|
||||
if (chunk.done) break;
|
||||
streamText += new TextDecoder().decode(chunk.value);
|
||||
}
|
||||
const dataFrames = streamText.split(/\r?\n/u).filter((line) => line.startsWith("data:"));
|
||||
if (
|
||||
firstChunk.done ||
|
||||
!streamText.includes("Hello from ") ||
|
||||
!streamText.includes("the Homarr provider") ||
|
||||
streamText.includes("mock/team-selected-model") ||
|
||||
!streamText.includes('"model":"homarr/model"') ||
|
||||
dataFrames.length < 3 ||
|
||||
dataFrames.at(-1)?.trim() !== "data: [DONE]" ||
|
||||
firstChunkAt - streamStartedAt > 5_000
|
||||
) {
|
||||
throw new Error("The Homarr provider did not preserve the upstream SSE stream");
|
||||
}
|
||||
const malformedStreamResponse = await fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...concurrencySession.headers },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "malformed stream" }],
|
||||
stream: true,
|
||||
}),
|
||||
});
|
||||
const malformedStreamText = await malformedStreamResponse.text();
|
||||
if (
|
||||
!malformedStreamResponse.ok ||
|
||||
!malformedStreamText.includes('"type":"homarr_provider_error"') ||
|
||||
malformedStreamText.includes('data: {"model":') ||
|
||||
!malformedStreamText.endsWith("data: [DONE]\n\n")
|
||||
) {
|
||||
throw new Error(`Malformed upstream streams did not terminate safely: ${malformedStreamText}`);
|
||||
}
|
||||
const toolResponse = await fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
...authorSession.headers,
|
||||
"http-referer": "https://attacker.example",
|
||||
"x-openrouter-title": "Attacker",
|
||||
"x-openrouter-metadata": "attacker",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [
|
||||
{ role: "user", content: "inspect my dashboard" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "one" }, { id: "two" }] },
|
||||
{ role: "tool", tool_call_id: "one", content: "{}" },
|
||||
{ role: "tool", tool_call_id: "two", content: "{}" },
|
||||
],
|
||||
stream: false,
|
||||
models: ["attacker/model"],
|
||||
provider: { order: ["attacker"] },
|
||||
route: "fallback",
|
||||
plugins: ["web"],
|
||||
transforms: ["middle-out"],
|
||||
max_tokens: 1_000_000,
|
||||
max_completion_tokens: 1_000_000,
|
||||
n: 100,
|
||||
parallel_tool_calls: true,
|
||||
extra_body: { provider: { order: ["attacker"] } },
|
||||
extra_headers: { Authorization: "Bearer attacker" },
|
||||
metadata: { user: "must-not-reach-openrouter" },
|
||||
audio: { format: "wav", voice: "alloy" },
|
||||
modalities: ["text", "audio"],
|
||||
logprobs: true,
|
||||
top_logprobs: 20,
|
||||
prediction: { content: "attacker-controlled prediction" },
|
||||
service_tier: "priority",
|
||||
reasoning: { effort: "high", max_tokens: 1_000_000 },
|
||||
user: "must-not-reach-openrouter",
|
||||
tools: [
|
||||
{ type: "function", function: { name: "board_list" } },
|
||||
{ type: "openrouter:web_search", parameters: { max_results: 1000, max_uses: 1000 } },
|
||||
{ type: "openrouter:web_search" },
|
||||
],
|
||||
}),
|
||||
});
|
||||
if (!toolResponse.ok || toolResponse.headers.get("x-homarr-quota-remaining") !== "48") {
|
||||
throw new Error("Every upstream inference must consume one Homarr provider request unit");
|
||||
}
|
||||
const toolCompletion = await toolResponse.json();
|
||||
if (
|
||||
toolCompletion.model !== "homarr/model" ||
|
||||
toolCompletion.choices?.[0]?.finish_reason !== "tool_calls" ||
|
||||
toolCompletion.choices?.[0]?.message?.tool_calls?.[0]?.function?.name !== "board_list"
|
||||
) {
|
||||
throw new Error(
|
||||
`The public model alias or function tool response was not forwarded: ${JSON.stringify(toolCompletion)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const streamedToolResponse = await fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...concurrencySession.headers },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "inspect my dashboard" }],
|
||||
tools: [{ type: "function", function: { name: "board_list", parameters: { type: "object" } } }],
|
||||
stream: true,
|
||||
}),
|
||||
});
|
||||
const streamedToolText = await streamedToolResponse.text();
|
||||
if (
|
||||
!streamedToolResponse.ok ||
|
||||
streamedToolText.includes("mock/team-selected-model") ||
|
||||
!streamedToolText.includes('"model":"homarr/model"') ||
|
||||
!streamedToolText.includes('"name":"board_list"') ||
|
||||
!streamedToolText.includes('"arguments":"{"') ||
|
||||
!streamedToolText.includes('"arguments":"}"') ||
|
||||
!streamedToolText.includes('"finish_reason":"tool_calls"') ||
|
||||
!streamedToolText.endsWith("data: [DONE]\n\n")
|
||||
) {
|
||||
throw new Error(`Streamed function tool calls were not preserved safely: ${streamedToolText}`);
|
||||
}
|
||||
|
||||
const afterToolsUsage = await request("/api/ai/usage", { headers: authorSession.headers });
|
||||
if (afterToolsUsage.used !== 2 || afterToolsUsage.remaining !== 48) {
|
||||
throw new Error(`Tool request accounting is incorrect: ${JSON.stringify(afterToolsUsage)}`);
|
||||
}
|
||||
|
||||
const upstreamFailure = await fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...authorSession.headers },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "upstream failure" }],
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
if (upstreamFailure.status !== 503 || upstreamFailure.headers.get("x-homarr-quota-remaining") !== "47") {
|
||||
throw new Error("Every request forwarded upstream must consume Homarr provider allowance");
|
||||
}
|
||||
const upstreamFailureBody = await upstreamFailure.text();
|
||||
if (upstreamFailureBody.includes("Simulated upstream failure")) {
|
||||
throw new Error("Upstream error details must not be exposed to clients");
|
||||
}
|
||||
const afterFailureUsage = await request("/api/ai/usage", { headers: authorSession.headers });
|
||||
if (afterFailureUsage.used !== 3 || afterFailureUsage.remaining !== 47) {
|
||||
throw new Error(`Forwarded upstream failure escaped quota accounting: ${JSON.stringify(afterFailureUsage)}`);
|
||||
}
|
||||
const visitorUsage = await request("/api/ai/usage", { headers: visitorSession.headers });
|
||||
if (visitorUsage.used !== 0 || visitorUsage.remaining !== 50) {
|
||||
throw new Error(`Provider allowance leaked across users: ${JSON.stringify(visitorUsage)}`);
|
||||
}
|
||||
|
||||
await expectStatus("/api/collections/assistant_quotas/records", { headers: authorSession.headers }, 403);
|
||||
await expectStatus("/api/collections/assistant_global_quota/records", { headers: authorSession.headers }, 403);
|
||||
const quotas = await request("/api/collections/assistant_quotas/records?perPage=20", { headers: rootHeaders });
|
||||
const authorQuota = quotas.items.find((item) => item.user === author.id);
|
||||
if (
|
||||
!authorQuota ||
|
||||
authorQuota.used !== 3 ||
|
||||
["dailyLimit", "inputTokens", "outputTokens", "totalTokens", "model", "cost"].some((field) => field in authorQuota)
|
||||
) {
|
||||
throw new Error(`Private provider quota is incorrect: ${JSON.stringify(authorQuota)}`);
|
||||
}
|
||||
|
||||
await request(`/api/collections/assistant_quotas/records/${authorQuota.id}`, {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({ day: "2000-01-01", used: 49 }),
|
||||
});
|
||||
const resetUsage = await request("/api/ai/usage", { headers: authorSession.headers });
|
||||
if (resetUsage.limit !== 50 || resetUsage.used !== 0 || resetUsage.remaining !== 50) {
|
||||
throw new Error(`Quota did not reset at the UTC day boundary: ${JSON.stringify(resetUsage)}`);
|
||||
}
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
const resetQuotas = (
|
||||
await request("/api/collections/assistant_quotas/records?perPage=20", { headers: rootHeaders })
|
||||
).items.filter((item) => item.user === author.id);
|
||||
const historicalQuota = resetQuotas.find((item) => item.id === authorQuota.id);
|
||||
const resetQuota = resetQuotas.find((item) => item.day === today);
|
||||
if (
|
||||
resetQuotas.length !== 2 ||
|
||||
historicalQuota?.day !== "2000-01-01" ||
|
||||
historicalQuota.used !== 49 ||
|
||||
!resetQuota ||
|
||||
resetQuota.used !== 0
|
||||
) {
|
||||
throw new Error(`Daily quota history was not preserved: ${JSON.stringify(resetQuotas)}`);
|
||||
}
|
||||
await request(`/api/collections/assistant_quotas/records/${resetQuota.id}`, {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({ used: 49 }),
|
||||
});
|
||||
|
||||
const allowanceProbe = () =>
|
||||
fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...authorSession.headers },
|
||||
body: JSON.stringify({
|
||||
model: "homarr/model",
|
||||
messages: [{ role: "user", content: "allowance probe" }],
|
||||
stream: false,
|
||||
}),
|
||||
});
|
||||
const concurrentAllowanceResponses = await Promise.all([allowanceProbe(), allowanceProbe()]);
|
||||
const concurrentStatuses = concurrentAllowanceResponses.map((response) => response.status).toSorted();
|
||||
const exhaustedResponse = concurrentAllowanceResponses.find((response) => response.status === 429);
|
||||
if (
|
||||
concurrentStatuses.join(",") !== "200,429" ||
|
||||
exhaustedResponse?.headers.get("x-homarr-quota-remaining") !== "0" ||
|
||||
!exhaustedResponse.headers.get("x-homarr-quota-reset")
|
||||
) {
|
||||
throw new Error("The per-user allowance was not enforced atomically");
|
||||
}
|
||||
|
||||
const globalQuota = (await request("/api/collections/assistant_global_quota/records", { headers: rootHeaders }))
|
||||
.items[0];
|
||||
await request(`/api/collections/assistant_global_quota/records/${globalQuota.id}`, {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({ day: new Date().toISOString().slice(0, 10), used: 9_999 }),
|
||||
});
|
||||
await request(`/api/collections/assistant_quotas/records/${resetQuota.id}`, {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({ used: 0 }),
|
||||
});
|
||||
const globalResponses = await Promise.all([
|
||||
allowanceProbe(),
|
||||
fetch(`${baseUrl}/api/ai/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", ...visitorSession.headers },
|
||||
body: JSON.stringify({ model: "homarr/model", messages: [{ role: "user", content: "global allowance probe" }] }),
|
||||
}),
|
||||
]);
|
||||
if (
|
||||
globalResponses
|
||||
.map((response) => response.status)
|
||||
.toSorted()
|
||||
.join(",") !== "200,429"
|
||||
) {
|
||||
throw new Error("The shared upstream allowance was not enforced atomically across users");
|
||||
}
|
||||
|
||||
const widget = {
|
||||
$schema: "homarr-custom-widget-v2",
|
||||
name: "Workshop runtime probe",
|
||||
sources: {
|
||||
default: {
|
||||
name: "API",
|
||||
baseUrl: "https://example.com",
|
||||
networkScope: "public",
|
||||
auth: "none",
|
||||
},
|
||||
},
|
||||
requests: {},
|
||||
options: {},
|
||||
template: "<Text>Runtime probe</Text>",
|
||||
};
|
||||
|
||||
const submission = await request("/api/collections/submissions/records", {
|
||||
method: "POST",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({
|
||||
type: "customWidget",
|
||||
title: "Workshop runtime probe",
|
||||
description: "PocketBase integration test",
|
||||
widgetSchema: widget.$schema,
|
||||
content: JSON.stringify(widget),
|
||||
author: author.id,
|
||||
revision: 999,
|
||||
changelog: "Forged publication metadata",
|
||||
outdated: true,
|
||||
}),
|
||||
});
|
||||
if (
|
||||
submission.author !== author.id ||
|
||||
submission.title !== "Workshop runtime probe" ||
|
||||
submission.widgetSchema !== widget.$schema ||
|
||||
submission.revision !== 1 ||
|
||||
submission.changelog !== "" ||
|
||||
submission.outdated !== false
|
||||
) {
|
||||
throw new Error("Submission publication metadata was not initialized server-side");
|
||||
}
|
||||
const ownerVotes = await request("/api/collections/votes/records", { headers: authorSession.headers });
|
||||
if (
|
||||
ownerVotes.items.length !== 1 ||
|
||||
ownerVotes.items[0].submission !== submission.id ||
|
||||
ownerVotes.items[0].value !== 1
|
||||
) {
|
||||
throw new Error("New submissions must receive one real author-owned upvote");
|
||||
}
|
||||
|
||||
const updatedSubmission = await request(`/api/collections/submissions/records/${submission.id}`, {
|
||||
method: "PATCH",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({ title: "Updated runtime probe", expectedRevision: 1, revision: 500 }),
|
||||
});
|
||||
if (updatedSubmission.title !== "Updated runtime probe" || updatedSubmission.revision !== 2)
|
||||
throw new Error("Authors must be able to edit their submission");
|
||||
const outdatedSubmission = await request(`/api/collections/submissions/records/${submission.id}`, {
|
||||
method: "PATCH",
|
||||
headers: authorSession.headers,
|
||||
body: JSON.stringify({ outdated: true, expectedRevision: 2, revision: 900, changelog: "Needs a newer API" }),
|
||||
});
|
||||
if (!outdatedSubmission.outdated || outdatedSubmission.revision !== 3) {
|
||||
throw new Error("PocketBase must own submission revision increments");
|
||||
}
|
||||
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
const expectedRevision = 3 + attempt;
|
||||
const concurrentUpdates = await Promise.all(
|
||||
["Concurrent first", "Concurrent second"].map((title) =>
|
||||
fetch(`${baseUrl}/api/collections/submissions/records/${submission.id}`, {
|
||||
method: "PATCH",
|
||||
headers: { "content-type": "application/json", ...authorSession.headers },
|
||||
body: JSON.stringify({ title: `${title} ${attempt}`, expectedRevision }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (concurrentUpdates.filter((response) => response.ok).length !== 1) {
|
||||
throw new Error("Exactly one update may consume an expected submission revision");
|
||||
}
|
||||
}
|
||||
|
||||
await expectStatus(
|
||||
`/api/collections/submissions/records/${submission.id}`,
|
||||
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ author: visitor.id }) },
|
||||
404,
|
||||
);
|
||||
await expectStatus(
|
||||
`/api/collections/submissions/records/${submission.id}`,
|
||||
{ method: "PATCH", headers: visitorSession.headers, body: JSON.stringify({ title: "Not mine" }) },
|
||||
404,
|
||||
);
|
||||
await expectStatus(
|
||||
`/api/collections/submissions/records/${submission.id}`,
|
||||
{ method: "DELETE", headers: visitorSession.headers },
|
||||
404,
|
||||
);
|
||||
|
||||
const vote = await request("/api/collections/votes/records", {
|
||||
method: "POST",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({ submission: submission.id, user: visitor.id, value: 1 }),
|
||||
});
|
||||
await expectStatus(
|
||||
"/api/collections/votes/records",
|
||||
{
|
||||
method: "POST",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({ submission: submission.id, user: visitor.id, value: 1 }),
|
||||
},
|
||||
400,
|
||||
);
|
||||
await expectStatus(
|
||||
`/api/collections/votes/records/${vote.id}`,
|
||||
{ method: "PATCH", headers: visitorSession.headers, body: JSON.stringify({ user: author.id }) },
|
||||
404,
|
||||
);
|
||||
await expectStatus(
|
||||
`/api/collections/votes/records/${vote.id}`,
|
||||
{ method: "PATCH", headers: visitorSession.headers, body: JSON.stringify({ value: 0 }) },
|
||||
404,
|
||||
);
|
||||
|
||||
const listing = await request(`/api/collections/workshop_listings/records/${submission.id}`);
|
||||
if (
|
||||
listing.score !== 2 ||
|
||||
listing.upvotes !== 2 ||
|
||||
listing.downvotes !== 0 ||
|
||||
listing.authorName !== "widget-author" ||
|
||||
listing.widgetSchema !== widget.$schema
|
||||
) {
|
||||
throw new Error("Workshop listing data is incorrect");
|
||||
}
|
||||
|
||||
const comment = await request("/api/collections/comments/records?expand=author", {
|
||||
method: "POST",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({ submission: submission.id, author: visitor.id, content: "Useful widget" }),
|
||||
});
|
||||
if (comment.author !== visitor.id || comment.expand.author.name !== "widget-visitor") {
|
||||
throw new Error("Comment author expansion is incorrect");
|
||||
}
|
||||
await expectStatus(
|
||||
`/api/collections/comments/records/${comment.id}`,
|
||||
{ method: "PATCH", headers: authorSession.headers, body: JSON.stringify({ content: "Not mine" }) },
|
||||
404,
|
||||
);
|
||||
const editedComment = await request(`/api/collections/comments/records/${comment.id}`, {
|
||||
method: "PATCH",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({ content: "Useful updated widget" }),
|
||||
});
|
||||
if (editedComment.content !== "Useful updated widget") throw new Error("Comment editing failed");
|
||||
|
||||
await expectStatus(
|
||||
"/api/collections/reports/records",
|
||||
{
|
||||
method: "POST",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({
|
||||
submission: submission.id,
|
||||
reporter: author.id,
|
||||
category: "other",
|
||||
explanation: "Spoofed reporter",
|
||||
status: "open",
|
||||
}),
|
||||
},
|
||||
400,
|
||||
);
|
||||
const report = await request("/api/collections/reports/records", {
|
||||
method: "POST",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({
|
||||
submission: submission.id,
|
||||
reporter: visitor.id,
|
||||
category: "outdated",
|
||||
explanation: "Runtime moderation test",
|
||||
status: "dismissed",
|
||||
}),
|
||||
});
|
||||
if (report.category !== "outdated") throw new Error("Outdated Workshop reports must be accepted");
|
||||
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 moderators");
|
||||
const visitorReportSummaries = await request("/api/collections/workshop_report_summaries/records", {
|
||||
headers: visitorSession.headers,
|
||||
});
|
||||
if (visitorReportSummaries.items.length !== 0) {
|
||||
throw new Error("Report explanations must remain private from unrelated Workshop users");
|
||||
}
|
||||
const authorReportSummaries = await request("/api/collections/workshop_report_summaries/records", {
|
||||
headers: authorSession.headers,
|
||||
});
|
||||
if (
|
||||
authorReportSummaries.items.length !== 1 ||
|
||||
authorReportSummaries.items[0].submission !== submission.id ||
|
||||
authorReportSummaries.items[0].explanation !== "Runtime moderation test" ||
|
||||
"reporter" in authorReportSummaries.items[0]
|
||||
) {
|
||||
throw new Error("Submission authors must see report reasons without exposing reporter identities");
|
||||
}
|
||||
await expectStatus(
|
||||
`/api/collections/reports/records/${report.id}`,
|
||||
{ method: "DELETE", headers: visitorSession.headers },
|
||||
404,
|
||||
);
|
||||
|
||||
const promotedAuthor = await request(`/api/collections/users/records/${author.id}`, {
|
||||
method: "PATCH",
|
||||
headers: rootHeaders,
|
||||
body: JSON.stringify({ isAdmin: true }),
|
||||
});
|
||||
if (promotedAuthor.isAdmin !== true) throw new Error("PocketBase superusers must be able to appoint admins");
|
||||
|
||||
await expectStatus(
|
||||
`/api/collections/comments/records/${comment.id}`,
|
||||
{ method: "DELETE", headers: authorSession.headers },
|
||||
204,
|
||||
);
|
||||
|
||||
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 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 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",
|
||||
headers: visitorSession.headers,
|
||||
body: JSON.stringify({
|
||||
type: "customWidget",
|
||||
title: "Administrator deletion probe",
|
||||
content: JSON.stringify(widget),
|
||||
widgetSchema: widget.$schema,
|
||||
author: visitor.id,
|
||||
revision: 1,
|
||||
changelog: "Initial publication",
|
||||
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 },
|
||||
204,
|
||||
);
|
||||
await expectStatus(
|
||||
`/api/collections/submissions/records/${submission.id}`,
|
||||
{ method: "DELETE", headers: authorSession.headers },
|
||||
204,
|
||||
);
|
||||
|
||||
console.log("Workshop PocketBase integration passed");
|
||||
Reference in new issue
Block a user