@sdflc/backend-helpers 1.0.138 → 1.0.140

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.
Files changed (58) hide show
  1. package/README.md +176 -20
  2. package/build/BaseGateway.js +18 -2
  3. package/build/EmergencyAlerter.d.ts +140 -0
  4. package/build/EmergencyAlerter.js +465 -0
  5. package/build/esm/BaseGateway.js +18 -2
  6. package/build/esm/EmergencyAlerter.d.ts +140 -0
  7. package/build/esm/EmergencyAlerter.js +454 -0
  8. package/build/esm/gateways/BaseExternalApiGateway.d.ts +94 -0
  9. package/build/esm/gateways/BaseExternalApiGateway.js +319 -0
  10. package/build/esm/gateways/DiscordWebhookGw.d.ts +50 -0
  11. package/build/esm/gateways/DiscordWebhookGw.js +70 -0
  12. package/build/esm/gateways/HttpWebhookGw.d.ts +43 -0
  13. package/build/esm/gateways/HttpWebhookGw.js +131 -0
  14. package/build/esm/gateways/SendGridGw.d.ts +41 -0
  15. package/build/esm/gateways/SendGridGw.js +116 -0
  16. package/build/esm/gateways/SlackWebhookGw.d.ts +23 -0
  17. package/build/esm/gateways/SlackWebhookGw.js +59 -0
  18. package/build/esm/gateways/TelegramGw.d.ts +45 -0
  19. package/build/esm/gateways/TelegramGw.js +110 -0
  20. package/build/esm/gateways/TwilioGw.d.ts +33 -0
  21. package/build/esm/gateways/TwilioGw.js +107 -0
  22. package/build/esm/gateways/externalUrl.d.ts +16 -0
  23. package/build/esm/gateways/externalUrl.js +116 -0
  24. package/build/esm/gateways/guardedFetch.d.ts +15 -0
  25. package/build/esm/gateways/guardedFetch.js +133 -0
  26. package/build/esm/gateways/index.d.ts +9 -0
  27. package/build/esm/gateways/index.js +9 -0
  28. package/build/esm/index.d.ts +2 -1
  29. package/build/esm/index.js +2 -1
  30. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  31. package/build/gateways/BaseExternalApiGateway.d.ts +94 -0
  32. package/build/gateways/BaseExternalApiGateway.js +326 -0
  33. package/build/gateways/DiscordWebhookGw.d.ts +50 -0
  34. package/build/gateways/DiscordWebhookGw.js +73 -0
  35. package/build/gateways/HttpWebhookGw.d.ts +43 -0
  36. package/build/gateways/HttpWebhookGw.js +135 -0
  37. package/build/gateways/SendGridGw.d.ts +41 -0
  38. package/build/gateways/SendGridGw.js +119 -0
  39. package/build/gateways/SlackWebhookGw.d.ts +23 -0
  40. package/build/gateways/SlackWebhookGw.js +62 -0
  41. package/build/gateways/TelegramGw.d.ts +45 -0
  42. package/build/gateways/TelegramGw.js +115 -0
  43. package/build/gateways/TwilioGw.d.ts +33 -0
  44. package/build/gateways/TwilioGw.js +110 -0
  45. package/build/gateways/externalUrl.d.ts +16 -0
  46. package/build/gateways/externalUrl.js +121 -0
  47. package/build/gateways/guardedFetch.d.ts +15 -0
  48. package/build/gateways/guardedFetch.js +141 -0
  49. package/build/gateways/index.d.ts +9 -0
  50. package/build/gateways/index.js +25 -0
  51. package/build/index.d.ts +2 -1
  52. package/build/index.js +2 -1
  53. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  54. package/package.json +2 -1
  55. package/build/BaseExternalApiGateway.d.ts +0 -16
  56. package/build/BaseExternalApiGateway.js +0 -54
  57. package/build/esm/BaseExternalApiGateway.d.ts +0 -16
  58. package/build/esm/BaseExternalApiGateway.js +0 -48
