Skip to content

Feat/vercel supabase hardening - #249

Open
WorkiDigital wants to merge 30 commits into
evolution-foundation:mainfrom
WorkiDigital:feat/vercel-supabase-hardening
Open

WorkiDigital wants to merge 30 commits into
evolution-foundation:mainfrom
WorkiDigital:feat/vercel-supabase-hardening

Conversation

@WorkiDigital

@WorkiDigital WorkiDigital commented Nov 23, 2026 •

Copy link
Copy Markdown

Description

Related Issue

Closes #(issue_number)

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Refactoring (no functional changes)
  • Performance improvement

Testing

  • Manual testing completed
  • Functionality verified in development environment
  • No breaking changes introduced

Screenshots (if applicable)

Checklist

  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have tested my changes thoroughly
  • Any dependent changes have been merged and published

Additional Notes

Summary by Sourcery

Deploy Evolution Go through a hardened Vercel gateway and Supabase-backed daemon bridge while preserving WhatsApp session ownership and upstream authentication.

New Features:

  • Add a Vercel-hosted stateless API gateway that queues authenticated Evolution Go JSON commands for an always-on daemon.
  • Add daemon-mode operation with Supabase PostgreSQL-backed command processing and singleton protection for WhatsApp sessions.
  • Add private Supabase Storage support for Evolution Go media.
  • Add deployment configuration and setup guidance for running the gateway and daemon on Vercel with Supabase.

Enhancements:

  • Harden the bridge with layered authentication, encrypted queued API keys, route restrictions, request and response limits, idempotency handling, and loopback-only daemon access.

Build:

  • Add dedicated Docker images and Vercel configuration for the API gateway and daemon.

CI:

  • Add CI coverage for bridge and storage tests, daemon and container builds, and Vercel configuration validation.

Documentation:

  • Document the experimental Vercel/Supabase architecture, API contract, setup, licensing, security considerations, and operational limitations.

Tests:

  • Add tests covering supported bridge routes, unauthorized access, encrypted API-key handling, and Supabase storage configuration and path validation.

Chores:

  • Add Supabase schema initialization for application, authentication, and private bridge command storage.

[WIP] Adaptação Evolution Go para Vercel Daemons + Supabase
@sourcery-ai

sourcery-ai Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Schema and migrations

Create the private PostgreSQL command queue and schemas used by the gateway and daemon, and provision a private media bucket.

  • deploy/supabase-setup.sql L1-34

API

Define the public gateway’s authenticated JSON routes, request limits, asynchronous job responses, and supported route allowlist.

  • cmd/vercel-api/main.go L1-209

Uses of the API

Wire Supabase Storage selection, daemon-only health and singleton behavior, queued-command processing, and loopback listening into the existing Evolution Go process.

  • cmd/evolution-go/main.go L149-157, L374-390, L455-465 (+3 small edits)

Implementation

Encrypt and decrypt queued API keys with AES-GCM so original credentials can be forwarded without storing them in plaintext.

  • pkg/vercelbridge/auth.go L1-41

Claim queued commands, dispatch them through the in-process router, persist results, and hold and monitor the daemon singleton lock.

  • pkg/vercelbridge/worker.go L1-176

Implement private Supabase Storage uploads, deletes, and signed URLs while validating project origins and object paths.

  • pkg/storage/supabase/media_storage.go L1-112

Configuration

Add container build definitions for the gateway and daemon and Vercel routing and daemon configuration.

  • Dockerfile.vercel-api L1-14
  • Dockerfile.vercel-daemon L1-19
  • vercel.json L1-28

Provide an example environment-variable configuration for the Vercel and Supabase deployment.

  • deploy/vercel.env.example L1-31

Add CI checks for bridge and storage tests, Go and image builds, and Vercel JSON syntax.

  • .github/workflows/vercel-bridge-ci.yml L1-36

Documentation

