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
@@ -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
+ }
@@ -0,0 +1,123 @@
1
+ import {listEntries} from '../../server/services/collections.js';
2
+ import {readableContactIds} from '../../server/services/hooks.js';
3
+ import {getPermissionsFor} from '../../server/services/roles.js';
4
+ import {getEffectiveRoles} from '../../server/services/userRoles.js';
5
+ import {isToolEnabled} from '../../server/services/tools.js';
6
+ import {createRecipientLookup} from './lib/recipients.js';
7
+ import defaults from './config.js';
8
+ import {getPluginSettings, savePluginState} from '../../server/services/plugins.js';
9
+ import {iceServers, readCallConfig} from '../_lib/call/ice.js';
10
+ import {CallingError, allows, createMeta, equalSecret, phone, ready, signed} from './lib/meta.js';
11
+ import {createCalls} from './lib/calls.js';
12
+
13
+ export default async function whatsappCalling(fastify, options) {
14
+ const settings = options.readSettings || (() => getPluginSettings('whatsapp-calling'));
15
+ const save = options.writeSettings || (value => savePluginState('whatsapp-calling', {settings: value}));
16
+ const meta = options.meta || createMeta({settings});
17
+ const lookupRecipients = createRecipientLookup({
18
+ canRead: viewer => isToolEnabled('contacts') && viewer.roles.some(r => getPermissionsFor('contacts', 'read').includes(r)),
19
+ list: async () => (await listEntries('contacts-contacts', {limit: 100000}).catch(() => ({entries: []}))).entries || [],
20
+ readable: readableContactIds
21
+ });
22
+ const calls = options.calls || createCalls({meta, getPhoneNumberId: async () => (await settings()).phoneNumberId});
23
+ const {authenticate, requirePermission, requireAdmin} = options.auth;
24
+ const can = action => ({preHandler: [authenticate, requirePermission('whatsapp-calling', action)]});
25
+ const admin = {preHandler: [authenticate, requireAdmin]};
26
+ const user = request => String(request.user?.id || request.user?.sub || '');
27
+ const secrets = ['accessToken', 'appSecret', 'verifyToken'];
28
+ const safe = c => ({phoneNumberId: c.phoneNumberId, apiVersion: c.apiVersion,
29
+ ready: ready(c), credentials: Object.fromEntries(secrets.map(k => [k, Boolean(c[k])]))});
30
+ fastify.addHook('onSend', async (_request, reply, payload) => {
31
+ reply.header('Cache-Control', 'no-store');
32
+ return payload;
33
+ });
34
+ fastify.setErrorHandler((error, _request, reply) => {
35
+ const known = error instanceof CallingError;
36
+ const status = known ? error.statusCode : (error.statusCode >= 400 && error.statusCode < 500 ? error.statusCode : 500);
37
+ reply.code(status).send({error: known ? error.message : status === 500 ? 'WhatsApp calling could not complete this request.' : 'Request refused.'});
38
+ });
39
+ // Preserve the exact signed bytes. Scoped parser, so other plugins and core retain their normal parser.
40
+ fastify.removeContentTypeParser('application/json');
41
+ fastify.addContentTypeParser('application/json', {parseAs: 'buffer', bodyLimit: 262144}, (request, body, done) => {
42
+ request.whatsappRawBody = body;
43
+ try { done(null, JSON.parse(body.toString('utf8'))); }
44
+ catch { const error = new CallingError('Invalid JSON.'); done(error); }
45
+ });
46
+ fastify.get('/webhook', async (request, reply) => {
47
+ const c = await settings(), q = request.query || {};
48
+ if (q['hub.mode'] !== 'subscribe' || !equalSecret(q['hub.verify_token'], c.verifyToken)
49
+ || typeof q['hub.challenge'] !== 'string' || q['hub.challenge'].length > 200) return reply.code(403).send({error: 'Verification failed.'});
50
+ return reply.type('text/plain').send(q['hub.challenge']);
51
+ });
52
+ fastify.post('/webhook', async (request, reply) => {
53
+ const c = await settings();
54
+ if (!ready(c) || !signed(request.whatsappRawBody, request.headers['x-hub-signature-256'], c.appSecret)) {
55
+ return reply.code(403).send({error: 'Invalid webhook signature.'});
56
+ }
57
+ calls.webhook(request.body, c.phoneNumberId);
58
+ return {success: true};
59
+ });
60
+ fastify.get('/availability', {preHandler: [authenticate, requirePermission('whatsapp-calling', 'read'), requirePermission('whatsapp-calling', 'create')]}, async () => ({ready: ready(await settings())}));
61
+ fastify.get('/recipients', can('create'), async request => {
62
+ const viewer = {id: user(request), roles: getEffectiveRoles(request.user || {})};
63
+ const email = String(request.query?.email || '').trim().slice(0, 254);
64
+ const contactId = String(request.query?.contactId || '').trim().slice(0, 100);
65
+ if (!email && !contactId) return {recipients: []};
66
+ return {recipients: await lookupRecipients(viewer, {email, contactId})};
67
+ });
68
+ fastify.get('/status', can('read'), async request => {
69
+ const c = await settings();
70
+ return {ready: ready(c), iceServers: iceServers(readCallConfig(), `whatsapp-${user(request)}`)};
71
+ });
72
+ fastify.get('/settings', admin, async () => safe(await settings()));
73
+ fastify.put('/settings', admin, async request => {
74
+ const previous = await settings(), body = request.body || {};
75
+ // Changing a number while calls exist would send subsequent hang-ups to the wrong number.
76
+ if (body.phoneNumberId !== undefined && body.phoneNumberId !== previous.phoneNumberId && calls.hasActive()) {
77
+ throw new CallingError('End all WhatsApp calls before changing the business number.', 409);
78
+ }
79
+ const next = {...defaults, ...previous};
80
+ for (const k of Object.keys(defaults)) {
81
+ if (body[k] === undefined) continue;
82
+ if (typeof body[k] !== 'string' || body[k].length > 4096) throw new CallingError('Invalid connection settings.');
83
+ const value = body[k].trim();
84
+ if (secrets.includes(k) && !value) continue; // Blank leaves an existing secret untouched.
85
+ next[k] = value;
86
+ }
87
+ if (next.phoneNumberId && !/^\d{5,30}$/.test(next.phoneNumberId)) throw new CallingError('Enter the Meta phone number ID, not the telephone number.');
88
+ if (!/^v\d{2}\.0$/.test(next.apiVersion)) throw new CallingError('Enter a Graph API version such as v23.0.');
89
+ await save(next);
90
+ return safe(next);
91
+ });
92
+ fastify.get('/permission', can('create'), async request => {
93
+ const result = await meta('call_permissions', {query: {user_wa_id: phone(request.query?.to)}});
94
+ return {status: result.permission?.status || 'no_permission',
95
+ expiresAt: result.permission?.expiration_time || null,
96
+ canCall: allows(result, 'start_call'), canRequest: allows(result, 'send_call_permission_request')};
97
+ });
98
+ fastify.post('/permission', {...can('create'), config: {rateLimit: {max: 5, timeWindow: '1 minute'}}}, async request => {
99
+ const to = phone(request.body?.to);
100
+ const permission = await meta('call_permissions', {query: {user_wa_id: to}});
101
+ if (!allows(permission, 'send_call_permission_request')) throw new CallingError('Meta does not currently allow another permission request to this person.', 409);
102
+ const text = String(request.body?.text || '').trim();
103
+ if (!text || text.length > 1024) throw new CallingError('Explain why you want to call, using at most 1,024 characters.');
104
+ await meta('messages', {method: 'POST', body: {messaging_product: 'whatsapp', to, type: 'interactive',
105
+ interactive: {type: 'call_permission_request', body: {text}, action: {name: 'call_permission_request'}}}});
106
+ return {sent: true};
107
+ });
108
+ fastify.get('/calls', can('read'), async request => ({calls: calls.list(user(request))}));
109
+ fastify.post('/calls', {...can('create'), config: {rateLimit: {max: 10, timeWindow: '1 minute'}}}, async (request, reply) => {
110
+ return reply.code(201).send(await calls.dial(user(request), request.body?.to, request.body?.session));
111
+ });
112
+ fastify.get('/calls/:id', can('create'), async request => calls.poll(request.params.id, user(request)));
113
+ fastify.post('/calls/:id/claim', can('create'), async request => calls.claim(request.params.id, user(request)));
114
+ fastify.post('/calls/:id/action', can('create'), async request => calls.action(request.params.id, user(request), request.body?.action, request.body?.session));
115
+ let sweeping = false;
116
+ const timer = setInterval(async () => {
117
+ if (sweeping) return;
118
+ sweeping = true;
119
+ try { await calls.sweep(); } finally { sweeping = false; }
120
+ }, 10000);
121
+ timer.unref();
122
+ fastify.addHook('onClose', async () => { clearInterval(timer); await calls.close(); });
123
+ }
@@ -0,0 +1,86 @@
1
+ {
2
+ "name": "whatsapp-calling",
3
+ "displayName": "WhatsApp Calling",
4
+ "version": "0.1.0",
5
+ "description": "Make and receive WhatsApp voice calls through the direct Meta Cloud API.",
6
+ "author": "Domma",
7
+ "date": "2026-11-08",
8
+ "icon": "phone",
9
+ "tier": "free",
10
+ "permissions": [
11
+ {
12
+ "key": "whatsapp-calling",
13
+ "label": "WhatsApp Calling",
14
+ "actions": [
15
+ "read",
16
+ "create"
17
+ ],
18
+ "grant": [
19
+ "admin"
20
+ ]
21
+ }
22
+ ],
23
+ "admin": {
24
+ "css": [
25
+ "admin/css/index.css"
26
+ ],
27
+ "sidebar": [
28
+ {
29
+ "id": "whatsapp-calling",
30
+ "text": "WhatsApp Calling",
31
+ "icon": "phone",
32
+ "url": "#/plugins/whatsapp-calling",
33
+ "section": "#/plugins/whatsapp-calling",
34
+ "permission": "whatsapp-calling",
35
+ "folder": "tools",
36
+ "group": "User"
37
+ }
38
+ ],
39
+ "routes": [
40
+ {
41
+ "path": "/plugins/whatsapp-calling",
42
+ "view": "plugin-whatsapp-calling",
43
+ "title": "WhatsApp Calling - Domma CMS"
44
+ }
45
+ ],
46
+ "views": {
47
+ "plugin-whatsapp-calling": {
48
+ "entry": "whatsapp-calling/admin/views/index.js",
49
+ "exportName": "indexView"
50
+ }
51
+ }
52
+ },
53
+ "settingsSchema": [
54
+ {
55
+ "key": "phoneNumberId",
56
+ "label": "Meta phone number ID",
57
+ "type": "text"
58
+ },
59
+ {
60
+ "key": "apiVersion",
61
+ "label": "Graph API version",
62
+ "type": "text"
63
+ },
64
+ {
65
+ "key": "accessToken",
66
+ "label": "System user access token",
67
+ "type": "text",
68
+ "secret": true
69
+ },
70
+ {
71
+ "key": "appSecret",
72
+ "label": "Meta app secret",
73
+ "type": "text",
74
+ "secret": true
75
+ },
76
+ {
77
+ "key": "verifyToken",
78
+ "label": "Webhook verification token",
79
+ "type": "text",
80
+ "secret": true
81
+ }
82
+ ],
83
+ "uses": {
84
+ "contacts": "Find readable contact phone numbers from Calendar and Email"
85
+ }
86
+ }