@@ -0,0 +1,116 @@
1
+ // ./src/gateways/SendGridGw.ts
2
+ //
3
+ // Sends email through SendGrid's v3 Mail Send API (https://api.sendgrid.com/v3/mail/send) — plain text, HTML, or a
4
+ // dynamic template. No SDK: one REST call.
5
+ //
6
+ // const sendGrid = new SendGridGw().configure({ apiKey, fromEmail: 'alerts@brand.com', fromName: 'Brand' });
7
+ // const result = await sendGrid.sendEmail({ to: 'ops@brand.com', subject: 'Hello', text: 'Hi' });
8
+ //
9
+ // ⚠ The From address must be on a domain authenticated in that SendGrid account, or SendGrid refuses the mail.
10
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
11
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
12
+ const SENDGRID_BASE_URL = 'https://api.sendgrid.com';
13
+ const addressOf = (one) => typeof one === 'string'
14
+ ? { email: one.trim() }
15
+ : { email: String(one?.email ?? '').trim(), ...(one?.name ? { name: one.name } : {}) };
16
+ const addressesOf = (many) => (Array.isArray(many) ? many : many ? [many] : []).map(addressOf);
17
+ /** A plausible email address (one @, something on each side, no spaces). */
18
+ const isEmail = (email) => /^[^\s@]+@[^\s@]+$/.test(email);
19
+ class SendGridGw extends BaseExternalApiGateway {
20
+ constructor(props) {
21
+ super({ baseUrl: SENDGRID_BASE_URL, ...(props ?? {}) });
22
+ }
23
+ validateSettings(settings) {
24
+ const problems = [];
25
+ if (!String(settings.apiKey ?? '').trim()) {
26
+ problems.push('the API key is missing');
27
+ }
28
+ if (settings.fromEmail !== undefined && settings.fromEmail !== '' && !String(settings.fromEmail).includes('@')) {
29
+ problems.push('the From address is not an email address');
30
+ }
31
+ return problems;
32
+ }
33
+ secretValues() {
34
+ return [String(this.settings.apiKey ?? '')];
35
+ }
36
+ /** ⚠ Not after a TIMEOUT: SendGrid may well have accepted the mail, and a retry sends it twice. */
37
+ shouldRetry(result) {
38
+ return result.getCode() !== OP_RESULT_CODES.TIMEOUT && super.shouldRetry(result);
39
+ }
40
+ errorMessageOf(reply) {
41
+ const errors = Array.isArray(reply.body?.errors) ? reply.body.errors : [];
42
+ return errors.length
43
+ ? errors
44
+ .map((e) => String(e?.message ?? ''))
45
+ .filter(Boolean)
46
+ .join('; ')
47
+ : super.errorMessageOf(reply);
48
+ }
49
+ /** Sends one email. OK with `{ messageId }` (SendGrid's `x-message-id`). Never throws. */
50
+ async sendEmail(email) {
51
+ if (!this.isConfigured()) {
52
+ return this.notConfigured();
53
+ }
54
+ const to = addressesOf(email?.to);
55
+ const cc = addressesOf(email?.cc);
56
+ const bcc = addressesOf(email?.bcc);
57
+ const from = email?.from
58
+ ? addressOf(email.from)
59
+ : this.settings.fromEmail
60
+ ? addressOf({ email: this.settings.fromEmail, name: this.settings.fromName })
61
+ : null;
62
+ const problems = [];
63
+ if (to.length === 0) {
64
+ problems.push('there is no recipient');
65
+ }
66
+ // ⚠ Refused, never dropped: silently leaving one address out sends a mail its sender believes reached them.
67
+ const malformed = [...to, ...cc, ...bcc].filter((one) => !isEmail(one.email));
68
+ if (malformed.length) {
69
+ problems.push(`${malformed.length} recipient address(es) are not email addresses`);
70
+ }
71
+ if (!from || !isEmail(from.email)) {
72
+ problems.push('there is no From address (configure fromEmail or pass from)');
73
+ }
74
+ if (!email?.templateId && !String(email?.subject ?? '').trim()) {
75
+ problems.push('there is no subject');
76
+ }
77
+ if (!email?.templateId && !email?.text && !email?.html) {
78
+ problems.push('there is no content (text, html or a template)');
79
+ }
80
+ if (problems.length) {
81
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `The email cannot be sent: ${problems.join('; ')}`);
82
+ }
83
+ const replyTo = email.replyTo ? addressOf(email.replyTo) : null;
84
+ const content = [
85
+ ...(email.text ? [{ type: 'text/plain', value: email.text }] : []),
86
+ ...(email.html ? [{ type: 'text/html', value: email.html }] : []),
87
+ ];
88
+ const result = await this.requestWithRetries({
89
+ url: `${this.baseUrl}/v3/mail/send`,
90
+ headers: { Authorization: `Bearer ${this.settings.apiKey}` },
91
+ json: {
92
+ personalizations: [
93
+ {
94
+ to,
95
+ ...(cc.length ? { cc } : {}),
96
+ ...(bcc.length ? { bcc } : {}),
97
+ ...(email.dynamicTemplateData ? { dynamic_template_data: email.dynamicTemplateData } : {}),
98
+ },
99
+ ],
100
+ from,
101
+ ...(replyTo ? { reply_to: replyTo } : {}),
102
+ ...(email.subject ? { subject: email.subject } : {}),
103
+ ...(content.length ? { content } : {}),
104
+ ...(email.templateId ? { template_id: email.templateId } : {}),
105
+ ...(email.categories?.length ? { categories: email.categories } : {}),
106
+ ...(email.customArgs ? { custom_args: email.customArgs } : {}),
107
+ },
108
+ });
109
+ if (result.didFail()) {
110
+ return result;
111
+ }
112
+ const reply = result.getDataFirst();
113
+ return OpResult.ok([{ messageId: reply?.headers?.['x-message-id'] ?? null }]);
114
+ }
115
+ }
116
+ export { SendGridGw };
@@ -0,0 +1,23 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
4
+ export interface SlackWebhookSettings {
5
+ /** `https://hooks.slack.com/services/…` */
6
+ webhookUrl: string;
7
+ }
8
+ export interface SlackMessage {
9
+ /** The message (and the notification text when `blocks` are given). */
10
+ text: string;
11
+ /** Block Kit blocks (https://api.slack.com/block-kit). */
12
+ blocks?: unknown[];
13
+ attachments?: unknown[];
14
+ }
15
+ declare class SlackWebhookGw extends BaseExternalApiGateway<SlackWebhookSettings> {
16
+ constructor(props?: BaseExternalApiGatewayPropsInterface<SlackWebhookSettings>);
17
+ protected validateSettings(settings: Partial<SlackWebhookSettings>): string[];
18
+ protected secretValues(): string[];
19
+ protected shouldRetry(result: OpResult): boolean;
20
+ /** Posts one message. OK with `{ messageId: null }` (Slack's webhook answers none). Never throws. */
21
+ postMessage(message: SlackMessage): Promise<OpResult>;
22
+ }
23
+ export { SlackWebhookGw };
@@ -0,0 +1,59 @@
1
+ // ./src/gateways/SlackWebhookGw.ts
2
+ //
3
+ // Posts a message to a Slack channel through an incoming webhook (https://api.slack.com/messaging/webhooks).
4
+ //
5
+ // const slack = new SlackWebhookGw().configure({ webhookUrl });
6
+ // const result = await slack.postMessage({ text: 'Hello' });
7
+ //
8
+ // ⚠ The webhook URL IS the credential — anyone holding it can post to the channel. It is scrubbed out of every error.
9
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
10
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
11
+ /** Refusals that will not change on a retry. */
12
+ const PERMANENT_ERRORS = [
13
+ 'invalid_payload',
14
+ 'channel_not_found',
15
+ 'channel_is_archived',
16
+ 'action_prohibited',
17
+ 'posting_to_general_channel_denied',
18
+ 'no_service',
19
+ 'invalid_token',
20
+ ];
21
+ class SlackWebhookGw extends BaseExternalApiGateway {
22
+ constructor(props) {
23
+ super(props);
24
+ }
25
+ validateSettings(settings) {
26
+ return String(settings.webhookUrl ?? '')
27
+ .trim()
28
+ .startsWith('https://hooks.slack.com/')
29
+ ? []
30
+ : ['the webhook URL is missing or not a Slack one (https://hooks.slack.com/…)'];
31
+ }
32
+ secretValues() {
33
+ return [String(this.settings.webhookUrl ?? '').trim()];
34
+ }
35
+ shouldRetry(result) {
36
+ const said = String(result.getDataFirst()?.body ?? '').toLowerCase();
37
+ return !PERMANENT_ERRORS.some((one) => said.includes(one)) && super.shouldRetry(result);
38
+ }
39
+ /** Posts one message. OK with `{ messageId: null }` (Slack's webhook answers none). Never throws. */
40
+ async postMessage(message) {
41
+ if (!this.isConfigured()) {
42
+ return this.notConfigured();
43
+ }
44
+ if (!String(message?.text ?? '').trim()) {
45
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The message is empty');
46
+ }
47
+ const result = await this.requestWithRetries({
48
+ url: String(this.settings.webhookUrl).trim(),
49
+ json: {
50
+ text: message.text,
51
+ ...(message.blocks ? { blocks: message.blocks } : {}),
52
+ ...(message.attachments ? { attachments: message.attachments } : {}),
53
+ },
54
+ });
55
+ // Slack's webhook answers no message id: the same shape as the other gateways, with none in it.
56
+ return result.didFail() ? result : OpResult.ok([{ messageId: null }]);
57
+ }
58
+ }
59
+ export { SlackWebhookGw };
@@ -0,0 +1,45 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface TelegramSettings {
5
+ /** `<numeric bot id>:<secret>`, from @BotFather */
6
+ botToken: string;
7
+ /** The default chat — a numeric id (negative for a group) or `@channelname`; `sendMessage({ chatId })` overrides it. */
8
+ chatId?: string;
9
+ /** Default 'HTML'. */
10
+ parseMode?: 'HTML' | 'MarkdownV2';
11
+ }
12
+ export interface TelegramMessage {
13
+ text: string;
14
+ chatId?: string;
15
+ parseMode?: 'HTML' | 'MarkdownV2' | null;
16
+ /** Default true. */
17
+ disableWebPagePreview?: boolean;
18
+ disableNotification?: boolean;
19
+ /** Rows of URL buttons under the message. */
20
+ inlineKeyboard?: Array<Array<{
21
+ text: string;
22
+ url: string;
23
+ }>>;
24
+ }
25
+ /** The API's own limit on one message. */
26
+ export declare const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;
27
+ /** True for a Telegram chat: a numeric id (negative for a group) or `@channelname`. Pure. */
28
+ export declare const isTelegramChatId: (value: unknown) => boolean;
29
+ /**
30
+ * The length Telegram counts — AFTER it parses the markup: tags are not characters, an entity is one. Pure.
31
+ * (For MarkdownV2 and plain text this is the raw length.)
32
+ */
33
+ export declare const telegramVisibleLength: (text: string, parseMode: string | null | undefined) => number;
34
+ declare class TelegramGw extends BaseExternalApiGateway<TelegramSettings> {
35
+ constructor(props?: BaseExternalApiGatewayPropsInterface<TelegramSettings>);
36
+ protected validateSettings(settings: Partial<TelegramSettings>): string[];
37
+ protected secretValues(): string[];
38
+ protected errorMessageOf(reply: ExternalApiReply): string;
39
+ protected shouldRetry(result: OpResult): boolean;
40
+ /** Telegram says how long to wait in its body (`parameters.retry_after`, seconds), not only in a header. */
41
+ protected retryAfterMs(result: OpResult): number | null;
42
+ /** Sends one message. OK with `{ messageId }`. Never throws. */
43
+ sendMessage(message: TelegramMessage): Promise<OpResult>;
44
+ }
45
+ export { TelegramGw };
@@ -0,0 +1,110 @@
1
+ // ./src/gateways/TelegramGw.ts
2
+ //
3
+ // Sends messages through the Telegram Bot API (https://core.telegram.org/bots/api#sendmessage). No SDK: one REST call.
4
+ //
5
+ // const telegram = new TelegramGw().configure({ botToken, chatId });
6
+ // const result = await telegram.sendMessage({ text: '<b>Hello</b>' });
7
+ //
8
+ // ⚠ The bot token sits in the request URL: it is scrubbed out of every error this returns.
9
+ // ⚠ A text over Telegram's 4096 characters is REFUSED, not cut: cutting finished HTML can split a tag or an entity, and
10
+ // Telegram then refuses the whole message anyway. A caller that sends long text cuts it BEFORE adding markup.
11
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
12
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
13
+ /** The API's own limit on one message. */
14
+ export const TELEGRAM_MAX_MESSAGE_LENGTH = 4096;
15
+ const TELEGRAM_BASE_URL = 'https://api.telegram.org';
16
+ const BOT_TOKEN_FORMAT = /^\d+:[A-Za-z0-9_-]+$/;
17
+ const CHAT_ID_FORMAT = /^(-?\d+|@[A-Za-z0-9_]{5,})$/;
18
+ /** True for a Telegram chat: a numeric id (negative for a group) or `@channelname`. Pure. */
19
+ export const isTelegramChatId = (value) => CHAT_ID_FORMAT.test(String(value ?? '').trim());
20
+ /**
21
+ * The length Telegram counts — AFTER it parses the markup: tags are not characters, an entity is one. Pure.
22
+ * (For MarkdownV2 and plain text this is the raw length.)
23
+ */
24
+ export const telegramVisibleLength = (text, parseMode) => parseMode === 'HTML'
25
+ ? String(text)
26
+ .replace(/<[^>]*>/g, '')
27
+ .replace(/&(?:#\d+|#x[0-9a-fA-F]+|[a-zA-Z]+);/g, '_').length
28
+ : String(text).length;
29
+ /** Refusals that will not change on a retry (a wrong chat, a blocked bot, a bad token, broken markup). */
30
+ const PERMANENT_DESCRIPTIONS = [
31
+ 'bot was blocked',
32
+ 'chat not found',
33
+ 'bot is not a member',
34
+ 'not enough rights',
35
+ 'chat_write_forbidden',
36
+ 'bot was kicked',
37
+ 'user is deactivated',
38
+ 'invalid token',
39
+ "can't parse entities",
40
+ ];
41
+ class TelegramGw extends BaseExternalApiGateway {
42
+ constructor(props) {
43
+ super({ baseUrl: TELEGRAM_BASE_URL, ...(props ?? {}) });
44
+ }
45
+ validateSettings(settings) {
46
+ const problems = [];
47
+ if (!BOT_TOKEN_FORMAT.test(String(settings.botToken ?? '').trim())) {
48
+ problems.push('the bot token is missing or malformed (expected <id>:<secret> from @BotFather)');
49
+ }
50
+ if (settings.chatId !== undefined && settings.chatId !== '' && !isTelegramChatId(settings.chatId)) {
51
+ problems.push('the chat id is malformed (a numeric id, or @channelname)');
52
+ }
53
+ return problems;
54
+ }
55
+ secretValues() {
56
+ return [String(this.settings.botToken ?? '').trim()];
57
+ }
58
+ errorMessageOf(reply) {
59
+ return String(reply.body?.description ?? super.errorMessageOf(reply)).slice(0, 500);
60
+ }
61
+ shouldRetry(result) {
62
+ const description = String(result.getDataFirst()?.body?.description ?? result.getErrorSummary('')).toLowerCase();
63
+ return !PERMANENT_DESCRIPTIONS.some((one) => description.includes(one)) && super.shouldRetry(result);
64
+ }
65
+ /** Telegram says how long to wait in its body (`parameters.retry_after`, seconds), not only in a header. */
66
+ retryAfterMs(result) {
67
+ const seconds = Number(result.getDataFirst()?.body?.parameters?.retry_after);
68
+ return Number.isFinite(seconds) && seconds >= 0 ? seconds * 1000 : super.retryAfterMs(result);
69
+ }
70
+ /** Sends one message. OK with `{ messageId }`. Never throws. */
71
+ async sendMessage(message) {
72
+ if (!this.isConfigured()) {
73
+ return this.notConfigured();
74
+ }
75
+ const chatId = String(message?.chatId ?? this.settings.chatId ?? '').trim();
76
+ const text = String(message?.text ?? '');
77
+ if (!isTelegramChatId(chatId)) {
78
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'There is no chat to send to (configure chatId or pass it)');
79
+ }
80
+ if (!text) {
81
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The message is empty');
82
+ }
83
+ const parseMode = message.parseMode === null ? undefined : (message.parseMode ?? this.settings.parseMode ?? 'HTML');
84
+ const length = telegramVisibleLength(text, parseMode);
85
+ if (length > TELEGRAM_MAX_MESSAGE_LENGTH) {
86
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `The message is ${length} characters; Telegram allows ${TELEGRAM_MAX_MESSAGE_LENGTH}`);
87
+ }
88
+ const result = await this.requestWithRetries({
89
+ url: `${this.baseUrl}/bot${String(this.settings.botToken).trim()}/sendMessage`,
90
+ json: {
91
+ chat_id: chatId,
92
+ text,
93
+ ...(parseMode ? { parse_mode: parseMode } : {}),
94
+ disable_web_page_preview: message.disableWebPagePreview !== false,
95
+ ...(message.disableNotification ? { disable_notification: true } : {}),
96
+ ...(message.inlineKeyboard ? { reply_markup: { inline_keyboard: message.inlineKeyboard } } : {}),
97
+ },
98
+ });
99
+ if (result.didFail()) {
100
+ return result;
101
+ }
102
+ const body = result.getDataFirst()?.body;
103
+ // A 200 with `ok: false` is a refusal too.
104
+ if (body?.ok !== true) {
105
+ return OpResult.fail(OP_RESULT_CODES.FAILED, null, this.scrub(String(body?.description ?? 'Telegram did not accept the message')));
106
+ }
107
+ return OpResult.ok([{ messageId: body?.result?.message_id ?? null }]);
108
+ }
109
+ }
110
+ export { TelegramGw };
@@ -0,0 +1,33 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface TwilioSettings {
5
+ /** `AC` + 32 hex characters */
6
+ accountSid: string;
7
+ authToken: string;
8
+ /** The default sender (a number, or `whatsapp:+…`); or send through a messaging service instead. */
9
+ from?: string;
10
+ messagingServiceSid?: string;
11
+ }
12
+ export interface TwilioMessage {
13
+ /** E.164 (`+15557654321`), or `whatsapp:+15557654321` */
14
+ to: string;
15
+ body: string;
16
+ from?: string;
17
+ /** Where Twilio reports delivery status. */
18
+ statusCallback?: string;
19
+ mediaUrl?: string[];
20
+ }
21
+ /** Twilio's limit on one message body. */
22
+ export declare const TWILIO_MAX_BODY_LENGTH = 1600;
23
+ declare class TwilioGw extends BaseExternalApiGateway<TwilioSettings> {
24
+ constructor(props?: BaseExternalApiGatewayPropsInterface<TwilioSettings>);
25
+ protected validateSettings(settings: Partial<TwilioSettings>): string[];
26
+ protected secretValues(): string[];
27
+ /** ⚠ Not after a TIMEOUT: Twilio may well have accepted the message, and a retry texts the person twice. */
28
+ protected shouldRetry(result: OpResult): boolean;
29
+ protected errorMessageOf(reply: ExternalApiReply): string;
30
+ /** Sends one message. OK with `{ sid, status }`. Never throws. */
31
+ sendMessage(message: TwilioMessage): Promise<OpResult>;
32
+ }
33
+ export { TwilioGw };
@@ -0,0 +1,107 @@
1
+ // ./src/gateways/TwilioGw.ts
2
+ //
3
+ // Sends SMS (and WhatsApp, with `whatsapp:` addresses) through Twilio's Messages API
4
+ // (POST https://api.twilio.com/2010-04-01/Accounts/{AccountSid}/Messages.json). No SDK: one REST call.
5
+ //
6
+ // const twilio = new TwilioGw().configure({ accountSid, authToken, from: '+15551234567' });
7
+ // const result = await twilio.sendMessage({ to: '+15557654321', body: 'Hello' });
8
+ //
9
+ // ⚠ The auth token is scrubbed out of every error this returns.
10
+ import { Buffer } from 'buffer';
11
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
12
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
13
+ const TWILIO_BASE_URL = 'https://api.twilio.com';
14
+ const ACCOUNT_SID_FORMAT = /^AC[0-9a-fA-F]{32}$/;
15
+ const ADDRESS_FORMAT = /^(whatsapp:)?\+[1-9]\d{6,14}$/;
16
+ /** Twilio's limit on one message body. */
17
+ export const TWILIO_MAX_BODY_LENGTH = 1600;
18
+ class TwilioGw extends BaseExternalApiGateway {
19
+ constructor(props) {
20
+ super({ baseUrl: TWILIO_BASE_URL, ...(props ?? {}) });
21
+ }
22
+ validateSettings(settings) {
23
+ const problems = [];
24
+ if (!ACCOUNT_SID_FORMAT.test(String(settings.accountSid ?? '').trim())) {
25
+ problems.push('the account SID is missing or malformed (AC + 32 hex characters)');
26
+ }
27
+ if (!String(settings.authToken ?? '').trim()) {
28
+ problems.push('the auth token is missing');
29
+ }
30
+ if (settings.from && !ADDRESS_FORMAT.test(String(settings.from).trim())) {
31
+ problems.push('the From number is not E.164 (+15551234567, or whatsapp:+15551234567)');
32
+ }
33
+ return problems;
34
+ }
35
+ secretValues() {
36
+ const sid = String(this.settings.accountSid ?? '').trim();
37
+ const token = String(this.settings.authToken ?? '').trim();
38
+ return [token, Buffer.from(`${sid}:${token}`).toString('base64')];
39
+ }
40
+ /** ⚠ Not after a TIMEOUT: Twilio may well have accepted the message, and a retry texts the person twice. */
41
+ shouldRetry(result) {
42
+ return result.getCode() !== OP_RESULT_CODES.TIMEOUT && super.shouldRetry(result);
43
+ }
44
+ errorMessageOf(reply) {
45
+ const body = reply.body;
46
+ if (body && typeof body === 'object' && body.message) {
47
+ return `${body.message}${body.code ? ` (Twilio ${body.code})` : ''}`.slice(0, 500);
48
+ }
49
+ return super.errorMessageOf(reply);
50
+ }
51
+ /** Sends one message. OK with `{ sid, status }`. Never throws. */
52
+ async sendMessage(message) {
53
+ if (!this.isConfigured()) {
54
+ return this.notConfigured();
55
+ }
56
+ const to = String(message?.to ?? '').trim();
57
+ const from = String(message?.from ?? this.settings.from ?? '').trim();
58
+ const body = String(message?.body ?? '');
59
+ const problems = [];
60
+ if (!ADDRESS_FORMAT.test(to)) {
61
+ problems.push('the recipient is not E.164 (+15557654321, or whatsapp:+15557654321)');
62
+ }
63
+ if (!from && !this.settings.messagingServiceSid) {
64
+ problems.push('there is no sender (configure from or messagingServiceSid, or pass from)');
65
+ }
66
+ if (from && !ADDRESS_FORMAT.test(from)) {
67
+ problems.push('the sender is not E.164');
68
+ }
69
+ if (!body) {
70
+ problems.push('the message is empty');
71
+ }
72
+ else if (body.length > TWILIO_MAX_BODY_LENGTH) {
73
+ problems.push(`the message is ${body.length} characters; Twilio allows ${TWILIO_MAX_BODY_LENGTH}`);
74
+ }
75
+ if (problems.length) {
76
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `The message cannot be sent: ${problems.join('; ')}`);
77
+ }
78
+ const form = new URLSearchParams();
79
+ form.set('To', to);
80
+ form.set('Body', body);
81
+ if (from) {
82
+ form.set('From', from);
83
+ }
84
+ else {
85
+ form.set('MessagingServiceSid', String(this.settings.messagingServiceSid));
86
+ }
87
+ if (message.statusCallback) {
88
+ form.set('StatusCallback', message.statusCallback);
89
+ }
90
+ for (const url of message.mediaUrl ?? []) {
91
+ form.append('MediaUrl', url);
92
+ }
93
+ const sid = String(this.settings.accountSid).trim();
94
+ const auth = Buffer.from(`${sid}:${String(this.settings.authToken).trim()}`).toString('base64');
95
+ const result = await this.requestWithRetries({
96
+ url: `${this.baseUrl}/2010-04-01/Accounts/${sid}/Messages.json`,
97
+ headers: { Authorization: `Basic ${auth}`, 'Content-Type': 'application/x-www-form-urlencoded' },
98
+ body: form,
99
+ });
100
+ if (result.didFail()) {
101
+ return result;
102
+ }
103
+ const reply = result.getDataFirst()?.body;
104
+ return OpResult.ok([{ sid: reply?.sid ?? null, status: reply?.status ?? null }]);
105
+ }
106
+ }
107
+ export { TwilioGw };
@@ -0,0 +1,16 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ /** True when an IP address is one a user-given URL must never reach. Pure. */
3
+ export declare const isBlockedAddress: (address: string) => boolean;
4
+ export interface ExternalUrlOptions {
5
+ /** Default ['https:', 'http:']. */
6
+ protocols?: string[];
7
+ /** Resolves a hostname to every address (tests pass their own). Default: the system resolver. */
8
+ lookup?: (hostname: string) => Promise<string[]>;
9
+ /** The field the error is reported under. Default '' (a general error, like every other gateway refusal). */
10
+ field?: string;
11
+ }
12
+ /**
13
+ * OK when `url` may be requested: a permitted protocol, no credentials in it, and a host that is not — and does not
14
+ * resolve to — a local, private or reserved address. Else VALIDATION_FAILED, saying why. Never throws.
15
+ */
16
+ export declare const checkExternalUrl: (url: string, opts?: ExternalUrlOptions) => Promise<OpResult>;
@@ -0,0 +1,116 @@
1
+ // ./src/gateways/externalUrl.ts
2
+ //
3
+ // Is this URL safe to send a request to on someone else's say-so? A URL a USER typed (a webhook) must not reach our own
4
+ // network: localhost, the private ranges, the cloud metadata service (169.254.169.254 hands out credentials), or any of
5
+ // them spelled another way (an IPv4 address written as IPv6, a hostname that resolves to one).
6
+ //
7
+ // ⚠ EVERY address a hostname resolves to is checked — a name with one public and one private address is refused.
8
+ // ⚠ What it cannot stop alone: a hostname that resolves to a public address now and a private one at the moment of the
9
+ // request (DNS rebinding). Gateways that use this also refuse to follow redirects; together that narrows it to a
10
+ // window of milliseconds, not closes it.
11
+ import { BlockList, isIP } from 'net';
12
+ import { promises as dns } from 'dns';
13
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
14
+ const BLOCKED = new BlockList();
15
+ // IPv4: "this network", private, carrier-grade NAT, loopback, link-local (metadata), protocol assignments, test nets,
16
+ // benchmarking, multicast, reserved, broadcast.
17
+ for (const [network, prefix] of [
18
+ ['0.0.0.0', 8],
19
+ ['10.0.0.0', 8],
20
+ ['100.64.0.0', 10],
21
+ ['127.0.0.0', 8],
22
+ ['169.254.0.0', 16],
23
+ ['172.16.0.0', 12],
24
+ ['192.0.0.0', 24],
25
+ ['192.0.2.0', 24],
26
+ ['192.168.0.0', 16],
27
+ ['198.18.0.0', 15],
28
+ ['192.88.99.0', 24],
29
+ ['198.51.100.0', 24],
30
+ ['203.0.113.0', 24],
31
+ ['224.0.0.0', 4],
32
+ ['240.0.0.0', 4],
33
+ ]) {
34
+ BLOCKED.addSubnet(network, prefix, 'ipv4');
35
+ }
36
+ // IPv6: unspecified, loopback, IPv4-compatible (`::127.0.0.1`), NAT64 — both prefixes — and 6to4 (all reach IPv4
37
+ // inside), discard-only, documentation, unique-local (fc00::/7 = fc… AND fd…), link-local, multicast.
38
+ // ⓘ IPv4-MAPPED (`::ffff:127.0.0.1`) needs no rule of its own: BlockList checks it against the IPv4 rules.
39
+ for (const [network, prefix] of [
40
+ ['::', 128],
41
+ ['::1', 128],
42
+ ['::', 96],
43
+ ['64:ff9b::', 96],
44
+ ['64:ff9b:1::', 48],
45
+ ['100::', 64],
46
+ ['2002::', 16],
47
+ ['2001:db8::', 32],
48
+ ['fc00::', 7],
49
+ ['fe80::', 10],
50
+ ['ff00::', 8],
51
+ ]) {
52
+ BLOCKED.addSubnet(network, prefix, 'ipv6');
53
+ }
54
+ const BLOCKED_HOSTNAMES = new Set(['localhost', 'localhost.localdomain', 'metadata', 'metadata.google.internal']);
55
+ /** True when an IP address is one a user-given URL must never reach. Pure. */
56
+ export const isBlockedAddress = (address) => {
57
+ const ip = String(address ?? '')
58
+ .replace(/^\[|\]$/g, '')
59
+ .split('%')[0];
60
+ const version = isIP(ip);
61
+ if (version === 4) {
62
+ return BLOCKED.check(ip, 'ipv4');
63
+ }
64
+ if (version === 6) {
65
+ // ⓘ BlockList matches an IPv4-MAPPED address (`::ffff:127.0.0.1`, `::ffff:7f00:1`) against the IPv4 rules itself.
66
+ return BLOCKED.check(ip, 'ipv6');
67
+ }
68
+ // Not an address at all: refuse rather than guess.
69
+ return true;
70
+ };
71
+ const systemLookup = async (hostname) => (await dns.lookup(hostname, { all: true, verbatim: true })).map((one) => one.address);
72
+ /**
73
+ * OK when `url` may be requested: a permitted protocol, no credentials in it, and a host that is not — and does not
74
+ * resolve to — a local, private or reserved address. Else VALIDATION_FAILED, saying why. Never throws.
75
+ */
76
+ export const checkExternalUrl = async (url, opts = {}) => {
77
+ const field = opts.field ?? '';
78
+ const refuse = (why) => OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, { [field]: why });
79
+ let parsed;
80
+ try {
81
+ parsed = new URL(String(url ?? '').trim());
82
+ }
83
+ catch {
84
+ return refuse('The URL is not valid');
85
+ }
86
+ if (!(opts.protocols ?? ['https:', 'http:']).includes(parsed.protocol)) {
87
+ return refuse(`Only ${(opts.protocols ?? ['https:', 'http:']).join(' and ')} URLs are allowed`);
88
+ }
89
+ if (parsed.username || parsed.password) {
90
+ return refuse('A URL must not carry a user name or password');
91
+ }
92
+ const host = parsed.hostname
93
+ .toLowerCase()
94
+ .replace(/^\[|\]$/g, '')
95
+ .replace(/\.$/, '');
96
+ if (!host || BLOCKED_HOSTNAMES.has(host) || host.endsWith('.localhost') || host.endsWith('.internal')) {
97
+ return refuse('This host is not allowed');
98
+ }
99
+ if (isIP(host)) {
100
+ return isBlockedAddress(host) ? refuse('This address is not allowed') : OpResult.ok([]);
101
+ }
102
+ let addresses;
103
+ try {
104
+ addresses = await (opts.lookup ?? systemLookup)(host);
105
+ }
106
+ catch {
107
+ return refuse('The host name does not resolve');
108
+ }
109
+ if (!addresses.length) {
110
+ return refuse('The host name does not resolve');
111
+ }
112
+ // ⚠ EVERY address: a name with one public and one private address is refused.
113
+ return addresses.some(isBlockedAddress)
114
+ ? refuse('The host name resolves to an address that is not allowed')
115
+ : OpResult.ok([]);
116
+ };
@@ -0,0 +1,15 @@
1
+ import { lookup as dnsLookup } from 'dns';
2
+ import { ExternalApiFetch } from '../interfaces';
3
+ export interface GuardedFetchOptions {
4
+ /** The resolver (dns.lookup's shape) — tests pass their own. */
5
+ dnsLookup?: typeof dnsLookup;
6
+ /** Which addresses are refused. Default `isBlockedAddress`. */
7
+ isBlocked?: (address: string) => boolean;
8
+ }
9
+ /**
10
+ * A `dns.lookup` that refuses when ANY address the name resolves to is blocked (a name with one private address among
11
+ * public ones is refused, whichever the socket would have picked).
12
+ */
13
+ export declare const guardedLookup: (opts?: GuardedFetchOptions) => (hostname: string, options: any, callback: (...args: any[]) => void) => void;
14
+ /** A fetch whose every connection goes through `guardedLookup`. The answer has `status`, `headers` and `text()`. */
15
+ export declare const createGuardedFetch: (opts?: GuardedFetchOptions) => ExternalApiFetch;