Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

fix!: harden browser auth, websocket delivery, and public defaults (#924)

Aldino Kemal56727a93b8b9
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index 906a4166..2cb38024 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -39,7 +39,7 @@ Before setting up the integration, ensure you have:
| `CHATWOOT_AUTO_CREATE` | No | `false` | Startup provisioning mode. When `true`, the app lists inboxes, reuses an API-channel inbox named `CHATWOOT_INBOX_NAME`, or creates one using `CHATWOOT_WEBHOOK_URL`; then it fills `CHATWOOT_INBOX_ID` in memory. |
| `CHATWOOT_INBOX_NAME` | No | `WhatsApp` | Inbox name used only by auto-provisioning. The app reuses a same-name `Channel::Api` inbox, but ignores same-name non-API inboxes because they cannot receive API-channel reply webhooks. |
| `CHATWOOT_WEBHOOK_URL` | Reply webhook | - | Public URL Chatwoot should call for agent replies: `https://your-gowa.example.com/chatwoot/webhook`. Used when creating an API inbox automatically, and useful as the value to place in an existing API channel's `webhook_url`. Keep the secret out of this URL when Chatwoot signs its webhooks; see [Webhook Secret](#webhook-secret). |
-| `CHATWOOT_WEBHOOK_SECRET` | Recommended | - | Secret that authenticates incoming Chatwoot webhook calls. If empty, webhooks are accepted without this check. If set, the request must carry Chatwoot's own signature (`X-Chatwoot-Signature` + `X-Chatwoot-Timestamp`, recommended) or present the secret through `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, `?secret=...`, or an `X-Hub-Signature-256` HMAC signature. |
+| `CHATWOOT_WEBHOOK_SECRET` | Recommended | - | Secret that authenticates incoming Chatwoot webhook calls. An empty effective secret rejects the call. Set `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED=true` only on a trusted network to restore unsigned delivery. When a secret is set, the request must carry Chatwoot's own signature (`X-Chatwoot-Signature` + `X-Chatwoot-Timestamp`, recommended) or present the secret through `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, `?secret=...`, or an `X-Hub-Signature-256` HMAC signature. |
| `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE` | No | `5m` | Maximum age (and clock difference) of the `X-Chatwoot-Timestamp` accepted with Chatwoot's signature. Older or further-ahead requests are rejected, which limits replay of a captured request. |
| `CHATWOOT_REOPEN_CONVERSATION` | No | `true` | When a contact has a resolved conversation and messages again, reopen/reuse that conversation instead of starting a new thread. Keeps REST and direct-DB behavior aligned. |
| `CHATWOOT_CONVERSATION_PENDING` | No | `false` | Create new conversations with status `pending` instead of `open`, so they land in the unassigned queue. Applies to REST and direct-DB paths. |
@@ -202,11 +202,11 @@ Notes:
- If `CHATWOOT_INBOX_ID` is already set, it takes precedence and auto-create is skipped (your explicit value wins).
- If `CHATWOOT_WEBHOOK_URL` is empty, the inbox is still created but **agent replies won't reach WhatsApp** until you set the webhook — a warning is logged.
- Provisioning failures are non-fatal; the app keeps running and you can fall back to manual setup.
-- Chatwoot generates the webhook secret of a new inbox, so it cannot be known before the inbox exists. After the first start, copy the secret from the created inbox into `CHATWOOT_WEBHOOK_SECRET` and restart. Until then the webhook endpoint is unauthenticated. See [Webhook Secret](#webhook-secret).
+- Chatwoot generates the webhook secret of a new inbox, so it cannot be known before the inbox exists. After the first start, copy the secret from the created inbox into `CHATWOOT_WEBHOOK_SECRET` and restart. Until then webhook calls are rejected. See [Webhook Secret](#webhook-secret).
## Webhook Secret
-`CHATWOOT_WEBHOOK_SECRET` protects GOWA's public `/chatwoot/webhook` endpoint, which sits outside basic auth so Chatwoot can reach it. When it is empty, GOWA accepts Chatwoot webhooks without this check. When it is set, a request is accepted only if it proves knowledge of the secret in one of these ways:
+`CHATWOOT_WEBHOOK_SECRET` protects GOWA's public `/chatwoot/webhook` endpoint, which sits outside basic auth so Chatwoot can reach it. When the effective secret is empty, GOWA rejects the call. Set `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED=true` only when the endpoint is reachable solely on a trusted network. When a secret is set, a request is accepted only if it proves knowledge of the secret in one of these ways:
| Method | What Chatwoot (or a proxy) sends | Notes |
|--------|----------------------------------|-------|
@@ -235,12 +235,12 @@ With [per-device configs](#per-device--multi-inbox-routing), each inbox is a dif
The secret that applies is the secret of the device the webhook is routed to, on both endpoints:
- The device has its own `webhook_secret`: the request must prove that secret. The global secret is not accepted for it, and neither is another device's secret.
-- The device has no `webhook_secret`: the global `CHATWOOT_WEBHOOK_SECRET` applies; when that is empty too, the device accepts unauthenticated webhooks.
+- The device has no `webhook_secret`: the global `CHATWOOT_WEBHOOK_SECRET` applies; when that is empty too, the call is rejected unless `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED=true`.
- No device resolves (unknown inbox, or an event GOWA ignores such as `conversation_updated`): the global secret applies. Nothing is sent for such a request either way.
This holds for the shared `/chatwoot/webhook` endpoint as well, which picks the device from the payload: nothing is sent, revoked, marked as read, or written before the request has been verified against the routed device's secret. A request signed with a device's secret is accepted there for that device's inbox, so several inboxes with different secrets can share the one URL. Events GOWA ignores are still checked against the global secret only, so prefer the per-device URL when devices have their own secrets and a global secret is also set.
-When `CHATWOOT_WEBHOOK_SECRET` is empty and at least one device has its own secret, an agent reply that resolves to no device is answered `401`, the same as a wrong secret, so the response does not show which account/inbox pairs are mapped to a protected device. Without any device secret such a request is acknowledged with `200` and dropped, as before.
+When `CHATWOOT_WEBHOOK_SECRET` is empty and at least one device has its own secret, an agent reply that resolves to no device is answered `401`, the same as a wrong secret, so the response does not show which account/inbox pairs are mapped to a protected device. Without any device secret the call is also rejected, unless `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED=true`, in which case it is acknowledged with `200` and dropped.
### Replayed requests
diff --git a/docs/webhook-payload.md b/docs/webhook-payload.md
index 9e39630a..c0ba9fa4 100644
--- a/docs/webhook-payload.md
+++ b/docs/webhook-payload.md
@@ -132,7 +132,7 @@ All webhook requests include an HMAC SHA256 signature for security verification:
- **Header**: `X-Hub-Signature-256`
- **Format**: `sha256={signature}`
- **Algorithm**: HMAC SHA256
-- **Default Secret**: `secret` (configurable via `--webhook-secret` or `WHATSAPP_WEBHOOK_SECRET`)
+- **Secret**: set `WHATSAPP_WEBHOOK_SECRET` or `--webhook-secret` to a private value. The old published default `secret` is not a signing key. When the secret is unset, the process generates a random key that changes on restart and logs a warning.
### Verification Example (Node.js)
diff --git a/readme.md b/readme.md
index ad7aadb8..a1569fd5 100644
--- a/readme.md
+++ b/readme.md
@@ -158,10 +158,12 @@ Download:
device's events (signed with the global secret, filtered by `WHATSAPP_WEBHOOK_EVENTS`) while the
device URL keeps its own secret and event filter.
- **Webhook signatures** — Webhook requests include an HMAC-SHA-256 signature in the `X-Hub-Signature-256`
- header, generated with the default key `secret`.
+ header. Set a private key with `--webhook-secret` or `WHATSAPP_WEBHOOK_SECRET`. The old published
+ default `secret` is not used. If no secret is configured, the process generates a random key and
+ logs a warning; that key changes on restart, so receivers should not rely on it.
- Change the key with:
- - `--webhook-secret="secret"`
+ Generate a stable key once, for example with `openssl rand -hex 32`, and set it with:
+ - `--webhook-secret="<generated key>"`
- **Webhook payload documentation** — For detailed schemas, security implementation, and integration examples,
see [Webhook Payload Documentation](./docs/webhook-payload.md).
- **Webhook event filtering** — Filter which events are forwarded to your webhook with:
@@ -245,10 +247,12 @@ To use environment variables:
| `APP_HOST` | Host address to bind the server | `0.0.0.0` | `APP_HOST=127.0.0.1` |
| `APP_DEBUG` | Enable debug logging | `false` | `APP_DEBUG=true` |
| `APP_OS` | OS name (device name in WhatsApp) | `GOWA` | `APP_OS=MyApp` |
-| `APP_BASIC_AUTH` | Basic authentication credentials | - | `APP_BASIC_AUTH=user1:pass1,user2:pass2` |
+| `APP_BASIC_AUTH` | Basic authentication credentials. Required for a non-loopback bind, with a username and password in every entry; loopback stays open for local dev | - | `APP_BASIC_AUTH=user1:pass1,user2:pass2` |
+| `APP_ALLOW_UNAUTHENTICATED` | Expose the API with no Basic Auth on a non-loopback bind (insecure; for reverse proxies) | `false` | `APP_ALLOW_UNAUTHENTICATED=true` |
+| `APP_TRUSTED_ORIGINS` | Extra browser origins for state-changing requests (request host and specific CORS origins are included). A reverse proxy that rewrites `Host` needs `proxy_set_header Host $host`, or `APP_TRUSTED_PROXIES` with `X-Forwarded-Host`, or the public origin listed here. App and extension origins such as `capacitor://localhost` are matched as written. `null` is never trusted: gowa-ui opened from a `file://` URL cannot make changes or open `/ws`, so serve it from gowa (the default) or from an http(s) origin listed here | - | `APP_TRUSTED_ORIGINS=https://ui.example.com` |
| `APP_BASE_PATH` | Base path for subpath deployment | - | `APP_BASE_PATH=/gowa` |
| `APP_TRUSTED_PROXIES` | Trusted proxy IP ranges for reverse proxy | - | `APP_TRUSTED_PROXIES=0.0.0.0/0` |
-| `APP_CORS_ALLOWED_ORIGINS` | Allowed CORS origins (any origin when empty) | - | `APP_CORS_ALLOWED_ORIGINS=https://ui.example.com` |
+| `APP_CORS_ALLOWED_ORIGINS` | Allowed CORS origins (any origin when empty). A wildcard (`*`, the default) does not authorize state-changing requests or `/ws`; a dashboard on a separate origin must be listed in `APP_TRUSTED_ORIGINS` or here as a specific origin | - | `APP_CORS_ALLOWED_ORIGINS=https://ui.example.com` |
| `APP_UI_ENABLED` | Serve the downloaded gowa-ui dashboard | `true` | `APP_UI_ENABLED=false` |
| `APP_UI_AUTO_UPDATE` | Download and periodically refresh the latest dashboard | `true` | `APP_UI_AUTO_UPDATE=false` |
| `APP_UI_REPO` | GitHub repository containing gowa-ui releases | `aldinokemal/gowa-ui` | `APP_UI_REPO=my-org/gowa-ui` |
@@ -270,7 +274,7 @@ To use environment variables:
| `WHATSAPP_IGNORE_STATUS_MEDIA` | Ignore downloading status media (status@broadcast) | `false` | `WHATSAPP_IGNORE_STATUS_MEDIA=true` |
| `WHATSAPP_AUTO_REJECT_CALL` | Auto-reject incoming WhatsApp calls | `false` | `WHATSAPP_AUTO_REJECT_CALL=true` |
| `WHATSAPP_WEBHOOK` | Webhook URL(s) for events (comma-separated) | - | `WHATSAPP_WEBHOOK=https://webhook.site/xxx` |
-| `WHATSAPP_WEBHOOK_SECRET` | Webhook secret for validation | `secret` | `WHATSAPP_WEBHOOK_SECRET=super-secret-key` |
+| `WHATSAPP_WEBHOOK_SECRET` | Webhook HMAC secret; generate one with `openssl rand -hex 32`. Empty or a published value (`secret`, `super-secret-key`, `your-private-key`) is replaced by a random per-process key | - | `WHATSAPP_WEBHOOK_SECRET=<generated key>` |
| `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY` | Skip TLS verification for webhooks (insecure) | `false` | `WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=true` |
| `WHATSAPP_WEBHOOK_EVENTS` | Whitelist of events to forward (comma-separated, empty = all) | - | `WHATSAPP_WEBHOOK_EVENTS=message,message.ack` |
| `WHATSAPP_WEBHOOK_IGNORE_JIDS` | JIDs/wildcards to skip when forwarding (comma-separated) | - | `[email protected]` |
@@ -296,7 +300,8 @@ To use environment variables:
| `CHATWOOT_AUTO_CREATE` | Auto-create or reuse the Chatwoot API inbox at startup | `false` | `CHATWOOT_AUTO_CREATE=true` |
| `CHATWOOT_INBOX_NAME` | Inbox name used when auto-create is enabled | `WhatsApp` | `CHATWOOT_INBOX_NAME=WhatsApp Support` |
| `CHATWOOT_WEBHOOK_URL` | Public GOWA Chatwoot reply webhook URL | - | `CHATWOOT_WEBHOOK_URL=https://api.example.com/chatwoot/webhook` |
-| `CHATWOOT_WEBHOOK_SECRET` | Secret for incoming Chatwoot webhooks (verifies Chatwoot's signature) | - | `CHATWOOT_WEBHOOK_SECRET=channel-webhook-secret` |
+| `CHATWOOT_WEBHOOK_SECRET` | Secret for incoming Chatwoot webhooks (verifies Chatwoot's signature). Empty rejects calls | - | `CHATWOOT_WEBHOOK_SECRET=channel-webhook-secret` |
+| `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED` | Accept Chatwoot webhooks when no secret is configured (insecure) | `false` | `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED=true` |
| `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE` | Maximum age of a signed Chatwoot webhook's timestamp | `5m` | `CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE=2m` |
| `CHATWOOT_REOPEN_CONVERSATION` | Reopen resolved Chatwoot conversations for returning contacts | `true` | `CHATWOOT_REOPEN_CONVERSATION=false` |
| `CHATWOOT_CONVERSATION_PENDING` | Create new Chatwoot conversations as pending | `false` | `CHATWOOT_CONVERSATION_PENDING=true` |
diff --git a/src/.env.example b/src/.env.example
index 64bf5dc6..0e372daa 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -4,6 +4,15 @@ APP_HOST=0.0.0.0
APP_DEBUG=false
APP_OS=Chrome
APP_BASIC_AUTH=user1:pass1,user2:pass2
+# Empty APP_BASIC_AUTH refuses to start when APP_HOST is not loopback (the
+# default 0.0.0.0). Loopback binds stay open for local development. Set this
+# only when a reverse proxy authenticates clients before they reach GOWA.
+APP_ALLOW_UNAUTHENTICATED=false
+# Browser origins allowed to perform state-changing requests, in addition to
+# the request's own host and any specific APP_CORS_ALLOWED_ORIGINS. A CORS
+# wildcard does not permit cross-site mutations. Example:
+# APP_TRUSTED_ORIGINS=https://ui.example.com
+APP_TRUSTED_ORIGINS=
APP_BASE_PATH=
APP_TRUSTED_PROXIES=0.0.0.0/0
# Restrict cross-origin browser access to specific origins (comma-separated); empty allows any origin
@@ -59,7 +68,11 @@ WHATSAPP_AUTO_REJECT_CALL=false
WHATSAPP_AUTO_DOWNLOAD_MEDIA=true
WHATSAPP_IGNORE_STATUS_MEDIA=false
WHATSAPP_WEBHOOK=https://webhook.site/07b69616-5943-4c7f-a8be-db4819df699e,https://webhook.site/09a38aff-d11a-4a38-a176-3f3efa0b5e8b
-WHATSAPP_WEBHOOK_SECRET=super-secret-key
+# HMAC key for X-Hub-Signature-256; generate one with `openssl rand -hex 32`.
+# The published values "secret", "super-secret-key" and "your-private-key" are
+# rejected. When this is empty, the process generates a random key that changes
+# on restart; set a stable secret before receivers verify signatures.
+WHATSAPP_WEBHOOK_SECRET=
WHATSAPP_WEBHOOK_INSECURE_SKIP_VERIFY=false
WHATSAPP_WEBHOOK_EVENTS=message,message.reaction,message.revoked,message.edited,message.ack,message.deleted,group.participants
# Comma-separated WhatsApp JIDs (or "@g.us"/"@s.whatsapp.net"/"@lid" wildcards) to skip when forwarding to the webhook.
@@ -102,7 +115,10 @@ CHATWOOT_INBOX_NAME=WhatsApp
CHATWOOT_WEBHOOK_URL=
# The API channel's webhook secret: GOWA then verifies Chatwoot's X-Chatwoot-Signature.
# Keep the secret out of CHATWOOT_WEBHOOK_URL (no ?secret=...): URLs end up in logs.
+# An empty secret rejects webhook calls. Set the next flag only for a trusted
+# local network that cannot sign requests.
CHATWOOT_WEBHOOK_SECRET=
+CHATWOOT_WEBHOOK_ALLOW_UNSIGNED=false
CHATWOOT_WEBHOOK_SIGNATURE_TOLERANCE=5m
# Conversation handling
CHATWOOT_REOPEN_CONVERSATION=true
diff --git a/src/cmd/auth_policy.go b/src/cmd/auth_policy.go
new file mode 100644
index 00000000..1f122371
--- /dev/null
+++ b/src/cmd/auth_policy.go
@@ -0,0 +1,99 @@
+package cmd
+
+import (
+ "net"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/sirupsen/logrus"
+ "github.com/spf13/viper"
+)
+
+// loadHTTPHardeningConfig applies env and .env values for settings that are
+// not wired in root.go. An explicit flag wins over the environment.
+func loadHTTPHardeningConfig() {
+ flags := rootCmd.PersistentFlags()
+ if flag := flags.Lookup("allow-unauthenticated"); flag == nil || !flag.Changed {
+ if viper.IsSet("app_allow_unauthenticated") {
+ config.AppAllowUnauthenticated = viper.GetBool("app_allow_unauthenticated")
+ }
+ }
+ if flag := flags.Lookup("chatwoot-webhook-allow-unsigned"); flag == nil || !flag.Changed {
+ if viper.IsSet("chatwoot_webhook_allow_unsigned") {
+ config.ChatwootWebhookAllowUnsigned = viper.GetBool("chatwoot_webhook_allow_unsigned")
+ }
+ }
+ if flag := flags.Lookup("trusted-origins"); flag == nil || !flag.Changed {
+ if raw := strings.TrimSpace(viper.GetString("app_trusted_origins")); raw != "" {
+ config.AppTrustedOrigins = splitComma(raw)
+ }
+ }
+}
+
+func splitComma(raw string) []string {
+ parts := strings.Split(raw, ",")
+ out := make([]string, 0, len(parts))
+ for _, part := range parts {
+ part = strings.TrimSpace(part)
+ if part != "" {
+ out = append(out, part)
+ }
+ }
+ return out
+}
+
+func ensureWebhookSigningSecret() {
+ replaced, err := config.UseEphemeralWebhookSecret()
+ if err != nil {
+ logrus.Fatalf("webhook signing secret: %v", err)
+ }
+ if !replaced {
+ return
+ }
+ logrus.Warn("WHATSAPP_WEBHOOK_SECRET is unset or still a published value (\"secret\", \"super-secret-key\" or \"your-private-key\"). Generated a random per-process signing key. It will change on restart, so set WHATSAPP_WEBHOOK_SECRET to a stable secret before receivers rely on signatures. Events stay signed; the published value is not used.")
+}
+
+func enforceAuthenticationPolicy() {
+ if basicAuthComplete(config.AppBasicAuthCredential) {
+ return
+ }
+ if config.AppAllowUnauthenticated {
+ logrus.Warn("APP_ALLOW_UNAUTHENTICATED is enabled: device administration, send, logout, webhook changes, and MCP routes are exposed without application authentication. Use this only behind a reverse proxy that authenticates clients.")
+ return
+ }
+ if isLoopbackHost(config.AppHost) {
+ logrus.Warn("APP_BASIC_AUTH is empty or has an entry with an empty username or password, and the listener is loopback (" + config.AppHost + "). The API is unauthenticated for local development. Do not publish this listener. A non-loopback bind requires APP_BASIC_AUTH or APP_ALLOW_UNAUTHENTICATED=true.")
+ return
+ }
+ logrus.Fatalf("APP_BASIC_AUTH is empty or has an entry with an empty username or password, and APP_HOST %q is not a loopback address. Refusing to expose device administration, send, logout, and webhook routes. Set APP_BASIC_AUTH, bind 127.0.0.1, or set APP_ALLOW_UNAUTHENTICATED=true when a reverse proxy performs authentication.", config.AppHost)
+}
+
+// basicAuthComplete reports whether APP_BASIC_AUTH protects the API: it has
+// at least one entry, and every entry has a username and a password. An entry
+// such as "admin:" would admit anyone who knows the username.
+func basicAuthComplete(credentials []string) bool {
+ for _, credential := range credentials {
+ user, password, ok := strings.Cut(credential, ":")
+ if !ok || user == "" || password == "" {
+ return false
+ }
+ }
+ return len(credentials) > 0
+}
+
+// unauthenticatedBindAllowed reports whether an empty credential list may
+// expose the API. Loopback binds stay open for local development. Any other
+// bind requires credentials or the explicit insecure switch.
+func unauthenticatedBindAllowed(host string, hasCredentials, allowInsecure bool) bool {
+ return hasCredentials || allowInsecure || isLoopbackHost(host)
+}
+
+func isLoopbackHost(host string) bool {
+ host = strings.TrimSpace(host)
+ host = strings.Trim(host, "[]")
+ if strings.EqualFold(host, "localhost") {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
diff --git a/src/cmd/auth_policy_test.go b/src/cmd/auth_policy_test.go
new file mode 100644
index 00000000..0e6d9b42
--- /dev/null
+++ b/src/cmd/auth_policy_test.go
@@ -0,0 +1,51 @@
+package cmd
+
+import "testing"
+
+func TestBasicAuthComplete(t *testing.T) {
+ for _, tt := range []struct {
+ credentials []string
+ want bool
+ }{
+ {nil, false},
+ {[]string{"admin:secret"}, true},
+ {[]string{"admin:secret", "guest:pass"}, true},
+ {[]string{"admin:"}, false},
+ {[]string{":secret"}, false},
+ {[]string{"admin"}, false},
+ {[]string{"admin:secret", "guest:"}, false},
+ } {
+ if got := basicAuthComplete(tt.credentials); got != tt.want {
+ t.Errorf("basicAuthComplete(%q) = %v, want %v", tt.credentials, got, tt.want)
+ }
+ }
+}
+
+func TestUnauthenticatedBindAllowed(t *testing.T) {
+ cases := []struct {
+ name string
+ host string
+ hasCredentials bool
+ allowInsecure bool
+ wantAllowed bool
+ }{
+ {name: "credentials on a public bind", host: "0.0.0.0", hasCredentials: true, wantAllowed: true},
+ {name: "loopback without credentials", host: "127.0.0.1", wantAllowed: true},
+ {name: "localhost without credentials", host: "localhost", wantAllowed: true},
+ {name: "ipv6 loopback without credentials", host: "::1", wantAllowed: true},
+ {name: "bracketed ipv6 loopback", host: "[::1]", wantAllowed: true},
+ {name: "all interfaces without credentials", host: "0.0.0.0", wantAllowed: false},
+ {name: "public address without credentials", host: "192.0.2.10", wantAllowed: false},
+ {name: "unspecified ipv6 without credentials", host: "::", wantAllowed: false},
+ {name: "empty host without credentials", host: "", wantAllowed: false},
+ {name: "public bind with explicit insecure switch", host: "0.0.0.0", allowInsecure: true, wantAllowed: true},
+ }
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ got := unauthenticatedBindAllowed(tt.host, tt.hasCredentials, tt.allowInsecure)
+ if got != tt.wantAllowed {
+ t.Fatalf("unauthenticatedBindAllowed(%q, creds=%v, allow=%v) = %v, want %v", tt.host, tt.hasCredentials, tt.allowInsecure, got, tt.wantAllowed)
+ }
+ })
+ }
+}
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 8510ca56..6f95908c 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -26,7 +26,6 @@ import (
"github.com/gofiber/fiber/v3/middleware/basicauth"
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/gofiber/fiber/v3/middleware/logger"
- "github.com/gofiber/fiber/v3/middleware/static"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
@@ -41,10 +40,31 @@ var restCmd = &cobra.Command{
func init() {
rootCmd.AddCommand(restCmd)
+ rootCmd.PersistentFlags().BoolVar(
+ &config.AppAllowUnauthenticated,
+ "allow-unauthenticated",
+ config.AppAllowUnauthenticated,
+ "expose the API without Basic Auth on a non-loopback bind (INSECURE). Use only behind a reverse proxy that authenticates clients",
+ )
+ rootCmd.PersistentFlags().StringSliceVar(
+ &config.AppTrustedOrigins,
+ "trusted-origins",
+ config.AppTrustedOrigins,
+ "extra browser origins allowed to perform state-changing requests, alongside the request host and APP_CORS_ALLOWED_ORIGINS",
+ )
+ rootCmd.PersistentFlags().BoolVar(
+ &config.ChatwootWebhookAllowUnsigned,
+ "chatwoot-webhook-allow-unsigned",
+ config.ChatwootWebhookAllowUnsigned,
+ "accept Chatwoot webhooks when no webhook secret is configured (INSECURE)",
+ )
}
func restServer(_ *cobra.Command, _ []string) {
// registerMcpOAuth depends on these values being loaded after flag parsing.
loadMcpOAuthEnvConfig()
+ loadHTTPHardeningConfig()
+ ensureWebhookSigningSecret()
+ enforceAuthenticationPolicy()
fiberConfig := fiber.Config{
TrustProxy: true,
BodyLimit: int(config.WhatsappSettingMaxVideoSize),
@@ -62,7 +82,7 @@ func restServer(_ *cobra.Command, _ []string) {
// fetch media under /statics and authenticate with the headers below.
app.Use(newCORSMiddleware())
- app.Use(config.AppBasePath+"/statics", static.New("./statics"))
+ registerStoredStatic(app)
app.Use(middleware.Recovery())
app.Use(middleware.RequestTimeout(middleware.DefaultRequestTimeout))
@@ -83,15 +103,19 @@ func restServer(_ *cobra.Command, _ []string) {
return c.Status(http.StatusServiceUnavailable).SendString("Service Unavailable")
})
- // Chatwoot webhook - registered BEFORE basic auth middleware
- // This allows Chatwoot to send webhooks without authentication. The handler
- // is stateless and shared with the authenticated sync routes registered below.
+ // Chatwoot webhook - registered BEFORE basic auth middleware so Chatwoot can
+ // reach it. The handler rejects an empty effective secret unless
+ // CHATWOOT_WEBHOOK_ALLOW_UNSIGNED is set. It is shared with the
+ // authenticated sync routes registered below.
var chatwootHandler *rest.ChatwootHandler
if config.ChatwootEnabled {
// Auto-provision the inbox, install the per-device client registry, then
// start the retry worker (registry before worker — see initChatwootForwarding).
initChatwootForwarding(chatStorageRepo)
+ if config.ChatwootWebhookAllowUnsigned {
+ logrus.Warn("CHATWOOT_WEBHOOK_ALLOW_UNSIGNED is enabled: Chatwoot webhooks are accepted when the effective secret is empty. Leave this off unless the endpoint is only reachable on a trusted network.")
+ }
chatwootHandler = rest.NewChatwootHandler(appUsecase, sendUsecase, messageUsecase, dm, chatStorageRepo)
webhookPath := "/chatwoot/webhook"
if config.AppBasePath != "" {
@@ -138,6 +162,12 @@ func restServer(_ *cobra.Command, _ []string) {
app.Use(newBasicAuthMiddleware(account))
}
+ // State-changing browser requests must come from a trusted origin. Routes
+ // registered above (health, stored files, Chatwoot webhooks, OAuth) are
+ // unchanged. Non-browser clients that send no Origin or Referer are still
+ // accepted.
+ app.Use(middleware.BrowserOriginGuard())
+
// Create base path group or use app directly
var apiGroup fiber.Router = app
if config.AppBasePath != "" {
diff --git a/src/cmd/root.go b/src/cmd/root.go
index 40e6a557..09ef3529 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -463,7 +463,7 @@ func initFlags() {
&config.WhatsappWebhookSecret,
"webhook-secret", "",
config.WhatsappWebhookSecret,
- `secure webhook request --webhook-secret <string> | example: --webhook-secret="super-secret-key"`,
+ `secure webhook request --webhook-secret <string> | example: --webhook-secret="<output of openssl rand -hex 32>"`,
)
rootCmd.PersistentFlags().BoolVarP(
&config.WhatsappWebhookInsecureSkipVerify,
diff --git a/src/cmd/stored_static.go b/src/cmd/stored_static.go
new file mode 100644
index 00000000..c448337c
--- /dev/null
+++ b/src/cmd/stored_static.go
@@ -0,0 +1,162 @@
+package cmd
+
+import (
+ "io"
+ "mime"
+ "net/http"
+ "net/url"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "unicode"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/gofiber/fiber/v3"
+)
+
+// storedStaticRoot is the directory published at {AppBasePath}/statics.
+// Tests point it at a temporary directory.
+var storedStaticRoot = "statics"
+
+// registerStoredStatic serves files under /statics. The embedded dashboard
+// HTML is registered separately at "/" and is not read from this tree.
+// User-supplied message documents are attachments with a non-active content
+// type. JPEG, PNG, GIF, and WebP are inline only on the image paths the
+// dashboard and QR screen use, and only when the bytes sniff as that image.
+func registerStoredStatic(app *fiber.App) {
+ prefix := storedStaticPrefix()
+ app.Use(prefix, serveStoredStatic)
+}
+
+func storedStaticPrefix() string {
+ base := strings.TrimRight(strings.TrimSpace(config.AppBasePath), "/")
+ return base + "/statics"
+}
+
+func serveStoredStatic(c fiber.Ctx) error {
+ if c.Method() != fiber.MethodGet && c.Method() != fiber.MethodHead {
+ return c.SendStatus(fiber.StatusMethodNotAllowed)
+ }
+ rel, ok := storedStaticRelative(c.Path())
+ if !ok {
+ return c.SendStatus(fiber.StatusNotFound)
+ }
+ root, err := filepath.Abs(storedStaticRoot)
+ if err != nil {
+ return c.SendStatus(fiber.StatusNotFound)
+ }
+ full := filepath.Join(root, filepath.FromSlash(rel))
+ full, err = filepath.Abs(full)
+ if err != nil || (full != root && !strings.HasPrefix(full, root+string(os.PathSeparator))) {
+ return c.SendStatus(fiber.StatusNotFound)
+ }
+ info, err := os.Stat(full)
+ if err != nil || info.IsDir() {
+ return c.SendStatus(fiber.StatusNotFound)
+ }
+ c.Set(fiber.HeaderLastModified, info.ModTime().UTC().Format(http.TimeFormat))
+ if c.Fresh() {
+ return c.SendStatus(fiber.StatusNotModified)
+ }
+ file, err := os.Open(full)
+ if err != nil {
+ return c.SendStatus(fiber.StatusNotFound)
+ }
+
+ header := make([]byte, 512)
+ n, readErr := io.ReadFull(file, header)
+ if readErr != nil && readErr != io.ErrUnexpectedEOF && readErr != io.EOF {
+ _ = file.Close()
+ return c.SendStatus(fiber.StatusInternalServerError)
+ }
+ if _, err := file.Seek(0, io.SeekStart); err != nil {
+ _ = file.Close()
+ return c.SendStatus(fiber.StatusInternalServerError)
+ }
+
+ c.Set(fiber.HeaderXContentTypeOptions, "nosniff")
+ if imageType, inline := inlineImageType(rel, header[:n]); inline {
+ c.Set(fiber.HeaderContentType, imageType)
+ c.Set(fiber.HeaderContentDisposition, "inline")
+ } else {
+ // Never let a stored document execute as this origin. HTML, SVG,
+ // scripts, and unrecognized bytes are downloads.
+ c.Set(fiber.HeaderContentType, "application/octet-stream")
+ c.Set(fiber.HeaderContentDisposition, attachmentDisposition(info.Name()))
+ }
+ // fasthttp closes the stream after writing the response. A HEAD response
+ // keeps the Content-Length and skips the body.
+ return c.SendStream(file, int(info.Size()))
+}
+
+func storedStaticRelative(requestPath string) (string, bool) {
+ prefix := storedStaticPrefix()
+ if requestPath != prefix && !strings.HasPrefix(requestPath, prefix+"/") {
+ return "", false
+ }
+ rel := strings.TrimPrefix(requestPath, prefix)
+ rel = strings.TrimPrefix(rel, "/")
+ // c.Path() is the raw request path, and stored file URLs escape each
+ // segment. Decode first so the traversal and backslash checks below see
+ // the real name.
+ rel, err := url.PathUnescape(rel)
+ if err != nil || strings.ContainsRune(rel, 0) {
+ return "", false
+ }
+ if rel == "" || rel == "." {
+ return "", false
+ }
+ cleaned := path.Clean("/" + rel)
+ cleaned = strings.TrimPrefix(cleaned, "/")
+ if cleaned == "" || cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") || strings.Contains(cleaned, "\\") {
+ return "", false
+ }
+ return cleaned, true
+}
+
+func inlineImageType(rel string, sniffed []byte) (string, bool) {
+ if !isImagePreviewPath(rel) {
+ return "", false
+ }
+ mediaType := sniffedMediaType(sniffed)
+ switch mediaType {
+ case "image/jpeg", "image/png", "image/gif", "image/webp":
+ return mediaType, true
+ default:
+ return "", false
+ }
+}
+
+func isImagePreviewPath(rel string) bool {
+ rel = strings.ToLower(strings.Trim(rel, "/"))
+ return rel == "qrcode" || strings.HasPrefix(rel, "qrcode/") ||
+ strings.HasPrefix(rel, "media/") ||
+ strings.HasPrefix(rel, "senditems/")
+}
+
+func sniffedMediaType(sniffed []byte) string {
+ detected := http.DetectContentType(sniffed)
+ mediaType, _, err := mime.ParseMediaType(detected)
+ if err != nil {
+ return ""
+ }
+ return strings.ToLower(mediaType)
+}
+
+func attachmentDisposition(name string) string {
+ cleaned := strings.Map(func(r rune) rune {
+ if r < 32 || r == '"' || r == '\\' || r == '/' {
+ return -1
+ }
+ return r
+ }, name)
+ if cleaned == "" {
+ cleaned = "download"
+ }
+ disposition := `attachment; filename="` + cleaned + `"`
+ if strings.ContainsFunc(cleaned, func(r rune) bool { return r > unicode.MaxASCII }) {
+ disposition += `; filename*=UTF-8''` + url.PathEscape(cleaned)
+ }
+ return disposition
+}
diff --git a/src/cmd/stored_static_test.go b/src/cmd/stored_static_test.go
new file mode 100644
index 00000000..12bb14f3
--- /dev/null
+++ b/src/cmd/stored_static_test.go
@@ -0,0 +1,161 @@
+package cmd
+
+import (
+ "io"
+ "net/http/httptest"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strconv"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/require"
+)
+
+func TestStoredDocumentsAreAttachmentsAndUIStillServesHTML(t *testing.T) {
+ root := t.TempDir()
+ prevRoot := storedStaticRoot
+ prevUI := config.AppUIEnabled
+ prevUpdate := config.AppUIAutoUpdate
+ prevBase := config.AppBasePath
+ prevCache := config.PathUICache
+ storedStaticRoot = root
+ config.AppUIEnabled = true
+ config.AppUIAutoUpdate = false
+ config.AppBasePath = ""
+ config.PathUICache = t.TempDir()
+ t.Cleanup(func() {
+ storedStaticRoot = prevRoot
+ config.AppUIEnabled = prevUI
+ config.AppUIAutoUpdate = prevUpdate
+ config.AppBasePath = prevBase
+ config.PathUICache = prevCache
+ })
+
+ htmlBody := []byte("<!DOCTYPE html><html><script>alert(1)</script></html>")
+ require.NoError(t, os.MkdirAll(filepath.Join(root, "media"), 0o755))
+ require.NoError(t, os.MkdirAll(filepath.Join(root, "qrcode"), 0o755))
+ require.NoError(t, os.WriteFile(filepath.Join(root, "media", "note.html"), htmlBody, 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(root, "media", "photo.png.html"), htmlBody, 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(root, "media", "icon.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"></svg>`), 0o644))
+ png := []byte{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D}
+ require.NoError(t, os.WriteFile(filepath.Join(root, "qrcode", "scan.png"), png, 0o644))
+ require.NoError(t, os.WriteFile(filepath.Join(root, "media", "pic.png"), png, 0o644))
+
+ app := fiber.New()
+ registerStoredStatic(app)
+ registerUIRoute(app, t.Context())
+
+ htmlResp := mustGet(t, app, "/statics/media/note.html")
+ require.Equal(t, fiber.StatusOK, htmlResp.StatusCode)
+ require.Equal(t, "application/octet-stream", htmlResp.Header.Get(fiber.HeaderContentType))
+ require.Contains(t, htmlResp.Header.Get(fiber.HeaderContentDisposition), "attachment")
+ require.Equal(t, "nosniff", htmlResp.Header.Get(fiber.HeaderXContentTypeOptions))
+ require.NotContains(t, htmlResp.Header.Get(fiber.HeaderContentType), "text/html")
+
+ disguised := mustGet(t, app, "/statics/media/photo.png.html")
+ require.Equal(t, "application/octet-stream", disguised.Header.Get(fiber.HeaderContentType))
+ require.Contains(t, disguised.Header.Get(fiber.HeaderContentDisposition), "attachment")
+
+ svgResp := mustGet(t, app, "/statics/media/icon.svg")
+ require.Equal(t, "application/octet-stream", svgResp.Header.Get(fiber.HeaderContentType))
+ require.Contains(t, svgResp.Header.Get(fiber.HeaderContentDisposition), "attachment")
+
+ qrResp := mustGet(t, app, "/statics/qrcode/scan.png")
+ require.Equal(t, fiber.StatusOK, qrResp.StatusCode)
+ require.Equal(t, "image/png", qrResp.Header.Get(fiber.HeaderContentType))
+ require.Equal(t, "inline", qrResp.Header.Get(fiber.HeaderContentDisposition))
+ require.Equal(t, "nosniff", qrResp.Header.Get(fiber.HeaderXContentTypeOptions))
+
+ imageResp := mustGet(t, app, "/statics/media/pic.png")
+ require.Equal(t, "image/png", imageResp.Header.Get(fiber.HeaderContentType))
+ require.Equal(t, "inline", imageResp.Header.Get(fiber.HeaderContentDisposition))
+
+ uiResp := mustGet(t, app, "/")
+ require.Equal(t, fiber.StatusOK, uiResp.StatusCode)
+ require.Contains(t, uiResp.Header.Get(fiber.HeaderContentType), "text/html")
+ uiBody, err := io.ReadAll(uiResp.Body)
+ require.NoError(t, err)
+ require.Contains(t, string(uiBody), "gowa")
+ require.Contains(t, string(uiBody), "dashboard has not been downloaded yet")
+}
+
+func TestStoredStaticEscapedNamesAndConditionalRequests(t *testing.T) {
+ base := t.TempDir()
+ root := filepath.Join(base, "statics")
+ prevRoot := storedStaticRoot
+ prevBase := config.AppBasePath
+ storedStaticRoot = root
+ config.AppBasePath = ""
+ t.Cleanup(func() {
+ storedStaticRoot = prevRoot
+ config.AppBasePath = prevBase
+ })
+
+ pdf := []byte("%PDF-1.4\n%gowa\n")
+ names := []string{"1700-uuid.final draft", "отчёт.pdf", "v1#2.pdf"}
+ require.NoError(t, os.MkdirAll(filepath.Join(root, "media"), 0o755))
+ for _, name := range names {
+ require.NoError(t, os.WriteFile(filepath.Join(root, "media", name), pdf, 0o644))
+ }
+ require.NoError(t, os.MkdirAll(filepath.Join(base, "storages"), 0o755))
+ require.NoError(t, os.WriteFile(filepath.Join(base, "storages", "whatsapp.db"), []byte("secret"), 0o644))
+
+ app := fiber.New()
+ registerStoredStatic(app)
+
+ // Stored file URLs escape each path segment.
+ for _, name := range names {
+ resp := mustGet(t, app, "/statics/media/"+url.PathEscape(name))
+ require.Equal(t, fiber.StatusOK, resp.StatusCode, name)
+ body, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ require.Equal(t, pdf, body)
+ }
+ unicodeResp := mustGet(t, app, "/statics/media/"+url.PathEscape("отчёт.pdf"))
+ require.Contains(t, unicodeResp.Header.Get(fiber.HeaderContentDisposition), "filename*=UTF-8''"+url.PathEscape("отчёт.pdf"))
+
+ head, err := app.Test(httptest.NewRequest(fiber.MethodHead, "/statics/media/v1%232.pdf", nil))
+ require.NoError(t, err)
+ require.NoError(t, head.Body.Close())
+ require.Equal(t, fiber.StatusOK, head.StatusCode)
+ require.Equal(t, strconv.Itoa(len(pdf)), head.Header.Get(fiber.HeaderContentLength))
+ lastModified := head.Header.Get(fiber.HeaderLastModified)
+ require.NotEmpty(t, lastModified)
+
+ conditional := httptest.NewRequest(fiber.MethodGet, "/statics/media/v1%232.pdf", nil)
+ conditional.Header.Set(fiber.HeaderIfModifiedSince, lastModified)
+ cached, err := app.Test(conditional)
+ require.NoError(t, err)
+ require.NoError(t, cached.Body.Close())
+ require.Equal(t, fiber.StatusNotModified, cached.StatusCode)
+
+ for _, target := range []string{
+ "/statics/%2e%2e/storages/whatsapp.db",
+ "/statics/..%2fstorages%2fwhatsapp.db",
+ "/statics/media/..%2f..%2fstorages/whatsapp.db",
+ "/statics/%252e%252e/storages/whatsapp.db",
+ "/statics/media/v1%232.pdf%00.png",
+ "/statics/media%5c..%5c..%5cstorages%5cwhatsapp.db",
+ } {
+ require.Equal(t, fiber.StatusNotFound, mustGet(t, app, target).StatusCode, target)
+ }
+ _, ok := storedStaticRelative("/statics/media/%zz")
+ require.False(t, ok)
+}
+
+func mustGet(t *testing.T, app *fiber.App, path string) *httpResponse {
+ t.Helper()
+ resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, nil))
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = resp.Body.Close() })
+ return &httpResponse{resp.StatusCode, resp.Header, resp.Body}
+}
+
+type httpResponse struct {
+ StatusCode int
+ Header interface{ Get(string) string }
+ Body io.ReadCloser
+}
diff --git a/src/config/origin.go b/src/config/origin.go
new file mode 100644
index 00000000..0fa4256f
--- /dev/null
+++ b/src/config/origin.go
@@ -0,0 +1,116 @@
+package config
+
+import (
+ "net/url"
+ "strings"
+)
+
+// BrowserSourceAllowed reports whether a browser-supplied source is trusted.
+// A request with no Origin and no Referer is treated as a non-browser client
+// unless Sec-Fetch-Site marks it as a same-site or cross-site browser request.
+// host is the request's own public host, including a non-default port.
+func BrowserSourceAllowed(host, origin, referer, fetchSite string) bool {
+ origin = strings.TrimSpace(origin)
+ referer = strings.TrimSpace(referer)
+ fetchSite = strings.ToLower(strings.TrimSpace(fetchSite))
+ if origin == "" && referer == "" {
+ return fetchSite == "" || fetchSite == "same-origin" || fetchSite == "none"
+ }
+ if origin != "" && !OriginAllowed(host, origin) {
+ return false
+ }
+ if referer != "" && !refererAllowed(host, referer) {
+ return false
+ }
+ return true
+}
+
+// OriginAllowed reports whether origin matches the request host or a
+// configured trusted origin. The literal "null" origin is never trusted.
+func OriginAllowed(host, origin string) bool {
+ normalized := NormalizeOrigin(origin)
+ if normalized == "" {
+ return false
+ }
+ for _, allowed := range TrustedBrowserOrigins(host) {
+ if strings.EqualFold(normalized, allowed) {
+ return true
+ }
+ }
+ return false
+}
+
+// TrustedBrowserOrigins is the allowlist shared by the HTTP guard and the
+// WebSocket upgrader. It includes the request's own host (the embedded
+// dashboard), APP_TRUSTED_ORIGINS, specific CORS origins, and the public app
+// URLs already configured for OAuth and Chatwoot. A CORS wildcard is not
+// trusted.
+func TrustedBrowserOrigins(host string) []string {
+ seen := make(map[string]struct{})
+ var out []string
+ add := func(raw string) {
+ normalized := NormalizeOrigin(raw)
+ if normalized == "" {
+ return
+ }
+ if _, ok := seen[normalized]; ok {
+ return
+ }
+ seen[normalized] = struct{}{}
+ out = append(out, normalized)
+ }
+ // The request's own host is trusted under either scheme, like Go's
+ // CrossOriginProtection: a TLS-terminating proxy forwards https traffic
+ // over plain http.
+ host = strings.TrimSpace(host)
+ add("https://" + host)
+ add("http://" + host)
+ for _, raw := range AppTrustedOrigins {
+ add(raw)
+ }
+ for _, raw := range AppCORSAllowedOrigins {
+ add(raw)
+ }
+ add(McpOAuthIssuerURL)
+ add(ChatwootWebhookURL)
+ return out
+}
+
+// NormalizeOrigin returns scheme://host[:port] for an http(s) URL or origin.
+// Default ports are omitted. An app or extension origin such as
+// capacitor://localhost is kept as written, lower-cased and without a
+// trailing slash. An empty string means the value is not a usable origin.
+func NormalizeOrigin(raw string) string {
+ raw = strings.TrimSpace(raw)
+ if raw == "" || raw == "*" || strings.EqualFold(raw, "null") {
+ return ""
+ }
+ parsed, err := url.Parse(raw)
+ if err != nil || parsed.Host == "" {
+ return ""
+ }
+ scheme := strings.ToLower(parsed.Scheme)
+ if scheme != "http" && scheme != "https" {
+ return strings.TrimRight(strings.ToLower(raw), "/")
+ }
+ host := strings.ToLower(parsed.Hostname())
+ if host == "" {
+ return ""
+ }
+ if strings.Contains(host, ":") {
+ host = "[" + host + "]"
+ }
+ port := parsed.Port()
+ if port == "" || (scheme == "http" && port == "80") || (scheme == "https" && port == "443") {
+ return scheme + "://" + host
+ }
+ return scheme + "://" + host + ":" + port
+}
+
+func refererAllowed(host, referer string) bool {
+ parsed, err := url.Parse(referer)
+ if err != nil || parsed.Scheme == "" || parsed.Host == "" {
+ return false
+ }
+ return OriginAllowed(host, parsed.Scheme+"://"+parsed.Host)
+}
diff --git a/src/config/settings.go b/src/config/settings.go
index ef7e6fb4..377eb0da 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -14,9 +14,19 @@ var (
AppOs = "GOWA"
AppPlatform = waCompanionReg.DeviceProps_PlatformType(1)
AppBasicAuthCredential []string
- AppBasePath = ""
- AppTrustedProxies []string // Trusted proxy IP ranges (e.g., "0.0.0.0/0" for all, or specific CIDRs)
- AppCORSAllowedOrigins []string // CORS allowed origins; empty means "*" (any origin)
+ // AppAllowUnauthenticated exposes device admin, send, logout, and MCP
+ // routes without Basic Auth. It is required when credentials are empty and
+ // AppHost is not a loopback address (the default 0.0.0.0). Loopback binds
+ // stay open for local development. Intended for a reverse proxy that
+ // authenticates in front of this process.
+ AppAllowUnauthenticated = false
+ // AppTrustedOrigins lists browser origins allowed to call state-changing
+ // routes, in addition to the request's own host and any specific
+ // AppCORSAllowedOrigins. A CORS wildcard does not allow cross-site mutations.
+ AppTrustedOrigins []string
+ AppBasePath = ""
+ AppTrustedProxies []string // Trusted proxy IP ranges (e.g., "0.0.0.0/0" for all, or specific CIDRs)
+ AppCORSAllowedOrigins []string // CORS allowed origins; empty means "*" (any origin)
// Web UI (gowa-ui) runtime download settings. The dashboard is a separate
// project released as a single HTML file; gowa fetches the latest release
@@ -42,12 +52,15 @@ var (
DBURI = "file:storages/whatsapp.db"
DBKeysURI = ""
- WhatsappAutoReplyMessage string
- WhatsappAutoMarkRead = false // Auto-mark incoming messages as read
- WhatsappAutoDownloadMedia = true // Auto-download media from incoming messages
- WhatsappIgnoreStatusMedia = false // Ignore downloading status media
- WhatsappWebhook []string
- WhatsappWebhookSecret = "secret"
+ WhatsappAutoReplyMessage string
+ WhatsappAutoMarkRead = false // Auto-mark incoming messages as read
+ WhatsappAutoDownloadMedia = true // Auto-download media from incoming messages
+ WhatsappIgnoreStatusMedia = false // Ignore downloading status media
+ WhatsappWebhook []string
+ // WhatsappWebhookSecret signs outbound webhooks. Empty, and the published
+ // default "secret", are replaced at startup with a random per-process key
+ // so receivers are not asked to trust a key that ships in the documentation.
+ WhatsappWebhookSecret = ""
WhatsappWebhookInsecureSkipVerify = false // Skip TLS certificate verification for webhooks (insecure)
WhatsappWebhookEvents []string // Whitelist of events to forward to webhook (empty = all events)
WhatsappWebhookIgnoreJids []string // JIDs (or "@g.us"/"@s.whatsapp.net"/"@lid" wildcards) to skip when forwarding to webhooks
@@ -122,9 +135,11 @@ var (
ChatwootAutoCreate = false
ChatwootInboxName = "WhatsApp"
ChatwootWebhookURL = ""
- // Optional shared secret for incoming Chatwoot webhooks. When empty, inbound
- // webhook requests remain unauthenticated for backward compatibility.
- ChatwootWebhookSecret = ""
+ // Optional shared secret for incoming Chatwoot webhooks. An empty effective
+ // secret rejects the request. ChatwootWebhookAllowUnsigned restores the
+ // previous open behavior and must be set explicitly.
+ ChatwootWebhookSecret = ""
+ ChatwootWebhookAllowUnsigned = false
// ChatwootWebhookSignatureTolerance bounds the age (and clock skew) of the
// X-Chatwoot-Timestamp accepted with Chatwoot's signed webhooks, which
// limits how long a captured request can be replayed.
diff --git a/src/config/webhook_secret.go b/src/config/webhook_secret.go
new file mode 100644
index 00000000..788695bb
--- /dev/null
+++ b/src/config/webhook_secret.go
@@ -0,0 +1,46 @@
+package config
+
+import (
+ "crypto/rand"
+ "encoding/hex"
+ "strings"
+)
+
+// PublishedWhatsappWebhookSecret is the historical default documented in
+// older releases. Receivers that still use it cannot tell a real delivery
+// from a forged body, so it is never used as an HMAC key.
+const PublishedWhatsappWebhookSecret = "secret"
+
+// PublishedExampleWebhookSecret is the example key older .env.example files
+// shipped. It is public for the same reason and is never used as an HMAC key.
+const PublishedExampleWebhookSecret = "super-secret-key"
+
+// PublishedPlaceholderWebhookSecret is a placeholder the README once showed.
+// It is public for the same reason and is never used as an HMAC key.
+const PublishedPlaceholderWebhookSecret = "your-private-key"
+
+// WebhookSecretUnusable reports whether secret is empty or a published
+// value. Callers must not sign webhook bodies with those values.
+func WebhookSecretUnusable(secret string) bool {
+ switch strings.TrimSpace(secret) {
+ case "", PublishedWhatsappWebhookSecret, PublishedExampleWebhookSecret, PublishedPlaceholderWebhookSecret:
+ return true
+ default:
+ return false
+ }
+}
+
+// UseEphemeralWebhookSecret replaces an unusable WhatsappWebhookSecret with
+// a random per-process key. A configured secret is left unchanged. The
+// replacement is not persisted and changes the next time the process starts.
+func UseEphemeralWebhookSecret() (replaced bool, err error) {
+ if !WebhookSecretUnusable(WhatsappWebhookSecret) {
+ return false, nil
+ }
+ buf := make([]byte, 32)
+ if _, err = rand.Read(buf); err != nil {
+ return false, err
+ }
+ WhatsappWebhookSecret = hex.EncodeToString(buf)
+ return true, nil
+}
diff --git a/src/config/webhook_secret_test.go b/src/config/webhook_secret_test.go
new file mode 100644
index 00000000..89a38280
--- /dev/null
+++ b/src/config/webhook_secret_test.go
@@ -0,0 +1,49 @@
+package config
+
+import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/hex"
+ "testing"
+
+ "github.com/stretchr/testify/require"
+)
+
+func digest(body, key []byte) string {
+ mac := hmac.New(sha256.New, key)
+ _, _ = mac.Write(body)
+ return hex.EncodeToString(mac.Sum(nil))
+}
+
+func TestWebhookHMACIsNotThePublishedDefault(t *testing.T) {
+ prev := WhatsappWebhookSecret
+ t.Cleanup(func() { WhatsappWebhookSecret = prev })
+
+ for _, configured := range []string{"", "secret", " secret ", "super-secret-key", " super-secret-key ", "your-private-key"} {
+ WhatsappWebhookSecret = configured
+ replaced, err := UseEphemeralWebhookSecret()
+ require.NoError(t, err)
+ require.True(t, replaced)
+ require.False(t, WebhookSecretUnusable(WhatsappWebhookSecret))
+ require.NotEqual(t, PublishedWhatsappWebhookSecret, WhatsappWebhookSecret)
+ require.NotEqual(t, PublishedExampleWebhookSecret, WhatsappWebhookSecret)
+
+ body := []byte(`{"event":"message","text":"hello"}`)
+ got := digest(body, []byte(WhatsappWebhookSecret))
+ published := digest(body, []byte(PublishedWhatsappWebhookSecret))
+ require.NotEqual(t, published, got, "configured %q still signs with the published default", configured)
+ example := digest(body, []byte(PublishedExampleWebhookSecret))
+ require.NotEqual(t, example, got, "configured %q still signs with the published example", configured)
+ }
+}
+
+func TestUseEphemeralWebhookSecretKeepsConfiguredKey(t *testing.T) {
+ prev := WhatsappWebhookSecret
+ t.Cleanup(func() { WhatsappWebhookSecret = prev })
+
+ WhatsappWebhookSecret = "operator-secret"
+ replaced, err := UseEphemeralWebhookSecret()
+ require.NoError(t, err)
+ require.False(t, replaced)
+ require.Equal(t, "operator-secret", WhatsappWebhookSecret)
+}
diff --git a/src/go.mod b/src/go.mod
index d01448a0..ab6308be 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -7,6 +7,7 @@ require (
github.com/PuerkitoBio/goquery v1.13.0
github.com/disintegration/imaging v1.6.2
github.com/dustin/go-humanize v1.0.1
+ github.com/fasthttp/websocket v1.5.12
github.com/go-ozzo/ozzo-validation/v4 v4.3.0
github.com/gofiber/contrib/v3/websocket v1.2.1
github.com/gofiber/fiber/v3 v3.4.0
@@ -38,7 +39,6 @@ require (
github.com/beeper/argo-go v1.1.2 // indirect
github.com/coder/websocket v1.8.15 // indirect
github.com/elliotchance/orderedmap/v3 v3.1.1 // indirect
- github.com/fasthttp/websocket v1.5.12 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/gofiber/schema v1.8.0 // indirect
diff --git a/src/infrastructure/chatwoot/AGENTS.md b/src/infrastructure/chatwoot/AGENTS.md
index 00e91c2e..019afc02 100644
--- a/src/infrastructure/chatwoot/AGENTS.md
+++ b/src/infrastructure/chatwoot/AGENTS.md
@@ -10,8 +10,8 @@ Direct Postgres changes have a [scoped guide](pgimport/AGENTS.md).
- Preserve device context on Chatwoot-to-WhatsApp sends. Once per-device configs
exist, `ClientRegistry` must not fall back to the global env inbox for an unmapped
or disabled device. Numeric account/inbox IDs differ from API-channel identifiers.
-- Webhooks in `../../ui/rest/chatwoot.go` bypass app Basic Auth and check
- `CHATWOOT_WEBHOOK_SECRET` when configured; a routed device's own `webhook_secret`
+- Webhooks in `../../ui/rest/chatwoot.go` bypass app Basic Auth and reject an
+ empty effective secret unless `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED` is set. A routed device's own `webhook_secret`
takes its place, on the shared endpoint too (`chatwootWebhookRouteGate`). Only outgoing messages send back to
WhatsApp; preserve `source_id = WAID:<message_id>` and sent-message echo guards.
- Persistent links support idempotency, replies, read/delete sync, and reverse
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index 53888cbe..f564ad75 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -11,7 +11,8 @@ usecases. REST and MCP share the `rest` process and device manager.
outside it. Pass `whatsapp.ContextWithDevice(c.Context(), getDeviceFromCtx(c))`
to device-bound usecases. Browser websockets select a device with `?device_id=`.
- Route/auth order lives in `../cmd/rest.go`. Chatwoot webhooks are mounted before
- Basic Auth but enforce `CHATWOOT_WEBHOOK_SECRET` when configured. A device config's own
+ Basic Auth and reject calls when the effective secret is empty, unless
+ `CHATWOOT_WEBHOOK_ALLOW_UNSIGNED` is set. A device config's own
`webhook_secret` replaces it for that device on both endpoints: call
`chatwootWebhookRouteGate` with the final route before acting on a webhook. Mount
`ChatwootWebhookReplayGuard` in front of the webhook routes: it remembers a signed
diff --git a/src/ui/rest/chatwoot_device_webhook_test.go b/src/ui/rest/chatwoot_device_webhook_test.go
index 14543203..2f28ac13 100644
--- a/src/ui/rest/chatwoot_device_webhook_test.go
+++ b/src/ui/rest/chatwoot_device_webhook_test.go
@@ -51,6 +51,7 @@ func (r *deviceWebhookTestRepo) CountChatwootDeviceConfigs() (int, error) {
// configured account/inbox is rejected (401), while a matching payload passes
// the gate (here a non-action event, so it returns 200 without sending).
func TestHandleDeviceWebhookValidatesAccountInbox(t *testing.T) {
+ withChatwootWebhookSecret(t, "device-gate")
repo := &deviceWebhookTestRepo{
cfg: &domainChatStorage.ChatwootDeviceConfig{ID: 1, DeviceID: "d", ChatwootURL: "https://chat.example.com", AccountID: 1, InboxID: 2, APIToken: "t", Enabled: true},
count: 1,
@@ -65,6 +66,7 @@ func TestHandleDeviceWebhookValidatesAccountInbox(t *testing.T) {
post := func(body string) int {
req := httptest.NewRequest(http.MethodPost, "/chatwoot/webhook/d", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Chatwoot-Webhook-Secret", "device-gate")
resp, err := app.Test(req)
if err != nil {
t.Fatalf("app.Test: %v", err)
@@ -112,11 +114,13 @@ func TestProcessChatwootWebhookDropsUnroutablePayload(t *testing.T) {
// End-to-end: the webhook handler must return 200 without touching the
// device manager (nil here — a delivery attempt would resolve the default
// device and panic on the nil usecases before responding).
+ withChatwootWebhookSecret(t, "gate-secret")
app := fiber.New()
app.Post("/chatwoot/webhook", handler.HandleWebhook)
body := `{"event":"message_created","message_type":"outgoing","account":{"id":1},"conversation":{"id":5,"inbox_id":9,"meta":{"sender":{"phone_number":"+628999999999"}}},"content":"hi"}`
req := httptest.NewRequest(http.MethodPost, "/chatwoot/webhook", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Chatwoot-Webhook-Secret", "gate-secret")
resp, err := app.Test(req)
if err != nil {
t.Fatalf("app.Test: %v", err)
diff --git a/src/ui/rest/chatwoot_test.go b/src/ui/rest/chatwoot_test.go
index 1fa870fc..50acd86c 100644
--- a/src/ui/rest/chatwoot_test.go
+++ b/src/ui/rest/chatwoot_test.go
@@ -521,8 +521,10 @@ func TestChatwootWebhookEmptyReplyText(t *testing.T) {
body += `,"attachments":` + tt.attachments
}
body += `}`
+ withChatwootWebhookSecret(t, "reply-secret")
req := httptest.NewRequest(http.MethodPost, "/chatwoot/webhook", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Chatwoot-Webhook-Secret", "reply-secret")
resp, err := app.Test(req)
if err != nil {
t.Fatalf("app.Test: %v", err)
diff --git a/src/ui/rest/chatwoot_webhook_auth.go b/src/ui/rest/chatwoot_webhook_auth.go
index 327cfd68..2f321b99 100644
--- a/src/ui/rest/chatwoot_webhook_auth.go
+++ b/src/ui/rest/chatwoot_webhook_auth.go
@@ -27,6 +27,7 @@ const (
var (
errChatwootSignatureMissing = errors.New("signature or timestamp header missing")
+ errChatwootSecretRequired = errors.New("webhook secret is not configured")
errChatwootSignatureTimestamp = errors.New("timestamp is not a unix time")
errChatwootSignatureExpired = errors.New("timestamp outside the tolerance window")
errChatwootSignatureMalformed = errors.New("signature is not sha256=<hex>")
@@ -77,9 +78,13 @@ func verifyChatwootSignature(secret, timestamp, signature string, body []byte, n
// point is to tell the operator once, not to add a line per webhook.
var chatwootQuerySecretWarning sync.Once
+// chatwootUnsignedWarning logs the explicit open-webhook opt-in once.
+var chatwootUnsignedWarning sync.Once
+
// chatwootWebhookAuthorizedWith authenticates an incoming Chatwoot webhook
-// with the given secret. An empty secret accepts every request (the check is
-// opt-in). Otherwise the request must satisfy one of:
+// with the given secret. An empty secret rejects the request unless
+// CHATWOOT_WEBHOOK_ALLOW_UNSIGNED is set. Otherwise the request must satisfy
+// one of:
//
// 1. Chatwoot's own signature: X-Chatwoot-Timestamp + X-Chatwoot-Signature.
// 2. The secret itself in X-Chatwoot-Webhook-Secret or X-Gowa-Chatwoot-Secret.
@@ -120,7 +125,13 @@ type chatwootVerifiedSecretKey struct{}
func chatwootWebhookVerify(c fiber.Ctx, secret string) (bool, error) {
secret = strings.TrimSpace(secret)
if secret == "" {
- return true, nil
+ if config.ChatwootWebhookAllowUnsigned {
+ chatwootUnsignedWarning.Do(func() {
+ logrus.Warn("Chatwoot Webhook: CHATWOOT_WEBHOOK_ALLOW_UNSIGNED is enabled; a request with an empty effective secret is accepted")
+ })
+ return true, nil
+ }
+ return false, errChatwootSecretRequired
}
if verified, ok := c.Locals(chatwootVerifiedSecretKey{}).(string); ok && chatwootSecretMatches(secret, verified) {
return true, nil
@@ -244,10 +255,11 @@ func (h *ChatwootHandler) anyChatwootDeviceWebhookSecret() (bool, error) {
// the global secret is refused for a device that has its own, and one device's
// secret cannot deliver through another device.
//
-// When nothing resolves and there is no global secret, no secret applies and
-// the request is acknowledged as before (nothing is acted on for it) - unless
-// some device has its own secret. Then it is answered like a wrong secret, so
-// the status does not tell a caller which account/inbox pairs are protected.
+// When nothing resolves and there is no global secret, the request is rejected
+// unless CHATWOOT_WEBHOOK_ALLOW_UNSIGNED is set. If some device has its own
+// secret, an unroutable request is answered like a wrong secret even in that
+// mode, so the status does not tell a caller which account/inbox pairs are
+// protected.
//
// A Chatwoot-signed request that was already accepted inside the tolerance
// window is authentic but handled: it is acknowledged (200) and not acted on.
diff --git a/src/ui/rest/chatwoot_webhook_auth_test.go b/src/ui/rest/chatwoot_webhook_auth_test.go
index 8192b1db..a00a9d91 100644
--- a/src/ui/rest/chatwoot_webhook_auth_test.go
+++ b/src/ui/rest/chatwoot_webhook_auth_test.go
@@ -238,7 +238,7 @@ func TestChatwootWebhookKeepsOlderSchemes(t *testing.T) {
}
}
-func TestChatwootWebhookWithoutSecretAcceptsEverything(t *testing.T) {
+func TestChatwootWebhookWithoutSecretRejectsRequests(t *testing.T) {
withChatwootWebhookSecret(t, "")
app := fiber.New()
app.Post("/chatwoot/webhook", (&ChatwootHandler{}).HandleWebhook)
@@ -248,12 +248,25 @@ func TestChatwootWebhookWithoutSecretAcceptsEverything(t *testing.T) {
"no headers": nil,
"unverifiable sign": {chatwootTimestampHeader: "1", chatwootSignatureHeader: "sha256=00"},
} {
- if got := postChatwootWebhook(t, app, webhookAuthRequest{body: body, headers: headers}); got != fiber.StatusOK {
- t.Fatalf("%s: status = %d, want 200 when no secret is configured", name, got)
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{body: body, headers: headers}); got != fiber.StatusUnauthorized {
+ t.Fatalf("%s: status = %d, want 401 when no secret is configured", name, got)
}
}
}
+func TestChatwootWebhookAllowUnsignedAcceptsEmptySecret(t *testing.T) {
+ withChatwootWebhookSecret(t, "")
+ prev := config.ChatwootWebhookAllowUnsigned
+ config.ChatwootWebhookAllowUnsigned = true
+ t.Cleanup(func() { config.ChatwootWebhookAllowUnsigned = prev })
+
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", (&ChatwootHandler{}).HandleWebhook)
+ if got := postChatwootWebhook(t, app, webhookAuthRequest{body: `{"event":"conversation_updated"}`}); got != fiber.StatusOK {
+ t.Fatalf("status = %d, want 200 when unsigned webhooks are explicitly enabled", got)
+ }
+}
+
func TestChatwootWebhookSignatureToleranceIsConfigurable(t *testing.T) {
const (
secret = "channel-secret"
diff --git a/src/ui/rest/chatwoot_webhook_route_auth_test.go b/src/ui/rest/chatwoot_webhook_route_auth_test.go
index dcda1bf4..b9d128bb 100644
--- a/src/ui/rest/chatwoot_webhook_route_auth_test.go
+++ b/src/ui/rest/chatwoot_webhook_route_auth_test.go
@@ -290,8 +290,8 @@ func TestChatwootSharedWebhookEnforcesRoutedDeviceSecret(t *testing.T) {
// Same answer as a wrong secret, so the status does not reveal
// which inboxes are mapped to a protected device.
{name: "unsigned reply for an unknown inbox", inbox: 99, want: 401},
- // A device with no secret at all is unauthenticated by configuration.
- {name: "unsigned reply for a device without any secret", inbox: 4, want: 200, wantSend: "open" + toContact},
+ // An empty effective secret is rejected unless the unsigned opt-in is set.
+ {name: "unsigned reply for a device without any secret", inbox: 4, want: 401},
})
})
@@ -341,21 +341,41 @@ func TestChatwootSharedWebhookEnforcesRoutedDeviceSecret(t *testing.T) {
})
})
- // Events nothing is done for are acknowledged as before.
- t.Run("ignored events without a global secret stay acknowledged", func(t *testing.T) {
+ // Events nothing is done for still require a secret. The explicit opt-in
+ // acknowledges them again, but a device that has its own secret stays closed.
+ t.Run("ignored events without a global secret are rejected", func(t *testing.T) {
f := newRouteAuthFixture(t, "")
for _, body := range []string{
`{"event":"conversation_updated","account":{"id":1}}`,
`{"event":"message_created","message_type":"incoming","id":1,"account":{"id":1},"conversation":{"id":5,"inbox_id":2}}`,
} {
- if got := postChatwootWebhook(t, f.app, webhookAuthRequest{body: body}); got != fiber.StatusOK {
- t.Errorf("status = %d for %s, want 200", got, body)
+ if got := postChatwootWebhook(t, f.app, webhookAuthRequest{body: body}); got != fiber.StatusUnauthorized {
+ t.Errorf("status = %d for %s, want 401", got, body)
}
}
if sends := f.send.taken(); len(sends) != 0 {
t.Errorf("sent %v, want nothing sent", sends)
}
})
+
+ t.Run("unsigned opt-in acknowledges events with no effective secret", func(t *testing.T) {
+ prev := config.ChatwootWebhookAllowUnsigned
+ config.ChatwootWebhookAllowUnsigned = true
+ t.Cleanup(func() { config.ChatwootWebhookAllowUnsigned = prev })
+
+ f := newRouteAuthFixture(t, "")
+ body := `{"event":"conversation_updated","account":{"id":1}}`
+ if got := postChatwootWebhook(t, f.app, webhookAuthRequest{body: body}); got != fiber.StatusOK {
+ t.Fatalf("status = %d, want 200 when unsigned webhooks are enabled", got)
+ }
+ protected := `{"event":"message_created","message_type":"outgoing","id":77,"content":"hi","account":{"id":1},"conversation":{"id":5,"inbox_id":2,"meta":{"sender":{"phone_number":"+628999999999"}}}}`
+ if got := postChatwootWebhook(t, f.app, webhookAuthRequest{body: protected}); got != fiber.StatusUnauthorized {
+ t.Fatalf("protected device status = %d, want 401 even when the unsigned opt-in is on", got)
+ }
+ if sends := f.send.taken(); len(sends) != 0 {
+ t.Fatalf("sent %v, want nothing sent", sends)
+ }
+ })
}
// TestChatwootSharedWebhookDeleteEnforcesRoutedDeviceSecret: deleting a
diff --git a/src/ui/rest/group.go b/src/ui/rest/group.go
index 2ebd38f1..7e2d5e35 100644
--- a/src/ui/rest/group.go
+++ b/src/ui/rest/group.go
@@ -4,7 +4,9 @@ import (
"bytes"
"encoding/csv"
"fmt"
+ "regexp"
"strings"
+ "unicode/utf8"
"github.com/sirupsen/logrus"
@@ -171,11 +173,11 @@ func (controller *Group) ExportParticipants(c fiber.Ctx) error {
}
record := []string{
- participant.JID,
- participant.PhoneNumber,
- participant.LID,
- participant.DisplayName,
- role,
+ spreadsheetSafeCell(participant.JID),
+ spreadsheetSafeCell(participant.PhoneNumber),
+ spreadsheetSafeCell(participant.LID),
+ spreadsheetSafeCell(participant.DisplayName),
+ spreadsheetSafeCell(role),
}
utils.PanicIfNeeded(writer.Write(record))
@@ -192,6 +194,29 @@ func (controller *Group) ExportParticipants(c fiber.Ctx) error {
return c.Send(buffer.Bytes())
}
+// spreadsheetSafeCell prefixes cells that spreadsheet applications would
+// treat as formulas, including the full-width = + - @ that some locales
+// accept. Leading ASCII space, tab, CR, and LF are skipped when deciding, and
+// the original cell is prefixed so the apostrophe is the first character a
+// spreadsheet sees. A spreadsheet that splits on ';' or tabs, or a parser
+// that ignores CSV quoting, starts another cell after a separator or line
+// break, so a formula prefix there gets an apostrophe after the separator.
+func spreadsheetSafeCell(value string) string {
+ trimmed := strings.TrimLeft(value, " \t\r\n")
+ safe := formulaAfterSeparator.ReplaceAllString(value, "${1}'${2}${3}")
+ first, _ := utf8.DecodeRuneInString(trimmed)
+ switch first {
+ case '=', '+', '-', '@', '\uFF1D', '\uFF0B', '\uFF0D', '\uFF20':
+ return "'" + safe
+ default:
+ return safe
+ }
+}
+
+// formulaAfterSeparator matches a separator or line break, optional spaces,
+// and a formula prefix that would start the next cell.
+var formulaAfterSeparator = regexp.MustCompile(`([;,\t\r\n])( *)([=+\-@\x{FF1D}\x{FF0B}\x{FF0D}\x{FF20}])`)
+
func (controller *Group) AddParticipants(c fiber.Ctx) error {
return controller.manageParticipants(c, whatsmeow.ParticipantChangeAdd, "Success add participants")
}
diff --git a/src/ui/rest/group_export_test.go b/src/ui/rest/group_export_test.go
new file mode 100644
index 00000000..68961116
--- /dev/null
+++ b/src/ui/rest/group_export_test.go
@@ -0,0 +1,72 @@
+package rest
+
+import (
+ "context"
+ "encoding/csv"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/require"
+)
+
+type exportGroupStub struct {
+ domainGroup.IGroupUsecase
+ result domainGroup.GetGroupParticipantsResponse
+}
+
+func (s exportGroupStub) GetGroupParticipants(context.Context, domainGroup.GetGroupParticipantsRequest) (domainGroup.GetGroupParticipantsResponse, error) {
+ return s.result, nil
+}
+
+func TestExportParticipantsQuotesFormulaCells(t *testing.T) {
+ app := fiber.New()
+ controller := Group{Service: exportGroupStub{result: domainGroup.GetGroupParticipantsResponse{
+ GroupID: "[email protected]",
+ Participants: []domainGroup.GroupParticipant{
+ {
+ PhoneNumber: "+62811",
+ LID: "1555@lid",
+ DisplayName: `=HYPERLINK("http://evil.example","click")`,
+ IsAdmin: true,
+ },
+ {JID: "\t=1", PhoneNumber: "-1", LID: "@evil", DisplayName: "+SUM(A1)"},
+ {JID: "[email protected]", PhoneNumber: "62812", LID: "2@lid", DisplayName: "Alice\r=cmd"},
+ {JID: "[email protected]", DisplayName: " =HYPERLINK(\"http://evil.example\",\"x\")"},
+ {JID: "[email protected]", DisplayName: "\t+SUM(A1)"},
+ {JID: "\t-1", PhoneNumber: "+62813", LID: "@evil", DisplayName: "=HYPERLINK(\"http://evil.example\",\"x\")"},
+ {JID: "[email protected]", DisplayName: "Bob;=1+1;x"},
+ {JID: "[email protected]", DisplayName: "Tab\t+1, @x;; -2"},
+ },
+ }}}
+ app.Get("/group/participants/export", controller.ExportParticipants)
+
+ resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/group/participants/[email protected]", nil))
+ require.NoError(t, err)
+ defer func() { require.NoError(t, resp.Body.Close()) }()
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+
+ records, err := csv.NewReader(resp.Body).ReadAll()
+ require.NoError(t, err)
+ require.Len(t, records, 9)
+ require.Equal(t, `'=HYPERLINK("http://evil.example","click")`, records[1][3])
+ require.Equal(t, "'+62811", records[1][1])
+ require.Equal(t, "admin", records[1][4])
+ require.Equal(t, "'\t'=1", records[2][0])
+ require.Equal(t, "'-1", records[2][1])
+ require.Equal(t, "'@evil", records[2][2])
+ require.Equal(t, "'+SUM(A1)", records[2][3])
+ require.Equal(t, "Alice\r'=cmd", records[3][3])
+ require.True(t, strings.HasPrefix(records[3][3], "Alice"))
+ require.Equal(t, "' =HYPERLINK(\"http://evil.example\",\"x\")", records[4][3])
+ require.Equal(t, "'\t'+SUM(A1)", records[5][3])
+ require.Equal(t, "'\t'-1", records[6][0])
+ require.Equal(t, "'+62813", records[6][1])
+ require.Equal(t, "'@evil", records[6][2])
+ require.Equal(t, "'=HYPERLINK(\"http://evil.example\",\"x\")", records[6][3])
+ require.Equal(t, "Bob;'=1+1;x", records[7][3])
+ require.Equal(t, "Tab\t'+1,' @x;;' -2", records[8][3])
+}
diff --git a/src/ui/rest/middleware/origin.go b/src/ui/rest/middleware/origin.go
new file mode 100644
index 00000000..1aa5f779
--- /dev/null
+++ b/src/ui/rest/middleware/origin.go
@@ -0,0 +1,171 @@
+package middleware
+
+import (
+ "strconv"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/gofiber/fiber/v3"
+)
+
+// BrowserOriginGuard rejects cross-site browser requests on state-changing
+// routes, including GET handlers that mutate (login, logout, reconnect, and
+// invite-link reset). API clients that omit Origin and Referer are allowed
+// so curl and server integrations keep working. When either header is
+// present it must match the trusted-origin allowlist. With neither header, a
+// Sec-Fetch-Site of same-site or cross-site is rejected, and so is a mutating
+// GET from a browser User-Agent that sent no Sec-Fetch-Site.
+func BrowserOriginGuard() fiber.Handler {
+ return func(c fiber.Ctx) error {
+ if !stateChangingRequest(c) || browserSourceAllowed(c) {
+ return c.Next()
+ }
+ return c.Status(fiber.StatusForbidden).JSON(utils.ResponseData{
+ Status: fiber.StatusForbidden,
+ Code: "CROSS_SITE_REQUEST_BLOCKED",
+ Message: "browser request origin is not allowed",
+ })
+ }
+}
+
+func browserSourceAllowed(c fiber.Ctx) bool {
+ origin, referer, fetchSite := c.Get(fiber.HeaderOrigin), c.Get(fiber.HeaderReferer), c.Get("Sec-Fetch-Site")
+ // Browsers send no Fetch Metadata to a plain-HTTP origin, and a page can
+ // hide its referrer on a navigation or an <img> or <script> load. Such a
+ // mutating GET is only trusted from a client that is not a browser: every
+ // browser User-Agent contains "Mozilla/", and a page cannot change it.
+ method := strings.ToUpper(c.Method())
+ if (method == fiber.MethodGet || method == fiber.MethodHead) && origin == "" && referer == "" && fetchSite == "" &&
+ strings.Contains(c.Get(fiber.HeaderUserAgent), "Mozilla/") {
+ return false
+ }
+ return config.BrowserSourceAllowed(c.Host(), origin, referer, fetchSite)
+}
+
+func stateChangingRequest(c fiber.Ctx) bool {
+ switch strings.ToUpper(c.Method()) {
+ case fiber.MethodPost, fiber.MethodPut, fiber.MethodPatch, fiber.MethodDelete:
+ return true
+ case fiber.MethodGet, fiber.MethodHead:
+ // Fiber copies GET handlers onto HEAD and matches paths
+ // case-insensitively with trailing slashes when strict routing is off.
+ return mutatingGET(c)
+ default:
+ return false
+ }
+}
+
+func mutatingGET(c fiber.Ctx) bool {
+ p := canonicalRequestPath(c.Path(), config.AppBasePath)
+ switch p {
+ case "/app/login", "/app/login-with-code", "/app/logout", "/app/reconnect":
+ return true
+ case "/group/invite-link":
+ return inviteLinkReset(c)
+ default:
+ // /devices/:device_id/login
+ return strings.HasPrefix(p, "/devices/") && strings.HasSuffix(p, "/login") && strings.Count(p, "/") == 3
+ }
+}
+
+// canonicalRequestPath strips the configured base path, letter case, and every
+// trailing slash so the guard sees the same route Fiber runs with strict
+// routing off. A lone slash stays "/".
+func canonicalRequestPath(path, base string) string {
+ if path == "" {
+ path = "/"
+ }
+ base = strings.TrimRight(strings.TrimSpace(base), "/")
+ if base != "" && len(path) >= len(base) && strings.EqualFold(path[:len(base)], base) {
+ rest := path[len(base):]
+ if rest == "" || strings.HasPrefix(rest, "/") {
+ path = rest
+ }
+ }
+ path = strings.ToLower(path)
+ for len(path) > 1 && strings.HasSuffix(path, "/") {
+ path = path[:len(path)-1]
+ }
+ if path == "" {
+ return "/"
+ }
+ if !strings.HasPrefix(path, "/") {
+ path = "/" + path
+ }
+ return path
+}
+
+// inviteLinkReset reports whether any reset query value would make
+// GetGroupInviteLink regenerate the link. The binder lowercases keys and
+// deletes every empty "[]" in the key, so []reset and re[]set are reset.
+// gofiber/schema convertBool treats the exact string "on" and strconv.ParseBool
+// truths as true. Any truthy value fails closed. reset[0] stays reset.0 and
+// does not set the field.
+func inviteLinkReset(c fiber.Ctx) bool {
+ reset := false
+ for key, value := range c.RequestCtx().QueryArgs().All() {
+ if !queryKeyIsReset(string(key)) {
+ continue
+ }
+ if schemaBoolTrue(string(value)) {
+ reset = true
+ }
+ }
+ return reset
+}
+
+// queryKeyIsReset reports whether key is the binder's reset field. Query
+// decoding has already turned %5B%5D into []. Empty "[]" pairs are removed
+// wherever they sit in the key, matching parseParamSquareBrackets, so
+// "[]reset" and "re[]set" become "reset". A non-empty index such as
+// "reset[0]" becomes "reset.0" and is not the field.
+func queryKeyIsReset(key string) bool {
+ normalized, ok := normalizeQueryBrackets(key)
+ if !ok {
+ return false
+ }
+ return strings.EqualFold(normalized, "reset")
+}
+
+// normalizeQueryBrackets copies Fiber's parseParamSquareBrackets: an empty
+// "[]" is deleted, and "[index]" becomes ".index". Unmatched brackets do not
+// bind.
+func normalizeQueryBrackets(key string) (string, bool) {
+ if !strings.Contains(key, "[") {
+ return key, true
+ }
+ var b strings.Builder
+ b.Grow(len(key))
+ open := 0
+ for i := 0; i < len(key); i++ {
+ switch key[i] {
+ case '[':
+ open++
+ if i+1 < len(key) && key[i+1] != ']' {
+ b.WriteByte('.')
+ }
+ case ']':
+ open--
+ if open < 0 {
+ return "", false
+ }
+ default:
+ b.WriteByte(key[i])
+ }
+ }
+ if open != 0 {
+ return "", false
+ }
+ return b.String(), true
+}
+
+// schemaBoolTrue matches gofiber/schema convertBool's true results:
+// the exact string "on", plus 1, t, T, true, TRUE, and True.
+func schemaBoolTrue(value string) bool {
+ if value == "on" {
+ return true
+ }
+ parsed, err := strconv.ParseBool(value)
+ return err == nil && parsed
+}
diff --git a/src/ui/rest/middleware/origin_test.go b/src/ui/rest/middleware/origin_test.go
new file mode 100644
index 00000000..174b1031
--- /dev/null
+++ b/src/ui/rest/middleware/origin_test.go
@@ -0,0 +1,392 @@
+package middleware
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/require"
+)
+
+func TestBrowserOriginGuard(t *testing.T) {
+ newApp := func() *fiber.App {
+ app := fiber.New()
+ app.Use(BrowserOriginGuard())
+ ok := func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) }
+ app.Post("/send/message", ok)
+ app.Get("/app/logout", ok)
+ app.Get("/app/status", ok)
+ app.Get("/group/invite-link", ok)
+ return app
+ }
+
+ t.Run("cross-site origin is rejected on a mutating route", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodPost, "http://gowa.example/send/message", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ body, err := io.ReadAll(resp.Body)
+ require.NoError(t, err)
+ require.Contains(t, string(body), "CROSS_SITE_REQUEST_BLOCKED")
+ })
+
+ t.Run("missing origin is allowed", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodPost, "http://gowa.example/send/message", nil)
+ req.Host = "gowa.example"
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ })
+
+ t.Run("trusted same-host origin is allowed", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodPost, "http://gowa.example/send/message", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "http://gowa.example")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ })
+
+ t.Run("configured origin is allowed", func(t *testing.T) {
+ prev := config.AppTrustedOrigins
+ config.AppTrustedOrigins = []string{"https://ui.example"}
+ t.Cleanup(func() { config.AppTrustedOrigins = prev })
+
+ req := httptest.NewRequest(fiber.MethodPost, "http://gowa.example/send/message", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://ui.example")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ })
+
+ t.Run("logout get is rejected for a foreign origin", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/app/logout", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ })
+
+ t.Run("invite-link reset is rejected for a foreign referer", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/group/invite-link?group_id=1&reset=true", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Referer", "https://evil.example/phish")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ })
+
+ t.Run("invite-link read is not treated as a mutation", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/group/invite-link?group_id=1", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ })
+
+ t.Run("cross-site fetch metadata without origin is rejected", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/app/logout", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ })
+
+ t.Run("request host is trusted under https behind a TLS proxy", func(t *testing.T) {
+ for _, target := range []struct {
+ method string
+ path string
+ header string
+ value string
+ want int
+ }{
+ {fiber.MethodPost, "/send/message", "Origin", "https://gowa.example", fiber.StatusOK},
+ {fiber.MethodGet, "/app/logout", "Referer", "https://gowa.example/", fiber.StatusOK},
+ {fiber.MethodPost, "/send/message", "Origin", "https://gowa.example:8443", fiber.StatusForbidden},
+ {fiber.MethodPost, "/send/message", "Origin", "https://evil.gowa.example", fiber.StatusForbidden},
+ } {
+ req := httptest.NewRequest(target.method, "http://gowa.example"+target.path, nil)
+ req.Host = "gowa.example"
+ req.Header.Set(target.header, target.value)
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, target.want, resp.StatusCode, target.value)
+ require.NoError(t, resp.Body.Close())
+ }
+ })
+
+ t.Run("configured app origin is matched as written", func(t *testing.T) {
+ prev := config.AppTrustedOrigins
+ config.AppTrustedOrigins = []string{"Capacitor://LocalHost/", "chrome-extension://abcdefgh", "null"}
+ t.Cleanup(func() { config.AppTrustedOrigins = prev })
+
+ for origin, want := range map[string]int{
+ "capacitor://localhost": fiber.StatusOK,
+ "chrome-extension://abcdefgh": fiber.StatusOK,
+ "capacitor://evil": fiber.StatusForbidden,
+ "chrome-extension://zzzzzzzz": fiber.StatusForbidden,
+ "null": fiber.StatusForbidden,
+ } {
+ req := httptest.NewRequest(fiber.MethodPost, "http://gowa.example/send/message", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", origin)
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, want, resp.StatusCode, origin)
+ require.NoError(t, resp.Body.Close())
+ }
+ })
+}
+
+func TestBrowserOriginGuardWithoutOriginOrReferer(t *testing.T) {
+ app := fiber.New()
+ app.Use(BrowserOriginGuard())
+ ok := func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) }
+ app.Post("/send/message", ok)
+ app.Get("/app/logout", ok)
+ app.Get("/app/status", ok)
+
+ const browser = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
+ cases := []struct {
+ name string
+ method string
+ path string
+ headers map[string]string
+ want int
+ }{
+ {"curl logout", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": "curl/8.7.1"}, fiber.StatusOK},
+ {"n8n logout", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": "axios/1.7.9"}, fiber.StatusOK},
+ {"browser logout with no referrer", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": browser}, fiber.StatusForbidden},
+ {"browser head logout with no referrer", fiber.MethodHead, "/app/logout", map[string]string{"User-Agent": browser}, fiber.StatusForbidden},
+ {"same-site logout", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": browser, "Sec-Fetch-Site": "same-site"}, fiber.StatusForbidden},
+ {"same-site post", fiber.MethodPost, "/send/message", map[string]string{"User-Agent": browser, "Sec-Fetch-Site": "same-site"}, fiber.StatusForbidden},
+ {"same-origin referer logout", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": browser, "Referer": "http://gowa.example/"}, fiber.StatusOK},
+ {"typed logout url", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": browser, "Sec-Fetch-Site": "none"}, fiber.StatusOK},
+ {"same-origin fetch metadata logout", fiber.MethodGet, "/app/logout", map[string]string{"User-Agent": browser, "Sec-Fetch-Site": "same-origin"}, fiber.StatusOK},
+ {"browser post with no origin", fiber.MethodPost, "/send/message", map[string]string{"User-Agent": browser}, fiber.StatusOK},
+ {"browser read with no referrer", fiber.MethodGet, "/app/status", map[string]string{"User-Agent": browser}, fiber.StatusOK},
+ }
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ req := httptest.NewRequest(tt.method, "http://gowa.example"+tt.path, nil)
+ req.Host = "gowa.example"
+ for key, value := range tt.headers {
+ req.Header.Set(key, value)
+ }
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, tt.want, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+ }
+}
+
+func TestMutatingGETAliasesAreRejected(t *testing.T) {
+ newApp := func() *fiber.App {
+ app := fiber.New()
+ app.Use(BrowserOriginGuard())
+ ok := func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) }
+ app.Get("/app/logout", ok)
+ app.Get("/app/reconnect", ok)
+ app.Get("/group/invite-link", ok)
+ app.Get("/app/login", ok)
+ app.Get("/app/login-with-code", ok)
+ app.Get("/devices/:device_id", ok)
+ app.Get("/devices/:device_id/login", ok)
+ return app
+ }
+ evil := func(method, target string) *http.Request {
+ req := httptest.NewRequest(method, target, nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ return req
+ }
+
+ cases := []struct {
+ name string
+ method string
+ target string
+ }{
+ {name: "logout trailing slash", method: fiber.MethodGet, target: "http://gowa.example/app/logout/"},
+ {name: "logout different case", method: fiber.MethodGet, target: "http://gowa.example/APP/LOGOUT"},
+ {name: "logout head", method: fiber.MethodHead, target: "http://gowa.example/app/logout"},
+ {name: "reconnect trailing slash", method: fiber.MethodGet, target: "http://gowa.example/app/reconnect/"},
+ {name: "reconnect head", method: fiber.MethodHead, target: "http://gowa.example/app/reconnect"},
+ {name: "invite trailing slash", method: fiber.MethodGet, target: "http://gowa.example/group/invite-link/?reset=true"},
+ {name: "invite different case", method: fiber.MethodGet, target: "http://gowa.example/GROUP/INVITE-LINK?reset=true"},
+ {name: "invite head", method: fiber.MethodHead, target: "http://gowa.example/group/invite-link?reset=true"},
+ {name: "logout two slashes", method: fiber.MethodGet, target: "http://gowa.example/app/logout//"},
+ {name: "logout three slashes", method: fiber.MethodGet, target: "http://gowa.example/app/logout///"},
+ {name: "logout case and two slashes", method: fiber.MethodGet, target: "http://gowa.example/APP/LOGOUT//"},
+ {name: "logout head two slashes", method: fiber.MethodHead, target: "http://gowa.example/app/logout//"},
+ {name: "reconnect two slashes", method: fiber.MethodGet, target: "http://gowa.example/app/reconnect//"},
+ {name: "invite two slashes", method: fiber.MethodGet, target: "http://gowa.example/group/invite-link//?reset=true"},
+ {name: "invite head two slashes", method: fiber.MethodHead, target: "http://gowa.example/group/invite-link//?reset=true"},
+ {name: "login", method: fiber.MethodGet, target: "http://gowa.example/app/login"},
+ {name: "login head", method: fiber.MethodHead, target: "http://gowa.example/app/login"},
+ {name: "login case and slashes", method: fiber.MethodGet, target: "http://gowa.example/APP/LOGIN//"},
+ {name: "login with code", method: fiber.MethodGet, target: "http://gowa.example/app/login-with-code?phone=628111"},
+ {name: "login with code head and slash", method: fiber.MethodHead, target: "http://gowa.example/App/Login-With-Code/?phone=628111"},
+ {name: "device login", method: fiber.MethodGet, target: "http://gowa.example/devices/dev-1/login"},
+ {name: "device login head", method: fiber.MethodHead, target: "http://gowa.example/devices/dev-1/login"},
+ {name: "device login case and slashes", method: fiber.MethodGet, target: "http://gowa.example/DEVICES/DEV-1/LOGIN//"},
+ {name: "device login escaped id", method: fiber.MethodGet, target: "http://gowa.example/devices/a%2Fb/login"},
+ }
+ for _, tt := range cases {
+ t.Run(tt.name, func(t *testing.T) {
+ resp, err := newApp().Test(evil(tt.method, tt.target))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+ }
+
+ t.Run("device read is not guarded", func(t *testing.T) {
+ resp, err := newApp().Test(evil(fiber.MethodGet, "http://gowa.example/devices/login"))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+
+ t.Run("non-canonical logout without origin is allowed", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/APP/LOGOUT", nil)
+ req.Host = "gowa.example"
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+
+ t.Run("double slash logout without origin is allowed", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/app/logout//", nil)
+ req.Host = "gowa.example"
+ resp, err := newApp().Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+
+ t.Run("base path trailing slash", func(t *testing.T) {
+ prev := config.AppBasePath
+ config.AppBasePath = "/gowa"
+ t.Cleanup(func() { config.AppBasePath = prev })
+
+ app := fiber.New()
+ app.Use(BrowserOriginGuard())
+ app.Get("/gowa/app/logout", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) })
+ app.Get("/gowa/group/invite-link", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) })
+ for _, target := range []struct {
+ method string
+ url string
+ }{
+ {fiber.MethodGet, "http://gowa.example/gowa/app/logout/"},
+ {fiber.MethodGet, "http://gowa.example/gowa/app/logout//"},
+ {fiber.MethodGet, "http://gowa.example/GOWA/APP/LOGOUT//"},
+ {fiber.MethodHead, "http://gowa.example/gowa/app/logout//"},
+ {fiber.MethodGet, "http://gowa.example/gowa/group/invite-link//?reset=true"},
+ } {
+ resp, err := app.Test(evil(target.method, target.url))
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode, target.url)
+ require.NoError(t, resp.Body.Close())
+ }
+ })
+}
+
+func TestInviteLinkResetMatchesBinder(t *testing.T) {
+ app := fiber.New()
+ app.Use(BrowserOriginGuard())
+ app.Get("/group/invite-link", func(c fiber.Ctx) error { return c.SendStatus(fiber.StatusOK) })
+
+ for _, target := range []string{
+ "http://gowa.example/group/invite-link?reset=on",
+ "http://gowa.example/group/invite-link?Reset=true",
+ "http://gowa.example/group/invite-link?reset=false&reset=true",
+ "http://gowa.example/group/invite-link?reset=false&reset=on",
+ "http://gowa.example/group/invite-link?reset=true&reset=false",
+ "http://gowa.example/group/invite-link?reset=TRUE",
+ "http://gowa.example/group/invite-link?reset=t",
+ "http://gowa.example/group/invite-link?reset=1",
+ "http://gowa.example/group/invite-link?reset[]=true",
+ "http://gowa.example/group/invite-link?reset[]=on",
+ "http://gowa.example/group/invite-link?Reset[]=true",
+ "http://gowa.example/group/invite-link?reset%5B%5D=true",
+ "http://gowa.example/group/invite-link?reset=false&reset[]=true",
+ "http://gowa.example/group/invite-link?[]reset=true",
+ "http://gowa.example/group/invite-link?re[]set=true",
+ "http://gowa.example/group/invite-link?[]reset[]=true",
+ "http://gowa.example/group/invite-link?r[]e[]s[]e[]t=true",
+ "http://gowa.example/group/invite-link?reset=false&[]reset=true",
+ "http://gowa.example/group/invite-link?[]Reset=true",
+ "http://gowa.example/group/invite-link?%5B%5Dreset=true",
+ } {
+ t.Run(target, func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, target, nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+ }
+
+ t.Run("indexed reset does not set the field", func(t *testing.T) {
+ var reset bool
+ var ran bool
+ indexed := fiber.New()
+ indexed.Use(BrowserOriginGuard())
+ indexed.Get("/group/invite-link", func(c fiber.Ctx) error {
+ ran = true
+ var request struct {
+ Reset bool `query:"reset"`
+ }
+ if err := c.Bind().Query(&request); err != nil {
+ return err
+ }
+ reset = request.Reset
+ return c.SendStatus(fiber.StatusOK)
+ })
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/group/invite-link?reset[0]=true", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ req.Header.Set("Sec-Fetch-Site", "cross-site")
+ resp, err := indexed.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ require.True(t, ran)
+ require.False(t, reset)
+ })
+
+ t.Run("final false only is not a reset", func(t *testing.T) {
+ req := httptest.NewRequest(fiber.MethodGet, "http://gowa.example/group/invite-link?reset=false", nil)
+ req.Host = "gowa.example"
+ req.Header.Set("Origin", "https://evil.example")
+ resp, err := app.Test(req)
+ require.NoError(t, err)
+ require.Equal(t, fiber.StatusOK, resp.StatusCode)
+ require.NoError(t, resp.Body.Close())
+ })
+}
+
+func TestNormalizeOrigin(t *testing.T) {
+ require.Equal(t, "https://ui.example", config.NormalizeOrigin("https://ui.example/dashboard"))
+ require.Equal(t, "http://localhost:3000", config.NormalizeOrigin("http://localhost:3000"))
+ require.Equal(t, "https://ui.example", config.NormalizeOrigin("https://ui.example:443"))
+ require.Empty(t, config.NormalizeOrigin("null"))
+ require.Empty(t, config.NormalizeOrigin("*"))
+ require.Equal(t, "capacitor://localhost", config.NormalizeOrigin("Capacitor://LocalHost/"))
+ require.Empty(t, config.NormalizeOrigin("file://"))
+}
diff --git a/src/ui/websocket/websocket.go b/src/ui/websocket/websocket.go
index e08f7e83..5b72e7e0 100644
--- a/src/ui/websocket/websocket.go
+++ b/src/ui/websocket/websocket.go
@@ -3,15 +3,103 @@ package websocket
import (
"context"
"encoding/json"
+ "sync"
+ "time"
"github.com/sirupsen/logrus"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
"github.com/gofiber/contrib/v3/websocket"
"github.com/gofiber/fiber/v3"
)
-type client struct{}
+// wsConn is the subset of a websocket connection the hub writes to. Tests
+// substitute a fake so a stalled client can be observed without a network.
+type wsConn interface {
+ WriteMessage(messageType int, data []byte) error
+ SetWriteDeadline(t time.Time) error
+ Close() error
+}
+
+type subscriber struct {
+ conn wsConn
+ send chan []byte
+ mu sync.Mutex
+ closed bool
+ once sync.Once
+ done chan struct{} // closed when writeLoop returns
+}
+
+// clientQueueSize bounds how many messages may wait for one client. A full
+// queue disconnects that client instead of stalling the hub.
+var clientQueueSize = 16
+
+// writeTimeout is the deadline for a single client write. A client that
+// stops reading is disconnected when the deadline passes.
+var writeTimeout = 10 * time.Second
+
+func newSubscriber(conn wsConn) *subscriber {
+ size := clientQueueSize
+ if size < 1 {
+ size = 1
+ }
+ return &subscriber{conn: conn, send: make(chan []byte, size), done: make(chan struct{})}
+}
+
+// trySend enqueues payload without blocking. A full or closed queue reports
+// failure so the caller can drop the slow client.
+func (s *subscriber) trySend(payload []byte) bool {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ if s.closed {
+ return false
+ }
+ select {
+ case s.send <- payload:
+ return true
+ default:
+ return false
+ }
+}
+
+func (s *subscriber) failSlow() {
+ s.mu.Lock()
+ if !s.closed {
+ s.closed = true
+ close(s.send)
+ }
+ s.mu.Unlock()
+ s.closeConn()
+}
+
+func (s *subscriber) closeConn() {
+ s.once.Do(func() {
+ _ = s.conn.Close()
+ })
+}
+
+func (s *subscriber) writeLoop() {
+ defer close(s.done)
+ defer func() {
+ s.failSlow()
+ Unregister <- s
+ }()
+ for payload := range s.send {
+ timeout := writeTimeout
+ if timeout <= 0 {
+ timeout = 10 * time.Second
+ }
+ if err := s.conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
+ logrus.Println("write deadline error:", err)
+ return
+ }
+ if err := s.conn.WriteMessage(websocket.TextMessage, payload); err != nil {
+ logrus.Println("write error:", err)
+ return
+ }
+ }
+}
type BroadcastMessage struct {
Code string `json:"code"`
@@ -20,19 +108,41 @@ type BroadcastMessage struct {
}
var (
- Clients = make(map[*websocket.Conn]client)
- Register = make(chan *websocket.Conn)
+ clients = make(map[*subscriber]struct{})
+ clientsMu sync.Mutex
+ Register = make(chan *subscriber)
Broadcast = make(chan BroadcastMessage)
- Unregister = make(chan *websocket.Conn)
+ Unregister = make(chan *subscriber)
)
-func handleRegister(conn *websocket.Conn) {
- Clients[conn] = client{}
+// Publish delivers message to the hub or returns false when ctx ends first.
+// A full per-client queue cannot block this send: the hub drops that client
+// and keeps broadcasting to the others. Existing callers may also send on
+// Broadcast; the hub no longer writes sockets on its own goroutine.
+func Publish(ctx context.Context, message BroadcastMessage) bool {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ select {
+ case Broadcast <- message:
+ return true
+ case <-ctx.Done():
+ return false
+ }
+}
+
+func handleRegister(sub *subscriber) {
+ clientsMu.Lock()
+ clients[sub] = struct{}{}
+ clientsMu.Unlock()
+ go sub.writeLoop()
logrus.Println("connection registered")
}
-func handleUnregister(conn *websocket.Conn) {
- delete(Clients, conn)
+func handleUnregister(sub *subscriber) {
+ clientsMu.Lock()
+ delete(clients, sub)
+ clientsMu.Unlock()
logrus.Println("connection unregistered")
}
@@ -43,22 +153,20 @@ func broadcastMessage(message BroadcastMessage) {
return
}
- for conn := range Clients {
- if err := conn.WriteMessage(websocket.TextMessage, marshalMessage); err != nil {
- logrus.Println("write error:", err)
- closeConnection(conn)
- }
+ clientsMu.Lock()
+ subs := make([]*subscriber, 0, len(clients))
+ for sub := range clients {
+ subs = append(subs, sub)
}
-}
+ clientsMu.Unlock()
-func closeConnection(conn *websocket.Conn) {
- if err := conn.WriteMessage(websocket.CloseMessage, []byte{}); err != nil {
- logrus.Println("write close message error:", err)
- }
- if err := conn.Close(); err != nil {
- logrus.Println("close connection error:", err)
+ for _, sub := range subs {
+ if sub.trySend(marshalMessage) {
+ continue
+ }
+ logrus.Println("disconnecting slow websocket client")
+ go sub.failSlow()
}
- delete(Clients, conn)
}
func RunHub() {
@@ -85,41 +193,65 @@ func RegisterRoutes(app fiber.Router, service domainApp.IAppUsecase) {
return c.SendStatus(fiber.StatusUpgradeRequired)
})
- app.Get("/ws", websocket.New(func(conn *websocket.Conn) {
- defer func() {
- Unregister <- conn
- _ = conn.Close()
- }()
-
- Register <- conn
+ app.Get("/ws", func(c fiber.Ctx) error {
+ // Reject before the upgrade so an untrusted browser never joins the hub.
+ // The upgrader repeats the same allowlist, and non-browser clients that
+ // omit Origin stay allowed.
+ if !config.BrowserSourceAllowed(c.Host(), c.Get(fiber.HeaderOrigin), c.Get(fiber.HeaderReferer), c.Get("Sec-Fetch-Site")) {
+ return c.Status(fiber.StatusForbidden).JSON(fiber.Map{
+ "code": "CROSS_SITE_REQUEST_BLOCKED",
+ "message": "browser request origin is not allowed",
+ })
+ }
+ origins := config.TrustedBrowserOrigins(c.Host())
+ if len(origins) == 0 {
+ // An empty list makes the adapter allow every origin.
+ origins = []string{"http://127.0.0.1"}
+ }
+ return websocket.New(func(conn *websocket.Conn) {
+ sub := newSubscriber(conn)
+ defer func() {
+ sub.failSlow()
+ // The adapter recycles conn once this handler returns, so the
+ // writer must stop first. failSlow closed the socket, which
+ // ends a pending write.
+ <-sub.done
+ Unregister <- sub
+ }()
- for {
- messageType, message, err := conn.ReadMessage()
- if err != nil {
- if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
- logrus.Println("read error:", err)
- }
- return
- }
+ Register <- sub
- if messageType == websocket.TextMessage {
- var messageData BroadcastMessage
- if err := json.Unmarshal(message, &messageData); err != nil {
- logrus.Println("unmarshal error:", err)
+ for {
+ messageType, message, err := conn.ReadMessage()
+ if err != nil {
+ if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
+ logrus.Println("read error:", err)
+ }
return
}
- if messageData.Code == "FETCH_DEVICES" {
- devices, _ := service.FetchDevices(context.Background())
- Broadcast <- BroadcastMessage{
- Code: "LIST_DEVICES",
- Message: "Device found",
- Result: devices,
+ if messageType == websocket.TextMessage {
+ var messageData BroadcastMessage
+ if err := json.Unmarshal(message, &messageData); err != nil {
+ logrus.Println("unmarshal error:", err)
+ return
+ }
+
+ if messageData.Code == "FETCH_DEVICES" {
+ devices, _ := service.FetchDevices(context.Background())
+ Broadcast <- BroadcastMessage{
+ Code: "LIST_DEVICES",
+ Message: "Device found",
+ Result: devices,
+ }
}
+ } else {
+ logrus.Println("unsupported message type:", messageType)
}
- } else {
- logrus.Println("unsupported message type:", messageType)
}
- }
- }))
+ }, websocket.Config{
+ Origins: origins,
+ AllowEmptyOrigin: true,
+ })(c)
+ })
}
diff --git a/src/ui/websocket/websocket_test.go b/src/ui/websocket/websocket_test.go
new file mode 100644
index 00000000..31dce1c2
--- /dev/null
+++ b/src/ui/websocket/websocket_test.go
@@ -0,0 +1,247 @@
+package websocket
+
+import (
+ "context"
+ "errors"
+ "net"
+ "net/http"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/fasthttp/websocket"
+ fiberws "github.com/gofiber/contrib/v3/websocket"
+ "github.com/gofiber/fiber/v3"
+ "github.com/stretchr/testify/require"
+)
+
+func TestMain(m *testing.M) {
+ go RunHub()
+ m.Run()
+}
+
+type recordingConn struct {
+ mu sync.Mutex
+ msgs [][]byte
+}
+
+func (c *recordingConn) WriteMessage(_ int, data []byte) error {
+ c.mu.Lock()
+ c.msgs = append(c.msgs, append([]byte(nil), data...))
+ c.mu.Unlock()
+ return nil
+}
+
+func (c *recordingConn) SetWriteDeadline(time.Time) error { return nil }
+
+func (c *recordingConn) Close() error { return nil }
+
+func (c *recordingConn) count() int {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return len(c.msgs)
+}
+
+type blockingConn struct {
+ mu sync.Mutex
+ deadline time.Time
+ once sync.Once
+ done chan struct{}
+}
+
+func newBlockingConn() *blockingConn {
+ return &blockingConn{done: make(chan struct{})}
+}
+
+func (c *blockingConn) SetWriteDeadline(t time.Time) error {
+ c.mu.Lock()
+ c.deadline = t
+ c.mu.Unlock()
+ return nil
+}
+
+func (c *blockingConn) WriteMessage(int, []byte) error {
+ c.mu.Lock()
+ deadline := c.deadline
+ c.mu.Unlock()
+ var timer <-chan time.Time
+ if !deadline.IsZero() {
+ timer = time.After(time.Until(deadline))
+ }
+ select {
+ case <-timer:
+ return errors.New("write deadline exceeded")
+ case <-c.done:
+ return errors.New("stalled client disconnected")
+ }
+}
+
+func (c *blockingConn) Close() error {
+ c.once.Do(func() { close(c.done) })
+ return nil
+}
+
+func waitForClients(t *testing.T, n int) {
+ t.Helper()
+ deadline := time.Now().Add(time.Second)
+ for time.Now().Before(deadline) {
+ clientsMu.Lock()
+ got := len(clients)
+ clientsMu.Unlock()
+ if got >= n {
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ t.Fatalf("timed out waiting for %d websocket clients", n)
+}
+
+// waitForSockets waits until exactly n subscribers on a real websocket are
+// registered. The fake connections of the hub tests are not counted.
+func waitForSockets(t *testing.T, n int) {
+ t.Helper()
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ got := 0
+ clientsMu.Lock()
+ for sub := range clients {
+ if _, ok := sub.conn.(*fiberws.Conn); ok {
+ got++
+ }
+ }
+ clientsMu.Unlock()
+ if got == n {
+ return
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ t.Fatalf("timed out waiting for %d websocket connections", n)
+}
+
+func TestHubDoesNotBlockWhenClientStopsReading(t *testing.T) {
+ prevTimeout := writeTimeout
+ prevQueue := clientQueueSize
+ // Longer than the publish timeout so a hub that writes synchronously fails the test.
+ writeTimeout = 2 * time.Second
+ clientQueueSize = 1
+ t.Cleanup(func() {
+ writeTimeout = prevTimeout
+ clientQueueSize = prevQueue
+ })
+
+ stalled := newBlockingConn()
+ healthy := &recordingConn{}
+ // The healthy queue holds both broadcasts, so only the stalled client can
+ // be dropped as slow.
+ subs := []*subscriber{newSubscriber(stalled), {conn: healthy, send: make(chan []byte, 2), done: make(chan struct{})}}
+ // Runs before the cleanup above: the writers read writeTimeout, so they
+ // must exit before it is restored.
+ t.Cleanup(func() {
+ for _, sub := range subs {
+ sub.failSlow()
+ <-sub.done
+ }
+ })
+
+ for _, sub := range subs {
+ Register <- sub
+ }
+ waitForClients(t, 2)
+
+ send := func() time.Duration {
+ t.Helper()
+ start := time.Now()
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ if !Publish(ctx, BroadcastMessage{Code: "PING", Message: "still going"}) {
+ t.Fatal("publish blocked or was cancelled while a client was stalled")
+ }
+ return time.Since(start)
+ }
+
+ if elapsed := send(); elapsed > 150*time.Millisecond {
+ t.Fatalf("first publish took %s; the hub waited on the stalled client", elapsed)
+ }
+ if elapsed := send(); elapsed > 150*time.Millisecond {
+ t.Fatalf("second publish took %s; a full or stalled client blocked the hub", elapsed)
+ }
+
+ deadline := time.Now().Add(time.Second)
+ for healthy.count() < 2 && time.Now().Before(deadline) {
+ time.Sleep(5 * time.Millisecond)
+ }
+ if healthy.count() < 2 {
+ t.Fatalf("healthy client received %d of 2 broadcasts while another client was stalled", healthy.count())
+ }
+}
+
+func TestWebsocketRejectsUntrustedOrigin(t *testing.T) {
+ app := fiber.New()
+ RegisterRoutes(app, nil)
+
+ ln, err := (&net.ListenConfig{}).Listen(t.Context(), "tcp", "127.0.0.1:0")
+ require.NoError(t, err)
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(func() {
+ cancel()
+ _ = ln.Close()
+ })
+ go func() {
+ _ = app.Listener(ln, fiber.ListenConfig{
+ DisableStartupMessage: true,
+ GracefulContext: ctx,
+ ShutdownTimeout: time.Second,
+ })
+ }()
+
+ endpoint := "ws://" + ln.Addr().String() + "/ws"
+ dialer := websocket.Dialer{HandshakeTimeout: time.Second}
+ var untrusted *websocket.Conn
+ var resp *http.Response
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ untrusted, resp, err = dialer.Dial(endpoint, http.Header{"Origin": []string{"https://evil.example"}})
+ if err == nil || resp != nil || time.Now().After(deadline) {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if untrusted != nil {
+ _ = untrusted.Close()
+ }
+ require.Error(t, err)
+ require.NotNil(t, resp)
+ require.Equal(t, fiber.StatusForbidden, resp.StatusCode)
+ _ = resp.Body.Close()
+
+ trustedOrigin := "http://" + ln.Addr().String()
+ conn, resp, err := dialer.Dial(endpoint, http.Header{"Origin": []string{trustedOrigin}})
+ if resp != nil && resp.Body != nil {
+ _ = resp.Body.Close()
+ }
+ require.NoError(t, err)
+ require.NotNil(t, conn)
+
+ // A TLS-terminating proxy forwards the dashboard's https origin over http.
+ proxied, resp, err := dialer.Dial(endpoint, http.Header{"Origin": []string{"https://" + ln.Addr().String()}})
+ if resp != nil && resp.Body != nil {
+ _ = resp.Body.Close()
+ }
+ require.NoError(t, err)
+ require.NotNil(t, proxied)
+
+ missing, resp, err := dialer.Dial(endpoint, nil)
+ if resp != nil && resp.Body != nil {
+ _ = resp.Body.Close()
+ }
+ require.NoError(t, err)
+ require.NotNil(t, missing)
+
+ // Each server handler must register and exit before the next test
+ // changes the globals it reads.
+ waitForSockets(t, 3)
+ _ = conn.Close()
+ _ = proxied.Close()
+ _ = missing.Close()
+ waitForSockets(t, 0)
+}