@chatwise/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.
Files changed (62) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/LICENSE +202 -0
  3. package/README.md +506 -2
  4. package/dist/cjs/client.d.ts +20 -0
  5. package/dist/cjs/client.js +32 -0
  6. package/dist/cjs/core/errors.d.ts +91 -0
  7. package/dist/cjs/core/errors.js +131 -0
  8. package/dist/cjs/core/http.d.ts +74 -0
  9. package/dist/cjs/core/http.js +336 -0
  10. package/dist/cjs/core/pagination.d.ts +35 -0
  11. package/dist/cjs/core/pagination.js +101 -0
  12. package/dist/cjs/generated/types.d.ts +969 -0
  13. package/dist/cjs/generated/types.js +3 -0
  14. package/dist/cjs/index.d.ts +15 -0
  15. package/dist/cjs/index.js +25 -0
  16. package/dist/cjs/package.json +1 -0
  17. package/dist/cjs/resources/conversations.d.ts +20 -0
  18. package/dist/cjs/resources/conversations.js +32 -0
  19. package/dist/cjs/resources/messages.d.ts +46 -0
  20. package/dist/cjs/resources/messages.js +60 -0
  21. package/dist/cjs/resources/webhook-deliveries.d.ts +27 -0
  22. package/dist/cjs/resources/webhook-deliveries.js +42 -0
  23. package/dist/cjs/resources/webhook-endpoints.d.ts +54 -0
  24. package/dist/cjs/resources/webhook-endpoints.js +82 -0
  25. package/dist/cjs/resources/webhook-event-types.d.ts +13 -0
  26. package/dist/cjs/resources/webhook-event-types.js +22 -0
  27. package/dist/cjs/resources/whatsapp-templates.d.ts +48 -0
  28. package/dist/cjs/resources/whatsapp-templates.js +69 -0
  29. package/dist/cjs/version.d.ts +2 -0
  30. package/dist/cjs/version.js +5 -0
  31. package/dist/cjs/webhooks.d.ts +74 -0
  32. package/dist/cjs/webhooks.js +123 -0
  33. package/dist/esm/client.d.ts +20 -0
  34. package/dist/esm/client.js +28 -0
  35. package/dist/esm/core/errors.d.ts +91 -0
  36. package/dist/esm/core/errors.js +113 -0
  37. package/dist/esm/core/http.d.ts +74 -0
  38. package/dist/esm/core/http.js +332 -0
  39. package/dist/esm/core/pagination.d.ts +35 -0
  40. package/dist/esm/core/pagination.js +95 -0
  41. package/dist/esm/generated/types.d.ts +969 -0
  42. package/dist/esm/generated/types.js +2 -0
  43. package/dist/esm/index.d.ts +15 -0
  44. package/dist/esm/index.js +4 -0
  45. package/dist/esm/package.json +1 -0
  46. package/dist/esm/resources/conversations.d.ts +20 -0
  47. package/dist/esm/resources/conversations.js +28 -0
  48. package/dist/esm/resources/messages.d.ts +46 -0
  49. package/dist/esm/resources/messages.js +56 -0
  50. package/dist/esm/resources/webhook-deliveries.d.ts +27 -0
  51. package/dist/esm/resources/webhook-deliveries.js +38 -0
  52. package/dist/esm/resources/webhook-endpoints.d.ts +54 -0
  53. package/dist/esm/resources/webhook-endpoints.js +78 -0
  54. package/dist/esm/resources/webhook-event-types.d.ts +13 -0
  55. package/dist/esm/resources/webhook-event-types.js +18 -0
  56. package/dist/esm/resources/whatsapp-templates.d.ts +48 -0
  57. package/dist/esm/resources/whatsapp-templates.js +65 -0
  58. package/dist/esm/version.d.ts +2 -0
  59. package/dist/esm/version.js +2 -0
  60. package/dist/esm/webhooks.d.ts +74 -0
  61. package/dist/esm/webhooks.js +118 -0
  62. package/package.json +79 -4
