Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(self-host): DISABLE_WORKSPACE_CREATION env var (MUL-2777) (#3441)
Bohan Jiang90ddfb04e287
diff --git a/.env.example b/.env.exampleindex 97c132f5ab..6d49d89cb3 100644--- a/.env.example+++ b/.env.example@@ -208,6 +208,14 @@ ALLOWED_EMAIL_DOMAINS=# Optional: Only allow these exact email addresses (comma-separated)ALLOWED_EMAILS=+# Set to "true" to disable workspace creation for every caller on this+# instance (#3433). Operators usually leave this unset, bootstrap the+# shared workspace, then flip this to "true" and restart so subsequent+# users join only via invitations and the entire deployment is visible to+# the platform admin. The web UI reads this from /api/config at runtime,+# so toggling requires a backend restart but not a frontend rebuild.+DISABLE_WORKSPACE_CREATION=+# ==================== Analytics (PostHog) ====================# Product analytics events feed the acquisition → activation → expansion funnel.# Leave POSTHOG_API_KEY empty for local dev / self-hosted instances; the serverdiff --git a/SELF_HOSTING.md b/SELF_HOSTING.mdindex 854474f8cd..4c7dfc31f2 100644--- a/SELF_HOSTING.md+++ b/SELF_HOSTING.md@@ -73,7 +73,7 @@ Open http://localhost:3000 in your browser. The Docker self-host stack defaults- **Without email configured:** the verification code is generated server-side and printed to the backend container logs (look for `[DEV] Verification code for ...:`). Useful for one-off testing on a single machine.- **Deterministic local/private testing:** set `APP_ENV=development` and `MULTICA_DEV_VERIFICATION_CODE=888888` in `.env`, then restart the backend. This fixed code is ignored when `APP_ENV=production`.-Changes to `ALLOW_SIGNUP` and `GOOGLE_CLIENT_ID` also take effect after restarting the backend / compose stack. The web UI reads both from `/api/config` at runtime, so no web rebuild is needed.+Changes to `ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, and `GOOGLE_CLIENT_ID` also take effect after restarting the backend / compose stack. The web UI reads all three from `/api/config` at runtime, so no web rebuild is needed. See [Advanced Configuration → Signup Controls](SELF_HOSTING_ADVANCED.md#signup-controls-optional) for the recommended sequence to lock down workspace creation.> **Warning:** do **not** set `MULTICA_DEV_VERIFICATION_CODE` on a publicly reachable instance — anyone who knows an email address can then log in with that fixed code.@@ -268,7 +268,7 @@ The chart defaults to `APP_ENV=production` (set in `values.yaml` under `backend.kubectl -n multica rollout restart deploy/multica-backend```-`ALLOW_SIGNUP` and `GOOGLE_CLIENT_ID` likewise live under `backend.config.*` in `values.yaml`. After `helm upgrade`, the backend pod will roll automatically because the ConfigMap hash changes; the web UI reads both from `/api/config` at runtime, so no web rebuild is needed.+`ALLOW_SIGNUP`, `DISABLE_WORKSPACE_CREATION`, and `GOOGLE_CLIENT_ID` likewise live under `backend.config.*` in `values.yaml` (as `allowSignup`, `disableWorkspaceCreation`, and `googleClientId`). After `helm upgrade`, the backend pod will roll automatically because the ConfigMap hash changes; the web UI reads all three from `/api/config` at runtime, so no web rebuild is needed.> **Warning:** do **not** set `MULTICA_DEV_VERIFICATION_CODE` on a publicly reachable instance — anyone who knows an email address can then log in with that fixed code.diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 6715bf3e9c..473797ad60 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -67,8 +67,20 @@ Changes take effect after restarting the backend / compose stack. The web UI rea| `ALLOW_SIGNUP` | Set to `false` to disable new user signups on a private instance || `ALLOWED_EMAIL_DOMAINS` | Optional comma-separated allowlist of email domains || `ALLOWED_EMAILS` | Optional comma-separated allowlist of exact email addresses |+| `DISABLE_WORKSPACE_CREATION` | Set to `true` to make `POST /api/workspaces` return 403 for every caller — users can only join workspaces they were invited to |-Changes take effect after restarting the backend / compose stack. The web UI reads `ALLOW_SIGNUP` from `/api/config` at runtime, so no web rebuild is needed.+Changes take effect after restarting the backend / compose stack. The web UI reads `ALLOW_SIGNUP` and `DISABLE_WORKSPACE_CREATION` from `/api/config` at runtime, so no web rebuild is needed.++#### Locking down workspace creation++`ALLOW_SIGNUP=false` blocks new accounts from being created, but it does **not** block an already-signed-in user from creating another workspace via `POST /api/workspaces`. On a self-hosted instance where every issue/repo/agent must be visible to the platform admin, set `DISABLE_WORKSPACE_CREATION=true` to close that gap. The recommended bootstrap sequence is:++1. Start the instance with `DISABLE_WORKSPACE_CREATION=false` (the default).+2. Sign in as the admin and create the shared workspace.+3. Set `DISABLE_WORKSPACE_CREATION=true` and restart the backend. Optionally set `ALLOW_SIGNUP=false` at the same time if you also want to block new account creation.+4. Going forward, additional users join via invitation only — the "Create workspace" affordance is hidden in the UI and any direct API call returns 403.++> Note: setting `ALLOW_SIGNUP=false` blocks **all** new account creation, including users who already have a pending invitation. If you need invited users to be able to sign up but not create their own workspaces, keep `ALLOW_SIGNUP=true` (optionally combined with `ALLOWED_EMAIL_DOMAINS` / `ALLOWED_EMAILS`) and only flip `DISABLE_WORKSPACE_CREATION=true`.### File Storage (Optional)diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 32bf09f636..93e03918ac 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -128,6 +128,22 @@ Three allowlist layers combine by priority. **If any layer is set to a non-empty**Invite flows themselves do not check the signup allowlist** — but the invitee must still be able to **sign in** before accepting the invite. If they already have a Multica account (for example from another workspace), they can accept directly, unaffected by the allowlist; **if they have never signed up**, the first step of sign-in (requesting a verification code) still passes through the allowlist check, and an email rejected by `ALLOW_SIGNUP=false` or by `ALLOWED_EMAILS` / `ALLOWED_EMAIL_DOMAINS` **cannot finish signup, and therefore cannot accept the invite**.+## Locking down workspace creation++`ALLOW_SIGNUP=false` blocks new accounts, but it does **not** block an already-signed-in user from creating another workspace via `POST /api/workspaces`. On a self-hosted instance where every issue, repo, and agent must be visible to the platform admin, set `DISABLE_WORKSPACE_CREATION=true` to close that gap.++| Variable | Default | Description |+|---|---|---|+| `DISABLE_WORKSPACE_CREATION` | `false` | When `true`, every call to `POST /api/workspaces` returns `403 workspace creation is disabled for this instance`. The web UI hides every "Create workspace" affordance via `/api/config`. There is no role/owner exception — the gate is global per instance |++Recommended bootstrap sequence:++1. Start the instance with `DISABLE_WORKSPACE_CREATION` unset (the default).+2. Sign in as the admin and create the shared workspace.+3. Set `DISABLE_WORKSPACE_CREATION=true` and restart the backend. From this point on, users join via invitation only.++If you also want to keep `ALLOW_SIGNUP=true` so invited users can finish signup with their first verification code, combine `DISABLE_WORKSPACE_CREATION=true` with `ALLOWED_EMAIL_DOMAINS` / `ALLOWED_EMAILS` to scope which addresses can sign up. Setting `ALLOW_SIGNUP=false` will additionally block pending invitees from creating their account at all — useful only on instances where every member already has a Multica account.+## Rate limiting (optional Redis)Public auth endpoints — `/auth/send-code`, `/auth/verify-code`, `/auth/google` — have per-IP fixed-window rate limiting in front of them. The limiter is backed by Redis. When `REDIS_URL` is unset the middleware is a **no-op** (fail-open) and the backend logs `rate limiting disabled: REDIS_URL not configured` at startup.diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 050a4d28c3..42e37e6d6c 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -128,6 +128,22 @@ Multica 存储用户上传的附件(评论里的图片、文件等)。**优**邀请流程本身不检查 signup 白名单**——但被邀请人必须先能**登录**才能接受邀请。如果对方已经有 Multica 账号(比如在其他工作区注册过),可以直接接受,不受白名单影响;**如果对方还没注册过**,他们登录的第一步(发送验证码)仍然会过白名单检查,被 `ALLOW_SIGNUP=false` 或 `ALLOWED_EMAILS` / `ALLOWED_EMAIL_DOMAINS` 拒绝的邮箱**无法完成注册,也就没法接受邀请**。+## 锁死工作区创建++`ALLOW_SIGNUP=false` 能挡住新注册,但**挡不住**已经登录的用户继续 `POST /api/workspaces` 自助开新工作区。在希望平台管理员能看到全部 issue / 仓库 / 智能体的自部署实例里,把 `DISABLE_WORKSPACE_CREATION=true` 打开以堵上这个口子。++| 环境变量 | 默认值 | 说明 |+|---|---|---|+| `DISABLE_WORKSPACE_CREATION` | `false` | 设为 `true` 时,对 `POST /api/workspaces` 的任何调用都返回 `403 workspace creation is disabled for this instance`。Web UI 通过 `/api/config` 隐藏所有「创建工作区」入口。该开关是实例级的,没有 owner / admin 例外 |++推荐的开服流程:++1. 启动实例时保持 `DISABLE_WORKSPACE_CREATION` 未设置(默认)。+2. 管理员登录并创建共享工作区。+3. 把 `DISABLE_WORKSPACE_CREATION=true` 设上并重启 backend。之后新用户只能通过邀请加入。++如果还想让被邀请的新用户能完成首次注册,保留 `ALLOW_SIGNUP=true`(必要时用 `ALLOWED_EMAIL_DOMAINS` / `ALLOWED_EMAILS` 限定可注册邮箱),只把 `DISABLE_WORKSPACE_CREATION=true` 打开即可;如果同时设 `ALLOW_SIGNUP=false`,连有 pending invite 的邮箱都无法完成首次注册,仅适合所有成员都已有 Multica 账号的实例。+## 速率限制(可选 Redis)公开认证端点——`/auth/send-code`、`/auth/verify-code`、`/auth/google`——前面挂了按 IP 的固定窗口限流。限流器后端是 Redis。`REDIS_URL` 不设时中间件**直通**(fail-open),后端启动会打日志 `rate limiting disabled: REDIS_URL not configured`。diff --git a/deploy/helm/multica/templates/configmap.yaml b/deploy/helm/multica/templates/configmap.yamlindex 9f9eb55a0e..af418e14dc 100644--- a/deploy/helm/multica/templates/configmap.yaml+++ b/deploy/helm/multica/templates/configmap.yaml@@ -16,6 +16,7 @@ data:ALLOW_SIGNUP: {{ .Values.backend.config.allowSignup | quote }}ALLOWED_EMAILS: {{ .Values.backend.config.allowedEmails | quote }}ALLOWED_EMAIL_DOMAINS: {{ .Values.backend.config.allowedEmailDomains | quote }}+ DISABLE_WORKSPACE_CREATION: {{ .Values.backend.config.disableWorkspaceCreation | quote }}GOOGLE_CLIENT_ID: {{ .Values.backend.config.googleClientId | quote }}GOOGLE_REDIRECT_URI: {{ .Values.backend.config.googleRedirectUri | quote }}S3_BUCKET: {{ .Values.backend.config.s3Bucket | quote }}diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yamlindex ff96de5fb9..cca884b3a2 100644--- a/deploy/helm/multica/values.yaml+++ b/deploy/helm/multica/values.yaml@@ -72,6 +72,10 @@ backend:allowSignup: trueallowedEmails: ""allowedEmailDomains: ""+ # Self-host gate (#3433): set true to make POST /api/workspaces 403 for+ # every caller. Bootstrap the workspace with this false, then flip to+ # true so users can only join via invitation.+ disableWorkspaceCreation: falsegoogleClientId: ""googleRedirectUri: http://multica.dev.lan/auth/callbacks3Bucket: ""diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 709407c28a..27d2f38f26 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -72,6 +72,7 @@ services:ALLOW_SIGNUP: ${ALLOW_SIGNUP:-true}ALLOWED_EMAILS: ${ALLOWED_EMAILS:-}ALLOWED_EMAIL_DOMAINS: ${ALLOWED_EMAIL_DOMAINS:-}+ DISABLE_WORKSPACE_CREATION: ${DISABLE_WORKSPACE_CREATION:-}GITHUB_APP_SLUG: ${GITHUB_APP_SLUG:-}GITHUB_WEBHOOK_SECRET: ${GITHUB_WEBHOOK_SECRET:-}# Public URL the API is reachable at from the open internet, nodiff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 4cea13112a..f76bd82b59 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1212,6 +1212,9 @@ export class ApiClient {posthog_key?: string;posthog_host?: string;analytics_environment?: string;+ // Self-host gate (#3433). Optional because older servers omit the field+ // entirely; consumers must default to false.+ workspace_creation_disabled?: boolean;}> {return this.fetch("/api/config");}diff --git a/packages/core/config/index.ts b/packages/core/config/index.tsindex 2afbcb744c..ee1cfd1c4c 100644--- a/packages/core/config/index.ts+++ b/packages/core/config/index.ts@@ -5,17 +5,26 @@ interface ConfigState {cdnDomain: string;allowSignup: boolean;googleClientId: string;+ // Self-host gate (#3433): when true, every "Create workspace" affordance+ // must be hidden. Defaults to false so unknown / older servers behave like+ // the managed-cloud case.+ workspaceCreationDisabled: boolean;setCdnDomain: (domain: string) => void;- setAuthConfig: (config: { allowSignup: boolean; googleClientId?: string }) => void;+ setAuthConfig: (config: {+ allowSignup: boolean;+ googleClientId?: string;+ workspaceCreationDisabled?: boolean;+ }) => void;}export const configStore = createStore<ConfigState>((set) => ({cdnDomain: "",allowSignup: true,googleClientId: "",+ workspaceCreationDisabled: false,setCdnDomain: (domain) => set({ cdnDomain: domain }),- setAuthConfig: ({ allowSignup, googleClientId = "" }) =>- set({ allowSignup, googleClientId }),+ setAuthConfig: ({ allowSignup, googleClientId = "", workspaceCreationDisabled = false }) =>+ set({ allowSignup, googleClientId, workspaceCreationDisabled }),}));export function useConfigStore(): ConfigState;diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsxindex 9fe77ec222..40dcb3d8be 100644--- a/packages/core/platform/auth-initializer.tsx+++ b/packages/core/platform/auth-initializer.tsx@@ -53,6 +53,9 @@ export function AuthInitializer({configStore.getState().setAuthConfig({allowSignup: cfg.allow_signup,googleClientId: cfg.google_client_id,+ // Old servers omit this field — treat that as "creation allowed"+ // (the managed-cloud default) rather than blocking the UI.+ workspaceCreationDisabled: cfg.workspace_creation_disabled === true,});if (cfg.posthog_key) {initAnalytics({diff --git a/packages/views/layout/app-sidebar.tsx b/packages/views/layout/app-sidebar.tsxindex 5d2938b64e..174f121835 100644--- a/packages/views/layout/app-sidebar.tsx+++ b/packages/views/layout/app-sidebar.tsx@@ -72,6 +72,7 @@ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";import { inboxKeys, deduplicateInboxItems } from "@multica/core/inbox/queries";import { api, ApiError } from "@multica/core/api";import { useModalStore } from "@multica/core/modals";+import { useConfigStore } from "@multica/core/config";import { useMyRuntimesNeedUpdate } from "@multica/core/runtimes/hooks";import { pinListOptions } from "@multica/core/pins/queries";import { useDeletePin, useReorderPins } from "@multica/core/pins/mutations";@@ -350,6 +351,7 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle }const p = useWorkspacePaths();const { data: workspaces = EMPTY_WORKSPACES } = useQuery(workspaceListOptions());const { data: myInvitations = EMPTY_INVITATIONS } = useQuery(myInvitationListOptions());+ const workspaceCreationDisabled = useConfigStore((s) => s.workspaceCreationDisabled);const wsId = workspace?.id;const { data: inboxItems = EMPTY_INBOX } = useQuery({@@ -525,14 +527,16 @@ export function AppSidebar({ topSlot, searchSlot, headerClassName, headerStyle })}</DropdownMenuItem>))}- <DropdownMenuItem- onClick={() =>- useModalStore.getState().open("create-workspace")- }- >- <Plus className="h-3.5 w-3.5" />- {t(($) => $.sidebar.create_workspace)}- </DropdownMenuItem>+ {!workspaceCreationDisabled && (+ <DropdownMenuItem+ onClick={() =>+ useModalStore.getState().open("create-workspace")+ }+ >+ <Plus className="h-3.5 w-3.5" />+ {t(($) => $.sidebar.create_workspace)}+ </DropdownMenuItem>+ )}</DropdownMenuGroup>{myInvitations.length > 0 && (<>diff --git a/packages/views/locales/en/onboarding.json b/packages/views/locales/en/onboarding.jsonindex c656ff220d..1f2bf35c1f 100644--- a/packages/views/locales/en/onboarding.json+++ b/packages/views/locales/en/onboarding.json@@ -296,7 +296,14 @@"skills_meta": "reusable playbooks","more_label": "And more","more_meta": "and more"- }+ },+ "creation_disabled_eyebrow": "Workspace creation is disabled",+ "creation_disabled_headline": "Ask your administrator for an invitation.",+ "creation_disabled_lede": "This Multica instance does not allow new workspaces to be created. Once an administrator invites you to a workspace, accept the invitation and refresh to continue.",+ "creation_disabled_logout": "Log out",+ "creation_disabled_eyebrow_resume": "Your workspace",+ "creation_disabled_headline_resume": "Continue with {{name}}.",+ "creation_disabled_lede_resume": "Workspace creation is disabled on this instance, so you'll continue into your existing workspace."},"step_runtime": {"scanning_headline": "Connecting this computer…",diff --git a/packages/views/locales/en/workspace.json b/packages/views/locales/en/workspace.jsonindex 9527ce95e9..8a1c82acbf 100644--- a/packages/views/locales/en/workspace.json+++ b/packages/views/locales/en/workspace.json@@ -21,6 +21,10 @@"description": "One workspace where you and your AI teammates work side by side — taking issues, leaving comments, sharing the same context.","invite_hint": "You can invite teammates once your workspace is ready."},+ "creation_disabled": {+ "title": "Workspace creation is disabled",+ "description": "This Multica instance does not allow new workspaces to be created. Ask your administrator for an invitation to an existing workspace."+ },"no_access": {"title": "Workspace not available","description": "This workspace doesn't exist or you don't have access.",diff --git a/packages/views/locales/zh-Hans/onboarding.json b/packages/views/locales/zh-Hans/onboarding.jsonindex 9787eb2788..261914c61d 100644--- a/packages/views/locales/zh-Hans/onboarding.json+++ b/packages/views/locales/zh-Hans/onboarding.json@@ -296,7 +296,14 @@"skills_meta": "可复用的剧本","more_label": "更多","more_meta": "等等"- }+ },+ "creation_disabled_eyebrow": "已禁用创建工作区",+ "creation_disabled_headline": "请联系管理员邀请你加入工作区。",+ "creation_disabled_lede": "该 Multica 实例不允许创建新的工作区。等管理员把你邀请到某个工作区后,接受邀请并刷新即可继续。",+ "creation_disabled_logout": "退出登录",+ "creation_disabled_eyebrow_resume": "你的工作区",+ "creation_disabled_headline_resume": "继续使用 {{name}}。",+ "creation_disabled_lede_resume": "该实例已禁用创建工作区,继续进入你已有的工作区即可。"},"step_runtime": {"scanning_headline": "正在连接这台电脑…",diff --git a/packages/views/locales/zh-Hans/workspace.json b/packages/views/locales/zh-Hans/workspace.jsonindex ab80e85b93..341e8ec929 100644--- a/packages/views/locales/zh-Hans/workspace.json+++ b/packages/views/locales/zh-Hans/workspace.json@@ -21,6 +21,10 @@"description": "一个工作区,让你和 AI 队友并肩协作——一起处理 issue、留下评论、共享同一份上下文。","invite_hint": "工作区创建后可邀请队友加入。"},+ "creation_disabled": {+ "title": "已禁用创建工作区",+ "description": "该 Multica 实例不允许创建新的工作区,请联系管理员邀请你加入已有工作区。"+ },"no_access": {"title": "工作区不可用","description": "该工作区不存在,或你没有访问权限。",diff --git a/packages/views/modals/create-workspace.tsx b/packages/views/modals/create-workspace.tsxindex 5739377ce6..8d296b29fb 100644--- a/packages/views/modals/create-workspace.tsx+++ b/packages/views/modals/create-workspace.tsx@@ -11,12 +11,15 @@ import {DialogDescription,} from "@multica/ui/components/ui/dialog";import { paths } from "@multica/core/paths";+import { useConfigStore } from "@multica/core/config";import { CreateWorkspaceForm } from "../workspace/create-workspace-form";import { useT } from "../i18n";export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {const { t } = useT("modals");+ const tWorkspace = useT("workspace").t;const router = useNavigation();+ const workspaceCreationDisabled = useConfigStore((s) => s.workspaceCreationDisabled);return (<Dialog@@ -50,25 +53,38 @@ export function CreateWorkspaceModal({ onClose }: { onClose: () => void }) {<div className="flex flex-1 flex-col items-center justify-center px-6 pb-12"><div className="flex w-full max-w-md flex-col items-center gap-6">- <div className="text-center">- <DialogTitle className="text-2xl font-semibold">- {t(($) => $.create_workspace.title)}- </DialogTitle>- <DialogDescription className="mt-2">- {t(($) => $.create_workspace.description)}- </DialogDescription>- </div>- <CreateWorkspaceForm- onSuccess={(newWs) => {- onClose();- // Navigate INTO the new workspace. The mutation's own onSuccess- // (in core/workspace/mutations.ts) runs before this callback and- // has already seeded the workspace list cache, so the destination- // [workspaceSlug]/layout will resolve newWs.slug → workspace- // synchronously without a loading flash.- router.push(paths.workspace(newWs.slug).issues());- }}- />+ {workspaceCreationDisabled ? (+ <div className="text-center">+ <DialogTitle className="text-2xl font-semibold">+ {tWorkspace(($) => $.creation_disabled.title)}+ </DialogTitle>+ <DialogDescription className="mt-2">+ {tWorkspace(($) => $.creation_disabled.description)}+ </DialogDescription>+ </div>+ ) : (+ <>+ <div className="text-center">+ <DialogTitle className="text-2xl font-semibold">+ {t(($) => $.create_workspace.title)}+ </DialogTitle>+ <DialogDescription className="mt-2">+ {t(($) => $.create_workspace.description)}+ </DialogDescription>+ </div>+ <CreateWorkspaceForm+ onSuccess={(newWs) => {+ onClose();+ // Navigate INTO the new workspace. The mutation's own onSuccess+ // (in core/workspace/mutations.ts) runs before this callback and+ // has already seeded the workspace list cache, so the destination+ // [workspaceSlug]/layout will resolve newWs.slug → workspace+ // synchronously without a loading flash.+ router.push(paths.workspace(newWs.slug).issues());+ }}+ />+ </>+ )}</div></div></DialogContent>diff --git a/packages/views/onboarding/steps/step-workspace.test.tsx b/packages/views/onboarding/steps/step-workspace.test.tsxnew file mode 100644index 0000000000..b5d248f502--- /dev/null+++ b/packages/views/onboarding/steps/step-workspace.test.tsx@@ -0,0 +1,135 @@+import type { ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";+import { render, screen } from "@testing-library/react";+import { I18nProvider } from "@multica/core/i18n/react";+import enCommon from "../../locales/en/common.json";+import enOnboarding from "../../locales/en/onboarding.json";+import enWorkspace from "../../locales/en/workspace.json";+import type { Workspace } from "@multica/core/types";++const TEST_RESOURCES = {+ en: {+ common: enCommon,+ onboarding: enOnboarding,+ workspace: enWorkspace,+ },+};++const mockLogout = vi.hoisted(() => vi.fn());+const mockUseConfigStore = vi.hoisted(() =>+ vi.fn(+ (selector: (state: { workspaceCreationDisabled: boolean }) => unknown) =>+ selector({ workspaceCreationDisabled: false }),+ ),+);++vi.mock("../../auth", () => ({+ useLogout: () => mockLogout,+}));++vi.mock("@multica/core/config", () => ({+ useConfigStore: (selector: (state: { workspaceCreationDisabled: boolean }) => unknown) =>+ mockUseConfigStore(selector),+}));++vi.mock("@multica/core/workspace/mutations", () => ({+ useCreateWorkspace: () => ({ mutate: vi.fn(), isPending: false }),+}));++import { StepWorkspace } from "./step-workspace";++function I18nWrapper({ children }: { children: ReactNode }) {+ return (+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ {children}+ </I18nProvider>+ );+}++function renderStep({+ existing,+ disabled,+}: {+ existing: Workspace | null;+ disabled: boolean;+}) {+ mockUseConfigStore.mockImplementation(+ (selector: (state: { workspaceCreationDisabled: boolean }) => unknown) =>+ selector({ workspaceCreationDisabled: disabled }),+ );+ return render(+ <StepWorkspace existing={existing} onCreated={vi.fn()} onBack={vi.fn()} />,+ { wrapper: I18nWrapper },+ );+}++const EXISTING_WORKSPACE: Workspace = {+ id: "00000000-0000-0000-0000-000000000001",+ name: "Acme",+ slug: "acme",+ description: null,+ context: null,+ settings: {},+ repos: [],+ issue_prefix: "ACM",+ created_at: "2025-01-01T00:00:00Z",+ updated_at: "2025-01-01T00:00:00Z",+} as unknown as Workspace;++// Regression for #3433 (PR feedback): when DISABLE_WORKSPACE_CREATION is on,+// every onboarding entry point must steer the user toward an existing+// workspace or a logout escape — never toward the create form, even+// indirectly (stale CTA copy, "or start another" prose, etc.).+describe("StepWorkspace — DISABLE_WORKSPACE_CREATION gate", () => {+ it("renders the create form when the flag is off and the user has no workspace", () => {+ renderStep({ existing: null, disabled: false });++ expect(+ screen.getByText("Name your workspace.", { exact: false }),+ ).toBeInTheDocument();+ expect(screen.getByLabelText("Workspace name")).toBeInTheDocument();+ expect(screen.getByLabelText("URL")).toBeInTheDocument();+ });++ it("hides the create form and shows the disabled notice when the flag is on and there is no workspace", () => {+ renderStep({ existing: null, disabled: true });++ expect(+ screen.getByText("Ask your administrator for an invitation.", {+ exact: false,+ }),+ ).toBeInTheDocument();+ expect(screen.queryByLabelText("Workspace name")).not.toBeInTheDocument();+ expect(screen.queryByLabelText("URL")).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: /log out/i })).toBeInTheDocument();+ });++ it("forces the existing-workspace-only state when the flag is on and the user already has a workspace", () => {+ renderStep({ existing: EXISTING_WORKSPACE, disabled: true });++ // Disabled-specific copy is used in place of the "or start another" prose.+ expect(+ screen.getByText("Continue with Acme.", { exact: false }),+ ).toBeInTheDocument();+ expect(+ screen.queryByText(/start another/i),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByText(/create a new one alongside it/i),+ ).not.toBeInTheDocument();++ // Resume picker still shows the existing workspace card (its name+ // appears multiple times across avatar / card / side panel — at least+ // one is enough to know the card is rendered), but the "Create a new+ // workspace" radio card is gone entirely.+ expect(screen.getAllByText("Acme").length).toBeGreaterThan(0);+ expect(+ screen.queryByText("Create a new workspace", { exact: false }),+ ).not.toBeInTheDocument();++ // CTA is pre-selected to the existing-only action and immediately+ // enabled, so the user can press it without further interaction.+ const cta = screen.getByRole("button", { name: "Open Acme" });+ expect(cta).toBeEnabled();+ });+});diff --git a/packages/views/onboarding/steps/step-workspace.tsx b/packages/views/onboarding/steps/step-workspace.tsxindex 2c945b8065..dde9577fa1 100644--- a/packages/views/onboarding/steps/step-workspace.tsx+++ b/packages/views/onboarding/steps/step-workspace.tsx@@ -24,7 +24,9 @@ import { cn } from "@multica/ui/lib/utils";import { useCreateWorkspace } from "@multica/core/workspace/mutations";import type { Workspace } from "@multica/core/types";import { isImeComposing } from "@multica/core/utils";+import { useConfigStore } from "@multica/core/config";import { DragStrip } from "@multica/views/platform";+import { useLogout } from "../../auth";import { StepHeader } from "../components/step-header";import { RadioMark } from "../components/option-card";import { WorkspaceAvatar } from "../../workspace/workspace-avatar";@@ -78,13 +80,25 @@ export function StepWorkspace({const { t } = useT("onboarding");const mainRef = useRef<HTMLElement>(null);const fadeStyle = useScrollFade(mainRef);+ const workspaceCreationDisabled = useConfigStore((s) => s.workspaceCreationDisabled);+ // Single source of truth for "can the user reach the create path on this+ // instance?" — drives the resume-mode picker, the eyebrow/headline/lede+ // copy, the side panel, and the footer CTA so the disabled state can't+ // leak a clickable create affordance even if /api/config arrives late+ // (#3433 review feedback).+ const workspaceCreationAllowed = !workspaceCreationDisabled;+ const logout = useLogout();const reusing = existing ?? null;// Resume path only: user picks which card. `null` = neither yet, so// the footer CTA stays disabled. Clicking either card toggles — a// second click on the same card deselects it. No-existing path- // ignores this state entirely.- const [mode, setMode] = useState<"existing" | "create" | null>(null);+ // ignores this state entirely. When workspace creation is disabled+ // and a workspace already exists, default to "existing" so the user+ // can press the CTA immediately — the only valid action.+ const [mode, setMode] = useState<"existing" | "create" | null>(() =>+ !workspaceCreationAllowed && existing ? "existing" : null,+ );const pickExisting = () =>setMode((m) => (m === "existing" ? null : "existing"));const pickCreate = () =>@@ -152,9 +166,13 @@ export function StepWorkspace({// Compute the footer CTA from whichever path the user is on. `null`// is only reachable in the resume path; `existing` is only valid// when we actually have a `reusing` workspace; everything else- // (including the no-existing path) funnels through `create`.+ // (including the no-existing path) funnels through `create` — except+ // when this instance has DISABLE_WORKSPACE_CREATION=true, in which+ // case the create path is unreachable and a no-reusing user falls+ // through to the disabled notice (rendered separately below).const isCreating = createWorkspace.isPending;- const creatingActive = !reusing || mode === "create";+ const creatingActive =+ workspaceCreationAllowed && (!reusing || mode === "create");const existingActive = Boolean(reusing) && mode === "existing";let hint: string;@@ -288,18 +306,30 @@ export function StepWorkspace({<div className="mx-auto w-full max-w-[620px] px-6 py-10 sm:px-10 md:px-14 lg:px-0 lg:py-14"><div className="mb-2 text-xs font-medium uppercase tracking-[0.08em] text-muted-foreground">{reusing- ? t(($) => $.step_workspace.eyebrow_resume)- : t(($) => $.step_workspace.eyebrow_first)}+ ? workspaceCreationAllowed+ ? t(($) => $.step_workspace.eyebrow_resume)+ : t(($) => $.step_workspace.creation_disabled_eyebrow_resume)+ : workspaceCreationAllowed+ ? t(($) => $.step_workspace.eyebrow_first)+ : t(($) => $.step_workspace.creation_disabled_eyebrow)}</div><h1 className="text-balance font-serif text-[36px] font-medium leading-[1.1] tracking-tight text-foreground">{reusing- ? t(($) => $.step_workspace.headline_resume, { name: reusing.name })- : t(($) => $.step_workspace.headline_first)}+ ? workspaceCreationAllowed+ ? t(($) => $.step_workspace.headline_resume, { name: reusing.name })+ : t(($) => $.step_workspace.creation_disabled_headline_resume, { name: reusing.name })+ : workspaceCreationAllowed+ ? t(($) => $.step_workspace.headline_first)+ : t(($) => $.step_workspace.creation_disabled_headline)}</h1><p className="mt-4 text-[15.5px] leading-[1.55] text-foreground/80">{reusing- ? t(($) => $.step_workspace.lede_resume)- : t(($) => $.step_workspace.lede_first)}+ ? workspaceCreationAllowed+ ? t(($) => $.step_workspace.lede_resume)+ : t(($) => $.step_workspace.creation_disabled_lede_resume)+ : workspaceCreationAllowed+ ? t(($) => $.step_workspace.lede_first)+ : t(($) => $.step_workspace.creation_disabled_lede)}</p><div className="mt-10">@@ -310,30 +340,40 @@ export function StepWorkspace({selected={mode === "existing"}onSelect={pickExisting}/>- <CreateNewWorkspaceCard- selected={mode === "create"}- onSelect={pickCreate}- >- {createFields}- </CreateNewWorkspaceCard>+ {/* Hide the create-new card entirely when the self-host+ gate (DISABLE_WORKSPACE_CREATION) is on (#3433) — the+ backend would 403 the POST and the user would be stuck+ with a useless form. */}+ {!workspaceCreationDisabled && (+ <CreateNewWorkspaceCard+ selected={mode === "create"}+ onSelect={pickCreate}+ >+ {createFields}+ </CreateNewWorkspaceCard>+ )}</div>+ ) : workspaceCreationDisabled ? (+ <CreationDisabledNotice onLogout={logout} />) : (createFields)}</div>- <div className="mt-8 flex flex-wrap items-center justify-end gap-x-4 gap-y-2">- <span- aria-live="polite"- className="mr-auto text-xs text-muted-foreground"- >- {hint}- </span>- <Button size="lg" disabled={continueDisabled} onClick={onContinue}>- {continueLabel}- <ArrowRight className="h-4 w-4" />- </Button>- </div>+ {!(workspaceCreationDisabled && !reusing) && (+ <div className="mt-8 flex flex-wrap items-center justify-end gap-x-4 gap-y-2">+ <span+ aria-live="polite"+ className="mr-auto text-xs text-muted-foreground"+ >+ {hint}+ </span>+ <Button size="lg" disabled={continueDisabled} onClick={onContinue}>+ {continueLabel}+ <ArrowRight className="h-4 w-4" />+ </Button>+ </div>+ )}</div></main></div>@@ -358,6 +398,24 @@ export function StepWorkspace({);}+/**+ * Onboarding-step notice rendered when the operator has set+ * DISABLE_WORKSPACE_CREATION=true (#3433) AND the user has no existing+ * workspace yet. The headline / lede above this block already carry the+ * messaging; this component only provides the logout escape so a user who+ * landed here without an invitation is not trapped.+ */+function CreationDisabledNotice({ onLogout }: { onLogout: () => void }) {+ const { t } = useT("onboarding");+ return (+ <div className="flex flex-col gap-3">+ <Button variant="outline" size="lg" onClick={onLogout}>+ {t(($) => $.step_workspace.creation_disabled_logout)}+ </Button>+ </div>+ );+}+function ExistingWorkspaceCard({workspace,selected,diff --git a/packages/views/workspace/new-workspace-page.tsx b/packages/views/workspace/new-workspace-page.tsxindex 4edd8fa311..b0afbbe4e1 100644--- a/packages/views/workspace/new-workspace-page.tsx+++ b/packages/views/workspace/new-workspace-page.tsx@@ -3,6 +3,7 @@import { ArrowLeft, LogOut } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import type { Workspace } from "@multica/core/types";+import { useConfigStore } from "@multica/core/config";import { useLogout } from "../auth";import { DragStrip } from "../platform";import { useT } from "../i18n";@@ -30,6 +31,7 @@ export function NewWorkspacePage({}) {const { t } = useT("workspace");const logout = useLogout();+ const workspaceCreationDisabled = useConfigStore((s) => s.workspaceCreationDisabled);return (<div className="relative flex min-h-svh flex-col bg-background">@@ -57,18 +59,31 @@ export function NewWorkspacePage({<div className="flex flex-1 flex-col items-center justify-center px-6 pb-12"><div className="flex w-full max-w-md flex-col items-center gap-6">- <div className="text-center">- <h1 className="text-3xl font-semibold tracking-tight">- {t(($) => $.new_page.title)}- </h1>- <p className="mt-3 text-muted-foreground">- {t(($) => $.new_page.description)}- </p>- </div>- <CreateWorkspaceForm onSuccess={onSuccess} />- <p className="text-center text-xs text-muted-foreground">- {t(($) => $.new_page.invite_hint)}- </p>+ {workspaceCreationDisabled ? (+ <div className="text-center">+ <h1 className="text-3xl font-semibold tracking-tight">+ {t(($) => $.creation_disabled.title)}+ </h1>+ <p className="mt-3 text-muted-foreground">+ {t(($) => $.creation_disabled.description)}+ </p>+ </div>+ ) : (+ <>+ <div className="text-center">+ <h1 className="text-3xl font-semibold tracking-tight">+ {t(($) => $.new_page.title)}+ </h1>+ <p className="mt-3 text-muted-foreground">+ {t(($) => $.new_page.description)}+ </p>+ </div>+ <CreateWorkspaceForm onSuccess={onSuccess} />+ <p className="text-center text-xs text-muted-foreground">+ {t(($) => $.new_page.invite_hint)}+ </p>+ </>+ )}</div></div></div>diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 781a08a109..e3fbbbc1cc 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -134,6 +134,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.BusAllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),+ DisableWorkspaceCreation: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("MULTICA_PUBLIC_URL")), "/"),TrustedProxies: parseTrustedProxies(os.Getenv("MULTICA_TRUSTED_PROXIES")),CloudRuntimeFleetURL: cloudRuntimeFleetURLFromEnv(),diff --git a/server/internal/handler/config.go b/server/internal/handler/config.goindex 3c7bfd54da..cbeccc504c 100644--- a/server/internal/handler/config.go+++ b/server/internal/handler/config.go@@ -14,6 +14,12 @@ type AppConfig struct {// toggle signup or wire Google OAuth.AllowSignup bool `json:"allow_signup"`GoogleClientID string `json:"google_client_id,omitempty"`+ // WorkspaceCreationDisabled mirrors the server-side+ // DISABLE_WORKSPACE_CREATION env var so the UI can hide every+ // "Create workspace" affordance on self-hosted instances. Omitted+ // from the JSON when false to keep responses identical to the+ // previous shape for the common managed-cloud case (#3433).+ WorkspaceCreationDisabled bool `json:"workspace_creation_disabled,omitempty"`// PostHog public config for the frontend. The key is the same Project// API Key the backend uses; returning it here (instead of baking it@@ -31,8 +37,9 @@ type AppConfig struct {// to anonymous callers — never user- or tenant-scoped data.func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {config := AppConfig{- AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",- GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),+ AllowSignup: os.Getenv("ALLOW_SIGNUP") != "false",+ GoogleClientID: os.Getenv("GOOGLE_CLIENT_ID"),+ WorkspaceCreationDisabled: os.Getenv("DISABLE_WORKSPACE_CREATION") == "true",}if h.Storage != nil {config.CdnDomain = h.Storage.CdnDomain()diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.goindex bf2bcf5228..d1c930849a 100644--- a/server/internal/handler/config_test.go+++ b/server/internal/handler/config_test.go@@ -48,4 +48,34 @@ func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {if cfg.AnalyticsEnvironment != "dev" {t.Fatalf("analytics_environment: want dev, got %q", cfg.AnalyticsEnvironment)}+ if cfg.WorkspaceCreationDisabled {+ t.Fatalf("workspace_creation_disabled: want false by default, got true")+ }+}++// TestGetConfigExposesWorkspaceCreationDisabled verifies that the self-host+// gate added by #3433 surfaces to the frontend through /api/config so the UI+// can hide every "Create workspace" affordance.+func TestGetConfigExposesWorkspaceCreationDisabled(t *testing.T) {+ origStorage := testHandler.Storage+ testHandler.Storage = &mockStorage{}+ defer func() { testHandler.Storage = origStorage }()++ t.Setenv("DISABLE_WORKSPACE_CREATION", "true")++ req := httptest.NewRequest(http.MethodGet, "/api/config", nil)+ w := httptest.NewRecorder()++ testHandler.GetConfig(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("GetConfig: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var cfg AppConfig+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil {+ t.Fatalf("decode config: %v", err)+ }+ if !cfg.WorkspaceCreationDisabled {+ t.Fatalf("workspace_creation_disabled: want true with env on, got false (body=%s)", w.Body.String())+ }}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex d6a40baee1..3edc4175f2 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -50,6 +50,13 @@ type Config struct {AllowSignup boolAllowedEmails []stringAllowedEmailDomains []string+ // DisableWorkspaceCreation, when true, makes POST /api/workspaces return+ // 403 for every caller. There is no role/owner exception because the repo+ // has no platform-admin concept; operators bootstrap the workspace with+ // the flag off, then flip it on and restart so subsequent users join via+ // invitation only. The public /api/config endpoint mirrors this flag so+ // the UI can hide every "Create workspace" affordance — see #3433.+ DisableWorkspaceCreation bool// PublicURL is the absolute base URL the API is reachable at from the// public internet, with no trailing slash (e.g. "https://app.multica.ai").// Used only to build webhook_url responses for autopilot webhook triggersdiff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.goindex 09c5eb248e..eb9b9d1ece 100644--- a/server/internal/handler/workspace.go+++ b/server/internal/handler/workspace.go@@ -141,6 +141,16 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {return}+ // Self-host gate (#3433): when the operator has set+ // DISABLE_WORKSPACE_CREATION=true, no caller — including existing+ // workspace owners — may create additional workspaces. The frontend+ // hides every "Create workspace" affordance via /api/config, but the+ // 403 here is the only authoritative check.+ if h.cfg.DisableWorkspaceCreation {+ writeError(w, http.StatusForbidden, "workspace creation is disabled for this instance")+ return+ }+var req CreateWorkspaceRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")diff --git a/server/internal/handler/workspace_test.go b/server/internal/handler/workspace_test.goindex 4ad05aea9b..c155589776 100644--- a/server/internal/handler/workspace_test.go+++ b/server/internal/handler/workspace_test.go@@ -81,6 +81,48 @@ func TestCreateWorkspace_DoesNotMarkOnboarded(t *testing.T) {}}+// TestCreateWorkspace_DisabledByConfig guards the self-host gate added by+// #3433: when DisableWorkspaceCreation is true on the handler config, every+// caller — even an already-authenticated user — must receive 403 and the+// workspace row must not be written.+func TestCreateWorkspace_DisabledByConfig(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ const slug = "handler-tests-disabled-create"+ ctx := context.Background()+ _, _ = testPool.Exec(ctx, `DELETE FROM workspace WHERE slug = $1`, slug)+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE slug = $1`, slug)+ })++ prev := testHandler.cfg+ testHandler.cfg = Config{+ AllowSignup: prev.AllowSignup,+ DisableWorkspaceCreation: true,+ }+ t.Cleanup(func() { testHandler.cfg = prev })++ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/workspaces", map[string]any{+ "name": "Disabled Create",+ "slug": slug,+ })+ testHandler.CreateWorkspace(w, req)+ if w.Code != http.StatusForbidden {+ t.Fatalf("CreateWorkspace: expected 403 with flag on, got %d: %s", w.Code, w.Body.String())+ }++ var count int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM workspace WHERE slug = $1`, slug).Scan(&count); err != nil {+ t.Fatalf("count workspaces: %v", err)+ }+ if count != 0 {+ t.Fatalf("expected no workspace row to be written when gate fires, found %d", count)+ }+}+// TestDeleteWorkspace_RequiresOwner exercises the in-handler authorization// added to DeleteWorkspace by calling the handler directly (bypassing the// router-level RequireWorkspaceRoleFromURL middleware). Without the handler