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(system): add admin password reset with session revocation
wizardchen8ec65941a5bf
diff --git a/docs/docs.go b/docs/docs.goindex aee638ac2..cf62b806f 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -11148,31 +11148,21 @@ const docTemplate = `{}}},- "/system/admin/settings": {+ "/system/admin/runtime/queues": {"get": {- "description": "Return every row in the system_settings table (system-scope,\nnot tenant-scope). SystemAdmin only.",+ "description": "返回各 asynq 队列的实时深度(pending/active/scheduled/retry 等)与 worker 并发配置,仅系统管理员可见","produces": ["application/json"],"tags": [- "System Admin"+ "系统管理"],- "summary": "List all system settings",+ "summary": "获取解析任务队列运行时状态","responses": {"200": {- "description": "list of settings",- "schema": {- "type": "array",- "items": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SystemSetting"- }- }- },- "403": {- "description": "Forbidden: not a system admin",+ "description": "OK","schema": {- "type": "object",- "additionalProperties": true+ "$ref": "#/definitions/internal_handler.RuntimeQueuesResponse"}}}@@ -11341,6 +11331,62 @@ const docTemplate = `{}}},+ "/system/admin/users/reset-password": {+ "post": {+ "description": "Replace another user's local password and revoke all of their existing sessions (SystemAdmin only).\nA system administrator cannot reset their own password through this endpoint; self-service password change still requires the old password.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "System Admin"+ ],+ "summary": "Reset another user's password",+ "parameters": [+ {+ "description": "Password reset request",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/internal_handler.ResetUserPasswordRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Password reset successfully",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "400": {+ "description": "Invalid request, weak password, or self reset",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "403": {+ "description": "Forbidden: not a system admin",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "404": {+ "description": "User not found",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ }+ }+ }+ },"/system/docreader/reconnect": {"post": {"consumes": [@@ -13737,6 +13783,7 @@ const docTemplate = `{2002,2003,2004,+ 2005,2100,2101,2102,@@ -13761,6 +13808,7 @@ const docTemplate = `{"ErrTenantInactive","ErrTenantNameRequired","ErrTenantInvalidStatus",+ "ErrTenantCreationDisabled","ErrAgentMissingThinkingModel","ErrAgentMissingAllowedTools","ErrAgentInvalidMaxIterations",@@ -13865,6 +13913,26 @@ const docTemplate = `{}}},+ "github_com_Tencent_WeKnora_internal_models_limiter.RuntimeStat": {+ "type": "object",+ "properties": {+ "active": {+ "type": "integer"+ },+ "limit": {+ "type": "integer"+ },+ "model_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "waiting": {+ "type": "integer"+ }+ }+ },"github_com_Tencent_WeKnora_internal_types.APIPrincipalMode": {"type": "string","enum": [@@ -13953,7 +14021,8 @@ const docTemplate = `{"opensearch.reindex_executed","system.setting_changed","system.admin_promoted",- "system.admin_revoked"+ "system.admin_revoked",+ "system.user_password_reset"],"x-enum-varnames": ["AuditActionMemberAdded",@@ -13974,7 +14043,8 @@ const docTemplate = `{"AuditActionOpenSearchReindexExecuted","AuditActionSystemSettingChanged","AuditActionSystemAdminPromoted",- "AuditActionSystemAdminRevoked"+ "AuditActionSystemAdminRevoked",+ "AuditActionSystemUserPasswordReset"]},"github_com_Tencent_WeKnora_internal_types.AuditLog": {@@ -14123,6 +14193,10 @@ const docTemplate = `{"description": "Strategy selects the adaptive chunking tier. Empty / \"legacy\" preserves\nthe historical recursive splitter; \"auto\" lets a profiler pick between\nheading-aware, heuristic and recursive tiers; \"heading\" / \"heuristic\" /\n\"recursive\" pin the tier explicitly.","type": "string"},+ "table_metadata_instructions": {+ "description": "TableMetadataInstructions contains optional business guidance used when\ngenerating searchable summaries for CSV/Excel tables. The system-owned\noutput contract remains fixed; these instructions only add domain context.",+ "type": "string"+ },"token_limit": {"description": "TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize\nas a character count.","type": "integer"@@ -14629,6 +14703,10 @@ const docTemplate = `{"github_com_Tencent_WeKnora_internal_types.ExtractConfig": {"type": "object","properties": {+ "custom_instructions": {+ "description": "CustomInstructions adds domain-specific extraction guidance while the\nsystem keeps ownership of the structured graph output protocol.",+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -16693,6 +16771,10 @@ const docTemplate = `{"github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig": {"type": "object","properties": {+ "custom_instructions": {+ "description": "CustomInstructions describes the intended audience or question style.\nIt is appended to the stable system question-generation template.",+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -16702,6 +16784,63 @@ const docTemplate = `{}}},+ "github_com_Tencent_WeKnora_internal_types.QueueStat": {+ "type": "object",+ "properties": {+ "active": {+ "type": "integer"+ },+ "archived": {+ "type": "integer"+ },+ "completed": {+ "type": "integer"+ },+ "failed": {+ "type": "integer"+ },+ "latency_ms": {+ "description": "LatencyMs is the age of the oldest pending task, in milliseconds.",+ "type": "integer"+ },+ "memory_usage_bytes": {+ "description": "MemoryUsageBytes is the approximate Redis memory the queue occupies.",+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "paused": {+ "description": "Paused reports whether the queue is paused (tasks not consumed).",+ "type": "boolean"+ },+ "pending": {+ "type": "integer"+ },+ "pool": {+ "description": "Pool is the independent worker pool that drains this queue.",+ "type": "string"+ },+ "processed": {+ "description": "Processed / Failed are today's counters (reset daily).",+ "type": "integer"+ },+ "retry": {+ "type": "integer"+ },+ "scheduled": {+ "type": "integer"+ },+ "size": {+ "description": "Size is the total number of tasks in the queue (pending + active +\nscheduled + retry + aggregating + archived).",+ "type": "integer"+ },+ "weight": {+ "description": "Weight is the queue's scheduling weight inside its pool.",+ "type": "integer"+ }+ }+ },"github_com_Tencent_WeKnora_internal_types.RegisterRequest": {"type": "object","required": [@@ -17943,6 +18082,14 @@ const docTemplate = `{"description": "Base URL","type": "string"},+ "custom_instructions": {+ "description": "CustomInstructions adds KB-specific image interpretation guidance without\nreplacing the system-owned OCR and Markdown output contract.",+ "type": "string"+ },+ "description_language": {+ "description": "DescriptionLanguage controls the language used for generated image\ncaptions. Empty means follow the document/request language.",+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -18127,6 +18274,10 @@ const docTemplate = `{"github_com_Tencent_WeKnora_internal_types.WikiConfig": {"type": "object","properties": {+ "content_instructions": {+ "description": "ContentInstructions controls tone, structure and emphasis for generated\nsummary/entity/index prose. Citation and merge rules remain system-owned.",+ "type": "string"+ },"extraction_granularity": {"description": "ExtractionGranularity controls how many candidate slugs Pass 0 extracts\nper document. Empty / unknown value is treated as WikiExtractionStandard.","allOf": [@@ -18135,6 +18286,10 @@ const docTemplate = `{}]},+ "extraction_instructions": {+ "description": "ExtractionInstructions tells candidate extraction which domain concepts\nto emphasize without replacing the stable JSON/citation protocol.",+ "type": "string"+ },"ingest_batch_size": {"description": "IngestBatchSize controls how many pending ops a single batch claims and\nprocesses before scheduling a follow-up. 0 falls back to the hard-coded\ndefault (5). Larger batches amortize per-batch setup and let more docs\nshare the batch-internal Map/Reduce fan-out; smaller batches spread a\nKB's backlog across more concurrent batches (finer scheduling grain).","type": "integer"@@ -19283,6 +19438,9 @@ const docTemplate = `{"description": "Strategy / TokenLimit / Languages use pointer types so the\nhandler can distinguish \"field absent in payload\" (no change)\nfrom \"field present with empty/zero value\" (clear / disable).\nWithout that distinction, users could set strategy=\"auto\" once\nbut never reset it back to legacy / unset.","type": "string"},+ "tableMetadataInstructions": {+ "type": "string"+ },"tokenLimit": {"type": "integer"}@@ -19308,6 +19466,9 @@ const docTemplate = `{"description": "知识图谱配置","type": "object","properties": {+ "customInstructions": {+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -19338,6 +19499,9 @@ const docTemplate = `{"description": "问题生成配置","type": "object","properties": {+ "customInstructions": {+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -19659,6 +19823,21 @@ const docTemplate = `{}}},+ "internal_handler.ResetUserPasswordRequest": {+ "type": "object",+ "required": [+ "email",+ "new_password"+ ],+ "properties": {+ "email": {+ "type": "string"+ },+ "new_password": {+ "type": "string"+ }+ }+ },"internal_handler.RevokeSystemAdminRequest": {"type": "object","required": [@@ -19670,6 +19849,81 @@ const docTemplate = `{}}},+ "internal_handler.RuntimeQueuesResponse": {+ "type": "object",+ "properties": {+ "available": {+ "type": "boolean"+ },+ "model_limiter_available": {+ "type": "boolean"+ },+ "models": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_models_limiter.RuntimeStat"+ }+ },+ "parse_concurrency": {+ "description": "compatibility alias for upstream_concurrency",+ "type": "integer"+ },+ "pools": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/internal_handler.RuntimeWorkerPool"+ }+ },+ "queues": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QueueStat"+ }+ },+ "timestamp": {+ "type": "integer"+ },+ "upstream_concurrency": {+ "type": "integer"+ },+ "wiki_concurrency": {+ "description": "compatibility field",+ "type": "integer"+ }+ }+ },+ "internal_handler.RuntimeWorkerPool": {+ "description": "Return every row in the system_settings table (system-scope, not tenant-scope). SystemAdmin only.",+ "type": "object",+ "properties": {+ "active": {+ "description": "live workers assigned to this pool",+ "type": "integer"+ },+ "cluster_capacity": {+ "description": "sum of live server concurrency",+ "type": "integer"+ },+ "concurrency": {+ "description": "configured per instance",+ "type": "integer"+ },+ "instances": {+ "description": "live asynq server heartbeats",+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "queue_count": {+ "type": "integer"+ },+ "utilization": {+ "description": "Active / ClusterCapacity",+ "type": "number"+ }+ }+ },"internal_handler.SearchMessagesRequest": {"type": "object","required": [diff --git a/docs/swagger.json b/docs/swagger.jsonindex f85960b0c..b7d3d209a 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -11141,31 +11141,21 @@}}},- "/system/admin/settings": {+ "/system/admin/runtime/queues": {"get": {- "description": "Return every row in the system_settings table (system-scope,\nnot tenant-scope). SystemAdmin only.",+ "description": "返回各 asynq 队列的实时深度(pending/active/scheduled/retry 等)与 worker 并发配置,仅系统管理员可见","produces": ["application/json"],"tags": [- "System Admin"+ "系统管理"],- "summary": "List all system settings",+ "summary": "获取解析任务队列运行时状态","responses": {"200": {- "description": "list of settings",- "schema": {- "type": "array",- "items": {- "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.SystemSetting"- }- }- },- "403": {- "description": "Forbidden: not a system admin",+ "description": "OK","schema": {- "type": "object",- "additionalProperties": true+ "$ref": "#/definitions/internal_handler.RuntimeQueuesResponse"}}}@@ -11334,6 +11324,62 @@}}},+ "/system/admin/users/reset-password": {+ "post": {+ "description": "Replace another user's local password and revoke all of their existing sessions (SystemAdmin only).\nA system administrator cannot reset their own password through this endpoint; self-service password change still requires the old password.",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "System Admin"+ ],+ "summary": "Reset another user's password",+ "parameters": [+ {+ "description": "Password reset request",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/internal_handler.ResetUserPasswordRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Password reset successfully",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "400": {+ "description": "Invalid request, weak password, or self reset",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "403": {+ "description": "Forbidden: not a system admin",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "404": {+ "description": "User not found",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ }+ }+ }+ },"/system/docreader/reconnect": {"post": {"consumes": [@@ -13730,6 +13776,7 @@2002,2003,2004,+ 2005,2100,2101,2102,@@ -13754,6 +13801,7 @@"ErrTenantInactive","ErrTenantNameRequired","ErrTenantInvalidStatus",+ "ErrTenantCreationDisabled","ErrAgentMissingThinkingModel","ErrAgentMissingAllowedTools","ErrAgentInvalidMaxIterations",@@ -13858,6 +13906,26 @@}}},+ "github_com_Tencent_WeKnora_internal_models_limiter.RuntimeStat": {+ "type": "object",+ "properties": {+ "active": {+ "type": "integer"+ },+ "limit": {+ "type": "integer"+ },+ "model_id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "waiting": {+ "type": "integer"+ }+ }+ },"github_com_Tencent_WeKnora_internal_types.APIPrincipalMode": {"type": "string","enum": [@@ -13946,7 +14014,8 @@"opensearch.reindex_executed","system.setting_changed","system.admin_promoted",- "system.admin_revoked"+ "system.admin_revoked",+ "system.user_password_reset"],"x-enum-varnames": ["AuditActionMemberAdded",@@ -13967,7 +14036,8 @@"AuditActionOpenSearchReindexExecuted","AuditActionSystemSettingChanged","AuditActionSystemAdminPromoted",- "AuditActionSystemAdminRevoked"+ "AuditActionSystemAdminRevoked",+ "AuditActionSystemUserPasswordReset"]},"github_com_Tencent_WeKnora_internal_types.AuditLog": {@@ -14116,6 +14186,10 @@"description": "Strategy selects the adaptive chunking tier. Empty / \"legacy\" preserves\nthe historical recursive splitter; \"auto\" lets a profiler pick between\nheading-aware, heuristic and recursive tiers; \"heading\" / \"heuristic\" /\n\"recursive\" pin the tier explicitly.","type": "string"},+ "table_metadata_instructions": {+ "description": "TableMetadataInstructions contains optional business guidance used when\ngenerating searchable summaries for CSV/Excel tables. The system-owned\noutput contract remains fixed; these instructions only add domain context.",+ "type": "string"+ },"token_limit": {"description": "TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize\nas a character count.","type": "integer"@@ -14622,6 +14696,10 @@"github_com_Tencent_WeKnora_internal_types.ExtractConfig": {"type": "object","properties": {+ "custom_instructions": {+ "description": "CustomInstructions adds domain-specific extraction guidance while the\nsystem keeps ownership of the structured graph output protocol.",+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -16686,6 +16764,10 @@"github_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig": {"type": "object","properties": {+ "custom_instructions": {+ "description": "CustomInstructions describes the intended audience or question style.\nIt is appended to the stable system question-generation template.",+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -16695,6 +16777,63 @@}}},+ "github_com_Tencent_WeKnora_internal_types.QueueStat": {+ "type": "object",+ "properties": {+ "active": {+ "type": "integer"+ },+ "archived": {+ "type": "integer"+ },+ "completed": {+ "type": "integer"+ },+ "failed": {+ "type": "integer"+ },+ "latency_ms": {+ "description": "LatencyMs is the age of the oldest pending task, in milliseconds.",+ "type": "integer"+ },+ "memory_usage_bytes": {+ "description": "MemoryUsageBytes is the approximate Redis memory the queue occupies.",+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "paused": {+ "description": "Paused reports whether the queue is paused (tasks not consumed).",+ "type": "boolean"+ },+ "pending": {+ "type": "integer"+ },+ "pool": {+ "description": "Pool is the independent worker pool that drains this queue.",+ "type": "string"+ },+ "processed": {+ "description": "Processed / Failed are today's counters (reset daily).",+ "type": "integer"+ },+ "retry": {+ "type": "integer"+ },+ "scheduled": {+ "type": "integer"+ },+ "size": {+ "description": "Size is the total number of tasks in the queue (pending + active +\nscheduled + retry + aggregating + archived).",+ "type": "integer"+ },+ "weight": {+ "description": "Weight is the queue's scheduling weight inside its pool.",+ "type": "integer"+ }+ }+ },"github_com_Tencent_WeKnora_internal_types.RegisterRequest": {"type": "object","required": [@@ -17936,6 +18075,14 @@"description": "Base URL","type": "string"},+ "custom_instructions": {+ "description": "CustomInstructions adds KB-specific image interpretation guidance without\nreplacing the system-owned OCR and Markdown output contract.",+ "type": "string"+ },+ "description_language": {+ "description": "DescriptionLanguage controls the language used for generated image\ncaptions. Empty means follow the document/request language.",+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -18120,6 +18267,10 @@"github_com_Tencent_WeKnora_internal_types.WikiConfig": {"type": "object","properties": {+ "content_instructions": {+ "description": "ContentInstructions controls tone, structure and emphasis for generated\nsummary/entity/index prose. Citation and merge rules remain system-owned.",+ "type": "string"+ },"extraction_granularity": {"description": "ExtractionGranularity controls how many candidate slugs Pass 0 extracts\nper document. Empty / unknown value is treated as WikiExtractionStandard.","allOf": [@@ -18128,6 +18279,10 @@}]},+ "extraction_instructions": {+ "description": "ExtractionInstructions tells candidate extraction which domain concepts\nto emphasize without replacing the stable JSON/citation protocol.",+ "type": "string"+ },"ingest_batch_size": {"description": "IngestBatchSize controls how many pending ops a single batch claims and\nprocesses before scheduling a follow-up. 0 falls back to the hard-coded\ndefault (5). Larger batches amortize per-batch setup and let more docs\nshare the batch-internal Map/Reduce fan-out; smaller batches spread a\nKB's backlog across more concurrent batches (finer scheduling grain).","type": "integer"@@ -19276,6 +19431,9 @@"description": "Strategy / TokenLimit / Languages use pointer types so the\nhandler can distinguish \"field absent in payload\" (no change)\nfrom \"field present with empty/zero value\" (clear / disable).\nWithout that distinction, users could set strategy=\"auto\" once\nbut never reset it back to legacy / unset.","type": "string"},+ "tableMetadataInstructions": {+ "type": "string"+ },"tokenLimit": {"type": "integer"}@@ -19301,6 +19459,9 @@"description": "知识图谱配置","type": "object","properties": {+ "customInstructions": {+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -19331,6 +19492,9 @@"description": "问题生成配置","type": "object","properties": {+ "customInstructions": {+ "type": "string"+ },"enabled": {"type": "boolean"},@@ -19652,6 +19816,21 @@}}},+ "internal_handler.ResetUserPasswordRequest": {+ "type": "object",+ "required": [+ "email",+ "new_password"+ ],+ "properties": {+ "email": {+ "type": "string"+ },+ "new_password": {+ "type": "string"+ }+ }+ },"internal_handler.RevokeSystemAdminRequest": {"type": "object","required": [@@ -19663,6 +19842,81 @@}}},+ "internal_handler.RuntimeQueuesResponse": {+ "type": "object",+ "properties": {+ "available": {+ "type": "boolean"+ },+ "model_limiter_available": {+ "type": "boolean"+ },+ "models": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_models_limiter.RuntimeStat"+ }+ },+ "parse_concurrency": {+ "description": "compatibility alias for upstream_concurrency",+ "type": "integer"+ },+ "pools": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/internal_handler.RuntimeWorkerPool"+ }+ },+ "queues": {+ "type": "array",+ "items": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_types.QueueStat"+ }+ },+ "timestamp": {+ "type": "integer"+ },+ "upstream_concurrency": {+ "type": "integer"+ },+ "wiki_concurrency": {+ "description": "compatibility field",+ "type": "integer"+ }+ }+ },+ "internal_handler.RuntimeWorkerPool": {+ "description": "Return every row in the system_settings table (system-scope, not tenant-scope). SystemAdmin only.",+ "type": "object",+ "properties": {+ "active": {+ "description": "live workers assigned to this pool",+ "type": "integer"+ },+ "cluster_capacity": {+ "description": "sum of live server concurrency",+ "type": "integer"+ },+ "concurrency": {+ "description": "configured per instance",+ "type": "integer"+ },+ "instances": {+ "description": "live asynq server heartbeats",+ "type": "integer"+ },+ "name": {+ "type": "string"+ },+ "queue_count": {+ "type": "integer"+ },+ "utilization": {+ "description": "Active / ClusterCapacity",+ "type": "number"+ }+ }+ },"internal_handler.SearchMessagesRequest": {"type": "object","required": [diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex e7e4e1af5..6e9accfa0 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -109,6 +109,7 @@ definitions:- 2002- 2003- 2004+ - 2005- 2100- 2101- 2102@@ -133,6 +134,7 @@ definitions:- ErrTenantInactive- ErrTenantNameRequired- ErrTenantInvalidStatus+ - ErrTenantCreationDisabled- ErrAgentMissingThinkingModel- ErrAgentMissingAllowedTools- ErrAgentInvalidMaxIterations@@ -205,6 +207,19 @@ definitions:tier:$ref: '#/definitions/github_com_Tencent_WeKnora_internal_infrastructure_chunker.StrategyTier'type: object+ github_com_Tencent_WeKnora_internal_models_limiter.RuntimeStat:+ properties:+ active:+ type: integer+ limit:+ type: integer+ model_id:+ type: string+ name:+ type: string+ waiting:+ type: integer+ type: objectgithub_com_Tencent_WeKnora_internal_types.APIPrincipalMode:enum:- tenant@@ -278,6 +293,7 @@ definitions:- system.setting_changed- system.admin_promoted- system.admin_revoked+ - system.user_password_resettype: stringx-enum-varnames:- AuditActionMemberAdded@@ -299,6 +315,7 @@ definitions:- AuditActionSystemSettingChanged- AuditActionSystemAdminPromoted- AuditActionSystemAdminRevoked+ - AuditActionSystemUserPasswordResetgithub_com_Tencent_WeKnora_internal_types.AuditLog:properties:action:@@ -419,6 +436,12 @@ definitions:heading-aware, heuristic and recursive tiers; "heading" / "heuristic" /"recursive" pin the tier explicitly.type: string+ table_metadata_instructions:+ description: |-+ TableMetadataInstructions contains optional business guidance used when+ generating searchable summaries for CSV/Excel tables. The system-owned+ output contract remains fixed; these instructions only add domain context.+ type: stringtoken_limit:description: |-TokenLimit caps chunk size in approximate tokens. 0 = use ChunkSize@@ -872,6 +895,11 @@ definitions:type: objectgithub_com_Tencent_WeKnora_internal_types.ExtractConfig:properties:+ custom_instructions:+ description: |-+ CustomInstructions adds domain-specific extraction guidance while the+ system keeps ownership of the structured graph output protocol.+ type: stringenabled:type: booleannodes:@@ -2407,6 +2435,11 @@ definitions:type: objectgithub_com_Tencent_WeKnora_internal_types.QuestionGenerationConfig:properties:+ custom_instructions:+ description: |-+ CustomInstructions describes the intended audience or question style.+ It is appended to the stable system question-generation template.+ type: stringenabled:type: booleanquestion_count:@@ -2414,6 +2447,48 @@ definitions:10)'type: integertype: object+ github_com_Tencent_WeKnora_internal_types.QueueStat:+ properties:+ active:+ type: integer+ archived:+ type: integer+ completed:+ type: integer+ failed:+ type: integer+ latency_ms:+ description: LatencyMs is the age of the oldest pending task, in milliseconds.+ type: integer+ memory_usage_bytes:+ description: MemoryUsageBytes is the approximate Redis memory the queue occupies.+ type: integer+ name:+ type: string+ paused:+ description: Paused reports whether the queue is paused (tasks not consumed).+ type: boolean+ pending:+ type: integer+ pool:+ description: Pool is the independent worker pool that drains this queue.+ type: string+ processed:+ description: Processed / Failed are today's counters (reset daily).+ type: integer+ retry:+ type: integer+ scheduled:+ type: integer+ size:+ description: |-+ Size is the total number of tasks in the queue (pending + active ++ scheduled + retry + aggregating + archived).+ type: integer+ weight:+ description: Weight is the queue's scheduling weight inside its pool.+ type: integer+ type: objectgithub_com_Tencent_WeKnora_internal_types.RegisterRequest:properties:email:@@ -3345,6 +3420,16 @@ definitions:base_url:description: Base URLtype: string+ custom_instructions:+ description: |-+ CustomInstructions adds KB-specific image interpretation guidance without+ replacing the system-owned OCR and Markdown output contract.+ type: string+ description_language:+ description: |-+ DescriptionLanguage controls the language used for generated image+ captions. Empty means follow the document/request language.+ type: stringenabled:type: booleaninterface_type:@@ -3484,12 +3569,22 @@ definitions:- WebSearchProviderTypeKeenablegithub_com_Tencent_WeKnora_internal_types.WikiConfig:properties:+ content_instructions:+ description: |-+ ContentInstructions controls tone, structure and emphasis for generated+ summary/entity/index prose. Citation and merge rules remain system-owned.+ type: stringextraction_granularity:allOf:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.WikiExtractionGranularity'description: |-ExtractionGranularity controls how many candidate slugs Pass 0 extractsper document. Empty / unknown value is treated as WikiExtractionStandard.+ extraction_instructions:+ description: |-+ ExtractionInstructions tells candidate extraction which domain concepts+ to emphasize without replacing the stable JSON/citation protocol.+ type: stringingest_batch_size:description: |-IngestBatchSize controls how many pending ops a single batch claims and@@ -4344,6 +4439,8 @@ definitions:Without that distinction, users could set strategy="auto" oncebut never reset it back to legacy / unset.type: string+ tableMetadataInstructions:+ type: stringtokenLimit:type: integertype: object@@ -4361,6 +4458,8 @@ definitions:nodeExtract:description: 知识图谱配置properties:+ customInstructions:+ type: stringenabled:type: booleannodes:@@ -4381,6 +4480,8 @@ definitions:questionGeneration:description: 问题生成配置properties:+ customInstructions:+ type: stringenabled:type: booleanquestionCount:@@ -4615,6 +4716,16 @@ definitions:required:- modelNametype: object+ internal_handler.ResetUserPasswordRequest:+ properties:+ email:+ type: string+ new_password:+ type: string+ required:+ - new_password+ type: objectinternal_handler.RevokeSystemAdminRequest:properties:user_id:@@ -4622,6 +4733,59 @@ definitions:required:- user_idtype: object+ internal_handler.RuntimeQueuesResponse:+ properties:+ available:+ type: boolean+ model_limiter_available:+ type: boolean+ models:+ items:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_models_limiter.RuntimeStat'+ type: array+ parse_concurrency:+ description: compatibility alias for upstream_concurrency+ type: integer+ pools:+ items:+ $ref: '#/definitions/internal_handler.RuntimeWorkerPool'+ type: array+ queues:+ items:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.QueueStat'+ type: array+ timestamp:+ type: integer+ upstream_concurrency:+ type: integer+ wiki_concurrency:+ description: compatibility field+ type: integer+ type: object+ internal_handler.RuntimeWorkerPool:+ description: Return every row in the system_settings table (system-scope, not+ tenant-scope). SystemAdmin only.+ properties:+ active:+ description: live workers assigned to this pool+ type: integer+ cluster_capacity:+ description: sum of live server concurrency+ type: integer+ concurrency:+ description: configured per instance+ type: integer+ instances:+ description: live asynq server heartbeats+ type: integer+ name:+ type: string+ queue_count:+ type: integer+ utilization:+ description: Active / ClusterCapacity+ type: number+ type: objectinternal_handler.SearchMessagesRequest:properties:limit:@@ -12261,28 +12425,19 @@ paths:summary: Revoke system administrator privileges from a usertags:- System Admin- /system/admin/settings:+ /system/admin/runtime/queues:get:- description: |-- Return every row in the system_settings table (system-scope,- not tenant-scope). SystemAdmin only.+ description: 返回各 asynq 队列的实时深度(pending/active/scheduled/retry 等)与 worker 并发配置,仅系统管理员可见produces:- application/jsonresponses:"200":- description: list of settings- schema:- items:- $ref: '#/definitions/github_com_Tencent_WeKnora_internal_types.SystemSetting'- type: array- "403":- description: 'Forbidden: not a system admin'+ description: OKschema:- additionalProperties: true- type: object- summary: List all system settings+ $ref: '#/definitions/internal_handler.RuntimeQueuesResponse'+ summary: 获取解析任务队列运行时状态tags:- - System Admin+ - 系统管理/system/admin/settings/{key}:delete:description: |-@@ -12410,6 +12565,46 @@ paths:summary: Apply the default storage quota to every existing tenanttags:- System Admin+ /system/admin/users/reset-password:+ post:+ consumes:+ - application/json+ description: |-+ Replace another user's local password and revoke all of their existing sessions (SystemAdmin only).+ A system administrator cannot reset their own password through this endpoint; self-service password change still requires the old password.+ parameters:+ - description: Password reset request+ in: body+ name: request+ required: true+ schema:+ $ref: '#/definitions/internal_handler.ResetUserPasswordRequest'+ produces:+ - application/json+ responses:+ "200":+ description: Password reset successfully+ schema:+ additionalProperties: true+ type: object+ "400":+ description: Invalid request, weak password, or self reset+ schema:+ additionalProperties: true+ type: object+ "403":+ description: 'Forbidden: not a system admin'+ schema:+ additionalProperties: true+ type: object+ "404":+ description: User not found+ schema:+ additionalProperties: true+ type: object+ summary: Reset another user's password+ tags:+ - System Admin/system/docreader/reconnect:post:consumes:diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.tsindex 5b4d58719..2aa92e668 100644--- a/frontend/src/api/system/index.ts+++ b/frontend/src/api/system/index.ts@@ -320,6 +320,21 @@ export async function listSystemAdmins(return response as unknown as ListSystemAdminsResponse}+export interface ResetUserPasswordRequest {+ email: string+ new_password: string+}++/**+ * Replace another user's password and revoke all of their active sessions.+ * The backend route is restricted to SystemAdmin callers and rejects attempts+ * to reset the caller's own password.+ */+export async function resetUserPassword(req: ResetUserPasswordRequest): Promise<{ message: string }> {+ const response = await post('/api/v1/system/admin/users/reset-password', req)+ return response as unknown as { message: string }+}+// ---- System Settings (P1) ----/**diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 43f8ffa97..43901927b 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -3768,6 +3768,32 @@ export default {},},},+ passwordReset: {+ label: 'Reset user password',+ description: 'Set a new password for another user who cannot sign in. A successful reset invalidates all of that user\'s current sessions, so they must sign in again with the new password.',+ action: 'Reset password',+ dialogTitle: 'Reset another user\'s password',+ warning: 'This is a high-risk action. Verify the user email carefully. You cannot reset your own password here.',+ emailLabel: 'User email',+ emailPlaceholder: 'Enter the email of the user to reset',+ newPasswordLabel: 'New password',+ newPasswordPlaceholder: '8-32 characters, including letters and numbers',+ confirmPasswordLabel: 'Confirm new password',+ confirmPasswordPlaceholder: 'Enter the new password again',+ confirmBtn: 'Confirm reset',+ success: 'Password reset; the user\'s existing sessions were revoked',+ failed: 'Failed to reset password',+ validation: {+ emailRequired: 'Enter the user email',+ emailInvalid: 'Enter a valid email address',+ passwordRequired: 'Enter a new password',+ passwordLength: 'Password must be 8-32 characters',+ passwordLetter: 'Password must contain a letter',+ passwordNumber: 'Password must contain a number',+ confirmRequired: 'Enter the new password again',+ passwordMismatch: 'The passwords do not match',+ },+ },bulkApply: {label: 'Apply to all existing tenants',tooltip: 'Saving the value only affects new tenants by default; click here to also overwrite every existing tenant.',@@ -3805,6 +3831,7 @@ export default {'system.setting_changed': 'System setting changed','system.admin_promoted': 'System admin granted','system.admin_revoked': 'System admin revoked',+ 'system.user_password_reset': 'User password reset',},outcome: {success: 'Success',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex e6fdc96f4..ca0b6ae2e 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -2753,6 +2753,32 @@ export default {},},},+ passwordReset: {+ label: "사용자 비밀번호 재설정",+ description: "로그인할 수 없는 다른 사용자의 새 비밀번호를 설정합니다. 재설정하면 해당 사용자의 현재 로그인 세션이 모두 만료되며 새 비밀번호로 다시 로그인해야 합니다.",+ action: "비밀번호 재설정",+ dialogTitle: "다른 사용자의 비밀번호 재설정",+ warning: "보안에 민감한 작업입니다. 사용자 이메일을 반드시 확인하세요. 여기서는 자신의 비밀번호를 재설정할 수 없습니다.",+ emailLabel: "사용자 이메일",+ emailPlaceholder: "비밀번호를 재설정할 사용자의 이메일 입력",+ newPasswordLabel: "새 비밀번호",+ newPasswordPlaceholder: "8~32자, 문자와 숫자 포함",+ confirmPasswordLabel: "새 비밀번호 확인",+ confirmPasswordPlaceholder: "새 비밀번호를 다시 입력",+ confirmBtn: "재설정 확인",+ success: "비밀번호가 재설정되고 기존 세션이 만료되었습니다",+ failed: "비밀번호 재설정 실패",+ validation: {+ emailRequired: "사용자 이메일을 입력하세요",+ emailInvalid: "올바른 이메일 주소를 입력하세요",+ passwordRequired: "새 비밀번호를 입력하세요",+ passwordLength: "비밀번호는 8~32자여야 합니다",+ passwordLetter: "비밀번호에 문자가 포함되어야 합니다",+ passwordNumber: "비밀번호에 숫자가 포함되어야 합니다",+ confirmRequired: "새 비밀번호를 다시 입력하세요",+ passwordMismatch: "비밀번호가 일치하지 않습니다",+ },+ },bulkApply: {label: "모든 기존 테넌트에 적용",tooltip: "저장한 값은 기본적으로 새로 생성되는 테넌트에만 적용됩니다. 이 버튼을 누르면 현재 값을 모든 기존 테넌트에도 덮어씁니다.",@@ -2790,6 +2816,7 @@ export default {"system.setting_changed": "시스템 설정 변경","system.admin_promoted": "시스템 관리자 부여","system.admin_revoked": "시스템 관리자 회수",+ "system.user_password_reset": "사용자 비밀번호 재설정",},outcome: {success: "성공",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex 6ef8b6975..4b16f73a2 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -2451,6 +2451,32 @@ export default {},},},+ passwordReset: {+ label: 'Сброс пароля пользователя',+ description: 'Задайте новый пароль другому пользователю, который не может войти. После сброса все его текущие сеансы будут завершены, и потребуется войти с новым паролем.',+ action: 'Сбросить пароль',+ dialogTitle: 'Сброс пароля другого пользователя',+ warning: 'Это операция повышенного риска. Внимательно проверьте email пользователя. Здесь нельзя сбросить собственный пароль.',+ emailLabel: 'Email пользователя',+ emailPlaceholder: 'Введите email пользователя',+ newPasswordLabel: 'Новый пароль',+ newPasswordPlaceholder: '8–32 символа, включая буквы и цифры',+ confirmPasswordLabel: 'Подтвердите новый пароль',+ confirmPasswordPlaceholder: 'Введите новый пароль ещё раз',+ confirmBtn: 'Подтвердить сброс',+ success: 'Пароль сброшен, существующие сеансы пользователя завершены',+ failed: 'Не удалось сбросить пароль',+ validation: {+ emailRequired: 'Введите email пользователя',+ emailInvalid: 'Введите корректный email',+ passwordRequired: 'Введите новый пароль',+ passwordLength: 'Пароль должен содержать от 8 до 32 символов',+ passwordLetter: 'Пароль должен содержать букву',+ passwordNumber: 'Пароль должен содержать цифру',+ confirmRequired: 'Введите новый пароль ещё раз',+ passwordMismatch: 'Пароли не совпадают',+ },+ },bulkApply: {label: 'Применить ко всем существующим тенантам',tooltip: 'По умолчанию сохранённое значение применяется только к новым тенантам. Нажмите, чтобы также перезаписать всех существующих.',@@ -2487,7 +2513,8 @@ export default {action: {'system.setting_changed': 'Изменена системная настройка','system.admin_promoted': 'Выдан системный администратор',- 'system.admin_revoked': 'Отозван системный администратор'+ 'system.admin_revoked': 'Отозван системный администратор',+ 'system.user_password_reset': 'Сброшен пароль пользователя'},outcome: {success: 'Успешно',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex fa79bb715..5c824dc89 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -2767,6 +2767,32 @@ export default {},},},+ passwordReset: {+ label: "重置用户密码",+ description: "为忘记密码的其他用户设置新密码。重置成功后,该用户当前所有登录会话都会失效,需要使用新密码重新登录。",+ action: "重置密码",+ dialogTitle: "重置其他用户的密码",+ warning: "这是高风险操作。请核对用户邮箱;出于安全考虑,不能在这里重置自己的密码。",+ emailLabel: "用户邮箱",+ emailPlaceholder: "输入需要重置密码的用户邮箱",+ newPasswordLabel: "新密码",+ newPasswordPlaceholder: "8-32 个字符,包含字母和数字",+ confirmPasswordLabel: "确认新密码",+ confirmPasswordPlaceholder: "再次输入新密码",+ confirmBtn: "确认重置",+ success: "密码已重置,该用户的现有会话已失效",+ failed: "重置密码失败",+ validation: {+ emailRequired: "请输入用户邮箱",+ emailInvalid: "请输入有效的邮箱地址",+ passwordRequired: "请输入新密码",+ passwordLength: "密码长度必须为 8-32 个字符",+ passwordLetter: "密码必须包含字母",+ passwordNumber: "密码必须包含数字",+ confirmRequired: "请再次输入新密码",+ passwordMismatch: "两次输入的密码不一致",+ },+ },bulkApply: {label: "应用到所有现有租户",tooltip: "保存的值默认只对之后新建的租户生效;点击此按钮将当前值同步写入所有现有租户。",@@ -2804,6 +2830,7 @@ export default {"system.setting_changed": "系统设置变更","system.admin_promoted": "授予系统管理员","system.admin_revoked": "回收系统管理员",+ "system.user_password_reset": "重置用户密码",},outcome: {success: "成功",diff --git a/frontend/src/views/system/SystemSettings.vue b/frontend/src/views/system/SystemSettings.vueindex fdae52bc2..57c47fa8d 100644--- a/frontend/src/views/system/SystemSettings.vue+++ b/frontend/src/views/system/SystemSettings.vue@@ -189,6 +189,24 @@</div></div>+ <div v-if="activeSettingsSection === 'access'" class="setting-row setting-row--password-reset">+ <div class="setting-info">+ <div class="setting-label">+ <span>{{ t('system.globalSettings.passwordReset.label') }}</span>+ <t-tag theme="danger" variant="light" size="small" class="setting-badge">+ {{ t('system.globalSettings.badgeHighRisk') }}+ </t-tag>+ </div>+ <p class="desc">{{ t('system.globalSettings.passwordReset.description') }}</p>+ </div>+ <div class="setting-control">+ <t-button theme="primary" variant="outline" @click="openPasswordResetDialog">+ <template #icon><t-icon name="lock-on" /></template>+ {{ t('system.globalSettings.passwordReset.action') }}+ </t-button>+ </div>+ </div>+<divv-for="item in activeSectionSettings":key="item.key"@@ -422,6 +440,68 @@<div class="sr-only" role="status" aria-live="polite">{{ saveAnnouncement }}</div></template>+ <t-dialog+ v-model:visible="passwordResetVisible"+ :header="t('system.globalSettings.passwordReset.dialogTitle')"+ width="460px"+ :confirm-btn="{+ content: t('system.globalSettings.passwordReset.confirmBtn'),+ theme: 'danger',+ loading: passwordResetSubmitting,+ }"+ :cancel-btn="t('system.globalSettings.confirm.cancelBtn')"+ :close-on-overlay-click="!passwordResetSubmitting"+ :close-btn="!passwordResetSubmitting"+ @confirm="submitPasswordReset"+ @close="resetPasswordResetForm"+ >+ <t-alert+ theme="warning"+ :message="t('system.globalSettings.passwordReset.warning')"+ class="password-reset-warning"+ />+ <t-form+ ref="passwordResetFormRef"+ :data="passwordResetForm"+ :rules="passwordResetRules"+ label-align="top"+ >+ <t-form-item :label="t('system.globalSettings.passwordReset.emailLabel')" name="email">+ <t-input+ v-model="passwordResetForm.email"+ type="email"+ clearable+ autocomplete="off"+ :disabled="passwordResetSubmitting"+ :placeholder="t('system.globalSettings.passwordReset.emailPlaceholder')"+ />+ </t-form-item>+ <t-form-item :label="t('system.globalSettings.passwordReset.newPasswordLabel')" name="newPassword">+ <t-input+ v-model="passwordResetForm.newPassword"+ type="password"+ autocomplete="new-password"+ :disabled="passwordResetSubmitting"+ :placeholder="t('system.globalSettings.passwordReset.newPasswordPlaceholder')"+ >+ <template #prefix-icon><t-icon name="lock-on" /></template>+ </t-input>+ </t-form-item>+ <t-form-item :label="t('system.globalSettings.passwordReset.confirmPasswordLabel')" name="confirmPassword">+ <t-input+ v-model="passwordResetForm.confirmPassword"+ type="password"+ autocomplete="new-password"+ :disabled="passwordResetSubmitting"+ :placeholder="t('system.globalSettings.passwordReset.confirmPasswordPlaceholder')"+ @enter="submitPasswordReset"+ >+ <template #prefix-icon><t-icon name="lock-on" /></template>+ </t-input>+ </t-form-item>+ </t-form>+ </t-dialog>+<!-- Platform audit-log drawer. Lazy-loaded on first open; closingand reopening doesn't re-fetch (refresh is explicit via thebutton inside the drawer). Backend route is SystemAdmin-gated,@@ -568,6 +648,7 @@import { ref, reactive, onMounted, onUnmounted, computed, nextTick, watch } from 'vue'import { useI18n } from 'vue-i18n'import { MessagePlugin } from 'tdesign-vue-next'+import type { FormInstanceFunctions, FormRule } from 'tdesign-vue-next'import {listSystemSettings,updateSystemSetting,@@ -576,6 +657,7 @@ import {listSystemAdmins,promoteUserToSystemAdmin,revokeSystemAdmin,+ resetUserPassword,listSystemAuditLog,type SystemSettingItem,type AuditLog,@@ -759,7 +841,7 @@ const restartRequiredCount = computed(() => settings.value.filter((item) => itemfunction sectionTabLabel(section: SettingsSection): string {const count = section === 'other'? unknownSettings.value.length- : SETTINGS_SECTION_KEYS[section].filter((key) => settingsByKey.value.has(key)).length + (section === 'access' ? 1 : 0)+ : SETTINGS_SECTION_KEYS[section].filter((key) => settingsByKey.value.has(key)).length + (section === 'access' ? 2 : 0)return t(`system.globalSettings.sections.${section}.tab`, { count })}@@ -788,6 +870,73 @@ const adminEmails = ref<string[]>([])const adminEmailToId = ref<Record<string, string>>({})const adminBusy = ref(false)+const passwordResetVisible = ref(false)+const passwordResetSubmitting = ref(false)+const passwordResetFormRef = ref<FormInstanceFunctions>()+const passwordResetForm = reactive({+ email: '',+ newPassword: '',+ confirmPassword: '',+})+const passwordResetRules: Record<string, FormRule[]> = {+ email: [+ { required: true, message: t('system.globalSettings.passwordReset.validation.emailRequired'), trigger: 'blur' },+ { email: true, message: t('system.globalSettings.passwordReset.validation.emailInvalid'), trigger: 'blur' },+ ],+ newPassword: [+ { required: true, message: t('system.globalSettings.passwordReset.validation.passwordRequired'), trigger: 'blur' },+ { min: 8, message: t('system.globalSettings.passwordReset.validation.passwordLength'), trigger: 'blur' },+ { max: 32, message: t('system.globalSettings.passwordReset.validation.passwordLength'), trigger: 'blur' },+ { pattern: /[a-zA-Z]/, message: t('system.globalSettings.passwordReset.validation.passwordLetter'), trigger: 'blur' },+ { pattern: /\d/, message: t('system.globalSettings.passwordReset.validation.passwordNumber'), trigger: 'blur' },+ ],+ confirmPassword: [+ { required: true, message: t('system.globalSettings.passwordReset.validation.confirmRequired'), trigger: 'blur' },+ {+ validator: (value: string) => value === passwordResetForm.newPassword,+ message: t('system.globalSettings.passwordReset.validation.passwordMismatch'),+ trigger: 'blur',+ },+ ],+}++function resetPasswordResetForm() {+ passwordResetForm.email = ''+ passwordResetForm.newPassword = ''+ passwordResetForm.confirmPassword = ''+ passwordResetFormRef.value?.clearValidate?.()+}++async function openPasswordResetDialog() {+ resetPasswordResetForm()+ passwordResetVisible.value = true+ await nextTick()+ passwordResetFormRef.value?.clearValidate?.()+}++async function submitPasswordReset() {+ if (passwordResetSubmitting.value) return+ const valid = await passwordResetFormRef.value?.validate?.()+ if (valid !== true) return++ passwordResetSubmitting.value = true+ try {+ await resetUserPassword({+ email: passwordResetForm.email.trim(),+ new_password: passwordResetForm.newPassword,+ })+ saveAnnouncement.value = t('system.globalSettings.passwordReset.success')+ MessagePlugin.success(t('system.globalSettings.passwordReset.success'))+ passwordResetVisible.value = false+ } catch (err: any) {+ const msg = err?.message || t('system.globalSettings.passwordReset.failed')+ saveAnnouncement.value = msg+ MessagePlugin.error(msg)+ } finally {+ passwordResetSubmitting.value = false+ }+}+// Guards ssrf.whitelist while an async confirm roundtrip is in flight.const listConfirmBusyKey = ref<string | null>(null)@@ -1393,6 +1542,8 @@ function auditActionTheme(case 'system.admin_revoked':case 'system.setting_changed':return 'warning'+ case 'system.user_password_reset':+ return 'danger'case 'rbac.access_denied':return 'danger'default:@@ -1459,7 +1610,11 @@ function auditTargetKey(row: AuditLog): string {if (details && typeof details.key === 'string' && details.key) return details.keyreturn row.target_id || row.target_type || ''}- if (row.action === 'system.admin_promoted' || row.action === 'system.admin_revoked') {+ if (+ row.action === 'system.admin_promoted'+ || row.action === 'system.admin_revoked'+ || row.action === 'system.user_password_reset'+ ) {if (!details) return row.target_user_id ? row.target_user_id.slice(0, 8) : ''const name = typeof details.target_username === 'string' ? details.target_username : ''const mail = typeof details.target_email === 'string' ? details.target_email : ''@@ -2339,6 +2494,10 @@ onUnmounted(() => {width: 320px;}+.password-reset-warning {+ margin-bottom: 18px;+}+@media (max-width: 860px) {.settings-overview,.settings-section-intro {diff --git a/internal/application/service/user.go b/internal/application/service/user.goindex eec1b2688..7c9637530 100644--- a/internal/application/service/user.go+++ b/internal/application/service/user.go@@ -14,6 +14,7 @@ import ("strings""sync""time"+ "unicode/utf8""github.com/golang-jwt/jwt/v5""github.com/google/uuid"@@ -30,8 +31,38 @@ import (var (jwtSecretOnce sync.OncejwtSecret string++ // ErrPasswordPolicy is returned when a newly chosen password does not+ // meet the product's public 8-32 character, letter-and-number contract.+ // It is exported so HTTP handlers can translate the failure to a 400+ // without exposing bcrypt or persistence errors.+ ErrPasswordPolicy = errors.New("password must be 8-32 characters and contain at least one letter and one number"))+// ValidatePasswordPolicy keeps administrative password resets aligned with+// the registration form's documented policy. Password bytes are never logged+// or included in the returned error.+func ValidatePasswordPolicy(password string) error {+ length := utf8.RuneCountInString(password)+ if length < 8 || length > 32 {+ return ErrPasswordPolicy+ }+ hasLetter := false+ hasNumber := false+ for _, r := range password {+ switch {+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z':+ hasLetter = true+ case r >= '0' && r <= '9':+ hasNumber = true+ }+ }+ if !hasLetter || !hasNumber {+ return ErrPasswordPolicy+ }+ return nil+}+// getJwtSecret retrieves the JWT secret from the environment, falling back to a securely generated random secret.func getJwtSecret() string {jwtSecretOnce.Do(func() {@@ -630,6 +661,33 @@ func (s *userService) ChangePassword(ctx context.Context, userID string, oldPassreturn s.tokenRepo.RevokeTokensByUserID(ctx, userID)}+// AdminResetPassword replaces a user's password without checking the previous+// credential. Authorization and the cannot-reset-self rule live at the system+// admin HTTP boundary; this service owns the security-critical persistence and+// session invalidation so no caller can accidentally update only one of them.+func (s *userService) AdminResetPassword(ctx context.Context, userID string, newPassword string) error {+ if err := ValidatePasswordPolicy(newPassword); err != nil {+ return err+ }++ user, err := s.userRepo.GetUserByID(ctx, userID)+ if err != nil {+ return err+ }+ hashedPassword, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)+ if err != nil {+ return err+ }++ user.PasswordHash = string(hashedPassword)+ user.UpdatedAt = time.Now()+ if err := s.userRepo.UpdateUser(ctx, user); err != nil {+ return err+ }++ return s.tokenRepo.RevokeTokensByUserID(ctx, userID)+}+// ValidatePassword validates user passwordfunc (s *userService) ValidatePassword(ctx context.Context, userID string, password string) error {user, err := s.userRepo.GetUserByID(ctx, userID)diff --git a/internal/application/service/user_auth_token_test.go b/internal/application/service/user_auth_token_test.goindex d922440b5..87d98e3ce 100644--- a/internal/application/service/user_auth_token_test.go+++ b/internal/application/service/user_auth_token_test.go@@ -8,6 +8,7 @@ import ("time""github.com/golang-jwt/jwt/v5"+ "golang.org/x/crypto/bcrypt""github.com/Tencent/WeKnora/internal/types")@@ -41,7 +42,8 @@ func (s *stubAuthTokenRepo) RevokeTokensByUserID(_ context.Context, userID strin}type stubUserRepoForAuth struct {- users map[string]*types.User+ users map[string]*types.User+ updateCalls int}func (s *stubUserRepoForAuth) CreateUser(context.Context, *types.User) error { return nil }@@ -64,8 +66,11 @@ func (s *stubUserRepoForAuth) GetUserByUsername(context.Context, string) (*typesfunc (s *stubUserRepoForAuth) GetUserByTenantID(context.Context, uint64) (*types.User, error) {return nil, nil}-func (s *stubUserRepoForAuth) UpdateUser(context.Context, *types.User) error { return nil }-func (s *stubUserRepoForAuth) DeleteUser(context.Context, string) error { return nil }+func (s *stubUserRepoForAuth) UpdateUser(context.Context, *types.User) error {+ s.updateCalls+++ return nil+}+func (s *stubUserRepoForAuth) DeleteUser(context.Context, string) error { return nil }func (s *stubUserRepoForAuth) ListUsers(context.Context, int, int) ([]*types.User, error) {return nil, nil}@@ -177,6 +182,44 @@ func TestLogoutRevokesAllUserTokens(t *testing.T) {}}+func TestAdminResetPasswordHashesPasswordAndRevokesSessions(t *testing.T) {+ ctx := context.Background()+ tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}+ svc := newAuthTestUserService(tokenRepo)+ repo := svc.userRepo.(*stubUserRepoForAuth)++ if err := svc.AdminResetPassword(ctx, "user-1", "NewSecure9"); err != nil {+ t.Fatalf("AdminResetPassword() err = %v", err)+ }+ if repo.updateCalls != 1 {+ t.Fatalf("UpdateUser calls = %d, want 1", repo.updateCalls)+ }+ user := repo.users["user-1"]+ if user.PasswordHash == "NewSecure9" || user.PasswordHash == "" {+ t.Fatalf("password was not stored as a hash")+ }+ if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte("NewSecure9")); err != nil {+ t.Fatalf("stored hash does not match new password: %v", err)+ }+ if len(tokenRepo.revokedUserIDs) != 1 || tokenRepo.revokedUserIDs[0] != "user-1" {+ t.Fatalf("RevokeTokensByUserID calls = %v, want [user-1]", tokenRepo.revokedUserIDs)+ }+}++func TestAdminResetPasswordRejectsWeakPasswordBeforeWrite(t *testing.T) {+ tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}+ svc := newAuthTestUserService(tokenRepo)+ repo := svc.userRepo.(*stubUserRepoForAuth)++ err := svc.AdminResetPassword(context.Background(), "user-1", "password")+ if !errors.Is(err, ErrPasswordPolicy) {+ t.Fatalf("AdminResetPassword() err = %v, want ErrPasswordPolicy", err)+ }+ if repo.updateCalls != 0 || len(tokenRepo.revokedUserIDs) != 0 {+ t.Fatalf("weak password caused side effects: updates=%d revocations=%v", repo.updateCalls, tokenRepo.revokedUserIDs)+ }+}+func TestUserIDFromSignedTokenAcceptsExpiredToken(t *testing.T) {expired := signTestJWT(jwt.MapClaims{"user_id": "user-1",diff --git a/internal/handler/system.go b/internal/handler/system.goindex 32de90cd4..cf2dd2761 100644--- a/internal/handler/system.go+++ b/internal/handler/system.go@@ -1362,6 +1362,72 @@ func (h *SystemHandler) ListSystemAdmins(c *gin.Context) {})}+// ResetUserPasswordRequest defines the system-administrator password-reset+// payload. Email is intentionally the only user-facing identifier: the UI is+// an operator tool and emails are easier to verify than UUIDs. The password is+// never written to logs or audit details.+type ResetUserPasswordRequest struct {+ Email string `json:"email" binding:"required,email"`+ NewPassword string `json:"new_password" binding:"required"`+}++// ResetUserPassword godoc+// @Summary Reset another user's password+// @Description Replace another user's local password and revoke all of their existing sessions (SystemAdmin only).+// @Description A system administrator cannot reset their own password through this endpoint; self-service password change still requires the old password.+// @Tags System Admin+// @Accept json+// @Produce json+// @Param request body ResetUserPasswordRequest true "Password reset request"+// @Success 200 {object} map[string]interface{} "Password reset successfully"+// @Failure 400 {object} map[string]interface{} "Invalid request, weak password, or self reset"+// @Failure 403 {object} map[string]interface{} "Forbidden: not a system admin"+// @Failure 404 {object} map[string]interface{} "User not found"+// @Router /system/admin/users/reset-password [post]+func (h *SystemHandler) ResetUserPassword(c *gin.Context) {+ ctx := logger.CloneContext(c.Request.Context())++ var req ResetUserPasswordRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid password reset request"})+ return+ }+ req.Email = strings.TrimSpace(req.Email)+ if err := service.ValidatePasswordPolicy(req.NewPassword); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }++ user, err := h.userSvc.GetUserByEmail(ctx, req.Email)+ if err != nil || user == nil {+ c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})+ return+ }+ callerID, _ := types.UserIDFromContext(ctx)+ if callerID == user.ID {+ c.JSON(http.StatusBadRequest, gin.H{"error": "Cannot reset your own password here"})+ return+ }++ if err := h.userSvc.AdminResetPassword(ctx, user.ID, req.NewPassword); err != nil {+ if errors.Is(err, service.ErrPasswordPolicy) {+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})+ return+ }+ logger.Errorf(ctx, "Failed to reset password for user %s: %v", user.ID, err)+ c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reset user password"})+ return+ }++ logger.Infof(ctx, "Password reset by system administrator for user ID: %s", user.ID)+ h.emitAdminAudit(ctx, types.AuditActionSystemUserPasswordReset, user, map[string]any{+ "target_email": user.Email,+ "target_username": user.Username,+ "sessions_revoked": true,+ })+ c.JSON(http.StatusOK, gin.H{"message": "Password reset successfully"})+}+// ============================================================================// System Settings (P1)// ----------------------------------------------------------------------------diff --git a/internal/handler/system_password_reset_test.go b/internal/handler/system_password_reset_test.gonew file mode 100644index 000000000..e929f6dfa--- /dev/null+++ b/internal/handler/system_password_reset_test.go@@ -0,0 +1,115 @@+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/Tencent/WeKnora/internal/types/interfaces"+ "github.com/gin-gonic/gin"+)++type resetPasswordUserService struct {+ interfaces.UserService+ target *types.User+ lookupCalls int+ resetCalls int+ resetUserID string+}++func (s *resetPasswordUserService) GetUserByEmail(context.Context, string) (*types.User, error) {+ s.lookupCalls+++ return s.target, nil+}++func (s *resetPasswordUserService) AdminResetPassword(_ context.Context, userID, _ string) error {+ s.resetCalls+++ s.resetUserID = userID+ return nil+}++func passwordResetRouter(h *SystemHandler, actorID string) *gin.Engine {+ gin.SetMode(gin.TestMode)+ r := gin.New()+ r.Use(func(c *gin.Context) {+ ctx := context.WithValue(c.Request.Context(), types.UserIDContextKey, actorID)+ c.Request = c.Request.WithContext(ctx)+ c.Next()+ })+ r.POST("/system/admin/users/reset-password", h.ResetUserPassword)+ return r+}++func performPasswordReset(t *testing.T, r *gin.Engine, body map[string]string) *httptest.ResponseRecorder {+ t.Helper()+ payload, err := json.Marshal(body)+ if err != nil {+ t.Fatal(err)+ }+ req := httptest.NewRequest(http.MethodPost, "/system/admin/users/reset-password", bytes.NewReader(payload))+ req.Header.Set("Content-Type", "application/json")+ w := httptest.NewRecorder()+ r.ServeHTTP(w, req)+ return w+}++func TestResetUserPasswordResetsOtherUserAndAuditsWithoutSecret(t *testing.T) {+ users := &resetPasswordUserService{target: &types.User{+ ID: "target-user", Username: "alice", Email: "[email protected]",+ }}+ audits := &capturingAuditService{}+ h := &SystemHandler{userSvc: users, auditSvc: audits}++ w := performPasswordReset(t, passwordResetRouter(h, "admin-user"), map[string]string{+ "email": "[email protected]", "new_password": "FreshPass9",+ })+ if w.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if users.resetCalls != 1 || users.resetUserID != "target-user" {+ t.Fatalf("reset calls=%d user=%q", users.resetCalls, users.resetUserID)+ }+ if len(audits.entries) != 1 || audits.entries[0].Action != types.AuditActionSystemUserPasswordReset {+ t.Fatalf("unexpected audit entries: %+v", audits.entries)+ }+ if strings.Contains(string(audits.entries[0].Details), "FreshPass9") {+ t.Fatal("audit details leaked the new password")+ }+}++func TestResetUserPasswordRejectsSelfReset(t *testing.T) {+ users := &resetPasswordUserService{target: &types.User{+ ID: "admin-user", Username: "admin", Email: "[email protected]",+ }}+ h := &SystemHandler{userSvc: users}++ w := performPasswordReset(t, passwordResetRouter(h, "admin-user"), map[string]string{+ "email": "[email protected]", "new_password": "FreshPass9",+ })+ if w.Code != http.StatusBadRequest {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if users.resetCalls != 0 {+ t.Fatalf("self reset reached service %d times", users.resetCalls)+ }+}++func TestResetUserPasswordRejectsWeakPasswordBeforeUserLookup(t *testing.T) {+ users := &resetPasswordUserService{target: &types.User{ID: "target-user"}}+ h := &SystemHandler{userSvc: users}++ w := performPasswordReset(t, passwordResetRouter(h, "admin-user"), map[string]string{+ "email": "[email protected]", "new_password": "password",+ })+ if w.Code != http.StatusBadRequest {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if users.lookupCalls != 0 || users.resetCalls != 0 {+ t.Fatalf("weak password caused side effects: lookups=%d resets=%d", users.lookupCalls, users.resetCalls)+ }+}diff --git a/internal/router/router.go b/internal/router/router.goindex 9d0dacbb6..55639d162 100644--- a/internal/router/router.go+++ b/internal/router/router.go@@ -875,6 +875,7 @@ func RegisterSystemAdminRoutes(adminRoutes.POST("/promote", handler.PromoteUserToSystemAdmin)adminRoutes.POST("/revoke", handler.RevokeSystemAdmin)adminRoutes.GET("/list", handler.ListSystemAdmins)+ adminRoutes.POST("/users/reset-password", handler.ResetUserPassword)// P1: platform-wide system settings (DB-backed runtime tunables).// Reads return raw model rows / arrays (no `gin.H{"data":...}`diff --git a/internal/types/audit_log.go b/internal/types/audit_log.goindex bf0eb0f66..613c310a4 100644--- a/internal/types/audit_log.go+++ b/internal/types/audit_log.go@@ -116,6 +116,11 @@ const (// reader can distinguish a real revoke from a noop attempt.// TenantID=0 because the change is system-scope.AuditActionSystemAdminRevoked AuditAction = "system.admin_revoked"++ // AuditActionSystemUserPasswordReset fires when a SystemAdmin replaces+ // another user's local password. Details identify the target and record+ // session revocation, but never contain the old or new password.+ AuditActionSystemUserPasswordReset AuditAction = "system.user_password_reset")// AuditOutcome distinguishes successful mutations from middleware-leveldiff --git a/internal/types/audit_log_test.go b/internal/types/audit_log_test.goindex 98583aa23..2407d7c82 100644--- a/internal/types/audit_log_test.go+++ b/internal/types/audit_log_test.go@@ -37,6 +37,7 @@ func TestAuditAction_DotNamespaceConvention(t *testing.T) {AuditActionSystemSettingChanged,AuditActionSystemAdminPromoted,AuditActionSystemAdminRevoked,+ AuditActionSystemUserPasswordReset,}for _, a := range all {s := string(a)@@ -118,9 +119,10 @@ func TestAuditAction_NoCollisionsAcrossNamespaces(t *testing.T) {register("AuditActionSystemSettingChanged", AuditActionSystemSettingChanged)register("AuditActionSystemAdminPromoted", AuditActionSystemAdminPromoted)register("AuditActionSystemAdminRevoked", AuditActionSystemAdminRevoked)+ register("AuditActionSystemUserPasswordReset", AuditActionSystemUserPasswordReset)}-// TestAuditAction_SystemNamespacePrefix pins the three system.* actions+// TestAuditAction_SystemNamespacePrefix pins the system.* actions// added in this PR to their shared area prefix. The prefix is the// contract by which the platform audit log endpoint// (GET /system/admin/audit-log) filters out per-tenant rbac.* rows —@@ -131,6 +133,7 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {AuditActionSystemSettingChanged,AuditActionSystemAdminPromoted,AuditActionSystemAdminRevoked,+ AuditActionSystemUserPasswordReset,}for _, a := range cases {assert.True(t,@@ -141,7 +144,7 @@ func TestAuditAction_SystemNamespacePrefix(t *testing.T) {}// TestAuditAction_SystemWireValues pins the exact wire strings for-// the three system.* actions. Audit-log consumers (Langfuse exporters,+// the system.* actions. Audit-log consumers (Langfuse exporters,// the new frontend platform audit drawer, future SIEM integrations)// match on these strings; changing them is a breaking change.func TestAuditAction_SystemWireValues(t *testing.T) {@@ -152,6 +155,7 @@ func TestAuditAction_SystemWireValues(t *testing.T) {{AuditActionSystemSettingChanged, "system.setting_changed"},{AuditActionSystemAdminPromoted, "system.admin_promoted"},{AuditActionSystemAdminRevoked, "system.admin_revoked"},+ {AuditActionSystemUserPasswordReset, "system.user_password_reset"},}for _, c := range cases {assert.Equal(t, c.wire, string(c.constant))diff --git a/internal/types/interfaces/user.go b/internal/types/interfaces/user.goindex 816d93f63..1633fda46 100644--- a/internal/types/interfaces/user.go+++ b/internal/types/interfaces/user.go@@ -37,6 +37,10 @@ type UserService interface {DeleteUser(ctx context.Context, id string) error// ChangePassword changes user passwordChangePassword(ctx context.Context, userID string, oldPassword, newPassword string) error+ // AdminResetPassword replaces a user's password without requiring the old+ // password and revokes all of that user's existing sessions. Callers must+ // enforce the system-admin and cannot-reset-self guards before invoking it.+ AdminResetPassword(ctx context.Context, userID string, newPassword string) error// ValidatePassword validates user passwordValidatePassword(ctx context.Context, userID string, password string) error// GenerateTokens generates access and refresh tokens for user