@12-apps/messaging 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +119 -0
- package/README.md +133 -2
- package/dist/channel-Cs_vLGl_.d.ts +293 -0
- package/dist/chunk-72TDAQUW.js +136 -0
- package/dist/chunk-72TDAQUW.js.map +1 -0
- package/dist/chunk-7QVYU63E.js +7 -0
- package/dist/chunk-7QVYU63E.js.map +1 -0
- package/dist/chunk-R3DKM2IV.js +42 -0
- package/dist/chunk-R3DKM2IV.js.map +1 -0
- package/dist/chunk-Y7MG2UDQ.js +36 -0
- package/dist/chunk-Y7MG2UDQ.js.map +1 -0
- package/dist/engine-B5EPo66m.d.ts +414 -0
- package/dist/index.d.ts +97 -0
- package/dist/index.js +988 -0
- package/dist/index.js.map +1 -0
- package/dist/manifest/index.d.ts +36 -0
- package/dist/manifest/index.js +14 -0
- package/dist/manifest/index.js.map +1 -0
- package/dist/manifest/server.d.ts +21 -0
- package/dist/manifest/server.js +17 -0
- package/dist/manifest/server.js.map +1 -0
- package/dist/server/index.d.ts +78 -0
- package/dist/server/index.js +15 -0
- package/dist/server/index.js.map +1 -0
- package/dist/whatsapp/index.d.ts +180 -0
- package/dist/whatsapp/index.js +385 -0
- package/dist/whatsapp/index.js.map +1 -0
- package/package.json +90 -4
- package/prisma/messaging.prisma +140 -0
- package/prisma/migrations/20261114120000_messaging_connector/migration.sql +110 -0
- package/src/core/channel.ts +106 -0
- package/src/core/connections.ts +67 -0
- package/src/core/context.ts +28 -0
- package/src/core/engine.ts +64 -0
- package/src/core/errors.ts +53 -0
- package/src/core/hash.ts +6 -0
- package/src/core/inbound.ts +240 -0
- package/src/core/inbox.ts +117 -0
- package/src/core/memory-store.ts +273 -0
- package/src/core/ports.ts +112 -0
- package/src/core/prisma-store.ts +354 -0
- package/src/core/retention.ts +27 -0
- package/src/core/sender.ts +106 -0
- package/src/core/store.ts +217 -0
- package/src/core/types.ts +189 -0
- package/src/index.ts +54 -0
- package/src/manifest/index.ts +32 -0
- package/src/manifest/server.ts +18 -0
- package/src/server/index.ts +22 -0
- package/src/server/jobs.ts +99 -0
- package/src/server/webhook.ts +92 -0
- package/src/whatsapp/graph.ts +136 -0
- package/src/whatsapp/index.ts +64 -0
- package/src/whatsapp/opt-out.ts +26 -0
- package/src/whatsapp/parse.ts +200 -0
- package/src/whatsapp/signature.ts +52 -0
- package/src/whatsapp/signup.ts +115 -0
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
2
|
+
// OWNED BY @12-apps/messaging — a host's multi-file schema folder holds only a
|
|
3
|
+
// COPY of this file. Conversations with people on a messaging channel live
|
|
4
|
+
// here, in the package, never in the application.
|
|
5
|
+
//
|
|
6
|
+
// Self-contained on purpose: `tenant_id` and `staff_user_id` are by-value
|
|
7
|
+
// String columns with NO foreign key into any host table, so the models work
|
|
8
|
+
// in every repo without schema coupling. What a conversation leads to (a cart,
|
|
9
|
+
// a customer record, an attributed sale) is the host's business, kept in the
|
|
10
|
+
// host's own tables keyed by the conversation id.
|
|
11
|
+
//
|
|
12
|
+
// Vocabulary columns (`channel`, `status`, `state`, `direction`, `kind`,
|
|
13
|
+
// `author_kind`, `delivery_status`) are Strings guarded by CHECKs in the
|
|
14
|
+
// migration, not Prisma enums: a new channel adapter is a new value, never a
|
|
15
|
+
// type the host's client has to regenerate around.
|
|
16
|
+
// ─────────────────────────────────────────────────────────────────────────────
|
|
17
|
+
|
|
18
|
+
// One account on a channel that a tenant connected: a WhatsApp phone number,
|
|
19
|
+
// later a mailbox or a workspace. `external_account_id` is the channel's own id
|
|
20
|
+
// for it (WhatsApp's phone_number_id), UNIQUE across tenants: an inbound
|
|
21
|
+
// delivery names the account, and the account names exactly one tenant.
|
|
22
|
+
model MessagingConnection {
|
|
23
|
+
id String @id @default(uuid())
|
|
24
|
+
tenantId String @map("tenant_id")
|
|
25
|
+
channel String
|
|
26
|
+
externalAccountId String @map("external_account_id")
|
|
27
|
+
// The channel's parent account when it has one (WhatsApp's WABA id).
|
|
28
|
+
externalParentId String? @map("external_parent_id")
|
|
29
|
+
// What a person reads as the address (a display phone number).
|
|
30
|
+
displayAddress String @map("display_address")
|
|
31
|
+
status String @default("CONNECTED")
|
|
32
|
+
// The channel credential, SEALED by the host's encryption port. The package
|
|
33
|
+
// never holds the key, never returns this column and never logs it.
|
|
34
|
+
// NULL once revoked: disconnecting removes the token.
|
|
35
|
+
credentialSealed String? @map("credential_sealed")
|
|
36
|
+
statusReason String? @map("status_reason")
|
|
37
|
+
connectedAt DateTime @default(now()) @map("connected_at")
|
|
38
|
+
revokedAt DateTime? @map("revoked_at")
|
|
39
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
40
|
+
updatedAt DateTime @updatedAt @map("updated_at")
|
|
41
|
+
conversations MessagingConversation[]
|
|
42
|
+
|
|
43
|
+
@@unique([channel, externalAccountId])
|
|
44
|
+
@@index([tenantId, channel])
|
|
45
|
+
@@map("messaging_connections")
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// One raw delivery, exactly as the channel posted it, stored BEFORE the
|
|
49
|
+
// acknowledgement. A channel that carries no per-delivery id (WhatsApp) is
|
|
50
|
+
// deduplicated on the hash of the raw body: a redelivery is the same bytes.
|
|
51
|
+
// The raw body is the channel's whole payload (message text, phone number,
|
|
52
|
+
// profile name), so the retention sweep DELETES the row past the retention
|
|
53
|
+
// window once it is PROCESSED or out of attempts; message-level dedupe lives on
|
|
54
|
+
// `messaging_messages (channel, external_id)`.
|
|
55
|
+
model MessagingInboxDelivery {
|
|
56
|
+
id String @id @default(uuid())
|
|
57
|
+
channel String
|
|
58
|
+
bodyHash String @map("body_hash")
|
|
59
|
+
rawBody String @map("raw_body")
|
|
60
|
+
state String @default("PENDING")
|
|
61
|
+
attempts Int @default(0)
|
|
62
|
+
error String?
|
|
63
|
+
receivedAt DateTime @map("received_at")
|
|
64
|
+
processedAt DateTime? @map("processed_at")
|
|
65
|
+
|
|
66
|
+
@@unique([channel, bodyHash])
|
|
67
|
+
// The reconciliation sweep: unprocessed deliveries, oldest first.
|
|
68
|
+
@@index([state, receivedAt])
|
|
69
|
+
@@map("messaging_inbox_deliveries")
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// One conversation between a tenant and one contact on one channel. The text
|
|
73
|
+
// of its messages is deleted after the retention window; this row, its state
|
|
74
|
+
// and its structured summary stay.
|
|
75
|
+
model MessagingConversation {
|
|
76
|
+
id String @id @default(uuid())
|
|
77
|
+
tenantId String @map("tenant_id")
|
|
78
|
+
channel String
|
|
79
|
+
// The contact's address on the channel (WhatsApp: the wa_id, E.164 digits).
|
|
80
|
+
contactId String @map("contact_id")
|
|
81
|
+
contactName String? @map("contact_name")
|
|
82
|
+
// The connection the contact last wrote to: where a reply is sent from.
|
|
83
|
+
connectionId String @map("connection_id")
|
|
84
|
+
state String @default("AGENT")
|
|
85
|
+
lastInboundAt DateTime? @map("last_inbound_at")
|
|
86
|
+
lastMessageAt DateTime? @map("last_message_at")
|
|
87
|
+
// When the contact last opted out, by the message's own time: a message
|
|
88
|
+
// sent before it never re-opens the conversation, whatever order the
|
|
89
|
+
// deliveries are processed in.
|
|
90
|
+
optedOutAt DateTime? @map("opted_out_at")
|
|
91
|
+
// Whether any message still carries text: the retention sweep's index.
|
|
92
|
+
hasText Boolean @default(false) @map("has_text")
|
|
93
|
+
// Structured, never free text (items discussed, a mode, an area), written by
|
|
94
|
+
// the host. Outlives the text.
|
|
95
|
+
summary Json?
|
|
96
|
+
summaryUpdatedAt DateTime? @map("summary_updated_at")
|
|
97
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
98
|
+
updatedAt DateTime @updatedAt @map("updated_at")
|
|
99
|
+
messages MessagingMessage[]
|
|
100
|
+
connection MessagingConnection @relation(fields: [connectionId], references: [id], onDelete: Restrict)
|
|
101
|
+
|
|
102
|
+
@@unique([tenantId, channel, contactId])
|
|
103
|
+
@@index([tenantId, lastMessageAt])
|
|
104
|
+
// The retention sweep: conversations still holding text, by last message.
|
|
105
|
+
@@index([hasText, lastMessageAt])
|
|
106
|
+
@@map("messaging_conversations")
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// One message, either way. `body` and `transcript` are the text the retention
|
|
110
|
+
// sweep deletes; `options` is an interactive message's choices as JSON text,
|
|
111
|
+
// deleted with it. `external_id` is the channel's id (WhatsApp's wamid),
|
|
112
|
+
// UNIQUE per channel: a redelivered inbound message is a no-op.
|
|
113
|
+
model MessagingMessage {
|
|
114
|
+
id String @id @default(uuid())
|
|
115
|
+
conversationId String @map("conversation_id")
|
|
116
|
+
tenantId String @map("tenant_id")
|
|
117
|
+
channel String
|
|
118
|
+
direction String
|
|
119
|
+
kind String
|
|
120
|
+
body String?
|
|
121
|
+
options String?
|
|
122
|
+
transcript String?
|
|
123
|
+
// An attachment's id on the channel (WhatsApp's media id), never its bytes.
|
|
124
|
+
attachmentRef String? @map("attachment_ref")
|
|
125
|
+
externalId String? @map("external_id")
|
|
126
|
+
deliveryStatus String @map("delivery_status")
|
|
127
|
+
authorKind String @map("author_kind")
|
|
128
|
+
staffUserId String? @map("staff_user_id")
|
|
129
|
+
error String?
|
|
130
|
+
createdAt DateTime @default(now()) @map("created_at")
|
|
131
|
+
sentAt DateTime? @map("sent_at")
|
|
132
|
+
deliveredAt DateTime? @map("delivered_at")
|
|
133
|
+
readAt DateTime? @map("read_at")
|
|
134
|
+
failedAt DateTime? @map("failed_at")
|
|
135
|
+
conversation MessagingConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
|
|
136
|
+
|
|
137
|
+
@@unique([channel, externalId])
|
|
138
|
+
@@index([conversationId, createdAt])
|
|
139
|
+
@@map("messaging_messages")
|
|
140
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
-- @12-apps/messaging: channel connections, the raw delivery inbox, conversations and messages.
|
|
2
|
+
CREATE TABLE "messaging_connections" (
|
|
3
|
+
"id" TEXT NOT NULL,
|
|
4
|
+
"tenant_id" TEXT NOT NULL,
|
|
5
|
+
"channel" TEXT NOT NULL,
|
|
6
|
+
"external_account_id" TEXT NOT NULL,
|
|
7
|
+
"external_parent_id" TEXT,
|
|
8
|
+
"display_address" TEXT NOT NULL,
|
|
9
|
+
"status" TEXT NOT NULL DEFAULT 'CONNECTED',
|
|
10
|
+
-- The sealed credential; NULL once the connection is revoked (disconnecting removes the token).
|
|
11
|
+
"credential_sealed" TEXT,
|
|
12
|
+
"status_reason" TEXT,
|
|
13
|
+
"connected_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
14
|
+
"revoked_at" TIMESTAMP(3),
|
|
15
|
+
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
16
|
+
"updated_at" TIMESTAMP(3) NOT NULL,
|
|
17
|
+
|
|
18
|
+
CONSTRAINT "messaging_connections_pkey" PRIMARY KEY ("id"),
|
|
19
|
+
CONSTRAINT "messaging_connections_channel_check" CHECK ("channel" ~ '^[a-z][a-z0-9-]*$'),
|
|
20
|
+
CONSTRAINT "messaging_connections_status_check" CHECK ("status" IN ('CONNECTED', 'REVOKED', 'ERROR'))
|
|
21
|
+
);
|
|
22
|
+
|
|
23
|
+
CREATE TABLE "messaging_inbox_deliveries" (
|
|
24
|
+
"id" TEXT NOT NULL,
|
|
25
|
+
"channel" TEXT NOT NULL,
|
|
26
|
+
"body_hash" TEXT NOT NULL,
|
|
27
|
+
"raw_body" TEXT NOT NULL,
|
|
28
|
+
"state" TEXT NOT NULL DEFAULT 'PENDING',
|
|
29
|
+
"attempts" INTEGER NOT NULL DEFAULT 0,
|
|
30
|
+
"error" TEXT,
|
|
31
|
+
"received_at" TIMESTAMP(3) NOT NULL,
|
|
32
|
+
"processed_at" TIMESTAMP(3),
|
|
33
|
+
|
|
34
|
+
CONSTRAINT "messaging_inbox_deliveries_pkey" PRIMARY KEY ("id"),
|
|
35
|
+
CONSTRAINT "messaging_inbox_deliveries_channel_check" CHECK ("channel" ~ '^[a-z][a-z0-9-]*$'),
|
|
36
|
+
CONSTRAINT "messaging_inbox_deliveries_state_check" CHECK ("state" IN ('PENDING', 'PROCESSED', 'FAILED'))
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
CREATE TABLE "messaging_conversations" (
|
|
40
|
+
"id" TEXT NOT NULL,
|
|
41
|
+
"tenant_id" TEXT NOT NULL,
|
|
42
|
+
"channel" TEXT NOT NULL,
|
|
43
|
+
"contact_id" TEXT NOT NULL,
|
|
44
|
+
"contact_name" TEXT,
|
|
45
|
+
"connection_id" TEXT NOT NULL,
|
|
46
|
+
"state" TEXT NOT NULL DEFAULT 'AGENT',
|
|
47
|
+
"last_inbound_at" TIMESTAMP(3),
|
|
48
|
+
"last_message_at" TIMESTAMP(3),
|
|
49
|
+
-- When the contact last opted out (the message's own time): an older message never re-opens the conversation.
|
|
50
|
+
"opted_out_at" TIMESTAMP(3),
|
|
51
|
+
"has_text" BOOLEAN NOT NULL DEFAULT false,
|
|
52
|
+
"summary" JSONB,
|
|
53
|
+
"summary_updated_at" TIMESTAMP(3),
|
|
54
|
+
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
55
|
+
"updated_at" TIMESTAMP(3) NOT NULL,
|
|
56
|
+
|
|
57
|
+
CONSTRAINT "messaging_conversations_pkey" PRIMARY KEY ("id"),
|
|
58
|
+
CONSTRAINT "messaging_conversations_channel_check" CHECK ("channel" ~ '^[a-z][a-z0-9-]*$'),
|
|
59
|
+
CONSTRAINT "messaging_conversations_state_check" CHECK ("state" IN ('AGENT', 'HUMAN', 'CLOSED', 'OPTED_OUT'))
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
CREATE TABLE "messaging_messages" (
|
|
63
|
+
"id" TEXT NOT NULL,
|
|
64
|
+
"conversation_id" TEXT NOT NULL,
|
|
65
|
+
"tenant_id" TEXT NOT NULL,
|
|
66
|
+
"channel" TEXT NOT NULL,
|
|
67
|
+
"direction" TEXT NOT NULL,
|
|
68
|
+
"kind" TEXT NOT NULL,
|
|
69
|
+
"body" TEXT,
|
|
70
|
+
"options" TEXT,
|
|
71
|
+
"transcript" TEXT,
|
|
72
|
+
"attachment_ref" TEXT,
|
|
73
|
+
"external_id" TEXT,
|
|
74
|
+
"delivery_status" TEXT NOT NULL,
|
|
75
|
+
"author_kind" TEXT NOT NULL,
|
|
76
|
+
"staff_user_id" TEXT,
|
|
77
|
+
"error" TEXT,
|
|
78
|
+
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
79
|
+
"sent_at" TIMESTAMP(3),
|
|
80
|
+
"delivered_at" TIMESTAMP(3),
|
|
81
|
+
"read_at" TIMESTAMP(3),
|
|
82
|
+
"failed_at" TIMESTAMP(3),
|
|
83
|
+
|
|
84
|
+
CONSTRAINT "messaging_messages_pkey" PRIMARY KEY ("id"),
|
|
85
|
+
CONSTRAINT "messaging_messages_channel_check" CHECK ("channel" ~ '^[a-z][a-z0-9-]*$'),
|
|
86
|
+
CONSTRAINT "messaging_messages_direction_check" CHECK ("direction" IN ('INBOUND', 'OUTBOUND')),
|
|
87
|
+
CONSTRAINT "messaging_messages_kind_check" CHECK ("kind" IN ('TEXT', 'INTERACTIVE', 'AUDIO', 'OTHER')),
|
|
88
|
+
CONSTRAINT "messaging_messages_delivery_status_check" CHECK ("delivery_status" IN ('RECEIVED', 'PENDING', 'ACCEPTED', 'SENT', 'DELIVERED', 'READ', 'FAILED')),
|
|
89
|
+
CONSTRAINT "messaging_messages_author_kind_check" CHECK ("author_kind" IN ('CONTACT', 'AGENT', 'STAFF')),
|
|
90
|
+
-- A staff user id (optional) appears only on a staff message.
|
|
91
|
+
CONSTRAINT "messaging_messages_staff_author_check" CHECK ("staff_user_id" IS NULL OR "author_kind" = 'STAFF'),
|
|
92
|
+
-- An inbound message is always the contact's, and always has its channel id.
|
|
93
|
+
CONSTRAINT "messaging_messages_inbound_check" CHECK ("direction" = 'OUTBOUND' OR ("author_kind" = 'CONTACT' AND "external_id" IS NOT NULL))
|
|
94
|
+
);
|
|
95
|
+
|
|
96
|
+
CREATE UNIQUE INDEX "messaging_connections_channel_external_account_id_key" ON "messaging_connections"("channel", "external_account_id");
|
|
97
|
+
CREATE INDEX "messaging_connections_tenant_id_channel_idx" ON "messaging_connections"("tenant_id", "channel");
|
|
98
|
+
|
|
99
|
+
CREATE UNIQUE INDEX "messaging_inbox_deliveries_channel_body_hash_key" ON "messaging_inbox_deliveries"("channel", "body_hash");
|
|
100
|
+
CREATE INDEX "messaging_inbox_deliveries_state_received_at_idx" ON "messaging_inbox_deliveries"("state", "received_at");
|
|
101
|
+
|
|
102
|
+
CREATE UNIQUE INDEX "messaging_conversations_tenant_id_channel_contact_id_key" ON "messaging_conversations"("tenant_id", "channel", "contact_id");
|
|
103
|
+
CREATE INDEX "messaging_conversations_tenant_id_last_message_at_idx" ON "messaging_conversations"("tenant_id", "last_message_at");
|
|
104
|
+
CREATE INDEX "messaging_conversations_has_text_last_message_at_idx" ON "messaging_conversations"("has_text", "last_message_at");
|
|
105
|
+
|
|
106
|
+
CREATE UNIQUE INDEX "messaging_messages_channel_external_id_key" ON "messaging_messages"("channel", "external_id");
|
|
107
|
+
CREATE INDEX "messaging_messages_conversation_id_created_at_idx" ON "messaging_messages"("conversation_id", "created_at");
|
|
108
|
+
|
|
109
|
+
ALTER TABLE "messaging_messages" ADD CONSTRAINT "messaging_messages_conversation_id_fkey" FOREIGN KEY ("conversation_id") REFERENCES "messaging_conversations"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
110
|
+
ALTER TABLE "messaging_conversations" ADD CONSTRAINT "messaging_conversations_connection_id_fkey" FOREIGN KEY ("connection_id") REFERENCES "messaging_connections"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { ChannelKind, NormalizedEvent, OutboundContent } from "./types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* THE CHANNEL ADAPTER: everything the engine needs to know about one
|
|
5
|
+
* messaging channel, and nothing the engine decides.
|
|
6
|
+
*
|
|
7
|
+
* The engine owns the mechanism — the inbox and its dedupe, the tenant
|
|
8
|
+
* resolution, the conversation and its state, the outbound bookkeeping, the
|
|
9
|
+
* retention. An adapter owns the channel's wire: how a delivery proves where
|
|
10
|
+
* it came from, what its body means, how a message goes out, and when the
|
|
11
|
+
* channel lets a tenant speak first. WhatsApp Cloud is the first adapter
|
|
12
|
+
* (`@12-apps/messaging/whatsapp`); e-mail or a chat workspace join the same
|
|
13
|
+
* way, as one more object of this shape.
|
|
14
|
+
*/
|
|
15
|
+
export interface ChannelAdapter {
|
|
16
|
+
/** The channel's key, stored on every row: `whatsapp`. Lowercase, dash-separated. */
|
|
17
|
+
readonly kind: ChannelKind;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Answer the channel's subscription handshake (a `GET` with a challenge),
|
|
21
|
+
* or null for a channel that has none. `ok: false` is a refusal (403).
|
|
22
|
+
*/
|
|
23
|
+
handshake(query: Readonly<Record<string, string | undefined>>): HandshakeAnswer | null;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Is this delivery really from the channel? Computed over the RAW body
|
|
27
|
+
* bytes, exactly as received. MUST fail closed: a missing secret, a missing
|
|
28
|
+
* header or a malformed one is `false`, never an exception and never `true`.
|
|
29
|
+
*/
|
|
30
|
+
verify(delivery: { rawBody: Uint8Array; header(name: string): string | null }): boolean;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Turn a raw body into normalized events, in the order the channel listed
|
|
34
|
+
* them. A body the adapter does not recognize yields `[]`; a body that is not
|
|
35
|
+
* even JSON throws (the inbox records the failure).
|
|
36
|
+
*/
|
|
37
|
+
parse(rawBody: string): NormalizedEvent[];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Send one message from a connected account and report the channel's id
|
|
41
|
+
* for it. Throws {@link ChannelSendFailure} when the channel refuses.
|
|
42
|
+
* `credential` is the OPENED credential: an adapter never logs it, never
|
|
43
|
+
* puts it in an error, never returns it.
|
|
44
|
+
*/
|
|
45
|
+
send(input: ChannelSendInput): Promise<{ externalId: string }>;
|
|
46
|
+
|
|
47
|
+
/** When this channel lets the tenant send free-form messages. */
|
|
48
|
+
readonly policy: SendPolicy;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type HandshakeAnswer = { ok: true; challenge: string } | { ok: false };
|
|
52
|
+
|
|
53
|
+
export interface ChannelSendInput {
|
|
54
|
+
/** The opened credential of the connection sending it. */
|
|
55
|
+
credential: string;
|
|
56
|
+
/** The connection's account on the channel (WhatsApp's phone_number_id). */
|
|
57
|
+
accountId: string;
|
|
58
|
+
/** The recipient's address. */
|
|
59
|
+
to: string;
|
|
60
|
+
content: OutboundContent;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** A channel refused or failed a send. `code` is the channel's own, as text. */
|
|
64
|
+
export class ChannelSendFailure extends Error {
|
|
65
|
+
readonly code: string;
|
|
66
|
+
constructor(code: string, message: string) {
|
|
67
|
+
super(message);
|
|
68
|
+
this.name = "ChannelSendFailure";
|
|
69
|
+
this.code = code;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** What a send policy is asked. */
|
|
74
|
+
export interface SendPolicyContext {
|
|
75
|
+
/** When the contact last wrote; null if never. */
|
|
76
|
+
lastInboundAt: Date | null;
|
|
77
|
+
now: Date;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export type SendPolicyVerdict = { allowed: true } | { allowed: false; reason: "WINDOW_CLOSED" };
|
|
81
|
+
|
|
82
|
+
/** A channel's rule for free-form sends. */
|
|
83
|
+
export interface SendPolicy {
|
|
84
|
+
check(context: SendPolicyContext): SendPolicyVerdict;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Is a service window still open? Open while LESS than `windowMs` has passed
|
|
89
|
+
* since the contact's last message: at exactly the window's length it is
|
|
90
|
+
* closed. Never open for a contact who never wrote.
|
|
91
|
+
*/
|
|
92
|
+
export function isWindowOpen(lastInboundAt: Date | null, now: Date, windowMs: number): boolean {
|
|
93
|
+
if (!lastInboundAt) return false;
|
|
94
|
+
return now.getTime() - lastInboundAt.getTime() < windowMs;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A policy that allows free-form sends only inside a window after the contact's last message. */
|
|
98
|
+
export function serviceWindowPolicy(windowMs: number): SendPolicy {
|
|
99
|
+
return {
|
|
100
|
+
check: ({ lastInboundAt, now }) =>
|
|
101
|
+
isWindowOpen(lastInboundAt, now, windowMs) ? { allowed: true } : { allowed: false, reason: "WINDOW_CLOSED" },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** A policy for a channel with no window (e-mail): every send is allowed. */
|
|
106
|
+
export const OPEN_SEND_POLICY: SendPolicy = { check: () => ({ allowed: true }) };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { EngineContext } from "./context";
|
|
2
|
+
import { MessagingConnectError } from "./errors";
|
|
3
|
+
import type { ConnectionView } from "./types";
|
|
4
|
+
|
|
5
|
+
export interface ConnectInput {
|
|
6
|
+
tenantId: string;
|
|
7
|
+
channel: string;
|
|
8
|
+
/** The channel's id for the account (WhatsApp's phone_number_id). */
|
|
9
|
+
externalAccountId: string;
|
|
10
|
+
/** The channel's parent account (WhatsApp's WABA id), when it has one. */
|
|
11
|
+
externalParentId?: string | null;
|
|
12
|
+
displayAddress: string;
|
|
13
|
+
/** The credential in clear (a business token). Sealed here; never stored, returned or logged in clear. */
|
|
14
|
+
credential: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Connect an account to a tenant. The account is UNIQUE across tenants: one
|
|
19
|
+
* held by another tenant (connected, or in error) is refused
|
|
20
|
+
* (`ACCOUNT_TAKEN`); only one that tenant revoked may be connected by another,
|
|
21
|
+
* who proves it through the channel's own signup. Re-connecting one's own
|
|
22
|
+
* account replaces its credential and clears its error.
|
|
23
|
+
*/
|
|
24
|
+
export async function connect(ctx: EngineContext, input: ConnectInput): Promise<ConnectionView> {
|
|
25
|
+
const { store, secrets, clock } = ctx.config;
|
|
26
|
+
if (!ctx.adapters.has(input.channel)) {
|
|
27
|
+
throw new MessagingConnectError("UNKNOWN_CHANNEL", `no adapter for channel "${input.channel}"`);
|
|
28
|
+
}
|
|
29
|
+
const existing = await store.findConnectionByAccount(input.channel, input.externalAccountId);
|
|
30
|
+
if (existing && existing.tenantId !== input.tenantId && existing.status !== "REVOKED") {
|
|
31
|
+
throw new MessagingConnectError("ACCOUNT_TAKEN", `account ${input.externalAccountId} is held by another tenant`);
|
|
32
|
+
}
|
|
33
|
+
const saved = await store.saveConnection({
|
|
34
|
+
tenantId: input.tenantId,
|
|
35
|
+
channel: input.channel,
|
|
36
|
+
externalAccountId: input.externalAccountId,
|
|
37
|
+
externalParentId: input.externalParentId ?? null,
|
|
38
|
+
displayAddress: input.displayAddress,
|
|
39
|
+
credentialSealed: await secrets.seal(input.credential),
|
|
40
|
+
connectedAt: clock.now(),
|
|
41
|
+
});
|
|
42
|
+
// The store's write is conditional, so a connect that lost a race for the account is refused here too.
|
|
43
|
+
if (!saved) throw new MessagingConnectError("ACCOUNT_TAKEN", `account ${input.externalAccountId} is held by another tenant`);
|
|
44
|
+
return saved;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Revoke a tenant's connection: inbound traffic for it is dropped, sends are
|
|
49
|
+
* refused, and the sealed credential is cleared — disconnecting removes the token.
|
|
50
|
+
*/
|
|
51
|
+
export async function revoke(ctx: EngineContext, tenantId: string, connectionId: string, reason: string | null = null) {
|
|
52
|
+
return ctx.config.store.setConnectionStatus(tenantId, connectionId, {
|
|
53
|
+
status: "REVOKED",
|
|
54
|
+
statusReason: reason,
|
|
55
|
+
revokedAt: ctx.config.clock.now(),
|
|
56
|
+
credentialSealed: null,
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Mark a connection in error (a token the channel rejects): treated as revoked until re-connected. */
|
|
61
|
+
export async function markError(ctx: EngineContext, tenantId: string, connectionId: string, reason: string) {
|
|
62
|
+
return ctx.config.store.setConnectionStatus(tenantId, connectionId, {
|
|
63
|
+
status: "ERROR",
|
|
64
|
+
statusReason: reason.slice(0, 500),
|
|
65
|
+
revokedAt: null,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ChannelAdapter } from "./channel";
|
|
2
|
+
import { MESSAGING_DEFAULTS, type MessagingEngineConfig } from "./ports";
|
|
3
|
+
|
|
4
|
+
/** The config with every default applied, and the adapters keyed by channel. */
|
|
5
|
+
export interface EngineContext {
|
|
6
|
+
config: MessagingEngineConfig & Required<Pick<MessagingEngineConfig, keyof typeof MESSAGING_DEFAULTS>>;
|
|
7
|
+
adapters: ReadonlyMap<string, ChannelAdapter>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/** Build the context; a channel mounted twice is a configuration error. */
|
|
11
|
+
export function engineContext(config: MessagingEngineConfig): EngineContext {
|
|
12
|
+
const adapters = new Map<string, ChannelAdapter>();
|
|
13
|
+
for (const adapter of config.adapters) {
|
|
14
|
+
if (adapters.has(adapter.kind)) throw new Error(`messaging: channel "${adapter.kind}" is mounted twice`);
|
|
15
|
+
adapters.set(adapter.kind, adapter);
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
config: {
|
|
19
|
+
...config,
|
|
20
|
+
retentionMs: config.retentionMs ?? MESSAGING_DEFAULTS.retentionMs,
|
|
21
|
+
retentionBatchSize: config.retentionBatchSize ?? MESSAGING_DEFAULTS.retentionBatchSize,
|
|
22
|
+
reconcileBatchSize: config.reconcileBatchSize ?? MESSAGING_DEFAULTS.reconcileBatchSize,
|
|
23
|
+
maxDeliveryAttempts: config.maxDeliveryAttempts ?? MESSAGING_DEFAULTS.maxDeliveryAttempts,
|
|
24
|
+
reconcileAfterMs: config.reconcileAfterMs ?? MESSAGING_DEFAULTS.reconcileAfterMs,
|
|
25
|
+
},
|
|
26
|
+
adapters,
|
|
27
|
+
};
|
|
28
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { connect, markError, revoke, type ConnectInput } from "./connections";
|
|
2
|
+
import { engineContext } from "./context";
|
|
3
|
+
import { processDelivery, receiveDelivery, reconcileInbox } from "./inbox";
|
|
4
|
+
import type { MessagingEngineConfig } from "./ports";
|
|
5
|
+
import { sweepRetention } from "./retention";
|
|
6
|
+
import { sendMessage, type SendInput } from "./sender";
|
|
7
|
+
import type { ConversationState, ConversationSummary } from "./types";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Mount the connector: one engine per process, over the host's store and
|
|
11
|
+
* ports, with one adapter per channel.
|
|
12
|
+
*/
|
|
13
|
+
export function createMessagingEngine(config: MessagingEngineConfig) {
|
|
14
|
+
const ctx = engineContext(config);
|
|
15
|
+
const { store, clock } = ctx.config;
|
|
16
|
+
return {
|
|
17
|
+
/** The adapter mounted for a channel, or undefined. */
|
|
18
|
+
adapter: (channel: string) => ctx.adapters.get(channel),
|
|
19
|
+
/** The channels this engine serves. */
|
|
20
|
+
channels: () => [...ctx.adapters.keys()],
|
|
21
|
+
|
|
22
|
+
// ── The pipeline ─────────────────────────────────────────────────────────
|
|
23
|
+
/** Store a VERIFIED raw delivery and queue its processing. The edge answers 200 after this. */
|
|
24
|
+
receive: (channel: string, rawBody: string) => receiveDelivery(ctx, channel, rawBody),
|
|
25
|
+
/** The `process-delivery` job's body. */
|
|
26
|
+
processDelivery: (deliveryId: string) => processDelivery(ctx, deliveryId),
|
|
27
|
+
/** The `reconcile-inbox` sweep's body. */
|
|
28
|
+
reconcile: () => reconcileInbox(ctx),
|
|
29
|
+
/** The `retention` sweep's body. */
|
|
30
|
+
sweepRetention: () => sweepRetention(ctx),
|
|
31
|
+
|
|
32
|
+
// ── Sending ──────────────────────────────────────────────────────────────
|
|
33
|
+
send: (input: SendInput) => sendMessage(ctx, input),
|
|
34
|
+
|
|
35
|
+
// ── Connections ──────────────────────────────────────────────────────────
|
|
36
|
+
connect: (input: ConnectInput) => connect(ctx, input),
|
|
37
|
+
revoke: (tenantId: string, connectionId: string, reason?: string | null) => revoke(ctx, tenantId, connectionId, reason),
|
|
38
|
+
markError: (tenantId: string, connectionId: string, reason: string) => markError(ctx, tenantId, connectionId, reason),
|
|
39
|
+
listConnections: (tenantId: string) => store.listConnections(tenantId),
|
|
40
|
+
|
|
41
|
+
// ── Conversations, for the host's own surfaces ───────────────────────────
|
|
42
|
+
getConversation: (tenantId: string, conversationId: string) => store.getConversation(tenantId, conversationId),
|
|
43
|
+
listMessages: (tenantId: string, conversationId: string) => store.listMessages(tenantId, conversationId),
|
|
44
|
+
/**
|
|
45
|
+
* Move a conversation between AGENT, HUMAN and CLOSED (a hand-off). OPTED_OUT
|
|
46
|
+
* is the contact's alone, both ways: an opted-out conversation is not
|
|
47
|
+
* moved (null), and only the contact's next message re-opens it.
|
|
48
|
+
*/
|
|
49
|
+
setState: (tenantId: string, conversationId: string, state: Exclude<ConversationState, "OPTED_OUT">) =>
|
|
50
|
+
// ONE guarded write: an opt-out landing between a read and this write cannot be overwritten.
|
|
51
|
+
store.updateConversation(tenantId, conversationId, { state }, { stateNot: "OPTED_OUT" }),
|
|
52
|
+
/** Replace the structured summary that outlives the text. */
|
|
53
|
+
setSummary: (tenantId: string, conversationId: string, summary: ConversationSummary) =>
|
|
54
|
+
store.updateConversation(tenantId, conversationId, { summary, summaryUpdatedAt: clock.now() }),
|
|
55
|
+
/** Store an audio message's transcript (deleted with the text). */
|
|
56
|
+
setTranscript: async (tenantId: string, messageId: string, transcript: string) => {
|
|
57
|
+
const message = await store.updateMessage(tenantId, messageId, { transcript });
|
|
58
|
+
if (message) await store.updateConversation(tenantId, message.conversationId, { hasText: true });
|
|
59
|
+
return message;
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export type MessagingEngine = ReturnType<typeof createMessagingEngine>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine's refusals, as typed errors with machine codes. The sentence a
|
|
3
|
+
* person reads for each is the host's copy, keyed by `code`.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** Why a send was refused or failed. */
|
|
7
|
+
export type MessagingSendErrorCode =
|
|
8
|
+
/** The contact opted out; nothing is sent until they write again. */
|
|
9
|
+
| "OPTED_OUT"
|
|
10
|
+
/** The channel's service window is closed (WhatsApp: 24 h after the contact's last message). */
|
|
11
|
+
| "WINDOW_CLOSED"
|
|
12
|
+
/** The conversation's connection is not connected (revoked, in error, or gone). */
|
|
13
|
+
| "NOT_CONNECTED"
|
|
14
|
+
/** No such conversation in this tenant. */
|
|
15
|
+
| "NOT_FOUND"
|
|
16
|
+
/** No adapter for the conversation's channel is mounted. */
|
|
17
|
+
| "UNKNOWN_CHANNEL"
|
|
18
|
+
/** The channel was called and refused or failed; the outbound row is FAILED. */
|
|
19
|
+
| "CHANNEL_FAILED";
|
|
20
|
+
|
|
21
|
+
export class MessagingSendError extends Error {
|
|
22
|
+
readonly code: MessagingSendErrorCode;
|
|
23
|
+
/** The outbound row, when one was recorded before the failure. */
|
|
24
|
+
readonly messageId: string | null;
|
|
25
|
+
constructor(code: MessagingSendErrorCode, message: string, messageId: string | null = null) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.name = "MessagingSendError";
|
|
28
|
+
this.code = code;
|
|
29
|
+
this.messageId = messageId;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Why a connection could not be saved. */
|
|
34
|
+
export type MessagingConnectErrorCode =
|
|
35
|
+
/** The account is connected to another tenant. */
|
|
36
|
+
| "ACCOUNT_TAKEN"
|
|
37
|
+
/** No adapter for that channel is mounted. */
|
|
38
|
+
| "UNKNOWN_CHANNEL";
|
|
39
|
+
|
|
40
|
+
export class MessagingConnectError extends Error {
|
|
41
|
+
readonly code: MessagingConnectErrorCode;
|
|
42
|
+
constructor(code: MessagingConnectErrorCode, message: string) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = "MessagingConnectError";
|
|
45
|
+
this.code = code;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The error text a row keeps: bounded, because a channel's error body can be a page. */
|
|
50
|
+
export function errorText(error: unknown): string {
|
|
51
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
52
|
+
return text.slice(0, 500);
|
|
53
|
+
}
|
package/src/core/hash.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
|
|
3
|
+
/** The inbox key of a raw body: its SHA-256, hex. A redelivery is the same bytes, so the same key. */
|
|
4
|
+
export function bodyHash(rawBody: string): string {
|
|
5
|
+
return createHash("sha256").update(rawBody, "utf8").digest("hex");
|
|
6
|
+
}
|