domma-cms 1.46.0 → 1.47.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 (123) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/admin/js/lib/api-tokens-arrange.js +2 -2
  3. package/admin/js/lib/whatsapp-call.js +1 -0
  4. package/admin/js/templates/contacts.html +2 -0
  5. package/admin/js/views/api-tokens.js +9 -4
  6. package/admin/js/views/contacts.js +12 -11
  7. package/admin/js/views/form-editor.js +5 -5
  8. package/admin/js/views/plugins.js +1 -1
  9. package/docs/api-reference.md +22 -0
  10. package/package.json +1 -1
  11. package/plugins/_lib/admin/mail/body-menu.js +1 -1
  12. package/plugins/_lib/admin/mail/cms-host.js +1 -1
  13. package/plugins/_lib/admin/mail/compose-window.js +1 -1
  14. package/plugins/_lib/admin/mail/contacts.js +1 -1
  15. package/plugins/_lib/admin/mail/diagnostics-section.js +1 -1
  16. package/plugins/_lib/admin/mail/drag-drop.js +1 -1
  17. package/plugins/_lib/admin/mail/folder-tree.js +1 -1
  18. package/plugins/_lib/admin/mail/font-controls.js +1 -1
  19. package/plugins/_lib/admin/mail/fonts.js +1 -1
  20. package/plugins/_lib/admin/mail/host-context.js +1 -1
  21. package/plugins/_lib/admin/mail/identity.js +1 -1
  22. package/plugins/_lib/admin/mail/image-senders-section.js +1 -1
  23. package/plugins/_lib/admin/mail/keyboard.js +1 -1
  24. package/plugins/_lib/admin/mail/mail.html +1 -1
  25. package/plugins/_lib/admin/mail/message-actions.js +1 -1
  26. package/plugins/_lib/admin/mail/oauth-panel.js +1 -1
  27. package/plugins/_lib/admin/mail/panes.js +1 -1
  28. package/plugins/_lib/admin/mail/reader-kit.js +1 -1
  29. package/plugins/_lib/admin/mail/reader-runtime.js +7 -6
  30. package/plugins/_lib/admin/mail/reader-view.js +1 -1
  31. package/plugins/_lib/admin/mail/resizable.js +1 -1
  32. package/plugins/_lib/admin/mail/restore-spam.js +1 -1
  33. package/plugins/_lib/admin/mail/rules.js +1 -1
  34. package/plugins/_lib/admin/mail/scheduling.js +1 -1
  35. package/plugins/_lib/admin/mail/section-kit.js +1 -1
  36. package/plugins/_lib/admin/mail/security-note.js +1 -1
  37. package/plugins/_lib/admin/mail/settings-section.js +1 -1
  38. package/plugins/_lib/admin/mail/templates.js +1 -1
  39. package/plugins/_lib/admin/mail/threads.js +1 -1
  40. package/plugins/_lib/admin/mail/vacation.js +1 -1
  41. package/plugins/_lib/admin/mail/when-closed.js +1 -1
  42. package/plugins/_lib/admin/ui/dates.js +1 -1
  43. package/plugins/_lib/admin/ui/resizable.js +1 -1
  44. package/plugins/_lib/domma-mail.lock.json +80 -80
  45. package/plugins/_lib/mail/accountFileStore.js +1 -1
  46. package/plugins/_lib/mail/accountRepository.js +1 -1
  47. package/plugins/_lib/mail/accountRoutes.js +1 -1
  48. package/plugins/_lib/mail/bodyTokenProvider.js +1 -1
  49. package/plugins/_lib/mail/bodyTokens.js +1 -1
  50. package/plugins/_lib/mail/compose.js +1 -1
  51. package/plugins/_lib/mail/defaults.js +1 -1
  52. package/plugins/_lib/mail/envelope.js +1 -1
  53. package/plugins/_lib/mail/folderActions.js +1 -1
  54. package/plugins/_lib/mail/folderRuntime.js +1 -1
  55. package/plugins/_lib/mail/folders.js +1 -1
  56. package/plugins/_lib/mail/imapPoolRuntime.js +1 -1
  57. package/plugins/_lib/mail/mbox.js +1 -1
  58. package/plugins/_lib/mail/message-action.js +1 -1
  59. package/plugins/_lib/mail/messageSecurity.js +1 -1
  60. package/plugins/_lib/mail/messageSecurityProvider.js +1 -1
  61. package/plugins/_lib/mail/networkAddresses.js +1 -1
  62. package/plugins/_lib/mail/networkPolicy.js +1 -1
  63. package/plugins/_lib/mail/oauthAccounts.js +1 -1
  64. package/plugins/_lib/mail/oauthRouteRuntime.js +1 -1
  65. package/plugins/_lib/mail/oauthRuntime.js +1 -1
  66. package/plugins/_lib/mail/pollSchedule.js +1 -1
  67. package/plugins/_lib/mail/poller.js +1 -1
  68. package/plugins/_lib/mail/pollerRuntime.js +1 -1
  69. package/plugins/_lib/mail/priority.js +1 -1
  70. package/plugins/_lib/mail/publicMailbox.js +1 -1
  71. package/plugins/_lib/mail/readRuntime.js +1 -1
  72. package/plugins/_lib/mail/render.js +1 -1
  73. package/plugins/_lib/mail/ruleRunner.js +1 -1
  74. package/plugins/_lib/mail/schedulerRuntime.js +1 -1
  75. package/plugins/_lib/mail/secretProvider.js +1 -1
  76. package/plugins/_lib/mail/secretbox.js +1 -1
  77. package/plugins/_lib/mail/senderAuth.js +1 -1
  78. package/plugins/_lib/mail/sieve.js +1 -1
  79. package/plugins/_lib/mail/smtpService.js +1 -1
  80. package/plugins/_lib/mail/snoozeRuntime.js +1 -1
  81. package/plugins/_lib/mail/store.js +1 -1
  82. package/plugins/_lib/mail/subscriptions.js +1 -1
  83. package/plugins/_lib/mail/syncPlan.js +1 -1
  84. package/plugins/_lib/mail/syncRuntime.js +1 -1
  85. package/plugins/_lib/mail/syncSelection.js +1 -1
  86. package/plugins/_lib/mail/unreadBadge.js +1 -1
  87. package/plugins/_lib/mail/unsubscribe.js +1 -1
  88. package/plugins/_lib/mail/vacationRuntime.js +1 -1
  89. package/plugins/_lib/mail/write.js +1 -1
  90. package/plugins/blog/CHANGELOG.md +5 -0
  91. package/plugins/blog/plugin.js +3 -0
  92. package/plugins/blog/plugin.json +2 -2
  93. package/plugins/free-tier.lock.json +37 -16
  94. package/plugins/security/CHANGELOG.md +6 -0
  95. package/plugins/security/admin/lib/health.js +4 -1
  96. package/plugins/security/plugin.json +2 -2
  97. package/plugins/security/server/facts.js +2 -1
  98. package/plugins/security/tests/security.test.js +5 -0
  99. package/plugins/shopping-cart/CHANGELOG.md +7 -0
  100. package/plugins/shopping-cart/admin/views/orders.js +3 -4
  101. package/plugins/shopping-cart/lib/summary.js +1 -1
  102. package/plugins/shopping-cart/plugin.json +2 -2
  103. package/plugins/shopping-cart/public/lib/orders.js +16 -0
  104. package/plugins/shopping-cart/public/shop.css +1 -1
  105. package/plugins/shopping-cart/tests/pure.test.js +16 -0
  106. package/plugins/whatsapp-calling/CLAUDE.md +12 -0
  107. package/plugins/whatsapp-calling/admin/css/index.css +22 -0
  108. package/plugins/whatsapp-calling/admin/templates/index.html +56 -0
  109. package/plugins/whatsapp-calling/admin/views/connection-help.js +55 -0
  110. package/plugins/whatsapp-calling/admin/views/index.js +275 -0
  111. package/plugins/whatsapp-calling/config.js +7 -0
  112. package/plugins/whatsapp-calling/docs/guide.md +70 -0
  113. package/plugins/whatsapp-calling/lib/calls.js +156 -0
  114. package/plugins/whatsapp-calling/lib/meta.js +55 -0
  115. package/plugins/whatsapp-calling/lib/recipients.js +26 -0
  116. package/plugins/whatsapp-calling/plugin.js +123 -0
  117. package/plugins/whatsapp-calling/plugin.json +86 -0
  118. package/plugins/whatsapp-calling/tests/calling.test.js +254 -0
  119. package/server/routes/api/api-tokens.js +2 -2
  120. package/server/routes/api/collections.js +42 -17
  121. package/server/routes/api/endpoints-public.js +1 -2
  122. package/server/services/apiTokens.js +59 -4
  123. package/server/services/presetCollections.js +1 -0
