@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,237 @@
|
|
|
1
|
+
import {createRequire} from "node:module";
|
|
2
|
+
import {logger, withApiErrorHandling} from "@terreno/api";
|
|
3
|
+
import {parsePhoneNumberFromString} from "libphonenumber-js";
|
|
4
|
+
|
|
5
|
+
import type {CommsErrorClass, SendResult, SmsMessage, SmsProvider} from "../types";
|
|
6
|
+
|
|
7
|
+
const nodeRequire = createRequire(__filename);
|
|
8
|
+
|
|
9
|
+
const TWILIO_SMS_CONSOLE_BASE = "https://console.twilio.com/us1/monitor/logs/sms";
|
|
10
|
+
|
|
11
|
+
const twilioMessageConsoleUrl = (sid: string): string => `${TWILIO_SMS_CONSOLE_BASE}/${sid}`;
|
|
12
|
+
|
|
13
|
+
const PERMANENT_CODES = new Set([21211, 21214, 21217, 21408, 21610, 30003, 30005, 30006, 30007]);
|
|
14
|
+
const TRANSIENT_CODES = new Set([20429, 30001, 30002]);
|
|
15
|
+
const CONFIG_CODES = new Set([20003, 20404]);
|
|
16
|
+
|
|
17
|
+
export interface TwilioMessageCreateParams {
|
|
18
|
+
body: string;
|
|
19
|
+
from?: string;
|
|
20
|
+
messagingServiceSid?: string;
|
|
21
|
+
statusCallback?: string;
|
|
22
|
+
to: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface TwilioSmsClient {
|
|
26
|
+
messages: {
|
|
27
|
+
create: (params: TwilioMessageCreateParams) => Promise<{sid: string}>;
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type TwilioFactory = (accountSid: string, authToken: string) => TwilioSmsClient;
|
|
32
|
+
|
|
33
|
+
export interface TwilioSmsProviderOptions {
|
|
34
|
+
accountSid?: string;
|
|
35
|
+
authToken?: string;
|
|
36
|
+
/** Injected client for tests. Production wiring loads `twilio`. */
|
|
37
|
+
client?: TwilioSmsClient;
|
|
38
|
+
fromNumber?: string;
|
|
39
|
+
messagingServiceSid?: string;
|
|
40
|
+
statusCallbackUrl?: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
interface TwilioErrorFields {
|
|
44
|
+
code?: number;
|
|
45
|
+
message: string;
|
|
46
|
+
payload: Record<string, unknown>;
|
|
47
|
+
status?: number;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const resolveCredentials = (
|
|
51
|
+
options?: TwilioSmsProviderOptions
|
|
52
|
+
): {accountSid: string; authToken: string} => {
|
|
53
|
+
const accountSid = options?.accountSid ?? process.env.TWILIO_ACCOUNT_SID;
|
|
54
|
+
const authToken = options?.authToken ?? process.env.TWILIO_AUTH_TOKEN;
|
|
55
|
+
if (!accountSid || !authToken) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
"TwilioSmsProvider requires TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN or matching constructor options"
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
return {accountSid, authToken};
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const loadTwilio = (): TwilioFactory => {
|
|
64
|
+
try {
|
|
65
|
+
// Optional peer — keep `twilio` out of core dependencies.
|
|
66
|
+
return nodeRequire("twilio") as TwilioFactory;
|
|
67
|
+
} catch {
|
|
68
|
+
throw new Error(
|
|
69
|
+
"TwilioSmsProvider requires optional peer dependency twilio. " +
|
|
70
|
+
"Install it with: bun add twilio"
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const toE164 = (to: string): string | undefined => {
|
|
76
|
+
const parsed = parsePhoneNumberFromString(to);
|
|
77
|
+
if (!parsed?.isValid()) {
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
return parsed.format("E.164");
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const invalidDestinationResult = (): SendResult => ({
|
|
84
|
+
accepted: false,
|
|
85
|
+
error: "Destination must be a valid E.164 phone number",
|
|
86
|
+
errorClass: "permanent",
|
|
87
|
+
errorCode: "twilio-invalid-destination",
|
|
88
|
+
isPermanentFailure: true,
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const twilioErrorFields = (error: unknown): TwilioErrorFields => {
|
|
92
|
+
if (!error || typeof error !== "object") {
|
|
93
|
+
return {
|
|
94
|
+
message: error instanceof Error ? error.message : "Twilio send failed",
|
|
95
|
+
payload: {error},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
const raw = error as {
|
|
99
|
+
code?: unknown;
|
|
100
|
+
message?: unknown;
|
|
101
|
+
moreInfo?: unknown;
|
|
102
|
+
status?: unknown;
|
|
103
|
+
};
|
|
104
|
+
const code = typeof raw.code === "number" ? raw.code : undefined;
|
|
105
|
+
const status = typeof raw.status === "number" ? raw.status : undefined;
|
|
106
|
+
const message =
|
|
107
|
+
typeof raw.message === "string" && raw.message.length > 0
|
|
108
|
+
? raw.message
|
|
109
|
+
: error instanceof Error
|
|
110
|
+
? error.message
|
|
111
|
+
: "Twilio send failed";
|
|
112
|
+
const payload: Record<string, unknown> = {};
|
|
113
|
+
if (code !== undefined) {
|
|
114
|
+
payload.code = code;
|
|
115
|
+
}
|
|
116
|
+
if (status !== undefined) {
|
|
117
|
+
payload.status = status;
|
|
118
|
+
}
|
|
119
|
+
payload.message = message;
|
|
120
|
+
if (typeof raw.moreInfo === "string") {
|
|
121
|
+
payload.moreInfo = raw.moreInfo;
|
|
122
|
+
}
|
|
123
|
+
return {code, message, payload, status};
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const classifyTwilioFailure = (
|
|
127
|
+
fields: TwilioErrorFields
|
|
128
|
+
): {errorClass: CommsErrorClass; errorCode: string} => {
|
|
129
|
+
if (fields.code !== undefined && PERMANENT_CODES.has(fields.code)) {
|
|
130
|
+
return {errorClass: "permanent", errorCode: String(fields.code)};
|
|
131
|
+
}
|
|
132
|
+
if (fields.code !== undefined && CONFIG_CODES.has(fields.code)) {
|
|
133
|
+
return {errorClass: "config", errorCode: String(fields.code)};
|
|
134
|
+
}
|
|
135
|
+
if (fields.code !== undefined && TRANSIENT_CODES.has(fields.code)) {
|
|
136
|
+
return {errorClass: "transient", errorCode: String(fields.code)};
|
|
137
|
+
}
|
|
138
|
+
if (fields.status === 429 || (fields.status !== undefined && fields.status >= 500)) {
|
|
139
|
+
return {
|
|
140
|
+
errorClass: "transient",
|
|
141
|
+
errorCode: fields.code !== undefined ? String(fields.code) : `twilio-${fields.status}`,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
if (fields.code !== undefined) {
|
|
145
|
+
return {errorClass: "transient", errorCode: String(fields.code)};
|
|
146
|
+
}
|
|
147
|
+
return {errorClass: "transient", errorCode: "twilio-network"};
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const failedResult = (error: unknown): SendResult => {
|
|
151
|
+
const fields = twilioErrorFields(error);
|
|
152
|
+
const {errorClass, errorCode} = classifyTwilioFailure(fields);
|
|
153
|
+
if (errorClass === "config") {
|
|
154
|
+
logger.error(`[comms:twilio] ${errorCode}: ${fields.message}`);
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
accepted: false,
|
|
158
|
+
error: fields.message,
|
|
159
|
+
errorClass,
|
|
160
|
+
errorCode,
|
|
161
|
+
isPermanentFailure: errorClass === "permanent",
|
|
162
|
+
metadata: {twilioError: fields.payload},
|
|
163
|
+
};
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
export class TwilioSmsProvider implements SmsProvider {
|
|
167
|
+
readonly id = "twilio";
|
|
168
|
+
private readonly authToken: string;
|
|
169
|
+
private readonly client: TwilioSmsClient;
|
|
170
|
+
private readonly fromNumber?: string;
|
|
171
|
+
private readonly messagingServiceSid?: string;
|
|
172
|
+
private statusCallbackUrl?: string;
|
|
173
|
+
|
|
174
|
+
constructor(options?: TwilioSmsProviderOptions) {
|
|
175
|
+
const {accountSid, authToken} = resolveCredentials(options);
|
|
176
|
+
this.authToken = authToken;
|
|
177
|
+
this.fromNumber = options?.fromNumber ?? process.env.TWILIO_FROM_NUMBER;
|
|
178
|
+
this.messagingServiceSid =
|
|
179
|
+
options?.messagingServiceSid ?? process.env.TWILIO_MESSAGING_SERVICE_SID;
|
|
180
|
+
this.statusCallbackUrl = options?.statusCallbackUrl;
|
|
181
|
+
|
|
182
|
+
if (options?.client) {
|
|
183
|
+
this.client = options.client;
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
this.client = loadTwilio()(accountSid, authToken);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
getAuthToken = (): string => {
|
|
191
|
+
return this.authToken;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
applyDefaultStatusCallbackUrl = (url: string): void => {
|
|
195
|
+
if (!this.statusCallbackUrl) {
|
|
196
|
+
this.statusCallbackUrl = url;
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
async sendSms(message: SmsMessage): Promise<SendResult> {
|
|
201
|
+
const to = toE164(message.to);
|
|
202
|
+
if (!to) {
|
|
203
|
+
return invalidDestinationResult();
|
|
204
|
+
}
|
|
205
|
+
const params: TwilioMessageCreateParams = {
|
|
206
|
+
body: message.body,
|
|
207
|
+
to,
|
|
208
|
+
...(this.statusCallbackUrl ? {statusCallback: this.statusCallbackUrl} : {}),
|
|
209
|
+
};
|
|
210
|
+
if (this.messagingServiceSid) {
|
|
211
|
+
params.messagingServiceSid = this.messagingServiceSid;
|
|
212
|
+
} else if (this.fromNumber) {
|
|
213
|
+
params.from = this.fromNumber;
|
|
214
|
+
} else {
|
|
215
|
+
return {
|
|
216
|
+
accepted: false,
|
|
217
|
+
error: "TwilioSmsProvider requires TWILIO_MESSAGING_SERVICE_SID or TWILIO_FROM_NUMBER",
|
|
218
|
+
errorClass: "config",
|
|
219
|
+
errorCode: "twilio-missing-sender",
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
const created = await withApiErrorHandling(() => this.client.messages.create(params), {
|
|
225
|
+
apiName: "twilio",
|
|
226
|
+
operation: "sendSms",
|
|
227
|
+
});
|
|
228
|
+
return {
|
|
229
|
+
accepted: true,
|
|
230
|
+
metadata: {consoleUrl: twilioMessageConsoleUrl(created.sid)},
|
|
231
|
+
providerMessageId: created.sid,
|
|
232
|
+
};
|
|
233
|
+
} catch (error: unknown) {
|
|
234
|
+
return failedResult(error);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import {describe, it} from "bun:test";
|
|
2
|
+
import {assert} from "chai";
|
|
3
|
+
import {evaluateRetryBlock} from "../commsRetry";
|
|
4
|
+
import {CommsService} from "../commsService";
|
|
5
|
+
import {CommsMessage} from "../models/commsMessage";
|
|
6
|
+
import {type TwilioVerifyClient, TwilioVerifyProvider} from "./twilioVerify";
|
|
7
|
+
|
|
8
|
+
interface VerifyStartCall {
|
|
9
|
+
channel: string;
|
|
10
|
+
to: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
interface VerifyCheckCall {
|
|
14
|
+
code: string;
|
|
15
|
+
to: string;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
const createMockClient = ({
|
|
19
|
+
checkStatus,
|
|
20
|
+
startError,
|
|
21
|
+
startSid = "VE123",
|
|
22
|
+
startStatus = "pending",
|
|
23
|
+
}: {
|
|
24
|
+
checkStatus?: string;
|
|
25
|
+
startError?: Error;
|
|
26
|
+
startSid?: string;
|
|
27
|
+
startStatus?: string;
|
|
28
|
+
} = {}): TwilioVerifyClient & {checkCalls: VerifyCheckCall[]; startCalls: VerifyStartCall[]} => {
|
|
29
|
+
const checkCalls: VerifyCheckCall[] = [];
|
|
30
|
+
const startCalls: VerifyStartCall[] = [];
|
|
31
|
+
return {
|
|
32
|
+
checkCalls,
|
|
33
|
+
startCalls,
|
|
34
|
+
verify: {
|
|
35
|
+
v2: {
|
|
36
|
+
services: () => ({
|
|
37
|
+
verificationChecks: {
|
|
38
|
+
create: async (params: VerifyCheckCall): Promise<{status: string}> => {
|
|
39
|
+
checkCalls.push(params);
|
|
40
|
+
return {status: checkStatus ?? "approved"};
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
verifications: {
|
|
44
|
+
create: async (params: VerifyStartCall): Promise<{sid: string; status: string}> => {
|
|
45
|
+
startCalls.push(params);
|
|
46
|
+
if (startError) {
|
|
47
|
+
throw startError;
|
|
48
|
+
}
|
|
49
|
+
return {sid: startSid, status: startStatus};
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
}),
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const providerOptions = (
|
|
59
|
+
client: TwilioVerifyClient
|
|
60
|
+
): ConstructorParameters<typeof TwilioVerifyProvider>[0] => ({
|
|
61
|
+
accountSid: "ACtest",
|
|
62
|
+
authToken: "token",
|
|
63
|
+
client,
|
|
64
|
+
verifyServiceSid: "VAservice",
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
describe("TwilioVerifyProvider", () => {
|
|
68
|
+
it("fails fast when verify service SID is missing", (): void => {
|
|
69
|
+
Reflect.deleteProperty(process.env, "TWILIO_VERIFY_SERVICE_SID");
|
|
70
|
+
assert.throws(
|
|
71
|
+
(): TwilioVerifyProvider =>
|
|
72
|
+
new TwilioVerifyProvider({
|
|
73
|
+
accountSid: "ACtest",
|
|
74
|
+
authToken: "token",
|
|
75
|
+
client: createMockClient(),
|
|
76
|
+
}),
|
|
77
|
+
/TWILIO_VERIFY_SERVICE_SID/
|
|
78
|
+
);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it("constructs without an injected client when the twilio peer is installed", (): void => {
|
|
82
|
+
const provider = new TwilioVerifyProvider({
|
|
83
|
+
accountSid: "ACtest",
|
|
84
|
+
authToken: "token",
|
|
85
|
+
verifyServiceSid: "VAservice",
|
|
86
|
+
});
|
|
87
|
+
assert.equal(provider.id, "twilio-verify");
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it("starts SMS and email verifications on the configured service", async (): Promise<void> => {
|
|
91
|
+
const client = createMockClient({startSid: "VEsms"});
|
|
92
|
+
const provider = new TwilioVerifyProvider(providerOptions(client));
|
|
93
|
+
|
|
94
|
+
const sms = await provider.startVerification({channel: "sms", to: "+14155552671"});
|
|
95
|
+
const email = await provider.startVerification({
|
|
96
|
+
channel: "email",
|
|
97
|
+
to: "person@example.com",
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
assert.isTrue(sms.accepted);
|
|
101
|
+
assert.equal(sms.providerMessageId, "VEsms");
|
|
102
|
+
assert.isTrue(email.accepted);
|
|
103
|
+
assert.deepEqual(
|
|
104
|
+
client.startCalls.map((call) => call.channel),
|
|
105
|
+
["sms", "email"]
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("returns valid true only for approved checks", async (): Promise<void> => {
|
|
110
|
+
const approved = createMockClient({checkStatus: "approved"});
|
|
111
|
+
const pending = createMockClient({checkStatus: "pending"});
|
|
112
|
+
const expired = createMockClient({checkStatus: "expired"});
|
|
113
|
+
const maxAttempts = createMockClient({checkStatus: "max_attempts_reached"});
|
|
114
|
+
|
|
115
|
+
const approvedResult = await new TwilioVerifyProvider(
|
|
116
|
+
providerOptions(approved)
|
|
117
|
+
).checkVerification({
|
|
118
|
+
code: "123456",
|
|
119
|
+
to: "+14155552671",
|
|
120
|
+
});
|
|
121
|
+
const pendingResult = await new TwilioVerifyProvider(
|
|
122
|
+
providerOptions(pending)
|
|
123
|
+
).checkVerification({
|
|
124
|
+
code: "123456",
|
|
125
|
+
to: "+14155552671",
|
|
126
|
+
});
|
|
127
|
+
const expiredResult = await new TwilioVerifyProvider(
|
|
128
|
+
providerOptions(expired)
|
|
129
|
+
).checkVerification({
|
|
130
|
+
code: "123456",
|
|
131
|
+
to: "+14155552671",
|
|
132
|
+
});
|
|
133
|
+
const maxResult = await new TwilioVerifyProvider(
|
|
134
|
+
providerOptions(maxAttempts)
|
|
135
|
+
).checkVerification({
|
|
136
|
+
code: "123456",
|
|
137
|
+
to: "+14155552671",
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
assert.isTrue(approvedResult.valid);
|
|
141
|
+
assert.isUndefined(approvedResult.error);
|
|
142
|
+
assert.isFalse(pendingResult.valid);
|
|
143
|
+
assert.equal(pendingResult.error, "pending");
|
|
144
|
+
assert.isFalse(expiredResult.valid);
|
|
145
|
+
assert.equal(expiredResult.error, "expired");
|
|
146
|
+
assert.isFalse(maxResult.valid);
|
|
147
|
+
assert.equal(maxResult.error, "max-attempts");
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it("redacts destination and omits codes from verification log rows", async (): Promise<void> => {
|
|
151
|
+
const client = createMockClient({startSid: "VElog"});
|
|
152
|
+
const provider = new TwilioVerifyProvider(providerOptions(client));
|
|
153
|
+
const service = new CommsService({verification: provider});
|
|
154
|
+
|
|
155
|
+
const result = await service.startVerification({
|
|
156
|
+
channel: "sms",
|
|
157
|
+
to: "+14155552671",
|
|
158
|
+
});
|
|
159
|
+
await service.checkVerification({code: "999111", to: "+14155552671"});
|
|
160
|
+
|
|
161
|
+
const startRow = await CommsMessage.findExactlyOne({_id: result.loggedMessageId});
|
|
162
|
+
const checkRow = await CommsMessage.findExactlyOne({
|
|
163
|
+
channel: "verification",
|
|
164
|
+
providerMessageId: {$exists: false},
|
|
165
|
+
status: "sent",
|
|
166
|
+
});
|
|
167
|
+
const serialized = JSON.stringify([startRow.toJSON(), checkRow.toJSON()]);
|
|
168
|
+
assert.equal(startRow.to, "[redacted]");
|
|
169
|
+
assert.equal(startRow.channel, "verification");
|
|
170
|
+
assert.equal((startRow.metadata as {verificationChannel?: string}).verificationChannel, "sms");
|
|
171
|
+
assert.include(String(startRow.metadata?.consoleUrl), "VAservice");
|
|
172
|
+
assert.notInclude(serialized, "999111");
|
|
173
|
+
assert.notInclude(serialized, "+14155552671");
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it("classifies start failures and fires onError without retrying verification", async (): Promise<void> => {
|
|
177
|
+
const startError = new Error("Authenticate") as Error & {code: number; status: number};
|
|
178
|
+
startError.code = 20003;
|
|
179
|
+
startError.status = 401;
|
|
180
|
+
const client = createMockClient({startError});
|
|
181
|
+
const provider = new TwilioVerifyProvider(providerOptions(client));
|
|
182
|
+
const onErrorCalls: Array<{errorClass?: string; errorCode?: string}> = [];
|
|
183
|
+
const service = new CommsService({
|
|
184
|
+
onError: async (_context, sendResult): Promise<void> => {
|
|
185
|
+
onErrorCalls.push(sendResult);
|
|
186
|
+
},
|
|
187
|
+
verification: provider,
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const result = await service.startVerification({
|
|
191
|
+
channel: "sms",
|
|
192
|
+
to: "+14155552671",
|
|
193
|
+
});
|
|
194
|
+
const row = await CommsMessage.findExactlyOne({_id: result.loggedMessageId});
|
|
195
|
+
const block = evaluateRetryBlock({
|
|
196
|
+
isChannelConfigured: () => true,
|
|
197
|
+
message: row,
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
assert.isFalse(result.accepted);
|
|
201
|
+
assert.equal(result.errorClass, "config");
|
|
202
|
+
assert.equal(result.errorCode, "20003");
|
|
203
|
+
assert.equal(onErrorCalls.length, 1);
|
|
204
|
+
assert.equal(onErrorCalls[0]?.errorClass, "config");
|
|
205
|
+
assert.equal(block?.code, "comms-retry-not-retryable");
|
|
206
|
+
});
|
|
207
|
+
});
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import {createRequire} from "node:module";
|
|
2
|
+
import {logger, withApiErrorHandling} from "@terreno/api";
|
|
3
|
+
|
|
4
|
+
import type {
|
|
5
|
+
CheckVerificationOptions,
|
|
6
|
+
CommsErrorClass,
|
|
7
|
+
SendResult,
|
|
8
|
+
StartVerificationOptions,
|
|
9
|
+
VerificationProvider,
|
|
10
|
+
VerificationResult,
|
|
11
|
+
} from "../types";
|
|
12
|
+
|
|
13
|
+
const PERMANENT_CODES = new Set([60200, 60202, 60203]);
|
|
14
|
+
const TRANSIENT_CODES = new Set([20429]);
|
|
15
|
+
const CONFIG_CODES = new Set([20003, 20404]);
|
|
16
|
+
const TWILIO_VERIFY_CONSOLE_BASE = "https://console.twilio.com/us1/develop/verify/services";
|
|
17
|
+
|
|
18
|
+
const nodeRequire = createRequire(__filename);
|
|
19
|
+
|
|
20
|
+
export interface TwilioVerifyStartParams {
|
|
21
|
+
channel: "email" | "sms";
|
|
22
|
+
to: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface TwilioVerifyCheckParams {
|
|
26
|
+
code: string;
|
|
27
|
+
to: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface TwilioVerifyService {
|
|
31
|
+
verificationChecks: {
|
|
32
|
+
create: (params: TwilioVerifyCheckParams) => Promise<{status: string}>;
|
|
33
|
+
};
|
|
34
|
+
verifications: {
|
|
35
|
+
create: (params: TwilioVerifyStartParams) => Promise<{sid: string; status: string}>;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface TwilioVerifyClient {
|
|
40
|
+
verify: {
|
|
41
|
+
v2: {
|
|
42
|
+
services: (serviceSid: string) => TwilioVerifyService;
|
|
43
|
+
};
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
type TwilioFactory = (accountSid: string, authToken: string) => TwilioVerifyClient;
|
|
48
|
+
|
|
49
|
+
export interface TwilioVerifyProviderOptions {
|
|
50
|
+
accountSid?: string;
|
|
51
|
+
authToken?: string;
|
|
52
|
+
/** Injected client for tests. Production wiring loads `twilio`. */
|
|
53
|
+
client?: TwilioVerifyClient;
|
|
54
|
+
verifyServiceSid?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const resolveCredentials = (
|
|
58
|
+
options?: TwilioVerifyProviderOptions
|
|
59
|
+
): {accountSid: string; authToken: string; verifyServiceSid: string} => {
|
|
60
|
+
const accountSid = options?.accountSid ?? process.env.TWILIO_ACCOUNT_SID;
|
|
61
|
+
const authToken = options?.authToken ?? process.env.TWILIO_AUTH_TOKEN;
|
|
62
|
+
const verifyServiceSid = options?.verifyServiceSid ?? process.env.TWILIO_VERIFY_SERVICE_SID;
|
|
63
|
+
if (!accountSid || !authToken) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
"TwilioVerifyProvider requires TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN or matching constructor options"
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
if (!verifyServiceSid) {
|
|
69
|
+
throw new Error(
|
|
70
|
+
"TwilioVerifyProvider requires TWILIO_VERIFY_SERVICE_SID or a verifyServiceSid constructor option"
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
return {accountSid, authToken, verifyServiceSid};
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const loadTwilio = (): TwilioFactory => {
|
|
77
|
+
try {
|
|
78
|
+
// Optional peer — keep `twilio` out of core dependencies.
|
|
79
|
+
return nodeRequire("twilio") as TwilioFactory;
|
|
80
|
+
} catch {
|
|
81
|
+
throw new Error(
|
|
82
|
+
"TwilioVerifyProvider requires optional peer dependency twilio. " +
|
|
83
|
+
"Install it with: bun add twilio"
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
const checkErrorForStatus = (status: string): string | undefined => {
|
|
89
|
+
if (status === "approved") {
|
|
90
|
+
return undefined;
|
|
91
|
+
}
|
|
92
|
+
if (status === "max_attempts_reached") {
|
|
93
|
+
return "max-attempts";
|
|
94
|
+
}
|
|
95
|
+
return status;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
interface TwilioErrorFields {
|
|
99
|
+
code?: number;
|
|
100
|
+
message: string;
|
|
101
|
+
payload: Record<string, unknown>;
|
|
102
|
+
status?: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const twilioErrorFields = (error: unknown): TwilioErrorFields => {
|
|
106
|
+
if (!error || typeof error !== "object") {
|
|
107
|
+
return {
|
|
108
|
+
message: error instanceof Error ? error.message : "Twilio Verify request failed",
|
|
109
|
+
payload: {error},
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
const raw = error as {code?: unknown; message?: unknown; moreInfo?: unknown; status?: unknown};
|
|
113
|
+
const code = typeof raw.code === "number" ? raw.code : undefined;
|
|
114
|
+
const status = typeof raw.status === "number" ? raw.status : undefined;
|
|
115
|
+
const message =
|
|
116
|
+
typeof raw.message === "string" && raw.message.length > 0
|
|
117
|
+
? raw.message
|
|
118
|
+
: error instanceof Error
|
|
119
|
+
? error.message
|
|
120
|
+
: "Twilio Verify request failed";
|
|
121
|
+
const payload: Record<string, unknown> = {message};
|
|
122
|
+
if (code !== undefined) {
|
|
123
|
+
payload.code = code;
|
|
124
|
+
}
|
|
125
|
+
if (status !== undefined) {
|
|
126
|
+
payload.status = status;
|
|
127
|
+
}
|
|
128
|
+
if (typeof raw.moreInfo === "string") {
|
|
129
|
+
payload.moreInfo = raw.moreInfo;
|
|
130
|
+
}
|
|
131
|
+
return {code, message, payload, status};
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const classifyTwilioVerifyFailure = (
|
|
135
|
+
fields: TwilioErrorFields
|
|
136
|
+
): {errorClass: CommsErrorClass; errorCode: string} => {
|
|
137
|
+
if (fields.code !== undefined && PERMANENT_CODES.has(fields.code)) {
|
|
138
|
+
return {errorClass: "permanent", errorCode: String(fields.code)};
|
|
139
|
+
}
|
|
140
|
+
if (fields.code !== undefined && CONFIG_CODES.has(fields.code)) {
|
|
141
|
+
return {errorClass: "config", errorCode: String(fields.code)};
|
|
142
|
+
}
|
|
143
|
+
if (fields.code !== undefined && TRANSIENT_CODES.has(fields.code)) {
|
|
144
|
+
return {errorClass: "transient", errorCode: String(fields.code)};
|
|
145
|
+
}
|
|
146
|
+
if (fields.status === 429 || (fields.status !== undefined && fields.status >= 500)) {
|
|
147
|
+
return {
|
|
148
|
+
errorClass: "transient",
|
|
149
|
+
errorCode: fields.code !== undefined ? String(fields.code) : `twilio-${fields.status}`,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
if (fields.code !== undefined) {
|
|
153
|
+
return {errorClass: "transient", errorCode: String(fields.code)};
|
|
154
|
+
}
|
|
155
|
+
return {errorClass: "transient", errorCode: "twilio-network"};
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
const failedStartResult = (error: unknown): SendResult => {
|
|
159
|
+
const fields = twilioErrorFields(error);
|
|
160
|
+
const {errorClass, errorCode} = classifyTwilioVerifyFailure(fields);
|
|
161
|
+
if (errorClass === "config") {
|
|
162
|
+
logger.error(`[comms:twilio-verify] ${errorCode}: ${fields.message}`);
|
|
163
|
+
}
|
|
164
|
+
return {
|
|
165
|
+
accepted: false,
|
|
166
|
+
error: fields.message,
|
|
167
|
+
errorClass,
|
|
168
|
+
errorCode,
|
|
169
|
+
isPermanentFailure: errorClass === "permanent",
|
|
170
|
+
metadata: {twilioError: fields.payload},
|
|
171
|
+
};
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
export class TwilioVerifyProvider implements VerificationProvider {
|
|
175
|
+
readonly id = "twilio-verify";
|
|
176
|
+
private readonly client: TwilioVerifyClient;
|
|
177
|
+
private readonly verifyServiceSid: string;
|
|
178
|
+
|
|
179
|
+
constructor(options?: TwilioVerifyProviderOptions) {
|
|
180
|
+
const {accountSid, authToken, verifyServiceSid} = resolveCredentials(options);
|
|
181
|
+
this.verifyServiceSid = verifyServiceSid;
|
|
182
|
+
if (options?.client) {
|
|
183
|
+
this.client = options.client;
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
this.client = loadTwilio()(accountSid, authToken);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async startVerification(options: StartVerificationOptions): Promise<SendResult> {
|
|
190
|
+
try {
|
|
191
|
+
const created = await withApiErrorHandling(
|
|
192
|
+
() =>
|
|
193
|
+
this.client.verify.v2
|
|
194
|
+
.services(this.verifyServiceSid)
|
|
195
|
+
.verifications.create({channel: options.channel, to: options.to}),
|
|
196
|
+
{apiName: "twilio-verify", operation: "startVerification"}
|
|
197
|
+
);
|
|
198
|
+
return {
|
|
199
|
+
accepted: true,
|
|
200
|
+
metadata: {consoleUrl: `${TWILIO_VERIFY_CONSOLE_BASE}/${this.verifyServiceSid}`},
|
|
201
|
+
providerMessageId: created.sid,
|
|
202
|
+
};
|
|
203
|
+
} catch (error: unknown) {
|
|
204
|
+
return failedStartResult(error);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async checkVerification(options: CheckVerificationOptions): Promise<VerificationResult> {
|
|
209
|
+
try {
|
|
210
|
+
const checked = await withApiErrorHandling(
|
|
211
|
+
() =>
|
|
212
|
+
this.client.verify.v2
|
|
213
|
+
.services(this.verifyServiceSid)
|
|
214
|
+
.verificationChecks.create({code: options.code, to: options.to}),
|
|
215
|
+
{apiName: "twilio-verify", operation: "checkVerification"}
|
|
216
|
+
);
|
|
217
|
+
const error = checkErrorForStatus(checked.status);
|
|
218
|
+
if (error === undefined) {
|
|
219
|
+
return {valid: true};
|
|
220
|
+
}
|
|
221
|
+
return {error, valid: false};
|
|
222
|
+
} catch (error: unknown) {
|
|
223
|
+
const fields = twilioErrorFields(error);
|
|
224
|
+
return {error: fields.message, valid: false};
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
package/src/commsApp.test.ts
CHANGED
|
@@ -55,6 +55,13 @@ describe("CommsApp", () => {
|
|
|
55
55
|
assert.strictEqual(getCommsService(), plugin.service);
|
|
56
56
|
});
|
|
57
57
|
|
|
58
|
+
it("labels the admin sidebar screen as Comms Dashboard", (): void => {
|
|
59
|
+
const contribution = new CommsApp().adminContribution();
|
|
60
|
+
|
|
61
|
+
assert.equal(contribution.customScreens?.[0]?.displayName, "Comms Dashboard");
|
|
62
|
+
assert.equal(contribution.customScreens?.[0]?.name, "comms");
|
|
63
|
+
});
|
|
64
|
+
|
|
58
65
|
it("upserts push tokens and isolates list and delete operations by owner", async (): Promise<void> => {
|
|
59
66
|
const app = buildApp();
|
|
60
67
|
const owner = await authAsUser(app, "notAdmin");
|
|
@@ -433,6 +440,12 @@ describe("CommsApp", () => {
|
|
|
433
440
|
assert.property(response.body.paths["/comms/pushTokens"], "post");
|
|
434
441
|
assert.property(response.body.paths, "/comms/messages");
|
|
435
442
|
assert.property(response.body.paths["/comms/messages"], "get");
|
|
443
|
+
assert.property(response.body.paths, "/comms/messages/{id}");
|
|
444
|
+
assert.property(response.body.paths["/comms/messages/{id}"], "get");
|
|
445
|
+
assert.property(response.body.paths, "/comms/messages/{id}/retry");
|
|
446
|
+
assert.property(response.body.paths["/comms/messages/{id}/retry"], "post");
|
|
447
|
+
assert.property(response.body.paths, "/comms/messages/retryMany");
|
|
448
|
+
assert.property(response.body.paths, "/comms/stats");
|
|
436
449
|
assert.notProperty(response.body.paths, "/comms/pushTokens/");
|
|
437
450
|
|
|
438
451
|
// A shared tag keeps generated SDK mutations invalidating the by-id read.
|