Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 24 additions & 18 deletions agent/app/dto/request/website.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,24 +211,30 @@ type WebsiteUpdateDirPermission struct {
}

type WebsiteProxyConfig struct {
ID uint `json:"id" validate:"required"`
Operate string `json:"operate" validate:"required"`
Enable bool `json:"enable" `
Cache bool `json:"cache" `
CacheTime int `json:"cacheTime"`
CacheUnit string `json:"cacheUnit"`
ServerCacheTime int `json:"serverCacheTime"`
ServerCacheUnit string `json:"serverCacheUnit"`
Name string `json:"name" validate:"required"`
Modifier string `json:"modifier"`
Match string `json:"match" validate:"required"`
ProxyPass string `json:"proxyPass" validate:"required"`
ProxyHost string `json:"proxyHost" validate:"required"`
Content string `json:"content"`
FilePath string `json:"filePath"`
Replaces map[string]string `json:"replaces"`
SNI bool `json:"sni"`
ProxySSLName string `json:"proxySSLName"`
ID uint `json:"id" validate:"required"`
Operate string `json:"operate" validate:"required"`
Enable bool `json:"enable" `
Cache bool `json:"cache" `
CacheTime int `json:"cacheTime"`
CacheUnit string `json:"cacheUnit"`
ServerCacheTime int `json:"serverCacheTime"`
ServerCacheUnit string `json:"serverCacheUnit"`
Name string `json:"name" validate:"required"`
Modifier string `json:"modifier"`
Match string `json:"match" validate:"required"`
ProxyPass string `json:"proxyPass" validate:"required"`
ProxyHost string `json:"proxyHost" validate:"required"`
Content string `json:"content"`
FilePath string `json:"filePath"`
Replaces map[string]string `json:"replaces"`
SNI bool `json:"sni"`
ProxySSLName string `json:"proxySSLName"`
Cors bool `json:"cors"`
AllowOrigins string `json:"allowOrigins"`
AllowMethods string `json:"allowMethods"`
AllowHeaders string `json:"allowHeaders"`
AllowCredentials bool `json:"allowCredentials"`
Preflight bool `json:"preflight"`
}

type WebsiteProxyReq struct {
Expand Down
37 changes: 36 additions & 1 deletion agent/app/service/website.go
Original file line number Diff line number Diff line change
Expand Up @@ -1681,7 +1681,7 @@ func (w WebsiteService) OperateProxy(req request.WebsiteProxyConfig) (err error)

switch req.Operate {
case "create":
config, err = parser.NewStringParser(string(nginx_conf.Proxy)).Parse()
config, err = parser.NewStringParser(string(nginx_conf.GetWebsiteFile("proxy.conf"))).Parse()
if err != nil {
return
}
Expand Down Expand Up @@ -1748,6 +1748,35 @@ func (w WebsiteService) OperateProxy(req request.WebsiteProxyConfig) (err error)
} else {
location.UpdateDirective("proxy_ssl_server_name", []string{"off"})
}
if req.Cors {
location.UpdateDirective("add_header", []string{"Access-Control-Allow-Origin", req.AllowOrigins, "always"})
if req.AllowMethods != "" {
location.UpdateDirective("add_header", []string{"Access-Control-Allow-Methods", req.AllowMethods, "always"})
} else {
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Methods"})
}
if req.AllowHeaders != "" {
location.UpdateDirective("add_header", []string{"Access-Control-Allow-Headers", req.AllowHeaders, "always"})
} else {
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Headers"})
}
if req.AllowCredentials {
location.UpdateDirective("add_header", []string{"Access-Control-Allow-Credentials", "true", "always"})
} else {
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Credentials"})
}
if req.Preflight {
location.AddCorsOption()
} else {
location.RemoveDirective("if", []string{"(", "$request_method", "=", "'OPTIONS'", ")"})
}
} else {
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Origin"})
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Methods"})
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Headers"})
location.RemoveDirective("add_header", []string{"Access-Control-Allow-Credentials"})
location.RemoveDirective("if", []string{"(", "$request_method", "=", "'OPTIONS'", ")"})
}
if err = nginx.WriteConfig(config, nginx.IndentedStyle); err != nil {
return buserr.WithErr("ErrUpdateBuWebsite", err)
}
Expand Down Expand Up @@ -1907,6 +1936,12 @@ func (w WebsiteService) GetProxies(id uint) (res []request.WebsiteProxyConfig, e
proxyConfig.ProxySSLName = directive.GetParameters()[0]
}
}
proxyConfig.Cors = location.Cors
proxyConfig.AllowCredentials = location.AllowCredentials
proxyConfig.AllowHeaders = location.AllowHeaders
proxyConfig.AllowOrigins = location.AllowOrigins
proxyConfig.AllowMethods = location.AllowMethods
proxyConfig.Preflight = location.Preflight
res = append(res, proxyConfig)
}
return
Expand Down
80 changes: 66 additions & 14 deletions agent/utils/nginx/components/location.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,26 @@ import (
)

