Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Add AUTH_MODE=password and the standalone Docker edition (#664)
Ben Senescu85485840052b
diff --git a/.env.example b/.env.exampleindex 278e415f..214430aa 100644--- a/.env.example+++ b/.env.example@@ -23,6 +23,11 @@# - cloudflare_access: validate Cloudflare Access JWTs (recommended for deploys)# - local_noauth: local trusted mode with injected admin user (admin@localhost)# - hosted: Better Auth email/password + organization mode+# - password: the standalone Docker edition (deploy/standalone). Better Auth+# accounts without the hosted services; needs BETTER_AUTH_URL and+# BETTER_AUTH_SECRET. The first visitor creates the admin account and+# invitations add the rest; the operator can also create accounts from the+# container.## Defaults to cloudflare_access when unset.# AUTH_MODE=cloudflare_accessdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 571ed2b9..f16341ea 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -44,6 +44,14 @@ jobs:- name: Build worker (eager-bundle guard)run: pnpm vite build+ # The standalone Docker edition: one server module for celld. Keeps the+ # single-module build and the crawl gateway honest without Docker.+ - name: Build standalone server+ run: pnpm build:standalone++ - name: Test standalone crawl gateway+ run: pnpm test:standalone:gateway+- name: Install website dependenciesrun: pnpm --dir web install --frozen-lockfile@@ -78,3 +86,26 @@ jobs:platforms: linux/amd64cache-from: type=ghacache-to: type=gha,mode=max++ standalone-image:+ runs-on: ubuntu-latest++ steps:+ - name: Checkout+ uses: actions/checkout@v4+ with:+ ref: ${{ github.event.pull_request.head.sha || github.sha }}++ - name: Set up Buildx+ uses: docker/setup-buildx-action@v3++ - name: Build standalone Docker image+ uses: docker/build-push-action@v6+ with:+ context: .+ file: deploy/standalone/Dockerfile+ push: false+ load: false+ platforms: linux/amd64+ cache-from: type=gha,scope=standalone+ cache-to: type=gha,mode=max,scope=standalonediff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.ymlindex d07b57e6..c41a95fa 100644--- a/.github/workflows/docker-image.yml+++ b/.github/workflows/docker-image.yml@@ -16,6 +16,18 @@ jobs:docker:if: github.repository == 'every-app/open-seo'runs-on: ubuntu-latest+ strategy:+ matrix:+ include:+ # The original single-container image. Existing installations+ # auto-update from :latest, so it must stay this image.+ - image: ghcr.io/every-app/open-seo+ file: deploy/docker/Dockerfile+ # The standalone edition (deploy/standalone/compose.yaml): a+ # multi-container stack whose data format differs, so it is never+ # published under the name above.+ - image: ghcr.io/every-app/open-seo-standalone+ file: deploy/standalone/Dockerfilesteps:- name: Checkoutuses: actions/checkout@v4@@ -37,7 +49,7 @@ jobs:id: metauses: docker/metadata-action@v5with:- images: ghcr.io/every-app/open-seo+ images: ${{ matrix.image }}tags: |type=ref,event=branchtype=ref,event=tag@@ -51,7 +63,7 @@ jobs:uses: docker/build-push-action@v6with:context: .- file: deploy/docker/Dockerfile+ file: ${{ matrix.file }}push: trueplatforms: linux/amd64,linux/arm64tags: ${{ steps.meta.outputs.tags }}diff --git a/.oss-scanner/threat_model.md b/.oss-scanner/threat_model.mdindex a20e9469..ee28e3eb 100644--- a/.oss-scanner/threat_model.md+++ b/.oss-scanner/threat_model.md@@ -109,7 +109,7 @@ The organization id comes from the signed-in session, never from the client.**Self-hosting**-- `local_noauth` has no login, so `/mcp` is open. It is meant to run behind the operator's own auth (`docs/SELF_HOSTING_DOCKER.md`).+- `local_noauth` has no login, so `/mcp` is open. It is meant to run behind the operator's own auth (`docs/SELF_HOSTING_DOCKER.md`, `docs/SELF_HOSTING_DOCKER_LEGACY.md`).- Every `cloudflare_access` user is owner of the one shared workspace.- Paid-plan checks, credit checks and report sharing are hosted-only.- The self-host telemetry heartbeat (`src/server/lib/self-host-telemetry.ts`) and preflight beacon (`scripts/selfhost-preflight.ts`). They send aggregate counts, a random install id, version, deploy target, database backend, install age, and the names of failed setup checks. They never send URLs, keywords or emails. Documented in `docs/SELF_HOSTING_DOCKER.md`; off with `OPENSEO_TELEMETRY_DISABLED` or `DO_NOT_TRACK`.diff --git a/README.md b/README.mdindex 0f1e0c71..7046c576 100644--- a/README.md+++ b/README.md@@ -45,12 +45,16 @@ OpenSEO exposes an MCP server so AI agents like Claude Code, OpenClaw, and Herme## Self-Hosting-OpenSEO supports two self-hosting paths:+OpenSEO supports two self-hosting paths. Both use email and password accounts: the first visitor creates the admin account, teammates join from invitation links, and MCP clients (Claude, ChatGPT, Codex, Cursor) sign in with the same accounts.-- **Simple: Docker (Best for testing it out)** - For personal use on your own machine. See [`docs/SELF_HOSTING_DOCKER.md`](./docs/SELF_HOSTING_DOCKER.md).- - Unless you already are self-hosting other apps and are confident doing so, we recommend self-hosting with Cloudflare as opposed to Railway, Coolify or Dokploy.- - We plan to make it simpler to host on those platforms in the next few months.-- **Recommended: Cloudflare** - For internet-facing self-hosting across multiple devices or with your team (works on the free plan). See [`docs/SELF_HOSTING_CLOUDFLARE.md`](./docs/SELF_HOSTING_CLOUDFLARE.md).+- **Docker** - On your own server or computer, with a prebuilt image that is ready in seconds. Works with Compose-based platforms such as Coolify, Portainer and Dokploy. See [`docs/SELF_HOSTING_DOCKER.md`](./docs/SELF_HOSTING_DOCKER.md).+ - Running the older single-container image? It keeps getting updates; [move to the new setup](./docs/SELF_HOSTING_DOCKER.md#move-from-the-old-docker-image) when you are ready, data included.+- **Cloudflare** - No server to run: one deploy command puts OpenSEO on your own Cloudflare account (works on the free plan). See [`docs/SELF_HOSTING_CLOUDFLARE.md`](./docs/SELF_HOSTING_CLOUDFLARE.md).++For security-conscious setups, two advanced options replace the accounts with your own network controls:++- **Cloudflare Access** in front of the Cloudflare deploy, so Cloudflare checks every request before it reaches OpenSEO. See [`docs/SELF_HOSTING_CLOUDFLARE.md`](./docs/SELF_HOSTING_CLOUDFLARE.md).+- **No sign-in on Docker**, behind Tailscale, a private network or your own authenticating proxy. See [Without sign-in](./docs/SELF_HOSTING_DOCKER.md#without-sign-in-advanced).Either way, you need a DataForSEO API key to get SEO data. See [`docs/DATAFORSEO_API_KEY.md`](./docs/DATAFORSEO_API_KEY.md).diff --git a/compose.yaml b/compose.yamlindex 866fd979..d1d43a04 100644--- a/compose.yaml+++ b/compose.yaml@@ -9,7 +9,7 @@ services:# `cp .env.example .env` creates it.env_file:- .env- # Anonymous usage heartbeat controls: docs/SELF_HOSTING_DOCKER.md#telemetry+ # Anonymous usage heartbeat controls: docs/SELF_HOSTING_DOCKER_LEGACY.md#telemetryenvironment:# Required for local Docker self-hosting: exposes Compose env vars to cloudflare:workers bindings.- CLOUDFLARE_INCLUDE_PROCESS_ENV=truediff --git a/deploy/.env.selfhost.example b/deploy/.env.selfhost.exampleindex 3d8e5277..aca2849c 100644--- a/deploy/.env.selfhost.example+++ b/deploy/.env.selfhost.example@@ -1,22 +1,39 @@-# OpenSEO Cloudflare self-host. Walkthrough: docs/SELF_HOSTING_CLOUDFLARE_ALCHEMY.md+# OpenSEO Cloudflare self-host. Walkthrough: docs/SELF_HOSTING_CLOUDFLARE.md# ---------- Required ----------# Get one at https://dataforseo.com — see docs/DATAFORSEO_API_KEY.mdDATAFORSEO_API_KEY=-# Who may sign in through Cloudflare Access, comma-separated-ACCESS_ALLOWED_EMAILS=+# ---------- Sign-in ----------++# password: email and password accounts. The first visitor creates the+# administrator's account, teammates join from invitation links, and MCP+# clients sign in with the same accounts. The deploy derives the app URL and+# generates the session secret.+AUTH_MODE=password++# cloudflare_access: Cloudflare's own login in front of the app, the most+# secure option, with more setup — see docs/SELF_HOSTING_CLOUDFLARE.md+# AUTH_MODE=cloudflare_access# ---------- Optional — uncomment to use ----------+# Operator account commands in password mode (password resets, accounts outside+# the invitation flow): any random value, e.g. `openssl rand -hex 32` — see+# docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md+# OPENSEO_OPERATOR_SECRET=+# Local SEO basemap. Server-only Map Tiles API key.# See docs/GOOGLE_MAPS_SETUP.md.# GOOGLE_MAPS_API_KEY=-# Google Search Console (all three together) — docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md+# Google Search Console — docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md# GOOGLE_CLIENT_ID=# GOOGLE_CLIENT_SECRET=+# With cloudflare_access, also set the secret that encrypts the stored tokens+# (at least 32 characters; password mode generates one)# BETTER_AUTH_SECRET=# SAM, the in-app agent (hidden if unset)diff --git a/deploy/alchemy/alchemy.run.ts b/deploy/alchemy/alchemy.run.tsindex e4ee71ad..5a8fe4a3 100644--- a/deploy/alchemy/alchemy.run.ts+++ b/deploy/alchemy/alchemy.run.ts@@ -149,6 +149,27 @@ const optionalSecret = (name: string) =>const accessScopeHint =" (if this is a permissions error, re-run `pnpm alchemy login --configure`, answer yes to “Customize OAuth scopes?”, and select access:write alongside the defaults)";+/**+ * The account's workers.dev subdomain (`<name>.workers.dev`): the configured+ * WORKERS_SUBDOMAIN when set, else one API read. Every worker hostname this+ * stack deploys derives from it.+ */+const resolveWorkersSubdomain = (configured: string, scopeHint: string) =>+ Effect.gen(function* () {+ if (configured) return configured;+ const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment;+ const observed = yield* CfWorkers.getSubdomain({ accountId }).pipe(+ Effect.catch((error) =>+ Effect.die(+ new Error(+ `Could not read the workers.dev subdomain: ${String(error)}${scopeHint}`,+ ),+ ),+ ),+ );+ return `${observed.subdomain}.workers.dev`;+ });+/*** Self-host auth (AUTH_MODE=cloudflare_access): derive the Access values* instead of making the user copy them out of the dashboard. TEAM_DOMAIN is@@ -174,20 +195,11 @@ const resolveSelfHostAccess = (// The workers.dev subdomain names both the Access application's hostname// (which must exist before the Worker resource does) and an auto-created- // Zero Trust team; it is deterministic from the account.- let subdomain = workersSubdomain;- if (!subdomain) {- const observed = yield* CfWorkers.getSubdomain({ accountId }).pipe(- Effect.catch((error) =>- Effect.die(- new Error(- `Could not read the workers.dev subdomain: ${String(error)}${accessScopeHint}`,- ),- ),- ),- );- subdomain = `${observed.subdomain}.workers.dev`;- }+ // Zero Trust team.+ const subdomain = yield* resolveWorkersSubdomain(+ workersSubdomain,+ accessScopeHint,+ );if (!teamDomain) {const organization = yield* ZeroTrust.listOrganizationsForAccount({@@ -251,8 +263,9 @@ const resolveSelfHostAccess = (// an `--env-file`, which the alchemy CLI loads into Config, NOT process.env;// the production workflow exports them as job/step env instead.const dataEnv = {- // AUTH_MODE, DATABASE_PROVIDER, BETTER_AUTH_URL, TEAM_DOMAIN, and- // POLICY_AUD are stage-dependent and set in the stack body below.+ // AUTH_MODE, DATABASE_PROVIDER, BETTER_AUTH_URL, TEAM_DOMAIN, POLICY_AUD,+ // and OPENSEO_OPERATOR_SECRET are stage-dependent and set in the stack body+ // below, which also replaces an unset BETTER_AUTH_SECRET in password mode.DATAFORSEO_API_KEY: Config.redacted("DATAFORSEO_API_KEY"),BYPASS_EMAIL_VERIFICATION: optionalVar("BYPASS_EMAIL_VERIFICATION"),BETTER_AUTH_SECRET: optionalSecret("BETTER_AUTH_SECRET"),@@ -305,6 +318,7 @@ export default Alchemy.Stack(const prod = stage === HOSTED_PROD_STAGE;// Fail closed: an unset AUTH_MODE gets the Access-gated mode (matching the// app's own default in src/lib/auth-mode.ts), never public hosted signup.+ // New self-host deployments get AUTH_MODE=password from deploy/.env.selfhost.example;// hosted/local_noauth must be set explicitly.const authMode = yield* Config.string("AUTH_MODE").pipe(Config.withDefault("cloudflare_access"),@@ -335,6 +349,12 @@ export default Alchemy.Stack(}} else if (workersSubdomain) {authUrl = `https://${workerName(stage)}.${workersSubdomain}`;+ } else if (authMode === "password") {+ // Password accounts need the real public URL (session cookies, the+ // OAuth callbacks MCP clients use). The self-host env file sets no+ // WORKERS_SUBDOMAIN, so read it from the account.+ const subdomain = yield* resolveWorkersSubdomain(workersSubdomain, "");+ authUrl = `https://${workerName(stage)}.${subdomain}`;} else if (authMode === "hosted") {return yield* Effect.die(new Error(@@ -353,6 +373,24 @@ export default Alchemy.Stack(workersSubdomain,);+ // Password accounts need a session secret. The self-host env file sets+ // none: the deploy mints one and keeps it in alchemy state, so redeploys+ // keep every session valid. An explicit BETTER_AUTH_SECRET always wins.+ const configuredAuthSecret = yield* dataEnv.BETTER_AUTH_SECRET;+ const betterAuthSecret =+ authMode === "password" && !Redacted.value(configuredAuthSecret)+ ? yield* Alchemy.makeRandom("BetterAuthSecret")+ : configuredAuthSecret;+ // Operator account commands (`pnpm selfhost:admin`: password resets,+ // accounts outside the invitation flow) stay off until the self-hoster+ // sets a secret for them.+ const operatorSecret = yield* optionalSecret("OPENSEO_OPERATOR_SECRET");++ // Self-host deploys may run on the free Workers plan, which rejects the+ // paid-plan CPU limits below.+ const selfHostPlan =+ authMode === "cloudflare_access" || authMode === "password";+// Created once and bound into BOTH workers — they share the same// D1/KV/R2 (and prod Hyperdrive). OAUTH_KV stays app-worker-only.const resources = makeResources(stage, databaseProvider !== "postgres");@@ -374,11 +412,8 @@ export default Alchemy.Stack(},// Audit workflow steps parse and persist batches of HTML — the same// CPU allowance the app worker used to carry for them. Configurable- // CPU limits are a paid-plan feature; self-host deploys- // (cloudflare_access) may run on the free plan, which rejects them.- ...(authMode === "cloudflare_access"- ? {}- : { limits: { cpuMs: 300_000 } }),+ // CPU limits are a paid-plan feature (see selfHostPlan).+ ...(selfHostPlan ? {} : { limits: { cpuMs: 300_000 } }),observability: {enabled: wrangler.observability?.enabled ?? true,traces: { enabled: wrangler.observability?.traces?.enabled ?? false },@@ -443,12 +478,9 @@ export default Alchemy.Stack(// Site audits moved to the open-seo-audit worker, but RankCheckWorkflow// still parses SERP batches here — keep the CPU allowance until that// workflow's per-tick CPU is measured or it moves too. Configurable CPU- // limits are a paid-plan feature, and self-host deploys- // (cloudflare_access) may run on the free plan — which rejects them —- // so those get the plan default instead.- ...(authMode === "cloudflare_access"- ? {}- : { limits: { cpuMs: 300_000 } }),+ // limits are a paid-plan feature; self-host deploys get the plan+ // default instead (see selfHostPlan).+ ...(selfHostPlan ? {} : { limits: { cpuMs: 300_000 } }),observability: {enabled: wrangler.observability?.enabled ?? true,traces: { enabled: wrangler.observability?.traces?.enabled ?? false },@@ -470,6 +502,10 @@ export default Alchemy.Stack(AUTH_MODE: authMode,DATABASE_PROVIDER: databaseProvider || "d1",BETTER_AUTH_URL: authUrl,+ BETTER_AUTH_SECRET: betterAuthSecret,+ ...(authMode === "password" && Redacted.value(operatorSecret)+ ? { OPENSEO_OPERATOR_SECRET: operatorSecret }+ : {}),// The audit worker above always binds BROWSER; the app worker checks// this before it offers "Render JavaScript".AUDIT_BROWSER_RENDERING: "true",diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfileindex 5b7ba049..f7aa77e6 100644--- a/deploy/docker/Dockerfile+++ b/deploy/docker/Dockerfile@@ -16,6 +16,10 @@ COPY . .EXPOSE 3001+# The app's boot-time build reads this to show the notice pointing to the+# standalone image (deploy/standalone/), which replaces this one.+ENV VITE_OPENSEO_LEGACY_DOCKER=true+# Readiness probe against the unauthenticated setup/health endpoint. The long# start period covers migrations plus the boot-time vite build (skipped when# the previous start's build is still valid; see deploy/docker/docker-entrypoint.sh).diff --git a/deploy/docker/docker-entrypoint.sh b/deploy/docker/docker-entrypoint.shindex 5f1d6e12..be205492 100644--- a/deploy/docker/docker-entrypoint.sh+++ b/deploy/docker/docker-entrypoint.sh@@ -7,7 +7,7 @@# rebuilds.set -e-echo 'OpenSEO sends an anonymous usage heartbeat (counts only). Disable: OPENSEO_TELEMETRY_DISABLED=1. Details: docs/SELF_HOSTING_DOCKER.md#telemetry'+echo 'OpenSEO sends an anonymous usage heartbeat (counts only). Disable: OPENSEO_TELEMETRY_DISABLED=1. Details: docs/SELF_HOSTING_DOCKER_LEGACY.md#telemetry'# The preflight validates env BEFORE the slow steps, so misconfiguration fails# in seconds with the exact fix instead of after a multi-minute build.diff --git a/deploy/standalone/.env.example b/deploy/standalone/.env.examplenew file mode 100644index 00000000..c20ee40d--- /dev/null+++ b/deploy/standalone/.env.example@@ -0,0 +1,18 @@+# Copy to .env. Choose unique storage credentials before the first start.+STORAGE_ACCESS_KEY=openseo+STORAGE_SECRET_KEY=replace-with-a-long-random-secret+# password: email and password accounts. The first visitor creates the+# admin account; invitations add the rest.+# local_noauth: no sign-in and one admin user, as the old Docker image ran;+# only for private networks.+AUTH_MODE=password+# The public URL of this installation, in either mode.+BETTER_AUTH_URL=http://localhost:3001+PORT=3001+# Optional feature credentials; these are set at initialization, never compiled.+DATAFORSEO_API_KEY=+OPENROUTER_API_KEY=+OPENROUTER_MODEL=+GOOGLE_CLIENT_ID=+GOOGLE_CLIENT_SECRET=+CONTEXT_API_KEY=diff --git a/deploy/standalone/Dockerfile b/deploy/standalone/Dockerfilenew file mode 100644index 00000000..074b01ed--- /dev/null+++ b/deploy/standalone/Dockerfile@@ -0,0 +1,36 @@+# The application is compiled once, at image build time. Runtime has no Vite,+# Wrangler, Miniflare, package manager, or node_modules.+FROM node:22-bookworm-slim@sha256:48e4b67d85f87bd551df43704e24d252f56cc5f8e9718841aace50f19948f0f9 AS build+WORKDIR /build+RUN corepack enable && corepack prepare [email protected] --activate+COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./+COPY patches ./patches+RUN pnpm install --frozen-lockfile+COPY . .+# The client bundle inlines AUTH_MODE at build time (vite envPrefix) only as a+# fallback: the server publishes the mode chosen at initialization+# (scripts/celld/runtime/configure.mjs) on every page it serves.+ENV VITE_SHOW_DEVTOOLS=false AUTH_MODE=password+RUN pnpm build:standalone++FROM node:22-bookworm-slim@sha256:48e4b67d85f87bd551df43704e24d252f56cc5f8e9718841aace50f19948f0f9 AS runtime+ARG TARGETARCH+ARG CELLD_VERSION=0.5.1+RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl && \+ rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules /opt/yarn* && \+ rm -f /usr/local/bin/npm /usr/local/bin/npx /usr/local/bin/corepack /usr/local/bin/yarn /usr/local/bin/yarnpkg+RUN case "$TARGETARCH" in \+ arm64) triple=aarch64-unknown-linux-gnu; checksum=375c7cd9446d61e6ee2c263d6be792650153ffd7cd562b2c4b6b644776b4494e;; \+ amd64) triple=x86_64-unknown-linux-gnu; checksum=b9f205da7365ef4a8b2e16f1f48065a8ddd5cda366edc258fea12a097d8ab4b7;; \+ *) exit 1;; \+ esac && \+ curl -fsSL "https://github.com/denoland/celld/releases/download/v${CELLD_VERSION}/celld-${triple}.gz" -o /tmp/celld.gz && \+ echo "$checksum /tmp/celld.gz" | sha256sum -c - && \+ gunzip /tmp/celld.gz && install -m 0755 /tmp/celld /usr/local/bin/celld && rm /tmp/celld+COPY --from=build /build/dist/celld /opt/openseo+COPY deploy/standalone/init.sh deploy/standalone/run.sh deploy/standalone/nginx.conf /opt/standalone/+COPY scripts/celld/runtime/admin.mjs scripts/celld/runtime/configure.mjs scripts/celld/runtime/crawl-gateway.mjs scripts/celld/runtime/import.mjs /opt/standalone/+RUN mkdir -p /config /data /web-config && chown -R node:node /config /data /web-config+USER node+ENV CELLD_WATCH=/data CELLD_IDLE_EVICT_S=300+CMD ["sh", "/opt/standalone/run.sh"]diff --git a/deploy/standalone/Dockerfile.dockerignore b/deploy/standalone/Dockerfile.dockerignorenew file mode 100644index 00000000..97be5b26--- /dev/null+++ b/deploy/standalone/Dockerfile.dockerignore@@ -0,0 +1,17 @@+.git+.github+.claude+.logs+**/.wrangler+**/node_modules+**/dist+**/coverage+*.log+**/.env+**/.env.*+.dev.vars+.dev.vars.*+**/.dev.vars+**/.dev.vars.*+!.env.example+.alchemy/diff --git a/deploy/standalone/compose.build.yaml b/deploy/standalone/compose.build.yamlnew file mode 100644index 00000000..a0b443a0--- /dev/null+++ b/deploy/standalone/compose.build.yaml@@ -0,0 +1,11 @@+# Builds the standalone image from this checkout instead of pulling it:+# export COMPOSE_FILE=deploy/standalone/compose.yaml:deploy/standalone/compose.build.yaml+# docker compose up -d --build+x-build: &build+ build:+ context: ../..+ dockerfile: deploy/standalone/Dockerfile+services:+ runtime: *build+ init: *build+ crawl-gateway: *builddiff --git a/deploy/standalone/compose.migrate.yaml b/deploy/standalone/compose.migrate.yamlnew file mode 100644index 00000000..ad6ffbb6--- /dev/null+++ b/deploy/standalone/compose.migrate.yaml@@ -0,0 +1,33 @@+# Moves an installation of the old Docker image (ghcr.io/every-app/open-seo,+# Miniflare state in its open_seo_data volume) into this stack. Add this file+# for one start, with the old installation stopped and LEGACY_VOLUME set to its+# data volume (docker volume ls):+# docker compose -f deploy/standalone/compose.yaml \+# -f deploy/standalone/compose.migrate.yaml up -d --build+# See docs/SELF_HOSTING_DOCKER.md, "Move from the old Docker image".+services:+ migrate:+ # The image's build stage: it has Miniflare, the only reader of the old+ # storage format, which the runtime image deliberately leaves out.+ image: openseo-standalone-migrate:local+ build:+ context: ../..+ dockerfile: deploy/standalone/Dockerfile+ target: build+ command: [node, scripts/celld/migrate-legacy.mjs]+ network_mode: service:runtime+ volumes:+ - legacy:/legacy:ro+ - config:/config+ depends_on:+ init: { condition: service_completed_successfully }+ restart: "no"+ web:+ # The import needs a database nobody has used yet, so the app stays+ # unreachable until the import has finished.+ depends_on:+ migrate: { condition: service_completed_successfully }+volumes:+ legacy:+ name: ${LEGACY_VOLUME:?Set LEGACY_VOLUME to the old installation's data volume (docker volume ls)}+ external: truediff --git a/deploy/standalone/compose.yaml b/deploy/standalone/compose.yamlnew file mode 100644index 00000000..d38ef8eb--- /dev/null+++ b/deploy/standalone/compose.yaml@@ -0,0 +1,99 @@+name: openseo-standalone+x-app: &app+ # The published image. To build it from this checkout instead, add+ # compose.build.yaml (see docs/SELF_HOSTING_DOCKER.md). This file+ # reads nothing else from the checkout, so it can be pasted into Coolify,+ # Portainer or Dokploy on its own.+ image: ${OPENSEO_IMAGE:-ghcr.io/every-app/open-seo-standalone:latest}+x-storage: &storage+ CELLD_BUCKET: openseo+ S3_ENDPOINT: http://storage:9000+ AWS_REGION: us-east-1+ AWS_ACCESS_KEY_ID: ${STORAGE_ACCESS_KEY:?Set STORAGE_ACCESS_KEY in .env}+ AWS_SECRET_ACCESS_KEY: ${STORAGE_SECRET_KEY:?Set STORAGE_SECRET_KEY in .env}+services:+ storage:+ # RustFS is the S3-compatible store celld keeps its state in. MinIO's+ # community images were delisted from Docker Hub and Quay in September+ # 2026; RustFS passes `celld diagnose` (conditional create and overwrite),+ # which Garage does not.+ image: rustfs/rustfs:1.0.3@sha256:9ca9559533b537d10482fe923288b676ad08f92a7069d9a17327fbae3cab688b+ environment:+ RUSTFS_ACCESS_KEY: ${STORAGE_ACCESS_KEY}+ RUSTFS_SECRET_KEY: ${STORAGE_SECRET_KEY}+ volumes: [storage:/data]+ restart: unless-stopped+ healthcheck:+ test: [CMD, curl, -f, http://localhost:9000/health]+ interval: 5s+ timeout: 3s+ retries: 20+ runtime:+ <<: *app+ environment:+ <<: *storage+ CELLD_MAX_RSS_MB: "1536"+ CELLD_MAX_RESIDENT_CELLS: "64"+ CELLD_V8_HEAP_LIMIT_MB: "256"+ CELLD_MAX_REQUEST_BODY_BYTES: "33554432"+ RUST_LOG: warn,cell_console=info+ mem_limit: 2g+ logging:+ driver: json-file+ options: { max-size: 10m, max-file: "3" }+ volumes: [runtime:/data, config:/config:ro]+ depends_on:+ storage: { condition: service_healthy }+ restart: unless-stopped+ stop_grace_period: 60s+ healthcheck:+ test: [CMD, curl, -fsS, http://localhost:8080/api/health]+ interval: 10s+ timeout: 5s+ start_period: 120s+ retries: 5+ init:+ <<: *app+ command: [sh, /opt/standalone/init.sh]+ network_mode: service:runtime+ environment:+ <<: *storage+ AUTH_MODE: ${AUTH_MODE:-password}+ BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3001}+ CONTEXT_API_KEY: ${CONTEXT_API_KEY:-}+ DATAFORSEO_API_KEY: ${DATAFORSEO_API_KEY:-}+ OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}+ OPENROUTER_MODEL: ${OPENROUTER_MODEL:-}+ GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-}+ GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-}+ volumes: [config:/config, web-config:/web-config]+ depends_on:+ runtime: { condition: service_started }+ restart: "no"+ crawl-gateway:+ <<: *app+ command: [node, /opt/standalone/crawl-gateway.mjs]+ volumes: [config:/config:ro]+ depends_on:+ init: { condition: service_completed_successfully }+ restart: unless-stopped+ web:+ image: nginx:1.28-alpine@sha256:a8b39bd9cf0f83869a2162827a0caf6137ddf759d50a171451b335cecc87d236+ ports: ["127.0.0.1:${PORT:-3001}:80"]+ # Written by init from deploy/standalone/nginx.conf in the image. nocopy+ # keeps nginx's own default.conf (root-owned) out of the shared volume.+ volumes:+ - type: volume+ source: web-config+ target: /etc/nginx/conf.d+ read_only: true+ volume: { nocopy: true }+ depends_on:+ init: { condition: service_completed_successfully }+ crawl-gateway: { condition: service_started }+ restart: unless-stopped+volumes:+ storage:+ runtime:+ config:+ web-config:diff --git a/deploy/standalone/init.sh b/deploy/standalone/init.shnew file mode 100644index 00000000..b0b932b4--- /dev/null+++ b/deploy/standalone/init.sh@@ -0,0 +1,33 @@+#!/bin/sh+set -eu+umask 077+# See run.sh: RustFS requires x-amz-content-sha256 on every SigV4 request.+EMPTY_SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+node /opt/standalone/configure.mjs+# Nginx's site config ships in this image, so the Compose file needs no files+# beside it (platforms such as Coolify and Portainer take the file alone).+install -m 0644 /opt/standalone/nginx.conf /web-config/default.conf+ready=0+for attempt in $(seq 1 90); do+ if curl -fsS --aws-sigv4 "aws:amz:${AWS_REGION}:s3" --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" -H "x-amz-content-sha256: $EMPTY_SHA256" -I "$S3_ENDPOINT/$CELLD_BUCKET" >/dev/null 2>&1; then ready=1; break; fi+ sleep 1+done+[ "$ready" = 1 ] || { echo 'Runtime did not start' >&2; exit 1; }+celld deploy /config/app+ready=0+for attempt in $(seq 1 90); do+ if curl -fsS -X POST http://127.0.0.1:8081/reload >/dev/null 2>&1; then ready=1; break; fi+ sleep 1+done+[ "$ready" = 1 ] || { echo 'Runtime did not load the deployment' >&2; exit 1; }+celld d1 migrations apply openseo-standalone /config/app+curl -fsS -X POST http://127.0.0.1:8081/reload >/dev/null+for attempt in $(seq 1 90); do+ if curl -fsS http://127.0.0.1:8080/api/health >/dev/null; then+ echo 'OpenSEO initialized and ready.'+ exit 0+ fi+ sleep 1+done+echo 'OpenSEO did not become ready; inspect runtime logs.' >&2+exit 1diff --git a/deploy/standalone/nginx.conf b/deploy/standalone/nginx.confnew file mode 100644index 00000000..d843fdf5--- /dev/null+++ b/deploy/standalone/nginx.conf@@ -0,0 +1,22 @@+server {+ listen 80;+ server_tokens off;+ client_max_body_size 20m;+ location = /api/standalone/import { return 404; }+ location = /api/standalone/admin { return 404; }+ location / {+ proxy_pass http://runtime:8080;+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ # Better Auth reads CF-Connecting-IP before X-Real-IP; only Cloudflare may set it.+ proxy_set_header CF-Connecting-IP "";+ proxy_set_header X-Forwarded-For $remote_addr;+ proxy_set_header X-Forwarded-Host $host;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header Upgrade $http_upgrade;+ proxy_set_header Connection "upgrade";+ proxy_read_timeout 3600s;+ proxy_buffering off;+ }+}diff --git a/deploy/standalone/run.sh b/deploy/standalone/run.shnew file mode 100644index 00000000..ddd5fe49--- /dev/null+++ b/deploy/standalone/run.sh@@ -0,0 +1,8 @@+#!/bin/sh+set -eu+# SHA-256 of an empty body: RustFS requires x-amz-content-sha256 on every+# SigV4 request and this image's curl does not add it on its own.+EMPTY_SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855+status=$(curl -sS -o /tmp/create-bucket-response -w '%{http_code}' --aws-sigv4 "aws:amz:${AWS_REGION}:s3" --user "$AWS_ACCESS_KEY_ID:$AWS_SECRET_ACCESS_KEY" -H "x-amz-content-sha256: $EMPTY_SHA256" -X PUT "$S3_ENDPOINT/$CELLD_BUCKET")+case "$status" in 200|409) ;; *) echo "Bucket initialization failed (HTTP $status)" >&2; exit 1;; esac+exec celld --listen 0.0.0.0:8080 --internal-listen 127.0.0.1:8081diff --git a/docs/DATAFORSEO_API_KEY.md b/docs/DATAFORSEO_API_KEY.mdindex 9bc34116..f94deea4 100644--- a/docs/DATAFORSEO_API_KEY.md+++ b/docs/DATAFORSEO_API_KEY.md@@ -14,6 +14,6 @@ New DataForSEO accounts include $1 of free credit to test with, and the minimumSet the value as `DATAFORSEO_API_KEY`:-- **Docker self-hosting:** in `.env` (see [`SELF_HOSTING_DOCKER.md`](./SELF_HOSTING_DOCKER.md)).+- **Docker self-hosting:** in `deploy/standalone/.env` (see [`SELF_HOSTING_DOCKER.md`](./SELF_HOSTING_DOCKER.md)), or `.env` for the [older single-container image](./SELF_HOSTING_DOCKER_LEGACY.md).- **Cloudflare self-hosting:** in `.env.selfhost` (see [`SELF_HOSTING_CLOUDFLARE.md`](./SELF_HOSTING_CLOUDFLARE.md)). Legacy button/Wrangler deployments: as a Worker secret in the dashboard under `Settings` -> `Variables & Secrets`.- **Local development:** in `.env.local` (see [`LOCAL_DEVELOPMENT.md`](./LOCAL_DEVELOPMENT.md)).diff --git a/docs/SELF_HOSTING_CLOUDFLARE.md b/docs/SELF_HOSTING_CLOUDFLARE.mdindex 7ee060fd..7beea7f2 100644--- a/docs/SELF_HOSTING_CLOUDFLARE.md+++ b/docs/SELF_HOSTING_CLOUDFLARE.md@@ -1,10 +1,12 @@# Cloudflare Self-Hosting-Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything, including the Cloudflare Access login gate. Works on Cloudflare's free plan.+Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything. Works on Cloudflare's free plan.++You sign in with email and password accounts: the first visitor creates the administrator's account, teammates join from invitation links, and MCP clients (Claude, ChatGPT, Codex, Cursor) sign in with the same accounts, with nothing to set up in Cloudflare. The most secure option is to put [Cloudflare Access](#cloudflare-access-the-most-secure-option) in front of the app instead, so Cloudflare checks every request before it reaches OpenSEO. It takes more setup.Related guides:-- [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): connect the MCP server, telemetry.+- [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): connect the MCP server, manage accounts, telemetry.- [Legacy deployments](./SELF_HOSTING_CLOUDFLARE_LEGACY.md): maintenance for installs created with the retired Deploy-button or manual Wrangler flows.## Prerequisites@@ -36,15 +38,13 @@ pnpm install## 2) Log in to Cloudflare (once)```bash-pnpm alchemy login # answer yes to "Customize OAuth scopes?" and enable access:write+pnpm alchemy login # the default scopes are enoughpnpm alchemy cloudflare bootstrap # deploys alchemy's state-store Worker to your account```-Already logged in from before without the `access:write` scope? Run `pnpm alchemy login --configure` — a plain repeat login doesn't re-ask about scopes.-## 3) Create `.env.selfhost`-Copy the template and fill in the required values:+Copy the template and set `DATAFORSEO_API_KEY`; everything else is optional:```bashcp deploy/.env.selfhost.example .env.selfhost@@ -56,17 +56,27 @@ cp deploy/.env.selfhost.example .env.selfhostpnpm deploy:selfhost --yes```-This provisions the D1 database, KV namespaces, and R2 bucket, applies the database migrations, deploys the Workers, and creates the Cloudflare Access application protecting it (allowing exactly `ACCESS_ALLOWED_EMAILS`). If the account has no Zero Trust team yet, one is created for you, named after your workers.dev subdomain.+This provisions the D1 database, KV namespaces, and R2 bucket, applies the database migrations, deploys the Workers, and generates the session secret. The secret is kept in Alchemy's state in your account, so later deploys keep everyone signed in.-To manage the Access application yourself instead, set `TEAM_DOMAIN` (`https://your-team.cloudflareaccess.com`) and `POLICY_AUD` (the application's audience tag) in `.env.selfhost` — the deploy then provisions no Access resources.--## 5) Validate setup+## 5) Create your account1. Open the Worker URL printed at the end of the deploy.-2. Sign in with Cloudflare Access.-3. OpenSEO should load after login.+2. Create the administrator's account. Do this right after the deploy finishes: registration closes once the first account exists, and until then anyone who finds the URL could claim the installation.+3. OpenSEO loads with a default project. Add your website to get started.++If something fails, see Troubleshooting below.++## Giving teammates access++Invite them from Team settings. The app copies an invitation link; the invited address creates its own account from that link and joins your workspace. There is no email delivery, so send the link yourself. Everyone works in one shared workspace and sees the same projects.-If it doesn't, see Troubleshooting below.+## Connecting MCP clients++MCP clients connect to `https://YOUR_WORKER_HOSTNAME/mcp` and sign in with your OpenSEO account, the same way they connect to the hosted service. Follow the [MCP setup guide](https://openseo.so/docs/mcp) with your Worker URL in place of the hosted one.++## Forgot a password?++There is no email delivery, so an operator resets passwords from a terminal. See [Manage accounts](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#manage-accounts).## Updating to the latest OpenSEO version@@ -76,16 +86,22 @@ pnpm installpnpm deploy:selfhost --yes```-## Giving teammates access+## Cloudflare Access: the most secure option++With `AUTH_MODE=cloudflare_access`, Cloudflare's own login protects the Worker: every request is checked at Cloudflare's edge before it reaches OpenSEO, and only the emails you list get through. It needs an extra login scope, a Zero Trust team (created for you), and Zero Trust settings before MCP clients can connect, so expect more setup. Choose the sign-in mode before your first deploy; the two keep separate user records.++1. In `.env.selfhost`, set `AUTH_MODE=cloudflare_access` and `ACCESS_ALLOWED_EMAILS` (comma-separated).+2. Add the `access:write` scope to your Cloudflare login: run `pnpm alchemy login --configure`, answer yes to "Customize OAuth scopes?", and select `access:write` alongside the defaults.+3. Run `pnpm deploy:selfhost --yes`. The deploy creates the Cloudflare Access application protecting the Worker (allowing exactly `ACCESS_ALLOWED_EMAILS`). If the account has no Zero Trust team yet, one is created for you, named after your workers.dev subdomain.-Add the teammate to `ACCESS_ALLOWED_EMAILS` in `.env.selfhost` and redeploy. Dashboard edits to that Access policy are overwritten on the next deploy. (If you manage the Access application yourself, edit its Allow policy in Zero Trust instead.)+Open the printed URL and sign in with Cloudflare Access. To add teammates, add them to `ACCESS_ALLOWED_EMAILS` and redeploy; dashboard edits to that Access policy are overwritten on the next deploy. To manage the Access application yourself, set `TEAM_DOMAIN` (`https://your-team.cloudflareaccess.com`) and `POLICY_AUD` (the application's audience tag) instead — the deploy then provisions no Access resources. MCP clients need Managed OAuth turned on for the Access application; see [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#through-cloudflare-access).-Everyone allowed through Cloudflare Access works in one shared workspace and sees the same projects. Deployments upgraded from older versions (which gave each user a separate workspace) show a one-time dashboard banner — clicking it migrates all previous per-user work into the shared workspace.+Deployments created before password accounts existed have no `AUTH_MODE` in `.env.selfhost`, which still means Cloudflare Access, so they keep working unchanged. Deployments upgraded from older versions (which gave each user a separate workspace) show a one-time dashboard banner — clicking it migrates all previous per-user work into the shared workspace.## Troubleshooting-- Login fails: re-check `ACCESS_ALLOWED_EMAILS` in `.env.selfhost` and redeploy.- `https://<your-worker-hostname>/api/health` reports runtime configuration checks and database status.+- Cloudflare Access login fails: re-check `ACCESS_ALLOWED_EMAILS` in `.env.selfhost` and redeploy.- For server errors, open the Worker `Logs` or run `pnpm exec wrangler tail`. Site audits run in a separate worker: `pnpm exec wrangler tail open-seo-selfhost-audit`.## Tearing it down@@ -94,8 +110,8 @@ Everyone allowed through Cloudflare Access works in one shared workspace and seepnpm alchemy destroy --env-file .env.selfhost --stage selfhost```-This deletes the Workers, the stage-suffixed D1/KV/R2 resources (including your data), and the Access application.+This deletes the Workers, the stage-suffixed D1/KV/R2 resources (including your data), and the Access application if the deploy created one.## Next steps-See [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md) for connecting MCP clients and telemetry.+See [Operations](./SELF_HOSTING_CLOUDFLARE_OPERATIONS.md) for managing accounts, connecting MCP clients, and telemetry.diff --git a/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md b/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.mdindex 052e9d4d..41348a60 100644--- a/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md+++ b/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md@@ -1,10 +1,14 @@# Cloudflare Self-Hosting: Operations-Day-to-day tasks after [initial setup](./SELF_HOSTING_CLOUDFLARE.md): connect the MCP server, render JavaScript in site audits, and manage telemetry. Updating and teammate access are covered in the [deploy guide](./SELF_HOSTING_CLOUDFLARE.md) (or the [legacy page](./SELF_HOSTING_CLOUDFLARE_LEGACY.md) for pre-alchemy deployments).+Day-to-day tasks after [initial setup](./SELF_HOSTING_CLOUDFLARE.md): connect the MCP server, manage accounts, render JavaScript in site audits, and manage telemetry. Updating and teammate access are covered in the [deploy guide](./SELF_HOSTING_CLOUDFLARE.md) (or the [legacy page](./SELF_HOSTING_CLOUDFLARE_LEGACY.md) for pre-alchemy deployments).-## Connect the MCP server through Cloudflare Access+## Connect the MCP server-Use the same Cloudflare Access application that protects your OpenSEO Worker.+With password accounts (`AUTH_MODE=password`, the default for new deployments), MCP clients connect to `https://YOUR_WORKER_HOSTNAME/mcp` and sign in with your OpenSEO account, exactly as they connect to the hosted service; nothing needs to be enabled in Cloudflare. Follow the [MCP setup guide](https://openseo.so/docs/mcp) with your Worker URL in place of the hosted one.++### Through Cloudflare Access++With `AUTH_MODE=cloudflare_access`, use the same Cloudflare Access application that protects your OpenSEO Worker.Managed OAuth is required for MCP clients and is not enabled by default.1. Open Cloudflare Zero Trust.@@ -26,6 +30,35 @@ MCP clients should connect to:https://YOUR_WORKER_HOSTNAME/mcp```+## Manage accounts++With password accounts, the first visitor creates the administrator's account and teammates join from invitation links (Team settings). There is no email delivery, so password resets and accounts outside the invitation flow are operator commands:++1. Set `OPENSEO_OPERATOR_SECRET` in `.env.selfhost` to a random value (`openssl rand -hex 32`) and redeploy. This turns on the operator endpoint, which answers only to requests carrying that secret.+2. Run the command with the password on standard input and the deployed URL in `OPENSEO_URL`. This Bash example keeps the password out of shell history and process arguments:++```bash+read -rs -p 'New password: ' password; echo+printf '%s\n' "$password" | OPENSEO_URL=https://YOUR_WORKER_HOSTNAME pnpm selfhost:admin reset-password [email protected]+unset password+```++A reset signs that user out everywhere. `pnpm selfhost:admin create-user [email protected] 'Your name'` creates an account the same way, for example to create the administrator's account from the terminal before anyone opens the URL. `OPENSEO_URL` can also live in `.env.selfhost`.++### Switching from Cloudflare Access to password accounts++Existing users keep their data, but they signed in through Cloudflare and have no password, and registration is closed once any user exists, so give each of them a password:++1. Set `AUTH_MODE=password` and `OPENSEO_OPERATOR_SECRET` in `.env.selfhost` and redeploy. The deploy removes the Access application it created, so the app is reachable without Cloudflare's login from then on.+2. Find each user's id in the `user` table of the `open-seo-db-selfhost` D1 database (Cloudflare dashboard, Storage & Databases, D1).+3. For each user, with the password on standard input as above:++```sh+OPENSEO_URL=https://YOUR_WORKER_HOSTNAME pnpm selfhost:admin claim-legacy-user USER_ID [email protected] shared-workspace+```++Everyone shares the `shared-workspace` organization; the command makes the user one of its owners.+## AI visibility trackingAI Visibility uses your `DATAFORSEO_API_KEY`; tracked questions are sent to DataForSEO and billed directly by the provider. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. Deployment configures background collection and a five-minute cron that dispatches due daily, weekly, or monthly checks. The app shows the collection cost before a check or schedule starts. See the [AI Visibility guide](https://openseo.so/docs/ai-visibility).diff --git a/docs/SELF_HOSTING_DOCKER.md b/docs/SELF_HOSTING_DOCKER.mdindex d9fa2e62..2aaf39ec 100644--- a/docs/SELF_HOSTING_DOCKER.md+++ b/docs/SELF_HOSTING_DOCKER.md@@ -1,113 +1,165 @@# Docker Self-Hosting-Run OpenSEO locally with Docker.+Run OpenSEO on your own server or computer with Docker Compose. The image is prebuilt (`ghcr.io/every-app/open-seo-standalone`), so OpenSEO is ready a few seconds after it starts. You sign in with email and password accounts: the first visitor creates the administrator's account and teammates join from invitation links. You pay DataForSEO, OpenRouter and any rendering provider directly.-In Docker mode, OpenSEO uses `AUTH_MODE=local_noauth` (no auth checks, local admin user `admin@localhost`). Only expose it behind your own auth-protected reverse proxy, tunnel, or private network.+Already running the older single-container image (`ghcr.io/every-app/open-seo`)? It keeps getting updates. When you are ready, [move to this setup](#move-from-the-old-docker-image); your data comes with you.-The default `compose.yaml` uses the published GHCR image:+## Install-- `ghcr.io/every-app/open-seo:latest`+You need Docker Engine or Docker Desktop with Compose, at least 4 GiB of memory for Docker, and a [DataForSEO API key](./DATAFORSEO_API_KEY.md). Every command below runs from the repository root:-## Prerequisites--- Docker Desktop (or Docker Engine + Docker Compose)-- A DataForSEO API key (see [`DATAFORSEO_API_KEY.md`](./DATAFORSEO_API_KEY.md))+```sh+git clone https://github.com/every-app/open-seo.git+cd open-seo+export COMPOSE_FILE=deploy/standalone/compose.yaml+cp deploy/standalone/.env.example deploy/standalone/.env+```-## Quickstart+In `deploy/standalone/.env`, set `STORAGE_SECRET_KEY` to a unique random value (for example the output of `openssl rand -hex 32`) and `DATAFORSEO_API_KEY` to your key. Leave `BETTER_AUTH_URL=http://localhost:3001` for use on this machine. Then start OpenSEO:-```bash-cp .env.example .env+```sh+docker compose pull+docker compose up -d+docker compose logs -f init```-Set `DATAFORSEO_API_KEY` in `.env` using the [DataForSEO setup guide](./DATAFORSEO_API_KEY.md), then start OpenSEO:+Wait for `OpenSEO initialized and ready.`, open <http://localhost:3001> and create the administrator's account. Registration closes once that account exists, so create it before you put the installation on the internet.++### Coolify, Portainer and Dokploy++`deploy/standalone/compose.yaml` reads no other files from the repository, so you can paste it into a platform that runs Compose files, with the variables from `deploy/standalone/.env.example`. Point the platform's domain at the `web` service on port 80 and set `BETTER_AUTH_URL` to that `https://` address. The `init` service exits after each start by design.++## Accounts++Invite teammates from Team settings. The app copies an invitation link; the invited address creates its own account from that link and joins your workspace. There is no email delivery, so send the link yourself.++Password resets and accounts outside the invitation flow are done from a terminal with the admin command. This Bash example keeps the password out of shell history:```bash-docker compose up -d+read -rs -p 'New password: ' password; echo+printf '%s\n' "$password" | pnpm standalone:admin reset-password [email protected]+unset password```-Open `http://localhost:<PORT>` (default `3001`). The first start builds the app and may take 1-2 minutes; follow progress with `docker compose logs -f`.+`create-user [email protected] 'Your name'` creates an account the same way. A reset signs that user out everywhere. Without pnpm, run `docker compose exec -T runtime node /opt/standalone/admin.mjs ...` instead.++### Without sign-in (advanced)-Optional env values:+`AUTH_MODE=local_noauth` runs OpenSEO without sign-in, as one admin user. Use it only where the network already controls who can reach the app, for example on a private network, behind Tailscale or behind your own authenticating proxy. To switch an existing installation to accounts later, set `AUTH_MODE=password`, run `docker compose up -d --force-recreate init web crawl-gateway`, and give the admin an email and password; its data and conversations stay:-- `PORT` (defaults to `3001`)-- `ALLOWED_HOST` (single reverse-proxy hostname to allow in Vite preview)-- `AUTH_MODE=local_noauth` (already set in compose)-- `OPEN_SEO_IMAGE` (defaults to `ghcr.io/every-app/open-seo:latest`)+```sh+pnpm standalone:admin claim-legacy-user local-admin [email protected] delegated-local-admin+```-AI Visibility uses your `DATAFORSEO_API_KEY` and sends tracked questions to DataForSEO. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. You pay providers directly; the app shows the collection cost before a check or schedule starts. Keep the container running for background answers and daily, weekly, or monthly tracking. The built-in scheduler checks for due work every five minutes; no host cron setup is required. See the [AI Visibility guide](https://openseo.so/docs/ai-visibility).+## Enable features-If you are putting Docker behind a reverse proxy or a temporary tunnel, remember that Docker self-hosting runs with app auth disabled. Only expose it behind your own auth-protected reverse proxy, tunnel, or private network, and add the public hostname before restarting:+Set credentials in `deploy/standalone/.env`, then apply them without rebuilding:-```bash-ALLOWED_HOST=yourdomain.com docker compose up -d+```sh+docker compose up -d --force-recreate init web crawl-gateway```-You can also persist it in `.env`.+| Variable | Purpose |+| ------------------------------------------ | ---------------------------------------------------------------------------- |+| `DATAFORSEO_API_KEY` | Base64-encoded `login:password`; keyword, backlink, rank and site data |+| `OPENROUTER_API_KEY` | SAM conversations, website research and summaries |+| `OPENROUTER_MODEL` | Optional model override |+| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | Optional Search Console and Analytics linking with your own Google OAuth app |+| `CONTEXT_API_KEY` | Optional JavaScript rendering for site audits |-## Telemetry+For Google, register your own OAuth application with these redirect URLs under your public address: `/api/gsc/oauth/callback` for Search Console and `/api/ga4/oauth/callback` for Analytics. See [`SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md`](./SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md). Signing in with Google is not offered; accounts use email and password.-OpenSEO collects anonymized telemetry for core usage events: heartbeats with aggregate counts (installs, users, projects, feature usage) tied to a random install ID, sent every 5 minutes during the first two hours after install, then at most once daily. Telemetry also includes failed setup check names and statuses, never values or error messages. No URLs, keywords, prompts, emails, or IP-derived location are collected, and idle installs send nothing.+Site audits can crawl up to 10,000 pages (1,000 with JavaScript rendering), with no lifetime quota. Costs are what the providers charge, with no OpenSEO markup.-Heartbeats are triggered by requests to the app or MCP server. Requests to `/api/health`, including Docker's automatic health checks, do not trigger telemetry.+MCP clients connect to `/mcp` and sign in with your OpenSEO account, or use an API key from Settings. Clients that register with a metadata URL (CIMD) are not supported; use dynamic client registration or an API key.-To disable it, set `OPENSEO_TELEMETRY_DISABLED=1` (or `DO_NOT_TRACK=1`) in `.env`, then run `docker compose up -d --force-recreate open-seo`.+## Public HTTPS-## Pin to a specific image tag+Set `BETTER_AUTH_URL=https://seo.example.com` before the first start, or run `docker compose up -d --force-recreate init web crawl-gateway` after changing it. Put an HTTPS reverse proxy in front of `127.0.0.1:3001` and forward WebSocket upgrades for SAM. Plain HTTP is accepted only for `localhost`.-Set `OPEN_SEO_IMAGE` in `.env` and restart:+Only Nginx is published, and only on the host's loopback address; storage, the crawl gateway and the runtime stay private. Crawls reach public addresses on ports 80 and 443 only; crawling private sites is intentionally unsupported.-```bash-OPEN_SEO_IMAGE=ghcr.io/every-app/open-seo:v1.2.3+## Updates++Make a backup, then pull the new image and restart:++```sh+node scripts/celld/backup.mjs backup ./backups/before-update+docker compose pull+docker compose stop web crawl-gateway runtimedocker compose up -d+docker compose logs init```-## Build your own image locally+Database migrations run in `init`. Going back to an older image does not undo them; restore the matching backup instead.-If you are testing local code changes, build and run a local tag:+To run your own changes instead of the published image, add the build file:-```bash-docker build -f deploy/docker/Dockerfile -t open-seo:local .-OPEN_SEO_IMAGE=open-seo:local docker compose up -d+```sh+export COMPOSE_FILE=deploy/standalone/compose.yaml:deploy/standalone/compose.build.yaml+docker compose up -d --build```-## Common commands+## Backup and restore-- Restart service after env changes:+A backup briefly stops the app, archives the storage and configuration volumes with checksums, then starts it again:-```bash-docker compose up -d open-seo+```sh+node scripts/celld/backup.mjs backup ./backups/2026-10-19```-- Pull latest published image and restart:+Backups contain credentials and user data; keep them somewhere private. Restore into a stopped, empty installation with the same storage credentials:-```bash-docker compose pull && docker compose up -d+```sh+node scripts/celld/backup.mjs restore ./backups/2026-10-19+docker compose up -d```-- Stop:+Restore refuses a non-empty volume and verifies the checksums. To test a restore beside a live installation, use a different `COMPOSE_PROJECT_NAME` and `PORT`.-```bash-docker compose down-```+The `config` volume holds the secrets generated at the first start. Keep it in your backups; nothing secret is built into the image.-## Health and troubleshooting+## Move from the old Docker image-Startup checks appear in `docker compose logs` before the build. Once running, `/api/health` reports configuration and database status, and `docker compose ps` reports container health. Scheduler failures appear as `[scheduler]` messages in container logs. The pinned Cloudflare Vite runtime exposes `/cdn-cgi/handler/scheduled`; the container calls it only at `127.0.0.1` using the configured `PORT`. It passes the five-minute cron expression without overriding the clock. Newer Cloudflare versions may use a different local route; the [Cron Triggers documentation](https://developers.cloudflare.com/workers/configuration/cron-triggers/#test-cron-triggers-locally) describes the local handler mechanism.+The older image (`ghcr.io/every-app/open-seo`) keeps its data in a volume named `open_seo_data`, in a format this setup cannot read directly. A one-time `migrate` service copies it over. It carries projects, saved keywords, rank trackers and their history, audits, reports and SAM conversations. It does not carry Google connections, sessions, API keys or MCP connections, provider caches, or work that is still running.-## Troubleshooting environment variables+1. Update the old installation and start it once (`docker compose pull && docker compose up -d` in its directory). Let running audits, rank checks and SAM replies finish.+2. Stop it with `docker compose down`. The data volume stays; find its name with `docker volume ls`. For a checkout in a directory called `open-seo` it is `open-seo_open_seo_data`.+3. Update the checkout (`git pull`), then prepare `deploy/standalone/.env` as in [Install](#install), but do not start it yet. Set `LEGACY_VOLUME` to the volume name. Set `AUTH_MODE=local_noauth` to keep working without sign-in, or leave `AUTH_MODE=password` to switch to accounts.+4. Start it with the migration file added:-To confirm Docker Compose is using the expected environment variables:+ ```sh+ export COMPOSE_FILE=deploy/standalone/compose.yaml:deploy/standalone/compose.migrate.yaml+ docker compose pull --ignore-buildable+ docker compose up -d --build+ docker compose logs -f migrate+ ```-```bash-docker compose config-```+ The app opens once the copy has finished. Starting again with the same files changes nothing. When it reports success, set `COMPOSE_FILE` back to `deploy/standalone/compose.yaml`.-Check that `AUTH_MODE=local_noauth`, and that `DATAFORSEO_API_KEY` is the base64-encoded value of your DataForSEO email and API password in this format:-`email:password`.+5. Without sign-in, open the app: everything is where it was. With accounts, give the old admin an email and password: `pnpm standalone:admin claim-legacy-user local-admin [email protected] delegated-local-admin`, with the password on standard input as in [Accounts](#accounts).+6. Check your projects and reports, then reconnect Google and review schedules.-If you changed `.env`, recreate the container so Compose reapplies it:+Keep the old volume until you are satisfied; only `docker volume rm` deletes it. If the copy stops partway, starting again resumes it. When the old volume is on another machine, run `node scripts/celld/export-legacy.mjs COPIED_STATE_V3 OUTPUT_DIR` from a checkout there and import the directory with `node /opt/standalone/import.mjs` inside the `init` container.-```bash-docker compose up -d --force-recreate open-seo+To hand the move to a coding agent, give it this:++```text+Move my OpenSEO Docker installation from the old image (ghcr.io/every-app/open-seo) to the new Docker setup, following "Move from the old Docker image" in docs/SELF_HOSTING_DOCKER.md of this checkout. Update the old installation first and let its running work finish, stop it, find its data volume, prepare deploy/standalone/.env (keep AUTH_MODE=local_noauth unless I say otherwise), run the migration, and then tell me what was not migrated and what I need to reconnect. Do not delete the old volume.+```++## Troubleshooting++```sh+docker compose ps+docker compose logs --tail 100 init runtime storage crawl-gateway web+curl --fail http://localhost:3001/api/health```++`/api/health` succeeds only when sign-in is configured and the database answers. If `init` fails, Nginx does not start; its log says why. `docker compose down -v` deletes the installation's data and secrets.++## How it works++OpenSEO is written for Cloudflare Workers. In Docker it runs on [celld](https://github.com/denoland/celld), an open-source runtime for Workers code, which provides the same database, storage, background workflows and scheduled jobs on your own machine. [RustFS](https://github.com/rustfs/rustfs) stores that state, Nginx serves the app, and a small crawl gateway keeps site crawls away from private network addresses. `init` runs once at each start: it generates secrets on the first run, loads the app and applies database migrations.++The runtime container is limited to 2 GiB of memory, and the whole stack typically uses 1 to 2 GiB. Adjust `mem_limit` in `deploy/standalone/compose.yaml` if you need to.diff --git a/docs/SELF_HOSTING_DOCKER_LEGACY.md b/docs/SELF_HOSTING_DOCKER_LEGACY.mdnew file mode 100644index 00000000..742c71f0--- /dev/null+++ b/docs/SELF_HOSTING_DOCKER_LEGACY.md@@ -0,0 +1,113 @@+# Docker Self-Hosting: older single-container image++This guide covers the older image, `ghcr.io/every-app/open-seo`, which builds the app each time it starts and runs without sign-in. It keeps getting updates, so existing installations keep working. New installations should use the [current Docker setup](./SELF_HOSTING_DOCKER.md), which starts in seconds and has accounts; existing ones can [move to it with their data](./SELF_HOSTING_DOCKER.md#move-from-the-old-docker-image).++In Docker mode, OpenSEO uses `AUTH_MODE=local_noauth` (no auth checks, local admin user `admin@localhost`). Only expose it behind your own auth-protected reverse proxy, tunnel, or private network.++The default `compose.yaml` uses the published GHCR image:++- `ghcr.io/every-app/open-seo:latest`++## Prerequisites++- Docker Desktop (or Docker Engine + Docker Compose)+- A DataForSEO API key (see [`DATAFORSEO_API_KEY.md`](./DATAFORSEO_API_KEY.md))++## Quickstart++```bash+cp .env.example .env+```++Set `DATAFORSEO_API_KEY` in `.env` using the [DataForSEO setup guide](./DATAFORSEO_API_KEY.md), then start OpenSEO:++```bash+docker compose up -d+```++Open `http://localhost:<PORT>` (default `3001`). The first start builds the app and may take 1-2 minutes; follow progress with `docker compose logs -f`.++Optional env values:++- `PORT` (defaults to `3001`)+- `ALLOWED_HOST` (single reverse-proxy hostname to allow in Vite preview)+- `AUTH_MODE=local_noauth` (already set in compose)+- `OPEN_SEO_IMAGE` (defaults to `ghcr.io/every-app/open-seo:latest`)++AI Visibility uses your `DATAFORSEO_API_KEY` and sends tracked questions to DataForSEO. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. You pay providers directly; the app shows the collection cost before a check or schedule starts. Keep the container running for background answers and daily, weekly, or monthly tracking. The built-in scheduler checks for due work every five minutes; no host cron setup is required. See the [AI Visibility guide](https://openseo.so/docs/ai-visibility).++If you are putting Docker behind a reverse proxy or a temporary tunnel, remember that Docker self-hosting runs with app auth disabled. Only expose it behind your own auth-protected reverse proxy, tunnel, or private network, and add the public hostname before restarting:++```bash+ALLOWED_HOST=yourdomain.com docker compose up -d+```++You can also persist it in `.env`.++## Telemetry++OpenSEO collects anonymized telemetry for core usage events: heartbeats with aggregate counts (installs, users, projects, feature usage) tied to a random install ID, sent every 5 minutes during the first two hours after install, then at most once daily. Telemetry also includes failed setup check names and statuses, never values or error messages. No URLs, keywords, prompts, emails, or IP-derived location are collected, and idle installs send nothing.++Heartbeats are triggered by requests to the app or MCP server. Requests to `/api/health`, including Docker's automatic health checks, do not trigger telemetry.++To disable it, set `OPENSEO_TELEMETRY_DISABLED=1` (or `DO_NOT_TRACK=1`) in `.env`, then run `docker compose up -d --force-recreate open-seo`.++## Pin to a specific image tag++Set `OPEN_SEO_IMAGE` in `.env` and restart:++```bash+OPEN_SEO_IMAGE=ghcr.io/every-app/open-seo:v1.2.3+docker compose up -d+```++## Build your own image locally++If you are testing local code changes, build and run a local tag:++```bash+docker build -f deploy/docker/Dockerfile -t open-seo:local .+OPEN_SEO_IMAGE=open-seo:local docker compose up -d+```++## Common commands++- Restart service after env changes:++```bash+docker compose up -d open-seo+```++- Pull latest published image and restart:++```bash+docker compose pull && docker compose up -d+```++- Stop:++```bash+docker compose down+```++## Health and troubleshooting++Startup checks appear in `docker compose logs` before the build. Once running, `/api/health` reports configuration and database status, and `docker compose ps` reports container health. Scheduler failures appear as `[scheduler]` messages in container logs. The pinned Cloudflare Vite runtime exposes `/cdn-cgi/handler/scheduled`; the container calls it only at `127.0.0.1` using the configured `PORT`. It passes the five-minute cron expression without overriding the clock. Newer Cloudflare versions may use a different local route; the [Cron Triggers documentation](https://developers.cloudflare.com/workers/configuration/cron-triggers/#test-cron-triggers-locally) describes the local handler mechanism.++## Troubleshooting environment variables++To confirm Docker Compose is using the expected environment variables:++```bash+docker compose config+```++Check that `AUTH_MODE=local_noauth`, and that `DATAFORSEO_API_KEY` is the base64+encoded value of your DataForSEO email and API password in this format:+`email:password`.++If you changed `.env`, recreate the container so Compose reapplies it:++```bash+docker compose up -d --force-recreate open-seo+```diff --git a/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md b/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.mdindex d1080ee1..799f5136 100644--- a/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md+++ b/docs/SELF_HOSTING_GOOGLE_SEARCH_CONSOLE.md@@ -63,7 +63,9 @@ Set these three values, then restart OpenSEO:| `BETTER_AUTH_SECRET` | A random string of **at least 32 characters** (encrypts stored tokens). |`BETTER_AUTH_SECRET` is not needed for normal self-hosting — only for Search-Console, because the stored OAuth tokens are encrypted at rest with it. Generate+Console, because the stored OAuth tokens are encrypted at rest with it. The+Cloudflare self-host with password accounts (`AUTH_MODE=password`) and the+Docker setup (`deploy/standalone`) generate one already; leave it unset there. Generateone with:```sh@@ -72,19 +74,23 @@ openssl rand -base64 32Where to set them:-- **Docker self-hosting:** `.env`+- **Docker self-hosting:** `deploy/standalone/.env`+- **Older Docker image:** `.env`- **Cloudflare:** the Workers dashboard (as secrets)- **Local development:** `.env.local`## 5) Restart and connectRestart OpenSEO so it picks up the new variables. For Docker, changing `.env`-means Compose has to recreate the container to reapply it:+means Compose has to recreate the containers to reapply it:```bash-docker compose up -d --force-recreate open-seo+docker compose up -d --force-recreate init web crawl-gateway```+On the older Docker image, run `docker compose up -d --force-recreate open-seo`+instead.+Then open **Integrations**, click **Connect with Google**, authorize the Googleaccount that owns your verified property, and pick the property to bind to yourproject.@@ -108,11 +114,7 @@ must exactly equal `<your-origin>/api/gsc/oauth/callback`. Re-check scheme(in the app or via the MCP tools) — one of `GOOGLE_CLIENT_ID`,`GOOGLE_CLIENT_SECRET`, or `BETTER_AUTH_SECRET` is missing, or the secret isshorter than 32 characters. Set all three and restart. On Docker, recreate the-container so Compose reapplies `.env`:--```bash-docker compose up -d --force-recreate open-seo-```+containers so Compose reapplies `.env`, as in [step 5](#5-restart-and-connect).**`access_denied` during sign-in** — the Google account isn't listed as a testuser on the OAuth consent screen (while the app is in Testing mode). Add it underdiff --git a/docs/maintainers/preview-deployments.md b/docs/maintainers/preview-deployments.mdindex f87eed2a..0c5b313b 100644--- a/docs/maintainers/preview-deployments.md+++ b/docs/maintainers/preview-deployments.md@@ -62,7 +62,8 @@ Zero Trust team domain. Set that full value in `.env.preview` as`https://open-seo-<stage>.<WORKERS_SUBDOMAIN>` — hosted previews use that as`BETTER_AUTH_URL`, and CI's verify step probes it; a wrong value fails thecheck. Previews in `local_noauth` or `cloudflare_access` mode deploy without-it, since nothing reads `BETTER_AUTH_URL` there.+it, since nothing reads `BETTER_AUTH_URL` there; `password` stages read the+subdomain from the account when it is unset.Set `ACCESS_ALLOWED_EMAILS` to the exact comma-separated emails that may openpreviews:diff --git a/docs/maintainers/specs/0018-docker-self-hosting.md b/docs/maintainers/specs/0018-docker-self-hosting.mdnew file mode 100644index 00000000..0ecdb360--- /dev/null+++ b/docs/maintainers/specs/0018-docker-self-hosting.md@@ -0,0 +1,31 @@+# Docker self-hosting++OpenSEO is written for Cloudflare Workers: D1, KV, R2, Durable Objects, Workflows and cron. Docker self-hosting runs that same code, unchanged, on a prebuilt image instead of rebuilding the app and running Cloudflare's local development server inside a container.++## How it works++The image (`deploy/standalone/Dockerfile`, published as `ghcr.io/every-app/open-seo-standalone`) contains the compiled app and [celld](https://github.com/denoland/celld), an open-source runtime for Workers code. celld provides D1 and Durable Objects on SQLite, KV, R2, Workflows and cron, and keeps their state in an S3-compatible bucket. `vite build --mode standalone` produces a single server module, because celld loads one module per deployment, and `scripts/celld/package.mjs` packages it with its assets and migrations.++The Compose stack (`deploy/standalone/compose.yaml`) runs:++- `runtime`: celld with the app.+- `storage`: RustFS, the S3-compatible store for celld's state.+- `init`: runs once at each start. It generates the secrets on the first start, writes the deployment configuration, loads the app, applies database migrations and writes Nginx's site config.+- `crawl-gateway`: the proxy every outbound crawl goes through. It resolves each target, rejects private and reserved addresses, and pins the connection to the address it checked, including on redirects.+- `web`: Nginx, the only published service. It blocks the operator endpoints from outside the stack.++The Compose file reads nothing else from the repository, so Compose-based platforms can run it on its own; `compose.build.yaml` adds the build for people running their own changes.++Sign-in is chosen at the first start with `AUTH_MODE`. `password` gives Better Auth accounts with none of the hosted service's billing, email or telemetry. Registration is open only for the first account and for addresses with a pending invitation. `local_noauth` runs without sign-in as one admin, as the original Docker image did. The server tells the client which mode is running, so one image serves both. Operator commands (create a user, reset a password, claim the old admin) go through an endpoint that requires a secret generated at the first start.++The original single-container image (`deploy/docker/`, `ghcr.io/every-app/open-seo`) keeps being published from the same workflow. Existing installations auto-update from its `:latest` tag and could not run a multi-container stack or read its storage, so the new image never takes that name. That image shows a notice that links to the migration. The `migrate` service in `compose.migrate.yaml` reads the old volume with Miniflare and imports it once into an unused database. It carries projects, keywords, rank history, audits, reports and SAM conversations, and leaves out sessions, API keys, OAuth grants, Google connections and caches.++## Alternatives++Rewriting the server for Node with a job queue and a separate actor system would have removed the Workers dependency, at the cost of a second implementation of every background feature that would drift from the hosted one. celld runs the hosted code as it is.++Keeping the original image and only skipping its startup build would have left Cloudflare's local development server, which is not built for long-running use, as the production runtime.++A separate repository for the Docker edition was planned, carrying its own changes to the app. Keeping one codebase and choosing behavior by `AUTH_MODE` avoids a fork that conflicts with every change to main.++MinIO's community images stopped being published in September 2026. Garage accepts but does not enforce conditional writes, which celld relies on. RustFS passes celld's storage checks.diff --git a/knip.jsonc b/knip.jsoncindex 9ac98153..8fdb4f8d 100644--- a/knip.jsonc+++ b/knip.jsonc@@ -5,6 +5,8 @@"deploy/alchemy/alchemy.preview-access.run.ts",// Site-audit aux worker entry (wrangler.audit.jsonc)"src/audit-worker.ts",+ // Docker self-hosting entry (wrangler.standalone.json)+ "src/standalone-server.ts",// Separately bundled MCP App, served as an inline HTML resource."src/client/mcp-widgets/main.tsx",// Detect Tanstack Start Routes@@ -45,6 +47,12 @@// Disable Drizzle plugin - it tries to load drizzle/sqlite.config.ts which imports cloudflare:workers"drizzle": false,"ignoreDependencies": [+ // Resolved on purpose through another package's dependency tree with+ // require.resolve(name, { paths }): the standalone build's portable+ // password hash via better-auth (vite.config.ts), and the legacy Docker+ // export via wrangler (scripts/celld).+ "@better-auth/utils",+ "miniflare",// Tailwindcss used via @tailwindcss/vite plugin"tailwindcss",// Imported by app.css; shadcn is also the component CLIdiff --git a/package.json b/package.jsonindex 1fc79348..942a7407 100644--- a/package.json+++ b/package.json@@ -12,6 +12,7 @@"dev:agents": "mkdir -p .logs && portless run vite dev 2>&1 | tee .logs/dev-server.log","dev:agents:force": "mkdir -p .logs && portless --force run vite dev 2>&1 | tee .logs/dev-server.log","build": "pnpm build:report-widgets && vite build && tsc --noEmit",+ "build:standalone": "pnpm build:report-widgets && vite build --mode standalone && node scripts/celld/package.mjs","build:report-widgets": "tsc --noEmit -p tsconfig.report-widgets.json && vite build -c vite.report-widgets.config.ts","lint": "oxlint . --type-aware","lint:fix": "oxlint . --type-aware --fix",@@ -45,6 +46,7 @@"test": "vitest run","test:watch": "vitest","test:ci": "vitest run --reporter=dot",+ "test:standalone:gateway": "node --test scripts/celld/runtime/crawl-gateway.test.mjs","test:e2e": "playwright test -c tests/playwright.config.ts","test:e2e:free-tools": "playwright test -c tests/playwright.free-tools.config.ts","test:e2e:mcp-isolation": "playwright test -c tests/playwright.mcp-isolation.config.ts",@@ -59,6 +61,8 @@"repair:rank-locations": "tsx scripts/repair-rank-tracking-locations.ts","seed:rank-tracking": "tsx scripts/seed-rank-tracking.ts","seed:projects": "tsx scripts/seed-projects.ts",+ "standalone:admin": "docker compose -f deploy/standalone/compose.yaml exec -T runtime node /opt/standalone/admin.mjs",+ "selfhost:admin": "node --env-file=.env.selfhost scripts/celld/runtime/admin.mjs","ci:check": "prettier --check . && knip && tsc --noEmit && tsc --noEmit -p tests/badseo/tsconfig.json && tsc --noEmit -p tsconfig.report-widgets.json && oxlint . --type-aware && pnpm sync-plugin-skills && test -z \"$(git status --porcelain -- plugins/openseo/skills)\""},"cloudflare": {diff --git a/scripts/celld/backup.mjs b/scripts/celld/backup.mjsnew file mode 100644index 00000000..3e0526d4--- /dev/null+++ b/scripts/celld/backup.mjs@@ -0,0 +1,160 @@+import { execFileSync, spawn } from "node:child_process";+import { createReadStream, createWriteStream } from "node:fs";+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { createHash } from "node:crypto";+import { resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { pipeline } from "node:stream/promises";++const [command, directory] = process.argv.slice(2);+if (!["backup", "restore"].includes(command) || !directory)+ throw new Error(+ "Usage: node scripts/celld/backup.mjs backup|restore DIRECTORY",+ );+const root = resolve(directory);+const docker = (...args) =>+ execFileSync("docker", args, {+ encoding: "utf8",+ stdio: ["ignore", "pipe", "inherit"],+ }).trim();+// The stack is defined in deploy/standalone; COMPOSE_FILE overrides it.+const composeFile =+ process.env.COMPOSE_FILE ??+ fileURLToPath(+ new URL("../../deploy/standalone/compose.yaml", import.meta.url),+ );+const compose = (...args) => docker("compose", "-f", composeFile, ...args);+const id = (service) => compose("ps", "-aq", service);+// The named volume behind a service mount. Restore binds it directly:+// --volumes-from would inherit runtime's read-only /config.+const volume = (service, path) =>+ docker(+ "inspect",+ "--format",+ `{{range .Mounts}}{{if eq .Destination "${path}"}}{{.Name}}{{end}}{{end}}`,+ id(service),+ );+async function hash(path) {+ const sum = createHash("sha256");+ for await (const part of createReadStream(path)) sum.update(part);+ return sum.digest("hex");+}+async function archive(service, path, file, restore = false) {+ const child = spawn(+ "docker",+ [+ "run",+ "--rm",+ "--network",+ "none",+ "-i",+ "-u",+ "0",+ ...(restore+ ? ["-v", `${volume(service, path)}:${path}`]+ : ["--volumes-from", `${id(service)}:ro`]),+ "--entrypoint",+ "tar",+ image,+ restore ? "-xzf" : "-czf",+ "-",+ "-C",+ path,+ ...(restore ? [] : ["."]),+ ],+ { stdio: ["pipe", "pipe", "inherit"] },+ );+ const completed = new Promise((resolve, reject) => {+ child.on("error", reject);+ child.on("close", (code) =>+ code === 0+ ? resolve()+ : reject(new Error(`Archive process exited ${code}`)),+ );+ });+ if (restore) {+ child.stdout.resume();+ await pipeline(createReadStream(file), child.stdin);+ } else {+ child.stdin.end();+ await pipeline(+ child.stdout,+ createWriteStream(file, { mode: 0o600, flags: "wx" }),+ );+ }+ await completed;+}+let image;+if (command === "backup") {+ await mkdir(root, { mode: 0o700 }); // refuse overwriting an existing backup+ if (!id("runtime") || !id("storage"))+ throw new Error("Create the Compose deployment first");+ image = docker("inspect", "--format", "{{.Image}}", id("runtime"));+ const running = compose("ps", "--services", "--status", "running")+ .split("\n")+ .filter((name) =>+ ["web", "runtime", "crawl-gateway", "storage"].includes(name),+ );+ compose("stop", "web", "crawl-gateway", "runtime", "storage");+ try {+ await archive("storage", "/data", `${root}/storage.tar.gz`);+ await archive("runtime", "/config", `${root}/config.tar.gz`);+ const manifest = {+ format: 1,+ celld: "0.5.1",+ image,+ createdAt: new Date().toISOString(),+ files: {},+ };+ for (const file of ["storage.tar.gz", "config.tar.gz"])+ manifest.files[file] = await hash(`${root}/${file}`);+ await writeFile(+ `${root}/manifest.json`,+ JSON.stringify(manifest, null, 2) + "\n",+ { mode: 0o600 },+ );+ console.log(+ `Backup complete: ${root}. Contains credentials; store it privately.`,+ );+ } finally {+ if (running.length) compose("start", ...running);+ }+} else {+ const manifest = JSON.parse(await readFile(`${root}/manifest.json`, "utf8"));+ if (manifest.format !== 1 || manifest.celld !== "0.5.1")+ throw new Error("Unsupported backup version");+ for (const file of ["storage.tar.gz", "config.tar.gz"])+ if ((await hash(`${root}/${file}`)) !== manifest.files[file])+ throw new Error(`Checksum mismatch: ${file}`);+ if (compose("ps", "--services", "--status", "running"))+ throw new Error("Restore requires a stopped, empty Compose deployment");+ compose("create", "--no-build", "storage", "runtime");+ image = docker("inspect", "--format", "{{.Image}}", id("runtime"));+ for (const [service, path] of [+ ["storage", "/data"],+ ["runtime", "/config"],+ ]) {+ docker(+ "run",+ "--rm",+ "--network",+ "none",+ "-u",+ "0",+ "--volumes-from",+ id(service),+ "--entrypoint",+ "sh",+ image,+ "-c",+ // Buckets, secrets and the deployment are visible entries; a fresh+ // RustFS volume only holds its hidden .rustfs system directory.+ `test -z "$(ls ${path})"`,+ );+ }+ await archive("storage", "/data", `${root}/storage.tar.gz`, true);+ await archive("runtime", "/config", `${root}/config.tar.gz`, true);+ console.log(+ "Restore complete. Set matching storage credentials and BETTER_AUTH_URL, then run docker compose up -d. Runtime cache is rebuilt from the restored bucket.",+ );+}diff --git a/scripts/celld/create-legacy-fixture.mjs b/scripts/celld/create-legacy-fixture.mjsnew file mode 100644index 00000000..602ebf37--- /dev/null+++ b/scripts/celld/create-legacy-fixture.mjs@@ -0,0 +1,100 @@+import { createRequire } from "node:module";+import { dirname, resolve, join } from "node:path";+import { mkdir, readFile, readdir } from "node:fs/promises";+const require = createRequire(import.meta.url);+const { Miniflare, convertV4MiniflareOptions } = require(+ require.resolve("miniflare", {+ paths: [dirname(require.resolve("wrangler"))],+ }),+);+const directory = resolve(process.argv[2] ?? "/tmp/openseo-legacy-fixture");+await mkdir(directory, { mode: 0o700 });+const mf = new Miniflare(+ convertV4MiniflareOptions({+ name: "open-seo",+ modules: true,+ compatibilityDate: "2025-09-02",+ script: `import {DurableObject} from 'cloudflare:workers';+ export class SamChatAgent extends DurableObject {+ seed() {+ this.ctx.storage.sql.exec("CREATE TABLE assistant_messages (id TEXT PRIMARY KEY, session_id TEXT NOT NULL DEFAULT '', parent_id TEXT, role TEXT NOT NULL, content TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP)");+ this.ctx.storage.sql.exec("INSERT INTO assistant_messages(id, role, content) VALUES (?, ?, ?)",'legacy-message','user',JSON.stringify({id:'legacy-message',role:'user',parts:[{type:'text',text:'Preserved migration conversation'}]}));+ }+ }+ export default {fetch(){return new Response('fixture')}};`,+ d1Databases: { DB: "37bee90a-e1aa-404f-b01e-b0d1d479bda1" },+ r2Buckets: { R2: "open-seo" },+ durableObjects: {+ SAM_CHAT: {+ className: "SamChatAgent",+ useSQLite: true,+ unsafeUniqueKey: "open-seo-SamChatAgent",+ },+ },+ resourcePersistencePath: directory,+ }),+);+try {+ const db = await mf.getD1Database("DB");+ for (const name of (await readdir("drizzle/sqlite"))+ .filter((n) => n.endsWith(".sql") && !n.startsWith("0048"))+ .sort()) {+ const sql = await readFile(join("drizzle/sqlite", name), "utf8");+ for (const statement of sql+ .split("--> statement-breakpoint")+ .map((s) => s.trim())+ .filter(Boolean))+ await db.prepare(statement).run();+ }+ await db+ .prepare(+ "INSERT INTO user (id,name,email,email_verified,created_at,updated_at) VALUES (?,?,?,?,?,?)",+ )+ .bind(+ "local-admin",+ "Legacy Admin",+ "admin@localhost",+ 1,+ Date.now(),+ Date.now(),+ )+ .run();+ await db+ .prepare(+ "INSERT INTO organization (id,name,slug,created_at) VALUES (?,?,?,?)",+ )+ .bind(+ "delegated-local-admin",+ "Legacy workspace",+ "legacy-workspace",+ Date.now(),+ )+ .run();+ await db+ .prepare(+ "INSERT INTO projects (id,organization_id,name,domain) VALUES (?,?,?,?)",+ )+ .bind(+ "legacy-project",+ "delegated-local-admin",+ "Legacy project",+ "example.com",+ )+ .run();+ await db+ .prepare(+ "INSERT INTO sam_sessions (id,project_id,user_id,title) VALUES (?,?,?,?)",+ )+ .bind("legacy-session", "legacy-project", "local-admin", "Preserved chat")+ .run();+ const namespace = await mf.getDurableObjectNamespace("SAM_CHAT");+ await namespace.get(namespace.idFromName("legacy-session")).seed();+ const bucket = await mf.getR2Bucket("R2");+ await bucket.put("fixture/report.html", "<h1>Preserved report</h1>", {+ httpMetadata: { contentType: "text/html" },+ customMetadata: { fixture: "yes" },+ });+ console.log(`Legacy fixture ready at ${directory}`);+} finally {+ await mf.dispose();+}diff --git a/scripts/celld/export-legacy.mjs b/scripts/celld/export-legacy.mjsnew file mode 100644index 00000000..85c9e67d--- /dev/null+++ b/scripts/celld/export-legacy.mjs@@ -0,0 +1,212 @@+// Run from this checkout against a STOPPED copy of the old Docker volume.+// Miniflare is a development-only reader for its own storage format. It never+// enters the new runtime image. The input snapshot is copied before opening it.+import { createRequire } from "node:module";+import { dirname, resolve, join } from "node:path";+import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { createHash } from "node:crypto";+const require = createRequire(import.meta.url);+const { Miniflare, convertV4MiniflareOptions } = require(+ require.resolve("miniflare", {+ paths: [dirname(require.resolve("wrangler"))],+ }),+);+const [source, destination] = process.argv.slice(2);+if (!source || !destination)+ throw new Error(+ "Usage: node scripts/celld/export-legacy.mjs COPIED_STATE_V3 OUTPUT_DIRECTORY",+ );+const output = resolve(destination);+await mkdir(output, { mode: 0o700 });+const scratch = await mkdtemp(join(tmpdir(), "openseo-export-"));+const manifest = {+ format: 1,+ source: "OpenSEO Miniflare state/v3",+ createdAt: new Date().toISOString(),+ tables: [],+ sam: [],+ artifacts: [],+ omitted: [+ "sessions, API keys, OAuth grants and verification tokens",+ "Google connections (reconnect after import)",+ "provider caches, billing and telemetry state",+ "running workflows, crawl scratchpads and pending SAM turns",+ ],+};+const quote = (name) => `"${name.replaceAll('"', '""')}"`;+const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");+let mf;+try {+ await cp(resolve(source), scratch, { recursive: true });+ // Miniflare 5 (wrangler 4.149+) replaced the options format; the converter+ // accepts the old one. resourcePersistencePath is the state/v3 directory,+ // with d1/, r2/ and do/ beneath it.+ mf = new Miniflare(+ convertV4MiniflareOptions({+ name: "open-seo",+ modules: true,+ compatibilityDate: "2025-09-02",+ script: `import { DurableObject } from 'cloudflare:workers';+ export class SamChatAgent extends DurableObject {+ tables() { return this.ctx.storage.sql.exec("SELECT name FROM sqlite_schema WHERE type='table'").toArray().map(r=>r.name).filter(n=>['assistant_messages','assistant_compactions','assistant_config','assistant_fts'].includes(n)); }+ columns(table) { if(!this.tables().includes(table)) throw new Error('Unknown table'); return this.ctx.storage.sql.exec('PRAGMA table_info("'+table+'")').toArray().map(r=>r.name); }+ rows(table,offset) { if(!this.tables().includes(table)) throw new Error('Unknown table'); return this.ctx.storage.sql.exec('SELECT * FROM "'+table+'" LIMIT 50 OFFSET ?',offset).toArray(); }+ }+ export default { fetch() { return new Response('Offline export reader'); } };`,+ d1Databases: {+ DB: process.env.LEGACY_D1_ID ?? "37bee90a-e1aa-404f-b01e-b0d1d479bda1",+ },+ r2Buckets: { R2: "open-seo" },+ durableObjects: {+ SAM_CHAT: {+ className: "SamChatAgent",+ useSQLite: true,+ unsafeUniqueKey: "open-seo-SamChatAgent",+ },+ },+ resourcePersistencePath: scratch,+ }),+ );+ const db = await mf.getD1Database("DB");+ const all = (+ await db+ .prepare(+ "SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'",+ )+ .all()+ ).results.map((r) => r.name);+ if (!all.includes("projects") || !all.includes("user"))+ throw new Error(+ "OpenSEO database not found. Check state/v3 path and LEGACY_D1_ID.",+ );+ for (const table of ["audits", "rank_check_runs"])+ if (all.includes(table)) {+ const row = await db+ .prepare(+ `SELECT count(*) AS n FROM ${quote(table)} WHERE status IN ('pending','running','queued')`,+ )+ .first();+ if (row.n)+ throw new Error(+ `Finish or cancel active ${table} in the old installation before exporting`,+ );+ }+ const excluded = new Set([+ "session",+ "verification",+ "apikey",+ "rate_limit",+ "d1_migrations",+ "gsc_connections",+ "ga4_connections",+ "billing_customer_status",+ "telemetry_state",+ ]);+ const pending = new Set(all.filter((n) => !excluded.has(n)));+ const ordered = [];+ while (pending.size) {+ let progressed = false;+ for (const table of pending) {+ const deps = (+ await db.prepare(`PRAGMA foreign_key_list(${quote(table)})`).all()+ ).results+ .map((r) => r.table)+ .filter((n) => n !== table);+ if (deps.some((n) => pending.has(n))) continue;+ pending.delete(table);+ ordered.push(table);+ progressed = true;+ }+ if (!progressed)+ throw new Error(+ `Unsupported cyclic database dependencies: ${[...pending].join(", ")}`,+ );+ }+ async function saveRows(collection, descriptor, columns, rows) {+ const serialized = JSON.stringify({+ table: descriptor.table,+ columns,+ rows: rows.map((row) => columns.map((column) => row[column])),+ });+ if (Buffer.byteLength(serialized) > 8 * 1024 * 1024)+ throw new Error("Export batch exceeds 8 MiB; reduce batch size");+ const filename = `rows-${manifest.tables.length + manifest.sam.length}.json`;+ await writeFile(join(output, filename), serialized, { mode: 0o600 });+ collection.push({+ ...descriptor,+ file: filename,+ sha256: sha(serialized),+ count: rows.length,+ });+ }+ for (const table of ordered) {+ const columns = (+ await db.prepare(`PRAGMA table_info(${quote(table)})`).all()+ ).results.map((r) => r.name);+ for (let offset = 0; ; offset += 50) {+ const filter =+ table === "account" ? " WHERE provider_id = 'credential'" : "";+ const rows = (+ await db+ .prepare(`SELECT * FROM ${quote(table)}${filter} LIMIT 50 OFFSET ?`)+ .bind(offset)+ .all()+ ).results;+ if (!rows.length) break;+ await saveRows(manifest.tables, { table }, columns, rows);+ }+ }+ const namespace = await mf.getDurableObjectNamespace("SAM_CHAT");+ if (all.includes("sam_sessions"))+ for (const { id } of (await db.prepare("SELECT id FROM sam_sessions").all())+ .results) {+ const stub = namespace.get(namespace.idFromName(id));+ const tables = await stub.tables();+ for (const table of tables) {+ const columns = await stub.columns(table);+ for (let offset = 0; ; offset += 50) {+ const rows = await stub.rows(table, offset);+ if (!rows.length) break;+ await saveRows(manifest.sam, { table, sessionId: id }, columns, rows);+ }+ }+ }+ const bucket = await mf.getR2Bucket("R2");+ let cursor;+ do {+ const listed = await bucket.list({ cursor });+ for (const item of listed.objects) {+ const object = await bucket.get(item.key);+ if (!object)+ throw new Error("Artifact disappeared from offline snapshot");+ if (object.size > 20 * 1024 * 1024)+ throw new Error(+ `Artifact ${item.key} exceeds the supported 20 MiB import size`,+ );+ const bytes = Buffer.from(await object.arrayBuffer());+ const file = `artifact-${manifest.artifacts.length}.bin`;+ await writeFile(join(output, file), bytes, { mode: 0o600 });+ manifest.artifacts.push({+ key: item.key,+ file,+ sha256: sha(bytes),+ size: bytes.length,+ httpMetadata: object.httpMetadata,+ customMetadata: object.customMetadata,+ });+ }+ cursor = listed.truncated ? listed.cursor : undefined;+ } while (cursor);+ await writeFile(+ join(output, "manifest.json"),+ JSON.stringify(manifest, null, 2) + "\n",+ { mode: 0o600 },+ );+ console.log(+ `Export complete: ${manifest.tables.reduce((n, t) => n + t.count, 0)} database rows, ${manifest.sam.reduce((n, t) => n + t.count, 0)} conversation rows, ${manifest.artifacts.length} artifacts. Review manifest omissions before importing.`,+ );+} finally {+ await mf?.dispose();+ await rm(scratch, { recursive: true, force: true });+}diff --git a/scripts/celld/migrate-legacy.mjs b/scripts/celld/migrate-legacy.mjsnew file mode 100644index 00000000..23e80747--- /dev/null+++ b/scripts/celld/migrate-legacy.mjs@@ -0,0 +1,39 @@+// Runs in the migrate service (deploy/standalone/compose.migrate.yaml): exports+// the old Docker image's Miniflare state, imports it through the operator+// endpoint, and records the result so a repeated start changes nothing.+import { spawnSync } from "node:child_process";+import { readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";++const marker = "/config/legacy-import.json";+const source = "/legacy/state/v3";+const previous = await readFile(marker, "utf8").catch(() => null);+if (previous) {+ console.log(+ `Legacy data was already imported on ${JSON.parse(previous).importedAt}; nothing to do.`,+ );+ process.exit(0);+}+function run(script, ...args) {+ const result = spawnSync(process.execPath, [script, ...args], {+ cwd: "/build",+ stdio: "inherit",+ });+ if (result.status !== 0) process.exit(result.status ?? 1);+}+const output = join(tmpdir(), `openseo-legacy-${process.pid}`);+try {+ run("scripts/celld/export-legacy.mjs", source, output);+ run("scripts/celld/runtime/import.mjs", output);+} finally {+ await rm(output, { recursive: true, force: true });+}+await writeFile(+ marker,+ `${JSON.stringify({ importedAt: new Date().toISOString(), source })}\n`,+ { mode: 0o644 },+);+console.log(+ "Legacy import finished. Reconnect Google in the app; with AUTH_MODE=password, claim the imported admin as described in docs/SELF_HOSTING_DOCKER.md.",+);diff --git a/scripts/celld/package.mjs b/scripts/celld/package.mjsnew file mode 100644index 00000000..c3516e94--- /dev/null+++ b/scripts/celld/package.mjs@@ -0,0 +1,33 @@+import { cp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";+import { resolve } from "node:path";++const destination = resolve(process.argv[2] ?? "dist/celld");+// Build artifacts only. Never copy .dev.vars, generated Wrangler variables,+// node_modules, or operator credentials into a distributable image.+await mkdir(destination, { recursive: true });+await cp("dist/server/index.js", `${destination}/index.js`);+await rm(`${destination}/assets`, { recursive: true, force: true });+await mkdir(`${destination}/assets`, { recursive: true });+for (const name of await readdir("dist/server/assets")) {+ if (name.endsWith(".wasm")) {+ await cp(`dist/server/assets/${name}`, `${destination}/assets/${name}`);+ }+}+await rm(`${destination}/public`, { recursive: true, force: true });+await cp("dist/client", `${destination}/public`, {+ recursive: true,+ filter: (path) =>+ ![".dev.vars", "wrangler.json", ".assetsignore"].includes(+ path.split("/").at(-1),+ ),+});+await cp("drizzle/sqlite", `${destination}/drizzle`, { recursive: true });+const config = JSON.parse(await readFile("wrangler.standalone.json", "utf8"));+config.main = "index.js";+config.no_bundle = true;+config.assets = { directory: "public" };+await writeFile(+ `${destination}/wrangler.json`,+ `${JSON.stringify(config, null, 2)}\n`,+);+console.log(`Packaged standalone application in ${destination}`);diff --git a/scripts/celld/runtime/admin.mjs b/scripts/celld/runtime/admin.mjsnew file mode 100644index 00000000..9d1541ff--- /dev/null+++ b/scripts/celld/runtime/admin.mjs@@ -0,0 +1,61 @@+import { readFile } from "node:fs/promises";+const [command, first, second, third] = process.argv.slice(2);+const email = command === "claim-legacy-user" ? second : first;+const name = command === "create-user" ? second : undefined;+const userId = command === "claim-legacy-user" ? first : undefined;+const organizationId = command === "claim-legacy-user" ? third : undefined;+if (+ !["create-user", "reset-password", "claim-legacy-user"].includes(command) ||+ !email ||+ (command === "create-user" && !name)+) {+ console.error(+ "Usage: admin.mjs create-user EMAIL NAME | reset-password EMAIL | claim-legacy-user USER_ID EMAIL ORGANIZATION_ID\nPass the password on standard input.",+ );+ process.exit(1);+}+let input = "";+for await (const chunk of process.stdin) input += chunk;+const password = input.replace(/\r?\n$/, "");+if (password.length < 8 || password.length > 128)+ throw new Error("Password must contain 8–128 characters");+// Inside the Docker runtime container the secret sits in the config volume+// and the app listens on 8080. A Cloudflare self-hoster runs this script from+// the repository (`pnpm selfhost:admin`) with the secret from .env.selfhost+// and the deployed URL in OPENSEO_URL.+const operatorSecret =+ process.env.OPENSEO_OPERATOR_SECRET ||+ JSON.parse(await readFile("/config/secrets.json", "utf8"))+ .OPENSEO_OPERATOR_SECRET;+const baseUrl = process.env.OPENSEO_URL || "http://127.0.0.1:8080";+const response = await fetch(`${baseUrl}/api/standalone/admin`, {+ method: "POST",+ headers: {+ "content-type": "application/json",+ "x-openseo-operator-secret": operatorSecret,+ },+ body: JSON.stringify({+ command,+ email,+ name,+ password,+ userId,+ organizationId,+ }),+});+const text = await response.text();+const result = (() => {+ try {+ return JSON.parse(text);+ } catch {+ return {};+ }+})();+if (!response.ok) {+ console.error(+ result.error ??+ `${response.status} ${text.trim()} — is OPENSEO_OPERATOR_SECRET set on this deployment?`,+ );+ process.exit(1);+}+console.log(`${command} succeeded for ${result.email}`);diff --git a/scripts/celld/runtime/configure.mjs b/scripts/celld/runtime/configure.mjsnew file mode 100644index 00000000..74ef77c7--- /dev/null+++ b/scripts/celld/runtime/configure.mjs@@ -0,0 +1,74 @@+import { randomBytes } from "node:crypto";+import { cp, mkdir, readFile, writeFile } from "node:fs/promises";++const root = "/config";+await mkdir(root, { recursive: true, mode: 0o700 });+const secretsFile = `${root}/secrets.json`;+let secrets;+try {+ secrets = JSON.parse(await readFile(secretsFile, "utf8"));+} catch (error) {+ if (error.code !== "ENOENT") throw error;+ secrets = Object.fromEntries(+ [+ "BETTER_AUTH_SECRET",+ "OPENSEO_OPERATOR_SECRET",+ "CRAWL_GATEWAY_SECRET",+ ].map((key) => [key, randomBytes(32).toString("hex")]),+ );+ await writeFile(secretsFile, JSON.stringify(secrets), {+ mode: 0o600,+ flag: "wx",+ });+}+// password: email and password accounts (the first visitor creates the+// admin's, invitations add the rest). local_noauth: no sign-in and one admin+// user, as the old Docker image ran (private networks only).+const authMode = process.env.AUTH_MODE || "password";+if (!["password", "local_noauth"].includes(authMode))+ throw new Error("AUTH_MODE must be password or local_noauth");+const url = new URL(process.env.BETTER_AUTH_URL ?? "http://localhost:3001");+if (+ url.protocol !== "https:" &&+ !(+ url.protocol === "http:" &&+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)+ )+) {+ throw new Error("BETTER_AUTH_URL must use HTTPS, except on loopback");+}+if (+ url.pathname !== "/" ||+ url.search ||+ url.hash ||+ url.username ||+ url.password+)+ throw new Error("BETTER_AUTH_URL must be an origin");+await cp("/opt/openseo", `${root}/app`, { recursive: true });+const config = JSON.parse(await readFile(`${root}/app/wrangler.json`, "utf8"));+const allowed = [+ "DATAFORSEO_API_KEY",+ "CONTEXT_API_KEY",+ "OPENROUTER_API_KEY",+ "OPENROUTER_MODEL",+ "GOOGLE_CLIENT_ID",+ "GOOGLE_CLIENT_SECRET",+];+config.vars = {+ ...secrets,+ BETTER_AUTH_URL: url.origin,+ CRAWL_GATEWAY_URL: "http://crawl-gateway:8090",+ AUTH_MODE: authMode,+ DATABASE_PROVIDER: "d1",+ OPENSEO_TELEMETRY_DISABLED: "true",+ DO_NOT_TRACK: "1",+};+for (const key of allowed)+ if (process.env[key]) config.vars[key] = process.env[key];+await writeFile(`${root}/app/wrangler.json`, JSON.stringify(config), {+ mode: 0o600,+});+console.log(+ `Standalone configuration prepared for AUTH_MODE=${authMode} (secret values omitted).`,+);diff --git a/scripts/celld/runtime/crawl-gateway.mjs b/scripts/celld/runtime/crawl-gateway.mjsnew file mode 100644index 00000000..d3914844--- /dev/null+++ b/scripts/celld/runtime/crawl-gateway.mjs@@ -0,0 +1,180 @@+// A DNS-pinned, public-Internet-only transport for user-supplied crawl URLs.+// Resolving then using ordinary fetch would re-resolve and permit DNS rebinding.+import { createServer, request as httpRequest } from "node:http";+import { request as httpsRequest } from "node:https";+import { lookup } from "node:dns/promises";+import { BlockList, isIP } from "node:net";+import { timingSafeEqual } from "node:crypto";+import { readFile } from "node:fs/promises";+import { pathToFileURL } from "node:url";++const blocked = new BlockList();+for (const [address, prefix] of [+ ["0.0.0.0", 8],+ ["10.0.0.0", 8],+ ["100.64.0.0", 10],+ ["127.0.0.0", 8],+ ["169.254.0.0", 16],+ ["172.16.0.0", 12],+ ["192.0.0.0", 24],+ ["192.0.2.0", 24],+ ["192.168.0.0", 16],+ ["198.18.0.0", 15],+ ["198.51.100.0", 24],+ ["203.0.113.0", 24],+ ["224.0.0.0", 3],+])+ blocked.addSubnet(address, prefix, "ipv4");+for (const [address, prefix] of [+ ["::", 96],+ ["64:ff9b::", 96],+ ["64:ff9b:1::", 48],+ ["100::", 64],+ ["2001::", 23],+ ["2001:db8::", 32],+ ["2002::", 16],+ ["fc00::", 7],+ ["fe80::", 10],+ ["fec0::", 10],+ ["ff00::", 8],+])+ blocked.addSubnet(address, prefix, "ipv6");+export function isPublicAddress(address) {+ const family = isIP(address);+ return (+ family !== 0 && !blocked.check(address, family === 4 ? "ipv4" : "ipv6")+ );+}+export async function resolveTarget(value, resolver = lookup) {+ const url = new URL(value);+ if (+ !["http:", "https:"].includes(url.protocol) ||+ url.username ||+ url.password ||+ (url.port && !["80", "443"].includes(url.port))+ )+ throw new Error("Only public HTTP and HTTPS targets are allowed");+ const hostname = url.hostname.replace(/^\[|\]$/g, "");+ const addresses = isIP(hostname)+ ? [{ address: hostname, family: isIP(hostname) }]+ : await resolver(hostname, { all: true, verbatim: true });+ if (+ !addresses.length ||+ addresses.some(({ address }) => !isPublicAddress(address))+ )+ throw new Error("Target resolves to a non-public address");+ return { url, address: addresses[0] };+}+// Forward only crawler headers. Never leak gateway credentials, cookies, or+// authorization headers to the target. Caller matches signatures to each host.+export function upstreamHeaders(incoming, url) {+ const headers = {+ "user-agent": incoming["user-agent"] ?? "OpenSEO-Audit/1.0",+ accept: incoming.accept ?? "*/*",+ "accept-encoding": "identity",+ };+ if (url.protocol === "https:") {+ for (const name of ["signature", "signature-input", "signature-agent"])+ if (incoming[name]) headers[name] = incoming[name];+ }+ return headers;+}++export function createGateway(secret) {+ if (typeof secret !== "string" || secret.length < 32)+ throw new Error("Missing gateway secret");+ let active = 0;+ return createServer(async (incoming, response) => {+ const supplied = Buffer.from(+ String(incoming.headers["x-crawl-secret"] ?? ""),+ );+ const expected = Buffer.from(secret);+ if (+ supplied.length !== expected.length ||+ !timingSafeEqual(supplied, expected)+ ) {+ response.writeHead(404).end();+ return;+ }+ if (!["GET", "HEAD"].includes(incoming.method)) {+ response.writeHead(405).end();+ return;+ }+ if (active >= 64) {+ response.writeHead(503, { "retry-after": "1" }).end();+ return;+ }+ active++;+ let released = false;+ const release = () => {+ if (!released) {+ released = true;+ active--;+ }+ };+ response.once("close", release);+ try {+ const { url, address } = await resolveTarget(+ incoming.headers["x-crawl-url"],+ );+ const upstream = (url.protocol === "https:" ? httpsRequest : httpRequest)(+ url,+ {+ method: incoming.method,+ agent: false,+ autoSelectFamily: false,+ lookup: (_hostname, _options, callback) =>+ callback(null, address.address, address.family),+ headers: upstreamHeaders(incoming.headers, url),+ signal: AbortSignal.timeout(30_000),+ },+ (result) => {+ const headers = {};+ for (const key of [+ "content-type",+ "content-length",+ "content-encoding",+ "location",+ "last-modified",+ "etag",+ "retry-after",+ "link",+ "x-robots-tag",+ "cf-mitigated",+ "powered-by",+ ])+ if (result.headers[key]) headers[key] = result.headers[key];+ response.writeHead(result.statusCode ?? 502, headers);+ let bytes = 0;+ result.on("data", (chunk) => {+ bytes += chunk.length;+ if (bytes > 20 * 1024 * 1024) {+ result.destroy();+ response.destroy();+ }+ });+ result.on("error", () => response.destroy());+ result.pipe(response);+ },+ );+ response.once("close", () => upstream.destroy());+ upstream.on("error", () => {+ if (!response.headersSent)+ response.writeHead(502).end("Crawl fetch failed");+ else response.destroy();+ });+ upstream.end();+ } catch {+ response.writeHead(403).end("Crawl target is not allowed");+ }+ });+}+if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ const { CRAWL_GATEWAY_SECRET } = JSON.parse(+ await readFile("/config/secrets.json", "utf8"),+ );+ createGateway(CRAWL_GATEWAY_SECRET).listen(8090, "0.0.0.0");+}diff --git a/scripts/celld/runtime/crawl-gateway.test.mjs b/scripts/celld/runtime/crawl-gateway.test.mjsnew file mode 100644index 00000000..cd93df50--- /dev/null+++ b/scripts/celld/runtime/crawl-gateway.test.mjs@@ -0,0 +1,89 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import {+ isPublicAddress,+ resolveTarget,+ createGateway,+ upstreamHeaders,+} from "./crawl-gateway.mjs";+test("blocks loopback, private, metadata, mapped IPv4 and special ranges", () => {+ for (const address of [+ "127.0.0.1",+ "10.0.0.1",+ "169.254.169.254",+ "172.16.0.1",+ "192.168.1.1",+ "100.64.0.1",+ "::1",+ "::ffff:127.0.0.1",+ "::ffff:a00:1",+ "fc00::1",+ "fe80::1",+ "64:ff9b::a00:1",+ "2002:7f00:1::",+ ])+ assert.equal(isPublicAddress(address), false, address);+ for (const address of ["1.1.1.1", "8.8.8.8", "2606:4700:4700::1111"])+ assert.equal(isPublicAddress(address), true, address);+});+test("fails closed on mixed DNS answers and pins the validated answer", async () => {+ await assert.rejects(+ resolveTarget("https://example.com", async () => [+ { address: "1.1.1.1", family: 4 },+ { address: "127.0.0.1", family: 4 },+ ]),+ );+ const target = await resolveTarget("https://example.com", async () => [+ { address: "1.1.1.1", family: 4 },+ ]);+ assert.deepEqual(target.address, { address: "1.1.1.1", family: 4 });+ for (const url of [+ "http://127.1",+ "http://2130706433",+ "http://[::ffff:7f00:1]",+ "http://example.com:9000",+ "file:///etc/passwd",+ "http://user:[email protected]",+ ])+ await assert.rejects(resolveTarget(url));+});+test("requires credentials and rejects localhost without contacting it", async () => {+ const secret = "a".repeat(64);+ const server = createGateway(secret).listen(0, "127.0.0.1");+ await new Promise((resolve) => server.once("listening", resolve));+ try {+ const base = `http://127.0.0.1:${server.address().port}`;+ assert.equal((await fetch(base)).status, 404);+ assert.equal(+ (+ await fetch(base, {+ headers: {+ "x-crawl-secret": secret,+ "x-crawl-url": "http://127.0.0.1:9000",+ },+ })+ ).status,+ 403,+ );+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+});++test("forwards HTTPS crawler signatures without leaking application credentials", () => {+ const headers = {+ signature: "sig1=:test:",+ "signature-input": "sig1=()",+ "signature-agent": '\"https://shopify.com\"',+ "x-crawl-secret": "gateway-secret",+ authorization: "Bearer app-token",+ cookie: "app-session",+ };+ const https = upstreamHeaders(headers, new URL("https://store.example"));+ assert.equal(https.signature, headers.signature);+ for (const name of ["x-crawl-secret", "authorization", "cookie"])+ assert.equal(https[name], undefined);+ const http = upstreamHeaders(headers, new URL("http://store.example"));+ for (const name of ["signature", "signature-input", "signature-agent"])+ assert.equal(http[name], undefined);+});diff --git a/scripts/celld/runtime/import.mjs b/scripts/celld/runtime/import.mjsnew file mode 100644index 00000000..b608feb5--- /dev/null+++ b/scripts/celld/runtime/import.mjs@@ -0,0 +1,100 @@+import { readFile } from "node:fs/promises";+import { createHash } from "node:crypto";+import { join, resolve, basename } from "node:path";+const directory = resolve(process.argv[2] ?? "/import");+const manifestBytes = await readFile(join(directory, "manifest.json"));+const manifest = JSON.parse(manifestBytes);+if (manifest.format !== 1) throw new Error("Unsupported import format");+const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");+const entries = [...manifest.tables, ...manifest.sam, ...manifest.artifacts];+for (const entry of entries) {+ if (basename(entry.file) !== entry.file)+ throw new Error("Invalid export filename");+ if (sha(await readFile(join(directory, entry.file))) !== entry.sha256)+ throw new Error(`Export checksum mismatch: ${entry.file}`);+}+const { OPENSEO_OPERATOR_SECRET } = JSON.parse(+ await readFile("/config/secrets.json", "utf8"),+);+const headers = {+ "content-type": "application/json",+ "x-openseo-operator-secret": OPENSEO_OPERATOR_SECRET,+};+const endpoint = "http://127.0.0.1:8080/api/standalone/import";+async function command(body) {+ const response = await fetch(endpoint, {+ method: "POST",+ headers,+ body: JSON.stringify(body),+ });+ if (!response.ok)+ throw new Error(+ `Import ${body.command} failed (${response.status}): ${await response.text()}`,+ );+ return response.json();+}+await command({ command: "begin", manifestHash: sha(manifestBytes) });+for (const entry of manifest.tables)+ await command({+ command: "rows",+ ...JSON.parse(await readFile(join(directory, entry.file), "utf8")),+ });+for (const entry of manifest.sam)+ await command({+ command: "sam",+ sessionId: entry.sessionId,+ ...JSON.parse(await readFile(join(directory, entry.file), "utf8")),+ });+for (const entry of manifest.artifacts) {+ const response = await fetch(`${endpoint}?artifact=1`, {+ method: "POST",+ headers: {+ "x-openseo-operator-secret": OPENSEO_OPERATOR_SECRET,+ "x-artifact-sha256": entry.sha256,+ "x-artifact-key": encodeURIComponent(entry.key),+ "x-artifact-metadata": JSON.stringify({+ httpMetadata: entry.httpMetadata,+ customMetadata: entry.customMetadata,+ }),+ },+ body: await readFile(join(directory, entry.file)),+ });+ if (!response.ok)+ throw new Error(`Artifact import failed (${response.status})`);+}+const counts = await command({ command: "counts" });+const expected = {};+for (const entry of manifest.tables)+ expected[entry.table] = (expected[entry.table] ?? 0) + entry.count;+for (const [table, count] of Object.entries(expected))+ if (counts[table] !== count)+ throw new Error(+ `Count mismatch for ${table}: expected ${count}, found ${counts[table]}`,+ );+const conversations = {};+for (const entry of manifest.sam) {+ const tables = (conversations[entry.sessionId] ??= {});+ tables[entry.table] = (tables[entry.table] ?? 0) + entry.count;+}+for (const [sessionId, tables] of Object.entries(conversations)) {+ const actual = await command({ command: "sam-counts", sessionId });+ for (const [table, count] of Object.entries(tables))+ if (actual[table] !== count)+ throw new Error(`Conversation count mismatch: ${sessionId}/${table}`);+}+await command({ command: "finish" });+console.log(+ JSON.stringify(+ {+ databaseRows: expected,+ conversationRows: manifest.sam.reduce((n, t) => n + t.count, 0),+ artifacts: manifest.artifacts.length,+ omitted: manifest.omitted,+ },+ null,+ 2,+ ),+);+console.log(+ "Import complete. Restart runtime to load conversation histories, then reset the imported account password. Reconnect Google and MCP clients.",+);diff --git a/scripts/selfhost-deploy-preflight.mjs b/scripts/selfhost-deploy-preflight.mjsindex 0f32165b..c13993c3 100644--- a/scripts/selfhost-deploy-preflight.mjs+++ b/scripts/selfhost-deploy-preflight.mjs@@ -35,7 +35,7 @@ if (!existsSync(envFile)) {"",` ${cmd("cp deploy/.env.selfhost.example .env.selfhost")}`,"",- `then set ${em("DATAFORSEO_API_KEY")} and ${em("ACCESS_ALLOWED_EMAILS")}.`,+ `then set ${em("DATAFORSEO_API_KEY")}.`,);}const env = {};@@ -48,10 +48,21 @@ if (!env.DATAFORSEO_API_KEY) {`${em("DATAFORSEO_API_KEY")} is not set in ${envFile} — see docs/DATAFORSEO_API_KEY.md for how to get one.`,);}-// When both are set, the deploy provisions no Access resources (hand-managed-// application) and needs neither ACCESS_ALLOWED_EMAILS nor the access:write-// login scope.-const managedAccess = !(env.TEAM_DOMAIN && env.POLICY_AUD);+// Mirrors the stack's default (deploy/alchemy/alchemy.run.ts): an unset+// AUTH_MODE is the Access-gated mode. A typo would deploy that mode without+// its Access application, so reject it here.+const AUTH_MODES = ["cloudflare_access", "local_noauth", "hosted", "password"];+const authMode = env.AUTH_MODE || "cloudflare_access";+if (!AUTH_MODES.includes(authMode)) {+ fail(+ `${em("AUTH_MODE")}=${authMode} in ${envFile} is not one of ${AUTH_MODES.join(", ")}.`,+ );+}+// Only the Access-gated mode provisions Access resources, and not when both+// TEAM_DOMAIN and POLICY_AUD name a hand-managed application. Nothing else+// needs ACCESS_ALLOWED_EMAILS or the access:write login scope.+const managedAccess =+ authMode === "cloudflare_access" && !(env.TEAM_DOMAIN && env.POLICY_AUD);if (managedAccess && !env.ACCESS_ALLOWED_EMAILS) {fail(`${em("ACCESS_ALLOWED_EMAILS")} is not set in ${envFile} — list who may sign in through`,@@ -73,8 +84,10 @@ if (!process.env.CLOUDFLARE_API_TOKEN) {}if (!cloudflare) {fail(- `No Cloudflare login found (alchemy profile "${profileName}") — run ${cmd("pnpm alchemy login")}`,- `first (answer yes to "Customize OAuth scopes?" and enable ${em("access:write")}).`,+ `No Cloudflare login found (alchemy profile "${profileName}") — run ${cmd("pnpm alchemy login")} first`,+ managedAccess+ ? `(answer yes to "Customize OAuth scopes?" and enable ${em("access:write")}).`+ : "(the default scopes are enough).",);}if (diff --git a/src/client/components/AuthErrorCard.tsx b/src/client/components/AuthErrorCard.tsxindex 19bf3e68..6c41b069 100644--- a/src/client/components/AuthErrorCard.tsx+++ b/src/client/components/AuthErrorCard.tsx@@ -13,7 +13,7 @@ import {CardHeader,CardTitle,} from "@/client/components/ui/card";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { getClientAuthMode, usesBetterAuthClient } from "@/lib/auth-mode";import { getSignInHref, getSignInHrefForLocation } from "@/lib/auth-redirect";const CLOUDFLARE_SETUP_GUIDE_URL =@@ -59,10 +59,9 @@ export function AuthErrorCard({}function AuthConfigErrorCard({ message, onRetry }: CardProps) {- // Only name a mode's settings when the client build names that mode. With- // AUTH_MODE unset here the server mode is unknown, and the alert above- // already carries the server's exact message.- const clientAuthMode = import.meta.env.AUTH_MODE;+ // The hint names the settings of the mode the server actually runs; the+ // alert above already carries the server's exact message.+ const clientAuthMode = getClientAuthMode();return (<Card className="w-full max-w-2xl">@@ -116,21 +115,22 @@ function AuthConfigErrorCard({ message, onRetry }: CardProps) {}function UnauthenticatedErrorCard({ message, onRetry }: CardProps) {- const isHostedMode = isHostedClientAuthMode();+ // A sign-in page exists wherever Better Auth accounts do.+ const hasSignIn = usesBetterAuthClient();const signInHref =typeof window === "undefined"? getSignInHref("/"): getSignInHrefForLocation(window.location);useEffect(() => {- if (typeof window === "undefined" || !isHostedMode) {+ if (typeof window === "undefined" || !hasSignIn) {return;}window.location.replace(signInHref);- }, [isHostedMode, signInHref]);+ }, [hasSignIn, signInHref]);- if (isHostedMode) {+ if (hasSignIn) {return null;}diff --git a/src/client/features/auth/AuthPage.tsx b/src/client/features/auth/AuthPage.tsxindex 3d746193..632e3041 100644--- a/src/client/features/auth/AuthPage.tsx+++ b/src/client/features/auth/AuthPage.tsx@@ -4,7 +4,7 @@ import {getCurrentAuthRedirect,getOAuthSignedQuery,} from "@/lib/auth-redirect";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { isHostedClientAuthMode, usesBetterAuthClient } from "@/lib/auth-mode";import { PRIVACY_URL, TERMS_URL } from "@/shared/terms";export const authRedirectSearchSchema = z.object({@@ -25,11 +25,15 @@ export function useAuthPageState(redirect: string | undefined) {? getOAuthSignedQuery(window.location.search): null;const isHostedMode = isHostedClientAuthMode();+ // Better Auth accounts exist (hosted or the standalone Docker edition), so+ // the email/password form can sign someone in.+ const isBetterAuthMode = usesBetterAuthClient();return {redirectTo,oauthQuery,isHostedMode,+ isBetterAuthMode,};}diff --git a/src/client/features/auth/signUpStatus.ts b/src/client/features/auth/signUpStatus.tsnew file mode 100644index 00000000..11030077--- /dev/null+++ b/src/client/features/auth/signUpStatus.ts@@ -0,0 +1,21 @@+import { queryOptions } from "@tanstack/react-query";+import { z } from "zod";++const signUpStatusSchema = z.object({ firstAccount: z.boolean() });++// Whether this standalone installation still has no account, so the auth+// pages can offer to create the administrator's+// (src/routes/api/sign-up-status.ts).+export const signUpStatusQueryOptions = () =>+ queryOptions({+ queryKey: ["sign-up-status"],+ queryFn: async () => {+ const response = await fetch("/api/sign-up-status");+ if (!response.ok) throw new Error(`sign-up status: ${response.status}`);+ return signUpStatusSchema.parse(await response.json());+ },+ // Fresh on every mount (the answer flips once the account exists), but+ // not behind the user's back while a form is on screen.+ staleTime: 0,+ refetchOnWindowFocus: false,+ });diff --git a/src/client/features/auth/useHostedAuthRouteGuard.ts b/src/client/features/auth/useHostedAuthRouteGuard.tsindex a203ad77..f5c34399 100644--- a/src/client/features/auth/useHostedAuthRouteGuard.ts+++ b/src/client/features/auth/useHostedAuthRouteGuard.ts@@ -4,6 +4,7 @@ import { useSession } from "@/lib/auth-client";import {isEmailVerificationBypassed,isHostedClientAuthMode,+ usesBetterAuthClient,} from "@/lib/auth-mode";import {getCurrentAuthRedirectFromHref,@@ -14,12 +15,16 @@ import {export function useHostedAuthRouteGuard() {const navigate = useNavigate();const { data: session, isPending } = useSession();+ // The session guard runs wherever Better Auth accounts exist (hosted and the+ // standalone Docker edition); isHostedMode is kept for callers that gate+ // hosted-only surfaces such as billing.const isHostedMode = isHostedClientAuthMode();+ const hasAccounts = usesBetterAuthClient();const emailVerified =session?.user?.emailVerified === true || isEmailVerificationBypassed();useEffect(() => {- if (isPending || !isHostedMode) {+ if (isPending || !hasAccounts) {return;}@@ -43,18 +48,18 @@ export function useHostedAuthRouteGuard() {}}, [isPending,- isHostedMode,+ hasAccounts,emailVerified,session?.user?.email,session?.user?.id,navigate,]);- const hasVerifiedHostedSession =+ const hasVerifiedSession =!isPending && Boolean(session?.user?.id) && emailVerified;return {isHostedMode,- canRenderAuthenticatedContent: !isHostedMode || hasVerifiedHostedSession,+ canRenderAuthenticatedContent: !hasAccounts || hasVerifiedSession,};}diff --git a/src/client/features/dashboard/DashboardOnboarding.tsx b/src/client/features/dashboard/DashboardOnboarding.tsxindex d91542c8..af748956 100644--- a/src/client/features/dashboard/DashboardOnboarding.tsx+++ b/src/client/features/dashboard/DashboardOnboarding.tsx@@ -1,7 +1,7 @@import { useState } from "react";import { useMutation, useQueryClient } from "@tanstack/react-query";import { Check, ChevronRight, RotateCcw } from "lucide-react";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";import { captureClientEvent } from "@/client/lib/posthog";import { setDashboardStepDismissed } from "@/serverFunctions/dashboard";import type { DashboardActivation } from "@/server/features/dashboard/services/DashboardService";@@ -47,7 +47,7 @@ export function DashboardOnboarding({},});const steps = setupSteps.filter(- (step) => step.id !== "team" || isHostedClientAuthMode(),+ (step) => step.id !== "team" || usesBetterAuthClient(),);const remaining = steps.filter((step) => getStepStatus(activation, step.id) === "todo",diff --git a/src/client/features/dashboard/DashboardPage.tsx b/src/client/features/dashboard/DashboardPage.tsxindex d35b3569..91ff611c 100644--- a/src/client/features/dashboard/DashboardPage.tsx+++ b/src/client/features/dashboard/DashboardPage.tsx@@ -32,7 +32,7 @@ import {getDashboardOverview,} from "@/serverFunctions/dashboard";import { Skeleton } from "@/client/components/ui/skeleton";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";export function DashboardPage({projectId,@@ -184,7 +184,7 @@ export function DashboardPage({</Button></div>- {isHostedClientAuthMode() &&+ {usesBetterAuthClient() &&getStepStatus(activation, "mcp") === "todo" ? (<DashboardAgentCard projectId={projectId} />) : null}diff --git a/src/client/features/dashboard/WorkspaceMergeBanner.tsx b/src/client/features/dashboard/WorkspaceMergeBanner.tsxindex 32579e80..b95daa23 100644--- a/src/client/features/dashboard/WorkspaceMergeBanner.tsx+++ b/src/client/features/dashboard/WorkspaceMergeBanner.tsx@@ -2,7 +2,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";import { Alert, AlertDescription } from "@/client/components/ui/alert";import { Button } from "@/client/components/ui/button";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";import {getWorkspaceMergeStatus,mergeLegacyWorkspaces,@@ -18,7 +18,7 @@ export function WorkspaceMergeBanner() {const statusQuery = useQuery({queryKey: ["workspaceMergeStatus"],queryFn: () => getWorkspaceMergeStatus(),- enabled: !isHostedClientAuthMode(),+ enabled: !usesBetterAuthClient(),});const mergeMutation = useMutation({diff --git a/src/client/features/team/InviteTeammateModal.tsx b/src/client/features/team/InviteTeammateModal.tsxindex 44438dd1..b03eb174 100644--- a/src/client/features/team/InviteTeammateModal.tsx+++ b/src/client/features/team/InviteTeammateModal.tsx@@ -14,6 +14,7 @@ import {} from "@/client/components/ui/dialog";import { getErrorCode } from "@/client/lib/error-messages";import { captureClientEvent } from "@/client/lib/posthog";+import { isHostedClientAuthMode, usesBetterAuthClient } from "@/lib/auth-mode";import { sendTeamInvitation } from "@/serverFunctions/organization";const inviteSchema = z.object({@@ -31,6 +32,29 @@ export function inviteErrorMessage(error: Error) {return "We couldn't send that invitation.";}+// Without an email transport (the standalone Docker edition) the server hands+// back the invitation link for the inviter to pass on; with one, it was sent.+export function announceInvitation(+ result: { invitationId: string; inviteUrl?: string },+ sentMessage: string,+) {+ if (!result.inviteUrl) {+ toast.success(sentMessage);+ return;+ }+ const inviteUrl = result.inviteUrl;+ void (+ navigator.clipboard?.writeText(inviteUrl) ?? Promise.reject(new Error())+ ).then(+ () => toast.success("Invitation link copied"),+ () =>+ toast.success("Invitation link", {+ description: inviteUrl,+ duration: 20000,+ }),+ );+}+export function InviteTeammateModal({onClose,onInvited,@@ -43,9 +67,9 @@ export function InviteTeammateModal({const inviteMutation = useMutation({mutationFn: (inviteeEmail: string) =>sendTeamInvitation({ data: { email: inviteeEmail } }),- onSuccess: () => {+ onSuccess: (result) => {captureClientEvent("team:invitation_send");- toast.success("Invitation sent");+ announceInvitation(result, "Invitation sent");onInvited();onClose();},@@ -62,6 +86,8 @@ export function InviteTeammateModal({},});+ const sharesLink = usesBetterAuthClient() && !isHostedClientAuthMode();+const form = useAppForm({defaultValues: { email: "" },validationLogic: revalidateLogic(),@@ -82,8 +108,9 @@ export function InviteTeammateModal({<DialogHeader><DialogTitle>Invite a teammate</DialogTitle><DialogDescription>- They’ll join as an Admin with full access to each project- except for billing. The invitation link expires in 7 days.+ {sharesLink+ ? "They'll join as an Admin with full access to each project. Share the invitation link with them; they create their account from it. It expires in 7 days."+ : "They'll join as an Admin with full access to each project except for billing. The invitation link expires in 7 days."}</DialogDescription></DialogHeader><form.AppField name="email">diff --git a/src/client/features/team/TeamSettings.tsx b/src/client/features/team/TeamSettings.tsxindex 3e0a00f2..e487df84 100644--- a/src/client/features/team/TeamSettings.tsx+++ b/src/client/features/team/TeamSettings.tsx@@ -21,6 +21,7 @@ import {} from "@/client/components/ui/table";import {InviteTeammateModal,+ announceInvitation,inviteErrorMessage,} from "@/client/features/team/InviteTeammateModal";import { organizationContextQueryOptions } from "@/client/features/team/organizationQueries";@@ -73,9 +74,9 @@ export function TeamSettings() {const resendMutation = useMutation({mutationKey: RESEND_KEY,mutationFn: (email: string) => sendTeamInvitation({ data: { email } }),- onSuccess: () => {+ onSuccess: (result) => {captureClientEvent("team:invitation_resend");- toast.success("Invitation resent");+ announceInvitation(result, "Invitation resent");void refreshTeam();},onError: (error: Error) => {diff --git a/src/client/layout/AppShell.tsx b/src/client/layout/AppShell.tsxindex 6d616dbe..af3d005b 100644--- a/src/client/layout/AppShell.tsx+++ b/src/client/layout/AppShell.tsx@@ -3,6 +3,7 @@ import { projectsQueryOptions } from "@/client/features/projects/projectQueries"import { Link, useLocation } from "@tanstack/react-router";import { useQuery } from "@tanstack/react-query";import {+ LegacyDockerBanner,MissingSeoSetupModal,SeoApiStatusBanners,} from "@/client/layout/AppShellParts";@@ -117,6 +118,7 @@ export function AuthenticatedAppLayout({shouldShowSeoApiWarning={shouldShowSeoApiWarning}seoApiKeyStatusError={seoApiKeyStatusError}/>+ <LegacyDockerBanner />{banner}<div className="min-h-0 flex-1 overflow-auto">{children}</div></SidebarInset>diff --git a/src/client/layout/AppShellParts.tsx b/src/client/layout/AppShellParts.tsxindex 7bea9a7b..a6fa8701 100644--- a/src/client/layout/AppShellParts.tsx+++ b/src/client/layout/AppShellParts.tsx@@ -1,5 +1,6 @@import { Link } from "@tanstack/react-router";-import { AlertTriangle, ExternalLink } from "lucide-react";+import { useState } from "react";+import { AlertTriangle, ExternalLink, Info } from "lucide-react";import { AppBanner } from "@/client/layout/AppBanner";import { dataforseoHelpLinkOptions } from "@/client/navigation/items";import { Button } from "@/client/components/ui/button";@@ -47,6 +48,46 @@ function SeoApiStatusBanners({);}+const DOCKER_MOVE_URL =+ "https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_DOCKER.md#move-from-the-old-docker-image";+const DOCKER_MOVE_DISMISSED_KEY = "openseo:docker-move-dismissed";++// The old single-container Docker image builds the app at startup with this+// flag set (deploy/docker/Dockerfile), so only its users see the notice.+function LegacyDockerBanner() {+ const [dismissed, setDismissed] = useState(+ () => localStorage.getItem(DOCKER_MOVE_DISMISSED_KEY) === "1",+ );+ if (import.meta.env.VITE_OPENSEO_LEGACY_DOCKER !== "true" || dismissed) {+ return null;+ }+ return (+ <AppBanner variant="info" icon={<Info className="size-4 shrink-0" />}>+ A new OpenSEO Docker setup starts in seconds and supports accounts. This+ image keeps getting updates, and moving keeps your data.{" "}+ <a+ href={DOCKER_MOVE_URL}+ target="_blank"+ rel="noreferrer"+ className="font-medium text-primary underline-offset-4 hover:underline"+ >+ How to move+ </a>{" "}+ ·{" "}+ <button+ type="button"+ className="font-medium text-primary underline-offset-4 hover:underline"+ onClick={() => {+ localStorage.setItem(DOCKER_MOVE_DISMISSED_KEY, "1");+ setDismissed(true);+ }}+ >+ Dismiss+ </button>+ </AppBanner>+ );+}+function MissingSeoSetupModal({ onClose }: { onClose: () => void }) {return (<Dialog open onOpenChange={(open) => !open && onClose()}>@@ -79,4 +120,4 @@ function MissingSeoSetupModal({ onClose }: { onClose: () => void }) {);}-export { MissingSeoSetupModal, SeoApiStatusBanners };+export { LegacyDockerBanner, MissingSeoSetupModal, SeoApiStatusBanners };diff --git a/src/db/d1/client.test.ts b/src/db/d1/client.test.tsnew file mode 100644index 00000000..957052c7--- /dev/null+++ b/src/db/d1/client.test.ts@@ -0,0 +1,42 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { sql } from "drizzle-orm";++const { env } = vi.hoisted(() => ({ env: {} as Record<string, unknown> }));+vi.mock("cloudflare:workers", () => ({ env }));++import { d1Db } from "./client";++function database() {+ const run = vi.fn(async () => ({ success: true }));+ const prepare = vi.fn(() => ({ bind: () => ({ run }), run }));+ return { prepare, run };+}++afterEach(() => {+ delete env.DB;+});++describe("D1 invocation bindings", () => {+ it("can import before bindings exist, but fails clearly if a query has no binding", () => {+ expect(() => d1Db.select()).toThrow("The D1 binding DB is unavailable");+ });++ it("uses the binding installed after module evaluation", async () => {+ const binding = database();+ env.DB = binding;+ await d1Db.run(sql`SELECT 1`);+ expect(binding.prepare).toHaveBeenCalledWith("SELECT 1");+ expect(binding.run).toHaveBeenCalledOnce();+ });++ it("does not retain another invocation's replaced binding", async () => {+ const first = database();+ const second = database();+ env.DB = first;+ await d1Db.run(sql`SELECT 1`);+ env.DB = second;+ await d1Db.run(sql`SELECT 2`);+ expect(first.prepare).toHaveBeenCalledTimes(1);+ expect(second.prepare).toHaveBeenCalledWith("SELECT 2");+ });+});diff --git a/src/db/d1/client.ts b/src/db/d1/client.tsindex 891e3ff2..79d19e9a 100644--- a/src/db/d1/client.ts+++ b/src/db/d1/client.ts@@ -2,4 +2,29 @@ import { env } from "cloudflare:workers";import { drizzle } from "drizzle-orm/d1";import * as schema from "./schema";-export const d1Db = drizzle(env.DB, { schema });+function createDatabase(binding: D1Database) {+ return drizzle(binding, { schema });+}++let binding: D1Database | undefined;+let database: ReturnType<typeof createDatabase> | undefined;++// celld installs bindings when an invocation starts, after evaluating the+// module. Never capture env.DB while the bundle is being initialized.+function getDatabase() {+ if (!env.DB) throw new Error("The D1 binding DB is unavailable");+ if (!database || binding !== env.DB) {+ binding = env.DB;+ database = createDatabase(binding);+ }+ return database;+}++// Match the lazy database handle already used by the Postgres adapter.+// oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the proxy delegates every access to the typed Drizzle instance+export const d1Db = new Proxy({} as ReturnType<typeof createDatabase>, {+ get(_target, property) {+ const value: unknown = Reflect.get(getDatabase(), property);+ return value;+ },+});diff --git a/src/db/runBatch.ts b/src/db/runBatch.tsindex 3c197792..5d182bc1 100644--- a/src/db/runBatch.ts+++ b/src/db/runBatch.ts@@ -1,3 +1,4 @@+import { env } from "cloudflare:workers";import { getDatabaseProvider } from "./provider";import { d1Db } from "./d1/client";import { pgDb } from "./pg/client";@@ -64,3 +65,16 @@ export async function executeInBatches<T>(await runBatch((tx) => chunk.map((item) => buildStatement(tx, item)));}}++/**+ * The standalone Docker edition's legacy import writes prepared D1 SQL rather+ * than Drizzle statements (its raw SQL builder cannot be batched with bound+ * values in 0.45.2). It lives here because every batch goes through this+ * module, which schema-parity.test.ts enforces.+ */+export async function runD1ImportBatch(statements: D1PreparedStatement[]) {+ if (getDatabaseProvider() !== "d1") {+ throw new Error("Legacy Docker import requires SQLite");+ }+ if (statements.length) await env.DB.batch(statements);+}diff --git a/src/env.d.ts b/src/env.d.tsindex 0c6af286..a9ce1491 100644--- a/src/env.d.ts+++ b/src/env.d.ts@@ -28,7 +28,7 @@ declare namespace Cloudflare {// oxlint-disable-next-line typescript-eslint/consistent-type-importsAUDIT_ENGINE: Service<typeof import("./audit-worker").default>;- AUTH_MODE?: "cloudflare_access" | "local_noauth" | "hosted";+ AUTH_MODE?: "cloudflare_access" | "local_noauth" | "hosted" | "password";BYPASS_EMAIL_VERIFICATION?: string;TEAM_DOMAIN?: string;POLICY_AUD?: string;@@ -103,7 +103,11 @@ declare namespace Cloudflare {}interface ImportMetaEnv {- readonly AUTH_MODE?: "cloudflare_access" | "local_noauth" | "hosted";+ readonly AUTH_MODE?:+ | "cloudflare_access"+ | "local_noauth"+ | "hosted"+ | "password";readonly DATABASE_PROVIDER?: "d1" | "postgres";readonly BYPASS_EMAIL_VERIFICATION?: string;readonly POSTHOG_PUBLIC_KEY?: string;@@ -111,6 +115,7 @@ interface ImportMetaEnv {readonly TURNSTILE_SITE_KEY?: string;readonly VITE_E2E_DOMAIN_FIXTURES?: string;readonly VITE_E2E_KEYWORD_FIXTURES?: string;+ readonly VITE_OPENSEO_LEGACY_DOCKER?: string;}interface ImportMeta {diff --git a/src/lib/auth-config.ts b/src/lib/auth-config.tsindex 6565c190..c372cdec 100644--- a/src/lib/auth-config.ts+++ b/src/lib/auth-config.ts@@ -16,8 +16,10 @@ export function createBaseAuthConfig(options?: {// On Cloudflare Workers the client IP arrives in CF-Connecting-IP;// x-forwarded-for (better-auth's default) is absent, so without this// getIp() returns null and rate limiting is silently skipped on every- // /api/auth endpoint. Header lookup is case-insensitive.- ipAddressHeaders: ["cf-connecting-ip"],+ // /api/auth endpoint. Header lookup is case-insensitive. The+ // standalone Docker edition's Nginx strips CF-Connecting-IP and sets+ // X-Real-IP instead (deploy/standalone/nginx.conf).+ ipAddressHeaders: ["cf-connecting-ip", "x-real-ip"],},// Better Auth writes the OAuth state verification row with a 10-minute// expiry but sets the matching signed cookie with maxAge 300, and checksdiff --git a/src/lib/auth-mode.test.ts b/src/lib/auth-mode.test.tsnew file mode 100644index 00000000..aa9c2baa--- /dev/null+++ b/src/lib/auth-mode.test.ts@@ -0,0 +1,14 @@+import { afterEach, expect, test, vi } from "vitest";+import { getClientAuthMode, setRuntimeAuthMode } from "./auth-mode";++afterEach(() => {+ setRuntimeAuthMode(undefined);+ vi.unstubAllEnvs();+});++test("the server's runtime mode wins over the bundle's build-time mode", () => {+ vi.stubEnv("AUTH_MODE", "password");+ expect(getClientAuthMode()).toBe("password");+ setRuntimeAuthMode("local_noauth");+ expect(getClientAuthMode()).toBe("local_noauth");+});diff --git a/src/lib/auth-mode.ts b/src/lib/auth-mode.tsindex 30797f23..8859d6eb 100644--- a/src/lib/auth-mode.ts+++ b/src/lib/auth-mode.ts@@ -1,9 +1,19 @@import { z } from "zod";+// - cloudflare_access / local_noauth: self-hosted, identity comes from outside+// the app (an Access JWT, or a fixed local admin); no accounts of its own.+// - hosted: OpenSEO Cloud. Better Auth accounts plus the hosted business+// services: billing, transactional email, Turnstile, Google sign-in, telemetry.+// - password: self-hosted with the app's own accounts (the Docker+// standalone edition and the Cloudflare self-host). Better Auth accounts+// (email and password, organizations, invitations, API keys) with none of+// the hosted business services; the first visitor creates the+// administrator's account and invitations add the rest.export const AUTH_MODES = ["cloudflare_access","local_noauth","hosted",+ "password",] as const;type AuthMode = (typeof AUTH_MODES)[number];@@ -33,13 +43,45 @@ export function isHostedAuthMode(value: string | null | undefined) {return getAuthMode(value) === "hosted";}+// True when the app runs its own accounts (sessions, organizations,+// invitations, API keys): hosted and password modes. Gate billing, email, and+// other OpenSEO Cloud services on isHostedAuthMode, never on this.+export function usesBetterAuth(value: string | null | undefined) {+ const mode = getAuthMode(value);+ return mode === "hosted" || mode === "password";+}++// The client bundle inlines AUTH_MODE at build time (vite envPrefix), so a+// deployment must build and run with the same value. The standalone Docker+// image is built once and picks its mode when it starts, so the server records+// its runtime mode per request (server.ts) and prints it into the document+// (__root.tsx) for the browser; both sides prefer that value and fall back to+// the build-time one, which is what every other deployment still relies on.+declare global {+ // `var` is how a property of globalThis is declared.+ var __OPENSEO_AUTH_MODE__: string | undefined;+}++export function setRuntimeAuthMode(value: string | undefined) {+ globalThis.__OPENSEO_AUTH_MODE__ = value;+}++export function getClientAuthMode() {+ return getAuthMode(+ globalThis.__OPENSEO_AUTH_MODE__ ?? import.meta.env.AUTH_MODE,+ );+}++export function runtimeAuthModeScript() {+ return `globalThis.__OPENSEO_AUTH_MODE__=${JSON.stringify(getClientAuthMode())}`;+}+export function isHostedClientAuthMode() {- // This is an explicit deploy-time contract: the operator must keep the- // client build-time AUTH_MODE aligned with the server runtime AUTH_MODE.- // We accept that tradeoff to avoid a startup round-trip just to ask the- // backend which auth UI to render. Hosted deployments must therefore set- // AUTH_MODE=hosted in both the client build environment and the runtime.- return isHostedAuthMode(import.meta.env.AUTH_MODE);+ return getClientAuthMode() === "hosted";+}++export function usesBetterAuthClient() {+ return usesBetterAuth(getClientAuthMode());}export function isEmailVerificationBypassed() {@@ -47,5 +89,11 @@ export function isEmailVerificationBypassed() {// verification and never marks users emailVerified, so the client must treat// the session as verified too — otherwise route guards and /verify-email// bounce each other in an infinite redirect loop.- return import.meta.env.BYPASS_EMAIL_VERIFICATION === "true";+ // Password mode has no email transport: accounts are created in the browser+ // (first visitor, invitation links) or by the operator and never confirm an+ // address.+ return (+ import.meta.env.BYPASS_EMAIL_VERIFICATION === "true" ||+ getClientAuthMode() === "password"+ );}diff --git a/src/lib/auth.ts b/src/lib/auth.tsindex 48f365e9..44aa01d5 100644--- a/src/lib/auth.ts+++ b/src/lib/auth.ts@@ -16,7 +16,7 @@ import * as pgSchema from "@/db/pg/schema";import { getDatabaseProvider } from "@/db/provider";import { z } from "zod";import { CURRENT_TERMS_VERSION } from "@/shared/terms";-import { isHostedAuthMode } from "@/lib/auth-mode";+import { getAuthMode, isHostedAuthMode, usesBetterAuth } from "@/lib/auth-mode";import { createApiKeyPlugin } from "@/lib/auth-api-key";import { getActiveOrganizationId } from "@/lib/auth-session";import { createBaseAuthConfig } from "@/lib/auth-config";@@ -27,6 +27,7 @@ import {import { resolveSignInHostedOrganization } from "@/server/auth/default-hosted-organization";import { onInvitationAccepted } from "@/server/auth/invited-member";import { AuthRepository } from "@/server/auth/repositories/AuthRepository";+import { assertStandaloneSignUpOpen } from "@/server/standalone/sign-up";import { captureDubReferralSignup } from "@/server/referrals/dub";import { captureMetaSignup } from "@/server/referrals/meta";import {@@ -51,22 +52,30 @@ const hostedBaseUrlSchema = zconst url = new URL(value);return (url.protocol === "https:" ||- (url.protocol === "http:" && url.hostname === "localhost")+ (url.protocol === "http:" &&+ ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)));- }, "BETTER_AUTH_URL must use https or localhost");+ }, "BETTER_AUTH_URL must use https or a loopback host");const createdApiKeySchema = z.object({ referenceId: z.string() });function createAuth() {- // Hosted needs the real configured URL (cookies, callbacks, /api/auth routes- // all use it). Self-hosted only builds this instance to mint/refresh Search- // Console tokens, which never read baseURL — so a placeholder is fine there.- const baseUrl = isHostedAuthMode(env.AUTH_MODE)+ // Modes with their own accounts need the real configured URL (cookies,+ // callbacks, /api/auth routes all use it). The other self-hosted modes only+ // build this instance to mint/refresh Search Console tokens, which never+ // read baseURL — so a placeholder is fine there.+ const baseUrl = usesBetterAuth(env.AUTH_MODE)? getHostedBaseUrl(): "http://localhost";- const bypassEmail = Reflect.get(env, "BYPASS_EMAIL_VERIFICATION") === "true";+ // Password mode (self-hosted accounts: the Docker standalone edition and the+ // Cloudflare self-host) has no email transport: accounts come from the+ // first visit, invitation links, or the operator's commands+ // (src/server/standalone/admin.ts), so nothing is ever verified by email.+ const standalone = getAuthMode(env.AUTH_MODE) === "password";+ const bypassEmail =+ standalone || Reflect.get(env, "BYPASS_EMAIL_VERIFICATION") === "true";const baseAuthConfig = createBaseAuthConfig(- isHostedAuthMode(env.AUTH_MODE)+ usesBetterAuth(env.AUTH_MODE)? {organization: {// No sendInvitationEmail here on purpose: better-auth swallows a@@ -178,17 +187,34 @@ function createAuth() {},},...baseAuthConfig,+ // Standalone reads every session from the database so an operator+ // password reset revokes it at once; hosted keeps the signed-cookie cache+ // (see auth-options.ts for the trade-off).+ session: standalone+ ? { ...baseAuthConfig.session, cookieCache: { enabled: false } }+ : baseAuthConfig.session,+ // Better Auth turns its rate limiter on only when NODE_ENV is+ // "production", which the standalone runtime does not set, so password+ // guessing against /sign-in/email was unlimited there. The memory store+ // is enough: the runtime keeps the app alive between requests.+ ...(standalone ? { rateLimit: { enabled: true } } : {}),emailAndPassword: {...baseAuthConfig.emailAndPassword,requireEmailVerification: !bypassEmail,resetPasswordTokenExpiresIn: 60 * 60,revokeSessionsOnPasswordReset: true,- sendResetPassword: async ({ user, url }) => {- await sendHostedPasswordResetEmail({- email: user.email,- resetUrl: url,- });- },+ // Standalone: the operator's create-user call must not mint a session+ // for anyone, and there is no email to carry a reset link.+ ...(standalone+ ? { autoSignIn: false }+ : {+ sendResetPassword: async ({ user, url }) => {+ await sendHostedPasswordResetEmail({+ email: user.email,+ resetUrl: url,+ });+ },+ }),},emailVerification: bypassEmail? undefined@@ -213,7 +239,7 @@ function createAuth() {database,plugins: [...baseAuthConfig.plugins,- ...(isHostedAuthMode(env.AUTH_MODE) ? [createApiKeyPlugin()] : []),+ ...(usesBetterAuth(env.AUTH_MODE) ? [createApiKeyPlugin()] : []),...(turnstileSecretKey? [captcha({@@ -226,18 +252,22 @@ function createAuth() {tanstackStartCookies(),],hooks: {- // Binds a new MCP API key to the organization the session is working- // in, server-side: the /mcp handler reads metadata.organizationId and- // bills/authorizes that org for the key's lifetime. The session's- // active org is only a hint; the member row is the authorization fact.- // Throwing here means an unbound key can never be minted through the- // HTTP endpoint. Better Auth merges the returned body over the- // request's, so an organizationId the client sends loses to this one.- // The owner can still rewrite metadata through /api-key/update, which- // gains nothing: a key pointed at an org they are not in fails the- // membership check on its next /mcp call, and one pointed at an org- // they are in is no different from a key created there.before: createAuthMiddleware(async (ctx) => {+ // Standalone closes registration (src/server/standalone/sign-up.ts).+ if (standalone && ctx.path === "/sign-up/email")+ return assertStandaloneSignUpOpen(ctx.headers, ctx.body);++ // Binds a new MCP API key to the organization the session is working+ // in, server-side: the /mcp handler reads metadata.organizationId and+ // bills/authorizes that org for the key's lifetime. The session's+ // active org is only a hint; the member row is the authorization fact.+ // Throwing here means an unbound key can never be minted through the+ // HTTP endpoint. Better Auth merges the returned body over the+ // request's, so an organizationId the client sends loses to this one.+ // The owner can still rewrite metadata through /api-key/update, which+ // gains nothing: a key pointed at an org they are not in fails the+ // membership check on its next /mcp call, and one pointed at an org+ // they are in is no different from a key created there.if (ctx.path !== "/api-key/create") return;// Minting a credential must see the stored session, not the cookie// cache: a cookie from a session revoked minutes ago must not mint a@@ -311,8 +341,8 @@ function createAuth() {};},after: async (user, ctx) => {- await syncHostedSignupContact(user);if (isHostedAuthMode(env.AUTH_MODE)) {+ await syncHostedSignupContact(user);// Partner attribution is a referral choice: an older dub_id// cookie must not credit a partner without it.if (requestPrivacyChoices(ctx?.request).referrals) {@@ -404,7 +434,7 @@ export function getHostedBaseUrl() {const baseUrl = env.BETTER_AUTH_URL?.trim();if (!baseUrl) {- throw new Error("BETTER_AUTH_URL is required in hosted mode");+ throw new Error("BETTER_AUTH_URL is required in hosted and password modes");}return hostedBaseUrlSchema.parse(baseUrl);@@ -476,10 +506,14 @@ function hasHostedAuthEmailConfig() {});}-export function hasHostedAuthConfig() {+// Whether this deployment can serve its own accounts. Standalone needs only+// the URL and the secret; hosted also needs Google sign-in, Turnstile, and+// (unless bypassed) the transactional email templates.+export function hasBetterAuthConfig() {try {getHostedBaseUrl();getHostedSecret();+ if (getAuthMode(env.AUTH_MODE) === "password") return true;getGoogleSocialProviderConfig();return (hasHostedTurnstileConfig(env) &&diff --git a/src/lib/selfhost-preflight.test.ts b/src/lib/selfhost-preflight.test.tsindex b07724a5..edd6b63b 100644--- a/src/lib/selfhost-preflight.test.ts+++ b/src/lib/selfhost-preflight.test.ts@@ -25,7 +25,7 @@ describe("runSelfhostPreflight", () => {expect(result.failed).toBe(true);expect(itemFor(result, "AUTH_MODE")?.message).toContain(- "cloudflare_access, local_noauth, hosted",+ "cloudflare_access, local_noauth, hosted, password",);});@@ -35,6 +35,10 @@ describe("runSelfhostPreflight", () => {{ AUTH_MODE: "hosted", BETTER_AUTH_SECRET: "x".repeat(40) },["BETTER_AUTH_URL", "GOOGLE_CLIENT_ID"],],+ [+ { AUTH_MODE: "password", BETTER_AUTH_SECRET: "x".repeat(40) },+ ["BETTER_AUTH_URL"],+ ],])("fails %o listing every missing variable", (env, mentions) => {const result = runSelfhostPreflight(env);diff --git a/src/lib/selfhost-preflight.ts b/src/lib/selfhost-preflight.tsindex d187a934..b2b93e99 100644--- a/src/lib/selfhost-preflight.ts+++ b/src/lib/selfhost-preflight.ts@@ -58,6 +58,34 @@ function checkAuthMode(env: EnvRecord, items: PreflightItem[]): void {return;}+ if (mode === "password") {+ const url = get(env, "BETTER_AUTH_URL");+ const secret = get(env, "BETTER_AUTH_SECRET");+ const missing = [+ url ? null : "BETTER_AUTH_URL",+ secret && secret.length >= MIN_BETTER_AUTH_SECRET_LENGTH+ ? null+ : `BETTER_AUTH_SECRET (at least ${MIN_BETTER_AUTH_SECRET_LENGTH} characters)`,+ ].filter(Boolean);+ items.push(+ missing.length+ ? {+ key: "auth",+ name: "AUTH_MODE",+ level: "fail",+ message: `password mode requires ${missing.join(" and ")}.`,+ }+ : {+ key: "auth",+ name: "AUTH_MODE",+ level: "ok",+ message:+ "password — email and password accounts; the first visitor creates the admin account and invitations add the rest",+ },+ );+ return;+ }+if (mode === "hosted") {const missing = ["BETTER_AUTH_URL",diff --git a/src/middleware/ensure-user/hosted.ts b/src/middleware/ensure-user/hosted.tsindex 0dfd25f5..68dbe88a 100644--- a/src/middleware/ensure-user/hosted.ts+++ b/src/middleware/ensure-user/hosted.ts@@ -1,4 +1,4 @@-import { getAuth, hasHostedAuthConfig } from "@/lib/auth";+import { getAuth, hasBetterAuthConfig } from "@/lib/auth";import { getActiveOrganizationId } from "@/lib/auth-session";import { AuthRepository } from "@/server/auth/repositories/AuthRepository";import { resolveActiveHostedOrganization } from "@/server/auth/default-hosted-organization";@@ -6,10 +6,10 @@ import { AppError } from "@/server/lib/errors";import type { EnsuredUserContext } from "./types";async function requireHostedSession(headers: Headers) {- if (!hasHostedAuthConfig()) {+ if (!hasBetterAuthConfig()) {throw new AppError("AUTH_CONFIG_MISSING",- "Missing Better Auth hosted configuration",+ "Missing Better Auth configuration",);}diff --git a/src/middleware/ensure-user/resolve.ts b/src/middleware/ensure-user/resolve.tsindex 81eefd4f..1ad0cb5d 100644--- a/src/middleware/ensure-user/resolve.ts+++ b/src/middleware/ensure-user/resolve.ts@@ -1,5 +1,5 @@import { env } from "cloudflare:workers";-import { getAuthMode, isHostedAuthMode } from "@/lib/auth-mode";+import { getAuthMode, usesBetterAuth } from "@/lib/auth-mode";import { resolveCloudflareAccessContext } from "./cloudflareAccess";import { resolveLocalNoAuthContext } from "./delegated";import { resolveHostedContext } from "./hosted";@@ -15,7 +15,7 @@ export async function resolveUserContextFromHeaders(if (authMode === "local_noauth") {return resolveLocalNoAuthContext();}- if (isHostedAuthMode(authMode)) {+ if (usesBetterAuth(authMode)) {return resolveHostedContext(headers);}return resolveCloudflareAccessContext(headers);diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.tsindex 88ff9aad..3b03d546 100644--- a/src/routeTree.gen.ts+++ b/src/routeTree.gen.ts@@ -32,6 +32,7 @@ import { Route as AuthenticatedYcRouteImport } from './routes/_authenticated.yc'import { Route as AcceptInvitationIdRouteImport } from './routes/accept-invitation.$id'import { Route as ApiHealthRouteImport } from './routes/api/health'import { Route as ApiPrivacyRegionRouteImport } from './routes/api/privacy-region'+import { Route as ApiSignUpStatusRouteImport } from './routes/api/sign-up-status'import { Route as RReportIdRouteImport } from './routes/r/$reportId'import { Route as AppBillingFixPaymentRouteImport } from './routes/_app/billing_.fix-payment'import { Route as AppHelpDataforseoApiKeyRouteImport } from './routes/_app/help/dataforseo-api-key'@@ -195,6 +196,11 @@ const ApiPrivacyRegionRoute = ApiPrivacyRegionRouteImport.update({path: '/api/privacy-region',getParentRoute: () => rootRouteImport,} as any)+const ApiSignUpStatusRoute = ApiSignUpStatusRouteImport.update({+ id: '/api/sign-up-status',+ path: '/api/sign-up-status',+ getParentRoute: () => rootRouteImport,+} as any)const RReportIdRoute = RReportIdRouteImport.update({id: '/r/$reportId',path: '/r/$reportId',@@ -473,6 +479,7 @@ export interface FileRoutesByFullPath {'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/api/privacy-region': typeof ApiPrivacyRegionRoute+ '/api/sign-up-status': typeof ApiSignUpStatusRoute'/r/$reportId': typeof RReportIdRoute'/p/$projectId': typeof AppPProjectIdRouteRouteWithChildren'/billing/fix-payment': typeof AppBillingFixPaymentRoute@@ -541,6 +548,7 @@ export interface FileRoutesByTo {'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/api/privacy-region': typeof ApiPrivacyRegionRoute+ '/api/sign-up-status': typeof ApiSignUpStatusRoute'/r/$reportId': typeof RReportIdRoute'/billing/fix-payment': typeof AppBillingFixPaymentRoute'/help/dataforseo-api-key': typeof AppHelpDataforseoApiKeyRoute@@ -608,6 +616,7 @@ export interface FileRoutesById {'/accept-invitation/$id': typeof AcceptInvitationIdRoute'/api/health': typeof ApiHealthRoute'/api/privacy-region': typeof ApiPrivacyRegionRoute+ '/api/sign-up-status': typeof ApiSignUpStatusRoute'/r/$reportId': typeof RReportIdRoute'/_app/': typeof AppIndexRoute'/_app/p/$projectId': typeof AppPProjectIdRouteRouteWithChildren@@ -680,6 +689,7 @@ export interface FileRouteTypes {| '/accept-invitation/$id'| '/api/health'| '/api/privacy-region'+ | '/api/sign-up-status'| '/r/$reportId'| '/p/$projectId'| '/billing/fix-payment'@@ -748,6 +758,7 @@ export interface FileRouteTypes {| '/accept-invitation/$id'| '/api/health'| '/api/privacy-region'+ | '/api/sign-up-status'| '/r/$reportId'| '/billing/fix-payment'| '/help/dataforseo-api-key'@@ -814,6 +825,7 @@ export interface FileRouteTypes {| '/accept-invitation/$id'| '/api/health'| '/api/privacy-region'+ | '/api/sign-up-status'| '/r/$reportId'| '/_app/'| '/_app/p/$projectId'@@ -877,6 +889,7 @@ export interface RootRouteChildren {AcceptInvitationIdRoute: typeof AcceptInvitationIdRouteApiHealthRoute: typeof ApiHealthRouteApiPrivacyRegionRoute: typeof ApiPrivacyRegionRoute+ ApiSignUpStatusRoute: typeof ApiSignUpStatusRouteRReportIdRoute: typeof RReportIdRouteApiAuthSplatRoute: typeof ApiAuthSplatRouteApiAutumnSplatRoute: typeof ApiAutumnSplatRoute@@ -1053,6 +1066,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ApiPrivacyRegionRouteImportparentRoute: typeof rootRouteImport}+ '/api/sign-up-status': {+ id: '/api/sign-up-status'+ path: '/api/sign-up-status'+ fullPath: '/api/sign-up-status'+ preLoaderRoute: typeof ApiSignUpStatusRouteImport+ parentRoute: typeof rootRouteImport+ }'/r/$reportId': {id: '/r/$reportId'path: '/r/$reportId'@@ -1591,6 +1611,7 @@ const rootRouteChildren: RootRouteChildren = {AcceptInvitationIdRoute: AcceptInvitationIdRoute,ApiHealthRoute: ApiHealthRoute,ApiPrivacyRegionRoute: ApiPrivacyRegionRoute,+ ApiSignUpStatusRoute: ApiSignUpStatusRoute,RReportIdRoute: RReportIdRoute,ApiAuthSplatRoute: ApiAuthSplatRoute,ApiAutumnSplatRoute: ApiAutumnSplatRoute,diff --git a/src/routes/__root.tsx b/src/routes/__root.tsxindex ca07f1ac..4c22e508 100644--- a/src/routes/__root.tsx+++ b/src/routes/__root.tsx@@ -14,6 +14,7 @@ import { DefaultCatchBoundary } from "@/client/components/DefaultCatchBoundary";import { captureGoogleLinkError } from "@/client/features/integrations/googleLinkError";import { ExportToSheetsModal } from "@/client/components/table/ExportToSheetsModal";import { themePreferenceInitScript } from "@/client/lib/theme";+import { runtimeAuthModeScript } from "@/lib/auth-mode";import { NotFound } from "@/client/components/NotFound";import { PrivacyBootstrap } from "@/client/components/PrivacyChoices";import { TooltipProvider } from "@/client/components/ui/tooltip";@@ -100,6 +101,7 @@ function RootDocument({ children }: { children: React.ReactNode }) {<scriptdangerouslySetInnerHTML={{ __html: themePreferenceInitScript }}/>+ <script dangerouslySetInnerHTML={{ __html: runtimeAuthModeScript() }} /><HeadContent /></head><body>diff --git a/src/routes/_app/ai.tsx b/src/routes/_app/ai.tsxindex a4624a6d..ef1dd490 100644--- a/src/routes/_app/ai.tsx+++ b/src/routes/_app/ai.tsx@@ -17,7 +17,7 @@ import {} from "@/client/components/ui/card";import { PageHeader } from "@/client/components/PageHeader";import { ArrowUpRight, ShieldAlert } from "lucide-react";-import { getAuthMode } from "@/lib/auth-mode";+import { getClientAuthMode } from "@/lib/auth-mode";import { captureClientEvent } from "@/client/lib/posthog";import {agentUpdatePrompt,@@ -185,7 +185,7 @@ function AiPage() {</Card></div>- {getAuthMode(import.meta.env.AUTH_MODE) === "cloudflare_access" ? (+ {getClientAuthMode() === "cloudflare_access" ? (<Alert variant="warning" className="mt-8"><ShieldAlert /><AlertDescription>diff --git a/src/routes/_app/p/$projectId/reports/$reportId.tsx b/src/routes/_app/p/$projectId/reports/$reportId.tsxindex 6910ca0f..294ca7ca 100644--- a/src/routes/_app/p/$projectId/reports/$reportId.tsx+++ b/src/routes/_app/p/$projectId/reports/$reportId.tsx@@ -32,7 +32,7 @@ import {useDeleteReport,} from "@/client/features/reports/shared";import { formatRelativeTime } from "@/client/lib/relative-time";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";import { getErrorCode } from "@/client/lib/error-messages";import { captureClientEvent } from "@/client/lib/posthog";import { getReport } from "@/serverFunctions/reports";@@ -48,7 +48,7 @@ export const Route = createFileRoute("/_app/p/$projectId/reports/$reportId")({function ReportDetailPage() {const { projectId, reportId } = Route.useParams();- const hosted = isHostedClientAuthMode();+ const canShare = usesBetterAuthClient();const { full } = Route.useSearch();const navigate = useNavigate({ from: Route.fullPath });const [showDelete, setShowDelete] = useState(false);@@ -190,12 +190,12 @@ function ReportDetailPage() {}actions={<>- {/* Share links are hosted-only (see shareAccess.ts), so a- self-hosted deployment keeps Export as its primary action- rather than offering a button the server would refuse. The+ {/* Share links need Better Auth accounts (see shareAccess.ts),+ so an Access / no-auth self-hosted deployment keeps Export as+ its primary action rather than a button the server refuses. Theicon carries the state: a globe once a public link is live, alock while only members can open it. */}- {hosted ? (+ {canShare ? (<Button onClick={() => setShowShare(true)}>{report.shareToken ? (<Globe data-icon="inline-start" />@@ -223,7 +223,7 @@ function ReportDetailPage() {<MoreHorizontal /></DropdownMenuTrigger><DropdownMenuContent align="end" className="w-52">- {hosted ? (+ {canShare ? (<><DropdownMenuItem onClick={exportPdf}><FileDown />diff --git a/src/routes/_app/settings.tsx b/src/routes/_app/settings.tsxindex cddd9fae..b82d0c21 100644--- a/src/routes/_app/settings.tsx+++ b/src/routes/_app/settings.tsx@@ -1,7 +1,7 @@import { createFileRoute, Outlet } from "@tanstack/react-router";import { NavTab, NavTabs } from "@/client/components/NavTabs";import { PageHeader } from "@/client/components/PageHeader";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";export const Route = createFileRoute("/_app/settings")({component: SettingsLayout,@@ -13,8 +13,9 @@ export const Route = createFileRoute("/_app/settings")({function SettingsLayout() {const tabs = [{ to: "/settings" as const, label: "Personal", exact: true },- // Self-host has no memberships — the organization tab would 404.- ...(isHostedClientAuthMode()+ // Access / no-auth self-host has no memberships — the organization tab+ // would 404.+ ...(usesBetterAuthClient()? [{ to: "/settings/organization" as const, label: "Organization" }]: []),];diff --git a/src/routes/_app/settings/index.tsx b/src/routes/_app/settings/index.tsxindex b84b8cff..dedcd730 100644--- a/src/routes/_app/settings/index.tsx+++ b/src/routes/_app/settings/index.tsx@@ -4,7 +4,7 @@ import { SectionHeader } from "@/client/components/PageHeader";import { ThemePreferenceRadio } from "@/client/components/ThemePreferenceMenuItems";import { McpConnectionsSettings } from "@/client/features/settings/McpConnectionsSettings";import { PrivacySettings } from "@/client/features/settings/PrivacySettings";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { isHostedClientAuthMode, usesBetterAuthClient } from "@/lib/auth-mode";import { version } from "../../../../package.json";export const Route = createFileRoute("/_app/settings/")({@@ -13,6 +13,9 @@ export const Route = createFileRoute("/_app/settings/")({function PersonalSettings() {const isHosted = isHostedClientAuthMode();+ // API keys need Better Auth accounts (hosted or the standalone Docker+ // edition); the analytics choices only exist on hosted.+ const hasAccounts = usesBetterAuthClient();return (<div className="space-y-10"><section className="space-y-3">@@ -23,14 +26,12 @@ function PersonalSettings() {</div></section>- {isHosted ? (- <>- <McpConnectionsSettings />+ {isHosted ? <McpConnectionsSettings /> : null}- <ApiKeySettings />+ {hasAccounts ? <ApiKeySettings /> : null}- <PrivacySettings />- </>+ {isHosted ? (+ <PrivacySettings />) : (<section className="space-y-3"><SectionHeader title="About" />diff --git a/src/routes/_app/settings/organization.tsx b/src/routes/_app/settings/organization.tsxindex ea7430a9..80a26256 100644--- a/src/routes/_app/settings/organization.tsx+++ b/src/routes/_app/settings/organization.tsx@@ -1,12 +1,12 @@import { createFileRoute, notFound } from "@tanstack/react-router";import { TeamSettings } from "@/client/features/team/TeamSettings";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";export const Route = createFileRoute("/_app/settings/organization")({- // Self-host has no memberships or invitations — the better-auth HTTP- // surface isn't even mounted there.+ // Access / no-auth self-host has no memberships or invitations — the+ // better-auth HTTP surface isn't even mounted there.beforeLoad: () => {- if (!isHostedClientAuthMode()) {+ if (!usesBetterAuthClient()) {throw notFound();}},diff --git a/src/routes/_auth.sign-in.tsx b/src/routes/_auth.sign-in.tsxindex 11b8da19..6e2a81bb 100644--- a/src/routes/_auth.sign-in.tsx+++ b/src/routes/_auth.sign-in.tsx@@ -1,5 +1,6 @@+import { useQuery } from "@tanstack/react-query";import { Link, createFileRoute, useNavigate } from "@tanstack/react-router";-import { useState } from "react";+import { useEffect, useState } from "react";import { useAppForm } from "@/client/components/form/useAppForm";import { Button } from "@/client/components/ui/button";import {@@ -11,6 +12,7 @@ import {authRedirectSearchSchema,useAuthPageState,} from "@/client/features/auth/AuthPage";+import { signUpStatusQueryOptions } from "@/client/features/auth/signUpStatus";import { useGoogleAuth } from "@/client/features/auth/useGoogleAuth";import { getFormError } from "@/client/lib/forms";import { captureClientEvent } from "@/client/lib/posthog";@@ -35,11 +37,29 @@ export const Route = createFileRoute("/_auth/sign-in")({function SignInPage() {const search = Route.useSearch();const navigate = useNavigate();- const { redirectTo, oauthQuery, isHostedMode } = useAuthPageState(- search.redirect,- );+ const { redirectTo, oauthQuery, isHostedMode, isBetterAuthMode } =+ useAuthPageState(search.redirect);const [showEmailForm, setShowEmailForm] = useState(false);+ // The standalone Docker edition has accounts but no Google sign-in and no+ // emailed password reset: go straight to the email form. Accounts come from+ // invitations, and a fresh installation has nobody to sign in, so its first+ // visitor is sent to create the admin account instead.+ const emailOnly = isBetterAuthMode && !isHostedMode;+ const emailFormVisible = showEmailForm || emailOnly;const google = useGoogleAuth({ redirectTo });+ const signUpStatus = useQuery({+ ...signUpStatusQueryOptions(),+ enabled: emailOnly,+ });+ const firstAccount = signUpStatus.data?.firstAccount === true;+ useEffect(() => {+ if (!firstAccount) return;+ void navigate({+ to: "/sign-up",+ search: getSignInSearch(redirectTo),+ replace: true,+ });+ }, [firstAccount, navigate, redirectTo]);const form = useAppForm({defaultValues: {@@ -105,7 +125,12 @@ function SignInPage() {<AuthPageCardtitle="Sign in"footer={- isHostedMode ? (+ emailOnly ? (+ <p className="text-sm text-foreground/50">+ Need an account? Ask an administrator for an invitation. Forgot your+ password? Ask your server administrator to reset it.+ </p>+ ) : isHostedMode ? (<divclassName={showEmailForm@@ -133,7 +158,7 @@ function SignInPage() {) : null}>- {!showEmailForm ? (+ {!emailFormVisible ? (<><AuthMethodChoosergoogleLabel="Continue with Google"diff --git a/src/routes/_auth.sign-up.tsx b/src/routes/_auth.sign-up.tsxindex 386058eb..48b66394 100644--- a/src/routes/_auth.sign-up.tsx+++ b/src/routes/_auth.sign-up.tsx@@ -1,5 +1,7 @@+import { useQuery } from "@tanstack/react-query";import { Link, createFileRoute, useNavigate } from "@tanstack/react-router";import { useState } from "react";+import { PageLoading } from "@/client/components/Spinner";import { useAppForm } from "@/client/components/form/useAppForm";import { Button } from "@/client/components/ui/button";import {@@ -17,11 +19,16 @@ import {useTurnstileCaptcha,} from "@/client/features/auth/TurnstileWidget";import { passwordSchema } from "@/client/features/auth/passwordSchema";+import { signUpStatusQueryOptions } from "@/client/features/auth/signUpStatus";import { useGoogleAuth } from "@/client/features/auth/useGoogleAuth";import { getFormError } from "@/client/lib/forms";import { captureClientEvent } from "@/client/lib/posthog";import { authClient } from "@/lib/auth-client";-import { getSignInSearch, getVerifyEmailSearch } from "@/lib/auth-redirect";+import {+ getSignInSearch,+ getVerifyEmailSearch,+ toAuthCallbackURL,+} from "@/lib/auth-redirect";import { z } from "zod";const UTM_PARAMS = [@@ -61,7 +68,9 @@ export const Route = createFileRoute("/_auth/sign-up")({function SignUpPage() {const search = Route.useSearch();const navigate = useNavigate();- const { redirectTo, isHostedMode } = useAuthPageState(search.redirect);+ const { redirectTo, isHostedMode, isBetterAuthMode } = useAuthPageState(+ search.redirect,+ );const onboardingSearch = new URLSearchParams();if (search.domain) onboardingSearch.set("domain", search.domain);for (const name of UTM_PARAMS) {@@ -76,6 +85,17 @@ function SignUpPage() {: "/onboarding";const [showEmailForm, setShowEmailForm] = useState(false);const google = useGoogleAuth({ redirectTo, postSignupRedirect });+ // The standalone Docker edition: no Google, no email verification, and the+ // server accepts a sign-up only for the first account or an invited address+ // (src/server/standalone/sign-up.ts).+ const standalone = isBetterAuthMode && !isHostedMode;+ const invited = redirectTo.startsWith("/accept-invitation/");+ const signUpStatus = useQuery({+ ...signUpStatusQueryOptions(),+ enabled: standalone,+ });+ const firstAccount = signUpStatus.data?.firstAccount === true;+ const emailFormVisible = showEmailForm || standalone;// Turnstile is active only in hosted mode with a configured site key.const isTurnstileEnabled = isHostedMode && Boolean(TURNSTILE_SITE_KEY);@@ -140,6 +160,27 @@ function SignUpPage() {captureClientEvent("auth:sign_up_success", {redirect_to: redirectTo,});+ if (standalone) {+ // Nothing to verify here, and autoSignIn is off so the operator's+ // create-user never mints a session: sign in explicitly, and the+ // layout sends the new session to redirectTo.+ const signedIn = await authClient.signIn.email({+ email,+ password: value.password,+ callbackURL: toAuthCallbackURL(redirectTo),+ });+ if (signedIn.error) {+ formApi.setErrorMap({+ onSubmit: {+ form:+ signedIn.error.message ||+ "Account created. Sign in to continue.",+ fields: {},+ },+ });+ }+ return;+ }void navigate({to: "/verify-email",search: getVerifyEmailSearch(email, postSignupRedirect),@@ -157,11 +198,54 @@ function SignUpPage() {},});+ if (standalone && !firstAccount && !invited) {+ if (signUpStatus.isPending) return <PageLoading />;+ return (+ <AuthPageCard+ title="Registration is closed"+ helperText="Ask an administrator for an invitation."+ footer={+ <p className="text-sm">+ <Link+ to="/sign-in"+ search={getSignInSearch(redirectTo)}+ className="text-muted-foreground hover:text-foreground transition-colors"+ >+ Back to sign in+ </Link>+ </p>+ }+ >+ {null}+ </AuthPageCard>+ );+ }+return (<AuthPageCard- title="Create your account"+ title={firstAccount ? "Create the admin account" : "Create your account"}+ helperText={+ firstAccount+ ? "This installation has no accounts yet. The first one becomes the administrator."+ : invited+ ? "Use the email address that received the invitation."+ : undefined+ }footer={- isHostedMode ? (+ standalone ? (+ firstAccount ? null : (+ <p className="text-sm text-foreground/50">+ Already have an account?{" "}+ <Link+ to="/sign-in"+ search={getSignInSearch(redirectTo)}+ className="text-foreground underline underline-offset-2 hover:text-foreground/80 transition-colors"+ >+ Sign in+ </Link>+ </p>+ )+ ) : isHostedMode ? (showEmailForm ? (<buttontype="button"@@ -190,7 +274,7 @@ function SignUpPage() {) : null}>- {!showEmailForm ? (+ {!emailFormVisible ? (<><AuthMethodChoosergoogleLabel="Continue with Google"@@ -283,7 +367,9 @@ function SignUpPage() {>{isSubmitting ? "Creating account..." : "Create account"}</Button>- <TermsAgreementNotice action="By creating an account" />+ {isHostedMode ? (+ <TermsAgreementNotice action="By creating an account" />+ ) : null}</>);}}diff --git a/src/routes/_auth.tsx b/src/routes/_auth.tsxindex d5fb0674..d4025a7d 100644--- a/src/routes/_auth.tsx+++ b/src/routes/_auth.tsx@@ -6,7 +6,7 @@ import {} from "@/client/features/auth/AuthPage";import { useSession } from "@/lib/auth-client";import { PageLoading } from "@/client/components/Spinner";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";import { getCurrentAuthRedirect, isDocumentRoute } from "@/lib/auth-redirect";export const Route = createFileRoute("/_auth")({@@ -19,7 +19,7 @@ function AuthPageLayout() {const navigate = useNavigate();const { data: session, isPending } = useSession();const [hasResolvedSession, setHasResolvedSession] = useState(false);- const isHostedMode = isHostedClientAuthMode();+ const hasAccounts = usesBetterAuthClient();const redirectTo = getCurrentAuthRedirect(search.redirect);useEffect(() => {@@ -46,7 +46,7 @@ function AuthPageLayout() {// Loading the session, or handing a signed-in user off to the destination.if (- isHostedMode &&+ hasAccounts &&((isPending && !hasResolvedSession) || session?.user?.id)) {return <PageLoading />;diff --git a/src/routes/accept-invitation.$id.tsx b/src/routes/accept-invitation.$id.tsxindex 96990ae7..47c9353d 100644--- a/src/routes/accept-invitation.$id.tsx+++ b/src/routes/accept-invitation.$id.tsx@@ -8,11 +8,11 @@ import { AuthPageCard, AuthPageShell } from "@/client/features/auth/AuthPage";import { clearLastProjectId } from "@/client/lib/active-project";import { captureClientEvent } from "@/client/lib/posthog";import { authClient, signOutAndRedirect, useSession } from "@/lib/auth-client";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { usesBetterAuthClient } from "@/lib/auth-mode";export const Route = createFileRoute("/accept-invitation/$id")({beforeLoad: () => {- if (!isHostedClientAuthMode()) {+ if (!usesBetterAuthClient()) {throw notFound();}},@@ -46,7 +46,8 @@ function SignedOutInvitationCard({ invitationId }: { invitationId: string }) {<AuthPageCard title="You’re invited"><p className="text-sm text-muted-foreground">You’ve been invited to join an organization on OpenSEO. Sign in- with the email address that received the invitation to accept it.+ with the email address that received the invitation, or create an+ account with it, to accept.</p><div className="space-y-2"><Buttondiff --git a/src/routes/api/auth/$.ts b/src/routes/api/auth/$.tsindex cc5c500b..537668e8 100644--- a/src/routes/api/auth/$.ts+++ b/src/routes/api/auth/$.ts@@ -1,17 +1,17 @@import { createFileRoute } from "@tanstack/react-router";import { env } from "cloudflare:workers";-import { getAuth, hasHostedAuthConfig } from "@/lib/auth";-import { isHostedAuthMode } from "@/lib/auth-mode";+import { getAuth, hasBetterAuthConfig } from "@/lib/auth";+import { usesBetterAuth } from "@/lib/auth-mode";async function handleAuthRequest(request: Request) {- if (!isHostedAuthMode(env.AUTH_MODE)) {+ if (!usesBetterAuth(env.AUTH_MODE)) {return new Response("Not found", {status: 404,});}- if (!hasHostedAuthConfig()) {- return new Response("Missing Better Auth hosted configuration", {+ if (!hasBetterAuthConfig()) {+ return new Response("Missing Better Auth configuration", {status: 500,});}diff --git a/src/routes/api/sign-up-status.ts b/src/routes/api/sign-up-status.tsnew file mode 100644index 00000000..58baef98--- /dev/null+++ b/src/routes/api/sign-up-status.ts@@ -0,0 +1,26 @@+import { createFileRoute } from "@tanstack/react-router";+import { env } from "cloudflare:workers";+import { getAuthMode } from "@/lib/auth-mode";++// Unauthenticated: tells the sign-in and sign-up pages whether this standalone+// installation still has no account, so its first visitor can create the+// administrator's. Every other mode answers false without a database read.+async function handleSignUpStatusRequest(): Promise<Response> {+ let firstAccount = false;+ if (getAuthMode(env.AUTH_MODE) === "password") {+ const { isFirstAccountOpen } = await import("@/server/standalone/sign-up");+ firstAccount = await isFirstAccountOpen();+ }+ return Response.json(+ { firstAccount },+ { headers: { "cache-control": "no-store" } },+ );+}++export const Route = createFileRoute("/api/sign-up-status")({+ server: {+ handlers: {+ GET: () => handleSignUpStatusRequest(),+ },+ },+});diff --git a/src/routes/forgot-password.tsx b/src/routes/forgot-password.tsxindex fb6ec5c2..881841c4 100644--- a/src/routes/forgot-password.tsx+++ b/src/routes/forgot-password.tsx@@ -9,7 +9,7 @@ import {} from "@/client/features/auth/AuthPage";import { getFormError } from "@/client/lib/forms";import { authClient } from "@/lib/auth-client";-import { isHostedClientAuthMode } from "@/lib/auth-mode";+import { isHostedClientAuthMode, usesBetterAuthClient } from "@/lib/auth-mode";import { getSignInSearch, normalizeAuthRedirect } from "@/lib/auth-redirect";import { z } from "zod";@@ -26,6 +26,9 @@ function ForgotPasswordPage() {const search = Route.useSearch();const redirectTo = normalizeAuthRedirect(search.redirect);const isHostedMode = isHostedClientAuthMode();+ // Self-hosted accounts have no email transport; the operator resets+ // passwords with the admin command.+ const isOperatorReset = !isHostedMode && usesBetterAuthClient();const form = useAppForm({defaultValues: {@@ -85,7 +88,9 @@ function ForgotPasswordPage() {? undefined: isHostedMode? "Enter your email and we'll send you a password reset link."- : "Password reset isn't available right now."+ : isOperatorReset+ ? "Ask your server administrator to reset your password."+ : "Password reset isn't available right now."}footer={<p className="text-sm">diff --git a/src/routes/r/$reportId.ts b/src/routes/r/$reportId.tsindex ef02ce72..38348a4f 100644--- a/src/routes/r/$reportId.ts+++ b/src/routes/r/$reportId.ts@@ -1,6 +1,6 @@import { env } from "cloudflare:workers";import { createFileRoute } from "@tanstack/react-router";-import { isHostedAuthMode } from "@/lib/auth-mode";+import { usesBetterAuth } from "@/lib/auth-mode";import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve";import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";@@ -29,11 +29,12 @@ async function handleReportRequest(try {context = await resolveUserContextFromHeaders(request.headers);} catch (error) {- // Only a missing session is answered here, and only in hosted mode. A- // config or session-store failure must not masquerade as "you are logged- // out", and the self-hosted modes have no sign-in page to complete.+ // Only a missing session is answered here, and only where the app has+ // its own sign-in page. A config or session-store failure must not+ // masquerade as "you are logged out", and the delegated self-hosted modes+ // have no sign-in page to complete.if (asAppError(error)?.code !== "UNAUTHENTICATED") throw error;- if (!isHostedAuthMode(env.AUTH_MODE)) {+ if (!usesBetterAuth(env.AUTH_MODE)) {return textResponse("Sign in to read this report.", 401);}// The most likely real entry: someone opening a report link in a browserdiff --git a/src/server.ts b/src/server.tsindex a3615db2..7574c700 100644--- a/src/server.ts+++ b/src/server.ts@@ -11,7 +11,12 @@ import { reconcileStaleAudits } from "@/server/features/audit/services/auditRecoimport { sendFirstAuditEmails } from "@/server/features/audit/services/firstAuditEmails";import { getOrCreateOrganizationCustomer } from "@/server/billing/subscription";import { isHostedServerAuthMode } from "@/server/lib/runtime-env";-import { getAuthMode, isHostedAuthMode } from "@/lib/auth-mode";+import {+ getAuthMode,+ isHostedAuthMode,+ setRuntimeAuthMode,+ usesBetterAuth,+} from "@/lib/auth-mode";import {createOpenSeoOAuthProvider,type OpenSeoOAuthEnv,@@ -27,6 +32,9 @@ import { sweepDubReferredOrganizations } from "@/server/referrals/dub";import { maybeSendSelfHostHeartbeat } from "@/server/lib/self-host-telemetry";import { handleGdprStorageErasure } from "@/server/gdpr/storage-erasure";import { GDPR_STORAGE_ERASURE_PATH } from "@/shared/gdpr-erasure";+import { handleOperatorRequest } from "@/server/standalone/admin";+import { handleImport, isLegacyImportActive } from "@/server/standalone/import";+import { hasOperatorSecret } from "@/server/standalone/operator-auth";const startHandler = createStartHandler(defaultStreamHandler);@@ -135,16 +143,31 @@ function fetch(return withPgClient(() => Promise.resolve(handleFetch(request, env, ctx)));}-function handleFetch(+async function handleFetch(request: Request,env: Env,ctx: ExecutionContext,-): Response | Promise<Response> {+): Promise<Response> {const authMode = getAuthMode(env.AUTH_MODE);+ setRuntimeAuthMode(env.AUTH_MODE);const publicRequest = requestWithPublicOrigin(request);const pathname = new URL(publicRequest.url).pathname;ctx.waitUntil(maybeSendSelfHostHeartbeat(pathname));+ // Standalone Docker operator tooling (account commands, legacy import).+ // Both handlers answer 404 without the operator secret; the block is also+ // what keeps hosted from paying a KV read per request.+ if (hasOperatorSecret()) {+ if (pathname === "/api/standalone/import")+ return handleImport(publicRequest);+ if (await isLegacyImportActive()) {+ return new Response("Data import in progress", { status: 503 });+ }+ if (pathname === "/api/standalone/admin") {+ return handleOperatorRequest(publicRequest);+ }+ }+if (pathname === "/api/ai-visibility/download") {return import("@/server/features/ai-visibility/services/aiVisibilityExport").then(({ handleAiVisibilityDownload }) =>@@ -160,11 +183,11 @@ function handleFetch(return routeChatAgents(publicRequest, env);}- if (isHostedAuthMode(authMode)) {- if (pathname === AUTUMN_WEBHOOK_PATH) {- return handleAutumnWebhookRequest(publicRequest);- }+ if (isHostedAuthMode(authMode) && pathname === AUTUMN_WEBHOOK_PATH) {+ return handleAutumnWebhookRequest(publicRequest);+ }+ if (usesBetterAuth(authMode)) {return openSeoOAuthProvider.fetch(publicRequest,env as OpenSeoOAuthEnv,@@ -204,13 +227,19 @@ export default {env: Env,_ctx: ExecutionContext,) {+ // A legacy Docker import owns the database until it finishes.+ if (hasOperatorSecret() && (await isLegacyImportActive())) return;if (controller.cron === MCP_OAUTH_PURGE_CRON) {- // Only hosted mode runs the OAuth provider (and has OAUTH_KV bound).- if (isHostedAuthMode(getAuthMode(env.AUTH_MODE))) {+ const authMode = getAuthMode(env.AUTH_MODE);+ // Only the modes with their own accounts run the OAuth provider (and+ // have OAUTH_KV bound).+ if (usesBetterAuth(authMode)) {const result = await openSeoOAuthProvider.purgeExpiredData(env as OpenSeoOAuthEnv,);console.log("[mcp-oauth] purged expired OAuth data", result);+ }+ if (isHostedAuthMode(authMode)) {// Daily referral-sale sweep: catches paid Autumn invoices the// billing.updated webhook path misses (renewals, one-time top-ups).try {diff --git a/src/server/auth/repositories/AuthRepository.ts b/src/server/auth/repositories/AuthRepository.tsindex f3ddcaf4..fef2f052 100644--- a/src/server/auth/repositories/AuthRepository.ts+++ b/src/server/auth/repositories/AuthRepository.ts@@ -275,6 +275,11 @@ async function hasPendingInvitationForEmail(email: string) {return pending !== undefined;}+async function hasAnyUser() {+ const [first] = await db.select({ id: authUser.id }).from(authUser).limit(1);+ return first !== undefined;+}+async function getLastActiveOrganizationId(userId: string) {const record = await db.query.user.findFirst({columns: { lastActiveOrganizationId: true },@@ -353,6 +358,7 @@ export const AuthRepository = {getHostedUserNames,getOrganizationOwner,hasPendingInvitationForEmail,+ hasAnyUser,isAnalyticsOptedOut,saveSignupCampaign,} as const;diff --git a/src/server/features/audit/services/AuditService.crawlerAccess.test.ts b/src/server/features/audit/services/AuditService.crawlerAccess.test.tsindex dbff50f8..c0c29ea8 100644--- a/src/server/features/audit/services/AuditService.crawlerAccess.test.ts+++ b/src/server/features/audit/services/AuditService.crawlerAccess.test.ts@@ -36,7 +36,9 @@ vi.mock("cloudflare:workers", () => ({}));vi.mock("@/server/lib/runtime-env", () => ({isHostedServerAuthMode: vi.fn().mockResolvedValue(false),- getOptionalEnvValue: vi.fn().mockResolvedValue(SECRET),+ getOptionalEnvValue: vi.fn(async (name: string) =>+ name === "CRAWLER_ACCESS_SECRET" ? SECRET : undefined,+ ),}));vi.mock("@/server/email/onboarding-drip", () => ({markOnboardingMilestone: vi.fn(),diff --git a/src/server/features/reports/repositories/ReportRepository.query.test.ts b/src/server/features/reports/repositories/ReportRepository.query.test.tsindex 5d682a9e..07e12de5 100644--- a/src/server/features/reports/repositories/ReportRepository.query.test.ts+++ b/src/server/features/reports/repositories/ReportRepository.query.test.ts@@ -16,6 +16,7 @@ const mocks = vi.hoisted(() => ({ captureServerEvent: vi.fn() }));vi.mock("cloudflare:workers", () => ({ env: { DATABASE_PROVIDER: "d1" } }));vi.mock("@/server/lib/runtime-env", () => ({isHostedServerAuthMode: async () => true,+ usesBetterAuthServer: async () => true,}));vi.mock("@/server/lib/posthog", () => ({captureServerEvent: mocks.captureServerEvent,diff --git a/src/server/features/reports/services/ReportService.test.ts b/src/server/features/reports/services/ReportService.test.tsindex 72cf2af5..75c05312 100644--- a/src/server/features/reports/services/ReportService.test.ts+++ b/src/server/features/reports/services/ReportService.test.ts@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { isHostedServerAuthMode } from "@/server/lib/runtime-env";+import { usesBetterAuthServer } from "@/server/lib/runtime-env";import { formatCount } from "@/shared/format";import {REPORT_MAX_BYTES_PER_ORG,@@ -24,7 +24,7 @@ vi.mock("@/server/features/reports/repositories/ReportRepository", () => ({}));vi.mock("@/server/lib/posthog", () => ({ captureServerEvent: vi.fn() }));vi.mock("@/server/lib/runtime-env", () => ({- isHostedServerAuthMode: vi.fn(),+ usesBetterAuthServer: vi.fn(),}));const html = "<!doctype html><html><body>Hi</body></html>";@@ -210,7 +210,7 @@ describe("sharing", () => {beforeEach(() => {mocks.setShareToken.mockResolvedValue(true);- vi.mocked(isHostedServerAuthMode).mockResolvedValue(true);+ vi.mocked(usesBetterAuthServer).mockResolvedValue(true);mocks.getReport.mockResolvedValue(storedReport);});@@ -265,7 +265,7 @@ describe("sharing", () => {// A self-hosted deployment cannot serve the link, so a minted token would be// a link that silently does nothing. Refused before the report is even read.it("refuses to mint when the deployment is not hosted", async () => {- vi.mocked(isHostedServerAuthMode).mockResolvedValue(false);+ vi.mocked(usesBetterAuthServer).mockResolvedValue(false);await expect(share()).rejects.toThrow("Sharing is only available on hosted OpenSEO.",diff --git a/src/server/features/reports/shareAccess.ts b/src/server/features/reports/shareAccess.tsindex 5a546fda..d78ef329 100644--- a/src/server/features/reports/shareAccess.ts+++ b/src/server/features/reports/shareAccess.ts@@ -1,4 +1,4 @@-import { isHostedServerAuthMode } from "@/server/lib/runtime-env";+import { usesBetterAuthServer } from "@/server/lib/runtime-env";// The two server-side gates every share path runs: is sharing on at all, and// does this path segment even look like a token. Server-only, so reading the@@ -6,13 +6,14 @@ import { isHostedServerAuthMode } from "@/server/lib/runtime-env";// client half of sharing is `sharePath` in @/shared/report-share./**- * Sharing is a hosted-only feature: a self-hosted deployment is behind- * Cloudflare Access or has no auth at all, and neither can serve a link to a+ * Sharing needs a deployment with its own accounts (hosted and password modes): a+ * public origin and a sign-in page. The other self-hosted modes are behind+ * Cloudflare Access or have no auth at all, and neither can serve a link to a* reader who is not signed in. One predicate, so the mint, the share page and* the raw endpoint cannot disagree.*/export function sharesEnabled(): Promise<boolean> {- return isHostedServerAuthMode();+ return usesBetterAuthServer();}/**diff --git a/src/server/features/sam/SamChatAgent.ts b/src/server/features/sam/SamChatAgent.tsindex f85dfbc9..d432c72c 100644--- a/src/server/features/sam/SamChatAgent.ts+++ b/src/server/features/sam/SamChatAgent.ts@@ -13,8 +13,7 @@ import type {} from "@cloudflare/think";import { clearChatTerminal } from "agents/chat";import { createCompactFunction } from "agents/experimental/memory/utils";-import { generateText } from "ai";-import type { UIMessage } from "ai";+import { generateText, type UIMessage } from "ai";import { z } from "zod";import { eq } from "drizzle-orm";import { db, withPgClient } from "@/db";@@ -36,6 +35,7 @@ import { buildChatAgentModel } from "@/server/lib/openrouter";import {getEnvValueSync,isHostedServerAuthMode,+ usesBetterAuthServer,} from "@/server/lib/runtime-env";import {checkUsageCreditsDepleted,@@ -351,16 +351,17 @@ export class SamChatAgent extends Think {const baseUrl =(await this.ctx.storage.get<string>(PUBLIC_ORIGIN_KEY)) ??"https://app.openseo.so";- // Delegated/self-host orgs have no member rows — implicit owner. In- // hosted mode a missing member row means the user was removed from the- // workspace; fail closed instead of letting the open socket keep- // owner-level tools (WebSockets authorize at connect time only, so this- // per-turn check is what actually revokes a removed member's chat).+ // Delegated/self-host orgs have no member rows — implicit owner. With+ // real accounts (hosted and password modes) a missing member row means the+ // user was removed from the workspace; fail closed instead of letting+ // the open socket keep owner-level tools (WebSockets authorize at+ // connect time only, so this per-turn check is what actually revokes a+ // removed member's chat).const membership = await AuthRepository.getMembership(ctx.row.userId,organizationId,);- if (hosted && !membership) {+ if ((await usesBetterAuthServer()) && !membership) {turn.refusal = "no_access";return this.refusalTurn("You no longer have access to this organization, so I can't continue this chat.",diff --git a/src/server/lib/audit/discovery.ts b/src/server/lib/audit/discovery.tsindex b6d87ca8..866e1fde 100644--- a/src/server/lib/audit/discovery.ts+++ b/src/server/lib/audit/discovery.ts@@ -6,6 +6,7 @@ import { XMLParser } from "fast-xml-parser";import { readBodyCapped } from "./html-response";import { isSameOrigin, normalizeUrl } from "./url-utils";import { isCrawlableUrl } from "./url-policy";+import { publicFetch } from "@/server/lib/public-fetch";import { createRateLimitWait, type RateLimitWait } from "./crawl-throttle";import type { CrawlerAccess } from "@/shared/crawler-access";import {@@ -83,7 +84,7 @@ async function fetchFollowingRedirects(const deadline = Date.now() + timeoutMs;let current = url;for (let hop = 0; hop <= MAX_DISCOVERY_REDIRECT_HOPS; hop++) {- const response = await fetch(current, {+ const response = await publicFetch(current, {headers: await auditRequestHeaders(current, access),redirect: "manual",signal: AbortSignal.timeout(Math.max(1, deadline - Date.now())),diff --git a/src/server/lib/audit/url-policy.ts b/src/server/lib/audit/url-policy.tsindex 7709aa61..527c4d8a 100644--- a/src/server/lib/audit/url-policy.ts+++ b/src/server/lib/audit/url-policy.ts@@ -1,4 +1,5 @@import { AppError } from "@/server/lib/errors";+import { publicFetch } from "@/server/lib/public-fetch";import type { CrawlerAccess } from "@/shared/crawler-access";import { auditRequestHeaders } from "@/server/lib/audit/web-bot-auth";@@ -280,7 +281,7 @@ export async function resolveStartUrlRedirects(for (let hop = 0; hop < START_URL_REDIRECT_HOPS; hop++) {let response: Response;try {- response = await fetch(current, {+ response = await publicFetch(current, {method: "HEAD",redirect: "manual",headers: await auditRequestHeaders(current, access),diff --git a/src/server/lib/public-fetch.ts b/src/server/lib/public-fetch.tsnew file mode 100644index 00000000..0169ed17--- /dev/null+++ b/src/server/lib/public-fetch.ts@@ -0,0 +1,25 @@+import { getOptionalEnvValue } from "@/server/lib/runtime-env";++/**+ * Fetch a user-supplied URL. On Workers the `global_fetch_strictly_public`+ * compatibility flag already refuses private and reserved addresses, so this+ * is plain `fetch`. The standalone Docker edition has no such guarantee and+ * sets CRAWL_GATEWAY_URL instead: the request then goes through its+ * DNS-pinning gateway (scripts/celld/runtime/crawl-gateway.mjs), so a target+ * cannot rebind to an internal address between resolution and connect.+ * Callers follow redirects themselves, re-validating each hop and sending it+ * back through here, so the gateway request is always manual.+ */+export async function publicFetch(+ input: string | URL,+ init: RequestInit = {},+): Promise<Response> {+ const gateway = await getOptionalEnvValue("CRAWL_GATEWAY_URL");+ if (!gateway) return fetch(input, init);+ const secret = await getOptionalEnvValue("CRAWL_GATEWAY_SECRET");+ if (!secret) throw new Error("CRAWL_GATEWAY_SECRET is required");+ const headers = new Headers(init.headers);+ headers.set("x-crawl-url", new URL(input).href);+ headers.set("x-crawl-secret", secret);+ return fetch(gateway, { ...init, headers, redirect: "manual" });+}diff --git a/src/server/lib/runtime-env.ts b/src/server/lib/runtime-env.tsindex cf8748f1..73287eac 100644--- a/src/server/lib/runtime-env.ts+++ b/src/server/lib/runtime-env.ts@@ -1,4 +1,4 @@-import { isHostedAuthMode } from "@/lib/auth-mode";+import { isHostedAuthMode, usesBetterAuth } from "@/lib/auth-mode";let workersEnvPromise: Promise<Record<string, unknown> | null> | null = null;@@ -41,6 +41,10 @@ export async function isHostedServerAuthMode(): Promise<boolean> {return isHostedAuthMode(await getOptionalEnvValue("AUTH_MODE"));}+export async function usesBetterAuthServer(): Promise<boolean> {+ return usesBetterAuth(await getOptionalEnvValue("AUTH_MODE"));+}+async function getWorkersEnv(): Promise<Record<string, unknown> | null> {if (!workersEnvPromise) {workersEnvPromise = loadWorkersEnv();diff --git a/src/server/lib/scrape.test.ts b/src/server/lib/scrape.test.tsindex 8836d657..318c44bb 100644--- a/src/server/lib/scrape.test.ts+++ b/src/server/lib/scrape.test.ts@@ -2,7 +2,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { readPages, readSite } from "@/server/lib/scrape";vi.mock("@/server/lib/runtime-env", () => ({- getOptionalEnvValue: async () => "context-test-key",+ getOptionalEnvValue: async (name: string) =>+ name === "CONTEXT_API_KEY" ? "context-test-key" : undefined,}));describe("readSite SSRF guard", () => {diff --git a/src/server/lib/scrape.ts b/src/server/lib/scrape.tsindex 0062f90f..a65f4d7b 100644--- a/src/server/lib/scrape.ts+++ b/src/server/lib/scrape.ts@@ -5,6 +5,7 @@// gracefully (less text); a Browser Rendering upgrade can slot in behind this// same interface later.+import { publicFetch } from "@/server/lib/public-fetch";import { normalizeAndValidateStartUrl } from "@/server/lib/audit/url-policy";import { RenderedPageService } from "@/server/lib/audit/rendered-page";import { getOptionalEnvValue } from "@/server/lib/runtime-env";@@ -67,7 +68,7 @@ async function fetchText(let current = url;try {for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {- const response = await fetch(current, {+ const response = await publicFetch(current, {headers: { "user-agent": USER_AGENT, accept: "text/html,*/*" },// Manual redirects so we can re-validate each hop against the SSRF guard;// redirect:"follow" would let a 30x to an internal host bypass it.diff --git a/src/server/lib/setup-status.ts b/src/server/lib/setup-status.tsindex 71932d62..a1cd53a8 100644--- a/src/server/lib/setup-status.ts+++ b/src/server/lib/setup-status.ts@@ -27,6 +27,7 @@ const CHECK_ENV_VARS = ["DATAFORSEO_API_KEY","GOOGLE_CLIENT_ID","GOOGLE_CLIENT_SECRET",+ "BETTER_AUTH_URL","BETTER_AUTH_SECRET","OPENROUTER_API_KEY","CONTEXT_API_KEY",diff --git a/src/server/mcp/public-origin.test.ts b/src/server/mcp/public-origin.test.tsindex 0473aa6a..71772a0f 100644--- a/src/server/mcp/public-origin.test.ts+++ b/src/server/mcp/public-origin.test.ts@@ -1,7 +1,41 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { getPublicOrigin, requestWithPublicOrigin } from "./public-origin";+const { env } = vi.hoisted(() => ({ env: {} as Record<string, string> }));+vi.mock("cloudflare:workers", () => ({ env }));++afterEach(() => {+ delete env.AUTH_MODE;+ delete env.BETTER_AUTH_URL;+ delete env.OPENSEO_OPERATOR_SECRET;+});+describe("getPublicOrigin", () => {+ it("uses the configured origin, not forwarded headers, in password mode", () => {+ env.AUTH_MODE = "password";+ env.BETTER_AUTH_URL = "https://seo.example.com";+ const request = new Request("http://runtime:8080/mcp", {+ headers: {+ "x-forwarded-proto": "https",+ "x-forwarded-host": "evil.test",+ },+ });++ expect(getPublicOrigin(request)).toBe("https://seo.example.com");+ });++ it("honors a configured origin in no-auth mode only in the standalone edition", () => {+ env.AUTH_MODE = "local_noauth";+ env.BETTER_AUTH_URL = "http://seo.internal:3001";+ const request = new Request("http://192.168.1.10:3001/mcp");++ // The old Docker image: BETTER_AUTH_URL may sit in its .env, no operator secret.+ expect(getPublicOrigin(request)).toBe("http://192.168.1.10:3001");++ env.OPENSEO_OPERATOR_SECRET = "s".repeat(32);+ expect(getPublicOrigin(request)).toBe("http://seo.internal:3001");+ });+it("uses the forwarded public protocol and host for tunneled requests", () => {const request = new Request("http://localhost:3102/api/oauth/consent", {headers: {diff --git a/src/server/mcp/public-origin.ts b/src/server/mcp/public-origin.tsindex 7540329d..ab3f0a69 100644--- a/src/server/mcp/public-origin.ts+++ b/src/server/mcp/public-origin.ts@@ -1,3 +1,7 @@+import { env } from "cloudflare:workers";+import { getAuthMode } from "@/lib/auth-mode";+import { hasOperatorSecret } from "@/server/standalone/operator-auth";+function firstHeaderValue(value: string | null) {return value?.split(",")[0]?.trim() || null;}@@ -8,6 +12,22 @@ function getForwardedProtocol(request: Request) {}export function getPublicOrigin(request: Request) {+ // Behind the standalone Docker edition's Nginx the forwarded host is just+ // the client's Host header, so the configured origin is the trusted one+ // (auth.ts validates BETTER_AUTH_URL when the auth instance is built). The+ // edition's no-auth mode configures the same URL next to its operator+ // secret. The old Docker image forwards its whole .env, so a stray+ // BETTER_AUTH_URL there must not change the origin it has always derived+ // from the request.+ const mode = getAuthMode(env.AUTH_MODE);+ const configured = env.BETTER_AUTH_URL?.trim();+ if (+ mode === "password" ||+ (mode === "local_noauth" && configured && hasOperatorSecret())+ ) {+ return new URL(configured ?? "").origin;+ }+const url = new URL(request.url);if (url.protocol === "https:") {return url.origin;diff --git a/src/server/mcp/tools/report-tools.test.ts b/src/server/mcp/tools/report-tools.test.tsindex 4be2f7d7..9ca7178c 100644--- a/src/server/mcp/tools/report-tools.test.ts+++ b/src/server/mcp/tools/report-tools.test.ts@@ -25,11 +25,13 @@ const mocks = vi.hoisted(() => ({captureServerEvent: vi.fn(),setShareToken: vi.fn(),isHostedServerAuthMode: vi.fn(),+ usesBetterAuthServer: vi.fn(),}));vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/server/lib/runtime-env", () => ({isHostedServerAuthMode: mocks.isHostedServerAuthMode,+ usesBetterAuthServer: mocks.usesBetterAuthServer,}));vi.mock("@/server/features/projects/services/ProjectService", () => ({ProjectService: {@@ -72,6 +74,7 @@ const storedReport = (beforeEach(() => {mocks.isHostedServerAuthMode.mockResolvedValue(true);+ mocks.usesBetterAuthServer.mockResolvedValue(true);mocks.setShareToken.mockResolvedValue(true);mocks.getProjectForOrganization.mockResolvedValue({ id: projectId });mocks.countReports.mockResolvedValue(3);@@ -316,6 +319,7 @@ describe("public report sharing", () => {it("hides unusable share URLs on self-hosted deployments but permits revocation", async () => {mocks.isHostedServerAuthMode.mockResolvedValue(false);+ mocks.usesBetterAuthServer.mockResolvedValue(false);mocks.getReport.mockResolvedValue(storedReport({ shareToken: "a".repeat(32) }),);diff --git a/src/server/mcp/transport-v2.test.ts b/src/server/mcp/transport-v2.test.tsindex 7492a0d5..8d312546 100644--- a/src/server/mcp/transport-v2.test.ts+++ b/src/server/mcp/transport-v2.test.ts@@ -5,6 +5,7 @@ import { z } from "zod";import { createWorkersOAuthMcpProps } from "@/server/mcp/context";import { handleAuthenticatedOpenSeoMcpRequest } from "@/server/mcp/transport";+vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/lib/auth", () => ({getHostedBaseUrl: () => "https://open-seo.test",}));diff --git a/src/server/mcp/transport.test.ts b/src/server/mcp/transport.test.tsindex f0ac6f92..f487785f 100644--- a/src/server/mcp/transport.test.ts+++ b/src/server/mcp/transport.test.ts@@ -21,6 +21,7 @@ const authRepositoryMocks = vi.hoisted(() => ({getMembership: vi.fn(),}));+vi.mock("cloudflare:workers", () => ({ env: {} }));vi.mock("@/server/auth/repositories/AuthRepository", () => ({AuthRepository: authRepositoryMocks,}));diff --git a/src/server/standalone/SamChatAgent.ts b/src/server/standalone/SamChatAgent.tsnew file mode 100644index 00000000..8456cb80--- /dev/null+++ b/src/server/standalone/SamChatAgent.ts@@ -0,0 +1,61 @@+import { SamChatAgent } from "@/server/features/sam/SamChatAgent";+import { importRowsSchema } from "./import-schema";++// Think's conversation storage, as copied by the legacy Docker import.+const LEGACY_HISTORY_TABLES = [+ "assistant_messages",+ "assistant_compactions",+ "assistant_config",+ "assistant_fts",+];++// The standalone build's SAM object: the hosted class plus the operator-only+// RPC the legacy Docker import uses (src/server/standalone/import.ts). Neither+// method is decorated @callable, so clients can never reach them. Import+// preserves the logical conversation tree, compactions and config, without+// restoring pending turns, tool executions or alarms.+export class StandaloneSamChatAgent extends SamChatAgent {+ async legacyHistoryCounts() {+ const counts: Record<string, number> = {};+ for (const table of LEGACY_HISTORY_TABLES) {+ counts[table] = this.ctx.storage.sql+ .exec<{ n: number }>(`SELECT count(*) AS n FROM "${table}"`)+ .one().n;+ }+ return counts;+ }++ async importLegacyHistory(input: unknown) {+ const data = importRowsSchema.parse(input);+ if (!LEGACY_HISTORY_TABLES.includes(data.table)) {+ throw new Error("Unsupported history table");+ }+ const columns = this.ctx.storage.sql+ .exec<{ name: string }>(`PRAGMA table_info("${data.table}")`)+ .toArray();+ if (+ data.columns.some(+ (name) => !columns.some((column) => column.name === name),+ )+ ) {+ throw new Error("History schema mismatch");+ }+ this.ctx.storage.transactionSync(() => {+ for (const row of data.rows) {+ if (row.length !== data.columns.length) {+ throw new Error("History row mismatch");+ }+ if (data.table === "assistant_fts") {+ this.ctx.storage.sql.exec(+ "DELETE FROM assistant_fts WHERE id = ?",+ row[data.columns.indexOf("id")],+ );+ }+ this.ctx.storage.sql.exec(+ `INSERT OR REPLACE INTO "${data.table}" (${data.columns.map((name) => `"${name}"`).join(",")}) VALUES (${data.columns.map(() => "?").join(",")})`,+ ...row,+ );+ }+ });+ }+}diff --git a/src/server/standalone/admin.ts b/src/server/standalone/admin.tsnew file mode 100644index 00000000..02b018d9--- /dev/null+++ b/src/server/standalone/admin.ts@@ -0,0 +1,148 @@+import { and, eq } from "drizzle-orm";+import { db } from "@/db";+import { member, organization, user } from "@/db/schema";+import { z } from "zod";+import { getAuth } from "@/lib/auth";+import { usesBetterAuthServer } from "@/server/lib/runtime-env";+import { isOperatorRequest } from "./operator-auth";++const commandSchema = z.discriminatedUnion("command", [+ z.object({+ command: z.literal("claim-legacy-user"),+ userId: z.string().min(1),+ organizationId: z.string().min(1),+ email: z+ .string()+ .email()+ .transform((s) => s.toLowerCase()),+ password: z.string().min(8).max(128),+ }),+ z.object({+ command: z.literal("create-user"),+ email: z+ .string()+ .email()+ .transform((s) => s.toLowerCase()),+ name: z.string().trim().min(1),+ password: z.string().min(8).max(128),+ }),+ z.object({+ command: z.literal("reset-password"),+ email: z+ .string()+ .email()+ .transform((s) => s.toLowerCase()),+ password: z.string().min(8).max(128),+ }),+]);++export async function handleOperatorRequest(+ request: Request,+): Promise<Response> {+ if (request.method !== "POST" || !isOperatorRequest(request.headers)) {+ return new Response("Not found", { status: 404 });+ }+ if (!(await usesBetterAuthServer())) {+ return Response.json(+ {+ error:+ "This installation runs without accounts (AUTH_MODE=local_noauth). Set AUTH_MODE=password and re-run initialization to manage accounts.",+ },+ { status: 409 },+ );+ }+ const parsed = commandSchema.safeParse(+ await request.json().catch(() => null),+ );+ if (!parsed.success)+ return Response.json({ error: "Invalid account command" }, { status: 400 });+ const command = parsed.data;+ const auth = getAuth();+ try {+ if (command.command === "create-user") {+ const result = await auth.api.signUpEmail({+ headers: request.headers,+ body: {+ name: command.name,+ email: command.email,+ password: command.password,+ },+ });+ return Response.json({ id: result.user.id, email: result.user.email });+ }+ const context = await auth.$context;+ if (command.command === "claim-legacy-user") {+ const [existing] = await db+ .select()+ .from(user)+ .where(eq(user.id, command.userId))+ .limit(1);+ const [workspace] = await db+ .select({ id: organization.id })+ .from(organization)+ .where(eq(organization.id, command.organizationId))+ .limit(1);+ if (!existing || !workspace)+ return Response.json(+ { error: "Imported user or organization not found" },+ { status: 404 },+ );+ await context.internalAdapter.updateUser(existing.id, {+ email: command.email,+ emailVerified: false,+ });+ const [membership] = await db+ .select({ id: member.id })+ .from(member)+ .where(+ and(+ eq(member.userId, existing.id),+ eq(member.organizationId, workspace.id),+ ),+ )+ .limit(1);+ if (membership)+ await db+ .update(member)+ .set({ role: "owner" })+ .where(eq(member.id, membership.id));+ else+ await db.insert(member).values({+ id: crypto.randomUUID(),+ userId: existing.id,+ organizationId: workspace.id,+ role: "owner",+ createdAt: new Date(),+ });+ await db+ .update(user)+ .set({ lastActiveOrganizationId: workspace.id })+ .where(eq(user.id, existing.id));+ }++ const found = await context.internalAdapter.findUserByEmail(command.email, {+ includeAccounts: true,+ });+ if (!found)+ return Response.json({ error: "Account not found" }, { status: 404 });+ const password = await context.password.hash(command.password);+ if (found.accounts.some((account) => account.providerId === "credential")) {+ await context.internalAdapter.updatePassword(found.user.id, password);+ } else {+ await context.internalAdapter.createAccount({+ userId: found.user.id,+ providerId: "credential",+ accountId: found.user.id,+ password,+ });+ }+ await context.internalAdapter.deleteUserSessions(found.user.id);+ return Response.json({ id: found.user.id, email: found.user.email });+ } catch (error) {+ console.error("[account-admin] Account command failed", error);+ return Response.json(+ { error: "Account command failed; check the server logs" },+ { status: 400 },+ );+ }+}diff --git a/src/server/standalone/import-schema.ts b/src/server/standalone/import-schema.tsnew file mode 100644index 00000000..86d2cf6a--- /dev/null+++ b/src/server/standalone/import-schema.ts@@ -0,0 +1,8 @@+import { z } from "zod";+export const identifier = z.string().regex(/^[a-zA-Z][a-zA-Z0-9_]*$/);+const value = z.union([z.string(), z.number().finite(), z.null()]);+export const importRowsSchema = z.object({+ table: identifier,+ columns: z.array(identifier).min(1).max(100),+ rows: z.array(z.array(value)).max(100),+});diff --git a/src/server/standalone/import.ts b/src/server/standalone/import.tsnew file mode 100644index 00000000..d9fac7bc--- /dev/null+++ b/src/server/standalone/import.ts@@ -0,0 +1,145 @@+import { getAgentByName } from "agents";+import { env } from "cloudflare:workers";+import { z } from "zod";+import { runD1ImportBatch } from "@/db/runBatch";+import { identifier, importRowsSchema } from "./import-schema";+import { isOperatorRequest } from "./operator-auth";+import type { StandaloneSamChatAgent } from "./SamChatAgent";+const requestSchema = z.discriminatedUnion("command", [+ z.object({+ command: z.literal("begin"),+ manifestHash: z.string().regex(/^[a-f0-9]{64}$/),+ }),+ z.object({ command: z.literal("rows"), ...importRowsSchema.shape }),+ z.object({+ command: z.literal("sam"),+ sessionId: z.string().min(1),+ ...importRowsSchema.shape,+ }),+ z.object({ command: z.literal("sam-counts"), sessionId: z.string().min(1) }),+ z.object({ command: z.literal("counts") }),+ z.object({ command: z.literal("finish") }),+]);+const excluded = new Set([+ "session",+ "verification",+ "apikey",+ "rate_limit",+ "d1_migrations",+]);+const marker = "standalone:legacy-import";++// While a legacy Docker import runs, nothing else may touch the database.+export async function isLegacyImportActive(): Promise<boolean> {+ const state = await env.KV.get(marker);+ return Boolean(state && !state.startsWith("complete:"));+}++export async function handleImport(request: Request): Promise<Response> {+ if (request.method !== "POST" || !isOperatorRequest(request.headers))+ return new Response("Not found", { status: 404 });+ if (new URL(request.url).searchParams.get("artifact")) {+ const state = await env.KV.get(marker);+ if (!state || state.startsWith("complete:"))+ return new Response("No active import", { status: 409 });+ const key = request.headers.get("x-artifact-key");+ if (!key) return new Response("Missing artifact key", { status: 400 });+ const metadata = z+ .object({+ httpMetadata: z.record(z.string(), z.string()).optional(),+ customMetadata: z.record(z.string(), z.string()).optional(),+ })+ .parse(JSON.parse(request.headers.get("x-artifact-metadata") ?? "{}"));+ const bytes = await request.arrayBuffer();+ if (bytes.byteLength > 20 * 1024 * 1024)+ return new Response("Artifact exceeds 20 MiB", { status: 413 });+ const hash = await crypto.subtle.digest("SHA-256", bytes);+ const digest = Array.from(new Uint8Array(hash), (byte) =>+ byte.toString(16).padStart(2, "0"),+ ).join("");+ if (digest !== request.headers.get("x-artifact-sha256"))+ return new Response("Artifact checksum mismatch", { status: 400 });+ const { cacheExpiry, ...httpMetadata } = metadata.httpMetadata ?? {};+ await env.R2.put(decodeURIComponent(key), bytes, {+ customMetadata: metadata.customMetadata,+ httpMetadata: {+ ...httpMetadata,+ ...(cacheExpiry+ ? { cacheExpiry: z.coerce.date().parse(cacheExpiry) }+ : {}),+ },+ });+ return Response.json({ ok: true });+ }+ const input = requestSchema.parse(await request.json());+ const state = await env.KV.get(marker);+ if (input.command === "begin") {+ if (state === input.manifestHash) return Response.json({ resumed: true });+ if (+ state ||+ (await env.DB.prepare('SELECT id FROM "user" LIMIT 1').first()) ||+ (await env.DB.prepare("SELECT id FROM projects LIMIT 1").first())+ )+ return new Response("Import requires a fresh database", { status: 409 });+ await env.KV.put(marker, input.manifestHash);+ return Response.json({ ok: true });+ }+ if (!state || state.startsWith("complete:"))+ return new Response("No active import", { status: 409 });+ if (input.command === "finish") {+ await env.KV.put(marker, `complete:${state}`);+ return Response.json({ ok: true });+ }+ if (input.command === "sam" || input.command === "sam-counts") {+ const session = await env.DB.prepare(+ "SELECT id FROM sam_sessions WHERE id = ?",+ )+ .bind(input.sessionId)+ .first();+ if (!session) return new Response("Unknown conversation", { status: 400 });+ // env.d.ts declares the DO bindings untyped (ambient contexts can't import+ // the classes); narrow here so the import RPCs are typed.+ const namespace =+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the binding is declared as this class in wrangler.standalone.json+ env.SAM_CHAT as unknown as DurableObjectNamespace<StandaloneSamChatAgent>;+ const stub = await getAgentByName(namespace, input.sessionId);+ if (input.command === "sam-counts")+ return Response.json(await stub.legacyHistoryCounts());+ await stub.importLegacyHistory(input);+ return Response.json({ ok: true });+ }+ const tables = await env.DB.prepare(+ "SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_cf_%'",+ ).all<{ name: string }>();+ if (input.command === "counts") {+ const counts: Record<string, number> = {};+ for (const { name } of tables.results) {+ if (!identifier.safeParse(name).success) continue;+ counts[name] =+ (await env.DB.prepare(+ `SELECT count(*) AS n FROM "${name}"`,+ ).first<number>("n")) ?? 0;+ }+ return Response.json(counts);+ }+ if (+ excluded.has(input.table) ||+ !tables.results.some((row) => row.name === input.table)+ )+ return new Response("Unknown or excluded table", { status: 400 });+ const columns = await env.DB.prepare(+ `PRAGMA table_info("${input.table}")`,+ ).all<{ name: string }>();+ if (+ input.columns.some(+ (name) => !columns.results.some((column) => column.name === name),+ ) ||+ input.rows.some((row) => row.length !== input.columns.length)+ )+ return new Response("Schema mismatch", { status: 400 });+ const insert = `INSERT INTO "${input.table}" (${input.columns.map((name) => `"${name}"`).join(",")}) VALUES (${input.columns.map(() => "?").join(",")}) ON CONFLICT DO NOTHING`;+ await runD1ImportBatch(+ input.rows.map((row) => env.DB.prepare(insert).bind(...row)),+ );+ return Response.json({ ok: true });+}diff --git a/src/server/standalone/operator-auth.ts b/src/server/standalone/operator-auth.tsnew file mode 100644index 00000000..a2a088e5--- /dev/null+++ b/src/server/standalone/operator-auth.ts@@ -0,0 +1,31 @@+import { env } from "cloudflare:workers";+import { timingSafeEqual } from "node:crypto";+import { Buffer } from "node:buffer";++const MIN_OPERATOR_SECRET_LENGTH = 32;++// The standalone Docker edition generates this secret at initialization+// (scripts/celld/runtime/configure.mjs) and a Cloudflare self-hoster sets it+// in .env.selfhost when they need the account commands; hosted and the modes+// whose identity comes from outside the app never set it, so everything it+// gates stays off there. A value too short for isOperatorRequest counts as+// unset.+export function hasOperatorSecret(): boolean {+ const secret: unknown = Reflect.get(env, "OPENSEO_OPERATOR_SECRET");+ return (+ typeof secret === "string" && secret.length >= MIN_OPERATOR_SECRET_LENGTH+ );+}++export function isOperatorRequest(headers: Headers | undefined): boolean {+ const secret: unknown = Reflect.get(env, "OPENSEO_OPERATOR_SECRET");+ const supplied = headers?.get("x-openseo-operator-secret");+ if (!hasOperatorSecret() || typeof secret !== "string" || !supplied)+ return false;+ const expectedBytes = Buffer.from(secret);+ const suppliedBytes = Buffer.from(supplied);+ return (+ expectedBytes.length === suppliedBytes.length &&+ timingSafeEqual(expectedBytes, suppliedBytes)+ );+}diff --git a/src/server/standalone/sign-up.test.ts b/src/server/standalone/sign-up.test.tsnew file mode 100644index 00000000..ff160462--- /dev/null+++ b/src/server/standalone/sign-up.test.ts@@ -0,0 +1,44 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { isStandaloneSignUpOpen } from "@/server/standalone/sign-up";++const mocks = vi.hoisted(() => ({+ hasAnyUser: vi.fn(),+ hasPendingInvitationForEmail: vi.fn(),+}));++vi.mock("cloudflare:workers", () => ({ env: {} }));+vi.mock("@/server/auth/repositories/AuthRepository", () => ({+ AuthRepository: mocks,+}));++describe("isStandaloneSignUpOpen", () => {+ beforeEach(() => {+ mocks.hasAnyUser.mockResolvedValue(true);+ mocks.hasPendingInvitationForEmail.mockResolvedValue(false);+ });++ it("lets the first account through on a fresh installation", async () => {+ mocks.hasAnyUser.mockResolvedValue(false);++ await expect(isStandaloneSignUpOpen("[email protected]")).resolves.toBe(+ true,+ );+ });++ it("closes once an account exists", async () => {+ await expect(isStandaloneSignUpOpen("[email protected]")).resolves.toBe(+ false,+ );+ });++ it("stays open for an address with a pending invitation", async () => {+ mocks.hasPendingInvitationForEmail.mockResolvedValue(true);++ await expect(isStandaloneSignUpOpen("[email protected]")).resolves.toBe(+ true,+ );+ expect(mocks.hasPendingInvitationForEmail).toHaveBeenCalledWith(+ "[email protected]",+ );+ });+});diff --git a/src/server/standalone/sign-up.ts b/src/server/standalone/sign-up.tsnew file mode 100644index 00000000..a478e8ca--- /dev/null+++ b/src/server/standalone/sign-up.ts@@ -0,0 +1,40 @@+import { APIError } from "better-auth/api";+import { z } from "zod";+import { AuthRepository } from "@/server/auth/repositories/AuthRepository";+import { isOperatorRequest } from "@/server/standalone/operator-auth";++const signUpBodySchema = z.object({ email: z.string() });++// The standalone Docker edition closes public registration. Two sign-ups are+// still allowed from the browser: the first account on a fresh installation,+// which becomes the administrator, and an address that holds a pending+// invitation, which joins the inviter's organization. Everything else comes+// from the operator command (src/server/standalone/admin.ts).+export async function isFirstAccountOpen(): Promise<boolean> {+ return !(await AuthRepository.hasAnyUser());+}++export async function isStandaloneSignUpOpen(+ email: string | undefined,+): Promise<boolean> {+ if (await isFirstAccountOpen()) return true;+ if (!email) return false;+ return AuthRepository.hasPendingInvitationForEmail(email);+}++// The Better Auth sign-up hook. The operator command, which carries the+// operator secret, may always create an account.+export async function assertStandaloneSignUpOpen(+ headers: Headers | undefined,+ body: unknown,+): Promise<void> {+ if (isOperatorRequest(headers)) return;+ const parsed = signUpBodySchema.safeParse(body);+ if (+ await isStandaloneSignUpOpen(parsed.success ? parsed.data.email : undefined)+ )+ return;+ throw new APIError("FORBIDDEN", {+ message: "Registration is closed. Ask an administrator for an invitation.",+ });+}diff --git a/src/server/workflows/site-audit-workflow-helpers.test.ts b/src/server/workflows/site-audit-workflow-helpers.test.tsindex 2c1ac6b7..149a90e6 100644--- a/src/server/workflows/site-audit-workflow-helpers.test.ts+++ b/src/server/workflows/site-audit-workflow-helpers.test.ts@@ -3,9 +3,12 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { createCrawlThrottle } from "@/server/lib/audit/crawl-throttle";import { crawlPage } from "@/server/workflows/site-audit-workflow-helpers";-// Resolves the request-signing env lookup instantly, so it can't race the-// fake timers below.-vi.mock("cloudflare:workers", () => ({ env: {} }));+// No crawl gateway and no signing key configured: publicFetch is plain fetch+// and requests go unsigned, and both env lookups must settle in microtasks so+// the fake-timer cases below can advance past them.+vi.mock("@/server/lib/runtime-env", () => ({+ getOptionalEnvValue: async () => undefined,+}));const PAGE_URL = "https://example.com/page";const PAGE_HTML =diff --git a/src/server/workflows/site-audit-workflow-helpers.ts b/src/server/workflows/site-audit-workflow-helpers.tsindex 6dfd443c..09e3b1d6 100644--- a/src/server/workflows/site-audit-workflow-helpers.ts+++ b/src/server/workflows/site-audit-workflow-helpers.ts@@ -6,6 +6,7 @@ import type { PageFetchClass } from "@/shared/audit-fetch-class";import { sha256Hex } from "@/server/lib/audit/ids";import { normalizeUrl } from "@/server/lib/audit/url-utils";import type { CrawlThrottle } from "@/server/lib/audit/crawl-throttle";+import { publicFetch } from "@/server/lib/public-fetch";import { crawlerHeadersFor, type CrawlerAccess } from "@/shared/crawler-access";import { auditRequestHeaders } from "@/server/lib/audit/web-bot-auth";@@ -82,7 +83,7 @@ async function fetchPage(// /docs/) need no special handling: normalizeUrl preserves trailing// slashes, so /docs and /docs/ are distinct URLs and the redirect resolves// to its canonical target instead of cycling back to its own source.- const response = await fetch(url, {+ const response = await publicFetch(url, {headers: {Accept: "text/html,application/xhtml+xml",...(await auditRequestHeaders(url, access)),diff --git a/src/serverFunctions/organization.ts b/src/serverFunctions/organization.tsindex 488c4a71..1df24e1f 100644--- a/src/serverFunctions/organization.ts+++ b/src/serverFunctions/organization.ts@@ -3,6 +3,7 @@ import { APIError } from "better-auth/api";import { getRequest } from "@tanstack/react-start/server";import { z } from "zod";import { getAuth, getHostedBaseUrl } from "@/lib/auth";+import { isHostedAuthMode } from "@/lib/auth-mode";import { hasOrgPermission } from "@/lib/org-permissions";import { consumeInvitationSendBudget } from "@/server/auth/invitation-send-limit";import { requireOrgPermission } from "@/server/auth/org-gate";@@ -10,6 +11,7 @@ import { transferOrganizationOwnership } from "@/server/auth/ownership-transfer"import { AuthRepository } from "@/server/auth/repositories/AuthRepository";import { sendHostedInvitationEmail } from "@/server/email/loops";import { AppError } from "@/server/lib/errors";+import { env } from "cloudflare:workers";import { requireAuthenticatedContext } from "@/serverFunctions/middleware";// The client's source of truth for "who am I in this organization": the active@@ -149,11 +151,17 @@ export const sendTeamInvitation = createServerFn({ method: "POST" })memberships.find((membership) => membership.organizationId === context.organizationId,)?.organizationName ?? "Organization";+ const inviteUrl = `${getHostedBaseUrl()}/accept-invitation/${invitation.id}`;++ // Password mode has no email transport: the inviter passes the link on.+ if (!isHostedAuthMode(env.AUTH_MODE)) {+ return { invitationId: invitation.id, inviteUrl };+ }try {await sendHostedInvitationEmail({email: data.email,- inviteUrl: `${getHostedBaseUrl()}/accept-invitation/${invitation.id}`,+ inviteUrl,organizationName,inviterName: inviter?.name?.trim() || context.userEmail,inviterEmail: context.userEmail,@@ -165,7 +173,7 @@ export const sendTeamInvitation = createServerFn({ method: "POST" })throw new AppError("UPSTREAM_UNAVAILABLE");}- return { invitationId: invitation.id };+ return { invitationId: invitation.id, inviteUrl: undefined };});const transferOwnershipSchema = z.object({ memberId: z.string().min(1) });diff --git a/src/standalone-server.ts b/src/standalone-server.tsnew file mode 100644index 00000000..9cf046f8--- /dev/null+++ b/src/standalone-server.ts@@ -0,0 +1,12 @@+// Keep all workflow and object classes in the same celld deployment: celld+// does not support workflow bindings targeting another script.+export {+ default as AuditEngine,+ AuditScratchpad,+ SiteAuditWorkflow,+} from "./audit-worker";+export { RankCheckWorkflow, default } from "./server";+// Same binding and class name as hosted (the SAM_CHAT binding and migrations+// in wrangler.standalone.json), with the legacy-import RPC added.+export { StandaloneSamChatAgent as SamChatAgent } from "./server/standalone/SamChatAgent";+export { AiVisibilityWorkflow } from "./server/workflows/AiVisibilityWorkflow";diff --git a/vite-plugin-lean-worker-bundle.ts b/vite-plugin-lean-worker-bundle.tsindex 5560e35b..4313a260 100644--- a/vite-plugin-lean-worker-bundle.ts+++ b/vite-plugin-lean-worker-bundle.ts@@ -17,8 +17,15 @@ const WORKERS_AI_PROVIDER_STUB = fileURLToPath(* out. `generateBundle` below fails the build if one sneaks back in via a* static import chain.*/-const EAGER_DENYLIST: Array<{ pattern: RegExp; expected: string }> = [+const EAGER_DENYLIST: Array<{+ pattern: RegExp;+ expected: string;+ // Enforced by code splitting rather than by a stub/alias, so it cannot+ // hold in the single-module standalone build (see vite.config.ts).+ requiresCodeSplitting?: boolean;+}> = [{+ requiresCodeSplitting: true,pattern: /node_modules\/autumn-js\//,expected: "lazy-loaded behind the facade in src/server/billing/autumn.ts",},@@ -45,6 +52,7 @@ const EAGER_DENYLIST: Array<{ pattern: RegExp; expected: string }> = ["localize zod errors)",},{+ requiresCodeSplitting: true,// Startup CPU, not memory: every tool's zod input/output schemas and the// SDK's protocol schemas are built at module scope, which pushed the main// worker toward the 400 ms startup CPU limit.@@ -56,6 +64,7 @@ const EAGER_DENYLIST: Array<{ pattern: RegExp; expected: string }> = ["(SamChatAgent.beforeTurn)",},{+ requiresCodeSplitting: true,// Pre-existing boundary from the site-audit engine, guarded here too.pattern: /node_modules\/cheerio\//,expected:@@ -101,7 +110,11 @@ const CLIENT_ENTRY_DENYLIST: Array<{ pattern: RegExp; expected: string }> = [* verbatim, so `generateBundle` escapes what is left in them.*/export function leanWorkerBundle(): Plugin {+ let standalone = false;return {+ configResolved(config) {+ standalone = config.mode === "standalone";+ },name: "lean-worker-bundle",config() {return {@@ -147,7 +160,9 @@ export function leanWorkerBundle(): Plugin {if (environment === "client") {denylist = CLIENT_ENTRY_DENYLIST;} else if (["ssr", "open_seo_audit"].includes(environment)) {- denylist = EAGER_DENYLIST;+ denylist = EAGER_DENYLIST.filter(+ (rule) => !standalone || !rule.requiresCodeSplitting,+ );} else {return;}diff --git a/vite.config.ts b/vite.config.tsindex eb6c87ec..9f64de64 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -5,9 +5,24 @@ import viteReact from "@vitejs/plugin-react";import tailwindcss from "@tailwindcss/vite";import { cloudflare } from "@cloudflare/vite-plugin";import { devtools } from "@tanstack/devtools-vite";+import { createRequire } from "node:module";+import { dirname, join } from "node:path";import { leanWorkerBundle } from "./vite-plugin-lean-worker-bundle.ts";import { mcpWidgets } from "./vite-plugin-mcp-widgets.ts";+const require = createRequire(import.meta.url);+// Better Auth's workerd export selects node:crypto.scrypt, which celld does+// not implement. The standalone build uses the package's portable scrypt+// instead; same parameters, same stored password format.+const portablePassword = join(+ dirname(+ require.resolve("@better-auth/utils/password", {+ paths: [dirname(require.resolve("better-auth"))],+ }),+ ),+ "password.mjs",+);+export default defineConfig(({ mode, command }) => {// Vitest sets mode to "test". Return a config without the Cloudflare and// TanStack Start plugins so unit tests never boot workerd or the SSR dev@@ -45,11 +60,20 @@ export default defineConfig(({ mode, command }) => {env.BETTER_AUTH_URL ? new URL(env.BETTER_AUTH_URL).hostname : undefined,].filter((host): host is string => Boolean(host));const emitSourcemaps = env.POSTHOG_SOURCEMAPS === "true";+ // `vite build --mode standalone` produces the Docker edition: one server+ // module for celld (see deploy/standalone/) instead of the Workers pair.+ const standalone = mode === "standalone";return {// Static files (favicons, manifest) live beside the app code instead of at// the repo root.publicDir: "src/public",+ resolve: {+ tsconfigPaths: true,+ alias: standalone+ ? { "@better-auth/utils/password": portablePassword }+ : undefined,+ },envPrefix: ["VITE_","AUTH_MODE",@@ -95,7 +119,17 @@ export default defineConfig(({ mode, command }) => {},},},- resolve: { tsconfigPaths: true },+ // celld's no_bundle deployment accepts a single JS module plus sibling+ // WASM files, so the standalone server build inlines its dynamic imports.+ environments: standalone+ ? {+ ssr: {+ build: {+ rolldownOptions: { output: { codeSplitting: false } },+ },+ },+ }+ : undefined,plugins: [mcpWidgets(),leanWorkerBundle(),@@ -108,6 +142,7 @@ export default defineConfig(({ mode, command }) => {}): null,cloudflare({+ ...(standalone ? { configPath: "./wrangler.standalone.json" } : {}),inspectorPort: false,viteEnvironment: { name: "ssr" },// The site-audit aux worker builds to dist/open_seo_audit/ and runs@@ -116,15 +151,19 @@ export default defineConfig(({ mode, command }) => {// resolved against it.// AUDIT_BROWSER_RENDERING=true attaches a remote Browser Run binding// to it in dev, for rendered audits without a Context key.- auxiliaryWorkers: [- {- configPath: "./wrangler.audit.jsonc",- config:- command === "serve" && env.AUDIT_BROWSER_RENDERING === "true"- ? { browser: { binding: "BROWSER", remote: true } }- : {},- },- ],+ // The standalone build exports the audit classes from its single+ // module instead (src/standalone-server.ts).+ auxiliaryWorkers: standalone+ ? []+ : [+ {+ configPath: "./wrangler.audit.jsonc",+ config:+ command === "serve" && env.AUDIT_BROWSER_RENDERING === "true"+ ? { browser: { binding: "BROWSER", remote: true } }+ : {},+ },+ ],}),tanstackStart(),viteReact(),diff --git a/web/content/docs/self-hosting/cloudflare.md b/web/content/docs/self-hosting/cloudflare.mdindex 3660d6ac..6b552ffc 100644--- a/web/content/docs/self-hosting/cloudflare.md+++ b/web/content/docs/self-hosting/cloudflare.md@@ -3,7 +3,9 @@ title: "Cloudflare Self-Hosting"description: "Deploy OpenSEO to your own Cloudflare account for internet-facing, multi-device, or team use."----Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything, including the Cloudflare Access login gate. Works on Cloudflare's free plan. JavaScript rendering in site audits needs a paid Workers plan.+Host OpenSEO on Cloudflare for internet-facing self-hosting across multiple devices or with your team. One deploy command provisions everything. Works on Cloudflare's free plan. JavaScript rendering in site audits needs a paid Workers plan.++You sign in with email and password accounts: the first visitor creates the administrator's account, teammates join from invitation links, and MCP clients (Claude, ChatGPT, Codex, Cursor) sign in with the same accounts, with nothing to set up in Cloudflare. The most secure option is to put [Cloudflare Access](#cloudflare-access-the-most-secure-option) in front of the app instead, so Cloudflare checks every request before it reaches OpenSEO. It takes more setup.## Prerequisites@@ -34,15 +36,13 @@ pnpm install## 2) Log in to Cloudflare (once)```bash-pnpm alchemy login # answer yes to "Customize OAuth scopes?" and enable access:write+pnpm alchemy login # the default scopes are enoughpnpm alchemy cloudflare bootstrap # deploys alchemy's state-store Worker to your account```-Already logged in from before without the `access:write` scope? Run `pnpm alchemy login --configure` — a plain repeat login doesn't re-ask about scopes.-## 3) Create `.env.selfhost`-Copy the template and fill in the required values:+Copy the template and set `DATAFORSEO_API_KEY`; everything else is optional:```bashcp deploy/.env.selfhost.example .env.selfhost@@ -54,42 +54,27 @@ cp deploy/.env.selfhost.example .env.selfhostpnpm deploy:selfhost --yes```-This provisions the D1 database, KV namespaces, and R2 bucket, applies the database migrations, deploys the Worker, and creates the Cloudflare Access application protecting it (allowing exactly `ACCESS_ALLOWED_EMAILS`). If the account has no Zero Trust team yet, one is created for you, named after your workers.dev subdomain.+This provisions the D1 database, KV namespaces, and R2 bucket, applies the database migrations, deploys the Workers, and generates the session secret. The secret is kept in Alchemy's state in your account, so later deploys keep everyone signed in.AI Visibility uses your `DATAFORSEO_API_KEY`; tracked questions are sent to DataForSEO and billed directly by the provider. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. Deployment configures background collection and a five-minute cron that dispatches due daily, weekly, or monthly checks. The app shows the collection cost before a check or schedule starts. See the [AI Visibility guide](/docs/ai-visibility).-## 5) Validate setup+## 5) Create your account1. Open the Worker URL printed at the end of the deploy.-2. Sign in with Cloudflare Access.-3. OpenSEO should load after login.--If login fails, re-check `ACCESS_ALLOWED_EMAILS` and redeploy.+2. Create the administrator's account. Do this right after the deploy finishes: registration closes once the first account exists, and until then anyone who finds the URL could claim the installation.+3. OpenSEO loads with a default project. Add your website to get started.-## Connect the MCP server through Cloudflare Access--Use the same Cloudflare Access application that protects your OpenSEO Worker. Managed OAuth is required for MCP clients and is not enabled by default.+## Give teammates access to OpenSEO-1. Open Cloudflare Zero Trust.-2. Go to `Access controls` -> `Applications`.-3. Find your OpenSEO application, then select `Edit`.-4. Go to `Additional settings` -> `OAuth`.-5. Turn on `Managed OAuth`.-6. In `Managed OAuth settings`, allow the redirect URIs your MCP clients use:- - Allow `localhost` / loopback clients for CLI and desktop agents (Codex CLI, Claude Code) that register `http://localhost:PORT/callback`.- - Add HTTPS redirect URIs for web connectors (a path may end in `/*`).- - Without this, clients can't finish [Dynamic Client Registration](https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/managed-oauth/) and log in but expose no tools.-7. Save.+Invite them from Team settings. The app copies an invitation link; the invited address creates its own account from that link and joins your workspace. There is no email delivery, so send the link yourself. Everyone works in one shared workspace and sees the same projects.-MCP clients should connect to:+## Connect MCP clients-```text-https://YOUR_WORKER_HOSTNAME/mcp-```+MCP clients connect to `https://YOUR_WORKER_HOSTNAME/mcp` and sign in with your OpenSEO account, the same way they connect to the hosted service. Follow the [MCP setup guide](/docs/mcp) with your Worker URL in place of the hosted one.-## Give teammates access to OpenSEO+## Forgot a password?-Add the teammate to `ACCESS_ALLOWED_EMAILS` in `.env.selfhost` and redeploy. Everyone allowed through shares one OpenSEO workspace.+There is no email delivery, so an operator resets passwords from a terminal. See [Manage accounts](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#manage-accounts) on GitHub.## Updating to the latest OpenSEO version@@ -99,7 +84,19 @@ pnpm installpnpm deploy:selfhost --yes```+## Cloudflare Access: the most secure option++With `AUTH_MODE=cloudflare_access`, Cloudflare's own login protects the Worker: every request is checked at Cloudflare's edge before it reaches OpenSEO, and only the emails you list get through. It needs an extra login scope, a Zero Trust team (created for you), and Zero Trust settings before MCP clients can connect, so expect more setup. Choose the sign-in mode before your first deploy; the two keep separate user records.++1. In `.env.selfhost`, set `AUTH_MODE=cloudflare_access` and `ACCESS_ALLOWED_EMAILS` (comma-separated).+2. Add the `access:write` scope to your Cloudflare login: run `pnpm alchemy login --configure`, answer yes to "Customize OAuth scopes?", and select `access:write` alongside the defaults.+3. Run `pnpm deploy:selfhost --yes`. The deploy creates the Cloudflare Access application protecting the Worker (allowing exactly `ACCESS_ALLOWED_EMAILS`). If the account has no Zero Trust team yet, one is created for you, named after your workers.dev subdomain.++Open the printed URL and sign in with Cloudflare Access. To add teammates, add them to `ACCESS_ALLOWED_EMAILS` and redeploy. MCP clients need Managed OAuth turned on for the Access application; see [Connect the MCP server through Cloudflare Access](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md#through-cloudflare-access) on GitHub.++Deployments created before password accounts existed have no `AUTH_MODE` in `.env.selfhost`, which still means Cloudflare Access, so they keep working unchanged.+## More guides on GitHub-- [Operations](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): JavaScript rendering for site audits, telemetry, and other day-to-day tasks.+- [Operations](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_OPERATIONS.md): managing accounts, MCP clients, JavaScript rendering for site audits, telemetry, and other day-to-day tasks.- [Legacy deployments](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_CLOUDFLARE_LEGACY.md): maintenance for installs created with the retired Deploy-button or manual Wrangler flows.diff --git a/web/content/docs/self-hosting/docker.md b/web/content/docs/self-hosting/docker.mdindex 17c5a93b..ada8fd91 100644--- a/web/content/docs/self-hosting/docker.md+++ b/web/content/docs/self-hosting/docker.md@@ -1,118 +1,50 @@---title: "Docker Self-Hosting"-description: "Run OpenSEO locally with Docker Compose using the published GHCR image."+description: "Run OpenSEO on your own server or computer with Docker Compose and a prebuilt image."----Run OpenSEO locally with Docker.--In Docker mode, OpenSEO uses `AUTH_MODE=local_noauth` (no auth checks, local admin user `admin@localhost`). Only expose it behind your own auth-protected reverse proxy, tunnel, or private network. For internet-facing self-hosting, use [Cloudflare](/docs/self-hosting/cloudflare) instead.--The default `compose.yaml` uses the published GHCR image:--- `ghcr.io/every-app/open-seo:latest`+Run OpenSEO on your own server or computer with Docker Compose. The image is prebuilt, so OpenSEO is ready a few seconds after it starts. You sign in with email and password accounts: the first visitor creates the administrator's account and teammates join from invitation links.## Prerequisites-- [Docker Desktop](https://www.docker.com/products/docker-desktop/) (or Docker Engine + Docker Compose)+- [Docker Desktop](https://www.docker.com/products/docker-desktop/) (or Docker Engine + Docker Compose), with at least 4 GiB of memory for Docker- A [DataForSEO API key](/docs/self-hosting#dataforseo-api-key-setup)## Quickstart-Clone the repo, then:-```bashgit clone https://github.com/every-app/open-seo.gitcd open-seo-cp .env.example .env+export COMPOSE_FILE=deploy/standalone/compose.yaml+cp deploy/standalone/.env.example deploy/standalone/.env```-Set `DATAFORSEO_API_KEY` in `.env` using the [DataForSEO setup guide](/docs/self-hosting#dataforseo-api-key-setup), then start OpenSEO:--```bash-docker compose up -d-```--Open `http://localhost:<PORT>` (default `3001`). Each container start builds the app and may take 1-2 minutes; follow progress with `docker compose logs -f`.--Optional env values:--- `PORT` (defaults to `3001`)-- `ALLOWED_HOST` (single reverse-proxy hostname to allow in Vite preview)-- `AUTH_MODE=local_noauth` (already set in compose)-- `OPEN_SEO_IMAGE` (defaults to `ghcr.io/every-app/open-seo:latest`)--AI Visibility uses your `DATAFORSEO_API_KEY` and sends tracked questions to DataForSEO. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. You pay providers directly; the app shows the collection cost before a check or schedule starts. Keep the container running for background answers and daily, weekly, or monthly tracking. The built-in scheduler checks for due work every five minutes; no host cron setup is required. See the [AI Visibility guide](/docs/ai-visibility).--If you are putting Docker behind a reverse proxy or a temporary tunnel, remember that Docker self-hosting runs with app auth disabled. Only expose it behind your own auth-protected reverse proxy, tunnel, or private network, and add the public hostname before restarting:--```bash-ALLOWED_HOST=yourdomain.com docker compose up -d-```--You can also persist it in `.env`.--## Telemetry--OpenSEO collects anonymized telemetry for core usage events: heartbeats with aggregate counts (installs, users, projects, feature usage) tied to a random install ID, sent every 5 minutes during the first two hours after install, then at most once daily. Telemetry also includes failed setup check names and statuses, never values or error messages. No URLs, keywords, prompts, emails, or IP-derived location are collected, and idle installs send nothing.--Heartbeats are triggered by requests to the app or MCP server. Requests to `/api/health`, including Docker's automatic health checks, do not trigger telemetry.--To disable it, set `OPENSEO_TELEMETRY_DISABLED=1` (or `DO_NOT_TRACK=1`) in `.env`, then run `docker compose up -d --force-recreate open-seo`.--## Pin to a specific image tag--Set `OPEN_SEO_IMAGE` in `.env` and restart:+In `deploy/standalone/.env`, set `STORAGE_SECRET_KEY` to a unique random value (for example the output of `openssl rand -hex 32`) and `DATAFORSEO_API_KEY` to your key. Then start OpenSEO:```bash-OPEN_SEO_IMAGE=ghcr.io/every-app/open-seo:v1.2.3+docker compose pulldocker compose up -d+docker compose logs -f init```-## Build your own image locally+Wait for `OpenSEO initialized and ready.`, open `http://localhost:3001` and create the administrator's account. Registration closes once that account exists, so create it before you put the installation on the internet.-If you are testing local code changes, build and run a local tag:+To add teammates, invite them from Team settings. The app copies an invitation link; send it yourself, since there is no email delivery.-```bash-docker build -f deploy/docker/Dockerfile -t open-seo:local .-OPEN_SEO_IMAGE=open-seo:local docker compose up -d-```+## Coolify, Portainer and Dokploy-## Common commands+`deploy/standalone/compose.yaml` reads no other files from the repository, so you can paste it into a platform that runs Compose files, with the variables from `deploy/standalone/.env.example`. Point the platform's domain at the `web` service on port 80 and set `BETTER_AUTH_URL` to that `https://` address.-Restart service after env changes:+## Public HTTPS, updates and backups-```bash-docker compose up -d open-seo-```+Set `BETTER_AUTH_URL` to your public `https://` address and put an HTTPS reverse proxy in front of `127.0.0.1:3001`. To update, pull the new image and restart. The full guide covers both, plus backups, password resets and optional features: [Docker self-hosting guide on GitHub](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_DOCKER.md).-Pull latest published image and restart:+AI Visibility uses your `DATAFORSEO_API_KEY` and sends tracked questions to DataForSEO. Set `OPENROUTER_API_KEY` for setup research, Prompt Research, and generated prompt suggestions. You pay providers directly; the app shows the collection cost before a check or schedule starts. Background answers and daily, weekly, or monthly tracking run on their own while the containers are up. See the [AI Visibility guide](/docs/ai-visibility).-```bash-docker compose pull && docker compose up -d-```--Stop:+## Without sign-in (advanced)-```bash-docker compose down-```+`AUTH_MODE=local_noauth` runs OpenSEO without sign-in, as one admin user. Use it only where the network already controls who can reach the app, such as Tailscale, a private network or your own authenticating proxy. See [Without sign-in](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_DOCKER.md#without-sign-in-advanced) on GitHub.-## Health and troubleshooting+## Running the older image?-Startup checks appear in `docker compose logs` before the build. Once running, `/api/health` reports configuration and database status, and `docker compose ps` reports container health.--## Troubleshooting environment variables--To confirm Docker Compose is using the expected environment variables:--```bash-docker compose config-```--Check that `AUTH_MODE=local_noauth`, and that `DATAFORSEO_API_KEY` is the base64 encoded value of your DataForSEO email and API password in this format: `email:password`.--If you changed `.env`, recreate the container so Compose reapplies it:--```bash-docker compose up -d --force-recreate open-seo-```+The older single-container image (`ghcr.io/every-app/open-seo`) keeps getting updates, so nothing breaks. When you are ready, [move to this setup](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_DOCKER.md#move-from-the-old-docker-image); your projects, keywords, rank history, audits and reports come with you. The older image's own instructions, including telemetry settings, are in the [older image guide](https://github.com/every-app/open-seo/blob/main/docs/SELF_HOSTING_DOCKER_LEGACY.md).diff --git a/web/content/docs/self-hosting/index.md b/web/content/docs/self-hosting/index.mdindex 734688c7..6a0c1cd0 100644--- a/web/content/docs/self-hosting/index.md+++ b/web/content/docs/self-hosting/index.md@@ -5,10 +5,12 @@ description: "Run OpenSEO yourself with Docker or Cloudflare, bring your own DatOpenSEO is free and open source. Self-hosting means the app costs $0. You bring your own DataForSEO API key and pay DataForSEO directly for API usage.-There are two self-hosting paths:+There are two self-hosting paths. Both use email and password accounts: the first visitor creates the admin account and teammates join from invitation links.-- **Simple: [Docker](/docs/self-hosting/docker)**, recommended for personal use on your own machine. Easiest way to get started.-- **Advanced: [Cloudflare](/docs/self-hosting/cloudflare)**, for internet-facing self-hosting across multiple devices or with your team. A SaaS-like experience with automatic database backups, and it works on Cloudflare's free plan. Slightly more setup if you're unfamiliar with Cloudflare.+- **[Docker](/docs/self-hosting/docker)**, on your own server or computer. A prebuilt image that is ready in seconds, and works with Compose-based platforms such as Coolify, Portainer and Dokploy.+- **[Cloudflare](/docs/self-hosting/cloudflare)**, with no server to run. One deploy command puts OpenSEO on your own Cloudflare account, with automatic database backups, and it works on Cloudflare's free plan.++For security-conscious setups, you can replace the accounts with your own network controls: Cloudflare Access in front of the Cloudflare deploy, or Docker without sign-in behind Tailscale or a private network.## DataForSEO API key setup@@ -18,8 +20,8 @@ OpenSEO uses [DataForSEO](https://dataforseo.com/?aff=255379) to fetch SEO data.2. Click "Send by email" to get your credentials.3. Copy the longer credentials labelled "Base64" credentials.4. Set this as `DATAFORSEO_API_KEY` in your environment:- - Docker: `.env`- - Cloudflare: as a Worker secret in the dashboard+ - Docker: `deploy/standalone/.env`+ - Cloudflare: `.env.selfhost`- Local development: `.env.local`New DataForSEO accounts include $1 of free credit to test with, and the minimum top-up is $50. See [pricing](/pricing) for cost estimates. Self-hosted costs run slightly lower, since the hosted service adds a 28% fee on DataForSEO requests.diff --git a/wrangler.standalone.json b/wrangler.standalone.jsonnew file mode 100644index 00000000..d2bedaed--- /dev/null+++ b/wrangler.standalone.json@@ -0,0 +1,75 @@+{+ "name": "openseo-standalone",+ "main": "src/standalone-server.ts",+ "compatibility_date": "2025-09-02",+ "compatibility_flags": ["nodejs_compat"],+ "workflows": [+ {+ "name": "site-audit-workflow",+ "binding": "SITE_AUDIT_WORKFLOW",+ "class_name": "SiteAuditWorkflow"+ },+ {+ "name": "rank-check-workflow",+ "binding": "RANK_CHECK_WORKFLOW",+ "class_name": "RankCheckWorkflow"+ },+ {+ "binding": "AI_VISIBILITY_WORKFLOW",+ "name": "ai-visibility-workflow",+ "class_name": "AiVisibilityWorkflow"+ }+ ],+ "durable_objects": {+ "bindings": [+ {+ "name": "SAM_CHAT",+ "class_name": "SamChatAgent"+ },+ {+ "name": "AUDIT_SCRATCHPAD",+ "class_name": "AuditScratchpad"+ }+ ]+ },+ "services": [+ {+ "binding": "AUDIT_ENGINE",+ "service": "openseo-standalone",+ "entrypoint": "AuditEngine"+ }+ ],+ "migrations": [+ {+ "tag": "v1",+ "new_sqlite_classes": ["SamChatAgent", "AuditScratchpad"]+ }+ ],+ "triggers": {+ "crons": ["*/5 * * * *", "17 3 * * *"]+ },+ "kv_namespaces": [+ {+ "binding": "KV",+ "id": "standalone-cache"+ },+ {+ "binding": "OAUTH_KV",+ "id": "standalone-oauth"+ }+ ],+ "d1_databases": [+ {+ "binding": "DB",+ "database_name": "openseo-standalone",+ "database_id": "standalone-db",+ "migrations_dir": "drizzle"+ }+ ],+ "r2_buckets": [+ {+ "binding": "R2",+ "bucket_name": "openseo-standalone"+ }+ ]+}