@@ -0,0 +1,275 @@
1
+ import {CONNECTION_HELP, connectionGuide} from './connection-help.js';
2
+
3
+ const BASE = '/plugins/whatsapp-calling';
4
+ const ENDED = new Set(['ended', 'failed', 'rejected']);
5
+ let disposePrevious = () => {};
6
+
7
+ /** Meta receives a complete SDP, including ICE candidates; this API has no trickle-ICE endpoint. */
8
+ export function gatherIce(pc, timeout = 15000) {
9
+ if (pc.iceGatheringState === 'complete') return Promise.resolve();
10
+ return new Promise((resolve, reject) => {
11
+ const finish = error => {
12
+ clearTimeout(timer);
13
+ pc.removeEventListener('icegatheringstatechange', changed);
14
+ error ? reject(error) : resolve();
15
+ };
16
+ const changed = () => { if (pc.iceGatheringState === 'complete') finish(); };
17
+ const timer = setTimeout(() => finish(new Error('The microphone connection timed out. Check your network or TURN settings.')), timeout);
18
+ pc.addEventListener('icegatheringstatechange', changed);
19
+ changed();
20
+ });
21
+ }
22
+
23
+ export const indexView = {
24
+ templateUrl: `${BASE}/admin/templates/index.html`,
25
+ async onMount($container, prefill = {}) {
26
+ disposePrevious();
27
+ const {apiRequest} = await import('/admin/js/api.js');
28
+ const root = $container.find('.wac').get(0);
29
+ const startingHash = location.hash;
30
+ const request = (path, method = 'GET', body) => apiRequest(`${BASE}${path}`, {
31
+ method, ...(body === undefined ? {} : {body: JSON.stringify(body)})
32
+ });
33
+ const status = M.observable('Checking the Meta connection...'), error = M.observable('');
34
+ const ready = M.observable(false), busy = M.observable(false), active = M.observable(false);
35
+ const permission = M.observable(''), incoming = M.observable([]), recent = M.observable([]);
36
+ const callLabel = M.observable(''), callStatus = M.observable(''), muted = M.observable(false);
37
+ let id = '', pc = null, stream = null, iceServers = [], disposed = false, polling = false, timer;
38
+ let sequence = 0, settingsPanel = null, dialForm;
39
+ const audio = $(root).find('.wac-audio').get(0);
40
+ const cleanupAudio = () => {
41
+ sequence++;
42
+ if (pc) { pc.ontrack = null; pc.onconnectionstatechange = null; pc.close(); pc = null; }
43
+ stream?.getTracks().forEach(t => t.stop()); stream = null;
44
+ audio.srcObject = null; muted.value = false;
45
+ };
46
+ const clearCall = () => { id = ''; active.value = false; cleanupAudio(); };
47
+ const run = async fn => {
48
+ if (busy.peek()) return;
49
+ busy.value = true; error.value = '';
50
+ try { await fn(); } catch (e) { if (!disposed) error.value = e.message || 'The call could not be completed.'; }
51
+ finally { if (!disposed) busy.value = false; }
52
+ };
53
+ async function stopRemote() {
54
+ if (!id) return;
55
+ await request(`/calls/${encodeURIComponent(id)}/action`, 'POST', {action: 'terminate'});
56
+ clearCall();
57
+ }
58
+ async function microphone() {
59
+ if (!globalThis.RTCPeerConnection || !navigator.mediaDevices?.getUserMedia) throw new Error('Voice calls need HTTPS and a browser with microphone support.');
60
+ const generation = ++sequence;
61
+ const media = await navigator.mediaDevices.getUserMedia({audio: true, video: false});
62
+ if (disposed || generation !== sequence) { media.getTracks().forEach(t => t.stop()); throw new Error('The call was cancelled.'); }
63
+ stream = media;
64
+ const peer = new RTCPeerConnection({iceServers, bundlePolicy: 'max-bundle'});
65
+ pc = peer;
66
+ media.getTracks().forEach(t => peer.addTrack(t, media));
67
+ peer.ontrack = event => {
68
+ audio.srcObject = event.streams[0] || new MediaStream([event.track]);
69
+ audio.play().catch(() => { if (!disposed) error.value = 'Your browser paused the audio. Press Play call audio.'; });
70
+ };
71
+ peer.onconnectionstatechange = () => {
72
+ if (disposed || pc !== peer) return;
73
+ if (peer.connectionState === 'connected') callStatus.value = 'Connected';
74
+ if (peer.connectionState === 'failed') {
75
+ error.value = 'The audio connection failed. Check your network or TURN settings.';
76
+ cleanupAudio();
77
+ stopRemote().catch(() => { /* Keep the call ID so polling and End call can retry. */ });
78
+ }
79
+ };
80
+ return peer;
81
+ }
82
+ async function callFailure() {
83
+ cleanupAudio();
84
+ if (id) {
85
+ try { await stopRemote(); }
86
+ catch { error.value = 'Audio stopped, but Meta has not confirmed hang-up. Press End call again.'; }
87
+ }
88
+ }
89
+ async function refresh() {
90
+ if (disposed || polling || !ready.peek()) return;
91
+ polling = true;
92
+ try {
93
+ if (id) {
94
+ const currentId = id;
95
+ const c = await request(`/calls/${encodeURIComponent(currentId)}`);
96
+ if (disposed || id !== currentId) return;
97
+ callStatus.value = c.status;
98
+ if (ENDED.has(c.status)) clearCall();
99
+ else if (pc && c.session?.sdp_type === 'answer' && !pc.remoteDescription) {
100
+ await pc.setRemoteDescription({type: 'answer', sdp: c.session.sdp});
101
+ }
102
+ }
103
+ const result = await request('/calls');
104
+ if (disposed) return;
105
+ incoming.value = result.calls.filter(c => c.direction === 'inbound' && c.status === 'ringing' && !c.claimed);
106
+ recent.value = result.calls.filter(c => ENDED.has(c.status));
107
+ } catch (e) { if (!disposed) error.value = e.message || 'The call status could not be checked.'; }
108
+ finally { polling = false; }
109
+ }
110
+ async function settings() {
111
+ if (settingsPanel) return;
112
+ await run(async () => {
113
+ const c = await request('/settings');
114
+ if (disposed) return;
115
+ const panel = E.slideover({title: 'WhatsApp connection', size: 'md', position: 'right'});
116
+ settingsPanel = panel;
117
+ const content = document.createElement('div'); content.className = 'wac-settings';
118
+ const note = document.createElement('p');
119
+ note.textContent = 'Use a Meta Cloud API business number with Calling enabled. Saved secrets stay on the server. Leave secret fields blank to keep them.';
120
+ content.appendChild(note);
121
+ const callbackUrl = `${location.origin}/api/plugins/whatsapp-calling/webhook`;
122
+ content.appendChild(connectionGuide(callbackUrl));
123
+ const host = document.createElement('div'); content.appendChild(host);
124
+ const schema = {
125
+ phoneNumberId: {type: 'string', label: 'Meta phone number ID'},
126
+ apiVersion: {type: 'string', label: 'Graph API version'},
127
+ accessToken: {type: 'string', label: `System user access token${c.credentials.accessToken ? ' (saved)' : ''}`, formConfig: {type: 'password'}},
128
+ appSecret: {type: 'string', label: `Meta app secret${c.credentials.appSecret ? ' (saved)' : ''}`, formConfig: {type: 'password'}},
129
+ verifyToken: {type: 'string', label: `Webhook verification token${c.credentials.verifyToken ? ' (saved)' : ''}`, formConfig: {type: 'password'}}
130
+ };
131
+ for (const [key, help] of Object.entries(CONNECTION_HELP)) {
132
+ schema[key].formConfig = {...schema[key].formConfig, hint: help.hint};
133
+ }
134
+ const form = F.create(schema, {phoneNumberId: c.phoneNumberId, apiVersion: c.apiVersion,
135
+ accessToken: '', appSecret: '', verifyToken: ''}, {showSubmitButton: false, layout: 'stacked'});
136
+ form.renderTo(host);
137
+ $(host).find('input').each((_index, input) => {
138
+ if (['accessToken', 'appSecret', 'verifyToken'].includes(input.name)) { input.type = 'password'; input.autocomplete = 'new-password'; }
139
+ });
140
+ $(host).find('label').each((_index, label) => {
141
+ const key = (label.getAttribute('for') || '').replace(/^field-/, '');
142
+ if (!CONNECTION_HELP[key]) return;
143
+ label.setAttribute('data-help', CONNECTION_HELP[key].text);
144
+ label.setAttribute('data-help-title', schema[key].label);
145
+ });
146
+ let disposeHelp = () => {};
147
+ try {
148
+ const {helpPopovers} = await import('/admin/js/lib/help-popover.js');
149
+ disposeHelp = helpPopovers(host);
150
+ } catch {
151
+ const {scanHelp} = await import('/plugins/_lib/admin/ui/help.js');
152
+ scanHelp(host);
153
+ }
154
+ const callback = document.createElement('p'); callback.className = 'wac-callback';
155
+ const callbackLabel = document.createElement('strong'); callbackLabel.textContent = 'Your webhook callback URL';
156
+ const callbackAddress = document.createElement('code'); callbackAddress.textContent = callbackUrl;
157
+ const callbackHint = document.createElement('span'); callbackHint.className = 'text-sm text-muted';
158
+ callbackHint.textContent = 'Save the connection first, then paste this URL into Meta > WhatsApp > Configuration > Webhooks. Subscribe to calls and messages.';
159
+ callback.append(callbackLabel, callbackAddress, callbackHint);
160
+ content.appendChild(callback);
161
+ const save = document.createElement('button'); save.type = 'button'; save.className = 'btn btn-primary'; save.textContent = 'Save connection';
162
+ const feedback = document.createElement('p'); feedback.setAttribute('role', 'status');
163
+ save.addEventListener('click', async () => {
164
+ save.disabled = true;
165
+ try {
166
+ if (!form.validate()) return;
167
+ const result = await request('/settings', 'PUT', form.getData());
168
+ ready.value = result.ready;
169
+ status.value = result.ready ? 'Meta connection configured. Ready for calls.' : 'Add all Meta credentials to enable calls.';
170
+ feedback.textContent = 'Connection saved.';
171
+ for (const input of host.querySelectorAll('input[type="password"]')) { input.value = ''; input.dispatchEvent(new Event('input', {bubbles: true})); }
172
+ const state = await request('/status'); iceServers = state.iceServers;
173
+ await refresh();
174
+ } catch (e) { feedback.textContent = e.message || 'Settings could not be saved.'; }
175
+ finally { save.disabled = false; }
176
+ });
177
+ content.append(save, feedback); panel.element.appendChild(content);
178
+ const close = panel.close.bind(panel);
179
+ panel.close = (...args) => {
180
+ panel.close = close; close(...args); settingsPanel = null; disposeHelp(); form.destroy?.();
181
+ setTimeout(() => { panel.destroy?.(); panel.element?.remove(); }, 400);
182
+ };
183
+ panel.open();
184
+ });
185
+ }
186
+ const model = {status, error, ready, busy, active, permission, incoming, recent, callLabel, callStatus, muted,
187
+ checkPermission: () => run(async () => {
188
+ const result = await request(`/permission?to=${encodeURIComponent(dialForm.getData().to)}`);
189
+ permission.value = result.canCall ? 'This person currently allows a call.' : `Calls are not currently allowed (${result.status}). Ask for permission if needed.`;
190
+ }),
191
+ requestPermission: () => run(async () => {
192
+ const data = dialForm.getData();
193
+ await request('/permission', 'POST', {to: data.to, text: data.reason});
194
+ permission.value = 'Permission request sent. Wait for their response, then check permission again.';
195
+ }),
196
+ dial: () => run(async () => {
197
+ try {
198
+ const data = dialForm.getData();
199
+ const allowed = await request(`/permission?to=${encodeURIComponent(data.to)}`);
200
+ if (!allowed.canCall) throw new Error('This person has not allowed a call, or Meta currently limits calls to them.');
201
+ const peer = await microphone();
202
+ await peer.setLocalDescription(await peer.createOffer()); await gatherIce(peer);
203
+ if (disposed) return;
204
+ const c = await request('/calls', 'POST', {to: data.to, session: {sdp_type: 'offer', sdp: peer.localDescription.sdp}});
205
+ id = c.id;
206
+ if (disposed) { await stopRemote(); return; }
207
+ active.value = true; callLabel.value = `Calling +${c.phone}`; callStatus.value = c.status;
208
+ await refresh();
209
+ } catch (e) { await callFailure(); throw e; }
210
+ }),
211
+ answer: c => run(async () => {
212
+ try {
213
+ // Obtain microphone consent before claiming, so denial leaves the call available to others.
214
+ const peer = await microphone();
215
+ const claimed = await request(`/calls/${encodeURIComponent(c.id)}/claim`, 'POST'); id = claimed.id;
216
+ if (disposed) { await stopRemote(); return; }
217
+ active.value = true; callLabel.value = `Call from +${c.phone}`; callStatus.value = 'Connecting';
218
+ await peer.setRemoteDescription({type: 'offer', sdp: claimed.session.sdp});
219
+ await peer.setLocalDescription(await peer.createAnswer()); await gatherIce(peer);
220
+ await request(`/calls/${encodeURIComponent(id)}/action`, 'POST', {action: 'accept', session: {sdp_type: 'answer', sdp: peer.localDescription.sdp}});
221
+ await refresh();
222
+ } catch (e) { await callFailure(); throw e; }
223
+ }),
224
+ reject: c => run(async () => {
225
+ const claimed = await request(`/calls/${encodeURIComponent(c.id)}/claim`, 'POST');
226
+ id = claimed.id;
227
+ if (disposed) { await stopRemote(); return; }
228
+ active.value = true; callLabel.value = `Call from +${c.phone}`;
229
+ await request(`/calls/${encodeURIComponent(id)}/action`, 'POST', {action: 'reject'});
230
+ clearCall(); await refresh();
231
+ }),
232
+ hangup: () => run(async () => { cleanupAudio(); await stopRemote(); await refresh(); }),
233
+ mute() { muted.value = !muted.peek(); stream?.getAudioTracks().forEach(t => { t.enabled = !muted.peek(); }); },
234
+ playAudio: () => run(() => audio.play())
235
+ };
236
+ const methods = Object.fromEntries(Object.entries(model).filter(([, v]) => typeof v === 'function' && !M.isObservable?.(v)));
237
+ const binding = M.applyBindings(model, root, {methods});
238
+ dialForm = F.create({
239
+ to: {type: 'string', label: 'WhatsApp number', formConfig: {placeholder: '+44 7700 900123'}},
240
+ reason: {type: 'string', label: 'Why would you like to call?', formConfig: {hint: 'Permission requests need an open WhatsApp customer service window. Meta applies its request limits.'}}
241
+ }, {to: prefill.phone || new URLSearchParams(location.hash.split('?')[1] || '').get('phone') || '',
242
+ reason: prefill.reason || 'We would like to call you about your enquiry. May we call you on WhatsApp?'}, {showSubmitButton: false, layout: 'stacked'});
243
+ dialForm.renderTo($(root).find('.wac-dial-form').get(0));
244
+ const onHash = () => { if (prefill.embedded ? location.hash !== startingHash : !/^#\/plugins\/whatsapp-calling(?:\?|$)/.test(location.hash)) disposePrevious(); };
245
+ disposePrevious = () => {
246
+ if (disposed) return;
247
+ disposed = true; clearInterval(timer); window.removeEventListener('hashchange', onHash);
248
+ cleanupAudio();
249
+ if (id) request(`/calls/${encodeURIComponent(id)}/action`, 'POST', {action: 'terminate'}).catch(() => {});
250
+ settingsPanel?.close(); dialForm.destroy?.(); binding?.dispose?.();
251
+ };
252
+ window.addEventListener('hashchange', onHash);
253
+ try {
254
+ const state = await request('/status');
255
+ if (disposed) return disposePrevious;
256
+ ready.value = state.ready; iceServers = state.iceServers;
257
+ status.value = state.ready ? 'Meta connection configured. Ready for calls.' : 'Configure your Meta connection using the settings button.';
258
+ await refresh();
259
+ timer = setInterval(refresh, 2000);
260
+ // Only administrators get the settings control. The server enforces this on both settings routes.
261
+ try {
262
+ await request('/settings');
263
+ if (disposed) return;
264
+ try {
265
+ const {addBannerAction} = await import('/admin/js/lib/plugin-chrome.js');
266
+ if (!addBannerAction($container, {icon: 'settings', title: 'WhatsApp connection', onClick: settings, id: 'wac-settings'})) throw new Error('No banner');
267
+ } catch {
268
+ const button = $(root).find('.wac-settings-fallback').get(0); button.hidden = false; button.addEventListener('click', settings);
269
+ }
270
+ } catch { /* Operators do not manage the site's credentials. */ }
271
+ } catch (e) { if (!disposed) error.value = e.message || 'WhatsApp calling is unavailable.'; }
272
+ I.scan(root);
273
+ return disposePrevious;
274
+ }
275
+ };
@@ -0,0 +1,7 @@
1
+ export default {
2
+ phoneNumberId: '',
3
+ apiVersion: 'v23.0',
4
+ accessToken: '',
5
+ appSecret: '',
6
+ verifyToken: ''
7
+ };
@@ -0,0 +1,70 @@
1
+ ---
2
+ title: WhatsApp Calling
3
+ order: 1
4
+ ---
5
+
6
+ ## Connect Meta
7
+
8
+ WhatsApp Calling connects directly to Meta's WhatsApp Cloud API. It makes and receives voice calls in the admin browser, using your business number. Meta charges for business-initiated calls. There is no Twilio account or provider markup.
9
+
10
+ 1. Prepare a Meta business app, a WhatsApp Business Account and a registered Cloud API phone number eligible for Calling. Enable Calling for that number using Meta's calling settings. Eligibility, supported countries and billing are controlled by Meta. This tool does not register a number or enable calling automatically.
11
+ 2. Create a system user access token with access to that number and `whatsapp_business_messaging`. Account management tasks in Meta may also require `whatsapp_business_management`. Keep your token current.
12
+ 3. Open WhatsApp Calling in the admin and click the settings cog in its banner. Enter the **phone number ID** from Meta, the Graph API version (default `v23.0`), the access token, your Meta app secret and a long random webhook verification token you choose. Save the connection. Blank secret fields keep the values already saved. A configured connection means all required fields exist; it does not certify Meta eligibility or token validity.
13
+ 4. In your Meta app's WhatsApp webhook settings, use `https://YOUR-SITE/api/plugins/whatsapp-calling/webhook` as the callback URL and the same verification token. Subscribe the app to your WhatsApp Business Account and subscribe to the `calls` and `messages` webhook fields. The app secret verifies incoming webhook signatures.
14
+ 5. Open this tool over HTTPS, allow microphone access and test a call with someone who has agreed to help. If audio cannot connect on your network, configure the CMS's existing `config/calls.json` STUN/TURN settings.
15
+
16
+ Connection credentials are server-side plugin settings in `config/plugins.json`. They are masked in the Marketplace and never returned by this tool. Protect that configuration and its backups as you do other CMS secrets.
17
+
18
+ ## Where to find each connection value
19
+
20
+ The connection panel includes a **Step-by-step Meta connection setup** guide, a visible hint under each field and a **(?)** button beside each label. Click a (?) for more detail without leaving the form.
21
+
22
+ | Field | Where to find it |
23
+ | --- | --- |
24
+ | Meta phone number ID | Meta for Developers > your app > WhatsApp > API Setup (or Getting Started). Select your business number and copy **Phone number ID**. This is different from the telephone number, App ID and WhatsApp Business Account ID. |
25
+ | Graph API version | Keep the default `v23.0` unless your app needs another supported Meta Graph API version. |
26
+ | System user access token | Meta Business Settings > Users > System users. Assign the app and WhatsApp Business Account to the system user, then generate a token with `whatsapp_business_messaging`. Account management may also need `whatsapp_business_management`. Temporary API Setup tokens expire; use a system user token for ongoing use. |
27
+ | Meta app secret | Meta for Developers > the same app > App settings > Basic > App secret > Show. |
28
+ | Webhook verification token | Create your own long random value. Save it here and use exactly the same value in Meta's webhook Verify token field. Meta does not generate this value for you. |
29
+
30
+ **Save the connection before choosing Verify and save in Meta.** The callback URL is shown below the fields and uses this site's address. Set it in WhatsApp > Configuration > Webhooks, enter the matching verification token, subscribe to `calls` and `messages`, and ensure the app is subscribed to your WhatsApp Business Account.
31
+
32
+ If verification fails, check that you saved the form, both verification tokens match and the HTTPS callback URL is reachable. If calls fail, check the access token's expiry and assigned assets, Calling eligibility and recipient permission.
33
+
34
+ Use [Meta apps](https://developers.facebook.com/apps/), [Meta Business Settings](https://business.facebook.com/settings/) and [Meta's Calling documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/) alongside the guide. Meta's screen labels may vary by app setup.
35
+
36
+ ## Call from Contacts, Calendar or Email
37
+
38
+ The tool appears under **Tools > User > WhatsApp Calling**. It also opens as a calling panel inside other tools, keeping your current page and unsaved work in place. Opening the panel never starts a call automatically.
39
+
40
+ - **Contacts and Contacts Pro:** choose **Call on WhatsApp** from a contact's menu, or **WhatsApp call** in the contact editor. The editor uses the number you have typed, even before saving.
41
+ - **Calendar:** the banner's phone button opens the caller. An event's **Call attendee on WhatsApp** menu lets you choose one attendee. An RSVP's menu also offers **Call on WhatsApp**.
42
+ - **Email Pro:** choose **Call sender on WhatsApp** from a message's menu, including the reading pane menu. The sender's address is matched to contacts you can read, including their extra email addresses. A signature's phone number is not used.
43
+
44
+ If a contact has several numbers or several readable contacts match an email address, choose the person and number first. If no readable contact has a number, enter the full international number manually. Contacts visibility and sharing rules still apply. The actions appear only while WhatsApp Calling is enabled and your role can make calls. Meta credentials and recipient permission are still required.
45
+
46
+ Closing the calling panel stops your microphone and requests hang-up. Leaving the source tool also closes the caller. Do not close it during a call you wish to keep.
47
+
48
+ ## Make a call
49
+
50
+ Enter a full international WhatsApp number, including its country code. **Check permission** asks Meta whether a call is currently allowed.
51
+
52
+ If needed, explain why you would like to call and choose **Request permission**. This sends a permission request through Meta. It requires an open customer service window and is subject to Meta's request limits. Sending the request does not grant permission. Wait for the recipient to respond, then check permission again. Requests outside that window require an approved Meta template; sending templates is not included in this version.
53
+
54
+ Choose **Call on WhatsApp** to allow your microphone and dial. The server checks Meta's permission again immediately before connecting. A permitted call may still fail if Meta eligibility, billing or country restrictions prevent it. Rejection messages include Meta's error code for diagnosis.
55
+
56
+ ## Receive a call
57
+
58
+ Keep WhatsApp Calling open to see incoming calls. Choose **Answer** to allow the microphone and take the call, or **Decline**. Once someone takes a call, it belongs to that operator and other operators cannot listen to it or control it. Answering and dialling require the WhatsApp Calling `create` permission; viewing the tool requires `read`. Administrators manage connection settings.
59
+
60
+ Only one active call per operator is supported. Calls use voice only. **Mute microphone**, **Play call audio** and **End call** control the current call. The Play button resumes audio if the browser blocks automatic playback.
61
+
62
+ ## Session behaviour
63
+
64
+ Keep the page open throughout a call. Leaving the tool stops the microphone and requests hang-up. If a browser disappears, the server attempts to end the abandoned call after 60 seconds without a heartbeat, retrying if Meta is temporarily unavailable. Unanswered incoming calls are declined after 60 seconds.
65
+
66
+ A server restart ends local call sessions. A graceful shutdown attempts remote hang-up; an abrupt server failure relies on Meta's disconnected-session expiry. Recent call metadata is retained in memory for up to one hour after hang-up and is cleared on restart. Audio and transcripts are not recorded or stored, and session descriptions are discarded at hang-up.
67
+
68
+ Use one CMS server process for this tool. Calls and operator ownership are process-local; a multi-worker deployment requires shared call state and webhook routing before it can use this plugin reliably.
69
+
70
+ See [Meta's Calling documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/) for current eligibility, permissions and charges.
@@ -0,0 +1,156 @@
1
+ import {randomUUID} from 'node:crypto';
2
+ import {CallingError, allows, phone, session} from './meta.js';
3
+
4
+ const ENDED = new Set(['ended', 'failed', 'rejected']);
5
+ /** A process owns its WebRTC sessions. Only metadata is retained, for one hour; SDP is erased at hang-up. */
6
+ export function createCalls({meta, now = Date.now, getPhoneNumberId = async () => ''}) {
7
+ const records = new Map();
8
+ const locks = new Set();
9
+ const active = c => !ENDED.has(c.status);
10
+ function trim() {
11
+ for (const [id, c] of records) if (!active(c) && now() - c.updatedAt > 3600000) records.delete(id);
12
+ if (records.size >= 500) {
13
+ for (const [id, c] of records) { if (!active(c)) records.delete(id); if (records.size < 500) break; }
14
+ }
15
+ }
16
+ function finish(c, status = 'ended') { c.status = status; c.session = null; c.updatedAt = now(); }
17
+ function add(values) {
18
+ trim();
19
+ if (records.size >= 500) throw new CallingError('The call queue is full. Try again later.', 429);
20
+ const c = {id: randomUUID(), metaId: '', owner: '', status: 'ringing', direction: 'inbound', session: null,
21
+ createdAt: now(), updatedAt: now(), heartbeat: now(), ...values};
22
+ records.set(c.id, c);
23
+ return c;
24
+ }
25
+ function get(id, user, claimable = false) {
26
+ const c = records.get(id);
27
+ if (!c || (c.owner !== user && !(claimable && !c.owner && c.direction === 'inbound' && active(c)))) {
28
+ throw new CallingError('That call is not available to you.', 404);
29
+ }
30
+ return c;
31
+ }
32
+ const shape = c => ({id: c.id, phone: c.phone, direction: c.direction, status: c.status,
33
+ createdAt: c.createdAt, updatedAt: c.updatedAt, claimed: Boolean(c.owner)});
34
+ function busy(user) { return [...records.values()].some(c => c.owner === user && active(c)); }
35
+ async function locked(id, fn) {
36
+ if (locks.has(id)) throw new CallingError('This call is being updated. Try again.', 409);
37
+ locks.add(id);
38
+ try { return await fn(); } finally { locks.delete(id); }
39
+ }
40
+ return {
41
+ hasActive: () => locks.size > 0 || [...records.values()].some(active),
42
+ async close() {
43
+ for (const c of records.values()) {
44
+ if (active(c) && c.metaId) {
45
+ try { await this.action(c.id, c.owner, c.direction === 'inbound' && c.status === 'ringing' ? 'reject' : 'terminate'); }
46
+ catch { /* Meta eventually expires disconnected sessions. */ }
47
+ }
48
+ }
49
+ },
50
+ list(user) {
51
+ trim();
52
+ return [...records.values()].filter(c => c.owner === user || (!c.owner && c.direction === 'inbound' && active(c)))
53
+ .sort((a, b) => b.createdAt - a.createdAt).slice(0, 50).map(shape);
54
+ },
55
+ async dial(user, to, offer) {
56
+ to = phone(to); offer = session(offer, 'offer');
57
+ return locked(`user:${user}`, async () => {
58
+ if (busy(user)) throw new CallingError('End your current call first.', 409);
59
+ const phoneNumberId = await getPhoneNumberId();
60
+ const permission = await meta('call_permissions', {query: {user_wa_id: to}, phoneNumberId});
61
+ if (!allows(permission, 'start_call')) throw new CallingError('This person has not allowed a call, or Meta currently limits calls to them.', 409);
62
+ const c = add({owner: user, phone: to, direction: 'outbound', status: 'dialling', phoneNumberId});
63
+ try {
64
+ const result = await meta('calls', {method: 'POST', phoneNumberId, body: {messaging_product: 'whatsapp', to,
65
+ action: 'connect', session: offer, biz_opaque_callback_data: c.id}});
66
+ c.metaId = result.calls?.[0]?.id || c.metaId;
67
+ if (!c.metaId) throw new CallingError('Meta did not return a call ID.', 502, true);
68
+ return shape(c);
69
+ } catch (e) {
70
+ if (e.uncertain || c.metaId) {
71
+ // A lost HTTP response does not mean Meta refused the call. Keep the correlation
72
+ // until its signed webhook supplies an ID, then sweep it straight into hang-up.
73
+ c.status = 'ending'; c.session = null; c.heartbeat = now() - 61000;
74
+ } else finish(c, 'failed');
75
+ throw e;
76
+ }
77
+ });
78
+ },
79
+ claim(id, user) {
80
+ const c = get(id, user, true);
81
+ if (!active(c) || c.direction !== 'inbound') throw new CallingError('That call has ended.', 409);
82
+ if (!c.owner && (busy(user) || locks.has(`user:${user}`))) throw new CallingError('End your current call first.', 409);
83
+ c.owner = user; c.heartbeat = now();
84
+ return {...shape(c), session: c.session};
85
+ },
86
+ poll(id, user) {
87
+ const c = get(id, user); c.heartbeat = now();
88
+ return {...shape(c), session: c.session};
89
+ },
90
+ async action(id, user, action, answer) {
91
+ return locked(id, async () => {
92
+ const c = get(id, user);
93
+ if (!active(c)) return shape(c);
94
+ if (!['accept', 'reject', 'terminate'].includes(action)) throw new CallingError('Unknown call action.');
95
+ if (action !== 'terminate' && (c.direction !== 'inbound' || c.status !== 'ringing')) throw new CallingError('That action is not available.', 409);
96
+ const body = {messaging_product: 'whatsapp', call_id: c.metaId, action};
97
+ if (action === 'accept') body.session = session(answer, 'answer');
98
+ await meta('calls', {method: 'POST', body, phoneNumberId: c.phoneNumberId});
99
+ if (action === 'accept') { if (active(c)) { c.status = 'connected'; c.updatedAt = now(); } }
100
+ else finish(c, action === 'reject' ? 'rejected' : 'ended');
101
+ return shape(c);
102
+ });
103
+ },
104
+ webhook(payload, phoneNumberId) {
105
+ if (payload?.object !== 'whatsapp_business_account') return;
106
+ for (const entry of payload.entry || []) for (const change of entry.changes || []) {
107
+ const value = change.value;
108
+ if (String(value?.metadata?.phone_number_id) !== phoneNumberId) continue;
109
+ for (const event of value.calls || []) {
110
+ if (typeof event.id !== 'string' || event.id.length > 250) continue;
111
+ let c = [...records.values()].find(x => x.metaId === event.id);
112
+ // A connect webhook can arrive before the HTTP connect response.
113
+ if (!c && typeof event.biz_opaque_callback_data === 'string') {
114
+ const pending = records.get(event.biz_opaque_callback_data);
115
+ if (pending?.direction === 'outbound' && !pending.metaId) c = pending;
116
+ }
117
+ if (!c && event.event === 'connect' && event.direction === 'USER_INITIATED') {
118
+ let to, offer;
119
+ try { to = phone(event.from); offer = session(event.session, 'offer'); } catch { continue; }
120
+ if (records.size >= 500) { trim(); if (records.size >= 500) continue; }
121
+ c = add({metaId: event.id, phone: to, session: offer, phoneNumberId});
122
+ }
123
+ if (!c && event.event === 'terminate') {
124
+ // Keep a bounded tombstone when delivery order puts hang-up before connect.
125
+ trim();
126
+ if (records.size < 500) add({metaId: event.id, phone: '', status: 'ended', phoneNumberId});
127
+ }
128
+ if (!c || !active(c)) continue;
129
+ c.metaId = event.id;
130
+ if (event.event === 'terminate') finish(c);
131
+ else if (event.event === 'connect' && c.direction === 'outbound' && c.status !== 'ending') {
132
+ try { c.session = session(event.session, 'answer'); c.status = 'connected'; } catch { continue; }
133
+ c.updatedAt = now();
134
+ }
135
+ }
136
+ for (const status of value.statuses || []) {
137
+ const c = [...records.values()].find(x => x.metaId === status.id);
138
+ if (c && active(c) && ['FAILED', 'REJECTED', 'COMPLETED'].includes(String(status.status).toUpperCase())) {
139
+ finish(c, String(status.status).toUpperCase() === 'FAILED' ? 'failed' : 'ended');
140
+ }
141
+ }
142
+ }
143
+ },
144
+ async sweep() {
145
+ for (const c of records.values()) {
146
+ if (!active(c)) continue;
147
+ const stale = c.status === 'ending' || (c.owner ? now() - c.heartbeat > 60000 : now() - c.createdAt > 60000);
148
+ if (c.status === 'ending' && !c.metaId && now() - c.createdAt > 120000) { finish(c, 'failed'); continue; }
149
+ if (!stale || locks.has(c.id) || !c.metaId) continue;
150
+ try { await this.action(c.id, c.owner, c.direction === 'inbound' && c.status === 'ringing' ? 'reject' : 'terminate'); }
151
+ catch { /* Retry at the next sweep; never silently abandon a potentially billable call. */ }
152
+ }
153
+ trim();
154
+ }
155
+ };
156
+ }
@@ -0,0 +1,55 @@
1
+ import {createHmac, timingSafeEqual} from 'node:crypto';
2
+
3
+ export class CallingError extends Error {
4
+ constructor(message, statusCode = 400, uncertain = false) { super(message); this.statusCode = statusCode; this.uncertain = uncertain; }
5
+ }
6
+ export function phone(value) {
7
+ const result = String(value || '').trim().replace(/[+ ()-]/g, '');
8
+ if (!/^[1-9]\d{6,14}$/.test(result)) throw new CallingError('Enter an international phone number, including its country code.');
9
+ return result;
10
+ }
11
+ export function session(value, type) {
12
+ if (value?.sdp_type !== type || typeof value.sdp !== 'string' || value.sdp.length > 64000
13
+ || !value.sdp.startsWith('v=0') || !/^m=audio /m.test(value.sdp) || /^m=video /m.test(value.sdp)) {
14
+ throw new CallingError('A valid voice call session is required.');
15
+ }
16
+ return {sdp_type: type, sdp: value.sdp};
17
+ }
18
+ export function signed(body, signature, secret) {
19
+ if (!secret || !Buffer.isBuffer(body) || !/^sha256=[a-f0-9]{64}$/.test(signature || '')) return false;
20
+ const expected = createHmac('sha256', secret).update(body).digest();
21
+ return timingSafeEqual(expected, Buffer.from(signature.slice(7), 'hex'));
22
+ }
23
+ export function equalSecret(a, b) {
24
+ const x = Buffer.from(String(a || '')), y = Buffer.from(String(b || ''));
25
+ return x.length > 0 && x.length === y.length && timingSafeEqual(x, y);
26
+ }
27
+ export function ready(c) {
28
+ return /^\d+$/.test(c.phoneNumberId || '') && /^v\d+\.0$/.test(c.apiVersion || '')
29
+ && Boolean(c.accessToken && c.appSecret && c.verifyToken);
30
+ }
31
+ export function createMeta({settings, fetcher = globalThis.fetch}) {
32
+ return async function meta(endpoint, {method = 'GET', body, query, phoneNumberId} = {}) {
33
+ const c = await settings();
34
+ if (!ready(c)) throw new CallingError('Configure the Meta connection first.', 409);
35
+ const numberId = phoneNumberId || c.phoneNumberId;
36
+ if (!/^\d+$/.test(numberId)) throw new CallingError('Invalid business phone number ID.');
37
+ const url = new URL(`https://graph.facebook.com/${c.apiVersion}/${numberId}/${endpoint}`);
38
+ for (const [k, v] of Object.entries(query || {})) url.searchParams.set(k, v);
39
+ let response;
40
+ try {
41
+ response = await fetcher(url, {method, redirect: 'error', signal: AbortSignal.timeout(15000),
42
+ headers: {Authorization: `Bearer ${c.accessToken}`, 'Content-Type': 'application/json'},
43
+ ...(body ? {body: JSON.stringify(body)} : {})});
44
+ } catch { throw new CallingError('Meta could not be reached. Check the connection before retrying.', 502, true); }
45
+ let result;
46
+ try { result = await response.json(); } catch { throw new CallingError('Meta returned an unreadable response.', 502, true); }
47
+ if (!response.ok || result.error) {
48
+ const code = Number(result.error?.code) || response.status;
49
+ // Meta's raw errors can echo request details. Keep credentials and SDP out of responses and logs.
50
+ throw new CallingError(`Meta rejected this request (code ${code}). Check calling eligibility, recipient permission and your Meta account.`, 502);
51
+ }
52
+ return result;
53
+ };
54
+ }
55
+ export const allows = (p, action) => p?.actions?.some(a => a.action_name === action && a.can_perform_action === true) === true;
@@ -0,0 +1,26 @@
1
+ /** Phone lookup never expands the caller's existing Contacts visibility. */
2
+ import {phone} from './meta.js';
3
+ export function recipientsFrom(entries, {email = '', contactId = ''} = {}) {
4
+ const wanted = String(email).trim().toLowerCase();
5
+ return entries.filter(c => contactId ? String(c.id) === contactId : wanted && [c.data?.email, c.data?.billingEmail,
6
+ ...(c.data?.emails || []).map(e => e.address)].some(e => String(e || '').trim().toLowerCase() === wanted))
7
+ .flatMap(c => {
8
+ const numbers = [c.data?.phone, ...(c.data?.phones || []).map(p => p.number)];
9
+ const seen = new Set();
10
+ return numbers.flatMap(value => {
11
+ let number;
12
+ try { number = phone(value); } catch { return []; }
13
+ if (seen.has(number)) return []; seen.add(number);
14
+ return [{id: c.id, name: String(c.data?.name || ''), phone: `+${number}`}];
15
+ });
16
+ }).slice(0, 30);
17
+ }
18
+
19
+ export function createRecipientLookup({canRead, list, readable}) {
20
+ return async (viewer, query) => {
21
+ if (!await canRead(viewer)) return [];
22
+ const entries = await list();
23
+ const ids = await readable(entries, viewer);
24
+ return recipientsFrom(entries.filter(c => ids.has(c.id)), query);
25
+ };
26
+ }