type Location struct {
Modifier string
Match string
Cache bool
ProxyPass string
Host string
CacheTime int
CacheUint string
Comment string
Directives []IDirective
Line int
Parameters []string
Replaces map[string]string
ServerCacheTime int
ServerCacheUint string
Modifier string
Match string
Cache bool
ProxyPass string
Host string
CacheTime int
CacheUint string
Comment string
Directives []IDirective
Line int
Parameters []string
Replaces map[string]string
ServerCacheTime int
ServerCacheUint string
Cors bool
AllowMethods string
AllowHeaders string
AllowOrigins string
AllowCredentials bool
Preflight bool
}

func (l *Location) GetCodeBlock() string {
Expand Down Expand Up @@ -69,6 +75,9 @@ func NewLocation(directive IDirective) *Location {
}
}
}
if params[0] == "(" && params[1] == "$request_method" && params[2] == `=` && params[3] == `'OPTIONS'` && params[4] == ")" {
location.Preflight = true
}
case "proxy_cache_valid":
timeParam := params[len(params)-1]
re := regexp.MustCompile(`^(\d+)(\w+)$`)
Expand All @@ -90,6 +99,20 @@ func NewLocation(directive IDirective) *Location {
location.Replaces = make(map[string]string, 0)
}
location.Replaces[strings.Trim(params[0], "\"")] = strings.Trim(params[1], "\"")
case "add_header":
if params[0] == "Access-Control-Allow-Origin" {
location.Cors = true
location.AllowOrigins = params[1]
}
if params[0] == "Access-Control-Allow-Methods" {
location.AllowMethods = params[1]
}
if params[0] == "Access-Control-Allow-Headers" {
location.AllowHeaders = params[1]
}
if params[0] == "Access-Control-Allow-Credentials" && params[1] == "true" {
location.AllowCredentials = true
}
}
}

Expand Down Expand Up @@ -264,3 +287,32 @@ func (l *Location) RemoveSubFilter() {
l.RemoveDirective("sub_filter_types", []string{"*"})
l.Replaces = nil
}

func (l *Location) AddCorsOption() {
newDir := &Directive{
Name: "if",
Parameters: []string{"(", "$request_method", "=", "'OPTIONS'", ")"},
Block: &Block{},
}
block := &Block{}
block.AppendDirectives(&Directive{
Name: "add_header",
Parameters: []string{"Access-Control-Max-Age", "1728000"},
})
block.AppendDirectives(&Directive{
Name: "add_header",
Parameters: []string{"Content-Type", "'text/plain;charset=UTF-8'"},
})
block.AppendDirectives(&Directive{
Name: "add_header",
Parameters: []string{"Content-Length", "0"},
})
block.AppendDirectives(&Directive{
Name: "return",
Parameters: []string{"204"},
})
newDir.Block = block
directives := l.GetDirectives()
directives = append(directives, newDir)
l.Directives = directives
}
6 changes: 6 additions & 0 deletions frontend/src/api/interface/website.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,12 @@ export namespace Website {
proxyProtocol?: string;
sni?: boolean;
proxySSLName: string;
cors: boolean;
allowOrigins: string;
allowMethods: string;
allowHeaders: string;
allowCredentials: boolean;
preflight: boolean;
}

