domma-cms 1.46.1 → 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 (121) hide show
  1. package/CHANGELOG.md +7 -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/docs/api-reference.md +22 -0
  9. package/package.json +1 -1
  10. package/plugins/_lib/admin/mail/body-menu.js +1 -1
  11. package/plugins/_lib/admin/mail/cms-host.js +1 -1
  12. package/plugins/_lib/admin/mail/compose-window.js +1 -1
  13. package/plugins/_lib/admin/mail/contacts.js +1 -1
  14. package/plugins/_lib/admin/mail/diagnostics-section.js +1 -1
  15. package/plugins/_lib/admin/mail/drag-drop.js +1 -1
  16. package/plugins/_lib/admin/mail/folder-tree.js +1 -1
  17. package/plugins/_lib/admin/mail/font-controls.js +1 -1
  18. package/plugins/_lib/admin/mail/fonts.js +1 -1
  19. package/plugins/_lib/admin/mail/host-context.js +1 -1
  20. package/plugins/_lib/admin/mail/identity.js +1 -1
  21. package/plugins/_lib/admin/mail/image-senders-section.js +1 -1
  22. package/plugins/_lib/admin/mail/keyboard.js +1 -1
  23. package/plugins/_lib/admin/mail/mail.html +1 -1
  24. package/plugins/_lib/admin/mail/message-actions.js +1 -1
  25. package/plugins/_lib/admin/mail/oauth-panel.js +1 -1
  26. package/plugins/_lib/admin/mail/panes.js +1 -1
  27. package/plugins/_lib/admin/mail/reader-kit.js +1 -1
  28. package/plugins/_lib/admin/mail/reader-runtime.js +7 -6
  29. package/plugins/_lib/admin/mail/reader-view.js +1 -1
  30. package/plugins/_lib/admin/mail/resizable.js +1 -1
  31. package/plugins/_lib/admin/mail/restore-spam.js +1 -1
  32. package/plugins/_lib/admin/mail/rules.js +1 -1
  33. package/plugins/_lib/admin/mail/scheduling.js +1 -1
  34. package/plugins/_lib/admin/mail/section-kit.js +1 -1
  35. package/plugins/_lib/admin/mail/security-note.js +1 -1
  36. package/plugins/_lib/admin/mail/settings-section.js +1 -1
  37. package/plugins/_lib/admin/mail/templates.js +1 -1
  38. package/plugins/_lib/admin/mail/threads.js +1 -1
  39. package/plugins/_lib/admin/mail/vacation.js +1 -1
  40. package/plugins/_lib/admin/mail/when-closed.js +1 -1
  41. package/plugins/_lib/admin/ui/dates.js +1 -1
  42. package/plugins/_lib/admin/ui/resizable.js +1 -1
  43. package/plugins/_lib/domma-mail.lock.json +80 -80
  44. package/plugins/_lib/mail/accountFileStore.js +1 -1
  45. package/plugins/_lib/mail/accountRepository.js +1 -1
  46. package/plugins/_lib/mail/accountRoutes.js +1 -1
  47. package/plugins/_lib/mail/bodyTokenProvider.js +1 -1
  48. package/plugins/_lib/mail/bodyTokens.js +1 -1
  49. package/plugins/_lib/mail/compose.js +1 -1
  50. package/plugins/_lib/mail/defaults.js +1 -1
  51. package/plugins/_lib/mail/envelope.js +1 -1
  52. package/plugins/_lib/mail/folderActions.js +1 -1
  53. package/plugins/_lib/mail/folderRuntime.js +1 -1
  54. package/plugins/_lib/mail/folders.js +1 -1
  55. package/plugins/_lib/mail/imapPoolRuntime.js +1 -1
  56. package/plugins/_lib/mail/mbox.js +1 -1
  57. package/plugins/_lib/mail/message-action.js +1 -1
  58. package/plugins/_lib/mail/messageSecurity.js +1 -1
  59. package/plugins/_lib/mail/messageSecurityProvider.js +1 -1
  60. package/plugins/_lib/mail/networkAddresses.js +1 -1
  61. package/plugins/_lib/mail/networkPolicy.js +1 -1
  62. package/plugins/_lib/mail/oauthAccounts.js +1 -1
  63. package/plugins/_lib/mail/oauthRouteRuntime.js +1 -1
  64. package/plugins/_lib/mail/oauthRuntime.js +1 -1
  65. package/plugins/_lib/mail/pollSchedule.js +1 -1
  66. package/plugins/_lib/mail/poller.js +1 -1
  67. package/plugins/_lib/mail/pollerRuntime.js +1 -1
  68. package/plugins/_lib/mail/priority.js +1 -1
  69. package/plugins/_lib/mail/publicMailbox.js +1 -1
  70. package/plugins/_lib/mail/readRuntime.js +1 -1
  71. package/plugins/_lib/mail/render.js +1 -1
  72. package/plugins/_lib/mail/ruleRunner.js +1 -1
  73. package/plugins/_lib/mail/schedulerRuntime.js +1 -1
  74. package/plugins/_lib/mail/secretProvider.js +1 -1
  75. package/plugins/_lib/mail/secretbox.js +1 -1
  76. package/plugins/_lib/mail/senderAuth.js +1 -1
  77. package/plugins/_lib/mail/sieve.js +1 -1
  78. package/plugins/_lib/mail/smtpService.js +1 -1
  79. package/plugins/_lib/mail/snoozeRuntime.js +1 -1
  80. package/plugins/_lib/mail/store.js +1 -1
  81. package/plugins/_lib/mail/subscriptions.js +1 -1
  82. package/plugins/_lib/mail/syncPlan.js +1 -1
  83. package/plugins/_lib/mail/syncRuntime.js +1 -1
  84. package/plugins/_lib/mail/syncSelection.js +1 -1
  85. package/plugins/_lib/mail/unreadBadge.js +1 -1
  86. package/plugins/_lib/mail/unsubscribe.js +1 -1
  87. package/plugins/_lib/mail/vacationRuntime.js +1 -1
  88. package/plugins/_lib/mail/write.js +1 -1
  89. package/plugins/blog/CHANGELOG.md +5 -0
  90. package/plugins/blog/plugin.js +3 -0
  91. package/plugins/blog/plugin.json +2 -2
  92. package/plugins/free-tier.lock.json +37 -16
  93. package/plugins/security/CHANGELOG.md +6 -0
  94. package/plugins/security/admin/lib/health.js +4 -1
  95. package/plugins/security/plugin.json +2 -2
  96. package/plugins/security/server/facts.js +2 -1
  97. package/plugins/security/tests/security.test.js +5 -0
  98. package/plugins/shopping-cart/CHANGELOG.md +7 -0
  99. package/plugins/shopping-cart/admin/views/orders.js +3 -4
  100. package/plugins/shopping-cart/lib/summary.js +1 -1
  101. package/plugins/shopping-cart/plugin.json +2 -2
  102. package/plugins/shopping-cart/public/lib/orders.js +16 -0
  103. package/plugins/shopping-cart/public/shop.css +1 -1
  104. package/plugins/shopping-cart/tests/pure.test.js +16 -0
  105. package/plugins/whatsapp-calling/CLAUDE.md +12 -0
  106. package/plugins/whatsapp-calling/admin/css/index.css +22 -0
  107. package/plugins/whatsapp-calling/admin/templates/index.html +56 -0
  108. package/plugins/whatsapp-calling/admin/views/connection-help.js +55 -0
  109. package/plugins/whatsapp-calling/admin/views/index.js +275 -0
  110. package/plugins/whatsapp-calling/config.js +7 -0
  111. package/plugins/whatsapp-calling/docs/guide.md +70 -0
  112. package/plugins/whatsapp-calling/lib/calls.js +156 -0
  113. package/plugins/whatsapp-calling/lib/meta.js +55 -0
  114. package/plugins/whatsapp-calling/lib/recipients.js +26 -0
  115. package/plugins/whatsapp-calling/plugin.js +123 -0
  116. package/plugins/whatsapp-calling/plugin.json +86 -0
  117. package/plugins/whatsapp-calling/tests/calling.test.js +254 -0
  118. package/server/routes/api/api-tokens.js +2 -2
  119. package/server/routes/api/collections.js +20 -2
  120. package/server/services/apiTokens.js +59 -4
  121. package/server/services/presetCollections.js +1 -0
