Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(plugins): accept digest-pinned http install URLs, enforced at the download funnel

Yudhi Armyndharis6833cf866a37
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index e20a6c308..699eff2e0 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -4467,8 +4467,8 @@ Create a webhook for the session.
**Path parameters**
-| Name | Type | Description |
-| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------ |
+| Name | Type | Description |
+| --------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------- |
| sessionId | string | Session the webhook is scoped to; stored as `webhook.sessionId`. The session must exist — an unknown id is refused with `404` at create time. |
**Request body** — `CreateWebhookDto`
@@ -4477,8 +4477,8 @@ Create a webhook for the session.
| ---------- | ---------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| url | string | yes | `@IsUrl({ require_tld: false })` (allows hostnames without a dot, e.g. `http://localhost:3000`); also run through the SSRF guard, which can reject with `400`. Entity column max 2048 chars. | Webhook URL to receive events. |
| events | string[] | no | `@IsArray`, `@ArrayMinSize(1)`, `@IsIn([...WEBHOOK_EVENTS, '*'], { each: true })` | Event names to subscribe to (see allowed set above). Defaults to `["message.received"]` when omitted. |
-| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |
-| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |
+| secret | string | no | `@IsString`, `@MaxLength(255)` | HMAC-SHA256 signing key. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). Used for `X-OpenWA-Signature`. Defaults to `null`. |
+| headers | Record<string,string> | no | `@IsHeaderMap()` — flat object (not array), ≤50 entries, names match `/^[A-Za-z0-9-]+$/`, values are strings ≤1024 chars with no C0 control/DEL (CR/LF injection guard). | Custom headers added to deliveries. **Write-only** — never returned by a webhook route (not returned by `GET /api/infra/export-data` either). At delivery, `content-type` and `x-openwa-*` names are stripped. Defaults to `{}`. |
| filters | WebhookFilters \| null | no | `@IsValidWebhookFilters()` — `{ conditions: [...] }`; each condition `{ field, operator('is'\|'isNot'\|'contains'\|'equals'), value(string\|string[]\|boolean), caseSensitive?:boolean }`; bounds: max 20 conditions, 100 values/condition, 1000-char text values. Message fields: `sender`, `recipient`, `body`, `type`, `isGroup`, `fromMe`, `hasMedia`, `mentions`. | Optional AND pre-filter; **all** conditions must match for the webhook to fire. Omit/null = fire on every subscribed event. Defaults to `null`. ⚠️ A condition whose field is DEFINED for the event family but absent from that event's payload cannot match, so it suppresses the event entirely (a field with no definition for the family is skipped instead, and does not suppress) — `message.ack`/`message.failed` carry `{ id, messageId, status, ack }` and `message.reaction` carries `{ messageId, chatId, reaction, senderId }`, none of which has a sender or body, so a `sender` filter silently drops all three. Scope the subscription with `events[]` rather than relying on a filter to be inert. Set `LOG_LEVEL=debug` to see each suppression and the payload fields that were available. |
| retryCount | number (int) | no | `@IsInt`, `@Min(0)`, `@Max(5)` | Delivery retry attempts on failure. Defaults to `3`. |
@@ -5514,7 +5514,7 @@ Replace all Data DB rows with the supplied export. **Destructive and transaction
| ----------------------------- | ------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `tables` | object | Yes | Container of per-table row arrays, keyed exactly as the export's `tables`. Absent, `null` or not an object is rejected `400` before the restore runs |
| `tables.sessions` | `SessionRow[]` | No | Inserted first; a row whose `name` is not a safe directory name is skipped with a warning (which then rolls the whole restore back) |
-| `tables.webhooks` | `WebhookRow[]` | No | Export rows omit `secret`/`headers`; an absent key restores as `null`/`{}` |
+| `tables.webhooks` | `WebhookRow[]` | No | Export rows omit `secret`/`headers`; an absent key restores as `null`/`{}` |
| `tables.messageBatches` | `MessageBatchRow[]` | No | snake_case columns |
| `tables.*` (the remaining 11) | `Row[]` | No | Same keys as the export; an omitted table restores **zero** rows into an emptied table |
| `stopOrphans` | boolean | No | Stop the running engines for sessions the backup does not contain, inside this request and before the replace (best-effort, time-bounded per engine). Preferred over `force` |
@@ -5812,17 +5812,17 @@ all kept. A directory the gateway did not install is still refused.
#### POST /api/plugins/install-url
-Install a plugin by downloading its `.zip` from an HTTPS URL (SSRF-guarded fetch: host validated, redirects followed with every hop re-validated through the guard and the chain capped at 5 hops, size-capped at `plugins.downloadMaxBytes`, default 5 MB). Plain `http://` is rejected — the package is executable code and must be integrity-protected in transit; private-network targets remain subject to the SSRF guard. A redirect hop that downgrades back to plain `http://` mid-chain is likewise refused (set `PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS=true` only if your vendor genuinely redirects that way); a chain over the cap fails with an explicit "too many redirects" error.
+Install a plugin by downloading its `.zip` from a URL (SSRF-guarded fetch: host validated, redirects followed with every hop re-validated through the guard and the chain capped at 5 hops, size-capped at `plugins.downloadMaxBytes`, default 5 MB). `https://` is accepted as-is; plain `http://` is only accepted when the URL carries a content pin (below) — the package is executable code and must be integrity-protected in transit; private-network targets remain subject to the SSRF guard. A redirect hop that downgrades back to plain `http://` mid-chain is likewise refused (set `PLUGIN_DOWNLOAD_ALLOW_INSECURE_REDIRECTS=true` only if your vendor genuinely redirects that way); a chain over the cap fails with an explicit "too many redirects" error.
-Optional content pinning: append `#sha256=<64 hex>` (URL fragment — never sent to the server) to require the downloaded bytes to match that digest; the fragment is the only honored marker — query params are deliberately ignored. A mismatch or a malformed marker fails the install closed; no marker means no verification (HTTPS + the SSRF guard are the baseline).
+Content pinning: append `#sha256=<64 hex>` (URL fragment — never sent to the server) to require the downloaded bytes to match that digest; the fragment is the only honored marker — query params are deliberately ignored. A mismatch or a malformed marker fails the install closed. The pin is optional over HTTPS (TLS + the SSRF guard are the baseline) and REQUIRED over plain HTTP, which is rejected without one.
**Auth:** API key (ADMIN)
**Request body** — `InstallFromUrlDto` (class-validated; extra fields → `400`)
-| Field | Type | Required | Constraints | Description |
-| ----- | ------ | -------- | -------------------------------------------------------- | ----------------------------------------------------------------- |
-| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the package; optional `#sha256=` digest pin |
+| Field | Type | Required | Constraints | Description |
+| ----- | ------ | -------- | --------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
+| `url` | string | Yes | `@IsUrl({ protocols:['http','https'], require_protocol:true })` | Absolute URL of the package; https as-is, plain http only with a `#sha256=` digest pin |
```json
{ "url": "https://github.com/openwa-plugins/chat-flow/releases/download/v1.0.0/chat-flow.zip" }
@@ -5977,7 +5977,7 @@ Set which sessions a session-scoped plugin is activated for. This is a **full re
#### POST /api/plugins/:id/update
-Update an installed plugin in place from a URL, preserving config + enabled state. The new package is written to a staging sibling and validated BEFORE the running plugin is stopped, then swapped in with two renames (live → backup, staging → live); a failure before or during the swap restores the previous version, and a process crash mid-swap is reconciled at boot (the backup is restored when the live directory is missing), so an interrupted update can never make the plugin silently vanish. Accepts the same optional `#sha256=` digest pin as `install-url` (fail-closed on mismatch).
+Update an installed plugin in place from a URL, preserving config + enabled state. The new package is written to a staging sibling and validated BEFORE the running plugin is stopped, then swapped in with two renames (live → backup, staging → live); a failure before or during the swap restores the previous version, and a process crash mid-swap is reconciled at boot (the backup is restored when the live directory is missing), so an interrupted update can never make the plugin silently vanish. The URL follows the same transport rule as `install-url`: https as-is, plain http only with a `#sha256=` digest pin (fail-closed on mismatch).
**Auth:** API key (ADMIN)
@@ -5989,9 +5989,9 @@ Update an installed plugin in place from a URL, preserving config + enabled stat
**Request body** — `InstallFromUrlDto` (class-validated)
-| Field | Type | Required | Constraints | Description |
-| ----- | ------ | -------- | -------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
-| `url` | string | Yes | `@IsUrl({ protocols:['https'], require_protocol:true })` | Absolute https URL of the new `.zip` (SSRF-guarded download); optional `#sha256=` digest pin |
+| Field | Type | Required | Constraints | Description |
+| ----- | ------ | -------- | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
+| `url` | string | Yes | `@IsUrl({ protocols:['http','https'], require_protocol:true })` | Absolute URL of the new `.zip` (SSRF-guarded download); https as-is, http only with a `#sha256=` pin |
```json
{ "url": "https://example.com/plugins/chat-flow-1.1.0.zip" }
diff --git a/openapi.json b/openapi.json
index de97fa68a..0b1a0b88c 100644
--- a/openapi.json
+++ b/openapi.json
@@ -16072,7 +16072,7 @@
"properties": {
"url": {
"type": "string",
- "description": "HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is executable code, so it must be integrity-protected in transit (hosts on private networks remain subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never sent to the server; query params are ignored) to require the downloaded archive to match that digest; a mismatch fails the install."
+ "description": "URL of the plugin .zip to download and install (SSRF-guarded; private-network hosts remain subject to the guard). https:// is accepted as-is. Plain http:// is only accepted when the URL pins the package content — append `#sha256=<64 hex>` (fragment — never sent to the server; query params are ignored) — because the package is executable code and must be integrity-protected in transit. A pinned digest that does not match the downloaded archive fails the install."
}
},
"required": [
diff --git a/src/modules/plugins/dto/plugin.dto.spec.ts b/src/modules/plugins/dto/plugin.dto.spec.ts
index f7461c46c..53a38707a 100644
--- a/src/modules/plugins/dto/plugin.dto.spec.ts
+++ b/src/modules/plugins/dto/plugin.dto.spec.ts
@@ -3,10 +3,10 @@ import { validate } from 'class-validator';
import { InstallFromUrlDto } from './plugin.dto';
/**
- * The install/update-from-URL boundary: plugin packages are executable code, so the download must
- * be integrity-protected in transit. Plain http:// is rejected with a clear message; https:// —
- * including an optional `#sha256=` integrity fragment — passes DTO validation (private-network
- * targets remain subject to the SSRF guard downstream).
+ * The install/update-from-URL boundary: the DTO checks only the coarse shape — an absolute http(s)
+ * URL. The transport policy itself (plain http is accepted only when the URL carries a `#sha256=`
+ * content pin, verified against the download) is enforced once, at the download funnel every install
+ * path shares — see plugin-download.spec.ts and plugins.service.spec.ts.
*/
describe('InstallFromUrlDto', () => {
const dtoWith = (url: string): InstallFromUrlDto => {
@@ -15,21 +15,6 @@ describe('InstallFromUrlDto', () => {
return dto;
};
- it('rejects a plain http:// URL with a clear message', async () => {
- const errors = await validate(dtoWith('http://plugins.example/pkg.zip'));
-
- expect(errors).toHaveLength(1);
- expect(errors[0].property).toBe('url');
- expect(JSON.stringify(errors[0].constraints)).toMatch(/https:\/\/ URL.*plain http is not accepted/i);
- });
-
- it('rejects http:// even for a localhost/private host (no scheme carve-out)', async () => {
- const errors = await validate(dtoWith('http://localhost:3000/pkg.zip'));
-
- expect(errors).toHaveLength(1);
- expect(errors[0].property).toBe('url');
- });
-
it('accepts an https:// URL', async () => {
await expect(validate(dtoWith('https://plugins.example/pkg.zip'))).resolves.toHaveLength(0);
});
@@ -39,6 +24,19 @@ describe('InstallFromUrlDto', () => {
await expect(validate(dtoWith(`https://plugins.example/pkg.zip#sha256=${digest}`))).resolves.toHaveLength(0);
});
+ it('accepts a plain http:// URL at the DTO — the pin requirement is enforced at the download funnel', async () => {
+ await expect(validate(dtoWith('http://plugins.example/pkg.zip'))).resolves.toHaveLength(0);
+ const digest = 'a'.repeat(64);
+ await expect(validate(dtoWith(`http://plugins.example/pkg.zip#sha256=${digest}`))).resolves.toHaveLength(0);
+ });
+
+ it('rejects a non-http(s) scheme', async () => {
+ const errors = await validate(dtoWith('ftp://plugins.example/pkg.zip'));
+
+ expect(errors).toHaveLength(1);
+ expect(errors[0].property).toBe('url');
+ });
+
it('rejects a non-URL value', async () => {
const errors = await validate(dtoWith('not-a-url'));
diff --git a/src/modules/plugins/dto/plugin.dto.ts b/src/modules/plugins/dto/plugin.dto.ts
index 99eabd2a9..9d7ce8616 100644
--- a/src/modules/plugins/dto/plugin.dto.ts
+++ b/src/modules/plugins/dto/plugin.dto.ts
@@ -85,17 +85,14 @@ export class PluginSessionsDto {
export class InstallFromUrlDto {
@ApiProperty({
description:
- 'HTTPS URL of the plugin .zip to download and install. Plain http:// is rejected: the package is ' +
- 'executable code, so it must be integrity-protected in transit (hosts on private networks remain ' +
- 'subject to the SSRF guard). Optional content pinning: append `#sha256=<64 hex>` (fragment — never ' +
- 'sent to the server; query params are ignored) to require the downloaded archive to match that ' +
- 'digest; a mismatch fails the install.',
+ 'URL of the plugin .zip to download and install (SSRF-guarded; private-network hosts remain ' +
+ 'subject to the guard). https:// is accepted as-is. Plain http:// is only accepted when the URL ' +
+ 'pins the package content — append `#sha256=<64 hex>` (fragment — never sent to the server; query ' +
+ 'params are ignored) — because the package is executable code and must be integrity-protected in ' +
+ 'transit. A pinned digest that does not match the downloaded archive fails the install.',
})
@IsString()
- @IsUrl(
- { protocols: ['https'], require_protocol: true },
- { message: 'url must be an https:// URL — plain http is not accepted for plugin downloads' },
- )
+ @IsUrl({ protocols: ['http', 'https'], require_protocol: true }, { message: 'url must be an absolute http(s) URL' })
url!: string;
}
diff --git a/src/modules/plugins/plugin-download.spec.ts b/src/modules/plugins/plugin-download.spec.ts
index da585a874..43c0d3931 100644
--- a/src/modules/plugins/plugin-download.spec.ts
+++ b/src/modules/plugins/plugin-download.spec.ts
@@ -1,4 +1,4 @@
-import { expectedSha256FromUrl, assertDownloadSha256 } from './plugin-download';
+import { expectedSha256FromUrl, assertDownloadSha256, assertPluginInstallUrl } from './plugin-download';
import { createHash } from 'crypto';
/**
@@ -55,3 +55,32 @@ describe('assertDownloadSha256', () => {
expect(() => assertDownloadSha256(`https://h/pkg.zip#sha256=${'0'.repeat(64)}`, body)).toThrow(/sha256 mismatch/i);
});
});
+
+describe('assertPluginInstallUrl', () => {
+ const digest = 'a'.repeat(64);
+
+ it('accepts https as-is, with or without an integrity pin', () => {
+ expect(() => assertPluginInstallUrl('https://h/pkg.zip')).not.toThrow();
+ expect(() => assertPluginInstallUrl(`https://h/pkg.zip#sha256=${digest}`)).not.toThrow();
+ });
+
+ it('rejects plain http without a content pin — the package is executable code', () => {
+ expect(() => assertPluginInstallUrl('http://h/pkg.zip')).toThrow(/#sha256=/);
+ // A query-param digest is NOT a pin (it belongs to the download host).
+ expect(() => assertPluginInstallUrl(`http://h/pkg.zip?sha256=${digest}`)).toThrow(/#sha256=/);
+ });
+
+ it('accepts plain http carrying a well-formed #sha256= pin (verified against the download)', () => {
+ expect(() => assertPluginInstallUrl(`http://h/pkg.zip#sha256=${digest}`)).not.toThrow();
+ expect(() => assertPluginInstallUrl(`http://h/pkg.zip#sha256=${digest.toUpperCase()}`)).not.toThrow();
+ });
+
+ it('fails closed on http with a malformed pin rather than degrading to no verification', () => {
+ expect(() => assertPluginInstallUrl('http://h/pkg.zip#sha256=xyz')).toThrow(/64-character hex/i);
+ });
+
+ it('leaves unparseable URLs and other schemes to the SSRF guard (no duplicate rejection here)', () => {
+ expect(() => assertPluginInstallUrl('not a url')).not.toThrow();
+ expect(() => assertPluginInstallUrl('ftp://h/pkg.zip')).not.toThrow();
+ });
+});
diff --git a/src/modules/plugins/plugin-download.ts b/src/modules/plugins/plugin-download.ts
index a06329351..8f38331f6 100644
--- a/src/modules/plugins/plugin-download.ts
+++ b/src/modules/plugins/plugin-download.ts
@@ -52,6 +52,28 @@ export function assertDownloadSha256(url: string, body: Buffer): void {
}
}
+/**
+ * Transport rule for a plugin install/update URL, enforced BEFORE any fetch. The downloaded bytes
+ * are executable code, so plain http is only accepted when the URL pins the expected content with a
+ * `#sha256=<64 hex>` fragment — the pin is then verified against the download (fail-closed) before
+ * anything is installed. https is accepted as-is (TLS is the integrity layer), and anything else —
+ * an unparseable URL or a non-http(s) scheme — is left for the SSRF guard to reject downstream.
+ */
+export function assertPluginInstallUrl(url: string): void {
+ let parsed: URL;
+ try {
+ parsed = new URL(url);
+ } catch {
+ return; // not a parseable URL — resolveSafeFetchTarget rejects it with the clearer error
+ }
+ if (parsed.protocol !== 'http:') return; // https unaffected; other schemes are the SSRF guard's call
+ // expectedSha256FromUrl throws on a malformed marker, so an explicit-but-unusable pin fails
+ // closed here rather than silently degrading to "no pin".
+ if (expectedSha256FromUrl(url) === null) {
+ throw new Error('plain http is only accepted with a content pin: append #sha256=<64 hex> to the URL, or use https');
+ }
+}
+
/**
* Fetch a remote resource (plugin .zip or catalog JSON) as a Buffer, always behind the SSRF guard:
* every host (the original URL and every redirect hop) is validated before its socket opens and a hop
diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.ts
index 89db33d73..20e927403 100644
--- a/src/modules/plugins/plugins.service.spec.ts
+++ b/src/modules/plugins/plugins.service.spec.ts
@@ -242,7 +242,7 @@ describe('PluginsService — install / uninstall (real loader + disk)', () => {
});
});
-describe('PluginsService — download integrity (optional #sha256 pinning)', () => {
+describe('PluginsService — download integrity + install-URL transport rule', () => {
let tmpDir: string;
let pluginsDir: string;
let loader: PluginLoaderService;
@@ -337,6 +337,49 @@ describe('PluginsService — download integrity (optional #sha256 pinning)', ()
expect(dto.id).toBe('svc-plg');
});
+ it('rejects a plain http URL without a content pin BEFORE any fetch', async () => {
+ fetchMock.mockClear();
+
+ await expect(service.installFromUrl('http://plugins.example/svc-plg.zip')).rejects.toThrow(/#sha256=/);
+
+ // Nothing was downloaded and nothing was installed.
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(loader.getPlugin('svc-plg')).toBeUndefined();
+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg'))).toBe(false);
+ });
+
+ it('installs over plain http when the #sha256 pin matches the downloaded bytes', async () => {
+ const buf = pkg();
+ serveOnce(buf);
+
+ const dto = await service.installFromUrl(`http://plugins.example/svc-plg.zip#sha256=${sha256(buf)}`);
+
+ expect(dto.id).toBe('svc-plg');
+ expect(loader.getPlugin('svc-plg')).toBeDefined();
+ });
+
+ it('fails closed over plain http when the pinned digest does not match', async () => {
+ serveOnce(pkg());
+ const wrong = '0'.repeat(64);
+
+ await expect(service.installFromUrl(`http://plugins.example/svc-plg.zip#sha256=${wrong}`)).rejects.toThrow(
+ /integrity check failed/i,
+ );
+
+ expect(loader.getPlugin('svc-plg')).toBeUndefined();
+ expect(fs.existsSync(path.join(pluginsDir, 'svc-plg'))).toBe(false);
+ });
+
+ it('updateFromUrl applies the same transport rule: plain http without a pin is rejected before any fetch', async () => {
+ service.install({ buffer: pkg({ version: '1.0.0' }) });
+ fetchMock.mockClear();
+
+ await expect(service.updateFromUrl('svc-plg', 'http://plugins.example/svc-plg.zip')).rejects.toThrow(/#sha256=/);
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(loader.getPlugin('svc-plg')?.manifest.version).toBe('1.0.0');
+ });
+
it('updateFromUrl fails closed on a mismatch and leaves the old version intact', async () => {
service.install({ buffer: pkg({ version: '1.0.0' }) });
serveOnce(pkg({ version: '2.0.0' }));
diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.ts
index 5e9787dde..759af489f 100644
--- a/src/modules/plugins/plugins.service.ts
+++ b/src/modules/plugins/plugins.service.ts
@@ -8,7 +8,7 @@ import type { PluginConfigSchema } from '../../core/plugins';
import { PluginDto } from './dto/plugin.dto';
import { redactSecretConfig, restoreSecretConfig } from './redact-config';
import { parsePluginPackage } from './plugin-installer';
-import { assertDownloadSha256, fetchSafeBuffer } from './plugin-download';
+import { assertDownloadSha256, assertPluginInstallUrl, fetchSafeBuffer } from './plugin-download';
import { annotateCatalog, CatalogEntry, CatalogPlugin } from './catalog';
import { redactSsrfError } from '../../common/security/ssrf-guard';
import { createLogger } from '../../common/services/logger.service';
@@ -374,7 +374,7 @@ export class PluginsService {
}
/**
- * Install a plugin from an HTTPS URL: download the .zip through the SSRF guard (host validated,
+ * Install a plugin from a URL: download the .zip through the SSRF guard (host validated,
* connection pinned, redirects followed with every hop re-validated through the guard and the
* chain capped at 5 hops, size-capped), then run the exact same validate-write-load
* pipeline as an uploaded package. The downloaded buffer is treated as untrusted, identical to an
@@ -383,6 +383,26 @@ export class PluginsService {
* means the package was substituted in transit and the install fails closed.
*/
async installFromUrl(url: string): Promise<PluginDto> {
+ const buffer = await this.downloadPackage(url);
+ // Peek the id (the SSRF download stays outside the lock) so the install — which writes the plugin
+ // directory — is serialized against any concurrent uninstall/update of the same id.
+ const { manifest } = parsePluginPackage(buffer);
+ return this.serialize(manifest.id, () => Promise.resolve(this.install({ buffer })));
+ }
+
+ /**
+ * The single funnel every URL-sourced package download passes through (install + update):
+ * enforce the transport rule (https, or plain http carrying a `#sha256=` content pin) BEFORE any
+ * fetch, download through the SSRF-guarded path, then verify a pinned digest against the bytes.
+ * The remote catalog is deliberately NOT routed through here — its URL is operator configuration
+ * and its JSON is data, not executable code.
+ */
+ private async downloadPackage(url: string): Promise<Buffer> {
+ try {
+ assertPluginInstallUrl(url);
+ } catch (error) {
+ throw new BadRequestException(error instanceof Error ? error.message : String(error));
+ }
const maxBytes = this.configService.get<number>('plugins.downloadMaxBytes') ?? 5 * 1024 * 1024;
let buffer: Buffer;
try {
@@ -399,10 +419,7 @@ export class PluginsService {
`Plugin download integrity check failed: ${error instanceof Error ? error.message : String(error)}`,
);
}
- // Peek the id (the SSRF download stays outside the lock) so the install — which writes the plugin
- // directory — is serialized against any concurrent uninstall/update of the same id.
- const { manifest } = parsePluginPackage(buffer);
- return this.serialize(manifest.id, () => Promise.resolve(this.install({ buffer })));
+ return buffer;
}
/**
@@ -596,22 +613,7 @@ export class PluginsService {
/** Update an installed plugin by downloading the new package from a URL (SSRF-guarded), then in place. */
async updateFromUrl(id: string, url: string): Promise<PluginDto> {
- const maxBytes = this.configService.get<number>('plugins.downloadMaxBytes') ?? 5 * 1024 * 1024;
- let buffer: Buffer;
- try {
- buffer = await fetchSafeBuffer(url, { maxBytes });
- } catch (error) {
- throw new BadRequestException(
- `Failed to download plugin from URL: ${redactSsrfError(error, logger, 'plugin download')}`,
- );
- }
- try {
- assertDownloadSha256(url, buffer);
- } catch (error) {
- throw new BadRequestException(
- `Plugin download integrity check failed: ${error instanceof Error ? error.message : String(error)}`,
- );
- }
+ const buffer = await this.downloadPackage(url);
return this.updatePackage(id, buffer);
}