From 5130b8778cf1183862dfba688d00928b569e06d8 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Mon, 16 Nov 2026 04:27:23 +0200 Subject: [PATCH 1/9] Migrate all four automation integrations to Connections --- CHANGELOG.md | 9 + README.md | 6 + contracts/coverage.json | 12 +- contracts/openapi.messaging.json | 4390 +++++++++++------ contracts/openapi.platform.json | 137 +- contracts/sdk-baseline.json | 67 +- contracts/source.json | 18 +- fixtures/events.json | 10 +- make/README.md | 2 +- make/connections/project/communication.json | 2 +- make/functions/polymorfaAdvanced.js | 4 +- make/functions/polymorfaEnvelope.js | 6 +- make/functions/polymorfaFindHook.js | 2 +- make/functions/polymorfaHook.js | 2 +- make/functions/polymorfaOwnedHook.js | 2 +- make/functions/polymorfaReceive.js | 4 +- make/functions/polymorfaRequest.js | 4 +- make/modules/apiRequest/parameters.json | 2 +- make/modules/callEnded/interface.json | 120 +- make/modules/connectionState/interface.json | 236 + make/modules/connectionState/metadata.json | 6 + .../listConnections/communication.json | 29 + .../interface.json | 28 +- make/modules/listConnections/metadata.json | 6 + .../parameters.json | 0 make/modules/listNumbers/communication.json | 29 - make/modules/listNumbers/metadata.json | 6 - make/modules/messageReceived/interface.json | 173 +- make/modules/messageState/interface.json | 302 +- make/modules/numberState/interface.json | 124 - make/modules/numberState/metadata.json | 6 - make/modules/react/parameters.json | 6 +- make/modules/sendMedia/interface.json | 52 + make/modules/sendMedia/parameters.json | 6 +- make/modules/sendTemplate/interface.json | 52 + make/modules/sendTemplate/parameters.json | 6 +- make/modules/sendText/interface.json | 52 + make/modules/sendText/parameters.json | 6 +- .../attach.json | 20 +- .../connectionState/communication.json | 9 + .../detach.json | 4 +- .../metadata.json | 2 +- .../parameters.json | 0 make/webhooks/numberState/communication.json | 9 - n8n/README.md | 6 +- n8n/credentials/PolymorfaApi.credentials.ts | 4 +- n8n/nodes/Polymorfa/Polymorfa.node.ts | 10 +- n8n/nodes/Polymorfa/PolymorfaTrigger.node.ts | 2 +- n8n/shared/catalog.js | 16 +- n8n/shared/core.js | 8 +- n8n/shared/hooks.js | 4 +- n8n/shared/samples.json | 12 +- pipedream/README.md | 6 +- pipedream/actions/apiRequest/apiRequest.mjs | 2 +- .../listConnections.mjs} | 4 +- pipedream/actions/react/react.mjs | 8 +- pipedream/actions/sendMedia/sendMedia.mjs | 8 +- .../actions/sendTemplate/sendTemplate.mjs | 8 +- pipedream/actions/sendText/sendText.mjs | 8 +- pipedream/common/catalog.cjs | 16 +- pipedream/common/core.cjs | 8 +- pipedream/common/hooks.cjs | 4 +- pipedream/common/samples.json | 12 +- pipedream/polymorfa.app.mjs | 2 +- .../connectionState.mjs} | 8 +- recipes/README.md | 2 +- recipes/field-maps.json | 2 +- recipes/n8n/order-notification.json | 2 +- scripts/generate.mjs | 8 +- scripts/verify-sdk.mjs | 2 +- shared/catalog.cjs | 16 +- shared/core.cjs | 8 +- shared/hooks.cjs | 4 +- tests/core.test.cjs | 18 +- tests/hooks.test.cjs | 21 +- tests/make.test.cjs | 16 +- tests/native.test.cjs | 4 +- tests/pipedream.test.mjs | 10 +- tests/recipes.test.cjs | 21 + zapier/README.md | 4 +- zapier/index.js | 6 +- zapier/shared/catalog.cjs | 16 +- zapier/shared/core.cjs | 8 +- zapier/shared/hooks.cjs | 4 +- zapier/shared/samples.json | 12 +- 85 files changed, 4277 insertions(+), 2031 deletions(-) create mode 100644 make/modules/connectionState/interface.json create mode 100644 make/modules/connectionState/metadata.json create mode 100644 make/modules/listConnections/communication.json rename make/modules/{listNumbers => listConnections}/interface.json (81%) create mode 100644 make/modules/listConnections/metadata.json rename make/modules/{listNumbers => listConnections}/parameters.json (100%) delete mode 100644 make/modules/listNumbers/communication.json delete mode 100644 make/modules/listNumbers/metadata.json delete mode 100644 make/modules/numberState/interface.json delete mode 100644 make/modules/numberState/metadata.json rename make/webhooks/{numberState => connectionState}/attach.json (61%) create mode 100644 make/webhooks/connectionState/communication.json rename make/webhooks/{numberState => connectionState}/detach.json (89%) rename make/webhooks/{numberState => connectionState}/metadata.json (58%) rename make/webhooks/{numberState => connectionState}/parameters.json (100%) delete mode 100644 make/webhooks/numberState/communication.json rename pipedream/actions/{listNumbers/listNumbers.mjs => listConnections/listConnections.mjs} (58%) rename pipedream/sources/{numberState/numberState.mjs => connectionState/connectionState.mjs} (69%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a63920..eb042a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +- Rename WhatsApp account inputs, lookups and state triggers to Connections on + n8n, Make, Zapier and Pipedream, including recipes and generated interfaces. +- Use `connection` event envelopes, `connection.*` lifecycle events, + `connections:read` and `/platform/connections`. Retired account names have no aliases. +- Keep opaque IDs, destination phone numbers, write idempotency and owned webhook + cleanup unchanged. This source candidate is not provider publication or acceptance. + +## Unreleased + - Separate webhook receiver secrets from public marker/idempotency metadata. - Remove the Webhook Creation Key field from all triggers. Each activation uses its own adapter-generated nonce, so off/on, n8n test listening and Pipedream diff --git a/README.md b/README.md index 6c18fe4..fe37370 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,12 @@ has been published, approved or listed in a provider's marketplace. Provider release evidence is recorded in `releases/`. The integrations follow the same public API contract as the Polymorfa SDKs. +Actions select the WhatsApp account with `connection`. Connection lookup uses +`/platform/connections` and `connections:read`; state triggers receive +`connection.status`, `connection.connected` and `connection.logged_out` in a +`connection` envelope. IDs stay strings. Credential connections in each workflow +platform still hold that platform's authentication settings. + They use each platform's own request and credential APIs. No integration builds a separate workflow engine or stores your third-party app connections. diff --git a/contracts/coverage.json b/contracts/coverage.json index fb67d96..d21faeb 100644 --- a/contracts/coverage.json +++ b/contracts/coverage.json @@ -3,7 +3,7 @@ "sendMessage": { "contract": "messaging", "method": "POST", - "path": "/messaging/{session}/messages/send", + "path": "/messaging/{connection}/messages/send", "scope": "messages:write", "sdkOperation": "sendMessage", "purpose": "action" @@ -11,7 +11,7 @@ "sendReaction": { "contract": "messaging", "method": "POST", - "path": "/messaging/{session}/messages/react", + "path": "/messaging/{connection}/messages/react", "scope": "messages:write", "sdkOperation": "sendReaction", "purpose": "action" @@ -32,12 +32,12 @@ "sdkOperation": "getProjectTemplate", "purpose": "action" }, - "listPlatformSessions": { + "listPlatformConnections": { "contract": "platform", "method": "GET", - "path": "/platform/sessions", - "scope": "sessions:read", - "sdkOperation": "listPlatformSessions", + "path": "/platform/connections", + "scope": "connections:read", + "sdkOperation": "listPlatformConnections", "purpose": "action" }, "listProjectWebhooks": { diff --git a/contracts/openapi.messaging.json b/contracts/openapi.messaging.json index da75fdb..fc07dac 100644 --- a/contracts/openapi.messaging.json +++ b/contracts/openapi.messaging.json @@ -1,23 +1,23 @@ { "openapi": "3.0.3", "info": { - "title": "Polymorfa automation messaging", - "version": "2026-09-22" - }, - "servers": [ - { - "url": "https://api.polymorfa.com" + "title": "Polymorfa WhatsApp API", + "version": "1.0.0", + "description": "Public Polymorfa REST API for connections, messaging, media, webhooks, campaigns, templates, client tokens, QuickLinks, and bridge routing.", + "contact": { + "name": "Polymorfa API", + "url": "https://docs.polymorfa.com" } - ], + }, "paths": { - "/messaging/{session}/messages/send": { + "/messaging/{connection}/messages/send": { "post": { "operationId": "sendMessage", "tags": [ "Messages" ], "summary": "Send a message", - "description": "**Protocols:** Linked Device API · Meta Cloud API\n\n**Required scope:** `messages:write`\n\nSend a message to a conversation. Put exactly one message kind inside content. Testing sessions send only to active testing numbers in the same project; supply the recipient phoneNumber.", + "description": "**Protocols:** Linked Device API · Meta Cloud API\n\n**Required scope:** `messages:write`\n\nSend a message to a conversation. Put exactly one message kind inside content. The complete JSON request body is limited to 72 MiB before parsing; decoded media remains limited to 50 MiB. Testing connections send only to active testing connections in the same project; supply the recipient phoneNumber.", "security": [ { "BearerAuth": [] @@ -30,14 +30,14 @@ "type": "string" }, "required": true, - "name": "session", + "name": "connection", "in": "path" }, { "name": "Idempotency-Key", "in": "header", "required": false, - "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 24 hours. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again: it returns `409 idempotency_completed` when the original succeeded, or the original server error, with `Idempotent-Replayed: true`. Reusing the key for a different request returns `409 idempotency_conflict`; a retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`.", + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", "schema": { "type": "string", "minLength": 1, @@ -73,6 +73,15 @@ } }, "headers": { + "Idempotent-Replayed": { + "description": "`true` when this response is the recorded response of an earlier request with the same Idempotency-Key.", + "schema": { + "type": "string", + "enum": [ + "true" + ] + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -94,6 +103,15 @@ } }, "headers": { + "Idempotent-Replayed": { + "description": "`true` when this response is the recorded response of an earlier request with the same Idempotency-Key.", + "schema": { + "type": "string", + "enum": [ + "true" + ] + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -148,7 +166,7 @@ } }, "402": { - "description": "`billing_credit_required`: credit is unavailable for this number. Add credit or review team billing.", + "description": "`billing_credit_required`: credit is unavailable for this connection. Add credit or review team billing.", "content": { "application/json": { "schema": { @@ -158,7 +176,7 @@ "error": { "type": "billing_error", "code": "billing_credit_required", - "message": "Credit is unavailable for this number. Add credit or review team billing.", + "message": "Credit is unavailable for this connection. Add credit or review team billing.", "param": null, "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" }, @@ -222,7 +240,7 @@ } }, "409": { - "description": "`unsupported_for_connection`: call permission requests need a Cloud API number; `call_permission_granted`: the person already granted permanent permission. The Idempotency-Key already succeeded (`idempotency_completed`), was used for a different request (`idempotency_conflict`), belongs to a request that is still running (`idempotency_in_progress`, with Retry-After), or belongs to a request whose outcome was not recorded (`idempotency_outcome_unknown`)", + "description": "`unsupported_for_connection`: call permission requests need a Cloud API connection; `call_permission_granted`: the person already granted permanent permission. The Idempotency-Key belongs to a request that is still running (`idempotency_in_progress`, with Retry-After) or whose outcome was not recorded (`idempotency_outcome_unknown`)", "content": { "application/json": { "schema": { @@ -232,7 +250,7 @@ "error": { "type": "conflict_error", "code": "unsupported_for_connection", - "message": "The session's connection does not support this call operation.", + "message": "The connection's connection does not support this call operation.", "param": null, "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" }, @@ -243,19 +261,16 @@ }, "headers": { "Retry-After": { - "description": "Seconds to wait before retrying `idempotency_in_progress`.", + "description": "Seconds to wait before checking again with the same key. Waiting does not release the execution fence or guarantee that replay data becomes available. Same-key retries are protected only within the one-hour receipt window.", "schema": { "type": "integer", "minimum": 0 } }, - "Idempotent-Replayed": { - "description": "`true` when this response reports the recorded outcome of an earlier request with the same Idempotency-Key.", + "Link": { + "description": "Link to the documentation for this Idempotency-Key error (`rel=\"describedby\"`).", "schema": { - "type": "string", - "enum": [ - "true" - ] + "type": "string" } }, "X-RateLimit-Limit": { @@ -269,8 +284,29 @@ } } }, + "413": { + "description": "The JSON request exceeds 72 MiB, or decoded media exceeds its size limit", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicError" + } + } + }, + "headers": { + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, "422": { - "description": "The supplied media URL could not be fetched", + "description": "The supplied media URL could not be fetched. The Idempotency-Key was already used for a different request (`idempotency_conflict`)", "content": { "application/json": { "schema": { @@ -279,6 +315,12 @@ } }, "headers": { + "Link": { + "description": "Link to the documentation for this Idempotency-Key error (`rel=\"describedby\"`).", + "schema": { + "type": "string" + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -328,7 +370,7 @@ "error": { "type": "rate_limit_error", "code": "call_permission_request_limited", - "message": "WhatsApp limits how often this number can ask this person for call permission. Follow Retry-After when supplied.", + "message": "WhatsApp limits how often this connection can ask this person for call permission. Follow Retry-After when supplied.", "param": null, "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" }, @@ -360,7 +402,7 @@ } }, "501": { - "description": "`operation_not_supported`: the number's connection cannot send this content, such as a poll, or a URL, call or copy-code button on an official WhatsApp Business number", + "description": "`operation_not_supported`: the selected method cannot send this content, such as a poll, or a URL, call or copy-code button on an Official API connection", "content": { "application/json": { "schema": { @@ -413,7 +455,7 @@ } }, "503": { - "description": "Session or service unavailable", + "description": "Connection or service unavailable. For `idempotency_replay_unavailable` only: the exact response for this Idempotency-Key is unavailable (with Retry-After). Opaque responses are not retained by default. The write did not run again. Keep the first response and reconcile events or the resource; waiting does not guarantee that replay data becomes available. Do not switch keys to resend", "content": { "application/json": { "schema": { @@ -422,6 +464,13 @@ } }, "headers": { + "Retry-After": { + "description": "Seconds to wait before checking again with the same key. Waiting does not release the execution fence or guarantee that replay data becomes available. Same-key retries are protected only within the one-hour receipt window.", + "schema": { + "type": "integer", + "minimum": 0 + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -455,16 +504,13 @@ } } }, - "x-mint": { - "content": "Linked Device API Meta Cloud API messages:write" - }, "x-protocols": [ "Linked Device API", "Meta Cloud API" ] } }, - "/messaging/{session}/messages/react": { + "/messaging/{connection}/messages/react": { "post": { "operationId": "sendReaction", "tags": [ @@ -483,14 +529,14 @@ "type": "string" }, "required": true, - "name": "session", + "name": "connection", "in": "path" }, { "name": "Idempotency-Key", "in": "header", "required": false, - "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 24 hours. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again: it returns `409 idempotency_completed` when the original succeeded, or the original server error, with `Idempotent-Replayed: true`. Reusing the key for a different request returns `409 idempotency_conflict`; a retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`.", + "description": "Unique key, 1 to 255 bytes of UTF-8, that makes this write safe to retry for 1 hour. A retry with the same key, credential, `Polymorfa-Version`, and request never runs the write again while its receipt is retained. Keep the first response. Exact response replay requires authorized replay data; opaque message or campaign bodies are not retained by default. An available exact replay carries `Idempotent-Replayed: true`. Authorization, rate-limit and state refusals (401, 403, 408, 409, 423, 425, 429) are not recorded, so the same key can retry them. Reusing the key for a different request returns `422 idempotency_conflict`. A retry while the original is still running returns `409 idempotency_in_progress`, and a retry after an unrecorded outcome returns `409 idempotency_outcome_unknown`. If the recorded response cannot be read, the retry returns `503 idempotency_replay_unavailable` with `Retry-After` and the write still does not run again.", "schema": { "type": "string", "minLength": 1, @@ -518,6 +564,15 @@ } }, "headers": { + "Idempotent-Replayed": { + "description": "`true` when this response is the recorded response of an earlier request with the same Idempotency-Key.", + "schema": { + "type": "string", + "enum": [ + "true" + ] + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -539,6 +594,15 @@ } }, "headers": { + "Idempotent-Replayed": { + "description": "`true` when this response is the recorded response of an earlier request with the same Idempotency-Key.", + "schema": { + "type": "string", + "enum": [ + "true" + ] + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -593,7 +657,7 @@ } }, "402": { - "description": "`billing_credit_required`: credit is unavailable for this number. Add credit or review team billing.", + "description": "`billing_credit_required`: credit is unavailable for this connection. Add credit or review team billing.", "content": { "application/json": { "schema": { @@ -603,7 +667,7 @@ "error": { "type": "billing_error", "code": "billing_credit_required", - "message": "Credit is unavailable for this number. Add credit or review team billing.", + "message": "Credit is unavailable for this connection. Add credit or review team billing.", "param": null, "request_id": "5f0c2a8e-3b1d-4c6f-9e2a-7d4b1c8f6a30" }, @@ -667,7 +731,7 @@ } }, "409": { - "description": "The Idempotency-Key already succeeded (`idempotency_completed`), was used for a different request (`idempotency_conflict`), belongs to a request that is still running (`idempotency_in_progress`, with Retry-After), or belongs to a request whose outcome was not recorded (`idempotency_outcome_unknown`)", + "description": "The Idempotency-Key belongs to a request that is still running (`idempotency_in_progress`, with Retry-After) or whose outcome was not recorded (`idempotency_outcome_unknown`)", "content": { "application/json": { "schema": { @@ -676,30 +740,47 @@ "example": { "error": { "type": "conflict_error", - "code": "idempotency_conflict", - "message": "This Idempotency-Key was already used with a different request. Use a new key for a different request.", + "code": "idempotency_in_progress", + "message": "A request with this Idempotency-Key is still in progress. Check again after Retry-After with the same key within the documented receipt window. Exact response data may be unavailable.", "param": null }, "data": null, - "docs": "https://docs.polymorfa.com/api/errors#idempotency-conflict" + "docs": "https://docs.polymorfa.com/api/errors#idempotency-in-progress" } } }, "headers": { "Retry-After": { - "description": "Seconds to wait before retrying `idempotency_in_progress`.", + "description": "Seconds to wait before checking again with the same key. Waiting does not release the execution fence or guarantee that replay data becomes available. Same-key retries are protected only within the one-hour receipt window.", "schema": { "type": "integer", "minimum": 0 } }, - "Idempotent-Replayed": { - "description": "`true` when this response reports the recorded outcome of an earlier request with the same Idempotency-Key.", + "Link": { + "description": "Link to the documentation for this Idempotency-Key error (`rel=\"describedby\"`).", "schema": { - "type": "string", - "enum": [ - "true" - ] + "type": "string" + } + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "422": { + "description": "The Idempotency-Key was already used for a different request (`idempotency_conflict`)", + "headers": { + "Link": { + "description": "Link to the documentation for this Idempotency-Key error (`rel=\"describedby\"`).", + "schema": { + "type": "string" } }, "X-RateLimit-Limit": { @@ -711,6 +792,23 @@ "X-RateLimit-Reset": { "$ref": "#/components/headers/X-RateLimit-Reset" } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicError" + }, + "example": { + "error": { + "type": "invalid_request_error", + "code": "idempotency_conflict", + "message": "This Idempotency-Key was already used with a different request. Use a new key for a different request.", + "param": null + }, + "data": null, + "docs": "https://docs.polymorfa.com/api/errors#idempotency-conflict" + } + } } }, "500": { @@ -756,7 +854,7 @@ } }, "503": { - "description": "Session or service unavailable", + "description": "Connection or service unavailable. For `idempotency_replay_unavailable` only: the exact response for this Idempotency-Key is unavailable (with Retry-After). Opaque responses are not retained by default. The write did not run again. Keep the first response and reconcile events or the resource; waiting does not guarantee that replay data becomes available. Do not switch keys to resend", "content": { "application/json": { "schema": { @@ -765,6 +863,13 @@ } }, "headers": { + "Retry-After": { + "description": "Seconds to wait before checking again with the same key. Waiting does not release the execution fence or guarantee that replay data becomes available. Same-key retries are protected only within the one-hour receipt window.", + "schema": { + "type": "integer", + "minimum": 0 + } + }, "X-RateLimit-Limit": { "$ref": "#/components/headers/X-RateLimit-Limit" }, @@ -798,9 +903,6 @@ } } }, - "x-mint": { - "content": "Linked Device API Meta Cloud API messages:write" - }, "x-protocols": [ "Linked Device API", "Meta Cloud API" @@ -1014,9 +1116,6 @@ } } }, - "x-mint": { - "content": "templates:read" - }, "description": "**Required scope:** `templates:read`" } }, @@ -1234,477 +1333,105 @@ } } }, - "x-mint": { - "content": "templates:read" - }, "description": "**Required scope:** `templates:read`" } } }, "components": { "schemas": { - "MessageReceivedEvent": { + "SendMessageRequest": { "type": "object", "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" + "conversation": { + "$ref": "#/components/schemas/ConversationReference" }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." + "isForwarded": { + "type": "boolean", + "description": "Mark this message as forwarded." }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" + "mentions": { + "type": "array", + "items": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "maxItems": 256, + "description": "User IDs to mention in this message." }, - "event": { - "type": "string", - "enum": [ - "message.received" - ], - "description": "Event type" + "quotedMessage": { + "$ref": "#/components/schemas/QuotedMessage" }, - "payload": { - "$ref": "#/components/schemas/MessageReceivedPayload" + "content": { + "$ref": "#/components/schemas/MessageContent" } }, "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] + "conversation", + "content" + ], + "additionalProperties": false, + "description": "Specify conversation and content containing exactly one message kind. Shared options remain outside content." }, - "MessageSentEvent": { + "ConversationReference": { "type": "object", "properties": { "id": { "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", "example": "739182640518203" }, - "externalId": { + "phoneNumber": { "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." + "pattern": "^\\+[1-9]\\d{1,14}$", + "description": "International phone number to look up, including + and the country code. WhatsApp determines the recipient account." }, - "timestamp": { + "bsuid": { "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" + "pattern": "^[A-Z]{2}\\.[A-Za-z0-9]{1,128}$" }, - "event": { + "username": { "type": "string", - "enum": [ - "message.sent" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/MessageSentPayload" + "minLength": 1, + "maxLength": 256, + "description": "Known username. This field alone does not select a conversation." } }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" + "additionalProperties": false, + "anyOf": [ + { + "required": [ + "id" + ] + }, + { + "required": [ + "phoneNumber" + ] + }, + { + "required": [ + "bsuid" + ] + } ] }, - "MessageAckEvent": { + "QuotedMessage": { "type": "object", "properties": { "id": { "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", "example": "739182640518203" }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "message.ack" - ], - "description": "Event type" + "type": { + "type": "string" }, - "payload": { - "$ref": "#/components/schemas/MessageAckPayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "MessageFailedEvent": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" - }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "message.failed" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/MessageFailedPayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "MessageUpdateEvent": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" - }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "message.update" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/MessagePayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "SessionStatusEvent": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" - }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "session.status" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/SessionStatusPayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "SessionConnectedEvent": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" - }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "session.connected" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/SessionConnectedPayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "SessionLoggedOutEvent": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" - }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "session.logged_out" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/SessionLoggedOutPayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "CallEndedEvent": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "Unique event identifier", - "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" - }, - "session": { - "type": "string", - "description": "Session that produced this event", - "example": "739182640518203" - }, - "externalId": { - "type": "string", - "description": "Integrator reference from the QuickLink that created this session. Included on session lifecycle events when supplied." - }, - "timestamp": { - "type": "string", - "description": "ISO 8601 timestamp", - "example": "2026-10-19T14:03:22.000Z" - }, - "event": { - "type": "string", - "enum": [ - "call.ended" - ], - "description": "Event type" - }, - "payload": { - "$ref": "#/components/schemas/CallEndedPayload" - } - }, - "required": [ - "id", - "session", - "timestamp", - "event", - "payload" - ] - }, - "SendMessageRequest": { - "type": "object", - "properties": { - "conversation": { - "$ref": "#/components/schemas/ConversationReference" - }, - "isForwarded": { - "type": "boolean", - "description": "Mark this message as forwarded." - }, - "mentions": { - "type": "array", - "items": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "maxItems": 256, - "description": "User IDs to mention in this message." - }, - "quotedMessage": { - "$ref": "#/components/schemas/QuotedMessage" - }, - "content": { - "$ref": "#/components/schemas/MessageContent" - } - }, - "required": [ - "conversation", - "content" - ], - "additionalProperties": false, - "description": "Specify conversation and content containing exactly one message kind. Shared options remain outside content." - }, - "ConversationReference": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "phoneNumber": { - "type": "string", - "pattern": "^\\+[1-9]\\d{1,14}$", - "description": "International phone number to look up, including + and the country code. WhatsApp determines the recipient account." - }, - "bsuid": { - "type": "string", - "pattern": "^[A-Z]{2}\\.[A-Za-z0-9]{1,128}$" - }, - "username": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Known username. This field alone does not select a conversation." - } - }, - "additionalProperties": false, - "anyOf": [ - { - "required": [ - "id" - ] - }, - { - "required": [ - "phoneNumber" - ] - }, - { - "required": [ - "bsuid" - ] - } - ] - }, - "QuotedMessage": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "type": { - "type": "string" - }, - "text": { - "type": "string" + "text": { + "type": "string" } }, "required": [ @@ -1801,7 +1528,7 @@ "type": "string", "minLength": 4, "maxLength": 21848, - "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices numbers only." + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." }, "descriptor": { "$ref": "#/components/schemas/VideoMediaDescriptor" @@ -1846,7 +1573,7 @@ "type": "string", "minLength": 4, "maxLength": 21848, - "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices numbers only." + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." }, "descriptor": { "$ref": "#/components/schemas/FileMediaDescriptor" @@ -1884,39 +1611,500 @@ "type": "string", "description": "Caption sent with the media." }, - "ptt": { - "type": "boolean" + "ptt": { + "type": "boolean" + }, + "descriptor": { + "$ref": "#/components/schemas/VoiceMediaDescriptor" + } + }, + "additionalProperties": false + } + }, + "required": [ + "voice" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "sticker": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "base64": { + "type": "string", + "minLength": 1, + "maxLength": 28000000 + }, + "descriptor": { + "$ref": "#/components/schemas/StickerMediaDescriptor" + }, + "emojis": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "maxItems": 10 + }, + "accessibilityLabel": { + "type": "string", + "minLength": 0 + } + }, + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "url" + ], + "not": { + "anyOf": [ + { + "required": [ + "base64" + ] + }, + { + "required": [ + "descriptor" + ] + } + ] + } + }, + { + "required": [ + "base64" + ], + "not": { + "anyOf": [ + { + "required": [ + "url" + ] + }, + { + "required": [ + "descriptor" + ] + } + ] + } }, - "descriptor": { - "$ref": "#/components/schemas/VoiceMediaDescriptor" + { + "required": [ + "descriptor" + ], + "not": { + "anyOf": [ + { + "required": [ + "url" + ] + }, + { + "required": [ + "base64" + ] + } + ] + } } - }, - "additionalProperties": false + ] } }, "required": [ - "voice" + "sticker" ], "additionalProperties": false }, { "type": "object", "properties": { - "sticker": { - "type": "object", - "properties": { - "descriptor": { - "$ref": "#/components/schemas/StickerMediaDescriptor" + "stickerPack": { + "anyOf": [ + { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 1 + }, + "publisher": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 0 + }, + "caption": { + "type": "string", + "minLength": 0 + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "emojis": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "maxItems": 10 + }, + "accessibilityLabel": { + "type": "string", + "minLength": 0 + }, + "fileName": { + "type": "string", + "minLength": 1, + "pattern": "^[^/\\\\:\\x00]+$" + }, + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "base64": { + "type": "string", + "minLength": 1, + "maxLength": 28000000 + } + }, + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "url" + ], + "not": { + "anyOf": [ + { + "required": [ + "base64" + ] + } + ] + } + }, + { + "required": [ + "base64" + ], + "not": { + "anyOf": [ + { + "required": [ + "url" + ] + } + ] + } + } + ] + }, + "minItems": 1, + "maxItems": 100 + }, + "trayIcon": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "base64": { + "type": "string", + "minLength": 1, + "maxLength": 28000000 + } + }, + "additionalProperties": false, + "oneOf": [ + { + "required": [ + "url" + ], + "not": { + "anyOf": [ + { + "required": [ + "base64" + ] + } + ] + } + }, + { + "required": [ + "base64" + ], + "not": { + "anyOf": [ + { + "required": [ + "url" + ] + } + ] + } + } + ] + } + }, + "required": [ + "id", + "name", + "publisher", + "items" + ], + "additionalProperties": false, + "description": "Convert up to 100 image items. Items and an explicit tray share 64 MiB of input and 128 million source plus 512px output frame pixels. Preparation stops at the command deadline or 30 seconds, whichever comes first. Reduce dimensions, frame counts or item count if the pack exceeds these limits." + }, + { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "name": { + "type": "string", + "minLength": 1 + }, + "publisher": { + "type": "string", + "minLength": 1 + }, + "description": { + "type": "string", + "minLength": 0 + }, + "caption": { + "type": "string", + "minLength": 0 + }, + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "fileName": { + "type": "string", + "minLength": 1, + "pattern": "^[^/\\\\:\\x00]+$" + }, + "stickerType": { + "type": "string", + "enum": [ + "static", + "animated", + "lottie" + ] + }, + "emojis": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "maxItems": 10 + }, + "accessibilityLabel": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "fileName", + "stickerType" + ], + "additionalProperties": false + }, + "minItems": 1, + "maxItems": 100 + }, + "descriptor": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 2048, + "pattern": "^https:\\/\\/[!-~]+$", + "description": "Media URL returned by the upload." + }, + "directPath": { + "type": "string", + "maxLength": 2048, + "pattern": "^\\/(?!\\/)[!-~]+$", + "description": "Direct path returned by the upload." + }, + "mediaKey": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 32-byte media key you encrypted the file with." + }, + "fileSha256": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 SHA-256 of the plaintext file." + }, + "fileEncSha256": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 SHA-256 of the uploaded ciphertext and MAC." + }, + "fileLength": { + "type": "integer", + "minimum": 1, + "maximum": 2147483648, + "description": "Plaintext file size in bytes." + }, + "mimeType": { + "type": "string", + "enum": [ + "application/zip" + ] + }, + "mediaKeyTimestamp": { + "type": "integer", + "minimum": 1, + "maximum": 1099511627776, + "description": "Unix time in seconds when the media key was created." + } + }, + "required": [ + "url", + "directPath", + "mediaKey", + "fileSha256", + "fileEncSha256", + "fileLength", + "mimeType" + ], + "additionalProperties": false + }, + "trayIconFileName": { + "type": "string", + "minLength": 1, + "pattern": "^[^/\\\\:\\x00]+$" + }, + "thumbnailDescriptor": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 2048, + "pattern": "^https:\\/\\/[!-~]+$", + "description": "Media URL returned by the upload." + }, + "directPath": { + "type": "string", + "maxLength": 2048, + "pattern": "^\\/(?!\\/)[!-~]+$", + "description": "Direct path returned by the upload." + }, + "mediaKey": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 32-byte media key you encrypted the file with." + }, + "fileSha256": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 SHA-256 of the plaintext file." + }, + "fileEncSha256": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 SHA-256 of the uploaded ciphertext and MAC." + }, + "fileLength": { + "type": "integer", + "minimum": 1, + "maximum": 2147483648, + "description": "Plaintext file size in bytes." + }, + "mimeType": { + "type": "string", + "enum": [ + "image/png" + ] + }, + "mediaKeyTimestamp": { + "type": "integer", + "minimum": 1, + "maximum": 1099511627776, + "description": "Unix time in seconds when the media key was created." + }, + "width": { + "type": "integer", + "minimum": 1, + "maximum": 65536, + "description": "Width in pixels. Send with height." + }, + "height": { + "type": "integer", + "minimum": 1, + "maximum": 65536, + "description": "Height in pixels. Send with width." + } + }, + "required": [ + "url", + "directPath", + "mediaKey", + "fileSha256", + "fileEncSha256", + "fileLength", + "mimeType" + ], + "additionalProperties": false + } + }, + "required": [ + "id", + "name", + "publisher", + "items", + "descriptor" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "forwardMedia": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$" + } + }, + "required": [ + "forwardMedia" + ], + "additionalProperties": false } - }, - "required": [ - "descriptor" - ], - "additionalProperties": false + ] } }, "required": [ - "sticker" + "stickerPack" ], "additionalProperties": false }, @@ -2332,11 +2520,392 @@ "buttonText", "sections" ], - "description": "On an official WhatsApp Business number, `title` is the header (at most 60 characters) and `description` the body (at most 1,024 characters); without `description`, `title` is the body. There, each section title allows at most 24 characters and is required when the list has more than one section, lists allow at most 10 rows in total, row titles at most 24 characters, row IDs at most 200, row descriptions at most 72, `buttonText` at most 20 and `footer` at most 60. Every number also limits `buttonText` to 64 UTF-8 bytes, row `id` to 256 bytes and `title` and `description` to 256 and 4,096 bytes, so multibyte text reaches those byte limits before the character limits. Content outside any limit returns `400`." + "description": "On an Official API connection, `title` is the header (at most 60 characters) and `description` the body (at most 1,024 characters); without `description`, `title` is the body. There, each section title allows at most 24 characters and is required when the list has more than one section, lists allow at most 10 rows in total, row titles at most 24 characters, row IDs at most 200, row descriptions at most 72, `buttonText` at most 20 and `footer` at most 60. Every connection also limits `buttonText` to 64 UTF-8 bytes, row `id` to 256 bytes and `title` and `description` to 256 and 4,096 bytes, so multibyte text reaches those byte limits before the character limits. Content outside any limit returns `400`." + } + }, + "required": [ + "list" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "carousel": { + "type": "object", + "properties": { + "body": { + "type": "string", + "minLength": 1 + }, + "footer": { + "type": "string", + "minLength": 0 + }, + "cards": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "body": { + "type": "string", + "minLength": 1 + }, + "buttons": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "url" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "type", + "text", + "url" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "call" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "phoneNumber": { + "type": "string", + "pattern": "^\\+?\\d{6,20}$" + } + }, + "required": [ + "type", + "text", + "phoneNumber" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "reply" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "type", + "text", + "id" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "copy" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "copyCode": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "type", + "text", + "copyCode" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "catalog" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "businessPhoneNumber": { + "type": "string", + "pattern": "^\\+?\\d{6,20}$" + }, + "catalogProductId": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "type", + "text", + "businessPhoneNumber" + ] + } + ] + }, + "minItems": 1, + "maxItems": 10 + }, + "image": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "base64": { + "type": "string", + "minLength": 1, + "maxLength": 70000000 + }, + "mimeType": { + "type": "string", + "minLength": 0 + } + }, + "additionalProperties": false + } + }, + "required": [ + "body", + "buttons", + "image" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "body": { + "type": "string", + "minLength": 1 + }, + "buttons": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "url" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "url": { + "type": "string", + "maxLength": 2048, + "format": "uri" + } + }, + "required": [ + "type", + "text", + "url" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "call" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "phoneNumber": { + "type": "string", + "pattern": "^\\+?\\d{6,20}$" + } + }, + "required": [ + "type", + "text", + "phoneNumber" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "reply" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "type", + "text", + "id" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "copy" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "copyCode": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "type", + "text", + "copyCode" + ] + }, + { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "catalog" + ] + }, + "text": { + "type": "string", + "minLength": 1 + }, + "businessPhoneNumber": { + "type": "string", + "pattern": "^\\+?\\d{6,20}$" + }, + "catalogProductId": { + "type": "string", + "minLength": 0 + } + }, + "required": [ + "type", + "text", + "businessPhoneNumber" + ] + } + ] + }, + "minItems": 1, + "maxItems": 10 + }, + "video": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "base64": { + "type": "string", + "minLength": 1, + "maxLength": 70000000 + }, + "mimeType": { + "type": "string", + "minLength": 0 + }, + "thumbnail": { + "type": "string", + "minLength": 4, + "maxLength": 21848, + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." + } + }, + "additionalProperties": false + } + }, + "required": [ + "body", + "buttons", + "video" + ], + "additionalProperties": false + } + ] + }, + "minItems": 2, + "maxItems": 10 + } + }, + "required": [ + "body", + "cards" + ], + "additionalProperties": false, + "description": "Linked Devices only: one message with 2–10 image/video cards and native buttons per card. Each card accepts up to ten replies or three CTAs without mixing; reply IDs are unique across cards. Combined media is bounded to 50 MiB. Official approved carousel templates use content.template instead." } }, "required": [ - "list" + "carousel" ], "additionalProperties": false }, @@ -2346,6 +2915,47 @@ "buttons": { "type": "object", "properties": { + "media": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 4096, + "format": "uri" + }, + "base64": { + "type": "string", + "minLength": 1, + "maxLength": 70000000 + }, + "mimeType": { + "type": "string", + "minLength": 0 + }, + "type": { + "type": "string", + "enum": [ + "image", + "video", + "document" + ] + }, + "filename": { + "type": "string", + "minLength": 0 + }, + "thumbnail": { + "type": "string", + "minLength": 4, + "maxLength": 21848, + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." + } + }, + "required": [ + "type" + ], + "additionalProperties": false + }, "title": { "type": "string", "minLength": 0 @@ -2490,14 +3100,14 @@ ] }, "minItems": 1, - "maxItems": 3 + "maxItems": 10 } }, "required": [ "body", "buttons" ], - "description": "On an official WhatsApp Business number, only `reply` buttons are sent; other button types return `501`. There, `body` allows at most 1,024 characters, `title` and `footer` at most 60, and each button needs a unique `id` and a unique `text` of at most 20 characters. Every number also limits each button `id` to 256 UTF-8 bytes. Content outside any limit returns `400`." + "description": "Linked Devices support up to 10 total buttons and at most 3 CTAs. Replies may be mixed with URL and call buttons using a hydrated template; copy/catalog buttons cannot be mixed with replies. An optional image, video or document header requires exactly one URL or base64 source and cannot be combined with a title. On an Official API connection, media headers require an approved template, and at most 3 `reply` buttons are sent; other button types return `501`. There, `body` allows at most 1,024 characters, `title` and `footer` at most 60, and each button needs a unique `id` and a unique `text` of at most 20 characters. Every connection also limits each button `id` to 256 UTF-8 bytes. Content outside any limit returns `400`." } }, "required": [ @@ -2648,7 +3258,7 @@ "body" ], "additionalProperties": false, - "description": "Ask the person for permission to call them. Cloud API numbers only; WhatsApp limits how often you can ask." + "description": "Ask the person for permission to call them. Cloud API connections only; WhatsApp limits how often you can ask." } }, "required": [ @@ -2743,7 +3353,7 @@ "type": "string", "minLength": 4, "maxLength": 21848, - "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices numbers only." + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." }, "width": { "type": "integer", @@ -2823,7 +3433,7 @@ "type": "string", "minLength": 4, "maxLength": 21848, - "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices numbers only." + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." }, "width": { "type": "integer", @@ -2909,7 +3519,7 @@ "type": "string", "minLength": 4, "maxLength": 21848, - "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices numbers only." + "description": "Base64-encoded JPEG preview shown before the media downloads, at most 16 KiB. Linked Devices connections only." } }, "required": [ @@ -2994,85 +3604,484 @@ "fileLength", "mimeType" ], - "additionalProperties": false, - "description": "Media you encrypted and uploaded yourself. Upload voice notes with type voice." + "additionalProperties": false, + "description": "Media you encrypted and uploaded yourself. Upload voice notes with type voice." + }, + "StickerMediaDescriptor": { + "type": "object", + "properties": { + "url": { + "type": "string", + "maxLength": 2048, + "pattern": "^https:\\/\\/[!-~]+$", + "description": "Media URL returned by the upload." + }, + "directPath": { + "type": "string", + "maxLength": 2048, + "pattern": "^\\/(?!\\/)[!-~]+$", + "description": "Direct path returned by the upload." + }, + "mediaKey": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 32-byte media key you encrypted the file with." + }, + "fileSha256": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 SHA-256 of the plaintext file." + }, + "fileEncSha256": { + "type": "string", + "pattern": "^[A-Za-z0-9+/]+={0,2}$", + "description": "Base64 SHA-256 of the uploaded ciphertext and MAC." + }, + "fileLength": { + "type": "integer", + "minimum": 1, + "maximum": 2147483648, + "description": "Plaintext file size in bytes." + }, + "mimeType": { + "type": "string", + "enum": [ + "image/webp", + "application/was" + ] + }, + "mediaKeyTimestamp": { + "type": "integer", + "minimum": 1, + "maximum": 1099511627776, + "description": "Unix time in seconds when the media key was created." + }, + "width": { + "type": "integer", + "minimum": 1, + "maximum": 65536, + "description": "Width in pixels. Send with height." + }, + "height": { + "type": "integer", + "minimum": 1, + "maximum": 65536, + "description": "Height in pixels. Send with width." + }, + "stickerType": { + "type": "string", + "enum": [ + "static", + "animated", + "lottie" + ] + } + }, + "required": [ + "url", + "directPath", + "mediaKey", + "fileSha256", + "fileEncSha256", + "fileLength", + "mimeType" + ], + "additionalProperties": false, + "oneOf": [ + { + "properties": { + "mimeType": { + "enum": [ + "image/webp" + ] + }, + "stickerType": { + "enum": [ + "static", + "animated" + ] + } + } + }, + { + "properties": { + "mimeType": { + "enum": [ + "application/was" + ] + }, + "stickerType": { + "enum": [ + "lottie" + ] + } + }, + "required": [ + "stickerType" + ] + } + ] + }, + "SendMessageResponse": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "enum": [ + true + ] + }, + "data": { + "$ref": "#/components/schemas/SentMessage" + } + }, + "required": [ + "success", + "data" + ] + }, + "SentMessage": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "whatsapp_ids": { + "$ref": "#/components/schemas/WhatsAppMessageIds" + }, + "whatsapp_id": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", + "deprecated": true + }, + "conversation": { + "allOf": [ + { + "$ref": "#/components/schemas/ConversationIdentity" + }, + { + "description": "The message's conversation, including its public ID and known aliases." + } + ] + }, + "timestamp": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Upstream acceptance status. Delivery and read receipts arrive separately." + }, + "type": { + "type": "string" + }, + "content": { + "$ref": "#/components/schemas/MessageContent" + }, + "mediaId": { + "type": "string" + }, + "hdMessageId": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "ID of the HD half of an image pair, present when `quality: \"hd\"` sent one. `id` is the standard-quality message.", + "example": "739182640518203" + } + }, + "required": [ + "id", + "whatsapp_ids", + "conversation", + "timestamp", + "status", + "type", + "content" + ] + }, + "WhatsAppMessageIds": { + "anyOf": [ + { + "type": "object", + "properties": { + "linked_devices": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "official_api": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + }, + "required": [ + "linked_devices" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "linked_devices": { + "type": "string", + "minLength": 1, + "maxLength": 512 + }, + "official_api": { + "type": "string", + "minLength": 1, + "maxLength": 512 + } + }, + "required": [ + "official_api" + ], + "additionalProperties": false + } + ], + "description": "Exact message references observed through Linked Devices, the Official API, or both. Use the Polymorfa message id for actions and replies. Unknown provider references are omitted." }, - "StickerMediaDescriptor": { + "ConversationIdentity": { "type": "object", "properties": { - "url": { - "type": "string", - "maxLength": 2048, - "pattern": "^https:\\/\\/[!-~]+$", - "description": "Media URL returned by the upload." - }, - "directPath": { + "id": { "type": "string", - "maxLength": 2048, - "pattern": "^\\/(?!\\/)[!-~]+$", - "description": "Direct path returned by the upload." + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" }, - "mediaKey": { + "phoneNumber": { "type": "string", - "pattern": "^[A-Za-z0-9+/]+={0,2}$", - "description": "Base64 32-byte media key you encrypted the file with." + "pattern": "^\\+[1-9]\\d{1,14}$", + "description": "Phone number reported by WhatsApp, when available. It can differ from the number supplied for lookup. Use id for later actions and replies." }, - "fileSha256": { + "bsuid": { "type": "string", - "pattern": "^[A-Za-z0-9+/]+={0,2}$", - "description": "Base64 SHA-256 of the plaintext file." + "pattern": "^[A-Z]{2}\\.[A-Za-z0-9]{1,128}$" }, - "fileEncSha256": { + "username": { "type": "string", - "pattern": "^[A-Za-z0-9+/]+={0,2}$", - "description": "Base64 SHA-256 of the uploaded ciphertext and MAC." + "minLength": 1, + "maxLength": 256 + } + }, + "required": [ + "id" + ], + "additionalProperties": false + }, + "AsyncAcceptedResponse": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "enum": [ + true + ] }, - "fileLength": { - "type": "integer", - "minimum": 1, - "maximum": 2147483648, - "description": "Plaintext file size in bytes." + "data": { + "type": "object", + "properties": { + "requestId": { + "type": "string", + "format": "uuid" + } + }, + "required": [ + "requestId" + ] + } + }, + "required": [ + "success", + "data" + ] + }, + "PublicError": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": [ + "invalid_request_error", + "authentication_error", + "permission_error", + "billing_error", + "conflict_error", + "rate_limit_error", + "api_error", + "upstream_error" + ] + }, + "code": { + "type": "string", + "enum": [ + "zero_knowledge_connection", + "invalid_parameter", + "invalid_credential", + "entitlement_required", + "gate_limit_reached", + "billing_credit_required", + "addon_required", + "safe_mode_not_entitled", + "warmup_plan_not_entitled", + "method_not_allowed", + "permission_denied", + "missing_scope", + "resource_not_found", + "hms_not_enabled", + "media_fetch_failed", + "resource_gone", + "feature_unavailable", + "stream_cursor_invalid", + "stream_cursor_expired", + "stream_connection_limit_reached", + "state_conflict", + "team_deletion_scheduled", + "hybrid_choice_required", + "hybrid_group_linked_devices_unavailable", + "terms_acceptance_required", + "terms_activation_blocked", + "idempotency_conflict", + "idempotency_in_progress", + "idempotency_outcome_unknown", + "idempotency_replay_unavailable", + "call_claimed", + "call_not_ringing", + "connection_limit", + "unsupported_for_connection", + "call_permission_required", + "invalid_sip_trunk", + "calls_disabled", + "call_recipient_opted_out", + "call_destination_blocked", + "call_permission_request_limited", + "call_permission_granted", + "call_opt_out_limit", + "connection_restricted", + "sip_trunk_in_use", + "sip_trunk_revision_conflict", + "sip_trunk_limit", + "sip_unavailable", + "voice_not_enabled", + "provider_credential_invalid", + "provider_unavailable", + "asset_not_ready", + "voice_asset_in_use", + "voice_asset_revision_conflict", + "voice_unavailable", + "rate_limit_exceeded", + "internal_error", + "operation_not_supported", + "upstream_failure", + "service_unavailable", + "credential_verification_unavailable", + "connection_not_ready", + "command_dispatch_failed", + "result_unknown", + "parent_bsuid_not_supported", + "recipient_not_on_whatsapp", + "conversation_window_closed", + "template_not_approved", + "media_too_large", + "whatsapp_rate_limited", + "new_chat_limit_reached", + "marketing_disabled_on_cloud_api", + "whatsapp_account_restricted", + "whatsapp_authorization_required", + "whatsapp_payment_method_required", + "whatsapp_number_not_registered", + "bansafe_suspended", + "bansafe_team_suspended", + "bansafe_cold_blocked", + "bansafe_cold_held", + "bansafe_throttled", + "bansafe_daily_allowance_reached", + "bansafe_accounting_unavailable", + "bansafe_send_outcome_unknown", + "campaigns_not_entitled", + "campaign_throughput_capped", + "campaign_approval_required", + "campaign_approval_stale", + "campaign_variables_missing" + ] + }, + "message": { + "type": "string" + }, + "param": { + "type": "string", + "nullable": true + }, + "request_id": { + "type": "string", + "description": "Matches the X-Request-Id response header. Include it when you contact support." + }, + "request_log_url": { + "type": "string", + "format": "uri", + "description": "Console page that shows this request. Returned only to team and project credentials whose request was logged." + } + }, + "required": [ + "type", + "code", + "message", + "param", + "request_id" + ] }, - "mimeType": { + "data": { "type": "string", + "nullable": true, "enum": [ - "image/webp" - ] - }, - "mediaKeyTimestamp": { - "type": "integer", - "minimum": 1, - "maximum": 1099511627776, - "description": "Unix time in seconds when the media key was created." + null + ], + "description": "Always null for a failed request." }, - "width": { - "type": "integer", - "minimum": 1, - "maximum": 65536, - "description": "Width in pixels. Send with height." + "docs": { + "type": "string", + "format": "uri" + } + }, + "required": [ + "error", + "data", + "docs" + ] + }, + "ReactRequest": { + "type": "object", + "properties": { + "conversation": { + "$ref": "#/components/schemas/ConversationReference" }, - "height": { - "type": "integer", - "minimum": 1, - "maximum": 65536, - "description": "Height in pixels. Send with width." + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" }, - "isAnimated": { - "type": "boolean" + "reaction": { + "type": "string" } }, "required": [ - "url", - "directPath", - "mediaKey", - "fileSha256", - "fileEncSha256", - "fileLength", - "mimeType" + "conversation", + "id", + "reaction" ], "additionalProperties": false }, - "SendMessageResponse": { + "SendReactionResponse": { "type": "object", "properties": { "success": { @@ -3082,7 +4091,7 @@ ] }, "data": { - "$ref": "#/components/schemas/SentMessage" + "$ref": "#/components/schemas/MessageReceipt" } }, "required": [ @@ -3090,7 +4099,7 @@ "data" ] }, - "SentMessage": { + "MessageReceipt": { "type": "object", "properties": { "id": { @@ -3126,469 +4135,637 @@ "status": { "type": "string", "description": "Upstream acceptance status. Delivery and read receipts arrive separately." + } + }, + "required": [ + "id", + "whatsapp_ids", + "conversation", + "timestamp", + "status" + ] + }, + "ListProjectTemplatesResponse": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "enum": [ + true + ] }, - "type": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/MessageTemplate" + } + } + }, + "required": [ + "success", + "data" + ] + }, + "MessageTemplate": { + "type": "object", + "properties": { + "id": { "type": "string" }, - "content": { - "$ref": "#/components/schemas/MessageContent" + "name": { + "type": "string" }, - "mediaId": { + "category": { "type": "string" }, - "hdMessageId": { + "language": { + "type": "string" + }, + "status": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "definition": {}, + "sampleValues": {}, + "cloudLinks": { + "type": "array", + "items": {} + }, + "createdAt": { + "type": "number" + }, + "updatedAt": { + "type": "number" + } + }, + "required": [ + "id", + "name", + "category", + "language", + "status", + "kind", + "cloudLinks", + "createdAt", + "updatedAt" + ] + }, + "GetProjectTemplateResponse": { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "enum": [ + true + ] + }, + "data": { + "$ref": "#/components/schemas/MessageTemplate" + } + }, + "required": [ + "success", + "data" + ] + }, + "MessageReceivedEvent": { + "type": "object", + "properties": { + "id": { "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "ID of the HD half of an image pair, present when `quality: \"hd\"` sent one. `id` is the standard-quality message.", + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" + }, + "connection": { + "type": "string", + "description": "Connection that produced this event", "example": "739182640518203" + }, + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." + }, + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" + }, + "event": { + "type": "string", + "enum": [ + "message.received" + ], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/MessageReceivedPayload" } }, "required": [ "id", - "whatsapp_ids", - "conversation", + "connection", "timestamp", - "status", - "type", - "content" + "event", + "payload" ] }, - "WhatsAppMessageIds": { - "anyOf": [ + "MessageReceivedPayload": { + "oneOf": [ + { + "$ref": "#/components/schemas/MessagePayload" + }, { + "$ref": "#/components/schemas/CloudMessagePayload" + } + ] + }, + "MessagePayload": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "whatsapp_ids": { + "$ref": "#/components/schemas/WhatsAppMessageIds" + }, + "whatsapp_id": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", + "deprecated": true + }, + "conversation": { + "$ref": "#/components/schemas/ConversationRef" + }, + "fromMe": { + "type": "boolean" + }, + "timestamp": { + "type": "number" + }, + "pushName": { + "type": "string" + }, + "isGroup": { + "type": "boolean" + }, + "type": { + "type": "string", + "enum": [ + "text", + "image", + "video", + "audio", + "document", + "location", + "contact", + "phone_number_shared", + "native_flow_response", + "button_reply", + "list_reply", + "poll", + "sticker", + "sticker_pack", + "reaction", + "revoke", + "edited", + "unknown" + ] + }, + "text": { + "type": "string" + }, + "caption": { + "type": "string" + }, + "mimeType": { + "type": "string" + }, + "ptt": { + "type": "boolean" + }, + "filename": { + "type": "string" + }, + "latitude": { + "type": "number" + }, + "longitude": { + "type": "number" + }, + "displayName": { + "type": "string" + }, + "title": { + "type": "string" + }, + "reaction": { + "type": "string" + }, + "reactionTo": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "revokedId": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "nativeFlowResponse": { "type": "object", "properties": { - "linked_devices": { + "name": { "type": "string", "minLength": 1, - "maxLength": 512 + "maxLength": 64 }, - "official_api": { + "paramsJson": { "type": "string", "minLength": 1, - "maxLength": 512 + "maxLength": 262144 + }, + "version": { + "type": "integer", + "minimum": 0 } }, "required": [ - "linked_devices" - ], - "additionalProperties": false + "name", + "paramsJson" + ] }, - { + "replyChoice": { "type": "object", "properties": { - "linked_devices": { + "kind": { "type": "string", - "minLength": 1, - "maxLength": 512 + "enum": [ + "button", + "list" + ], + "description": "Reply control the contact used: a reply or quick-reply button, or a list row." }, - "official_api": { + "id": { "type": "string", "minLength": 1, - "maxLength": 512 + "maxLength": 256, + "description": "ID you assigned to the selected button or list row. It is never the visible label, except for a template quick-reply button sent without a payload, where WhatsApp returns the button text." } }, "required": [ - "official_api" + "kind", + "id" ], - "additionalProperties": false - } - ], - "description": "Exact message references observed through Linked Devices, the Official API, or both. Use the Polymorfa message id for actions and replies. Unknown provider references are omitted." - }, - "ConversationIdentity": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" + "description": "Present when the contact selects a reply button or list row." }, - "phoneNumber": { + "parentMessageId": { "type": "string", - "pattern": "^\\+[1-9]\\d{1,14}$", - "description": "Phone number reported by WhatsApp, when available. It can differ from the number supplied for lookup. Use id for later actions and replies." + "minLength": 1, + "maxLength": 128, + "description": "WhatsApp ID of the message this one quotes, when WhatsApp supplies one. It is not necessarily a message you sent." }, - "bsuid": { - "type": "string", - "pattern": "^[A-Z]{2}\\.[A-Za-z0-9]{1,128}$" + "media": { + "type": "string" }, - "username": { + "mediaUrl": { + "type": "string" + }, + "edited": { + "type": "boolean" + }, + "pollOptions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PollOption" + } + }, + "unavailable": { + "type": "boolean" + }, + "unavailableReason": { + "type": "string" + }, + "stickerType": { "type": "string", - "minLength": 1, - "maxLength": 256 - } - }, - "required": [ - "id" - ], - "additionalProperties": false - }, - "AsyncAcceptedResponse": { - "type": "object", - "properties": { - "success": { - "type": "boolean", "enum": [ - true + "static", + "animated", + "lottie" ] }, - "data": { - "type": "object", - "properties": { - "requestId": { - "type": "string", - "format": "uuid" - } - }, - "required": [ - "requestId" + "origin": { + "type": "string", + "enum": [ + "avatar", + "ai" ] - } - }, - "required": [ - "success", - "data" - ] - }, - "PublicError": { - "type": "object", - "properties": { - "error": { - "type": "object", - "properties": { - "type": { - "type": "string", - "enum": [ - "invalid_request_error", - "authentication_error", - "permission_error", - "billing_error", - "conflict_error", - "rate_limit_error", - "api_error", - "upstream_error" - ] - }, - "code": { - "type": "string", - "enum": [ - "zero_knowledge_session", - "invalid_parameter", - "invalid_credential", - "entitlement_required", - "gate_limit_reached", - "billing_credit_required", - "addon_required", - "safe_mode_not_entitled", - "warmup_plan_not_entitled", - "method_not_allowed", - "permission_denied", - "missing_scope", - "resource_not_found", - "hms_not_enabled", - "media_fetch_failed", - "resource_gone", - "feature_unavailable", - "stream_cursor_invalid", - "stream_cursor_expired", - "stream_connection_limit_reached", - "state_conflict", - "team_deletion_scheduled", - "hybrid_choice_required", - "hybrid_group_linked_devices_unavailable", - "idempotency_conflict", - "idempotency_in_progress", - "idempotency_completed", - "idempotency_outcome_unknown", - "call_claimed", - "call_not_ringing", - "connection_limit", - "unsupported_for_connection", - "call_permission_required", - "invalid_sip_trunk", - "calls_disabled", - "call_recipient_opted_out", - "call_destination_blocked", - "call_permission_request_limited", - "call_permission_granted", - "call_opt_out_limit", - "number_restricted", - "sip_trunk_in_use", - "sip_trunk_revision_conflict", - "sip_trunk_limit", - "sip_unavailable", - "voice_not_enabled", - "provider_credential_invalid", - "provider_unavailable", - "asset_not_ready", - "voice_asset_in_use", - "voice_asset_revision_conflict", - "voice_unavailable", - "rate_limit_exceeded", - "internal_error", - "operation_not_supported", - "upstream_failure", - "service_unavailable", - "credential_verification_unavailable", - "session_not_ready", - "command_dispatch_failed", - "result_unknown", - "parent_bsuid_not_supported", - "recipient_not_on_whatsapp", - "conversation_window_closed", - "template_not_approved", - "media_too_large", - "whatsapp_rate_limited", - "new_chat_limit_reached", - "marketing_disabled_on_cloud_api", - "whatsapp_account_restricted", - "whatsapp_authorization_required", - "whatsapp_payment_method_required", - "whatsapp_number_not_registered", - "bansafe_suspended", - "bansafe_org_suspended", - "bansafe_cold_blocked", - "bansafe_cold_held", - "bansafe_throttled", - "bansafe_daily_allowance_reached", - "bansafe_accounting_unavailable", - "bansafe_send_outcome_unknown", - "campaigns_not_entitled", - "campaign_throughput_capped", - "campaign_approval_required", - "campaign_approval_stale", - "campaign_variables_missing" - ] - }, - "message": { - "type": "string" - }, - "param": { - "type": "string", - "nullable": true - }, - "request_id": { - "type": "string", - "description": "Matches the X-Request-Id response header. Include it when you contact support." - }, - "request_log_url": { - "type": "string", - "format": "uri", - "description": "Console page that shows this request. Returned only to organization and project credentials whose request was logged." - } + }, + "emojis": { + "type": "array", + "items": { + "type": "string" + } + }, + "accessibilityLabel": { + "type": "string" + }, + "stickerPack": { + "$ref": "#/components/schemas/StickerPackMetadata" + }, + "width": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true, + "description": "Image, video or sticker width in pixels, as declared by the sender." + }, + "height": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true, + "description": "Image, video or sticker height in pixels, as declared by the sender." + }, + "seconds": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true, + "description": "Audio or video duration in seconds." + }, + "waveform": { + "type": "array", + "items": { + "type": "number", + "minimum": 0, + "maximum": 1 }, - "required": [ - "type", - "code", - "message", - "param", - "request_id" - ] + "maxItems": 64, + "description": "Voice-note waveform: up to 64 samples from 0 to 1." }, - "data": { + "pageCount": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true, + "description": "Document page count, as declared by the sender." + }, + "thumbnail": { + "$ref": "#/components/schemas/MediaThumbnail" + }, + "linkPreview": { + "$ref": "#/components/schemas/LinkPreview" + }, + "association": { + "$ref": "#/components/schemas/MessageAssociation" + }, + "quality": { "type": "string", - "nullable": true, "enum": [ - null + "standard", + "hd" ], - "description": "Always null for a failed request." + "description": "`hd` on the HD half of a pair; `standard` on a standard message that announced an HD half." + } + }, + "required": [ + "id", + "whatsapp_ids", + "conversation", + "fromMe", + "timestamp", + "pushName", + "isGroup", + "type" + ] + }, + "ConversationRef": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" }, - "docs": { + "phoneNumber": { + "type": "string" + }, + "bsuid": { + "type": "string" + }, + "username": { + "type": "string" + }, + "parentBsuid": { "type": "string", - "format": "uri" + "description": "Parent business-scoped user ID (`CC.ENT.…`), present only when WhatsApp reports one for this person. It identifies the person across the business portfolios enrolled in one parent account. It cannot be used to send messages or block people; use `id` or `bsuid`.", + "example": "US.ENT.11815799212886844830" + }, + "sender": { + "$ref": "#/components/schemas/IdentityRef" } }, "required": [ - "error", - "data", - "docs" + "id" ] }, - "ReactRequest": { + "IdentityRef": { "type": "object", "properties": { - "conversation": { - "$ref": "#/components/schemas/ConversationReference" - }, "id": { "type": "string", "pattern": "^[1-9][0-9]{0,18}$", "description": "Opaque Polymorfa resource ID. Keep this value as a string.", "example": "739182640518203" }, - "reaction": { + "phoneNumber": { + "type": "string" + }, + "bsuid": { + "type": "string" + }, + "username": { "type": "string" + }, + "parentBsuid": { + "type": "string", + "description": "Parent business-scoped user ID (`CC.ENT.…`), present only when WhatsApp reports one for this person. It identifies the person across the business portfolios enrolled in one parent account. It cannot be used to send messages or block people; use `id` or `bsuid`.", + "example": "US.ENT.11815799212886844830" } }, "required": [ - "conversation", - "id", - "reaction" - ], - "additionalProperties": false + "id" + ] }, - "SendReactionResponse": { + "PollOption": { "type": "object", "properties": { - "success": { - "type": "boolean", - "enum": [ - true - ] + "name": { + "type": "string" }, - "data": { - "$ref": "#/components/schemas/MessageReceipt" + "hash": { + "type": "string" } }, "required": [ - "success", - "data" + "name", + "hash" ] }, - "MessageReceipt": { + "StickerPackMetadata": { "type": "object", "properties": { "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" + "type": "string" }, - "whatsapp_ids": { - "$ref": "#/components/schemas/WhatsAppMessageIds" + "name": { + "type": "string" }, - "whatsapp_id": { - "type": "string", - "minLength": 1, - "maxLength": 512, - "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", - "deprecated": true + "publisher": { + "type": "string" }, - "conversation": { - "allOf": [ - { - "$ref": "#/components/schemas/ConversationIdentity" - }, - { - "description": "The message's conversation, including its public ID and known aliases." - } - ] + "description": { + "type": "string" }, - "timestamp": { - "type": "string", - "format": "date-time" + "trayIconFileName": { + "type": "string" }, - "status": { - "type": "string", - "description": "Upstream acceptance status. Delivery and read receipts arrive separately." + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StickerPackItem" + } } }, "required": [ "id", - "whatsapp_ids", - "conversation", - "timestamp", - "status" + "name", + "publisher", + "items" ] }, - "ListProjectTemplatesResponse": { + "StickerPackItem": { "type": "object", "properties": { - "success": { - "type": "boolean", + "fileName": { + "type": "string" + }, + "stickerType": { + "type": "string", "enum": [ - true + "static", + "animated", + "lottie" ] }, - "data": { + "mimeType": { + "type": "string" + }, + "emojis": { "type": "array", "items": { - "$ref": "#/components/schemas/MessageTemplate" + "type": "string" } + }, + "accessibilityLabel": { + "type": "string" + }, + "premium": { + "type": "integer" } }, "required": [ - "success", - "data" + "fileName", + "stickerType", + "mimeType" ] }, - "MessageTemplate": { + "MediaThumbnail": { "type": "object", "properties": { - "id": { - "type": "string" + "contentType": { + "type": "string", + "enum": [ + "image/jpeg" + ] }, - "name": { - "type": "string" + "data": { + "type": "string", + "description": "Base64-encoded JPEG bytes, at most 16 KiB decoded." }, - "category": { - "type": "string" + "width": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true }, - "language": { - "type": "string" + "height": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true + } + }, + "required": [ + "contentType", + "data" + ], + "description": "Low-resolution JPEG preview embedded in the message. Present only when the sender embedded one of at most 16 KiB; previews WhatsApp stores separately are not fetched." + }, + "LinkPreview": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL the preview describes, as matched in the message text." }, - "status": { + "title": { "type": "string" }, - "kind": { + "description": { "type": "string" }, - "definition": {}, - "sampleValues": {}, - "cloudLinks": { - "type": "array", - "items": {} - }, - "createdAt": { - "type": "number" + "previewType": { + "type": "string", + "description": "WhatsApp's preview kind in lower case, such as `none`, `video` or `image`." }, - "updatedAt": { - "type": "number" + "thumbnail": { + "$ref": "#/components/schemas/MediaThumbnail" } }, "required": [ - "id", - "name", - "category", - "language", - "status", - "kind", - "cloudLinks", - "createdAt", - "updatedAt" - ] + "url" + ], + "description": "Preview the sender attached to a text message containing a URL." }, - "GetProjectTemplateResponse": { + "MessageAssociation": { "type": "object", "properties": { - "success": { - "type": "boolean", + "type": { + "type": "string", "enum": [ - true + "hd_image", + "hd_video" ] }, - "data": { - "$ref": "#/components/schemas/MessageTemplate" + "parentMessageId": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "`id` of the standard-quality message this HD message belongs to. It can arrive before that message.", + "example": "739182640518203" } }, "required": [ - "success", - "data" - ] - }, - "MessageReceivedPayload": { - "oneOf": [ - { - "$ref": "#/components/schemas/MessagePayload" - }, - { - "$ref": "#/components/schemas/CloudMessagePayload" - } - ] + "type", + "parentMessageId" + ], + "description": "Present on the HD half of an HD media pair. Show it in place of the standard message it names." }, - "MessagePayload": { + "CloudMessagePayload": { "type": "object", "properties": { "id": { @@ -3610,82 +4787,15 @@ "conversation": { "$ref": "#/components/schemas/ConversationRef" }, - "fromMe": { - "type": "boolean" - }, "timestamp": { - "type": "number" - }, - "pushName": { "type": "string" }, - "isGroup": { - "type": "boolean" - }, "type": { - "type": "string", - "enum": [ - "text", - "image", - "video", - "audio", - "document", - "location", - "contact", - "phone_number_shared", - "native_flow_response", - "button_reply", - "list_reply", - "poll", - "sticker", - "reaction", - "revoke", - "edited", - "unknown" - ] - }, - "text": { - "type": "string" - }, - "caption": { - "type": "string" - }, - "mimeType": { - "type": "string" - }, - "ptt": { - "type": "boolean" - }, - "filename": { - "type": "string" - }, - "latitude": { - "type": "number" - }, - "longitude": { - "type": "number" - }, - "displayName": { "type": "string" }, - "title": { - "type": "string" - }, - "reaction": { + "senderName": { "type": "string" }, - "reactionTo": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "revokedId": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, "nativeFlowResponse": { "type": "object", "properties": { @@ -3739,27 +4849,198 @@ "maxLength": 128, "description": "WhatsApp ID of the message this one quotes, when WhatsApp supplies one. It is not necessarily a message you sent." }, - "media": { - "type": "string" + "interactive": { + "type": "object", + "additionalProperties": {} + }, + "order": { + "$ref": "#/components/schemas/CloudOrder" + }, + "referral": { + "type": "object", + "properties": { + "source_type": { + "type": "string" + }, + "source_id": { + "type": "string" + }, + "source_url": { + "type": "string" + }, + "ctwa_clid": { + "type": "string" + } + }, + "description": "Meta-supplied Click-to-WhatsApp entry point. Does not establish a conversion or payment." + } + }, + "required": [ + "id", + "whatsapp_ids", + "conversation", + "timestamp", + "type" + ] + }, + "CloudOrder": { + "type": "object", + "properties": { + "catalogId": { + "type": "string", + "pattern": "^[0-9]{1,32}$", + "description": "Meta catalog ID the cart was built from." + }, + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4096, + "description": "Text the contact sent with the order." + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/CloudOrderItem" + }, + "minItems": 1, + "maxItems": 1000 + } + }, + "required": [ + "catalogId", + "items" + ], + "description": "Present on `type: \"order\"` messages when every cart line is readable. There is no order total: multiply `quantity` by `itemPrice` per item if you need one. Prices and availability can differ from your catalog; confirm them before you fulfil the order." + }, + "CloudOrderItem": { + "type": "object", + "properties": { + "productRetailerId": { + "type": "string", + "minLength": 1, + "maxLength": 256, + "description": "Your retailer ID (SKU), at most 256 UTF-8 bytes with no control characters." + }, + "quantity": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true, + "description": "Units ordered." + }, + "itemPrice": { + "type": "number", + "minimum": 0, + "description": "Unit price as Meta reported it. Polymorfa does not convert or recompute it." + }, + "currency": { + "type": "string", + "pattern": "^[A-Z]{3}$", + "description": "ISO 4217 currency code Meta reported for the item." + } + }, + "required": [ + "productRetailerId", + "quantity", + "itemPrice", + "currency" + ] + }, + "MessageSentEvent": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" + }, + "connection": { + "type": "string", + "description": "Connection that produced this event", + "example": "739182640518203" + }, + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." + }, + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" + }, + "event": { + "type": "string", + "enum": [ + "message.sent" + ], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/MessageSentPayload" + } + }, + "required": [ + "id", + "connection", + "timestamp", + "event", + "payload" + ] + }, + "MessageSentPayload": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "whatsapp_ids": { + "$ref": "#/components/schemas/WhatsAppMessageIds" + }, + "whatsapp_id": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", + "deprecated": true + }, + "conversation": { + "$ref": "#/components/schemas/ConversationRef" }, - "mediaUrl": { + "type": { "type": "string" }, - "edited": { - "type": "boolean" + "timestamp": { + "type": "number" }, - "pollOptions": { + "stickerType": { + "type": "string", + "enum": [ + "static", + "animated", + "lottie" + ] + }, + "origin": { + "type": "string", + "enum": [ + "avatar", + "ai" + ] + }, + "emojis": { "type": "array", "items": { - "$ref": "#/components/schemas/PollOption" + "type": "string" } }, - "unavailable": { - "type": "boolean" - }, - "unavailableReason": { + "accessibilityLabel": { "type": "string" }, + "stickerPack": { + "$ref": "#/components/schemas/StickerPackMetadata" + }, "width": { "type": "integer", "minimum": 0, @@ -3816,516 +5097,622 @@ "id", "whatsapp_ids", "conversation", - "fromMe", - "timestamp", - "pushName", - "isGroup", - "type" + "type", + "timestamp" ] }, - "ConversationRef": { + "MessageAckEvent": { "type": "object", "properties": { "id": { "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" }, - "phoneNumber": { - "type": "string" + "connection": { + "type": "string", + "description": "Connection that produced this event", + "example": "739182640518203" }, - "bsuid": { - "type": "string" + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." }, - "username": { - "type": "string" + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" }, - "parentBsuid": { + "event": { "type": "string", - "description": "Parent business-scoped user ID (`CC.ENT.…`), present only when WhatsApp reports one for this person. It identifies the person across the business portfolios enrolled in one parent account. It cannot be used to send messages or block people; use `id` or `bsuid`.", - "example": "US.ENT.11815799212886844830" + "enum": [ + "message.ack" + ], + "description": "Event type" }, - "sender": { - "$ref": "#/components/schemas/IdentityRef" + "payload": { + "$ref": "#/components/schemas/MessageAckPayload" } }, "required": [ - "id" + "id", + "connection", + "timestamp", + "event", + "payload" ] }, - "IdentityRef": { + "MessageAckPayload": { "type": "object", "properties": { - "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" + "messages": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" + }, + "whatsapp_ids": { + "$ref": "#/components/schemas/WhatsAppMessageIds" + }, + "whatsapp_id": { + "type": "string", + "minLength": 1, + "maxLength": 512, + "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", + "deprecated": true + } + }, + "required": [ + "id", + "whatsapp_ids" + ] + } }, - "phoneNumber": { - "type": "string" + "conversation": { + "$ref": "#/components/schemas/ConversationRef" }, - "bsuid": { - "type": "string" + "from": { + "$ref": "#/components/schemas/IdentityRef" }, - "username": { - "type": "string" + "sender": { + "$ref": "#/components/schemas/IdentityRef" }, - "parentBsuid": { + "type": { "type": "string", - "description": "Parent business-scoped user ID (`CC.ENT.…`), present only when WhatsApp reports one for this person. It identifies the person across the business portfolios enrolled in one parent account. It cannot be used to send messages or block people; use `id` or `bsuid`.", - "example": "US.ENT.11815799212886844830" + "description": "Ack type: error, delivered, read, played" + }, + "timestamp": { + "type": "number" + }, + "pricing": { + "$ref": "#/components/schemas/MetaPricingReport" } }, "required": [ - "id" + "messages", + "conversation", + "type", + "timestamp" ] }, - "PollOption": { + "MetaPricingReport": { "type": "object", "properties": { - "name": { - "type": "string" + "billable": { + "type": "boolean", + "description": "Whether WhatsApp reported the message as billable. WhatsApp is deprecating this field; use `type`." }, - "hash": { - "type": "string" + "pricing_model": { + "type": "string", + "description": "WhatsApp pricing model, for example `PMP` (per-message pricing).", + "example": "PMP" + }, + "category": { + "type": "string", + "description": "WhatsApp pricing category, for example `marketing`, `utility`, `authentication` or `service`.", + "example": "utility" + }, + "type": { + "type": "string", + "description": "WhatsApp pricing type, for example `regular`, `free_customer_service` or `free_entry_point`.", + "example": "free_customer_service" + } + }, + "description": "Official API only. The pricing classification WhatsApp reported for this message, copied as reported. Meta bills your WhatsApp Business Account directly; this is not a Polymorfa charge and contains no price." + }, + "MessageUpdateEvent": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" + }, + "connection": { + "type": "string", + "description": "Connection that produced this event", + "example": "739182640518203" + }, + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." + }, + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" + }, + "event": { + "type": "string", + "enum": [ + "message.update" + ], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/MessagePayload" } }, "required": [ - "name", - "hash" + "id", + "connection", + "timestamp", + "event", + "payload" ] }, - "MediaThumbnail": { + "ConnectionStatusEvent": { "type": "object", "properties": { - "contentType": { + "id": { "type": "string", - "enum": [ - "image/jpeg" - ] + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" }, - "data": { + "connection": { "type": "string", - "description": "Base64-encoded JPEG bytes, at most 16 KiB decoded." + "description": "Connection that produced this event", + "example": "739182640518203" }, - "width": { - "type": "integer", - "minimum": 0, - "exclusiveMinimum": true + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." }, - "height": { - "type": "integer", - "minimum": 0, - "exclusiveMinimum": true + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" + }, + "event": { + "type": "string", + "enum": [ + "connection.status" + ], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/ConnectionStatusPayload" } }, "required": [ - "contentType", - "data" - ], - "description": "Low-resolution JPEG preview embedded in the message. Present only when the sender embedded one of at most 16 KiB; previews WhatsApp stores separately are not fetched." + "id", + "connection", + "timestamp", + "event", + "payload" + ] }, - "LinkPreview": { + "ConnectionStatusPayload": { + "anyOf": [ + { + "$ref": "#/components/schemas/RuntimeConnectionStatusPayload" + }, + { + "$ref": "#/components/schemas/CloudAccountStatusPayload" + } + ] + }, + "RuntimeConnectionStatusPayload": { "type": "object", "properties": { - "url": { + "status": { "type": "string", - "description": "The URL the preview describes, as matched in the message text." + "description": "Connection status: CONNECTING, CONNECTED, DISCONNECTED", + "example": "DISCONNECTED" }, - "title": { - "type": "string" + "statusReason": { + "type": "string", + "description": "Reason for the status: SCAN_QR, AUTO_RECONNECT, FAILED, MANUAL_STOP, QR_TIMEOUT, LOGGED_OUT, TEMPORARY_BAN, STREAM_ERROR", + "example": "TEMPORARY_BAN" }, - "description": { - "type": "string" + "banCode": { + "type": "integer", + "minimum": 0, + "description": "WhatsApp temporary-ban code (present only when statusReason is TEMPORARY_BAN).", + "example": 101 }, - "previewType": { + "banReason": { "type": "string", - "description": "WhatsApp's preview kind in lower case, such as `none`, `video` or `image`." + "description": "Human-readable label for the ban code (present only when statusReason is TEMPORARY_BAN).", + "example": "Suspected spam activity" }, - "thumbnail": { - "$ref": "#/components/schemas/MediaThumbnail" + "banExpiresAt": { + "type": "integer", + "description": "Unix timestamp in seconds when the temporary ban lifts, when WhatsApp provides a duration.", + "format": "int64", + "example": 1789000000 + }, + "detail": { + "type": "string", + "description": "Extra context for FAILED and STREAM_ERROR statuses (for example the connect-failure reason)." } }, "required": [ - "url" - ], - "description": "Preview the sender attached to a text message containing a URL." + "status" + ] }, - "MessageAssociation": { + "CloudAccountStatusPayload": { "type": "object", "properties": { - "type": { + "source": { "type": "string", "enum": [ - "hd_image", - "hd_video" - ] + "meta" + ], + "description": "Always `meta`: a WhatsApp Business Account notification, not a method-state change" }, - "parentMessageId": { + "kind": { "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "`id` of the standard-quality message this HD message belongs to. It can arrive before that message.", - "example": "739182640518203" + "enum": [ + "account_alerts", + "account_update", + "phone_number_name_update" + ], + "description": "WhatsApp notification field that produced the event" + }, + "wabaId": { + "type": "string", + "description": "WhatsApp Business Account id the notification belongs to", + "example": "102290129340398" + }, + "value": { + "type": "object", + "additionalProperties": {}, + "description": "The notification's `value` object exactly as WhatsApp sent it; its fields vary by notification" } }, "required": [ - "type", - "parentMessageId" - ], - "description": "Present on the HD half of an HD media pair. Show it in place of the standard message it names." + "source", + "kind", + "value" + ] }, - "CloudMessagePayload": { + "ConnectionConnectedEvent": { "type": "object", "properties": { "id": { "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" + }, + "connection": { + "type": "string", + "description": "Connection that produced this event", "example": "739182640518203" }, - "whatsapp_ids": { - "$ref": "#/components/schemas/WhatsAppMessageIds" + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." }, - "whatsapp_id": { + "timestamp": { "type": "string", - "minLength": 1, - "maxLength": 512, - "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", - "deprecated": true + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" }, - "conversation": { - "$ref": "#/components/schemas/ConversationRef" + "event": { + "type": "string", + "enum": [ + "connection.connected" + ], + "description": "Event type" }, - "timestamp": { + "payload": { + "$ref": "#/components/schemas/ConnectionConnectedPayload" + } + }, + "required": [ + "id", + "connection", + "timestamp", + "event", + "payload" + ] + }, + "ConnectionConnectedPayload": { + "type": "object", + "properties": { + "phoneNumber": { "type": "string" }, - "type": { - "type": "string" + "id": { + "type": "string", + "description": "Polymorfa ID of the connected account." }, - "senderName": { + "pushName": { "type": "string" }, - "nativeFlowResponse": { - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1, - "maxLength": 64 - }, - "paramsJson": { - "type": "string", - "minLength": 1, - "maxLength": 262144 - }, - "version": { - "type": "integer", - "minimum": 0 - } - }, - "required": [ - "name", - "paramsJson" - ] - }, - "replyChoice": { - "type": "object", - "properties": { - "kind": { - "type": "string", - "enum": [ - "button", - "list" - ], - "description": "Reply control the contact used: a reply or quick-reply button, or a list row." - }, - "id": { - "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "ID you assigned to the selected button or list row. It is never the visible label, except for a template quick-reply button sent without a payload, where WhatsApp returns the button text." - } - }, - "required": [ - "kind", - "id" + "phonePlatform": { + "type": "string", + "enum": [ + "android", + "ios", + "meta_cloud", + "unknown" ], - "description": "Present when the contact selects a reply button or list row." + "description": "Where the account's primary WhatsApp client runs.", + "x-enumDescriptions": { + "android": "WhatsApp or WhatsApp Business on an Android phone.", + "ios": "WhatsApp or WhatsApp Business on an iPhone.", + "meta_cloud": "Meta hosts the connection through Cloud API.", + "unknown": "The phone has not reported a recognized platform." + } }, - "parentMessageId": { + "accountType": { "type": "string", - "minLength": 1, - "maxLength": 128, - "description": "WhatsApp ID of the message this one quotes, when WhatsApp supplies one. It is not necessarily a message you sent." - }, - "interactive": { - "type": "object", - "additionalProperties": {} - }, - "order": { - "$ref": "#/components/schemas/CloudOrder" + "enum": [ + "whatsapp_app", + "business_app", + "meta_cloud", + "meta_coexistence" + ], + "description": "How the account uses WhatsApp.", + "x-enumDescriptions": { + "whatsapp_app": "WhatsApp app, connected as a linked device.", + "business_app": "WhatsApp Business app, connected as a linked device.", + "meta_cloud": "Meta Cloud API.", + "meta_coexistence": "Meta Cloud API, with the WhatsApp Business app still active on the phone." + } }, - "referral": { - "type": "object", - "properties": { - "source_type": { - "type": "string" - }, - "source_id": { - "type": "string" - }, - "source_url": { - "type": "string" - }, - "ctwa_clid": { - "type": "string" - } - }, - "description": "Meta-supplied Click-to-WhatsApp entry point. Does not establish a conversion or payment." + "businessName": { + "type": "string" } }, "required": [ - "id", - "whatsapp_ids", - "conversation", - "timestamp", - "type" + "phoneNumber", + "pushName", + "phonePlatform", + "accountType" ] }, - "CloudOrder": { + "ConnectionLoggedOutEvent": { "type": "object", "properties": { - "catalogId": { + "id": { "type": "string", - "pattern": "^[0-9]{1,32}$", - "description": "Meta catalog ID the cart was built from." + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" }, - "text": { + "connection": { "type": "string", - "minLength": 1, - "maxLength": 4096, - "description": "Text the contact sent with the order." + "description": "Connection that produced this event", + "example": "739182640518203" }, - "items": { - "type": "array", - "items": { - "$ref": "#/components/schemas/CloudOrderItem" - }, - "minItems": 1, - "maxItems": 1000 + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." + }, + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" + }, + "event": { + "type": "string", + "enum": [ + "connection.logged_out" + ], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/ConnectionLoggedOutPayload" } }, "required": [ - "catalogId", - "items" - ], - "description": "Present on `type: \"order\"` messages when every cart line is readable. There is no order total: multiply `quantity` by `itemPrice` per item if you need one. Prices and availability can differ from your catalog; confirm them before you fulfil the order." + "id", + "connection", + "timestamp", + "event", + "payload" + ] }, - "CloudOrderItem": { + "ConnectionLoggedOutPayload": { "type": "object", "properties": { - "productRetailerId": { + "reason": { "type": "string", - "minLength": 1, - "maxLength": 256, - "description": "Your retailer ID (SKU), at most 256 UTF-8 bytes with no control characters." + "enum": [ + "banned", + "device_removed", + "unknown" + ], + "description": "Why the connection was logged out: `banned` when WhatsApp banned the account, `device_removed` when the linked device was removed from the phone or from another device, `unknown` otherwise (including a locked account).", + "example": "device_removed" }, - "quantity": { + "code": { "type": "integer", - "minimum": 0, - "exclusiveMinimum": true, - "description": "Units ordered." - }, - "itemPrice": { - "type": "number", - "minimum": 0, - "description": "Unit price as Meta reported it. Polymorfa does not convert or recompute it." - }, - "currency": { - "type": "string", - "pattern": "^[A-Z]{3}$", - "description": "ISO 4217 currency code Meta reported for the item." + "description": "WhatsApp's logout code: 401 (removed), 403 (locked) or 406 (banned); 0 when WhatsApp gave none.", + "example": 401 } }, "required": [ - "productRetailerId", - "quantity", - "itemPrice", - "currency" + "reason", + "code" ] }, - "MessageSentPayload": { + "CallEndedEvent": { "type": "object", "properties": { "id": { "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "whatsapp_ids": { - "$ref": "#/components/schemas/WhatsAppMessageIds" + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" }, - "whatsapp_id": { + "connection": { "type": "string", - "minLength": 1, - "maxLength": 512, - "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", - "deprecated": true - }, - "conversation": { - "$ref": "#/components/schemas/ConversationRef" + "description": "Connection that produced this event", + "example": "739182640518203" }, - "type": { - "type": "string" + "externalId": { + "type": "string", + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." }, "timestamp": { - "type": "number" - }, - "width": { - "type": "integer", - "minimum": 0, - "exclusiveMinimum": true, - "description": "Image, video or sticker width in pixels, as declared by the sender." - }, - "height": { - "type": "integer", - "minimum": 0, - "exclusiveMinimum": true, - "description": "Image, video or sticker height in pixels, as declared by the sender." - }, - "seconds": { - "type": "integer", - "minimum": 0, - "exclusiveMinimum": true, - "description": "Audio or video duration in seconds." - }, - "waveform": { - "type": "array", - "items": { - "type": "number", - "minimum": 0, - "maximum": 1 - }, - "maxItems": 64, - "description": "Voice-note waveform: up to 64 samples from 0 to 1." - }, - "pageCount": { - "type": "integer", - "minimum": 0, - "exclusiveMinimum": true, - "description": "Document page count, as declared by the sender." - }, - "thumbnail": { - "$ref": "#/components/schemas/MediaThumbnail" - }, - "linkPreview": { - "$ref": "#/components/schemas/LinkPreview" - }, - "association": { - "$ref": "#/components/schemas/MessageAssociation" + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" }, - "quality": { + "event": { "type": "string", "enum": [ - "standard", - "hd" + "call.ended" ], - "description": "`hd` on the HD half of a pair; `standard` on a standard message that announced an HD half." + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/CallEndedPayload" } }, "required": [ "id", - "whatsapp_ids", - "conversation", - "type", - "timestamp" + "connection", + "timestamp", + "event", + "payload" ] }, - "MessageAckPayload": { + "CallEndedPayload": { "type": "object", "properties": { - "messages": { - "type": "array", - "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "whatsapp_ids": { - "$ref": "#/components/schemas/WhatsAppMessageIds" - }, - "whatsapp_id": { - "type": "string", - "minLength": 1, - "maxLength": 512, - "description": "Temporary singular provider reference for older consumers. Use whatsapp_ids for transport-specific references.", - "deprecated": true - } + "from": { + "type": "object", + "nullable": true, + "properties": { + "id": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$", + "description": "Opaque Polymorfa resource ID. Keep this value as a string.", + "example": "739182640518203" }, - "required": [ - "id", - "whatsapp_ids" - ] - } + "phoneNumber": { + "type": "string" + }, + "bsuid": { + "type": "string" + }, + "username": { + "type": "string" + }, + "parentBsuid": { + "type": "string", + "description": "Parent business-scoped user ID (`CC.ENT.…`), present only when WhatsApp reports one for this person. It identifies the person across the business portfolios enrolled in one parent account. It cannot be used to send messages or block people; use `id` or `bsuid`.", + "example": "US.ENT.11815799212886844830" + } + }, + "required": [ + "id" + ] }, - "conversation": { - "$ref": "#/components/schemas/ConversationRef" + "callId": { + "type": "string" }, - "from": { - "$ref": "#/components/schemas/IdentityRef" + "durationSeconds": { + "type": "integer", + "description": "Total connected duration in seconds (0 if never answered).", + "example": 42 }, - "sender": { - "$ref": "#/components/schemas/IdentityRef" + "reason": { + "type": "string", + "description": "Termination reason: user_hangup | timeout | lost_connection | rejected | capacity | pod_lost | connection_failed | upstream_failed | call_restricted (WhatsApp refused the call because the connection is restricted to calling people it has already chatted with).", + "example": "user_hangup" }, - "type": { + "direction": { "type": "string", - "description": "Ack type: error, delivered, read, played" + "enum": [ + "inbound", + "outbound" + ], + "description": "Call direction.", + "example": "inbound" }, - "timestamp": { - "type": "number" + "hadVideo": { + "type": "boolean", + "description": "Whether the call carried video.", + "example": false }, - "pricing": { - "$ref": "#/components/schemas/MetaPricingReport" + "connectionMethod": { + "type": "string", + "enum": [ + "linked_device", + "cloud_api" + ], + "description": "Method that carries the call: a linked device or the WhatsApp Business Cloud API.", + "example": "linked_device" } }, "required": [ - "messages", - "conversation", - "type", - "timestamp" + "from", + "callId", + "durationSeconds", + "reason", + "direction", + "hadVideo" ] }, - "MetaPricingReport": { + "MessageFailedEvent": { "type": "object", "properties": { - "billable": { - "type": "boolean", - "description": "Whether WhatsApp reported the message as billable. WhatsApp is deprecating this field; use `type`." + "id": { + "type": "string", + "description": "Unique event identifier", + "example": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71" }, - "pricing_model": { + "connection": { "type": "string", - "description": "WhatsApp pricing model, for example `PMP` (per-message pricing).", - "example": "PMP" + "description": "Connection that produced this event", + "example": "739182640518203" }, - "category": { + "externalId": { "type": "string", - "description": "WhatsApp pricing category, for example `marketing`, `utility`, `authentication` or `service`.", - "example": "utility" + "description": "Integrator reference from the QuickLink that created this connection. Included on connection lifecycle events when supplied." + }, + "timestamp": { + "type": "string", + "description": "ISO 8601 timestamp", + "example": "2026-10-19T14:03:22.000Z" }, - "type": { + "event": { "type": "string", - "description": "WhatsApp pricing type, for example `regular`, `free_customer_service` or `free_entry_point`.", - "example": "free_customer_service" + "enum": [ + "message.failed" + ], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/MessageFailedPayload" } }, - "description": "Official API only. The pricing classification WhatsApp reported for this message, copied as reported. Meta bills your WhatsApp Business Account directly; this is not a Polymorfa charge and contains no price." + "required": [ + "id", + "connection", + "timestamp", + "event", + "payload" + ] }, "MessageFailedPayload": { "type": "object", @@ -4349,7 +5736,7 @@ "type": "string", "enum": [ "invalid_recipient", - "session_not_connected", + "connection_not_connected", "ack_timeout", "send_failed", "blocked_by_safety" @@ -4383,255 +5770,202 @@ "timestamp" ] }, - "SessionStatusPayload": { - "anyOf": [ - { - "$ref": "#/components/schemas/RuntimeSessionStatusPayload" - }, - { - "$ref": "#/components/schemas/CloudAccountStatusPayload" - } - ] - }, - "RuntimeSessionStatusPayload": { + "TriggerTestEventResponse": { "type": "object", "properties": { - "status": { - "type": "string", - "description": "Session status: CONNECTING, CONNECTED, DISCONNECTED", - "example": "DISCONNECTED" - }, - "statusReason": { + "event": { "type": "string", - "description": "Reason for the status: SCAN_QR, AUTO_RECONNECT, FAILED, MANUAL_STOP, QR_TIMEOUT, LOGGED_OUT, TEMPORARY_BAN, STREAM_ERROR", - "example": "TEMPORARY_BAN" + "enum": [ + "message.received", + "message.ack", + "message.failed", + "call.received", + "call.missed", + "call.ended", + "connection.status", + "connection.restriction_updated", + "template.status" + ] }, - "banCode": { - "type": "integer", - "minimum": 0, - "description": "WhatsApp temporary-ban code (present only when statusReason is TEMPORARY_BAN).", - "example": 101 + "connection": { + "type": "string" }, - "banReason": { + "delivery": { "type": "string", - "description": "Human-readable label for the ban code (present only when statusReason is TEMPORARY_BAN).", - "example": "Suspected spam activity" + "enum": [ + "generated", + "simulated" + ] }, - "banExpiresAt": { - "type": "integer", - "description": "Unix timestamp in seconds when the temporary ban lifts, when WhatsApp provides a duration.", - "format": "int64", - "example": 1789000000 + "eventId": { + "type": "string", + "nullable": true, + "format": "uuid" }, - "detail": { + "source": { "type": "string", - "description": "Extra context for FAILED and STREAM_ERROR statuses (for example the connect-failure reason)." + "enum": [ + "test", + "runtime" + ] } }, "required": [ - "status" + "event", + "connection", + "delivery", + "eventId", + "source" ] }, - "CloudAccountStatusPayload": { + "TriggerTestEventRequest": { "type": "object", "properties": { - "source": { + "event": { "type": "string", "enum": [ - "meta" + "message.received", + "message.ack", + "message.failed", + "call.received", + "call.missed", + "call.ended", + "connection.status", + "connection.restriction_updated", + "template.status" ], - "description": "Always `meta`: a WhatsApp Business Account notification, not a connection-state change" + "description": "Fixture name. Each name is the event type it produces." }, - "kind": { - "type": "string", - "enum": [ - "account_alerts", - "account_update", - "phone_number_name_update" - ], - "description": "WhatsApp notification field that produced the event" + "overrides": { + "$ref": "#/components/schemas/TestEventOverrides" }, - "wabaId": { + "fromConnection": { "type": "string", - "description": "WhatsApp Business Account id the notification belongs to", - "example": "102290129340398" - }, - "value": { - "type": "object", - "additionalProperties": {}, - "description": "The notification's `value` object exactly as WhatsApp sent it; its fields vary by notification" + "minLength": 1, + "maxLength": 128, + "description": "message.received only. Send a simulated text message from this other connected Test connection in the same project instead of generating an event." } }, "required": [ - "source", - "kind", - "value" - ] + "event" + ], + "additionalProperties": false }, - "SessionConnectedPayload": { + "TestEventOverrides": { "type": "object", "properties": { - "phoneNumber": { - "type": "string" + "text": { + "type": "string", + "minLength": 1, + "maxLength": 4096 }, - "id": { + "from": { "type": "string", - "description": "Polymorfa ID of the connected account." + "pattern": "^\\+[1-9]\\d{7,14}$" }, "pushName": { - "type": "string" + "type": "string", + "minLength": 1, + "maxLength": 64 }, - "phonePlatform": { + "mediaType": { "type": "string", "enum": [ - "android", - "ios", - "meta_cloud", - "unknown" - ], - "description": "Where the account's primary WhatsApp client runs.", - "x-enumDescriptions": { - "android": "WhatsApp or WhatsApp Business on an Android phone.", - "ios": "WhatsApp or WhatsApp Business on an iPhone.", - "meta_cloud": "Meta hosts the number through Cloud API.", - "unknown": "The phone has not reported a recognized platform." - } + "image", + "video", + "audio", + "document", + "sticker" + ] }, - "accountType": { + "caption": { "type": "string", - "enum": [ - "whatsapp_app", - "business_app", - "meta_cloud", - "meta_coexistence" - ], - "description": "How the account uses WhatsApp.", - "x-enumDescriptions": { - "whatsapp_app": "WhatsApp app, connected as a linked device.", - "business_app": "WhatsApp Business app, connected as a linked device.", - "meta_cloud": "Meta Cloud API.", - "meta_coexistence": "Meta Cloud API, with the WhatsApp Business app still active on the phone." - } + "minLength": 1, + "maxLength": 1024 }, - "businessName": { - "type": "string" - } - }, - "required": [ - "phoneNumber", - "pushName", - "phonePlatform", - "accountType" - ] - }, - "SessionLoggedOutPayload": { - "type": "object", - "properties": { - "reason": { + "ackStatus": { "type": "string", "enum": [ - "banned", - "device_removed", - "unknown" - ], - "description": "Why the session was logged out: `banned` when WhatsApp banned the account, `device_removed` when the linked device was removed from the phone or from another device, `unknown` otherwise (including a locked account).", - "example": "device_removed" + "delivered", + "read", + "played", + "error" + ] }, - "code": { - "type": "integer", - "description": "WhatsApp's logout code: 401 (removed), 403 (locked) or 406 (banned); 0 when WhatsApp gave none.", - "example": 401 - } - }, - "required": [ - "reason", - "code" - ] - }, - "CallEndedPayload": { - "type": "object", - "properties": { - "from": { - "type": "object", - "nullable": true, - "properties": { - "id": { - "type": "string", - "pattern": "^[1-9][0-9]{0,18}$", - "description": "Opaque Polymorfa resource ID. Keep this value as a string.", - "example": "739182640518203" - }, - "phoneNumber": { - "type": "string" - }, - "bsuid": { - "type": "string" - }, - "username": { - "type": "string" - }, - "parentBsuid": { - "type": "string", - "description": "Parent business-scoped user ID (`CC.ENT.…`), present only when WhatsApp reports one for this person. It identifies the person across the business portfolios enrolled in one parent account. It cannot be used to send messages or block people; use `id` or `bsuid`.", - "example": "US.ENT.11815799212886844830" - } - }, - "required": [ - "id" + "messageId": { + "type": "string", + "pattern": "^[1-9][0-9]{0,18}$" + }, + "failureReason": { + "type": "string", + "enum": [ + "invalid_recipient", + "connection_not_connected", + "ack_timeout", + "send_failed", + "blocked_by_safety" ] }, - "callId": { - "type": "string" + "video": { + "type": "boolean" }, "durationSeconds": { "type": "integer", - "description": "Total connected duration in seconds (0 if never answered).", - "example": 42 + "minimum": 0, + "maximum": 86400 }, - "reason": { + "callEndReason": { "type": "string", - "description": "Termination reason: user_hangup | timeout | lost_connection | rejected | capacity | pod_lost | connection_failed | upstream_failed | call_restricted (WhatsApp refused the call because the number is restricted to calling people it has already chatted with).", - "example": "user_hangup" + "enum": [ + "user_hangup", + "timeout", + "lost_connection", + "rejected", + "call_restricted" + ] }, - "direction": { + "restrictionActive": { + "type": "boolean" + }, + "status": { "type": "string", "enum": [ - "inbound", - "outbound" - ], - "description": "Call direction.", - "example": "inbound" + "CONNECTING", + "CONNECTED", + "DISCONNECTED" + ] }, - "hadVideo": { - "type": "boolean", - "description": "Whether the call carried video.", - "example": false + "statusReason": { + "type": "string", + "enum": [ + "SCAN_QR", + "AUTO_RECONNECT", + "FAILED", + "MANUAL_STOP", + "QR_TIMEOUT", + "LOGGED_OUT", + "TEMPORARY_BAN", + "STREAM_ERROR" + ] + }, + "templateName": { + "type": "string", + "pattern": "^[a-z0-9_]{1,512}$" }, - "sessionConnection": { + "templateStatus": { "type": "string", "enum": [ - "linked_device", - "cloud_api" - ], - "description": "Connection of the session that carries the call: a linked device or the WhatsApp Business Cloud API.", - "example": "linked_device" + "APPROVED", + "REJECTED" + ] + }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 256 } }, - "required": [ - "from", - "callId", - "durationSeconds", - "reason", - "direction", - "hadVideo" - ] - } - }, - "securitySchemes": { - "BearerAuth": { - "type": "http", - "scheme": "bearer", - "description": "Polymorfa team key (pmfa_ prefix), project token (pmfa_pt_ prefix) where supported, or short-lived client token (pmfa_ct_ prefix). Team keys and project tokens may be personal or service-account owned and enforce selected action scopes. Team keys cover the team and its projects; project tokens stay inside one project. Client tokens stay inside their live project and session and enforce their client rules and immutable mint-time action ceiling. Treat all credentials as opaque strings. Never parse them or assume a fixed length; store at least 512 characters. Server keys use issuance-record lookup; short-lived client tokens carry a signed permission ceiling." + "additionalProperties": false } }, "headers": { diff --git a/contracts/openapi.platform.json b/contracts/openapi.platform.json index 221f0de..2da0f20 100644 --- a/contracts/openapi.platform.json +++ b/contracts/openapi.platform.json @@ -1,29 +1,25 @@ { "openapi": "3.0.3", "info": { - "title": "Polymorfa automation platform", - "version": "2026-09-22" + "title": "Polymorfa Platform API", + "version": "1.0.0", + "description": "Manage your team, projects, connections, and webhooks.\n\nAuthenticate with a team API key or a project token with the permissions required by the method." }, - "servers": [ - { - "url": "https://api.polymorfa.com" - } - ], "paths": { - "/platform/sessions": { + "/platform/connections": { "get": { - "operationId": "listPlatformSessions", + "operationId": "listPlatformConnections", "tags": [ - "sessions" + "connections" ], - "summary": "List sessions", - "description": "Lists sessions in the authenticated team or selected project, including disconnected sessions and their latest status reason. A Test key returns only test numbers in its project, or an empty list when there are none. Other project tokens return all sessions in their own project.\n\nRequires `sessions:read`. Project tokens only access resources in their own project.", + "summary": "List connections", + "description": "Lists connections in the authenticated team or selected project, including disconnected connections and their latest status reason. A Test key returns only test connections in its project, or an empty list when there are none. Other project tokens return all connections in their own project.\n\nRequires `connections:read`. Project tokens only access resources in their own project.", "x-audience": "public", "x-polymorfa-resource-boundary": "project", "x-excluded-from-public": false, - "x-required-scope": "sessions:read", + "x-required-scope": "connections:read", "x-merged-endpoints": [ - "listSessionsByOrganization" + "listConnectionsByTeam" ], "security": [ { @@ -73,7 +69,7 @@ "data": { "type": "array", "items": { - "$ref": "#/components/schemas/PlatformSession" + "$ref": "#/components/schemas/PlatformConnection" } } }, @@ -325,6 +321,9 @@ }, "409": { "$ref": "#/components/responses/Conflict" + }, + "422": { + "$ref": "#/components/responses/IdempotencyKeyReused" } } } @@ -522,6 +521,9 @@ }, "409": { "$ref": "#/components/responses/Conflict" + }, + "422": { + "$ref": "#/components/responses/IdempotencyKeyReused" } } } @@ -529,7 +531,7 @@ }, "components": { "schemas": { - "PlatformSession": { + "PlatformConnection": { "type": "object", "additionalProperties": false, "properties": { @@ -544,8 +546,8 @@ "projectId": { "$ref": "#/components/schemas/ProjectId" }, - "sessionId": { - "$ref": "#/components/schemas/SessionIdentifier" + "connectionId": { + "$ref": "#/components/schemas/ConnectionIdentifier" }, "name": { "type": "string", @@ -578,12 +580,12 @@ }, "status": { "type": "string", - "description": "Latest runtime connection status." + "description": "Latest runtime method status." }, "statusReason": { "type": "string", "nullable": true, - "description": "Machine-readable reason for the latest connection status, when available." + "description": "Machine-readable reason for the latest method status, when available." }, "messageCount": { "type": "integer", @@ -672,13 +674,25 @@ ] } ] + }, + "inspector": { + "type": "object", + "additionalProperties": false, + "properties": { + "claim": { + "$ref": "#/components/schemas/InspectorClaimState" + } + }, + "required": [ + "claim" + ] } }, "required": [ "_id", "_creationTime", "projectId", - "sessionId", + "connectionId", "name", "phone", "platform", @@ -691,7 +705,8 @@ "lastActiveAt", "paidUntil", "customer", - "claim" + "claim", + "inspector" ] }, "ProjectId": { @@ -699,11 +714,31 @@ "format": "uuid", "description": "Project UUID. Optional where an operation can infer or search team scope; required where the operation creates a project-owned resource." }, - "SessionIdentifier": { + "ConnectionIdentifier": { "type": "string", "minLength": 1, "maxLength": 64, - "description": "Database session UUID or stable session slug." + "description": "Database connection UUID or stable connection slug." + }, + "InspectorClaimState": { + "type": "object", + "additionalProperties": false, + "description": "Whether a team member has claimed this Connection in Inspector. The claimant's identity is not included.", + "properties": { + "claimed": { + "type": "boolean" + }, + "claimedAt": { + "type": "string", + "format": "date-time", + "nullable": true, + "description": "When the current claim was made. Null when unclaimed." + } + }, + "required": [ + "claimed", + "claimedAt" + ] }, "ErrorEnvelope": { "type": "object", @@ -756,7 +791,7 @@ "request_log_url": { "type": "string", "format": "uri", - "description": "Console page that shows this request. Returned only to organization and project credentials whose request was logged." + "description": "Console page that shows this request. Returned only to team and project credentials whose request was logged." } } }, @@ -783,7 +818,7 @@ "type": "string", "format": "uuid" }, - "organizationId": { + "teamId": { "type": "string", "format": "uuid" }, @@ -830,7 +865,7 @@ "type": "integer", "minimum": 7, "maximum": 13, - "description": "First day without the phone on which this endpoint receives session.phone_offline." + "description": "First day without the phone on which this endpoint receives connection.phone_offline." }, "headers": { "type": "array", @@ -853,7 +888,7 @@ }, "required": [ "id", - "organizationId", + "teamId", "owner", "projectId", "url", @@ -994,7 +1029,7 @@ "minimum": 7, "maximum": 13, "default": 10, - "description": "First day without the phone on which this endpoint receives session.phone_offline. WhatsApp signs the linked device out on day 14. On PATCH, omission preserves the stored value. To stop the warning, remove session.phone_offline from eventTypes." + "description": "First day without the phone on which this endpoint receives connection.phone_offline. WhatsApp signs the linked device out on day 14. On PATCH, omission preserves the stored value. To stop the warning, remove connection.phone_offline from eventTypes." }, "headers": { "type": "array", @@ -1162,13 +1197,6 @@ ] } }, - "securitySchemes": { - "ApiKeyAuth": { - "type": "http", - "scheme": "bearer", - "description": "Send your team API key or project token as `Authorization: Bearer `. Treat credentials as opaque strings. Never parse them or assume a fixed length; store at least 512 characters. Permissions and ownership come from the live issuance record. Project tokens can access only their own project." - } - }, "responses": { "BadRequest": { "description": "A path, query, or request-body value did not pass validation.", @@ -1324,6 +1352,43 @@ } } } + }, + "IdempotencyKeyReused": { + "description": "The Idempotency-Key was already used for a different request (`idempotency_conflict`).", + "headers": { + "X-Request-Id": { + "schema": { + "type": "string" + }, + "description": "Stable request correlation identifier." + }, + "X-Trace-Id": { + "schema": { + "type": "string", + "pattern": "^[0-9a-f]{32}$" + }, + "description": "W3C trace ID of this request. Your `traceparent` trace ID when you sent a valid one." + }, + "Polymorfa-Version": { + "schema": { + "type": "string" + }, + "description": "API version applied to this response." + }, + "Link": { + "description": "Documentation for this Idempotency-Key error (`rel=\"describedby\"`).", + "schema": { + "type": "string" + } + } + }, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorEnvelope" + } + } + } } } } diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index bf34010..dff94e1 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,60 +1,69 @@ { - "source": "b3bd05843342275f25f304bfe1fc67ca872740ba", - "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", + "source": "fe83375c38218dc15dc76a5ab7ebf82da94f12cf", + "note": "Fingerprints of reviewed SDK fragments for this public Connection source candidate. No additional operation or publication is implied.", "fragments": { "messaging": { - "POST /messaging/{session}/messages/send": "93a1803cdc95b7fe7d8d74d829a4e80587a4c0c9fc5ac5b2c33ba16c8de802d2", - "#/components/schemas/SendMessageRequest": "8386e01b57b58f9c9ab5121eee080bad3064f9c14df978e8d020a3057ff796e3", - "#/components/schemas/ConversationReference": "1f4775033765255d64b33210b8b8f2d46657ecb0ae79aa6de890074b79fecd1a", + "POST /messaging/{connection}/messages/send": "2df7ed3a7ddfe696eee235901701f4992531820135486f34063e736d1c22c928", + "#/components/schemas/SendMessageRequest": "9b9dc19d1f058f6cf57afba332db5f30c7c332cd28450c33e88487893de1d5b6", + "#/components/schemas/ConversationReference": "3acec7fb257547a56f9fffa23a7c0044786a2419449b84fddc1e3fbc87f6ea03", "#/components/schemas/QuotedMessage": "e62e128f03711c6436ccc1ed81a3b3455c2320a0fa49913510ea005f52007b47", - "#/components/schemas/MessageContent": "60672a06e516d8616144dca4f0402cc51fe8d4daa51fc96f952c01a4c2bdecb0", - "#/components/schemas/OrderDetailsContent": "68ea6689f4f688e78cc0225339f6790f0015d3e0545b24362839dd3e75f8cca7", + "#/components/schemas/MessageContent": "c79d4f4e223df082f3f94c15559953eb3040851a5c831aa37a6ca0ba0889b060", + "#/components/schemas/ImageMediaDescriptor": "4c4566b70764add63610f83f402bbe27b4680c040e83ecfdf9844ddea243d5c2", + "#/components/schemas/VideoMediaDescriptor": "2e0735269dfdef32191fa9a7913238e02b20a6f9bd247874a06f1fdc8359d1d0", + "#/components/schemas/FileMediaDescriptor": "be69f66a04d0dedad16c801832d06d6f06509f503261f2cc2466cef671bf7548", + "#/components/schemas/VoiceMediaDescriptor": "c53f4e6264d96fd928c81d6730ea0828053aaf990b6c290ba6d913ec7b74e0bb", + "#/components/schemas/StickerMediaDescriptor": "95a0475ecd82d3fcc9b05823e6a0bef4fed7e1e89caecb24a1cd5c79d8be76a9", + "#/components/schemas/OrderDetailsContent": "88868e0d9af610a091e9ecbe1ff375d3dbb919c54c58e4d59362166d4f151b95", "#/components/schemas/PaymentOrderAmount": "fe7303e8acd3f51ba5c93cd55adde3e8b20e67b7f5806d3a3bd49e55545346b9", "#/components/schemas/OrderStatusContent": "97d62fab1e4cf5d1ef32a368ace21e99e2781db74871b1b0116cdb8131ac8760", "#/components/schemas/SendMessageResponse": "92f27ea117567391bfe669ec3e6e5181b15eb9a9591e1aebd1850ed5361bbd48", - "#/components/schemas/SentMessage": "39e68ee360e477804ccd31463e13408bafbfd20c0a1507e351d6e053ebc6994f", + "#/components/schemas/SentMessage": "c9858f90cc165d64aa7d1a5a02c48959d41736db57f562d8204c607d6b4350e9", "#/components/schemas/WhatsAppMessageIds": "da7eed5d59e28c5a8fcf17d9ef94ff47ea5c26fb1f949996a6d959b91d21bedf", - "#/components/schemas/ConversationIdentity": "c35833feef8f250a734714f2c5dc209b4d8ab3ac5a65ca4b2212ca2371f620e3", + "#/components/schemas/ConversationIdentity": "9f9e95c9349f1014242753ff2b32161b9f99a2302ebbb4a5257abfd6badcceef", "#/components/headers/X-RateLimit-Limit": "b2965eeaed5d8b40ddc39a5ffe5cb6e042e275517f264bb7ed9ba2ba4e18fab1", "#/components/headers/X-RateLimit-Remaining": "0610aa688cc7c86ff568195eaa5f93a92df64d62dc4e872007ed39b56682952c", "#/components/headers/X-RateLimit-Reset": "2bbf04658a8168fde104816fbd462bdf6bfcc9203bfacd253b17f845c2cd4774", "#/components/schemas/AsyncAcceptedResponse": "49e01a5a3f22c3fc2fa173292e14fe1bc413fbf1e4292239173eb40738bb0c8b", - "#/components/schemas/PublicError": "f70f822587b737f02c8c00d3a78fdb66ed2e7ac186208055a8db32aeed1eb48f", - "POST /messaging/{session}/messages/react": "d126f34d3d1336b0060f9321e4cb5f6d81fb54f75afe60b62c6c478345eda8b3", + "#/components/schemas/PublicError": "1cdcb3143be0a8fbd45ff52d3d3b8ff8477d046ce118801c83451a9766f46683", + "POST /messaging/{connection}/messages/react": "d2c777aeb26817d56ac345175c4bfde8de564857f061ba1579ced90a85843d8e", "#/components/schemas/ReactRequest": "a97d67926f9fcce0f703654aeaa5805b3c89baac707b624374dcd7dfe074a22d", "#/components/schemas/SendReactionResponse": "8de0bc201c1fcb15f766a55daa24e219ec2b91ce8a28f6758ffb0a53f299eb03", - "#/components/schemas/MessageReceipt": "a03d8eaf5edc18b0156aa0d41784dd2ecd69832e25f782564fc630371e3bcb4a", - "GET /messaging/projects/{projectSlug}/templates": "3bdf7aa2f992d9e0440148476fa6ad65961ee9510c9c16a4d9e779ca06a94b78", + "#/components/schemas/MessageReceipt": "074b877651f0615122cd8eae2cde69fbc8fffe13b262f86aeae7554a1a2cc826", + "GET /messaging/projects/{projectSlug}/templates": "15686d78464d29ee23fb0c93ed1b376f70bacd708a1912a76ae12e9d77a7c06c", "#/components/schemas/ListProjectTemplatesResponse": "e9c785aa85c147ee71b61c21b4dc2fd408a508ca33625c4a2369b280f41bfe94", "#/components/schemas/MessageTemplate": "7280880879333454e0f12fe0821fc129c8de58fc1e15c998d8808a429e02ec8f", - "GET /messaging/projects/{projectSlug}/templates/{id}": "e594f033929c61980e66dad427f3bdee5ba8fe49574425f807e028c3fa7fb65b", + "GET /messaging/projects/{projectSlug}/templates/{id}": "e0f10e2141a298e0e1547df7e245bb0d32b7849c4e324505dd9b744a3f69df5b", "#/components/schemas/GetProjectTemplateResponse": "3a266572c06eed33e7a39c89b77230060c3314a1ab4eee511cfc0df6d6bbc67f" }, "platform": { - "GET /platform/sessions": "dab70dab3c2c738345e7a5bc355deb9efc5cbe614c684d9bcc36928e5152fc81", - "#/components/schemas/PlatformSession": "a469d4c1af411d11d48d13923c96c89496f96df8e2c10cf9d122a7b2fb842761", + "GET /platform/connections": "ae337194f72720059e107c2353fa28fc515414bb15a47d7df79cf544c93ef6e8", + "#/components/schemas/PlatformConnection": "015c4350dfb81d78c45995a2c0a9145f29d2451aba2b29d395cfed349b2953d9", "#/components/schemas/ProjectId": "fdccf22724eac520992fae4b95b48d6309b1fa46dbdf0031873afb384a7ae282", - "#/components/schemas/SessionIdentifier": "67cdaffd7124ebe30e3ed110c7a1b851cbab3b4888ad6fc59d054d096fb65515", - "#/components/responses/BadRequest": "3a84c67f0face498ff4bf02ce59fa3e76cf590da59b02ba07bae25df3a05e157", - "#/components/schemas/ErrorEnvelope": "cf6263c6ed85daf3d68f5dfe62e5a49bc7ff5745ab9f13112a89ffba0661f702", - "#/components/responses/Unauthorized": "28e2654ec1441f573c15fcc22de9c88ac07a38ca550be07c6171a42352c918ca", - "#/components/responses/Forbidden": "9cbec049fedd88431891e560a7402126e29f516216812546d78f694391011713", - "GET /platform/projects/{projectId}/webhooks": "d8e86e19a0a1d07e1a12c2b047ea22b215da71805c712a563f731d33922b867c", - "#/components/schemas/ProjectWebhook": "8e9579e600f25f638b5e3c9dbd3504543ca36be5c800e8d64bb86a02075fa348", + "#/components/schemas/ConnectionIdentifier": "ff17d190ddd482925157c9d5d5c0eb0af8079207f355153c1376acfb1e589b32", + "#/components/schemas/InspectorClaimState": "876a2d5d45bb116eee14a8be124ce5d09f9cef51d291a3aa2af291234084238a", + "#/components/responses/BadRequest": "b91bd2505bec85e8cecf9fad49c467f88064e63e9be1d60d19d5004e33b436ce", + "#/components/schemas/ErrorEnvelope": "feea2cda36ed5364b1f913166fae17020e0dceaa81f2b8e36fdda7b02910a78e", + "#/components/responses/Unauthorized": "537cc76b10b9c59a898d7932431a959953b2970ec0b921720c4ad89e2986644f", + "#/components/responses/Forbidden": "77cf31c9dba76b12afcb168938a8694396def2b37d9854076e7fb658e03b5e91", + "GET /platform/projects/{projectId}/webhooks": "a2c9288bb21cf3fdad6b5fb3aa0471d6075805deeca87f9c67a52593ad387c8f", + "#/components/schemas/ProjectWebhook": "447a7260884850ee6c8c327635710cb4dd19188e019408c3b8d1e353afda2848", "#/components/schemas/WebhookRetryPolicy": "a953fbcee54bed638f93e85b00670d4563f4ff8d17b80d456c831e2a7b0dd9f5", "#/components/schemas/WebhookHeaderMetadata": "f03e715b0afdde824ab991f4a664cddfaed3586081926e0fca7b5d6c1440a366", "#/components/schemas/WebhookSigningSecretMetadata": "0fed4dc6a07f2066215081784225210e7c0025c864fddfdc77eeca232d1b40b5", + "#/components/schemas/WebhookBatching": "d3be6ee4c2b556f31ffa1974ceff744d90df01baca29344e6cb281aeb6b9ff80", "#/components/schemas/CursorPageMetadata": "a491dc0e4a93fd2ce4925bade45affaf3bcc840f905251a5b9c643f4b64e35da", - "#/components/responses/NotFound": "61d43cb4a9d7b627a86f47462d5b04413109bfe31a967cbbaf69919204091a67", - "POST /platform/projects/{projectId}/webhooks": "4299c2c587a455349b5ec2ce70442f4ba8dd910b6a922e0ccc94323af545a0dd", - "#/components/schemas/CreateProjectWebhookInput": "8332551baf79f9adca43bfb8261c23677090d5931b716cdf08107876e5d09522", + "#/components/responses/NotFound": "7091da86cd9fffdf72d2c07f0f758177d72202a2a1aee8cd1672e983d1db274e", + "POST /platform/projects/{projectId}/webhooks": "1b9a4bc78ae0f3b985c7bd683375354d25c4bf53e252a6c4e3fb8951d24086b7", + "#/components/schemas/CreateProjectWebhookInput": "8fc3291ddf5e7c17c231ccd9d40d564fd2c724eb6c0e259be05bd5dc486f8880", "#/components/schemas/WebhookRetryPolicyInput": "a953fbcee54bed638f93e85b00670d4563f4ff8d17b80d456c831e2a7b0dd9f5", "#/components/schemas/WebhookHeaderInput": "9439ff800367858e22668035c1e432e1023d52fc39d65cfdc83a17068c989a51", + "#/components/schemas/WebhookBatchingInput": "29143d6b029716cb24416ad08db6ec11dc0ad865e4dea44530fe0a283dc5bab3", "#/components/schemas/ProjectWebhookCreationReceipt": "8fa37c1b86463fb4e451e456ac2b4d0afda26c8648407b937ed7ef22dc1d8147", "#/components/schemas/IdempotencyReceipt": "20651991bf1da3fa2a4662f6672727d81896a0d3d931f1a30eeb926c8326a1c9", - "#/components/responses/Conflict": "88bc9c23f816071e5834b751fa69b1d8e37e21381f6eacddf29a9276c3a656c7", - "GET /platform/projects/{projectId}/webhooks/{webhookId}": "cef68b5bddb2010ac270e0816d2c74e56145009ff27c700aba695beebc257ab0", - "DELETE /platform/projects/{projectId}/webhooks/{webhookId}": "8da0a9d120858a05b0ab20e1d52f2951418305112475c8ca1b3b5b0fa793c89a", + "#/components/responses/Conflict": "4ed94d3b833bb541ca39006152425c39e815fb1e374ca3d2a1b080e828ce9601", + "#/components/responses/IdempotencyKeyReused": "71d6cfda5625056e1c0403431391037dd915590e6a1b1316e4aceb902662b08f", + "GET /platform/projects/{projectId}/webhooks/{webhookId}": "ab5b5809d6b39bfa03bd1c3b53f44a7ae367f1de47210b3c8ca0579906e5dd68", + "DELETE /platform/projects/{projectId}/webhooks/{webhookId}": "24b746bd786d823e8737035ba770a877821d376e8de691562a2dcda8c671c652", "#/components/schemas/ProjectWebhookDeletionReceipt": "b3a9d35885f3523ae1789e95230009ff1749f6f34dced9359a09703f1c2289e5" } } diff --git a/contracts/source.json b/contracts/source.json index c1deaa4..6e3ef4b 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,30 +1,32 @@ { "apiVersion": "2026-09-22", - "apiSource": "1307601eb7c2eb5e29715d2c1784e38e01e61433", + "apiSource": "8354399b827d9127210b9759cd055586e967449e", "sdk": { "repository": "polymorfa/sdks", - "source": "b3bd05843342275f25f304bfe1fc67ca872740ba", + "source": "fe83375c38218dc15dc76a5ab7ebf82da94f12cf", "publishedPackage": null }, "specs": { "messaging": { "publicSourcePath": "docs/api-reference/openapi.json", - "publicSourceSha256": "4a7b397119f4722b3d2cdcae440a152ca7249ebbc054ed6ebd93c5821f0f28ce", + "publicSourceSha256": "9e6a9520b5f64eff9b6b23621ce6e7f7e667b44e45e8a7f56c7e1e94f0d271e8", "snapshot": "contracts/openapi.messaging.json", - "sha256": "1a92c533626b793e4ed65ef585f7cba37e83a21c38c9bd517c7f1270a38e58c7", + "sha256": "5fc4b8f5af37c7694fe307d1d3a5b05a5ad82109a14892cb5b685bbd41bd58d5", "sdkSnapshotPath": "contracts/openapi.messaging.json" }, "platform": { "publicSourcePath": "docs/api-reference/openapi.management.json", - "publicSourceSha256": "f2e7963d5ddb0070c58dfe049c63e40b8bfdd806b7443f3b670b1e888ee4f10f", + "publicSourceSha256": "613eb7aa47c29cda851fccec8b05aa07c9e637ed3ff2b57a920e7ea40e4db6a1", "snapshot": "contracts/openapi.platform.json", - "sha256": "34a7f677d02899a4a392f68468eca0ee5b3b004416337bb33f46301a3dd06984", + "sha256": "ec4bcfb5e37c68015c30b086316585b539a7504912487599cc166fa3b2f99b3c", "sdkSnapshotPath": "contracts/openapi.platform.json" } }, - "audience": "published public exports only", + "audience": "Public API source candidate only; nine covered operations projected without private SDK operations.", "acceptance": { "staging": null, "production": null - } + }, + "releaseStatus": "source-only", + "releaseGate": "Matching staging/production API acceptance and SDK publication are required before integration publication. Fixture and local package checks do not establish provider/editor acceptance." } diff --git a/fixtures/events.json b/fixtures/events.json index 2673ff8..0fcfa19 100644 --- a/fixtures/events.json +++ b/fixtures/events.json @@ -1,7 +1,7 @@ { "messageReceived": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71", - "session": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.received", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.received", "payload": { "id": "739182640518204", "whatsapp_ids": { "linked_devices": "SYNTHETIC-EXAMPLE" }, "conversation": { "id": "739182640518205" }, "fromMe": false, @@ -11,17 +11,17 @@ }, "messageState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a72", - "session": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.sent", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.sent", "payload": { "id": "739182640518204", "whatsapp_ids": { "linked_devices": "SYNTHETIC-EXAMPLE" }, "conversation": { "id": "739182640518205" }, "type": "text", "timestamp": 1793534400 } }, - "numberState": { + "connectionState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a73", - "session": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "session.status", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "connection.status", "payload": { "status": "connected" } }, "callEnded": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a74", - "session": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "call.ended", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "call.ended", "payload": { "from": { "id": "739182640518205" }, "callId": "SYNTHETIC-CALL", "durationSeconds": 60, "reason": "ended", "direction": "inbound", "hadVideo": false } } } diff --git a/make/README.md b/make/README.md index 201c1f6..b91bd0d 100644 --- a/make/README.md +++ b/make/README.md @@ -51,7 +51,7 @@ webhooks under one Polymorfa-owned app. Keep API keys and derived receiver value in private connection/webhook state. Map static and mappable parameter files in the native editor. Real API upload/import and editor acceptance are pending. -Connection tests require `sessions:read`. Sends/reactions need `messages:write`, +Connection tests require `connections:read`. Sends/reactions need `messages:write`, template lookup `templates:read`, and hooks `webhooks:read` plus `webhooks:manage`. The universal **Make an API call** module permits only the public allowlist on the fixed Polymorfa origin; it cannot call arbitrary hosts or change principals. diff --git a/make/connections/project/communication.json b/make/connections/project/communication.json index de9f9f6..6a09677 100644 --- a/make/connections/project/communication.json +++ b/make/connections/project/communication.json @@ -1,5 +1,5 @@ { - "url": "/platform/sessions", + "url": "/platform/connections", "method": "GET", "qs": { "projectId": "{{parameters.projectId}}" diff --git a/make/functions/polymorfaAdvanced.js b/make/functions/polymorfaAdvanced.js index 8f6b9fd..06df9c8 100644 --- a/make/functions/polymorfaAdvanced.js +++ b/make/functions/polymorfaAdvanced.js @@ -25,7 +25,7 @@ function advanced(p, auth) { const path = required(p.path, 'path'); if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; - const allowed = (method === 'GET' && (path === '/platform/sessions' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || + const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; @@ -33,7 +33,7 @@ function advanced(p, auth) { const keys = path.endsWith('/react') ? ['conversation', 'id', 'reaction'] : ['conversation', 'isForwarded', 'mentions', 'quotedMessage', 'content']; if (Object.keys(body).some(k => !keys.includes(k))) throw new IntegrationError('unsupported_request_field'); } - return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/sessions' ? { query: { projectId: auth.projectId } } : {}) }; + return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/connections' ? { query: { projectId: auth.projectId } } : {}) }; } return advanced(p, auth); } diff --git a/make/functions/polymorfaEnvelope.js b/make/functions/polymorfaEnvelope.js index ca1526e..1fc0f4f 100644 --- a/make/functions/polymorfaEnvelope.js +++ b/make/functions/polymorfaEnvelope.js @@ -10,11 +10,11 @@ class IntegrationError extends Error { this.requestId = requestId; this.retryAfter = retryAfter; } } -const events = {"messageReceived":{"label":"New Message","description":"Triggers when a message is received.","types":["message.received"]},"messageState":{"label":"Message State Changed","description":"Triggers when a message is sent, acknowledged, failed or updated.","types":["message.sent","message.ack","message.failed","message.update"]},"numberState":{"label":"Number State Changed","description":"Triggers when a Number changes state, connects or logs out.","types":["session.status","session.connected","session.logged_out"]},"callEnded":{"label":"Call Ended","description":"Triggers when a call ends.","types":["call.ended"]}}; +const events = {"messageReceived":{"label":"New Message","description":"Triggers when a message is received.","types":["message.received"]},"messageState":{"label":"Message State Changed","description":"Triggers when a message is sent, acknowledged, failed or updated.","types":["message.sent","message.ack","message.failed","message.update"]},"connectionState":{"label":"Connection State Changed","description":"Triggers when a Connection changes state, connects or logs out.","types":["connection.status","connection.connected","connection.logged_out"]},"callEnded":{"label":"Call Ended","description":"Triggers when a call ends.","types":["call.ended"]}}; function envelope(body, group) { - if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.session !== 'string' || !body.session || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); + if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.connection !== 'string' || !body.connection || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); // Copy the defined envelope only. Never export arbitrary top-level transport fields. - return { id: body.id, session: body.session, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; + return { id: body.id, connection: body.connection, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; } return envelope(body, group); } diff --git a/make/functions/polymorfaFindHook.js b/make/functions/polymorfaFindHook.js index 40b208a..0e8d083 100644 --- a/make/functions/polymorfaFindHook.js +++ b/make/functions/polymorfaFindHook.js @@ -1,6 +1,6 @@ function polymorfaFindHook(body, auth, url, group, key) { const expected = iml.polymorfaHook(auth, group, key); -const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"numberState":["session.status","session.connected","session.logged_out"],"callEnded":["call.ended"]}; +const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"connectionState":["connection.status","connection.connected","connection.logged_out"],"callEnded":["call.ended"]}; // Match shared sameCallback: an invalid URL on any hook is simply not a match. const same = h => { try { return iml.polymorfaCallback(h.url) === iml.polymorfaCallback(url); } catch (error) { return false; } }; if (!Array.isArray(body.data) || body.page?.hasMore) throw new Error('Subscription inventory needs reconciliation.'); diff --git a/make/functions/polymorfaHook.js b/make/functions/polymorfaHook.js index eb2c2bb..1e18147 100644 --- a/make/functions/polymorfaHook.js +++ b/make/functions/polymorfaHook.js @@ -19,7 +19,7 @@ function segment(value, name) { if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new IntegrationError(`invalid_${name}`); return value; } -const events = {"messageReceived":{"label":"New Message","description":"Triggers when a message is received.","types":["message.received"]},"messageState":{"label":"Message State Changed","description":"Triggers when a message is sent, acknowledged, failed or updated.","types":["message.sent","message.ack","message.failed","message.update"]},"numberState":{"label":"Number State Changed","description":"Triggers when a Number changes state, connects or logs out.","types":["session.status","session.connected","session.logged_out"]},"callEnded":{"label":"Call Ended","description":"Triggers when a call ends.","types":["call.ended"]}}; +const events = {"messageReceived":{"label":"New Message","description":"Triggers when a message is received.","types":["message.received"]},"messageState":{"label":"Message State Changed","description":"Triggers when a message is sent, acknowledged, failed or updated.","types":["message.sent","message.ack","message.failed","message.update"]},"connectionState":{"label":"Connection State Changed","description":"Triggers when a Connection changes state, connects or logs out.","types":["connection.status","connection.connected","connection.logged_out"]},"callEnded":{"label":"Call Ended","description":"Triggers when a call ends.","types":["call.ended"]}}; if (!events[group]) throw new IntegrationError('invalid_event_group'); required(subscriptionKey, 'subscription_key'); if (subscriptionKey.length > 200) throw new IntegrationError('invalid_subscription_key'); diff --git a/make/functions/polymorfaOwnedHook.js b/make/functions/polymorfaOwnedHook.js index f0f63df..864c4bf 100644 --- a/make/functions/polymorfaOwnedHook.js +++ b/make/functions/polymorfaOwnedHook.js @@ -1,5 +1,5 @@ function polymorfaOwnedHook(body, projectId, ownedUrl, markerName, group) { -const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"numberState":["session.status","session.connected","session.logged_out"],"callEnded":["call.ended"]}; +const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"connectionState":["connection.status","connection.connected","connection.logged_out"],"callEnded":["call.ended"]}; const same = (a, b) => { try { return iml.polymorfaCallback(a) === iml.polymorfaCallback(b); } catch (error) { return false; } }; const h = body.data; if (!h || h.owner !== 'project' || h.projectId !== projectId || !same(h.url, ownedUrl) || h.format !== 'native' || !h.headers?.some(x => x.name.toLowerCase() === markerName.toLowerCase()) || h.eventTypes?.length !== types[group]?.length || !types[group].every(t => h.eventTypes.includes(t))) throw new Error('Subscription ownership mismatch.'); diff --git a/make/functions/polymorfaReceive.js b/make/functions/polymorfaReceive.js index bd4aa64..e9e279a 100644 --- a/make/functions/polymorfaReceive.js +++ b/make/functions/polymorfaReceive.js @@ -1,6 +1,6 @@ function polymorfaReceive(expectedName, expectedValue, group, headers, body) { -const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"numberState":["session.status","session.connected","session.logged_out"],"callEnded":["call.ended"]}; +const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"connectionState":["connection.status","connection.connected","connection.logged_out"],"callEnded":["call.ended"]}; const entries = Object.entries(headers || {}).filter(([key]) => key.toLowerCase() === String(expectedName).toLowerCase()); if (!expectedValue || entries.length !== 1 || entries[0][1] !== expectedValue) return false; -return !!(body && typeof body.id === 'string' && body.id && typeof body.session === 'string' && body.session && types[group] && types[group].includes(body.event) && typeof body.timestamp === 'string' && Number.isFinite(Date.parse(body.timestamp)) && body.payload && typeof body.payload === 'object' && !Array.isArray(body.payload)); +return !!(body && typeof body.id === 'string' && body.id && typeof body.connection === 'string' && body.connection && types[group] && types[group].includes(body.event) && typeof body.timestamp === 'string' && Number.isFinite(Date.parse(body.timestamp)) && body.payload && typeof body.payload === 'object' && !Array.isArray(body.payload)); } diff --git a/make/functions/polymorfaRequest.js b/make/functions/polymorfaRequest.js index e2db7b8..3bad655 100644 --- a/make/functions/polymorfaRequest.js +++ b/make/functions/polymorfaRequest.js @@ -35,8 +35,8 @@ function writeHeaders(p, now = Date.now()) { } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.session, 'number')}/messages/${action === 'react' ? 'react' : 'send'}`, body: iml.polymorfaBody(action, p) }; - else if (action === 'listNumbers') r = { method: 'GET', url: ORIGIN + '/platform/sessions', query: { projectId: auth.projectId } }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: iml.polymorfaBody(action, p) }; + else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = iml.polymorfaAdvanced(p, auth); else throw new IntegrationError('unknown_action'); diff --git a/make/modules/apiRequest/parameters.json b/make/modules/apiRequest/parameters.json index 15edf64..56f8c4b 100644 --- a/make/modules/apiRequest/parameters.json +++ b/make/modules/apiRequest/parameters.json @@ -21,7 +21,7 @@ "type": "text", "label": "Path", "required": true, - "help": "A supported relative public API path, for example /platform/sessions. External hosts and credential operations are refused." + "help": "A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused." }, { "name": "requestBody", diff --git a/make/modules/callEnded/interface.json b/make/modules/callEnded/interface.json index b683ae9..b03a13c 100644 --- a/make/modules/callEnded/interface.json +++ b/make/modules/callEnded/interface.json @@ -5,8 +5,8 @@ "type": "text" }, { - "name": "session", - "label": "session", + "name": "connection", + "label": "connection", "type": "text" }, { @@ -87,10 +87,122 @@ "type": "boolean" }, { - "name": "sessionConnection", - "label": "sessionConnection", + "name": "connectionMethod", + "label": "connectionMethod", "type": "text" } ] + }, + { + "name": "delivery", + "label": "delivery", + "type": "text" + }, + { + "name": "eventId", + "label": "eventId", + "type": "text" + }, + { + "name": "source", + "label": "source", + "type": "text" + }, + { + "name": "overrides", + "label": "overrides", + "type": "collection", + "spec": [ + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "from", + "label": "from", + "type": "text" + }, + { + "name": "pushName", + "label": "pushName", + "type": "text" + }, + { + "name": "mediaType", + "label": "mediaType", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "ackStatus", + "label": "ackStatus", + "type": "text" + }, + { + "name": "messageId", + "label": "messageId", + "type": "text" + }, + { + "name": "failureReason", + "label": "failureReason", + "type": "text" + }, + { + "name": "video", + "label": "video", + "type": "boolean" + }, + { + "name": "durationSeconds", + "label": "durationSeconds", + "type": "number" + }, + { + "name": "callEndReason", + "label": "callEndReason", + "type": "text" + }, + { + "name": "restrictionActive", + "label": "restrictionActive", + "type": "boolean" + }, + { + "name": "status", + "label": "status", + "type": "text" + }, + { + "name": "statusReason", + "label": "statusReason", + "type": "text" + }, + { + "name": "templateName", + "label": "templateName", + "type": "text" + }, + { + "name": "templateStatus", + "label": "templateStatus", + "type": "text" + }, + { + "name": "reason", + "label": "reason", + "type": "text" + } + ] + }, + { + "name": "fromConnection", + "label": "fromConnection", + "type": "text" } ] diff --git a/make/modules/connectionState/interface.json b/make/modules/connectionState/interface.json new file mode 100644 index 0000000..b659b46 --- /dev/null +++ b/make/modules/connectionState/interface.json @@ -0,0 +1,236 @@ +[ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "connection", + "label": "connection", + "type": "text" + }, + { + "name": "externalId", + "label": "externalId", + "type": "text" + }, + { + "name": "timestamp", + "label": "timestamp", + "type": "text" + }, + { + "name": "event", + "label": "event", + "type": "text" + }, + { + "name": "payload", + "label": "payload", + "type": "collection", + "spec": [ + { + "name": "status", + "label": "status", + "type": "text" + }, + { + "name": "statusReason", + "label": "statusReason", + "type": "text" + }, + { + "name": "banCode", + "label": "banCode", + "type": "number" + }, + { + "name": "banReason", + "label": "banReason", + "type": "text" + }, + { + "name": "banExpiresAt", + "label": "banExpiresAt", + "type": "number" + }, + { + "name": "detail", + "label": "detail", + "type": "text" + }, + { + "name": "source", + "label": "source", + "type": "text" + }, + { + "name": "kind", + "label": "kind", + "type": "text" + }, + { + "name": "wabaId", + "label": "wabaId", + "type": "text" + }, + { + "name": "value", + "label": "value", + "type": "collection" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "pushName", + "label": "pushName", + "type": "text" + }, + { + "name": "phonePlatform", + "label": "phonePlatform", + "type": "text" + }, + { + "name": "accountType", + "label": "accountType", + "type": "text" + }, + { + "name": "businessName", + "label": "businessName", + "type": "text" + }, + { + "name": "reason", + "label": "reason", + "type": "text" + }, + { + "name": "code", + "label": "code", + "type": "number" + } + ] + }, + { + "name": "delivery", + "label": "delivery", + "type": "text" + }, + { + "name": "eventId", + "label": "eventId", + "type": "text" + }, + { + "name": "source", + "label": "source", + "type": "text" + }, + { + "name": "overrides", + "label": "overrides", + "type": "collection", + "spec": [ + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "from", + "label": "from", + "type": "text" + }, + { + "name": "pushName", + "label": "pushName", + "type": "text" + }, + { + "name": "mediaType", + "label": "mediaType", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "ackStatus", + "label": "ackStatus", + "type": "text" + }, + { + "name": "messageId", + "label": "messageId", + "type": "text" + }, + { + "name": "failureReason", + "label": "failureReason", + "type": "text" + }, + { + "name": "video", + "label": "video", + "type": "boolean" + }, + { + "name": "durationSeconds", + "label": "durationSeconds", + "type": "number" + }, + { + "name": "callEndReason", + "label": "callEndReason", + "type": "text" + }, + { + "name": "restrictionActive", + "label": "restrictionActive", + "type": "boolean" + }, + { + "name": "status", + "label": "status", + "type": "text" + }, + { + "name": "statusReason", + "label": "statusReason", + "type": "text" + }, + { + "name": "templateName", + "label": "templateName", + "type": "text" + }, + { + "name": "templateStatus", + "label": "templateStatus", + "type": "text" + }, + { + "name": "reason", + "label": "reason", + "type": "text" + } + ] + }, + { + "name": "fromConnection", + "label": "fromConnection", + "type": "text" + } +] diff --git a/make/modules/connectionState/metadata.json b/make/modules/connectionState/metadata.json new file mode 100644 index 0000000..5243bc0 --- /dev/null +++ b/make/modules/connectionState/metadata.json @@ -0,0 +1,6 @@ +{ + "label": "Connection State Changed", + "description": "Triggers when a Connection changes state, connects or logs out.", + "type": "instant", + "webhook": "connectionState" +} diff --git a/make/modules/listConnections/communication.json b/make/modules/listConnections/communication.json new file mode 100644 index 0000000..ee14dc8 --- /dev/null +++ b/make/modules/listConnections/communication.json @@ -0,0 +1,29 @@ +{ + "url": "{{get(polymorfaRequest('listConnections'; parameters; connection); 'url')}}", + "method": "{{get(polymorfaRequest('listConnections'; parameters; connection); 'method')}}", + "headers": "{{get(polymorfaRequest('listConnections'; parameters; connection); 'headers')}}", + "qs": "{{get(polymorfaRequest('listConnections'; parameters; connection); 'query')}}", + "body": "{{get(polymorfaRequest('listConnections'; parameters; connection); 'body')}}", + "type": "json", + "followRedirect": false, + "response": { + "valid": "{{polymorfaResult(statusCode; headers; body) != null}}", + "output": "{{polymorfaResult(statusCode; headers; body)}}", + "error": { + "409": { + "message": "{{polymorfaError(statusCode; headers; body; get(polymorfaRequest('listConnections'; parameters; connection); 'method'))}}" + }, + "429": { + "type": "RateLimitError", + "message": "{{polymorfaError(statusCode; headers; body; get(polymorfaRequest('listConnections'; parameters; connection); 'method'))}}" + }, + "message": "{{polymorfaError(statusCode; headers; body; get(polymorfaRequest('listConnections'; parameters; connection); 'method'))}}" + } + }, + "log": { + "sanitize": [ + "request.headers.authorization", + "request.headers.idempotency-key" + ] + } +} diff --git a/make/modules/listNumbers/interface.json b/make/modules/listConnections/interface.json similarity index 81% rename from make/modules/listNumbers/interface.json rename to make/modules/listConnections/interface.json index 8e782c0..188e8a2 100644 --- a/make/modules/listNumbers/interface.json +++ b/make/modules/listConnections/interface.json @@ -22,8 +22,8 @@ "type": "text" }, { - "name": "sessionId", - "label": "sessionId", + "name": "connectionId", + "label": "connectionId", "type": "text" }, { @@ -134,6 +134,30 @@ "type": "number" } ] + }, + { + "name": "inspector", + "label": "inspector", + "type": "collection", + "spec": [ + { + "name": "claim", + "label": "claim", + "type": "collection", + "spec": [ + { + "name": "claimed", + "label": "claimed", + "type": "boolean" + }, + { + "name": "claimedAt", + "label": "claimedAt", + "type": "date" + } + ] + } + ] } ] } diff --git a/make/modules/listConnections/metadata.json b/make/modules/listConnections/metadata.json new file mode 100644 index 0000000..14b4748 --- /dev/null +++ b/make/modules/listConnections/metadata.json @@ -0,0 +1,6 @@ +{ + "label": "List Connections", + "description": "Lists Connections visible to the connected project.", + "connection": "project", + "type": "action" +} diff --git a/make/modules/listNumbers/parameters.json b/make/modules/listConnections/parameters.json similarity index 100% rename from make/modules/listNumbers/parameters.json rename to make/modules/listConnections/parameters.json diff --git a/make/modules/listNumbers/communication.json b/make/modules/listNumbers/communication.json deleted file mode 100644 index 795a06a..0000000 --- a/make/modules/listNumbers/communication.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "url": "{{get(polymorfaRequest('listNumbers'; parameters; connection); 'url')}}", - "method": "{{get(polymorfaRequest('listNumbers'; parameters; connection); 'method')}}", - "headers": "{{get(polymorfaRequest('listNumbers'; parameters; connection); 'headers')}}", - "qs": "{{get(polymorfaRequest('listNumbers'; parameters; connection); 'query')}}", - "body": "{{get(polymorfaRequest('listNumbers'; parameters; connection); 'body')}}", - "type": "json", - "followRedirect": false, - "response": { - "valid": "{{polymorfaResult(statusCode; headers; body) != null}}", - "output": "{{polymorfaResult(statusCode; headers; body)}}", - "error": { - "409": { - "message": "{{polymorfaError(statusCode; headers; body; get(polymorfaRequest('listNumbers'; parameters; connection); 'method'))}}" - }, - "429": { - "type": "RateLimitError", - "message": "{{polymorfaError(statusCode; headers; body; get(polymorfaRequest('listNumbers'; parameters; connection); 'method'))}}" - }, - "message": "{{polymorfaError(statusCode; headers; body; get(polymorfaRequest('listNumbers'; parameters; connection); 'method'))}}" - } - }, - "log": { - "sanitize": [ - "request.headers.authorization", - "request.headers.idempotency-key" - ] - } -} diff --git a/make/modules/listNumbers/metadata.json b/make/modules/listNumbers/metadata.json deleted file mode 100644 index 280f699..0000000 --- a/make/modules/listNumbers/metadata.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "List Numbers", - "description": "Lists Numbers visible to the connected project.", - "connection": "project", - "type": "action" -} diff --git a/make/modules/messageReceived/interface.json b/make/modules/messageReceived/interface.json index fcad85f..923841a 100644 --- a/make/modules/messageReceived/interface.json +++ b/make/modules/messageReceived/interface.json @@ -5,8 +5,8 @@ "type": "text" }, { - "name": "session", - "label": "session", + "name": "connection", + "label": "connection", "type": "text" }, { @@ -240,6 +240,63 @@ "label": "unavailableReason", "type": "text" }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + }, + { + "name": "origin", + "label": "origin", + "type": "text" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "stickerPack", + "label": "stickerPack", + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "name", + "label": "name", + "type": "text" + }, + { + "name": "publisher", + "label": "publisher", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + }, + { + "name": "trayIconFileName", + "label": "trayIconFileName", + "type": "text" + }, + { + "name": "items", + "label": "items", + "type": "array" + } + ] + }, { "name": "width", "label": "width", @@ -406,5 +463,117 @@ ] } ] + }, + { + "name": "delivery", + "label": "delivery", + "type": "text" + }, + { + "name": "eventId", + "label": "eventId", + "type": "text" + }, + { + "name": "source", + "label": "source", + "type": "text" + }, + { + "name": "overrides", + "label": "overrides", + "type": "collection", + "spec": [ + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "from", + "label": "from", + "type": "text" + }, + { + "name": "pushName", + "label": "pushName", + "type": "text" + }, + { + "name": "mediaType", + "label": "mediaType", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "ackStatus", + "label": "ackStatus", + "type": "text" + }, + { + "name": "messageId", + "label": "messageId", + "type": "text" + }, + { + "name": "failureReason", + "label": "failureReason", + "type": "text" + }, + { + "name": "video", + "label": "video", + "type": "boolean" + }, + { + "name": "durationSeconds", + "label": "durationSeconds", + "type": "number" + }, + { + "name": "callEndReason", + "label": "callEndReason", + "type": "text" + }, + { + "name": "restrictionActive", + "label": "restrictionActive", + "type": "boolean" + }, + { + "name": "status", + "label": "status", + "type": "text" + }, + { + "name": "statusReason", + "label": "statusReason", + "type": "text" + }, + { + "name": "templateName", + "label": "templateName", + "type": "text" + }, + { + "name": "templateStatus", + "label": "templateStatus", + "type": "text" + }, + { + "name": "reason", + "label": "reason", + "type": "text" + } + ] + }, + { + "name": "fromConnection", + "label": "fromConnection", + "type": "text" } ] diff --git a/make/modules/messageState/interface.json b/make/modules/messageState/interface.json index ed8250e..d68468f 100644 --- a/make/modules/messageState/interface.json +++ b/make/modules/messageState/interface.json @@ -5,8 +5,8 @@ "type": "text" }, { - "name": "session", - "label": "session", + "name": "connection", + "label": "connection", "type": "text" }, { @@ -130,6 +130,98 @@ "label": "timestamp", "type": "number" }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + }, + { + "name": "origin", + "label": "origin", + "type": "text" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "stickerPack", + "label": "stickerPack", + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "name", + "label": "name", + "type": "text" + }, + { + "name": "publisher", + "label": "publisher", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + }, + { + "name": "trayIconFileName", + "label": "trayIconFileName", + "type": "text" + }, + { + "name": "items", + "label": "items", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "fileName", + "label": "fileName", + "type": "text" + }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "premium", + "label": "premium", + "type": "number" + } + ] + } + } + ] + }, { "name": "width", "label": "width", @@ -386,53 +478,6 @@ } ] }, - { - "name": "to", - "label": "to", - "type": "collection", - "spec": [ - { - "name": "id", - "label": "id", - "type": "text" - }, - { - "name": "phoneNumber", - "label": "phoneNumber", - "type": "text" - }, - { - "name": "bsuid", - "label": "bsuid", - "type": "text" - }, - { - "name": "username", - "label": "username", - "type": "text" - }, - { - "name": "parentBsuid", - "label": "parentBsuid", - "type": "text" - } - ] - }, - { - "name": "error", - "label": "error", - "type": "text" - }, - { - "name": "code", - "label": "code", - "type": "text" - }, - { - "name": "retryAfter", - "label": "retryAfter", - "type": "number" - }, { "name": "fromMe", "label": "fromMe", @@ -596,7 +641,166 @@ "name": "unavailableReason", "label": "unavailableReason", "type": "text" + }, + { + "name": "to", + "label": "to", + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "bsuid", + "label": "bsuid", + "type": "text" + }, + { + "name": "username", + "label": "username", + "type": "text" + }, + { + "name": "parentBsuid", + "label": "parentBsuid", + "type": "text" + } + ] + }, + { + "name": "error", + "label": "error", + "type": "text" + }, + { + "name": "code", + "label": "code", + "type": "text" + }, + { + "name": "retryAfter", + "label": "retryAfter", + "type": "number" } ] + }, + { + "name": "delivery", + "label": "delivery", + "type": "text" + }, + { + "name": "eventId", + "label": "eventId", + "type": "text" + }, + { + "name": "source", + "label": "source", + "type": "text" + }, + { + "name": "overrides", + "label": "overrides", + "type": "collection", + "spec": [ + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "from", + "label": "from", + "type": "text" + }, + { + "name": "pushName", + "label": "pushName", + "type": "text" + }, + { + "name": "mediaType", + "label": "mediaType", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "ackStatus", + "label": "ackStatus", + "type": "text" + }, + { + "name": "messageId", + "label": "messageId", + "type": "text" + }, + { + "name": "failureReason", + "label": "failureReason", + "type": "text" + }, + { + "name": "video", + "label": "video", + "type": "boolean" + }, + { + "name": "durationSeconds", + "label": "durationSeconds", + "type": "number" + }, + { + "name": "callEndReason", + "label": "callEndReason", + "type": "text" + }, + { + "name": "restrictionActive", + "label": "restrictionActive", + "type": "boolean" + }, + { + "name": "status", + "label": "status", + "type": "text" + }, + { + "name": "statusReason", + "label": "statusReason", + "type": "text" + }, + { + "name": "templateName", + "label": "templateName", + "type": "text" + }, + { + "name": "templateStatus", + "label": "templateStatus", + "type": "text" + }, + { + "name": "reason", + "label": "reason", + "type": "text" + } + ] + }, + { + "name": "fromConnection", + "label": "fromConnection", + "type": "text" } ] diff --git a/make/modules/numberState/interface.json b/make/modules/numberState/interface.json deleted file mode 100644 index ff1fe0c..0000000 --- a/make/modules/numberState/interface.json +++ /dev/null @@ -1,124 +0,0 @@ -[ - { - "name": "id", - "label": "id", - "type": "text" - }, - { - "name": "session", - "label": "session", - "type": "text" - }, - { - "name": "externalId", - "label": "externalId", - "type": "text" - }, - { - "name": "timestamp", - "label": "timestamp", - "type": "text" - }, - { - "name": "event", - "label": "event", - "type": "text" - }, - { - "name": "payload", - "label": "payload", - "type": "collection", - "spec": [ - { - "name": "status", - "label": "status", - "type": "text" - }, - { - "name": "statusReason", - "label": "statusReason", - "type": "text" - }, - { - "name": "banCode", - "label": "banCode", - "type": "number" - }, - { - "name": "banReason", - "label": "banReason", - "type": "text" - }, - { - "name": "banExpiresAt", - "label": "banExpiresAt", - "type": "number" - }, - { - "name": "detail", - "label": "detail", - "type": "text" - }, - { - "name": "source", - "label": "source", - "type": "text" - }, - { - "name": "kind", - "label": "kind", - "type": "text" - }, - { - "name": "wabaId", - "label": "wabaId", - "type": "text" - }, - { - "name": "value", - "label": "value", - "type": "collection" - }, - { - "name": "phoneNumber", - "label": "phoneNumber", - "type": "text" - }, - { - "name": "id", - "label": "id", - "type": "text" - }, - { - "name": "pushName", - "label": "pushName", - "type": "text" - }, - { - "name": "phonePlatform", - "label": "phonePlatform", - "type": "text" - }, - { - "name": "accountType", - "label": "accountType", - "type": "text" - }, - { - "name": "businessName", - "label": "businessName", - "type": "text" - }, - { - "name": "reason", - "label": "reason", - "type": "text" - }, - { - "name": "code", - "label": "code", - "type": "number" - } - ] - } -] diff --git a/make/modules/numberState/metadata.json b/make/modules/numberState/metadata.json deleted file mode 100644 index e834c46..0000000 --- a/make/modules/numberState/metadata.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Number State Changed", - "description": "Triggers when a Number changes state, connects or logs out.", - "type": "instant", - "webhook": "numberState" -} diff --git a/make/modules/react/parameters.json b/make/modules/react/parameters.json index 4d96b30..0a0964d 100644 --- a/make/modules/react/parameters.json +++ b/make/modules/react/parameters.json @@ -1,10 +1,10 @@ [ { - "name": "session", + "name": "connection", "type": "text", - "label": "Number", + "label": "Connection", "required": true, - "help": "The exact Number identifier from Polymorfa. Keep it as a string." + "help": "The exact Connection identifier from Polymorfa. Keep it as a string." }, { "name": "recipientType", diff --git a/make/modules/sendMedia/interface.json b/make/modules/sendMedia/interface.json index 1585677..624281c 100644 --- a/make/modules/sendMedia/interface.json +++ b/make/modules/sendMedia/interface.json @@ -246,13 +246,38 @@ "label": "sticker", "type": "collection", "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, { "name": "descriptor", "label": "descriptor", "type": "collection" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" } ] }, + { + "name": "stickerPack", + "label": "stickerPack", + "type": "collection" + }, { "name": "location", "label": "location", @@ -517,11 +542,38 @@ } ] }, + { + "name": "carousel", + "label": "carousel", + "type": "collection", + "spec": [ + { + "name": "body", + "label": "body", + "type": "text" + }, + { + "name": "footer", + "label": "footer", + "type": "text" + }, + { + "name": "cards", + "label": "cards", + "type": "array" + } + ] + }, { "name": "buttons", "label": "buttons", "type": "collection", "spec": [ + { + "name": "media", + "label": "media", + "type": "collection" + }, { "name": "title", "label": "title", diff --git a/make/modules/sendMedia/parameters.json b/make/modules/sendMedia/parameters.json index 517a4f3..5a322f6 100644 --- a/make/modules/sendMedia/parameters.json +++ b/make/modules/sendMedia/parameters.json @@ -1,10 +1,10 @@ [ { - "name": "session", + "name": "connection", "type": "text", - "label": "Number", + "label": "Connection", "required": true, - "help": "The exact Number identifier from Polymorfa. Keep it as a string." + "help": "The exact Connection identifier from Polymorfa. Keep it as a string." }, { "name": "recipientType", diff --git a/make/modules/sendTemplate/interface.json b/make/modules/sendTemplate/interface.json index 1585677..624281c 100644 --- a/make/modules/sendTemplate/interface.json +++ b/make/modules/sendTemplate/interface.json @@ -246,13 +246,38 @@ "label": "sticker", "type": "collection", "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, { "name": "descriptor", "label": "descriptor", "type": "collection" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" } ] }, + { + "name": "stickerPack", + "label": "stickerPack", + "type": "collection" + }, { "name": "location", "label": "location", @@ -517,11 +542,38 @@ } ] }, + { + "name": "carousel", + "label": "carousel", + "type": "collection", + "spec": [ + { + "name": "body", + "label": "body", + "type": "text" + }, + { + "name": "footer", + "label": "footer", + "type": "text" + }, + { + "name": "cards", + "label": "cards", + "type": "array" + } + ] + }, { "name": "buttons", "label": "buttons", "type": "collection", "spec": [ + { + "name": "media", + "label": "media", + "type": "collection" + }, { "name": "title", "label": "title", diff --git a/make/modules/sendTemplate/parameters.json b/make/modules/sendTemplate/parameters.json index 58fff62..a9781cc 100644 --- a/make/modules/sendTemplate/parameters.json +++ b/make/modules/sendTemplate/parameters.json @@ -1,10 +1,10 @@ [ { - "name": "session", + "name": "connection", "type": "text", - "label": "Number", + "label": "Connection", "required": true, - "help": "The exact Number identifier from Polymorfa. Keep it as a string." + "help": "The exact Connection identifier from Polymorfa. Keep it as a string." }, { "name": "recipientType", diff --git a/make/modules/sendText/interface.json b/make/modules/sendText/interface.json index 1585677..624281c 100644 --- a/make/modules/sendText/interface.json +++ b/make/modules/sendText/interface.json @@ -246,13 +246,38 @@ "label": "sticker", "type": "collection", "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, { "name": "descriptor", "label": "descriptor", "type": "collection" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" } ] }, + { + "name": "stickerPack", + "label": "stickerPack", + "type": "collection" + }, { "name": "location", "label": "location", @@ -517,11 +542,38 @@ } ] }, + { + "name": "carousel", + "label": "carousel", + "type": "collection", + "spec": [ + { + "name": "body", + "label": "body", + "type": "text" + }, + { + "name": "footer", + "label": "footer", + "type": "text" + }, + { + "name": "cards", + "label": "cards", + "type": "array" + } + ] + }, { "name": "buttons", "label": "buttons", "type": "collection", "spec": [ + { + "name": "media", + "label": "media", + "type": "collection" + }, { "name": "title", "label": "title", diff --git a/make/modules/sendText/parameters.json b/make/modules/sendText/parameters.json index 45a4c4a..ec1d38a 100644 --- a/make/modules/sendText/parameters.json +++ b/make/modules/sendText/parameters.json @@ -1,10 +1,10 @@ [ { - "name": "session", + "name": "connection", "type": "text", - "label": "Number", + "label": "Connection", "required": true, - "help": "The exact Number identifier from Polymorfa. Keep it as a string." + "help": "The exact Connection identifier from Polymorfa. Keep it as a string." }, { "name": "recipientType", diff --git a/make/webhooks/numberState/attach.json b/make/webhooks/connectionState/attach.json similarity index 61% rename from make/webhooks/numberState/attach.json rename to make/webhooks/connectionState/attach.json index 35ff5d6..da4a7b3 100644 --- a/make/webhooks/numberState/attach.json +++ b/make/webhooks/connectionState/attach.json @@ -7,7 +7,7 @@ }, "response": { "temp": { - "ownedId": "{{polymorfaFindHook(body; connection; webhook.url; 'numberState'; parameters.subscriptionKey)}}", + "ownedId": "{{polymorfaFindHook(body; connection; webhook.url; 'connectionState'; parameters.subscriptionKey)}}", "nonce": "{{polymorfaCreationNonce(webhook.url)}}" } } @@ -17,21 +17,21 @@ "url": "/platform/projects/{{polymorfaSegment(connection.projectId)}}/webhooks", "method": "POST", "headers": { - "Idempotency-Key": "{{polymorfaCreateKey(get(polymorfaHook(connection; 'numberState'; parameters.subscriptionKey); 'key'); temp.nonce)}}" + "Idempotency-Key": "{{polymorfaCreateKey(get(polymorfaHook(connection; 'connectionState'; parameters.subscriptionKey); 'key'); temp.nonce)}}" }, "body": { "url": "{{webhook.url}}", "eventTypes": [ - "session.status", - "session.connected", - "session.logged_out" + "connection.status", + "connection.connected", + "connection.logged_out" ], "format": "native", "enabled": true, "headers": [ { - "name": "{{get(polymorfaHook(connection; 'numberState'; parameters.subscriptionKey); 'name')}}", - "value": "{{get(polymorfaHook(connection; 'numberState'; parameters.subscriptionKey); 'value')}}" + "name": "{{get(polymorfaHook(connection; 'connectionState'; parameters.subscriptionKey); 'name')}}", + "value": "{{get(polymorfaHook(connection; 'connectionState'; parameters.subscriptionKey); 'value')}}" } ] }, @@ -52,10 +52,10 @@ }, "response": { "data": { - "externalHookId": "{{polymorfaLiveHook(body; connection; webhook.url; 'numberState'; parameters.subscriptionKey; ifempty(temp.ownedId; temp.createdId))}}", + "externalHookId": "{{polymorfaLiveHook(body; connection; webhook.url; 'connectionState'; parameters.subscriptionKey; ifempty(temp.ownedId; temp.createdId))}}", "ownedUrl": "{{webhook.url}}", - "receiverName": "{{get(polymorfaHook(connection; 'numberState'; parameters.subscriptionKey); 'name')}}", - "receiverValue": "{{get(polymorfaHook(connection; 'numberState'; parameters.subscriptionKey); 'value')}}" + "receiverName": "{{get(polymorfaHook(connection; 'connectionState'; parameters.subscriptionKey); 'name')}}", + "receiverValue": "{{get(polymorfaHook(connection; 'connectionState'; parameters.subscriptionKey); 'value')}}" } } } diff --git a/make/webhooks/connectionState/communication.json b/make/webhooks/connectionState/communication.json new file mode 100644 index 0000000..1f3602c --- /dev/null +++ b/make/webhooks/connectionState/communication.json @@ -0,0 +1,9 @@ +{ + "condition": "{{polymorfaReceive(parameters.receiverName; parameters.receiverValue; 'connectionState'; headers; body)}}", + "respond": { + "status": "{{if(polymorfaReceive(parameters.receiverName; parameters.receiverValue; 'connectionState'; headers; body); 200; 401)}}", + "type": "json", + "body": {} + }, + "output": "{{polymorfaEnvelope(body; 'connectionState')}}" +} diff --git a/make/webhooks/numberState/detach.json b/make/webhooks/connectionState/detach.json similarity index 89% rename from make/webhooks/numberState/detach.json rename to make/webhooks/connectionState/detach.json index 4f2c35b..3cb6a1a 100644 --- a/make/webhooks/numberState/detach.json +++ b/make/webhooks/connectionState/detach.json @@ -3,9 +3,9 @@ "url": "/platform/projects/{{polymorfaSegment(connection.projectId)}}/webhooks/{{polymorfaSegment(webhook.externalHookId)}}", "method": "GET", "response": { - "valid": "{{polymorfaDetachHook(statusCode; body; webhook.externalHookId; connection.projectId; webhook.ownedUrl; webhook.receiverName; 'numberState') != null}}", + "valid": "{{polymorfaDetachHook(statusCode; body; webhook.externalHookId; connection.projectId; webhook.ownedUrl; webhook.receiverName; 'connectionState') != null}}", "temp": { - "ownedPresent": "{{polymorfaDetachHook(statusCode; body; webhook.externalHookId; connection.projectId; webhook.ownedUrl; webhook.receiverName; 'numberState')}}" + "ownedPresent": "{{polymorfaDetachHook(statusCode; body; webhook.externalHookId; connection.projectId; webhook.ownedUrl; webhook.receiverName; 'connectionState')}}" } } }, diff --git a/make/webhooks/numberState/metadata.json b/make/webhooks/connectionState/metadata.json similarity index 58% rename from make/webhooks/numberState/metadata.json rename to make/webhooks/connectionState/metadata.json index 85a747f..4e43446 100644 --- a/make/webhooks/numberState/metadata.json +++ b/make/webhooks/connectionState/metadata.json @@ -1,5 +1,5 @@ { "type": "dedicated", "connection": "project", - "label": "Number State Changed" + "label": "Connection State Changed" } diff --git a/make/webhooks/numberState/parameters.json b/make/webhooks/connectionState/parameters.json similarity index 100% rename from make/webhooks/numberState/parameters.json rename to make/webhooks/connectionState/parameters.json diff --git a/make/webhooks/numberState/communication.json b/make/webhooks/numberState/communication.json deleted file mode 100644 index 7885eb3..0000000 --- a/make/webhooks/numberState/communication.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "condition": "{{polymorfaReceive(parameters.receiverName; parameters.receiverValue; 'numberState'; headers; body)}}", - "respond": { - "status": "{{if(polymorfaReceive(parameters.receiverName; parameters.receiverValue; 'numberState'; headers; body); 200; 401)}}", - "type": "json", - "body": {} - }, - "output": "{{polymorfaEnvelope(body; 'numberState')}}" -} diff --git a/n8n/README.md b/n8n/README.md index 5386459..ccb2f6e 100644 --- a/n8n/README.md +++ b/n8n/README.md @@ -5,8 +5,8 @@ not been published or verified by n8n. Do not treat an npm name or this source a a marketplace listing. The node sends text/replies, templates, image/video/file/voice media and reactions; -lists Numbers/templates; and makes allowlisted public API calls. It is usable as -an AI tool. The trigger receives project-wide message, Number-state and completed +lists Connections/templates; and makes allowlisted public API calls. It is usable as +an AI tool. The trigger receives project-wide message, Connection-state and completed call events. Functions and asynchronous operation reads are not exposed yet. Build from this repository's root using the instructions in `MAINTAINING.md`. @@ -17,7 +17,7 @@ npm pack --workspace n8n-nodes-polymorfa ``` Create a **Polymorfa API** credential with a restricted project token and project -UUID. The credential test and Number picker need `sessions:read`; sends and +UUID. The credential test and Connection picker need `connections:read`; sends and reactions need `messages:write`; template lookup needs `templates:read`. Triggers also need `webhooks:read` and `webhooks:manage`. diff --git a/n8n/credentials/PolymorfaApi.credentials.ts b/n8n/credentials/PolymorfaApi.credentials.ts index 1d9de7d..4c36ed8 100644 --- a/n8n/credentials/PolymorfaApi.credentials.ts +++ b/n8n/credentials/PolymorfaApi.credentials.ts @@ -7,8 +7,8 @@ export class PolymorfaApi implements ICredentialType { icon: ICredentialType['icon'] = { light: 'file:../nodes/Polymorfa/polymorfa.light.svg', dark: 'file:../nodes/Polymorfa/polymorfa.dark.svg' }; properties: INodeProperties[] = [ { displayName: 'Project Token', name: 'apiKey', type: 'string', typeOptions: { password: true }, default: '', required: true }, - { displayName: 'Project ID', name: 'projectId', type: 'string', default: '', required: true, description: 'The project UUID for the token. The token needs sessions:read to test the connection.' }, + { displayName: 'Project ID', name: 'projectId', type: 'string', default: '', required: true, description: 'The project UUID for the token. The token needs connections:read to test the connection.' }, ]; authenticate: IAuthenticateGeneric = { type: 'generic', properties: { headers: { Authorization: '=Bearer {{$credentials.apiKey}}', 'Polymorfa-Version': '2026-09-22' } } }; - test: ICredentialTestRequest = { request: { baseURL: 'https://api.polymorfa.com', url: '/platform/sessions', qs: { projectId: '={{$credentials.projectId}}' } } }; + test: ICredentialTestRequest = { request: { baseURL: 'https://api.polymorfa.com', url: '/platform/connections', qs: { projectId: '={{$credentials.projectId}}' } } }; } diff --git a/n8n/nodes/Polymorfa/Polymorfa.node.ts b/n8n/nodes/Polymorfa/Polymorfa.node.ts index 8bb6f92..e75555e 100644 --- a/n8n/nodes/Polymorfa/Polymorfa.node.ts +++ b/n8n/nodes/Polymorfa/Polymorfa.node.ts @@ -9,8 +9,8 @@ const descriptors = fields as Record; const properties: INodeProperties[] = [ { displayName: 'Operation', name: 'operation', type: 'options', noDataExpression: true, default: 'sendText', options: Object.entries(actions).map(([value, a]) => ({ name: a.label, value, description: a.description, action: a.label })) }, ...Object.entries(descriptors).map(([name, f]): INodeProperties => ({ - displayName: f.label, name, type: f.options || name === 'session' ? 'options' : 'string', default: f.default ?? '', - ...(name === 'session' ? { typeOptions: { loadOptionsMethod: 'getNumbers' } } : {}), + displayName: f.label, name, type: f.options || name === 'connection' ? 'options' : 'string', default: f.default ?? '', + ...(name === 'connection' ? { typeOptions: { loadOptionsMethod: 'getConnections' } } : {}), required: f.required ?? false, description: f.help, ...(f.options ? { options: Object.entries({ ...f.options, ...(name === 'mediaSource' ? { binary: 'n8n Binary Input' } : {}) }).map(([value, label]) => ({ name: label, value })) } : {}), displayOptions: { show: { operation: Object.entries(actions).filter(([, a]) => (a.fields as readonly string[]).includes(name)).map(([key]) => key) } }, @@ -29,10 +29,10 @@ export class Polymorfa implements INodeType { credentials: [{ name: 'polymorfaApi', required: true }], properties, }; methods = { loadOptions: { - async getNumbers(this: ILoadOptionsFunctions) { + async getConnections(this: ILoadOptionsFunctions) { const auth = await this.getCredentials('polymorfaApi'); - const result = await execute('listNumbers', {}, auth, transport(this), 'n8n'); - return result.data.map((n: { sessionId: string; name?: string | null }) => ({ name: n.name ? `${n.name} (${n.sessionId})` : n.sessionId, value: n.sessionId })); + const result = await execute('listConnections', {}, auth, transport(this), 'n8n'); + return result.data.map((n: { connectionId: string; name?: string | null }) => ({ name: n.name ? `${n.name} (${n.connectionId})` : n.connectionId, value: n.connectionId })); }, } }; async execute(this: IExecuteFunctions): Promise { diff --git a/n8n/nodes/Polymorfa/PolymorfaTrigger.node.ts b/n8n/nodes/Polymorfa/PolymorfaTrigger.node.ts index 215e4de..a839406 100644 --- a/n8n/nodes/Polymorfa/PolymorfaTrigger.node.ts +++ b/n8n/nodes/Polymorfa/PolymorfaTrigger.node.ts @@ -14,7 +14,7 @@ export class PolymorfaTrigger implements INodeType { properties: [ { displayName: 'Event', name: 'eventGroup', type: 'options', default: 'messageReceived', options: Object.entries(events).map(([value, event]) => ({ name: event.label, value, description: event.description })) }, { displayName: 'Subscription Key', name: 'subscriptionKey', type: 'string', required: true, default: '', description: 'A unique stable label for this trigger. Keep it on reactivation; use a different value for another trigger.' }, - { displayName: 'Events are project-wide. Filtering after receipt does not limit which Numbers disclose events to n8n.', name: 'scopeNotice', type: 'notice', default: '' }, + { displayName: 'Events are project-wide. Filtering after receipt does not limit which Connections disclose events to n8n.', name: 'scopeNotice', type: 'notice', default: '' }, ], }; webhookMethods = { default: { diff --git a/n8n/shared/catalog.js b/n8n/shared/catalog.js index eb14536..e8d0221 100644 --- a/n8n/shared/catalog.js +++ b/n8n/shared/catalog.js @@ -2,16 +2,16 @@ 'use strict'; const actions = { - sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, - sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, - sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, - react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['session', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, - listNumbers: { label: 'List Numbers', description: 'Lists Numbers visible to the connected project.', operation: 'listPlatformSessions', fields: [] }, + sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, + sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, + sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, + react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['connection', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, + listConnections: { label: 'List Connections', description: 'Lists Connections visible to the connected project.', operation: 'listPlatformConnections', fields: [] }, listTemplates: { label: 'List Templates', description: 'Lists message templates for a project.', operation: 'listProjectTemplates', fields: ['projectSlug'] }, apiRequest: { label: 'Make an API Call', description: 'Performs an authorized call to a supported public Polymorfa operation.', operation: null, fields: ['method', 'path', 'requestBody', 'idempotencyKey', 'writeCreatedAt'] }, }; const fields = { - session: { label: 'Number', required: true, help: 'The exact Number identifier from Polymorfa. Keep it as a string.' }, + connection: { label: 'Connection', required: true, help: 'The exact Connection identifier from Polymorfa. Keep it as a string.' }, recipientType: { label: 'Recipient Type', required: true, options: { phoneNumber: 'Phone Number', id: 'Conversation ID', bsuid: 'Business-scoped User ID' }, default: 'phoneNumber' }, recipient: { label: 'Recipient', required: true, help: 'Use an international phone number including +, a conversation ID, or a business-scoped user ID.' }, text: { label: 'Text', required: true }, @@ -31,13 +31,13 @@ const fields = { writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, - path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/sessions. External hosts and credential operations are refused.' }, + path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, requestBody: { label: 'Request Body', json: true, default: '{}', help: 'JSON object. Authentication and version headers are supplied by the connection.' }, }; const events = { messageReceived: { label: 'New Message', description: 'Triggers when a message is received.', types: ['message.received'] }, messageState: { label: 'Message State Changed', description: 'Triggers when a message is sent, acknowledged, failed or updated.', types: ['message.sent', 'message.ack', 'message.failed', 'message.update'] }, - numberState: { label: 'Number State Changed', description: 'Triggers when a Number changes state, connects or logs out.', types: ['session.status', 'session.connected', 'session.logged_out'] }, + connectionState: { label: 'Connection State Changed', description: 'Triggers when a Connection changes state, connects or logs out.', types: ['connection.status', 'connection.connected', 'connection.logged_out'] }, callEnded: { label: 'Call Ended', description: 'Triggers when a call ends.', types: ['call.ended'] }, }; module.exports = { actions, fields, events }; diff --git a/n8n/shared/core.js b/n8n/shared/core.js index 3d7596b..c2302db 100644 --- a/n8n/shared/core.js +++ b/n8n/shared/core.js @@ -92,7 +92,7 @@ function advanced(p, auth) { const path = required(p.path, 'path'); if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; - const allowed = (method === 'GET' && (path === '/platform/sessions' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || + const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; @@ -100,12 +100,12 @@ function advanced(p, auth) { const keys = path.endsWith('/react') ? ['conversation', 'id', 'reaction'] : ['conversation', 'isForwarded', 'mentions', 'quotedMessage', 'content']; if (Object.keys(body).some(k => !keys.includes(k))) throw new IntegrationError('unsupported_request_field'); } - return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/sessions' ? { query: { projectId: auth.projectId } } : {}) }; + return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/connections' ? { query: { projectId: auth.projectId } } : {}) }; } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.session, 'number')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; - else if (action === 'listNumbers') r = { method: 'GET', url: ORIGIN + '/platform/sessions', query: { projectId: auth.projectId } }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); else throw new IntegrationError('unknown_action'); diff --git a/n8n/shared/hooks.js b/n8n/shared/hooks.js index 9b68200..87143ea 100644 --- a/n8n/shared/hooks.js +++ b/n8n/shared/hooks.js @@ -127,8 +127,8 @@ function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = return timingSafeEqual(Buffer.from(entries[0][1]), Buffer.from(expected.value)); } function envelope(body, group) { - if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.session !== 'string' || !body.session || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); + if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.connection !== 'string' || !body.connection || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); // Copy the defined envelope only. Never export arbitrary top-level transport fields. - return { id: body.id, session: body.session, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; + return { id: body.id, connection: body.connection, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; } module.exports = { identity, callback, sameCallback, creationKey, creation, owns, find, subscribe, activate, unsubscribe, authenticate, envelope }; diff --git a/n8n/shared/samples.json b/n8n/shared/samples.json index a5b25e2..3232e33 100644 --- a/n8n/shared/samples.json +++ b/n8n/shared/samples.json @@ -1,7 +1,7 @@ { "messageReceived": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.received", "payload": { @@ -22,7 +22,7 @@ }, "messageState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a72", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.sent", "payload": { @@ -37,18 +37,18 @@ "timestamp": 1793534400 } }, - "numberState": { + "connectionState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a73", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", - "event": "session.status", + "event": "connection.status", "payload": { "status": "connected" } }, "callEnded": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a74", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "call.ended", "payload": { diff --git a/pipedream/README.md b/pipedream/README.md index f655617..915aa0c 100644 --- a/pipedream/README.md +++ b/pipedream/README.md @@ -6,8 +6,8 @@ record has been requested and no registry PR has been submitted. The app slug The requested custom authentication fields are `api_key` (a secret project token) and `project_id` (its project UUID). Verify credentials through -`GET /platform/sessions?projectId=...` with the accepted `Polymorfa-Version`. -This needs `sessions:read`. Restrict each connection's remaining scopes to its +`GET /platform/connections?projectId=...` with the accepted `Polymorfa-Version`. +This needs `connections:read`. Restrict each connection's remaining scopes to its actions and hooks. Never use dashboard cookies or client-token impersonation. Each native action uses `polymorfa.app.mjs` and the provider's Axios helper with @@ -25,4 +25,4 @@ Examples target Connect action/tool/event use. Do not create recipes around the Workflows builder scheduled to retire on March 31, 2027. Pipedream processing has its own residency and retention. Do not imply that a -Polymorfa EU/Brazil Number places external component execution in that region. +Polymorfa EU/Brazil Connection places external component execution in that region. diff --git a/pipedream/actions/apiRequest/apiRequest.mjs b/pipedream/actions/apiRequest/apiRequest.mjs index 642afd1..804ad0a 100644 --- a/pipedream/actions/apiRequest/apiRequest.mjs +++ b/pipedream/actions/apiRequest/apiRequest.mjs @@ -24,7 +24,7 @@ export default { "type": "string", "label": "Path", "optional": false, - "description": "A supported relative public API path, for example /platform/sessions. External hosts and credential operations are refused." + "description": "A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused." }, "requestBody": { "type": "string", diff --git a/pipedream/actions/listNumbers/listNumbers.mjs b/pipedream/actions/listConnections/listConnections.mjs similarity index 58% rename from pipedream/actions/listNumbers/listNumbers.mjs rename to pipedream/actions/listConnections/listConnections.mjs index 91dadba..4052702 100644 --- a/pipedream/actions/listNumbers/listNumbers.mjs +++ b/pipedream/actions/listConnections/listConnections.mjs @@ -1,11 +1,11 @@ // Generated from shared/catalog.cjs. import polymorfa from '../../polymorfa.app.mjs'; export default { - key: "polymorfa-listNumbers", name: "List Numbers", description: "Lists Numbers visible to the connected project.", + key: "polymorfa-listConnections", name: "List Connections", description: "Lists Connections visible to the connected project.", version: '0.1.0', type: 'action', props: { polymorfa, ...{} }, async run({ $ }) { const input = Object.fromEntries([].map(key => [key, this[key]])); - return this.polymorfa.execute($, "listNumbers", input); + return this.polymorfa.execute($, "listConnections", input); }, }; diff --git a/pipedream/actions/react/react.mjs b/pipedream/actions/react/react.mjs index efb0d5e..183ec99 100644 --- a/pipedream/actions/react/react.mjs +++ b/pipedream/actions/react/react.mjs @@ -4,11 +4,11 @@ export default { key: "polymorfa-react", name: "React to Message", description: "Adds or removes a reaction on a message.", version: '0.1.0', type: 'action', props: { polymorfa, ...{ - "session": { + "connection": { "type": "string", - "label": "Number", + "label": "Connection", "optional": false, - "description": "The exact Number identifier from Polymorfa. Keep it as a string." + "description": "The exact Connection identifier from Polymorfa. Keep it as a string." }, "recipientType": { "type": "string", @@ -61,7 +61,7 @@ export default { } } }, async run({ $ }) { - const input = Object.fromEntries(["session","recipientType","recipient","messageId","reaction","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); + const input = Object.fromEntries(["connection","recipientType","recipient","messageId","reaction","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); return this.polymorfa.execute($, "react", input); }, }; diff --git a/pipedream/actions/sendMedia/sendMedia.mjs b/pipedream/actions/sendMedia/sendMedia.mjs index b1586e0..156656b 100644 --- a/pipedream/actions/sendMedia/sendMedia.mjs +++ b/pipedream/actions/sendMedia/sendMedia.mjs @@ -4,11 +4,11 @@ export default { key: "polymorfa-sendMedia", name: "Send Media", description: "Sends an image, video, file or voice message.", version: '0.1.0', type: 'action', props: { polymorfa, ...{ - "session": { + "connection": { "type": "string", - "label": "Number", + "label": "Connection", "optional": false, - "description": "The exact Number identifier from Polymorfa. Keep it as a string." + "description": "The exact Connection identifier from Polymorfa. Keep it as a string." }, "recipientType": { "type": "string", @@ -112,7 +112,7 @@ export default { } } }, async run({ $ }) { - const input = Object.fromEntries(["session","recipientType","recipient","mediaType","mediaSource","media","mimeType","caption","filename","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); + const input = Object.fromEntries(["connection","recipientType","recipient","mediaType","mediaSource","media","mimeType","caption","filename","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); return this.polymorfa.execute($, "sendMedia", input); }, }; diff --git a/pipedream/actions/sendTemplate/sendTemplate.mjs b/pipedream/actions/sendTemplate/sendTemplate.mjs index 5d96166..358c94f 100644 --- a/pipedream/actions/sendTemplate/sendTemplate.mjs +++ b/pipedream/actions/sendTemplate/sendTemplate.mjs @@ -4,11 +4,11 @@ export default { key: "polymorfa-sendTemplate", name: "Send Template", description: "Sends a template with its approved name and language.", version: '0.1.0', type: 'action', props: { polymorfa, ...{ - "session": { + "connection": { "type": "string", - "label": "Number", + "label": "Connection", "optional": false, - "description": "The exact Number identifier from Polymorfa. Keep it as a string." + "description": "The exact Connection identifier from Polymorfa. Keep it as a string." }, "recipientType": { "type": "string", @@ -68,7 +68,7 @@ export default { } } }, async run({ $ }) { - const input = Object.fromEntries(["session","recipientType","recipient","templateName","language","components","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); + const input = Object.fromEntries(["connection","recipientType","recipient","templateName","language","components","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); return this.polymorfa.execute($, "sendTemplate", input); }, }; diff --git a/pipedream/actions/sendText/sendText.mjs b/pipedream/actions/sendText/sendText.mjs index 3b810e2..8157c3d 100644 --- a/pipedream/actions/sendText/sendText.mjs +++ b/pipedream/actions/sendText/sendText.mjs @@ -4,11 +4,11 @@ export default { key: "polymorfa-sendText", name: "Send Text", description: "Sends a text message or replies to a message.", version: '0.1.0', type: 'action', props: { polymorfa, ...{ - "session": { + "connection": { "type": "string", - "label": "Number", + "label": "Connection", "optional": false, - "description": "The exact Number identifier from Polymorfa. Keep it as a string." + "description": "The exact Connection identifier from Polymorfa. Keep it as a string." }, "recipientType": { "type": "string", @@ -61,7 +61,7 @@ export default { } } }, async run({ $ }) { - const input = Object.fromEntries(["session","recipientType","recipient","text","quotedMessageId","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); + const input = Object.fromEntries(["connection","recipientType","recipient","text","quotedMessageId","idempotencyKey","writeCreatedAt"].map(key => [key, this[key]])); return this.polymorfa.execute($, "sendText", input); }, }; diff --git a/pipedream/common/catalog.cjs b/pipedream/common/catalog.cjs index eb14536..e8d0221 100644 --- a/pipedream/common/catalog.cjs +++ b/pipedream/common/catalog.cjs @@ -2,16 +2,16 @@ 'use strict'; const actions = { - sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, - sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, - sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, - react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['session', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, - listNumbers: { label: 'List Numbers', description: 'Lists Numbers visible to the connected project.', operation: 'listPlatformSessions', fields: [] }, + sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, + sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, + sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, + react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['connection', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, + listConnections: { label: 'List Connections', description: 'Lists Connections visible to the connected project.', operation: 'listPlatformConnections', fields: [] }, listTemplates: { label: 'List Templates', description: 'Lists message templates for a project.', operation: 'listProjectTemplates', fields: ['projectSlug'] }, apiRequest: { label: 'Make an API Call', description: 'Performs an authorized call to a supported public Polymorfa operation.', operation: null, fields: ['method', 'path', 'requestBody', 'idempotencyKey', 'writeCreatedAt'] }, }; const fields = { - session: { label: 'Number', required: true, help: 'The exact Number identifier from Polymorfa. Keep it as a string.' }, + connection: { label: 'Connection', required: true, help: 'The exact Connection identifier from Polymorfa. Keep it as a string.' }, recipientType: { label: 'Recipient Type', required: true, options: { phoneNumber: 'Phone Number', id: 'Conversation ID', bsuid: 'Business-scoped User ID' }, default: 'phoneNumber' }, recipient: { label: 'Recipient', required: true, help: 'Use an international phone number including +, a conversation ID, or a business-scoped user ID.' }, text: { label: 'Text', required: true }, @@ -31,13 +31,13 @@ const fields = { writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, - path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/sessions. External hosts and credential operations are refused.' }, + path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, requestBody: { label: 'Request Body', json: true, default: '{}', help: 'JSON object. Authentication and version headers are supplied by the connection.' }, }; const events = { messageReceived: { label: 'New Message', description: 'Triggers when a message is received.', types: ['message.received'] }, messageState: { label: 'Message State Changed', description: 'Triggers when a message is sent, acknowledged, failed or updated.', types: ['message.sent', 'message.ack', 'message.failed', 'message.update'] }, - numberState: { label: 'Number State Changed', description: 'Triggers when a Number changes state, connects or logs out.', types: ['session.status', 'session.connected', 'session.logged_out'] }, + connectionState: { label: 'Connection State Changed', description: 'Triggers when a Connection changes state, connects or logs out.', types: ['connection.status', 'connection.connected', 'connection.logged_out'] }, callEnded: { label: 'Call Ended', description: 'Triggers when a call ends.', types: ['call.ended'] }, }; module.exports = { actions, fields, events }; diff --git a/pipedream/common/core.cjs b/pipedream/common/core.cjs index 3d7596b..c2302db 100644 --- a/pipedream/common/core.cjs +++ b/pipedream/common/core.cjs @@ -92,7 +92,7 @@ function advanced(p, auth) { const path = required(p.path, 'path'); if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; - const allowed = (method === 'GET' && (path === '/platform/sessions' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || + const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; @@ -100,12 +100,12 @@ function advanced(p, auth) { const keys = path.endsWith('/react') ? ['conversation', 'id', 'reaction'] : ['conversation', 'isForwarded', 'mentions', 'quotedMessage', 'content']; if (Object.keys(body).some(k => !keys.includes(k))) throw new IntegrationError('unsupported_request_field'); } - return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/sessions' ? { query: { projectId: auth.projectId } } : {}) }; + return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/connections' ? { query: { projectId: auth.projectId } } : {}) }; } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.session, 'number')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; - else if (action === 'listNumbers') r = { method: 'GET', url: ORIGIN + '/platform/sessions', query: { projectId: auth.projectId } }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); else throw new IntegrationError('unknown_action'); diff --git a/pipedream/common/hooks.cjs b/pipedream/common/hooks.cjs index 8b518a7..4818f39 100644 --- a/pipedream/common/hooks.cjs +++ b/pipedream/common/hooks.cjs @@ -127,8 +127,8 @@ function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = return timingSafeEqual(Buffer.from(entries[0][1]), Buffer.from(expected.value)); } function envelope(body, group) { - if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.session !== 'string' || !body.session || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); + if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.connection !== 'string' || !body.connection || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); // Copy the defined envelope only. Never export arbitrary top-level transport fields. - return { id: body.id, session: body.session, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; + return { id: body.id, connection: body.connection, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; } module.exports = { identity, callback, sameCallback, creationKey, creation, owns, find, subscribe, activate, unsubscribe, authenticate, envelope }; diff --git a/pipedream/common/samples.json b/pipedream/common/samples.json index a5b25e2..3232e33 100644 --- a/pipedream/common/samples.json +++ b/pipedream/common/samples.json @@ -1,7 +1,7 @@ { "messageReceived": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.received", "payload": { @@ -22,7 +22,7 @@ }, "messageState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a72", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.sent", "payload": { @@ -37,18 +37,18 @@ "timestamp": 1793534400 } }, - "numberState": { + "connectionState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a73", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", - "event": "session.status", + "event": "connection.status", "payload": { "status": "connected" } }, "callEnded": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a74", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "call.ended", "payload": { diff --git a/pipedream/polymorfa.app.mjs b/pipedream/polymorfa.app.mjs index 29f56b8..d1b20ce 100644 --- a/pipedream/polymorfa.app.mjs +++ b/pipedream/polymorfa.app.mjs @@ -5,7 +5,7 @@ import hooks from './common/hooks.cjs'; export default { type: 'app', app: 'polymorfa', propDefinitions: { - session: { type: 'string', label: 'Number', description: 'Exact Polymorfa Number identifier, kept as a string.' }, + connection: { type: 'string', label: 'Connection', description: 'Exact Polymorfa Connection identifier, kept as a string.' }, }, methods: { auth() { return { apiKey: this.$auth.api_key, projectId: this.$auth.project_id }; }, diff --git a/pipedream/sources/numberState/numberState.mjs b/pipedream/sources/connectionState/connectionState.mjs similarity index 69% rename from pipedream/sources/numberState/numberState.mjs rename to pipedream/sources/connectionState/connectionState.mjs index cff0dfd..12f902b 100644 --- a/pipedream/sources/numberState/numberState.mjs +++ b/pipedream/sources/connectionState/connectionState.mjs @@ -1,14 +1,14 @@ // Generated from shared/catalog.cjs. import polymorfa from '../../polymorfa.app.mjs'; export default { - key: "polymorfa-numberState", name: "Number State Changed", description: "Triggers when a Number changes state, connects or logs out.", + key: "polymorfa-connectionState", name: "Connection State Changed", description: "Triggers when a Connection changes state, connects or logs out.", version: '0.1.0', type: 'source', dedupe: 'unique', props: { polymorfa, db: '$.service.db', http: { type: '$.interface.http', customResponse: true }, subscriptionKey: { type: 'string', label: 'Subscription Key', description: 'Unique stable label for this source. Events are project-wide.' } }, hooks: { async activate() { const store = { get: () => this.db.get('pendingCreation'), set: value => this.db.set('pendingCreation', value || null) }; - const owned = await this.polymorfa.activate(undefined, this.http.endpoint, "numberState", this.subscriptionKey, store); + const owned = await this.polymorfa.activate(undefined, this.http.endpoint, "connectionState", this.subscriptionKey, store); this.db.set('ownedSubscription', owned); }, async deactivate() { @@ -18,9 +18,9 @@ export default { }, }, async run(event) { - if (!this.polymorfa.authenticate("numberState", this.subscriptionKey, event.headers)) { this.http.respond({ status: 401 }); return; } + if (!this.polymorfa.authenticate("connectionState", this.subscriptionKey, event.headers)) { this.http.respond({ status: 401 }); return; } let data; - try { data = this.polymorfa.envelope(event.body, "numberState"); } catch { this.http.respond({ status: 400 }); return; } + try { data = this.polymorfa.envelope(event.body, "connectionState"); } catch { this.http.respond({ status: 400 }); return; } this.$emit(data, { id: data.id, summary: data.event, ts: Date.parse(data.timestamp) }); this.http.respond({ status: 200 }); }, diff --git a/recipes/README.md b/recipes/README.md index 4148763..f3bcf92 100644 --- a/recipes/README.md +++ b/recipes/README.md @@ -16,7 +16,7 @@ source that supplies these string fields: ```json { - "numberId": "YOUR_NUMBER_ID", + "connectionId": "YOUR_CONNECTION_ID", "recipient": "YOUR_AUTHORIZED_TEST_RECIPIENT", "notificationId": "YOUR_SAVED_NOTIFICATION_ID", "notificationStartedAt": "YOUR_SAVED_ISO_TIMESTAMP", diff --git a/recipes/field-maps.json b/recipes/field-maps.json index c5ef87d..56f2589 100644 --- a/recipes/field-maps.json +++ b/recipes/field-maps.json @@ -2,7 +2,7 @@ "stage": "native templates pending assigned app IDs and editor acceptance", "orderNotification": { "action": "sendText", - "fields": { "session": "order.numberId", "recipientType": "phoneNumber", "recipient": "order.recipient", "text": "order.notificationText", "idempotencyKey": "order-notification:{savedNotificationId}", "writeCreatedAt": "order.savedNotificationStartedAt" }, + "fields": { "connection": "order.connectionId", "recipientType": "phoneNumber", "recipient": "order.recipient", "text": "order.notificationText", "idempotencyKey": "order-notification:{savedNotificationId}", "writeCreatedAt": "order.savedNotificationStartedAt" }, "platforms": { "make": { "module": "sendText", "appId": null, "blueprintId": null }, "zapier": { "action": "sendText", "appId": null, "templateId": null }, diff --git a/recipes/n8n/order-notification.json b/recipes/n8n/order-notification.json index 6b63a86..0486e5b 100644 --- a/recipes/n8n/order-notification.json +++ b/recipes/n8n/order-notification.json @@ -37,7 +37,7 @@ ], "parameters": { "operation": "sendText", - "session": "={{$json.numberId}}", + "connection": "={{$json.connectionId}}", "recipientType": "phoneNumber", "recipient": "={{$json.recipient}}", "text": "={{$json.notificationText}}", diff --git a/scripts/generate.mjs b/scripts/generate.mjs index 08e70b6..ca65246 100644 --- a/scripts/generate.mjs +++ b/scripts/generate.mjs @@ -71,7 +71,7 @@ imlFunction('polymorfaEnvelope', 'body, group', `${errorClass}\nconst events = $ imlFunction('polymorfaLiveHook', 'body, auth, url, group, key, expectedId', '', `const id = iml.polymorfaFindHook(body, auth, url, group, key);\nif (!id || id !== expectedId) throw new Error('Subscription receipt needs reconciliation.');\nreturn id;`); imlFunction('polymorfaCallback', 'value', '', `if (typeof value !== 'string' || /[\\s\\\\\\x00-\\x1f\\x7f]/.test(value)) throw new Error('Invalid callback.');\nconst parts = value.match(/^https:\\/\\/([^/?#]+)([^?#]*)(\\?[^#]*)?$/i);\nif (!parts || parts[1].includes('@')) throw new Error('Invalid callback.');\nreturn 'https://' + parts[1].toLowerCase().replace(/:443$/, '') + (parts[2] || '/') + (parts[3] || '');`); imlFunction('polymorfaError', 'status, headers, body, method', '', `try { iml.polymorfaResult(status, headers, body, method); return 'Polymorfa invalid_response'; } catch (error) { return error.message; }`); -imlFunction('polymorfaReceive', 'expectedName, expectedValue, group, headers, body', `const types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};`, `const entries = Object.entries(headers || {}).filter(([key]) => key.toLowerCase() === String(expectedName).toLowerCase());\nif (!expectedValue || entries.length !== 1 || entries[0][1] !== expectedValue) return false;\nreturn !!(body && typeof body.id === 'string' && body.id && typeof body.session === 'string' && body.session && types[group] && types[group].includes(body.event) && typeof body.timestamp === 'string' && Number.isFinite(Date.parse(body.timestamp)) && body.payload && typeof body.payload === 'object' && !Array.isArray(body.payload));`); +imlFunction('polymorfaReceive', 'expectedName, expectedValue, group, headers, body', `const types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};`, `const entries = Object.entries(headers || {}).filter(([key]) => key.toLowerCase() === String(expectedName).toLowerCase());\nif (!expectedValue || entries.length !== 1 || entries[0][1] !== expectedValue) return false;\nreturn !!(body && typeof body.id === 'string' && body.id && typeof body.connection === 'string' && body.connection && types[group] && types[group].includes(body.event) && typeof body.timestamp === 'string' && Number.isFinite(Date.parse(body.timestamp)) && body.payload && typeof body.payload === 'object' && !Array.isArray(body.payload));`); imlFunction('polymorfaFindHook', 'body, auth, url, group, key', `const expected = iml.polymorfaHook(auth, group, key);\nconst types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};\n// Match shared sameCallback: an invalid URL on any hook is simply not a match.\nconst same = h => { try { return iml.polymorfaCallback(h.url) === iml.polymorfaCallback(url); } catch (error) { return false; } };`, `if (!Array.isArray(body.data) || body.page?.hasMore) throw new Error('Subscription inventory needs reconciliation.');\nif (body.data.some(h => !same(h) && h.headers?.some(x => x.name.toLowerCase() === expected.name.toLowerCase()))) throw new Error('Subscription key is already in use.');\nconst owns = h => h.projectId === auth.projectId && h.owner === 'project' && same(h) && h.format === 'native' && h.enabled && h.headers?.some(x => x.name.toLowerCase() === expected.name.toLowerCase()) && h.eventTypes?.length === types[group].length && types[group].every(t => h.eventTypes.includes(t));\nif (body.data.some(h => (same(h) || h.headers?.some(x => x.name.toLowerCase() === expected.name.toLowerCase())) && !owns(h))) throw new Error('Changed subscription needs reconciliation.');\nconst matches = body.data.filter(owns);\nif (matches.length > 1) throw new Error('Duplicate owned subscriptions need reconciliation.');\nreturn matches[0]?.id || null;`); imlFunction('polymorfaOwnedHook', 'body, projectId, ownedUrl, markerName, group', `const types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};\nconst same = (a, b) => { try { return iml.polymorfaCallback(a) === iml.polymorfaCallback(b); } catch (error) { return false; } };`, `const h = body.data;\nif (!h || h.owner !== 'project' || h.projectId !== projectId || !same(h.url, ownedUrl) || h.format !== 'native' || !h.headers?.some(x => x.name.toLowerCase() === markerName.toLowerCase()) || h.eventTypes?.length !== types[group]?.length || !types[group].every(t => h.eventTypes.includes(t))) throw new Error('Subscription ownership mismatch.');\nreturn true;`); // Detach reads the one recorded webhook by ID. 404 means it is already gone. @@ -81,7 +81,7 @@ emit('make/app.json', { name: 'polymorfa', label: 'Polymorfa', version: 1, theme const makeError = '{{polymorfaError(statusCode; headers; body)}}'; emit('make/base.json', { baseUrl: core.ORIGIN, headers: { Authorization: 'Bearer {{connection.apiKey}}', 'Polymorfa-Version': core.VERSION, 'User-Agent': 'polymorfa-make/0.1.0' }, log: { sanitize: ['request.headers.authorization', 'request.headers.Authorization', 'request.headers.idempotency-key', 'request.headers.Idempotency-Key', 'request.body.headers', 'response.body.data.secret', 'response.body.data.idempotency.key'] }, response: { error: { message: makeError, '409': { message: makeError }, '429': { type: 'RateLimitError', message: makeError } } } }); emit('make/connections/project/parameters.json', [{ name: 'apiKey', type: 'password', label: 'Project Token', required: true }, { name: 'projectId', type: 'text', label: 'Project ID', required: true }]); -emit('make/connections/project/communication.json', { url: '/platform/sessions', method: 'GET', qs: { projectId: '{{parameters.projectId}}' }, headers: { Authorization: 'Bearer {{parameters.apiKey}}', 'Polymorfa-Version': core.VERSION }, response: { valid: '{{statusCode = 200}}', metadata: { type: 'text', value: '{{parameters.projectId}}' } }, log: { sanitize: ['request.headers.authorization'] } }); +emit('make/connections/project/communication.json', { url: '/platform/connections', method: 'GET', qs: { projectId: '{{parameters.projectId}}' }, headers: { Authorization: 'Bearer {{parameters.apiKey}}', 'Polymorfa-Version': core.VERSION }, response: { valid: '{{statusCode = 200}}', metadata: { type: 'text', value: '{{parameters.projectId}}' } }, log: { sanitize: ['request.headers.authorization'] } }); for (const [key, action] of Object.entries(actions)) { emit(`make/modules/${key}/metadata.json`, { label: key === 'apiRequest' ? 'Make an API call' : action.label, description: key === 'apiRequest' ? 'Calls an allowlisted public operation on the Polymorfa API.' : action.description, connection: 'project', type: 'action' }); emit(`make/modules/${key}/parameters.json`, action.fields.map(name => { @@ -91,8 +91,8 @@ for (const [key, action] of Object.entries(actions)) { const r = `polymorfaRequest('${key}'; parameters; connection)`; const moduleError = `{{polymorfaError(statusCode; headers; body; get(${r}; 'method'))}}`; emit(`make/modules/${key}/communication.json`, { url: `{{get(${r}; 'url')}}`, method: `{{get(${r}; 'method')}}`, headers: `{{get(${r}; 'headers')}}`, qs: `{{get(${r}; 'query')}}`, body: `{{get(${r}; 'body')}}`, type: 'json', followRedirect: false, response: { valid: '{{polymorfaResult(statusCode; headers; body) != null}}', output: '{{polymorfaResult(statusCode; headers; body)}}', error: { message: moduleError, '409': { message: moduleError }, '429': { type: 'RateLimitError', message: moduleError } } }, log: { sanitize: ['request.headers.authorization', 'request.headers.idempotency-key'] } }); - const spec = key === 'listNumbers' ? specs.platform : specs.messaging; - const response = key === 'listNumbers' ? { type: 'object', properties: { data: { type: 'array', items: { $ref: '#/components/schemas/PlatformSession' } } } } : spec.components.schemas[key === 'listTemplates' ? 'ListProjectTemplatesResponse' : key === 'react' ? 'SendReactionResponse' : 'SendMessageResponse']; + const spec = key === 'listConnections' ? specs.platform : specs.messaging; + const response = key === 'listConnections' ? { type: 'object', properties: { data: { type: 'array', items: { $ref: '#/components/schemas/PlatformConnection' } } } } : spec.components.schemas[key === 'listTemplates' ? 'ListProjectTemplatesResponse' : key === 'react' ? 'SendReactionResponse' : 'SendMessageResponse']; emit(`make/modules/${key}/interface.json`, key === 'apiRequest' ? [{ name: 'data', label: 'Result', type: 'collection' }] : interfaceFields(response, spec)); } for (const [key, e] of Object.entries(events)) { diff --git a/scripts/verify-sdk.mjs b/scripts/verify-sdk.mjs index 68165b0..50d60f9 100644 --- a/scripts/verify-sdk.mjs +++ b/scripts/verify-sdk.mjs @@ -14,7 +14,7 @@ for (const kind of ['messaging', 'platform']) { ajv.addSchema(openApi3(await response.json()), kind); } const auth = { apiKey: 'synthetic-project-token', projectId: '11111111-1111-4111-8111-111111111111' }; -const input = { session: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'Synthetic', idempotencyKey: 'synthetic-write', writeCreatedAt: new Date().toISOString() }; +const input = { connection: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'Synthetic', idempotencyKey: 'synthetic-write', writeCreatedAt: new Date().toISOString() }; const cases = [['sendText', {}], ['sendTemplate', { templateName: 'order_ready', language: 'en', components: '[]' }], ['react', { messageId: '739182640518204', reaction: '' }], ...['image', 'video', 'file', 'voice'].flatMap(mediaType => ['url', 'base64'].map(mediaSource => ['sendMedia', { mediaType, mediaSource, media: mediaSource === 'url' ? 'https://example.com/media' : 'AAECAw==' }]))]; for (const [action, extra] of cases) { const request = buildRequest(action, { ...input, ...extra }, auth); diff --git a/shared/catalog.cjs b/shared/catalog.cjs index 378d8e7..d5113d8 100644 --- a/shared/catalog.cjs +++ b/shared/catalog.cjs @@ -1,16 +1,16 @@ 'use strict'; const actions = { - sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, - sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, - sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, - react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['session', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, - listNumbers: { label: 'List Numbers', description: 'Lists Numbers visible to the connected project.', operation: 'listPlatformSessions', fields: [] }, + sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, + sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, + sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, + react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['connection', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, + listConnections: { label: 'List Connections', description: 'Lists Connections visible to the connected project.', operation: 'listPlatformConnections', fields: [] }, listTemplates: { label: 'List Templates', description: 'Lists message templates for a project.', operation: 'listProjectTemplates', fields: ['projectSlug'] }, apiRequest: { label: 'Make an API Call', description: 'Performs an authorized call to a supported public Polymorfa operation.', operation: null, fields: ['method', 'path', 'requestBody', 'idempotencyKey', 'writeCreatedAt'] }, }; const fields = { - session: { label: 'Number', required: true, help: 'The exact Number identifier from Polymorfa. Keep it as a string.' }, + connection: { label: 'Connection', required: true, help: 'The exact Connection identifier from Polymorfa. Keep it as a string.' }, recipientType: { label: 'Recipient Type', required: true, options: { phoneNumber: 'Phone Number', id: 'Conversation ID', bsuid: 'Business-scoped User ID' }, default: 'phoneNumber' }, recipient: { label: 'Recipient', required: true, help: 'Use an international phone number including +, a conversation ID, or a business-scoped user ID.' }, text: { label: 'Text', required: true }, @@ -30,13 +30,13 @@ const fields = { writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, - path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/sessions. External hosts and credential operations are refused.' }, + path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, requestBody: { label: 'Request Body', json: true, default: '{}', help: 'JSON object. Authentication and version headers are supplied by the connection.' }, }; const events = { messageReceived: { label: 'New Message', description: 'Triggers when a message is received.', types: ['message.received'] }, messageState: { label: 'Message State Changed', description: 'Triggers when a message is sent, acknowledged, failed or updated.', types: ['message.sent', 'message.ack', 'message.failed', 'message.update'] }, - numberState: { label: 'Number State Changed', description: 'Triggers when a Number changes state, connects or logs out.', types: ['session.status', 'session.connected', 'session.logged_out'] }, + connectionState: { label: 'Connection State Changed', description: 'Triggers when a Connection changes state, connects or logs out.', types: ['connection.status', 'connection.connected', 'connection.logged_out'] }, callEnded: { label: 'Call Ended', description: 'Triggers when a call ends.', types: ['call.ended'] }, }; module.exports = { actions, fields, events }; diff --git a/shared/core.cjs b/shared/core.cjs index 5288dff..400c844 100644 --- a/shared/core.cjs +++ b/shared/core.cjs @@ -91,7 +91,7 @@ function advanced(p, auth) { const path = required(p.path, 'path'); if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; - const allowed = (method === 'GET' && (path === '/platform/sessions' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || + const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; @@ -99,12 +99,12 @@ function advanced(p, auth) { const keys = path.endsWith('/react') ? ['conversation', 'id', 'reaction'] : ['conversation', 'isForwarded', 'mentions', 'quotedMessage', 'content']; if (Object.keys(body).some(k => !keys.includes(k))) throw new IntegrationError('unsupported_request_field'); } - return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/sessions' ? { query: { projectId: auth.projectId } } : {}) }; + return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/connections' ? { query: { projectId: auth.projectId } } : {}) }; } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.session, 'number')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; - else if (action === 'listNumbers') r = { method: 'GET', url: ORIGIN + '/platform/sessions', query: { projectId: auth.projectId } }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); else throw new IntegrationError('unknown_action'); diff --git a/shared/hooks.cjs b/shared/hooks.cjs index 68538a6..aa53287 100644 --- a/shared/hooks.cjs +++ b/shared/hooks.cjs @@ -126,8 +126,8 @@ function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = return timingSafeEqual(Buffer.from(entries[0][1]), Buffer.from(expected.value)); } function envelope(body, group) { - if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.session !== 'string' || !body.session || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); + if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.connection !== 'string' || !body.connection || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); // Copy the defined envelope only. Never export arbitrary top-level transport fields. - return { id: body.id, session: body.session, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; + return { id: body.id, connection: body.connection, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; } module.exports = { identity, callback, sameCallback, creationKey, creation, owns, find, subscribe, activate, unsubscribe, authenticate, envelope }; diff --git a/tests/core.test.cjs b/tests/core.test.cjs index ca50d23..38188ef 100644 --- a/tests/core.test.cjs +++ b/tests/core.test.cjs @@ -10,7 +10,7 @@ const ajv = new Ajv({ strict: false, allErrors: true }); addFormats(ajv); ajv.addSchema(spec, 'messaging'); const now = Date.parse('2026-11-01T12:00:00Z'); const auth = { apiKey: 'synthetic-project-token-not-a-credential', projectId: '11111111-1111-4111-8111-111111111111' }; -const input = { session: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'An order is ready.', idempotencyKey: 'order-123-notification-1', writeCreatedAt: '2026-11-01T11:59:00Z' }; +const input = { connection: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'An order is ready.', idempotencyKey: 'order-123-notification-1', writeCreatedAt: '2026-11-01T11:59:00Z' }; test('valid base64 media through the decoded limit does not exhaust the regex stack', () => { for (const size of [core.MAX_MEDIA_BYTES - 2, core.MAX_MEDIA_BYTES - 1, core.MAX_MEDIA_BYTES]) { @@ -59,13 +59,13 @@ for (const created of [undefined, 'not a date', '2026-10-31T12:00:00Z', '2026-11 assert.throws(() => core.buildRequest('sendText', { ...input, writeCreatedAt: created }, auth, 'test', now)); }); for (const [method, path] of [ - ['POST', 'https://attacker.example/'], ['GET', '//attacker.example/'], ['GET', '/platform/sessions?projectId=other'], - ['GET', '/platform/../admin'], ['GET', '/platform/%2e%2e/credentials'], ['GET', '/platform\\sessions'], + ['POST', 'https://attacker.example/'], ['GET', '//attacker.example/'], ['GET', '/platform/connections?projectId=other'], + ['GET', '/platform/../admin'], ['GET', '/platform/%2e%2e/credentials'], ['GET', '/platform\\connections'], ['GET', '/platform/projects/project/credentials'], ['POST', '/platform/projects/project/webhooks'], ['POST', '/platform/functions/invoke'], ['DELETE', '/messaging/number/messages/send'], ]) test(`advanced request refuses ${method} ${path}`, () => assert.throws(() => core.buildRequest('apiRequest', { method, path, requestBody: '{}' }, auth, 'test', now))); -test('advanced allowed read scopes the Number list to the connected project', () => { - const r = core.buildRequest('apiRequest', { method: 'GET', path: '/platform/sessions' }, auth); +test('advanced allowed read scopes the Connection list to the connected project', () => { + const r = core.buildRequest('apiRequest', { method: 'GET', path: '/platform/connections' }, auth); assert.deepEqual(r.query, { projectId: auth.projectId }); }); test('advanced sends cannot add SDK-only transport fields to the public request', () => { @@ -102,8 +102,14 @@ test('a server error on a write keeps reconcile guidance even when the body carr for (const status of [500, 503]) { const transport = async () => ({ status, headers: { 'x-request-id': 'safe-request' }, body: { error: { code: 'internal_error', message: auth.apiKey } } }); await assert.rejects(core.execute('sendText', input, auth, transport, 'test', now), e => e.code === 'internal_error' && e.status === status && /Reconcile the original write before retrying\. Keep its key and start time\./.test(e.message) && !e.message.includes(auth.apiKey)); - await assert.rejects(core.execute('listNumbers', {}, auth, transport, 'test', now), e => e.code === 'internal_error' && !/Reconcile/.test(e.message)); + await assert.rejects(core.execute('listConnections', {}, auth, transport, 'test', now), e => e.code === 'internal_error' && !/Reconcile/.test(e.message)); } const inProgress = async () => ({ status: 409, headers: { 'retry-after': '5' }, body: { error: { code: 'idempotency_in_progress' } } }); await assert.rejects(core.execute('sendText', input, auth, inProgress, 'test', now), e => e.retryAfter === 5 && /Reconcile/.test(e.message) && /Wait at least 5 seconds/.test(e.message)); }); + +test('retired account inputs, actions and routes have no runtime aliases', () => { + assert.throws(() => core.buildRequest('sendText', { ...input, connection: undefined, session: input.connection }, auth, 'test', now), e => e.code === 'invalid_connection'); + assert.throws(() => core.buildRequest('listNumbers', {}, auth), e => e.code === 'unknown_action'); + assert.throws(() => core.buildRequest('apiRequest', { method: 'GET', path: '/platform/sessions' }, auth), e => e.code === 'unsupported_operation'); +}); diff --git a/tests/hooks.test.cjs b/tests/hooks.test.cjs index 686c36f..8ba645b 100644 --- a/tests/hooks.test.cjs +++ b/tests/hooks.test.cjs @@ -60,14 +60,14 @@ test('only the selected public envelope is emitted and event IDs remain stable', for (const [group, body] of Object.entries(samples)) { const event = hooks.envelope({ ...body, headers: { Authorization: 'must-not-escape' } }, group); assert.equal(event.id, body.id); assert.ok(!('headers' in event)); - assert.throws(() => hooks.envelope({ ...body, event: 'session.qr' }, group)); - assert.throws(() => hooks.envelope({ ...body, session: 739182640518203 }, group)); + assert.throws(() => hooks.envelope({ ...body, event: 'connection.qr' }, group)); + assert.throws(() => hooks.envelope({ ...body, connection: 739182640518203 }, group)); } }); test('editor samples match their public event schemas', () => { const ajv = new Ajv({ strict: false, allErrors: true }); addFormats(ajv); ajv.addSchema(require('../scripts/openapi-schema.cjs')(require('../contracts/openapi.messaging.json')), 'messaging'); - const names = { messageReceived: 'MessageReceivedEvent', messageState: 'MessageSentEvent', numberState: 'SessionStatusEvent', callEnded: 'CallEndedEvent' }; + const names = { messageReceived: 'MessageReceivedEvent', messageState: 'MessageSentEvent', connectionState: 'ConnectionStatusEvent', callEnded: 'CallEndedEvent' }; for (const [group, sample] of Object.entries(require('../fixtures/events.json'))) { const validate = ajv.compile({ $ref: `messaging#/components/schemas/${names[group]}` }); assert.ok(validate(sample), `${group}: ${JSON.stringify(validate.errors)}`); @@ -158,10 +158,10 @@ test('uncertain creation errors keep reconcile guidance even when the server sen }); test('public QuickLink reference survives the event projection without arbitrary transport data', () => { - const sample = require('../fixtures/events.json').numberState; - const projected = hooks.envelope({ ...sample, externalId: 'synthetic-order-reference', transportSecret: 'must-not-escape' }, 'numberState'); + const sample = require('../fixtures/events.json').connectionState; + const projected = hooks.envelope({ ...sample, externalId: 'synthetic-order-reference', transportSecret: 'must-not-escape' }, 'connectionState'); assert.equal(projected.externalId, 'synthetic-order-reference'); assert.ok(!('transportSecret' in projected)); - assert.ok(!('externalId' in hooks.envelope({ ...sample, externalId: { invalid: true } }, 'numberState'))); + assert.ok(!('externalId' in hooks.envelope({ ...sample, externalId: { invalid: true } }, 'connectionState'))); }); test('callback normalization preserves ownership across activation and cleanup', async () => { @@ -182,3 +182,12 @@ for (const status of [403, 422, 429]) test(`definite subscription rejection ${st }, 'test', NONCE), e => e.status === status && e.code === 'scope_denied' && e.retryAfter === 17 && e.requestId === 'safe-request'); assert.equal(reads, 1); }); + +test('current Connection event envelopes reject the retired account envelope without rewriting it', () => { + const sample = require('../fixtures/events.json').connectionState; + const { connection, ...rest } = sample; + const old = { ...rest, session: connection, event: 'session.status' }; + const before = JSON.stringify(old); + assert.throws(() => hooks.envelope(old, 'connectionState'), e => e.code === 'invalid_event'); + assert.equal(JSON.stringify(old), before); +}); diff --git a/tests/make.test.cjs b/tests/make.test.cjs index 9d2824c..04ab4fd 100644 --- a/tests/make.test.cjs +++ b/tests/make.test.cjs @@ -13,8 +13,8 @@ for (const file of readdirSync('make/functions')) { } const auth = { apiKey: 'synthetic-token', projectId: '11111111-1111-4111-8111-111111111111' }; test('Make function output matches the shared public request across text, media and advanced calls', () => { - const p = { session: '739182640518203', recipientType: 'id', recipient: '739182640518204', text: 'Synthetic', idempotencyKey: 'synthetic-write-1', writeCreatedAt: new Date().toISOString() }; - for (const [action, extra] of [['sendText', {}], ['sendMedia', { mediaType: 'file', mediaSource: 'base64', media: 'AAECAw==' }], ['sendMedia', { mediaType: 'image', mediaSource: 'url', media: 'https://example.com/synthetic.png' }], ['apiRequest', { method: 'GET', path: '/platform/sessions' }]]) { + const p = { connection: '739182640518203', recipientType: 'id', recipient: '739182640518204', text: 'Synthetic', idempotencyKey: 'synthetic-write-1', writeCreatedAt: new Date().toISOString() }; + for (const [action, extra] of [['sendText', {}], ['sendMedia', { mediaType: 'file', mediaSource: 'base64', media: 'AAECAw==' }], ['sendMedia', { mediaType: 'image', mediaSource: 'url', media: 'https://example.com/synthetic.png' }], ['apiRequest', { method: 'GET', path: '/platform/connections' }]]) { const expected = core.buildRequest(action, { ...p, ...extra }, auth, 'make'); const actual = iml.polymorfaRequest(action, { ...p, ...extra }, auth); assert.deepEqual(JSON.parse(JSON.stringify(actual)), expected); @@ -54,15 +54,15 @@ test('Make activation keys are independent of receiver secrets and change betwee }); test('Make verifies live creation receipts and maps the optional public QuickLink reference', () => { - const marker = iml.polymorfaHook(auth, 'numberState', 'key'); - const row = { id: 'owned', projectId: auth.projectId, owner: 'project', url: 'https://example.com/', enabled: true, format: 'native', headers: [{ name: marker.name }], eventTypes: ['session.status', 'session.connected', 'session.logged_out'] }; - const args = [auth, row.url, 'numberState', 'key', 'owned']; + const marker = iml.polymorfaHook(auth, 'connectionState', 'key'); + const row = { id: 'owned', projectId: auth.projectId, owner: 'project', url: 'https://example.com/', enabled: true, format: 'native', headers: [{ name: marker.name }], eventTypes: ['connection.status', 'connection.connected', 'connection.logged_out'] }; + const args = [auth, row.url, 'connectionState', 'key', 'owned']; assert.equal(iml.polymorfaLiveHook({ data: [row], page: { hasMore: false } }, ...args), 'owned'); assert.throws(() => iml.polymorfaLiveHook({ data: [], page: { hasMore: false } }, ...args)); assert.throws(() => iml.polymorfaLiveHook({ data: [{ ...row, id: 'different' }], page: { hasMore: false } }, ...args)); - const sample = { ...require('../fixtures/events.json').numberState, externalId: 'synthetic-order-reference', transportSecret: 'must-not-escape' }; - assert.deepEqual(JSON.parse(JSON.stringify(iml.polymorfaEnvelope(sample, 'numberState'))), hooks.envelope(sample, 'numberState')); - const attach = JSON.parse(readFileSync('make/webhooks/numberState/attach.json')); + const sample = { ...require('../fixtures/events.json').connectionState, externalId: 'synthetic-order-reference', transportSecret: 'must-not-escape' }; + assert.deepEqual(JSON.parse(JSON.stringify(iml.polymorfaEnvelope(sample, 'connectionState'))), hooks.envelope(sample, 'connectionState')); + const attach = JSON.parse(readFileSync('make/webhooks/connectionState/attach.json')); assert.ok(attach[0].response.temp.nonce.includes('polymorfaCreationNonce(webhook.url)')); assert.ok(attach[1].headers['Idempotency-Key'].includes('temp.nonce')); assert.ok(!JSON.stringify(attach).includes('registrationKey')); diff --git a/tests/native.test.cjs b/tests/native.test.cjs index 2585b03..a9289b0 100644 --- a/tests/native.test.cjs +++ b/tests/native.test.cjs @@ -6,7 +6,7 @@ const zapier = require('../zapier'); const hooks = require('../shared/hooks.cjs'); const fake = require('./fake-webhooks.cjs'); const auth = { apiKey: 'synthetic-project-token', projectId: '11111111-1111-4111-8111-111111111111' }; -const input = { operation: 'sendText', session: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'Synthetic', idempotencyKey: 'synthetic-write-1', writeCreatedAt: new Date().toISOString() }; +const input = { operation: 'sendText', connection: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'Synthetic', idempotencyKey: 'synthetic-write-1', writeCreatedAt: new Date().toISOString() }; test('compiled n8n node uses native request helpers, preserved input pairing and disabled redirects', async () => { const calls = []; const context = { @@ -80,7 +80,7 @@ test('Zapier routes real throttling middleware through shared parsing and its na const response = request => ({ request, status: 429, headers: new Headers({ 'Retry-After': '12' }), content: '{"error":{"code":"rate_limited"}}' }); assert.throws(() => middleware(response({})), e => e.name === 'ThrottledError'); const z = { errors, request: async request => middleware(response(request)) }; - for (const [action, inputData] of [['sendText', input], ['listNumbers', {}]]) { + for (const [action, inputData] of [['sendText', input], ['listConnections', {}]]) { await assert.rejects(zapier.creates[action].operation.perform(z, { authData: auth, inputData }), e => e.name === 'ThrottledError' && JSON.parse(e.message).delay === 12 && JSON.parse(e.message).message.includes('rate_limited')); } }); diff --git a/tests/pipedream.test.mjs b/tests/pipedream.test.mjs index aa2a033..574f8d6 100644 --- a/tests/pipedream.test.mjs +++ b/tests/pipedream.test.mjs @@ -4,7 +4,7 @@ import source from '../pipedream/sources/messageReceived/messageReceived.mjs'; import hooks from '../shared/hooks.cjs'; import { readFileSync } from 'node:fs'; test('Pipedream action passes exact fields to the app request boundary', async () => { - const input = { session: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'Synthetic', quotedMessageId: undefined, idempotencyKey: 'write-1', writeCreatedAt: '2026-11-01T12:00:00Z' }; + const input = { connection: '739182640518203', recipientType: 'id', recipient: '9007199254740993123', text: 'Synthetic', quotedMessageId: undefined, idempotencyKey: 'write-1', writeCreatedAt: '2026-11-01T12:00:00Z' }; let call; const result = await action.run.call({ ...input, polymorfa: { execute: async ($, key, values) => { call = { key, values }; return { data: { id: '739182640518204' } }; } } }, { $: {} }); assert.deepEqual(call, { key: 'sendText', values: input }); assert.equal(result.data.id, '739182640518204'); @@ -52,3 +52,11 @@ test('Pipedream sources expose no webhook creation key prop', async () => { assert.deepEqual(Object.keys(component.props).sort(), ['db', 'http', 'polymorfa', 'subscriptionKey']); } }); + +test('the native app exposes the Connection prop with no retired account prop', () => { + assert.equal(app.propDefinitions.connection.type, 'string'); + assert.equal(app.propDefinitions.connection.label, 'Connection'); + assert.equal(app.propDefinitions.session, undefined); + assert.equal(action.props.connection.label, 'Connection'); + assert.equal(action.props.session, undefined); +}); diff --git a/tests/recipes.test.cjs b/tests/recipes.test.cjs index cb6f8d0..3e520f4 100644 --- a/tests/recipes.test.cjs +++ b/tests/recipes.test.cjs @@ -33,3 +33,24 @@ test('inbound handoff trigger parameters satisfy the node description and activa await methods.create.call(context); assert.equal(s.rows.length, 1); assert.equal(staticData.subscription.subscriptionKey, params.subscriptionKey); }); + +test('the imported order recipe uses supported action fields and sends its stable Connection selector', async () => { + const { Polymorfa } = require('../n8n/dist/nodes/Polymorfa/Polymorfa.node.js'); + const send = recipe.nodes.find(n => n.type === 'n8n-nodes-polymorfa.polymorfa'); + const description = new Polymorfa().description; + const names = description.properties.map(p => p.name); + for (const name of Object.keys(send.parameters)) assert.ok(names.includes(name), `unknown action parameter ${name}`); + const order = { connectionId: 'stable-session-id', notificationId: 'saved-order-1', notificationStartedAt: new Date().toISOString(), recipient: '+14155550123', notificationText: 'Synthetic order update' }; + const validate = recipe.nodes.find(n => n.id === 'validate-order'); + const [validated] = vm.runInNewContext(`(function () { ${validate.parameters.jsCode} })()`, { $input: { all: () => [{ json: order }] } }); + const evaluate = value => typeof value === 'string' && value.startsWith('={{') ? vm.runInNewContext(value.slice(3, -2), { $json: validated.json }) : value; + const params = Object.fromEntries(Object.entries(send.parameters).map(([k, v]) => [k, evaluate(v)])); + const calls = []; + const context = { getCredentials: async () => fake.auth, getInputData: () => [validated], getNodeParameter: (k, i, fallback) => params[k] ?? fallback, getNode: () => ({ name: send.name }), helpers: { httpRequest: async request => { calls.push(request); return { statusCode: 200, body: { success: true, data: { id: '739182640518204' } }, headers: {} }; } } }; + await new Polymorfa().execute.call(context); + assert.equal(calls.length, 1); + assert.equal(new URL(calls[0].url).pathname, '/messaging/stable-session-id/messages/send'); + assert.equal(calls[0].headers['Idempotency-Key'], params.idempotencyKey); + assert.deepEqual(calls[0].body.conversation, { phoneNumber: order.recipient }); + assert.equal(params.writeCreatedAt, order.notificationStartedAt); +}); diff --git a/zapier/README.md b/zapier/README.md index ea6b925..99f98e4 100644 --- a/zapier/README.md +++ b/zapier/README.md @@ -4,7 +4,7 @@ The native integration source passes local schema validation. No Zapier app has been registered, uploaded, promoted or listed by this repository. Use a restricted project token and its project UUID. Connection testing requires -`sessions:read`. Sends/reactions require `messages:write`, template lookup +`connections:read`. Sends/reactions require `messages:write`, template lookup `templates:read`, and REST Hook lifecycle `webhooks:read` plus `webhooks:manage`. Actions preserve the public Polymorfa response envelope. A 202 response is an @@ -36,4 +36,4 @@ Record the approved Beta/Public status and actual directory URL. Do not submit a duplicate app or promote a version merely because local validation passes. Zapier has its own execution, retention and billing. Its processing location is -separate from the Polymorfa region selected for a Number. +separate from the Polymorfa region selected for a Connection. diff --git a/zapier/index.js b/zapier/index.js index 10c9ce0..b1d6fad 100644 --- a/zapier/index.js +++ b/zapier/index.js @@ -65,7 +65,7 @@ const triggers = Object.fromEntries(Object.entries(events).map(([key, event]) => }, async performList() { return [require('./shared/samples.json')[key]]; }, sample: require('./shared/samples.json')[key], - outputFields: [{ key: 'id', type: 'string' }, { key: 'session', type: 'string' }, { key: 'externalId', type: 'string' }, { key: 'timestamp', type: 'datetime' }, { key: 'event', type: 'string' }], + outputFields: [{ key: 'id', type: 'string' }, { key: 'connection', type: 'string' }, { key: 'externalId', type: 'string' }, { key: 'timestamp', type: 'datetime' }, { key: 'event', type: 'string' }], }, }])); module.exports = { @@ -73,10 +73,10 @@ module.exports = { authentication: { type: 'custom', connectionLabel: '{{projectId}}', fields: [ - { key: 'apiKey', label: 'Project Token', type: 'password', required: true, helpText: 'A restricted project token. Connection testing requires sessions:read.' }, + { key: 'apiKey', label: 'Project Token', type: 'password', required: true, helpText: 'A restricted project token. Connection testing requires connections:read.' }, { key: 'projectId', label: 'Project ID', type: 'string', required: true }, ], - async test(z, bundle) { await withThrottling(z, () => core.execute('listNumbers', {}, bundle.authData, transport(z), 'zapier')); return { projectId: bundle.authData.projectId }; }, + async test(z, bundle) { await withThrottling(z, () => core.execute('listConnections', {}, bundle.authData, transport(z), 'zapier')); return { projectId: bundle.authData.projectId }; }, }, creates, triggers, }; diff --git a/zapier/shared/catalog.cjs b/zapier/shared/catalog.cjs index eb14536..e8d0221 100644 --- a/zapier/shared/catalog.cjs +++ b/zapier/shared/catalog.cjs @@ -2,16 +2,16 @@ 'use strict'; const actions = { - sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, - sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, - sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['session', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, - react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['session', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, - listNumbers: { label: 'List Numbers', description: 'Lists Numbers visible to the connected project.', operation: 'listPlatformSessions', fields: [] }, + sendText: { label: 'Send Text', description: 'Sends a text message or replies to a message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'text', 'quotedMessageId', 'idempotencyKey', 'writeCreatedAt'] }, + sendTemplate: { label: 'Send Template', description: 'Sends a template with its approved name and language.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'templateName', 'language', 'components', 'idempotencyKey', 'writeCreatedAt'] }, + sendMedia: { label: 'Send Media', description: 'Sends an image, video, file or voice message.', operation: 'sendMessage', fields: ['connection', 'recipientType', 'recipient', 'mediaType', 'mediaSource', 'media', 'mimeType', 'caption', 'filename', 'idempotencyKey', 'writeCreatedAt'] }, + react: { label: 'React to Message', description: 'Adds or removes a reaction on a message.', operation: 'sendReaction', fields: ['connection', 'recipientType', 'recipient', 'messageId', 'reaction', 'idempotencyKey', 'writeCreatedAt'] }, + listConnections: { label: 'List Connections', description: 'Lists Connections visible to the connected project.', operation: 'listPlatformConnections', fields: [] }, listTemplates: { label: 'List Templates', description: 'Lists message templates for a project.', operation: 'listProjectTemplates', fields: ['projectSlug'] }, apiRequest: { label: 'Make an API Call', description: 'Performs an authorized call to a supported public Polymorfa operation.', operation: null, fields: ['method', 'path', 'requestBody', 'idempotencyKey', 'writeCreatedAt'] }, }; const fields = { - session: { label: 'Number', required: true, help: 'The exact Number identifier from Polymorfa. Keep it as a string.' }, + connection: { label: 'Connection', required: true, help: 'The exact Connection identifier from Polymorfa. Keep it as a string.' }, recipientType: { label: 'Recipient Type', required: true, options: { phoneNumber: 'Phone Number', id: 'Conversation ID', bsuid: 'Business-scoped User ID' }, default: 'phoneNumber' }, recipient: { label: 'Recipient', required: true, help: 'Use an international phone number including +, a conversation ID, or a business-scoped user ID.' }, text: { label: 'Text', required: true }, @@ -31,13 +31,13 @@ const fields = { writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, - path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/sessions. External hosts and credential operations are refused.' }, + path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, requestBody: { label: 'Request Body', json: true, default: '{}', help: 'JSON object. Authentication and version headers are supplied by the connection.' }, }; const events = { messageReceived: { label: 'New Message', description: 'Triggers when a message is received.', types: ['message.received'] }, messageState: { label: 'Message State Changed', description: 'Triggers when a message is sent, acknowledged, failed or updated.', types: ['message.sent', 'message.ack', 'message.failed', 'message.update'] }, - numberState: { label: 'Number State Changed', description: 'Triggers when a Number changes state, connects or logs out.', types: ['session.status', 'session.connected', 'session.logged_out'] }, + connectionState: { label: 'Connection State Changed', description: 'Triggers when a Connection changes state, connects or logs out.', types: ['connection.status', 'connection.connected', 'connection.logged_out'] }, callEnded: { label: 'Call Ended', description: 'Triggers when a call ends.', types: ['call.ended'] }, }; module.exports = { actions, fields, events }; diff --git a/zapier/shared/core.cjs b/zapier/shared/core.cjs index 3d7596b..c2302db 100644 --- a/zapier/shared/core.cjs +++ b/zapier/shared/core.cjs @@ -92,7 +92,7 @@ function advanced(p, auth) { const path = required(p.path, 'path'); if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; - const allowed = (method === 'GET' && (path === '/platform/sessions' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || + const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; @@ -100,12 +100,12 @@ function advanced(p, auth) { const keys = path.endsWith('/react') ? ['conversation', 'id', 'reaction'] : ['conversation', 'isForwarded', 'mentions', 'quotedMessage', 'content']; if (Object.keys(body).some(k => !keys.includes(k))) throw new IntegrationError('unsupported_request_field'); } - return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/sessions' ? { query: { projectId: auth.projectId } } : {}) }; + return { method, url: ORIGIN + path, ...(body ? { body } : {}), ...(path === '/platform/connections' ? { query: { projectId: auth.projectId } } : {}) }; } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.session, 'number')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; - else if (action === 'listNumbers') r = { method: 'GET', url: ORIGIN + '/platform/sessions', query: { projectId: auth.projectId } }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); else throw new IntegrationError('unknown_action'); diff --git a/zapier/shared/hooks.cjs b/zapier/shared/hooks.cjs index 8b518a7..4818f39 100644 --- a/zapier/shared/hooks.cjs +++ b/zapier/shared/hooks.cjs @@ -127,8 +127,8 @@ function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = return timingSafeEqual(Buffer.from(entries[0][1]), Buffer.from(expected.value)); } function envelope(body, group) { - if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.session !== 'string' || !body.session || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); + if (!events[group] || !body || typeof body !== 'object' || Array.isArray(body) || typeof body.id !== 'string' || !body.id || typeof body.connection !== 'string' || !body.connection || typeof body.timestamp !== 'string' || !Number.isFinite(Date.parse(body.timestamp)) || !events[group].types.includes(body.event) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) throw new IntegrationError('invalid_event'); // Copy the defined envelope only. Never export arbitrary top-level transport fields. - return { id: body.id, session: body.session, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; + return { id: body.id, connection: body.connection, ...(typeof body.externalId === 'string' ? { externalId: body.externalId } : {}), timestamp: body.timestamp, event: body.event, payload: body.payload }; } module.exports = { identity, callback, sameCallback, creationKey, creation, owns, find, subscribe, activate, unsubscribe, authenticate, envelope }; diff --git a/zapier/shared/samples.json b/zapier/shared/samples.json index a5b25e2..3232e33 100644 --- a/zapier/shared/samples.json +++ b/zapier/shared/samples.json @@ -1,7 +1,7 @@ { "messageReceived": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a71", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.received", "payload": { @@ -22,7 +22,7 @@ }, "messageState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a72", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "message.sent", "payload": { @@ -37,18 +37,18 @@ "timestamp": 1793534400 } }, - "numberState": { + "connectionState": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a73", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", - "event": "session.status", + "event": "connection.status", "payload": { "status": "connected" } }, "callEnded": { "id": "0190f2a4-6c1e-7b9d-9f3a-2e8c4d5b6a74", - "session": "739182640518203", + "connection": "739182640518203", "timestamp": "2026-11-01T12:00:00.000Z", "event": "call.ended", "payload": { From 7a6277154154a7947c349841a539ec8d8abe31bd Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Mon, 16 Nov 2026 06:02:46 +0200 Subject: [PATCH 2/9] Bind public integrations to final Connection SDK source --- contracts/sdk-baseline.json | 2 +- contracts/source.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index dff94e1..a0860d3 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,5 +1,5 @@ { - "source": "fe83375c38218dc15dc76a5ab7ebf82da94f12cf", + "source": "ef2a629d74e46648cdd613b8126ab63f8e5ee15d", "note": "Fingerprints of reviewed SDK fragments for this public Connection source candidate. No additional operation or publication is implied.", "fragments": { "messaging": { diff --git a/contracts/source.json b/contracts/source.json index 6e3ef4b..fa694b2 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -3,7 +3,7 @@ "apiSource": "8354399b827d9127210b9759cd055586e967449e", "sdk": { "repository": "polymorfa/sdks", - "source": "fe83375c38218dc15dc76a5ab7ebf82da94f12cf", + "source": "ef2a629d74e46648cdd613b8126ab63f8e5ee15d", "publishedPackage": null }, "specs": { From 67124bf2cfef51a39f1b0d2a831b0901601b4323 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 07:25:46 +0200 Subject: [PATCH 3/9] fix: bind public Connection adapters and preserve bounded recovery --- README.md | 12 + contracts/openapi.messaging.json | 17 + contracts/openapi.platform.json | 12 + contracts/sdk-baseline.json | 8 +- contracts/source.json | 10 +- make/functions/polymorfaAdvanced.js | 2 +- make/functions/polymorfaRequest.js | 8 +- make/modules/apiRequest/parameters.json | 2 +- make/modules/callEnded/interface.json | 112 --- make/modules/connectionState/interface.json | 112 --- make/modules/messageReceived/interface.json | 260 +++--- make/modules/messageState/interface.json | 112 --- make/modules/react/parameters.json | 2 +- make/modules/sendMedia/interface.json | 745 +++++++++++++++++- make/modules/sendMedia/parameters.json | 2 +- make/modules/sendTemplate/interface.json | 745 +++++++++++++++++- make/modules/sendTemplate/parameters.json | 2 +- make/modules/sendText/interface.json | 745 +++++++++++++++++- make/modules/sendText/parameters.json | 2 +- n8n/shared/catalog.js | 2 +- n8n/shared/core.js | 12 +- n8n/shared/hooks.js | 26 +- pipedream/actions/apiRequest/apiRequest.mjs | 2 +- pipedream/actions/react/react.mjs | 2 +- pipedream/actions/sendMedia/sendMedia.mjs | 2 +- .../actions/sendTemplate/sendTemplate.mjs | 2 +- pipedream/actions/sendText/sendText.mjs | 2 +- pipedream/common/catalog.cjs | 2 +- pipedream/common/core.cjs | 12 +- pipedream/common/hooks.cjs | 26 +- pipedream/sources/callEnded/callEnded.mjs | 2 + .../connectionState/connectionState.mjs | 2 + .../messageReceived/messageReceived.mjs | 2 + .../sources/messageState/messageState.mjs | 2 + scripts/check-contracts.mjs | 11 + scripts/generate.mjs | 20 +- scripts/sync-api-contracts.mjs | 64 ++ shared/catalog.cjs | 2 +- shared/core.cjs | 12 +- shared/hooks.cjs | 26 +- .../connection-migration-regressions.test.cjs | 82 ++ tests/hooks.test.cjs | 6 +- tests/public-projection.test.mjs | 16 + zapier/shared/catalog.cjs | 2 +- zapier/shared/core.cjs | 12 +- zapier/shared/hooks.cjs | 26 +- 46 files changed, 2713 insertions(+), 574 deletions(-) create mode 100644 scripts/sync-api-contracts.mjs create mode 100644 tests/connection-migration-regressions.test.cjs create mode 100644 tests/public-projection.test.mjs diff --git a/README.md b/README.md index fe37370..8473ffe 100644 --- a/README.md +++ b/README.md @@ -37,3 +37,15 @@ record the remaining native acceptance and publication work. License: MIT. Newly authored connector code only; no archived Titan adapter code is included. + + +Connection names use the public 1-to-64-character selector format, including +names such as `sales.eu`. Messaging retries stop at 55 minutes, before the API's +one-hour receipt expires. Preserve the original write key and start time when +reconciling an uncertain result. + +Trigger cleanup may remove an exactly owned pre-rename webhook. It does not +register or emit retired event names. An unresolved activation keeps its nonce +and start time; a changed target or expired receipt needs reconciliation before +another creation. These source changes do not establish provider publication or +installed-platform acceptance. diff --git a/contracts/openapi.messaging.json b/contracts/openapi.messaging.json index fc07dac..f5fab5c 100644 --- a/contracts/openapi.messaging.json +++ b/contracts/openapi.messaging.json @@ -9,6 +9,16 @@ "url": "https://docs.polymorfa.com" } }, + "servers": [ + { + "url": "https://api.polymorfa.com" + } + ], + "security": [ + { + "BearerAuth": [] + } + ], "paths": { "/messaging/{connection}/messages/send": { "post": { @@ -5968,6 +5978,13 @@ "additionalProperties": false } }, + "securitySchemes": { + "BearerAuth": { + "type": "http", + "scheme": "bearer", + "description": "Polymorfa team key (pmfa_ prefix), project token (pmfa_pt_ prefix) where supported, or short-lived client token (pmfa_ct_ prefix). Team keys and project tokens may be personal or service-account owned and enforce selected action scopes. Team keys cover the team and its projects; project tokens stay inside one project. Client tokens stay inside their live project and connection and enforce their client rules and immutable mint-time action ceiling. Treat all credentials as opaque strings. Never parse them or assume a fixed length; store at least 512 characters. Server keys use issuance-record lookup; short-lived client tokens carry a signed permission ceiling." + } + }, "headers": { "X-RateLimit-Limit": { "description": "Team request quota per rolling minute, when the per-team request limiter applies.", diff --git a/contracts/openapi.platform.json b/contracts/openapi.platform.json index 2da0f20..76b52c5 100644 --- a/contracts/openapi.platform.json +++ b/contracts/openapi.platform.json @@ -5,6 +5,11 @@ "version": "1.0.0", "description": "Manage your team, projects, connections, and webhooks.\n\nAuthenticate with a team API key or a project token with the permissions required by the method." }, + "servers": [ + { + "url": "https://api.polymorfa.com" + } + ], "paths": { "/platform/connections": { "get": { @@ -1197,6 +1202,13 @@ ] } }, + "securitySchemes": { + "ApiKeyAuth": { + "type": "http", + "scheme": "bearer", + "description": "Send your team API key or project token as `Authorization: Bearer `. Treat credentials as opaque strings. Never parse them or assume a fixed length; store at least 512 characters. Permissions and ownership come from the live issuance record. Project tokens can access only their own project." + } + }, "responses": { "BadRequest": { "description": "A path, query, or request-body value did not pass validation.", diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index a0860d3..cb3d547 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,6 +1,6 @@ { - "source": "ef2a629d74e46648cdd613b8126ab63f8e5ee15d", - "note": "Fingerprints of reviewed SDK fragments for this public Connection source candidate. No additional operation or publication is implied.", + "source": "fea8a591514b18a386d66347b71baff88d8604ba", + "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", "fragments": { "messaging": { "POST /messaging/{connection}/messages/send": "2df7ed3a7ddfe696eee235901701f4992531820135486f34063e736d1c22c928", @@ -48,16 +48,16 @@ "GET /platform/projects/{projectId}/webhooks": "a2c9288bb21cf3fdad6b5fb3aa0471d6075805deeca87f9c67a52593ad387c8f", "#/components/schemas/ProjectWebhook": "447a7260884850ee6c8c327635710cb4dd19188e019408c3b8d1e353afda2848", "#/components/schemas/WebhookRetryPolicy": "a953fbcee54bed638f93e85b00670d4563f4ff8d17b80d456c831e2a7b0dd9f5", + "#/components/schemas/WebhookBatching": "d3be6ee4c2b556f31ffa1974ceff744d90df01baca29344e6cb281aeb6b9ff80", "#/components/schemas/WebhookHeaderMetadata": "f03e715b0afdde824ab991f4a664cddfaed3586081926e0fca7b5d6c1440a366", "#/components/schemas/WebhookSigningSecretMetadata": "0fed4dc6a07f2066215081784225210e7c0025c864fddfdc77eeca232d1b40b5", - "#/components/schemas/WebhookBatching": "d3be6ee4c2b556f31ffa1974ceff744d90df01baca29344e6cb281aeb6b9ff80", "#/components/schemas/CursorPageMetadata": "a491dc0e4a93fd2ce4925bade45affaf3bcc840f905251a5b9c643f4b64e35da", "#/components/responses/NotFound": "7091da86cd9fffdf72d2c07f0f758177d72202a2a1aee8cd1672e983d1db274e", "POST /platform/projects/{projectId}/webhooks": "1b9a4bc78ae0f3b985c7bd683375354d25c4bf53e252a6c4e3fb8951d24086b7", "#/components/schemas/CreateProjectWebhookInput": "8fc3291ddf5e7c17c231ccd9d40d564fd2c724eb6c0e259be05bd5dc486f8880", "#/components/schemas/WebhookRetryPolicyInput": "a953fbcee54bed638f93e85b00670d4563f4ff8d17b80d456c831e2a7b0dd9f5", - "#/components/schemas/WebhookHeaderInput": "9439ff800367858e22668035c1e432e1023d52fc39d65cfdc83a17068c989a51", "#/components/schemas/WebhookBatchingInput": "29143d6b029716cb24416ad08db6ec11dc0ad865e4dea44530fe0a283dc5bab3", + "#/components/schemas/WebhookHeaderInput": "9439ff800367858e22668035c1e432e1023d52fc39d65cfdc83a17068c989a51", "#/components/schemas/ProjectWebhookCreationReceipt": "8fa37c1b86463fb4e451e456ac2b4d0afda26c8648407b937ed7ef22dc1d8147", "#/components/schemas/IdempotencyReceipt": "20651991bf1da3fa2a4662f6672727d81896a0d3d931f1a30eeb926c8326a1c9", "#/components/responses/Conflict": "4ed94d3b833bb541ca39006152425c39e815fb1e374ca3d2a1b080e828ce9601", diff --git a/contracts/source.json b/contracts/source.json index fa694b2..c5a672e 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,9 +1,9 @@ { "apiVersion": "2026-09-22", - "apiSource": "8354399b827d9127210b9759cd055586e967449e", + "apiSource": "a7cab53684b989b1ce68882989d31e2277841bdc", "sdk": { "repository": "polymorfa/sdks", - "source": "ef2a629d74e46648cdd613b8126ab63f8e5ee15d", + "source": "fea8a591514b18a386d66347b71baff88d8604ba", "publishedPackage": null }, "specs": { @@ -11,14 +11,14 @@ "publicSourcePath": "docs/api-reference/openapi.json", "publicSourceSha256": "9e6a9520b5f64eff9b6b23621ce6e7f7e667b44e45e8a7f56c7e1e94f0d271e8", "snapshot": "contracts/openapi.messaging.json", - "sha256": "5fc4b8f5af37c7694fe307d1d3a5b05a5ad82109a14892cb5b685bbd41bd58d5", + "sha256": "a35f83031cc710168bcb3252bc5c8d8098801792b0e2eea9aa7661c8b704fdbc", "sdkSnapshotPath": "contracts/openapi.messaging.json" }, "platform": { "publicSourcePath": "docs/api-reference/openapi.management.json", - "publicSourceSha256": "613eb7aa47c29cda851fccec8b05aa07c9e637ed3ff2b57a920e7ea40e4db6a1", + "publicSourceSha256": "9cc6160102b2c968c9a5b7b47a7cd7376fdf4189ff3be690d0ae279bf3ade7cf", "snapshot": "contracts/openapi.platform.json", - "sha256": "ec4bcfb5e37c68015c30b086316585b539a7504912487599cc166fa3b2f99b3c", + "sha256": "dc06edaae904e0a9e44cb2fcdefaf1954c719983f85061b6881f25d9aa183097", "sdkSnapshotPath": "contracts/openapi.platform.json" } }, diff --git a/make/functions/polymorfaAdvanced.js b/make/functions/polymorfaAdvanced.js index 06df9c8..e0249d2 100644 --- a/make/functions/polymorfaAdvanced.js +++ b/make/functions/polymorfaAdvanced.js @@ -26,7 +26,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { diff --git a/make/functions/polymorfaRequest.js b/make/functions/polymorfaRequest.js index 3bad655..0e0ae60 100644 --- a/make/functions/polymorfaRequest.js +++ b/make/functions/polymorfaRequest.js @@ -10,7 +10,7 @@ class IntegrationError extends Error { this.requestId = requestId; this.retryAfter = retryAfter; } } -const ORIGIN = 'https://api.polymorfa.com', VERSION = '2026-09-22', MAX_WRITE_AGE = 82800000; +const ORIGIN = 'https://api.polymorfa.com', VERSION = '2026-09-22', MAX_WRITE_AGE = 3300000; function required(value, name) { if (typeof value !== 'string' || !value.trim()) throw new IntegrationError(`invalid_${name}`); return value; @@ -20,6 +20,10 @@ function segment(value, name) { if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new IntegrationError(`invalid_${name}`); return value; } +function connectionSegment(value) { + if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + return encodeURIComponent(value); +} function headers(auth, provider) { const token = required(auth.apiKey, 'project_token'); if (/[\r\n]/.test(token)) throw new IntegrationError('invalid_project_token'); @@ -35,7 +39,7 @@ function writeHeaders(p, now = Date.now()) { } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: iml.polymorfaBody(action, p) }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${connectionSegment(p.connection)}/messages/${action === 'react' ? 'react' : 'send'}`, body: iml.polymorfaBody(action, p) }; else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = iml.polymorfaAdvanced(p, auth); diff --git a/make/modules/apiRequest/parameters.json b/make/modules/apiRequest/parameters.json index 56f8c4b..752b1c4 100644 --- a/make/modules/apiRequest/parameters.json +++ b/make/modules/apiRequest/parameters.json @@ -43,6 +43,6 @@ "type": "text", "label": "Write Started At", "required": false, - "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } ] diff --git a/make/modules/callEnded/interface.json b/make/modules/callEnded/interface.json index b03a13c..c823f3b 100644 --- a/make/modules/callEnded/interface.json +++ b/make/modules/callEnded/interface.json @@ -92,117 +92,5 @@ "type": "text" } ] - }, - { - "name": "delivery", - "label": "delivery", - "type": "text" - }, - { - "name": "eventId", - "label": "eventId", - "type": "text" - }, - { - "name": "source", - "label": "source", - "type": "text" - }, - { - "name": "overrides", - "label": "overrides", - "type": "collection", - "spec": [ - { - "name": "text", - "label": "text", - "type": "text" - }, - { - "name": "from", - "label": "from", - "type": "text" - }, - { - "name": "pushName", - "label": "pushName", - "type": "text" - }, - { - "name": "mediaType", - "label": "mediaType", - "type": "text" - }, - { - "name": "caption", - "label": "caption", - "type": "text" - }, - { - "name": "ackStatus", - "label": "ackStatus", - "type": "text" - }, - { - "name": "messageId", - "label": "messageId", - "type": "text" - }, - { - "name": "failureReason", - "label": "failureReason", - "type": "text" - }, - { - "name": "video", - "label": "video", - "type": "boolean" - }, - { - "name": "durationSeconds", - "label": "durationSeconds", - "type": "number" - }, - { - "name": "callEndReason", - "label": "callEndReason", - "type": "text" - }, - { - "name": "restrictionActive", - "label": "restrictionActive", - "type": "boolean" - }, - { - "name": "status", - "label": "status", - "type": "text" - }, - { - "name": "statusReason", - "label": "statusReason", - "type": "text" - }, - { - "name": "templateName", - "label": "templateName", - "type": "text" - }, - { - "name": "templateStatus", - "label": "templateStatus", - "type": "text" - }, - { - "name": "reason", - "label": "reason", - "type": "text" - } - ] - }, - { - "name": "fromConnection", - "label": "fromConnection", - "type": "text" } ] diff --git a/make/modules/connectionState/interface.json b/make/modules/connectionState/interface.json index b659b46..8c60305 100644 --- a/make/modules/connectionState/interface.json +++ b/make/modules/connectionState/interface.json @@ -120,117 +120,5 @@ "type": "number" } ] - }, - { - "name": "delivery", - "label": "delivery", - "type": "text" - }, - { - "name": "eventId", - "label": "eventId", - "type": "text" - }, - { - "name": "source", - "label": "source", - "type": "text" - }, - { - "name": "overrides", - "label": "overrides", - "type": "collection", - "spec": [ - { - "name": "text", - "label": "text", - "type": "text" - }, - { - "name": "from", - "label": "from", - "type": "text" - }, - { - "name": "pushName", - "label": "pushName", - "type": "text" - }, - { - "name": "mediaType", - "label": "mediaType", - "type": "text" - }, - { - "name": "caption", - "label": "caption", - "type": "text" - }, - { - "name": "ackStatus", - "label": "ackStatus", - "type": "text" - }, - { - "name": "messageId", - "label": "messageId", - "type": "text" - }, - { - "name": "failureReason", - "label": "failureReason", - "type": "text" - }, - { - "name": "video", - "label": "video", - "type": "boolean" - }, - { - "name": "durationSeconds", - "label": "durationSeconds", - "type": "number" - }, - { - "name": "callEndReason", - "label": "callEndReason", - "type": "text" - }, - { - "name": "restrictionActive", - "label": "restrictionActive", - "type": "boolean" - }, - { - "name": "status", - "label": "status", - "type": "text" - }, - { - "name": "statusReason", - "label": "statusReason", - "type": "text" - }, - { - "name": "templateName", - "label": "templateName", - "type": "text" - }, - { - "name": "templateStatus", - "label": "templateStatus", - "type": "text" - }, - { - "name": "reason", - "label": "reason", - "type": "text" - } - ] - }, - { - "name": "fromConnection", - "label": "fromConnection", - "type": "text" } ] diff --git a/make/modules/messageReceived/interface.json b/make/modules/messageReceived/interface.json index 923841a..7f777cf 100644 --- a/make/modules/messageReceived/interface.json +++ b/make/modules/messageReceived/interface.json @@ -37,7 +37,19 @@ { "name": "whatsapp_ids", "label": "whatsapp_ids", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "linked_devices", + "label": "linked_devices", + "type": "text" + }, + { + "name": "official_api", + "label": "official_api", + "type": "text" + } + ] }, { "name": "whatsapp_id", @@ -77,7 +89,34 @@ { "name": "sender", "label": "sender", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "bsuid", + "label": "bsuid", + "type": "text" + }, + { + "name": "username", + "label": "username", + "type": "text" + }, + { + "name": "parentBsuid", + "label": "parentBsuid", + "type": "text" + } + ] } ] }, @@ -228,7 +267,22 @@ { "name": "pollOptions", "label": "pollOptions", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "name", + "label": "name", + "type": "text" + }, + { + "name": "hash", + "label": "hash", + "type": "text" + } + ] + } }, { "name": "unavailable", @@ -293,7 +347,42 @@ { "name": "items", "label": "items", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "fileName", + "label": "fileName", + "type": "text" + }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "premium", + "label": "premium", + "type": "number" + } + ] + } } ] }, @@ -377,7 +466,29 @@ { "name": "thumbnail", "label": "thumbnail", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "contentType", + "label": "contentType", + "type": "text" + }, + { + "name": "data", + "label": "data", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] } ] }, @@ -431,7 +542,32 @@ { "name": "items", "label": "items", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "productRetailerId", + "label": "productRetailerId", + "type": "text" + }, + { + "name": "quantity", + "label": "quantity", + "type": "number" + }, + { + "name": "itemPrice", + "label": "itemPrice", + "type": "number" + }, + { + "name": "currency", + "label": "currency", + "type": "text" + } + ] + } } ] }, @@ -463,117 +599,5 @@ ] } ] - }, - { - "name": "delivery", - "label": "delivery", - "type": "text" - }, - { - "name": "eventId", - "label": "eventId", - "type": "text" - }, - { - "name": "source", - "label": "source", - "type": "text" - }, - { - "name": "overrides", - "label": "overrides", - "type": "collection", - "spec": [ - { - "name": "text", - "label": "text", - "type": "text" - }, - { - "name": "from", - "label": "from", - "type": "text" - }, - { - "name": "pushName", - "label": "pushName", - "type": "text" - }, - { - "name": "mediaType", - "label": "mediaType", - "type": "text" - }, - { - "name": "caption", - "label": "caption", - "type": "text" - }, - { - "name": "ackStatus", - "label": "ackStatus", - "type": "text" - }, - { - "name": "messageId", - "label": "messageId", - "type": "text" - }, - { - "name": "failureReason", - "label": "failureReason", - "type": "text" - }, - { - "name": "video", - "label": "video", - "type": "boolean" - }, - { - "name": "durationSeconds", - "label": "durationSeconds", - "type": "number" - }, - { - "name": "callEndReason", - "label": "callEndReason", - "type": "text" - }, - { - "name": "restrictionActive", - "label": "restrictionActive", - "type": "boolean" - }, - { - "name": "status", - "label": "status", - "type": "text" - }, - { - "name": "statusReason", - "label": "statusReason", - "type": "text" - }, - { - "name": "templateName", - "label": "templateName", - "type": "text" - }, - { - "name": "templateStatus", - "label": "templateStatus", - "type": "text" - }, - { - "name": "reason", - "label": "reason", - "type": "text" - } - ] - }, - { - "name": "fromConnection", - "label": "fromConnection", - "type": "text" } ] diff --git a/make/modules/messageState/interface.json b/make/modules/messageState/interface.json index d68468f..4dd9097 100644 --- a/make/modules/messageState/interface.json +++ b/make/modules/messageState/interface.json @@ -690,117 +690,5 @@ "type": "number" } ] - }, - { - "name": "delivery", - "label": "delivery", - "type": "text" - }, - { - "name": "eventId", - "label": "eventId", - "type": "text" - }, - { - "name": "source", - "label": "source", - "type": "text" - }, - { - "name": "overrides", - "label": "overrides", - "type": "collection", - "spec": [ - { - "name": "text", - "label": "text", - "type": "text" - }, - { - "name": "from", - "label": "from", - "type": "text" - }, - { - "name": "pushName", - "label": "pushName", - "type": "text" - }, - { - "name": "mediaType", - "label": "mediaType", - "type": "text" - }, - { - "name": "caption", - "label": "caption", - "type": "text" - }, - { - "name": "ackStatus", - "label": "ackStatus", - "type": "text" - }, - { - "name": "messageId", - "label": "messageId", - "type": "text" - }, - { - "name": "failureReason", - "label": "failureReason", - "type": "text" - }, - { - "name": "video", - "label": "video", - "type": "boolean" - }, - { - "name": "durationSeconds", - "label": "durationSeconds", - "type": "number" - }, - { - "name": "callEndReason", - "label": "callEndReason", - "type": "text" - }, - { - "name": "restrictionActive", - "label": "restrictionActive", - "type": "boolean" - }, - { - "name": "status", - "label": "status", - "type": "text" - }, - { - "name": "statusReason", - "label": "statusReason", - "type": "text" - }, - { - "name": "templateName", - "label": "templateName", - "type": "text" - }, - { - "name": "templateStatus", - "label": "templateStatus", - "type": "text" - }, - { - "name": "reason", - "label": "reason", - "type": "text" - } - ] - }, - { - "name": "fromConnection", - "label": "fromConnection", - "type": "text" } ] diff --git a/make/modules/react/parameters.json b/make/modules/react/parameters.json index 0a0964d..1f80fa7 100644 --- a/make/modules/react/parameters.json +++ b/make/modules/react/parameters.json @@ -59,6 +59,6 @@ "type": "text", "label": "Write Started At", "required": true, - "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } ] diff --git a/make/modules/sendMedia/interface.json b/make/modules/sendMedia/interface.json index 624281c..33ca677 100644 --- a/make/modules/sendMedia/interface.json +++ b/make/modules/sendMedia/interface.json @@ -116,7 +116,64 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] }, { "name": "quality", @@ -158,7 +215,69 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + }, + { + "name": "seconds", + "label": "seconds", + "type": "number" + } + ] } ] }, @@ -200,7 +319,54 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] } ] }, @@ -237,7 +403,59 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "seconds", + "label": "seconds", + "type": "number" + }, + { + "name": "waveform", + "label": "waveform", + "type": "text" + } + ] } ] }, @@ -259,7 +477,64 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + } + ] }, { "name": "emojis", @@ -276,7 +551,200 @@ { "name": "stickerPack", "label": "stickerPack", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "name", + "label": "name", + "type": "text" + }, + { + "name": "publisher", + "label": "publisher", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "items", + "label": "items", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "fileName", + "label": "fileName", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + } + ] + } + }, + { + "name": "trayIcon", + "label": "trayIcon", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + } + ] + }, + { + "name": "descriptor", + "label": "descriptor", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + } + ] + }, + { + "name": "trayIconFileName", + "label": "trayIconFileName", + "type": "text" + }, + { + "name": "thumbnailDescriptor", + "label": "thumbnailDescriptor", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] + }, + { + "name": "forwardMedia", + "label": "forwardMedia", + "type": "text" + } + ] }, { "name": "location", @@ -397,7 +865,24 @@ { "name": "image", "label": "image", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + } + ] }, { "name": "body", @@ -444,7 +929,22 @@ { "name": "sections", "label": "sections", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "productIds", + "label": "productIds", + "type": "array" + } + ] + } } ] }, @@ -538,7 +1038,42 @@ { "name": "sections", "label": "sections", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "rows", + "label": "rows", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + } + ] + } + } + ] + } } ] }, @@ -560,7 +1095,116 @@ { "name": "cards", "label": "cards", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "body", + "label": "body", + "type": "text" + }, + { + "name": "buttons", + "label": "buttons", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "copyCode", + "label": "copyCode", + "type": "text" + }, + { + "name": "businessPhoneNumber", + "label": "businessPhoneNumber", + "type": "text" + }, + { + "name": "catalogProductId", + "label": "catalogProductId", + "type": "text" + } + ] + } + }, + { + "name": "image", + "label": "image", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + } + ] + }, + { + "name": "video", + "label": "video", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] + } + ] + } } ] }, @@ -572,7 +1216,39 @@ { "name": "media", "label": "media", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "filename", + "label": "filename", + "type": "text" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] }, { "name": "title", @@ -592,7 +1268,52 @@ { "name": "buttons", "label": "buttons", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "copyCode", + "label": "copyCode", + "type": "text" + }, + { + "name": "businessPhoneNumber", + "label": "businessPhoneNumber", + "type": "text" + }, + { + "name": "catalogProductId", + "label": "catalogProductId", + "type": "text" + } + ] + } } ] }, diff --git a/make/modules/sendMedia/parameters.json b/make/modules/sendMedia/parameters.json index 5a322f6..dcb6775 100644 --- a/make/modules/sendMedia/parameters.json +++ b/make/modules/sendMedia/parameters.json @@ -114,6 +114,6 @@ "type": "text", "label": "Write Started At", "required": true, - "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } ] diff --git a/make/modules/sendTemplate/interface.json b/make/modules/sendTemplate/interface.json index 624281c..33ca677 100644 --- a/make/modules/sendTemplate/interface.json +++ b/make/modules/sendTemplate/interface.json @@ -116,7 +116,64 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] }, { "name": "quality", @@ -158,7 +215,69 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + }, + { + "name": "seconds", + "label": "seconds", + "type": "number" + } + ] } ] }, @@ -200,7 +319,54 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] } ] }, @@ -237,7 +403,59 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "seconds", + "label": "seconds", + "type": "number" + }, + { + "name": "waveform", + "label": "waveform", + "type": "text" + } + ] } ] }, @@ -259,7 +477,64 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + } + ] }, { "name": "emojis", @@ -276,7 +551,200 @@ { "name": "stickerPack", "label": "stickerPack", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "name", + "label": "name", + "type": "text" + }, + { + "name": "publisher", + "label": "publisher", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "items", + "label": "items", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "fileName", + "label": "fileName", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + } + ] + } + }, + { + "name": "trayIcon", + "label": "trayIcon", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + } + ] + }, + { + "name": "descriptor", + "label": "descriptor", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + } + ] + }, + { + "name": "trayIconFileName", + "label": "trayIconFileName", + "type": "text" + }, + { + "name": "thumbnailDescriptor", + "label": "thumbnailDescriptor", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] + }, + { + "name": "forwardMedia", + "label": "forwardMedia", + "type": "text" + } + ] }, { "name": "location", @@ -397,7 +865,24 @@ { "name": "image", "label": "image", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + } + ] }, { "name": "body", @@ -444,7 +929,22 @@ { "name": "sections", "label": "sections", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "productIds", + "label": "productIds", + "type": "array" + } + ] + } } ] }, @@ -538,7 +1038,42 @@ { "name": "sections", "label": "sections", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "rows", + "label": "rows", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + } + ] + } + } + ] + } } ] }, @@ -560,7 +1095,116 @@ { "name": "cards", "label": "cards", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "body", + "label": "body", + "type": "text" + }, + { + "name": "buttons", + "label": "buttons", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "copyCode", + "label": "copyCode", + "type": "text" + }, + { + "name": "businessPhoneNumber", + "label": "businessPhoneNumber", + "type": "text" + }, + { + "name": "catalogProductId", + "label": "catalogProductId", + "type": "text" + } + ] + } + }, + { + "name": "image", + "label": "image", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + } + ] + }, + { + "name": "video", + "label": "video", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] + } + ] + } } ] }, @@ -572,7 +1216,39 @@ { "name": "media", "label": "media", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "filename", + "label": "filename", + "type": "text" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] }, { "name": "title", @@ -592,7 +1268,52 @@ { "name": "buttons", "label": "buttons", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "copyCode", + "label": "copyCode", + "type": "text" + }, + { + "name": "businessPhoneNumber", + "label": "businessPhoneNumber", + "type": "text" + }, + { + "name": "catalogProductId", + "label": "catalogProductId", + "type": "text" + } + ] + } } ] }, diff --git a/make/modules/sendTemplate/parameters.json b/make/modules/sendTemplate/parameters.json index a9781cc..06ecc0b 100644 --- a/make/modules/sendTemplate/parameters.json +++ b/make/modules/sendTemplate/parameters.json @@ -67,6 +67,6 @@ "type": "text", "label": "Write Started At", "required": true, - "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } ] diff --git a/make/modules/sendText/interface.json b/make/modules/sendText/interface.json index 624281c..33ca677 100644 --- a/make/modules/sendText/interface.json +++ b/make/modules/sendText/interface.json @@ -116,7 +116,64 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] }, { "name": "quality", @@ -158,7 +215,69 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + }, + { + "name": "seconds", + "label": "seconds", + "type": "number" + } + ] } ] }, @@ -200,7 +319,54 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] } ] }, @@ -237,7 +403,59 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "seconds", + "label": "seconds", + "type": "number" + }, + { + "name": "waveform", + "label": "waveform", + "type": "text" + } + ] } ] }, @@ -259,7 +477,64 @@ { "name": "descriptor", "label": "descriptor", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + }, + { + "name": "stickerType", + "label": "stickerType", + "type": "text" + } + ] }, { "name": "emojis", @@ -276,7 +551,200 @@ { "name": "stickerPack", "label": "stickerPack", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "name", + "label": "name", + "type": "text" + }, + { + "name": "publisher", + "label": "publisher", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + }, + { + "name": "caption", + "label": "caption", + "type": "text" + }, + { + "name": "items", + "label": "items", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "emojis", + "label": "emojis", + "type": "array" + }, + { + "name": "accessibilityLabel", + "label": "accessibilityLabel", + "type": "text" + }, + { + "name": "fileName", + "label": "fileName", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + } + ] + } + }, + { + "name": "trayIcon", + "label": "trayIcon", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + } + ] + }, + { + "name": "descriptor", + "label": "descriptor", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + } + ] + }, + { + "name": "trayIconFileName", + "label": "trayIconFileName", + "type": "text" + }, + { + "name": "thumbnailDescriptor", + "label": "thumbnailDescriptor", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "directPath", + "label": "directPath", + "type": "text" + }, + { + "name": "mediaKey", + "label": "mediaKey", + "type": "text" + }, + { + "name": "fileSha256", + "label": "fileSha256", + "type": "text" + }, + { + "name": "fileEncSha256", + "label": "fileEncSha256", + "type": "text" + }, + { + "name": "fileLength", + "label": "fileLength", + "type": "number" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "mediaKeyTimestamp", + "label": "mediaKeyTimestamp", + "type": "number" + }, + { + "name": "width", + "label": "width", + "type": "number" + }, + { + "name": "height", + "label": "height", + "type": "number" + } + ] + }, + { + "name": "forwardMedia", + "label": "forwardMedia", + "type": "text" + } + ] }, { "name": "location", @@ -397,7 +865,24 @@ { "name": "image", "label": "image", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + } + ] }, { "name": "body", @@ -444,7 +929,22 @@ { "name": "sections", "label": "sections", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "productIds", + "label": "productIds", + "type": "array" + } + ] + } } ] }, @@ -538,7 +1038,42 @@ { "name": "sections", "label": "sections", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "rows", + "label": "rows", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "title", + "label": "title", + "type": "text" + }, + { + "name": "description", + "label": "description", + "type": "text" + } + ] + } + } + ] + } } ] }, @@ -560,7 +1095,116 @@ { "name": "cards", "label": "cards", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "body", + "label": "body", + "type": "text" + }, + { + "name": "buttons", + "label": "buttons", + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "copyCode", + "label": "copyCode", + "type": "text" + }, + { + "name": "businessPhoneNumber", + "label": "businessPhoneNumber", + "type": "text" + }, + { + "name": "catalogProductId", + "label": "catalogProductId", + "type": "text" + } + ] + } + }, + { + "name": "image", + "label": "image", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + } + ] + }, + { + "name": "video", + "label": "video", + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] + } + ] + } } ] }, @@ -572,7 +1216,39 @@ { "name": "media", "label": "media", - "type": "collection" + "type": "collection", + "spec": [ + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "base64", + "label": "base64", + "type": "text" + }, + { + "name": "mimeType", + "label": "mimeType", + "type": "text" + }, + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "filename", + "label": "filename", + "type": "text" + }, + { + "name": "thumbnail", + "label": "thumbnail", + "type": "text" + } + ] }, { "name": "title", @@ -592,7 +1268,52 @@ { "name": "buttons", "label": "buttons", - "type": "array" + "type": "array", + "spec": { + "type": "collection", + "spec": [ + { + "name": "type", + "label": "type", + "type": "text" + }, + { + "name": "text", + "label": "text", + "type": "text" + }, + { + "name": "url", + "label": "url", + "type": "text" + }, + { + "name": "phoneNumber", + "label": "phoneNumber", + "type": "text" + }, + { + "name": "id", + "label": "id", + "type": "text" + }, + { + "name": "copyCode", + "label": "copyCode", + "type": "text" + }, + { + "name": "businessPhoneNumber", + "label": "businessPhoneNumber", + "type": "text" + }, + { + "name": "catalogProductId", + "label": "catalogProductId", + "type": "text" + } + ] + } } ] }, diff --git a/make/modules/sendText/parameters.json b/make/modules/sendText/parameters.json index ec1d38a..2160725 100644 --- a/make/modules/sendText/parameters.json +++ b/make/modules/sendText/parameters.json @@ -59,6 +59,6 @@ "type": "text", "label": "Write Started At", "required": true, - "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "help": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } ] diff --git a/n8n/shared/catalog.js b/n8n/shared/catalog.js index e8d0221..0072bee 100644 --- a/n8n/shared/catalog.js +++ b/n8n/shared/catalog.js @@ -28,7 +28,7 @@ const fields = { messageId: { label: 'Message ID', required: true }, reaction: { label: 'Reaction', help: 'An emoji. Leave empty to remove the reaction.' }, idempotencyKey: { label: 'Idempotency Key', help: 'Required for writes. Map a stable business key unique to this write. Preserve it across retries.' }, - writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, + writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, diff --git a/n8n/shared/core.js b/n8n/shared/core.js index c2302db..5f48e35 100644 --- a/n8n/shared/core.js +++ b/n8n/shared/core.js @@ -4,7 +4,7 @@ const ORIGIN = 'https://api.polymorfa.com'; const VERSION = '2026-09-22'; const MAX_MEDIA_BYTES = 4 * 1024 * 1024; -const MAX_WRITE_AGE = 23 * 60 * 60 * 1000; +const MAX_WRITE_AGE = 55 * 60 * 1000; class IntegrationError extends Error { constructor(code, status = 0, requestId, retryAfter, write = false) { // A write that ended in a server error or is still running has an uncertain outcome, whatever its code. @@ -25,6 +25,10 @@ function segment(value, name) { if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new IntegrationError(`invalid_${name}`); return value; } +function connectionSegment(value) { + if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + return encodeURIComponent(value); +} function object(value, name) { let parsed = value; try { if (typeof value === 'string') parsed = JSON.parse(value); } catch { throw new IntegrationError(`invalid_${name}_json`); } @@ -93,7 +97,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { @@ -104,7 +108,7 @@ function advanced(p, auth) { } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${connectionSegment(p.connection)}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); @@ -135,4 +139,4 @@ async function execute(action, p, auth, transport, provider, now) { try { response = await transport(request); } catch { throw new IntegrationError(request.method === 'GET' ? 'network_error' : 'outcome_unknown'); } return parseResponse({ ...response, method: request.method }); } -module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, IntegrationError, required, segment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; +module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, MAX_WRITE_AGE, IntegrationError, required, segment, connectionSegment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; diff --git a/n8n/shared/hooks.js b/n8n/shared/hooks.js index 87143ea..c7e5aff 100644 --- a/n8n/shared/hooks.js +++ b/n8n/shared/hooks.js @@ -25,10 +25,10 @@ function creationKey(markerKey, nonce) { if (typeof nonce !== 'string' || !NONCE.test(nonce)) throw new IntegrationError('invalid_creation_nonce'); return 'integration-create-' + createHmac('sha256', markerKey).update(nonce).digest('hex'); } -function owns(hook, auth, url, group, subscriptionKey, recordedMarker) { +function owns(hook, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes) { const marker = (recordedMarker || identity(auth, group, subscriptionKey).name).toLowerCase(); - const types = events[group].types; - return hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && + const types = cleanupTypes || events[group]?.types; + return types && hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && Array.isArray(hook.headers) && hook.headers.some(h => h.name.toLowerCase() === marker) && Array.isArray(hook.eventTypes) && hook.eventTypes.length === types.length && types.every(t => hook.eventTypes.includes(t)); } @@ -89,15 +89,14 @@ async function subscribe(auth, url, group, subscriptionKey, transport, provider, throw new IntegrationError('subscription_receipt_requires_reconciliation'); } function creation(url, group, subscriptionKey) { - return { nonce: randomUUID(), url: callback(url), group, subscriptionKey }; + return { nonce: randomUUID(), url: callback(url), group, subscriptionKey, startedAt: new Date().toISOString() }; } // Store: provider-private { get(), set(value) } for this trigger's pending creation. async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (!pending || pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce)) { - pending = creation(target, group, subscriptionKey); - } + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); let owned; @@ -111,12 +110,23 @@ async function activate(auth, url, group, subscriptionKey, transport, provider, return owned; } async function unsubscribe(auth, id, url, group, subscriptionKey, transport, provider, recordedMarker) { + // Cleanup only: the accepted pre-rename trigger stored this exact group and + // filter set. It never enters registration, authentication or event emission. + let cleanupTypes; + if (group === 'numberState') { + required(subscriptionKey, 'subscription_key'); + if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); + const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); + const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); + if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; + } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; let hook; try { hook = (await call(auth, transport, provider, 'GET', path)).data; } catch (error) { if (error.status === 404) return; throw error; } // Disabled hooks remain owned and may be deleted; all other ownership checks still apply. - if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); + if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes)) throw new IntegrationError('subscription_ownership_mismatch'); await call(auth, transport, provider, 'DELETE', path, undefined, `integration-delete-${id}`); } function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = ['']) { diff --git a/pipedream/actions/apiRequest/apiRequest.mjs b/pipedream/actions/apiRequest/apiRequest.mjs index 804ad0a..baf3ed5 100644 --- a/pipedream/actions/apiRequest/apiRequest.mjs +++ b/pipedream/actions/apiRequest/apiRequest.mjs @@ -43,7 +43,7 @@ export default { "type": "string", "label": "Write Started At", "optional": true, - "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } } }, async run({ $ }) { diff --git a/pipedream/actions/react/react.mjs b/pipedream/actions/react/react.mjs index 183ec99..942b731 100644 --- a/pipedream/actions/react/react.mjs +++ b/pipedream/actions/react/react.mjs @@ -57,7 +57,7 @@ export default { "type": "string", "label": "Write Started At", "optional": false, - "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } } }, async run({ $ }) { diff --git a/pipedream/actions/sendMedia/sendMedia.mjs b/pipedream/actions/sendMedia/sendMedia.mjs index 156656b..90fa41a 100644 --- a/pipedream/actions/sendMedia/sendMedia.mjs +++ b/pipedream/actions/sendMedia/sendMedia.mjs @@ -108,7 +108,7 @@ export default { "type": "string", "label": "Write Started At", "optional": false, - "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } } }, async run({ $ }) { diff --git a/pipedream/actions/sendTemplate/sendTemplate.mjs b/pipedream/actions/sendTemplate/sendTemplate.mjs index 358c94f..10a42a8 100644 --- a/pipedream/actions/sendTemplate/sendTemplate.mjs +++ b/pipedream/actions/sendTemplate/sendTemplate.mjs @@ -64,7 +64,7 @@ export default { "type": "string", "label": "Write Started At", "optional": false, - "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } } }, async run({ $ }) { diff --git a/pipedream/actions/sendText/sendText.mjs b/pipedream/actions/sendText/sendText.mjs index 8157c3d..084d0d3 100644 --- a/pipedream/actions/sendText/sendText.mjs +++ b/pipedream/actions/sendText/sendText.mjs @@ -57,7 +57,7 @@ export default { "type": "string", "label": "Write Started At", "optional": false, - "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation." + "description": "Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation." } } }, async run({ $ }) { diff --git a/pipedream/common/catalog.cjs b/pipedream/common/catalog.cjs index e8d0221..0072bee 100644 --- a/pipedream/common/catalog.cjs +++ b/pipedream/common/catalog.cjs @@ -28,7 +28,7 @@ const fields = { messageId: { label: 'Message ID', required: true }, reaction: { label: 'Reaction', help: 'An emoji. Leave empty to remove the reaction.' }, idempotencyKey: { label: 'Idempotency Key', help: 'Required for writes. Map a stable business key unique to this write. Preserve it across retries.' }, - writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, + writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, diff --git a/pipedream/common/core.cjs b/pipedream/common/core.cjs index c2302db..5f48e35 100644 --- a/pipedream/common/core.cjs +++ b/pipedream/common/core.cjs @@ -4,7 +4,7 @@ const ORIGIN = 'https://api.polymorfa.com'; const VERSION = '2026-09-22'; const MAX_MEDIA_BYTES = 4 * 1024 * 1024; -const MAX_WRITE_AGE = 23 * 60 * 60 * 1000; +const MAX_WRITE_AGE = 55 * 60 * 1000; class IntegrationError extends Error { constructor(code, status = 0, requestId, retryAfter, write = false) { // A write that ended in a server error or is still running has an uncertain outcome, whatever its code. @@ -25,6 +25,10 @@ function segment(value, name) { if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new IntegrationError(`invalid_${name}`); return value; } +function connectionSegment(value) { + if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + return encodeURIComponent(value); +} function object(value, name) { let parsed = value; try { if (typeof value === 'string') parsed = JSON.parse(value); } catch { throw new IntegrationError(`invalid_${name}_json`); } @@ -93,7 +97,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { @@ -104,7 +108,7 @@ function advanced(p, auth) { } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${connectionSegment(p.connection)}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); @@ -135,4 +139,4 @@ async function execute(action, p, auth, transport, provider, now) { try { response = await transport(request); } catch { throw new IntegrationError(request.method === 'GET' ? 'network_error' : 'outcome_unknown'); } return parseResponse({ ...response, method: request.method }); } -module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, IntegrationError, required, segment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; +module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, MAX_WRITE_AGE, IntegrationError, required, segment, connectionSegment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; diff --git a/pipedream/common/hooks.cjs b/pipedream/common/hooks.cjs index 4818f39..2130449 100644 --- a/pipedream/common/hooks.cjs +++ b/pipedream/common/hooks.cjs @@ -25,10 +25,10 @@ function creationKey(markerKey, nonce) { if (typeof nonce !== 'string' || !NONCE.test(nonce)) throw new IntegrationError('invalid_creation_nonce'); return 'integration-create-' + createHmac('sha256', markerKey).update(nonce).digest('hex'); } -function owns(hook, auth, url, group, subscriptionKey, recordedMarker) { +function owns(hook, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes) { const marker = (recordedMarker || identity(auth, group, subscriptionKey).name).toLowerCase(); - const types = events[group].types; - return hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && + const types = cleanupTypes || events[group]?.types; + return types && hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && Array.isArray(hook.headers) && hook.headers.some(h => h.name.toLowerCase() === marker) && Array.isArray(hook.eventTypes) && hook.eventTypes.length === types.length && types.every(t => hook.eventTypes.includes(t)); } @@ -89,15 +89,14 @@ async function subscribe(auth, url, group, subscriptionKey, transport, provider, throw new IntegrationError('subscription_receipt_requires_reconciliation'); } function creation(url, group, subscriptionKey) { - return { nonce: randomUUID(), url: callback(url), group, subscriptionKey }; + return { nonce: randomUUID(), url: callback(url), group, subscriptionKey, startedAt: new Date().toISOString() }; } // Store: provider-private { get(), set(value) } for this trigger's pending creation. async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (!pending || pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce)) { - pending = creation(target, group, subscriptionKey); - } + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); let owned; @@ -111,12 +110,23 @@ async function activate(auth, url, group, subscriptionKey, transport, provider, return owned; } async function unsubscribe(auth, id, url, group, subscriptionKey, transport, provider, recordedMarker) { + // Cleanup only: the accepted pre-rename trigger stored this exact group and + // filter set. It never enters registration, authentication or event emission. + let cleanupTypes; + if (group === 'numberState') { + required(subscriptionKey, 'subscription_key'); + if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); + const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); + const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); + if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; + } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; let hook; try { hook = (await call(auth, transport, provider, 'GET', path)).data; } catch (error) { if (error.status === 404) return; throw error; } // Disabled hooks remain owned and may be deleted; all other ownership checks still apply. - if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); + if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes)) throw new IntegrationError('subscription_ownership_mismatch'); await call(auth, transport, provider, 'DELETE', path, undefined, `integration-delete-${id}`); } function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = ['']) { diff --git a/pipedream/sources/callEnded/callEnded.mjs b/pipedream/sources/callEnded/callEnded.mjs index dfe12a7..715dede 100644 --- a/pipedream/sources/callEnded/callEnded.mjs +++ b/pipedream/sources/callEnded/callEnded.mjs @@ -1,5 +1,6 @@ // Generated from shared/catalog.cjs. import polymorfa from '../../polymorfa.app.mjs'; +import core from '../../common/core.cjs'; export default { key: "polymorfa-callEnded", name: "Call Ended", description: "Triggers when a call ends.", version: '0.1.0', type: 'source', dedupe: 'unique', @@ -12,6 +13,7 @@ export default { this.db.set('ownedSubscription', owned); }, async deactivate() { + if (this.db.get('pendingCreation')) throw new core.IntegrationError('subscription_requires_reconciliation'); const owned = this.db.get('ownedSubscription'); if (owned) { await this.polymorfa.unsubscribe(undefined, owned); this.db.set('ownedSubscription', null); } this.db.set('pendingCreation', null); diff --git a/pipedream/sources/connectionState/connectionState.mjs b/pipedream/sources/connectionState/connectionState.mjs index 12f902b..956146a 100644 --- a/pipedream/sources/connectionState/connectionState.mjs +++ b/pipedream/sources/connectionState/connectionState.mjs @@ -1,5 +1,6 @@ // Generated from shared/catalog.cjs. import polymorfa from '../../polymorfa.app.mjs'; +import core from '../../common/core.cjs'; export default { key: "polymorfa-connectionState", name: "Connection State Changed", description: "Triggers when a Connection changes state, connects or logs out.", version: '0.1.0', type: 'source', dedupe: 'unique', @@ -12,6 +13,7 @@ export default { this.db.set('ownedSubscription', owned); }, async deactivate() { + if (this.db.get('pendingCreation')) throw new core.IntegrationError('subscription_requires_reconciliation'); const owned = this.db.get('ownedSubscription'); if (owned) { await this.polymorfa.unsubscribe(undefined, owned); this.db.set('ownedSubscription', null); } this.db.set('pendingCreation', null); diff --git a/pipedream/sources/messageReceived/messageReceived.mjs b/pipedream/sources/messageReceived/messageReceived.mjs index 963c23d..28010f6 100644 --- a/pipedream/sources/messageReceived/messageReceived.mjs +++ b/pipedream/sources/messageReceived/messageReceived.mjs @@ -1,5 +1,6 @@ // Generated from shared/catalog.cjs. import polymorfa from '../../polymorfa.app.mjs'; +import core from '../../common/core.cjs'; export default { key: "polymorfa-messageReceived", name: "New Message", description: "Triggers when a message is received.", version: '0.1.0', type: 'source', dedupe: 'unique', @@ -12,6 +13,7 @@ export default { this.db.set('ownedSubscription', owned); }, async deactivate() { + if (this.db.get('pendingCreation')) throw new core.IntegrationError('subscription_requires_reconciliation'); const owned = this.db.get('ownedSubscription'); if (owned) { await this.polymorfa.unsubscribe(undefined, owned); this.db.set('ownedSubscription', null); } this.db.set('pendingCreation', null); diff --git a/pipedream/sources/messageState/messageState.mjs b/pipedream/sources/messageState/messageState.mjs index 8aba13e..183b63b 100644 --- a/pipedream/sources/messageState/messageState.mjs +++ b/pipedream/sources/messageState/messageState.mjs @@ -1,5 +1,6 @@ // Generated from shared/catalog.cjs. import polymorfa from '../../polymorfa.app.mjs'; +import core from '../../common/core.cjs'; export default { key: "polymorfa-messageState", name: "Message State Changed", description: "Triggers when a message is sent, acknowledged, failed or updated.", version: '0.1.0', type: 'source', dedupe: 'unique', @@ -12,6 +13,7 @@ export default { this.db.set('ownedSubscription', owned); }, async deactivate() { + if (this.db.get('pendingCreation')) throw new core.IntegrationError('subscription_requires_reconciliation'); const owned = this.db.get('ownedSubscription'); if (owned) { await this.polymorfa.unsubscribe(undefined, owned); this.db.set('ownedSubscription', null); } this.db.set('pendingCreation', null); diff --git a/scripts/check-contracts.mjs b/scripts/check-contracts.mjs index 1eb0bef..185cb54 100644 --- a/scripts/check-contracts.mjs +++ b/scripts/check-contracts.mjs @@ -18,6 +18,17 @@ for (const [kind, pin] of Object.entries(source.specs)) { assert.equal(entry.contract, kind); assert.equal(entry.path, path); assert.equal(entry.method, method.toUpperCase()); operationIds.add(operation.operationId); } + const verifyReferences = value => { + if (Array.isArray(value)) return value.forEach(verifyReferences); + if (!value || typeof value !== 'object') return; + if (typeof value.$ref === 'string') { + const match = /^#\/components\/([^/]+)\/([^/]+)$/.exec(value.$ref); + assert.ok(match && spec.components?.[match[1]]?.[match[2]], `Unresolved public reference ${value.$ref}`); + } + if (Array.isArray(value.security)) for (const requirement of value.security) for (const name of Object.keys(requirement)) assert.ok(spec.components.securitySchemes?.[name], `Unresolved public security scheme ${name}`); + Object.values(value).forEach(verifyReferences); + }; + verifyReferences(spec); for (const schema of Object.values(spec.components.schemas)) for (const value of schema.properties?.event?.enum || []) eventTypes.add(value); assert.ok(!Object.keys(spec.paths).some(p => /functions|admin|console|quicklink|credentials/i.test(p))); } diff --git a/scripts/generate.mjs b/scripts/generate.mjs index ca65246..fc0283b 100644 --- a/scripts/generate.mjs +++ b/scripts/generate.mjs @@ -25,16 +25,20 @@ for (const target of ['n8n/shared', 'zapier/shared', 'pipedream/common']) { } for (const name of ['LICENSE', 'NOTICE.md']) emit(`n8n/${name}`, readFileSync(name, 'utf8')); const specs = Object.fromEntries(['messaging', 'platform'].map(k => [k, JSON.parse(readFileSync(`contracts/openapi.${k}.json`))])); -function interfaceFields(schema, spec, depth = 0) { - if (!schema || depth > 4) return []; - if (schema.$ref) return interfaceFields(spec.components.schemas[schema.$ref.split('/').at(-1)], spec, depth + 1); +function interfaceFields(schema, spec, ancestors = new Set()) { + if (!schema) return []; + if (schema.$ref) { + if (ancestors.has(schema.$ref)) return []; + return interfaceFields(spec.components.schemas[schema.$ref.split('/').at(-1)], spec, new Set([...ancestors, schema.$ref])); + } const fields = { ...schema.properties }; - for (const variant of [...(schema.allOf || []), ...(schema.oneOf || []), ...(schema.anyOf || [])]) for (const item of interfaceFields(variant, spec, depth + 1)) if (!fields[item.name]) fields[item.name] = { __interface: item }; + for (const variant of [...(schema.allOf || []), ...(schema.oneOf || []), ...(schema.anyOf || [])]) for (const item of interfaceFields(variant, spec, ancestors)) if (!fields[item.name]) fields[item.name] = { __interface: item }; return Object.entries(fields).map(([name, s]) => { if (s.__interface) return s.__interface; const resolved = s.$ref ? spec.components.schemas[s.$ref.split('/').at(-1)] : s; + if (!resolved) throw new Error(`Missing interface schema: ${s.$ref}`); const type = resolved.type === 'array' ? 'array' : resolved.type === 'boolean' ? 'boolean' : ['number', 'integer'].includes(resolved.type) ? 'number' : resolved.type === 'object' || resolved.properties || resolved.oneOf || resolved.anyOf || resolved.allOf ? 'collection' : resolved.format === 'date-time' ? 'date' : 'text'; - const children = type === 'array' ? interfaceFields(resolved.items, spec, depth + 1) : type === 'collection' ? interfaceFields(resolved, spec, depth + 1) : []; + const children = type === 'array' ? interfaceFields(resolved.items, spec, ancestors) : type === 'collection' ? interfaceFields(s, spec, ancestors) : []; return { name, label: name, type, ...(children.length ? { spec: type === 'array' ? { type: 'collection', spec: children } : children } : {}) }; }); } @@ -47,7 +51,7 @@ for (const [key, action] of Object.entries(actions)) { } emit(`pipedream/actions/${key}/${key}.mjs`, `// Generated from shared/catalog.cjs.\nimport polymorfa from '../../polymorfa.app.mjs';\nexport default {\n key: ${JSON.stringify('polymorfa-' + key)}, name: ${JSON.stringify(action.label)}, description: ${JSON.stringify(action.description)},\n version: '0.1.0', type: 'action',\n props: { polymorfa, ...${JSON.stringify(props, null, 2)} },\n async run({ $ }) {\n const input = Object.fromEntries(${JSON.stringify(action.fields)}.map(key => [key, this[key]]));\n return this.polymorfa.execute($, ${JSON.stringify(key)}, input);\n },\n};\n`); } -for (const [key, event] of Object.entries(events)) emit(`pipedream/sources/${key}/${key}.mjs`, `// Generated from shared/catalog.cjs.\nimport polymorfa from '../../polymorfa.app.mjs';\nexport default {\n key: ${JSON.stringify('polymorfa-' + key)}, name: ${JSON.stringify(event.label)}, description: ${JSON.stringify(event.description)},\n version: '0.1.0', type: 'source', dedupe: 'unique',\n props: { polymorfa, db: '$.service.db', http: { type: '$.interface.http', customResponse: true },\n subscriptionKey: { type: 'string', label: 'Subscription Key', description: 'Unique stable label for this source. Events are project-wide.' } },\n hooks: {\n async activate() {\n const store = { get: () => this.db.get('pendingCreation'), set: value => this.db.set('pendingCreation', value || null) };\n const owned = await this.polymorfa.activate(undefined, this.http.endpoint, ${JSON.stringify(key)}, this.subscriptionKey, store);\n this.db.set('ownedSubscription', owned);\n },\n async deactivate() {\n const owned = this.db.get('ownedSubscription');\n if (owned) { await this.polymorfa.unsubscribe(undefined, owned); this.db.set('ownedSubscription', null); }\n this.db.set('pendingCreation', null);\n },\n },\n async run(event) {\n if (!this.polymorfa.authenticate(${JSON.stringify(key)}, this.subscriptionKey, event.headers)) { this.http.respond({ status: 401 }); return; }\n let data;\n try { data = this.polymorfa.envelope(event.body, ${JSON.stringify(key)}); } catch { this.http.respond({ status: 400 }); return; }\n this.$emit(data, { id: data.id, summary: data.event, ts: Date.parse(data.timestamp) });\n this.http.respond({ status: 200 });\n },\n};\n`); +for (const [key, event] of Object.entries(events)) emit(`pipedream/sources/${key}/${key}.mjs`, `// Generated from shared/catalog.cjs.\nimport polymorfa from '../../polymorfa.app.mjs';\nimport core from '../../common/core.cjs';\nexport default {\n key: ${JSON.stringify('polymorfa-' + key)}, name: ${JSON.stringify(event.label)}, description: ${JSON.stringify(event.description)},\n version: '0.1.0', type: 'source', dedupe: 'unique',\n props: { polymorfa, db: '$.service.db', http: { type: '$.interface.http', customResponse: true },\n subscriptionKey: { type: 'string', label: 'Subscription Key', description: 'Unique stable label for this source. Events are project-wide.' } },\n hooks: {\n async activate() {\n const store = { get: () => this.db.get('pendingCreation'), set: value => this.db.set('pendingCreation', value || null) };\n const owned = await this.polymorfa.activate(undefined, this.http.endpoint, ${JSON.stringify(key)}, this.subscriptionKey, store);\n this.db.set('ownedSubscription', owned);\n },\n async deactivate() {\n if (this.db.get('pendingCreation')) throw new core.IntegrationError('subscription_requires_reconciliation');\n const owned = this.db.get('ownedSubscription');\n if (owned) { await this.polymorfa.unsubscribe(undefined, owned); this.db.set('ownedSubscription', null); }\n this.db.set('pendingCreation', null);\n },\n },\n async run(event) {\n if (!this.polymorfa.authenticate(${JSON.stringify(key)}, this.subscriptionKey, event.headers)) { this.http.respond({ status: 401 }); return; }\n let data;\n try { data = this.polymorfa.envelope(event.body, ${JSON.stringify(key)}); } catch { this.http.respond({ status: 400 }); return; }\n this.$emit(data, { id: data.id, summary: data.event, ts: Date.parse(data.timestamp) });\n this.http.respond({ status: 200 });\n },\n};\n`); // Make custom IML functions reuse the exact shared request/response behavior. // Every function fits Make's 5,000-character limit. They require provider enablement. @@ -60,7 +64,7 @@ function imlFunction(name, args, definitions, statement) { } imlFunction('polymorfaBody', 'action, p', `${errorClass}\nconst MAX_MEDIA_BYTES = ${core.MAX_MEDIA_BYTES};\n${core.required}\n${core.conversation || ''}\n${core.messageBody}`, 'return messageBody(action, p);'); imlFunction('polymorfaAdvanced', 'p, auth', `${errorClass}\n${core.required}\n${core.object || ''}\nconst ORIGIN = '${core.ORIGIN}';\n${core.advanced || ''}`, 'return advanced(p, auth);'); -imlFunction('polymorfaRequest', 'action, p, auth', `${errorClass}\nconst ORIGIN = '${core.ORIGIN}', VERSION = '${core.VERSION}', MAX_WRITE_AGE = ${23 * 60 * 60 * 1000};\n${core.required}\n${core.segment}\n${core.headers}\n${core.writeHeaders}\n${core.buildRequest.toString().replace('messageBody(action, p)', 'iml.polymorfaBody(action, p)').replace('advanced(p, auth)', 'iml.polymorfaAdvanced(p, auth)')}`, "return buildRequest(action, p, auth, 'make');"); +imlFunction('polymorfaRequest', 'action, p, auth', `${errorClass}\nconst ORIGIN = '${core.ORIGIN}', VERSION = '${core.VERSION}', MAX_WRITE_AGE = ${core.MAX_WRITE_AGE};\n${core.required}\n${core.segment}\n${core.connectionSegment}\n${core.headers}\n${core.writeHeaders}\n${core.buildRequest.toString().replace('messageBody(action, p)', 'iml.polymorfaBody(action, p)').replace('advanced(p, auth)', 'iml.polymorfaAdvanced(p, auth)')}`, "return buildRequest(action, p, auth, 'make');"); imlFunction('polymorfaResult', 'status, headers, body, method', `${errorClass}\n${safeCode}\n${core.parseResponse}`, 'return parseResponse({ status, headers, body, method });'); imlFunction('polymorfaSegment', 'value', `${errorClass}\n${core.required}\n${core.segment}`, "return segment(value, 'resource_id');"); imlFunction('polymorfaHook', 'auth, group, subscriptionKey', `${errorClass}\n${core.required}\n${core.segment}\nconst events = ${JSON.stringify(events)};`, `if (!events[group]) throw new IntegrationError('invalid_event_group');\nrequired(subscriptionKey, 'subscription_key');\nif (subscriptionKey.length > 200) throw new IntegrationError('invalid_subscription_key');\nconst scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]);\nconst derive = label => iml.sha256(label + ':' + scope, 'hex', auth.apiKey);\nreturn { name: 'X-Polymorfa-Integration-Token-' + derive('marker').slice(0, 24), value: derive('receiver'), key: derive('create') };`); @@ -97,7 +101,7 @@ for (const [key, action] of Object.entries(actions)) { } for (const [key, e] of Object.entries(events)) { emit(`make/modules/${key}/metadata.json`, { label: e.label, description: e.description, type: 'instant', webhook: key }); - const schemas = Object.values(specs.messaging.components.schemas).filter(s => s.properties?.event?.enum?.some(type => e.types.includes(type))); + const schemas = Object.values(specs.messaging.components.schemas).filter(s => s.properties?.event?.enum?.some(type => e.types.includes(type))).map(s => ({ ...s, properties: Object.fromEntries(Object.entries(s.properties).filter(([name]) => ['id', 'connection', 'externalId', 'timestamp', 'event', 'payload'].includes(name))) })); const merge = (a, b) => { const result = [...a]; for (const item of b) { diff --git a/scripts/sync-api-contracts.mjs b/scripts/sync-api-contracts.mjs new file mode 100644 index 0000000..9debe3a --- /dev/null +++ b/scripts/sync-api-contracts.mjs @@ -0,0 +1,64 @@ +import assert from 'node:assert/strict'; +import { readFileSync, writeFileSync } from 'node:fs'; +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { pathToFileURL } from 'node:url'; +import { createRequire } from 'node:module'; +const require = createRequire(import.meta.url); + +// Project only covered public operations and their referenced components. Event +// schemas are independent roots because OpenAPI does not reference webhooks from +// HTTP operations. Security requirements also reference named components. +export function projectContract(spec, kind, coverage, eventTypes) { + const components = { schemas: {} }; const paths = {}; const seen = new Set(); + const include = (section, name) => { + const key = `${section}/${name}`; + if (seen.has(key)) return; + const value = spec.components?.[section]?.[name]; + assert.ok(value, `Missing public component ${key}`); + seen.add(key); (components[section] ??= {})[name] = value; visit(value); + }; + const visit = value => { + if (Array.isArray(value)) { value.forEach(visit); return; } + if (!value || typeof value !== 'object') return; + if (typeof value.$ref === 'string') { + const match = /^#\/components\/([^/]+)\/([^/]+)$/.exec(value.$ref); + assert.ok(match, `Unsupported public reference ${value.$ref}`); + include(match[1], match[2]); + } + if (Array.isArray(value.security)) for (const requirement of value.security) for (const name of Object.keys(requirement)) include('securitySchemes', name); + Object.values(value).forEach(visit); + }; + if (spec.security) visit({ security: spec.security }); + for (const [operationId, operation] of Object.entries(coverage.operations).filter(([, item]) => item.contract === kind)) { + const method = operation.method.toLowerCase(); const item = spec.paths[operation.path]; + assert.equal(item?.[method]?.operationId, operationId, `Missing covered public operation ${operationId}`); + const target = paths[operation.path] ??= {}; + if (item.parameters) { target.parameters = item.parameters; visit(item.parameters); } + target[method] = item[method]; visit(item[method]); + } + if (kind === 'messaging') for (const [name, schema] of Object.entries(spec.components.schemas)) { + if (schema.properties?.event?.enum?.some(type => eventTypes.includes(type))) include('schemas', name); + } + return { openapi: spec.openapi, info: spec.info, ...(spec.servers ? { servers: spec.servers } : {}), ...(spec.security ? { security: spec.security } : {}), paths, components }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const args = process.argv.slice(2); const value = name => args[args.indexOf(name) + 1]; + assert.ok(args.includes('--api-root') && args.includes('--source'), 'Pass --api-root and immutable --source SHA.'); + const sourceSha = value('--source'); assert.match(sourceSha, /^[a-f0-9]{40}$/); + const source = JSON.parse(readFileSync('contracts/source.json')); + const coverage = JSON.parse(readFileSync('contracts/coverage.json')); + const events = Object.values(require('../shared/catalog.cjs').events).flatMap(event => event.types); + for (const [kind, pin] of Object.entries(source.specs)) { + const bytes = execFileSync('git', ['-C', value('--api-root'), 'show', `${sourceSha}:${pin.publicSourcePath}`], { maxBuffer: 32 * 1024 * 1024 }); + const spec = JSON.parse(bytes); const projected = projectContract(spec, kind, coverage, events); + const snapshot = JSON.stringify(projected, null, 2) + '\n'; + writeFileSync(pin.snapshot, snapshot); + pin.publicSourceSha256 = createHash('sha256').update(bytes).digest('hex'); + pin.sha256 = createHash('sha256').update(snapshot).digest('hex'); + } + source.apiSource = sourceSha; + writeFileSync('contracts/source.json', JSON.stringify(source, null, 2) + '\n'); + console.log(`Projected nine covered public operations from ${sourceSha}. SDK binding and release acceptance remain separate.`); +} diff --git a/shared/catalog.cjs b/shared/catalog.cjs index d5113d8..65d884f 100644 --- a/shared/catalog.cjs +++ b/shared/catalog.cjs @@ -27,7 +27,7 @@ const fields = { messageId: { label: 'Message ID', required: true }, reaction: { label: 'Reaction', help: 'An emoji. Leave empty to remove the reaction.' }, idempotencyKey: { label: 'Idempotency Key', help: 'Required for writes. Map a stable business key unique to this write. Preserve it across retries.' }, - writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, + writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, diff --git a/shared/core.cjs b/shared/core.cjs index 400c844..3bcd2db 100644 --- a/shared/core.cjs +++ b/shared/core.cjs @@ -3,7 +3,7 @@ const ORIGIN = 'https://api.polymorfa.com'; const VERSION = '2026-09-22'; const MAX_MEDIA_BYTES = 4 * 1024 * 1024; -const MAX_WRITE_AGE = 23 * 60 * 60 * 1000; +const MAX_WRITE_AGE = 55 * 60 * 1000; class IntegrationError extends Error { constructor(code, status = 0, requestId, retryAfter, write = false) { // A write that ended in a server error or is still running has an uncertain outcome, whatever its code. @@ -24,6 +24,10 @@ function segment(value, name) { if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new IntegrationError(`invalid_${name}`); return value; } +function connectionSegment(value) { + if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + return encodeURIComponent(value); +} function object(value, name) { let parsed = value; try { if (typeof value === 'string') parsed = JSON.parse(value); } catch { throw new IntegrationError(`invalid_${name}_json`); } @@ -92,7 +96,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { @@ -103,7 +107,7 @@ function advanced(p, auth) { } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${connectionSegment(p.connection)}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); @@ -134,4 +138,4 @@ async function execute(action, p, auth, transport, provider, now) { try { response = await transport(request); } catch { throw new IntegrationError(request.method === 'GET' ? 'network_error' : 'outcome_unknown'); } return parseResponse({ ...response, method: request.method }); } -module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, IntegrationError, required, segment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; +module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, MAX_WRITE_AGE, IntegrationError, required, segment, connectionSegment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; diff --git a/shared/hooks.cjs b/shared/hooks.cjs index aa53287..e240b74 100644 --- a/shared/hooks.cjs +++ b/shared/hooks.cjs @@ -24,10 +24,10 @@ function creationKey(markerKey, nonce) { if (typeof nonce !== 'string' || !NONCE.test(nonce)) throw new IntegrationError('invalid_creation_nonce'); return 'integration-create-' + createHmac('sha256', markerKey).update(nonce).digest('hex'); } -function owns(hook, auth, url, group, subscriptionKey, recordedMarker) { +function owns(hook, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes) { const marker = (recordedMarker || identity(auth, group, subscriptionKey).name).toLowerCase(); - const types = events[group].types; - return hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && + const types = cleanupTypes || events[group]?.types; + return types && hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && Array.isArray(hook.headers) && hook.headers.some(h => h.name.toLowerCase() === marker) && Array.isArray(hook.eventTypes) && hook.eventTypes.length === types.length && types.every(t => hook.eventTypes.includes(t)); } @@ -88,15 +88,14 @@ async function subscribe(auth, url, group, subscriptionKey, transport, provider, throw new IntegrationError('subscription_receipt_requires_reconciliation'); } function creation(url, group, subscriptionKey) { - return { nonce: randomUUID(), url: callback(url), group, subscriptionKey }; + return { nonce: randomUUID(), url: callback(url), group, subscriptionKey, startedAt: new Date().toISOString() }; } // Store: provider-private { get(), set(value) } for this trigger's pending creation. async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (!pending || pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce)) { - pending = creation(target, group, subscriptionKey); - } + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); let owned; @@ -110,12 +109,23 @@ async function activate(auth, url, group, subscriptionKey, transport, provider, return owned; } async function unsubscribe(auth, id, url, group, subscriptionKey, transport, provider, recordedMarker) { + // Cleanup only: the accepted pre-rename trigger stored this exact group and + // filter set. It never enters registration, authentication or event emission. + let cleanupTypes; + if (group === 'numberState') { + required(subscriptionKey, 'subscription_key'); + if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); + const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); + const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); + if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; + } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; let hook; try { hook = (await call(auth, transport, provider, 'GET', path)).data; } catch (error) { if (error.status === 404) return; throw error; } // Disabled hooks remain owned and may be deleted; all other ownership checks still apply. - if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); + if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes)) throw new IntegrationError('subscription_ownership_mismatch'); await call(auth, transport, provider, 'DELETE', path, undefined, `integration-delete-${id}`); } function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = ['']) { diff --git a/tests/connection-migration-regressions.test.cjs b/tests/connection-migration-regressions.test.cjs new file mode 100644 index 0000000..7911a56 --- /dev/null +++ b/tests/connection-migration-regressions.test.cjs @@ -0,0 +1,82 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { readFileSync } = require('node:fs'); +const { createHmac } = require('node:crypto'); +const vm = require('node:vm'); +const core = require('../shared/core.cjs'); +const hooks = require('../shared/hooks.cjs'); +const { auth, server } = require('./fake-webhooks.cjs'); +const now = Date.parse('2026-11-01T12:00:00Z'); +const input = { connection: 'sales.eu', recipientType: 'id', recipient: '739182640518204', text: 'Synthetic', idempotencyKey: 'synthetic-write', writeCreatedAt: new Date(now - 54 * 60_000).toISOString() }; +function field(items, ...path) { + let result; + for (const name of path) { + result = items.find(item => item.name === name); + assert.ok(result, `missing Make output ${path.join('.')}`); + items = result.type === 'array' ? result.spec?.spec : result.spec; + } + return result; +} +test('messaging retries stop before the API one-hour receipt expires', () => { + core.buildRequest('sendText', { ...input, connection: 'support' }, auth, 'test', now); + for (const minutes of [55, 60, 120]) assert.throws(() => core.buildRequest('sendText', { ...input, connection: 'support', writeCreatedAt: new Date(now - minutes * 60_000).toISOString() }, auth, 'test', now), e => e.code === 'write_requires_reconciliation'); +}); +test('only Connection selectors accept the canonical dotted name and 64-character boundary', () => { + for (const connection of ['sales.eu', 'a', 'a'.repeat(64)]) { + assert.ok(core.buildRequest('sendText', { ...input, connection }, auth, 'test', now).url.endsWith(`/messaging/${connection}/messages/send`)); + assert.ok(core.buildRequest('apiRequest', { ...input, method: 'POST', path: `/messaging/${connection}/messages/send`, requestBody: { content: { text: 'Synthetic' } } }, auth, 'test', now)); + } + for (const connection of ['..', '.hidden', 'a'.repeat(65), 'sales/eu', 'sales%2Feu', 'sales\\eu']) assert.throws(() => core.buildRequest('sendText', { ...input, connection }, auth, 'test', now)); + assert.throws(() => core.buildRequest('listConnections', {}, { ...auth, projectId: 'project.eu' })); +}); +test('Make mapping exposes only the projected envelope and includes nested native message outputs', () => { + for (const name of ['messageReceived', 'messageState', 'connectionState', 'callEnded']) { + const items = JSON.parse(readFileSync(`make/modules/${name}/interface.json`)); + assert.deepEqual(items.map(item => item.name).sort(), ['connection', 'event', 'externalId', 'id', 'payload', 'timestamp']); + } + const received = JSON.parse(readFileSync('make/modules/messageReceived/interface.json')); + for (const key of ['fileName', 'stickerType']) field(received, 'payload', 'stickerPack', 'items', key); + const sent = JSON.parse(readFileSync('make/modules/sendText/interface.json')); + field(sent, 'data', 'content', 'buttons', 'media'); + field(sent, 'data', 'content', 'stickerPack', 'items', 'fileName'); +}); +test('Make uses the same dotted Connection validation and bounded retry policy', () => { + const iml = {}; + for (const name of ['polymorfaBody', 'polymorfaAdvanced', 'polymorfaRequest']) iml[name] = vm.runInNewContext(`(${readFileSync(`make/functions/${name}.js`, 'utf8')})`, { Buffer, iml }); + const p = { ...input, writeCreatedAt: new Date(Date.now() - 54 * 60_000).toISOString() }; + assert.equal(iml.polymorfaRequest('sendText', p, auth).url, 'https://api.polymorfa.com/messaging/sales.eu/messages/send'); + assert.throws(() => iml.polymorfaRequest('sendText', { ...p, writeCreatedAt: new Date(Date.now() - 60 * 60_000).toISOString() }, auth), e => e.code === 'write_requires_reconciliation'); +}); +test('retained Number trigger receipts can only remove their exact owned legacy webhook', async () => { + const s = server(); const url = 'https://example.com/synthetic'; const key = 'source-1'; + const scope = JSON.stringify(['polymorfa-webhook-v1', auth.projectId, 'numberState', key]); + const marker = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', auth.apiKey).update('marker:' + scope).digest('hex').slice(0, 24); + const owned = { id: 'retained', owner: 'project', projectId: auth.projectId, url, enabled: false, format: 'native', headers: [{ name: marker }], eventTypes: ['session.status', 'session.connected', 'session.logged_out'] }; + s.rows.push(owned); + await assert.rejects(hooks.unsubscribe(auth, owned.id, url, 'numberState', 'different-key', s.transport, 'test', marker), e => e.code === 'subscription_ownership_mismatch'); + assert.equal(s.rows.length, 1); + await hooks.unsubscribe(auth, owned.id, url, 'numberState', key, s.transport, 'test', marker); + assert.equal(s.rows.length, 0); + assert.throws(() => hooks.identity(auth, 'numberState', key), e => e.code === 'invalid_event_group'); +}); +test('Pipedream preserves unresolved legacy activation state when deactivation cannot prove an owned ID', async () => { + const { default: source } = await import('../pipedream/sources/connectionState/connectionState.mjs'); + const pending = { nonce: '11111111-1111-4111-8111-111111111111', group: 'numberState', url: 'https://example.com/synthetic', subscriptionKey: 'source-1' }; + const values = new Map([['pendingCreation', pending]]); + const context = { db: { get: key => values.get(key), set: (key, value) => values.set(key, value) }, polymorfa: { unsubscribe: () => { throw new Error('must not dispatch'); } } }; + await assert.rejects(source.hooks.deactivate.call(context), e => e.code === 'subscription_requires_reconciliation'); + assert.deepEqual(values.get('pendingCreation'), pending); + const store = { get: () => pending, set: () => { throw new Error('must not replace uncertain nonce'); } }; + await assert.rejects(hooks.activate(auth, pending.url, 'connectionState', pending.subscriptionKey, () => { throw new Error('must not dispatch'); }, 'test', store), e => e.code === 'subscription_requires_reconciliation'); +}); + +test('expired or unknown webhook activation age preserves its original identity without dispatch', async () => { + for (const startedAt of [undefined, 'invalid', new Date(Date.now() - 24 * 60 * 60_000).toISOString()]) { + const pending = { nonce: '11111111-1111-4111-8111-111111111111', group: 'messageReceived', url: 'https://example.com/synthetic', subscriptionKey: 'source-1', startedAt }; + const before = JSON.stringify(pending); + let called = false; + await assert.rejects(hooks.activate(auth, pending.url, pending.group, pending.subscriptionKey, () => { called = true; }, 'test', { get: () => pending, set: () => { throw new Error('must preserve pending'); } }), e => e.code === 'subscription_requires_reconciliation'); + assert.equal(called, false); assert.equal(JSON.stringify(pending), before); + } +}); diff --git a/tests/hooks.test.cjs b/tests/hooks.test.cjs index 8ba645b..627006d 100644 --- a/tests/hooks.test.cjs +++ b/tests/hooks.test.cjs @@ -148,8 +148,10 @@ test('creation keys require an adapter nonce and a pending nonce is bound to its await assert.rejects(hooks.subscribe(auth, url, 'messageReceived', key, async () => ({ status: 200, body: { data: [], page: {} } }), 'test'), e => e.code === 'invalid_creation_nonce'); const s = server(); const store = memory(); store.set({ nonce: NONCE, url: 'https://other.example/hook', group: 'messageReceived', subscriptionKey: key }); - await hooks.activate(auth, url, 'messageReceived', key, s.transport, 'test', store); - assert.notEqual(s.posts()[0].headers['Idempotency-Key'], hooks.creationKey(hooks.identity(auth, 'messageReceived', key).key, NONCE)); + const pending = store.peek(); + await assert.rejects(hooks.activate(auth, url, 'messageReceived', key, s.transport, 'test', store), e => e.code === 'subscription_requires_reconciliation'); + assert.deepEqual(store.peek(), pending); + assert.equal(s.posts().length, 0); }); test('uncertain creation errors keep reconcile guidance even when the server sends an error code', async () => { diff --git a/tests/public-projection.test.mjs b/tests/public-projection.test.mjs new file mode 100644 index 0000000..f60e401 --- /dev/null +++ b/tests/public-projection.test.mjs @@ -0,0 +1,16 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { projectContract } from '../scripts/sync-api-contracts.mjs'; +const coverage = { operations: { listConnections: { contract: 'platform', path: '/platform/connections', method: 'GET' } } }; +function fixture() { return { openapi: '3.0.0', info: { title: 'Synthetic', version: '2026-09-22' }, paths: { '/platform/connections': { get: { operationId: 'listConnections', security: [{ ApiKeyAuth: [] }], responses: { 200: { content: { 'application/json': { schema: { $ref: '#/components/schemas/Connection' } } } } } } }, '/console/private': { get: { operationId: 'private' } } }, components: { schemas: { Connection: { type: 'object', properties: { id: { type: 'string' } } }, Private: { type: 'object' } }, securitySchemes: { ApiKeyAuth: { type: 'apiKey', in: 'header', name: 'Authorization' } } } }; } +test('public projection retains referenced authentication without importing private operations or unreachable schemas', () => { + const source = fixture(); const result = projectContract(source, 'platform', coverage, []); + assert.deepEqual(result.components.securitySchemes, source.components.securitySchemes); + assert.deepEqual(Object.keys(result.paths), ['/platform/connections']); + assert.deepEqual(Object.keys(result.components.schemas), ['Connection']); + assert.deepEqual(result.paths['/platform/connections'].get, source.paths['/platform/connections'].get); +}); +test('unresolved security requirements refuse generation', () => { + const source = fixture(); delete source.components.securitySchemes; + assert.throws(() => projectContract(source, 'platform', coverage, []), /Missing public component securitySchemes\/ApiKeyAuth/); +}); diff --git a/zapier/shared/catalog.cjs b/zapier/shared/catalog.cjs index e8d0221..0072bee 100644 --- a/zapier/shared/catalog.cjs +++ b/zapier/shared/catalog.cjs @@ -28,7 +28,7 @@ const fields = { messageId: { label: 'Message ID', required: true }, reaction: { label: 'Reaction', help: 'An emoji. Leave empty to remove the reaction.' }, idempotencyKey: { label: 'Idempotency Key', help: 'Required for writes. Map a stable business key unique to this write. Preserve it across retries.' }, - writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes older than 23 hours require reconciliation.' }, + writeCreatedAt: { label: 'Write Started At', help: 'Required for writes. ISO timestamp saved when this logical write first began. Preserve it across retries; writes at least 55 minutes old require reconciliation.' }, projectSlug: { label: 'Project Slug', required: true }, method: { label: 'Method', required: true, options: { GET: 'GET', POST: 'POST' }, default: 'GET' }, path: { label: 'Path', required: true, help: 'A supported relative public API path, for example /platform/connections. External hosts and credential operations are refused.' }, diff --git a/zapier/shared/core.cjs b/zapier/shared/core.cjs index c2302db..5f48e35 100644 --- a/zapier/shared/core.cjs +++ b/zapier/shared/core.cjs @@ -4,7 +4,7 @@ const ORIGIN = 'https://api.polymorfa.com'; const VERSION = '2026-09-22'; const MAX_MEDIA_BYTES = 4 * 1024 * 1024; -const MAX_WRITE_AGE = 23 * 60 * 60 * 1000; +const MAX_WRITE_AGE = 55 * 60 * 1000; class IntegrationError extends Error { constructor(code, status = 0, requestId, retryAfter, write = false) { // A write that ended in a server error or is still running has an uncertain outcome, whatever its code. @@ -25,6 +25,10 @@ function segment(value, name) { if (!/^[A-Za-z0-9_-]{1,256}$/.test(value)) throw new IntegrationError(`invalid_${name}`); return value; } +function connectionSegment(value) { + if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + return encodeURIComponent(value); +} function object(value, name) { let parsed = value; try { if (typeof value === 'string') parsed = JSON.parse(value); } catch { throw new IntegrationError(`invalid_${name}_json`); } @@ -93,7 +97,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9_-]+\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { @@ -104,7 +108,7 @@ function advanced(p, auth) { } function buildRequest(action, p, auth, provider = 'integration', now) { let r; - if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${segment(p.connection, 'connection')}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; + if (['sendText', 'sendTemplate', 'sendMedia', 'react'].includes(action)) r = { method: 'POST', url: `${ORIGIN}/messaging/${connectionSegment(p.connection)}/messages/${action === 'react' ? 'react' : 'send'}`, body: messageBody(action, p) }; else if (action === 'listConnections') r = { method: 'GET', url: ORIGIN + '/platform/connections', query: { projectId: auth.projectId } }; else if (action === 'listTemplates') r = { method: 'GET', url: `${ORIGIN}/messaging/projects/${segment(p.projectSlug, 'project_slug')}/templates` }; else if (action === 'apiRequest') r = advanced(p, auth); @@ -135,4 +139,4 @@ async function execute(action, p, auth, transport, provider, now) { try { response = await transport(request); } catch { throw new IntegrationError(request.method === 'GET' ? 'network_error' : 'outcome_unknown'); } return parseResponse({ ...response, method: request.method }); } -module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, IntegrationError, required, segment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; +module.exports = { ORIGIN, VERSION, MAX_MEDIA_BYTES, MAX_WRITE_AGE, IntegrationError, required, segment, connectionSegment, object, conversation, advanced, headers, writeHeaders, messageBody, buildRequest, parseResponse, execute }; diff --git a/zapier/shared/hooks.cjs b/zapier/shared/hooks.cjs index 4818f39..2130449 100644 --- a/zapier/shared/hooks.cjs +++ b/zapier/shared/hooks.cjs @@ -25,10 +25,10 @@ function creationKey(markerKey, nonce) { if (typeof nonce !== 'string' || !NONCE.test(nonce)) throw new IntegrationError('invalid_creation_nonce'); return 'integration-create-' + createHmac('sha256', markerKey).update(nonce).digest('hex'); } -function owns(hook, auth, url, group, subscriptionKey, recordedMarker) { +function owns(hook, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes) { const marker = (recordedMarker || identity(auth, group, subscriptionKey).name).toLowerCase(); - const types = events[group].types; - return hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && + const types = cleanupTypes || events[group]?.types; + return types && hook && hook.owner === 'project' && hook.projectId === auth.projectId && sameCallback(hook.url, url) && hook.format === 'native' && hook.enabled === true && Array.isArray(hook.headers) && hook.headers.some(h => h.name.toLowerCase() === marker) && Array.isArray(hook.eventTypes) && hook.eventTypes.length === types.length && types.every(t => hook.eventTypes.includes(t)); } @@ -89,15 +89,14 @@ async function subscribe(auth, url, group, subscriptionKey, transport, provider, throw new IntegrationError('subscription_receipt_requires_reconciliation'); } function creation(url, group, subscriptionKey) { - return { nonce: randomUUID(), url: callback(url), group, subscriptionKey }; + return { nonce: randomUUID(), url: callback(url), group, subscriptionKey, startedAt: new Date().toISOString() }; } // Store: provider-private { get(), set(value) } for this trigger's pending creation. async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (!pending || pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce)) { - pending = creation(target, group, subscriptionKey); - } + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); let owned; @@ -111,12 +110,23 @@ async function activate(auth, url, group, subscriptionKey, transport, provider, return owned; } async function unsubscribe(auth, id, url, group, subscriptionKey, transport, provider, recordedMarker) { + // Cleanup only: the accepted pre-rename trigger stored this exact group and + // filter set. It never enters registration, authentication or event emission. + let cleanupTypes; + if (group === 'numberState') { + required(subscriptionKey, 'subscription_key'); + if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); + const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); + const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); + if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; + } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; let hook; try { hook = (await call(auth, transport, provider, 'GET', path)).data; } catch (error) { if (error.status === 404) return; throw error; } // Disabled hooks remain owned and may be deleted; all other ownership checks still apply. - if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); + if (!owns({ ...hook, enabled: true }, auth, url, group, subscriptionKey, recordedMarker, cleanupTypes)) throw new IntegrationError('subscription_ownership_mismatch'); await call(auth, transport, provider, 'DELETE', path, undefined, `integration-delete-${id}`); } function authenticate(auth, group, subscriptionKey, incomingHeaders, prefixes = ['']) { From e3dad207434cf96ae1becded62bce9b54b8f9e49 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 08:52:05 +0200 Subject: [PATCH 4/9] Repair reviewed Connection hook recovery and bind checked consumers --- README.md | 12 +++-- contracts/sdk-baseline.json | 2 +- contracts/source.json | 4 +- make/functions/polymorfaAdvanced.js | 2 +- make/functions/polymorfaRequest.js | 2 +- n8n/shared/core.js | 4 +- n8n/shared/hooks.js | 17 +++++-- pipedream/common/core.cjs | 4 +- pipedream/common/hooks.cjs | 17 +++++-- scripts/sync-api-contracts.mjs | 5 +- shared/core.cjs | 4 +- shared/hooks.cjs | 17 +++++-- .../connection-migration-regressions.test.cjs | 8 +-- tests/contract-sync.test.mjs | 30 +++++++++++ tests/review-regressions.test.cjs | 50 +++++++++++++++++++ zapier/shared/core.cjs | 4 +- zapier/shared/hooks.cjs | 17 +++++-- 17 files changed, 161 insertions(+), 38 deletions(-) create mode 100644 tests/contract-sync.test.mjs create mode 100644 tests/review-regressions.test.cjs diff --git a/README.md b/README.md index 8473ffe..f30f74a 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,11 @@ one-hour receipt expires. Preserve the original write key and start time when reconciling an uncertain result. Trigger cleanup may remove an exactly owned pre-rename webhook. It does not -register or emit retired event names. An unresolved activation keeps its nonce -and start time; a changed target or expired receipt needs reconciliation before -another creation. These source changes do not establish provider publication or -installed-platform acceptance. +register or emit retired event names. Cleanup checks the saved marker against +the live project, callback and event filters, including after token rotation. +An unresolved activation keeps its nonce and start time. After its creation +receipt expires, activating again only looks for the existing owned webhook. +If found, it records that webhook without another POST; it can then be +deactivated normally. Missing, changed or ambiguous inventory stays blocked for +reconciliation. A changed target never starts another creation. These source +changes do not establish provider publication or installed-platform acceptance. diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index cb3d547..d66c55d 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,5 +1,5 @@ { - "source": "fea8a591514b18a386d66347b71baff88d8604ba", + "source": "d9fe38300db8021ed4930106cf2e98ae796c7e30", "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", "fragments": { "messaging": { diff --git a/contracts/source.json b/contracts/source.json index c5a672e..6e0c033 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,9 +1,9 @@ { "apiVersion": "2026-09-22", - "apiSource": "a7cab53684b989b1ce68882989d31e2277841bdc", + "apiSource": "20b482dfe31dbe88e624682c90669a61f9a2b5a6", "sdk": { "repository": "polymorfa/sdks", - "source": "fea8a591514b18a386d66347b71baff88d8604ba", + "source": "d9fe38300db8021ed4930106cf2e98ae796c7e30", "publishedPackage": null }, "specs": { diff --git a/make/functions/polymorfaAdvanced.js b/make/functions/polymorfaAdvanced.js index e0249d2..7e5497f 100644 --- a/make/functions/polymorfaAdvanced.js +++ b/make/functions/polymorfaAdvanced.js @@ -26,7 +26,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9._-]{1,64}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { diff --git a/make/functions/polymorfaRequest.js b/make/functions/polymorfaRequest.js index 0e0ae60..69ae686 100644 --- a/make/functions/polymorfaRequest.js +++ b/make/functions/polymorfaRequest.js @@ -21,7 +21,7 @@ function segment(value, name) { return value; } function connectionSegment(value) { - if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + if (typeof value !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(value) || value === '.' || value === '..') throw new IntegrationError('invalid_connection'); return encodeURIComponent(value); } function headers(auth, provider) { diff --git a/n8n/shared/core.js b/n8n/shared/core.js index 5f48e35..fe13632 100644 --- a/n8n/shared/core.js +++ b/n8n/shared/core.js @@ -26,7 +26,7 @@ function segment(value, name) { return value; } function connectionSegment(value) { - if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + if (typeof value !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(value) || value === '.' || value === '..') throw new IntegrationError('invalid_connection'); return encodeURIComponent(value); } function object(value, name) { @@ -97,7 +97,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9._-]{1,64}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { diff --git a/n8n/shared/hooks.js b/n8n/shared/hooks.js index c7e5aff..ec21513 100644 --- a/n8n/shared/hooks.js +++ b/n8n/shared/hooks.js @@ -95,7 +95,16 @@ function creation(url, group, subscriptionKey) { async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000) { + // Expiry forbids another create, but a read may prove the original effect. + // Missing, changed or ambiguous inventory never clears an uncertain nonce. + const existing = await find(auth, target, group, subscriptionKey, transport, provider); + if (!existing) throw new IntegrationError('subscription_requires_reconciliation'); + const owned = { id: existing.id, url: target, group, subscriptionKey, markerName: identity(auth, group, subscriptionKey).name }; + await store.set(null); + return owned; + } if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); @@ -116,9 +125,9 @@ async function unsubscribe(auth, id, url, group, subscriptionKey, transport, pro if (group === 'numberState') { required(subscriptionKey, 'subscription_key'); if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); - const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); - const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); - if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + // Like current-group cleanup, ownership comes from the private receipt and + // the live project/callback/filter/header checks, even after token rotation. + if (typeof recordedMarker !== 'string' || !/^X-Polymorfa-Integration-Token-[a-f0-9]{24}$/i.test(recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; diff --git a/pipedream/common/core.cjs b/pipedream/common/core.cjs index 5f48e35..fe13632 100644 --- a/pipedream/common/core.cjs +++ b/pipedream/common/core.cjs @@ -26,7 +26,7 @@ function segment(value, name) { return value; } function connectionSegment(value) { - if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + if (typeof value !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(value) || value === '.' || value === '..') throw new IntegrationError('invalid_connection'); return encodeURIComponent(value); } function object(value, name) { @@ -97,7 +97,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9._-]{1,64}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { diff --git a/pipedream/common/hooks.cjs b/pipedream/common/hooks.cjs index 2130449..ca8435a 100644 --- a/pipedream/common/hooks.cjs +++ b/pipedream/common/hooks.cjs @@ -95,7 +95,16 @@ function creation(url, group, subscriptionKey) { async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000) { + // Expiry forbids another create, but a read may prove the original effect. + // Missing, changed or ambiguous inventory never clears an uncertain nonce. + const existing = await find(auth, target, group, subscriptionKey, transport, provider); + if (!existing) throw new IntegrationError('subscription_requires_reconciliation'); + const owned = { id: existing.id, url: target, group, subscriptionKey, markerName: identity(auth, group, subscriptionKey).name }; + await store.set(null); + return owned; + } if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); @@ -116,9 +125,9 @@ async function unsubscribe(auth, id, url, group, subscriptionKey, transport, pro if (group === 'numberState') { required(subscriptionKey, 'subscription_key'); if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); - const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); - const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); - if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + // Like current-group cleanup, ownership comes from the private receipt and + // the live project/callback/filter/header checks, even after token rotation. + if (typeof recordedMarker !== 'string' || !/^X-Polymorfa-Integration-Token-[a-f0-9]{24}$/i.test(recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; diff --git a/scripts/sync-api-contracts.mjs b/scripts/sync-api-contracts.mjs index 9debe3a..f938942 100644 --- a/scripts/sync-api-contracts.mjs +++ b/scripts/sync-api-contracts.mjs @@ -50,15 +50,18 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) const source = JSON.parse(readFileSync('contracts/source.json')); const coverage = JSON.parse(readFileSync('contracts/coverage.json')); const events = Object.values(require('../shared/catalog.cjs').events).flatMap(event => event.types); + const snapshots = []; for (const [kind, pin] of Object.entries(source.specs)) { const bytes = execFileSync('git', ['-C', value('--api-root'), 'show', `${sourceSha}:${pin.publicSourcePath}`], { maxBuffer: 32 * 1024 * 1024 }); const spec = JSON.parse(bytes); const projected = projectContract(spec, kind, coverage, events); const snapshot = JSON.stringify(projected, null, 2) + '\n'; - writeFileSync(pin.snapshot, snapshot); + snapshots.push([pin.snapshot, snapshot]); pin.publicSourceSha256 = createHash('sha256').update(bytes).digest('hex'); pin.sha256 = createHash('sha256').update(snapshot).digest('hex'); } source.apiSource = sourceSha; + // A validation failure in any spec must leave every existing file untouched. + for (const [path, snapshot] of snapshots) writeFileSync(path, snapshot); writeFileSync('contracts/source.json', JSON.stringify(source, null, 2) + '\n'); console.log(`Projected nine covered public operations from ${sourceSha}. SDK binding and release acceptance remain separate.`); } diff --git a/shared/core.cjs b/shared/core.cjs index 3bcd2db..937458e 100644 --- a/shared/core.cjs +++ b/shared/core.cjs @@ -25,7 +25,7 @@ function segment(value, name) { return value; } function connectionSegment(value) { - if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + if (typeof value !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(value) || value === '.' || value === '..') throw new IntegrationError('invalid_connection'); return encodeURIComponent(value); } function object(value, name) { @@ -96,7 +96,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9._-]{1,64}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { diff --git a/shared/hooks.cjs b/shared/hooks.cjs index e240b74..58d79b4 100644 --- a/shared/hooks.cjs +++ b/shared/hooks.cjs @@ -94,7 +94,16 @@ function creation(url, group, subscriptionKey) { async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000) { + // Expiry forbids another create, but a read may prove the original effect. + // Missing, changed or ambiguous inventory never clears an uncertain nonce. + const existing = await find(auth, target, group, subscriptionKey, transport, provider); + if (!existing) throw new IntegrationError('subscription_requires_reconciliation'); + const owned = { id: existing.id, url: target, group, subscriptionKey, markerName: identity(auth, group, subscriptionKey).name }; + await store.set(null); + return owned; + } if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); @@ -115,9 +124,9 @@ async function unsubscribe(auth, id, url, group, subscriptionKey, transport, pro if (group === 'numberState') { required(subscriptionKey, 'subscription_key'); if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); - const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); - const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); - if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + // Like current-group cleanup, ownership comes from the private receipt and + // the live project/callback/filter/header checks, even after token rotation. + if (typeof recordedMarker !== 'string' || !/^X-Polymorfa-Integration-Token-[a-f0-9]{24}$/i.test(recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; diff --git a/tests/connection-migration-regressions.test.cjs b/tests/connection-migration-regressions.test.cjs index 7911a56..4226881 100644 --- a/tests/connection-migration-regressions.test.cjs +++ b/tests/connection-migration-regressions.test.cjs @@ -27,7 +27,7 @@ test('only Connection selectors accept the canonical dotted name and 64-characte assert.ok(core.buildRequest('sendText', { ...input, connection }, auth, 'test', now).url.endsWith(`/messaging/${connection}/messages/send`)); assert.ok(core.buildRequest('apiRequest', { ...input, method: 'POST', path: `/messaging/${connection}/messages/send`, requestBody: { content: { text: 'Synthetic' } } }, auth, 'test', now)); } - for (const connection of ['..', '.hidden', 'a'.repeat(65), 'sales/eu', 'sales%2Feu', 'sales\\eu']) assert.throws(() => core.buildRequest('sendText', { ...input, connection }, auth, 'test', now)); + for (const connection of ['.', '..', 'a'.repeat(65), 'sales/eu', 'sales%2Feu', 'sales\\eu']) assert.throws(() => core.buildRequest('sendText', { ...input, connection }, auth, 'test', now)); assert.throws(() => core.buildRequest('listConnections', {}, { ...auth, projectId: 'project.eu' })); }); test('Make mapping exposes only the projected envelope and includes nested native message outputs', () => { @@ -54,7 +54,7 @@ test('retained Number trigger receipts can only remove their exact owned legacy const marker = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', auth.apiKey).update('marker:' + scope).digest('hex').slice(0, 24); const owned = { id: 'retained', owner: 'project', projectId: auth.projectId, url, enabled: false, format: 'native', headers: [{ name: marker }], eventTypes: ['session.status', 'session.connected', 'session.logged_out'] }; s.rows.push(owned); - await assert.rejects(hooks.unsubscribe(auth, owned.id, url, 'numberState', 'different-key', s.transport, 'test', marker), e => e.code === 'subscription_ownership_mismatch'); + await assert.rejects(hooks.unsubscribe(auth, owned.id, url, 'numberState', key, s.transport, 'test', marker.slice(0, -1) + (marker.endsWith('0') ? '1' : '0')), e => e.code === 'subscription_ownership_mismatch'); assert.equal(s.rows.length, 1); await hooks.unsubscribe(auth, owned.id, url, 'numberState', key, s.transport, 'test', marker); assert.equal(s.rows.length, 0); @@ -71,8 +71,8 @@ test('Pipedream preserves unresolved legacy activation state when deactivation c await assert.rejects(hooks.activate(auth, pending.url, 'connectionState', pending.subscriptionKey, () => { throw new Error('must not dispatch'); }, 'test', store), e => e.code === 'subscription_requires_reconciliation'); }); -test('expired or unknown webhook activation age preserves its original identity without dispatch', async () => { - for (const startedAt of [undefined, 'invalid', new Date(Date.now() - 24 * 60 * 60_000).toISOString()]) { +test('unknown webhook activation age preserves its original identity without dispatch', async () => { + for (const startedAt of [undefined, 'invalid']) { const pending = { nonce: '11111111-1111-4111-8111-111111111111', group: 'messageReceived', url: 'https://example.com/synthetic', subscriptionKey: 'source-1', startedAt }; const before = JSON.stringify(pending); let called = false; diff --git a/tests/contract-sync.test.mjs b/tests/contract-sync.test.mjs new file mode 100644 index 0000000..2ad167c --- /dev/null +++ b/tests/contract-sync.test.mjs @@ -0,0 +1,30 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +test('a later invalid public spec cannot partially replace contract snapshots or their manifest', () => { + const root = resolve(homedir(), '.polymorfa-agent-work/connections-rename-20261114/integrations/contract-sync-tests'); + mkdirSync(root, { recursive: true }); + const work = mkdtempSync(join(root, 'validation-')); + const api = join(work, 'api'); mkdirSync(api); mkdirSync(join(work, 'contracts')); + const valid = { openapi: '3.0.0', info: { title: 'Synthetic', version: '2026-09-22' }, paths: { '/messages': { post: { operationId: 'sendText', responses: {} } } }, components: { schemas: {} } }; + writeFileSync(join(api, 'messaging.json'), JSON.stringify(valid)); + writeFileSync(join(api, 'platform.json'), JSON.stringify({ ...valid, paths: {} })); + execFileSync('git', ['init', '-q', api]); execFileSync('git', ['-C', api, 'add', '.']); + execFileSync('git', ['-C', api, '-c', 'user.name=Synthetic fixture', '-c', 'user.email=fixture@example.invalid', '-c', 'commit.gpgsign=false', 'commit', '-qm', 'Synthetic source']); + const sha = execFileSync('git', ['-C', api, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim(); + const specs = Object.fromEntries(['messaging', 'platform'].map(kind => [kind, { publicSourcePath: `${kind}.json`, snapshot: `contracts/openapi.${kind}.json`, sha256: 'old-snapshot-hash', publicSourceSha256: 'old-source-hash' }])); + writeFileSync(join(work, 'contracts/source.json'), JSON.stringify({ apiSource: 'old-source', specs })); + writeFileSync(join(work, 'contracts/coverage.json'), JSON.stringify({ operations: { sendText: { contract: 'messaging', path: '/messages', method: 'POST' }, listConnections: { contract: 'platform', path: '/platform/connections', method: 'GET' } } })); + for (const kind of ['messaging', 'platform']) writeFileSync(join(work, `contracts/openapi.${kind}.json`), `unchanged-${kind}`); + const files = ['source.json', 'openapi.messaging.json', 'openapi.platform.json']; + const before = files.map(name => readFileSync(join(work, 'contracts', name), 'utf8')); + const script = fileURLToPath(new URL('../scripts/sync-api-contracts.mjs', import.meta.url)); + const result = spawnSync(process.execPath, [script, '--api-root', api, '--source', sha], { cwd: work, encoding: 'utf8' }); + assert.notEqual(result.status, 0); assert.match(result.stderr, /Missing covered public operation listConnections/); + assert.deepEqual(files.map(name => readFileSync(join(work, 'contracts', name), 'utf8')), before); +}); diff --git a/tests/review-regressions.test.cjs b/tests/review-regressions.test.cjs new file mode 100644 index 0000000..0af96fd --- /dev/null +++ b/tests/review-regressions.test.cjs @@ -0,0 +1,50 @@ +'use strict'; +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const { createHmac } = require('node:crypto'); +const core = require('../shared/core.cjs'); +const hooks = require('../shared/hooks.cjs'); +const { auth, server } = require('./fake-webhooks.cjs'); + +test('Connection selectors can start with an underscore, hyphen or non-traversal dot', () => { + const input = { recipientType: 'id', recipient: '739182640518204', text: 'Synthetic', idempotencyKey: 'synthetic-write', writeCreatedAt: new Date().toISOString() }; + for (const connection of ['_tenant', '-tenant', '.tenant']) { + assert.equal(core.buildRequest('sendText', { ...input, connection }, auth).url, `https://api.polymorfa.com/messaging/${connection}/messages/send`); + assert.equal(core.buildRequest('apiRequest', { ...input, method: 'POST', path: `/messaging/${connection}/messages/send`, requestBody: { content: { text: 'Synthetic' } } }, auth).url, `https://api.polymorfa.com/messaging/${connection}/messages/send`); + } + for (const connection of ['.', '..', 'sales/eu', 'sales%2Feu', 'sales\\eu', 'a'.repeat(65)]) assert.throws(() => core.connectionSegment(connection)); +}); + +test('an expired pending create recovers the proven live webhook without another POST', async () => { + const s = server(); let pending; + const store = { get: () => pending, set: value => { pending = value; } }; + const url = 'https://example.com/synthetic'; + s.loseNextCreate(); s.hideNewest(2); + await assert.rejects(hooks.activate(auth, url, 'messageReceived', 'source-1', s.transport, 'test', store), e => e.code === 'subscription_requires_reconciliation'); + pending.startedAt = new Date(Date.now() - 24 * 60 * 60_000).toISOString(); + const originalNonce = pending.nonce; + const owned = await hooks.activate(auth, url, 'messageReceived', 'source-1', s.transport, 'test', store); + assert.equal(owned.id, s.rows[0].id); assert.equal(s.posts().length, 1); assert.equal(pending, null); + assert.ok(originalNonce); + await hooks.unsubscribe(auth, owned.id, owned.url, owned.group, owned.subscriptionKey, s.transport, 'test', owned.markerName); + assert.equal(s.rows.length, 0); +}); + +test('an expired pending create with no proven live webhook stays closed after its read-only lookup', async () => { + const s = server(); const pending = { nonce: '11111111-1111-4111-8111-111111111111', group: 'messageReceived', url: 'https://example.com/synthetic', subscriptionKey: 'source-1', startedAt: new Date(Date.now() - 24 * 60 * 60_000).toISOString() }; + const before = JSON.stringify(pending); + await assert.rejects(hooks.activate(auth, pending.url, pending.group, pending.subscriptionKey, s.transport, 'test', { get: () => pending, set: () => assert.fail('must preserve unresolved receipt') }), e => e.code === 'subscription_requires_reconciliation'); + assert.equal(s.posts().length, 0); assert.equal(s.calls.length, 1); assert.equal(s.calls[0].method, 'GET'); assert.equal(JSON.stringify(pending), before); +}); + +test('retained Number-state cleanup uses the exact stored marker after token rotation', async () => { + const s = server(); const key = 'source-1'; const url = 'https://example.com/synthetic'; + const scope = JSON.stringify(['polymorfa-webhook-v1', auth.projectId, 'numberState', key]); + const marker = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', 'synthetic-previous-token').update('marker:' + scope).digest('hex').slice(0, 24); + const row = { id: 'retained', owner: 'project', projectId: auth.projectId, url, enabled: false, format: 'native', headers: [{ name: marker }], eventTypes: ['session.status', 'session.connected', 'session.logged_out'] }; + s.rows.push(row); + for (const invalid of [undefined, '', 'X-Other', marker.slice(0, -1) + (marker.endsWith('0') ? '1' : '0')]) await assert.rejects(hooks.unsubscribe(auth, row.id, url, 'numberState', key, s.transport, 'test', invalid), e => e.code === 'subscription_ownership_mismatch'); + assert.equal(s.rows.length, 1); + await hooks.unsubscribe(auth, row.id, url, 'numberState', key, s.transport, 'test', marker); + assert.equal(s.rows.length, 0); assert.equal(s.posts().length, 0); +}); diff --git a/zapier/shared/core.cjs b/zapier/shared/core.cjs index 5f48e35..fe13632 100644 --- a/zapier/shared/core.cjs +++ b/zapier/shared/core.cjs @@ -26,7 +26,7 @@ function segment(value, name) { return value; } function connectionSegment(value) { - if (typeof value !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value)) throw new IntegrationError('invalid_connection'); + if (typeof value !== 'string' || !/^[A-Za-z0-9._-]{1,64}$/.test(value) || value === '.' || value === '..') throw new IntegrationError('invalid_connection'); return encodeURIComponent(value); } function object(value, name) { @@ -97,7 +97,7 @@ function advanced(p, auth) { if (!path.startsWith('/') || path.startsWith('//') || /[%\\?#\s]/.test(path) || path.split('/').some(x => x === '.' || x === '..')) throw new IntegrationError('unsupported_path'); const method = p.method; const allowed = (method === 'GET' && (path === '/platform/connections' || /^\/messaging\/projects\/[A-Za-z0-9_-]+\/templates(?:\/[A-Za-z0-9_-]+)?$/.test(path))) || - (method === 'POST' && /^\/messaging\/[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/messages\/(send|react)$/.test(path)); + (method === 'POST' && /^\/messaging\/[A-Za-z0-9._-]{1,64}\/messages\/(send|react)$/.test(path)); if (!allowed) throw new IntegrationError('unsupported_operation'); const body = method === 'POST' ? object(p.requestBody, 'request_body') : undefined; if (body) { diff --git a/zapier/shared/hooks.cjs b/zapier/shared/hooks.cjs index 2130449..ca8435a 100644 --- a/zapier/shared/hooks.cjs +++ b/zapier/shared/hooks.cjs @@ -95,7 +95,16 @@ function creation(url, group, subscriptionKey) { async function activate(auth, url, group, subscriptionKey, transport, provider, store) { const target = callback(url); let pending = await store.get(); - if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000 || Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && (pending.url !== target || pending.group !== group || pending.subscriptionKey !== subscriptionKey || typeof pending.nonce !== 'string' || !NONCE.test(pending.nonce) || typeof pending.startedAt !== 'string' || !Number.isFinite(Date.parse(pending.startedAt)) || Date.parse(pending.startedAt) > Date.now() + 60_000)) throw new IntegrationError('subscription_requires_reconciliation'); + if (pending && Date.now() - Date.parse(pending.startedAt) >= 23 * 60 * 60 * 1000) { + // Expiry forbids another create, but a read may prove the original effect. + // Missing, changed or ambiguous inventory never clears an uncertain nonce. + const existing = await find(auth, target, group, subscriptionKey, transport, provider); + if (!existing) throw new IntegrationError('subscription_requires_reconciliation'); + const owned = { id: existing.id, url: target, group, subscriptionKey, markerName: identity(auth, group, subscriptionKey).name }; + await store.set(null); + return owned; + } if (!pending) pending = creation(target, group, subscriptionKey); // Save before the create so an uncertain retry of this activation sends the same key. await store.set(pending); @@ -116,9 +125,9 @@ async function unsubscribe(auth, id, url, group, subscriptionKey, transport, pro if (group === 'numberState') { required(subscriptionKey, 'subscription_key'); if (subscriptionKey.length > 200) throw new IntegrationError('subscription_ownership_mismatch'); - const scope = JSON.stringify(['polymorfa-webhook-v1', segment(auth.projectId, 'project_id'), group, subscriptionKey]); - const expected = 'X-Polymorfa-Integration-Token-' + createHmac('sha256', required(auth.apiKey, 'project_token')).update('marker:' + scope).digest('hex').slice(0, 24); - if (recordedMarker !== expected) throw new IntegrationError('subscription_ownership_mismatch'); + // Like current-group cleanup, ownership comes from the private receipt and + // the live project/callback/filter/header checks, even after token rotation. + if (typeof recordedMarker !== 'string' || !/^X-Polymorfa-Integration-Token-[a-f0-9]{24}$/i.test(recordedMarker)) throw new IntegrationError('subscription_ownership_mismatch'); cleanupTypes = ['session.status', 'session.connected', 'session.logged_out']; } else if (!events[group]) throw new IntegrationError('invalid_event_group'); const path = `/platform/projects/${segment(auth.projectId, 'project_id')}/webhooks/${segment(id, 'webhook_id')}`; From 6c45056d59cb32466d0f9cb996dc219ffbd17a36 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 09:40:11 +0200 Subject: [PATCH 5/9] Keep Make retained webhook cleanup narrowly owned --- make/functions/polymorfaOwnedHook.js | 6 +++++- scripts/generate.mjs | 2 +- tests/make.test.cjs | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/make/functions/polymorfaOwnedHook.js b/make/functions/polymorfaOwnedHook.js index 864c4bf..120ae99 100644 --- a/make/functions/polymorfaOwnedHook.js +++ b/make/functions/polymorfaOwnedHook.js @@ -2,6 +2,10 @@ function polymorfaOwnedHook(body, projectId, ownedUrl, markerName, group) { const types = {"messageReceived":["message.received"],"messageState":["message.sent","message.ack","message.failed","message.update"],"connectionState":["connection.status","connection.connected","connection.logged_out"],"callEnded":["call.ended"]}; const same = (a, b) => { try { return iml.polymorfaCallback(a) === iml.polymorfaCallback(b); } catch (error) { return false; } }; const h = body.data; -if (!h || h.owner !== 'project' || h.projectId !== projectId || !same(h.url, ownedUrl) || h.format !== 'native' || !h.headers?.some(x => x.name.toLowerCase() === markerName.toLowerCase()) || h.eventTypes?.length !== types[group]?.length || !types[group].every(t => h.eventTypes.includes(t))) throw new Error('Subscription ownership mismatch.'); +// Cleanup only. Neither registration nor event emission accepts this retired set. +const legacy = ['session.status', 'session.connected', 'session.logged_out']; +const allowed = group === 'numberState' ? [legacy] : group === 'connectionState' ? [types[group], legacy] : [types[group]]; +const matches = t => t && h?.eventTypes?.length === t.length && t.every(e => h.eventTypes.includes(e)); +if (typeof markerName !== 'string' || !/^X-Polymorfa-Integration-Token-[a-f0-9]{24}$/i.test(markerName) || !h || h.owner !== 'project' || h.projectId !== projectId || !same(h.url, ownedUrl) || h.format !== 'native' || !h.headers?.some(x => x.name.toLowerCase() === markerName.toLowerCase()) || !allowed.some(matches)) throw new Error('Subscription ownership mismatch.'); return true; } diff --git a/scripts/generate.mjs b/scripts/generate.mjs index fc0283b..65acd2f 100644 --- a/scripts/generate.mjs +++ b/scripts/generate.mjs @@ -77,7 +77,7 @@ imlFunction('polymorfaCallback', 'value', '', `if (typeof value !== 'string' || imlFunction('polymorfaError', 'status, headers, body, method', '', `try { iml.polymorfaResult(status, headers, body, method); return 'Polymorfa invalid_response'; } catch (error) { return error.message; }`); imlFunction('polymorfaReceive', 'expectedName, expectedValue, group, headers, body', `const types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};`, `const entries = Object.entries(headers || {}).filter(([key]) => key.toLowerCase() === String(expectedName).toLowerCase());\nif (!expectedValue || entries.length !== 1 || entries[0][1] !== expectedValue) return false;\nreturn !!(body && typeof body.id === 'string' && body.id && typeof body.connection === 'string' && body.connection && types[group] && types[group].includes(body.event) && typeof body.timestamp === 'string' && Number.isFinite(Date.parse(body.timestamp)) && body.payload && typeof body.payload === 'object' && !Array.isArray(body.payload));`); imlFunction('polymorfaFindHook', 'body, auth, url, group, key', `const expected = iml.polymorfaHook(auth, group, key);\nconst types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};\n// Match shared sameCallback: an invalid URL on any hook is simply not a match.\nconst same = h => { try { return iml.polymorfaCallback(h.url) === iml.polymorfaCallback(url); } catch (error) { return false; } };`, `if (!Array.isArray(body.data) || body.page?.hasMore) throw new Error('Subscription inventory needs reconciliation.');\nif (body.data.some(h => !same(h) && h.headers?.some(x => x.name.toLowerCase() === expected.name.toLowerCase()))) throw new Error('Subscription key is already in use.');\nconst owns = h => h.projectId === auth.projectId && h.owner === 'project' && same(h) && h.format === 'native' && h.enabled && h.headers?.some(x => x.name.toLowerCase() === expected.name.toLowerCase()) && h.eventTypes?.length === types[group].length && types[group].every(t => h.eventTypes.includes(t));\nif (body.data.some(h => (same(h) || h.headers?.some(x => x.name.toLowerCase() === expected.name.toLowerCase())) && !owns(h))) throw new Error('Changed subscription needs reconciliation.');\nconst matches = body.data.filter(owns);\nif (matches.length > 1) throw new Error('Duplicate owned subscriptions need reconciliation.');\nreturn matches[0]?.id || null;`); -imlFunction('polymorfaOwnedHook', 'body, projectId, ownedUrl, markerName, group', `const types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};\nconst same = (a, b) => { try { return iml.polymorfaCallback(a) === iml.polymorfaCallback(b); } catch (error) { return false; } };`, `const h = body.data;\nif (!h || h.owner !== 'project' || h.projectId !== projectId || !same(h.url, ownedUrl) || h.format !== 'native' || !h.headers?.some(x => x.name.toLowerCase() === markerName.toLowerCase()) || h.eventTypes?.length !== types[group]?.length || !types[group].every(t => h.eventTypes.includes(t))) throw new Error('Subscription ownership mismatch.');\nreturn true;`); +imlFunction('polymorfaOwnedHook', 'body, projectId, ownedUrl, markerName, group', `const types = ${JSON.stringify(Object.fromEntries(Object.entries(events).map(([k, e]) => [k, e.types])))};\nconst same = (a, b) => { try { return iml.polymorfaCallback(a) === iml.polymorfaCallback(b); } catch (error) { return false; } };`, `const h = body.data;\n// Cleanup only. Neither registration nor event emission accepts this retired set.\nconst legacy = ['session.status', 'session.connected', 'session.logged_out'];\nconst allowed = group === 'numberState' ? [legacy] : group === 'connectionState' ? [types[group], legacy] : [types[group]];\nconst matches = t => t && h?.eventTypes?.length === t.length && t.every(e => h.eventTypes.includes(e));\nif (typeof markerName !== 'string' || !/^X-Polymorfa-Integration-Token-[a-f0-9]{24}$/i.test(markerName) || !h || h.owner !== 'project' || h.projectId !== projectId || !same(h.url, ownedUrl) || h.format !== 'native' || !h.headers?.some(x => x.name.toLowerCase() === markerName.toLowerCase()) || !allowed.some(matches)) throw new Error('Subscription ownership mismatch.');\nreturn true;`); // Detach reads the one recorded webhook by ID. 404 means it is already gone. imlFunction('polymorfaDetachHook', 'status, body, id, projectId, ownedUrl, markerName, group', '', `if (status === 404) return false;\nif (status !== 200) throw new Error(iml.polymorfaError(status, {}, body, 'GET'));\nif (!body || !body.data || body.data.id !== id) throw new Error('Subscription ownership mismatch.');\nreturn iml.polymorfaOwnedHook(body, projectId, ownedUrl, markerName, group);`); diff --git a/tests/make.test.cjs b/tests/make.test.cjs index 04ab4fd..303371b 100644 --- a/tests/make.test.cjs +++ b/tests/make.test.cjs @@ -89,6 +89,24 @@ test('Make detach reads the recorded webhook by ID and deletes it only when owne } }); +test('Make detaches exact retained state subscriptions without registering or emitting retired events', () => { + const marker = 'X-Polymorfa-Integration-Token-' + 'a'.repeat(24); + const row = { id: 'retained', owner: 'project', projectId: auth.projectId, url: 'https://example.com/', enabled: false, + format: 'native', headers: [{ name: marker }], eventTypes: ['session.status', 'session.connected', 'session.logged_out'] }; + for (const group of ['numberState', 'connectionState']) { + const detach = value => iml.polymorfaDetachHook(200, { data: value }, row.id, auth.projectId, row.url, marker, group); + assert.equal(detach(row), true); + for (const changed of [{ id: 'other' }, { projectId: 'other' }, { owner: 'team' }, { url: 'https://elsewhere.example/' }, + { format: 'cloud' }, { headers: [{ name: 'X-Other' }] }, { eventTypes: ['session.connected'] }, + { eventTypes: ['session.status', 'connection.connected', 'session.logged_out'] }]) assert.throws(() => detach({ ...row, ...changed }), /ownership mismatch/); + assert.throws(() => iml.polymorfaDetachHook(200, { data: row }, row.id, auth.projectId, row.url, '', group), /ownership mismatch/); + } + assert.throws(() => iml.polymorfaHook(auth, 'numberState', 'retained'), e => e.code === 'invalid_event_group'); + assert.throws(() => iml.polymorfaFindHook({ data: [row], page: { hasMore: false } }, auth, row.url, 'numberState', 'retained'), e => e.code === 'invalid_event_group'); + const event = { ...require('../fixtures/events.json').connectionState, event: 'session.connected' }; + assert.equal(iml.polymorfaReceive(marker, 'synthetic-secret', 'connectionState', { [marker]: 'synthetic-secret' }, event), false); +}); + test('Make hook lookup matches shared find over the same inventories, including unusual URLs', async () => { const marker = hooks.identity(auth, 'messageReceived', 'key'); const own = { id: 'owned', owner: 'project', projectId: auth.projectId, url: 'https://example.com/', enabled: true, format: 'native', headers: [{ name: marker.name }], eventTypes: ['message.received'] }; From 56085cdac68579bd4e2f0341048cc798de321295 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 11:22:00 +0200 Subject: [PATCH 6/9] Bind integration projections to the qualified Connection source and SDK --- contracts/sdk-baseline.json | 2 +- contracts/source.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index d66c55d..4dce9a7 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,5 +1,5 @@ { - "source": "d9fe38300db8021ed4930106cf2e98ae796c7e30", + "source": "93352af97f704206d77f3dc2618f5acdd7f34c09", "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", "fragments": { "messaging": { diff --git a/contracts/source.json b/contracts/source.json index 6e0c033..bb7ae6e 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,9 +1,9 @@ { "apiVersion": "2026-09-22", - "apiSource": "20b482dfe31dbe88e624682c90669a61f9a2b5a6", + "apiSource": "653fe445b611c9bf168f3004313ce3331ce584e2", "sdk": { "repository": "polymorfa/sdks", - "source": "d9fe38300db8021ed4930106cf2e98ae796c7e30", + "source": "93352af97f704206d77f3dc2618f5acdd7f34c09", "publishedPackage": null }, "specs": { From 0aa4cbefbfa076b15d54310bd596b2006b95f3bb Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 12:00:09 +0200 Subject: [PATCH 7/9] Bind integration consumers to the reviewed authority source and verified SDK --- contracts/sdk-baseline.json | 2 +- contracts/source.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index 4dce9a7..ce14ffc 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,5 +1,5 @@ { - "source": "93352af97f704206d77f3dc2618f5acdd7f34c09", + "source": "797815afd4da378d1f1ec2dba1e639386c789a57", "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", "fragments": { "messaging": { diff --git a/contracts/source.json b/contracts/source.json index bb7ae6e..820fb9b 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,9 +1,9 @@ { "apiVersion": "2026-09-22", - "apiSource": "653fe445b611c9bf168f3004313ce3331ce584e2", + "apiSource": "f7f058a0a543f74b42ab76eecb9e75c1cc9e03b8", "sdk": { "repository": "polymorfa/sdks", - "source": "93352af97f704206d77f3dc2618f5acdd7f34c09", + "source": "797815afd4da378d1f1ec2dba1e639386c789a57", "publishedPackage": null }, "specs": { From 70783c7d45c011aacf98f9414e9388a7b47dc186 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 16:43:42 +0200 Subject: [PATCH 8/9] chore: align public adapters with qualified Connection source --- contracts/sdk-baseline.json | 2 +- contracts/source.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index ce14ffc..517f290 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,5 +1,5 @@ { - "source": "797815afd4da378d1f1ec2dba1e639386c789a57", + "source": "aa778674c3382b101d1562c7a2a39d131a6a46e4", "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", "fragments": { "messaging": { diff --git a/contracts/source.json b/contracts/source.json index 820fb9b..6ee56be 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,9 +1,9 @@ { "apiVersion": "2026-09-22", - "apiSource": "f7f058a0a543f74b42ab76eecb9e75c1cc9e03b8", + "apiSource": "d3e21ffbb26360ff620164f0f72ca2058dc2e018", "sdk": { "repository": "polymorfa/sdks", - "source": "797815afd4da378d1f1ec2dba1e639386c789a57", + "source": "aa778674c3382b101d1562c7a2a39d131a6a46e4", "publishedPackage": null }, "specs": { From 313a06df53e098da60be7a0fd159e6a223419599 Mon Sep 17 00:00:00 2001 From: Rajeh Taher Date: Tue, 17 Nov 2026 21:09:57 +0200 Subject: [PATCH 9/9] Bind integration contracts to retained R6 source --- contracts/sdk-baseline.json | 2 +- contracts/source.json | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/contracts/sdk-baseline.json b/contracts/sdk-baseline.json index 517f290..f15998d 100644 --- a/contracts/sdk-baseline.json +++ b/contracts/sdk-baseline.json @@ -1,5 +1,5 @@ { - "source": "aa778674c3382b101d1562c7a2a39d131a6a46e4", + "source": "d3affdf45db6cb1a1e88aad2716a32915277081f", "note": "Fingerprints of reviewed public SDK fragments. The SDK audience differs from the public API projection; no extra operation is imported. Changes require reconciliation, not automatic repinning.", "fragments": { "messaging": { diff --git a/contracts/source.json b/contracts/source.json index 6ee56be..a33e9a4 100644 --- a/contracts/source.json +++ b/contracts/source.json @@ -1,9 +1,9 @@ { "apiVersion": "2026-09-22", - "apiSource": "d3e21ffbb26360ff620164f0f72ca2058dc2e018", + "apiSource": "15db8b1c9d88e2ceccb58c851e731feabb659a39", "sdk": { "repository": "polymorfa/sdks", - "source": "aa778674c3382b101d1562c7a2a39d131a6a46e4", + "source": "d3affdf45db6cb1a1e88aad2716a32915277081f", "publishedPackage": null }, "specs": {