Document the experimental deployment architecture, API contract, setup, licensing, security, and operational limitations.

  • deploy/VERCEL_SUPABASE.md L1-77

Tests

Check gateway route allowlisting and ensure unauthenticated requests are rejected before database access.

  • cmd/vercel-api/main_test.go L1-45

Test encryption round trips, nonce freshness, tamper rejection, and invalid token-key handling.

  • pkg/vercelbridge/auth_test.go L1-28

Test Supabase Storage origin validation and object-path sanitization.

  • pkg/storage/supabase/media_storage_test.go L1-25

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 14 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="cmd/vercel-api/main.go" line_range="200" />
<code_context>
+    // Explicitly omit /manager, /ws, /assets, /passkey and all license routes.
+    if p=="/server/ok" { return true }
+    for _,prefix:=range []string{
+        "/instance/","/send/","/message/","/group/","/chat/","/user/",
+        "/community/","/label/","/unlabel/","/newsletter/","/call/","/polls/",
+    } {
</code_context>
<issue_to_address>
**Media URLs reach private services**

When a caller with a valid instance API key submits `/send/media` with a URL targeting a private or metadata service, `ServeHTTP` queues authenticated `/send/media` requests and `RunWorker` dispatches them through the daemon router; `SendMediaUrl` then fetches the caller-supplied URL with `http.Get` without checking its destination, letting a caller use the daemon to reach private network services and send fetched media through WhatsApp.

Restrict media fetches to approved public destinations and revalidate resolved addresses and redirect targets before connecting.
</issue_to_address>

### Comment 2
<location path="cmd/vercel-api/main.go" line_range="113" />
<code_context>
+    id:=uuid.New()
+    if key := strings.TrimSpace(r.Header.Get("X-Idempotency-Key")); key!="" {
+        if len(key)>128 { http.Error(w,"idempotency key too long",400); return }
+        id=uuid.NewSHA1(uuid.NameSpaceOID,[]byte(r.Method+"\n"+uri+"\n"+key))
+    }
+    _,err=g.db.ExecContext(r.Context(),`
</code_context>
<issue_to_address>
**Callers read other instances’ results**

When clients for different instances share the bridge secret and one learns or guesses another instance’s job ID, `lookup` selects by job ID alone, and `writeJob` returns that row without checking the caller’s instance `apikey`, so the caller receives another instance’s response body.

Bind job lookups to the authenticated instance and verify ownership before returning a result.

Also at `cmd/vercel-api/main.go:155-157`, `cmd/vercel-api/main.go:166`.
</issue_to_address>

### Comment 3
<location path="cmd/vercel-api/main.go" line_range="113" />
<code_context>
+    id:=uuid.New()
+    if key := strings.TrimSpace(r.Header.Get("X-Idempotency-Key")); key!="" {
+        if len(key)>128 { http.Error(w,"idempotency key too long",400); return }
+        id=uuid.NewSHA1(uuid.NameSpaceOID,[]byte(r.Method+"\n"+uri+"\n"+key))
+    }
+    _,err=g.db.ExecContext(r.Context(),`
</code_context>
<issue_to_address>
**Idempotency keys collide across callers**

When different callers or instances reuse the same idempotency key for the same method and URI, the deterministic job ID uses only the method, URI, and key, while `request_sha256` includes the instance `apikey`; the second insert conflicts with the first row and returns 409 instead of queueing its command.

Include caller identity in the deterministic job ID, or otherwise scope idempotency keys to the caller.

Also at `deploy/supabase-setup.sql:11`.
</issue_to_address>

### Comment 4
<location path="cmd/evolution-go/main.go" line_range="459" />
<code_context>
+		// Worker dispatches queued requests through the authenticated Gin router.
+		sqlDB, err := db.DB()
+		if err != nil { log.Fatal(err) }
+		go vercelbridge.RunWorker(heartbeatCtx, sqlDB, r, os.Getenv("BRIDGE_TOKEN_KEY"))
+	}

</code_context>
<issue_to_address>
**Startup races instance initialization**

When a queued command causes `StartInstance` for an instance while the startup loop is starting that same instance, the worker can dispatch an instance command while `ConnectOnStartup` is still calling `StartInstance` for that same instance. Both calls write `killChannel[instance.Id]` without synchronization in `StartInstance`, so concurrent map access can crash the daemon before the command completes.

Serialize instance startup or protect `killChannel` and related shared client state with synchronization.
</issue_to_address>

### Comment 5
<location path="cmd/evolution-go/main.go" line_range="459" />
<code_context>
+		// Worker dispatches queued requests through the authenticated Gin router.
+		sqlDB, err := db.DB()
+		if err != nil { log.Fatal(err) }
+		go vercelbridge.RunWorker(heartbeatCtx, sqlDB, r, os.Getenv("BRIDGE_TOKEN_KEY"))
+	}

