@baatzo/node 0.0.0-stage → 0.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Aashita Technosoft Private Limited
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,74 @@
1
- # Temporary Holding Version
1
+ # @baatzo/node
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Send approved Utility and Authentication WhatsApp templates with the [Baatzo API](https://api.baatzo.com/docs), read their status and verify status webhooks. Node.js 20 or later, no dependencies, types included.
4
+
5
+ ```sh
6
+ npm install @baatzo/node
7
+ ```
8
+
9
+ Make a key in the Baatzo web app under Settings, Developers. Start with a sandbox key (`bz_test_`): it is free on every plan and nothing reaches WhatsApp. Keep keys on your server.
10
+
11
+ ## Send
12
+
13
+ ```js
14
+ import { Baatzo } from '@baatzo/node';
15
+
16
+ const baatzo = new Baatzo(); // reads BAATZO_KEY
17
+
18
+ const sent = await baatzo.messages.send(
19
+ {
20
+ to: '+919829012345',
21
+ template: { name: 'login_code', language: 'en' },
22
+ variables: { body: { code: '482913' } },
23
+ reference: 'login-88213',
24
+ },
25
+ { idempotencyKey: 'login-88213-1' },
26
+ );
27
+ // { id: '0193…', status: 'accepted', … }
28
+ ```
29
+
30
+ Give your own `idempotencyKey` when your code may run the same send again, after a crash for example: the same key never sends twice in 24 hours. Without one, each call makes a new key.
31
+
32
+ ## Read
33
+
34
+ ```js
35
+ const message = await baatzo.messages.get(sent.id);
36
+ console.log(message.status, message.charge);
37
+ ```
38
+
39
+ ## Webhooks
40
+
41
+ Check the raw body, before any JSON parsing.
42
+
43
+ ```js
44
+ import { verifyWebhook } from '@baatzo/node';
45
+
46
+ app.post('/baatzo-webhook', express.raw({ type: 'application/json' }), (req, res) => {
47
+ let event;
48
+ try {
49
+ event = verifyWebhook(req.body, req.get('Baatzo-Signature'), process.env.BAATZO_WEBHOOK_SECRET);
50
+ } catch {
51
+ return res.status(400).end();
52
+ }
53
+ res.status(200).end(); // answer within 5 seconds, then do the work
54
+ // Drop a repeat by event.id; ignore a lower event.data.status_rank than you have.
55
+ });
56
+ ```
57
+
58
+ `verifySignature(rawBody, header, secret)` answers true or false instead.
59
+
60
+ ## Errors and retries
61
+
62
+ - `BaatzoError`: Baatzo refused. It has `status`, `code` ([the list](https://api.baatzo.com/docs#errors)), `details`, `requestId` and `retryAfter`.
63
+ - `BaatzoConnectionError`: no answer came. The message may have been sent: try again with its `idempotencyKey`.
64
+ - `BaatzoSignatureError`: a webhook that does not verify.
65
+
66
+ The client tries again, twice by default and always with the same `Idempotency-Key`, after a 429, a 5xx, `request_in_progress` and a connection failure. It does not try `retry_later` again: send a fresh code.
67
+
68
+ A send can succeed as a request and still be refused by WhatsApp: check `status` for `failed` and `withheld`.
69
+
70
+ Options: `new Baatzo({ apiKey, baseUrl, timeoutMs: 30000, maxRetries: 2 })`.
71
+
72
+ ## Licence
73
+
74
+ MIT. By Aashita Technosoft Private Limited.
package/index.cjs ADDED
@@ -0,0 +1,142 @@
1
+ 'use strict';
2
+ const { createHmac, randomUUID, timingSafeEqual } = require('node:crypto');
3
+ const { version } = require('./package.json');
4
+
5
+ const TOLERANCE_SECONDS = 300;
6
+ /** A longer Retry-After than this is the caller's to wait for. */
7
+ const MAX_WAIT_MS = 30_000;
8
+
9
+ /** Baatzo answered with an error. Act on `code`; `message` is for people and may change. */
10
+ class BaatzoError extends Error {
11
+ constructor(status, body, headers) {
12
+ const answer = body && typeof body === 'object' ? body : {};
13
+ super(answer.message || `Baatzo answered HTTP ${status}`);
14
+ this.name = 'BaatzoError';
15
+ this.status = status;
16
+ this.code = answer.code || 'unexpected_answer';
17
+ this.details = answer.details;
18
+ this.requestId = headers.get('x-request-id');
19
+ const after = headers.get('retry-after');
20
+ this.retryAfter = after !== null && /^\d+$/.test(after) ? Number(after) : null;
21
+ }
22
+ }
23
+
24
+ /** No answer arrived (the network, a timeout). `idempotencyKey` is the one to send again with. */
25
+ class BaatzoConnectionError extends Error {
26
+ constructor(cause, idempotencyKey) {
27
+ super(cause && cause.name === 'TimeoutError' ? 'Baatzo did not answer in time' : 'Could not reach Baatzo', { cause });
28
+ this.name = 'BaatzoConnectionError';
29
+ this.idempotencyKey = idempotencyKey;
30
+ }
31
+ }
32
+
33
+ /** A webhook that is not from Baatzo, was changed on the way, or is too old. */
34
+ class BaatzoSignatureError extends Error {
35
+ constructor(message) {
36
+ super(message);
37
+ this.name = 'BaatzoSignatureError';
38
+ }
39
+ }
40
+
41
+ const isLocal = (host) => host === 'localhost' || host === '127.0.0.1' || host === '[::1]';
42
+
43
+ class Baatzo {
44
+ #apiKey;
45
+ #base;
46
+ #timeoutMs;
47
+ #maxRetries;
48
+ #fetch;
49
+
50
+ constructor(options = {}) {
51
+ const { apiKey = process.env.BAATZO_KEY, baseUrl = 'https://api.baatzo.com', timeoutMs = 30_000, maxRetries = 2, fetch: fetchImpl = globalThis.fetch } = typeof options === 'string' ? { apiKey: options } : options;
52
+ if (typeof apiKey !== 'string' || !apiKey) throw new TypeError('Give an API key, or set BAATZO_KEY.');
53
+ if (!/^[\x21-\x7e]+$/.test(apiKey)) throw new TypeError('The API key has a space or a line break in it.');
54
+ const url = new URL(baseUrl);
55
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLocal(url.hostname))) throw new TypeError('baseUrl must use https.');
56
+ this.#apiKey = apiKey;
57
+ this.#base = baseUrl.replace(/\/+$/, '');
58
+ this.#timeoutMs = timeoutMs;
59
+ this.#maxRetries = maxRetries;
60
+ this.#fetch = fetchImpl;
61
+ this.messages = {
62
+ send: async (message, { idempotencyKey = randomUUID() } = {}) => {
63
+ if (typeof idempotencyKey !== 'string' || !/^[\x21-\x7e]{1,255}$/.test(idempotencyKey)) throw new TypeError('idempotencyKey must be 1 to 255 visible ASCII characters.');
64
+ return this.#request('POST', '/v1/messages', message, idempotencyKey);
65
+ },
66
+ get: async (id) => {
67
+ if (typeof id !== 'string' || !id) throw new TypeError('Give the message id.');
68
+ return this.#request('GET', `/v1/messages/${encodeURIComponent(id)}`);
69
+ },
70
+ };
71
+ }
72
+
73
+ async #request(method, path, body, idempotencyKey) {
74
+ const headers = { authorization: `Bearer ${this.#apiKey}`, accept: 'application/json', 'user-agent': `baatzo-node/${version}` };
75
+ if (body !== undefined) headers['content-type'] = 'application/json';
76
+ if (idempotencyKey) headers['idempotency-key'] = idempotencyKey;
77
+ const payload = body === undefined ? undefined : JSON.stringify(body);
78
+ for (let attempt = 0; ; attempt++) {
79
+ let error;
80
+ try {
81
+ // A redirect is refused, so the key never goes to another address.
82
+ const res = await this.#fetch(this.#base + path, { method, headers, body: payload, redirect: 'error', signal: AbortSignal.timeout(this.#timeoutMs) });
83
+ const text = await res.text();
84
+ let answer;
85
+ try {
86
+ answer = JSON.parse(text);
87
+ } catch {
88
+ answer = undefined;
89
+ }
90
+ if (res.ok && answer !== undefined) return answer;
91
+ error = new BaatzoError(res.status, answer, res.headers);
92
+ } catch (cause) {
93
+ error = new BaatzoConnectionError(cause, idempotencyKey);
94
+ }
95
+ const wait = retryWait(error, attempt);
96
+ if (attempt >= this.#maxRetries || wait === null) throw error;
97
+ await new Promise((r) => setTimeout(r, wait));
98
+ }
99
+ }
100
+ }
101
+
102
+ /**
103
+ * How long to wait before the same request again, or null when trying again cannot help. Every try carries the
104
+ * same Idempotency-Key, so a message is never sent twice. `retry_later` is not retried: it means an
105
+ * Authentication send needs a fresh code.
106
+ */
107
+ function retryWait(error, attempt) {
108
+ const backoff = 500 * 2 ** attempt + Math.random() * 250;
109
+ if (error instanceof BaatzoConnectionError) return backoff;
110
+ const again = error.status === 429 || error.code === 'request_in_progress' || (error.status >= 500 && error.code !== 'retry_later');
111
+ if (!again) return null;
112
+ const wait = error.retryAfter === null ? backoff : error.retryAfter * 1000;
113
+ return wait > MAX_WAIT_MS ? null : wait;
114
+ }
115
+
116
+ /** True when `header` is a valid Baatzo-Signature of `rawBody` made at most 5 minutes from now. */
117
+ function verifySignature(rawBody, header, secret, { now = Date.now() } = {}) {
118
+ if (typeof header !== 'string' || typeof secret !== 'string' || !secret) return false;
119
+ let t = null;
120
+ const signatures = [];
121
+ for (const part of header.split(',')) {
122
+ const i = part.indexOf('=');
123
+ const k = part.slice(0, i).trim();
124
+ const v = part.slice(i + 1).trim();
125
+ if (k === 't' && /^\d{1,12}$/.test(v)) t = Number(v);
126
+ if (k === 'v1' && /^[0-9a-f]{64}$/.test(v)) signatures.push(Buffer.from(v, 'hex'));
127
+ }
128
+ if (t === null || !signatures.length) return false;
129
+ if (Math.abs(Math.floor(now / 1000) - t) > TOLERANCE_SECONDS) return false;
130
+ const expected = createHmac('sha256', secret).update(`${t}.`).update(rawBody).digest();
131
+ return signatures.some((s) => timingSafeEqual(s, expected));
132
+ }
133
+
134
+ /** The event of a webhook request, after its signature is checked. Throws BaatzoSignatureError. */
135
+ function verifyWebhook(rawBody, header, secret, options) {
136
+ if (typeof secret !== 'string' || !secret) throw new TypeError('Give the signing secret (whsec_...).');
137
+ if (typeof rawBody !== 'string' && !(rawBody instanceof Uint8Array)) throw new TypeError('rawBody must be the raw body (a Buffer or string), before any JSON parsing.');
138
+ if (!verifySignature(rawBody, header, secret, options)) throw new BaatzoSignatureError('The Baatzo-Signature header does not match this body, or is more than 5 minutes old.');
139
+ return JSON.parse(typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody).toString('utf8'));
140
+ }
141
+
142
+ module.exports = { Baatzo, BaatzoError, BaatzoConnectionError, BaatzoSignatureError, verifySignature, verifyWebhook };
package/index.d.ts ADDED
@@ -0,0 +1,106 @@
1
+ export type MessageStatus = 'queued' | 'unknown' | 'accepted' | 'held' | 'sent' | 'delivered' | 'read' | 'failed' | 'withheld';
2
+
3
+ export interface SendMessage {
4
+ /** The number in E.164, such as +919829012345. */
5
+ to: string;
6
+ /** Meta's phone number ID of the sending number; needed only when the workspace has more than one. */
7
+ from?: string;
8
+ template: { name: string; language: string };
9
+ variables?: {
10
+ body?: Record<string, string>;
11
+ header?: { text?: Record<string, string>; document?: { link: string; filename: string } };
12
+ buttons?: { index?: number; url?: string; copy_code?: string }[];
13
+ };
14
+ /** Your own id, up to 64 characters, returned in reads and webhooks. */
15
+ reference?: string;
16
+ }
17
+
18
+ export interface MessageError {
19
+ code?: number | null;
20
+ title?: string | null;
21
+ explanation?: { en: string; hi: string } | null;
22
+ [key: string]: unknown;
23
+ }
24
+
25
+ export interface SendResult {
26
+ id: string;
27
+ status: MessageStatus;
28
+ reference?: string | null;
29
+ error?: MessageError | null;
30
+ wamid?: string | null;
31
+ /** Present and true only for a sandbox key. */
32
+ sandbox?: boolean;
33
+ }
34
+
35
+ export interface Charge {
36
+ category?: string | null;
37
+ baatzo_fee_paise?: number;
38
+ state?: string;
39
+ meta_charge_estimate?: { amount_micro_rupees: string; is_estimate: true } | null;
40
+ }
41
+
42
+ export interface Message extends SendResult {
43
+ status_rank: number;
44
+ template: { name: string; language: string; category: 'utility' | 'authentication' };
45
+ created_at: string;
46
+ times: Record<string, string | null>;
47
+ charge: Charge | null;
48
+ }
49
+
50
+ export interface StatusEvent {
51
+ /** The same on every retry and replay of this event: drop a repeat. */
52
+ id: string;
53
+ type: 'message.sent' | 'message.delivered' | 'message.read' | 'message.failed' | 'webhook.test';
54
+ created_at: string;
55
+ sandbox?: boolean;
56
+ data: {
57
+ message_id?: string;
58
+ reference?: string | null;
59
+ wamid?: string | null;
60
+ status?: MessageStatus;
61
+ /** Higher is later: ignore an event whose rank is below one you have. */
62
+ status_rank?: number;
63
+ charge?: Charge | null;
64
+ error?: MessageError | null;
65
+ sandbox?: boolean;
66
+ [key: string]: unknown;
67
+ };
68
+ }
69
+
70
+ export interface BaatzoOptions {
71
+ /** Default: the BAATZO_KEY environment variable. */
72
+ apiKey?: string;
73
+ baseUrl?: string;
74
+ /** For one attempt. Default 30000. */
75
+ timeoutMs?: number;
76
+ /** Extra attempts, all with the same Idempotency-Key. Default 2; 0 turns retries off. */
77
+ maxRetries?: number;
78
+ fetch?: typeof fetch;
79
+ }
80
+
81
+ export class Baatzo {
82
+ constructor(options?: BaatzoOptions | string);
83
+ readonly messages: {
84
+ send(message: SendMessage, options?: { idempotencyKey?: string }): Promise<SendResult>;
85
+ get(id: string): Promise<Message>;
86
+ };
87
+ }
88
+
89
+ export class BaatzoError extends Error {
90
+ readonly status: number;
91
+ readonly code: string;
92
+ readonly details: unknown;
93
+ /** Support asks for this. */
94
+ readonly requestId: string | null;
95
+ /** Seconds. */
96
+ readonly retryAfter: number | null;
97
+ }
98
+
99
+ export class BaatzoConnectionError extends Error {
100
+ readonly idempotencyKey: string | undefined;
101
+ }
102
+
103
+ export class BaatzoSignatureError extends Error {}
104
+
105
+ export function verifySignature(rawBody: Uint8Array | string, header: string | null | undefined, secret: string, options?: { now?: number }): boolean;
106
+ export function verifyWebhook(rawBody: Uint8Array | string, header: string | null | undefined, secret: string, options?: { now?: number }): StatusEvent;
package/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import sdk from './index.cjs';
2
+
3
+ export const { Baatzo, BaatzoError, BaatzoConnectionError, BaatzoSignatureError, verifySignature, verifyWebhook } = sdk;
package/package.json CHANGED
@@ -1,6 +1,23 @@
1
1
  {
2
2
  "name": "@baatzo/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Send WhatsApp templates with the Baatzo API, read their status and verify webhooks.",
5
+ "keywords": ["baatzo", "whatsapp", "whatsapp business", "whatsapp api", "otp"],
6
+ "homepage": "https://api.baatzo.com/docs",
7
+ "author": "Aashita Technosoft Private Limited",
8
+ "license": "MIT",
9
+ "engines": { "node": ">=20" },
10
+ "main": "./index.cjs",
11
+ "module": "./index.mjs",
12
+ "types": "./index.d.ts",
13
+ "exports": {
14
+ ".": { "types": "./index.d.ts", "import": "./index.mjs", "require": "./index.cjs" }
15
+ },
16
+ "files": ["index.cjs", "index.mjs", "index.d.ts"],
17
+ "sideEffects": false,
18
+ "publishConfig": { "access": "public" },
19
+ "scripts": {
20
+ "test": "node --test test/*.test.mjs",
21
+ "prepublishOnly": "npm test"
22
+ }
23
+ }