export interface ProxReplace {
Expand Down
9 changes: 9 additions & 0 deletions frontend/src/lang/modules/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2598,6 +2598,15 @@ const message = {
'If unsure, you can enter 0.0.0.0/0 (ipv4) ::/0 (ipv6) [Note: Allowing any source IP is not secure]',
http3Helper:
'HTTP/3 is an upgrade to HTTP/2, offering faster connection speeds and better performance, but not all browsers support HTTP/3. Enabling it may cause some browsers to be unable to access the site.',
cors: 'Cross-Origin Resource Sharing (CORS)',
enableCors: 'Enable CORS',
allowOrigins: 'Allowed domains',
allowMethods: 'Allowed request methods',
allowHeaders: 'Allowed request headers',
allowCredentials: 'Allow cookies to be sent',
preflight: 'Preflight request fast response',
preflightHleper:
'When enabled, when the browser sends a cross-origin preflight request (OPTIONS request), the system will automatically return a 204 status code and set the necessary cross-origin response headers',

changeDatabase: 'Change Database',
changeDatabaseHelper1: 'Database association is used for backing up and restoring the website.',
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/es-es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2575,6 +2575,16 @@ const message = {
ipFromExample2: 'Si el frontend es un CDN: rango IP del CDN',
ipFromExample3: 'En caso de duda: 0.0.0.0/0 (IPv4) ::/0 (IPv6) [Nota: poco seguro]',
http3Helper: 'HTTP/3 ofrece mayor velocidad y rendimiento, pero no todos los navegadores lo soportan.',
cors: 'Intercambio de Recursos de Origen Cruzado (CORS)',
enableCors: 'Habilitar CORS',
allowOrigins: 'Dominios permitidos',
allowMethods: 'Métodos de solicitud permitidos',
allowHeaders: 'Encabezados de solicitud permitidos',
allowCredentials: 'Permitir enviar cookies',
preflight: 'Respuesta rápida a solicitud de preflight',
preflightHleper:
'Cuando está habilitado, cuando el navegador envía una solicitud de preflight de origen cruzado (solicitud OPTIONS), el sistema devolverá automáticamente un código de estado 204 y establecerá los encabezados de respuesta de origen cruzado necesarios',

changeDatabase: 'Cambiar base de datos',
changeDatabaseHelper1: 'La asociación se usa en backups/restauraciones.',
changeDatabaseHelper2: 'Cambiar de DB invalida backups previos.',
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2514,6 +2514,16 @@ const message = {
'不明な場合は、0.0.0.0/0(IPv4)または::/0(IPv6)を入力できます。[注意:任意のソースIPを許可することは安全ではありません。]',
http3Helper:
'HTTP/3はHTTP/2のアップグレード版で、より高速な接続速度とパフォーマンスを提供します。ただし、すべてのブラウザがHTTP/3をサポートしているわけではなく、有効にすると一部のブラウザがサイトにアクセスできなくなる可能性があります。',
cors: 'クロスオリジンリソース共有(CORS)',
enableCors: 'CORSを有効にする',
allowOrigins: '許可されたドメイン',
allowMethods: '許可されたリクエストメソッド',
allowHeaders: '許可されたリクエストヘッダー',
allowCredentials: 'Cookieの送信を許可する',
preflight: 'プリフライトリクエストの高速応答',
preflightHleper:
'有効にすると、ブラウザがクロスオリジンのプリフライトリクエスト(OPTIONSリクエスト)を送信した場合、システムは自動的に204ステータスコードを返し、必要なクロスオリジン応答ヘッダーを設定します',

changeDatabase: 'データベースを切り替え',
changeDatabaseHelper1: 'データベースの関連付けは、ウェブサイトのバックアップと復元に使用されます。',
changeDatabaseHelper2: '別のデータベースに切り替えると、以前のバックアップが復元できなくなる可能性があります。',
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2471,6 +2471,16 @@ const message = {
'확실하지 않은 경우 0.0.0.0/0 (IPv4) 또는 ::/0 (IPv6)를 입력할 수 있습니다. [주의: 모든 소스 IP를 허용하는 것은 안전하지 않습니다.]',
http3Helper:
'HTTP/3는 HTTP/2의 업그레이드 버전으로, 더 빠른 연결 속도와 더 나은 성능을 제공합니다. 그러나 모든 브라우저가 HTTP/3를 지원하는 것은 아니며, 활성화하면 일부 브라우저가 사이트에 접근하지 못할 수 있습니다.',
cors: '교차 출처 리소스 공유(CORS)',
enableCors: 'CORS 활성화',
allowOrigins: '허용된 도메인',
allowMethods: '허용된 요청 메서드',
allowHeaders: '허용된 요청 헤더',
allowCredentials: '쿠키 전송 허용',
preflight: '프리플라이트 요청 빠른 응답',
preflightHleper:
'활성화하면 브라우저가 교차 출처 프리플라이트 요청(OPTIONS 요청)을 보낼 때 시스템이 자동으로 204 상태 코드를 반환하고 필요한 교차 출처 응답 헤더를 설정합니다',

changeDatabase: '데이터베이스 전환',
changeDatabaseHelper1: '데이터베이스 연관은 웹사이트 백업 및 복원에 사용됩니다.',
changeDatabaseHelper2: '다른 데이터베이스로 전환하면 이전 백업을 복원할 수 없게 될 수 있습니다.',
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/ms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2570,6 +2570,16 @@ const message = {
'Jika tidak pasti, anda boleh mengisi 0.0.0.0/0 (IPv4) atau ::/0 (IPv6). [Nota: Membenarkan sebarang sumber IP tidak selamat.]',
http3Helper:
'HTTP/3 adalah versi naik taraf HTTP/2, menyediakan kelajuan sambungan yang lebih pantas dan prestasi yang lebih baik. Walau bagaimanapun, tidak semua penyemak imbas menyokong HTTP/3, dan mengaktifkannya mungkin menyebabkan beberapa penyemak imbas tidak dapat mengakses laman web.',
cors: 'Perkongsian Sumber Asal Silang (CORS)',
enableCors: 'Dayakan CORS',
allowOrigins: 'Domain yang dibenarkan',
allowMethods: 'Kaedah permintaan yang dibenarkan',
allowHeaders: 'Pengepala permintaan yang dibenarkan',
allowCredentials: 'Benarkan kuki dihantar',
preflight: 'Tindak balas pantas permintaan preflight',
preflightHleper:
'Apabila didayakan, apabila pelayar menghantar permintaan preflight asal silang (permintaan OPTIONS), sistem akan secara automatik mengembalikan kod status 204 dan menetapkan pengepala respons asal silang yang diperlukan',

changeDatabase: 'Tukar Pangkalan Data',
changeDatabaseHelper1: 'Perkaitan pangkalan data digunakan untuk sandaran dan pemulihan laman web.',
changeDatabaseHelper2:
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/pt-br.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2575,6 +2575,16 @@ const message = {
'Se não tiver certeza, você pode preencher 0.0.0.0/0 (IPv4) ou ::/0 (IPv6). [Nota: Permitir qualquer fonte de IP não é seguro.]',
http3Helper:
'O HTTP/3 é uma versão atualizada do HTTP/2, fornecendo velocidades de conexão mais rápidas e melhor desempenho. No entanto, nem todos os navegadores suportam HTTP/3, e ativá-lo pode fazer com que alguns navegadores não consigam acessar o site.',
cors: 'Compartilhamento de Recursos de Origem Cruzada (CORS)',
enableCors: 'Habilitar CORS',
allowOrigins: 'Domínios permitidos',
allowMethods: 'Métodos de solicitação permitidos',
allowHeaders: 'Cabeçalhos de solicitação permitidos',
allowCredentials: 'Permitir envio de cookies',
preflight: 'Resposta rápida a solicitação de preflight',
preflightHleper:
'Quando habilitado, quando o navegador envia uma solicitação de preflight de origem cruzada (solicitação OPTIONS), o sistema retornará automaticamente um código de status 204 e definirá os cabeçalhos de resposta de origem cruzada necessários',

changeDatabase: 'Alterar Banco de Dados',
changeDatabaseHelper1: 'A associação do banco de dados é usada para backup e restauração do site.',
changeDatabaseHelper2: 'Alternar para outro banco de dados pode tornar backups anteriores irrecuperáveis.',
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2572,6 +2572,16 @@ const message = {
'Если вы не уверены, вы можете указать 0.0.0.0/0 (IPv4) или ::/0 (IPv6). [Примечание: Разрешение любого источника IP небезопасно.]',
http3Helper:
'HTTP/3 — это обновленная версия HTTP/2, обеспечивающая более высокую скорость соединения и лучшую производительность. Однако не все браузеры поддерживают HTTP/3, и его включение может привести к тому, что некоторые браузеры не смогут получить доступ к сайту.',
cors: 'Межсайтовый обмен ресурсами (CORS)',
enableCors: 'Включить CORS',
allowOrigins: 'Разрешенные домены',
allowMethods: 'Разрешенные методы запроса',
allowHeaders: 'Разрешенные заголовки запроса',
allowCredentials: 'Разрешить отправку cookies',
preflight: 'Быстрый ответ на предварительный запрос',
preflightHleper:
'При включении, когда браузер отправляет межсайтовый предварительный запрос (запрос OPTIONS), система автоматически вернет статус 204 и установит необходимые межсайтовые заголовки ответа',

changeDatabase: 'Сменить Базу Данных',
changeDatabaseHelper1: 'Связь базы данных используется для резервного копирования и восстановления сайта.',
changeDatabaseHelper2:
Expand Down
10 changes: 10 additions & 0 deletions frontend/src/lang/modules/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2630,6 +2630,16 @@ const message = {
'Emin değilseniz, 0.0.0.0/0 (ipv4) ::/0 (ipv6) girebilirsiniz [Not: Herhangi bir kaynak IP’ye izin vermek güvenli değildir]',
http3Helper:
'HTTP/3, HTTP/2’nin bir yükseltmesidir, daha hızlı bağlantı hızları ve daha iyi performans sunar, ancak tüm tarayıcılar HTTP/3’ü desteklemez. Etkinleştirilmesi bazı tarayıcıların siteye erişememesine neden olabilir.',
cors: 'Çapraz Kaynak Paylaşımı (CORS)',
enableCors: 'CORS etkinleştir',
allowOrigins: 'İzin verilen alan adları',
allowMethods: 'İzin verilen istek yöntemleri',
allowHeaders: 'İzin verilen istek başlıkları',
allowCredentials: 'Çerezlerin gönderilmesine izin ver',
preflight: 'Ön istek hızlı yanıtı',
preflightHleper:
'Etkinleştirildiğinde, tarayıcı çapraz kaynak ön isteği (OPTIONS isteği) gönderdiğinde, sistem otomatik olarak 204 durum kodunu döndürecek ve gerekli çapraz kaynak yanıt başlıklarını ayarlayacaktır',

changeDatabase: 'Veritabanını Değiştir',
changeDatabaseHelper1:
'Veritabanı ilişkilendirmesi, web sitesinin yedeklenmesi ve geri yüklenmesi için kullanılır.',
Expand Down
Loading
Loading