@@ -329,3 +329,19 @@ test('admin: no form fields inside E.confirm (its message is sanitised; inputs v
329
329
  for (const m of src.matchAll(/E\.confirm\(`([^`]*)`/g)) assert.ok(!/<(input|select|textarea)\b/.test(m[1]), `${f}: E.confirm with form fields`);
330
330
  }
331
331
  });
332
+
333
+ test('orderFacts shows extensions\' words and numbers, not their bookkeeping', async () => {
334
+ const {orderFacts} = await import('../public/lib/orders.js');
335
+ const facts = orderFacts({'shopping-cart-pro': {counted: true, granted: '2026-08-16T16:00:00.319Z', keysShort: 2, downloads: [{}]},
336
+ takeaway: {stage: 'Ready', emailed: {ready: '2026-08-16T16:00:00Z'}, note: ''}});
337
+ assert.deepEqual(facts.map(f => `${f.label}: ${f.v}`), ['keys short: 2', 'stage: Ready']);
338
+ assert.deepEqual(orderFacts(undefined), []);
339
+ });
340
+
341
+ test('Needs you says a sold-out option is sold out, not ": 0"', async () => {
342
+ const {summarise} = await import('../lib/summary.js');
343
+ const products = [{id: 'p1', data: {name: 'Ring Spanner Set', status: 'active', trackStock: true,
344
+ variants: [{name: 'Imperial', stock: 0}, {name: 'Metric', stock: 2}, {name: 'Mixed', stock: 30}]}}];
345
+ const s = summarise([], products, {lowStockAt: 3});
346
+ assert.deepEqual(s.lowStock[0].variants, ['Imperial sold out', 'Metric: 2 left']);
347
+ });
@@ -0,0 +1,12 @@
1
+ # WhatsApp Calling
2
+
3
+ Direct Meta Cloud API voice calling. Maintained in `dcms-marketplace/plugins/whatsapp-calling`; the CMS copy is synchronised through `make sync-free-tier`.
4
+
5
+ - `plugin.js`: authenticated operator routes, admin-only masked connection settings, and unauthenticated HMAC-verified webhook at `/api/plugins/whatsapp-calling/webhook`. The scoped JSON parser preserves exact signed bytes.
6
+ - `lib/meta.js`: fixed-origin Graph client, input validation and signature verification. Never log tokens, SDP or raw upstream errors. Never retry connect/message POSTs automatically.
7
+ - `lib/calls.js`: bounded process-local sessions and ownership, permission checks, webhook deduplication, stale-browser cleanup. One server process only. SDP is erased on termination.
8
+ - `admin/views/index.js`: Domma reactive screen, Forma forms, browser WebRTC and full ICE gathering. Dispose microphone and peer connection when leaving. Secrets are blank on read and remain unchanged on blank save.
9
+ - `docs/guide.md`: operator setup and limitations. Update with behaviour.
10
+ - `tests/calling.test.js`: Graph contract, signature byte integrity, auth and ownership, permission checks, concurrency, races and abandoned calls. No live Meta calls.
11
+
12
+ Run the CMS isolated harness: `npm test -- plugins/whatsapp-calling/tests/calling.test.js` from `domma-cms`.
@@ -0,0 +1,22 @@
1
+ .wac { max-width: 960px; display: grid; gap: 1rem; }
2
+ .wac .card-body { display: grid; gap: .75rem; }
3
+ .wac-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
4
+ .wac-note { color: var(--dm-text-muted, #64748b); min-height: 1.5em; }
5
+ .wac-error { color: var(--dm-danger, #b91c1c); }
6
+ .wac-row { display: flex; align-items: center; justify-content: space-between; gap: 1rem; padding: .75rem 0; border-bottom: 1px solid var(--dm-border, #e2e8f0); }
7
+ .wac-settings { padding: 1rem; display: grid; gap: 1rem; align-content: start; }
8
+ .wac-settings > .btn { justify-self: start; }
9
+ .wac-settings code { overflow-wrap: anywhere; }
10
+ .wac [hidden] { display: none !important; }
11
+ @media (max-width: 560px) { .wac-row { flex-wrap: wrap; } }
12
+
13
+ .wac-setup-guide { border: 1px solid var(--dm-border); border-radius: .5rem; padding: .75rem; }
14
+ .wac-setup-guide summary { cursor: pointer; font-weight: 600; color: var(--dm-primary); }
15
+ .wac-setup-guide p { margin: .5rem 0; font-size: .875rem; }
16
+ .wac-setup-guide ol { padding-left: 1.25rem; margin: .75rem 0; }
17
+ .wac-setup-guide li { margin-bottom: 1rem; }
18
+ .wac-setup-guide a { font-size: .875rem; }
19
+ .wac-callback { display: grid; gap: .5rem; }
20
+ .wac-settings label.form-label { display: inline-flex; align-items: center; gap: .25rem; }
21
+
22
+ .wac-embedded { padding: 1rem; overflow-y: auto; flex: 1; min-height: 0; }
@@ -0,0 +1,56 @@
1
+ <div class="wac">
2
+ <p class="wac-note" role="status" data-bind-text="status.value">Checking the Meta connection...</p>
3
+ <p class="wac-error" role="alert" data-bind-text="error.value" data-bind-hidden="!error.value"></p>
4
+ <button type="button" class="btn btn-outline wac-settings-fallback" hidden>Connection settings</button>
5
+ <section class="card" data-bind-hidden="!ready.value">
6
+ <div class="card-body">
7
+ <h2 class="text-xl">Call someone</h2>
8
+ <p class="text-muted">Use their full international number. Outgoing calls use Meta's paid calling API.</p>
9
+ <div class="wac-dial-form"></div>
10
+ <div class="wac-actions">
11
+ <button type="button" class="btn btn-outline" data-on-click="checkPermission" data-bind-disabled="busy.value || active.value">Check permission</button>
12
+ <button type="button" class="btn btn-outline" data-on-click="requestPermission" data-bind-disabled="busy.value || active.value">Request permission</button>
13
+ <button type="button" class="btn btn-primary" data-on-click="dial" data-bind-disabled="busy.value || active.value">Call on WhatsApp</button>
14
+ </div>
15
+ <p class="wac-note" data-bind-text="permission.value" role="status"></p>
16
+ </div>
17
+ </section>
18
+ <section class="card wac-live" data-bind-hidden="!active.value" hidden>
19
+ <div class="card-body">
20
+ <h2 class="text-xl" data-bind-text="callLabel.value"></h2>
21
+ <p role="status" data-bind-text="callStatus.value"></p>
22
+ <div class="wac-actions">
23
+ <button type="button" class="btn btn-outline" data-on-click="mute" data-bind-text="muted.value ? 'Unmute microphone' : 'Mute microphone'"></button>
24
+ <button type="button" class="btn btn-outline" data-on-click="playAudio">Play call audio</button>
25
+ <button type="button" class="btn btn-danger" data-on-click="hangup" data-bind-disabled="busy.value">End call</button>
26
+ </div>
27
+ <p class="text-muted">Keep this page open during your call.</p>
28
+ <audio class="wac-audio" autoplay playsinline></audio>
29
+ </div>
30
+ </section>
31
+ <section class="card" data-bind-hidden="!ready.value">
32
+ <div class="card-body">
33
+ <h2 class="text-xl">Incoming calls</h2>
34
+ <p class="text-muted">Keep this tool open to see calls arrive.</p>
35
+ <p data-bind-hidden="incoming.value.length > 0">No incoming calls.</p>
36
+ <div data-each="incoming.value key=id" class="wac-incoming">
37
+ <div class="wac-row">
38
+ <strong data-bind-text="phone"></strong>
39
+ <div class="wac-actions">
40
+ <button type="button" class="btn btn-primary" data-on-click="$root.answer($data)" data-bind-disabled="$root.busy.value || $root.active.value">Answer</button>
41
+ <button type="button" class="btn btn-outline" data-on-click="$root.reject($data)" data-bind-disabled="$root.busy.value || $root.active.value">Decline</button>
42
+ </div>
43
+ </div>
44
+ </div>
45
+ </div>
46
+ </section>
47
+ <section class="card" data-bind-hidden="recent.value.length === 0" hidden>
48
+ <div class="card-body">
49
+ <h2 class="text-xl">Your recent calls</h2>
50
+ <div data-each="recent.value key=id">
51
+ <div class="wac-row"><span data-bind-text="phone"></span><span data-bind-text="direction"></span><span data-bind-text="status"></span></div>
52
+ </div>
53
+ <p class="text-muted">Recent calls are kept for this server session, for up to one hour. Calls are not recorded.</p>
54
+ </div>
55
+ </section>
56
+ </div>
@@ -0,0 +1,55 @@
1
+ /** Connection help stays beside the form so setup instructions ship with the tool. */
2
+ export const CONNECTION_HELP = {
3
+ phoneNumberId: {
4
+ hint: 'Meta app > WhatsApp > API Setup (sometimes called Getting Started) > Phone number ID.',
5
+ text: 'Open your app in Meta for Developers, then WhatsApp > API Setup (or Getting Started). Select your business number and copy its Phone number ID. Use the numeric ID, not the telephone number, App ID or WhatsApp Business Account ID.'
6
+ },
7
+ apiVersion: {
8
+ hint: 'Keep v23.0 unless your Meta app requires another supported Graph API version.',
9
+ text: 'This selects the version of Meta\'s Graph API used for calls and permission requests. The supplied default is v23.0. If you change it, use a supported version shown by Meta, written as v followed by the version number and .0.'
10
+ },
11
+ accessToken: {
12
+ hint: 'Meta Business Settings > Users > System users > Generate token.',
13
+ text: 'In Meta Business Settings, create or select a system user and assign access to your app and WhatsApp Business Account. Generate a token for that app with whatsapp_business_messaging. Account management tasks may also need whatsapp_business_management. Use a system user token for ongoing use; the temporary API Setup token expires. Leave this field blank to keep a saved token.'
14
+ },
15
+ appSecret: {
16
+ hint: 'Meta for Developers > your app > App settings > Basic > App secret > Show.',
17
+ text: 'Copy the App secret from the same Meta app you use for WhatsApp. Meta may ask you to sign in again before showing it. Domma uses this secret to check that incoming webhook events were signed by Meta. This is different from the access token. Leave blank to keep a saved secret.'
18
+ },
19
+ verifyToken: {
20
+ hint: 'Choose your own long random value, then use exactly the same value in Meta\'s webhook settings.',
21
+ text: 'You create this value yourself; Meta does not issue it. Choose a long random value, save it here, and paste the identical value into the Verify token field when configuring the webhook in your Meta app. Do not use your access token or app secret. Leave blank to keep the saved verification token.'
22
+ }
23
+ };
24
+
25
+ export function connectionGuide(callbackUrl) {
26
+ const guide = document.createElement('details'); guide.className = 'wac-setup-guide';
27
+ const summary = document.createElement('summary'); summary.textContent = 'Step-by-step Meta connection setup'; guide.appendChild(summary);
28
+ const intro = document.createElement('p'); intro.textContent = 'You need access to your Meta developer app and business settings. Meta may label some screens differently depending on your app setup.'; guide.appendChild(intro);
29
+ const list = document.createElement('ol');
30
+ const steps = [
31
+ ['Prepare your business number', 'Open Meta for Developers, create or select your business app and add WhatsApp. Connect your WhatsApp Business Account and register your business number with the Cloud API. Make sure the number is eligible for Calling and enable Calling in Meta. Adding credentials here does not enable Calling for the number.', 'Open Meta apps', 'https://developers.facebook.com/apps/'],
32
+ ['Copy the Phone number ID', 'In the app, open WhatsApp > API Setup (or Getting Started), select your business number and copy Phone number ID into the field below. The App ID, business account ID and telephone number are different values.'],
33
+ ['Create the access token', 'Open Meta Business Settings > Users > System users. Create or select a system user, assign your app and WhatsApp Business Account, then generate a token for the app with whatsapp_business_messaging. Account management may also require whatsapp_business_management. Paste the token below and keep track of its expiry.', 'Open Meta Business Settings', 'https://business.facebook.com/settings/'],
34
+ ['Copy the app secret', 'In Meta for Developers, open the same app > App settings > Basic. Choose Show beside App secret and copy it into the field below.'],
35
+ ['Choose the verification token and save', 'Create a long random verification token of your own and enter it below. Keep Graph API version at its default unless you need another supported version. Save the connection before asking Meta to verify the webhook.'],
36
+ ['Connect the webhook in Meta', `Open WhatsApp > Configuration > Webhooks in your Meta app. Set Callback URL to ${callbackUrl} and Verify token to the exact value you saved here. Choose Verify and save. Subscribe to calls and messages, and ensure the app is subscribed to your WhatsApp Business Account.`],
37
+ ['Test a call', 'Return to this tool over HTTPS and allow your microphone. Ask the recipient for call permission, check that Meta allows the call, then dial. Incoming calls appear while this tool is open. Outgoing calls require Meta billing and carry Meta usage charges.']
38
+ ];
39
+ for (const [title, text, linkText, href] of steps) {
40
+ const item = document.createElement('li');
41
+ const heading = document.createElement('strong'); heading.textContent = title;
42
+ const body = document.createElement('p'); body.textContent = text;
43
+ item.append(heading, body);
44
+ if (href) {
45
+ const link = document.createElement('a'); link.href = href; link.target = '_blank'; link.rel = 'noopener noreferrer'; link.textContent = linkText; item.appendChild(link);
46
+ }
47
+ list.appendChild(item);
48
+ }
49
+ guide.appendChild(list);
50
+ const troubleshoot = document.createElement('p');
51
+ troubleshoot.textContent = 'If webhook verification fails, save this form first, check that both verification tokens match, and check that Meta can reach the HTTPS callback URL. If calls are rejected, check token expiry, assigned business assets, Calling eligibility and recipient permission. A configured connection has not yet been verified by Meta.';
52
+ guide.appendChild(troubleshoot);
53
+ const reference = document.createElement('a'); reference.href = 'https://developers.facebook.com/documentation/business-messaging/whatsapp/calling/'; reference.target = '_blank'; reference.rel = 'noopener noreferrer'; reference.textContent = 'Meta Calling documentation'; guide.appendChild(reference);
54
+ return guide;
55
+ }
@@ -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.