</code_context>
<issue_to_address>
**Commands remain stuck after shutdown**

When a deployment or termination signal arrives while a command is being handled, `main` cancels the worker but does not wait for the in-flight handler to finish before exiting; the claimed command can remain `processing`, so polling clients never receive a final result and the command is not retried.

Drain or join the worker during shutdown, and ensure interrupted commands are made available for retry.

Also at `pkg/vercelbridge/worker.go:63-67`.
</issue_to_address>

### Comment 6
<location path="cmd/evolution-go/main.go" line_range="385-387" />
<code_context>
+		if err != nil { log.Fatalf("[vercelbridge] refusing to start duplicate WhatsApp engine: %v", err) }
+		defer lock.Close()
+		go func() {
+			if err := vercelbridge.MonitorSingleton(singletonCtx, lock); err != nil {
+				log.Printf("[vercelbridge] FATAL: %v; terminating daemon", err)
+				_ = syscall.Kill(os.Getpid(), syscall.SIGTERM)
+			}
+		}()
</code_context>
<issue_to_address>
**Lost lock permits overlapping daemons**

When the lock connection is lost while WhatsApp clients remain connected, the database releases the session advisory lock when its pinned connection is lost, so a replacement daemon can acquire the lock while this process still has live WhatsApp clients. `MonitorSingleton` only then sends `SIGTERM`; the old daemon can continue running those clients during shutdown, producing overlapping sessions.

Make loss of the singleton lock stop or fence WhatsApp activity before another daemon can take over, rather than relying only on asynchronous process shutdown.
</issue_to_address>

### Comment 7
<location path="pkg/vercelbridge/worker.go" line_range="108" />
<code_context>
+        code = result.StatusCode
+        contentType = result.Header.Get("Content-Type")
+        if contentType == "" { contentType = "application/json" }
+        if rec.Body.Len() > MaxResponseBytes {
+            code = http.StatusRequestEntityTooLarge
+            body = []byte("response exceeds 1 MiB bridge limit")
</code_context>
<issue_to_address>
**Large responses exhaust daemon memory**

When a supported route returns a response substantially larger than 1 MiB, `process` runs `router.ServeHTTP` into an `httptest.ResponseRecorder`, which buffers the complete body before checking `MaxResponseBytes`; the daemon can exhaust memory before enforcing the limit.

Enforce the response limit while the router writes the body rather than after buffering the complete response.

Also at `pkg/vercelbridge/worker.go:90`.
</issue_to_address>

### Comment 8
<location path="pkg/vercelbridge/worker.go" line_range="108-112" />
<code_context>
+        code = result.StatusCode
+        contentType = result.Header.Get("Content-Type")
+        if contentType == "" { contentType = "application/json" }
+        if rec.Body.Len() > MaxResponseBytes {
+            code = http.StatusRequestEntityTooLarge
+            body = []byte("response exceeds 1 MiB bridge limit")
+            contentType = "text/plain"
+            return
+        }
+        body = append([]byte(nil), rec.Body.Bytes()...)
</code_context>
<issue_to_address>
**Completed writes appear rejected**

When a mutating command succeeds but its response exceeds 1 MiB, the Gin handler has already run before `process` checks the buffered response size. When it exceeds 1 MiB, `process` records HTTP 413 instead of the handler’s result, so callers see a rejection even though the write took effect and can repeat it.

Represent oversized successful responses as completed writes with an explicit unavailable or truncated response, rather than reporting that the request was rejected.
</issue_to_address>

### Comment 9
<location path="pkg/vercelbridge/worker.go" line_range="102" />
<code_context>
+                log.Printf("[vercelbridge] handler panic for command %s: %v", c.ID, r)
+            }
+        }()
+        router.ServeHTTP(rec, req)
+        result := rec.Result()
+        defer result.Body.Close()
</code_context>
<issue_to_address>
**Later commands stop progressing**

