@corbit2/node-red-corbit-sms 1.0.0 → 1.0.2

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.
@@ -1,428 +1,449 @@
1
- 'use strict';
2
-
3
- // Plain helpers for the Corbit SMS API. They do not depend on Node-RED, so they
4
- // can be tested on their own.
5
-
6
- const DEFAULT_BASE_URL = 'https://api.corbit.sa';
7
- const MAX_MESSAGE_LENGTH = 1600;
8
- const MAX_IDEMPOTENCY_KEY_LENGTH = 255;
9
- const REQUEST_TIMEOUT_MS = 30000;
10
-
11
- /** An error with a short message for the user and an optional hint and API code. */
12
- class CorbitError extends Error {
13
- constructor(message, extra = {}) {
14
- super(message);
15
- this.name = 'CorbitError';
16
- if (extra.hint) this.hint = extra.hint;
17
- if (extra.code) this.code = extra.code;
18
- if (extra.statusCode) this.statusCode = extra.statusCode;
19
- if (extra.retryAfter) this.retryAfter = extra.retryAfter;
20
- }
21
- }
22
-
23
- /**
24
- * Turns a phone number into the digits-only international format the API expects.
25
- * Accepts "+966 50 123 4567", "00966501234567", "966501234567", "+966 (0)50 123 4567",
26
- * Arabic-Indic digits, and the Saudi local forms "0501234567" and "501234567".
27
- * Anything that could turn into a wrong number is rejected instead of guessed:
28
- * local numbers of other countries, decimals, "9.66501E+11", "ext 12".
29
- * Returns undefined when the number cannot be used.
30
- */
31
- function normalizeNumber(raw) {
32
- let text;
33
- if (typeof raw === 'number') {
34
- if (!Number.isSafeInteger(raw) || raw <= 0) return undefined;
35
- text = String(raw);
36
- } else if (typeof raw === 'string') {
37
- text = raw
38
- .trim()
39
- .replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660))
40
- .replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06f0));
41
- } else {
42
- return undefined;
43
- }
44
- if (!/^\+?[\d\s\-()]+$/.test(text)) return undefined;
45
- let digits = text.replace(/\D/g, '');
46
- if (text.startsWith('+')) {
47
- // Already international.
48
- } else if (digits.startsWith('00')) {
49
- digits = digits.slice(2);
50
- } else if (/^05\d{8}$/.test(digits)) {
51
- digits = '966' + digits.slice(1);
52
- } else if (/^5\d{8}$/.test(digits)) {
53
- digits = '966' + digits;
54
- } else if (digits.startsWith('0')) {
55
- return undefined;
56
- }
57
- // "+966 (0)50 …": drop the trunk zero after the Saudi country code.
58
- if (/^9660\d{9}$/.test(digits)) digits = '966' + digits.slice(4);
59
- return /^[1-9]\d{7,14}$/.test(digits) ? digits : undefined;
60
- }
61
-
62
- /** Splits a list given as text (commas, semicolons or new lines) or as an array. */
63
- function splitNumbers(value) {
64
- if (Array.isArray(value)) return value.flatMap((v) => splitNumbers(v));
65
- if (value === null || value === undefined) return [];
66
- if (typeof value === 'number') return [value];
67
- return String(value)
68
- .split(/[,;\r\n]+/)
69
- .map((v) => v.trim())
70
- .filter((v) => v !== '');
71
- }
72
-
73
- /** Checks the SMS text and returns it as a string (numbers, e.g. an OTP, are converted). */
74
- function checkMessage(raw) {
75
- if (raw !== null && raw !== undefined && typeof raw === 'object') {
76
- throw new CorbitError('The message must be text, not an object', {
77
- hint: 'Set the Message field to the text of the SMS, or put the text in msg.payload.',
78
- });
79
- }
80
- const message = raw === null || raw === undefined ? '' : String(raw);
81
- if (message.trim() === '') {
82
- throw new CorbitError('The message is empty', { hint: 'Put the text of the SMS in msg.payload or in the Message field.' });
83
- }
84
- if (message.length > MAX_MESSAGE_LENGTH) {
85
- throw new CorbitError(`The message is ${message.length} characters; the limit is ${MAX_MESSAGE_LENGTH}`);
86
- }
87
- return message;
88
- }
89
-
90
- const CODE_HINTS = {
91
- INSUFFICIENT_BALANCE: 'Your Corbit SMS balance is not enough. Top up at sms.corbit.sa and try again.',
92
- SENDER_NOT_ALLOWED: 'This sender name is not approved on your account. Pick one from the Sender list.',
93
- DUPLICATE:
94
- 'The same text was sent to the same number within the last hour. Tick "Allow duplicate" (or set msg.allowDuplicate = true) to send it again on purpose.',
95
- IDEMPOTENCY_IN_PROGRESS: 'A request with the same idempotency key is still being processed. Wait a moment and try again.',
96
- IDEMPOTENCY_KEY_REUSED:
97
- 'This idempotency key was already used for a different message. Use a key that is different for each message.',
98
- };
99
-
100
- /** Builds a CorbitError from an API error response. */
101
- function errorFromResponse(statusCode, body, headers = {}) {
102
- const apiMessage = body && typeof body.message === 'string' && body.message ? body.message.slice(0, 300) : '';
103
- const code = body && typeof body.code === 'string' ? body.code : '';
104
- let hint = code ? CODE_HINTS[code] : undefined;
105
- let retryAfter;
106
- if (statusCode === 401) {
107
- hint = 'The API token was rejected. Check the API token in the Corbit SMS account settings of this node.';
108
- } else if (statusCode === 429 || code === 'RATE_LIMIT') {
109
- retryAfter = headers['retry-after'];
110
- hint = `Too many requests.${retryAfter ? ` Try again in ${retryAfter} seconds.` : ''}`;
111
- }
112
- return new CorbitError(apiMessage || `Corbit SMS returned HTTP ${statusCode}`, {
113
- hint,
114
- code: code || undefined,
115
- statusCode,
116
- retryAfter,
117
- });
118
- }
119
-
120
- /**
121
- * Checks the base URL. HTTPS is required, except for a server on this machine
122
- * (useful for testing), so the token is never sent in clear text over the network.
123
- */
124
- function cleanBaseUrl(baseUrl) {
125
- const text = String(baseUrl || DEFAULT_BASE_URL).trim().replace(/\/+$/, '');
126
- let url;
127
- try {
128
- url = new URL(text);
129
- } catch {
130
- url = undefined;
131
- }
132
- const local = url && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
133
- if (!url || !(url.protocol === 'https:' || (url.protocol === 'http:' && local)) || url.username || url.password) {
134
- throw new CorbitError(`The base URL is not valid: "${text}"`, { hint: `Use ${DEFAULT_BASE_URL}.` });
135
- }
136
- return text;
137
- }
138
-
139
- /** Header values must be printable ASCII; a pasted token with a line break would otherwise end up in error messages. */
140
- function checkToken(token) {
141
- const value = token === null || token === undefined ? '' : String(token).trim();
142
- if (value === '') {
143
- throw new CorbitError('The API token is missing', {
144
- hint: 'Open the Corbit SMS account settings of this node and paste your API token from sms.corbit.sa.',
145
- });
146
- }
147
- if (!/^[\x21-\x7e]+$/.test(value)) {
148
- throw new CorbitError('The API token contains spaces, line breaks or other characters that are not allowed', {
149
- hint: 'Copy the API token again from sms.corbit.sa and paste it into the Corbit SMS account settings.',
150
- });
151
- }
152
- return value;
153
- }
154
-
155
- /**
156
- * Calls the Corbit SMS API. Returns the parsed body, or throws a CorbitError with
157
- * the API's own message when the call fails. `signal` cancels the call (e.g. on redeploy);
158
- * `sends` marks calls that send SMS, so a timeout warns that the SMS may have gone out.
159
- */
160
- async function apiRequest({ token, baseUrl, method, path, body, query, headers = {}, signal, sends = false, fetchImpl, timeoutMs = REQUEST_TIMEOUT_MS }) {
161
- const doFetch = fetchImpl || globalThis.fetch;
162
- if (typeof doFetch !== 'function') {
163
- throw new CorbitError('This Node.js version has no fetch()', { hint: 'Run Node-RED on Node.js 18 or later.' });
164
- }
165
- const cleanToken = checkToken(token);
166
- let url = cleanBaseUrl(baseUrl) + path;
167
- if (query) {
168
- const qs = new URLSearchParams();
169
- for (const [k, v] of Object.entries(query)) if (v !== undefined) qs.set(k, String(v));
170
- url += (url.includes('?') ? '&' : '?') + qs.toString();
171
- }
172
-
173
- const controller = new AbortController();
174
- let timedOut = false;
175
- const timer = setTimeout(() => {
176
- timedOut = true;
177
- controller.abort();
178
- }, timeoutMs);
179
- const onAbort = () => controller.abort();
180
- if (signal) {
181
- if (signal.aborted) controller.abort();
182
- else signal.addEventListener('abort', onAbort, { once: true });
183
- }
184
-
185
- const init = {
186
- method,
187
- headers: { Accept: 'application/json', Authorization: `Bearer ${cleanToken}`, ...headers },
188
- signal: controller.signal,
189
- };
190
- if (body !== undefined) {
191
- init.body = JSON.stringify(body);
192
- init.headers['Content-Type'] = 'application/json';
193
- }
194
-
195
- let response;
196
- let text;
197
- try {
198
- response = await doFetch(url, init);
199
- text = await response.text();
200
- } catch (error) {
201
- if (timedOut) {
202
- throw new CorbitError(
203
- sends ? `No reply from Corbit SMS within ${Math.round(timeoutMs / 1000)} seconds; the SMS may have been sent` : `No reply from Corbit SMS within ${Math.round(timeoutMs / 1000)} seconds`,
204
- {
205
- hint: sends
206
- ? 'Check the message status or your Corbit SMS account before you send again, so the SMS is not sent twice.'
207
- : 'Try again later.',
208
- },
209
- );
210
- }
211
- if (controller.signal.aborted) throw new CorbitError('The request was cancelled');
212
- // Never put the error text itself in the message: it can contain header values.
213
- const code = error && error.cause && typeof error.cause.code === 'string' ? error.cause.code : 'network error';
214
- throw new CorbitError(`Could not reach Corbit SMS (${code})`, {
215
- hint: 'Check the internet connection of the Node-RED server and the base URL.',
216
- });
217
- } finally {
218
- clearTimeout(timer);
219
- if (signal) signal.removeEventListener('abort', onAbort);
220
- }
221
-
222
- let data;
223
- try {
224
- data = text ? JSON.parse(text) : {};
225
- } catch {
226
- data = {};
227
- }
228
- const parsed = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
229
- const responseHeaders = {};
230
- if (response.headers && typeof response.headers.forEach === 'function') {
231
- response.headers.forEach((v, k) => {
232
- responseHeaders[k.toLowerCase()] = v;
233
- });
234
- }
235
- if (response.status >= 400 || parsed.status === 'Error') {
236
- throw errorFromResponse(response.status, parsed, responseHeaders);
237
- }
238
- if (Array.isArray(data)) return { data };
239
- return parsed;
240
- }
241
-
242
- /**
243
- * Reads the sender names page by page. Stops after `maxItems` names when given,
244
- * when the last page is reached, or when the API keeps returning the same page.
245
- */
246
- async function getAllSenderNames(conn, maxItems) {
247
- const perPage = 50;
248
- const all = [];
249
- let previousFirst;
250
- for (let page = 1; page <= 100; page++) {
251
- const response = await apiRequest({ ...conn, method: 'GET', path: '/api/v1/sendernames', query: { per_page: perPage, page } });
252
- const items = Array.isArray(response.data) ? response.data : [];
253
- if (items.length === 0) break;
254
- const first = JSON.stringify(items[0]);
255
- if (page > 1 && first === previousFirst) break;
256
- previousFirst = first;
257
- all.push(...items);
258
- if (maxItems !== undefined && all.length >= maxItems) break;
259
- const pagination = response.pagination || {};
260
- const total = Number(pagination.total);
261
- const currentPage = Number(pagination.current_page);
262
- const pageSize = Number(pagination.per_page) || perPage;
263
- if (Number.isFinite(total) && all.length >= total) break;
264
- if (!Number.isFinite(total) && items.length < pageSize) break;
265
- if (Number.isFinite(currentPage) && currentPage !== page) break;
266
- }
267
- return maxItems === undefined ? all : all.slice(0, maxItems);
268
- }
269
-
270
- /** Approved sender names, sorted, for the editor list. */
271
- async function approvedSenderNames(conn) {
272
- const all = await getAllSenderNames(conn);
273
- return [...new Set(all.filter((s) => String(s.status).toLowerCase() === 'approved').map((s) => String(s.name)))].sort((a, b) =>
274
- a.localeCompare(b),
275
- );
276
- }
277
-
278
- function sendHeaders({ idempotencyKey, allowDuplicate }) {
279
- const headers = {};
280
- if (idempotencyKey !== undefined && idempotencyKey !== null && String(idempotencyKey) !== '') {
281
- if (typeof idempotencyKey === 'object') {
282
- throw new CorbitError('The idempotency key must be text, not an object');
283
- }
284
- const key = String(idempotencyKey);
285
- if (key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
286
- throw new CorbitError(`The idempotency key is ${key.length} characters; the limit is ${MAX_IDEMPOTENCY_KEY_LENGTH}`);
287
- }
288
- if (!/^[\x20-\x7e]+$/.test(key)) {
289
- throw new CorbitError('The idempotency key may only contain English letters, digits and symbols', {
290
- hint: 'Use an ID such as an order number.',
291
- });
292
- }
293
- headers['Idempotency-Key'] = key;
294
- }
295
- if (allowDuplicate === true) headers['X-Allow-Duplicate'] = 'true';
296
- return headers;
297
- }
298
-
299
- function checkSender(raw) {
300
- const sender = raw === null || raw === undefined || typeof raw === 'object' ? '' : String(raw).trim();
301
- if (sender === '') {
302
- throw new CorbitError('No sender name', { hint: 'Choose an approved sender name in the node, or set msg.sender.' });
303
- }
304
- return sender;
305
- }
306
-
307
- function describe(value) {
308
- if (value === undefined || value === null) return '';
309
- return typeof value === 'object' ? JSON.stringify(value).slice(0, 60) : String(value).slice(0, 60);
310
- }
311
-
312
- /** Sends one SMS. Returns { messageId, status, to, senderName }. */
313
- async function sendSms(conn, { sender, to, message, idempotencyKey, allowDuplicate }) {
314
- const senderName = checkSender(sender);
315
- const number = normalizeNumber(to);
316
- if (!number) {
317
- throw new CorbitError(`The mobile number is not valid: "${describe(to)}"`, {
318
- hint: 'Use the international format, e.g. 966501234567. Saudi local numbers (05XXXXXXXX) are converted automatically.',
319
- });
320
- }
321
- const messageBody = checkMessage(message);
322
- const headers = sendHeaders({ idempotencyKey, allowDuplicate });
323
- const response = await apiRequest({
324
- ...conn,
325
- method: 'POST',
326
- path: '/api/v1/send',
327
- body: { senderName, number, messageBody, sendAtOption: 'NOW' },
328
- headers,
329
- sends: true,
330
- });
331
- const sent = (response.data && response.data.message) || {};
332
- return { messageId: sent.id, status: sent.status, to: number, senderName };
333
- }
334
-
335
- /** Sends the same SMS to many numbers. Returns { messageId, status, recipients, numbers, senderName }. */
336
- async function sendBulkSms(conn, { sender, numbers: rawNumbers, message, idempotencyKey, allowDuplicate }) {
337
- const senderName = checkSender(sender);
338
- const raw = splitNumbers(rawNumbers);
339
- const invalid = raw.filter((n) => !normalizeNumber(n)).map(describe);
340
- if (invalid.length > 0) {
341
- throw new CorbitError(
342
- `Invalid mobile numbers: ${invalid.slice(0, 5).join(', ')}${invalid.length > 5 ? ` and ${invalid.length - 5} more` : ''}`,
343
- {
344
- hint: 'Use the international format, e.g. 966501234567. Corbit SMS rejects the whole request if any number is invalid, so nothing was sent.',
345
- },
346
- );
347
- }
348
- const numbers = [...new Set(raw.map((n) => normalizeNumber(n)))];
349
- if (numbers.length === 0) {
350
- throw new CorbitError('The list of numbers is empty', { hint: 'Put the numbers in msg.numbers (an array or comma-separated text) or in the Numbers field.' });
351
- }
352
- const messageBody = checkMessage(message);
353
- const headers = sendHeaders({ idempotencyKey, allowDuplicate });
354
- const response = await apiRequest({
355
- ...conn,
356
- method: 'POST',
357
- path: '/api/v1/send-bulk',
358
- body: { senderName, numbers, messageBody, sendAtOption: 'Now' },
359
- headers,
360
- sends: true,
361
- });
362
- const sent = (response.data && response.data.message) || {};
363
- return { messageId: sent.id, status: sent.status, recipients: numbers.length, numbers, senderName };
364
- }
365
-
366
- function checkMessageId(raw) {
367
- const id = raw === null || raw === undefined || typeof raw === 'object' ? '' : String(raw).trim();
368
- if (id === '') {
369
- throw new CorbitError('The message ID is empty', { hint: 'Use the messageId returned by a send, e.g. msg.payload.messageId.' });
370
- }
371
- return id;
372
- }
373
-
374
- /** Returns { messageId, status }. */
375
- async function getStatus(conn, messageId) {
376
- const id = checkMessageId(messageId);
377
- const response = await apiRequest({ ...conn, method: 'POST', path: '/api/v1/message-status/' + encodeURIComponent(id) });
378
- return { messageId: id, status: (response.data || {}).status };
379
- }
380
-
381
- /** Returns { messageId, jobId, recipients: [...] } with one entry per recipient. */
382
- async function getReport(conn, messageId) {
383
- const id = checkMessageId(messageId);
384
- const response = await apiRequest({ ...conn, method: 'POST', path: '/api/v1/message-report/' + encodeURIComponent(id) });
385
- const recipients = Array.isArray(response.msgs) ? response.msgs : [];
386
- return { messageId: id, jobId: response.jobId, recipients };
387
- }
388
-
389
- /** Returns { balance }. */
390
- async function getBalance(conn) {
391
- const response = await apiRequest({ ...conn, method: 'POST', path: '/api/v1/get-balance' });
392
- return { balance: (response.data || {}).balance };
393
- }
394
-
395
- /** Returns the sender names, optionally only those with one status. */
396
- async function listSenderNames(conn, status) {
397
- const all = await getAllSenderNames(conn);
398
- if (!status || status === 'all') return all;
399
- return all.filter((s) => String(s.status).toLowerCase() === status);
400
- }
401
-
402
- /** Shows only the last 4 digits of a number, for the node status under the node. */
403
- function maskNumber(number) {
404
- const s = String(number || '');
405
- return s.length > 4 ? '…' + s.slice(-4) : s;
406
- }
407
-
408
- module.exports = {
409
- CorbitError,
410
- DEFAULT_BASE_URL,
411
- MAX_MESSAGE_LENGTH,
412
- MAX_IDEMPOTENCY_KEY_LENGTH,
413
- normalizeNumber,
414
- splitNumbers,
415
- checkMessage,
416
- cleanBaseUrl,
417
- errorFromResponse,
418
- apiRequest,
419
- getAllSenderNames,
420
- approvedSenderNames,
421
- sendSms,
422
- sendBulkSms,
423
- getStatus,
424
- getReport,
425
- getBalance,
426
- listSenderNames,
427
- maskNumber,
428
- };
1
+ 'use strict';
2
+
3
+ // Plain helpers for the Corbit SMS API. They do not depend on Node-RED, so they
4
+ // can be tested on their own.
5
+
6
+ const DEFAULT_BASE_URL = 'https://api.corbit.sa';
7
+ const MAX_MESSAGE_LENGTH = 1600;
8
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 255;
9
+ const REQUEST_TIMEOUT_MS = 30000;
10
+
11
+ /** An error with a short message for the user and an optional hint and API code. */
12
+ class CorbitError extends Error {
13
+ constructor(message, extra = {}) {
14
+ super(message);
15
+ this.name = 'CorbitError';
16
+ if (extra.hint) this.hint = extra.hint;
17
+ if (extra.code) this.code = extra.code;
18
+ if (extra.statusCode) this.statusCode = extra.statusCode;
19
+ if (extra.retryAfter) this.retryAfter = extra.retryAfter;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Turns a phone number into the digits-only international format the API expects.
25
+ * Accepts "+966 50 123 4567", "00966501234567", "966501234567", "+966 (0)50 123 4567",
26
+ * Arabic-Indic digits, and the Saudi local forms "0501234567" and "501234567".
27
+ * Anything that could turn into a wrong number is rejected instead of guessed:
28
+ * local numbers of other countries, decimals, "9.66501E+11", "ext 12".
29
+ * Returns undefined when the number cannot be used.
30
+ */
31
+ function normalizeNumber(raw) {
32
+ let text;
33
+ if (typeof raw === 'number') {
34
+ if (!Number.isSafeInteger(raw) || raw <= 0) return undefined;
35
+ text = String(raw);
36
+ } else if (typeof raw === 'string') {
37
+ text = raw
38
+ .trim()
39
+ .replace(/[٠-٩]/g, (d) => String(d.charCodeAt(0) - 0x0660))
40
+ .replace(/[۰-۹]/g, (d) => String(d.charCodeAt(0) - 0x06f0));
41
+ } else {
42
+ return undefined;
43
+ }
44
+ if (!/^\+?[\d\s\-()]+$/.test(text)) return undefined;
45
+ let digits = text.replace(/\D/g, '');
46
+ if (text.startsWith('+')) {
47
+ // Already international.
48
+ } else if (digits.startsWith('00')) {
49
+ digits = digits.slice(2);
50
+ } else if (/^05\d{8}$/.test(digits)) {
51
+ digits = '966' + digits.slice(1);
52
+ } else if (/^5\d{8}$/.test(digits)) {
53
+ digits = '966' + digits;
54
+ } else if (digits.startsWith('0')) {
55
+ return undefined;
56
+ }
57
+ // "+966 (0)50 …": drop the trunk zero after the Saudi country code.
58
+ if (/^9660\d{9}$/.test(digits)) digits = '966' + digits.slice(4);
59
+ return /^[1-9]\d{7,14}$/.test(digits) ? digits : undefined;
60
+ }
61
+
62
+ // What separates one number from the next in a pasted list: comma, semicolon,
63
+ // new line, tab, and the Arabic comma and semicolon (what the Arabic iPhone
64
+ // keyboard types). A space alone is not a separator: see splitNumbers.
65
+ const LIST_SEPARATORS = /[,;،؛\r\n\t]+/;
66
+ // A piece that reads as one number written with spaces (as copied from phone contacts).
67
+ const SPACED_NUMBER = /^\+?[0-9٠-٩۰-۹()\-\s]+$/;
68
+
69
+ /**
70
+ * Splits a list given as text or as an array, the same way the Corbit SMS app does.
71
+ * "+966 50 123 4567" stays one number; "0501234567 0509876543" becomes two, because a
72
+ * piece is split on its spaces only when it is not a number once the spaces are removed.
73
+ */
74
+ function splitNumbers(value) {
75
+ if (Array.isArray(value)) return value.flatMap((v) => splitNumbers(v));
76
+ if (value === null || value === undefined) return [];
77
+ if (typeof value === 'number') return [value];
78
+ const tokens = [];
79
+ for (const piece of String(value).split(LIST_SEPARATORS)) {
80
+ const p = piece.trim();
81
+ if (p === '') continue;
82
+ if (SPACED_NUMBER.test(p)) {
83
+ const joined = p.replace(/\s+/g, '');
84
+ if (normalizeNumber(joined)) {
85
+ tokens.push(joined);
86
+ continue;
87
+ }
88
+ }
89
+ tokens.push(...p.split(/\s+/).filter((t) => t !== ''));
90
+ }
91
+ return tokens;
92
+ }
93
+
94
+ /** Checks the SMS text and returns it as a string (numbers, e.g. an OTP, are converted). */
95
+ function checkMessage(raw) {
96
+ if (raw !== null && raw !== undefined && typeof raw === 'object') {
97
+ throw new CorbitError('The message must be text, not an object', {
98
+ hint: 'Set the Message field to the text of the SMS, or put the text in msg.payload.',
99
+ });
100
+ }
101
+ const message = raw === null || raw === undefined ? '' : String(raw);
102
+ if (message.trim() === '') {
103
+ throw new CorbitError('The message is empty', { hint: 'Put the text of the SMS in msg.payload or in the Message field.' });
104
+ }
105
+ if (message.length > MAX_MESSAGE_LENGTH) {
106
+ throw new CorbitError(`The message is ${message.length} characters; the limit is ${MAX_MESSAGE_LENGTH}`);
107
+ }
108
+ return message;
109
+ }
110
+
111
+ const CODE_HINTS = {
112
+ INSUFFICIENT_BALANCE: 'Your Corbit SMS balance is not enough. Top up at sms.corbit.sa and try again.',
113
+ SENDER_NOT_ALLOWED: 'This sender name is not approved on your account. Pick one from the Sender list.',
114
+ DUPLICATE:
115
+ 'The same text was sent to the same number within the last hour. Tick "Allow duplicate" (or set msg.allowDuplicate = true) to send it again on purpose.',
116
+ IDEMPOTENCY_IN_PROGRESS: 'A request with the same idempotency key is still being processed. Wait a moment and try again.',
117
+ IDEMPOTENCY_KEY_REUSED:
118
+ 'This idempotency key was already used for a different message. Use a key that is different for each message.',
119
+ };
120
+
121
+ /** Builds a CorbitError from an API error response. */
122
+ function errorFromResponse(statusCode, body, headers = {}) {
123
+ const apiMessage = body && typeof body.message === 'string' && body.message ? body.message.slice(0, 300) : '';
124
+ const code = body && typeof body.code === 'string' ? body.code : '';
125
+ let hint = code ? CODE_HINTS[code] : undefined;
126
+ let retryAfter;
127
+ if (statusCode === 401) {
128
+ hint = 'The API token was rejected. Check the API token in the Corbit SMS account settings of this node.';
129
+ } else if (statusCode === 429 || code === 'RATE_LIMIT') {
130
+ retryAfter = headers['retry-after'];
131
+ hint = `Too many requests.${retryAfter ? ` Try again in ${retryAfter} seconds.` : ''}`;
132
+ }
133
+ return new CorbitError(apiMessage || `Corbit SMS returned HTTP ${statusCode}`, {
134
+ hint,
135
+ code: code || undefined,
136
+ statusCode,
137
+ retryAfter,
138
+ });
139
+ }
140
+
141
+ /**
142
+ * Checks the base URL. HTTPS is required, except for a server on this machine
143
+ * (useful for testing), so the token is never sent in clear text over the network.
144
+ */
145
+ function cleanBaseUrl(baseUrl) {
146
+ const text = String(baseUrl || DEFAULT_BASE_URL).trim().replace(/\/+$/, '');
147
+ let url;
148
+ try {
149
+ url = new URL(text);
150
+ } catch {
151
+ url = undefined;
152
+ }
153
+ const local = url && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
154
+ if (!url || !(url.protocol === 'https:' || (url.protocol === 'http:' && local)) || url.username || url.password) {
155
+ throw new CorbitError(`The base URL is not valid: "${text}"`, { hint: `Use ${DEFAULT_BASE_URL}.` });
156
+ }
157
+ return text;
158
+ }
159
+
160
+ /** Header values must be printable ASCII; a pasted token with a line break would otherwise end up in error messages. */
161
+ function checkToken(token) {
162
+ const value = token === null || token === undefined ? '' : String(token).trim();
163
+ if (value === '') {
164
+ throw new CorbitError('The API token is missing', {
165
+ hint: 'Open the Corbit SMS account settings of this node and paste your API token from sms.corbit.sa.',
166
+ });
167
+ }
168
+ if (!/^[\x21-\x7e]+$/.test(value)) {
169
+ throw new CorbitError('The API token contains spaces, line breaks or other characters that are not allowed', {
170
+ hint: 'Copy the API token again from sms.corbit.sa and paste it into the Corbit SMS account settings.',
171
+ });
172
+ }
173
+ return value;
174
+ }
175
+
176
+ /**
177
+ * Calls the Corbit SMS API. Returns the parsed body, or throws a CorbitError with
178
+ * the API's own message when the call fails. `signal` cancels the call (e.g. on redeploy);
179
+ * `sends` marks calls that send SMS, so a timeout warns that the SMS may have gone out.
180
+ */
181
+ async function apiRequest({ token, baseUrl, method, path, body, query, headers = {}, signal, sends = false, fetchImpl, timeoutMs = REQUEST_TIMEOUT_MS }) {
182
+ const doFetch = fetchImpl || globalThis.fetch;
183
+ if (typeof doFetch !== 'function') {
184
+ throw new CorbitError('This Node.js version has no fetch()', { hint: 'Run Node-RED on Node.js 18 or later.' });
185
+ }
186
+ const cleanToken = checkToken(token);
187
+ let url = cleanBaseUrl(baseUrl) + path;
188
+ if (query) {
189
+ const qs = new URLSearchParams();
190
+ for (const [k, v] of Object.entries(query)) if (v !== undefined) qs.set(k, String(v));
191
+ url += (url.includes('?') ? '&' : '?') + qs.toString();
192
+ }
193
+
194
+ const controller = new AbortController();
195
+ let timedOut = false;
196
+ const timer = setTimeout(() => {
197
+ timedOut = true;
198
+ controller.abort();
199
+ }, timeoutMs);
200
+ const onAbort = () => controller.abort();
201
+ if (signal) {
202
+ if (signal.aborted) controller.abort();
203
+ else signal.addEventListener('abort', onAbort, { once: true });
204
+ }
205
+
206
+ const init = {
207
+ method,
208
+ headers: { Accept: 'application/json', Authorization: `Bearer ${cleanToken}`, ...headers },
209
+ signal: controller.signal,
210
+ };
211
+ if (body !== undefined) {
212
+ init.body = JSON.stringify(body);
213
+ init.headers['Content-Type'] = 'application/json';
214
+ }
215
+
216
+ let response;
217
+ let text;
218
+ try {
219
+ response = await doFetch(url, init);
220
+ text = await response.text();
221
+ } catch (error) {
222
+ if (timedOut) {
223
+ throw new CorbitError(
224
+ sends ? `No reply from Corbit SMS within ${Math.round(timeoutMs / 1000)} seconds; the SMS may have been sent` : `No reply from Corbit SMS within ${Math.round(timeoutMs / 1000)} seconds`,
225
+ {
226
+ hint: sends
227
+ ? 'Check the message status or your Corbit SMS account before you send again, so the SMS is not sent twice.'
228
+ : 'Try again later.',
229
+ },
230
+ );
231
+ }
232
+ if (controller.signal.aborted) throw new CorbitError('The request was cancelled');
233
+ // Never put the error text itself in the message: it can contain header values.
234
+ const code = error && error.cause && typeof error.cause.code === 'string' ? error.cause.code : 'network error';
235
+ throw new CorbitError(`Could not reach Corbit SMS (${code})`, {
236
+ hint: 'Check the internet connection of the Node-RED server and the base URL.',
237
+ });
238
+ } finally {
239
+ clearTimeout(timer);
240
+ if (signal) signal.removeEventListener('abort', onAbort);
241
+ }
242
+
243
+ let data;
244
+ try {
245
+ data = text ? JSON.parse(text) : {};
246
+ } catch {
247
+ data = {};
248
+ }
249
+ const parsed = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
250
+ const responseHeaders = {};
251
+ if (response.headers && typeof response.headers.forEach === 'function') {
252
+ response.headers.forEach((v, k) => {
253
+ responseHeaders[k.toLowerCase()] = v;
254
+ });
255
+ }
256
+ if (response.status >= 400 || parsed.status === 'Error') {
257
+ throw errorFromResponse(response.status, parsed, responseHeaders);
258
+ }
259
+ if (Array.isArray(data)) return { data };
260
+ return parsed;
261
+ }
262
+
263
+ /**
264
+ * Reads the sender names page by page. Stops after `maxItems` names when given,
265
+ * when the last page is reached, or when the API keeps returning the same page.
266
+ */
267
+ async function getAllSenderNames(conn, maxItems) {
268
+ const perPage = 50;
269
+ const all = [];
270
+ let previousFirst;
271
+ for (let page = 1; page <= 100; page++) {
272
+ const response = await apiRequest({ ...conn, method: 'GET', path: '/api/v1/sendernames', query: { per_page: perPage, page } });
273
+ const items = Array.isArray(response.data) ? response.data : [];
274
+ if (items.length === 0) break;
275
+ const first = JSON.stringify(items[0]);
276
+ if (page > 1 && first === previousFirst) break;
277
+ previousFirst = first;
278
+ all.push(...items);
279
+ if (maxItems !== undefined && all.length >= maxItems) break;
280
+ const pagination = response.pagination || {};
281
+ const total = Number(pagination.total);
282
+ const currentPage = Number(pagination.current_page);
283
+ const pageSize = Number(pagination.per_page) || perPage;
284
+ if (Number.isFinite(total) && all.length >= total) break;
285
+ if (!Number.isFinite(total) && items.length < pageSize) break;
286
+ if (Number.isFinite(currentPage) && currentPage !== page) break;
287
+ }
288
+ return maxItems === undefined ? all : all.slice(0, maxItems);
289
+ }
290
+
291
+ /** Approved sender names, sorted, for the editor list. */
292
+ async function approvedSenderNames(conn) {
293
+ const all = await getAllSenderNames(conn);
294
+ return [...new Set(all.filter((s) => String(s.status).toLowerCase() === 'approved').map((s) => String(s.name)))].sort((a, b) =>
295
+ a.localeCompare(b),
296
+ );
297
+ }
298
+
299
+ function sendHeaders({ idempotencyKey, allowDuplicate }) {
300
+ const headers = {};
301
+ if (idempotencyKey !== undefined && idempotencyKey !== null && String(idempotencyKey) !== '') {
302
+ if (typeof idempotencyKey === 'object') {
303
+ throw new CorbitError('The idempotency key must be text, not an object');
304
+ }
305
+ const key = String(idempotencyKey);
306
+ if (key.length > MAX_IDEMPOTENCY_KEY_LENGTH) {
307
+ throw new CorbitError(`The idempotency key is ${key.length} characters; the limit is ${MAX_IDEMPOTENCY_KEY_LENGTH}`);
308
+ }
309
+ if (!/^[\x20-\x7e]+$/.test(key)) {
310
+ throw new CorbitError('The idempotency key may only contain English letters, digits and symbols', {
311
+ hint: 'Use an ID such as an order number.',
312
+ });
313
+ }
314
+ headers['Idempotency-Key'] = key;
315
+ }
316
+ if (allowDuplicate === true) headers['X-Allow-Duplicate'] = 'true';
317
+ return headers;
318
+ }
319
+
320
+ function checkSender(raw) {
321
+ const sender = raw === null || raw === undefined || typeof raw === 'object' ? '' : String(raw).trim();
322
+ if (sender === '') {
323
+ throw new CorbitError('No sender name', { hint: 'Choose an approved sender name in the node, or set msg.sender.' });
324
+ }
325
+ return sender;
326
+ }
327
+
328
+ function describe(value) {
329
+ if (value === undefined || value === null) return '';
330
+ return typeof value === 'object' ? JSON.stringify(value).slice(0, 60) : String(value).slice(0, 60);
331
+ }
332
+
333
+ /** Sends one SMS. Returns { messageId, status, to, senderName }. */
334
+ async function sendSms(conn, { sender, to, message, idempotencyKey, allowDuplicate }) {
335
+ const senderName = checkSender(sender);
336
+ const number = normalizeNumber(to);
337
+ if (!number) {
338
+ throw new CorbitError(`The mobile number is not valid: "${describe(to)}"`, {
339
+ hint: 'Use the international format, e.g. 966501234567. Saudi local numbers (05XXXXXXXX) are converted automatically.',
340
+ });
341
+ }
342
+ const messageBody = checkMessage(message);
343
+ const headers = sendHeaders({ idempotencyKey, allowDuplicate });
344
+ const response = await apiRequest({
345
+ ...conn,
346
+ method: 'POST',
347
+ path: '/api/v1/send',
348
+ body: { senderName, number, messageBody, sendAtOption: 'NOW' },
349
+ headers,
350
+ sends: true,
351
+ });
352
+ const sent = (response.data && response.data.message) || {};
353
+ return { messageId: sent.id, status: sent.status, to: number, senderName };
354
+ }
355
+
356
+ /** Sends the same SMS to many numbers. Returns { messageId, status, recipients, numbers, senderName }. */
357
+ async function sendBulkSms(conn, { sender, numbers: rawNumbers, message, idempotencyKey, allowDuplicate }) {
358
+ const senderName = checkSender(sender);
359
+ const raw = splitNumbers(rawNumbers);
360
+ const invalid = raw.filter((n) => !normalizeNumber(n)).map(describe);
361
+ if (invalid.length > 0) {
362
+ throw new CorbitError(
363
+ `Invalid mobile numbers: ${invalid.slice(0, 5).join(', ')}${invalid.length > 5 ? ` and ${invalid.length - 5} more` : ''}`,
364
+ {
365
+ hint: 'Use the international format, e.g. 966501234567. Corbit SMS rejects the whole request if any number is invalid, so nothing was sent.',
366
+ },
367
+ );
368
+ }
369
+ const numbers = [...new Set(raw.map((n) => normalizeNumber(n)))];
370
+ if (numbers.length === 0) {
371
+ throw new CorbitError('The list of numbers is empty', { hint: 'Put the numbers in msg.numbers (an array or comma-separated text) or in the Numbers field.' });
372
+ }
373
+ const messageBody = checkMessage(message);
374
+ const headers = sendHeaders({ idempotencyKey, allowDuplicate });
375
+ const response = await apiRequest({
376
+ ...conn,
377
+ method: 'POST',
378
+ path: '/api/v1/send-bulk',
379
+ body: { senderName, numbers, messageBody, sendAtOption: 'Now' },
380
+ headers,
381
+ sends: true,
382
+ });
383
+ const sent = (response.data && response.data.message) || {};
384
+ return { messageId: sent.id, status: sent.status, recipients: numbers.length, numbers, senderName };
385
+ }
386
+
387
+ function checkMessageId(raw) {
388
+ const id = raw === null || raw === undefined || typeof raw === 'object' ? '' : String(raw).trim();
389
+ if (id === '') {
390
+ throw new CorbitError('The message ID is empty', { hint: 'Use the messageId returned by a send, e.g. msg.payload.messageId.' });
391
+ }
392
+ return id;
393
+ }
394
+
395
+ /** Returns { messageId, status }. */
396
+ async function getStatus(conn, messageId) {
397
+ const id = checkMessageId(messageId);
398
+ const response = await apiRequest({ ...conn, method: 'POST', path: '/api/v1/message-status/' + encodeURIComponent(id) });
399
+ return { messageId: id, status: (response.data || {}).status };
400
+ }
401
+
402
+ /** Returns { messageId, jobId, recipients: [...] } with one entry per recipient. */
403
+ async function getReport(conn, messageId) {
404
+ const id = checkMessageId(messageId);
405
+ const response = await apiRequest({ ...conn, method: 'POST', path: '/api/v1/message-report/' + encodeURIComponent(id) });
406
+ const recipients = Array.isArray(response.msgs) ? response.msgs : [];
407
+ return { messageId: id, jobId: response.jobId, recipients };
408
+ }
409
+
410
+ /** Returns { balance }. */
411
+ async function getBalance(conn) {
412
+ const response = await apiRequest({ ...conn, method: 'POST', path: '/api/v1/get-balance' });
413
+ return { balance: (response.data || {}).balance };
414
+ }
415
+
416
+ /** Returns the sender names, optionally only those with one status. */
417
+ async function listSenderNames(conn, status) {
418
+ const all = await getAllSenderNames(conn);
419
+ if (!status || status === 'all') return all;
420
+ return all.filter((s) => String(s.status).toLowerCase() === status);
421
+ }
422
+
423
+ /** Shows only the last 4 digits of a number, for the node status under the node. */
424
+ function maskNumber(number) {
425
+ const s = String(number || '');
426
+ return s.length > 4 ? '…' + s.slice(-4) : s;
427
+ }
428
+
429
+ module.exports = {
430
+ CorbitError,
431
+ DEFAULT_BASE_URL,
432
+ MAX_MESSAGE_LENGTH,
433
+ MAX_IDEMPOTENCY_KEY_LENGTH,
434
+ normalizeNumber,
435
+ splitNumbers,
436
+ checkMessage,
437
+ cleanBaseUrl,
438
+ errorFromResponse,
439
+ apiRequest,
440
+ getAllSenderNames,
441
+ approvedSenderNames,
442
+ sendSms,
443
+ sendBulkSms,
444
+ getStatus,
445
+ getReport,
446
+ getBalance,
447
+ listSenderNames,
448
+ maskNumber,
449
+ };