@@ -0,0 +1,118 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { types } from 'node:util';
3
+ import { ChatwiseError } from './core/errors.js';
4
+ /** The request isn't a valid webhook from Chatwise. Answer 400. */
5
+ export class WebhookVerificationError extends ChatwiseError {
6
+ name = 'WebhookVerificationError';
7
+ code;
8
+ constructor(code, message) {
9
+ super(message);
10
+ this.code = code;
11
+ }
12
+ }
13
+ const SECRET_PREFIX = 'whsec_';
14
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
15
+ // Mistakes on the receiver's side are plain ChatwiseErrors: answering 400 to them would make Chatwise
16
+ // give up on deliveries that are fine, while an unhandled error's 500 makes it try again.
17
+ function readSecrets(secret) {
18
+ const secrets = Array.isArray(secret) ? secret : [secret];
19
+ if (!secrets.length)
20
+ throw new ChatwiseError('No webhook signing secret. Pass the endpoint\'s as `secret`.');
21
+ return secrets.map((value) => {
22
+ const text = typeof value === 'string' ? value.trim() : '';
23
+ if (!text)
24
+ throw new ChatwiseError('No webhook signing secret. Pass the endpoint\'s as `secret`.');
25
+ const encoded = text.slice(SECRET_PREFIX.length);
26
+ const key = text.startsWith(SECRET_PREFIX) && BASE64.test(encoded) ? Buffer.from(encoded, 'base64') : undefined;
27
+ if (!key || key.length < 24 || key.length > 64) {
28
+ throw new ChatwiseError('The webhook signing secret is not valid: it starts with `whsec_`, followed by base64.');
29
+ }
30
+ return key;
31
+ });
32
+ }
33
+ function readHeader(headers, name) {
34
+ let value;
35
+ if (typeof headers.get === 'function') {
36
+ value = headers.get(name);
37
+ }
38
+ else {
39
+ for (const [key, found] of Object.entries(headers)) {
40
+ if (key.toLowerCase() === name)
41
+ value = Array.isArray(found) && found.length === 1 ? found[0] : found;
42
+ }
43
+ }
44
+ if (Array.isArray(value))
45
+ throw new WebhookVerificationError('malformed_header', `The ${name} header was sent more than once.`);
46
+ if (typeof value !== 'string' || !value)
47
+ throw new WebhookVerificationError('missing_header', `The ${name} header is missing.`);
48
+ return value;
49
+ }
50
+ /**
51
+ * Checks that a request really comes from Chatwise and returns its event. Throws a
52
+ * `WebhookVerificationError` if it doesn't: answer 400 then. It checks the signature in constant time
53
+ * and that the request isn't old, as Standard Webhooks says to.
54
+ *
55
+ * Pass the body exactly as received. The same event can arrive more than once, with the same `id`.
56
+ */
57
+ export function verifyWebhook(options) {
58
+ if (typeof options !== 'object' || options === null) {
59
+ throw new ChatwiseError('Pass verifyWebhook an object with the request\'s payload and headers, and the secret.');
60
+ }
61
+ const { payload, headers, secret, toleranceSeconds = 300, now } = options;
62
+ const keys = readSecrets(secret);
63
+ // Not instanceof, which refuses bytes from another realm, as tests and sandboxes have them.
64
+ if (typeof payload !== 'string' && !types.isUint8Array(payload)) {
65
+ if (types.isAnyArrayBuffer(payload)) {
66
+ throw new ChatwiseError('payload must be the raw request body, as a string or bytes. Of an ArrayBuffer, pass `new Uint8Array(payload)`.');
67
+ }
68
+ throw new ChatwiseError('payload must be the raw request body, as a string or bytes. It looks parsed: verify the request before anything parses its body.');
69
+ }
70
+ if (typeof headers !== 'object' || headers === null)
71
+ throw new ChatwiseError('headers must be the request\'s headers.');
72
+ if (!Number.isFinite(toleranceSeconds) || toleranceSeconds < 0)
73
+ throw new ChatwiseError('toleranceSeconds must be a number of seconds.');
74
+ const currentTime = now === undefined ? Date.now() : now instanceof Date && now.getTime();
75
+ if (typeof currentTime !== 'number' || Number.isNaN(currentTime))
76
+ throw new ChatwiseError('now must be a valid Date.');
77
+ const id = readHeader(headers, 'webhook-id');
78
+ const timestamp = readHeader(headers, 'webhook-timestamp');
79
+ const signatures = readHeader(headers, 'webhook-signature');
80
+ if (!/^\d{1,12}$/.test(timestamp)) {
81
+ throw new WebhookVerificationError('malformed_header', 'The webhook-timestamp header is not a time in Unix seconds.');
82
+ }
83
+ const age = currentTime / 1000 - Number(timestamp);
84
+ if (age > toleranceSeconds)
85
+ throw new WebhookVerificationError('timestamp_too_old', `The request is ${Math.round(age)} seconds old.`);
86
+ if (age < -toleranceSeconds)
87
+ throw new WebhookVerificationError('timestamp_too_new', `The request is from ${Math.round(-age)} seconds in the future.`);
88
+ // `v1,<base64>`, one or more with spaces between. Other versions may be added, so they are skipped.
89
+ const candidates = signatures.split(' ').flatMap((entry) => {
90
+ const match = /^v1,([A-Za-z0-9+/]{43}=)$/.exec(entry);
91
+ return match ? [Buffer.from(match[1])] : [];
92
+ });
93
+ if (!candidates.length) {
94
+ throw new WebhookVerificationError('malformed_header', 'The webhook-signature header has no v1 signature.');
95
+ }
96
+ let matches = false;
97
+ for (const key of keys) {
98
+ const expected = Buffer.from(createHmac('sha256', key).update(`${id}.${timestamp}.`).update(payload).digest('base64'));
99
+ // Every candidate is 44 characters, as long as `expected`. No early exit, so that the time tells nothing.
100
+ for (const candidate of candidates)
101
+ matches = timingSafeEqual(candidate, expected) || matches;
102
+ }
103
+ if (!matches) {
104
+ throw new WebhookVerificationError('signature_mismatch', 'No signature matches. Check that the secret is this endpoint\'s and that the body is exactly as received, before any parsing.');
105
+ }
106
+ let event;
107
+ try {
108
+ event = JSON.parse(typeof payload === 'string' ? payload : Buffer.from(payload).toString('utf8'));
109
+ }
110
+ catch {
111
+ throw new WebhookVerificationError('invalid_payload', 'The body is not JSON.');
112
+ }
113
+ const { id: eventId, type } = (event ?? {});
114
+ if (typeof eventId !== 'string' || typeof type !== 'string') {
115
+ throw new WebhookVerificationError('invalid_payload', 'The body is not an event.');
116
+ }
117
+ return event;
118
+ }
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@chatwise/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": "Official Node.js SDK for the Chatwise API: read your WhatsApp, Instagram, Messenger and Website Chat inbox, send WhatsApp templates and verify webhooks.",
5
+ "keywords": [
6
+ "chatwise",
7
+ "whatsapp",
8
+ "whatsapp-business",
9
+ "instagram",
10
+ "messenger",
11
+ "inbox",
12
+ "webhooks",
13
+ "api",
14
+ "sdk"
15
+ ],
16
+ "homepage": "https://chatwise.so/docs",
17
+ "bugs": "https://github.com/vectorscalelabs/chatwise-node/issues",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/vectorscalelabs/chatwise-node.git"
21
+ },
22
+ "license": "Apache-2.0",
23
+ "author": "Chatwise (https://chatwise.so)",
24
+ "type": "module",
25
+ "sideEffects": false,
26
+ "main": "./dist/cjs/index.js",
27
+ "module": "./dist/esm/index.js",
28
+ "types": "./dist/cjs/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "import": {
32
+ "types": "./dist/esm/index.d.ts",
33
+ "default": "./dist/esm/index.js"
34
+ },
35
+ "require": {
36
+ "types": "./dist/cjs/index.d.ts",
37
+ "default": "./dist/cjs/index.js"
38
+ }
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "CHANGELOG.md"
45
+ ],
46
+ "engines": {
47
+ "node": ">=20"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "scripts": {
53
+ "spec:update": "node scripts/update-spec.mjs && npm run generate",
54
+ "generate": "node scripts/generate.mjs",
55
+ "generate:check": "node scripts/generate.mjs --check",
56
+ "build": "node scripts/build.mjs",
57
+ "lint": "eslint .",
58
+ "typecheck": "tsc -p tsconfig.json",
59
+ "test": "npm run build && node scripts/test.mjs",
60
+ "check:package": "npm run build && node scripts/check-package.mjs",
61
+ "check": "npm run generate:check && npm run lint && npm run typecheck && npm test && npm run check:package"
62
+ },
63
+ "devDependencies": {
64
+ "@arethetypeswrong/cli": "^0.18.5",
65
+ "@eslint/js": "^10.0.1",
66
+ "@hono/node-server": "^2.1.11",
67
+ "@types/express": "^5.0.6",
68
+ "@types/node": "^20.19.43",
69
+ "ajv": "^8.20.0",
70
+ "ajv-formats": "^3.0.1",
71
+ "esbuild": "^0.28.2",
72
+ "eslint": "^10.16.0",
73
+ "express": "^5.3.0",
74
+ "hono": "^4.13.23",
75
+ "publint": "^0.3.25",
76
+ "typescript": "~6.0.3",
77
+ "typescript-eslint": "^8.74.0",
78
+ "typescript5": "npm:typescript@5.0.4",
79
+ "typescript7": "npm:typescript@7.0.2"
80
+ }
81
+ }