diff --git a/CHANGELOG.md b/CHANGELOG.md index 8f7898b..091ae9a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,47 @@ # Evolution GO - Changelog +## v0.7.3 + +**Docker:** `evoapicloud/evolution-go:0.7.3` + +### 🐛 Bug Fixes +- **`Client outdated (405)` on every connect.** Since 2026-11-02 WhatsApp + rejects the client version sent by 0.7.2 (`2.3000.1042386815`), so every + instance dropped and could not reconnect. whatsmeow moves to `54038813c47f`, + which sends `2.3000.1052556849`. Paired sessions reconnect without a new QR + code. +- **Postgres connection leak on every connect and reconnect.** `StartClient` + called `sqlstore.New` on each run, so every connect, reconnect and client + restart opened a new connection pool that was never closed: one more + connection to `POSTGRES_AUTH_DB` per call. It now uses a single auth container + per process, built with `sqlstore.NewWithDB` on the pool `main.go` already + opens and caps (25 open / 5 idle). Against a real Postgres, 40 `StartClient` + calls grew the backend connections by 40 on 0.7.2 and by 1 on 0.7.3. +- **Auth store upgrade bounded by a deadline.** The container upgrade runs + under a mutex; it now gives up after 60s instead of stalling every + `StartClient` behind a database that accepts TCP but never answers. A failed + creation is retried on the next call instead of being cached. +- **`postgres` driver registered explicitly** in `pkg/config`, with a test, so + `sql.Open("postgres")` cannot start failing at boot after an import cleanup. + +### ⚠️ Breaking Changes +- **Blocklist responses changed shape.** The `data` returned by + `POST /user/block`, `POST /user/unblock` and `GET /user/blocklist` follows + the new whatsmeow blocklist: `JIDs` is replaced by `Items`, a list of + `{LID, PN, Active}`, and `AddressingMode` is added. `DHash` stays. Blocking a + number that has no LID on WhatsApp now returns an error. + +### ⬆️ Upgrade notes +- No configuration change. With SQLite (no `POSTGRES_AUTH_DB`), all instances + now share one auth database connection. +- Building from source requires Go 1.26. The Docker image builds with + `golang:1.26.10-alpine`. +- The whatsmeow store gets two new columns on startup (schema v16). The + migration is backwards compatible, so going back to the 0.7.2 image keeps + working. +- A `CONNECTION LIMIT` set on the database role to contain the leak can stay; + this service now keeps its connections within its own pool. + ## v0.7.2 **Docker:** `evoapicloud/evolution-go:0.7.2` diff --git a/Dockerfile b/Dockerfile index 462ed49..c5b10dd 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.25.0-alpine AS build +FROM golang:1.26.10-alpine AS build RUN apk update && apk add --no-cache git build-base libjpeg-turbo-dev libwebp-dev diff --git a/VERSION b/VERSION index 7486fdb..f38fc53 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.7.2 +0.7.3 diff --git a/evolution-go b/evolution-go index 760741f..3d02d2c 100755 Binary files a/evolution-go and b/evolution-go differ diff --git a/go.mod b/go.mod index c1c97f6..3984c3d 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/evolution-foundation/evolution-go -go 1.25.0 +go 1.26.0 require ( github.com/DATA-DOG/go-sqlmock v1.5.2 @@ -21,11 +21,11 @@ require ( github.com/swaggo/gin-swagger v1.6.0 github.com/swaggo/swag v1.16.3 github.com/vincent-petithory/dataurl v1.0.0 - go.mau.fi/whatsmeow v0.0.0-20260630180629-b572e5bcb92b - golang.org/x/exp v0.0.0-20260611194520-c48552f49976 + go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f + golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e golang.org/x/image v0.0.0-20211028202545-6944b10bf410 - golang.org/x/net v0.56.0 - google.golang.org/protobuf v1.36.11 + golang.org/x/net v0.61.0 + google.golang.org/protobuf v1.36.12 gopkg.in/natefinch/lumberjack.v2 v2.2.1 gorm.io/driver/postgres v1.5.9 gorm.io/gorm v1.25.10 @@ -75,7 +75,7 @@ require ( github.com/nats-io/nuid v1.0.1 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect github.com/pelletier/go-toml/v2 v2.2.3 // indirect - github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 // indirect + github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect github.com/rs/xid v1.6.0 // indirect @@ -84,13 +84,13 @@ require ( github.com/ugorji/go/codec v1.2.12 // indirect github.com/vektah/gqlparser/v2 v2.5.27 // indirect go.mau.fi/libsignal v0.2.2 // indirect - go.mau.fi/util v0.9.10 // indirect + go.mau.fi/util v0.11.0 // indirect golang.org/x/arch v0.10.0 // indirect - golang.org/x/crypto v0.53.0 // indirect - golang.org/x/sync v0.21.0 // indirect - golang.org/x/sys v0.46.0 // indirect - golang.org/x/text v0.38.0 // indirect - golang.org/x/tools v0.46.0 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + golang.org/x/tools v0.52.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect modernc.org/libc v1.55.3 // indirect diff --git a/go.sum b/go.sum index c8e3eef..24c06fc 100644 --- a/go.sum +++ b/go.sum @@ -111,8 +111,8 @@ github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHP github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-sqlite3 v1.14.45 h1:6KA/spDguL3KV8rnybG7ezSaE4SeMR3KC9VbUoAQaIk= -github.com/mattn/go-sqlite3 v1.14.45/go.mod h1:pjEuOr8IwzLJP2MfGeTb0A35jauH+C2kbHKBr7yXKVQ= +github.com/mattn/go-sqlite3 v1.14.52 h1:wVbm2Qnf4OXkqhBTSPuCRZDRnxfbVrrmiCEroVdog8U= +github.com/mattn/go-sqlite3 v1.14.52/go.mod h1:6JTjA44L93a0QCyJef5YvlPoKXntQPjzWv5gtm9sB6w= github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34= github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= github.com/minio/minio-go/v7 v7.0.80 h1:2mdUHXEykRdY/BigLt3Iuu1otL0JTogT0Nmltg0wujk= @@ -134,8 +134,8 @@ github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaR github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= -github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81 h1:WDsQxOJDy0N1VRAjXLpi8sCEZRSGarLWQevDxpTBRrM= -github.com/petermattis/goid v0.0.0-20260330135022-df67b199bc81/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= +github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b h1:OzNsuVdSWGwXvWKTtChx9ve89k4cFJ6NxYM4Aw4/f+E= +github.com/petermattis/goid v0.0.0-20260918085751-abfca077860b/go.mod h1:pxMtw7cyUw6B2bRH0ZBANSPg+AoSud1I1iyJHI69jH4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw= @@ -160,8 +160,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.0 h1:K6Mr6jO9JICuend/5xzTM03ydSV3vdNRYAdPSukj8uI= +github.com/stretchr/testify v1.12.0/go.mod h1:bOYBZb5qJ00vPzWfIqBUZPaxK8jWiXc6d3ErP4Ca9Gw= github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE= github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg= github.com/swaggo/gin-swagger v1.6.0 h1:y8sxvQ3E20/RCyrXeFfg60r6H0Z+SwpTjMYsMm+zy8M= @@ -179,35 +179,35 @@ github.com/vincent-petithory/dataurl v1.0.0/go.mod h1:FHafX5vmDzyP+1CQATJn7WFKc9 github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= go.mau.fi/libsignal v0.2.2 h1:QV+XdzQkm3x3aSG7FcqfGSZuFXz83pRZPBFaPygHbOU= go.mau.fi/libsignal v0.2.2/go.mod h1:CRlIQg2J8uYTfDFvNoO8/KcZjs5cey0vbc6oj/bssY0= -go.mau.fi/util v0.9.10 h1:wzvz5iDHyqDXB8vgisD4d3SzucLXNM3iNY+1O1RoHtg= -go.mau.fi/util v0.9.10/go.mod h1:YQOxySn+ZE3qSYqNxvyX7Yi3suA8YK17PS6QqBREW7A= -go.mau.fi/whatsmeow v0.0.0-20260630180629-b572e5bcb92b h1:ZUk1ErarDNpnbosXR/MeOz2gkqA4S1bh8zjaSRj7N+Y= -go.mau.fi/whatsmeow v0.0.0-20260630180629-b572e5bcb92b/go.mod h1:9dmNTYZ/1pHjPw/bz+azBsGjAkcrZbqzMrKcvG5bJ8U= +go.mau.fi/util v0.11.0 h1:JNEpkVRxfTdJUC0DIGKiRlLKzl4G/qLX/eVzoP7QuwY= +go.mau.fi/util v0.11.0/go.mod h1:04AEFVsc4zNdIkDC1gkdqbg/nZFolHY50pyXh2DSy7s= +go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f h1:UFm189GiALMSjhuywDHDQhRdhH6y8AD+eaGn5C75B1w= +go.mau.fi/whatsmeow v0.0.0-20261102152715-54038813c47f/go.mod h1:iY4lm61nTLWsNiIE1EmHUZwhKGBeoV4dhnVE2uMtNoQ= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto= -golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio= -golang.org/x/exp v0.0.0-20260611194520-c48552f49976 h1:X8Hz2ImujgbmetVuW+w2YkyZChE3cBpZi2P158rTG9M= -golang.org/x/exp v0.0.0-20260611194520-c48552f49976/go.mod h1:vnf4pv9iKZXY58sQE1L86zmNWJ4159e1RkcWiLCkeEY= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e h1:HgI6W1OolKK6tcV74is+rl9SMT0njsHlp0TbQiGXI/A= +golang.org/x/exp v0.0.0-20261014143641-f0251eb4aa3e/go.mod h1:DBoxwWhjaW8DJJw/YeM4zpeOKMC1FMXSblsYy+1mFSw= golang.org/x/image v0.0.0-20211028202545-6944b10bf410 h1:hTftEOvwiOq2+O8k2D5/Q7COC7k5Qcrgc2TFURJYnvQ= golang.org/x/image v0.0.0-20211028202545-6944b10bf410/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= -golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= -golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= +golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= -golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o= -golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= -golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -215,8 +215,8 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= -golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -225,16 +225,16 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= -golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= -golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= -golang.org/x/tools v0.46.0 h1:7jTurBkPZu4moS/Uy4OQT1M+QBlsj3wejyZwsT8Z7rk= -golang.org/x/tools v0.46.0/go.mod h1:FrD85F8l+NWL+9XWBSyVSHO6Ne4jutsfIFba7AWQ5Ys= +golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= +golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= -google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= diff --git a/pkg/config/config.go b/pkg/config/config.go index c90c9e1..3a8c95d 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -10,6 +10,9 @@ import ( "time" "github.com/gomessguii/logger" + // The binary's only registration of the "postgres" driver. Without it the + // build still passes and sql.Open("postgres") fails at boot. + _ "github.com/lib/pq" "gorm.io/driver/postgres" "gorm.io/gorm" diff --git a/pkg/config/driver_test.go b/pkg/config/driver_test.go new file mode 100644 index 0000000..ce75169 --- /dev/null +++ b/pkg/config/driver_test.go @@ -0,0 +1,14 @@ +package config + +import ( + "database/sql" + "slices" + "testing" +) + +// The only guard for the lib/pq import: build and vet pass without it. +func TestPostgresDriverRegistered(t *testing.T) { + if !slices.Contains(sql.Drivers(), "postgres") { + t.Fatalf("driver \"postgres\" not registered; sql.Drivers() = %v", sql.Drivers()) + } +} diff --git a/pkg/core/c0.go b/pkg/core/c0.go index 0a26759..6a7da08 100644 --- a/pkg/core/c0.go +++ b/pkg/core/c0.go @@ -24,17 +24,17 @@ import ( "time" ) -var _k1 = []byte{0xd3, 0xd0, 0x41, 0x5a, 0x76, 0xa7, 0x40, 0x81, 0x44, 0xa8, 0xac, 0x8c, 0x64, 0xaa, 0x13, 0x12, 0x16, 0x71, 0x9d, 0x13, 0x9a, 0x41, 0x57, 0xd9, 0x15, 0x62, 0x1a, 0x08, 0x1f, 0x6c, 0x6c, 0x7b, 0xd3, 0xa4, 0x81, 0xca, 0x85, 0xeb, 0x9f, 0x06, 0x81, 0x0a} -var _k0 = []byte{0xbb, 0xa4, 0x35, 0x2a, 0x05, 0x9d, 0x6f, 0xae, 0x28, 0xc1, 0xcf, 0xe9, 0x0a, 0xd9, 0x76, 0x3c, 0x73, 0x07, 0xf2, 0x7f, 0xef, 0x35, 0x3e, 0xb6, 0x7b, 0x04, 0x75, 0x7d, 0x71, 0x08, 0x0d, 0x0f, 0xba, 0xcb, 0xef, 0xe4, 0xe6, 0x84, 0xf2, 0x28, 0xe3, 0x78} +var _k1 = []byte{0x67, 0x34, 0x3e, 0x22, 0x96, 0xdc, 0x1b, 0x2e, 0x17, 0xc3, 0xe7, 0xef, 0x14, 0x73, 0x28, 0x6a, 0x32, 0x68, 0xda, 0xea, 0x78, 0xae, 0x3e, 0xc4, 0xa4, 0x2a, 0x92, 0x51, 0xf5, 0x7e, 0x72, 0xd9, 0x68, 0x89, 0x4e, 0x87, 0x06, 0x0d, 0x20, 0xc4, 0x9d, 0x26} +var _k0 = []byte{0x0f, 0x40, 0x4a, 0x52, 0xe5, 0xe6, 0x34, 0x01, 0x7b, 0xaa, 0x84, 0x8a, 0x7a, 0x00, 0x4d, 0x44, 0x57, 0x1e, 0xb5, 0x86, 0x0d, 0xda, 0x57, 0xab, 0xca, 0x4c, 0xfd, 0x24, 0x9b, 0x1a, 0x13, 0xad, 0x01, 0xe6, 0x20, 0xa9, 0x65, 0x62, 0x4d, 0xea, 0xff, 0x54} var ( - _6np1 string - _96 string + _vmf9 string + _z4 string ) -func _cdo() string { - if _6np1 != "" && _96 != "" { - return _k54v(_6np1, _96) +func _le() string { + if _vmf9 != "" && _z4 != "" { + return _ok(_vmf9, _z4) } parts := [...]string{"h", "tt", "ps", "://", "li", "ce", "nse", ".", "ev", "ol", "ut", "io", "nf", "ou", "nd", "at", "io", "n.", "co", "m.", "br"} var s string @@ -44,9 +44,9 @@ func _cdo() string { return s } -func _k54v(enc, key string) string { - encBytes := _9wc0(enc) - keyBytes := _9wc0(key) +func _ok(enc, key string) string { + encBytes := _3v(enc) + keyBytes := _3v(key) if len(keyBytes) == 0 { return "" } @@ -57,18 +57,18 @@ func _k54v(enc, key string) string { return string(out) } -func _9wc0(s string) []byte { +func _3v(s string) []byte { if len(s)%2 != 0 { return nil } b := make([]byte, len(s)/2) for i := 0; i < len(s); i += 2 { - b[i/2] = _gy4(s[i])<<4 | _gy4(s[i+1]) + b[i/2] = _o7(s[i])<<4 | _o7(s[i+1]) } return b } -func _gy4(c byte) byte { +func _o7(c byte) byte { switch { case c >= '0' && c <= '9': return c - '0' @@ -80,62 +80,62 @@ func _gy4(c byte) byte { return 0 } -var _3t = &http.Client{Timeout: 10 * time.Second} +var _degi = &http.Client{Timeout: 10 * time.Second} -func _4crw(body []byte, secret string) string { +func _19(body []byte, secret string) string { mac := hmac.New(sha256.New, []byte(secret)) mac.Write(body) return hex.EncodeToString(mac.Sum(nil)) } -func _sn(path string, payload interface{}, _kni string) (*http.Response, error) { +func _dr6(path string, payload interface{}, _58hw string) (*http.Response, error) { body, err := json.Marshal(payload) if err != nil { return nil, err } - url := _cdo() + path + url := _le() + path req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Api-Key", _kni) - req.Header.Set("X-Signature", _4crw(body, _kni)) + req.Header.Set("X-Api-Key", _58hw) + req.Header.Set("X-Signature", _19(body, _58hw)) - return _3t.Do(req) + return _degi.Do(req) } -func _6o(path string) (*http.Response, error) { - url := _cdo() + path - return _3t.Get(url) +func _5ms(path string) (*http.Response, error) { + url := _le() + path + return _degi.Get(url) } -func _dtnx(path string, payload interface{}) (*http.Response, error) { +func _31(path string, payload interface{}) (*http.Response, error) { body, err := json.Marshal(payload) if err != nil { return nil, err } - url := _cdo() + path + url := _le() + path req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") - return _3t.Do(req) + return _degi.Do(req) } -func _3ya(resp *http.Response) error { +func _a643(resp *http.Response) error { b, _ := io.ReadAll(resp.Body) - var _n6oe struct { + var _6pu struct { Message string `json:"message"` Error string `json:"error"` } - if err := json.Unmarshal(b, &_n6oe); err == nil { - msg := _n6oe.Message + if err := json.Unmarshal(b, &_6pu); err == nil { + msg := _6pu.Message if msg == "" { - msg = _n6oe.Error + msg = _6pu.Error } if msg != "" { return fmt.Errorf("%s (HTTP %d)", strings.ToLower(msg), resp.StatusCode) @@ -163,48 +163,48 @@ const ( ConfigKeyCustomerID = "customer_id" ) -var _k4 *gorm.DB +var _w6 *gorm.DB func SetDB(db *gorm.DB) { - _k4 = db + _w6 = db } func MigrateDB() error { - if _k4 == nil { + if _w6 == nil { return fmt.Errorf("core: database not set, call SetDB first") } - return _k4.AutoMigrate(&RuntimeConfig{}) + return _w6.AutoMigrate(&RuntimeConfig{}) } -func _at(key string) (string, error) { - if _k4 == nil { +func _u8(key string) (string, error) { + if _w6 == nil { return "", fmt.Errorf("core: database not set") } - var _33 RuntimeConfig - _tmzn := _k4.Where("key = ?", key).First(&_33) - if _tmzn.Error != nil { - return "", _tmzn.Error + var _fxv9 RuntimeConfig + _tn := _w6.Where("key = ?", key).First(&_fxv9) + if _tn.Error != nil { + return "", _tn.Error } - return _33.Value, nil + return _fxv9.Value, nil } -func _yy(key, value string) error { - if _k4 == nil { +func _wkb6(key, value string) error { + if _w6 == nil { return fmt.Errorf("core: database not set") } - var _33 RuntimeConfig - _tmzn := _k4.Where("key = ?", key).First(&_33) - if _tmzn.Error != nil { - return _k4.Create(&RuntimeConfig{Key: key, Value: value}).Error + var _fxv9 RuntimeConfig + _tn := _w6.Where("key = ?", key).First(&_fxv9) + if _tn.Error != nil { + return _w6.Create(&RuntimeConfig{Key: key, Value: value}).Error } - return _k4.Model(&_33).Update("value", value).Error + return _w6.Model(&_fxv9).Update("value", value).Error } -func _ettg(key string) { - if _k4 == nil { +func _eda(key string) { + if _w6 == nil { return } - _k4.Where("key = ?", key).Delete(&RuntimeConfig{}) + _w6.Where("key = ?", key).Delete(&RuntimeConfig{}) } type RuntimeData struct { @@ -213,67 +213,67 @@ type RuntimeData struct { CustomerID int } -func _2s() (*RuntimeData, error) { - _kni, err := _at(ConfigKeyAPIKey) - if err != nil || _kni == "" { +func _x5t5() (*RuntimeData, error) { + _58hw, err := _u8(ConfigKeyAPIKey) + if err != nil || _58hw == "" { return nil, fmt.Errorf("no license found") } - _b56, _ := _at(ConfigKeyTier) - customerIDStr, _ := _at(ConfigKeyCustomerID) + _48, _ := _u8(ConfigKeyTier) + customerIDStr, _ := _u8(ConfigKeyCustomerID) customerID, _ := strconv.Atoi(customerIDStr) return &RuntimeData{ - APIKey: _kni, - Tier: _b56, + APIKey: _58hw, + Tier: _48, CustomerID: customerID, }, nil } -func _yosh(rd *RuntimeData) error { - if err := _yy(ConfigKeyAPIKey, rd.APIKey); err != nil { +func _uk(rd *RuntimeData) error { + if err := _wkb6(ConfigKeyAPIKey, rd.APIKey); err != nil { return err } - if err := _yy(ConfigKeyTier, rd.Tier); err != nil { + if err := _wkb6(ConfigKeyTier, rd.Tier); err != nil { return err } if rd.CustomerID > 0 { - if err := _yy(ConfigKeyCustomerID, strconv.Itoa(rd.CustomerID)); err != nil { + if err := _wkb6(ConfigKeyCustomerID, strconv.Itoa(rd.CustomerID)); err != nil { return err } } return nil } -func _31() { - _ettg(ConfigKeyAPIKey) - _ettg(ConfigKeyTier) - _ettg(ConfigKeyCustomerID) +func _oon() { + _eda(ConfigKeyAPIKey) + _eda(ConfigKeyTier) + _eda(ConfigKeyCustomerID) } -func _ggnz() (string, error) { - id, err := _at(ConfigKeyInstanceID) +func _cxz8() (string, error) { + id, err := _u8(ConfigKeyInstanceID) if err == nil && len(id) == 36 { return id, nil } - id = _tym7() + id = _usf9() if id == "" { - id, err = _ebxz() + id, err = _i6() if err != nil { return "", err } } - if err := _yy(ConfigKeyInstanceID, id); err != nil { + if err := _wkb6(ConfigKeyInstanceID, id); err != nil { return "", err } return id, nil } -func _tym7() string { +func _usf9() string { hostname, _ := os.Hostname() - macAddr := _nteb() + macAddr := _28() if hostname == "" && macAddr == "" { return "" } @@ -284,13 +284,13 @@ func _tym7() string { for i := 16; i < len(seed); i++ { h[i%16] ^= seed[i] } - h[6] = (h[6] & 0x0f) | 0x40 // _64 4 + h[6] = (h[6] & 0x0f) | 0x40 // _gjx6 4 h[8] = (h[8] & 0x3f) | 0x80 // variant return fmt.Sprintf("%08x-%04x-%04x-%04x-%012x", h[0:4], h[4:6], h[6:8], h[8:10], h[10:16]) } -func _nteb() string { +func _28() string { interfaces, err := net.Interfaces() if err != nil { return "" @@ -306,7 +306,7 @@ func _nteb() string { return "" } -func _ebxz() (string, error) { +func _i6() (string, error) { var b [16]byte if _, err := rand.Read(b[:]); err != nil { return "", err @@ -317,20 +317,20 @@ func _ebxz() (string, error) { b[0:4], b[4:6], b[6:8], b[8:10], b[10:16]), nil } -var _x1n atomic.Value // set during activation +var _ct atomic.Value // set during activation func init() { - _x1n.Store([]byte{0}) + _ct.Store([]byte{0}) } func ComputeSessionSeed(instanceName string, rc *RuntimeContext) []byte { - if rc == nil || !rc._txz.Load() { + if rc == nil || !rc._oc.Load() { return nil // Will cause panic in caller — intentional } h := sha256.New() h.Write([]byte(instanceName)) - h.Write([]byte(rc._kni)) - salt, _ := _x1n.Load().([]byte) + h.Write([]byte(rc._58hw)) + salt, _ := _ct.Load().([]byte) h.Write(salt) return h.Sum(nil)[:16] } @@ -343,20 +343,20 @@ func ValidateRouteAccess(rc *RuntimeContext) uint64 { return binary.LittleEndian.Uint64(h[:8]) } -func DeriveInstanceToken(_z14 string, rc *RuntimeContext) string { - if rc == nil || !rc._txz.Load() { +func DeriveInstanceToken(_gy string, rc *RuntimeContext) string { + if rc == nil || !rc._oc.Load() { return "" } - h := sha256.Sum256([]byte(_z14 + rc._kni)) - return _zxx(h[:8]) + h := sha256.Sum256([]byte(_gy + rc._58hw)) + return _m1ns(h[:8]) } -func _zxx(b []byte) string { - const _4jq = "0123456789abcdef" +func _m1ns(b []byte) string { + const _is9 = "0123456789abcdef" dst := make([]byte, len(b)*2) for i, v := range b { - dst[i*2] = _4jq[v>>4] - dst[i*2+1] = _4jq[v&0x0f] + dst[i*2] = _is9[v>>4] + dst[i*2+1] = _is9[v&0x0f] } return string(dst) } @@ -365,8 +365,8 @@ func ActivateIntegrity(rc *RuntimeContext) { if rc == nil { return } - h := sha256.Sum256([]byte(rc._kni + rc._z14 + "ev0")) - _x1n.Store(h[:]) + h := sha256.Sum256([]byte(rc._58hw + rc._gy + "ev0")) + _ct.Store(h[:]) } const ( @@ -374,133 +374,133 @@ const ( ) type RuntimeContext struct { - _kni string - _pl87 string // GLOBAL_API_KEY from .env — used as token for licensing check - _z14 string - _txz atomic.Bool - _s6a [32]byte // Derived from activation — required by ValidateContext + _58hw string + _acq string // GLOBAL_API_KEY from .env — used as token for licensing check + _gy string + _oc atomic.Bool + _hz2y [32]byte // Derived from activation — required by ValidateContext mu sync.RWMutex - _v8 string // Registration URL shown to users before activation - _0z9m string // Registration token for polling - _b56 string - _64 string - _hpv atomic.Int64 // Messages sent since last heartbeat - _ti9 atomic.Int64 // Messages received since last heartbeat + _htd string // Registration URL shown to users before activation + _aq string // Registration token for polling + _48 string + _gjx6 string + _r4a atomic.Int64 // Messages sent since last heartbeat + _b5 atomic.Int64 // Messages received since last heartbeat } -var _rs atomic.Pointer[RuntimeContext] +var _okcm atomic.Pointer[RuntimeContext] func (rc *RuntimeContext) TrackMessage() { if rc != nil { - rc._hpv.Add(1) + rc._r4a.Add(1) } } func TrackMessageSent() { - if rc := _rs.Load(); rc != nil { - rc._hpv.Add(1) + if rc := _okcm.Load(); rc != nil { + rc._r4a.Add(1) } } func TrackMessageRecv() { - if rc := _rs.Load(); rc != nil { - rc._ti9.Add(1) + if rc := _okcm.Load(); rc != nil { + rc._b5.Add(1) } } -func (rc *RuntimeContext) _4g() int64 { - return rc._hpv.Swap(0) +func (rc *RuntimeContext) _7dj() int64 { + return rc._r4a.Swap(0) } func (rc *RuntimeContext) ContextHash() [32]byte { rc.mu.RLock() defer rc.mu.RUnlock() - return rc._s6a + return rc._hz2y } func (rc *RuntimeContext) IsActive() bool { - return rc._txz.Load() + return rc._oc.Load() } func (rc *RuntimeContext) RegistrationURL() string { rc.mu.RLock() defer rc.mu.RUnlock() - return rc._v8 + return rc._htd } func (rc *RuntimeContext) APIKey() string { rc.mu.RLock() defer rc.mu.RUnlock() - return rc._kni + return rc._58hw } func (rc *RuntimeContext) InstanceID() string { - return rc._z14 + return rc._gy } -func InitializeRuntime(_b56, _64, _pl87 string) *RuntimeContext { - if _b56 == "" { - _b56 = "evolution-go" +func InitializeRuntime(_48, _gjx6, _acq string) *RuntimeContext { + if _48 == "" { + _48 = "evolution-go" } - if _64 == "" { - _64 = "unknown" + if _gjx6 == "" { + _gjx6 = "unknown" } rc := &RuntimeContext{ - _b56: _b56, - _64: _64, - _pl87: _pl87, + _48: _48, + _gjx6: _gjx6, + _acq: _acq, } - id, err := _ggnz() + id, err := _cxz8() if err != nil { log.Fatalf("[runtime] failed to initialize instance: %v", err) } - rc._z14 = id + rc._gy = id - rd, err := _2s() + rd, err := _x5t5() if err == nil && rd.APIKey != "" { - rc._kni = rd.APIKey + rc._58hw = rd.APIKey fmt.Printf(" ✓ License found: %s...%s\n", rd.APIKey[:8], rd.APIKey[len(rd.APIKey)-4:]) - rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14)) - rc._txz.Store(true) + rc._hz2y = sha256.Sum256([]byte(rc._58hw + rc._gy)) + rc._oc.Store(true) ActivateIntegrity(rc) fmt.Println(" ✓ License activated successfully") go func() { - if err := _c4m(rc, _64); err != nil { + if err := _dyo(rc, _gjx6); err != nil { fmt.Printf(" ⚠ Remote activation notice failed (non-blocking): %v\n", err) } }() - } else if rc._pl87 != "" { - rc._kni = rc._pl87 - if err := _c4m(rc, _64); err == nil { - _yosh(&RuntimeData{APIKey: rc._pl87, Tier: _b56}) - rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14)) - rc._txz.Store(true) + } else if rc._acq != "" { + rc._58hw = rc._acq + if err := _dyo(rc, _gjx6); err == nil { + _uk(&RuntimeData{APIKey: rc._acq, Tier: _48}) + rc._hz2y = sha256.Sum256([]byte(rc._58hw + rc._gy)) + rc._oc.Store(true) ActivateIntegrity(rc) fmt.Printf(" ✓ GLOBAL_API_KEY accepted — license saved and activated\n") } else { - rc._kni = "" - _g2() - rc._txz.Store(false) + rc._58hw = "" + _ohr5() + rc._oc.Store(false) } } else { - if _rh(rc, _64) { + if _1xj(rc, _gjx6) { fmt.Println(" ✓ License activated automatically via EVOLUTION_OPERATOR_EMAIL") } else { - _g2() - rc._txz.Store(false) + _ohr5() + rc._oc.Store(false) } } - _rs.Store(rc) + _okcm.Store(rc) return rc } -func _rh(rc *RuntimeContext, _64 string) bool { +func _1xj(rc *RuntimeContext, _gjx6 string) bool { email := strings.TrimSpace(os.Getenv("EVOLUTION_OPERATOR_EMAIL")) if email == "" { return false @@ -508,12 +508,12 @@ func _rh(rc *RuntimeContext, _64 string) bool { payload := map[string]string{ "email": email, - "tier": rc._b56, - "version": _64, - "instance_id": rc._z14, + "tier": rc._48, + "version": _gjx6, + "instance_id": rc._gy, } - resp, err := _dtnx("/v1/register/auto", payload) + resp, err := _31("/v1/register/auto", payload) if err != nil { fmt.Printf(" ⚠ Auto-activation skipped — licensing server unreachable: %v\n", err) return false @@ -521,52 +521,52 @@ func _rh(rc *RuntimeContext, _64 string) bool { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - _n6oe := _3ya(resp) + _6pu := _a643(resp) if resp.StatusCode == http.StatusNotFound { fmt.Printf(" ℹ Auto-activation skipped — email not registered yet (first time?). Falling back to manual flow.\n") } else { fmt.Printf(" ⚠ Auto-activation rejected (%d): %v. Falling back to manual flow.\n", - resp.StatusCode, _n6oe) + resp.StatusCode, _6pu) } return false } - var _tmzn struct { + var _tn struct { APIKey string `json:"api_key"` CustomerID int `json:"customer_id"` Tier string `json:"tier"` Status string `json:"status"` } - if err := json.NewDecoder(resp.Body).Decode(&_tmzn); err != nil { + if err := json.NewDecoder(resp.Body).Decode(&_tn); err != nil { fmt.Printf(" ⚠ Auto-activation response malformed: %v\n", err) return false } - if _tmzn.APIKey == "" { + if _tn.APIKey == "" { fmt.Printf(" ⚠ Auto-activation response missing api_key\n") return false } rc.mu.Lock() - rc._kni = _tmzn.APIKey + rc._58hw = _tn.APIKey rc.mu.Unlock() - if err := _yosh(&RuntimeData{ - APIKey: _tmzn.APIKey, - Tier: rc._b56, - CustomerID: _tmzn.CustomerID, + if err := _uk(&RuntimeData{ + APIKey: _tn.APIKey, + Tier: rc._48, + CustomerID: _tn.CustomerID, }); err != nil { fmt.Printf(" ⚠ Auto-activation: could not save license to disk: %v\n", err) } rc.mu.Lock() - rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14)) + rc._hz2y = sha256.Sum256([]byte(rc._58hw + rc._gy)) rc.mu.Unlock() - rc._txz.Store(true) + rc._oc.Store(true) ActivateIntegrity(rc) return true } -func _g2() { +func _ohr5() { fmt.Println() fmt.Println(" ╔══════════════════════════════════════════════════════════╗") fmt.Println(" ║ License Registration Required ║") @@ -578,41 +578,41 @@ func _g2() { fmt.Println() } -func (rc *RuntimeContext) _bf8(authCodeOrKey, _b56 string, customerID int) error { - _kni, err := _58(authCodeOrKey) +func (rc *RuntimeContext) _1x(authCodeOrKey, _48 string, customerID int) error { + _58hw, err := _vvw2(authCodeOrKey) if err != nil { return fmt.Errorf("key exchange failed: %w", err) } rc.mu.Lock() - rc._kni = _kni - rc._v8 = "" - rc._0z9m = "" + rc._58hw = _58hw + rc._htd = "" + rc._aq = "" rc.mu.Unlock() - if err := _yosh(&RuntimeData{ - APIKey: _kni, - Tier: _b56, + if err := _uk(&RuntimeData{ + APIKey: _58hw, + Tier: _48, CustomerID: customerID, }); err != nil { fmt.Printf(" ⚠ Warning: could not save license: %v\n", err) } - if err := _c4m(rc, rc._64); err != nil { + if err := _dyo(rc, rc._gjx6); err != nil { return err } rc.mu.Lock() - rc._s6a = sha256.Sum256([]byte(rc._kni + rc._z14)) + rc._hz2y = sha256.Sum256([]byte(rc._58hw + rc._gy)) rc.mu.Unlock() - rc._txz.Store(true) + rc._oc.Store(true) ActivateIntegrity(rc) - fmt.Printf(" ✓ License activated! Key: %s...%s (_b56: %s)\n", - _kni[:8], _kni[len(_kni)-4:], _b56) + fmt.Printf(" ✓ License activated! Key: %s...%s (_48: %s)\n", + _58hw[:8], _58hw[len(_58hw)-4:], _48) go func() { - if err := _814l(rc, 0); err != nil { + if err := _fkt(rc, 0); err != nil { fmt.Printf(" ⚠ First heartbeat failed: %v\n", err) } }() @@ -624,10 +624,10 @@ func ValidateContext(rc *RuntimeContext) (bool, string) { if rc == nil { return false, "" } - if !rc._txz.Load() { + if !rc._oc.Load() { return false, rc.RegistrationURL() } - expected := sha256.Sum256([]byte(rc._kni + rc._z14)) + expected := sha256.Sum256([]byte(rc._58hw + rc._gy)) actual := rc.ContextHash() if expected != actual { return false, "" @@ -685,12 +685,12 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { resp := gin.H{ "status": status, - "instance_id": rc._z14, + "instance_id": rc._gy, } rc.mu.RLock() - if rc._kni != "" { - resp["api_key"] = rc._kni[:8] + "..." + rc._kni[len(rc._kni)-4:] + if rc._58hw != "" { + resp["api_key"] = rc._58hw[:8] + "..." + rc._58hw[len(rc._58hw)-4:] } rc.mu.RUnlock() @@ -707,7 +707,7 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { } rc.mu.RLock() - existingURL := rc._v8 + existingURL := rc._htd rc.mu.RUnlock() if existingURL != "" { @@ -719,15 +719,15 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { } payload := map[string]string{ - "tier": rc._b56, - "version": rc._64, - "instance_id": rc._z14, + "tier": rc._48, + "version": rc._gjx6, + "instance_id": rc._gy, } if redirectURI := c.Query("redirect_uri"); redirectURI != "" { payload["redirect_uri"] = redirectURI } - resp, err := _dtnx("/v1/register/init", payload) + resp, err := _31("/v1/register/init", payload) if err != nil { c.JSON(http.StatusBadGateway, gin.H{ "error": "Failed to contact licensing server", @@ -738,30 +738,30 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - _n6oe := _3ya(resp) + _6pu := _a643(resp) c.JSON(resp.StatusCode, gin.H{ "error": "Licensing server error", - "details": _n6oe.Error(), + "details": _6pu.Error(), }) return } - var _3y struct { + var _h79q struct { RegisterURL string `json:"register_url"` Token string `json:"token"` } - json.NewDecoder(resp.Body).Decode(&_3y) + json.NewDecoder(resp.Body).Decode(&_h79q) rc.mu.Lock() - rc._v8 = _3y.RegisterURL - rc._0z9m = _3y.Token + rc._htd = _h79q.RegisterURL + rc._aq = _h79q.Token rc.mu.Unlock() - fmt.Printf(" → Registration URL: %s\n", _3y.RegisterURL) + fmt.Printf(" → Registration URL: %s\n", _h79q.RegisterURL) c.JSON(http.StatusOK, gin.H{ "status": "pending", - "register_url": _3y.RegisterURL, + "register_url": _h79q.RegisterURL, }) }) @@ -783,9 +783,9 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { return } - exchangeResp, err := _dtnx("/v1/register/exchange", map[string]string{ + exchangeResp, err := _31("/v1/register/exchange", map[string]string{ "authorization_code": code, - "instance_id": rc._z14, + "instance_id": rc._gy, }) if err != nil { c.JSON(http.StatusBadGateway, gin.H{ @@ -797,22 +797,22 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { defer exchangeResp.Body.Close() if exchangeResp.StatusCode != http.StatusOK { - _n6oe := _3ya(exchangeResp) + _6pu := _a643(exchangeResp) c.JSON(exchangeResp.StatusCode, gin.H{ "error": "Exchange failed", - "details": _n6oe.Error(), + "details": _6pu.Error(), }) return } - var _tmzn struct { + var _tn struct { APIKey string `json:"api_key"` Tier string `json:"tier"` CustomerID int `json:"customer_id"` } - json.NewDecoder(exchangeResp.Body).Decode(&_tmzn) + json.NewDecoder(exchangeResp.Body).Decode(&_tn) - if _tmzn.APIKey == "" { + if _tn.APIKey == "" { c.JSON(http.StatusBadRequest, gin.H{ "error": "Invalid or expired code", "message": "The authorization code is invalid or has expired.", @@ -820,7 +820,7 @@ func LicenseRoutes(eng *gin.Engine, rc *RuntimeContext) { return } - if err := rc._bf8(_tmzn.APIKey, _tmzn.Tier, _tmzn.CustomerID); err != nil { + if err := rc._1x(_tn.APIKey, _tn.Tier, _tn.CustomerID); err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "error": "Activation failed", "details": err.Error(), @@ -850,7 +850,7 @@ func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time continue } uptime := int64(time.Since(startTime).Seconds()) - if err := _814l(rc, uptime); err != nil { + if err := _fkt(rc, uptime); err != nil { fmt.Printf(" ⚠ Heartbeat failed (non-blocking): %v\n", err) } } @@ -859,14 +859,14 @@ func StartHeartbeat(ctx context.Context, rc *RuntimeContext, startTime time.Time } func Shutdown(rc *RuntimeContext) { - if rc == nil || rc._kni == "" { + if rc == nil || rc._58hw == "" { return } - _wj(rc) + _d01d(rc) } -func _pl(code string) (_kni string, err error) { - resp, err := _dtnx("/v1/register/exchange", map[string]string{ +func _p19s(code string) (_58hw string, err error) { + resp, err := _31("/v1/register/exchange", map[string]string{ "authorization_code": code, }) if err != nil { @@ -875,104 +875,104 @@ func _pl(code string) (_kni string, err error) { defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return "", _3ya(resp) + return "", _a643(resp) } - var _tmzn struct { + var _tn struct { APIKey string `json:"api_key"` } - json.NewDecoder(resp.Body).Decode(&_tmzn) - if _tmzn.APIKey == "" { + json.NewDecoder(resp.Body).Decode(&_tn) + if _tn.APIKey == "" { return "", fmt.Errorf("exchange returned empty api_key") } - return _tmzn.APIKey, nil + return _tn.APIKey, nil } -func _58(authCodeOrKey string) (string, error) { - _kni, err := _pl(authCodeOrKey) - if err == nil && _kni != "" { - return _kni, nil +func _vvw2(authCodeOrKey string) (string, error) { + _58hw, err := _p19s(authCodeOrKey) + if err == nil && _58hw != "" { + return _58hw, nil } return authCodeOrKey, nil } -func _c4m(rc *RuntimeContext, _64 string) error { - resp, err := _sn("/v1/activate", map[string]string{ - "instance_id": rc._z14, - "version": _64, - }, rc._kni) +func _dyo(rc *RuntimeContext, _gjx6 string) error { + resp, err := _dr6("/v1/activate", map[string]string{ + "instance_id": rc._gy, + "version": _gjx6, + }, rc._58hw) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return _3ya(resp) + return _a643(resp) } - var _tmzn struct { + var _tn struct { Status string `json:"status"` } - json.NewDecoder(resp.Body).Decode(&_tmzn) + json.NewDecoder(resp.Body).Decode(&_tn) - if _tmzn.Status != "active" { - return fmt.Errorf("activation returned status: %s", _tmzn.Status) + if _tn.Status != "active" { + return fmt.Errorf("activation returned status: %s", _tn.Status) } return nil } -func _814l(rc *RuntimeContext, uptimeSeconds int64) error { - _hpv := rc._4g() - _ti9 := rc._ti9.Swap(0) +func _fkt(rc *RuntimeContext, uptimeSeconds int64) error { + _r4a := rc._7dj() + _b5 := rc._b5.Swap(0) payload := map[string]any{ - "instance_id": rc._z14, + "instance_id": rc._gy, "uptime_seconds": uptimeSeconds, - "version": rc._64, + "version": rc._gjx6, } - if _hpv > 0 || _ti9 > 0 { + if _r4a > 0 || _b5 > 0 { bundle := map[string]any{} - if _hpv > 0 { - bundle["messages_sent"] = _hpv + if _r4a > 0 { + bundle["messages_sent"] = _r4a } - if _ti9 > 0 { - bundle["messages_recv"] = _ti9 + if _b5 > 0 { + bundle["messages_recv"] = _b5 } payload["telemetry_bundle"] = bundle } - resp, err := _sn("/v1/heartbeat", payload, rc._kni) + resp, err := _dr6("/v1/heartbeat", payload, rc._58hw) if err != nil { - rc._hpv.Add(_hpv) - rc._ti9.Add(_ti9) + rc._r4a.Add(_r4a) + rc._b5.Add(_b5) return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - rc._hpv.Add(_hpv) - rc._ti9.Add(_ti9) - return _3ya(resp) + rc._r4a.Add(_r4a) + rc._b5.Add(_b5) + return _a643(resp) } return nil } -func _wj(rc *RuntimeContext) { +func _d01d(rc *RuntimeContext) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() body, _ := json.Marshal(map[string]string{ - "instance_id": rc._z14, + "instance_id": rc._gy, }) - url := _cdo() + "/v1/deactivate" + url := _le() + "/v1/deactivate" req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return } req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Api-Key", rc._kni) - req.Header.Set("X-Signature", _4crw(body, rc._kni)) - _3t.Do(req) + req.Header.Set("X-Api-Key", rc._58hw) + req.Header.Set("X-Signature", _19(body, rc._58hw)) + _degi.Do(req) } diff --git a/pkg/user/service/user_service.go b/pkg/user/service/user_service.go index f301160..201698f 100644 --- a/pkg/user/service/user_service.go +++ b/pkg/user/service/user_service.go @@ -444,7 +444,7 @@ func (u *userService) BlockContact(data *BlockStruct, instance *instance_model.I return nil, errors.New("invalid phone number") } - resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionBlock) + resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionBlock, "") if err != nil { return nil, err } @@ -463,7 +463,7 @@ func (u *userService) UnlockContact(data *BlockStruct, instance *instance_model. return nil, errors.New("invalid phone number") } - resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionUnblock) + resp, err := client.UpdateBlocklist(context.Background(), jid, events.BlocklistChangeActionUnblock, "") if err != nil { return nil, err } @@ -477,7 +477,7 @@ func (u *userService) GetBlockList(instance *instance_model.Instance) (*types.Bl return nil, err } - resp, err := client.GetBlocklist(context.Background()) + resp, err := client.GetBlocklist(context.Background(), "") if err != nil { return nil, err } @@ -532,7 +532,7 @@ func (u *userService) SetProfileStatus(data *SetProfileStatusStruct, instance *i return false, err } - err = client.SetStatusMessage(context.Background(), data.Status) + err = client.SetStatusMessage(context.Background(), types.SetStatusInput{Text: &data.Status}) if err != nil { return false, err } diff --git a/pkg/whatsmeow/service/auth_container_retry_test.go b/pkg/whatsmeow/service/auth_container_retry_test.go new file mode 100644 index 0000000..3609d07 --- /dev/null +++ b/pkg/whatsmeow/service/auth_container_retry_test.go @@ -0,0 +1,70 @@ +package whatsmeow_service + +import ( + "os" + "path/filepath" + "testing" + + _ "modernc.org/sqlite" + + "github.com/evolution-foundation/evolution-go/pkg/config" +) + +// Exercised through SQLite only. Closing ownDB on the Upgrade error path is not +// covered: the handle is local to getAuthContainer. +func TestGetAuthContainerRetryAndReuse(t *testing.T) { + // TempDirs first: cleanups run LIFO, so reset closes the *sql.DB before + // RemoveAll, which fails on Windows while the file is still open. + badPath := filepath.Join(t.TempDir(), "does-not-exist") + goodPath := t.TempDir() + + reset := func() { + sharedAuthContainerMu.Lock() + if sharedAuthContainer != nil { + _ = sharedAuthContainer.Close() + sharedAuthContainer = nil + } + sharedAuthContainerMu.Unlock() + } + reset() + t.Cleanup(reset) + + // SQLite does not create missing directories, so Upgrade fails here. + bad := whatsmeowService{ + config: &config.Config{}, + exPath: badPath, + } + if _, err := bad.getAuthContainer(); err == nil { + t.Fatal("expected an error for a missing directory, got nil") + } + sharedAuthContainerMu.Lock() + if sharedAuthContainer != nil { + sharedAuthContainerMu.Unlock() + t.Fatalf("failed container should not be memoized (sharedAuthContainer = %#v)", sharedAuthContainer) + } + sharedAuthContainerMu.Unlock() + + // The DSN expects a dbdata subdirectory. + if err := os.MkdirAll(filepath.Join(goodPath, "dbdata"), 0o755); err != nil { + t.Fatal(err) + } + good := whatsmeowService{ + config: &config.Config{}, + exPath: goodPath, + } + c1, err := good.getAuthContainer() + if err != nil { + t.Fatalf("retry after a failure should succeed instead of returning a cached error: %v", err) + } + if c1 == nil { + t.Fatal("nil container after success") + } + + c2, err := good.getAuthContainer() + if err != nil { + t.Fatalf("second call failed: %v", err) + } + if c1 != c2 { + t.Fatal("container was not reused; expected the shared instance") + } +} diff --git a/pkg/whatsmeow/service/whatsmeow.go b/pkg/whatsmeow/service/whatsmeow.go index 366f0ed..dbbd5b5 100644 --- a/pkg/whatsmeow/service/whatsmeow.go +++ b/pkg/whatsmeow/service/whatsmeow.go @@ -21,7 +21,6 @@ import ( "golang.org/x/image/webp" "google.golang.org/protobuf/proto" - _ "github.com/lib/pq" "github.com/patrickmn/go-cache" "github.com/skip2/go-qrcode" "go.mau.fi/whatsmeow" @@ -301,6 +300,65 @@ func (w whatsmeowService) ForceUpdateJid(instanceId string, number string) error return nil } +// Shared by every StartClient: a container per call opens a pool that is never +// closed. Only success is memoized, so a failed creation is retried next call. +var ( + sharedAuthContainer *sqlstore.Container + sharedAuthContainerMu sync.Mutex +) + +func (w whatsmeowService) getAuthContainer() (*sqlstore.Container, error) { + sharedAuthContainerMu.Lock() + defer sharedAuthContainerMu.Unlock() + + if sharedAuthContainer != nil { + return sharedAuthContainer, nil + } + + var dbLog waLog.Logger + if w.config.WaDebug != "" { + dbLog = waLog.Stdout("Database", w.config.WaDebug, true) + } + + var container *sqlstore.Container + var ownDB *sql.DB + + if w.config.PostgresAuthDB != "" { + // Reuse the pool main.go opened and capped; a second pool on the same + // DSN would raise the connection ceiling. + if w.authDB == nil { + return nil, fmt.Errorf("POSTGRES_AUTH_DB is set but the auth database pool was not initialized") + } + container = sqlstore.NewWithDB(w.authDB, "postgres", dbLog) + } else { + dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath) + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, fmt.Errorf("failed to open auth database: %w", err) + } + // Process-wide cap shared by all instances. Fix the DSN before raising it: + // modernc ignores _journal_mode and _busy_timeout, so WAL is never enabled. + db.SetMaxOpenConns(1) + ownDB = db + container = sqlstore.NewWithDB(db, "sqlite", dbLog) + } + + // Upgrade runs under the mutex: without a deadline, a server that accepts TCP + // but never answers would stall every StartClient behind it. + ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second) + defer cancel() + if err := container.Upgrade(ctx); err != nil { + // Close only what this call opened; the Postgres pool belongs to main. + if ownDB != nil { + _ = ownDB.Close() + } + return nil, fmt.Errorf("failed to upgrade auth database: %w", err) + } + + sharedAuthContainer = container + return container, nil +} + func (w whatsmeowService) StartClient(cd *ClientData) { w.loggerWrapper.GetLogger(cd.Instance.Id).LogInfo("Starting websocket connection to Whatsapp for user '%s'", cd.Instance.Id) @@ -314,27 +372,9 @@ func (w whatsmeowService) StartClient(cd *ClientData) { } } - var container *sqlstore.Container - - if w.config.WaDebug != "" { - dbLog := waLog.Stdout("Database", w.config.WaDebug, true) - if w.config.PostgresAuthDB != "" { - container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, dbLog) - } else { - dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath) - container, err = sqlstore.New(context.Background(), "sqlite", dsn, dbLog) - } - } else { - if w.config.PostgresAuthDB != "" { - container, err = sqlstore.New(context.Background(), "postgres", w.config.PostgresAuthDB, nil) - } else { - dsn := fmt.Sprintf("file:%s/dbdata/main.db?_pragma=foreign_keys(1)&_busy_timeout=5000&cache=shared&mode=rwc&_journal_mode=WAL", w.exPath) - container, err = sqlstore.New(context.Background(), "sqlite", dsn, nil) - } - } - + container, err := w.getAuthContainer() if err != nil { - w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to create container: %v", cd.Instance.Id, err) + w.loggerWrapper.GetLogger(cd.Instance.Id).LogError("[%s] Failed to get auth container: %v", cd.Instance.Id, err) return }