@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,50 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
4
+ export interface DiscordWebhookSettings {
5
+ /** `https://discord.com/api/webhooks/<id>/<token>` */
6
+ webhookUrl: string;
7
+ /** The name and avatar the messages appear under (defaults: the webhook's own). */
8
+ username?: string;
9
+ avatarUrl?: string;
10
+ }
11
+ export interface DiscordEmbed {
12
+ title?: string;
13
+ description?: string;
14
+ url?: string;
15
+ color?: number;
16
+ fields?: Array<{
17
+ name: string;
18
+ value: string;
19
+ inline?: boolean;
20
+ }>;
21
+ footer?: {
22
+ text: string;
23
+ };
24
+ timestamp?: string;
25
+ }
26
+ export interface DiscordMessage {
27
+ /** At most 2000 characters; required unless there are embeds. */
28
+ content?: string;
29
+ /** At most 10. */
30
+ embeds?: DiscordEmbed[];
31
+ username?: string;
32
+ avatarUrl?: string;
33
+ /** Who may be pinged — default nobody (`{ parse: [] }`). */
34
+ allowedMentions?: {
35
+ parse?: Array<'roles' | 'users' | 'everyone'>;
36
+ users?: string[];
37
+ roles?: string[];
38
+ };
39
+ }
40
+ export declare const DISCORD_MAX_CONTENT_LENGTH = 2000;
41
+ export declare const DISCORD_MAX_EMBEDS = 10;
42
+ declare class DiscordWebhookGw extends BaseExternalApiGateway<DiscordWebhookSettings> {
43
+ constructor(props?: BaseExternalApiGatewayPropsInterface<DiscordWebhookSettings>);
44
+ protected validateSettings(settings: Partial<DiscordWebhookSettings>): string[];
45
+ protected secretValues(): string[];
46
+ protected shouldRetry(result: OpResult): boolean;
47
+ /** Posts one message. OK with `{ messageId }`. Never throws. */
48
+ postMessage(message: DiscordMessage): Promise<OpResult>;
49
+ }
50
+ export { DiscordWebhookGw };
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DiscordWebhookGw = exports.DISCORD_MAX_EMBEDS = exports.DISCORD_MAX_CONTENT_LENGTH = void 0;
4
+ // ./src/gateways/DiscordWebhookGw.ts
5
+ //
6
+ // Posts a message to a Discord channel through a webhook (https://discord.com/developers/docs/resources/webhook).
7
+ //
8
+ // const discord = new DiscordWebhookGw().configure({ webhookUrl, username: 'Alerts' });
9
+ // const result = await discord.postMessage({ content: 'Hello' });
10
+ //
11
+ // ⚠ The webhook URL IS the credential — anyone holding it can post to the channel. It is scrubbed out of every error.
12
+ // ⚠ Mentions are OFF unless asked for (`allowedMentions`): a text that happens to contain @everyone must not ping a server.
13
+ const api_helpers_1 = require("@sdflc/api-helpers");
14
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
15
+ exports.DISCORD_MAX_CONTENT_LENGTH = 2000;
16
+ exports.DISCORD_MAX_EMBEDS = 10;
17
+ const WEBHOOK_PREFIXES = ['https://discord.com/api/webhooks/', 'https://discordapp.com/api/webhooks/'];
18
+ /** Discord error codes that will not change on a retry: an unknown webhook, a bad webhook token. */
19
+ const PERMANENT_CODES = [10015, 50027];
20
+ class DiscordWebhookGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
21
+ constructor(props) {
22
+ super(props);
23
+ }
24
+ validateSettings(settings) {
25
+ const url = String(settings.webhookUrl ?? '').trim();
26
+ return WEBHOOK_PREFIXES.some((prefix) => url.startsWith(prefix))
27
+ ? []
28
+ : ['the webhook URL is missing or not a Discord one (https://discord.com/api/webhooks/…)'];
29
+ }
30
+ secretValues() {
31
+ return [String(this.settings.webhookUrl ?? '').trim()];
32
+ }
33
+ shouldRetry(result) {
34
+ const code = Number(result.getDataFirst()?.body?.code);
35
+ return !PERMANENT_CODES.includes(code) && super.shouldRetry(result);
36
+ }
37
+ /** Posts one message. OK with `{ messageId }`. Never throws. */
38
+ async postMessage(message) {
39
+ if (!this.isConfigured()) {
40
+ return this.notConfigured();
41
+ }
42
+ const content = String(message?.content ?? '');
43
+ const embeds = Array.isArray(message?.embeds) ? message.embeds : [];
44
+ if (!content.trim() && embeds.length === 0) {
45
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The message is empty (no content and no embeds)');
46
+ }
47
+ if (content.length > exports.DISCORD_MAX_CONTENT_LENGTH) {
48
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, `The message is ${content.length} characters; Discord allows ${exports.DISCORD_MAX_CONTENT_LENGTH}`);
49
+ }
50
+ if (embeds.length > exports.DISCORD_MAX_EMBEDS) {
51
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, `${embeds.length} embeds; Discord allows ${exports.DISCORD_MAX_EMBEDS}`);
52
+ }
53
+ const username = message.username ?? this.settings.username;
54
+ const avatarUrl = message.avatarUrl ?? this.settings.avatarUrl;
55
+ const url = String(this.settings.webhookUrl).trim();
56
+ // `wait=true` makes Discord answer with the message (and its id) instead of an empty 204.
57
+ const result = await this.requestWithRetries({
58
+ url: `${url}${url.includes('?') ? '&' : '?'}wait=true`,
59
+ json: {
60
+ ...(content ? { content } : {}),
61
+ ...(embeds.length ? { embeds } : {}),
62
+ ...(username ? { username } : {}),
63
+ ...(avatarUrl ? { avatar_url: avatarUrl } : {}),
64
+ allowed_mentions: message.allowedMentions ?? { parse: [] },
65
+ },
66
+ });
67
+ if (result.didFail()) {
68
+ return result;
69
+ }
70
+ return api_helpers_1.OpResult.ok([{ messageId: result.getDataFirst()?.body?.id ?? null }]);
71
+ }
72
+ }
73
+ exports.DiscordWebhookGw = DiscordWebhookGw;
@@ -0,0 +1,43 @@
1
+ import { OpResult } from '@sdflc/api-helpers';
2
+ import { BaseExternalApiGatewayPropsInterface } from '../interfaces';
3
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
4
+ import { GuardedFetchOptions } from './guardedFetch';
5
+ export interface HttpWebhookSettings {
6
+ url: string;
7
+ /** Default POST. */
8
+ method?: 'POST' | 'PUT' | 'PATCH';
9
+ headers?: Record<string, string>;
10
+ /** Signs every request (see the file header). */
11
+ signingSecret?: string;
12
+ }
13
+ export interface HttpWebhookGwProps extends BaseExternalApiGatewayPropsInterface<HttpWebhookSettings> {
14
+ /**
15
+ * Only for URLs WE configure (an internal service) — never for one a user typed. It is a constructor prop on purpose:
16
+ * nothing a tenant controls can turn it on. Default false.
17
+ */
18
+ allowPrivateNetwork?: boolean;
19
+ /** Resolves a host to every address (the pre-check) — tests pass their own. */
20
+ lookup?: (hostname: string) => Promise<string[]>;
21
+ /** The resolver the CONNECT-time check uses (dns.lookup's shape) — tests pass their own. */
22
+ dnsLookup?: GuardedFetchOptions['dnsLookup'];
23
+ }
24
+ export interface HttpWebhookSend {
25
+ payload: unknown;
26
+ /** Added to (and overriding) the configured headers for this request. */
27
+ headers?: Record<string, string>;
28
+ }
29
+ export declare const WEBHOOK_ID_HEADER = "X-Webhook-Id";
30
+ export declare const WEBHOOK_TIMESTAMP_HEADER = "X-Webhook-Timestamp";
31
+ export declare const WEBHOOK_SIGNATURE_HEADER = "X-Webhook-Signature";
32
+ /** The signature header's value for a body sent at `timestamp` (unix seconds). Pure — receivers can use it too. */
33
+ export declare const webhookSignatureOf: (secret: string, timestamp: number, body: string) => string;
34
+ declare class HttpWebhookGw extends BaseExternalApiGateway<HttpWebhookSettings> {
35
+ private readonly allowPrivateNetwork;
36
+ private readonly lookup?;
37
+ constructor(props?: HttpWebhookGwProps);
38
+ protected validateSettings(settings: Partial<HttpWebhookSettings>): string[];
39
+ protected secretValues(): string[];
40
+ /** Sends one request. OK with `{ status, body }` of the receiver's answer (scrubbed). Never throws. */
41
+ send(request: HttpWebhookSend): Promise<OpResult>;
42
+ }
43
+ export { HttpWebhookGw };
@@ -0,0 +1,135 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpWebhookGw = exports.webhookSignatureOf = exports.WEBHOOK_SIGNATURE_HEADER = exports.WEBHOOK_TIMESTAMP_HEADER = exports.WEBHOOK_ID_HEADER = void 0;
4
+ // ./src/gateways/HttpWebhookGw.ts
5
+ //
6
+ // Sends JSON to any URL — for whatever has no gateway of its own. Optionally SIGNED, so the receiver can tell the
7
+ // request came from us and was not replayed.
8
+ //
9
+ // const hook = new HttpWebhookGw(); // once
10
+ // hook.configure({ url, signingSecret }); // per tenant, whenever
11
+ // const result = await hook.send({ payload: { event: 'order.paid', id } });
12
+ //
13
+ // Every request carries `X-Webhook-Id` (one per send — the same on its retries, so a receiver can drop a duplicate).
14
+ // Signed (with `signingSecret`): `X-Webhook-Timestamp: <unix seconds>` and
15
+ // `X-Webhook-Signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<body>">`. A receiver recomputes it over the RAW body
16
+ // (`webhookSignatureOf`) and refuses a timestamp older than a few minutes.
17
+ //
18
+ // ⚠ A webhook URL is one a USER typed: it must not reach our own network or the cloud metadata service. The URL is
19
+ // checked before the request (`checkExternalUrl`, for a clear refusal), and the address the socket CONNECTS to is
20
+ // checked again at that moment (`createGuardedFetch`) — a check made only beforehand loses to DNS rebinding.
21
+ // ⚠ `allowPrivateNetwork` is a CONSTRUCTOR prop, never a setting: settings often come from a tenant's own row, and a
22
+ // tenant must not be able to switch the protection off.
23
+ // ⚠ The signing secret and every header value — configured or per request — are scrubbed out of what this returns.
24
+ const crypto_1 = require("crypto");
25
+ const api_helpers_1 = require("@sdflc/api-helpers");
26
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
27
+ const externalUrl_1 = require("./externalUrl");
28
+ const guardedFetch_1 = require("./guardedFetch");
29
+ exports.WEBHOOK_ID_HEADER = 'X-Webhook-Id';
30
+ exports.WEBHOOK_TIMESTAMP_HEADER = 'X-Webhook-Timestamp';
31
+ exports.WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';
32
+ /** The headers this gateway sets itself — a configured or per-request header of the same name never replaces them. */
33
+ const OWN_HEADERS = [exports.WEBHOOK_ID_HEADER, exports.WEBHOOK_TIMESTAMP_HEADER, exports.WEBHOOK_SIGNATURE_HEADER].map((one) => one.toLowerCase());
34
+ /** The signature header's value for a body sent at `timestamp` (unix seconds). Pure — receivers can use it too. */
35
+ const webhookSignatureOf = (secret, timestamp, body) => `sha256=${(0, crypto_1.createHmac)('sha256', secret).update(`${timestamp}.${body}`).digest('hex')}`;
36
+ exports.webhookSignatureOf = webhookSignatureOf;
37
+ /** Each value whole AND each of its words — a service that echoes `Bearer <token>` back often echoes only the token. */
38
+ const secretsOfHeaders = (headers) => {
39
+ const values = Object.values(headers ?? {}).map(String);
40
+ return [...values, ...values.flatMap((value) => value.split(/\s+/)).filter((word) => word.length >= 8)];
41
+ };
42
+ /** Headers merged by NAME, case-insensitively — the later wins, under the later's spelling. */
43
+ const mergeHeaders = (...sets) => {
44
+ const out = new Map();
45
+ for (const set of sets) {
46
+ for (const [name, value] of Object.entries(set ?? {})) {
47
+ out.set(name.toLowerCase(), [name, String(value)]);
48
+ }
49
+ }
50
+ return Object.fromEntries([...out.values()]);
51
+ };
52
+ class HttpWebhookGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
53
+ allowPrivateNetwork;
54
+ lookup;
55
+ constructor(props) {
56
+ const allowPrivateNetwork = props?.allowPrivateNetwork === true;
57
+ // ⚠ The address is checked AT CONNECT TIME unless a test passes its own fetch, or WE allowed private addresses.
58
+ super({
59
+ ...(props ?? {}),
60
+ fetch: props?.fetch ?? (allowPrivateNetwork ? undefined : (0, guardedFetch_1.createGuardedFetch)({ dnsLookup: props?.dnsLookup })),
61
+ });
62
+ this.allowPrivateNetwork = allowPrivateNetwork;
63
+ this.lookup = props?.lookup;
64
+ }
65
+ validateSettings(settings) {
66
+ const problems = [];
67
+ try {
68
+ const url = new URL(String(settings.url ?? '').trim());
69
+ if (!['https:', 'http:'].includes(url.protocol)) {
70
+ problems.push('the URL must be http or https');
71
+ }
72
+ }
73
+ catch {
74
+ problems.push('the URL is missing or not valid');
75
+ }
76
+ if (settings.method && !['POST', 'PUT', 'PATCH'].includes(String(settings.method).toUpperCase())) {
77
+ problems.push('the method must be POST, PUT or PATCH');
78
+ }
79
+ if (Object.entries(settings.headers ?? {}).some(([name, value]) => /[\r\n]/.test(`${name}${value}`))) {
80
+ problems.push('a header contains a line break');
81
+ }
82
+ return problems;
83
+ }
84
+ secretValues() {
85
+ return [String(this.settings.signingSecret ?? ''), ...secretsOfHeaders(this.settings.headers)];
86
+ }
87
+ /** Sends one request. OK with `{ status, body }` of the receiver's answer (scrubbed). Never throws. */
88
+ async send(request) {
89
+ if (!this.isConfigured()) {
90
+ return this.notConfigured();
91
+ }
92
+ if (Object.entries(request?.headers ?? {}).some(([name, value]) => /[\r\n]/.test(`${name}${value}`))) {
93
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'A header contains a line break');
94
+ }
95
+ const url = String(this.settings.url).trim();
96
+ if (!this.allowPrivateNetwork) {
97
+ const safe = await (0, externalUrl_1.checkExternalUrl)(url, { lookup: this.lookup });
98
+ if (safe.didFail()) {
99
+ return safe;
100
+ }
101
+ }
102
+ let body;
103
+ try {
104
+ body = JSON.stringify(request?.payload ?? null);
105
+ }
106
+ catch {
107
+ body = undefined;
108
+ }
109
+ // JSON.stringify answers undefined (no throw) for a function or a symbol: that is nothing to send, not an empty send.
110
+ if (typeof body !== 'string') {
111
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The payload cannot be sent as JSON');
112
+ }
113
+ const own = { [exports.WEBHOOK_ID_HEADER]: (0, crypto_1.randomUUID)() };
114
+ if (this.settings.signingSecret) {
115
+ const timestamp = Math.floor(Date.now() / 1000);
116
+ own[exports.WEBHOOK_TIMESTAMP_HEADER] = String(timestamp);
117
+ own[exports.WEBHOOK_SIGNATURE_HEADER] = (0, exports.webhookSignatureOf)(this.settings.signingSecret, timestamp, body);
118
+ }
119
+ const given = mergeHeaders(this.settings.headers, request?.headers);
120
+ const headers = mergeHeaders({ 'Content-Type': 'application/json' }, Object.fromEntries(Object.entries(given).filter(([name]) => !OWN_HEADERS.includes(name.toLowerCase()))), own);
121
+ const result = await this.requestWithRetries({
122
+ url,
123
+ method: String(this.settings.method ?? 'POST').toUpperCase(),
124
+ headers,
125
+ body,
126
+ secrets: secretsOfHeaders(request?.headers),
127
+ });
128
+ if (result.didFail()) {
129
+ return result;
130
+ }
131
+ const reply = result.getDataFirst();
132
+ return api_helpers_1.OpResult.ok([{ status: reply?.status, body: reply?.body }]);
133
+ }
134
+ }
135
+ exports.HttpWebhookGw = 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,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SendGridGw = void 0;
4
+ // ./src/gateways/SendGridGw.ts
5
+ //
6
+ // Sends email through SendGrid's v3 Mail Send API (https://api.sendgrid.com/v3/mail/send) — plain text, HTML, or a
7
+ // dynamic template. No SDK: one REST call.
8
+ //
9
+ // const sendGrid = new SendGridGw().configure({ apiKey, fromEmail: 'alerts@brand.com', fromName: 'Brand' });
10
+ // const result = await sendGrid.sendEmail({ to: 'ops@brand.com', subject: 'Hello', text: 'Hi' });
11
+ //
12
+ // ⚠ The From address must be on a domain authenticated in that SendGrid account, or SendGrid refuses the mail.
13
+ const api_helpers_1 = require("@sdflc/api-helpers");
14
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
15
+ const SENDGRID_BASE_URL = 'https://api.sendgrid.com';
16
+ const addressOf = (one) => typeof one === 'string'
17
+ ? { email: one.trim() }
18
+ : { email: String(one?.email ?? '').trim(), ...(one?.name ? { name: one.name } : {}) };
19
+ const addressesOf = (many) => (Array.isArray(many) ? many : many ? [many] : []).map(addressOf);
20
+ /** A plausible email address (one @, something on each side, no spaces). */
21
+ const isEmail = (email) => /^[^\s@]+@[^\s@]+$/.test(email);
22
+ class SendGridGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
23
+ constructor(props) {
24
+ super({ baseUrl: SENDGRID_BASE_URL, ...(props ?? {}) });
25
+ }
26
+ validateSettings(settings) {
27
+ const problems = [];
28
+ if (!String(settings.apiKey ?? '').trim()) {
29
+ problems.push('the API key is missing');
30
+ }
31
+ if (settings.fromEmail !== undefined && settings.fromEmail !== '' && !String(settings.fromEmail).includes('@')) {
32
+ problems.push('the From address is not an email address');
33
+ }
34
+ return problems;
35
+ }
36
+ secretValues() {
37
+ return [String(this.settings.apiKey ?? '')];
38
+ }
39
+ /** ⚠ Not after a TIMEOUT: SendGrid may well have accepted the mail, and a retry sends it twice. */
40
+ shouldRetry(result) {
41
+ return result.getCode() !== api_helpers_1.OP_RESULT_CODES.TIMEOUT && super.shouldRetry(result);
42
+ }
43
+ errorMessageOf(reply) {
44
+ const errors = Array.isArray(reply.body?.errors) ? reply.body.errors : [];
45
+ return errors.length
46
+ ? errors
47
+ .map((e) => String(e?.message ?? ''))
48
+ .filter(Boolean)
49
+ .join('; ')
50
+ : super.errorMessageOf(reply);
51
+ }
52
+ /** Sends one email. OK with `{ messageId }` (SendGrid's `x-message-id`). Never throws. */
53
+ async sendEmail(email) {
54
+ if (!this.isConfigured()) {
55
+ return this.notConfigured();
56
+ }
57
+ const to = addressesOf(email?.to);
58
+ const cc = addressesOf(email?.cc);
59
+ const bcc = addressesOf(email?.bcc);
60
+ const from = email?.from
61
+ ? addressOf(email.from)
62
+ : this.settings.fromEmail
63
+ ? addressOf({ email: this.settings.fromEmail, name: this.settings.fromName })
64
+ : null;
65
+ const problems = [];
66
+ if (to.length === 0) {
67
+ problems.push('there is no recipient');
68
+ }
69
+ // ⚠ Refused, never dropped: silently leaving one address out sends a mail its sender believes reached them.
70
+ const malformed = [...to, ...cc, ...bcc].filter((one) => !isEmail(one.email));
71
+ if (malformed.length) {
72
+ problems.push(`${malformed.length} recipient address(es) are not email addresses`);
73
+ }
74
+ if (!from || !isEmail(from.email)) {
75
+ problems.push('there is no From address (configure fromEmail or pass from)');
76
+ }
77
+ if (!email?.templateId && !String(email?.subject ?? '').trim()) {
78
+ problems.push('there is no subject');
79
+ }
80
+ if (!email?.templateId && !email?.text && !email?.html) {
81
+ problems.push('there is no content (text, html or a template)');
82
+ }
83
+ if (problems.length) {
84
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, `The email cannot be sent: ${problems.join('; ')}`);
85
+ }
86
+ const replyTo = email.replyTo ? addressOf(email.replyTo) : null;
87
+ const content = [
88
+ ...(email.text ? [{ type: 'text/plain', value: email.text }] : []),
89
+ ...(email.html ? [{ type: 'text/html', value: email.html }] : []),
90
+ ];
91
+ const result = await this.requestWithRetries({
92
+ url: `${this.baseUrl}/v3/mail/send`,
93
+ headers: { Authorization: `Bearer ${this.settings.apiKey}` },
94
+ json: {
95
+ personalizations: [
96
+ {
97
+ to,
98
+ ...(cc.length ? { cc } : {}),
99
+ ...(bcc.length ? { bcc } : {}),
100
+ ...(email.dynamicTemplateData ? { dynamic_template_data: email.dynamicTemplateData } : {}),
101
+ },
102
+ ],
103
+ from,
104
+ ...(replyTo ? { reply_to: replyTo } : {}),
105
+ ...(email.subject ? { subject: email.subject } : {}),
106
+ ...(content.length ? { content } : {}),
107
+ ...(email.templateId ? { template_id: email.templateId } : {}),
108
+ ...(email.categories?.length ? { categories: email.categories } : {}),
109
+ ...(email.customArgs ? { custom_args: email.customArgs } : {}),
110
+ },
111
+ });
112
+ if (result.didFail()) {
113
+ return result;
114
+ }
115
+ const reply = result.getDataFirst();
116
+ return api_helpers_1.OpResult.ok([{ messageId: reply?.headers?.['x-message-id'] ?? null }]);
117
+ }
118
+ }
119
+ exports.SendGridGw = 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,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SlackWebhookGw = void 0;
4
+ // ./src/gateways/SlackWebhookGw.ts
5
+ //
6
+ // Posts a message to a Slack channel through an incoming webhook (https://api.slack.com/messaging/webhooks).
7
+ //
8
+ // const slack = new SlackWebhookGw().configure({ webhookUrl });
9
+ // const result = await slack.postMessage({ text: 'Hello' });
10
+ //
11
+ // ⚠ The webhook URL IS the credential — anyone holding it can post to the channel. It is scrubbed out of every error.
12
+ const api_helpers_1 = require("@sdflc/api-helpers");
13
+ const BaseExternalApiGateway_1 = require("./BaseExternalApiGateway");
14
+ /** Refusals that will not change on a retry. */
15
+ const PERMANENT_ERRORS = [
16
+ 'invalid_payload',
17
+ 'channel_not_found',
18
+ 'channel_is_archived',
19
+ 'action_prohibited',
20
+ 'posting_to_general_channel_denied',
21
+ 'no_service',
22
+ 'invalid_token',
23
+ ];
24
+ class SlackWebhookGw extends BaseExternalApiGateway_1.BaseExternalApiGateway {
25
+ constructor(props) {
26
+ super(props);
27
+ }
28
+ validateSettings(settings) {
29
+ return String(settings.webhookUrl ?? '')
30
+ .trim()
31
+ .startsWith('https://hooks.slack.com/')
32
+ ? []
33
+ : ['the webhook URL is missing or not a Slack one (https://hooks.slack.com/…)'];
34
+ }
35
+ secretValues() {
36
+ return [String(this.settings.webhookUrl ?? '').trim()];
37
+ }
38
+ shouldRetry(result) {
39
+ const said = String(result.getDataFirst()?.body ?? '').toLowerCase();
40
+ return !PERMANENT_ERRORS.some((one) => said.includes(one)) && super.shouldRetry(result);
41
+ }
42
+ /** Posts one message. OK with `{ messageId: null }` (Slack's webhook answers none). Never throws. */
43
+ async postMessage(message) {
44
+ if (!this.isConfigured()) {
45
+ return this.notConfigured();
46
+ }
47
+ if (!String(message?.text ?? '').trim()) {
48
+ return api_helpers_1.OpResult.fail(api_helpers_1.OP_RESULT_CODES.VALIDATION_FAILED, null, 'The message is empty');
49
+ }
50
+ const result = await this.requestWithRetries({
51
+ url: String(this.settings.webhookUrl).trim(),
52
+ json: {
53
+ text: message.text,
54
+ ...(message.blocks ? { blocks: message.blocks } : {}),
55
+ ...(message.attachments ? { attachments: message.attachments } : {}),
56
+ },
57
+ });
58
+ // Slack's webhook answers no message id: the same shape as the other gateways, with none in it.
59
+ return result.didFail() ? result : api_helpers_1.OpResult.ok([{ messageId: null }]);
60
+ }
61
+ }
62
+ exports.SlackWebhookGw = 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 };