diff --git a/monkeyai/backend/api/admin.yaml b/monkeyai/backend/api/admin.yaml index a515b4613..5f1ee972b 100644 --- a/monkeyai/backend/api/admin.yaml +++ b/monkeyai/backend/api/admin.yaml @@ -7,6 +7,40 @@ servers: security: - AdminSession: [] paths: + /api/admin/v1/settings/client_access_policy: + get: + summary: 查询客户端登录与令牌续期策略(仅超级管理员) + description: 默认四类均允许。客户端是否受实例支持仍以客户端发现接口为准。关闭不会注销已签发令牌或断开连接,不影响后台登录、托管云电脑。 + responses: + '200': &clientAccessResponse + description: 四类客户端各自的允许状态 + content: + application/json: + schema: + type: object + required: [clients] + properties: + clients: {type: object, required: [monkeyai-desktop, monkeyai-mobile, monkeyai-web, monkeyai-runtime], additionalProperties: {type: boolean}} + '401': {description: 未登录} + '403': {description: 非超级管理员} + patch: + summary: 原子更新一个客户端登录开关(仅超级管理员) + requestBody: + required: true + content: + application/json: + schema: + type: object + additionalProperties: false + required: [client_id, enabled] + properties: + client_id: {type: string, enum: [monkeyai-desktop, monkeyai-mobile, monkeyai-web, monkeyai-runtime]} + enabled: {type: boolean} + responses: + '200': *clientAccessResponse + '400': {description: 请求格式或客户端 ID 无效} + '401': {description: 未登录} + '403': {description: 非超级管理员} /api/admin/v1/settings/member_resource_policy: get: summary: 获取六类成员资源的添加修改与分享策略,未配置时全部允许 diff --git a/monkeyai/backend/api/agent.yaml b/monkeyai/backend/api/agent.yaml index 61e891936..983138e04 100644 --- a/monkeyai/backend/api/agent.yaml +++ b/monkeyai/backend/api/agent.yaml @@ -877,7 +877,7 @@ paths: server_id: {type: string, format: uuid, description: 独立授权的控制面标识} scope: {type: string, description: 用户批准的规范化权限;兼容授权为空字符串} '400': - description: OAuth invalid_grant、invalid_client、invalid_request、authorization_pending、slow_down、access_denied、expired_token 或 unsupported_grant_type + description: OAuth invalid_grant、invalid_client、invalid_request、authorization_pending、slow_down、access_denied、expired_token 或 unsupported_grant_type。管理员关闭此客户端登录时,签发和续期返回 unauthorized_client;已签发的访问令牌仍按原有效期使用,不主动断开连接。 content: application/json: schema: {$ref: '#/components/schemas/OAuthError'} diff --git a/monkeyai/backend/internal/identity/clientaccess_test.go b/monkeyai/backend/internal/identity/clientaccess_test.go new file mode 100644 index 000000000..e02c9f0dc --- /dev/null +++ b/monkeyai/backend/internal/identity/clientaccess_test.go @@ -0,0 +1,96 @@ +package identity + +import ( + "github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity/sqlc" + "github.com/google/uuid" + "net/http" + "net/url" + "testing" +) + +func setClientLogin(t *testing.T, s *Service, user, id string, on bool) { + t.Helper() + _, err := s.db.Exec(t.Context(), `INSERT INTO settings(key,value,schema_version,updated_by_user_id) VALUES('authentication',jsonb_build_object('client_access_policy',jsonb_build_object($1::text,$2::bool)),1,$3) ON CONFLICT(key) DO UPDATE SET value=excluded.value`, id, on, user) + if err != nil { + t.Fatal(err) + } +} +func TestClientLoginPolicyExchangeAndRefresh(t *testing.T) { + s, user, _, _ := deviceService(t) + ctx := t.Context() + old := grantToken(t, s, user.ID, "device:manage") + r, v := grantRequest(t, s, "device:manage") + approved := []string{"device:manage"} + redirect, err := s.completeAuthorization(ctx, r.ID, user.ID, &approved) + if err != nil { + t.Fatal(err) + } + u, err := url.Parse(redirect) + if err != nil { + t.Fatal(err) + } + setClientLogin(t, s, user.ID, r.ClientID, false) + _, err = s.ExchangeCode(ctx, r.ClientID, r.RedirectURI, u.Query().Get("code"), v) + oauthCode(t, err, "unauthorized_client") + _, err = s.Refresh(ctx, r.ClientID, old.RefreshToken) + oauthCode(t, err, "unauthorized_client") + tokenPrincipal(t, s, old.AccessToken, http.StatusNoContent) + setClientLogin(t, s, user.ID, r.ClientID, true) + if _, err = s.Refresh(ctx, r.ClientID, old.RefreshToken); err != nil { + t.Fatal("被策略拒绝不能消费刷新凭据", err) + } + if _, err = s.ExchangeCode(ctx, r.ClientID, r.RedirectURI, u.Query().Get("code"), v); err != nil { + t.Fatal("有效授权码不应被消费", err) + } +} +func TestClientLoginPolicyMobilePairing(t *testing.T) { + s, user, _, _ := deviceService(t) + ctx := t.Context() + desktop := grantToken(t, s, user.ID, "device:manage") + pair := pairingCreate(t, s, desktop.AccessToken) + joined, v := pairingJoinRequest(t, s, pair) + pairingApprove(t, s, desktop.AccessToken, pair.ID, joined.UserCode, 200) + setClientLogin(t, s, user.ID, "monkeyai-mobile", false) + _, err := s.ExchangePairingCode(ctx, "monkeyai-mobile", joined.DeviceCode, v) + oauthCode(t, err, "unauthorized_client") + if _, err = s.Refresh(ctx, "monkeyai-desktop", desktop.RefreshToken); err != nil { + t.Fatal(err) + } +} +func TestClientLoginPolicyRuntimeOwnership(t *testing.T) { + s, user, cookie, _ := deviceService(t) + ctx := t.Context() + d := deviceApplication(t, s) + view := deviceView(t, s, d, cookie) + deviceDecide(t, s, view, cookie, "approve", nil, false, view["csrf_token"].(string), 200) + setClientLogin(t, s, user.ID, RuntimeClientID, false) + exec := func(query string, args ...any) { + t.Helper() + if _, err := s.db.Exec(ctx, query, args...); err != nil { + t.Fatal(err) + } + } + exec("UPDATE oauth_device_requests SET next_poll_at=now()-interval '1 second' WHERE id=$1", view["request_id"]) + _, err := s.ExchangeDeviceCode(ctx, RuntimeClientID, d.DeviceCode) + oauthCode(t, err, "unauthorized_client") + code, _ := canonicalUserCode(d.UserCode) + request, err := sqlc.New(s.db).DeviceRequestByCode(ctx, s.userCodeHash(code)) + if err != nil { + t.Fatal(err) + } + s.WithRuntimeAccess(&runtimeGate{allowed: true}) + env, host := uuid.NewString(), uuid.NewString() + exec("INSERT INTO hosts(id,user_id,name,status,architecture,version) VALUES($1,$2,'host','active','amd64','test')", host, user.ID) + exec("INSERT INTO environments(id,user_id,host_id,name,generation,instance_id,desired,spec,cpu_millis,memory_bytes) VALUES($1,$2,$3,'test',1,$1,'running','{}',1,1)", env, user.ID, host) + exec("INSERT INTO environment_runtimes(environment_id,machine_id,public_key,instance_id,generation) VALUES($1,$2,$3,$1,1)", env, request.MachineID, make([]byte, 32)) + _, err = s.ExchangeDeviceCode(ctx, RuntimeClientID, d.DeviceCode) + oauthCode(t, err, "unauthorized_client") + exec("UPDATE environment_runtimes SET public_key=$2 WHERE environment_id=$1", env, request.ExecutionPublicKey) + token, err := s.ExchangeDeviceCode(ctx, RuntimeClientID, d.DeviceCode) + if err != nil { + t.Fatal(err) + } + if _, err = s.Refresh(ctx, RuntimeClientID, token.RefreshToken); err != nil { + t.Fatal("平台托管的运行端应能续期", err) + } +} diff --git a/monkeyai/backend/internal/identity/device.go b/monkeyai/backend/internal/identity/device.go index f4f534e71..6ae3b216b 100644 --- a/monkeyai/backend/internal/identity/device.go +++ b/monkeyai/backend/internal/identity/device.go @@ -505,7 +505,7 @@ func (s *Service) ExchangeDeviceCode(ctx context.Context, clientID, code string) } serverID, _ := s.DeviceServerID() token := Token{AccessToken: access, RefreshToken: refresh, TokenType: "Bearer", ExpiresIn: int64(s.accessTTL.Seconds()), ExpiresAt: now.Add(s.accessTTL), GrantID: grant.ID, Scope: runtimeTokenScope, ServerID: serverID, MachineID: request.MachineID} - if _, err = q.CreateToken(ctx, sqlc.CreateTokenParams{UserID: grant.UserID, ClientID: RuntimeClientID, GrantID: grant.ID, AccessTokenHash: tokenHash(access), RefreshTokenHash: tokenHash(refresh), AccessExpiresAt: token.ExpiresAt, RefreshExpiresAt: grant.ExpiresAt}); err != nil { + if err = issueClientToken(ctx, q, sqlc.CreateTokenParams{UserID: grant.UserID, ClientID: RuntimeClientID, GrantID: grant.ID, AccessTokenHash: tokenHash(access), RefreshTokenHash: tokenHash(refresh), AccessExpiresAt: token.ExpiresAt, RefreshExpiresAt: grant.ExpiresAt}); err != nil { return Token{}, err } if err = q.ResolveDeviceRequest(ctx, sqlc.ResolveDeviceRequestParams{ID: request.ID, Status: "consumed"}); err != nil { diff --git a/monkeyai/backend/internal/identity/grant.go b/monkeyai/backend/internal/identity/grant.go index 5102e85df..0c994a8b6 100644 --- a/monkeyai/backend/internal/identity/grant.go +++ b/monkeyai/backend/internal/identity/grant.go @@ -14,6 +14,20 @@ import ( var errAuthorizationCodeUsed = errors.New("授权码已被使用") var errInvalidGrant = errors.New("授权族或刷新凭据不可用") +// Every OAuth grant type, including refresh, goes through this gate inside its +// transaction. A refusal rolls back code redemption and token rotation alike. +func issueClientToken(ctx context.Context, q *sqlc.Queries, token sqlc.CreateTokenParams) error { + allowed, err := q.ClientMayIssueToken(ctx, sqlc.ClientMayIssueTokenParams{ClientID: token.ClientID, GrantID: token.GrantID}) + if err != nil { + return err + } + if allowed == nil || !*allowed { + return oauthError("unauthorized_client", "管理员已关闭此客户端登录,不能获取或续期令牌") + } + _, err = q.CreateToken(ctx, token) + return err +} + func (s *Service) redeemCodeAndStoreToken(ctx context.Context, code AuthorizationCode, accessHash, refreshHash string, accessExpiry, refreshExpiry time.Time) (sqlc.OauthGrant, error) { tx, err := s.db.Begin(ctx) if err != nil { @@ -44,7 +58,7 @@ func (s *Service) redeemCodeAndStoreToken(ctx context.Context, code Authorizatio if err != nil { return sqlc.OauthGrant{}, err } - _, err = q.CreateToken(ctx, sqlc.CreateTokenParams{UserID: code.UserID, ClientID: code.ClientID, GrantID: grant.ID, + err = issueClientToken(ctx, q, sqlc.CreateTokenParams{UserID: code.UserID, ClientID: code.ClientID, GrantID: grant.ID, AccessTokenHash: accessHash, RefreshTokenHash: refreshHash, AccessExpiresAt: accessExpiry, RefreshExpiresAt: refreshExpiry}) if err != nil { return sqlc.OauthGrant{}, err @@ -105,7 +119,7 @@ func (s *Service) rotateToken(ctx context.Context, oldRefreshHash, clientID, acc if changed != 1 { return sqlc.OauthGrant{}, errInvalidGrant } - _, err = q.CreateToken(ctx, sqlc.CreateTokenParams{UserID: old.UserID, ClientID: clientID, GrantID: old.GrantID, ParentID: new(old.ID), + err = issueClientToken(ctx, q, sqlc.CreateTokenParams{UserID: old.UserID, ClientID: clientID, GrantID: old.GrantID, ParentID: new(old.ID), AccessTokenHash: accessHash, RefreshTokenHash: refreshHash, AccessExpiresAt: accessExpiry, RefreshExpiresAt: refreshExpiry}) if err != nil { return sqlc.OauthGrant{}, err diff --git a/monkeyai/backend/internal/identity/pairing.go b/monkeyai/backend/internal/identity/pairing.go index cfb8447b7..b5e64babd 100644 --- a/monkeyai/backend/internal/identity/pairing.go +++ b/monkeyai/backend/internal/identity/pairing.go @@ -424,7 +424,7 @@ func (s *Service) ExchangePairingCode(ctx context.Context, clientID, deviceCode, return Token{}, err } token := Token{AccessToken: access, RefreshToken: refresh, TokenType: "Bearer", ExpiresIn: int64(s.accessTTL.Seconds()), ExpiresAt: now.Add(s.accessTTL), GrantID: grant.ID, Scope: strings.Join(grant.Scopes, " ")} - if _, err = q.CreateToken(ctx, sqlc.CreateTokenParams{UserID: request.CreatorUserID, ClientID: clientID, GrantID: grant.ID, AccessTokenHash: tokenHash(access), RefreshTokenHash: tokenHash(refresh), AccessExpiresAt: token.ExpiresAt, RefreshExpiresAt: grant.ExpiresAt}); err != nil { + if err = issueClientToken(ctx, q, sqlc.CreateTokenParams{UserID: request.CreatorUserID, ClientID: clientID, GrantID: grant.ID, AccessTokenHash: tokenHash(access), RefreshTokenHash: tokenHash(refresh), AccessExpiresAt: token.ExpiresAt, RefreshExpiresAt: grant.ExpiresAt}); err != nil { return Token{}, err } if err = tx.Commit(ctx); err != nil { diff --git a/monkeyai/backend/internal/identity/query.sql b/monkeyai/backend/internal/identity/query.sql index 66a5ca621..f4a03cd1c 100644 --- a/monkeyai/backend/internal/identity/query.sql +++ b/monkeyai/backend/internal/identity/query.sql @@ -110,6 +110,17 @@ WHERE AND redeemed_at IS NULL AND expires_at > now(); +-- name: ClientMayIssueToken :one +-- Applies to issuance/rotation only, never to an already issued access token. +WITH policy AS (SELECT value->'client_access_policy' AS rules FROM settings WHERE key='authentication' FOR SHARE) +SELECT COALESCE((SELECT jsonb_typeof(rules)='object' AND COALESCE(rules->(sqlc.arg(client_id)::text)='true'::jsonb,true) FROM policy),true) + OR (sqlc.arg(client_id)::text='monkeyai-runtime' AND EXISTS ( + SELECT 1 FROM oauth_grants g JOIN environment_runtimes r ON r.machine_id=g.requested_machine_id + JOIN environments e ON e.id=r.environment_id AND e.user_id=g.user_id + WHERE g.id=sqlc.arg(grant_id)::uuid AND g.client_id='monkeyai-runtime' AND g.purpose='runtime' + AND g.requested_key_id=translate(encode(sha256(r.public_key),'base64'),'+/=','-_') + )) AS allowed; + -- name: CreateToken :execresult INSERT INTO oauth_tokens (user_id, client_id, access_token_hash, refresh_token_hash, access_expires_at, refresh_expires_at, grant_id, parent_id) VALUES ($1, $2, $3, $4, $5, $6, $7, $8); diff --git a/monkeyai/backend/internal/identity/sqlc/query.sql.go b/monkeyai/backend/internal/identity/sqlc/query.sql.go index 1eb7de76b..76693a6ab 100644 --- a/monkeyai/backend/internal/identity/sqlc/query.sql.go +++ b/monkeyai/backend/internal/identity/sqlc/query.sql.go @@ -66,6 +66,30 @@ func (q *Queries) CleanEmailDeliveries(ctx context.Context) error { return err } +const clientMayIssueToken = `-- name: ClientMayIssueToken :one +WITH policy AS (SELECT value->'client_access_policy' AS rules FROM settings WHERE key='authentication' FOR SHARE) +SELECT COALESCE((SELECT jsonb_typeof(rules)='object' AND COALESCE(rules->($1::text)='true'::jsonb,true) FROM policy),true) + OR ($1::text='monkeyai-runtime' AND EXISTS ( + SELECT 1 FROM oauth_grants g JOIN environment_runtimes r ON r.machine_id=g.requested_machine_id + JOIN environments e ON e.id=r.environment_id AND e.user_id=g.user_id + WHERE g.id=$2::uuid AND g.client_id='monkeyai-runtime' AND g.purpose='runtime' + AND g.requested_key_id=translate(encode(sha256(r.public_key),'base64'),'+/=','-_') + )) AS allowed +` + +type ClientMayIssueTokenParams struct { + ClientID string + GrantID string +} + +// Applies to issuance/rotation only, never to an already issued access token. +func (q *Queries) ClientMayIssueToken(ctx context.Context, arg ClientMayIssueTokenParams) (*bool, error) { + row := q.db.QueryRow(ctx, clientMayIssueToken, arg.ClientID, arg.GrantID) + var allowed *bool + err := row.Scan(&allowed) + return allowed, err +} + const completeAuthorizationRequest = `-- name: CompleteAuthorizationRequest :execresult UPDATE oauth_authorization_requests diff --git a/monkeyai/backend/internal/setting/admin.go b/monkeyai/backend/internal/setting/admin.go index 1d783a973..d99a247d4 100644 --- a/monkeyai/backend/internal/setting/admin.go +++ b/monkeyai/backend/internal/setting/admin.go @@ -44,6 +44,8 @@ func (s *Service) RegisterAdmin(router chi.Router) { router.Put("/settings/{key}", s.putSetting) router.Patch("/settings/"+memberpolicy.Key, s.patchMemberPolicy) router.Patch("/settings/authentication", s.patchRegistrationDomains) + router.Get("/settings/"+clientAccessKey, s.clientAccessPolicy) + router.Patch("/settings/"+clientAccessKey, s.clientAccessPolicy) router.Post("/settings/email/test", s.testEmail) } diff --git a/monkeyai/backend/internal/setting/clientaccess.go b/monkeyai/backend/internal/setting/clientaccess.go new file mode 100644 index 000000000..a09928b21 --- /dev/null +++ b/monkeyai/backend/internal/setting/clientaccess.go @@ -0,0 +1,89 @@ +package setting + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + + "github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity" + "github.com/chaitin/MonkeyCode/monkeyai/backend/internal/web" +) + +const clientAccessKey = "client_access_policy" + +// Only the client switches are exposed here, never other authentication settings. +func clientSwitches(raw json.RawMessage) (map[string]bool, error) { + var auth map[string]json.RawMessage + if err := json.Unmarshal(raw, &auth); err != nil { + return nil, err + } + policy := make(map[string]bool, len(identity.Clients)) + for id := range identity.Clients { + policy[id] = true + } + if value, ok := auth[clientAccessKey]; ok { + var overrides map[string]*bool + if err := json.Unmarshal(value, &overrides); err != nil { + return nil, err + } + if overrides == nil { + return nil, errors.New("客户端策略不是对象") + } + for id, enabled := range overrides { + if _, known := policy[id]; known { + if enabled == nil { + return nil, errors.New("客户端策略值不是布尔值") + } + policy[id] = *enabled + } + } + } + return policy, nil +} + +func (s *Service) clientAccessPolicy(w http.ResponseWriter, r *http.Request) { + ctx := r.Context() + var raw json.RawMessage + var err error + if r.Method == http.MethodPatch { + var in struct { + ClientID string `json:"client_id"` + Enabled *bool `json:"enabled"` + } + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)) + dec.DisallowUnknownFields() + if e := dec.Decode(&in); e != nil || dec.Decode(new(any)) != io.EOF || in.Enabled == nil { + web.JSON(ctx, w, 400, map[string]any{"error": web.Body(ctx, "invalid_request", "")}) + return + } + if _, known := identity.Clients[in.ClientID]; !known { + web.JSON(ctx, w, 400, map[string]any{"error": web.Body(ctx, "invalid_request", "")}) + return + } + writer, ok := s.store.(interface { + PatchClientAccess(context.Context, string, bool, string) (json.RawMessage, error) + }) + if !ok { + _ = web.InternalResponse(ctx, w) + return + } + user, _ := identity.UserFromContext(ctx) + raw, err = writer.PatchClientAccess(ctx, in.ClientID, *in.Enabled, user.ID) + } else { + raw, err = s.GetValue(ctx, "authentication") + } + if err == nil { + var policy map[string]bool + policy, err = clientSwitches(raw) + if err == nil { + w.Header().Set("Cache-Control", "no-store") + settingJSON(ctx, w, 200, map[string]any{"clients": policy}) + return + } + } + slog.ErrorContext(ctx, "读写客户端登录策略失败", "error", err) + _ = web.InternalResponse(ctx, w) +} diff --git a/monkeyai/backend/internal/setting/clientaccess_test.go b/monkeyai/backend/internal/setting/clientaccess_test.go new file mode 100644 index 000000000..5841dd7ae --- /dev/null +++ b/monkeyai/backend/internal/setting/clientaccess_test.go @@ -0,0 +1,54 @@ +package setting + +import ( + "context" + "encoding/json" + "github.com/go-chi/chi/v5" + "net/http/httptest" + "strings" + "testing" +) + +type clientPolicyStore struct { + memoryStore + calls int +} + +func (m *clientPolicyStore) PatchClientAccess(_ context.Context, id string, enabled bool, _ string) (json.RawMessage, error) { + m.calls++ + return json.Marshal(map[string]any{clientAccessKey: map[string]bool{id: enabled}, "oauth_connections": []any{map[string]string{"client_secret": "test-secret"}}}) +} +func TestClientLoginPolicyHTTP(t *testing.T) { + store := &clientPolicyStore{} + s := NewService(store) + r := chi.NewRouter() + s.RegisterAdmin(r) + request := func(method, body string, want int) map[string]bool { + t.Helper() + w := httptest.NewRecorder() + r.ServeHTTP(w, httptest.NewRequest(method, "/settings/client_access_policy", strings.NewReader(body))) + if w.Code != want || strings.Contains(w.Body.String(), "test-secret") { + t.Fatal(w.Code, w.Body.String()) + } + if want != 200 { + return nil + } + var v struct{ Clients map[string]bool } + if err := json.Unmarshal(w.Body.Bytes(), &v); err != nil || len(v.Clients) != 4 { + t.Fatal(v, err) + } + return v.Clients + } + for _, v := range request("GET", "", 200) { + if !v { + t.Fatal("缺省应允许") + } + } + for _, bad := range []string{`{}`, `{"client_id":"unknown","enabled":false}`, `{"client_id":"monkeyai-web","enabled":null}`, `{"client_id":"monkeyai-web","enabled":false,"unexpected":true}`} { + request("PATCH", bad, 400) + } + p := request("PATCH", `{"client_id":"monkeyai-mobile","enabled":false}`, 200) + if store.calls != 1 || p["monkeyai-mobile"] || !p["monkeyai-web"] { + t.Fatal(p, store.calls) + } +} diff --git a/monkeyai/backend/internal/setting/postgres.go b/monkeyai/backend/internal/setting/postgres.go index 6d053a707..06dd48403 100644 --- a/monkeyai/backend/internal/setting/postgres.go +++ b/monkeyai/backend/internal/setting/postgres.go @@ -18,6 +18,10 @@ type Postgres struct { pool *pgxpool.Pool } +func (p *Postgres) PatchClientAccess(ctx context.Context, id string, enabled bool, actor string) (json.RawMessage, error) { + return sqlc.New(p.pool).PatchClientAccess(ctx, sqlc.PatchClientAccessParams{ClientID: id, Enabled: enabled, Actor: actor}) +} + func NewPostgres(pool *pgxpool.Pool) *Postgres { return &Postgres{pool: pool} } diff --git a/monkeyai/backend/internal/setting/query.sql b/monkeyai/backend/internal/setting/query.sql index 9b6e99848..4574289b4 100644 --- a/monkeyai/backend/internal/setting/query.sql +++ b/monkeyai/backend/internal/setting/query.sql @@ -34,9 +34,10 @@ INSERT INTO settings (KEY, value, schema_version, updated_by_user_id) VALUES ($1, $2, $3, $4) ON CONFLICT (KEY) DO UPDATE SET - -- A full authentication save must not clear or revert a concurrent domain patch. - value = CASE WHEN settings.key = 'authentication' AND settings.value ? 'email_code_auto_registration_domains' - THEN jsonb_set(EXCLUDED.value, '{email_code_auto_registration_domains}', settings.value->'email_code_auto_registration_domains') + -- These fields are owned by their PATCH endpoints, not by a stale authentication form. + value = CASE WHEN settings.key = 'authentication' + THEN EXCLUDED.value || COALESCE((SELECT jsonb_object_agg(f.key,f.value) + FROM jsonb_each(settings.value) AS f WHERE f.key IN ('email_code_auto_registration_domains','client_access_policy')), '{}'::jsonb) ELSE EXCLUDED.value END, schema_version = EXCLUDED.schema_version, updated_by_user_id = EXCLUDED.updated_by_user_id, @@ -59,3 +60,11 @@ RETURNING key,value,schema_version,updated_by_user_id,updated_at; -- name: PatchRegistrationDomains :execrows UPDATE settings SET value=jsonb_set(value,'{email_code_auto_registration_domains}',sqlc.arg(domains)::jsonb), updated_by_user_id=sqlc.arg(actor)::uuid, updated_at=now() WHERE key='authentication' AND value @> '{"email_code_auto_registration_enabled":true}'::jsonb; + +-- name: PatchClientAccess :one +INSERT INTO settings (key,value,schema_version,updated_by_user_id) +VALUES ('authentication',jsonb_build_object('client_access_policy', jsonb_build_object(sqlc.arg(client_id)::text, sqlc.arg(enabled)::boolean)),1,sqlc.arg(actor)::uuid) +ON CONFLICT (key) DO UPDATE SET value=jsonb_set(settings.value,'{client_access_policy}', + COALESCE(settings.value->'client_access_policy','{}'::jsonb) || (EXCLUDED.value->'client_access_policy')), + updated_by_user_id=EXCLUDED.updated_by_user_id, updated_at=now() +RETURNING value; diff --git a/monkeyai/backend/internal/setting/service.go b/monkeyai/backend/internal/setting/service.go index ff921deb1..b834cbdc9 100644 --- a/monkeyai/backend/internal/setting/service.go +++ b/monkeyai/backend/internal/setting/service.go @@ -107,9 +107,12 @@ func (s *Service) Put(ctx context.Context, key string, value json.RawMessage, sc return Record{}, errors.New("value 必须是 JSON 对象") } if key == "authentication" { - // Old clients PUT the full auth form. Only the domain PATCH owns this field. - if _, present := object[emaildomain.Key]; present { + // Preserve fields with dedicated PATCH routes when older clients PUT the full form. + _, hasDomains := object[emaildomain.Key] + _, hasPolicy := object[clientAccessKey] + if hasDomains || hasPolicy { delete(object, emaildomain.Key) + delete(object, clientAccessKey) b, err := json.Marshal(object) if err != nil { return Record{}, err @@ -305,6 +308,7 @@ func redact(key string, value json.RawMessage, forAgent bool) (json.RawMessage, case "authentication": if forAgent { delete(object, emaildomain.Key) + delete(object, clientAccessKey) } connections, _ := object["oauth_connections"].([]any) for _, item := range connections { diff --git a/monkeyai/backend/internal/setting/sqlc/query.sql.go b/monkeyai/backend/internal/setting/sqlc/query.sql.go index 4a39758ed..338f70411 100644 --- a/monkeyai/backend/internal/setting/sqlc/query.sql.go +++ b/monkeyai/backend/internal/setting/sqlc/query.sql.go @@ -91,6 +91,28 @@ func (q *Queries) ListSettings(ctx context.Context) ([]ListSettingsRow, error) { return items, nil } +const patchClientAccess = `-- name: PatchClientAccess :one +INSERT INTO settings (key,value,schema_version,updated_by_user_id) +VALUES ('authentication',jsonb_build_object('client_access_policy', jsonb_build_object($1::text, $2::boolean)),1,$3::uuid) +ON CONFLICT (key) DO UPDATE SET value=jsonb_set(settings.value,'{client_access_policy}', + COALESCE(settings.value->'client_access_policy','{}'::jsonb) || (EXCLUDED.value->'client_access_policy')), + updated_by_user_id=EXCLUDED.updated_by_user_id, updated_at=now() +RETURNING value +` + +type PatchClientAccessParams struct { + ClientID string + Enabled bool + Actor string +} + +func (q *Queries) PatchClientAccess(ctx context.Context, arg PatchClientAccessParams) ([]byte, error) { + row := q.db.QueryRow(ctx, patchClientAccess, arg.ClientID, arg.Enabled, arg.Actor) + var value []byte + err := row.Scan(&value) + return value, err +} + const patchMemberPolicy = `-- name: PatchMemberPolicy :one INSERT INTO settings (key,value,schema_version,updated_by_user_id) VALUES ('member_resource_policy', jsonb_set($1::jsonb, @@ -174,9 +196,10 @@ INSERT INTO settings (KEY, value, schema_version, updated_by_user_id) VALUES ($1, $2, $3, $4) ON CONFLICT (KEY) DO UPDATE SET - -- A full authentication save must not clear or revert a concurrent domain patch. - value = CASE WHEN settings.key = 'authentication' AND settings.value ? 'email_code_auto_registration_domains' - THEN jsonb_set(EXCLUDED.value, '{email_code_auto_registration_domains}', settings.value->'email_code_auto_registration_domains') + -- These fields are owned by their PATCH endpoints, not by a stale authentication form. + value = CASE WHEN settings.key = 'authentication' + THEN EXCLUDED.value || COALESCE((SELECT jsonb_object_agg(f.key,f.value) + FROM jsonb_each(settings.value) AS f WHERE f.key IN ('email_code_auto_registration_domains','client_access_policy')), '{}'::jsonb) ELSE EXCLUDED.value END, schema_version = EXCLUDED.schema_version, updated_by_user_id = EXCLUDED.updated_by_user_id, diff --git a/monkeyai/backend/internal/web/internal/i18n/additional.json b/monkeyai/backend/internal/web/internal/i18n/additional.json index d5d82b611..5d581062c 100644 --- a/monkeyai/backend/internal/web/internal/i18n/additional.json +++ b/monkeyai/backend/internal/web/internal/i18n/additional.json @@ -1,4 +1,5 @@ { + "unauthorized_client": {"zh-CN":"管理员已关闭此客户端登录,不能获取或续期令牌。","en-US":"Sign-in for this client is disabled. Tokens cannot be issued or refreshed."}, "invalid_registration_domain": {"zh-CN":"邮箱域名格式无效,请检查对应的域名条目。","en-US":"Invalid email domain. Check the indicated entry."}, "email_registration_disabled": {"zh-CN":"邮箱自动注册已关闭,请刷新页面。","en-US":"Email auto-registration is disabled. Refresh the page."}, "import_unavailable": {"zh-CN":"文件导入签名密钥未配置。","en-US":"The file import signing key is not configured."}, diff --git a/monkeyai/web/src/i18n/locales/ar.ts b/monkeyai/web/src/i18n/locales/ar.ts index 515d8de63..64a299919 100644 --- a/monkeyai/web/src/i18n/locales/ar.ts +++ b/monkeyai/web/src/i18n/locales/ar.ts @@ -2901,6 +2901,16 @@ export const ar = { description: "إدارة الموافقات على الموارد.", }, security: { + clientRestrictions: { + title: "قيود تطبيقات العميل", + description: "اختر التطبيقات التي يُسمح للأعضاء بتسجيل الدخول إليها أو تفويضها. لا يتأثر تسجيل الدخول إلى لوحة الإدارة.", + runtime: "بيئة تشغيل مستقلة", + unavailable: "تفويض الأجهزة غير متاح في هذا المثيل.", + confirmTitle: "هل تريد تغيير صلاحية الوصول؟", + enable: "هل تسمح للأعضاء باستخدام {{client}}؟", + disable: "هل تريد تعطيل تسجيل الدخول عبر {{client}}؟ سيتم حظر تسجيل الدخول الجديد وتجديد الرموز، ولن يتم فصل الأجهزة المتصلة فورًا.", + lastClient: "هذا آخر تطبيق يُسمح باستخدامه.", + }, title: "الأمان", description: "إدارة إعدادات أمان النظام.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/de-DE.ts b/monkeyai/web/src/i18n/locales/de-DE.ts index 3c54a30c6..c0cdce271 100644 --- a/monkeyai/web/src/i18n/locales/de-DE.ts +++ b/monkeyai/web/src/i18n/locales/de-DE.ts @@ -2962,6 +2962,16 @@ export const deDE = { description: "Ressourcenfreigaben verwalten.", }, security: { + clientRestrictions: { + title: "Clientbeschränkungen", + description: "Wählen Sie, welche Clients Mitglieder anmelden oder autorisieren dürfen. Die Verwaltungskonsole ist davon ausgenommen.", + runtime: "Eigenständige Runtime", + unavailable: "Die Geräteautorisierung ist auf dieser Instanz nicht verfügbar.", + confirmTitle: "Clientzugriff ändern?", + enable: "Mitgliedern den Zugriff auf {{client}} erlauben?", + disable: "Anmeldung für {{client}} sperren? Neue Anmeldungen und Verlängerungen werden blockiert. Angemeldete Geräte bleiben zunächst verbunden.", + lastClient: "Dies ist der letzte zugelassene Client.", + }, title: "Sicherheit", description: "Sicherheitseinstellungen des Systems verwalten.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/en-US.ts b/monkeyai/web/src/i18n/locales/en-US.ts index 83cdb8095..641f7cee4 100644 --- a/monkeyai/web/src/i18n/locales/en-US.ts +++ b/monkeyai/web/src/i18n/locales/en-US.ts @@ -3061,6 +3061,16 @@ export const enUS = { description: "Manage resource approvals.", }, security: { + clientRestrictions: { + title: "Client restrictions", + description: "Choose which clients members may sign in to or authorize. Admin console sign-in is separate.", + runtime: "Standalone runtime", + unavailable: "Device authorization is unavailable on this instance.", + confirmTitle: "Change client access?", + enable: "Allow members to sign in to or authorize {{client}}?", + disable: "Disable sign-in for {{client}}? New sign-ins and renewals will be blocked. Signed-in devices will not be disconnected immediately.", + lastClient: "This is the last allowed client.", + }, title: "Security", description: "Manage system security settings.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/es-419.ts b/monkeyai/web/src/i18n/locales/es-419.ts index 1fb021186..5bb097e4e 100644 --- a/monkeyai/web/src/i18n/locales/es-419.ts +++ b/monkeyai/web/src/i18n/locales/es-419.ts @@ -2946,6 +2946,16 @@ export const es419 = { description: "Administra las aprobaciones de recursos.", }, security: { + clientRestrictions: { + title: "Restricciones de clientes", + description: "Elige qué clientes pueden usar o autorizar los miembros. No afecta el acceso a la consola de administración.", + runtime: "Runtime independiente", + unavailable: "La autorización de dispositivos no está disponible en esta instancia.", + confirmTitle: "¿Cambiar el acceso al cliente?", + enable: "¿Permitir que los miembros usen {{client}}?", + disable: "¿Bloquear el acceso de {{client}}? Se impedirán nuevos inicios de sesión y renovaciones. Los dispositivos conectados no se desconectarán de inmediato.", + lastClient: "Este es el último cliente permitido.", + }, title: "Seguridad", description: "Administra la configuración de seguridad del sistema.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/fr-FR.ts b/monkeyai/web/src/i18n/locales/fr-FR.ts index d2824daee..d4de71907 100644 --- a/monkeyai/web/src/i18n/locales/fr-FR.ts +++ b/monkeyai/web/src/i18n/locales/fr-FR.ts @@ -2961,6 +2961,16 @@ export const frFR = { description: "Gérez les approbations des ressources.", }, security: { + clientRestrictions: { + title: "Restrictions des clients", + description: "Choisissez les clients auxquels les membres peuvent se connecter ou qu’ils peuvent autoriser. La console d’administration n’est pas concernée.", + runtime: "Runtime autonome", + unavailable: "L’autorisation des appareils est indisponible sur cette instance.", + confirmTitle: "Modifier l’accès au client ?", + enable: "Autoriser les membres à utiliser {{client}} ?", + disable: "Bloquer la connexion de {{client}} ? Les nouvelles connexions et les renouvellements seront refusés. Les appareils déjà connectés ne seront pas immédiatement déconnectés.", + lastClient: "Il s’agit du dernier client autorisé.", + }, title: "Sécurité", description: "Gérez les paramètres de sécurité du système.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/ja-JP.ts b/monkeyai/web/src/i18n/locales/ja-JP.ts index 084fcb110..8e425752c 100644 --- a/monkeyai/web/src/i18n/locales/ja-JP.ts +++ b/monkeyai/web/src/i18n/locales/ja-JP.ts @@ -2921,6 +2921,16 @@ export const jaJP = { description: "リソースの承認を管理します。", }, security: { + clientRestrictions: { + title: "クライアント制限", + description: "メンバーがログインまたは認可できるクライアントを選択します。管理画面へのログインには影響しません。", + runtime: "独立 Runtime", + unavailable: "このインスタンスではデバイス認可を利用できません。", + confirmTitle: "クライアントの利用権限を変更しますか?", + enable: "メンバーによる「{{client}}」の利用を許可しますか?", + disable: "「{{client}}」のログインを無効にしますか?新規ログインと更新はできなくなりますが、ログイン中の端末はすぐには切断されません。", + lastClient: "これは利用を許可している最後のクライアントです。", + }, title: "セキュリティ", description: "システムのセキュリティ設定を管理します。", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/ko-KR.ts b/monkeyai/web/src/i18n/locales/ko-KR.ts index 448b03346..88253370e 100644 --- a/monkeyai/web/src/i18n/locales/ko-KR.ts +++ b/monkeyai/web/src/i18n/locales/ko-KR.ts @@ -2904,6 +2904,16 @@ export const koKR = { description: "리소스 승인을 관리합니다.", }, security: { + clientRestrictions: { + title: "클라이언트 제한", + description: "구성원이 로그인하거나 승인할 수 있는 클라이언트를 선택하세요. 관리 콘솔 로그인에는 영향을 주지 않습니다.", + runtime: "독립 런타임", + unavailable: "이 인스턴스에서는 기기 인증을 사용할 수 없습니다.", + confirmTitle: "클라이언트 접근 권한을 변경할까요?", + enable: "구성원의 {{client}} 사용을 허용할까요?", + disable: "{{client}} 로그인을 차단할까요? 새 로그인과 갱신은 차단되지만 로그인 중인 기기는 즉시 연결이 끊기지 않습니다.", + lastClient: "현재 허용된 마지막 클라이언트입니다.", + }, title: "보안", description: "시스템 보안 설정을 관리합니다.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/ru-RU.ts b/monkeyai/web/src/i18n/locales/ru-RU.ts index c4ebc8292..9c5334d1e 100644 --- a/monkeyai/web/src/i18n/locales/ru-RU.ts +++ b/monkeyai/web/src/i18n/locales/ru-RU.ts @@ -2948,6 +2948,16 @@ export const ruRU = { description: "Управление одобрением ресурсов.", }, security: { + clientRestrictions: { + title: "Ограничения клиентов", + description: "Выберите клиенты, в которые участники могут входить или которым могут разрешить доступ. Вход в консоль администратора не меняется.", + runtime: "Автономная среда выполнения", + unavailable: "Авторизация устройств недоступна на этом экземпляре.", + confirmTitle: "Изменить доступ к клиенту?", + enable: "Разрешить участникам использовать клиент «{{client}}»?", + disable: "Запретить вход через «{{client}}»? Новый вход и продление токенов будут недоступны. Уже подключённые устройства не будут отключены немедленно.", + lastClient: "Это последний разрешённый клиент.", + }, title: "Безопасность", description: "Управление настройками безопасности системы.", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/zh-CN.ts b/monkeyai/web/src/i18n/locales/zh-CN.ts index bc68f86de..eebe8490d 100644 --- a/monkeyai/web/src/i18n/locales/zh-CN.ts +++ b/monkeyai/web/src/i18n/locales/zh-CN.ts @@ -2920,6 +2920,16 @@ export const zhCN = { description: "管理资源审核。", }, security: { + clientRestrictions: { + title: "客户端限制", + description: "选择允许成员登录或授权使用的客户端。不影响管理后台登录。", + runtime: "独立 Runtime", + unavailable: "当前实例未启用此客户端所需的设备授权。", + confirmTitle: "确认修改客户端权限?", + enable: "允许成员使用「{{client}}」登录或授权?", + disable: "关闭「{{client}}」登录?关闭后不能新登录或续期,已登录的设备不会立即下线。", + lastClient: "这是最后一个允许使用的客户端。", + }, title: "安全", description: "管理系统安全设置。", userCreation: { diff --git a/monkeyai/web/src/i18n/locales/zh-TW.ts b/monkeyai/web/src/i18n/locales/zh-TW.ts index a7596a86c..db00d19e2 100644 --- a/monkeyai/web/src/i18n/locales/zh-TW.ts +++ b/monkeyai/web/src/i18n/locales/zh-TW.ts @@ -2860,6 +2860,16 @@ export const zhTW = { description: "管理資源審核。", }, security: { + clientRestrictions: { + title: "用戶端限制", + description: "選擇允許成員登入或授權使用的用戶端。不影響管理後台登入。", + runtime: "獨立 Runtime", + unavailable: "此執行個體未啟用該用戶端所需的裝置授權。", + confirmTitle: "確認變更用戶端權限?", + enable: "允許成員使用「{{client}}」登入或授權?", + disable: "關閉「{{client}}」登入?關閉後無法再登入或續期,已登入的裝置不會立即離線。", + lastClient: "這是最後一個允許使用的用戶端。", + }, title: "安全", description: "管理系統安全設定。", userCreation: { diff --git a/monkeyai/web/src/pages/admin/security-page.tsx b/monkeyai/web/src/pages/admin/security-page.tsx index 910f3dc4d..cb1aa95fd 100644 --- a/monkeyai/web/src/pages/admin/security-page.tsx +++ b/monkeyai/web/src/pages/admin/security-page.tsx @@ -17,7 +17,14 @@ import { AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog" -import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card" +import { Switch } from "@/components/ui/switch" import { Item, ItemActions, ItemContent, ItemTitle } from "@/components/ui/item" import { Select, @@ -157,6 +164,196 @@ function MemberPolicyOption({ ) } +const clientOptions = [ + ["monkeyai-desktop", "landing.downloads.desktopClients"], + ["monkeyai-mobile", "landing.downloads.mobileClients"], + ["monkeyai-web", "app.webClient"], + ["monkeyai-runtime", "pages.security.clientRestrictions.runtime"], +] as const +type LoginClient = (typeof clientOptions)[number][0] +type ClientPolicy = { clients: Record } +const clientPolicyEndpoint = "/api/admin/v1/settings/client_access_policy" + +function ClientRestrictionsCard() { + const { t } = useTranslation() + const labels = "pages.security.clientRestrictions" + const { showToast } = useAppToast() + const [policy, setPolicy] = useState() + const [available, setAvailable] = useState([]) + const [failed, setFailed] = useState(false) + const [refresh, setRefresh] = useState(0) + const [saving, setSaving] = useState(false) + useEffect(() => { + const c = new AbortController() + const options = { signal: c.signal } + Promise.all([ + api(clientPolicyEndpoint, options), + api<{ clients: { client_id: string }[] }>( + "/api/auth/v1/clients", + options + ), + ]) + .then(([p, cap]) => { + if (!c.signal.aborted) { + setAvailable(cap.clients.map((x) => x.client_id)) + setPolicy(p) + setFailed(false) + } + }) + .catch((e) => { + if (!c.signal.aborted) { + setFailed(true) + showToast({ + status: "error", + title: ( + + ), + }) + } + }) + return () => c.abort() + }, [refresh, showToast]) + const selected = clientOptions.filter( + ([id]) => available.includes(id) && policy?.clients[id] + ).length + async function save(id: LoginClient, enabled: boolean) { + setSaving(true) + try { + setPolicy( + await api(clientPolicyEndpoint, { + method: "PATCH", + body: JSON.stringify({ client_id: id, enabled }), + }) + ) + } catch (e) { + showToast({ + status: "error", + title: , + }) + } finally { + setSaving(false) + } + } + return ( + + + {t(labels + ".title")} + {t(labels + ".description")} + + + {!policy && + (failed ? ( + + ) : ( + + ))} + {policy && + clientOptions.map(([id, label]) => ( + void save(id, checked)} + /> + ))} + + + ) +} + +function ClientAccessOption({ + id, + label, + checked, + available, + saving, + lastAllowed, + onConfirm, +}: { + id: string + label: string + checked: boolean + available: boolean + saving: boolean + lastAllowed: boolean + onConfirm: (checked: boolean) => void +}) { + const { t } = useTranslation() + const [pending, setPending] = useState(null) + const switchRef = useRef(null) + return ( + { + if (!open) setPending(null) + }} + > + + + {label} + {!available && ( + + {t("pages.security.clientRestrictions.unavailable")} + + )} + + + + + + + + + {t("pages.security.clientRestrictions.confirmTitle")} + + + + {t( + pending + ? "pages.security.clientRestrictions.enable" + : "pages.security.clientRestrictions.disable", + { client: label } + )} + {lastAllowed && pending === false && ( + <> {t("pages.security.clientRestrictions.lastClient")} + )} + + + + {t("pages.security.additionPolicy.cancel")} + + { + if (pending !== null) onConfirm(pending) + setPending(null) + }} + > + {t("pages.security.additionPolicy.confirm")} + + + + + ) +} + export function SecurityPage() { const { user } = useAuth() if (user?.role !== "admin") @@ -243,6 +440,7 @@ function SecuritySettings() { return (
+ {policyOptions("models")}