Repository navigation
Feat/vercel supabase hardening - #249
WorkiDigital wants to merge 30 commits into
Conversation
[WIP] Adaptação Evolution Go para Vercel Daemons + Supabase
…r-instance authentication
Reviewer's GuideSchema and migrationsCreate the private PostgreSQL command queue and schemas used by the gateway and daemon, and provision a private media bucket.
APIDefine the public gateway’s authenticated JSON routes, request limits, asynchronous job responses, and supported route allowlist.
Uses of the APIWire Supabase Storage selection, daemon-only health and singleton behavior, queued-command processing, and loopback listening into the existing Evolution Go process.
ImplementationEncrypt and decrypt queued API keys with AES-GCM so original credentials can be forwarded without storing them in plaintext.
Claim queued commands, dispatch them through the in-process router, persist results, and hold and monitor the daemon singleton lock.
Implement private Supabase Storage uploads, deletes, and signed URLs while validating project origins and object paths.
ConfigurationAdd container build definitions for the gateway and daemon and Vercel routing and daemon configuration.
Provide an example environment-variable configuration for the Vercel and Supabase deployment.
Add CI checks for bridge and storage tests, Go and image builds, and Vercel JSON syntax.
DocumentationDocument the experimental deployment architecture, API contract, setup, licensing, security, and operational limitations.
TestsCheck gateway route allowlisting and ensure unauthenticated requests are rejected before database access.
Test encryption round trips, nonce freshness, tamper rejection, and invalid token-key handling.
Test Supabase Storage origin validation and object-path sanitization.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
There was a problem hiding this comment.
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
| // 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/", |
There was a problem hiding this comment.
🟡 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.| 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)) |
There was a problem hiding this comment.
🟡 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`.| 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)) |
There was a problem hiding this comment.
🟡 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`.| // 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")) |
There was a problem hiding this comment.
🟠 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.| // 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")) |
There was a problem hiding this comment.
🟡 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`.| var mediaStorage storage_interfaces.MediaStorage | ||
| var err error | ||
| if config.MinioEnabled { | ||
| if os.Getenv("SUPABASE_URL") != "" { |
There was a problem hiding this comment.
🟠 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`.| } | ||
|
|
||
| listenAddr := ":" + os.Getenv("SERVER_PORT") | ||
| if daemonMode { listenAddr = "127.0.0.1:" + os.Getenv("SERVER_PORT") } |
There was a problem hiding this comment.
🟠 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.| db.SetMaxOpenConns(8) | ||
| db.SetMaxIdleConns(2) | ||
| db.SetConnMaxLifetime(4*time.Minute) | ||
| if err := db.Ping(); err != nil { log.Fatalf("database connection failed: %v", err) } |
There was a problem hiding this comment.
🟡 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.| 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 } |
There was a problem hiding this comment.
🟡 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.| 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 |
There was a problem hiding this comment.
🟡 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`.
Description
Related Issue
Closes #(issue_number)
Type of Change
Testing
Screenshots (if applicable)
Checklist
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:
Enhancements:
Build:
CI:
Documentation:
Tests:
Chores: