@terreno/comms 57.2.0 → 57.3.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 +58 -0
- package/dist/adapters/expoPush.d.ts +54 -0
- package/dist/adapters/expoPush.js +400 -0
- package/dist/adapters/sendgrid.d.ts +3 -0
- package/dist/adapters/sendgrid.js +7 -1
- package/dist/adapters/twilioSms.d.ts +36 -0
- package/dist/adapters/twilioSms.js +232 -0
- package/dist/adapters/twilioVerify.d.ts +44 -0
- package/dist/adapters/twilioVerify.js +212 -0
- package/dist/commsApp.d.ts +4 -1
- package/dist/commsApp.js +28 -2
- package/dist/commsQuery.d.ts +30 -0
- package/dist/commsQuery.js +134 -0
- package/dist/commsRetry.d.ts +16 -0
- package/dist/commsRetry.js +79 -0
- package/dist/commsService.d.ts +11 -4
- package/dist/commsService.js +217 -47
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -1
- package/dist/routes/commsDashboard.d.ts +11 -0
- package/dist/routes/commsDashboard.js +414 -0
- package/dist/templates.d.ts +9 -0
- package/dist/templates.js +34 -1
- package/dist/types.d.ts +11 -0
- package/dist/webhooks/sendgridWebhooks.d.ts +16 -0
- package/dist/webhooks/sendgridWebhooks.js +251 -0
- package/dist/webhooks/twilioWebhooks.d.ts +18 -0
- package/dist/webhooks/twilioWebhooks.js +175 -0
- package/package.json +26 -5
- package/src/adapters/expoPush.test.ts +585 -0
- package/src/adapters/expoPush.ts +304 -0
- package/src/adapters/sendgrid.ts +8 -0
- package/src/adapters/twilioSms.test.ts +374 -0
- package/src/adapters/twilioSms.ts +237 -0
- package/src/adapters/twilioVerify.test.ts +207 -0
- package/src/adapters/twilioVerify.ts +227 -0
- package/src/commsApp.test.ts +13 -0
- package/src/commsApp.ts +38 -3
- package/src/commsQuery.test.ts +165 -0
- package/src/commsQuery.ts +162 -0
- package/src/commsRetry.ts +87 -0
- package/src/commsService.test.ts +68 -0
- package/src/commsService.ts +177 -20
- package/src/index.ts +9 -2
- package/src/routes/commsDashboard.test.ts +310 -0
- package/src/routes/commsDashboard.ts +327 -0
- package/src/templates.test.ts +63 -1
- package/src/templates.ts +47 -0
- package/src/tests/bunSetup.ts +8 -0
- package/src/types.ts +13 -0
- package/src/webhooks/sendgridWebhooks.test.ts +520 -0
- package/src/webhooks/sendgridWebhooks.ts +166 -0
- package/src/webhooks/twilioWebhooks.test.ts +352 -0
- package/src/webhooks/twilioWebhooks.ts +154 -0
- package/dist/routes/commsExplorer.d.ts +0 -7
- package/dist/routes/commsExplorer.js +0 -147
- package/src/routes/commsExplorer.ts +0 -114
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import {createRequire} from "node:module";
|
|
2
|
+
import {logger} from "@terreno/api";
|
|
3
|
+
|
|
4
|
+
import type {CommsErrorClass, DeliveryEvent, PushMessage, PushProvider, SendResult} from "../types";
|
|
5
|
+
|
|
6
|
+
const nodeRequire = createRequire(__filename);
|
|
7
|
+
const DEFAULT_RECEIPT_POLL_DELAY_MS = 15 * 60 * 1000;
|
|
8
|
+
|
|
9
|
+
export interface ExpoPushMessage {
|
|
10
|
+
badge?: number;
|
|
11
|
+
body: string;
|
|
12
|
+
data?: Record<string, unknown>;
|
|
13
|
+
sound?: string | null;
|
|
14
|
+
title: string;
|
|
15
|
+
to: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface ExpoPushTicket {
|
|
19
|
+
details?: {error?: string};
|
|
20
|
+
id?: string;
|
|
21
|
+
message?: string;
|
|
22
|
+
status: "error" | "ok";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ExpoPushReceipt {
|
|
26
|
+
details?: {error?: string};
|
|
27
|
+
message?: string;
|
|
28
|
+
status: "error" | "ok";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface ExpoPushClient {
|
|
32
|
+
chunkPushNotificationReceiptIds: (receiptIds: string[]) => string[][];
|
|
33
|
+
chunkPushNotifications: (messages: ExpoPushMessage[]) => ExpoPushMessage[][];
|
|
34
|
+
getPushNotificationReceiptsAsync: (
|
|
35
|
+
receiptIds: string[]
|
|
36
|
+
) => Promise<Record<string, ExpoPushReceipt>>;
|
|
37
|
+
sendPushNotificationsAsync: (messages: ExpoPushMessage[]) => Promise<ExpoPushTicket[]>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface ExpoSdkModule {
|
|
41
|
+
Expo: {
|
|
42
|
+
isExpoPushToken: (token: string) => boolean;
|
|
43
|
+
new (options?: {accessToken?: string}): ExpoPushClient;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export interface ExpoPushProviderOptions {
|
|
48
|
+
accessToken?: string;
|
|
49
|
+
/** Injected client for tests. Production wiring loads `expo-server-sdk`. */
|
|
50
|
+
client?: ExpoPushClient;
|
|
51
|
+
isExpoPushToken?: (token: string) => boolean;
|
|
52
|
+
onDeadToken?: (token: string) => Promise<void>;
|
|
53
|
+
onDeliveryEvent?: (event: DeliveryEvent) => Promise<void>;
|
|
54
|
+
receiptPollDelayMs?: number;
|
|
55
|
+
scheduleReceiptPoll?: (delayMs: number, run: () => Promise<void>) => void;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const resolveAccessToken = (options?: ExpoPushProviderOptions): string | undefined =>
|
|
59
|
+
options?.accessToken ?? process.env.EXPO_ACCESS_TOKEN;
|
|
60
|
+
|
|
61
|
+
const loadExpoSdk = (): ExpoSdkModule => {
|
|
62
|
+
try {
|
|
63
|
+
// Optional peer — keep `expo-server-sdk` out of core dependencies.
|
|
64
|
+
return nodeRequire("expo-server-sdk") as ExpoSdkModule;
|
|
65
|
+
} catch {
|
|
66
|
+
throw new Error(
|
|
67
|
+
"ExpoPushProvider requires optional peer dependency expo-server-sdk. " +
|
|
68
|
+
"Install it with: bun add expo-server-sdk"
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const defaultIsExpoPushToken = (token: string): boolean =>
|
|
74
|
+
(token.startsWith("ExponentPushToken[") || token.startsWith("ExpoPushToken[")) &&
|
|
75
|
+
token.endsWith("]");
|
|
76
|
+
|
|
77
|
+
const classifyExpoError = (
|
|
78
|
+
code: string | undefined
|
|
79
|
+
): {errorClass: CommsErrorClass; errorCode: string} => {
|
|
80
|
+
if (code === "InvalidCredentials" || code === "MessageTooBig") {
|
|
81
|
+
return {errorClass: "config", errorCode: code};
|
|
82
|
+
}
|
|
83
|
+
if (code === "DeviceNotRegistered") {
|
|
84
|
+
return {errorClass: "permanent", errorCode: code};
|
|
85
|
+
}
|
|
86
|
+
if (code === "MessageRateExceeded") {
|
|
87
|
+
return {errorClass: "transient", errorCode: code};
|
|
88
|
+
}
|
|
89
|
+
return {errorClass: "transient", errorCode: code ?? "expo-unknown"};
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
const failedResult = ({
|
|
93
|
+
error,
|
|
94
|
+
errorClass,
|
|
95
|
+
errorCode,
|
|
96
|
+
}: {
|
|
97
|
+
error: string;
|
|
98
|
+
errorClass: CommsErrorClass;
|
|
99
|
+
errorCode: string;
|
|
100
|
+
}): SendResult => {
|
|
101
|
+
if (errorClass === "config") {
|
|
102
|
+
logger.error(`[comms:expo] ${errorCode}: ${error}`);
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
accepted: false,
|
|
106
|
+
error,
|
|
107
|
+
errorClass,
|
|
108
|
+
errorCode,
|
|
109
|
+
isPermanentFailure: errorClass === "permanent",
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const invalidTokenResult = (): SendResult =>
|
|
114
|
+
failedResult({
|
|
115
|
+
error: "Not an Expo push token",
|
|
116
|
+
errorClass: "permanent",
|
|
117
|
+
errorCode: "expo-invalid-token",
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
const ticketToResult = (ticket: ExpoPushTicket | undefined): SendResult => {
|
|
121
|
+
if (!ticket) {
|
|
122
|
+
return failedResult({
|
|
123
|
+
error: "Expo returned no ticket for this token",
|
|
124
|
+
errorClass: "transient",
|
|
125
|
+
errorCode: "expo-missing-ticket",
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
if (ticket.status === "ok") {
|
|
129
|
+
return {accepted: true, providerMessageId: ticket.id};
|
|
130
|
+
}
|
|
131
|
+
const {errorClass, errorCode} = classifyExpoError(ticket.details?.error);
|
|
132
|
+
return failedResult({
|
|
133
|
+
error: ticket.message ?? errorCode,
|
|
134
|
+
errorClass,
|
|
135
|
+
errorCode,
|
|
136
|
+
});
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const defaultScheduleReceiptPoll = (delayMs: number, run: () => Promise<void>): void => {
|
|
140
|
+
setTimeout(() => {
|
|
141
|
+
void run();
|
|
142
|
+
}, delayMs);
|
|
143
|
+
};
|
|
144
|
+
|
|
145
|
+
export class ExpoPushProvider implements PushProvider {
|
|
146
|
+
readonly id = "expo";
|
|
147
|
+
private readonly client: ExpoPushClient;
|
|
148
|
+
private readonly isExpoPushToken: (token: string) => boolean;
|
|
149
|
+
private readonly onDeadToken?: (token: string) => Promise<void>;
|
|
150
|
+
private readonly onDeliveryEvent?: (event: DeliveryEvent) => Promise<void>;
|
|
151
|
+
private readonly receiptPollDelayMs: number;
|
|
152
|
+
private readonly scheduleReceiptPoll: (delayMs: number, run: () => Promise<void>) => void;
|
|
153
|
+
private pendingReceipts = new Map<string, string>();
|
|
154
|
+
|
|
155
|
+
constructor(options?: ExpoPushProviderOptions) {
|
|
156
|
+
this.onDeadToken = options?.onDeadToken;
|
|
157
|
+
this.onDeliveryEvent = options?.onDeliveryEvent;
|
|
158
|
+
this.receiptPollDelayMs = options?.receiptPollDelayMs ?? DEFAULT_RECEIPT_POLL_DELAY_MS;
|
|
159
|
+
this.scheduleReceiptPoll = options?.scheduleReceiptPoll ?? defaultScheduleReceiptPoll;
|
|
160
|
+
|
|
161
|
+
if (options?.client) {
|
|
162
|
+
this.client = options.client;
|
|
163
|
+
this.isExpoPushToken = options.isExpoPushToken ?? defaultIsExpoPushToken;
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const ExpoSdk = loadExpoSdk();
|
|
168
|
+
const accessToken = resolveAccessToken(options);
|
|
169
|
+
this.client = new ExpoSdk.Expo(accessToken ? {accessToken} : {});
|
|
170
|
+
this.isExpoPushToken = options?.isExpoPushToken ?? ExpoSdk.Expo.isExpoPushToken;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
async sendPush(message: PushMessage): Promise<SendResult[]> {
|
|
174
|
+
const results: SendResult[] = message.tokens.map((token) =>
|
|
175
|
+
this.isExpoPushToken(token) ? {accepted: false, errorCode: "pending"} : invalidTokenResult()
|
|
176
|
+
);
|
|
177
|
+
const validIndexes: number[] = [];
|
|
178
|
+
const expoMessages: ExpoPushMessage[] = [];
|
|
179
|
+
message.tokens.forEach((token, index) => {
|
|
180
|
+
if (!this.isExpoPushToken(token)) {
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
validIndexes.push(index);
|
|
184
|
+
expoMessages.push({
|
|
185
|
+
badge: message.badge,
|
|
186
|
+
body: message.body,
|
|
187
|
+
data: message.data,
|
|
188
|
+
sound: message.sound,
|
|
189
|
+
title: message.title,
|
|
190
|
+
to: token,
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
if (expoMessages.length === 0) {
|
|
195
|
+
return results.map((result) =>
|
|
196
|
+
result.errorCode === "pending" ? invalidTokenResult() : result
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const chunks = this.client.chunkPushNotifications(expoMessages);
|
|
201
|
+
let cursor = 0;
|
|
202
|
+
const newReceipts: string[] = [];
|
|
203
|
+
for (const chunk of chunks) {
|
|
204
|
+
let tickets: ExpoPushTicket[];
|
|
205
|
+
try {
|
|
206
|
+
tickets = await this.client.sendPushNotificationsAsync(chunk);
|
|
207
|
+
} catch (error: unknown) {
|
|
208
|
+
const errorMessage = error instanceof Error ? error.message : "Expo send failed";
|
|
209
|
+
for (let offset = 0; offset < chunk.length; offset += 1) {
|
|
210
|
+
const tokenIndex = validIndexes[cursor + offset];
|
|
211
|
+
if (tokenIndex === undefined) {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
results[tokenIndex] = failedResult({
|
|
215
|
+
error: errorMessage,
|
|
216
|
+
errorClass: "transient",
|
|
217
|
+
errorCode: "expo-send-throw",
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
cursor += chunk.length;
|
|
221
|
+
continue;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
chunk.forEach((expoMessage, offset) => {
|
|
225
|
+
const tokenIndex = validIndexes[cursor + offset];
|
|
226
|
+
if (tokenIndex === undefined) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const result = ticketToResult(tickets[offset]);
|
|
230
|
+
results[tokenIndex] = result;
|
|
231
|
+
if (result.accepted && result.providerMessageId) {
|
|
232
|
+
this.pendingReceipts.set(result.providerMessageId, String(expoMessage.to));
|
|
233
|
+
newReceipts.push(result.providerMessageId);
|
|
234
|
+
}
|
|
235
|
+
});
|
|
236
|
+
cursor += chunk.length;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
if (newReceipts.length > 0) {
|
|
240
|
+
this.scheduleReceiptPoll(this.receiptPollDelayMs, () => this.pollReceipts(newReceipts));
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return results.map((result) =>
|
|
244
|
+
result.errorCode === "pending"
|
|
245
|
+
? failedResult({
|
|
246
|
+
error: "Expo returned no ticket for this token",
|
|
247
|
+
errorClass: "transient",
|
|
248
|
+
errorCode: "expo-missing-ticket",
|
|
249
|
+
})
|
|
250
|
+
: result
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
private async pollReceipts(receiptIds: string[]): Promise<void> {
|
|
255
|
+
const chunks = this.client.chunkPushNotificationReceiptIds(receiptIds);
|
|
256
|
+
for (const chunk of chunks) {
|
|
257
|
+
let receipts: Record<string, ExpoPushReceipt>;
|
|
258
|
+
try {
|
|
259
|
+
receipts = await this.client.getPushNotificationReceiptsAsync(chunk);
|
|
260
|
+
} catch (error: unknown) {
|
|
261
|
+
logger.warn(`[comms:expo] Receipt poll failed: ${String(error)}`);
|
|
262
|
+
for (const receiptId of chunk) {
|
|
263
|
+
this.pendingReceipts.delete(receiptId);
|
|
264
|
+
}
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
await Promise.all(
|
|
268
|
+
Object.entries(receipts).map(([receiptId, receipt]) =>
|
|
269
|
+
this.applyReceipt(receiptId, receipt)
|
|
270
|
+
)
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
private async applyReceipt(receiptId: string, receipt: ExpoPushReceipt): Promise<void> {
|
|
276
|
+
const token = this.pendingReceipts.get(receiptId);
|
|
277
|
+
this.pendingReceipts.delete(receiptId);
|
|
278
|
+
if (receipt.status === "ok") {
|
|
279
|
+
if (this.onDeliveryEvent) {
|
|
280
|
+
await this.onDeliveryEvent({
|
|
281
|
+
channel: "push",
|
|
282
|
+
providerMessageId: receiptId,
|
|
283
|
+
raw: receipt,
|
|
284
|
+
status: "delivered",
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
const {errorClass, errorCode} = classifyExpoError(receipt.details?.error);
|
|
290
|
+
if (this.onDeliveryEvent) {
|
|
291
|
+
await this.onDeliveryEvent({
|
|
292
|
+
channel: "push",
|
|
293
|
+
errorClass,
|
|
294
|
+
errorCode,
|
|
295
|
+
providerMessageId: receiptId,
|
|
296
|
+
raw: receipt,
|
|
297
|
+
status: "failed",
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
if (token && errorClass === "permanent" && this.onDeadToken) {
|
|
301
|
+
await this.onDeadToken(token);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
package/src/adapters/sendgrid.ts
CHANGED
|
@@ -27,6 +27,7 @@ export interface SendGridMailProviderOptions {
|
|
|
27
27
|
fromEmail?: string;
|
|
28
28
|
fromName?: string;
|
|
29
29
|
sandboxMode?: boolean;
|
|
30
|
+
webhookVerificationKey?: string;
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
const EMAIL_ACTIVITY_BASE = "https://app.sendgrid.com/email_activity";
|
|
@@ -155,12 +156,15 @@ export class SendGridMailProvider implements MailProvider {
|
|
|
155
156
|
private readonly fromEmail?: string;
|
|
156
157
|
private readonly fromName?: string;
|
|
157
158
|
private readonly sandboxMode: boolean;
|
|
159
|
+
private readonly webhookVerificationKey?: string;
|
|
158
160
|
|
|
159
161
|
constructor(options?: SendGridMailProviderOptions) {
|
|
160
162
|
const apiKey = resolveApiKey(options);
|
|
161
163
|
this.fromEmail = options?.fromEmail;
|
|
162
164
|
this.fromName = options?.fromName;
|
|
163
165
|
this.sandboxMode = options?.sandboxMode ?? process.env.NODE_ENV === "test";
|
|
166
|
+
this.webhookVerificationKey =
|
|
167
|
+
options?.webhookVerificationKey ?? process.env.SENDGRID_WEBHOOK_VERIFICATION_KEY;
|
|
164
168
|
|
|
165
169
|
if (options?.client) {
|
|
166
170
|
this.client = options.client;
|
|
@@ -172,6 +176,10 @@ export class SendGridMailProvider implements MailProvider {
|
|
|
172
176
|
this.client = sgMail;
|
|
173
177
|
}
|
|
174
178
|
|
|
179
|
+
getWebhookVerificationKey = (): string | undefined => {
|
|
180
|
+
return this.webhookVerificationKey;
|
|
181
|
+
};
|
|
182
|
+
|
|
175
183
|
async sendMail(message: MailMessage): Promise<SendResult> {
|
|
176
184
|
const fromEmail = this.fromEmail ?? message.from;
|
|
177
185
|
if (!fromEmail) {
|
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
import {describe, it, spyOn} from "bun:test";
|
|
2
|
+
import {logger} from "@terreno/api";
|
|
3
|
+
import {assert} from "chai";
|
|
4
|
+
|
|
5
|
+
import {CommsService} from "../commsService";
|
|
6
|
+
import {CommsMessage} from "../models/commsMessage";
|
|
7
|
+
import {type TwilioSmsClient, TwilioSmsProvider} from "./twilioSms";
|
|
8
|
+
|
|
9
|
+
interface MockCreateCall {
|
|
10
|
+
params: {
|
|
11
|
+
body: string;
|
|
12
|
+
from?: string;
|
|
13
|
+
messagingServiceSid?: string;
|
|
14
|
+
statusCallback?: string;
|
|
15
|
+
to: string;
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const createMockClient = (
|
|
20
|
+
behavior?: (params: MockCreateCall["params"]) => Promise<{sid: string}>
|
|
21
|
+
): TwilioSmsClient & {calls: MockCreateCall[]} => {
|
|
22
|
+
const calls: MockCreateCall[] = [];
|
|
23
|
+
return {
|
|
24
|
+
calls,
|
|
25
|
+
messages: {
|
|
26
|
+
create: async (params): Promise<{sid: string}> => {
|
|
27
|
+
calls.push({params});
|
|
28
|
+
if (behavior) {
|
|
29
|
+
return behavior(params);
|
|
30
|
+
}
|
|
31
|
+
return {sid: "SM123"};
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const twilioRestError = ({
|
|
38
|
+
code,
|
|
39
|
+
message,
|
|
40
|
+
status,
|
|
41
|
+
}: {
|
|
42
|
+
code: number;
|
|
43
|
+
message: string;
|
|
44
|
+
status: number;
|
|
45
|
+
}): Error & {code: number; moreInfo: string; status: number} => {
|
|
46
|
+
const error = new Error(message) as Error & {code: number; moreInfo: string; status: number};
|
|
47
|
+
error.code = code;
|
|
48
|
+
error.moreInfo = `https://www.twilio.com/docs/errors/${code}`;
|
|
49
|
+
error.status = status;
|
|
50
|
+
return error;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
describe("TwilioSmsProvider", () => {
|
|
54
|
+
it("fails fast when account SID or auth token is missing", (): void => {
|
|
55
|
+
Reflect.deleteProperty(process.env, "TWILIO_ACCOUNT_SID");
|
|
56
|
+
Reflect.deleteProperty(process.env, "TWILIO_AUTH_TOKEN");
|
|
57
|
+
assert.throws(
|
|
58
|
+
(): TwilioSmsProvider => new TwilioSmsProvider({client: createMockClient()}),
|
|
59
|
+
/TWILIO_ACCOUNT_SID/
|
|
60
|
+
);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("constructs without an injected client when the twilio peer is installed", (): void => {
|
|
64
|
+
const provider = new TwilioSmsProvider({
|
|
65
|
+
accountSid: "ACtest",
|
|
66
|
+
authToken: "token",
|
|
67
|
+
});
|
|
68
|
+
assert.equal(provider.id, "twilio");
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
it("sends with messagingServiceSid when both senders are configured", async (): Promise<void> => {
|
|
72
|
+
const client = createMockClient();
|
|
73
|
+
const provider = new TwilioSmsProvider({
|
|
74
|
+
accountSid: "ACtest",
|
|
75
|
+
authToken: "token",
|
|
76
|
+
client,
|
|
77
|
+
fromNumber: "+15555550199",
|
|
78
|
+
messagingServiceSid: "MGservice",
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
const result = await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
82
|
+
|
|
83
|
+
assert.isTrue(result.accepted);
|
|
84
|
+
assert.equal(result.providerMessageId, "SM123");
|
|
85
|
+
assert.equal(client.calls.length, 1);
|
|
86
|
+
assert.equal(client.calls[0]?.params.messagingServiceSid, "MGservice");
|
|
87
|
+
assert.isUndefined(client.calls[0]?.params.from);
|
|
88
|
+
assert.equal(client.calls[0]?.params.to, "+14155552671");
|
|
89
|
+
assert.equal(client.calls[0]?.params.body, "Hello");
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("sends with fromNumber when no messaging service is configured", async (): Promise<void> => {
|
|
93
|
+
const client = createMockClient();
|
|
94
|
+
const provider = new TwilioSmsProvider({
|
|
95
|
+
accountSid: "ACtest",
|
|
96
|
+
authToken: "token",
|
|
97
|
+
client,
|
|
98
|
+
fromNumber: "+15555550199",
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const result = await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
102
|
+
|
|
103
|
+
assert.isTrue(result.accepted);
|
|
104
|
+
assert.equal(client.calls[0]?.params.from, "+15555550199");
|
|
105
|
+
assert.isUndefined(client.calls[0]?.params.messagingServiceSid);
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
it("prefers constructor sender options over env", async (): Promise<void> => {
|
|
109
|
+
process.env.TWILIO_MESSAGING_SERVICE_SID = "MGenv";
|
|
110
|
+
process.env.TWILIO_FROM_NUMBER = "+15555550000";
|
|
111
|
+
const client = createMockClient();
|
|
112
|
+
const provider = new TwilioSmsProvider({
|
|
113
|
+
accountSid: "ACtest",
|
|
114
|
+
authToken: "token",
|
|
115
|
+
client,
|
|
116
|
+
fromNumber: "+15555550199",
|
|
117
|
+
messagingServiceSid: "MGctor",
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
121
|
+
|
|
122
|
+
assert.equal(client.calls[0]?.params.messagingServiceSid, "MGctor");
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("reads credentials and messaging service from env", async (): Promise<void> => {
|
|
126
|
+
process.env.TWILIO_ACCOUNT_SID = "ACenv";
|
|
127
|
+
process.env.TWILIO_AUTH_TOKEN = "env-token";
|
|
128
|
+
process.env.TWILIO_MESSAGING_SERVICE_SID = "MGenv";
|
|
129
|
+
const client = createMockClient();
|
|
130
|
+
const provider = new TwilioSmsProvider({client});
|
|
131
|
+
|
|
132
|
+
await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
133
|
+
|
|
134
|
+
assert.equal(client.calls[0]?.params.messagingServiceSid, "MGenv");
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
it("returns a config failure when no sender is configured", async (): Promise<void> => {
|
|
138
|
+
const client = createMockClient();
|
|
139
|
+
const provider = new TwilioSmsProvider({
|
|
140
|
+
accountSid: "ACtest",
|
|
141
|
+
authToken: "token",
|
|
142
|
+
client,
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const result = await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
146
|
+
|
|
147
|
+
assert.isFalse(result.accepted);
|
|
148
|
+
assert.equal(result.errorClass, "config");
|
|
149
|
+
assert.equal(result.errorCode, "twilio-missing-sender");
|
|
150
|
+
assert.equal(client.calls.length, 0);
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it("rejects a non-E.164 destination as a permanent result before calling Twilio", async (): Promise<void> => {
|
|
154
|
+
const client = createMockClient();
|
|
155
|
+
const provider = new TwilioSmsProvider({
|
|
156
|
+
accountSid: "ACtest",
|
|
157
|
+
authToken: "token",
|
|
158
|
+
client,
|
|
159
|
+
messagingServiceSid: "MGservice",
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const result = await provider.sendSms({body: "Hello", to: "not-a-phone"});
|
|
163
|
+
|
|
164
|
+
assert.isFalse(result.accepted);
|
|
165
|
+
assert.equal(result.errorClass, "permanent");
|
|
166
|
+
assert.equal(result.errorCode, "twilio-invalid-destination");
|
|
167
|
+
assert.isTrue(result.isPermanentFailure);
|
|
168
|
+
assert.equal(client.calls.length, 0);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it("does not retry invalid destinations through the facade", async (): Promise<void> => {
|
|
172
|
+
const client = createMockClient();
|
|
173
|
+
const provider = new TwilioSmsProvider({
|
|
174
|
+
accountSid: "ACtest",
|
|
175
|
+
authToken: "token",
|
|
176
|
+
client,
|
|
177
|
+
messagingServiceSid: "MGservice",
|
|
178
|
+
});
|
|
179
|
+
const service = new CommsService({sms: provider});
|
|
180
|
+
|
|
181
|
+
const result = await service.sendSms({body: "Hello", to: "not-a-phone"});
|
|
182
|
+
|
|
183
|
+
assert.isFalse(result.accepted);
|
|
184
|
+
assert.equal(result.errorClass, "permanent");
|
|
185
|
+
assert.equal(result.errorCode, "twilio-invalid-destination");
|
|
186
|
+
assert.equal(client.calls.length, 0);
|
|
187
|
+
});
|
|
188
|
+
|
|
189
|
+
it("normalizes a valid destination to E.164 before calling Twilio", async (): Promise<void> => {
|
|
190
|
+
const client = createMockClient();
|
|
191
|
+
const provider = new TwilioSmsProvider({
|
|
192
|
+
accountSid: "ACtest",
|
|
193
|
+
authToken: "token",
|
|
194
|
+
client,
|
|
195
|
+
messagingServiceSid: "MGservice",
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
await provider.sendSms({body: "Hello", to: "+1 (415) 555-2671"});
|
|
199
|
+
|
|
200
|
+
assert.equal(client.calls[0]?.params.to, "+14155552671");
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
it("stores a Twilio console deep link for accepted sends", async (): Promise<void> => {
|
|
204
|
+
const client = createMockClient(async () => ({sid: "SMconsole1"}));
|
|
205
|
+
const provider = new TwilioSmsProvider({
|
|
206
|
+
accountSid: "ACtest",
|
|
207
|
+
authToken: "token",
|
|
208
|
+
client,
|
|
209
|
+
messagingServiceSid: "MGservice",
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const result = await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
213
|
+
|
|
214
|
+
assert.isTrue(result.accepted);
|
|
215
|
+
assert.equal(result.providerMessageId, "SMconsole1");
|
|
216
|
+
assert.include(String(result.metadata?.consoleUrl), "SMconsole1");
|
|
217
|
+
assert.include(String(result.metadata?.consoleUrl), "console.twilio.com");
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("fires onError with the classified result when the send fails", async (): Promise<void> => {
|
|
221
|
+
const client = createMockClient(async () => {
|
|
222
|
+
throw twilioRestError({
|
|
223
|
+
code: 21610,
|
|
224
|
+
message: "Attempt to send to unsubscribed recipient",
|
|
225
|
+
status: 400,
|
|
226
|
+
});
|
|
227
|
+
});
|
|
228
|
+
const provider = new TwilioSmsProvider({
|
|
229
|
+
accountSid: "ACtest",
|
|
230
|
+
authToken: "token",
|
|
231
|
+
client,
|
|
232
|
+
messagingServiceSid: "MGservice",
|
|
233
|
+
});
|
|
234
|
+
const onErrorCalls: Array<{errorClass?: string; errorCode?: string}> = [];
|
|
235
|
+
const service = new CommsService({
|
|
236
|
+
onError: async (_context, result): Promise<void> => {
|
|
237
|
+
onErrorCalls.push(result);
|
|
238
|
+
},
|
|
239
|
+
sms: provider,
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
const result = await service.sendSms({body: "Hello", to: "+14155552671"});
|
|
243
|
+
|
|
244
|
+
assert.isFalse(result.accepted);
|
|
245
|
+
assert.equal(onErrorCalls.length, 1);
|
|
246
|
+
assert.equal(onErrorCalls[0]?.errorClass, "permanent");
|
|
247
|
+
assert.equal(onErrorCalls[0]?.errorCode, "21610");
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("classifies 21610 as permanent and never retries", async (): Promise<void> => {
|
|
251
|
+
let attempts = 0;
|
|
252
|
+
const client = createMockClient(async () => {
|
|
253
|
+
attempts += 1;
|
|
254
|
+
throw twilioRestError({
|
|
255
|
+
code: 21610,
|
|
256
|
+
message: "Attempt to send to unsubscribed recipient",
|
|
257
|
+
status: 400,
|
|
258
|
+
});
|
|
259
|
+
});
|
|
260
|
+
const provider = new TwilioSmsProvider({
|
|
261
|
+
accountSid: "ACtest",
|
|
262
|
+
authToken: "token",
|
|
263
|
+
client,
|
|
264
|
+
messagingServiceSid: "MGservice",
|
|
265
|
+
});
|
|
266
|
+
const service = new CommsService({sms: provider});
|
|
267
|
+
|
|
268
|
+
const result = await service.sendSms({body: "Hello", to: "+14155552671"});
|
|
269
|
+
|
|
270
|
+
assert.isFalse(result.accepted);
|
|
271
|
+
assert.equal(result.errorClass, "permanent");
|
|
272
|
+
assert.equal(result.errorCode, "21610");
|
|
273
|
+
assert.isTrue(result.isPermanentFailure);
|
|
274
|
+
assert.equal(attempts, 1);
|
|
275
|
+
const row = await CommsMessage.findExactlyOne({_id: result.loggedMessageId});
|
|
276
|
+
assert.equal((row.metadata as {twilioError?: {code?: number}})?.twilioError?.code, 21610);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it("classifies 20429 as transient so the facade retries once", async (): Promise<void> => {
|
|
280
|
+
let attempts = 0;
|
|
281
|
+
const client = createMockClient(async () => {
|
|
282
|
+
attempts += 1;
|
|
283
|
+
if (attempts === 1) {
|
|
284
|
+
throw twilioRestError({
|
|
285
|
+
code: 20429,
|
|
286
|
+
message: "Too many requests",
|
|
287
|
+
status: 429,
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return {sid: "SM-retry-ok"};
|
|
291
|
+
});
|
|
292
|
+
const provider = new TwilioSmsProvider({
|
|
293
|
+
accountSid: "ACtest",
|
|
294
|
+
authToken: "token",
|
|
295
|
+
client,
|
|
296
|
+
messagingServiceSid: "MGservice",
|
|
297
|
+
});
|
|
298
|
+
const service = new CommsService({sms: provider});
|
|
299
|
+
|
|
300
|
+
const result = await service.sendSms({body: "Hello", to: "+14155552671"});
|
|
301
|
+
|
|
302
|
+
assert.isTrue(result.accepted);
|
|
303
|
+
assert.equal(attempts, 2);
|
|
304
|
+
});
|
|
305
|
+
|
|
306
|
+
it("classifies 20003 as config and logs an error", async (): Promise<void> => {
|
|
307
|
+
const errorSpy = spyOn(logger, "error").mockImplementation(() => undefined);
|
|
308
|
+
try {
|
|
309
|
+
const client = createMockClient(async () => {
|
|
310
|
+
throw twilioRestError({
|
|
311
|
+
code: 20003,
|
|
312
|
+
message: "Authenticate",
|
|
313
|
+
status: 401,
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
const provider = new TwilioSmsProvider({
|
|
317
|
+
accountSid: "ACtest",
|
|
318
|
+
authToken: "token",
|
|
319
|
+
client,
|
|
320
|
+
messagingServiceSid: "MGservice",
|
|
321
|
+
});
|
|
322
|
+
|
|
323
|
+
const result = await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
324
|
+
|
|
325
|
+
assert.isFalse(result.accepted);
|
|
326
|
+
assert.equal(result.errorClass, "config");
|
|
327
|
+
assert.equal(result.errorCode, "20003");
|
|
328
|
+
assert.isTrue(errorSpy.mock.calls.some((call) => String(call[0]).includes("20003")));
|
|
329
|
+
} finally {
|
|
330
|
+
errorSpy.mockRestore();
|
|
331
|
+
}
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
it("classifies unknown Twilio codes as transient", async (): Promise<void> => {
|
|
335
|
+
const client = createMockClient(async () => {
|
|
336
|
+
throw twilioRestError({
|
|
337
|
+
code: 99999,
|
|
338
|
+
message: "Mystery",
|
|
339
|
+
status: 400,
|
|
340
|
+
});
|
|
341
|
+
});
|
|
342
|
+
const provider = new TwilioSmsProvider({
|
|
343
|
+
accountSid: "ACtest",
|
|
344
|
+
authToken: "token",
|
|
345
|
+
client,
|
|
346
|
+
messagingServiceSid: "MGservice",
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
const result = await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
350
|
+
|
|
351
|
+
assert.isFalse(result.accepted);
|
|
352
|
+
assert.equal(result.errorClass, "transient");
|
|
353
|
+
assert.equal(result.errorCode, "99999");
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
it("applies a default statusCallbackUrl only when unset", async (): Promise<void> => {
|
|
357
|
+
const client = createMockClient();
|
|
358
|
+
const provider = new TwilioSmsProvider({
|
|
359
|
+
accountSid: "ACtest",
|
|
360
|
+
authToken: "token",
|
|
361
|
+
client,
|
|
362
|
+
fromNumber: "+15555550199",
|
|
363
|
+
});
|
|
364
|
+
provider.applyDefaultStatusCallbackUrl("https://api.example.test/comms/webhooks/twilio/status");
|
|
365
|
+
provider.applyDefaultStatusCallbackUrl("https://ignored.example.test/status");
|
|
366
|
+
|
|
367
|
+
await provider.sendSms({body: "Hello", to: "+14155552671"});
|
|
368
|
+
|
|
369
|
+
assert.equal(
|
|
370
|
+
client.calls[0]?.params.statusCallback,
|
|
371
|
+
"https://api.example.test/comms/webhooks/twilio/status"
|
|
372
|
+
);
|
|
373
|
+
});
|
|
374
|
+
});
|