Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
feat(auth): 新增仅限邀请注册档位 (#3900)
lyingbug5225edc0f746
diff --git a/frontend/src/api/auth/index.ts b/frontend/src/api/auth/index.tsindex 247eff201..5e92a06bd 100644--- a/frontend/src/api/auth/index.ts+++ b/frontend/src/api/auth/index.ts@@ -262,13 +262,14 @@ export async function getOIDCConfig(): Promise<OIDCConfigResponse> {** 后端通过 `auth.registration_mode` 控制是否允许自助注册:* - "self_serve" 保留现有自助注册入口(默认)- * - "invite_only" 关闭注册,要求管理员邀请+ * - "invite_register" 仅持有效邀请链接可注册+ * - "invite_only" 禁止注册,已有账号仍可接受邀请*- * 失败时回落到 self_serve,避免接口异常导致注册入口直接消失。+ * 失败时隐藏注册入口,避免误展示不允许的注册流程。*/export interface AuthConfigResponse {success: boolean- registration_mode: 'self_serve' | 'invite_only' | string+ registration_mode: 'self_serve' | 'invite_register' | 'invite_only' | stringcomplex_password_enabled: boolean}@@ -277,7 +278,7 @@ export async function getAuthConfig(): Promise<AuthConfigResponse> {const response = await get('/api/v1/auth/config')return response as unknown as AuthConfigResponse} catch {- return { success: false, registration_mode: 'self_serve', complex_password_enabled: false }+ return { success: false, registration_mode: '', complex_password_enabled: false }}}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex f3b31a940..d0c7b4b7d 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -4620,7 +4620,7 @@ export default {},keyLabels: {auth: {- registration_mode: 'Self-service registration mode',+ registration_mode: 'Registration mode',default_tenant_mode: 'Default workspace provisioning',complex_password_enabled: 'Require complex password'},@@ -4651,7 +4651,7 @@ export default {},keyDescriptions: {auth: {- registration_mode: 'Self-service registration mode. self_serve = anyone can register an account; invite_only = public registration is disabled and only Owners/Admins can invite. Takes effect immediately after saving, but use self_serve with care (the public internet will send spam sign-ups).',+ registration_mode: 'Registration mode. Open registration allows anyone to create an account; invitation registration requires a valid invitation link; disabled registration prevents account creation while existing accounts can still accept invitations. Changes take effect immediately.',default_tenant_mode: 'Workspace provisioning after public registration. create_personal creates an Owner workspace; tenantless creates only the account until the user accepts an invitation or creates a workspace. Applies to new users only.',complex_password_enabled: 'Whether to require complex passwords. When enabled, passwords must contain uppercase and lowercase letters, numbers, and special characters. Changes take effect immediately and only apply to newly registered users or new password changes/resets. Special characters include {specialChars}'},@@ -4684,7 +4684,8 @@ export default {auth: {registration_mode: {self_serve: 'Self-service (anyone can register)',- invite_only: 'Invite only (public registration disabled)'+ invite_register: 'Invitation registration (valid link required)',+ invite_only: 'Registration disabled (existing accounts can accept invitations)'},default_tenant_mode: {create_personal: 'Create personal workspace',diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.tsindex 1bf3e3d88..1cbb54ecd 100644--- a/frontend/src/i18n/locales/ja-JP.ts+++ b/frontend/src/i18n/locales/ja-JP.ts@@ -4620,7 +4620,7 @@ export default {},keyLabels: {auth: {- registration_mode: 'セルフサービス登録モード',+ registration_mode: '登録モード',default_tenant_mode: 'デフォルトのワークスペース作成方式',complex_password_enabled: '複雑なパスワードを必須にする'},@@ -4651,7 +4651,7 @@ export default {},keyDescriptions: {auth: {- registration_mode: 'セルフサービス登録のモードです。self_serveは誰でもアカウントを登録でき、invite_onlyは公開登録を無効にし、オーナー/管理者による招待のみを許可します。保存後すぐに反映されますが、self_serveはインターネットからのスパム登録を招くため慎重に利用してください。',+ registration_mode: '登録モード。公開登録では誰でもアカウントを作成できます。招待登録には有効な招待リンクが必要です。登録禁止でも既存アカウントは招待を承諾できます。保存後すぐに反映されます。',default_tenant_mode: '公開登録後のワークスペース作成方式です。create_personalはオーナー権限のワークスペースを作成し、tenantlessはアカウントのみを作成して、ユーザが招待を承諾するかワークスペースを作成するまで待ちます。新規ユーザにのみ適用されます。',complex_password_enabled: '複雑なパスワードを必須にするかどうかです。有効にすると、パスワードに大文字・小文字・数字・特殊文字を含める必要があります。変更はすぐに反映され、新規登録ユーザおよび新たなパスワード変更・リセットにのみ適用されます。特殊文字は{specialChars}です'},@@ -4684,7 +4684,8 @@ export default {auth: {registration_mode: {self_serve: 'セルフサービス(誰でも登録可能)',- invite_only: '招待のみ(公開登録は無効)'+ invite_register: '招待リンクでのみ登録可能',+ invite_only: '登録禁止(既存アカウントは招待を承諾可能)'},default_tenant_mode: {create_personal: '個人ワークスペースを作成',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex 01b968fa9..2af18593d 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -3409,7 +3409,8 @@ export default {},registration_mode: {self_serve: '셀프 가입 (누구나 가입 가능)',- invite_only: '초대 전용 (공개 가입 비활성)'+ invite_register: '초대 가입 (유효한 링크 필요)',+ invite_only: '가입 금지 (기존 계정은 초대 수락 가능)'}}},@@ -3439,7 +3440,7 @@ export default {docker_enabled: 'Docker 샌드박스 백엔드를 허용할지 설정합니다. 로컬 docker.sock은 호스트 root와 같으므로 기본값은 꺼짐입니다. 시스템 관리자만 켤 수 있으며 저장 즉시 적용됩니다. 데몬 소켓을 마운트했거나 TLS가 있는 원격 tcp:// 를 쓰는 프라이빗 단일 노드에서만 켜세요.'},auth: {- registration_mode: '셀프 가입 모드입니다. self_serve = 누구나 계정을 만들 수 있음; invite_only = 공개 가입을 끄고 Owner/Admin만 초대 가능. 저장 즉시 적용되며, self_serve는 스팸 가입이 들어올 수 있으니 신중히 사용하세요.',+ registration_mode: '가입 모드입니다. 공개 가입은 누구나 계정을 만들 수 있고, 초대 가입은 유효한 초대 링크가 필요합니다. 가입 금지 상태에서도 기존 계정은 초대를 수락할 수 있습니다. 저장 즉시 적용됩니다.',default_tenant_mode: '공개 가입 후 공간 초기화 정책입니다. create_personal은 개인 공간을 만들고 Owner를 부여하며, tenantless는 초대 수락 또는 직접 공간 생성 전까지 계정만 만듭니다.',complex_password_enabled: '복잡한 비밀번호를 사용할지 여부입니다. 활성화하면 비밀번호에 대문자, 소문자, 숫자 및 특수 문자가 포함되어야 합니다. 변경 사항은 즉시 적용되며, 새로 가입하는 사용자 또는 비밀번호를 새로 변경하거나 재설정하는 경우에만 적용됩니다. 특수 문자는 다음을 포함합니다: {specialChars}'}@@ -3470,7 +3471,7 @@ export default {docker_enabled: 'Docker 샌드박스 사용'},auth: {- registration_mode: '셀프 가입 모드',+ registration_mode: '가입 모드',default_tenant_mode: '기본 공간 프로비저닝',complex_password_enabled: '복잡한 비밀번호 사용'}diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex d0fed0d59..7adf0269d 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -3409,7 +3409,8 @@ export default {},registration_mode: {self_serve: 'Самостоятельная (любой может зарегистрироваться)',- invite_only: 'Только по приглашению (открытая регистрация отключена)'+ invite_register: 'Регистрация по приглашению (нужна действующая ссылка)',+ invite_only: 'Регистрация закрыта (существующие аккаунты могут принять приглашение)'}}},@@ -3439,7 +3440,7 @@ export default {docker_enabled: 'Разрешить бэкенд песочницы Docker. Локальный docker.sock равносилен root на хосте, поэтому по умолчанию выключено. Включить может только системный администратор; изменение действует сразу. Включайте только на частной одноузловой установке с примонтированным сокетом демона или удалённым tcp:// с TLS.'},auth: {- registration_mode: 'Режим самостоятельной регистрации. self_serve = любой может создать аккаунт; invite_only = открытая регистрация отключена, приглашать могут только Owner/Admin. Вступает в силу сразу после сохранения; используйте self_serve осторожно (в публичном интернете появятся спам-регистрации).',+ registration_mode: 'Режим регистрации. Открытая регистрация позволяет любому создать аккаунт; регистрация по приглашению требует действующую ссылку; при закрытой регистрации существующие аккаунты могут принимать приглашения. Изменения применяются сразу.',default_tenant_mode: 'Политика пространства после открытой регистрации. create_personal создаёт личное пространство с ролью Owner; tenantless создаёт только аккаунт до принятия приглашения или самостоятельного создания пространства.',complex_password_enabled: 'Определяет, требуется ли сложный пароль. При включении пароль должен содержать прописные и строчные буквы, цифры и специальные символы. Изменение вступает в силу немедленно и применяется только к новым пользователям при регистрации, а также при изменении или сбросе пароля. Специальные символы включают: {specialChars}'}@@ -3470,7 +3471,7 @@ export default {docker_enabled: 'Включить песочницу Docker'},auth: {- registration_mode: 'Режим самостоятельной регистрации',+ registration_mode: 'Режим регистрации',default_tenant_mode: 'Создание пространства по умолчанию',complex_password_enabled: 'Включить сложные пароли'}diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex 63ba96f2b..01245a89d 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -3411,7 +3411,8 @@ export default {},registration_mode: {self_serve: '自助注册(任何人可注册)',- invite_only: '仅邀请(关闭公网注册)'+ invite_register: '仅限邀请注册(需有效邀请链接)',+ invite_only: '禁止注册(已有账号仍可接受邀请)'}}},@@ -3441,7 +3442,7 @@ export default {docker_enabled: '是否允许 Docker 沙箱后端。本机 docker.sock 等同宿主机 root,默认关闭。仅系统管理员可打开;打开后立即生效,无需重启。私有化单机且已挂载 daemon socket,或配置了带 TLS 的远程 tcp:// 时再启用。'},auth: {- registration_mode: '自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册,仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。',+ registration_mode: '注册模式。开放注册允许任何人创建账号;仅限邀请注册要求有效邀请链接;禁止注册不允许创建账号,但已有账号仍可接受邀请。保存后立即生效。',default_tenant_mode: '公开注册后的空间初始化策略。create_personal 会自动创建个人空间并授予 Owner;tenantless 仅创建账户,用户需要接受邀请或主动创建空间。只影响之后注册的用户。',complex_password_enabled: '是否启用复杂密码。开启后密码必须包含大小写字母、数字和特殊字符。修改后立即生效,只影响新注册用户或新密码修改/重置操作。特殊字符包含:{specialChars}'}@@ -3472,7 +3473,7 @@ export default {docker_enabled: '启用 Docker 沙箱'},auth: {- registration_mode: '自助注册模式',+ registration_mode: '注册模式',default_tenant_mode: '注册默认空间策略',complex_password_enabled: '启用复杂密码'}diff --git a/frontend/src/views/auth/Login.vue b/frontend/src/views/auth/Login.vueindex 48e051c94..6dd7d4b5a 100755--- a/frontend/src/views/auth/Login.vue+++ b/frontend/src/views/auth/Login.vue@@ -177,7 +177,7 @@<div class="form-panel"><!-- Login Card --><div class="form-card" v-if="!isRegisterMode">- <!-- invite_only 模式下共享链接停在登录卡,同样需要邀请上下文。 -->+ <!-- 登录已有账号时保留邀请上下文。 --><div v-if="inviteLookup" class="invite-banner"><t-icon name="link" class="invite-banner__icon" /><div class="invite-banner__text">@@ -253,11 +253,8 @@</div></div>- <!-- Register Card. Renders when the user is in register mode- AND either self-service registration is enabled OR they- arrived with a valid share-link token (which bypasses the- invite_only gate). -->- <div class="form-card" v-if="isRegisterMode && (registrationEnabled || inviteLookup)">+ <!-- Registration must be allowed for this mode and invitation. -->+ <div class="form-card" v-if="isRegisterMode && registrationEnabled"><!-- Share-link banner: shown only when ?token= resolved to areal invitation row. Sits above the form header so theinvitee instantly sees who invited them and into which@@ -345,6 +342,7 @@ import { useRoute, useRouter } from 'vue-router'import { MessagePlugin } from 'tdesign-vue-next'import { useRoleLabel } from '@/composables/useRoleLabel'import { notifyLoginSuccess } from '@/utils/loginNotify'+import { canRegister } from './registrationPolicy'import { newPasswordRules } from '@/utils/passwordPolicy'import { Swiper, SwiperSlide } from 'swiper/vue'import { Autoplay, EffectFade, Pagination } from 'swiper/modules'@@ -416,16 +414,14 @@ const isRegisterMode = ref(false)const showLanguageMenu = ref(false)const oidcEnabled = ref(false)const oidcProviderName = ref('')-// registrationEnabled defaults to true so that on first paint the Register-// link is visible; the actual mode is fetched from /auth/config in onMounted.-// In invite_only mode the link/card are hidden.-const registrationEnabled = ref(true)+// Wait for configuration before showing a registration entry.+const registrationMode = ref('')+const registrationEnabled = computed(() => canRegister(registrationMode.value, !!inviteLookup.value))const complexPasswordEnabled = ref(false)// invite-link state. When the URL carries ?token=xxx we resolve it to// the originating tenant + role and switch the form into a "register-// via invitation" mode. The token bypasses the normal invite_only-// gate — possessing it IS the authorisation. Submitting the register+// via invitation" mode when invitation registration is enabled. Submitting the register// form with this set hits /auth/register-by-invite (auto-login on// success) instead of /auth/register.const inviteToken = ref('')@@ -507,7 +503,7 @@ const registerRules = computed(() => ({// Toggle login/register modeconst toggleMode = () => {- isRegisterMode.value = !isRegisterMode.value+ isRegisterMode.value = !isRegisterMode.value && registrationEnabled.valueObject.keys(registerData).forEach(key => {(registerData as any)[key] = ''@@ -612,16 +608,14 @@ const loadOIDCConfig = async () => {}}-// loadAuthConfig fetches /auth/config and caches whether self-service-// registration is allowed. Failures fall back to "enabled" so a transient-// network glitch doesn't lock new users out of an open deployment.+// Registration stays hidden if configuration cannot be loaded.const loadAuthConfig = async () => {try {const response = await getAuthConfig()- registrationEnabled.value = response.registration_mode !== 'invite_only'+ registrationMode.value = response.success ? response.registration_mode : ''complexPasswordEnabled.value = response.complex_password_enabled} catch {- registrationEnabled.value = true+ registrationMode.value = ''complexPasswordEnabled.value = false}}@@ -707,6 +701,7 @@ const handleLogin = async () => {// login on success); without -> the normal self-service register// (drops back to the login form for the user to sign in).const handleRegister = async () => {+ if (!registrationEnabled.value) returntry {const valid = await registerFormRef.value?.validate()if (valid !== true) return@@ -794,17 +789,15 @@ onMounted(async () => {inviteLookupLoading.value = false}- // 2. 已登录则直接兑换 token 进入空间(两种模式通用)。+ // 2. 已登录则直接兑换 token 进入空间(三种模式通用)。if (authStore.isLoggedIn && (await authStore.refreshFromAuthMe())) {await acceptAndEnter(tokenFromQuery)return}- // 3. 未登录:按注册模式决定界面。invite_only 停在登录页、登录后再兑换;self_serve 保持注册流程。- const cfg = await getAuthConfig()- const inviteOnly = cfg.registration_mode === 'invite_only'- registrationEnabled.value = !inviteOnly- isRegisterMode.value = !inviteOnly+ // 3. Only enabled registration modes may create an invited account.+ await loadAuthConfig()+ isRegisterMode.value = registrationEnabled.valueloadOIDCConfig()return}diff --git a/frontend/src/views/auth/registrationPolicy.test.ts b/frontend/src/views/auth/registrationPolicy.test.tsnew file mode 100644index 000000000..d04f7808c--- /dev/null+++ b/frontend/src/views/auth/registrationPolicy.test.ts@@ -0,0 +1,16 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { canRegister } from './registrationPolicy'++for (const [mode, withoutInvite, withInvite] of [+ ['self_serve', true, true],+ ['invite_register', false, true],+ ['invite_only', false, false],+ ['', false, false],+ ['unknown', false, false],+] as const) {+ test(`registration entry for ${mode || 'unavailable configuration'}`, () => {+ assert.equal(canRegister(mode, false), withoutInvite)+ assert.equal(canRegister(mode, true), withInvite)+ })+}diff --git a/frontend/src/views/auth/registrationPolicy.ts b/frontend/src/views/auth/registrationPolicy.tsnew file mode 100644index 000000000..5238b301e--- /dev/null+++ b/frontend/src/views/auth/registrationPolicy.ts@@ -0,0 +1,4 @@+/** Whether the login page may offer password registration. */+export function canRegister(mode: string, hasValidInvitation: boolean): boolean {+ return mode === 'self_serve' || (mode === 'invite_register' && hasValidInvitation)+}diff --git a/internal/application/service/system_setting.go b/internal/application/service/system_setting.goindex 3edd34b62..187819059 100644--- a/internal/application/service/system_setting.go+++ b/internal/application/service/system_setting.go@@ -139,10 +139,10 @@ var registry = map[string]settingSpec{Type: "string",EnvName: "", // No env fallback — handler passes cfg.Auth.RegistrationMode as defaultDefault: "self_serve",- Enum: []string{"self_serve", "invite_only"},+ Enum: []string{"self_serve", "invite_register", "invite_only"},Category: "auth",- Description: "自助注册模式。self_serve = 任何人可注册账号;invite_only = 关闭公网注册," +- "仅 Owner/Admin 可邀请。修改后立即生效,但谨慎对待 self_serve(公网会接受 spam)。",+ Description: "注册模式。self_serve = 开放注册;invite_register = 仅持有效邀请链接的新用户可注册;" ++ "invite_only = 禁止注册,邀请仅供已有账号加入空间。保存后立即生效。",},"auth.default_tenant_mode": {Type: "string",diff --git a/internal/application/service/system_setting_validation_test.go b/internal/application/service/system_setting_validation_test.goindex 0523e6b26..c92e5e8ea 100644--- a/internal/application/service/system_setting_validation_test.go+++ b/internal/application/service/system_setting_validation_test.go@@ -1,6 +1,12 @@package service-import "testing"+import (+ "context"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+)func TestValidateWorkerConcurrencyMinimums(t *testing.T) {tests := []struct {@@ -31,3 +37,34 @@ func TestValidateWorkerConcurrencyMinimums(t *testing.T) {})}}++type registrationSettingRepo struct {+ interfaces.SystemSettingRepository+ row *types.SystemSetting+}++func (r *registrationSettingRepo) Get(context.Context, string) (*types.SystemSetting, error) {+ return r.row, nil+}++func (r *registrationSettingRepo) Upsert(_ context.Context, row *types.SystemSetting) error {+ r.row = row+ return nil+}++func TestValidateRegistrationModes(t *testing.T) {+ svc := &systemSettingService{repo: ®istrationSettingRepo{}, cache: make(map[string]*types.SystemSetting)}+ ctx := context.WithValue(context.Background(), types.UserIDContextKey, "system-admin")+ for _, mode := range []string{"self_serve", "invite_register", "invite_only"} {+ row, err := svc.Update(ctx, "auth.registration_mode", mode)+ if err != nil {+ t.Fatalf("mode %q rejected: %v", mode, err)+ }+ if len(row.Enum) != 3 || svc.GetString(ctx, "auth.registration_mode", "", "") != mode {+ t.Fatalf("saved mode %q must be effective and expose all three choices", mode)+ }+ }+ if _, err := svc.Update(ctx, "auth.registration_mode", "unknown"); err == nil {+ t.Fatal("unknown registration mode accepted")+ }+}diff --git a/internal/config/auth_legacy_env_test.go b/internal/config/auth_legacy_env_test.goindex 5160c3f00..c948b3a3e 100644--- a/internal/config/auth_legacy_env_test.go+++ b/internal/config/auth_legacy_env_test.go@@ -23,6 +23,14 @@ func TestApplyAuthAndTenantDefaults_DisableRegistrationDrivesRegistrationMode(t{"false leaves YAML untouched", "false", AuthRegistrationModeSelfServe, AuthRegistrationModeSelfServe},{"unset falls back to default self_serve", "", "", AuthRegistrationModeSelfServe},{"unset keeps explicit invite_only YAML", "", AuthRegistrationModeInviteOnly, AuthRegistrationModeInviteOnly},+ {+ "unset keeps invitation registration", "",+ AuthRegistrationModeInviteRegister, AuthRegistrationModeInviteRegister,+ },+ {+ "legacy disable overrides invitation registration", "true",+ AuthRegistrationModeInviteRegister, AuthRegistrationModeInviteOnly,+ },}for _, tc := range cases {@@ -181,3 +189,10 @@ func TestApplyAuthAndTenantDefaults_ComplexPasswordEnabledEnv(t *testing.T) {}})}++func TestValidateInvitationRegistrationMode(t *testing.T) {+ cfg := &Config{Auth: &AuthConfig{RegistrationMode: AuthRegistrationModeInviteRegister}}+ if err := ValidateConfig(cfg); err != nil {+ t.Fatalf("invitation registration mode rejected: %v", err)+ }+}diff --git a/internal/config/config.go b/internal/config/config.goindex 058824f39..541bc42a1 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -273,13 +273,14 @@ type AuditConfig struct {// AuthConfig governs the user authentication entry points.type AuthConfig struct {- // RegistrationMode controls who may call POST /auth/register.+ // RegistrationMode controls public and invitation password registration.// "self_serve" (default) — anyone may register; a new tenant is// auto-created and the registrant becomes// its Owner. Preserves existing behaviour.- // "invite_only" — public registration is rejected; new- // users only enter through the invitation- // flow added in PR 3.+ // "invite_register" — new users need a valid invitation link.+ // "invite_only" — no password registration; invitations can+ // only be accepted by existing accounts.+ // Kept as the legacy disabled mode.RegistrationMode string `yaml:"registration_mode" json:"registration_mode"`// DefaultTenantMode controls public password-registration provisioning.// create_personal preserves the historical one-user-one-workspace default;@@ -293,14 +294,13 @@ type AuthConfig struct {const (AuthRegistrationModeSelfServe = "self_serve"AuthRegistrationModeInviteOnly = "invite_only"+ AuthRegistrationModeInviteRegister = "invite_register"AuthDefaultTenantModeCreatePersonal = "create_personal"AuthDefaultTenantModeTenantless = "tenantless")-// IsInviteOnly returns true when registration is gated behind invitations.-// Treats nil receiver and empty/unknown values as "not invite-only" so the-// default keeps current behaviour even if the section is missing from the-// config file.+// IsInviteOnly identifies the legacy disabled-registration mode.+// It does not identify the invite_register mode, which permits new accounts.func (c *AuthConfig) IsInviteOnly() bool {if c == nil {return false@@ -638,9 +638,11 @@ func ValidateConfig(cfg *Config) error {if cfg.Auth != nil {mode := strings.TrimSpace(cfg.Auth.RegistrationMode)- if mode != "" && mode != AuthRegistrationModeSelfServe && mode != AuthRegistrationModeInviteOnly {- errs = append(errs, fmt.Sprintf("auth.registration_mode must be %q or %q, got %q",- AuthRegistrationModeSelfServe, AuthRegistrationModeInviteOnly, mode))+ if mode != "" && mode != AuthRegistrationModeSelfServe &&+ mode != AuthRegistrationModeInviteOnly && mode != AuthRegistrationModeInviteRegister {+ errs = append(errs, fmt.Sprintf("auth.registration_mode must be %q, %q or %q, got %q",+ AuthRegistrationModeSelfServe, AuthRegistrationModeInviteOnly,+ AuthRegistrationModeInviteRegister, mode))}tenantMode := strings.TrimSpace(cfg.Auth.DefaultTenantMode)diff --git a/internal/handler/auth.go b/internal/handler/auth.goindex 85283189e..9efeaed51 100644--- a/internal/handler/auth.go+++ b/internal/handler/auth.go@@ -181,16 +181,11 @@ func (h *AuthHandler) Register(c *gin.Context) {logger.Info(ctx, "Start user registration")- // 当 auth.registration_mode=invite_only 时,public 注册被关闭。- // 优先级:DB system_settings > cfg.Auth.RegistrationMode > "self_serve"。- // SystemAdmin 通过「全局设置」UI 实时切换 self_serve / invite_only,立即- // 生效,不需要重启服务。历史变量 DISABLE_REGISTRATION=true 仍在 config- // 启动阶段被等价提升为 invite_only(applyAuthAndTenantDefaults),- // 作为 cfg-default 进入 resolveRegistrationMode。- if h.resolveRegistrationMode(ctx) == config.AuthRegistrationModeInviteOnly {- logger.Warn(ctx, "Registration rejected: auth.registration_mode=invite_only")- appErr := errors.NewForbiddenError("Registration is invite-only")- c.Error(appErr)+ // Only self_serve permits registration without an invitation. Resolve+ // each request so system-settings changes take effect immediately.+ if h.resolveRegistrationMode(ctx) != config.AuthRegistrationModeSelfServe {+ logger.Warn(ctx, "Public registration rejected by auth.registration_mode")+ _ = c.Error(errors.NewForbiddenError("Public registration is disabled"))return}diff --git a/internal/handler/auth_register_by_invite.go b/internal/handler/auth_register_by_invite.goindex 2c20860de..1e5394f9d 100644--- a/internal/handler/auth_register_by_invite.go+++ b/internal/handler/auth_register_by_invite.go@@ -7,6 +7,7 @@ import ("github.com/gin-gonic/gin""github.com/Tencent/WeKnora/internal/application/service"+ "github.com/Tencent/WeKnora/internal/config"apperrors "github.com/Tencent/WeKnora/internal/errors""github.com/Tencent/WeKnora/internal/handler/dto""github.com/Tencent/WeKnora/internal/logger"@@ -107,7 +108,7 @@ func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {// RegisterByInvite godoc// @Summary 使用共享链接注册-// @Description 通过 Owner 生成的共享邀请链接 token 完成注册,绕过 invite_only 模式拦截。+// @Description 通过共享邀请链接 token 完成注册,仅 self_serve / invite_register 模式允许。// @Description 注册者自填邮箱(与 token 不绑定);注册成功后自动加入对应空间。// @Tags 认证// @Accept json@@ -115,16 +116,21 @@ func (h *AuthHandler) LookupInvitationByToken(c *gin.Context) {// @Param request body registerByInviteRequest true "邀请注册请求"// @Success 201 {object} types.LoginResponse// @Failure 400 {object} apperrors.AppError "请求参数错误"+// @Failure 403 {object} apperrors.AppError "注册功能已禁用"// @Failure 409 {object} apperrors.AppError "邮箱已注册"// @Failure 410 {object} apperrors.AppError "链接无效或已撤销"// @Router /auth/register-by-invite [post]//-// RegisterByInvite is intentionally NOT subject to the invite_only gate:-// the gate suppresses public registration, while this endpoint requires-// a valid token issued by an Owner. The token IS the authorisation.+// RegisterByInvite requires both an enabled registration mode and a valid token.func (h *AuthHandler) RegisterByInvite(c *gin.Context) {ctx := c.Request.Context()+ mode := h.resolveRegistrationMode(ctx)+ if mode != config.AuthRegistrationModeSelfServe && mode != config.AuthRegistrationModeInviteRegister {+ _ = c.Error(apperrors.NewForbiddenError("Registration is disabled"))+ return+ }+if h.invitationSvc == nil {c.Error(apperrors.NewInternalServerError("invitation service unavailable"))returndiff --git a/internal/handler/auth_register_by_invite_tenant_test.go b/internal/handler/auth_register_by_invite_tenant_test.goindex f961aa840..a016b549d 100644--- a/internal/handler/auth_register_by_invite_tenant_test.go+++ b/internal/handler/auth_register_by_invite_tenant_test.go@@ -8,6 +8,7 @@ import ("net/http/httptest""testing"+ "github.com/Tencent/WeKnora/internal/config""github.com/Tencent/WeKnora/internal/types""github.com/Tencent/WeKnora/internal/types/interfaces""github.com/gin-gonic/gin"@@ -42,9 +43,13 @@ func (s *invitedRegistrationUserService) GenerateTokens(context.Context, *types.type invitedRegistrationInvitationService struct {interfaces.TenantInvitationServiceacceptErr error+ lookupErr error}func (s *invitedRegistrationInvitationService) LookupByToken(context.Context, string) (*types.TenantInvitation, error) {+ if s.lookupErr != nil {+ return nil, s.lookupErr+ }return &types.TenantInvitation{TenantID: 42, Role: types.TenantRoleViewer}, nil}@@ -147,3 +152,49 @@ func TestRegisterByInviteRejectsSimplePasswordWhenComplexEnabled(t *testing.T) {t.Fatalf("Register was called with mode=%q", users.registeredMode)}}++func TestRegisterByInviteRegistrationModes(t *testing.T) {+ for _, tc := range []struct {+ name string+ mode string+ lookupErr error+ want int+ }{+ {"open", config.AuthRegistrationModeSelfServe, nil, http.StatusCreated},+ {"invited", config.AuthRegistrationModeInviteRegister, nil, http.StatusCreated},+ {"disabled", config.AuthRegistrationModeInviteOnly, nil, http.StatusForbidden},+ {"unknown mode", "invalid", nil, http.StatusForbidden},+ {"invalid invitation", config.AuthRegistrationModeInviteRegister, errors.New("invalid"), http.StatusGone},+ {"expired invitation", config.AuthRegistrationModeInviteRegister, errors.New("expired"), http.StatusGone},+ {"revoked invitation", config.AuthRegistrationModeInviteRegister, errors.New("revoked"), http.StatusGone},+ } {+ t.Run(tc.name, func(t *testing.T) {+ users := &invitedRegistrationUserService{}+ h := &AuthHandler{+ configInfo: &config.Config{Auth: &config.AuthConfig{RegistrationMode: tc.mode}},+ userService: users,+ tenantService: &invitedRegistrationTenantService{},+ invitationSvc: &invitedRegistrationInvitationService{lookupErr: tc.lookupErr},+ }+ r := gin.New()+ r.Use(errorCapture())+ r.POST("/auth/register-by-invite", h.RegisterByInvite)+ req := httptest.NewRequest(http.MethodPost, "/auth/register-by-invite", bytes.NewBufferString(+ `{"token":"invite-token","email":"[email protected]","username":"alice","password":"supersecret1"}`))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)+ if w.Code != tc.want {+ t.Fatalf("status=%d, want %d body=%s", w.Code, tc.want, w.Body.String())+ }+ if tc.want == http.StatusCreated {+ if users.registeredMode != types.TenantProvisioningTenantless || users.updatedTenant != 42 {+ t.Fatalf("expected account in invited tenant only: mode=%q tenant=%d",+ users.registeredMode, users.updatedTenant)+ }+ } else if users.registeredMode != "" {+ t.Fatal("rejected registration must not create an account")+ }+ })+ }+}diff --git a/internal/handler/auth_register_invite_only_test.go b/internal/handler/auth_register_invite_only_test.goindex 02c55f987..7330ef7ab 100644--- a/internal/handler/auth_register_invite_only_test.go+++ b/internal/handler/auth_register_invite_only_test.go@@ -223,3 +223,68 @@ func TestRegister_PreservesPasswordBytes(t *testing.T) {gotPassword, originalPassword)}}++// Settings are resolved on every request, for the UI and both registration APIs.+type registrationModeSettings struct {+ interfaces.SystemSettingService+ mode string+}++func (s *registrationModeSettings) GetString(_ context.Context, key, _, fallback string) string {+ if key == "auth.registration_mode" {+ return s.mode+ }+ return fallback+}++func (s *registrationModeSettings) GetBool(_ context.Context, _, _ string, fallback bool) bool {+ return fallback+}++func TestRegistrationModeChangesApplyImmediately(t *testing.T) {+ settings := ®istrationModeSettings{}+ h := &AuthHandler{+ configInfo: &config.Config{+ Auth: &config.AuthConfig{RegistrationMode: config.AuthRegistrationModeInviteOnly},+ },+ systemSettingSvc: settings,+ userService: &invitedRegistrationUserService{},+ tenantService: &invitedRegistrationTenantService{},+ invitationSvc: &invitedRegistrationInvitationService{},+ }+ r := newRegisterTestRouter(h)+ r.POST("/auth/register-by-invite", h.RegisterByInvite)+ r.GET("/auth/config", h.GetAuthConfig)+ for _, mode := range []string{+ config.AuthRegistrationModeInviteRegister,+ config.AuthRegistrationModeSelfServe,+ config.AuthRegistrationModeInviteOnly,+ } {+ settings.mode = mode+ w := httptest.NewRecorder()+ r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/auth/config", nil))+ var cfg struct {+ RegistrationMode string `json:"registration_mode"`+ }+ if err := json.Unmarshal(w.Body.Bytes(), &cfg); err != nil || cfg.RegistrationMode != mode {+ t.Fatalf("config must expose live mode %q: %s", mode, w.Body.String())+ }+ for _, path := range []string{"/auth/register", "/auth/register-by-invite"} {+ body := validRegisterBody()+ body["token"] = "valid-token"+ data, _ := json.Marshal(body)+ req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(data))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)+ want := http.StatusForbidden+ if mode == config.AuthRegistrationModeSelfServe ||+ (mode == config.AuthRegistrationModeInviteRegister && path == "/auth/register-by-invite") {+ want = http.StatusCreated+ }+ if w.Code != want {+ t.Fatalf("mode=%s path=%s status=%d want=%d body=%s", mode, path, w.Code, want, w.Body.String())+ }+ }+ }+}diff --git a/website-docs/03-features/01-tenant-auth.md b/website-docs/03-features/01-tenant-auth.mdindex babbe2e53..eda134141 100644--- a/website-docs/03-features/01-tenant-auth.md+++ b/website-docs/03-features/01-tenant-auth.md@@ -80,7 +80,7 @@ graph TB```gotype AuthConfig struct {- RegistrationMode string // "self_serve"(默认,公开注册) | "invite_only"(仅邀请)+ RegistrationMode string // "self_serve"(默认,公开注册) | "invite_register"(仅限邀请注册) | "invite_only"(禁止注册,保留旧配置值)DefaultTenantMode string // "create_personal"(默认,自动建个人租户) | "tenantless"(无租户等待邀请)}@@ -97,10 +97,17 @@ func (c *AuthConfig) IsInviteOnly() bool {后果是:系统管理员在界面上把 `auth.registration_mode` 设成 `self_serve` 后,即使部署里仍写着 `DISABLE_REGISTRATION=true`,公开注册也是开着的。要彻底关掉,得把数据库里那一行重置(`DELETE /system/admin/settings/auth.registration_mode`)。-`invite_only` 模式下 `POST /auth/register` 返回 403,但它只挡住**密码自助注册**这一条路,以下两条不受影响:+注册模式有三个档位,可在全局设置中即时切换:-- **邀请注册端点** `POST /auth/register-by-invite`(设计如此,见 [邀请注册(register-by-invite)](#_2-3-邀请注册-register-by-invite));-- **OIDC 首次登录**:`LoginWithOIDC()` 查不到邮箱时直接 `provisionOIDCUser()` 建号,全程不读注册模式。也就是说开了 OIDC 之后,`invite_only` 挡不住 IdP 里的任何人——要限制范围得在 IdP 侧做(应用可见性 / 用户组),或干脆关掉 OIDC。+| 模式 | 公开注册 | 有效邀请链接注册 | 已有账号接受邀请 |+| --- | --- | --- | --- |+| `self_serve`(开放注册) | 允许 | 允许 | 允许 |+| `invite_register`(仅限邀请注册) | 禁止 | 允许 | 允许 |+| `invite_only`(禁止注册,保留旧配置值) | 禁止 | 禁止 | 允许 |++`DISABLE_REGISTRATION=true` 仍映射到原有的 `invite_only`。需要让受邀的新用户注册时,将全局设置改为 `invite_register`。禁止注册时,`POST /auth/register-by-invite` 也返回 403,与登录页行为一致。++这些档位控制密码注册。**OIDC 首次登录**仍由 IdP 的应用可见性、用户组等策略控制;管理员创建账号也不受此设置影响。#### 密码注册 / 登录 {#_2-2-密码注册-登录}@@ -112,7 +119,7 @@ func (c *AuthConfig) IsInviteOnly() bool {#### 邀请注册(register-by-invite) {#_2-3-邀请注册-register-by-invite}-`internal/handler/auth_register_by_invite.go`。租户 Owner 生成的**共享邀请链接**(share link,见 [共享邀请链接(invite link)](#_7-2-共享邀请链接-invite-link))持有 token,注册页凭 token 完成注册,即使系统处于 `invite_only` 模式:+`internal/handler/auth_register_by_invite.go`。租户 Owner 生成的**共享邀请链接**(share link,见 [共享邀请链接(invite link)](#_7-2-共享邀请链接-invite-link))持有 token,注册页凭 token 完成注册,支持 `self_serve` 和 `invite_register` 模式:```go// POST /auth/register-by-invite@@ -130,7 +137,7 @@ type registerByInviteRequest struct {#### 已注册用户通过邀请链接加入-invite_only 部署中,邀请页面引导用户先登录,再向 `POST /me/invitations/accept-by-token` 提交 token 加入空间;不需要为已注册邮箱再创建账号。没有默认空间的用户首次加入后,以该空间作为默认空间。`register-by-invite` 仍是凭有效邀请创建新账号的 API。+invite_only 部署中,邀请页面引导用户先登录,再向 `POST /me/invitations/accept-by-token` 提交 token 加入空间;不需要为已注册邮箱再创建账号。没有默认空间的用户首次加入后,以该空间作为默认空间。`invite_register` 模式下,新用户可凭有效邀请注册;已有账号可切换到登录表单加入,且可以切回注册表单。邮箱邀请已注册用户还受 `tenant.auto_accept_invitation` 控制:默认 false,创建 pending 邀请并等收件箱确认;true 时直接加入,返回 active 成员并处理已有 pending 邀请。前端从 `GET /auth/me` 的 `capabilities.auto_accept_invitation` 感知该开关。它不把任意共享链接变成免登录入口。@@ -474,7 +481,7 @@ sequenceDiagram| 配置项 | 取值 | 默认 | 作用 || --- | --- | --- | --- |-| `auth.registration_mode` | `self_serve` / `invite_only` | `self_serve` | 公开注册开关(DB system_settings 可热改) |+| `auth.registration_mode` | `self_serve` / `invite_register` / `invite_only` | `self_serve` | 密码注册模式(DB system_settings 可热改) || `auth.default_tenant_mode` | `create_personal` / `tenantless` | `create_personal` | 新用户是否自动建个人租户 || `tenant.enable_rbac` | `true` / `false` | `true` | RBAC 强制执行 / 仅日志模式 || `JWT_SECRET`(环境变量) | 任意字符串 | 随机 32 字节 | JWT HMAC 密钥 |diff --git a/website-docs/04-api/02-api-auth.md b/website-docs/04-api/02-api-auth.mdindex b1585230c..7211ed1f2 100644--- a/website-docs/04-api/02-api-auth.md+++ b/website-docs/04-api/02-api-auth.md@@ -16,7 +16,7 @@| `email` | string | 是 | 邮箱 || `password` | string | 是 | 密码(8–32 位,字母+数字;复杂模式另需大小写和特殊字符) |-是否自动创建个人空间由服务端的 `auth.default_tenant_mode` 决定,请求体不能指定。`invite_only` 模式下返回 403。+是否自动创建个人空间由服务端的 `auth.default_tenant_mode` 决定,请求体不能指定。`invite_register`(仅限邀请注册)和 `invite_only`(禁止注册)模式下返回 403。响应:201 `{"success":true,"message":"...","user":{User}}`@@ -27,6 +27,8 @@ curl -X POST $BASE/api/v1/auth/register -H 'Content-Type: application/json' \### POST /api/v1/auth/register-by-invite+仅 `self_serve` 和 `invite_register` 模式允许凭有效邀请链接注册;`invite_only` 模式返回 403。+用途:通过邀请/分享链接 token 注册并加入空间。免认证,IP 限流 30 次/分钟。Handler: `internal/handler/auth_register_by_invite.go`| 字段 | 类型 | 必填 | 说明 |@@ -82,7 +84,7 @@ curl -X POST $BASE/api/v1/auth/login -H 'Content-Type: application/json' -d '{"e用途:查询注册模式等认证配置。免认证。Handler: `internal/handler/auth.go`-响应:200 `{"success":true,"registration_mode":"self_serve|invite_only","complex_password_enabled":false}`+响应:200 `{"success":true,"registration_mode":"self_serve|invite_register|invite_only","complex_password_enabled":false}````bashcurl $BASE/api/v1/auth/config