When a dispatched handler or downstream operation blocks beyond 45 seconds without observing the request context, `router.ServeHTTP` runs synchronously, and canceling `runCtx` cannot stop a handler or downstream call that ignores the request context; the sole worker remains blocked and later queued commands go unprocessed.

Make dispatched handlers and downstream operations honor request-context cancellation so the worker can resume processing queued commands.

Also at `pkg/vercelbridge/worker.go:49`, `pkg/vercelbridge/worker.go:81-83`, `cmd/vercel-api/main.go:200`.
</issue_to_address>

### Comment 10
<location path="cmd/evolution-go/main.go" line_range="149" />
<code_context>
 	var mediaStorage storage_interfaces.MediaStorage
 	var err error
-	if config.MinioEnabled {
+	if os.Getenv("SUPABASE_URL") != "" {
+		if config.MinioEnabled { log.Fatal("enable either Supabase Storage or MinIO, not both") }
+		mediaStorage, err = supabase_storage.New(
</code_context>
<issue_to_address>
**Supabase media is not stored**

When supabase Storage is configured with the documented `MINIO_ENABLED=false` setting, `myEventHandler` calls `MediaStorage.Store` only when `config.MinioEnabled` is true, so it takes the base64 fallback instead; media is not saved to Supabase and callers do not receive the storage URL.

Have the media handler use the configured storage adapter instead of gating storage on `config.MinioEnabled`.

Also at `cmd/evolution-go/main.go:151-156`.
</issue_to_address>

### Comment 11
<location path="cmd/evolution-go/main.go" line_range="463" />
<code_context>
+	}

+	listenAddr := ":" + os.Getenv("SERVER_PORT")
+	if daemonMode { listenAddr = "127.0.0.1:" + os.Getenv("SERVER_PORT") }
 	srv := &http.Server{
-		Addr:    ":" + os.Getenv("SERVER_PORT"),
</code_context>
<issue_to_address>
**Liveness probe cannot reach daemon**

When vercel’s liveness probe connects through the container network interface, `ListenAndServe` binds the daemon to `127.0.0.1`, so the probe cannot reach `/_bridge/health` through the container address and Vercel restarts the daemon.

Bind the daemon to an address reachable through the container network interface.
</issue_to_address>

### Comment 12
<location path="cmd/vercel-api/main.go" line_range="54" />
<code_context>
+    db.SetMaxOpenConns(8)
+    db.SetMaxIdleConns(2)
+    db.SetConnMaxLifetime(4*time.Minute)
+    if err := db.Ping(); err != nil { log.Fatalf("database connection failed: %v", err) }
+    port := os.Getenv("PORT")
+    if port == "" { port = "8080" }
</code_context>
<issue_to_address>
**Database outage hangs gateway startup**

When the configured PostgreSQL endpoint silently drops or stalls connection attempts, `db.Ping()` has no deadline, so a PostgreSQL connection attempt that stalls leaves the process blocked before it starts listening. The gateway stays unavailable instead of failing within a bounded time or becoming available after the database recovers.

Use a bounded `PingContext` and a bounded retry policy before starting the server.
</issue_to_address>

### Comment 13
<location path="cmd/vercel-api/main.go" line_range="104" />
<code_context>
+    if len(data)>maxRequestBytes { http.Error(w,"request exceeds 256 KiB",413); return }
+
+    authKey:=r.Header.Get("apikey")
+    if authKey=="" || len(authKey)>4096 { http.Error(w,"missing or invalid apikey",401); return }
+    encrypted,err:=vercelbridge.SealAPIKey(authKey,g.tokenKeyHex)
+    if err!=nil { http.Error(w,"bridge key configuration invalid",503); return }
</code_context>
<issue_to_address>
**Daemon health check requires an instance key**

When A health-check caller sends the documented bridge key but omits an instance `apikey`, `ServeHTTP` requires an `apikey` for every queued route, but `/server/ok` is registered without instance authentication and the documented header contract requires an instance key only for instance routes. A caller using only the bridge key therefore gets 401 instead of the daemon health response.

Handle `/server/ok` separately or exempt it from the per-instance `apikey` requirement while retaining bridge authentication.
</issue_to_address>

### Comment 14
<location path="deploy/supabase-setup.sql" line_range="10-24" />
<code_context>
+CREATE SCHEMA IF NOT EXISTS evo_bridge;
+REVOKE ALL ON SCHEMA evo_app, evo_auth, evo_bridge FROM PUBLIC;
+REVOKE ALL ON SCHEMA evo_app, evo_auth, evo_bridge FROM anon, authenticated;
+CREATE TABLE IF NOT EXISTS evo_bridge.commands (
+    id uuid PRIMARY KEY,
+    method text NOT NULL CHECK (method IN ('GET','POST','PUT','PATCH','DELETE')),
+    request_path text NOT NULL,
+    request_body bytea NOT NULL DEFAULT '\x'::bytea,
+    request_sha256 text NOT NULL,
+    auth_ciphertext bytea NOT NULL,
+    state text NOT NULL DEFAULT 'queued'
+      CHECK (state IN ('queued','processing','finished')),
+    response_code integer,
+    response_body bytea,
+    response_type text,
+    created_at timestamptz NOT NULL DEFAULT now(),
+    started_at timestamptz,
+    finished_at timestamptz
+);
+CREATE INDEX IF NOT EXISTS evo_bridge_commands_queue_idx
</code_context>
<issue_to_address>
**Command rows consume database quota**

When the deployment processes commands without an independently configured retention policy, the setup and gateway retain request and response data in `evo_bridge.commands` without deleting completed jobs, so the table grows until database quota is consumed and new commands fail with 503.

Add a retention policy that deletes completed command rows and their payloads.

Also at `cmd/vercel-api/main.go:116`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 14 findings to address first, and the gateway queues authenticated commands that the daemon executes against the WhatsApp engine, including message sends and group or instance mutations. If a command is wrongly authorized or dispatched, a message may already be sent or state changed; reverting the code cannot undo those effects.

Blocking findings: cmd/vercel-api/main.go:200, cmd/vercel-api/main.go:113, cmd/vercel-api/main.go:113, cmd/evolution-go/main.go:459, cmd/evolution-go/main.go:459, and 9 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread cmd/vercel-api/main.go
// Explicitly omit /manager, /ws, /assets, /passkey and all license routes.
if p=="/server/ok" { return true }
for _,prefix:=range []string{
"/instance/","/send/","/message/","/group/","/chat/","/user/",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Media URLs reach private services

When a caller with a valid instance API key submits /send/media with a URL targeting a private or metadata service, ServeHTTP queues authenticated /send/media requests and RunWorker dispatches them through the daemon router; SendMediaUrl then fetches the caller-supplied URL with http.Get without checking its destination, letting a caller use the daemon to reach private network services and send fetched media through WhatsApp.

Restrict media fetches to approved public destinations and revalidate resolved addresses and redirect targets before connecting.

Prompt for AI agents
In `cmd/vercel-api/main.go` at line 200:

**Media URLs reach private services**

When a caller with a valid instance API key submits `/send/media` with a URL targeting a private or metadata service, `ServeHTTP` queues authenticated `/send/media` requests and `RunWorker` dispatches them through the daemon router; `SendMediaUrl` then fetches the caller-supplied URL with `http.Get` without checking its destination, letting a caller use the daemon to reach private network services and send fetched media through WhatsApp.

Restrict media fetches to approved public destinations and revalidate resolved addresses and redirect targets before connecting.

Comment thread cmd/vercel-api/main.go
id:=uuid.New()
if key := strings.TrimSpace(r.Header.Get("X-Idempotency-Key")); key!="" {
if len(key)>128 { http.Error(w,"idempotency key too long",400); return }
id=uuid.NewSHA1(uuid.NameSpaceOID,[]byte(r.Method+"\n"+uri+"\n"+key))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Callers read other instances’ results

When clients for different instances share the bridge secret and one learns or guesses another instance’s job ID, lookup selects by job ID alone, and writeJob returns that row without checking the caller’s instance apikey, so the caller receives another instance’s response body.

Bind job lookups to the authenticated instance and verify ownership before returning a result.

Also at cmd/vercel-api/main.go:155-157, cmd/vercel-api/main.go:166.

Prompt for AI agents
In `cmd/vercel-api/main.go` at line 113:

**Callers read other instances’ results**

When clients for different instances share the bridge secret and one learns or guesses another instance’s job ID, `lookup` selects by job ID alone, and `writeJob` returns that row without checking the caller’s instance `apikey`, so the caller receives another instance’s response body.

Bind job lookups to the authenticated instance and verify ownership before returning a result.

Also at `cmd/vercel-api/main.go:155-157`, `cmd/vercel-api/main.go:166`.

Comment thread cmd/vercel-api/main.go
id:=uuid.New()
if key := strings.TrimSpace(r.Header.Get("X-Idempotency-Key")); key!="" {
if len(key)>128 { http.Error(w,"idempotency key too long",400); return }
id=uuid.NewSHA1(uuid.NameSpaceOID,[]byte(r.Method+"\n"+uri+"\n"+key))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Idempotency keys collide across callers

When different callers or instances reuse the same idempotency key for the same method and URI, the deterministic job ID uses only the method, URI, and key, while request_sha256 includes the instance apikey; the second insert conflicts with the first row and returns 409 instead of queueing its command.

Include caller identity in the deterministic job ID, or otherwise scope idempotency keys to the caller.

Also at deploy/supabase-setup.sql:11.

Prompt for AI agents
In `cmd/vercel-api/main.go` at line 113:

**Idempotency keys collide across callers**

When different callers or instances reuse the same idempotency key for the same method and URI, the deterministic job ID uses only the method, URI, and key, while `request_sha256` includes the instance `apikey`; the second insert conflicts with the first row and returns 409 instead of queueing its command.

Include caller identity in the deterministic job ID, or otherwise scope idempotency keys to the caller.

Also at `deploy/supabase-setup.sql:11`.

Comment thread cmd/evolution-go/main.go
// Worker dispatches queued requests through the authenticated Gin router.
sqlDB, err := db.DB()
if err != nil { log.Fatal(err) }
go vercelbridge.RunWorker(heartbeatCtx, sqlDB, r, os.Getenv("BRIDGE_TOKEN_KEY"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Startup races instance initialization

When a queued command causes StartInstance for an instance while the startup loop is starting that same instance, the worker can dispatch an instance command while ConnectOnStartup is still calling StartInstance for that same instance. Both calls write killChannel[instance.Id] without synchronization in StartInstance, so concurrent map access can crash the daemon before the command completes.

Serialize instance startup or protect killChannel and related shared client state with synchronization.

Prompt for AI agents
In `cmd/evolution-go/main.go` at line 459:

**Startup races instance initialization**

When a queued command causes `StartInstance` for an instance while the startup loop is starting that same instance, the worker can dispatch an instance command while `ConnectOnStartup` is still calling `StartInstance` for that same instance. Both calls write `killChannel[instance.Id]` without synchronization in `StartInstance`, so concurrent map access can crash the daemon before the command completes.

Serialize instance startup or protect `killChannel` and related shared client state with synchronization.

Comment thread cmd/evolution-go/main.go
// Worker dispatches queued requests through the authenticated Gin router.
sqlDB, err := db.DB()
if err != nil { log.Fatal(err) }
go vercelbridge.RunWorker(heartbeatCtx, sqlDB, r, os.Getenv("BRIDGE_TOKEN_KEY"))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Commands remain stuck after shutdown

When a deployment or termination signal arrives while a command is being handled, main cancels the worker but does not wait for the in-flight handler to finish before exiting; the claimed command can remain processing, so polling clients never receive a final result and the command is not retried.

Drain or join the worker during shutdown, and ensure interrupted commands are made available for retry.

Also at pkg/vercelbridge/worker.go:63-67.

Prompt for AI agents
In `cmd/evolution-go/main.go` at line 459:

**Commands remain stuck after shutdown**

When a deployment or termination signal arrives while a command is being handled, `main` cancels the worker but does not wait for the in-flight handler to finish before exiting; the claimed command can remain `processing`, so polling clients never receive a final result and the command is not retried.

Drain or join the worker during shutdown, and ensure interrupted commands are made available for retry.

Also at `pkg/vercelbridge/worker.go:63-67`.

Comment thread cmd/evolution-go/main.go
var mediaStorage storage_interfaces.MediaStorage
var err error
if config.MinioEnabled {
if os.Getenv("SUPABASE_URL") != "" {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Supabase media is not stored

When supabase Storage is configured with the documented MINIO_ENABLED=false setting, myEventHandler calls MediaStorage.Store only when config.MinioEnabled is true, so it takes the base64 fallback instead; media is not saved to Supabase and callers do not receive the storage URL.

Have the media handler use the configured storage adapter instead of gating storage on config.MinioEnabled.

Also at cmd/evolution-go/main.go:151-156.

Prompt for AI agents
In `cmd/evolution-go/main.go` at line 149:

**Supabase media is not stored**

When supabase Storage is configured with the documented `MINIO_ENABLED=false` setting, `myEventHandler` calls `MediaStorage.Store` only when `config.MinioEnabled` is true, so it takes the base64 fallback instead; media is not saved to Supabase and callers do not receive the storage URL.

Have the media handler use the configured storage adapter instead of gating storage on `config.MinioEnabled`.

Also at `cmd/evolution-go/main.go:151-156`.

Comment thread cmd/evolution-go/main.go
}

listenAddr := ":" + os.Getenv("SERVER_PORT")
if daemonMode { listenAddr = "127.0.0.1:" + os.Getenv("SERVER_PORT") }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Liveness probe cannot reach daemon

When vercel’s liveness probe connects through the container network interface, ListenAndServe binds the daemon to 127.0.0.1, so the probe cannot reach /_bridge/health through the container address and Vercel restarts the daemon.

Bind the daemon to an address reachable through the container network interface.

Prompt for AI agents
In `cmd/evolution-go/main.go` at line 463:

**Liveness probe cannot reach daemon**

When vercel’s liveness probe connects through the container network interface, `ListenAndServe` binds the daemon to `127.0.0.1`, so the probe cannot reach `/_bridge/health` through the container address and Vercel restarts the daemon.

Bind the daemon to an address reachable through the container network interface.

Comment thread cmd/vercel-api/main.go
db.SetMaxOpenConns(8)
db.SetMaxIdleConns(2)
db.SetConnMaxLifetime(4*time.Minute)
if err := db.Ping(); err != nil { log.Fatalf("database connection failed: %v", err) }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Database outage hangs gateway startup

When the configured PostgreSQL endpoint silently drops or stalls connection attempts, db.Ping() has no deadline, so a PostgreSQL connection attempt that stalls leaves the process blocked before it starts listening. The gateway stays unavailable instead of failing within a bounded time or becoming available after the database recovers.

Use a bounded PingContext and a bounded retry policy before starting the server.

Prompt for AI agents
In `cmd/vercel-api/main.go` at line 54:

**Database outage hangs gateway startup**

When the configured PostgreSQL endpoint silently drops or stalls connection attempts, `db.Ping()` has no deadline, so a PostgreSQL connection attempt that stalls leaves the process blocked before it starts listening. The gateway stays unavailable instead of failing within a bounded time or becoming available after the database recovers.

Use a bounded `PingContext` and a bounded retry policy before starting the server.

Comment thread cmd/vercel-api/main.go
if len(data)>maxRequestBytes { http.Error(w,"request exceeds 256 KiB",413); return }

authKey:=r.Header.Get("apikey")
if authKey=="" || len(authKey)>4096 { http.Error(w,"missing or invalid apikey",401); return }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Daemon health check requires an instance key

When A health-check caller sends the documented bridge key but omits an instance apikey, ServeHTTP requires an apikey for every queued route, but /server/ok is registered without instance authentication and the documented header contract requires an instance key only for instance routes. A caller using only the bridge key therefore gets 401 instead of the daemon health response.

Handle /server/ok separately or exempt it from the per-instance apikey requirement while retaining bridge authentication.

Prompt for AI agents
In `cmd/vercel-api/main.go` at line 104:

**Daemon health check requires an instance key**

When A health-check caller sends the documented bridge key but omits an instance `apikey`, `ServeHTTP` requires an `apikey` for every queued route, but `/server/ok` is registered without instance authentication and the documented header contract requires an instance key only for instance routes. A caller using only the bridge key therefore gets 401 instead of the daemon health response.

Handle `/server/ok` separately or exempt it from the per-instance `apikey` requirement while retaining bridge authentication.

Comment thread deploy/supabase-setup.sql
Comment on lines +10 to +24
CREATE TABLE IF NOT EXISTS evo_bridge.commands (
id uuid PRIMARY KEY,
method text NOT NULL CHECK (method IN ('GET','POST','PUT','PATCH','DELETE')),
request_path text NOT NULL,
request_body bytea NOT NULL DEFAULT '\x'::bytea,
request_sha256 text NOT NULL,
auth_ciphertext bytea NOT NULL,
state text NOT NULL DEFAULT 'queued'
CHECK (state IN ('queued','processing','finished')),
response_code integer,
response_body bytea,
response_type text,
created_at timestamptz NOT NULL DEFAULT now(),
started_at timestamptz,
finished_at timestamptz

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Command rows consume database quota

When the deployment processes commands without an independently configured retention policy, the setup and gateway retain request and response data in evo_bridge.commands without deleting completed jobs, so the table grows until database quota is consumed and new commands fail with 503.

Add a retention policy that deletes completed command rows and their payloads.

Also at cmd/vercel-api/main.go:116.

Prompt for AI agents
In `deploy/supabase-setup.sql` at lines 10-24:

**Command rows consume database quota**

When the deployment processes commands without an independently configured retention policy, the setup and gateway retain request and response data in `evo_bridge.commands` without deleting completed jobs, so the table grows until database quota is consumed and new commands fail with 503.

Add a retention policy that deletes completed command rows and their payloads.

Also at `cmd/vercel-api/main.go:116`.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant