@sdflc/backend-helpers 1.0.139 → 1.0.141

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 (56) hide show
  1. package/README.md +471 -29
  2. package/build/EmergencyAlerter.d.ts +140 -0
  3. package/build/EmergencyAlerter.js +465 -0
  4. package/build/esm/EmergencyAlerter.d.ts +140 -0
  5. package/build/esm/EmergencyAlerter.js +454 -0
  6. package/build/esm/gateways/BaseExternalApiGateway.d.ts +94 -0
  7. package/build/esm/gateways/BaseExternalApiGateway.js +319 -0
  8. package/build/esm/gateways/DiscordWebhookGw.d.ts +50 -0
  9. package/build/esm/gateways/DiscordWebhookGw.js +70 -0
  10. package/build/esm/gateways/HttpWebhookGw.d.ts +43 -0
  11. package/build/esm/gateways/HttpWebhookGw.js +131 -0
  12. package/build/esm/gateways/SendGridGw.d.ts +41 -0
  13. package/build/esm/gateways/SendGridGw.js +116 -0
  14. package/build/esm/gateways/SlackWebhookGw.d.ts +23 -0
  15. package/build/esm/gateways/SlackWebhookGw.js +59 -0
  16. package/build/esm/gateways/TelegramGw.d.ts +45 -0
  17. package/build/esm/gateways/TelegramGw.js +110 -0
  18. package/build/esm/gateways/TwilioGw.d.ts +33 -0
  19. package/build/esm/gateways/TwilioGw.js +107 -0
  20. package/build/esm/gateways/externalUrl.d.ts +16 -0
  21. package/build/esm/gateways/externalUrl.js +116 -0
  22. package/build/esm/gateways/guardedFetch.d.ts +15 -0
  23. package/build/esm/gateways/guardedFetch.js +133 -0
  24. package/build/esm/gateways/index.d.ts +9 -0
  25. package/build/esm/gateways/index.js +9 -0
  26. package/build/esm/index.d.ts +2 -1
  27. package/build/esm/index.js +2 -1
  28. package/build/esm/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  29. package/build/gateways/BaseExternalApiGateway.d.ts +94 -0
  30. package/build/gateways/BaseExternalApiGateway.js +326 -0
  31. package/build/gateways/DiscordWebhookGw.d.ts +50 -0
  32. package/build/gateways/DiscordWebhookGw.js +73 -0
  33. package/build/gateways/HttpWebhookGw.d.ts +43 -0
  34. package/build/gateways/HttpWebhookGw.js +135 -0
  35. package/build/gateways/SendGridGw.d.ts +41 -0
  36. package/build/gateways/SendGridGw.js +119 -0
  37. package/build/gateways/SlackWebhookGw.d.ts +23 -0
  38. package/build/gateways/SlackWebhookGw.js +62 -0
  39. package/build/gateways/TelegramGw.d.ts +45 -0
  40. package/build/gateways/TelegramGw.js +115 -0
  41. package/build/gateways/TwilioGw.d.ts +33 -0
  42. package/build/gateways/TwilioGw.js +110 -0
  43. package/build/gateways/externalUrl.d.ts +16 -0
  44. package/build/gateways/externalUrl.js +121 -0
  45. package/build/gateways/guardedFetch.d.ts +15 -0
  46. package/build/gateways/guardedFetch.js +141 -0
  47. package/build/gateways/index.d.ts +9 -0
  48. package/build/gateways/index.js +25 -0
  49. package/build/index.d.ts +2 -1
  50. package/build/index.js +2 -1
  51. package/build/interfaces/BaseExternalApiGatewayPropsInterface.d.ts +16 -2
  52. package/package.json +2 -1
  53. package/build/BaseExternalApiGateway.d.ts +0 -16
  54. package/build/BaseExternalApiGateway.js +0 -54
  55. package/build/esm/BaseExternalApiGateway.d.ts +0 -16
  56. package/build/esm/BaseExternalApiGateway.js +0 -48
