diff --git a/contracts/coverage.json b/contracts/coverage.json index bcbb5ad2a..32baf2aef 100644 --- a/contracts/coverage.json +++ b/contracts/coverage.json @@ -21882,6 +21882,14 @@ "language": "typescript", "baselineUnchanged": true, "published": false + }, + "statusPublicationsCandidate": { + "inventory": "contracts/status-publications.candidate.json", + "baselineUnchanged": true, + "published": false, + "sourceAccepted": false, + "sourceCommit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "scope": "Only the three status publication events, shared received content and existing Signal event parser extensions; no whole-contract or deployment claim." } }, "retiredOperations": [ diff --git a/contracts/doc-snippets.json b/contracts/doc-snippets.json index eb1532571..9c4f8cae6 100644 --- a/contracts/doc-snippets.json +++ b/contracts/doc-snippets.json @@ -1,7 +1,7 @@ { "schemaVersion": 1, - "sourceCommit": "641230d38744d862cbf66ae3af56fbfb203e1e73", - "sourceFilesSha256": "2c9b8c527fdebf3ca68ffb320c2ac118778502c74571365cd116c53427b475f8", + "sourceCommit": "101b11a4c69144fa123080ec4dfd68ed26d79ec6", + "sourceFilesSha256": "6a3a155d11aaf2d7fc01123fe1115b9a86b780afd8c64ef15767a0c41119ba38", "apiVersion": "2026-09-22", "apiSourceCommit": "f180dc1ee2bd45dbecf01702f73bdd75c664634b", "specs": { diff --git a/contracts/fixtures/status-publications.json b/contracts/fixtures/status-publications.json new file mode 100644 index 000000000..5929af495 --- /dev/null +++ b/contracts/fixtures/status-publications.json @@ -0,0 +1,51 @@ +{ + "statusReceived": { + "id": "018f0000-0000-7000-8000-000000000001", + "session": "739182640518203", + "timestamp": "2026-11-15T00:00:00.000Z", + "event": "status.received", + "payload": { + "id": "739182640518204", + "whatsapp_ids": { + "linked_devices": "AUTHORED-STATUS-EXAMPLE" + }, + "scope": "personal", + "fromMe": false, + "timestamp": 1794700800, + "pushName": "Authored example", + "content": { + "type": "text", + "text": "Authored status example. No live account or customer traffic." + }, + "publisher": { + "id": "739182640518205" + } + } + }, + "statusUpdated": { + "id": "018f0000-0000-7000-8000-000000000001", + "session": "739182640518203", + "timestamp": "2026-11-15T00:00:00.000Z", + "event": "status.update", + "payload": { + "id": "739182640518204", + "whatsapp_ids": { + "linked_devices": "AUTHORED-STATUS-EXAMPLE" + }, + "scope": "group", + "fromMe": false, + "timestamp": 1794700800, + "pushName": "Authored example", + "content": { + "type": "text", + "text": "Authored status example. No live account or customer traffic." + }, + "publisher": { + "id": "739182640518205" + }, + "group": { + "id": "739182640518206" + } + } + } +} diff --git a/contracts/status-publications.candidate.json b/contracts/status-publications.candidate.json new file mode 100644 index 000000000..0c119ac89 --- /dev/null +++ b/contracts/status-publications.candidate.json @@ -0,0 +1,703 @@ +{ + "schemaVersion": 1, + "sourceAccepted": false, + "published": false, + "apiVersion": "2026-09-22", + "candidateSource": { + "repository": "polymorfa/polymorfa", + "commit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "branch": "fix/status-stanza-delivery", + "pullRequest": "https://github.com/polymorfa/polymorfa/pull/1026", + "files": [ + { + "path": "apps/api/docs/openapi.json", + "sha256": "bb7810211838dda0a1a3280b0fb5b5e2401ddae1b6bf40d0d0f417a05f4461f6" + } + ] + }, + "acceptance": { + "staging": null, + "production": null + }, + "scope": "Only the three native status publication events and their schema closure. Existing accepted API and SDK source pins are unchanged.", + "events": { + "status.received": "StatusReceivedEvent", + "status.update": "StatusUpdateEvent", + "status.revoked": "StatusRevokedEvent" + }, + "openapi": "3.0.3", + "info": { + "title": "Status publication candidate", + "version": "2026-09-22" + }, + "paths": {}, + "components": { + "schemas": { + "IdentityRef": { + "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" + }, + "bsuid": { + "type": "string" + }, + "username": { + "type": "string" + }, + "parentBsuid": { + "type": "string", + "description": "Parent business-scoped user ID (`CC.ENT.\u2026`), 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"] + }, + "LinkPreview": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "The URL the preview describes, as matched in the message text." + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + }, + "previewType": { + "type": "string", + "description": "WhatsApp's preview kind in lower case, such as `none`, `video` or `image`." + }, + "thumbnail": { + "$ref": "#/components/schemas/MediaThumbnail" + } + }, + "required": ["url"], + "description": "Preview the sender attached to a text message containing a URL." + }, + "MediaThumbnail": { + "type": "object", + "properties": { + "contentType": { + "type": "string", + "enum": ["image/jpeg"] + }, + "data": { + "type": "string", + "description": "Base64-encoded JPEG bytes, at most 16 KiB decoded." + }, + "width": { + "type": "integer", + "minimum": 0, + "exclusiveMinimum": true + }, + "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." + }, + "MessageAssociation": { + "type": "object", + "properties": { + "type": { + "type": "string", + "enum": ["hd_image", "hd_video"] + }, + "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": ["type", "parentMessageId"], + "description": "Present on the HD half of an HD media pair. Show it in place of the standard message it names." + }, + "PollOption": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "hash": { + "type": "string" + } + }, + "required": ["name", "hash"] + }, + "ReceivedContent": { + "type": "object", + "properties": { + "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": { + "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"], + "description": "Present when the contact selects a reply button or list row." + }, + "parentMessageId": { + "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." + }, + "media": { + "type": "string" + }, + "mediaUrl": { + "type": "string" + }, + "edited": { + "type": "boolean" + }, + "pollOptions": { + "type": "array", + "items": { + "$ref": "#/components/schemas/PollOption" + } + }, + "unavailable": { + "type": "boolean" + }, + "unavailableReason": { + "type": "string" + }, + "stickerType": { + "type": "string", + "enum": ["static", "animated", "lottie"] + }, + "origin": { + "type": "string", + "enum": ["avatar", "ai"] + }, + "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 + }, + "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" + }, + "quality": { + "type": "string", + "enum": ["standard", "hd"], + "description": "`hd` on the HD half of a pair; `standard` on a standard message that announced an HD half." + } + }, + "required": ["type"] + }, + "StatusPublicationPayload": { + "oneOf": [ + { + "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 + }, + "fromMe": { + "type": "boolean" + }, + "timestamp": { + "type": "integer", + "minimum": 0 + }, + "pushName": { + "type": "string" + }, + "content": { + "$ref": "#/components/schemas/ReceivedContent" + }, + "scope": { + "type": "string", + "enum": ["personal"] + }, + "publisher": { + "$ref": "#/components/schemas/IdentityRef" + } + }, + "required": [ + "id", + "whatsapp_ids", + "fromMe", + "timestamp", + "pushName", + "content", + "scope", + "publisher" + ], + "additionalProperties": false + }, + { + "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 + }, + "fromMe": { + "type": "boolean" + }, + "timestamp": { + "type": "integer", + "minimum": 0 + }, + "pushName": { + "type": "string" + }, + "content": { + "$ref": "#/components/schemas/ReceivedContent" + }, + "scope": { + "type": "string", + "enum": ["group"] + }, + "publisher": { + "$ref": "#/components/schemas/IdentityRef" + }, + "group": { + "$ref": "#/components/schemas/IdentityRef" + } + }, + "required": [ + "id", + "whatsapp_ids", + "fromMe", + "timestamp", + "pushName", + "content", + "scope", + "publisher", + "group" + ], + "additionalProperties": false + }, + { + "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 + }, + "fromMe": { + "type": "boolean" + }, + "timestamp": { + "type": "integer", + "minimum": 0 + }, + "pushName": { + "type": "string" + }, + "content": { + "$ref": "#/components/schemas/ReceivedContent" + }, + "scope": { + "type": "string", + "enum": ["channel"] + }, + "channel": { + "$ref": "#/components/schemas/IdentityRef" + } + }, + "required": [ + "id", + "whatsapp_ids", + "fromMe", + "timestamp", + "pushName", + "content", + "scope", + "channel" + ], + "additionalProperties": false + } + ] + }, + "StatusReceivedEvent": { + "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": ["status.received"], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/StatusPublicationPayload" + } + }, + "required": ["id", "session", "timestamp", "event", "payload"] + }, + "StatusRevokedEvent": { + "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": ["status.revoked"], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/StatusPublicationPayload" + } + }, + "required": ["id", "session", "timestamp", "event", "payload"] + }, + "StatusUpdateEvent": { + "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": ["status.update"], + "description": "Event type" + }, + "payload": { + "$ref": "#/components/schemas/StatusPublicationPayload" + } + }, + "required": ["id", "session", "timestamp", "event", "payload"] + }, + "StickerPackItem": { + "type": "object", + "properties": { + "fileName": { + "type": "string" + }, + "stickerType": { + "type": "string", + "enum": ["static", "animated", "lottie"] + }, + "mimeType": { + "type": "string" + }, + "emojis": { + "type": "array", + "items": { + "type": "string" + } + }, + "accessibilityLabel": { + "type": "string" + }, + "premium": { + "type": "integer" + } + }, + "required": ["fileName", "stickerType", "mimeType"] + }, + "StickerPackMetadata": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "name": { + "type": "string" + }, + "publisher": { + "type": "string" + }, + "description": { + "type": "string" + }, + "trayIconFileName": { + "type": "string" + }, + "items": { + "type": "array", + "items": { + "$ref": "#/components/schemas/StickerPackItem" + } + } + }, + "required": ["id", "name", "publisher", "items"] + }, + "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." + } + } + } +} diff --git a/packages/dotnet/README.md b/packages/dotnet/README.md index 16eb34717..dc1f195f4 100644 --- a/packages/dotnet/README.md +++ b/packages/dotnet/README.md @@ -1188,3 +1188,17 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP path; programmatic media WebSocket controls retain their credential rechecks. This source requires the matching unreleased backend. It does not enable a customer environment or advance package/API availability. + +### Candidate status publication events + +The source models recognize `status.received`, `status.update` and +`status.revoked` separately from message events. Their payload shares received +content types and identifies `scope` as `personal`, `group` or `channel`. +Personal and group publications identify their publisher; group and channel +publications identify their respective audience. Replies and mentions remain +message events. Status publications do not create a chat conversation. + +These events have no released API or SDK version and are unavailable in staging +and production. Keep existing subscriptions until a release notice confirms +availability for your API version. The separately pinned candidate contract +does not advance the accepted API baseline or authorize package publication. diff --git a/packages/dotnet/coverage.json b/packages/dotnet/coverage.json index 52e856f5a..dca2b117b 100644 --- a/packages/dotnet/coverage.json +++ b/packages/dotnet/coverage.json @@ -5251,6 +5251,14 @@ "language": "dotnet", "baselineUnchanged": true, "published": false + }, + "statusPublicationsCandidate": { + "inventory": "contracts/status-publications.candidate.json", + "baselineUnchanged": true, + "published": false, + "sourceAccepted": false, + "sourceCommit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "scope": "Only the three status publication events, shared received content and existing Signal event parser extensions; no whole-contract or deployment claim." } } } diff --git a/packages/dotnet/src/Polymorfa.Sdk/SignalClient.cs b/packages/dotnet/src/Polymorfa.Sdk/SignalClient.cs index ca9f77071..7f436f287 100644 --- a/packages/dotnet/src/Polymorfa.Sdk/SignalClient.cs +++ b/packages/dotnet/src/Polymorfa.Sdk/SignalClient.cs @@ -68,6 +68,7 @@ public HistoryChunkInput ChunkInput() } public sealed record SignalEvent { + public string? StatusScope { get; init; } public required string Id { get; init; } public required string Type { get; init; } public required string SessionId { get; init; } @@ -185,6 +186,7 @@ public async IAsyncEnumerable EventsAsync(string? session = null, [ try { item = JsonSerializer.Deserialize(data.ToString(), Json) ?? throw InvalidResponse(); } catch (JsonException) { throw InvalidResponse(); } if (string.IsNullOrEmpty(item.Id) || item.Id != eventId || item.Type != kind || session is not null && item.SessionId != session) throw InvalidResponse(); + RequireStatusScope(item); yield return item; } data.Clear(); eventId = null; kind = null; @@ -202,9 +204,13 @@ public static SignalEvent VerifyWebhook(ReadOnlySpan secret, long timestam mac.AppendData(Encoding.ASCII.GetBytes(timestamp.ToString(System.Globalization.CultureInfo.InvariantCulture) + ".")); mac.AppendData(body); if (!CryptographicOperations.FixedTimeEquals(mac.GetHashAndReset(), received)) throw BadSignature(); if (body.Length > BodyLimit) throw InvalidResponse(); - try { var item = JsonSerializer.Deserialize(body, Json) ?? throw InvalidResponse(); if (string.IsNullOrEmpty(item.Id)) throw InvalidResponse(); return item; } + try { var item = JsonSerializer.Deserialize(body, Json) ?? throw InvalidResponse(); if (string.IsNullOrEmpty(item.Id)) throw InvalidResponse(); RequireStatusScope(item); return item; } catch (JsonException) { throw InvalidResponse(); } } + private static void RequireStatusScope(SignalEvent item) + { + if (item.Type == "status.received" && item.StatusScope is not ("personal" or "group" or "channel")) throw InvalidResponse(); + } private static PolymorfaException BadSignature() => new("Invalid Signal webhook signature or timestamp.", "invalid_signature"); private static PolymorfaException InvalidResponse() => new PolymorfaServerException("Signal service returned an invalid response.", "invalid_response"); } diff --git a/packages/dotnet/src/Polymorfa.Sdk/WebhookParsers.cs b/packages/dotnet/src/Polymorfa.Sdk/WebhookParsers.cs index eda768773..4fa4a5b4c 100644 --- a/packages/dotnet/src/Polymorfa.Sdk/WebhookParsers.cs +++ b/packages/dotnet/src/Polymorfa.Sdk/WebhookParsers.cs @@ -68,6 +68,7 @@ public static partial class Webhooks "message.ack" => Typed(envelope), "message.delete" => Typed(envelope), "message.echo" => Typed(envelope), + "status.received" or "status.update" or "status.revoked" => Typed(envelope), "message.edited" or "message.revoked" or "message.update" => Typed(envelope), "message.failed" => Typed(envelope), "message.reaction" or "message.received" => Field(envelope, "timestamp") is not null ? Typed(envelope) : Typed(envelope), diff --git a/packages/dotnet/src/Polymorfa.Sdk/WebhookPayloads.cs b/packages/dotnet/src/Polymorfa.Sdk/WebhookPayloads.cs index 7ce24ea0c..d2c4ebec5 100644 --- a/packages/dotnet/src/Polymorfa.Sdk/WebhookPayloads.cs +++ b/packages/dotnet/src/Polymorfa.Sdk/WebhookPayloads.cs @@ -12,14 +12,18 @@ public sealed record EventConversation(string Id, string? PhoneNumber = null, st public sealed record NativeFlowResponse(string Name, string ParamsJson, int? Version = null); public sealed record ReplyChoice(string Kind, string Id); public sealed record PollOption(string Name, string Hash); -public sealed record LinkedDeviceMessagePayload(string Id, [property: JsonPropertyName("whatsapp_ids")] WhatsAppMessageIds WhatsAppIds, EventConversation Conversation, bool FromMe, long Timestamp, string PushName, bool IsGroup, string Type, string? Text = null, string? Caption = null, string? MimeType = null, bool? Ptt = null, string? Filename = null, double? Latitude = null, double? Longitude = null, string? DisplayName = null, string? Title = null, string? Reaction = null, string? ReactionTo = null, string? RevokedId = null, string? Media = null, string? MediaUrl = null, bool? Edited = null, IReadOnlyList? PollOptions = null, bool? Unavailable = null, string? UnavailableReason = null, NativeFlowResponse? NativeFlowResponse = null, ReplyChoice? ReplyChoice = null, string? ParentMessageId = null, [property: JsonPropertyName("whatsapp_id")] string? WhatsAppId = null) +public record ReceivedContent(string Type, string? Text = null, string? Caption = null, string? MimeType = null, bool? Ptt = null, string? Filename = null, double? Latitude = null, double? Longitude = null, string? DisplayName = null, string? Title = null, string? Reaction = null, string? ReactionTo = null, string? RevokedId = null, string? Media = null, string? MediaUrl = null, bool? Edited = null, IReadOnlyList? PollOptions = null, bool? Unavailable = null, string? UnavailableReason = null, NativeFlowResponse? NativeFlowResponse = null, ReplyChoice? ReplyChoice = null, string? ParentMessageId = null) { [JsonExtensionData] public Dictionary? AdditionalFields { get; init; } } + +public sealed record LinkedDeviceMessagePayload(string Id, [property: JsonPropertyName("whatsapp_ids")] WhatsAppMessageIds WhatsAppIds, EventConversation Conversation, bool FromMe, long Timestamp, string PushName, bool IsGroup, string Type, string? Text = null, string? Caption = null, string? MimeType = null, bool? Ptt = null, string? Filename = null, double? Latitude = null, double? Longitude = null, string? DisplayName = null, string? Title = null, string? Reaction = null, string? ReactionTo = null, string? RevokedId = null, string? Media = null, string? MediaUrl = null, bool? Edited = null, IReadOnlyList? PollOptions = null, bool? Unavailable = null, string? UnavailableReason = null, NativeFlowResponse? NativeFlowResponse = null, ReplyChoice? ReplyChoice = null, string? ParentMessageId = null, [property: JsonPropertyName("whatsapp_id")] string? WhatsAppId = null) : ReceivedContent(Type, Text, Caption, MimeType, Ptt, Filename, Latitude, Longitude, DisplayName, Title, Reaction, ReactionTo, RevokedId, Media, MediaUrl, Edited, PollOptions, Unavailable, UnavailableReason, NativeFlowResponse, ReplyChoice, ParentMessageId); public sealed record CloudMessageReferral([property: JsonPropertyName("source_type")] string? SourceType = null, [property: JsonPropertyName("source_id")] string? SourceId = null, [property: JsonPropertyName("source_url")] string? SourceUrl = null, [property: JsonPropertyName("ctwa_clid")] string? ClickId = null) { [JsonExtensionData] public Dictionary? AdditionalFields { get; init; } } +public sealed record StatusPublicationPayload(string Id, [property: JsonPropertyName("whatsapp_ids")] WhatsAppMessageIds WhatsAppIds, string Scope, bool FromMe, long Timestamp, string PushName, ReceivedContent Content, EventConversation? Publisher = null, EventConversation? Group = null, EventConversation? Channel = null, [property: JsonPropertyName("whatsapp_id")] string? WhatsAppId = null); + public sealed record CloudMessagePayload(string Id, [property: JsonPropertyName("whatsapp_ids")] WhatsAppMessageIds WhatsAppIds, EventConversation Conversation, string Timestamp, string Type, string? SenderName = null, NativeFlowResponse? NativeFlowResponse = null, ReplyChoice? ReplyChoice = null, string? ParentMessageId = null, IReadOnlyDictionary? Interactive = null, CloudMessageReferral? Referral = null, [property: JsonPropertyName("whatsapp_id")] string? WhatsAppId = null, CloudOrder? Order = null) { [JsonExtensionData] public Dictionary? AdditionalFields { get; init; } diff --git a/packages/dotnet/src/Polymorfa.Sdk/Webhooks.cs b/packages/dotnet/src/Polymorfa.Sdk/Webhooks.cs index 7f9cd7c3c..5c8822cfd 100644 --- a/packages/dotnet/src/Polymorfa.Sdk/Webhooks.cs +++ b/packages/dotnet/src/Polymorfa.Sdk/Webhooks.cs @@ -89,6 +89,7 @@ public static WebhookEvent ConstructLocalEvent(ReadOnlySpan rawBody, strin } public static IReadOnlySet KnownEventTypes { get; } = new[] { + "status.received", "status.update", "status.revoked", "bansafe.action","bansafe.claim","bansafe.health_threshold","bansafe.incident","blocklist.update","business.quick_reply.update", "call.accepted","call.connection_joined","call.connection_left","call.ended","call.missed","call.participant_joined","call.participant_left","call.participant_state","call.permission_changed","call.received","call.rejected","call.telemetry", "campaign.cap_reached","campaign.cold_blocked","campaign.completed","campaign.failed","campaign.launched","campaign.paused","campaign.recipient_failed","campaign.recipient_sent","campaign.recipient_skipped","campaign.rescheduled","campaign.resumed","campaign.stopped","campaign.throttled", diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/ConsumerRepairTests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/ConsumerRepairTests.cs index f387a3d44..bd116205d 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/ConsumerRepairTests.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/ConsumerRepairTests.cs @@ -44,6 +44,15 @@ public static async Task SignalSessionAsync() await using var peer = new Peer((request, stream, _) => { SignalHeaders(request); return SignalReply(stream, ": keepalive\r\n\r\n" + SignalFrame("s")); }); using var client = new SignalClient(new(peer.Url, SignalSecret)); var events = new List(); await foreach (var item in client.EventsAsync(filter)) events.Add(item); Check(events.Count == 1 && events[0].SessionId == "s", "Valid Signal filter/EOF changed"); } + foreach (var scope in new string?[] { null, "", "future", "personal", "group", "channel" }) + { + var fragment = scope is null ? "" : ",\"status_scope\":" + JsonSerializer.Serialize(scope); + var frame = SignalFrame("s").Replace("event: message", "event: status.received").Replace("\"type\":\"message\"", "\"type\":\"status.received\"" + fragment); + await using var peer = new Peer((request, stream, _) => { SignalHeaders(request); return SignalReply(stream, frame); }); + using var client = new SignalClient(new(peer.Url, SignalSecret)); + if (scope is "personal" or "group" or "channel") { var events = new List(); await foreach (var item in client.EventsAsync("s")) events.Add(item); Check(events.Count == 1 && events[0].StatusScope == scope, "Valid status scope changed"); } + else { try { await foreach (var _ in client.EventsAsync("s")) throw new Exception("Invalid status scope escaped"); throw new Exception("Missing status scope error"); } catch (PolymorfaServerException error) { Check(error.Code == "invalid_response", "Status scope error changed"); } } + } Console.WriteLine("PASS public Signal: session filtering and unfiltered/clean EOF controls"); } public static async Task SignalTruncationAsync() diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/SignalTests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/SignalTests.cs index 7ae96411f..f5e0d4fd8 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/SignalTests.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/SignalTests.cs @@ -23,6 +23,19 @@ internal static void WebhookKeys() ResourceTests.Equal(Code(() => SignalClient.VerifyWebhook(key, 100, body, Sign(Encoding.ASCII.GetBytes("another-fixture-secret"), 100, body), 100, TimeSpan.FromSeconds(5))), "invalid_signature"); ResourceTests.Equal(Code(() => SignalClient.VerifyWebhook(key, 100, body, Sign(key, 100, body), 106, TimeSpan.FromSeconds(5))), "invalid_signature"); } + foreach (var scope in new string?[] { null, "", "future", "personal", "group", "channel" }) + { + var fragment = scope is null ? "" : ",\"status_scope\":" + JsonSerializer.Serialize(scope); + var bytes = Encoding.UTF8.GetBytes(Event.Replace("\"type\":\"message\"", "\"type\":\"status.received\"" + fragment)); + var key = Encoding.ASCII.GetBytes(Secret); + if (scope is "personal" or "group" or "channel") ResourceTests.Equal(SignalClient.VerifyWebhook(key, 100, bytes, Sign(key, 100, bytes), 100).StatusScope, scope); + else ResourceTests.Equal(Code(() => SignalClient.VerifyWebhook(key, 100, bytes, Sign(key, 100, bytes), 100)), "invalid_response"); + } + var statusBody = Encoding.UTF8.GetBytes(Event.Replace("\"type\":\"message\"", "\"type\":\"status.received\",\"status_scope\":\"group\"")); + var statusKey = Encoding.ASCII.GetBytes(Secret); + var statusEvent = SignalClient.VerifyWebhook(statusKey, 100, statusBody, Sign(statusKey, 100, statusBody), 100, TimeSpan.FromSeconds(5)); + ResourceTests.Equal(statusEvent.Type, "status.received"); + ResourceTests.Equal(statusEvent.StatusScope, "group"); var valid = Enumerable.Repeat((byte)'k', 16).ToArray(); var invalid = Encoding.UTF8.GetBytes("{not json"); ResourceTests.Equal(Code(() => SignalClient.VerifyWebhook(valid, 100, invalid, Sign(valid, 100, invalid), 100, TimeSpan.FromSeconds(5))), "invalid_response"); diff --git a/packages/dotnet/tests/Polymorfa.Sdk.Tests/WebhookTests.cs b/packages/dotnet/tests/Polymorfa.Sdk.Tests/WebhookTests.cs index 1fa219fc0..541413557 100644 --- a/packages/dotnet/tests/Polymorfa.Sdk.Tests/WebhookTests.cs +++ b/packages/dotnet/tests/Polymorfa.Sdk.Tests/WebhookTests.cs @@ -7,6 +7,8 @@ internal static class WebhookTests { public static void Run() { + var status = Parse("status.received", """{"id":"123","whatsapp_ids":{"linked_devices":"authored-status"},"scope":"group","publisher":{"id":"456"},"group":{"id":"789"},"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"text","text":"publication","futureMediaField":123}}"""); + Check(status.Scope == "group" && status.Group?.Id == "789" && status.Content.Text == "publication" && status.Content.AdditionalFields?["futureMediaField"].GetInt32() == 123, "separate status publication with shared content"); var linked = Parse("message.received", """{"id":"m1","whatsapp_ids":{"linked_devices":"wa1"},"conversation":{"id":"peer","sender":{"id":"lid","bsuid":"US.123"}},"fromMe":false,"timestamp":1726170122,"pushName":"Zoë 🐈","isGroup":true,"type":"text","text":"héllo","edited":false,"pollOptions":[{"name":"A","hash":"abc"}],"future":{"enabled":true}}"""); Check(linked.WhatsAppIds.LinkedDevices == "wa1" && linked.Text == "héllo" && linked.Timestamp == 1726170122 && linked.Conversation.Sender?.Bsuid == "US.123" && linked.AdditionalFields?["future"].GetProperty("enabled").GetBoolean() == true, "linked-device payload"); var cloud = Parse("message.reaction", """{"id":"m2","whatsapp_ids":{"official_api":"wa2"},"conversation":{"id":"peer"},"timestamp":"1726170122","type":"interactive","senderName":"Zoë","nativeFlowResponse":{"name":"flow","paramsJson":"{\"choice\":false}","version":3},"referral":{"source_type":"ad","ctwa_clid":"click","future":"kept"},"interactive":{"button_reply":{"id":"yes"}}}"""); @@ -47,7 +49,7 @@ public static void Run() try { Webhooks.ConstructEvent(invalid, new string('0', 64), "secret"); throw new Exception("signature accepted"); } catch (WebhookSignatureException) { } var signature = Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes("secret"), invalid)); try { Webhooks.ConstructEvent(invalid, signature, "secret"); throw new Exception("invalid JSON accepted"); } catch (PolymorfaValidationException e) { Check(e.Code == "invalid_webhook_json", "JSON failure"); } - Check(Webhooks.KnownEventTypes.Count == 86, "known registry count"); + Check(Webhooks.KnownEventTypes.Count == 89, "known registry count"); var flow = Encoding.UTF8.GetBytes("{\"action\":\"INIT\",\"data\":{\"selected\":false}}"); var time = DateTimeOffset.FromUnixTimeSeconds(1726170122); var signedFlow = Encoding.UTF8.GetBytes("1726170122.").Concat(flow).ToArray(); diff --git a/packages/go/README.md b/packages/go/README.md index 2bc663f3c..23fc60ff7 100644 --- a/packages/go/README.md +++ b/packages/go/README.md @@ -999,3 +999,17 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP path; programmatic media WebSocket controls retain their credential rechecks. This source requires the matching unreleased backend. It does not enable a customer environment or advance package/API availability. + +### Candidate status publication events + +The source models recognize `status.received`, `status.update` and +`status.revoked` separately from message events. Their payload shares received +content types and identifies `scope` as `personal`, `group` or `channel`. +Personal and group publications identify their publisher; group and channel +publications identify their respective audience. Replies and mentions remain +message events. Status publications do not create a chat conversation. + +These events have no released API or SDK version and are unavailable in staging +and production. Keep existing subscriptions until a release notice confirms +availability for your API version. The separately pinned candidate contract +does not advance the accepted API baseline or authorize package publication. diff --git a/packages/go/coverage.json b/packages/go/coverage.json index 7f18c0c45..bcfe87e58 100644 --- a/packages/go/coverage.json +++ b/packages/go/coverage.json @@ -5251,6 +5251,14 @@ "language": "go", "baselineUnchanged": true, "published": false + }, + "statusPublicationsCandidate": { + "inventory": "contracts/status-publications.candidate.json", + "baselineUnchanged": true, + "published": false, + "sourceAccepted": false, + "sourceCommit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "scope": "Only the three status publication events, shared received content and existing Signal event parser extensions; no whole-contract or deployment claim." } } } diff --git a/packages/go/signal_sidecar_types.go b/packages/go/signal_sidecar_types.go index 3c472dade..e0f5d962a 100644 --- a/packages/go/signal_sidecar_types.go +++ b/packages/go/signal_sidecar_types.go @@ -105,6 +105,7 @@ func (v SignalHistoryDescriptor) GoString() string { return v.String() func (SignalHistoryDescriptor) MarshalJSON() ([]byte, error) { return []byte(`{"redacted":true}`), nil } type SignalEvent struct { + StatusScope *StatusScope `json:"status_scope,omitempty"` ID string `json:"id"` Type string `json:"type"` SessionID string `json:"session_id"` @@ -159,7 +160,10 @@ func parseSignalEvent(raw []byte) (SignalEvent, error) { return SignalEvent{}, signalInvalid() } var event SignalEvent - if json.Unmarshal(raw, &event) != nil || event.ID == "" || event.SessionID == "" || (event.Type != "message" && event.Type != "history.sync") { + if json.Unmarshal(raw, &event) != nil || event.ID == "" || event.SessionID == "" || (event.Type != "message" && event.Type != "history.sync" && event.Type != "status.received") { + return SignalEvent{}, signalInvalid() + } + if event.Type == "status.received" && (event.StatusScope == nil || (*event.StatusScope != StatusPersonal && *event.StatusScope != StatusGroup && *event.StatusScope != StatusChannel)) { return SignalEvent{}, signalInvalid() } if event.Type == "history.sync" && (event.History == nil || len(event.MessageProto) != 0) { diff --git a/packages/go/status_publications_test.go b/packages/go/status_publications_test.go new file mode 100644 index 000000000..ca4e305ee --- /dev/null +++ b/packages/go/status_publications_test.go @@ -0,0 +1,59 @@ +package polymorfa + +import ( + "encoding/json" + "testing" +) + +func TestStatusPublicationPayloadHasSharedContentAndSeparateScope(t *testing.T) { + var payload StatusPublicationPayload + if err := json.Unmarshal([]byte(`{"id":"123","whatsapp_ids":{"linked_devices":"authored-status"},"scope":"group","publisher":{"id":"456"},"group":{"id":"789"},"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"text","text":"publication","futureMediaField":123}}`), &payload); err != nil { + t.Fatal(err) + } + if payload.Scope != StatusGroup || payload.Group.ID != "789" || payload.Content.Text != "publication" { + t.Fatalf("wrong typed publication: %#v", payload) + } + body, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(body, &fields); err != nil { + t.Fatal(err) + } + var content map[string]any + if err := json.Unmarshal(fields["content"], &content); err != nil { + t.Fatal(err) + } + if content["futureMediaField"] != float64(123) { + t.Fatal("lost forward content metadata") + } + if _, exists := fields["conversation"]; exists { + t.Fatal("status has a chat conversation") + } +} + +func TestSignalStatusEventDoesNotFallBackToMessage(t *testing.T) { + event, err := parseSignalEvent([]byte(`{"id":"authored-status-event","type":"status.received","status_scope":"personal","session_id":"authored-session","chat":"status@broadcast","sender":"123@s.whatsapp.net","message_id":"authored-publication","timestamp":1700000000,"is_from_me":false,"redelivered":false,"identity_changed":false,"message_proto":"CgdmaXh0dXJl","text":"authored publication"}`)) + if err != nil { + t.Fatal(err) + } + if event.Type != "status.received" || event.StatusScope == nil || *event.StatusScope != StatusPersonal { + t.Fatal("remote status classification was lost") + } +} + +func TestLinkedMessageLiteralStillBuildsWithOwnedFields(t *testing.T) { + payload := LinkedDeviceMessagePayload{Type: "text", Text: "authored legacy construction"} + encoded, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + var decoded LinkedDeviceMessagePayload + if err := json.Unmarshal(encoded, &decoded); err != nil { + t.Fatal(err) + } + if decoded.Type != payload.Type || decoded.Text != payload.Text { + t.Fatal("message construction changed") + } +} diff --git a/packages/go/webhook_payloads.go b/packages/go/webhook_payloads.go index a7dbe92cc..b75680be3 100644 --- a/packages/go/webhook_payloads.go +++ b/packages/go/webhook_payloads.go @@ -71,6 +71,33 @@ type LinkedDeviceMessagePayload struct { ParentMessageID string `json:"parentMessageId,omitempty"` Extra PlatformPayload `json:"-"` } + +// ReceivedContent is shared by messages and status publications. +type ReceivedContent struct { + Type string `json:"type"` + Text string `json:"text,omitempty"` + Caption string `json:"caption,omitempty"` + MimeType string `json:"mimeType,omitempty"` + PTT *bool `json:"ptt,omitempty"` + Filename string `json:"filename,omitempty"` + Latitude *float64 `json:"latitude,omitempty"` + Longitude *float64 `json:"longitude,omitempty"` + DisplayName string `json:"displayName,omitempty"` + Title string `json:"title,omitempty"` + Reaction string `json:"reaction,omitempty"` + ReactionTo string `json:"reactionTo,omitempty"` + RevokedID string `json:"revokedId,omitempty"` + Media string `json:"media,omitempty"` + MediaURL string `json:"mediaUrl,omitempty"` + Edited *bool `json:"edited,omitempty"` + PollOptions []WebhookPollOption `json:"pollOptions,omitempty"` + Unavailable *bool `json:"unavailable,omitempty"` + UnavailableReason string `json:"unavailableReason,omitempty"` + NativeFlowResponse *NativeFlowResponse `json:"nativeFlowResponse,omitempty"` + ReplyChoice *ReplyChoice `json:"replyChoice,omitempty"` + ParentMessageID string `json:"parentMessageId,omitempty"` + Extra PlatformPayload `json:"-"` +} type CloudMessageReferral struct { SourceType string `json:"source_type,omitempty"` SourceID string `json:"source_id,omitempty"` @@ -78,6 +105,61 @@ type CloudMessageReferral struct { CTWAClid string `json:"ctwa_clid,omitempty"` Extra PlatformPayload `json:"-"` } +type StatusScope string + +const ( + StatusPersonal StatusScope = "personal" + StatusGroup StatusScope = "group" + StatusChannel StatusScope = "channel" +) + +type StatusPublicationPayload struct { + webhookPayloadBase + ID string `json:"id"` + WhatsAppIDs WhatsAppMessageIDs `json:"whatsapp_ids"` + WhatsAppID string `json:"whatsapp_id,omitempty"` + Scope StatusScope `json:"scope"` + Publisher *WebhookIdentity `json:"publisher,omitempty"` + Group *WebhookIdentity `json:"group,omitempty"` + Channel *WebhookIdentity `json:"channel,omitempty"` + FromMe bool `json:"fromMe"` + Timestamp int64 `json:"timestamp"` + PushName string `json:"pushName"` + Content ReceivedContent `json:"content"` + Extra PlatformPayload `json:"-"` +} + +func (v *StatusPublicationPayload) UnmarshalJSON(body []byte) error { + type plain StatusPublicationPayload + if err := webhookOpenDecode(body, (*plain)(v), &v.Extra); err != nil { + return err + } + var raw struct { + Content json.RawMessage `json:"content"` + } + if err := json.Unmarshal(body, &raw); err != nil { + return err + } + return webhookOpenDecode(raw.Content, &v.Content, &v.Content.Extra) +} +func (v StatusPublicationPayload) MarshalJSON() ([]byte, error) { + type plain StatusPublicationPayload + body, err := webhookOpenEncode(plain(v), v.Extra) + if err != nil { + return nil, err + } + var raw map[string]json.RawMessage + if err := json.Unmarshal(body, &raw); err != nil { + return nil, err + } + content, err := webhookOpenEncode(v.Content, v.Content.Extra) + if err != nil { + return nil, err + } + raw["content"] = content + return json.Marshal(raw) +} + type CloudMessagePayload struct { Order *CloudOrder `json:"order,omitempty"` webhookPayloadBase @@ -907,6 +989,8 @@ type SessionCapabilitiesUpdatedPayload struct { func (e WebhookEvent) TypedPayload() (KnownWebhookPayload, bool, error) { var v KnownWebhookPayload switch e.Event { + case "status.received", "status.update", "status.revoked": + v = &StatusPublicationPayload{} case "message.received", "message.reaction": var ts struct { Timestamp json.RawMessage `json:"timestamp"` diff --git a/packages/go/webhook_payloads_test.go b/packages/go/webhook_payloads_test.go index d2abf7683..25ffa126b 100644 --- a/packages/go/webhook_payloads_test.go +++ b/packages/go/webhook_payloads_test.go @@ -14,6 +14,7 @@ import ( func TestKnownWebhookPayloadFamilies(t *testing.T) { families := []struct{ events, kind, body, field string }{ + {"status.received status.update status.revoked", "StatusPublicationPayload", `{"id":"123","whatsapp_ids":{"linked_devices":"authored-status"},"scope":"personal","publisher":{"id":"456"},"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"text","text":"publication"}}`, "content.text"}, {"bansafe.action", "BanSafeActionPayload", `{"rung":"throttle","health":null,"requires":[{"findingKey":"risk","severity":"warning"}]}`, "requires.0.findingKey"}, {"bansafe.claim", "BanSafeClaimPayload", `{"amountCents":0.123456,"decidedAt":null}`, "amountCents"}, {"bansafe.health_threshold", "BanSafeHealthThresholdPayload", `{"policyVersion":2,"healthSource":"ml_model","modelVersion":null}`, "policyVersion"}, diff --git a/packages/go/webhooks.go b/packages/go/webhooks.go index 49accf3b3..052e4c25a 100644 --- a/packages/go/webhooks.go +++ b/packages/go/webhooks.go @@ -57,6 +57,7 @@ func ParseVerifiedWebhookEvent(body []byte) (WebhookEvent, error) { func (e WebhookEvent) Known() bool { _, ok := knownWebhookEvents[e.Event]; return ok } var knownWebhookEvents = map[string]struct{}{ + "status.received": {}, "status.update": {}, "status.revoked": {}, "marketing.onboarding_updated": {}, "contact.marketing_preference_updated": {}, "bansafe.action": {}, "bansafe.claim": {}, "bansafe.health_threshold": {}, "bansafe.incident": {}, "blocklist.update": {}, "business.quick_reply.update": {}, "call.accepted": {}, "call.connection_joined": {}, "call.connection_left": {}, "call.ended": {}, "call.missed": {}, "call.participant_joined": {}, "call.participant_left": {}, "call.participant_state": {}, "call.permission_changed": {}, "call.received": {}, "call.rejected": {}, "call.telemetry": {}, diff --git a/packages/php/README.md b/packages/php/README.md index 4a31f7cad..100aa7aca 100644 --- a/packages/php/README.md +++ b/packages/php/README.md @@ -1134,3 +1134,17 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP path; programmatic media WebSocket controls retain their credential rechecks. This source requires the matching unreleased backend. It does not enable a customer environment or advance package/API availability. + +### Candidate status publication events + +The source models recognize `status.received`, `status.update` and +`status.revoked` separately from message events. Their payload shares received +content types and identifies `scope` as `personal`, `group` or `channel`. +Personal and group publications identify their publisher; group and channel +publications identify their respective audience. Replies and mentions remain +message events. Status publications do not create a chat conversation. + +These events have no released API or SDK version and are unavailable in staging +and production. Keep existing subscriptions until a release notice confirms +availability for your API version. The separately pinned candidate contract +does not advance the accepted API baseline or authorize package publication. diff --git a/packages/php/coverage.json b/packages/php/coverage.json index 8040d515a..b9c2e4434 100644 --- a/packages/php/coverage.json +++ b/packages/php/coverage.json @@ -5388,6 +5388,14 @@ "language": "php", "baselineUnchanged": true, "published": false + }, + "statusPublicationsCandidate": { + "inventory": "contracts/status-publications.candidate.json", + "baselineUnchanged": true, + "published": false, + "sourceAccepted": false, + "sourceCommit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "scope": "Only the three status publication events, shared received content and existing Signal event parser extensions; no whole-contract or deployment claim." } } } diff --git a/packages/php/src/SignalEvent.php b/packages/php/src/SignalEvent.php index 79eb6917e..e53dd4bba 100644 --- a/packages/php/src/SignalEvent.php +++ b/packages/php/src/SignalEvent.php @@ -6,7 +6,7 @@ final readonly class SignalEvent implements \JsonSerializable { - public function __construct(public string $id, public string $type, public string $sessionId, #[\SensitiveParameter] public string $chat, #[\SensitiveParameter] public string $sender, public string $messageId, public int $timestamp, public bool $isFromMe, public bool $redelivered, public bool $identityChanged, #[\SensitiveParameter] public string $messageProto, #[\SensitiveParameter] public string $rawJson, #[\SensitiveParameter] public ?string $senderAlt = null, #[\SensitiveParameter] public ?string $text = null, public ?SignalMediaDescriptor $media = null, public ?SignalHistoryDescriptor $history = null) + public function __construct(public string $id, public string $type, public string $sessionId, #[\SensitiveParameter] public string $chat, #[\SensitiveParameter] public string $sender, public string $messageId, public int $timestamp, public bool $isFromMe, public bool $redelivered, public bool $identityChanged, #[\SensitiveParameter] public string $messageProto, #[\SensitiveParameter] public string $rawJson, #[\SensitiveParameter] public ?string $senderAlt = null, #[\SensitiveParameter] public ?string $text = null, public ?SignalMediaDescriptor $media = null, public ?SignalHistoryDescriptor $history = null, public ?string $statusScope = null) { } public static function fromJson(#[\SensitiveParameter] string $raw): self @@ -15,9 +15,11 @@ public static function fromJson(#[\SensitiveParameter] string $raw): self $id = SignalCodec::string($data, 'id'); $type = SignalCodec::string($data, 'type'); $session = SignalCodec::string($data, 'session_id'); - if ($id === '' || $session === '' || !in_array($type, ['message','history.sync'], true)) { + if ($id === '' || $session === '' || !in_array($type, ['message','history.sync','status.received'], true)) { SignalCodec::invalid(); } + $statusScope = SignalCodec::optionalString($data, 'status_scope'); + if ($type === 'status.received' && !in_array($statusScope, ['personal','group','channel'], true)) { SignalCodec::invalid(); } $media = $history = null; foreach (['media','history'] as $field) { if (array_key_exists($field, $data)) { @@ -34,7 +36,7 @@ public static function fromJson(#[\SensitiveParameter] string $raw): self if ($type === 'history.sync' && ($history === null || $proto !== '')) { SignalCodec::invalid(); } - return new self($id, $type, $session, SignalCodec::string($data, 'chat'), SignalCodec::string($data, 'sender'), SignalCodec::string($data, 'message_id'), SignalCodec::integer($data, 'timestamp'), SignalCodec::boolean($data, 'is_from_me'), SignalCodec::boolean($data, 'redelivered'), SignalCodec::boolean($data, 'identity_changed'), $proto, $raw, SignalCodec::optionalString($data, 'sender_alt'), SignalCodec::optionalString($data, 'text'), $media, $history); + return new self($id, $type, $session, SignalCodec::string($data, 'chat'), SignalCodec::string($data, 'sender'), SignalCodec::string($data, 'message_id'), SignalCodec::integer($data, 'timestamp'), SignalCodec::boolean($data, 'is_from_me'), SignalCodec::boolean($data, 'redelivered'), SignalCodec::boolean($data, 'identity_changed'), $proto, $raw, SignalCodec::optionalString($data, 'sender_alt'), SignalCodec::optionalString($data, 'text'), $media, $history, $statusScope); } /** @return array{redacted:true} */public function __debugInfo(): array { diff --git a/packages/php/src/WebhookModels.php b/packages/php/src/WebhookModels.php index b55c6281d..82ef451d9 100644 --- a/packages/php/src/WebhookModels.php +++ b/packages/php/src/WebhookModels.php @@ -17,7 +17,12 @@ * @phpstan-type Conversation array{id:string,phoneNumber?:string,bsuid?:string,parentBsuid?:string,username?:string,sender?:Identity} * @phpstan-type NativeFlow array{name:string,paramsJson:string,version?:int|float} * @phpstan-type ReplyChoice array{kind:'button'|'list',id:string} - * @phpstan-type LinkedMessage array{id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,conversation:Conversation,fromMe:bool,timestamp:int|float,pushName:string,isGroup:bool,type:'text'|'image'|'video'|'audio'|'document'|'location'|'contact'|'phone_number_shared'|'native_flow_response'|'button_reply'|'list_reply'|'poll'|'sticker'|'reaction'|'revoke'|'edited'|'unknown',text?:string,caption?:string,mimeType?:string,ptt?:bool,filename?:string,latitude?:int|float,longitude?:int|float,displayName?:string,title?:string,reaction?:string,reactionTo?:string,revokedId?:string,media?:string,mediaUrl?:string,edited?:bool,pollOptions?:list,unavailable?:bool,unavailableReason?:string,nativeFlowResponse?:NativeFlow,replyChoice?:ReplyChoice,parentMessageId?:string,...} + * @phpstan-type ReceivedContent array{type:'text'|'image'|'video'|'audio'|'document'|'location'|'contact'|'phone_number_shared'|'native_flow_response'|'button_reply'|'list_reply'|'poll'|'sticker'|'reaction'|'revoke'|'edited'|'unknown',text?:string,caption?:string,mimeType?:string,ptt?:bool,filename?:string,latitude?:int|float,longitude?:int|float,displayName?:string,title?:string,reaction?:string,reactionTo?:string,revokedId?:string,media?:string,mediaUrl?:string,edited?:bool,pollOptions?:list,unavailable?:bool,unavailableReason?:string,nativeFlowResponse?:NativeFlow,replyChoice?:ReplyChoice,parentMessageId?:string,...} + * @phpstan-type LinkedMessage array{id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,conversation:Conversation,fromMe:bool,timestamp:int|float,pushName:string,isGroup:bool,...}&ReceivedContent + * @phpstan-type PersonalStatusPublication array{id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,fromMe:bool,timestamp:int,pushName:string,content:ReceivedContent,scope:'personal',publisher:Identity} + * @phpstan-type GroupStatusPublication array{id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,fromMe:bool,timestamp:int,pushName:string,content:ReceivedContent,scope:'group',publisher:Identity,group:Identity} + * @phpstan-type ChannelStatusPublication array{id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,fromMe:bool,timestamp:int,pushName:string,content:ReceivedContent,scope:'channel',channel:Identity} + * @phpstan-type StatusPublication PersonalStatusPublication|GroupStatusPublication|ChannelStatusPublication * @phpstan-type CloudMessage array{order?:CloudOrder,id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,conversation:Conversation,timestamp:string,type:string,senderName?:string,nativeFlowResponse?:NativeFlow,replyChoice?:ReplyChoice,parentMessageId?:string,interactive?:array,referral?:array{source_type?:string,source_id?:string,source_url?:string,ctwa_clid?:string,...},...} * @phpstan-type Received LinkedMessage|CloudMessage * @phpstan-type Sent array{id:string,whatsapp_ids:MessageIds,whatsapp_id?:string,conversation:Conversation,type:string,timestamp:int|float} @@ -96,7 +101,7 @@ * @phpstan-type CampaignCold array{campaignId:string,recipientId:string,phone:string,surface:string,reason:string,at:int|float} * @phpstan-type VoiceReady array{eventId:string,occurredAt:string,teamId:string,projectId:string,assetId:string,name:string,source:string,durationMs:int|float,contentSha256:string,originalFormat:string} * @phpstan-type VoiceFailed array{eventId:string,occurredAt:string,teamId:string,projectId:string,assetId:string,name:string,source:string,failureReason:string} - * @phpstan-type KnownEvent array{id:string,session:string,externalId?:string,timestamp:string,event:'marketing.onboarding_updated',payload:MarketingOnboarding}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.marketing_preference_updated',payload:MarketingPreference}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.received'|'message.reaction',payload:Received}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.edited'|'message.revoked'|'message.update',payload:LinkedMessage}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.sent',payload:Sent}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.ack',payload:Ack}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.delete',payload:Deleted}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.vote',payload:Vote}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.failed',payload:Failed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.echo',payload:array{source:'whatsapp_business_app',value:array}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.status',payload:RuntimeStatus|CloudStatus}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.connected',payload:Connected}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.logged_out',payload:array{reason:'banned'|'device_removed'|'unknown',code:int|float}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.phone_offline',payload:Offline}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.restriction_updated',payload:Restriction}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.capabilities_updated',payload:array{session:string,projectId:string,status:'synced'|'unknown',syncedAt:?string,checkedAt:?string,accountType:'business'|'personal'|null,capabilities:list,changedKeys:list}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'group.update',payload:GroupUpdate}|array{id:string,session:string,externalId?:string,timestamp:string,event:'group.participant',payload:GroupParticipant}|array{id:string,session:string,externalId?:string,timestamp:string,event:'presence.update',payload:Presence}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.opted_in'|'contact.opted_out',payload:ContactOpt}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.update',payload:ContactUpdate}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.sync',payload:array{kind:'contacts',value:array}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.archive',payload:Archive}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.mute',payload:Mute}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.read',payload:Read}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.clear'|'chat.delete',payload:array{from:Identity}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.received',payload:CallReceived}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.accepted',payload:CallAccepted}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.rejected',payload:array{from:Identity,callId:string}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.missed',payload:array{from:Identity,callId:string,reason:string}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.ended',payload:CallEnded}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.telemetry',payload:CallTelemetry}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.participant_joined'|'call.participant_state',payload:ParticipantEvent}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.participant_left',payload:array{callId:string,participantId:string,reason?:string}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.connection_joined',payload:ConnectionJoined}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.connection_left',payload:ConnectionLeft}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.permission_changed',payload:Permission}|array{id:string,session:string,externalId?:string,timestamp:string,event:'order.payment_updated',payload:PaymentStatus|PaymentMethod}|array{id:string,session:string,externalId?:string,timestamp:string,event:'newsletter.update',payload:array{id:string,action:string,muted?:bool}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'blocklist.update',payload:Blocklist}|array{id:string,session:string,externalId?:string,timestamp:string,event:'labels.update',payload:Labels}|array{id:string,session:string,externalId?:string,timestamp:string,event:'history.sync',payload:LinkedHistory|DirectHistory|array{kind:'history',value:array}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'command.result',payload:Command}|array{id:string,session:string,externalId?:string,timestamp:string,event:'business.quick_reply.update',payload:QuickReply}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.created'|'customer.archived'|'customer.restored',payload:Customer}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.updated',payload:CustomerUpdated}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.enabled',payload:CustomerEnabled}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.archiving',payload:CustomerArchiving}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.created'|'customer.pairing_link.opened'|'customer.pairing_link.expired',payload:Pairing}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.connected',payload:PairingConnected}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.failed',payload:PairingFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.revoked',payload:PairingRevoked}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.number.attached',payload:NumberAttached}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.number.transferred',payload:NumberTransferred}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.number.disconnected',payload:NumberDisconnected}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.health_threshold',payload:HealthThreshold}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.action',payload:BanSafeAction}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.incident',payload:BanSafeIncident}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.claim',payload:BanSafeClaim}|array{id:string,session:string,externalId?:string,timestamp:string,event:'template.status',payload:RuntimeTemplate|CloudTemplate}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.launched',payload:CampaignLaunched}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.paused',payload:CampaignPaused}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.rescheduled',payload:CampaignRescheduled}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.resumed',payload:CampaignResumed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.completed',payload:CampaignCompleted}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.failed',payload:CampaignFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.stopped',payload:CampaignStopped}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.recipient_sent',payload:RecipientSent}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.recipient_failed',payload:RecipientFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.recipient_skipped',payload:RecipientSkipped}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.throttled',payload:CampaignThrottled}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.cap_reached',payload:CampaignCap}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.cold_blocked',payload:CampaignCold}|array{id:string,session:string,externalId?:string,timestamp:string,event:'usage.recorded',payload:UsageRecord}|array{id:string,session:string,externalId?:string,timestamp:string,event:'voice.asset_ready',payload:VoiceReady}|array{id:string,session:string,externalId?:string,timestamp:string,event:'voice.asset_failed',payload:VoiceFailed} + * @phpstan-type KnownEvent array{id:string,session:string,externalId?:string,timestamp:string,event:'marketing.onboarding_updated',payload:MarketingOnboarding}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.marketing_preference_updated',payload:MarketingPreference}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.received'|'message.reaction',payload:Received}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.edited'|'message.revoked'|'message.update',payload:LinkedMessage}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.sent',payload:Sent}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.ack',payload:Ack}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.delete',payload:Deleted}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.vote',payload:Vote}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.failed',payload:Failed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'message.echo',payload:array{source:'whatsapp_business_app',value:array}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.status',payload:RuntimeStatus|CloudStatus}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.connected',payload:Connected}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.logged_out',payload:array{reason:'banned'|'device_removed'|'unknown',code:int|float}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.phone_offline',payload:Offline}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.restriction_updated',payload:Restriction}|array{id:string,session:string,externalId?:string,timestamp:string,event:'session.capabilities_updated',payload:array{session:string,projectId:string,status:'synced'|'unknown',syncedAt:?string,checkedAt:?string,accountType:'business'|'personal'|null,capabilities:list,changedKeys:list}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'group.update',payload:GroupUpdate}|array{id:string,session:string,externalId?:string,timestamp:string,event:'group.participant',payload:GroupParticipant}|array{id:string,session:string,externalId?:string,timestamp:string,event:'presence.update',payload:Presence}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.opted_in'|'contact.opted_out',payload:ContactOpt}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.update',payload:ContactUpdate}|array{id:string,session:string,externalId?:string,timestamp:string,event:'contact.sync',payload:array{kind:'contacts',value:array}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.archive',payload:Archive}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.mute',payload:Mute}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.read',payload:Read}|array{id:string,session:string,externalId?:string,timestamp:string,event:'chat.clear'|'chat.delete',payload:array{from:Identity}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.received',payload:CallReceived}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.accepted',payload:CallAccepted}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.rejected',payload:array{from:Identity,callId:string}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.missed',payload:array{from:Identity,callId:string,reason:string}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.ended',payload:CallEnded}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.telemetry',payload:CallTelemetry}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.participant_joined'|'call.participant_state',payload:ParticipantEvent}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.participant_left',payload:array{callId:string,participantId:string,reason?:string}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.connection_joined',payload:ConnectionJoined}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.connection_left',payload:ConnectionLeft}|array{id:string,session:string,externalId?:string,timestamp:string,event:'call.permission_changed',payload:Permission}|array{id:string,session:string,externalId?:string,timestamp:string,event:'order.payment_updated',payload:PaymentStatus|PaymentMethod}|array{id:string,session:string,externalId?:string,timestamp:string,event:'newsletter.update',payload:array{id:string,action:string,muted?:bool}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'blocklist.update',payload:Blocklist}|array{id:string,session:string,externalId?:string,timestamp:string,event:'labels.update',payload:Labels}|array{id:string,session:string,externalId?:string,timestamp:string,event:'history.sync',payload:LinkedHistory|DirectHistory|array{kind:'history',value:array}}|array{id:string,session:string,externalId?:string,timestamp:string,event:'command.result',payload:Command}|array{id:string,session:string,externalId?:string,timestamp:string,event:'business.quick_reply.update',payload:QuickReply}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.created'|'customer.archived'|'customer.restored',payload:Customer}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.updated',payload:CustomerUpdated}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.enabled',payload:CustomerEnabled}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.archiving',payload:CustomerArchiving}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.created'|'customer.pairing_link.opened'|'customer.pairing_link.expired',payload:Pairing}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.connected',payload:PairingConnected}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.failed',payload:PairingFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.pairing_link.revoked',payload:PairingRevoked}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.number.attached',payload:NumberAttached}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.number.transferred',payload:NumberTransferred}|array{id:string,session:string,externalId?:string,timestamp:string,event:'customer.number.disconnected',payload:NumberDisconnected}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.health_threshold',payload:HealthThreshold}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.action',payload:BanSafeAction}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.incident',payload:BanSafeIncident}|array{id:string,session:string,externalId?:string,timestamp:string,event:'bansafe.claim',payload:BanSafeClaim}|array{id:string,session:string,externalId?:string,timestamp:string,event:'template.status',payload:RuntimeTemplate|CloudTemplate}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.launched',payload:CampaignLaunched}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.paused',payload:CampaignPaused}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.rescheduled',payload:CampaignRescheduled}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.resumed',payload:CampaignResumed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.completed',payload:CampaignCompleted}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.failed',payload:CampaignFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.stopped',payload:CampaignStopped}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.recipient_sent',payload:RecipientSent}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.recipient_failed',payload:RecipientFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.recipient_skipped',payload:RecipientSkipped}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.throttled',payload:CampaignThrottled}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.cap_reached',payload:CampaignCap}|array{id:string,session:string,externalId?:string,timestamp:string,event:'campaign.cold_blocked',payload:CampaignCold}|array{id:string,session:string,externalId?:string,timestamp:string,event:'usage.recorded',payload:UsageRecord}|array{id:string,session:string,externalId?:string,timestamp:string,event:'voice.asset_ready',payload:VoiceReady}|array{id:string,session:string,externalId?:string,timestamp:string,event:'voice.asset_failed',payload:VoiceFailed}|array{id:string,session:string,externalId?:string,timestamp:string,event:'status.received',payload:StatusPublication}|array{id:string,session:string,externalId?:string,timestamp:string,event:'status.update',payload:StatusPublication}|array{id:string,session:string,externalId?:string,timestamp:string,event:'status.revoked',payload:StatusPublication} */ final class WebhookModels { diff --git a/packages/php/src/Webhooks.php b/packages/php/src/Webhooks.php index 2d81de731..17efc73c2 100644 --- a/packages/php/src/Webhooks.php +++ b/packages/php/src/Webhooks.php @@ -19,6 +19,7 @@ final class Webhooks 'customer.pairing_link.connected', 'customer.pairing_link.created', 'customer.pairing_link.expired', 'customer.pairing_link.failed', 'customer.pairing_link.opened', 'customer.pairing_link.revoked', 'customer.restored', 'customer.updated', 'group.participant', 'group.update', 'history.sync', 'labels.update', 'message.ack', 'message.delete', 'message.echo', 'message.edited', + 'status.received', 'status.update', 'status.revoked', 'message.failed', 'message.reaction', 'message.received', 'message.revoked', 'message.sent', 'message.update', 'message.vote', 'newsletter.update', 'order.payment_updated', 'presence.update', 'session.capabilities_updated', 'session.connected', 'session.logged_out', 'session.phone_offline', 'session.restriction_updated', 'session.status', 'template.status', diff --git a/packages/php/tests/analytics.php b/packages/php/tests/analytics.php index f8df7caf6..6b7726c2e 100644 --- a/packages/php/tests/analytics.php +++ b/packages/php/tests/analytics.php @@ -31,7 +31,11 @@ $listener = stream_socket_server('tcp://127.0.0.1:0', $errno, $error); $address = stream_socket_get_name($listener, false); fclose($listener); -$process = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/analytics-server.php'], [0 => ['pipe','r'],1 => ['pipe','w'],2 => ['pipe','w']], $pipes); +$httpLog = tmpfile(); +if ($httpLog === false) { + throw new RuntimeException('Cannot create fixture server log.'); +} +$process = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/analytics-server.php'], [0 => ['pipe','r'],1 => $httpLog,2 => $httpLog], $pipes); try { $http = new GuzzleHttp\Client(['http_errors' => false]); for ($attempt = 0;$attempt < 100;$attempt++) { @@ -52,4 +56,5 @@ foreach ($pipes as $pipe) { fclose($pipe); } proc_close($process); + fclose($httpLog); } diff --git a/packages/php/tests/call-records.php b/packages/php/tests/call-records.php index 97f3d3f08..a04e05322 100644 --- a/packages/php/tests/call-records.php +++ b/packages/php/tests/call-records.php @@ -28,7 +28,11 @@ $listener = stream_socket_server('tcp://127.0.0.1:0', $errno, $error); $address = stream_socket_get_name($listener, false); fclose($listener); -$process = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/call-export-server.php'], [0 => ['pipe','r'],1 => ['pipe','w'],2 => ['pipe','w']], $pipes); +$httpLog = tmpfile(); +if ($httpLog === false) { + throw new RuntimeException('Cannot create fixture server log.'); +} +$process = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/call-export-server.php'], [0 => ['pipe','r'],1 => $httpLog,2 => $httpLog], $pipes); try { $http = new GuzzleHttp\Client(['http_errors' => false]); for ($attempt = 0;$attempt < 100;$attempt++) { @@ -48,4 +52,5 @@ foreach ($pipes as $pipe) { fclose($pipe); } proc_close($process); + fclose($httpLog); } diff --git a/packages/php/tests/calls_runtime.php b/packages/php/tests/calls_runtime.php index 1bb01b4e6..a8d45fe49 100644 --- a/packages/php/tests/calls_runtime.php +++ b/packages/php/tests/calls_runtime.php @@ -112,7 +112,11 @@ function callsCheck(bool $condition, string $message): void $address = stream_socket_get_name($httpSocket, false); fclose($httpSocket); $httpUrl = 'http://'.$address; -$http = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/calls-runtime-http.php'], [['pipe','r'],['pipe','w'],['pipe','w']], $httpPipes, null, $env); +$httpLog = tmpfile(); +if ($httpLog === false) { + throw new RuntimeException('Cannot create fixture server log.'); +} +$http = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/calls-runtime-http.php'], [['pipe','r'],$httpLog,$httpLog], $httpPipes, null, $env); $ws = proc_open([PHP_BINARY,__DIR__.'/calls-runtime-server.php'], [['pipe','r'],['pipe','w'],['pipe','w']], $wsPipes, null, $env); try { $wire = json_decode(fgets($wsPipes[1]), true, flags:JSON_THROW_ON_ERROR); @@ -225,6 +229,7 @@ function callsCheck(bool $condition, string $message): void fclose($pipe); } proc_close($process); } + fclose($httpLog); foreach (glob($state.'.*') as $file) { unlink($file); } diff --git a/packages/php/tests/native.php b/packages/php/tests/native.php index 8147df01e..cce0d4c8c 100644 --- a/packages/php/tests/native.php +++ b/packages/php/tests/native.php @@ -13,7 +13,9 @@ function nativeCases(array $cases, callable $makeClient, ?Polymorfa\Credential $ $socket = stream_socket_server('tcp://127.0.0.1:0', $errno, $error); $address = stream_socket_get_name($socket, false); fclose($socket); - $server = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/native-server.php'], [0 => ['pipe','r'],1 => ['pipe','w'],2 => ['pipe','w']], $pipes, null, ['POLYMORFA_PHP_WIRE_STATE' => $state] + getenv()); + // PHP's request logs can fill an unread pipe and stall the fixture server. + $serverLog = $scratch.'/server-'.getmypid().'.log'; + $server = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/native-server.php'], [0 => ['pipe','r'],1 => ['file',$serverLog,'a'],2 => ['file',$serverLog,'a']], $pipes, null, ['POLYMORFA_PHP_WIRE_STATE' => $state] + getenv()); if (!is_resource($server)) { throw new RuntimeException('Cannot start native PHP fixture server.'); } diff --git a/packages/php/tests/raw_parity.php b/packages/php/tests/raw_parity.php index 85f65b44a..cee005596 100644 --- a/packages/php/tests/raw_parity.php +++ b/packages/php/tests/raw_parity.php @@ -28,7 +28,11 @@ $socket = stream_socket_server('tcp://127.0.0.1:0', $errno, $message); $address = stream_socket_get_name($socket, false); fclose($socket); -$server = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/raw-pagination-server.php'], [0 => ['pipe','r'],1 => ['pipe','w'],2 => ['pipe','w']], $pipes, null, ['POLYMORFA_RAW_PAGINATION_STATE' => $state] + getenv()); +$httpLog = tmpfile(); +if ($httpLog === false) { + throw new RuntimeException('Cannot create fixture server log.'); +} +$server = proc_open([PHP_BINARY,'-S',$address,__DIR__.'/raw-pagination-server.php'], [0 => ['pipe','r'],1 => $httpLog,2 => $httpLog], $pipes, null, ['POLYMORFA_RAW_PAGINATION_STATE' => $state] + getenv()); $http = new GuzzleHttp\Client(['timeout' => 3]); try { for ($i = 0;$i < 100;$i++) { @@ -71,6 +75,7 @@ foreach ($pipes as $pipe) { fclose($pipe); } proc_close($server); + fclose($httpLog); unlink($state); } echo "Raw JSON, decoded pagination, project confinement and Graph header native checks passed.\n"; diff --git a/packages/php/tests/webhook_models.php b/packages/php/tests/webhook_models.php index dc2109d80..cedcd53fb 100644 --- a/packages/php/tests/webhook_models.php +++ b/packages/php/tests/webhook_models.php @@ -7,7 +7,9 @@ $cloud = ['id' => 'message','whatsapp_ids' => ['official_api' => 'wamid.fixture'],'conversation' => ['id' => 'business-user','bsuid' => 'business-user'],'timestamp' => '1','type' => 'interactive','nativeFlowResponse' => ['name' => 'flow','paramsJson' => '{"answer":false}'],'replyChoice' => ['kind' => 'button','id' => 'choice'],'referral' => ['ctwa_clid' => 'click','source_id' => 'ad']]; $customer = ['eventId' => 'event','occurredAt' => 'now','teamId' => 'team','projectId' => 'project','customerId' => 'customer','actorKind' => 'team_key']; $payment = ['reportedBy' => 'whatsapp','providerEventId' => 'provider','referenceId' => 'order','conversation' => ['phoneNumber' => '+15555555555']]; +$status = ['id'=>'123','whatsapp_ids'=>$messageIds,'scope'=>'personal','publisher'=>['id'=>'456'],'fromMe'=>false,'timestamp'=>1700000000,'pushName'=>'Authored','content'=>['type'=>'text','text'=>'publication']]; $cases = [ + ['status.received',$status],['status.update',$status],['status.revoked',$status], ['marketing.onboarding_updated',['kind'=>'terms_signed','wabaId'=>'w','metaEvent'=>'MM_LITE_TERMS_SIGNED']], ['contact.marketing_preference_updated',['waId'=>'opaque','preference'=>'stop','category'=>'marketing_messages']], ['message.received',$linked],['message.received',$cloud],['message.reaction',$linked], @@ -52,7 +54,7 @@ foreach (Polymorfa\Webhooks::KNOWN_TYPES as $name) { check(str_contains($source, "'".$name."'"), 'Every known name has a typed union variant: '.$name); } -check(count(Polymorfa\Webhooks::KNOWN_TYPES) === 86, 'Pinned known event catalog'); +check(count(Polymorfa\Webhooks::KNOWN_TYPES) === 89, 'Pinned known event catalog'); $raw = '{"id":"event","session":"","timestamp":"now","event":"future.event","payload":null}'; $flow = 't=1000,v1='.strtoupper(hash_hmac('sha256', '1000.'.$raw, 'secret')); check(Polymorfa\Webhooks::verifyFlowForwardSignature($raw, $flow, 'secret', nowUnixSeconds:1000.5), 'Flow raw HMAC and uppercase signature'); @@ -75,3 +77,6 @@ check(Polymorfa\ErrorCodes::isKnown('whatsapp_payment_method_required'), 'Known Official API code: whatsapp_payment_method_required'); check((new Polymorfa\PolymorfaException('Fixture', 'future_api_code'))->errorCode === 'future_api_code', 'Unknown API codes preserved'); echo count($cases)." signed typed webhook fixtures, 84 union variants and signature utility checks passed.\n"; + +$remoteStatus = Polymorfa\SignalEvent::fromJson('{"id":"authored-status-event","type":"status.received","status_scope":"personal","session_id":"authored-session","chat":"status@broadcast","sender":"123@s.whatsapp.net","message_id":"authored-publication","timestamp":1700000000,"is_from_me":false,"redelivered":false,"identity_changed":false,"message_proto":"CgdmaXh0dXJl","text":"authored publication"}'); +check($remoteStatus->type === 'status.received' && $remoteStatus->statusScope === 'personal', 'Remote status scope stays separate from messages'); diff --git a/packages/python/README.md b/packages/python/README.md index 362ebd789..d010947e1 100644 --- a/packages/python/README.md +++ b/packages/python/README.md @@ -1005,3 +1005,17 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP path; programmatic media WebSocket controls retain their credential rechecks. This source requires the matching unreleased backend. It does not enable a customer environment or advance package/API availability. + +### Candidate status publication events + +The source models recognize `status.received`, `status.update` and +`status.revoked` separately from message events. Their payload shares received +content types and identifies `scope` as `personal`, `group` or `channel`. +Personal and group publications identify their publisher; group and channel +publications identify their respective audience. Replies and mentions remain +message events. Status publications do not create a chat conversation. + +These events have no released API or SDK version and are unavailable in staging +and production. Keep existing subscriptions until a release notice confirms +availability for your API version. The separately pinned candidate contract +does not advance the accepted API baseline or authorize package publication. diff --git a/packages/python/coverage.json b/packages/python/coverage.json index e41b61eeb..40b852402 100644 --- a/packages/python/coverage.json +++ b/packages/python/coverage.json @@ -5388,6 +5388,14 @@ "language": "python", "baselineUnchanged": true, "published": false + }, + "statusPublicationsCandidate": { + "inventory": "contracts/status-publications.candidate.json", + "baselineUnchanged": true, + "published": false, + "sourceAccepted": false, + "sourceCommit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "scope": "Only the three status publication events, shared received content and existing Signal event parser extensions; no whole-contract or deployment claim." } } } diff --git a/packages/python/src/polymorfa/__init__.py b/packages/python/src/polymorfa/__init__.py index 1aa4288a6..da66bae7c 100644 --- a/packages/python/src/polymorfa/__init__.py +++ b/packages/python/src/polymorfa/__init__.py @@ -572,6 +572,13 @@ from .official_round2 import ( MarketingMessagesStatus as MarketingMessagesStatus, ) +from .webhook_models import ( + ChannelStatusPublication, + GroupStatusPublication, + PersonalStatusPublication, + ReceivedContent, + StatusPublicationPayload, +) from .webhooks import ( WebhookDelivery as WebhookDelivery, ) @@ -584,3 +591,11 @@ from .webhooks import ( parse_verified_webhook_delivery as parse_verified_webhook_delivery, ) + +__all__ += [ + "ChannelStatusPublication", + "GroupStatusPublication", + "PersonalStatusPublication", + "ReceivedContent", + "StatusPublicationPayload", +] diff --git a/packages/python/src/polymorfa/signal_node.py b/packages/python/src/polymorfa/signal_node.py index 8bbb7e8d9..1306ef629 100644 --- a/packages/python/src/polymorfa/signal_node.py +++ b/packages/python/src/polymorfa/signal_node.py @@ -279,7 +279,7 @@ def inline_bytes(self) -> bytes | None: @dataclass(frozen=True, repr=False) class SignalNodeEvent: id: str - type: Literal["message", "history.sync"] + type: Literal["message", "history.sync", "status.received"] session_id: str chat: str sender: str @@ -294,6 +294,7 @@ class SignalNodeEvent: media: SignalMediaDescriptor | None = None history: SignalHistoryDescriptor | None = None raw: dict[str, Json] = field(default_factory=dict) + status_scope: str | None = None def __repr__(self) -> str: return "SignalNodeEvent()" @@ -302,11 +303,16 @@ def __repr__(self) -> str: def from_wire(cls, value: object) -> SignalNodeEvent: data = _record(value) kind = data.get("type") - if kind not in ("message", "history.sync"): + if kind not in ("message", "history.sync", "status.received"): + raise _invalid() + scope = data.get("status_scope") + if scope is not None and not isinstance(scope, str): + raise _invalid() + if kind == "status.received" and scope not in ("personal", "group", "channel"): raise _invalid() return cls( _string(data.get("id")), - cast(Literal["message", "history.sync"], kind), + cast(Literal["message", "history.sync", "status.received"], kind), _string(data.get("session_id")), _string(data.get("chat")), _string(data.get("sender")), @@ -325,6 +331,7 @@ def from_wire(cls, value: object) -> SignalNodeEvent: if data.get("history") is not None else None, data, + scope, ) def message_bytes(self) -> bytes: diff --git a/packages/python/src/polymorfa/webhook_models.py b/packages/python/src/polymorfa/webhook_models.py index 8723722ad..572f92f8f 100644 --- a/packages/python/src/polymorfa/webhook_models.py +++ b/packages/python/src/polymorfa/webhook_models.py @@ -59,6 +59,7 @@ class PollOption(TypedDict): "list_reply", "poll", "sticker", + "sticker_pack", "reaction", "revoke", "edited", @@ -66,15 +67,7 @@ class PollOption(TypedDict): ] -class LinkedDeviceMessagePayload(TypedDict): - id: str - whatsapp_ids: WhatsAppMessageIds - whatsapp_id: NotRequired[str] - conversation: ConversationReference - fromMe: bool - timestamp: float - pushName: str - isGroup: bool +class ReceivedContent(TypedDict): type: LinkedDeviceMessageType text: NotRequired[str] caption: NotRequired[str] @@ -99,6 +92,48 @@ class LinkedDeviceMessagePayload(TypedDict): parentMessageId: NotRequired[str] +class LinkedDeviceMessagePayload(ReceivedContent): + id: str + whatsapp_ids: WhatsAppMessageIds + whatsapp_id: NotRequired[str] + conversation: ConversationReference + fromMe: bool + timestamp: float + pushName: str + isGroup: bool + + +class StatusPublicationBase(TypedDict): + id: str + whatsapp_ids: WhatsAppMessageIds + whatsapp_id: NotRequired[str] + fromMe: bool + timestamp: float + pushName: str + content: ReceivedContent + + +class PersonalStatusPublication(StatusPublicationBase): + scope: Literal["personal"] + publisher: IdentityReference + + +class GroupStatusPublication(StatusPublicationBase): + scope: Literal["group"] + publisher: IdentityReference + group: IdentityReference + + +class ChannelStatusPublication(StatusPublicationBase): + scope: Literal["channel"] + channel: IdentityReference + + +StatusPublicationPayload = ( + PersonalStatusPublication | GroupStatusPublication | ChannelStatusPublication +) + + MessagePayload = LinkedDeviceMessagePayload diff --git a/packages/python/src/polymorfa/webhook_types.py b/packages/python/src/polymorfa/webhook_types.py index 241150552..f9a914b64 100644 --- a/packages/python/src/polymorfa/webhook_types.py +++ b/packages/python/src/polymorfa/webhook_types.py @@ -8,6 +8,15 @@ from .webhook_models import TypedWebhookEvent +@overload +def is_event( + event: TypedWebhookEvent[str, object], + event_type: Literal["status.received", "status.update", "status.revoked"], +) -> TypeGuard[ + TypedWebhookEvent[ + Literal["status.received", "status.update", "status.revoked"], m.StatusPublicationPayload + ] +]: ... @overload def is_event( event: TypedWebhookEvent[str, object], event_type: Literal["marketing.onboarding_updated"] diff --git a/packages/python/src/polymorfa/webhooks.py b/packages/python/src/polymorfa/webhooks.py index 3b2991818..0effac751 100644 --- a/packages/python/src/polymorfa/webhooks.py +++ b/packages/python/src/polymorfa/webhooks.py @@ -92,6 +92,9 @@ "message.edited", "message.failed", "message.reaction", + "status.received", + "status.update", + "status.revoked", "message.received", "message.revoked", "message.sent", diff --git a/packages/python/tests/test_status_signal_event.py b/packages/python/tests/test_status_signal_event.py new file mode 100644 index 000000000..0510fe4df --- /dev/null +++ b/packages/python/tests/test_status_signal_event.py @@ -0,0 +1,21 @@ +import json + +from polymorfa.signal_node import SignalNodeEvent + + +def test_remote_status_keeps_scope_without_becoming_a_message() -> None: + event = SignalNodeEvent.from_wire( + json.loads( + '{"id":"authored-status-event","type":"status.received","status_scope":"personal","session_id":"authored-session","chat":"status@broadcast","sender":"123@s.whatsapp.net","message_id":"authored-publication","timestamp":1700000000,"is_from_me":false,"redelivered":false,"identity_changed":false,"message_proto":"CgdmaXh0dXJl","text":"authored publication"}' + ) + ) + assert event.type == "status.received" + assert event.status_scope == "personal" + assert event.chat == "status@broadcast" + + +def test_status_sticker_pack_is_a_typed_received_content() -> None: + from polymorfa.webhook_models import ReceivedContent + + content: ReceivedContent = {"type": "sticker_pack"} + assert content["type"] == "sticker_pack" diff --git a/packages/python/tests/test_webhook_models.py b/packages/python/tests/test_webhook_models.py index e06189c48..5c5b0d402 100644 --- a/packages/python/tests/test_webhook_models.py +++ b/packages/python/tests/test_webhook_models.py @@ -719,6 +719,22 @@ ), ] +CASES += [ + ( + ("status.received", "status.update", "status.revoked"), + { + "id": "123", + "whatsapp_ids": IDS, + "scope": "personal", + "publisher": IDENTITY, + "fromMe": False, + "timestamp": 1700000000, + "pushName": "Authored", + "content": {"type": "text", "text": "publication"}, + }, + ), +] + EXPANDED = [(event_type, payload) for types, payload in CASES for event_type in types] diff --git a/packages/rust/README.md b/packages/rust/README.md index dfc1ea4e3..f276efae9 100644 --- a/packages/rust/README.md +++ b/packages/rust/README.md @@ -1125,3 +1125,17 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP path; programmatic media WebSocket controls retain their credential rechecks. This source requires the matching unreleased backend. It does not enable a customer environment or advance package/API availability. + +### Candidate status publication events + +The source models recognize `status.received`, `status.update` and +`status.revoked` separately from message events. Their payload shares received +content types and identifies `scope` as `personal`, `group` or `channel`. +Personal and group publications identify their publisher; group and channel +publications identify their respective audience. Replies and mentions remain +message events. Status publications do not create a chat conversation. + +These events have no released API or SDK version and are unavailable in staging +and production. Keep existing subscriptions until a release notice confirms +availability for your API version. The separately pinned candidate contract +does not advance the accepted API baseline or authorize package publication. diff --git a/packages/rust/coverage.json b/packages/rust/coverage.json index 16bbadce3..c0ed3ee60 100644 --- a/packages/rust/coverage.json +++ b/packages/rust/coverage.json @@ -5388,6 +5388,14 @@ "language": "rust", "baselineUnchanged": true, "published": false + }, + "statusPublicationsCandidate": { + "inventory": "contracts/status-publications.candidate.json", + "baselineUnchanged": true, + "published": false, + "sourceAccepted": false, + "sourceCommit": "b7b3534c37a671344f291986e2329bb743b5cbdc", + "scope": "Only the three status publication events, shared received content and existing Signal event parser extensions; no whole-contract or deployment claim." } } } diff --git a/packages/rust/src/signal.rs b/packages/rust/src/signal.rs index 60433789e..6f5ab8edb 100644 --- a/packages/rust/src/signal.rs +++ b/packages/rust/src/signal.rs @@ -118,6 +118,7 @@ pub struct SignalHistoryDescriptor { /// Plaintext stays in the caller's application. Never log the event body. #[derive(Clone, Deserialize)] pub struct SignalEvent { + pub status_scope: Option, pub id: String, #[serde(rename = "type")] pub event_type: String, @@ -137,6 +138,19 @@ pub struct SignalEvent { #[serde(flatten)] pub additional: std::collections::BTreeMap, } +impl SignalEvent { + fn require_status_scope(&self) -> Result<()> { + if self.event_type == "status.received" + && !matches!( + self.status_scope.as_deref(), + Some("personal" | "group" | "channel") + ) + { + return Err(malformed()); + } + Ok(()) + } +} impl SignalMediaDescriptor { pub fn download_descriptor(&self) -> Result { let kind = match self.kind.as_str() { @@ -376,6 +390,7 @@ impl SignalClient { let Some(chunk)=next.map_err(|_|Error::local(ErrorKind::Timeout,"Signal event stream timed out.","request_timeout"))? else {parser.finish()?; break}; for message in parser.feed(&chunk.map_err(|_|network())?)? { let event:SignalEvent=serde_json::from_str(&message.data).map_err(|_|malformed())?; + event.require_status_scope()?; if event.id.is_empty() || message.id.as_deref()!=Some(event.id.as_str()) || message.event!=event.event_type || expected_session.as_ref().is_some_and(|session| session != &event.session_id) {Err(malformed())?;} yield event; } @@ -422,6 +437,7 @@ pub fn verify_signal_webhook( return Err(malformed()); } let event: SignalEvent = serde_json::from_slice(body).map_err(|_| malformed())?; + event.require_status_scope()?; if event.id.is_empty() { return Err(malformed()); } diff --git a/packages/rust/src/webhook_payloads.rs b/packages/rust/src/webhook_payloads.rs index 1a46553d0..3fda412d9 100644 --- a/packages/rust/src/webhook_payloads.rs +++ b/packages/rust/src/webhook_payloads.rs @@ -39,6 +39,7 @@ pub enum LinkedDeviceMessageType { ListReply, Poll, Sticker, + StickerPack, Reaction, Revoke, Edited, @@ -104,6 +105,88 @@ pub struct LinkedDeviceMessagePayload { #[serde(flatten)] pub extensions: BTreeMap, } + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ReceivedContent { + #[serde(rename = "type")] + pub message_type: LinkedDeviceMessageType, + #[serde(skip_serializing_if = "Option::is_none")] + pub text: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub caption: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub mime_type: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ptt: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub filename: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub latitude: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub longitude: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub display_name: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub title: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reaction: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reaction_to: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub revoked_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub media: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub media_url: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub edited: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub poll_options: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub unavailable: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub unavailable_reason: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub native_flow_response: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub reply_choice: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub parent_message_id: Option, + #[serde(flatten)] + pub extensions: BTreeMap, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(tag = "scope", rename_all = "snake_case")] +pub enum StatusAudience { + Personal { + publisher: ConversationIdentity, + }, + Group { + publisher: ConversationIdentity, + group: ConversationIdentity, + }, + Channel { + channel: ConversationIdentity, + }, +} +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StatusPublicationPayload { + pub id: String, + #[serde(rename = "whatsapp_ids")] + pub whatsapp_ids: WhatsAppMessageIds, + #[serde(rename = "whatsapp_id", skip_serializing_if = "Option::is_none")] + pub whatsapp_id: Option, + #[serde(flatten)] + pub audience: StatusAudience, + pub from_me: bool, + pub timestamp: u64, + pub push_name: String, + pub content: ReceivedContent, +} + #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CloudMessageReferral { #[serde(skip_serializing_if = "Option::is_none")] @@ -816,6 +899,12 @@ pub struct SessionCapabilitiesUpdatedPayload { #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "event", content = "payload")] pub enum KnownWebhookPayload { + #[serde(rename = "status.received")] + StatusReceived(Box), + #[serde(rename = "status.update")] + StatusUpdate(Box), + #[serde(rename = "status.revoked")] + StatusRevoked(Box), #[serde(rename = "marketing.onboarding_updated")] MarketingOnboardingUpdated(Box), #[serde(rename = "contact.marketing_preference_updated")] diff --git a/packages/rust/src/webhooks.rs b/packages/rust/src/webhooks.rs index 0db61610b..1d6e42407 100644 --- a/packages/rust/src/webhooks.rs +++ b/packages/rust/src/webhooks.rs @@ -357,6 +357,9 @@ fn signature_error() -> Error { ) } pub const KNOWN_EVENT_TYPES: &[&str] = &[ + "status.received", + "status.update", + "status.revoked", "marketing.onboarding_updated", "contact.marketing_preference_updated", "bansafe.action", diff --git a/packages/rust/tests/status_signal_event.rs b/packages/rust/tests/status_signal_event.rs new file mode 100644 index 000000000..4c08d908d --- /dev/null +++ b/packages/rust/tests/status_signal_event.rs @@ -0,0 +1,41 @@ +#[test] +fn remote_status_preserves_its_scope() { + let event: polymorfa_sdk::signal::SignalEvent = serde_json::from_str(r#"{"id":"authored-status-event","type":"status.received","status_scope":"personal","session_id":"authored-session","chat":"status@broadcast","sender":"123@s.whatsapp.net","message_id":"authored-publication","timestamp":1700000000,"is_from_me":false,"redelivered":false,"identity_changed":false,"message_proto":"CgdmaXh0dXJl","text":"authored publication"}"#).unwrap(); + assert_eq!(event.event_type, "status.received"); + assert_eq!(event.status_scope.as_deref(), Some("personal")); +} + +#[test] +fn verified_status_events_require_a_known_scope_while_messages_do_not() { + use hmac::{Hmac, Mac}; + use polymorfa_sdk::signal::verify_signal_webhook; + use sha2::Sha256; + use std::time::Duration; + for scope in [ + None, + Some(""), + Some("future"), + Some("personal"), + Some("group"), + Some("channel"), + ] { + for event_type in ["message", "status.received"] { + let mut value = serde_json::json!({"id":"authored-status-event","type":event_type,"session_id":"authored-session","chat":"status@broadcast","sender":"123@s.whatsapp.net","message_id":"authored-publication","timestamp":1700000000,"is_from_me":false,"redelivered":false,"identity_changed":false,"message_proto":""}); + if let Some(scope) = scope { + value["status_scope"] = scope.into(); + } + let body = serde_json::to_vec(&value).unwrap(); + let secret = b"authored-signal-webhook-secret"; + let mut mac = Hmac::::new_from_slice(secret).unwrap(); + mac.update(b"100."); + mac.update(&body); + let signature = format!("v1={}", hex::encode(mac.finalize().into_bytes())); + let result = + verify_signal_webhook(secret, 100, &body, &signature, 100, Duration::from_secs(5)); + assert_eq!( + result.is_ok(), + event_type == "message" || matches!(scope, Some("personal" | "group" | "channel")) + ); + } + } +} diff --git a/packages/rust/tests/webhook_payloads.rs b/packages/rust/tests/webhook_payloads.rs index 707ac1b77..092804f43 100644 --- a/packages/rust/tests/webhook_payloads.rs +++ b/packages/rust/tests/webhook_payloads.rs @@ -284,6 +284,18 @@ fn every_pinned_known_event_has_a_typed_verified_payload_and_unknown_events_pres ), ("message.reaction", cloud()), ("message.received", linked()), + ( + "status.received", + json!({"id":"123","whatsapp_ids":ids(),"scope":"personal","publisher":identity(),"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"text","text":"publication"}}), + ), + ( + "status.update", + json!({"id":"123","whatsapp_ids":ids(),"scope":"group","publisher":identity(),"group":identity(),"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"text","text":"publication"}}), + ), + ( + "status.revoked", + json!({"id":"123","whatsapp_ids":ids(),"scope":"channel","channel":identity(),"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"revoke","revokedId":"456"}}), + ), ("message.revoked", linked()), ( "message.sent", @@ -368,6 +380,12 @@ fn every_pinned_known_event_has_a_typed_verified_payload_and_unknown_events_pres pinned["sourceSdkCommit"], "ff51567105b64bf6997e7330ba8eb502d875e7b9" ); + let status_candidate: Value = serde_json::from_str(include_str!( + "../../../contracts/status-publications.candidate.json" + )) + .unwrap(); + assert_eq!(status_candidate["sourceAccepted"], false); + assert_eq!(status_candidate["published"], false); assert_eq!( KNOWN_EVENT_TYPES.iter().copied().collect::>(), pinned["events"] @@ -375,6 +393,13 @@ fn every_pinned_known_event_has_a_typed_verified_payload_and_unknown_events_pres .unwrap() .iter() .map(|event| event.as_str().unwrap()) + .chain( + status_candidate["events"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + ) .collect() ); for (event, expected) in cases { @@ -447,3 +472,32 @@ fn cloud_variants_and_payment_method_selections_preserve_distinct_shapes() { .unwrap(); assert_eq!(encoded["payload"]["timestamp"], "1800000000"); } + +#[test] +fn status_sticker_packs_decode_through_the_verified_event_parser() { + use polymorfa_sdk::webhook_payloads::LinkedDeviceMessageType; + let event = signed( + "status.received", + json!({"id":"123","whatsapp_ids":{"linked_devices":"authored-pack"},"scope":"personal","publisher":{"id":"456"},"fromMe":false,"timestamp":1700000000,"pushName":"Authored","content":{"type":"sticker_pack","stickerPack":{"name":"authored"}}}), + ); + let WebhookEvent::Known { + payload: KnownWebhookPayload::StatusReceived(payload), + .. + } = event + else { + panic!("status classification lost") + }; + assert!(matches!( + payload.content.message_type, + LinkedDeviceMessageType::StickerPack + )); +} + +#[test] +fn existing_message_fields_remain_owned_and_mutable() { + use polymorfa_sdk::webhook_payloads::LinkedDeviceMessagePayload; + let mut payload: LinkedDeviceMessagePayload = serde_json::from_value(linked()).unwrap(); + payload.text = Some("authored direct mutation".into()); + let moved = payload.text; + assert_eq!(moved.as_deref(), Some("authored direct mutation")); +} diff --git a/packages/storage/test/status-publications.test.ts b/packages/storage/test/status-publications.test.ts new file mode 100644 index 000000000..2b372596a --- /dev/null +++ b/packages/storage/test/status-publications.test.ts @@ -0,0 +1,25 @@ +import { describe, it, expect } from "vitest"; +import { reduceEvent, STORED_EVENT_TYPES } from "../src/reducer/events.js"; +import type { WebhookEvent } from "@polymorfa/sdk"; + +describe("status publication storage boundary", () => { + it.each(["status.received", "status.update", "status.revoked"])( + "does not turn %s into chats, contacts or messages", + (event) => { + const publication = { + id: "event", + session: "number", + timestamp: "2026-11-15T00:00:00Z", + event, + payload: { + id: "123", + scope: "personal", + publisher: { id: "456" }, + content: { type: "text", text: "authored publication" }, + }, + } as WebhookEvent; + expect(reduceEvent(publication).operations).toEqual([]); + expect(STORED_EVENT_TYPES).not.toContain(event); + }, + ); +}); diff --git a/packages/typescript/README.md b/packages/typescript/README.md index 9b915ba09..041f15d38 100644 --- a/packages/typescript/README.md +++ b/packages/typescript/README.md @@ -3595,3 +3595,17 @@ or unknown outcome must not be replayed. Browser UI-kit controls use this HTTP path; programmatic media WebSocket controls retain their credential rechecks. This source requires the matching unreleased backend. It does not enable a customer environment or advance package/API availability. + +### Candidate status publication events + +The source models recognize `status.received`, `status.update` and +`status.revoked` separately from message events. Their payload shares received +content types and identifies `scope` as `personal`, `group` or `channel`. +Personal and group publications identify their publisher; group and channel +publications identify their respective audience. Replies and mentions remain +message events. Status publications do not create a chat conversation. + +These events have no released API or SDK version and are unavailable in staging +and production. Keep existing subscriptions until a release notice confirms +availability for your API version. The separately pinned candidate contract +does not advance the accepted API baseline or authorize package publication. diff --git a/packages/typescript/src/index.ts b/packages/typescript/src/index.ts index 49602ff56..b591e14f5 100644 --- a/packages/typescript/src/index.ts +++ b/packages/typescript/src/index.ts @@ -1317,6 +1317,8 @@ export { FLOW_FORWARD_SIGNATURE_HEADER, verifyFlowForwardSignature, type VerifyFlowForwardSignatureOptions, + type ReceivedContent, + type StatusPublicationPayload, } from "./webhooks/index.js"; export type * from "./messaging/session-configuration.js"; diff --git a/packages/typescript/src/webhooks/events.ts b/packages/typescript/src/webhooks/events.ts index f5cbfb5d3..84c6b1c48 100644 --- a/packages/typescript/src/webhooks/events.ts +++ b/packages/typescript/src/webhooks/events.ts @@ -23,6 +23,9 @@ import type { import type { SessionCapabilities } from "../platform/types.js"; export const KNOWN_WEBHOOK_EVENT_TYPES = [ + "status.received", + "status.update", + "status.revoked", "bansafe.action", "bansafe.claim", "bansafe.health_threshold", @@ -160,12 +163,13 @@ export type LinkedDeviceMessageType = | "list_reply" | "poll" | "sticker" + | "sticker_pack" | "reaction" | "revoke" | "edited" | "unknown"; -export interface LinkedDeviceMessagePayload { +export interface LinkedDeviceMessagePayload extends ReceivedContent { readonly order?: IncomingOrderCart; readonly id: string; readonly whatsapp_ids: WhatsAppMessageIds; @@ -176,6 +180,9 @@ export interface LinkedDeviceMessagePayload { readonly timestamp: number; readonly pushName: string; readonly isGroup: boolean; +} + +export interface ReceivedContent { readonly type: LinkedDeviceMessageType; readonly text?: string; readonly caption?: string; @@ -201,6 +208,24 @@ export interface LinkedDeviceMessagePayload { readonly [key: string]: unknown; } +export type StatusPublicationPayload = { + readonly id: string; + readonly whatsapp_ids: WhatsAppMessageIds; + readonly whatsapp_id?: string; + readonly fromMe: boolean; + readonly timestamp: number; + readonly pushName: string; + readonly content: ReceivedContent; +} & ( + | { readonly scope: "personal"; readonly publisher: IdentityReference } + | { + readonly scope: "group"; + readonly publisher: IdentityReference; + readonly group: IdentityReference; + } + | { readonly scope: "channel"; readonly channel: IdentityReference } +); + export type MessagePayload = LinkedDeviceMessagePayload; /** Meta-supplied Click-to-WhatsApp entry point; it does not prove a conversion. */ @@ -1255,6 +1280,9 @@ export interface UsageRecordedPayload { } export interface WebhookPayloadMap { + readonly "status.received": StatusPublicationPayload; + readonly "status.update": StatusPublicationPayload; + readonly "status.revoked": StatusPublicationPayload; readonly "bansafe.action": BanSafeActionPayload; readonly "bansafe.claim": BanSafeClaimPayload; readonly "bansafe.health_threshold": BanSafeHealthThresholdPayload; diff --git a/packages/typescript/src/webhooks/index.ts b/packages/typescript/src/webhooks/index.ts index 2a5ac701f..af5440919 100644 --- a/packages/typescript/src/webhooks/index.ts +++ b/packages/typescript/src/webhooks/index.ts @@ -2,6 +2,8 @@ export { KNOWN_WEBHOOK_EVENT_TYPES, PHONE_OFFLINE_START_DAY, isEvent, + type ReceivedContent, + type StatusPublicationPayload, type BanSafeActionPayload, type BanSafeClaimPayload, type BanSafeEventRung, diff --git a/packages/typescript/test/status-publications.test.ts b/packages/typescript/test/status-publications.test.ts new file mode 100644 index 000000000..ed5e9e7fd --- /dev/null +++ b/packages/typescript/test/status-publications.test.ts @@ -0,0 +1,44 @@ +import { describe, it, expect } from "vitest"; +import { + isEvent, + KNOWN_WEBHOOK_EVENT_TYPES, + type WebhookEvent, + type StatusPublicationPayload, +} from "../src/webhooks/events.js"; + +describe("status publications", () => { + it("narrows a status audience and shares content without inventing a chat", () => { + const payload: StatusPublicationPayload = { + id: "123", + whatsapp_ids: { linked_devices: "authored-status" }, + scope: "group", + publisher: { id: "456" }, + group: { id: "789" }, + fromMe: false, + timestamp: 1700000000, + pushName: "Authored", + content: { type: "text", text: "publication" }, + }; + const event: WebhookEvent = { + id: "event", + session: "number", + timestamp: "2026-11-15T00:00:00Z", + event: "status.received", + payload, + }; + expect(KNOWN_WEBHOOK_EVENT_TYPES).toContain("status.received"); + expect(isEvent(event, "message.received")).toBe(false); + if (!isEvent(event, "status.received")) + throw new Error("status not recognized"); + expect(event.payload.content.text).toBe("publication"); + if (event.payload.scope === "group") + expect(event.payload.group.id).toBe("789"); + expect(event.payload).not.toHaveProperty("conversation"); + }); + it("accepts the candidate sticker-pack content discriminator", () => { + const content: StatusPublicationPayload["content"] = { + type: "sticker_pack", + }; + expect(content.type).toBe("sticker_pack"); + }); +}); diff --git a/packages/typescript/test/webhook-contract.test.ts b/packages/typescript/test/webhook-contract.test.ts index 1618eae76..dd6bc4776 100644 --- a/packages/typescript/test/webhook-contract.test.ts +++ b/packages/typescript/test/webhook-contract.test.ts @@ -88,14 +88,30 @@ const messaging: OpenApiDocument = { }, }, }; +const statusCandidate = JSON.parse( + readFileSync( + resolve(root, "contracts/status-publications.candidate.json"), + "utf8", + ), +) as OpenApiDocument; + const platform = load("platform"); function resolveRef(document: OpenApiDocument, schema: Schema): Schema { if (schema.$ref === undefined) return schema; - const name = schema.$ref.split("/").pop()!; - const target = document.components.schemas[name]; + const parts = schema.$ref + .slice(2) + .split("/") + .map((part) => part.replaceAll("~1", "/").replaceAll("~0", "~")); + let target: unknown = + parts[0] === "components" ? document : document.components.schemas; + for (const part of parts) { + if (target === null || typeof target !== "object") + throw new Error(`Unresolved ${schema.$ref}`); + target = (target as Record)[part]; + } if (target === undefined) throw new Error(`Unresolved ${schema.$ref}`); - return resolveRef(document, target); + return resolveRef(document, target as Schema); } /** Validates a value against the OpenAPI subset used by webhook schemas. */ @@ -246,8 +262,83 @@ const PAYLOADS: { K in Exclude ]: K extends "template.status" ? Shape - : Shape; + : K extends `status.${string}` + ? Shape> + : Shape; } = { + "status.received": shape< + Extract + >()( + { + id: "739182640518204", + whatsapp_ids: { linked_devices: "AUTHORED-STATUS" }, + whatsapp_id: "AUTHORED-STATUS", + scope: "personal", + publisher: { id: "739182640518205" }, + fromMe: false, + timestamp: 1794700800, + pushName: "Authored", + content: { type: "text", text: "authored publication" }, + }, + [ + "id", + "whatsapp_ids", + "scope", + "publisher", + "fromMe", + "timestamp", + "pushName", + "content", + ], + ), + "status.update": shape>()( + { + id: "739182640518204", + whatsapp_ids: { linked_devices: "AUTHORED-STATUS" }, + whatsapp_id: "AUTHORED-STATUS", + scope: "personal", + publisher: { id: "739182640518205" }, + fromMe: false, + timestamp: 1794700800, + pushName: "Authored", + content: { type: "text", text: "authored publication" }, + }, + [ + "id", + "whatsapp_ids", + "scope", + "publisher", + "fromMe", + "timestamp", + "pushName", + "content", + ], + ), + "status.revoked": shape< + Extract + >()( + { + id: "739182640518204", + whatsapp_ids: { linked_devices: "AUTHORED-STATUS" }, + whatsapp_id: "AUTHORED-STATUS", + scope: "personal", + publisher: { id: "739182640518205" }, + fromMe: false, + timestamp: 1794700800, + pushName: "Authored", + content: { type: "revoke", revokedId: "739182640518206" }, + }, + [ + "id", + "whatsapp_ids", + "scope", + "publisher", + "fromMe", + "timestamp", + "pushName", + "content", + ], + ), "session.capabilities_updated": shape()( { session: "support", @@ -821,6 +912,7 @@ const PAYLOADS: { type LegacyEventType = Exclude< KnownWebhookEventType, | `customer.${string}` + | `status.${string}` | "contact.opted_in" | "contact.opted_out" | `bansafe.${string}` @@ -849,6 +941,16 @@ function specEvents(): Map { if (event?.enum?.length !== 1 || payload?.$ref === undefined) continue; events.set(String(event.enum[0]), payload.$ref.split("/").pop()!); } + for (const schema of Object.values(statusCandidate.components.schemas)) { + const event = schema.properties?.event; + const payload = schema.properties?.payload; + if ( + event?.enum?.length === 1 && + String(event.enum[0]).startsWith("status.") && + payload?.$ref !== undefined + ) + events.set(String(event.enum[0]), payload.$ref.split("/").pop()!); + } return events; } @@ -915,7 +1017,32 @@ describe("webhook catalog contract", () => { type, ).toContain(`#/components/schemas/${variant}`); } - expectShape(messaging, variant ?? schemaName!, fixture); + if (type.startsWith("status.")) { + const union = resolveRef(statusCandidate, { $ref: `#/${schemaName!}` }); + const matches = (union.oneOf ?? union.anyOf ?? []) + .map((part) => resolveRef(statusCandidate, part)) + .filter( + (part) => + violations(statusCandidate, part, fixture.value).length === 0, + ); + expect( + matches, + JSON.stringify( + (union.oneOf ?? union.anyOf ?? []).map((part) => + violations(statusCandidate, part, fixture.value), + ), + ), + ).toHaveLength(1); + expect(Object.keys(fixture.value).sort()).toEqual( + Object.keys(matches[0]!.properties ?? {}).sort(), + ); + expect([...fixture.required].sort()).toEqual( + [...(matches[0]!.required ?? [])].sort(), + ); + expect(violations(statusCandidate, union, fixture.value)).toEqual([]); + } else { + expectShape(messaging, variant ?? schemaName!, fixture); + } }, ); diff --git a/packages/typescript/test/webhook-event-types.test.ts b/packages/typescript/test/webhook-event-types.test.ts index 864458b5d..302dc5e2a 100644 --- a/packages/typescript/test/webhook-event-types.test.ts +++ b/packages/typescript/test/webhook-event-types.test.ts @@ -102,6 +102,7 @@ type ExpectedLinkedDeviceMessageType = | "list_reply" | "poll" | "sticker" + | "sticker_pack" | "reaction" | "revoke" | "edited" diff --git a/scripts/doc-snippets/recipes.mjs b/scripts/doc-snippets/recipes.mjs index e3b822d66..2cf58ef5d 100644 --- a/scripts/doc-snippets/recipes.mjs +++ b/scripts/doc-snippets/recipes.mjs @@ -1,7 +1,8 @@ // Requests come from the pinned OpenAPI and existing native wire fixtures. // Calls are handwritten in the language modules. Never derive arguments from // contracts/coverage.json's display-only method names. -export const sourceCommit = "641230d38744d862cbf66ae3af56fbfb203e1e73"; +export const sourceCommit = "101b11a4c69144fa123080ec4dfd68ed26d79ec6"; + export const apiVersion = "2026-09-22"; export const languages = [ "typescript",