@fabric-harness/channels 0.27.1 → 0.28.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/README.md +121 -3
- package/dist/buzz.d.ts +8 -5
- package/dist/buzz.d.ts.map +1 -1
- package/dist/buzz.js +3 -2
- package/dist/buzz.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/twilio.d.ts +245 -4
- package/dist/twilio.d.ts.map +1 -1
- package/dist/twilio.js +558 -28
- package/dist/twilio.js.map +1 -1
- package/package.json +15 -10
package/dist/twilio.js
CHANGED
|
@@ -1,8 +1,66 @@
|
|
|
1
|
-
import { conversationKey, defineChannel, defineTool, parseConversationKey, readRequestBody } from '@fabric-harness/sdk/channel';
|
|
1
|
+
import { assertAgentMaySend, conversationKey, defineChannel, defineTool, parseConversationKey, readRequestBody } from '@fabric-harness/sdk/channel';
|
|
2
2
|
import { timingSafeString } from './webhook-shared.js';
|
|
3
3
|
export function twilioConversationKey(ref) {
|
|
4
4
|
return conversationKey('twilio', 'v1', ref.accountSid, ref.from, ref.to);
|
|
5
5
|
}
|
|
6
|
+
// ── Conversation ownership keys ──
|
|
7
|
+
// The one grammar of addresses a Twilio ownership key accepts, and which side of the conversation
|
|
8
|
+
// each form may be on: E.164 numbers, `whatsapp:` plus an E.164 number, short codes (3 to 7 digits, on either side: our
|
|
9
|
+
// sender, or the customer's From when Twilio delivers short-code messages), and the
|
|
10
|
+
// WhatsApp business-scoped user id Twilio puts in From/To when a customer's
|
|
11
|
+
// phone number is hidden, `whatsapp:` + a two-letter country code + "." + upper-case letters and
|
|
12
|
+
// digits (https://www.twilio.com/docs/whatsapp/key-concepts, e.g. `whatsapp:US.ABC123XYZ`).
|
|
13
|
+
const TWILIO_OWNERSHIP_ADDRESSES = [
|
|
14
|
+
{ form: "E.164", pattern: /^\+[1-9][0-9]{1,14}$/, customer: true, sender: true },
|
|
15
|
+
{ form: "whatsapp: E.164", pattern: /^whatsapp:\+[1-9][0-9]{1,14}$/, customer: true, sender: true },
|
|
16
|
+
{ form: "short code", pattern: /^[0-9]{3,7}$/, customer: true, sender: true },
|
|
17
|
+
{ form: "WhatsApp business-scoped user id", pattern: /^whatsapp:[A-Z]{2}\.[A-Z0-9]+$/, customer: true, sender: false },
|
|
18
|
+
];
|
|
19
|
+
// Short codes are three to seven digits depending on the origin country:
|
|
20
|
+
// https://www.twilio.com/docs/messaging/guides/sending-international-sms-guide
|
|
21
|
+
// "AC" and letters or digits. Not narrowed to Twilio's AC + 32 hex form, because the package's
|
|
22
|
+
// tests and examples use short ids such as "AC1".
|
|
23
|
+
const TWILIO_OWNERSHIP_ACCOUNT = /^AC[0-9A-Za-z]{1,32}$/;
|
|
24
|
+
const isTwilioOwnershipAddress = (value, side) => typeof value === "string" && TWILIO_OWNERSHIP_ADDRESSES.some((entry) => entry[side] && entry.pattern.test(value));
|
|
25
|
+
/**
|
|
26
|
+
* The conversation-ownership key for a Twilio conversation, or `null` when it cannot be named: the
|
|
27
|
+
* account id is not `AC` followed by letters or digits, or an address is not one of the supported
|
|
28
|
+
* forms for its side. The customer may be an E.164 number, `whatsapp:` + an E.164 number, a short code
|
|
29
|
+
* (3 to 7 digits), or a WhatsApp business-scoped user id (`whatsapp:US.ABC123XYZ`); the sender may be an
|
|
30
|
+
* E.164 number, `whatsapp:` + an E.164 number, or a short code. A long number typed without "+" is refused.
|
|
31
|
+
* Ownership is per key: a WhatsApp customer reachable under both a phone number and a business-scoped
|
|
32
|
+
* user id has two keys, and this function cannot resolve one to the other. For a supported tuple the key equals
|
|
33
|
+
* `twilioConversationKey({ accountSid, from: customer, to: sender })`, the inbound dispatch's
|
|
34
|
+
* `instanceId`. Every ownership decision in this module takes its key from this function: the
|
|
35
|
+
* inbound and delivery-status dispatches' `ownershipKey`, `replyWithTwilio` and the messaging
|
|
36
|
+
* client's agent sends (tests: twilio-ownership.test.ts, "every Twilio ownership decision uses one
|
|
37
|
+
* key function").
|
|
38
|
+
*/
|
|
39
|
+
export function twilioOwnershipKey(accountSid, customer, sender) {
|
|
40
|
+
if (typeof accountSid !== "string" || !TWILIO_OWNERSHIP_ACCOUNT.test(accountSid))
|
|
41
|
+
return null;
|
|
42
|
+
if (!isTwilioOwnershipAddress(customer, "customer") || !isTwilioOwnershipAddress(sender, "sender"))
|
|
43
|
+
return null;
|
|
44
|
+
return twilioConversationKey({ accountSid, from: customer, to: sender });
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* A signed webhook's ownership key. The signature covers every distinct value of a repeated field
|
|
48
|
+
* while the route reads the first, so an AccountSid, From or To with more than one distinct value
|
|
49
|
+
* gives `null`. A missing AccountSid means the channel's account, as for the inbound `instanceId`.
|
|
50
|
+
* `customerField` is From on an inbound message and To on a status callback.
|
|
51
|
+
*/
|
|
52
|
+
function twilioWebhookOwnershipKey(params, channelAccountSid, customerField) {
|
|
53
|
+
const single = (name) => {
|
|
54
|
+
const values = [...new Set(params.getAll(name))];
|
|
55
|
+
return values.length === 0 ? undefined : values.length === 1 ? values[0] : null;
|
|
56
|
+
};
|
|
57
|
+
const account = single("AccountSid");
|
|
58
|
+
const customer = single(customerField);
|
|
59
|
+
const sender = single(customerField === "From" ? "To" : "From");
|
|
60
|
+
if (account === null)
|
|
61
|
+
return null;
|
|
62
|
+
return twilioOwnershipKey(account ?? channelAccountSid, customer, sender);
|
|
63
|
+
}
|
|
6
64
|
export function parseTwilioConversationKey(id) {
|
|
7
65
|
const parsed = parseConversationKey(id);
|
|
8
66
|
if (parsed.provider !== 'twilio' || parsed.version !== 'v1' || parsed.segments.length !== 3)
|
|
@@ -11,6 +69,9 @@ export function parseTwilioConversationKey(id) {
|
|
|
11
69
|
return { accountSid, from, to };
|
|
12
70
|
}
|
|
13
71
|
export function createTwilioChannel(options) {
|
|
72
|
+
// Policies and callbacks are read and validated once, here. The handler uses only these records.
|
|
73
|
+
const keywordPolicies = resolveTwilioKeywordPolicies(options.keywords);
|
|
74
|
+
const keywordCallbacks = resolveTwilioKeywordCallbacks(options);
|
|
14
75
|
async function messages(request, ctx) {
|
|
15
76
|
const body = await readRequestBody(request);
|
|
16
77
|
if (!body)
|
|
@@ -20,31 +81,145 @@ export function createTwilioChannel(options) {
|
|
|
20
81
|
const valid = await verifyTwilioSignature(options.authToken, options.webhookUrl ?? request.url, params, signature);
|
|
21
82
|
if (!valid)
|
|
22
83
|
return new Response(null, { status: 401 });
|
|
84
|
+
// A non-empty MessageStatus marks a status callback, which the delivery-status branch answers, so
|
|
85
|
+
// nothing below sees one; an empty MessageStatus takes the inbound path (tests: "treats an empty
|
|
86
|
+
// MessageStatus as absent", "does not classify status callbacks").
|
|
87
|
+
if (params.get('MessageStatus'))
|
|
88
|
+
return handleTwilioDeliveryStatus(options, params, ctx);
|
|
23
89
|
const from = params.get('From');
|
|
24
90
|
const to = params.get('To');
|
|
25
91
|
const text = params.get('Body');
|
|
26
|
-
const status = params.get('MessageStatus');
|
|
27
92
|
const messageSid = params.get('MessageSid');
|
|
28
|
-
|
|
93
|
+
// Callback eligibility: a signed inbound webhook Twilio classified through OptOutType reaches the callback
|
|
94
|
+
// even without a Body field. Dispatch eligibility is decided separately below.
|
|
95
|
+
const keyword = from && to ? await handleTwilioKeyword(options, keywordPolicies, keywordCallbacks, params, text ?? '', from, to, messageSid) : undefined;
|
|
96
|
+
// Dispatch eligibility: an inbound webhook without a Body field is not dispatched (the `text !== null` clause;
|
|
97
|
+
// tests: "a signed webhook with OptOutType and no Body field"), and a keyword is dispatched when its
|
|
98
|
+
// class's policy is one of the two delivery values (deliversTwilioKeyword).
|
|
99
|
+
const dispatchable = text !== null && (!keyword || deliversTwilioKeyword(keyword.policy));
|
|
100
|
+
if (from && to && dispatchable) {
|
|
29
101
|
const ref = { accountSid: params.get('AccountSid') ?? options.accountSid, from, to };
|
|
30
102
|
await ctx.dispatch(options.agent, {
|
|
31
103
|
instanceId: twilioConversationKey(ref),
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
104
|
+
// Set explicitly, string or null, so a wrapped channel never decides on instanceId.
|
|
105
|
+
ownershipKey: twilioWebhookOwnershipKey(params, options.accountSid, 'From'),
|
|
106
|
+
input: { type: from.startsWith('whatsapp:') ? 'twilio.whatsapp' : 'twilio.sms', text, from, to, mediaCount: params.get('NumMedia'),
|
|
107
|
+
...(keyword?.policy === 'deliver_with_classification' ? { keyword: keyword.classification } : {}) },
|
|
108
|
+
...(messageSid ? { dedupeKey: messageSid } : {}),
|
|
36
109
|
...(options.tenantId ? { tenantId: options.tenantId } : {}),
|
|
37
110
|
actor: { onBehalfOf: from },
|
|
38
111
|
});
|
|
39
112
|
}
|
|
40
|
-
return
|
|
113
|
+
return emptyTwimlResponse();
|
|
41
114
|
}
|
|
115
|
+
validateDispatchDeliveryStatuses(options.dispatchDeliveryStatuses);
|
|
42
116
|
return defineChannel({
|
|
43
117
|
name: 'twilio', routes: [{ method: 'POST', path: '/messages', handler: messages }],
|
|
44
118
|
conversationKey: (ref) => twilioConversationKey(ref),
|
|
45
119
|
parseConversationKey: (id) => parseTwilioConversationKey(id),
|
|
46
120
|
});
|
|
47
121
|
}
|
|
122
|
+
const OPT_OUT_KEYWORDS = new Set(['STOP', 'UNSUBSCRIBE', 'END', 'QUIT', 'STOPALL', 'REVOKE', 'OPTOUT', 'CANCEL']);
|
|
123
|
+
const OPT_IN_KEYWORDS = new Set(['START', 'UNSTOP']);
|
|
124
|
+
const HELP_KEYWORDS = new Set(['HELP']);
|
|
125
|
+
const OPT_OUT_TYPE_CLASSES = { STOP: 'opt_out', START: 'opt_in', HELP: 'help' };
|
|
126
|
+
function classifyTwilioInbound(body, optOutType) {
|
|
127
|
+
const fromType = optOutType === undefined ? undefined : OPT_OUT_TYPE_CLASSES[optOutType.trim().toUpperCase()];
|
|
128
|
+
if (fromType)
|
|
129
|
+
return { class: fromType, source: 'opt_out_type' };
|
|
130
|
+
const keyword = body.trim().toUpperCase();
|
|
131
|
+
if (OPT_OUT_KEYWORDS.has(keyword))
|
|
132
|
+
return { class: 'opt_out', source: 'body' };
|
|
133
|
+
if (OPT_IN_KEYWORDS.has(keyword))
|
|
134
|
+
return { class: 'opt_in', source: 'body' };
|
|
135
|
+
if (HELP_KEYWORDS.has(keyword))
|
|
136
|
+
return { class: 'help', source: 'body' };
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Classify an inbound Twilio message. The whole trimmed, case-folded body must be
|
|
141
|
+
* a keyword; a sentence containing one is not. A valid `OptOutType` webhook value
|
|
142
|
+
* (STOP, START or HELP, which Twilio sends when Advanced Opt-Out matches a keyword)
|
|
143
|
+
* wins over the body; an unrecognized value falls back to the body.
|
|
144
|
+
*/
|
|
145
|
+
export function classifyTwilioKeyword(body, optOutType) {
|
|
146
|
+
return classifyTwilioInbound(body, optOutType)?.class;
|
|
147
|
+
}
|
|
148
|
+
const KEYWORD_POLICIES = ['deliver', 'deliver_with_classification', 'callback_only'];
|
|
149
|
+
const KEYWORD_OPTION_KEYS = { opt_out: 'optOut', opt_in: 'optIn', help: 'help' };
|
|
150
|
+
const KEYWORD_CALLBACK_KEYS = { opt_out: 'onOptOut', opt_in: 'onOptIn', help: 'onHelp' };
|
|
151
|
+
/**
|
|
152
|
+
* Reads the three known policy keys once, validates each value and returns a frozen record.
|
|
153
|
+
* Unset classes get `'callback_only'`. The request handler is passed this record instead of
|
|
154
|
+
* `options.keywords`, so a later mutation of that object does not change what is dispatched
|
|
155
|
+
* (tests: "policies are read once, when the channel is created").
|
|
156
|
+
* `undefined` means the defaults; `null`, a non-object or an array throws.
|
|
157
|
+
*/
|
|
158
|
+
function resolveTwilioKeywordPolicies(keywords) {
|
|
159
|
+
const policies = { opt_out: 'callback_only', opt_in: 'callback_only', help: 'callback_only' };
|
|
160
|
+
if (keywords === undefined)
|
|
161
|
+
return Object.freeze(policies);
|
|
162
|
+
if (typeof keywords !== 'object' || keywords === null || Array.isArray(keywords)) {
|
|
163
|
+
throw new Error('Twilio keywords must be an object with optOut, optIn and help policies.');
|
|
164
|
+
}
|
|
165
|
+
const known = Object.values(KEYWORD_OPTION_KEYS);
|
|
166
|
+
for (const key of Object.keys(keywords)) {
|
|
167
|
+
if (!known.includes(key))
|
|
168
|
+
throw new Error(`Unknown Twilio keywords key "${key}"; use optOut, optIn or help.`);
|
|
169
|
+
}
|
|
170
|
+
for (const cls of Object.keys(KEYWORD_OPTION_KEYS)) {
|
|
171
|
+
const key = KEYWORD_OPTION_KEYS[cls];
|
|
172
|
+
const value = keywords[key];
|
|
173
|
+
if (value === undefined)
|
|
174
|
+
continue;
|
|
175
|
+
if (!KEYWORD_POLICIES.includes(value)) {
|
|
176
|
+
throw new Error(`Unsupported Twilio keyword policy "${String(value)}" for "${key}"; use ${KEYWORD_POLICIES.map((p) => `'${p}'`).join(', ')}.`);
|
|
177
|
+
}
|
|
178
|
+
policies[cls] = value;
|
|
179
|
+
}
|
|
180
|
+
return Object.freeze(policies);
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Reads the class callbacks once and throws for a value that is set but not a function.
|
|
184
|
+
* The handler calls them as plain functions, so `this` is not the options object.
|
|
185
|
+
*/
|
|
186
|
+
function resolveTwilioKeywordCallbacks(options) {
|
|
187
|
+
const callbacks = {};
|
|
188
|
+
for (const cls of Object.keys(KEYWORD_CALLBACK_KEYS)) {
|
|
189
|
+
const key = KEYWORD_CALLBACK_KEYS[cls];
|
|
190
|
+
const value = options[key];
|
|
191
|
+
if (value === undefined)
|
|
192
|
+
continue;
|
|
193
|
+
if (typeof value !== 'function')
|
|
194
|
+
throw new Error(`Twilio ${key} must be a function.`);
|
|
195
|
+
callbacks[cls] = value;
|
|
196
|
+
}
|
|
197
|
+
return Object.freeze(callbacks);
|
|
198
|
+
}
|
|
199
|
+
/** A positive match on the two delivery values; any other value does not dispatch. */
|
|
200
|
+
function deliversTwilioKeyword(policy) {
|
|
201
|
+
return policy === 'deliver' || policy === 'deliver_with_classification';
|
|
202
|
+
}
|
|
203
|
+
/**
|
|
204
|
+
* Runs the class callback (awaited; a throw propagates so the request fails and
|
|
205
|
+
* Twilio sees the failure) and returns the policy that decides what the agent gets.
|
|
206
|
+
*/
|
|
207
|
+
async function handleTwilioKeyword(options, policies, callbacks, params, text, from, to, messageSid) {
|
|
208
|
+
const found = classifyTwilioInbound(text, params.get('OptOutType') ?? undefined);
|
|
209
|
+
if (!found)
|
|
210
|
+
return undefined;
|
|
211
|
+
const classification = { class: found.class, keyword: text.trim().toUpperCase(), source: found.source };
|
|
212
|
+
await callbacks[found.class]?.({
|
|
213
|
+
...classification, from, to, messageSid,
|
|
214
|
+
accountSid: params.get('AccountSid') ?? options.accountSid,
|
|
215
|
+
...(options.tenantId ? { tenantId: options.tenantId } : {}),
|
|
216
|
+
channel: from.startsWith('whatsapp:') ? 'whatsapp' : 'sms',
|
|
217
|
+
});
|
|
218
|
+
return { policy: policies[found.class], classification };
|
|
219
|
+
}
|
|
220
|
+
function emptyTwimlResponse() {
|
|
221
|
+
return new Response('<?xml version="1.0" encoding="UTF-8"?><Response></Response>', { status: 200, headers: { 'content-type': 'text/xml' } });
|
|
222
|
+
}
|
|
48
223
|
/**
|
|
49
224
|
* Verify HMAC-SHA1 using deduplicated, sorted form values and the exact URL,
|
|
50
225
|
* its parsed port-free form, or its parsed form with an explicit port.
|
|
@@ -97,18 +272,59 @@ function bytesToBase64(bytes) {
|
|
|
97
272
|
function stringToBase64(value) {
|
|
98
273
|
return bytesToBase64(new TextEncoder().encode(value));
|
|
99
274
|
}
|
|
275
|
+
/**
|
|
276
|
+
* Tool that replies from `ref.to` to `ref.from`. It returns Twilio's JSON response. With a
|
|
277
|
+
* `sentMessageStore`, an accepted reply without a sid throws `TwilioMessagingError`
|
|
278
|
+
* (`invalid_response`), and a failed record write throws `TwilioSentMessageRecordError`
|
|
279
|
+
* after the message was sent. With an `ownershipStore`, a reply on a person-owned conversation
|
|
280
|
+
* throws `ConversationOwnedByPersonError` and a failed ownership read throws
|
|
281
|
+
* `ConversationOwnershipReadError`; in both cases nothing is sent.
|
|
282
|
+
*/
|
|
100
283
|
export function replyWithTwilio(ref, options) {
|
|
284
|
+
validateTwilioCallback(options.statusCallbackUrl);
|
|
101
285
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
102
286
|
return defineTool({
|
|
103
287
|
name: 'reply_with_twilio', description: 'Reply by SMS or WhatsApp through Twilio.',
|
|
104
288
|
inputSchema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', minLength: 1 } }, required: ['text'] },
|
|
105
289
|
metadata: { effect: 'write', provider: 'twilio', channel: 'twilio' },
|
|
106
290
|
execute: async ({ text }) => {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
291
|
+
// Read the ref and options once, before the request; nothing after the await reads `ref` or
|
|
292
|
+
// `options` (tests: "replyWithTwilio records to the store it ran with when the store is ...").
|
|
293
|
+
const { accountSid, from, to } = ref;
|
|
294
|
+
const { authToken, sentMessageStore: store, agent, actor, tenantId, ownershipStore } = options;
|
|
295
|
+
const ownershipKey = twilioOwnershipKey(accountSid, from, to);
|
|
296
|
+
if (ownershipStore && ownershipKey === null)
|
|
297
|
+
throw new TypeError('replyWithTwilio with an ownershipStore needs a ref in a supported address form (see twilioOwnershipKey)');
|
|
298
|
+
const statusCallback = twilioText(options.statusCallbackUrl);
|
|
299
|
+
let recording;
|
|
300
|
+
if (store) {
|
|
301
|
+
const conversation = readSentConversation({
|
|
302
|
+
instanceId: twilioConversationKey({ accountSid, from, to }),
|
|
303
|
+
...(agent !== undefined ? { agent } : {}),
|
|
304
|
+
...(actor !== undefined ? { actor } : {}),
|
|
305
|
+
...(tenantId !== undefined ? { tenantId } : {}),
|
|
306
|
+
});
|
|
307
|
+
if (!conversation)
|
|
308
|
+
throw new TypeError(INVALID_CONVERSATION);
|
|
309
|
+
recording = { store, conversation };
|
|
310
|
+
}
|
|
311
|
+
const body = new URLSearchParams({ From: to, To: from, Body: text });
|
|
312
|
+
if (statusCallback)
|
|
313
|
+
body.set('StatusCallback', statusCallback);
|
|
314
|
+
// The ownership check is the last await before the request (tests: twilio-ownership.test.ts).
|
|
315
|
+
if (ownershipStore && ownershipKey !== null)
|
|
316
|
+
await assertAgentMaySend(ownershipStore, ownershipKey);
|
|
317
|
+
const response = await fetchImpl(`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`, {
|
|
318
|
+
method: 'POST', headers: { authorization: `Basic ${stringToBase64(`${accountSid}:${authToken}`)}`, 'content-type': 'application/x-www-form-urlencoded' }, body,
|
|
110
319
|
});
|
|
111
|
-
|
|
320
|
+
const json = await response.json();
|
|
321
|
+
if (recording && response.ok) {
|
|
322
|
+
const sid = json && typeof json === 'object' ? twilioText(json.sid) : undefined;
|
|
323
|
+
if (!sid)
|
|
324
|
+
throw new TwilioMessagingError('invalid_response', response.status);
|
|
325
|
+
await recordTwilioSend(recording.store, { messageSid: sid, ...recording.conversation });
|
|
326
|
+
}
|
|
327
|
+
return json;
|
|
112
328
|
},
|
|
113
329
|
});
|
|
114
330
|
}
|
|
@@ -203,18 +419,53 @@ export function createTwilioMessagingClient(options) {
|
|
|
203
419
|
const fetchImpl = options.fetchImpl ?? fetch;
|
|
204
420
|
return {
|
|
205
421
|
async send(input) {
|
|
206
|
-
|
|
422
|
+
// Read the input and the store once, before the request; nothing after the await reads
|
|
423
|
+
// `input` or `options` (tests: "send() records to the store it was called with ...",
|
|
424
|
+
// "send() reports the recipient ...", "send() classifies a failure by the signal ...").
|
|
425
|
+
const { to, body: text, from, messagingServiceSid, statusCallback, signal, sentBy } = input;
|
|
426
|
+
// The account and credentials are read once, here, and used for both the ownership key and the
|
|
427
|
+
// request, so a change to `options` during the ownership read cannot split them (tests:
|
|
428
|
+
// "checks and sends with the account it read before the ownership read ...").
|
|
429
|
+
const { accountSid, authToken } = options;
|
|
430
|
+
const store = options.sentMessageStore;
|
|
431
|
+
const ownershipStore = options.ownershipStore;
|
|
432
|
+
if (sentBy !== undefined && sentBy !== "agent" && sentBy !== "person")
|
|
433
|
+
throw new TypeError('Twilio sentBy must be "agent" or "person"');
|
|
434
|
+
if (!twilioText(to) || !twilioText(text))
|
|
207
435
|
throw new TypeError("Twilio to and body are required");
|
|
208
|
-
if (!twilioText(
|
|
436
|
+
if (!twilioText(from) && !twilioText(messagingServiceSid))
|
|
209
437
|
throw new TypeError("Twilio sender is required");
|
|
210
|
-
const callback = twilioText(
|
|
438
|
+
const callback = twilioText(statusCallback) ?? twilioText(options.statusCallbackUrl);
|
|
211
439
|
validateTwilioCallback(callback);
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
440
|
+
// The conversation is copied field by field now, so the record describes this call.
|
|
441
|
+
let recording;
|
|
442
|
+
if (input.conversation !== undefined) {
|
|
443
|
+
if (!store)
|
|
444
|
+
throw new TypeError("Twilio conversation requires a sentMessageStore");
|
|
445
|
+
const conversation = readSentConversation(input.conversation);
|
|
446
|
+
if (!conversation)
|
|
447
|
+
throw new TypeError(INVALID_CONVERSATION);
|
|
448
|
+
recording = { store, conversation };
|
|
449
|
+
}
|
|
450
|
+
// An agent send with an ownership store is decided by one read of the canonical key the inbound
|
|
451
|
+
// side uses for this recipient and sender number. conversation.instanceId is delivery
|
|
452
|
+
// metadata and is not an ownership key (tests: twilio-ownership.test.ts).
|
|
453
|
+
let ownershipKey = null;
|
|
454
|
+
if (ownershipStore && sentBy !== "person") {
|
|
455
|
+
ownershipKey = twilioOwnershipKey(accountSid, to, from);
|
|
456
|
+
if (ownershipKey === null)
|
|
457
|
+
throw new TypeError("Twilio agent send with an ownershipStore needs a supported account id, to and from (see twilioOwnershipKey); a Messaging Service alone cannot identify the conversation");
|
|
458
|
+
}
|
|
459
|
+
// The ownership read is the last await before the request; the abort check below runs after
|
|
460
|
+
// it so an abort during the read stops the send.
|
|
461
|
+
if (ownershipStore && ownershipKey !== null)
|
|
462
|
+
await assertAgentMaySend(ownershipStore, ownershipKey);
|
|
463
|
+
if (signal?.aborted)
|
|
464
|
+
throw new TwilioMessagingError("aborted", undefined, undefined, undefined, undefined, signal.reason);
|
|
465
|
+
const body = new URLSearchParams({ To: to, Body: text });
|
|
215
466
|
for (const [key, value] of [
|
|
216
|
-
["From",
|
|
217
|
-
["MessagingServiceSid",
|
|
467
|
+
["From", from],
|
|
468
|
+
["MessagingServiceSid", messagingServiceSid],
|
|
218
469
|
["StatusCallback", callback],
|
|
219
470
|
])
|
|
220
471
|
if (value !== undefined && twilioText(value))
|
|
@@ -222,8 +473,8 @@ export function createTwilioMessagingClient(options) {
|
|
|
222
473
|
const controller = new AbortController();
|
|
223
474
|
let timedOut = false;
|
|
224
475
|
let status;
|
|
225
|
-
const onAbort = () => controller.abort(
|
|
226
|
-
|
|
476
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
477
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
227
478
|
const timer = setTimeout(() => {
|
|
228
479
|
timedOut = true;
|
|
229
480
|
controller.abort(new DOMException("Timeout", "TimeoutError"));
|
|
@@ -234,13 +485,14 @@ export function createTwilioMessagingClient(options) {
|
|
|
234
485
|
controller.signal.addEventListener("abort", rejectAbort, { once: true });
|
|
235
486
|
});
|
|
236
487
|
void aborted.catch(() => { });
|
|
488
|
+
let result;
|
|
237
489
|
try {
|
|
238
490
|
const response = await Promise.race([
|
|
239
491
|
aborted,
|
|
240
|
-
fetchImpl(`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(
|
|
492
|
+
fetchImpl(`https://api.twilio.com/2010-04-01/Accounts/${encodeURIComponent(accountSid)}/Messages.json`, {
|
|
241
493
|
method: "POST",
|
|
242
494
|
headers: {
|
|
243
|
-
authorization: `Basic ${stringToBase64(`${
|
|
495
|
+
authorization: `Basic ${stringToBase64(`${accountSid}:${authToken}`)}`,
|
|
244
496
|
"content-type": "application/x-www-form-urlencoded",
|
|
245
497
|
},
|
|
246
498
|
body,
|
|
@@ -272,10 +524,10 @@ export function createTwilioMessagingClient(options) {
|
|
|
272
524
|
const sid = twilioText(json.sid);
|
|
273
525
|
if (!sid)
|
|
274
526
|
throw new TwilioMessagingError("invalid_response", status);
|
|
275
|
-
|
|
527
|
+
result = {
|
|
276
528
|
sid,
|
|
277
529
|
status: twilioText(json.status) ?? "",
|
|
278
|
-
to: twilioText(json.to) ??
|
|
530
|
+
to: twilioText(json.to) ?? to,
|
|
279
531
|
from: twilioText(json.from) ?? null,
|
|
280
532
|
messagingServiceSid: twilioText(json.messaging_service_sid) ?? null,
|
|
281
533
|
numSegments: twilioNumber(json.num_segments),
|
|
@@ -287,14 +539,292 @@ export function createTwilioMessagingClient(options) {
|
|
|
287
539
|
catch (cause) {
|
|
288
540
|
if (cause instanceof TwilioMessagingError)
|
|
289
541
|
throw cause;
|
|
290
|
-
throw new TwilioMessagingError(timedOut ? "timeout" :
|
|
542
|
+
throw new TwilioMessagingError(timedOut ? "timeout" : signal?.aborted ? "aborted" : "network", status, undefined, undefined, undefined, cause);
|
|
291
543
|
}
|
|
292
544
|
finally {
|
|
293
545
|
clearTimeout(timer);
|
|
294
|
-
|
|
546
|
+
signal?.removeEventListener("abort", onAbort);
|
|
295
547
|
controller.signal.removeEventListener("abort", rejectAbort);
|
|
296
548
|
}
|
|
549
|
+
// Recorded outside the try above, so a store failure is not reported as a send failure.
|
|
550
|
+
if (recording)
|
|
551
|
+
await recordTwilioSend(recording.store, { messageSid: result.sid, ...recording.conversation }, result);
|
|
552
|
+
return result;
|
|
553
|
+
},
|
|
554
|
+
};
|
|
555
|
+
}
|
|
556
|
+
const TWILIO_DELIVERY_STATUSES = ["delivered", "failed", "undelivered"];
|
|
557
|
+
const DEFAULT_DISPATCH_DELIVERY_STATUSES = ["failed", "undelivered"];
|
|
558
|
+
// Each code is mapped only where https://www.twilio.com/docs/api/errors/<code> confirms it.
|
|
559
|
+
const TWILIO_DELIVERY_FAILURE_REASONS = new Map([
|
|
560
|
+
[21610, "opt_out"],
|
|
561
|
+
[30034, "unregistered_sender"],
|
|
562
|
+
[30003, "unreachable"],
|
|
563
|
+
[30005, "unreachable"],
|
|
564
|
+
[30006, "unreachable"],
|
|
565
|
+
[30007, "carrier_filtered"],
|
|
566
|
+
]);
|
|
567
|
+
/**
|
|
568
|
+
* Classify a Twilio delivery error code. Codes outside the documented table, and a missing
|
|
569
|
+
* code, return `unknown`; the raw code stays on the event.
|
|
570
|
+
*/
|
|
571
|
+
export function classifyTwilioDeliveryFailure(errorCode) {
|
|
572
|
+
return TWILIO_DELIVERY_FAILURE_REASONS.get(errorCode) ?? "unknown";
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Test/development sent-message store. Not durable: records live in process memory. It keeps its
|
|
576
|
+
* own field-by-field copy of each record and returns a fresh copy from `findSent` and `all`.
|
|
577
|
+
*/
|
|
578
|
+
export function inMemoryTwilioSentMessageStore() {
|
|
579
|
+
const records = new Map();
|
|
580
|
+
const copy = (message) => ({ messageSid: message.messageSid, ...copySentConversation(message) });
|
|
581
|
+
return {
|
|
582
|
+
async recordSent(message) {
|
|
583
|
+
const conversation = readSentConversation(message);
|
|
584
|
+
const messageSid = twilioText(message?.messageSid);
|
|
585
|
+
if (!conversation || !messageSid)
|
|
586
|
+
throw new TypeError("Invalid Twilio sent message: messageSid and instanceId must be non-blank and the other fields must match TwilioSentMessage");
|
|
587
|
+
records.set(messageSid, { messageSid, ...conversation });
|
|
588
|
+
},
|
|
589
|
+
async findSent(messageSid) {
|
|
590
|
+
const message = records.get(messageSid);
|
|
591
|
+
return message ? copy(message) : undefined;
|
|
297
592
|
},
|
|
593
|
+
all() {
|
|
594
|
+
return [...records.values()].map(copy);
|
|
595
|
+
},
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
/**
|
|
599
|
+
* The message was sent (Twilio returned its sid) but the store write failed, so its status
|
|
600
|
+
* callbacks are reported as unmatched until the record is written. Do not resend; retry
|
|
601
|
+
* `recordSent(sentMessage)`.
|
|
602
|
+
*/
|
|
603
|
+
export class TwilioSentMessageRecordError extends Error {
|
|
604
|
+
sentMessage;
|
|
605
|
+
result;
|
|
606
|
+
name = "TwilioSentMessageRecordError";
|
|
607
|
+
messageSent = true;
|
|
608
|
+
messageSid;
|
|
609
|
+
constructor(sentMessage, result, cause) {
|
|
610
|
+
super(`Twilio message ${sentMessage.messageSid} was sent, but its delivery record could not be saved; do not resend it`, { cause });
|
|
611
|
+
this.sentMessage = sentMessage;
|
|
612
|
+
this.result = result;
|
|
613
|
+
this.messageSid = sentMessage.messageSid;
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
const ACTOR_IDENTITY_KEYS = ["agentId", "onBehalfOf", "approver"];
|
|
617
|
+
const IDENTITY_FIELDS = ["id", "type", "provider", "tenantId", "displayName"];
|
|
618
|
+
const PRINCIPAL_FIELDS = ["kind", "id", "ucPrincipal", "displayName"];
|
|
619
|
+
const CONVERSATION_FIELDS = ["instanceId", "agent", "tenantId"];
|
|
620
|
+
const INVALID_CONVERSATION = "Invalid Twilio conversation: instanceId must be non-blank and agent, tenantId and actor must match TwilioSentMessageConversation";
|
|
621
|
+
/**
|
|
622
|
+
* Copies the listed fields of an object into a fresh one. Returns undefined for a non-object, for
|
|
623
|
+
* a listed field that is set but not a string, and for a missing required field.
|
|
624
|
+
*/
|
|
625
|
+
function readStringFields(value, fields, required = []) {
|
|
626
|
+
if (typeof value !== "object" || value === null)
|
|
627
|
+
return undefined;
|
|
628
|
+
const copy = {};
|
|
629
|
+
for (const field of fields) {
|
|
630
|
+
const item = value[field];
|
|
631
|
+
if (item === undefined)
|
|
632
|
+
continue;
|
|
633
|
+
if (typeof item !== "string")
|
|
634
|
+
return undefined;
|
|
635
|
+
copy[field] = item;
|
|
636
|
+
}
|
|
637
|
+
return required.every((field) => copy[field] !== undefined) ? copy : undefined;
|
|
638
|
+
}
|
|
639
|
+
/** Copies a FabricActor: each identity is a string or an object with a string `id`; a principal has string `kind` and `id`. */
|
|
640
|
+
function readActor(value) {
|
|
641
|
+
if (typeof value !== "object" || value === null)
|
|
642
|
+
return undefined;
|
|
643
|
+
const source = value;
|
|
644
|
+
const actor = {};
|
|
645
|
+
for (const key of ACTOR_IDENTITY_KEYS) {
|
|
646
|
+
const item = source[key];
|
|
647
|
+
if (item === undefined)
|
|
648
|
+
continue;
|
|
649
|
+
const identity = typeof item === "string" ? item : readStringFields(item, IDENTITY_FIELDS, ["id"]);
|
|
650
|
+
if (identity === undefined)
|
|
651
|
+
return undefined;
|
|
652
|
+
actor[key] = identity;
|
|
653
|
+
}
|
|
654
|
+
const principalValue = source.principal;
|
|
655
|
+
if (principalValue !== undefined) {
|
|
656
|
+
const principal = readStringFields(principalValue, PRINCIPAL_FIELDS, ["kind", "id"]);
|
|
657
|
+
if (!principal)
|
|
658
|
+
return undefined;
|
|
659
|
+
actor.principal = principal;
|
|
660
|
+
}
|
|
661
|
+
return actor;
|
|
662
|
+
}
|
|
663
|
+
/** Copies a conversation's documented fields; undefined when it does not have that shape. */
|
|
664
|
+
function readSentConversation(value) {
|
|
665
|
+
const fields = readStringFields(value, CONVERSATION_FIELDS);
|
|
666
|
+
if (!fields)
|
|
667
|
+
return undefined;
|
|
668
|
+
const instanceId = twilioText(fields.instanceId);
|
|
669
|
+
if (!instanceId)
|
|
670
|
+
return undefined;
|
|
671
|
+
const actorValue = value.actor;
|
|
672
|
+
let actor;
|
|
673
|
+
if (actorValue !== undefined) {
|
|
674
|
+
actor = readActor(actorValue);
|
|
675
|
+
if (!actor)
|
|
676
|
+
return undefined;
|
|
677
|
+
}
|
|
678
|
+
return {
|
|
679
|
+
instanceId,
|
|
680
|
+
...(fields.agent !== undefined ? { agent: fields.agent } : {}),
|
|
681
|
+
...(fields.tenantId !== undefined ? { tenantId: fields.tenantId } : {}),
|
|
682
|
+
...(actor ? { actor } : {}),
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
/** A fresh copy of a conversation that readSentConversation produced, so it holds only plain documented fields. */
|
|
686
|
+
function copySentConversation(conversation) {
|
|
687
|
+
const { actor } = conversation;
|
|
688
|
+
let actorCopy;
|
|
689
|
+
if (actor) {
|
|
690
|
+
actorCopy = {};
|
|
691
|
+
for (const key of ACTOR_IDENTITY_KEYS) {
|
|
692
|
+
const identity = actor[key];
|
|
693
|
+
if (identity !== undefined)
|
|
694
|
+
actorCopy[key] = typeof identity === "string" ? identity : { ...identity };
|
|
695
|
+
}
|
|
696
|
+
if (actor.principal)
|
|
697
|
+
actorCopy.principal = { ...actor.principal };
|
|
698
|
+
}
|
|
699
|
+
return {
|
|
700
|
+
instanceId: conversation.instanceId,
|
|
701
|
+
...(conversation.agent !== undefined ? { agent: conversation.agent } : {}),
|
|
702
|
+
...(conversation.tenantId !== undefined ? { tenantId: conversation.tenantId } : {}),
|
|
703
|
+
...(actorCopy ? { actor: actorCopy } : {}),
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
async function recordTwilioSend(store, sentMessage, result) {
|
|
707
|
+
try {
|
|
708
|
+
await store.recordSent(sentMessage);
|
|
709
|
+
}
|
|
710
|
+
catch (cause) {
|
|
711
|
+
throw new TwilioSentMessageRecordError(sentMessage, result, cause);
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
function isTwilioDeliveryStatus(status) {
|
|
715
|
+
return TWILIO_DELIVERY_STATUSES.includes(status);
|
|
716
|
+
}
|
|
717
|
+
function validateDispatchDeliveryStatuses(statuses) {
|
|
718
|
+
if (statuses === undefined)
|
|
719
|
+
return;
|
|
720
|
+
if (!Array.isArray(statuses) || !statuses.every(isTwilioDeliveryStatus))
|
|
721
|
+
throw new TypeError(`Twilio dispatchDeliveryStatuses accepts only ${TWILIO_DELIVERY_STATUSES.join(", ")}`);
|
|
722
|
+
}
|
|
723
|
+
// The status values and the sid pattern (^(SM|MM)[0-9a-fA-F]{32}$) on Twilio's Message resource
|
|
724
|
+
// page: https://www.twilio.com/docs/messaging/api/message-resource
|
|
725
|
+
const TWILIO_MESSAGE_STATUSES = [
|
|
726
|
+
"queued", "sending", "sent", "failed", "delivered", "undelivered", "receiving", "received",
|
|
727
|
+
"accepted", "scheduled", "read", "partially_delivered", "canceled",
|
|
728
|
+
];
|
|
729
|
+
const TWILIO_MESSAGE_SID = /^(SM|MM)[0-9a-fA-F]{32}$/;
|
|
730
|
+
const UNRECOGNIZED = "unrecognized";
|
|
731
|
+
async function reportUnmatchedStatus(options, record, cause) {
|
|
732
|
+
if (options.onUnmatchedStatus)
|
|
733
|
+
return options.onUnmatchedStatus(record, cause);
|
|
734
|
+
// Default report: the event name, the cause, and the status and sid only when they are values
|
|
735
|
+
// Twilio documents; anything else in the request is replaced or left out.
|
|
736
|
+
const status = TWILIO_MESSAGE_STATUSES.includes(record.status) ? record.status : UNRECOGNIZED;
|
|
737
|
+
const messageSid = TWILIO_MESSAGE_SID.test(record.messageSid) ? record.messageSid : UNRECOGNIZED;
|
|
738
|
+
console.warn(`[fabric-harness:twilio] ${JSON.stringify({ event: "twilio.status_unmatched", messageSid, status, reason: cause })}`);
|
|
739
|
+
}
|
|
740
|
+
function twilioAcknowledgement() {
|
|
741
|
+
return new Response('<?xml version="1.0" encoding="UTF-8"?><Response></Response>', { status: 200, headers: { "content-type": "text/xml" } });
|
|
742
|
+
}
|
|
743
|
+
function deliverySignalBody(messageSid, status, reason, errorCode) {
|
|
744
|
+
if (status === "delivered")
|
|
745
|
+
return `Twilio reports message ${messageSid} as delivered.`;
|
|
746
|
+
const code = errorCode === undefined ? "" : `, Twilio error ${errorCode}`;
|
|
747
|
+
return `Twilio reports message ${messageSid} as ${status} (reason: ${reason ?? "unknown"}${code}). The recipient did not receive it.`;
|
|
748
|
+
}
|
|
749
|
+
async function handleTwilioDeliveryStatus(options, params, ctx) {
|
|
750
|
+
const record = parseTwilioStatusParams(params);
|
|
751
|
+
if (!record)
|
|
752
|
+
return new Response(null, { status: 400 });
|
|
753
|
+
const store = options.sentMessageStore;
|
|
754
|
+
if (!store) {
|
|
755
|
+
await reportUnmatchedStatus(options, record, "no_store");
|
|
756
|
+
return twilioAcknowledgement();
|
|
757
|
+
}
|
|
758
|
+
let found;
|
|
759
|
+
try {
|
|
760
|
+
found = await store.findSent(record.messageSid);
|
|
761
|
+
}
|
|
762
|
+
catch {
|
|
763
|
+
// A failed lookup is not "unmatched": fail the request so Twilio may retry it.
|
|
764
|
+
return new Response(null, { status: 500 });
|
|
765
|
+
}
|
|
766
|
+
if (found === undefined) {
|
|
767
|
+
await reportUnmatchedStatus(options, record, "not_recorded");
|
|
768
|
+
return twilioAcknowledgement();
|
|
769
|
+
}
|
|
770
|
+
// The event's copy of the store's record (tests: "leaves the object the store returned unchanged").
|
|
771
|
+
const conversation = readSentConversation(found);
|
|
772
|
+
if (!conversation)
|
|
773
|
+
return new Response(null, { status: 500 });
|
|
774
|
+
// A record for a different message would route this event to another conversation, so it fails the
|
|
775
|
+
// request like any other unusable lookup (test: "fails the request when the store returns a record for another message").
|
|
776
|
+
if (found.messageSid !== record.messageSid)
|
|
777
|
+
return new Response(null, { status: 500 });
|
|
778
|
+
if (!isTwilioDeliveryStatus(record.status))
|
|
779
|
+
return twilioAcknowledgement();
|
|
780
|
+
const { messageSid, status, errorCode, dedupeKey } = record;
|
|
781
|
+
const reason = status !== "delivered" ? classifyTwilioDeliveryFailure(errorCode) : undefined;
|
|
782
|
+
const startsAgentTurn = (options.dispatchDeliveryStatuses ?? DEFAULT_DISPATCH_DELIVERY_STATUSES).includes(status);
|
|
783
|
+
// The dispatch is built before the hook runs, from its own copy of the conversation and from
|
|
784
|
+
// strings and numbers, so the hook cannot change it (tests: "keeps the dispatch unchanged ...").
|
|
785
|
+
let dispatch;
|
|
786
|
+
if (startsAgentTurn) {
|
|
787
|
+
const target = copySentConversation(conversation);
|
|
788
|
+
const tenantId = target.tenantId ?? options.tenantId;
|
|
789
|
+
dispatch = {
|
|
790
|
+
agent: target.agent ?? options.agent,
|
|
791
|
+
request: {
|
|
792
|
+
// The dispatch goes to the recorded instance, but ownership is decided on the
|
|
793
|
+
// conversation's address key (tests: twilio-ownership.test.ts, "whatever instance id the
|
|
794
|
+
// send recorded").
|
|
795
|
+
instanceId: target.instanceId,
|
|
796
|
+
ownershipKey: twilioWebhookOwnershipKey(params, options.accountSid, "To"),
|
|
797
|
+
message: {
|
|
798
|
+
kind: "signal",
|
|
799
|
+
type: "twilio.delivery",
|
|
800
|
+
body: deliverySignalBody(messageSid, status, reason, errorCode),
|
|
801
|
+
attributes: {
|
|
802
|
+
messageSid,
|
|
803
|
+
status,
|
|
804
|
+
...(reason !== undefined ? { reason } : {}),
|
|
805
|
+
...(errorCode !== undefined ? { errorCode: String(errorCode) } : {}),
|
|
806
|
+
},
|
|
807
|
+
},
|
|
808
|
+
dedupeKey,
|
|
809
|
+
...(tenantId !== undefined ? { tenantId } : {}),
|
|
810
|
+
...(target.actor !== undefined ? { actor: target.actor } : {}),
|
|
811
|
+
},
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
const event = {
|
|
815
|
+
type: "twilio.delivery",
|
|
816
|
+
messageSid,
|
|
817
|
+
status,
|
|
818
|
+
...(reason !== undefined ? { reason } : {}),
|
|
819
|
+
...(errorCode !== undefined ? { errorCode } : {}),
|
|
820
|
+
dedupeKey,
|
|
821
|
+
conversation: { messageSid, ...conversation },
|
|
822
|
+
startsAgentTurn,
|
|
823
|
+
record,
|
|
298
824
|
};
|
|
825
|
+
await options.onDeliveryEvent?.(event);
|
|
826
|
+
if (dispatch)
|
|
827
|
+
await ctx.dispatch(dispatch.agent, dispatch.request);
|
|
828
|
+
return twilioAcknowledgement();
|
|
299
829
|
}
|
|
300
830
|
//# sourceMappingURL=twilio.js.map
|