mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-12-05 21:00:15 +08:00
feat: 支持按客户端限制登录和令牌续期
This commit is contained in:
1 parent
272e0d761e
commit
5ed458ebe6
27 files changed
+677
-14
No files matched your search
@@ -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: 获取六类成员资源的添加修改与分享策略,未配置时全部允许
|
||||
|
||||
@@ -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'}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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."},
|
||||
|
||||
@@ -2901,6 +2901,16 @@ export const ar = {
|
||||
description: "إدارة الموافقات على الموارد.",
|
||||
},
|
||||
security: {
|
||||
clientRestrictions: {
|
||||
title: "قيود تطبيقات العميل",
|
||||
description: "اختر التطبيقات التي يُسمح للأعضاء بتسجيل الدخول إليها أو تفويضها. لا يتأثر تسجيل الدخول إلى لوحة الإدارة.",
|
||||
runtime: "بيئة تشغيل مستقلة",
|
||||
unavailable: "تفويض الأجهزة غير متاح في هذا المثيل.",
|
||||
confirmTitle: "هل تريد تغيير صلاحية الوصول؟",
|
||||
enable: "هل تسمح للأعضاء باستخدام {{client}}؟",
|
||||
disable: "هل تريد تعطيل تسجيل الدخول عبر {{client}}؟ سيتم حظر تسجيل الدخول الجديد وتجديد الرموز، ولن يتم فصل الأجهزة المتصلة فورًا.",
|
||||
lastClient: "هذا آخر تطبيق يُسمح باستخدامه.",
|
||||
},
|
||||
title: "الأمان",
|
||||
description: "إدارة إعدادات أمان النظام.",
|
||||
userCreation: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -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: {
|
||||
|
||||
@@ -2921,6 +2921,16 @@ export const jaJP = {
|
||||
description: "リソースの承認を管理します。",
|
||||
},
|
||||
security: {
|
||||
clientRestrictions: {
|
||||
title: "クライアント制限",
|
||||
description: "メンバーがログインまたは認可できるクライアントを選択します。管理画面へのログインには影響しません。",
|
||||
runtime: "独立 Runtime",
|
||||
unavailable: "このインスタンスではデバイス認可を利用できません。",
|
||||
confirmTitle: "クライアントの利用権限を変更しますか?",
|
||||
enable: "メンバーによる「{{client}}」の利用を許可しますか?",
|
||||
disable: "「{{client}}」のログインを無効にしますか?新規ログインと更新はできなくなりますが、ログイン中の端末はすぐには切断されません。",
|
||||
lastClient: "これは利用を許可している最後のクライアントです。",
|
||||
},
|
||||
title: "セキュリティ",
|
||||
description: "システムのセキュリティ設定を管理します。",
|
||||
userCreation: {
|
||||
|
||||
@@ -2904,6 +2904,16 @@ export const koKR = {
|
||||
description: "리소스 승인을 관리합니다.",
|
||||
},
|
||||
security: {
|
||||
clientRestrictions: {
|
||||
title: "클라이언트 제한",
|
||||
description: "구성원이 로그인하거나 승인할 수 있는 클라이언트를 선택하세요. 관리 콘솔 로그인에는 영향을 주지 않습니다.",
|
||||
runtime: "독립 런타임",
|
||||
unavailable: "이 인스턴스에서는 기기 인증을 사용할 수 없습니다.",
|
||||
confirmTitle: "클라이언트 접근 권한을 변경할까요?",
|
||||
enable: "구성원의 {{client}} 사용을 허용할까요?",
|
||||
disable: "{{client}} 로그인을 차단할까요? 새 로그인과 갱신은 차단되지만 로그인 중인 기기는 즉시 연결이 끊기지 않습니다.",
|
||||
lastClient: "현재 허용된 마지막 클라이언트입니다.",
|
||||
},
|
||||
title: "보안",
|
||||
description: "시스템 보안 설정을 관리합니다.",
|
||||
userCreation: {
|
||||
|
||||
@@ -2948,6 +2948,16 @@ export const ruRU = {
|
||||
description: "Управление одобрением ресурсов.",
|
||||
},
|
||||
security: {
|
||||
clientRestrictions: {
|
||||
title: "Ограничения клиентов",
|
||||
description: "Выберите клиенты, в которые участники могут входить или которым могут разрешить доступ. Вход в консоль администратора не меняется.",
|
||||
runtime: "Автономная среда выполнения",
|
||||
unavailable: "Авторизация устройств недоступна на этом экземпляре.",
|
||||
confirmTitle: "Изменить доступ к клиенту?",
|
||||
enable: "Разрешить участникам использовать клиент «{{client}}»?",
|
||||
disable: "Запретить вход через «{{client}}»? Новый вход и продление токенов будут недоступны. Уже подключённые устройства не будут отключены немедленно.",
|
||||
lastClient: "Это последний разрешённый клиент.",
|
||||
},
|
||||
title: "Безопасность",
|
||||
description: "Управление настройками безопасности системы.",
|
||||
userCreation: {
|
||||
|
||||
@@ -2920,6 +2920,16 @@ export const zhCN = {
|
||||
description: "管理资源审核。",
|
||||
},
|
||||
security: {
|
||||
clientRestrictions: {
|
||||
title: "客户端限制",
|
||||
description: "选择允许成员登录或授权使用的客户端。不影响管理后台登录。",
|
||||
runtime: "独立 Runtime",
|
||||
unavailable: "当前实例未启用此客户端所需的设备授权。",
|
||||
confirmTitle: "确认修改客户端权限?",
|
||||
enable: "允许成员使用「{{client}}」登录或授权?",
|
||||
disable: "关闭「{{client}}」登录?关闭后不能新登录或续期,已登录的设备不会立即下线。",
|
||||
lastClient: "这是最后一个允许使用的客户端。",
|
||||
},
|
||||
title: "安全",
|
||||
description: "管理系统安全设置。",
|
||||
userCreation: {
|
||||
|
||||
@@ -2860,6 +2860,16 @@ export const zhTW = {
|
||||
description: "管理資源審核。",
|
||||
},
|
||||
security: {
|
||||
clientRestrictions: {
|
||||
title: "用戶端限制",
|
||||
description: "選擇允許成員登入或授權使用的用戶端。不影響管理後台登入。",
|
||||
runtime: "獨立 Runtime",
|
||||
unavailable: "此執行個體未啟用該用戶端所需的裝置授權。",
|
||||
confirmTitle: "確認變更用戶端權限?",
|
||||
enable: "允許成員使用「{{client}}」登入或授權?",
|
||||
disable: "關閉「{{client}}」登入?關閉後無法再登入或續期,已登入的裝置不會立即離線。",
|
||||
lastClient: "這是最後一個允許使用的用戶端。",
|
||||
},
|
||||
title: "安全",
|
||||
description: "管理系統安全設定。",
|
||||
userCreation: {
|
||||
|
||||
@@ -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<LoginClient, boolean> }
|
||||
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<ClientPolicy>()
|
||||
const [available, setAvailable] = useState<string[]>([])
|
||||
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<ClientPolicy>(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: (
|
||||
<LocalizedMessage message={uiError(e, "webUi.requestFailed")} />
|
||||
),
|
||||
})
|
||||
}
|
||||
})
|
||||
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<ClientPolicy>(clientPolicyEndpoint, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ client_id: id, enabled }),
|
||||
})
|
||||
)
|
||||
} catch (e) {
|
||||
showToast({
|
||||
status: "error",
|
||||
title: <LocalizedMessage message={uiError(e, "webUi.requestFailed")} />,
|
||||
})
|
||||
} finally {
|
||||
setSaving(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t(labels + ".title")}</CardTitle>
|
||||
<CardDescription>{t(labels + ".description")}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!policy &&
|
||||
(failed ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => {
|
||||
setFailed(false)
|
||||
setRefresh((n) => n + 1)
|
||||
}}
|
||||
>
|
||||
{t("statistics.retry")}
|
||||
</Button>
|
||||
) : (
|
||||
<TableLoading />
|
||||
))}
|
||||
{policy &&
|
||||
clientOptions.map(([id, label]) => (
|
||||
<ClientAccessOption
|
||||
key={id}
|
||||
id={id}
|
||||
label={t(label)}
|
||||
checked={policy.clients[id]}
|
||||
available={available.includes(id)}
|
||||
saving={saving}
|
||||
lastAllowed={selected === 1 && policy.clients[id]}
|
||||
onConfirm={(checked) => void save(id, checked)}
|
||||
/>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
|
||||
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<boolean | null>(null)
|
||||
const switchRef = useRef<HTMLButtonElement>(null)
|
||||
return (
|
||||
<AlertDialog
|
||||
open={pending !== null}
|
||||
onOpenChange={(open) => {
|
||||
if (!open) setPending(null)
|
||||
}}
|
||||
>
|
||||
<Item variant="outline">
|
||||
<ItemContent>
|
||||
<ItemTitle id={"security-client-" + id}>{label}</ItemTitle>
|
||||
{!available && (
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{t("pages.security.clientRestrictions.unavailable")}
|
||||
</span>
|
||||
)}
|
||||
</ItemContent>
|
||||
<ItemActions>
|
||||
<Switch
|
||||
ref={switchRef}
|
||||
aria-labelledby={"security-client-" + id}
|
||||
checked={checked}
|
||||
disabled={!available || saving}
|
||||
onCheckedChange={setPending}
|
||||
/>
|
||||
</ItemActions>
|
||||
</Item>
|
||||
<AlertDialogContent finalFocus={switchRef}>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t("pages.security.clientRestrictions.confirmTitle")}
|
||||
</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogDescription>
|
||||
{t(
|
||||
pending
|
||||
? "pages.security.clientRestrictions.enable"
|
||||
: "pages.security.clientRestrictions.disable",
|
||||
{ client: label }
|
||||
)}
|
||||
{lastAllowed && pending === false && (
|
||||
<> {t("pages.security.clientRestrictions.lastClient")}</>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>
|
||||
{t("pages.security.additionPolicy.cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => {
|
||||
if (pending !== null) onConfirm(pending)
|
||||
setPending(null)
|
||||
}}
|
||||
>
|
||||
{t("pages.security.additionPolicy.confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)
|
||||
}
|
||||
|
||||
export function SecurityPage() {
|
||||
const { user } = useAuth()
|
||||
if (user?.role !== "admin")
|
||||
@@ -243,6 +440,7 @@ function SecuritySettings() {
|
||||
return (
|
||||
<PolicyContext.Provider value={value ? { value, busy, save } : null}>
|
||||
<section className="flex flex-1 flex-col gap-4 p-4 pt-0">
|
||||
<ClientRestrictionsCard />
|
||||
<NetworkSettingsCard settingKey="model_network">
|
||||
{policyOptions("models")}
|
||||
</NetworkSettingsCard>
|
||||
|
||||
Reference in new issue
Block a user