@@ -0,0 +1,131 @@
1
+ // ./src/gateways/HttpWebhookGw.ts
2
+ //
3
+ // Sends JSON to any URL — for whatever has no gateway of its own. Optionally SIGNED, so the receiver can tell the
4
+ // request came from us and was not replayed.
5
+ //
6
+ // const hook = new HttpWebhookGw(); // once
7
+ // hook.configure({ url, signingSecret }); // per tenant, whenever
8
+ // const result = await hook.send({ payload: { event: 'order.paid', id } });
9
+ //
10
+ // Every request carries `X-Webhook-Id` (one per send — the same on its retries, so a receiver can drop a duplicate).
11
+ // Signed (with `signingSecret`): `X-Webhook-Timestamp: <unix seconds>` and
12
+ // `X-Webhook-Signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<body>">`. A receiver recomputes it over the RAW body
13
+ // (`webhookSignatureOf`) and refuses a timestamp older than a few minutes.
14
+ //
15
+ // ⚠ A webhook URL is one a USER typed: it must not reach our own network or the cloud metadata service. The URL is
16
+ // checked before the request (`checkExternalUrl`, for a clear refusal), and the address the socket CONNECTS to is
17
+ // checked again at that moment (`createGuardedFetch`) — a check made only beforehand loses to DNS rebinding.
18
+ // ⚠ `allowPrivateNetwork` is a CONSTRUCTOR prop, never a setting: settings often come from a tenant's own row, and a
19
+ // tenant must not be able to switch the protection off.
20
+ // ⚠ The signing secret and every header value — configured or per request — are scrubbed out of what this returns.
21
+ import { createHmac, randomUUID } from 'crypto';
22
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
23
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
24
+ import { checkExternalUrl } from './externalUrl';
25
+ import { createGuardedFetch } from './guardedFetch';
26
+ export const WEBHOOK_ID_HEADER = 'X-Webhook-Id';
27
+ export const WEBHOOK_TIMESTAMP_HEADER = 'X-Webhook-Timestamp';
28
+ export const WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';
29
+ /** The headers this gateway sets itself — a configured or per-request header of the same name never replaces them. */
30
+ const OWN_HEADERS = [WEBHOOK_ID_HEADER, WEBHOOK_TIMESTAMP_HEADER, WEBHOOK_SIGNATURE_HEADER].map((one) => one.toLowerCase());
31
+ /** The signature header's value for a body sent at `timestamp` (unix seconds). Pure — receivers can use it too. */
32
+ export const webhookSignatureOf = (secret, timestamp, body) => `sha256=${createHmac('sha256', secret).update(`${timestamp}.${body}`).digest('hex')}`;
33
+ /** Each value whole AND each of its words — a service that echoes `Bearer <token>` back often echoes only the token. */
34
+ const secretsOfHeaders = (headers) => {
35
+ const values = Object.values(headers ?? {}).map(String);
36
+ return [...values, ...values.flatMap((value) => value.split(/\s+/)).filter((word) => word.length >= 8)];
37
+ };
38
+ /** Headers merged by NAME, case-insensitively — the later wins, under the later's spelling. */
39
+ const mergeHeaders = (...sets) => {
40
+ const out = new Map();
41
+ for (const set of sets) {
42
+ for (const [name, value] of Object.entries(set ?? {})) {
43
+ out.set(name.toLowerCase(), [name, String(value)]);
44
+ }
45
+ }
46
+ return Object.fromEntries([...out.values()]);
47
+ };
48
+ class HttpWebhookGw extends BaseExternalApiGateway {
49
+ allowPrivateNetwork;
50
+ lookup;
51
+ constructor(props) {
52
+ const allowPrivateNetwork = props?.allowPrivateNetwork === true;
53
+ // ⚠ The address is checked AT CONNECT TIME unless a test passes its own fetch, or WE allowed private addresses.
54
+ super({
55
+ ...(props ?? {}),
56
+ fetch: props?.fetch ?? (allowPrivateNetwork ? undefined : createGuardedFetch({ dnsLookup: props?.dnsLookup })),
57
+ });
58
+ this.allowPrivateNetwork = allowPrivateNetwork;
59
+ this.lookup = props?.lookup;
60
+ }
61
+ validateSettings(settings) {
62
+ const problems = [];
63
+ try {
64
+ const url = new URL(String(settings.url ?? '').trim());
65
+ if (!['https:', 'http:'].includes(url.protocol)) {
66
+ problems.push('the URL must be http or https');
67
+ }
68
+ }
69
+ catch {
70
+ problems.push('the URL is missing or not valid');
71
+ }
72
+ if (settings.method && !['POST', 'PUT', 'PATCH'].includes(String(settings.method).toUpperCase())) {
73
+ problems.push('the method must be POST, PUT or PATCH');
74
+ }
75
+ if (Object.entries(settings.headers ?? {}).some(([name, value]) => /[\r\n]/.test(`${name}${value}`))) {
76
+ problems.push('a header contains a line break');
77
+ }
78
+ return problems;
79
+ }
80
+ secretValues() {
81
+ return [String(this.settings.signingSecret ?? ''), ...secretsOfHeaders(this.settings.headers)];
82
+ }
83
+ /** Sends one request. OK with `{ status, body }` of the receiver's answer (scrubbed). Never throws. */
84
+ async send(request) {
85
+ if (!this.isConfigured()) {
86
+ return this.notConfigured();
87
+ }
88
+ if (Object.entries(request?.headers ?? {}).some(([name, value]) => /[\r\n]/.test(`${name}${value}`))) {
89
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'A header contains a line break');
90
+ }
91
+ const url = String(this.settings.url).trim();
92
+ if (!this.allowPrivateNetwork) {
93
+ const safe = await checkExternalUrl(url, { lookup: this.lookup });
94
+ if (safe.didFail()) {
95
+ return safe;
96
+ }
97
+ }
98
+ let body;
99
+ try {
100
+ body = JSON.stringify(request?.payload ?? null);
101
+ }
102
+ catch {
103
+ body = undefined;
104
+ }
105
+ // JSON.stringify answers undefined (no throw) for a function or a symbol: that is nothing to send, not an empty send.
106
+ if (typeof body !== 'string') {
107
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The payload cannot be sent as JSON');
108
+ }
109
+ const own = { [WEBHOOK_ID_HEADER]: randomUUID() };
110
+ if (this.settings.signingSecret) {
111
+ const timestamp = Math.floor(Date.now() / 1000);
112
+ own[WEBHOOK_TIMESTAMP_HEADER] = String(timestamp);
113
+ own[WEBHOOK_SIGNATURE_HEADER] = webhookSignatureOf(this.settings.signingSecret, timestamp, body);
114
+ }
115
+ const given = mergeHeaders(this.settings.headers, request?.headers);
116
+ const headers = mergeHeaders({ 'Content-Type': 'application/json' }, Object.fromEntries(Object.entries(given).filter(([name]) => !OWN_HEADERS.includes(name.toLowerCase()))), own);
117
+ const result = await this.requestWithRetries({
118
+ url,
119
+ method: String(this.settings.method ?? 'POST').toUpperCase(),
120
+ headers,
121
+ body,
122
+ secrets: secretsOfHeaders(request?.headers),
123
+ });
124
+ if (result.didFail()) {
125
+ return result;
126
+ }
127
+ const reply = result.getDataFirst();
128
+ return OpResult.ok([{ status: reply?.status, body: reply?.body }]);
129
+ }
130
+ }
131
+ export { HttpWebhookGw };
@@ -0,0 +1,41 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway, ExternalApiReply } from './BaseExternalApiGateway';
4
+ export interface SendGridSettings {
5
+ apiKey: string;
6
+ /** The default sender; `sendEmail({ from })` overrides it. */
7
+ fromEmail?: string;
8
+ fromName?: string;
9
+ }
10
+ /** `'a@b.com'` or `{ email: 'a@b.com', name: 'A' }`. */
11
+ export type SendGridAddress = string | {
12
+ email: string;
13
+ name?: string;
14
+ };
15
+ export interface SendGridEmail {
16
+ to: SendGridAddress | SendGridAddress[];
17
+ cc?: SendGridAddress | SendGridAddress[];
18
+ bcc?: SendGridAddress | SendGridAddress[];
19
+ from?: SendGridAddress;
20
+ replyTo?: SendGridAddress;
21
+ /** Required unless a template supplies it. */
22
+ subject?: string;
23
+ text?: string;
24
+ html?: string;
25
+ /** A SendGrid dynamic template (`d-…`) and its data. */
26
+ templateId?: string;
27
+ dynamicTemplateData?: Record<string, unknown>;
28
+ categories?: string[];
29
+ customArgs?: Record<string, string>;
30
+ }
31
+ declare class SendGridGw extends BaseExternalApiGateway<SendGridSettings> {
32
+ constructor(props?: BaseExternalApiGatewayPropsInterface<SendGridSettings>);
33
+ protected validateSettings(settings: Partial<SendGridSettings>): string[];
34
+ protected secretValues(): string[];
35
+ /** ⚠ Not after a TIMEOUT: SendGrid may well have accepted the mail, and a retry sends it twice. */
36
+ protected shouldRetry(result: OpResult): boolean;
37
+ protected errorMessageOf(reply: ExternalApiReply): string;
38
+ /** Sends one email. OK with `{ messageId }` (SendGrid's `x-message-id`). Never throws. */
39
+ sendEmail(email: SendGridEmail): Promise<OpResult>;
40
+ }
41
+ export { SendGridGw };
@@ -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 };