feat: CPU/RAM limits per stage, NPM access list (global + per-project)
Resource limits: - Add cpu_limit (cores) and memory_limit (MB) fields to Stage model - Pass limits to Docker container via NanoCPUs and Memory in HostConfig - Add CPU/Memory fields to stage creation form in project detail - 0 = unlimited (default) NPM access list: - Add npm_access_list_id to Settings (global default) and Project (per-project override) - Per-project overrides global when > 0 - NPM provider passes access_list_id when configuring proxy hosts - Add GET /api/settings/npm-access-lists endpoint to list NPM access lists - Add access list picker on NPM settings page (global) - Add access list ID field on project edit form (per-project) - DB migrations for all new columns
This commit is contained in:
+27
-8
@@ -13,14 +13,16 @@ import (
|
|||||||
|
|
||||||
// stageRequest is the expected JSON body for creating/updating a stage.
|
// stageRequest is the expected JSON body for creating/updating a stage.
|
||||||
type stageRequest struct {
|
type stageRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
TagPattern string `json:"tag_pattern"`
|
TagPattern string `json:"tag_pattern"`
|
||||||
AutoDeploy *bool `json:"auto_deploy"`
|
AutoDeploy *bool `json:"auto_deploy"`
|
||||||
MaxInstances *int `json:"max_instances"`
|
MaxInstances *int `json:"max_instances"`
|
||||||
Confirm *bool `json:"confirm"`
|
Confirm *bool `json:"confirm"`
|
||||||
PromoteFrom string `json:"promote_from"`
|
PromoteFrom string `json:"promote_from"`
|
||||||
Subdomain string `json:"subdomain"`
|
Subdomain string `json:"subdomain"`
|
||||||
NotificationURL string `json:"notification_url"`
|
NotificationURL string `json:"notification_url"`
|
||||||
|
CpuLimit *float64 `json:"cpu_limit"`
|
||||||
|
MemoryLimit *int `json:"memory_limit"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// createStage handles POST /api/projects/{id}/stages.
|
// createStage handles POST /api/projects/{id}/stages.
|
||||||
@@ -64,6 +66,15 @@ func (s *Server) createStage(w http.ResponseWriter, r *http.Request) {
|
|||||||
confirm = *req.Confirm
|
confirm = *req.Confirm
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var cpuLimit float64
|
||||||
|
if req.CpuLimit != nil {
|
||||||
|
cpuLimit = *req.CpuLimit
|
||||||
|
}
|
||||||
|
var memoryLimit int
|
||||||
|
if req.MemoryLimit != nil {
|
||||||
|
memoryLimit = *req.MemoryLimit
|
||||||
|
}
|
||||||
|
|
||||||
stage, err := s.store.CreateStage(store.Stage{
|
stage, err := s.store.CreateStage(store.Stage{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
Name: req.Name,
|
Name: req.Name,
|
||||||
@@ -74,6 +85,8 @@ func (s *Server) createStage(w http.ResponseWriter, r *http.Request) {
|
|||||||
PromoteFrom: req.PromoteFrom,
|
PromoteFrom: req.PromoteFrom,
|
||||||
Subdomain: req.Subdomain,
|
Subdomain: req.Subdomain,
|
||||||
NotificationURL: req.NotificationURL,
|
NotificationURL: req.NotificationURL,
|
||||||
|
CpuLimit: cpuLimit,
|
||||||
|
MemoryLimit: memoryLimit,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
slog.Error("failed to create stage", "error", err)
|
slog.Error("failed to create stage", "error", err)
|
||||||
@@ -131,6 +144,12 @@ func (s *Server) updateStage(w http.ResponseWriter, r *http.Request) {
|
|||||||
updated.PromoteFrom = req.PromoteFrom
|
updated.PromoteFrom = req.PromoteFrom
|
||||||
updated.Subdomain = req.Subdomain
|
updated.Subdomain = req.Subdomain
|
||||||
updated.NotificationURL = req.NotificationURL
|
updated.NotificationURL = req.NotificationURL
|
||||||
|
if req.CpuLimit != nil {
|
||||||
|
updated.CpuLimit = *req.CpuLimit
|
||||||
|
}
|
||||||
|
if req.MemoryLimit != nil {
|
||||||
|
updated.MemoryLimit = *req.MemoryLimit
|
||||||
|
}
|
||||||
|
|
||||||
if err := s.store.UpdateStage(updated); err != nil {
|
if err := s.store.UpdateStage(updated); err != nil {
|
||||||
slog.Error("failed to update stage", "error", err)
|
slog.Error("failed to update stage", "error", err)
|
||||||
|
|||||||
@@ -49,6 +49,12 @@ type ContainerConfig struct {
|
|||||||
|
|
||||||
// Mounts is a list of bind mounts to attach to the container.
|
// Mounts is a list of bind mounts to attach to the container.
|
||||||
Mounts []mount.Mount
|
Mounts []mount.Mount
|
||||||
|
|
||||||
|
// CpuLimit is the CPU limit in cores (e.g., 0.5, 1, 2). 0 = unlimited.
|
||||||
|
CpuLimit float64
|
||||||
|
|
||||||
|
// MemoryLimit is the memory limit in megabytes. 0 = unlimited.
|
||||||
|
MemoryLimit int
|
||||||
}
|
}
|
||||||
|
|
||||||
// sanitizeTag replaces characters that are invalid in Docker container names
|
// sanitizeTag replaces characters that are invalid in Docker container names
|
||||||
@@ -101,6 +107,7 @@ func (c *Client) CreateContainer(ctx context.Context, cfg ContainerConfig) (stri
|
|||||||
PortBindings: portBindings,
|
PortBindings: portBindings,
|
||||||
RestartPolicy: container.RestartPolicy{Name: container.RestartPolicyDisabled},
|
RestartPolicy: container.RestartPolicy{Name: container.RestartPolicyDisabled},
|
||||||
Mounts: cfg.Mounts,
|
Mounts: cfg.Mounts,
|
||||||
|
Resources: containerResources(cfg.CpuLimit, cfg.MemoryLimit),
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attach to network at creation time if specified.
|
// Attach to network at creation time if specified.
|
||||||
@@ -128,6 +135,19 @@ func (c *Client) CreateContainer(ctx context.Context, cfg ContainerConfig) (stri
|
|||||||
return resp.ID, nil
|
return resp.ID, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// containerResources builds Docker resource constraints from CPU cores and memory MB.
|
||||||
|
func containerResources(cpuLimit float64, memoryLimitMB int) container.Resources {
|
||||||
|
r := container.Resources{}
|
||||||
|
if cpuLimit > 0 {
|
||||||
|
// NanoCPUs is in units of 1e-9 CPUs. 1 core = 1e9 nanoCPUs.
|
||||||
|
r.NanoCPUs = int64(cpuLimit * 1e9)
|
||||||
|
}
|
||||||
|
if memoryLimitMB > 0 {
|
||||||
|
r.Memory = int64(memoryLimitMB) * 1024 * 1024
|
||||||
|
}
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
// StartContainer starts a stopped container.
|
// StartContainer starts a stopped container.
|
||||||
func (c *Client) StartContainer(ctx context.Context, containerID string) error {
|
func (c *Client) StartContainer(ctx context.Context, containerID string) error {
|
||||||
if _, err := c.api.ContainerStart(ctx, containerID, client.ContainerStartOptions{}); err != nil {
|
if _, err := c.api.ContainerStart(ctx, containerID, client.ContainerStartOptions{}); err != nil {
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ func (p *NpmProvider) ConfigureRoute(ctx context.Context, domain, targetHost str
|
|||||||
BlockExploits: true,
|
BlockExploits: true,
|
||||||
AllowWebsocket: true,
|
AllowWebsocket: true,
|
||||||
HTTP2Support: true,
|
HTTP2Support: true,
|
||||||
|
AccessListID: opts.AccessListID,
|
||||||
Meta: npm.Meta{},
|
Meta: npm.Meta{},
|
||||||
Locations: []any{},
|
Locations: []any{},
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import "context"
|
|||||||
// RouteOptions holds optional configuration for a proxy route.
|
// RouteOptions holds optional configuration for a proxy route.
|
||||||
type RouteOptions struct {
|
type RouteOptions struct {
|
||||||
SSLCertificateID int
|
SSLCertificateID int
|
||||||
|
AccessListID int // NPM access list ID for authentication, 0 = public
|
||||||
ForwardScheme string // "http" or "https", defaults to "http"
|
ForwardScheme string // "http" or "https", defaults to "http"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ type Project struct {
|
|||||||
Image string `json:"image"`
|
Image string `json:"image"`
|
||||||
Port int `json:"port"`
|
Port int `json:"port"`
|
||||||
Healthcheck string `json:"healthcheck"`
|
Healthcheck string `json:"healthcheck"`
|
||||||
Env string `json:"env"` // JSON-encoded map
|
Env string `json:"env"` // JSON-encoded map
|
||||||
Volumes string `json:"volumes"` // JSON-encoded map
|
Volumes string `json:"volumes"` // JSON-encoded map
|
||||||
CreatedAt string `json:"created_at"`
|
NpmAccessListID int `json:"npm_access_list_id"` // per-project override, 0 = use global
|
||||||
UpdatedAt string `json:"updated_at"`
|
CreatedAt string `json:"created_at"`
|
||||||
|
UpdatedAt string `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stage represents a deployment stage within a project (e.g. dev, rel, prod).
|
// Stage represents a deployment stage within a project (e.g. dev, rel, prod).
|
||||||
@@ -23,10 +24,12 @@ type Stage struct {
|
|||||||
AutoDeploy bool `json:"auto_deploy"`
|
AutoDeploy bool `json:"auto_deploy"`
|
||||||
MaxInstances int `json:"max_instances"`
|
MaxInstances int `json:"max_instances"`
|
||||||
Confirm bool `json:"confirm"`
|
Confirm bool `json:"confirm"`
|
||||||
EnableProxy bool `json:"enable_proxy"`
|
EnableProxy bool `json:"enable_proxy"`
|
||||||
PromoteFrom string `json:"promote_from"`
|
PromoteFrom string `json:"promote_from"`
|
||||||
Subdomain string `json:"subdomain"`
|
Subdomain string `json:"subdomain"`
|
||||||
NotificationURL string `json:"notification_url"`
|
NotificationURL string `json:"notification_url"`
|
||||||
|
CpuLimit float64 `json:"cpu_limit"` // CPU cores (e.g., 0.5, 1, 2), 0 = unlimited
|
||||||
|
MemoryLimit int `json:"memory_limit"` // megabytes, 0 = unlimited
|
||||||
CreatedAt string `json:"created_at"`
|
CreatedAt string `json:"created_at"`
|
||||||
UpdatedAt string `json:"updated_at"`
|
UpdatedAt string `json:"updated_at"`
|
||||||
}
|
}
|
||||||
@@ -64,6 +67,7 @@ type Settings struct {
|
|||||||
CloudflareAPIToken string `json:"cloudflare_api_token"`
|
CloudflareAPIToken string `json:"cloudflare_api_token"`
|
||||||
CloudflareZoneID string `json:"cloudflare_zone_id"`
|
CloudflareZoneID string `json:"cloudflare_zone_id"`
|
||||||
NpmRemote bool `json:"npm_remote"`
|
NpmRemote bool `json:"npm_remote"`
|
||||||
|
NpmAccessListID int `json:"npm_access_list_id"`
|
||||||
ProxyProvider string `json:"proxy_provider"`
|
ProxyProvider string `json:"proxy_provider"`
|
||||||
TraefikEntrypoint string `json:"traefik_entrypoint"`
|
TraefikEntrypoint string `json:"traefik_entrypoint"`
|
||||||
TraefikCertResolver string `json:"traefik_cert_resolver"`
|
TraefikCertResolver string `json:"traefik_cert_resolver"`
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import (
|
|||||||
"github.com/google/uuid"
|
"github.com/google/uuid"
|
||||||
)
|
)
|
||||||
|
|
||||||
const stageColumns = `id, project_id, name, tag_pattern, auto_deploy, max_instances, confirm, enable_proxy, promote_from, subdomain, notification_url, created_at, updated_at`
|
const stageColumns = `id, project_id, name, tag_pattern, auto_deploy, max_instances, confirm, enable_proxy, promote_from, subdomain, notification_url, cpu_limit, memory_limit, created_at, updated_at`
|
||||||
|
|
||||||
// CreateStage inserts a new stage for a project.
|
// CreateStage inserts a new stage for a project.
|
||||||
func (s *Store) CreateStage(st Stage) (Stage, error) {
|
func (s *Store) CreateStage(st Stage) (Stage, error) {
|
||||||
@@ -17,9 +17,10 @@ func (s *Store) CreateStage(st Stage) (Stage, error) {
|
|||||||
st.UpdatedAt = st.CreatedAt
|
st.UpdatedAt = st.CreatedAt
|
||||||
|
|
||||||
_, err := s.db.Exec(
|
_, err := s.db.Exec(
|
||||||
`INSERT INTO stages (`+stageColumns+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
`INSERT INTO stages (`+stageColumns+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
st.ID, st.ProjectID, st.Name, st.TagPattern, BoolToInt(st.AutoDeploy), st.MaxInstances,
|
st.ID, st.ProjectID, st.Name, st.TagPattern, BoolToInt(st.AutoDeploy), st.MaxInstances,
|
||||||
BoolToInt(st.Confirm), BoolToInt(st.EnableProxy), st.PromoteFrom, st.Subdomain, st.NotificationURL, st.CreatedAt, st.UpdatedAt,
|
BoolToInt(st.Confirm), BoolToInt(st.EnableProxy), st.PromoteFrom, st.Subdomain, st.NotificationURL,
|
||||||
|
st.CpuLimit, st.MemoryLimit, st.CreatedAt, st.UpdatedAt,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Stage{}, fmt.Errorf("insert stage: %w", err)
|
return Stage{}, fmt.Errorf("insert stage: %w", err)
|
||||||
@@ -55,7 +56,8 @@ func (s *Store) GetStageByID(id string) (Stage, error) {
|
|||||||
err := s.db.QueryRow(
|
err := s.db.QueryRow(
|
||||||
`SELECT `+stageColumns+` FROM stages WHERE id = ?`, id,
|
`SELECT `+stageColumns+` FROM stages WHERE id = ?`, id,
|
||||||
).Scan(&st.ID, &st.ProjectID, &st.Name, &st.TagPattern, &autoDeploy, &st.MaxInstances,
|
).Scan(&st.ID, &st.ProjectID, &st.Name, &st.TagPattern, &autoDeploy, &st.MaxInstances,
|
||||||
&confirm, &enableProxy, &st.PromoteFrom, &st.Subdomain, &st.NotificationURL, &st.CreatedAt, &st.UpdatedAt)
|
&confirm, &enableProxy, &st.PromoteFrom, &st.Subdomain, &st.NotificationURL,
|
||||||
|
&st.CpuLimit, &st.MemoryLimit, &st.CreatedAt, &st.UpdatedAt)
|
||||||
if errors.Is(err, sql.ErrNoRows) {
|
if errors.Is(err, sql.ErrNoRows) {
|
||||||
return Stage{}, fmt.Errorf("stage %s: %w", id, ErrNotFound)
|
return Stage{}, fmt.Errorf("stage %s: %w", id, ErrNotFound)
|
||||||
}
|
}
|
||||||
@@ -72,10 +74,11 @@ func (s *Store) GetStageByID(id string) (Stage, error) {
|
|||||||
func (s *Store) UpdateStage(st Stage) error {
|
func (s *Store) UpdateStage(st Stage) error {
|
||||||
st.UpdatedAt = Now()
|
st.UpdatedAt = Now()
|
||||||
result, err := s.db.Exec(
|
result, err := s.db.Exec(
|
||||||
`UPDATE stages SET name=?, tag_pattern=?, auto_deploy=?, max_instances=?, confirm=?, enable_proxy=?, promote_from=?, subdomain=?, notification_url=?, updated_at=?
|
`UPDATE stages SET name=?, tag_pattern=?, auto_deploy=?, max_instances=?, confirm=?, enable_proxy=?, promote_from=?, subdomain=?, notification_url=?, cpu_limit=?, memory_limit=?, updated_at=?
|
||||||
WHERE id=?`,
|
WHERE id=?`,
|
||||||
st.Name, st.TagPattern, BoolToInt(st.AutoDeploy), st.MaxInstances,
|
st.Name, st.TagPattern, BoolToInt(st.AutoDeploy), st.MaxInstances,
|
||||||
BoolToInt(st.Confirm), BoolToInt(st.EnableProxy), st.PromoteFrom, st.Subdomain, st.NotificationURL, st.UpdatedAt, st.ID,
|
BoolToInt(st.Confirm), BoolToInt(st.EnableProxy), st.PromoteFrom, st.Subdomain, st.NotificationURL,
|
||||||
|
st.CpuLimit, st.MemoryLimit, st.UpdatedAt, st.ID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("update stage: %w", err)
|
return fmt.Errorf("update stage: %w", err)
|
||||||
@@ -113,7 +116,8 @@ func scanStage(rows *sql.Rows) (Stage, error) {
|
|||||||
var st Stage
|
var st Stage
|
||||||
var autoDeploy, confirm, enableProxy int
|
var autoDeploy, confirm, enableProxy int
|
||||||
err := rows.Scan(&st.ID, &st.ProjectID, &st.Name, &st.TagPattern, &autoDeploy, &st.MaxInstances,
|
err := rows.Scan(&st.ID, &st.ProjectID, &st.Name, &st.TagPattern, &autoDeploy, &st.MaxInstances,
|
||||||
&confirm, &enableProxy, &st.PromoteFrom, &st.Subdomain, &st.NotificationURL, &st.CreatedAt, &st.UpdatedAt)
|
&confirm, &enableProxy, &st.PromoteFrom, &st.Subdomain, &st.NotificationURL,
|
||||||
|
&st.CpuLimit, &st.MemoryLimit, &st.CreatedAt, &st.UpdatedAt)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return Stage{}, fmt.Errorf("scan stage: %w", err)
|
return Stage{}, fmt.Errorf("scan stage: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import type {
|
|||||||
InspectResult,
|
InspectResult,
|
||||||
Instance,
|
Instance,
|
||||||
NpmCertificate,
|
NpmCertificate,
|
||||||
|
NpmAccessList,
|
||||||
ProxyRoute,
|
ProxyRoute,
|
||||||
Project,
|
Project,
|
||||||
ProjectDetail,
|
ProjectDetail,
|
||||||
@@ -282,6 +283,10 @@ export function listNpmCertificates(): Promise<NpmCertificate[]> {
|
|||||||
return get<NpmCertificate[]>('/api/settings/npm-certificates');
|
return get<NpmCertificate[]>('/api/settings/npm-certificates');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function listNpmAccessLists(): Promise<NpmAccessList[]> {
|
||||||
|
return get<NpmAccessList[]>('/api/settings/npm-access-lists');
|
||||||
|
}
|
||||||
|
|
||||||
// ── DNS ────────────────────────────────────────────────────────────
|
// ── DNS ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function testDnsConnection(provider: string, token: string, zoneId: string): Promise<{ success: boolean; error?: string }> {
|
export function testDnsConnection(provider: string, token: string, zoneId: string): Promise<{ success: boolean; error?: string }> {
|
||||||
|
|||||||
@@ -103,6 +103,12 @@
|
|||||||
"maxInstances": "Max Instances",
|
"maxInstances": "Max Instances",
|
||||||
"autoDeployLabel": "Auto Deploy",
|
"autoDeployLabel": "Auto Deploy",
|
||||||
"enableProxy": "Enable Proxy",
|
"enableProxy": "Enable Proxy",
|
||||||
|
"accessListId": "NPM Access List ID",
|
||||||
|
"accessListIdHelp": "Per-project override. 0 = use global default from NPM settings.",
|
||||||
|
"cpuLimit": "CPU Limit (cores)",
|
||||||
|
"cpuLimitHelp": "e.g., 0.5, 1, 2. Leave 0 for unlimited",
|
||||||
|
"memoryLimit": "Memory Limit (MB)",
|
||||||
|
"memoryLimitHelp": "e.g., 256, 512, 1024. Leave 0 for unlimited",
|
||||||
"npmProxy": "NPM Proxy",
|
"npmProxy": "NPM Proxy",
|
||||||
"creating": "Creating...",
|
"creating": "Creating...",
|
||||||
"createStage": "Create Stage",
|
"createStage": "Create Stage",
|
||||||
@@ -376,7 +382,13 @@
|
|||||||
"saveFailedConnection": "Cannot save \u2014 connection test failed",
|
"saveFailedConnection": "Cannot save \u2014 connection test failed",
|
||||||
"remoteMode": "Remote NPM",
|
"remoteMode": "Remote NPM",
|
||||||
"remoteModeHelp": "Enable when NPM runs on a different machine than Docker. Forwards to Server IP with published host ports.",
|
"remoteModeHelp": "Enable when NPM runs on a different machine than Docker. Forwards to Server IP with published host ports.",
|
||||||
"remoteModeWarning": "Requires Server IP in General settings. Ports are auto-mapped to random host ports."
|
"remoteModeWarning": "Requires Server IP in General settings. Ports are auto-mapped to random host ports.",
|
||||||
|
"accessList": "Default Access List",
|
||||||
|
"accessListHelp": "NPM access list for HTTP authentication on proxy hosts. Can be overridden per project.",
|
||||||
|
"noAccessList": "None (public)",
|
||||||
|
"selectAccessList": "Select an access list",
|
||||||
|
"noAccessLists": "No access lists found in NPM",
|
||||||
|
"accessListLoadFailed": "Failed to load access lists"
|
||||||
},
|
},
|
||||||
"settingsCredentials": {
|
"settingsCredentials": {
|
||||||
"title": "Credentials",
|
"title": "Credentials",
|
||||||
|
|||||||
@@ -103,6 +103,12 @@
|
|||||||
"maxInstances": "Макс. экземпляров",
|
"maxInstances": "Макс. экземпляров",
|
||||||
"autoDeployLabel": "Авто-деплой",
|
"autoDeployLabel": "Авто-деплой",
|
||||||
"enableProxy": "Включить прокси",
|
"enableProxy": "Включить прокси",
|
||||||
|
"accessListId": "ID списка доступа NPM",
|
||||||
|
"accessListIdHelp": "Переопределение для проекта. 0 = использовать глобальное из настроек NPM.",
|
||||||
|
"cpuLimit": "Лимит CPU (ядра)",
|
||||||
|
"cpuLimitHelp": "напр., 0.5, 1, 2. Оставьте 0 для без ограничений",
|
||||||
|
"memoryLimit": "Лимит памяти (МБ)",
|
||||||
|
"memoryLimitHelp": "напр., 256, 512, 1024. Оставьте 0 для без ограничений",
|
||||||
"npmProxy": "NPM прокси",
|
"npmProxy": "NPM прокси",
|
||||||
"creating": "Создание...",
|
"creating": "Создание...",
|
||||||
"createStage": "Создать стадию",
|
"createStage": "Создать стадию",
|
||||||
@@ -376,7 +382,13 @@
|
|||||||
"saveFailedConnection": "Невозможно сохранить — проверка соединения не пройдена",
|
"saveFailedConnection": "Невозможно сохранить — проверка соединения не пройдена",
|
||||||
"remoteMode": "Удалённый NPM",
|
"remoteMode": "Удалённый NPM",
|
||||||
"remoteModeHelp": "Включите, если NPM работает на другой машине. Перенаправление на IP сервера с опубликованными портами.",
|
"remoteModeHelp": "Включите, если NPM работает на другой машине. Перенаправление на IP сервера с опубликованными портами.",
|
||||||
"remoteModeWarning": "Требуется IP сервера в общих настройках. Порты автоматически привязываются к случайным портам хоста."
|
"remoteModeWarning": "Требуется IP сервера в общих настройках. Порты автоматически привязываются к случайным портам хоста.",
|
||||||
|
"accessList": "Список доступа по умолчанию",
|
||||||
|
"accessListHelp": "Список доступа NPM для HTTP-аутентификации на прокси-хостах. Можно переопределить для каждого проекта.",
|
||||||
|
"noAccessList": "Нет (публичный)",
|
||||||
|
"selectAccessList": "Выберите список доступа",
|
||||||
|
"noAccessLists": "Списки доступа в NPM не найдены",
|
||||||
|
"accessListLoadFailed": "Не удалось загрузить списки доступа"
|
||||||
},
|
},
|
||||||
"settingsCredentials": {
|
"settingsCredentials": {
|
||||||
"title": "Учётные данные",
|
"title": "Учётные данные",
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export interface Project {
|
|||||||
healthcheck: string;
|
healthcheck: string;
|
||||||
env: string;
|
env: string;
|
||||||
volumes: string;
|
volumes: string;
|
||||||
|
npm_access_list_id: number;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
@@ -24,6 +25,8 @@ export interface Stage {
|
|||||||
enable_proxy: boolean;
|
enable_proxy: boolean;
|
||||||
promote_from: string;
|
promote_from: string;
|
||||||
subdomain: string;
|
subdomain: string;
|
||||||
|
cpu_limit: number;
|
||||||
|
memory_limit: number;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
@@ -107,6 +110,7 @@ export interface Settings {
|
|||||||
/** Sent on PUT to update the password; never returned by GET. */
|
/** Sent on PUT to update the password; never returned by GET. */
|
||||||
npm_password?: string;
|
npm_password?: string;
|
||||||
npm_remote: boolean;
|
npm_remote: boolean;
|
||||||
|
npm_access_list_id: number;
|
||||||
polling_interval: string;
|
polling_interval: string;
|
||||||
base_volume_path: string;
|
base_volume_path: string;
|
||||||
ssl_certificate_id: number;
|
ssl_certificate_id: number;
|
||||||
@@ -258,6 +262,12 @@ export interface ProxyHealth {
|
|||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** An NPM access list for proxy authentication. */
|
||||||
|
export interface NpmAccessList {
|
||||||
|
id: number;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
/** A proxy route managed by a deployed instance. */
|
/** A proxy route managed by a deployed instance. */
|
||||||
export interface ProxyRoute {
|
export interface ProxyRoute {
|
||||||
instance_id: string;
|
instance_id: string;
|
||||||
|
|||||||
@@ -35,6 +35,8 @@
|
|||||||
let stageAutoDeploy = $state(true);
|
let stageAutoDeploy = $state(true);
|
||||||
let stageEnableProxy = $state(true);
|
let stageEnableProxy = $state(true);
|
||||||
let stageMaxInstances = $state('1');
|
let stageMaxInstances = $state('1');
|
||||||
|
let stageCpuLimit = $state('');
|
||||||
|
let stageMemoryLimit = $state('');
|
||||||
let addingStage = $state(false);
|
let addingStage = $state(false);
|
||||||
|
|
||||||
async function handleAddStage() {
|
async function handleAddStage() {
|
||||||
@@ -47,9 +49,11 @@
|
|||||||
auto_deploy: stageAutoDeploy,
|
auto_deploy: stageAutoDeploy,
|
||||||
enable_proxy: stageEnableProxy,
|
enable_proxy: stageEnableProxy,
|
||||||
max_instances: parseInt(stageMaxInstances) || 1,
|
max_instances: parseInt(stageMaxInstances) || 1,
|
||||||
|
cpu_limit: parseFloat(stageCpuLimit) || 0,
|
||||||
|
memory_limit: parseInt(stageMemoryLimit) || 0,
|
||||||
});
|
});
|
||||||
toasts.success($t('projectDetail.stageCreated', { name: stageName }));
|
toasts.success($t('projectDetail.stageCreated', { name: stageName }));
|
||||||
stageName = ''; stageTagPattern = '*'; stageAutoDeploy = true; stageEnableProxy = true; stageMaxInstances = '1';
|
stageName = ''; stageTagPattern = '*'; stageAutoDeploy = true; stageEnableProxy = true; stageMaxInstances = '1'; stageCpuLimit = ''; stageMemoryLimit = '';
|
||||||
showAddStage = false;
|
showAddStage = false;
|
||||||
await loadProject();
|
await loadProject();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -65,6 +69,7 @@
|
|||||||
let editImage = $state('');
|
let editImage = $state('');
|
||||||
let editPort = $state('');
|
let editPort = $state('');
|
||||||
let editHealthcheck = $state('');
|
let editHealthcheck = $state('');
|
||||||
|
let editAccessListId = $state('');
|
||||||
let saving = $state(false);
|
let saving = $state(false);
|
||||||
|
|
||||||
function startEditing() {
|
function startEditing() {
|
||||||
@@ -73,6 +78,7 @@
|
|||||||
editImage = project.image;
|
editImage = project.image;
|
||||||
editPort = String(project.port || '');
|
editPort = String(project.port || '');
|
||||||
editHealthcheck = project.healthcheck || '';
|
editHealthcheck = project.healthcheck || '';
|
||||||
|
editAccessListId = String(project.npm_access_list_id || '0');
|
||||||
editing = true;
|
editing = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -85,6 +91,7 @@
|
|||||||
image: editImage.trim(),
|
image: editImage.trim(),
|
||||||
port: parseInt(editPort) || 0,
|
port: parseInt(editPort) || 0,
|
||||||
healthcheck: editHealthcheck.trim(),
|
healthcheck: editHealthcheck.trim(),
|
||||||
|
npm_access_list_id: parseInt(editAccessListId) || 0,
|
||||||
});
|
});
|
||||||
toasts.success($t('projectDetail.projectUpdated'));
|
toasts.success($t('projectDetail.projectUpdated'));
|
||||||
editing = false;
|
editing = false;
|
||||||
@@ -281,6 +288,7 @@
|
|||||||
<FormField label={$t('projectDetail.imageLabel')} name="editImage" bind:value={editImage} />
|
<FormField label={$t('projectDetail.imageLabel')} name="editImage" bind:value={editImage} />
|
||||||
<FormField label={$t('projectDetail.portLabel')} name="editPort" type="number" bind:value={editPort} />
|
<FormField label={$t('projectDetail.portLabel')} name="editPort" type="number" bind:value={editPort} />
|
||||||
<FormField label={$t('projectDetail.healthcheckLabel')} name="editHealthcheck" bind:value={editHealthcheck} placeholder="/api/health" />
|
<FormField label={$t('projectDetail.healthcheckLabel')} name="editHealthcheck" bind:value={editHealthcheck} placeholder="/api/health" />
|
||||||
|
<FormField label={$t('projectDetail.accessListId')} name="editAccessListId" type="number" bind:value={editAccessListId} placeholder="0" helpText={$t('projectDetail.accessListIdHelp')} />
|
||||||
</div>
|
</div>
|
||||||
<div class="mt-4 flex items-center gap-2 justify-end">
|
<div class="mt-4 flex items-center gap-2 justify-end">
|
||||||
<button
|
<button
|
||||||
@@ -349,23 +357,29 @@
|
|||||||
|
|
||||||
{#if showAddStage}
|
{#if showAddStage}
|
||||||
<div class="mt-3 rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-4 animate-scale-in">
|
<div class="mt-3 rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-4 animate-scale-in">
|
||||||
<div class="grid grid-cols-2 gap-3 sm:grid-cols-5">
|
<div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
<FormField label={$t('projectDetail.nameLabel')} name="stageName" bind:value={stageName} placeholder="dev" />
|
<FormField label={$t('projectDetail.nameLabel')} name="stageName" bind:value={stageName} placeholder="dev" />
|
||||||
<FormField label={$t('projectDetail.tagPattern')} name="stagePattern" bind:value={stageTagPattern} placeholder="dev-*" helpText={$t('projectDetail.tagPatternHelp')} />
|
<FormField label={$t('projectDetail.tagPattern')} name="stagePattern" bind:value={stageTagPattern} placeholder="dev-*" helpText={$t('projectDetail.tagPatternHelp')} />
|
||||||
<FormField label={$t('projectDetail.maxInstances')} name="stageMax" type="number" bind:value={stageMaxInstances} />
|
<FormField label={$t('projectDetail.maxInstances')} name="stageMax" type="number" bind:value={stageMaxInstances} />
|
||||||
<div class="flex flex-col gap-1.5">
|
<div class="flex gap-4 items-end">
|
||||||
<label class="text-sm font-medium text-[var(--text-primary)]">{$t('projectDetail.autoDeployLabel')}</label>
|
<div class="flex flex-col gap-1.5">
|
||||||
<div class="flex items-center h-[38px]">
|
<label class="text-sm font-medium text-[var(--text-primary)]">{$t('projectDetail.autoDeployLabel')}</label>
|
||||||
<ToggleSwitch bind:checked={stageAutoDeploy} label={$t('projectDetail.autoDeployLabel')} />
|
<div class="flex items-center h-[38px]">
|
||||||
</div>
|
<ToggleSwitch bind:checked={stageAutoDeploy} label={$t('projectDetail.autoDeployLabel')} />
|
||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col gap-1.5">
|
</div>
|
||||||
<label class="text-sm font-medium text-[var(--text-primary)]">{$t('projectDetail.enableProxy')}</label>
|
<div class="flex flex-col gap-1.5">
|
||||||
<div class="flex items-center h-[38px]">
|
<label class="text-sm font-medium text-[var(--text-primary)]">{$t('projectDetail.enableProxy')}</label>
|
||||||
<ToggleSwitch bind:checked={stageEnableProxy} label={$t('projectDetail.enableProxy')} />
|
<div class="flex items-center h-[38px]">
|
||||||
|
<ToggleSwitch bind:checked={stageEnableProxy} label={$t('projectDetail.enableProxy')} />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="mt-3 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
|
<FormField label={$t('projectDetail.cpuLimit')} name="stageCpu" type="number" bind:value={stageCpuLimit} placeholder="0" helpText={$t('projectDetail.cpuLimitHelp')} />
|
||||||
|
<FormField label={$t('projectDetail.memoryLimit')} name="stageMem" type="number" bind:value={stageMemoryLimit} placeholder="0" helpText={$t('projectDetail.memoryLimitHelp')} />
|
||||||
|
</div>
|
||||||
<div class="mt-3 flex justify-end">
|
<div class="mt-3 flex justify-end">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import { getSettings, updateSettings, listNpmCertificates, testNpmConnection } from '$lib/api';
|
import { getSettings, updateSettings, listNpmCertificates, listNpmAccessLists, testNpmConnection } from '$lib/api';
|
||||||
import type { EntityPickerItem } from '$lib/types';
|
import type { EntityPickerItem } from '$lib/types';
|
||||||
import FormField from '$lib/components/FormField.svelte';
|
import FormField from '$lib/components/FormField.svelte';
|
||||||
import ToggleSwitch from '$lib/components/ToggleSwitch.svelte';
|
import ToggleSwitch from '$lib/components/ToggleSwitch.svelte';
|
||||||
@@ -26,6 +26,12 @@
|
|||||||
let certPickerItems = $state<EntityPickerItem[]>([]);
|
let certPickerItems = $state<EntityPickerItem[]>([]);
|
||||||
let loadingCerts = $state(false);
|
let loadingCerts = $state(false);
|
||||||
|
|
||||||
|
let accessListId = $state(0);
|
||||||
|
let accessListName = $state('');
|
||||||
|
let accessListPickerOpen = $state(false);
|
||||||
|
let accessListPickerItems = $state<EntityPickerItem[]>([]);
|
||||||
|
let loadingAccessLists = $state(false);
|
||||||
|
|
||||||
function validateNpmForm(): boolean {
|
function validateNpmForm(): boolean {
|
||||||
const newErrors: Record<string, string> = {};
|
const newErrors: Record<string, string> = {};
|
||||||
if (!npmUrl.trim()) { newErrors.npmUrl = $t('validation.required', { field: 'NPM URL' }); } else { try { new URL(npmUrl.trim()); } catch { newErrors.npmUrl = $t('validation.invalidUrl'); } }
|
if (!npmUrl.trim()) { newErrors.npmUrl = $t('validation.required', { field: 'NPM URL' }); } else { try { new URL(npmUrl.trim()); } catch { newErrors.npmUrl = $t('validation.invalidUrl'); } }
|
||||||
@@ -45,7 +51,9 @@
|
|||||||
npmPassword = '';
|
npmPassword = '';
|
||||||
sslCertificateId = settings.ssl_certificate_id ?? 0;
|
sslCertificateId = settings.ssl_certificate_id ?? 0;
|
||||||
npmRemote = settings.npm_remote ?? false;
|
npmRemote = settings.npm_remote ?? false;
|
||||||
|
accessListId = settings.npm_access_list_id ?? 0;
|
||||||
if (sslCertificateId > 0) sslCertName = `Certificate #${sslCertificateId}`;
|
if (sslCertificateId > 0) sslCertName = `Certificate #${sslCertificateId}`;
|
||||||
|
if (accessListId > 0) accessListName = `Access List #${accessListId}`;
|
||||||
} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.loadFailed')); } finally { loading = false; }
|
} catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.loadFailed')); } finally { loading = false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -121,6 +129,36 @@
|
|||||||
|
|
||||||
function clearCertificate() { sslCertificateId = 0; sslCertName = ''; saveCertificate(0); }
|
function clearCertificate() { sslCertificateId = 0; sslCertName = ''; saveCertificate(0); }
|
||||||
|
|
||||||
|
async function openAccessListPicker() {
|
||||||
|
loadingAccessLists = true;
|
||||||
|
try {
|
||||||
|
const lists = await listNpmAccessLists();
|
||||||
|
if (lists.length === 0) { toasts.info($t('settingsNpm.noAccessLists')); return; }
|
||||||
|
accessListPickerItems = lists.map((al): EntityPickerItem => ({
|
||||||
|
value: String(al.id),
|
||||||
|
label: al.name || `Access List #${al.id}`,
|
||||||
|
}));
|
||||||
|
accessListPickerOpen = true;
|
||||||
|
} catch (err) {
|
||||||
|
toasts.error(err instanceof Error ? err.message : $t('settingsNpm.accessListLoadFailed'));
|
||||||
|
} finally { loadingAccessLists = false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveAccessList(id: number) {
|
||||||
|
try { await updateSettings({ npm_access_list_id: id } as any); toasts.success($t('settingsCredentials.saved')); }
|
||||||
|
catch (err) { toasts.error(err instanceof Error ? err.message : $t('settingsCredentials.saveFailed')); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleAccessListSelect(value: string) {
|
||||||
|
accessListId = parseInt(value, 10);
|
||||||
|
const item = accessListPickerItems.find((i) => i.value === value);
|
||||||
|
accessListName = item?.label ?? '';
|
||||||
|
accessListPickerOpen = false;
|
||||||
|
saveAccessList(accessListId);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearAccessList() { accessListId = 0; accessListName = ''; saveAccessList(0); }
|
||||||
|
|
||||||
async function resolveCertName() {
|
async function resolveCertName() {
|
||||||
if (sslCertificateId <= 0) return;
|
if (sslCertificateId <= 0) return;
|
||||||
try {
|
try {
|
||||||
@@ -255,6 +293,36 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Default Access List -->
|
||||||
|
<div class="rounded-xl border border-[var(--border-primary)] bg-[var(--surface-card)] p-6 shadow-[var(--shadow-sm)]">
|
||||||
|
<div class="flex items-start gap-3">
|
||||||
|
<div class="flex-1">
|
||||||
|
<h3 class="text-sm font-semibold text-[var(--text-primary)]">{$t('settingsNpm.accessList')}</h3>
|
||||||
|
<p class="mt-0.5 text-xs text-[var(--text-tertiary)]">{$t('settingsNpm.accessListHelp')}</p>
|
||||||
|
<div class="mt-3 flex items-center gap-2">
|
||||||
|
<button type="button" onclick={openAccessListPicker} disabled={loadingAccessLists}
|
||||||
|
class="inline-flex items-center gap-2 rounded-lg border border-[var(--border-primary)] px-3 py-2 text-sm text-[var(--text-secondary)] hover:bg-[var(--surface-card-hover)] transition-colors disabled:opacity-50">
|
||||||
|
<IconShield size={16} />
|
||||||
|
{#if loadingAccessLists}
|
||||||
|
{$t('common.loading')}
|
||||||
|
{:else if accessListId > 0 && accessListName}
|
||||||
|
{accessListName}
|
||||||
|
{:else}
|
||||||
|
{$t('settingsNpm.noAccessList')}
|
||||||
|
{/if}
|
||||||
|
</button>
|
||||||
|
{#if accessListId > 0}
|
||||||
|
<button type="button" onclick={clearAccessList}
|
||||||
|
class="inline-flex items-center gap-1 rounded-lg border border-[var(--border-primary)] px-2 py-2 text-sm text-[var(--text-tertiary)] hover:text-[var(--color-danger)] hover:bg-[var(--surface-card-hover)] transition-colors"
|
||||||
|
title={$t('settingsGeneral.clearCertificate')}>
|
||||||
|
<IconX size={14} />
|
||||||
|
</button>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -266,3 +334,12 @@
|
|||||||
onselect={handleCertSelect}
|
onselect={handleCertSelect}
|
||||||
onclose={() => { certPickerOpen = false; }}
|
onclose={() => { certPickerOpen = false; }}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<EntityPicker
|
||||||
|
bind:open={accessListPickerOpen}
|
||||||
|
items={accessListPickerItems}
|
||||||
|
current={String(accessListId)}
|
||||||
|
title={$t('settingsNpm.selectAccessList')}
|
||||||
|
onselect={handleAccessListSelect}
|
||||||
|
onclose={() => { accessListPickerOpen = false; }}
|
||||||
|
/>
|
||||||
|
|||||||
Reference in New Issue
Block a user