Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(infra): report whether a newer OpenWA release exists
Yudhi Armyndharisa46a542d73cc
diff --git a/.env.example b/.env.exampleindex 615e3ad7d..9d75dbd10 100644--- a/.env.example+++ b/.env.example@@ -760,6 +760,11 @@ PLUGINS_DIR=./data/plugins # Plugin directory (default: ./data/plugins)# the SSRF guard, so an internal host must also be named in SSRF_ALLOWED_HOSTS or the request is# refused — a private index on a non-public address does not work on this key alone.# PLUGIN_CATALOG_URL=https://raw.githubusercontent.com/rmyndharis/OpenWA-plugins/main/plugins.json+# Tell dashboard admins when a newer OpenWA release exists. The gateway asks api.github.com for the+# latest release through the SSRF guard, caches the answer for six hours (fifteen minutes after a+# failure) and shows nothing while the host has never been reached. The request goes out directly, not+# through HTTP(S)_PROXY. Set to false to make no request at all.+# UPDATE_CHECK_ENABLED=true# =============================================================================# SECURITYdiff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 70840252c..ca508938f 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -270,6 +270,8 @@ services:- PLUGIN_CATALOG_URL=${PLUGIN_CATALOG_URL:-}- PLUGIN_CAP_TIMEOUT_MS=${PLUGIN_CAP_TIMEOUT_MS:-}- PLUGIN_STORAGE_MAX_BYTES=${PLUGIN_STORAGE_MAX_BYTES:-}+ # The dashboard's update notice asks GitHub for the latest release; false turns that request off.+ - UPDATE_CHECK_ENABLED=${UPDATE_CHECK_ENABLED:-}# Misc application tuning.- AUDIT_RETENTION_DAYS=${AUDIT_RETENTION_DAYS:-}- BULK_MAX_CONCURRENT_BATCHES=${BULK_MAX_CONCURRENT_BATCHES:-}diff --git a/docker-compose.yml b/docker-compose.ymlindex f96c1ef11..dedde4f64 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -371,6 +371,8 @@ services:- PLUGIN_CATALOG_URL=${PLUGIN_CATALOG_URL:-}- PLUGIN_CAP_TIMEOUT_MS=${PLUGIN_CAP_TIMEOUT_MS:-}- PLUGIN_STORAGE_MAX_BYTES=${PLUGIN_STORAGE_MAX_BYTES:-}+ # The dashboard's update notice asks GitHub for the latest release; false turns that request off.+ - UPDATE_CHECK_ENABLED=${UPDATE_CHECK_ENABLED:-}# Misc application tuning.- AUDIT_RETENTION_DAYS=${AUDIT_RETENTION_DAYS:-}- BULK_MAX_CONCURRENT_BATCHES=${BULK_MAX_CONCURRENT_BATCHES:-}diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 1fe8e3a8a..b752b100f 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5343,6 +5343,39 @@ Get the currently active engine type.---+#### GET /api/infra/update-check++Compare the running version with the latest published OpenWA release. The dashboard uses it to show+admins a link to the release notes next to the version. The gateway reads GitHub's latest release+through the SSRF-guarded fetch and caches the answer for six hours (fifteen minutes after a failure).+The request goes out directly, not through `HTTP(S)_PROXY`. A pre-release or draft is never offered. A+failure never becomes an error response: an instance that has never reached `api.github.com` answers+`latest: null`, and one that has keeps the last release it saw. `UPDATE_CHECK_ENABLED=false` turns the+outbound request off.++A running pre-release counts as older than its own final release, so `X.Y.Z` is offered to an+instance on `X.Y.Z-rc.1`.++`current` is the running code's `package.json` version, so a build from `main` reports the last+release number until the next release bumps it.++**Auth:** API key (ADMIN)++**Response** `200`++```json+{+ "current": "0.23.5",+ "latest": "0.23.6",+ "updateAvailable": true,+ "releaseUrl": "https://github.com/rmyndharis/OpenWA/releases/tag/v0.23.6"+}+```++**Errors:** `401` · `403`++---+#### GET /api/infra/configRead the effective infrastructure config used to hydrate the dashboard form. Each field resolves with the boot precedence: a value pinned by the host environment (e.g. Compose `environment:`) or the project `.env` wins over `data/.env.generated`, while a key that only ever lived in the saved file reports the freshly-saved value even before a restart applies it ("saved, pending restart"). **Secrets are never returned** — only `*Set`/`*CredentialsSet` booleans indicate that a secret is stored.diff --git a/openapi.json b/openapi.jsonindex 35844f218..631c4176f 100644--- a/openapi.json+++ b/openapi.json@@ -4232,6 +4232,29 @@]}},+ "/api/infra/update-check": {+ "get": {+ "description": "Reads the latest published GitHub release through the SSRF-guarded fetch and caches it. Set UPDATE_CHECK_ENABLED=false to turn the outbound request off.",+ "operationId": "InfraStatusController_getUpdateCheck",+ "parameters": [],+ "responses": {+ "200": {+ "description": "Update check result",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/InfraUpdateCheckResponseDto"+ }+ }+ }+ }+ },+ "summary": "Compare the running version with the latest OpenWA release",+ "tags": [+ "infrastructure"+ ]+ }+ },"/api/infra/health": {"get": {"operationId": "InfraStatusController_healthCheck",@@ -13528,6 +13551,39 @@"engineType"]},+ "InfraUpdateCheckResponseDto": {+ "type": "object",+ "properties": {+ "current": {+ "type": "string",+ "description": "Version of the running code.",+ "example": "0.23.5"+ },+ "latest": {+ "type": "string",+ "nullable": true,+ "description": "Latest published release, or null when the check is off or GitHub has not been reached yet. A later failed check keeps the last known release.",+ "example": "0.23.6"+ },+ "updateAvailable": {+ "type": "boolean",+ "description": "Whether `latest` is newer than `current`.",+ "example": true+ },+ "releaseUrl": {+ "type": "string",+ "nullable": true,+ "description": "Release notes page for `latest`.",+ "example": "https://github.com/rmyndharis/OpenWA/releases/tag/v0.23.6"+ }+ },+ "required": [+ "current",+ "latest",+ "updateAvailable",+ "releaseUrl"+ ]+ },"InfraHealthResponseDto": {"type": "object","properties": {diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.tsindex 3a89a6be7..38da765af 100644--- a/src/config/env-precedence.ts+++ b/src/config/env-precedence.ts@@ -226,6 +226,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = ['PLUGIN_CATALOG_URL','PLUGIN_CAP_TIMEOUT_MS','PLUGIN_STORAGE_MAX_BYTES',+ 'UPDATE_CHECK_ENABLED','AUDIT_RETENTION_DAYS','BULK_MAX_CONCURRENT_BATCHES','TEMPLATE_RENDER_MAX_CHARS',diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 55e533694..c2a2705b2 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -425,6 +425,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {// but an operator whose proxy cannot reach arbitrary media hosts asked for the opposite and// would see every send-by-URL on a proxied session fail instead.'SESSION_PROXY_URL_FETCH',+ // `=== 'false'`: a typo leaves the outbound release check on when the operator asked for it off.+ 'UPDATE_CHECK_ENABLED',// Engine behaviour flags: a typo leaves full-history sync off, or leaves the account marked// online on connect (#871 — it suppresses notifications on the operator's own phone).'BAILEYS_SYNC_FULL_HISTORY',diff --git a/src/modules/infra/dto/infra-response.dto.ts b/src/modules/infra/dto/infra-response.dto.tsindex 53a6d996b..92598026a 100644--- a/src/modules/infra/dto/infra-response.dto.ts+++ b/src/modules/infra/dto/infra-response.dto.ts@@ -193,6 +193,34 @@ export class InfraCurrentEngineResponseDto {engineType!: string;}+// ---------- GET /infra/update-check ----------++export class InfraUpdateCheckResponseDto {+ @ApiProperty({ description: 'Version of the running code.', example: '0.23.5' })+ current!: string;++ @ApiProperty({+ type: String,+ nullable: true,+ description:+ 'Latest published release, or null when the check is off or GitHub has not been reached yet. A ' ++ 'later failed check keeps the last known release.',+ example: '0.23.6',+ })+ latest!: string | null;++ @ApiProperty({ description: 'Whether `latest` is newer than `current`.', example: true })+ updateAvailable!: boolean;++ @ApiProperty({+ type: String,+ nullable: true,+ description: 'Release notes page for `latest`.',+ example: 'https://github.com/rmyndharis/OpenWA/releases/tag/v0.23.6',+ })+ releaseUrl!: string | null;+}+// ---------- GET /infra/config ----------export class InfraConfigDatabaseDto {diff --git a/src/modules/infra/infra-access-control.spec.ts b/src/modules/infra/infra-access-control.spec.tsindex 6881e12e6..f4930806b 100644--- a/src/modules/infra/infra-access-control.spec.ts+++ b/src/modules/infra/infra-access-control.spec.ts@@ -46,6 +46,7 @@ describe('Infra controllers access control', () => {[InfraStatusController, 'getStatus'], // GET /infra/status[InfraStatusController, 'getEngines'], // GET /infra/engines[InfraStatusController, 'getCurrentEngine'], // GET /infra/engines/current+ [InfraStatusController, 'getUpdateCheck'], // GET /infra/update-check (outbound request to GitHub)[InfraStorageController, 'getStorageFileCount'], // GET /infra/storage/files/count] as const;diff --git a/src/modules/infra/infra-status.controller.ts b/src/modules/infra/infra-status.controller.tsindex 324b96caa..3b8e33f76 100644--- a/src/modules/infra/infra-status.controller.ts+++ b/src/modules/infra/infra-status.controller.ts@@ -5,6 +5,7 @@ import {InfraCurrentEngineResponseDto,InfraHealthResponseDto,InfraStatusResponseDto,+ InfraUpdateCheckResponseDto,} from './dto/infra-response.dto';import { InjectQueue } from '@nestjs/bullmq';import { Queue } from 'bullmq';@@ -22,6 +23,7 @@ import { StorageService } from '../../common/storage/storage.service';import { createLogger } from '../../common/services/logger.service';import { readGeneratedEnv } from './generated-env';import { isEnvPinned } from '../../config/env-precedence';+import { checkForUpdate, type UpdateCheck } from './update-check';interface InfraStatus {// `builtIn` reflects whether OpenWA's own bundled container is actually running and backing this@@ -256,6 +258,19 @@ export class InfraStatusController {return { engineType: this.engineFactory.getCurrentEngine() };}+ @Get('update-check')+ @RequireRole(ApiKeyRole.ADMIN)+ @ApiOperation({+ summary: 'Compare the running version with the latest OpenWA release',+ description:+ 'Reads the latest published GitHub release through the SSRF-guarded fetch and caches it. ' ++ 'Set UPDATE_CHECK_ENABLED=false to turn the outbound request off.',+ })+ @ApiResponse({ status: 200, description: 'Update check result', type: InfraUpdateCheckResponseDto })+ getUpdateCheck(): Promise<UpdateCheck> {+ return checkForUpdate();+ }+@Get('health')@Public()@ApiOperation({ summary: 'Health check endpoint' })diff --git a/src/modules/infra/update-check.spec.ts b/src/modules/infra/update-check.spec.tsnew file mode 100644index 000000000..4589856f2--- /dev/null+++ b/src/modules/infra/update-check.spec.ts@@ -0,0 +1,108 @@+jest.mock('../plugins/plugin-download', () => ({ fetchSafeBuffer: jest.fn() }));++import { fetchSafeBuffer } from '../plugins/plugin-download';+import { __resetUpdateCheckCache, checkForUpdate, isNewerRelease } from './update-check';++// eslint-disable-next-line @typescript-eslint/no-require-imports+const { version: RUNNING } = require('../../../package.json') as { version: string };++const fetchMock = fetchSafeBuffer as jest.MockedFunction<typeof fetchSafeBuffer>;+const release = (tag: unknown) => Buffer.from(JSON.stringify({ tag_name: tag, html_url: 'https://evil.example/x' }));+const bump = (v: string) => {+ const [major, minor, patch] = v.split('-')[0].split('.').map(Number);+ return `${major}.${minor}.${patch + 1}`;+};++describe('checkForUpdate', () => {+ beforeEach(() => {+ __resetUpdateCheckCache();+ fetchMock.mockReset();+ delete process.env.UPDATE_CHECK_ENABLED;+ });++ it('reports a newer release with a link built from its tag', async () => {+ fetchMock.mockResolvedValueOnce(release(`v${bump(RUNNING)}`));++ await expect(checkForUpdate()).resolves.toEqual({+ current: RUNNING,+ latest: bump(RUNNING),+ updateAvailable: true,+ releaseUrl: `https://github.com/rmyndharis/OpenWA/releases/tag/v${bump(RUNNING)}`,+ });+ });++ it('reports no update when the latest release is the running one', async () => {+ fetchMock.mockResolvedValueOnce(release(`v${RUNNING}`));++ await expect(checkForUpdate()).resolves.toMatchObject({ updateAvailable: false });+ });++ // compareSemver reads a bare `v1` as 0, so an unstripped `v1.0.0` would never beat a 0.x version.+ it('compares a major release correctly despite the v prefix', async () => {+ fetchMock.mockResolvedValueOnce(release('v99.0.0'));++ await expect(checkForUpdate()).resolves.toMatchObject({ latest: '99.0.0', updateAvailable: true });+ });++ it('ignores a tag that is not a plain release version', async () => {+ fetchMock.mockResolvedValueOnce(release('v99.0.0-rc.1'));++ await expect(checkForUpdate()).resolves.toMatchObject({ latest: null, updateAvailable: false, releaseUrl: null });+ });++ it('asks GitHub once per cache window', async () => {+ fetchMock.mockResolvedValue(release('v99.0.0'));++ await checkForUpdate();+ await checkForUpdate();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('reports no update and backs off when GitHub cannot be reached', async () => {+ fetchMock.mockRejectedValue(new Error('getaddrinfo ENOTFOUND api.github.com'));++ await expect(checkForUpdate()).resolves.toMatchObject({ latest: null, updateAvailable: false });+ await checkForUpdate();++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('makes no request when UPDATE_CHECK_ENABLED=false', async () => {+ process.env.UPDATE_CHECK_ENABLED = 'false';++ await expect(checkForUpdate()).resolves.toEqual({+ current: RUNNING,+ latest: null,+ updateAvailable: false,+ releaseUrl: null,+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('keeps the last known release when a later refresh fails', async () => {+ const now = jest.spyOn(Date, 'now').mockReturnValue(1_000);+ fetchMock.mockResolvedValueOnce(release('v99.0.0')).mockRejectedValueOnce(new Error('ETIMEDOUT'));++ await checkForUpdate();+ now.mockReturnValue(1_000 + 7 * 60 * 60_000); // past the six-hour window+ await expect(checkForUpdate()).resolves.toMatchObject({ latest: '99.0.0', updateAvailable: true });++ expect(fetchMock).toHaveBeenCalledTimes(2);+ now.mockRestore();+ });+});++describe('isNewerRelease', () => {+ it.each([+ ['0.23.6', '0.23.5', true],+ ['0.23.5', '0.23.5', false],+ ['0.23.4', '0.23.5', false],+ ['0.23.10', '0.23.9', true],+ // A running prerelease is older than its own final release.+ ['0.24.0', '0.24.0-rc.1', true],+ ['0.23.9', '0.24.0-rc.1', false],+ ])('%s over a running %s is %s', (latest, current, expected) => {+ expect(isNewerRelease(latest, current)).toBe(expected);+ });+});diff --git a/src/modules/infra/update-check.ts b/src/modules/infra/update-check.tsnew file mode 100644index 000000000..dc9b43843--- /dev/null+++ b/src/modules/infra/update-check.ts@@ -0,0 +1,96 @@+import { fetchSafeBuffer } from '../plugins/plugin-download';+import { compareSemver } from '../plugins/catalog';+import { redactSsrfError } from '../../common/security/ssrf-guard';+import { createLogger } from '../../common/services/logger.service';++const logger = createLogger('UpdateCheck');++// Same source as /api/health: the version that ships with the running code, not a build-time stamp.+// eslint-disable-next-line @typescript-eslint/no-require-imports+const { version: APP_VERSION } = require('../../../package.json') as { version: string };++/**+ * Whether a newer OpenWA release than the running one exists, for the dashboard's update notice.+ *+ * Read-only by design: it names a release and links its notes, and upgrading stays the documented+ * procedure. It runs on the server because the dashboard's CSP only allows its own origin. The request+ * goes out directly through the SSRF guard's pinned connection, not through HTTP(S)_PROXY, and a+ * failure is only logged at debug level: an instance that never reaches GitHub reports no release, and+ * one that reached it before keeps the last answer.+ */+export interface UpdateCheck {+ current: string;+ latest: string | null;+ updateAvailable: boolean;+ releaseUrl: string | null;+}++// GitHub's `/releases/latest` skips drafts and prereleases, so only a published release is offered.+const LATEST_RELEASE_URL = 'https://api.github.com/repos/rmyndharis/OpenWA/releases/latest';+const RELEASE_PAGE_URL = 'https://github.com/rmyndharis/OpenWA/releases/tag/';+// One unauthenticated request per process per window stays far inside GitHub's 60 per hour per IP,+// while a long-running instance still notices a new release the same day.+const SUCCESS_TTL_MS = 6 * 60 * 60_000;+const FAILURE_BACKOFF_MS = 15 * 60_000;+// The response carries the release notes, which run to tens of KB.+const MAX_BYTES = 256 * 1024;+const TIMEOUT_MS = 5_000;+// A plain release tag only. The `v` is stripped before comparing: compareSemver reads `v1` as 0.+const RELEASE_TAG = /^v?(\d+\.\d+\.\d+)$/;++let latest: { version: string; url: string } | null = null;+let nextCheckAt = 0;+let inFlight: Promise<void> | null = null;++/** Test-only: forget the cached release between cases. */+export function __resetUpdateCheckCache(): void {+ latest = null;+ nextCheckAt = 0;+ inFlight = null;+}++async function refresh(): Promise<void> {+ try {+ const body = JSON.parse(+ (await fetchSafeBuffer(LATEST_RELEASE_URL, { maxBytes: MAX_BYTES, timeoutMs: TIMEOUT_MS })).toString('utf8'),+ ) as { tag_name?: unknown };+ const tag = typeof body.tag_name === 'string' ? body.tag_name : '';+ const match = RELEASE_TAG.exec(tag);+ // The link is built from the validated tag rather than taken from the response.+ latest = match ? { version: match[1], url: `${RELEASE_PAGE_URL}${tag}` } : null;+ nextCheckAt = Date.now() + SUCCESS_TTL_MS;+ } catch (error) {+ // Offline, blocked by egress policy, rate-limited or malformed: keep whatever was known and retry+ // later. Logged once per backoff window, redacted like any other guarded fetch.+ logger.debug('Release check failed', { error: redactSsrfError(error) });+ nextCheckAt = Date.now() + FAILURE_BACKOFF_MS;+ }+}++/**+ * Whether `latest` (a plain X.Y.Z) is newer than the running version. A running prerelease counts as+ * older than its own final release: compareSemver ignores the `-rc.1` suffix, so without this an+ * instance on 0.24.0-rc.1 would never hear that 0.24.0 is out.+ */+export function isNewerRelease(latest: string, current: string): boolean {+ const cmp = compareSemver(latest, current);+ return cmp > 0 || (cmp === 0 && current.includes('-'));+}++export async function checkForUpdate(): Promise<UpdateCheck> {+ if (process.env.UPDATE_CHECK_ENABLED === 'false') {+ return { current: APP_VERSION, latest: null, updateAvailable: false, releaseUrl: null };+ }+ if (Date.now() >= nextCheckAt) {+ inFlight ??= refresh().finally(() => {+ inFlight = null;+ });+ await inFlight;+ }+ return {+ current: APP_VERSION,+ latest: latest?.version ?? null,+ updateAvailable: latest !== null && isNewerRelease(latest.version, APP_VERSION),+ releaseUrl: latest?.url ?? null,+ };+}