@sdflc/backend-helpers 1.0.139 → 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 (56) hide show
  1. package/README.md +176 -20
  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,319 @@
1
+ // ./src/gateways/BaseExternalApiGateway.ts
2
+ //
3
+ // The base of every gateway to an outside service (SendGrid, Telegram, Twilio, Slack, Discord, an HTTP webhook, Stripe…).
4
+ //
5
+ // ONE way to set a gateway up: `configure(settings)`. A gateway is created ONCE and configured — and re-configured — at
6
+ // run time: per brand, per tenant, per request. `configure` REPLACES the settings (never merges), so a gateway
7
+ // re-pointed at another tenant never keeps a value of the last one.
8
+ //
9
+ // ONE way to answer: every public operation returns an `OpResult` and never throws. An HTTP refusal maps onto the
10
+ // standard codes (401 → UNAUTHORIZED, 404 → NOT_FOUND, 429 → TOO_MANY_REQUESTS, 5xx → FAILED, no answer →
11
+ // NETWORK_ERROR / TIMEOUT), so `result.isRetryableError()` and friends mean the same thing for every gateway.
12
+ //
13
+ // ⚠ Secrets (API keys, bot tokens, webhook URLs) never leave in an error: every message is scrubbed of the values the
14
+ // gateway names in `secretValues()`.
15
+ import check from 'check-types';
16
+ import { Buffer } from 'buffer';
17
+ import { setTimeout as sleep } from 'timers/promises';
18
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
19
+ import { Logger, LoggerLevels, isLogger } from '@sdflc/utils';
20
+ const DEFAULT_TIMEOUT_MS = 10_000;
21
+ const DEFAULT_RETRY_DELAYS_MS = [1000, 2000];
22
+ /** The most of a reply that is read: a hostile receiver must not be able to stream until memory runs out. */
23
+ export const MAX_REPLY_BYTES = 64 * 1024;
24
+ /** The longest wait a `Retry-After` may ask for and still be retried — longer, and the failure is returned at once. */
25
+ export const MAX_RETRY_WAIT_MS = 10_000;
26
+ /** A secret shorter than this is not scrubbed (it would garble ordinary words). */
27
+ const MIN_SECRET_LENGTH = 4;
28
+ /** The standard OpResult code for an HTTP status that is not a success. Pure. */
29
+ export const opResultCodeOfHttpStatus = (status) => {
30
+ if (status === 401) {
31
+ return OP_RESULT_CODES.UNAUTHORIZED;
32
+ }
33
+ if (status === 403) {
34
+ return OP_RESULT_CODES.FORBIDDEN;
35
+ }
36
+ if (status === 404) {
37
+ return OP_RESULT_CODES.NOT_FOUND;
38
+ }
39
+ if (status === 408) {
40
+ return OP_RESULT_CODES.TIMEOUT;
41
+ }
42
+ if (status === 409) {
43
+ return OP_RESULT_CODES.CONFLICT;
44
+ }
45
+ if (status === 429) {
46
+ return OP_RESULT_CODES.TOO_MANY_REQUESTS;
47
+ }
48
+ if (status >= 500) {
49
+ return OP_RESULT_CODES.FAILED;
50
+ }
51
+ // Any other refusal (400, 405, 413, 422 …, or a redirect that was not followed) is about the request itself.
52
+ return OP_RESULT_CODES.VALIDATION_FAILED;
53
+ };
54
+ class BaseExternalApiGateway {
55
+ logger;
56
+ baseUrl;
57
+ timeoutMs;
58
+ retries;
59
+ retryDelaysMs;
60
+ fetchImpl;
61
+ _settings = {};
62
+ _credentials = null;
63
+ _credentialsSet = false;
64
+ constructor(props) {
65
+ const { settings, credentials, baseUrl, timeoutMs, retries, retryDelaysMs, fetch, logger } = props || {};
66
+ this.baseUrl = baseUrl ?? '';
67
+ this.timeoutMs = timeoutMs ?? DEFAULT_TIMEOUT_MS;
68
+ this.retries = Math.max(0, retries ?? 2);
69
+ this.retryDelaysMs = retryDelaysMs?.length ? retryDelaysMs : DEFAULT_RETRY_DELAYS_MS;
70
+ this.fetchImpl = fetch ?? ((url, init) => globalThis.fetch(url, init));
71
+ this.logger = isLogger(logger) ? logger : new Logger({ level: LoggerLevels.ERROR });
72
+ if (credentials !== undefined) {
73
+ this.setCredentials(credentials);
74
+ }
75
+ if (settings !== undefined) {
76
+ this.configure(settings);
77
+ }
78
+ }
79
+ // ─── Settings ──────────────────────────────────────────────────────────────
80
+ /**
81
+ * Sets the gateway up. REPLACES whatever was set before (never merges), so re-pointing a shared instance at another
82
+ * tenant keeps nothing of the last one. Never throws: a setting that is missing or malformed is reported by
83
+ * `getConfigProblems()`, and every operation refuses with VALIDATION_FAILED until it is fixed.
84
+ */
85
+ configure(settings) {
86
+ this._settings = { ...(settings ?? {}) };
87
+ this.onConfigured();
88
+ return this;
89
+ }
90
+ /** What is missing or malformed in the settings, in words — never a value. Empty when the gateway can be used. */
91
+ getConfigProblems() {
92
+ return this.validateSettings(this._settings);
93
+ }
94
+ /** True when the settings are complete and well-formed. */
95
+ isConfigured() {
96
+ return this.getConfigProblems().length === 0;
97
+ }
98
+ /** The current settings. ⚠ They hold secrets: for the gateway itself, never to be logged or returned. */
99
+ get settings() {
100
+ return this._settings;
101
+ }
102
+ /** What is wrong with these settings (override per gateway). */
103
+ validateSettings(_settings) {
104
+ return [];
105
+ }
106
+ /** The values to scrub out of every error message (override per gateway: keys, tokens, secret URLs). */
107
+ secretValues() {
108
+ return [];
109
+ }
110
+ /** Called after every `configure` (override to rebuild an SDK client). */
111
+ onConfigured() {
112
+ // no-op
113
+ }
114
+ /** The refusal every operation answers while the gateway is not set up. */
115
+ notConfigured() {
116
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `${this.constructor.name} is not configured: ${this.getConfigProblems().join('; ')}`);
117
+ }
118
+ // ─── Requests ──────────────────────────────────────────────────────────────
119
+ /** `text` with every secret of this gateway (and `extra`) replaced by `***`. */
120
+ scrub(text, extra = []) {
121
+ let out = String(text ?? '');
122
+ // Longest first: a secret that contains another must be replaced whole.
123
+ const secrets = [...this.secretValues(), ...extra]
124
+ .map((one) => String(one ?? ''))
125
+ .filter((one) => one.length >= MIN_SECRET_LENGTH)
126
+ .sort((a, b) => b.length - a.length);
127
+ for (const secret of secrets) {
128
+ out = out.split(secret).join('***');
129
+ }
130
+ return out;
131
+ }
132
+ /** `value` (a string, or anything JSON) with every secret replaced by `***`. */
133
+ scrubValue(value, extra = []) {
134
+ if (value === null || value === undefined) {
135
+ return value;
136
+ }
137
+ if (typeof value === 'string') {
138
+ return this.scrub(value, extra);
139
+ }
140
+ try {
141
+ return JSON.parse(this.scrub(JSON.stringify(value), extra));
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ /** The words of a refusal, from the service's answer (override per gateway for its error shape). */
148
+ errorMessageOf(reply) {
149
+ const body = reply.body;
150
+ if (typeof body === 'string') {
151
+ return body.slice(0, 500);
152
+ }
153
+ return String(body?.message ?? body?.error ?? body?.description ?? `HTTP ${reply.status}`).slice(0, 500);
154
+ }
155
+ /** Whether a failed attempt is worth repeating (override per gateway to refuse the hopeless ones). */
156
+ shouldRetry(result) {
157
+ return result.isRetryableError() || result.getCode() === OP_RESULT_CODES.TOO_MANY_REQUESTS;
158
+ }
159
+ /** How long the service asked us to wait before trying again, in ms (its `Retry-After`), or null. */
160
+ retryAfterMs(result) {
161
+ const raw = String(result.getDataFirst()?.headers?.['retry-after'] ?? '').trim();
162
+ if (!raw) {
163
+ return null;
164
+ }
165
+ if (/^\d+$/.test(raw)) {
166
+ return Number(raw) * 1000;
167
+ }
168
+ const at = Date.parse(raw);
169
+ return Number.isFinite(at) ? Math.max(0, at - Date.now()) : null;
170
+ }
171
+ /**
172
+ * ONE attempt. OK with `{status, headers, body}` for a 2xx; else the standard code for the status (with the same data,
173
+ * so a gateway can read the service's own error), NETWORK_ERROR or TIMEOUT when nothing answered, VALIDATION_FAILED
174
+ * when the request itself could not be made (a malformed header). The reply is scrubbed and capped. Never throws.
175
+ * Redirects are not followed.
176
+ */
177
+ async request(req) {
178
+ const extra = req.secrets ?? [];
179
+ const headers = { ...(req.headers ?? {}) };
180
+ const hasHeader = (name) => Object.keys(headers).some((key) => key.toLowerCase() === name);
181
+ let body = req.body;
182
+ if (body === undefined && req.json !== undefined) {
183
+ body = JSON.stringify(req.json);
184
+ if (!hasHeader('content-type')) {
185
+ headers['Content-Type'] = 'application/json';
186
+ }
187
+ }
188
+ try {
189
+ const response = await this.fetchImpl(req.url, {
190
+ method: req.method ?? 'POST',
191
+ headers,
192
+ body,
193
+ // ⚠ Not followed: a redirect is where an allowed address hands the request to one that is not.
194
+ redirect: 'manual',
195
+ signal: AbortSignal.timeout(req.timeoutMs ?? this.timeoutMs),
196
+ });
197
+ const text = await readCapped(response, MAX_REPLY_BYTES).catch(() => '');
198
+ let parsed = text || null;
199
+ try {
200
+ parsed = text ? JSON.parse(text) : null;
201
+ }
202
+ catch {
203
+ // Not JSON: keep the text.
204
+ }
205
+ const replyHeaders = headersOf(response.headers);
206
+ delete replyHeaders['set-cookie'];
207
+ const reply = {
208
+ status: Number(response.status),
209
+ headers: this.scrubValue(replyHeaders, extra) ?? {},
210
+ body: this.scrubValue(parsed, extra),
211
+ };
212
+ if (reply.status >= 200 && reply.status < 300) {
213
+ return OpResult.ok([reply]);
214
+ }
215
+ return OpResult.fail(opResultCodeOfHttpStatus(reply.status), [reply], this.scrub(`[${reply.status}] ${this.errorMessageOf(reply)}`, extra));
216
+ }
217
+ catch (e) {
218
+ const timedOut = e?.name === 'TimeoutError' || e?.name === 'AbortError';
219
+ // A request that could not even be made (a malformed header, a refused address) will not be fixed by a retry.
220
+ const malformed = e?.code === 'EBLOCKED' || (e instanceof TypeError && e.message !== 'fetch failed');
221
+ const why = timedOut
222
+ ? `no answer within ${req.timeoutMs ?? this.timeoutMs} ms`
223
+ : String(e?.cause?.message ?? e?.message ?? e);
224
+ const code = timedOut
225
+ ? OP_RESULT_CODES.TIMEOUT
226
+ : malformed
227
+ ? OP_RESULT_CODES.VALIDATION_FAILED
228
+ : OP_RESULT_CODES.NETWORK_ERROR;
229
+ return OpResult.fail(code, null, this.scrub(why, extra).slice(0, 500));
230
+ }
231
+ }
232
+ /**
233
+ * `request`, repeated while `shouldRetry` says a failure is worth it — after the service's `Retry-After` when it gave
234
+ * one (and not at all when it asks for longer than MAX_RETRY_WAIT_MS), else after the configured waits. Never throws.
235
+ */
236
+ async requestWithRetries(req) {
237
+ let result = await this.request(req);
238
+ for (let attempt = 1; attempt <= this.retries && result.didFail() && this.shouldRetry(result); attempt++) {
239
+ const asked = this.retryAfterMs(result);
240
+ if (asked !== null && asked > MAX_RETRY_WAIT_MS) {
241
+ break;
242
+ }
243
+ this.logger.debug(`${this.constructor.name}: attempt ${attempt} failed (${result.getErrorSummary('')}), retrying`);
244
+ await sleep(asked ?? this.retryDelaysMs[Math.min(attempt - 1, this.retryDelaysMs.length - 1)]);
245
+ result = await this.request(req);
246
+ }
247
+ return result;
248
+ }
249
+ // ─── Credentials (kept for gateways written before configure()) ───────────
250
+ setCredentials(credentials) {
251
+ if (!check.string(credentials) && !check.object(credentials)) {
252
+ throw new Error(`${this.constructor.name}.setCredentials: credentials must be a string or an object`);
253
+ }
254
+ if (check.string(credentials) && !credentials.trim()) {
255
+ throw new Error(`${this.constructor.name}.setCredentials: credentials string must not be empty`);
256
+ }
257
+ this._credentials = credentials;
258
+ this._credentialsSet = true;
259
+ this.onCredentialsSet();
260
+ return this;
261
+ }
262
+ hasCredentials() {
263
+ return this._credentialsSet;
264
+ }
265
+ get credentials() {
266
+ return this._credentials;
267
+ }
268
+ assertCredentials() {
269
+ if (!this._credentialsSet) {
270
+ throw new Error(`${this.constructor.name}: credentials have not been set. ` + `Call setCredentials() before making API calls.`);
271
+ }
272
+ }
273
+ onCredentialsSet() {
274
+ // no-op — override in subclass to initialise SDK clients etc.
275
+ }
276
+ }
277
+ /**
278
+ * A reply's text, at most `max` bytes: read through the stream and cancelled at the cap (a body without a stream is read
279
+ * whole and cut).
280
+ */
281
+ const readCapped = async (response, max) => {
282
+ const reader = response?.body?.getReader?.();
283
+ if (!reader) {
284
+ return String((await response.text()) ?? '').slice(0, max);
285
+ }
286
+ const chunks = [];
287
+ let size = 0;
288
+ for (;;) {
289
+ const { done, value } = await reader.read();
290
+ if (done) {
291
+ break;
292
+ }
293
+ const chunk = Buffer.from(value);
294
+ if (size + chunk.length > max) {
295
+ chunks.push(chunk.subarray(0, max - size));
296
+ await reader.cancel().catch(() => null);
297
+ break;
298
+ }
299
+ chunks.push(chunk);
300
+ size += chunk.length;
301
+ }
302
+ return Buffer.concat(chunks).toString('utf8');
303
+ };
304
+ /** A fetch Headers object (or a plain one) as a lower-cased record. */
305
+ const headersOf = (headers) => {
306
+ const out = {};
307
+ if (headers && typeof headers.forEach === 'function') {
308
+ headers.forEach((value, key) => {
309
+ out[String(key).toLowerCase()] = String(value);
310
+ });
311
+ }
312
+ else if (headers && typeof headers === 'object') {
313
+ for (const [key, value] of Object.entries(headers)) {
314
+ out[key.toLowerCase()] = String(value);
315
+ }
316
+ }
317
+ return out;
318
+ };
319
+ export { BaseExternalApiGateway };
@@ -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,70 @@
1
+ // ./src/gateways/DiscordWebhookGw.ts
2
+ //
3
+ // Posts a message to a Discord channel through a webhook (https://discord.com/developers/docs/resources/webhook).
4
+ //
5
+ // const discord = new DiscordWebhookGw().configure({ webhookUrl, username: 'Alerts' });
6
+ // const result = await discord.postMessage({ content: '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
+ // ⚠ Mentions are OFF unless asked for (`allowedMentions`): a text that happens to contain @everyone must not ping a server.
10
+ import { OP_RESULT_CODES, OpResult } from '@sdflc/api-helpers';
11
+ import { BaseExternalApiGateway } from './BaseExternalApiGateway';
12
+ export const DISCORD_MAX_CONTENT_LENGTH = 2000;
13
+ export const DISCORD_MAX_EMBEDS = 10;
14
+ const WEBHOOK_PREFIXES = ['https://discord.com/api/webhooks/', 'https://discordapp.com/api/webhooks/'];
15
+ /** Discord error codes that will not change on a retry: an unknown webhook, a bad webhook token. */
16
+ const PERMANENT_CODES = [10015, 50027];
17
+ class DiscordWebhookGw extends BaseExternalApiGateway {
18
+ constructor(props) {
19
+ super(props);
20
+ }
21
+ validateSettings(settings) {
22
+ const url = String(settings.webhookUrl ?? '').trim();
23
+ return WEBHOOK_PREFIXES.some((prefix) => url.startsWith(prefix))
24
+ ? []
25
+ : ['the webhook URL is missing or not a Discord one (https://discord.com/api/webhooks/…)'];
26
+ }
27
+ secretValues() {
28
+ return [String(this.settings.webhookUrl ?? '').trim()];
29
+ }
30
+ shouldRetry(result) {
31
+ const code = Number(result.getDataFirst()?.body?.code);
32
+ return !PERMANENT_CODES.includes(code) && super.shouldRetry(result);
33
+ }
34
+ /** Posts one message. OK with `{ messageId }`. Never throws. */
35
+ async postMessage(message) {
36
+ if (!this.isConfigured()) {
37
+ return this.notConfigured();
38
+ }
39
+ const content = String(message?.content ?? '');
40
+ const embeds = Array.isArray(message?.embeds) ? message.embeds : [];
41
+ if (!content.trim() && embeds.length === 0) {
42
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, 'The message is empty (no content and no embeds)');
43
+ }
44
+ if (content.length > DISCORD_MAX_CONTENT_LENGTH) {
45
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `The message is ${content.length} characters; Discord allows ${DISCORD_MAX_CONTENT_LENGTH}`);
46
+ }
47
+ if (embeds.length > DISCORD_MAX_EMBEDS) {
48
+ return OpResult.fail(OP_RESULT_CODES.VALIDATION_FAILED, null, `${embeds.length} embeds; Discord allows ${DISCORD_MAX_EMBEDS}`);
49
+ }
50
+ const username = message.username ?? this.settings.username;
51
+ const avatarUrl = message.avatarUrl ?? this.settings.avatarUrl;
52
+ const url = String(this.settings.webhookUrl).trim();
53
+ // `wait=true` makes Discord answer with the message (and its id) instead of an empty 204.
54
+ const result = await this.requestWithRetries({
55
+ url: `${url}${url.includes('?') ? '&' : '?'}wait=true`,
56
+ json: {
57
+ ...(content ? { content } : {}),
58
+ ...(embeds.length ? { embeds } : {}),
59
+ ...(username ? { username } : {}),
60
+ ...(avatarUrl ? { avatar_url: avatarUrl } : {}),
61
+ allowed_mentions: message.allowedMentions ?? { parse: [] },
62
+ },
63
+ });
64
+ if (result.didFail()) {
65
+ return result;
66
+ }
67
+ return OpResult.ok([{ messageId: result.getDataFirst()?.body?.id ?? null }]);
68
+ }
69
+ }
70
+ export { 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,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 };