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,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
+ }
@@ -0,0 +1,254 @@
1
+ import {test} from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {createHmac} from 'node:crypto';
4
+ import Fastify from 'fastify';
5
+ import plugin from '../plugin.js';
6
+ import {createCalls} from '../lib/calls.js';
7
+ import {CallingError, createMeta, signed, phone} from '../lib/meta.js';
8
+ import {gatherIce} from '../admin/views/index.js';
9
+
10
+ const offer = {sdp_type: 'offer', sdp: 'v=0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n'};
11
+ const answer = {...offer, sdp_type: 'answer'};
12
+ const config = {phoneNumberId: '123456', apiVersion: 'v23.0', accessToken: 'private-token', appSecret: 'private-app-secret', verifyToken: 'private-verify-token'};
13
+ const permission = allowed => ({permission: {status: allowed ? 'temporary' : 'no_permission'}, actions: [
14
+ {action_name: 'start_call', can_perform_action: allowed}, {action_name: 'send_call_permission_request', can_perform_action: true}
15
+ ]});
16
+ const webhook = (...events) => ({object: 'whatsapp_business_account', entry: [{changes: [{field: 'calls', value: {metadata: {phone_number_id: '123456'}, calls: events}}]}]});
17
+ const inbound = (id = 'wa-in') => ({id, event: 'connect', direction: 'USER_INITIATED', from: '447700900123', session: offer});
18
+ function fake() {
19
+ const sent = [];
20
+ const meta = async (endpoint, opts = {}) => {
21
+ sent.push({endpoint, ...opts});
22
+ if (endpoint === 'call_permissions') return permission(true);
23
+ if (opts.body?.action === 'connect') return {calls: [{id: 'wa-out'}]};
24
+ return {success: true};
25
+ };
26
+ return {meta, sent};
27
+ }
28
+ async function app({allow = true, meta = fake().meta} = {}) {
29
+ let settings = {...config};
30
+ const server = Fastify();
31
+ await server.register(plugin, {prefix: '/api/plugins/whatsapp-calling', meta,
32
+ readSettings: async () => settings, writeSettings: async c => { settings = c; },
33
+ auth: {
34
+ authenticate: async (r, reply) => { if (!r.headers['x-user']) return reply.code(401).send({error: 'No login'}); r.user = {id: r.headers['x-user']}; },
35
+ requirePermission: () => async (_r, reply) => { if (!allow) return reply.code(403).send({error: 'No permission'}); },
36
+ requireAdmin: async (r, reply) => { if (r.user.id !== 'admin') return reply.code(403).send({error: 'Admin only'}); }
37
+ }});
38
+ return server;
39
+ }
40
+ const url = path => `/api/plugins/whatsapp-calling${path}`;
41
+ const alice = {'x-user': 'alice'}, bob = {'x-user': 'bob'};
42
+
43
+ test('phone input and byte-exact webhook verification', () => {
44
+ assert.equal(phone('+44 (7700) 900-123'), '447700900123');
45
+ assert.throws(() => phone('https://attacker.test'));
46
+ const body = Buffer.from('{ "ok": true }');
47
+ const sig = `sha256=${createHmac('sha256', config.appSecret).update(body).digest('hex')}`;
48
+ assert.equal(signed(body, sig, config.appSecret), true);
49
+ assert.equal(signed(Buffer.from('{"ok":true}'), sig, config.appSecret), false);
50
+ assert.equal(signed(body, 'sha256=x', config.appSecret), false);
51
+ });
52
+
53
+ test('Graph client uses fixed HTTPS origin, bearer header, exact API shape and hides upstream details', async () => {
54
+ let request;
55
+ const meta = createMeta({settings: async () => config, fetcher: async (u, options) => {
56
+ request = {u: String(u), options}; return {ok: true, json: async () => permission(true)};
57
+ }});
58
+ await meta('call_permissions', {query: {user_wa_id: '447700900123'}});
59
+ assert.equal(request.u, 'https://graph.facebook.com/v23.0/123456/call_permissions?user_wa_id=447700900123');
60
+ assert.equal(request.options.headers.Authorization, 'Bearer private-token');
61
+ assert.equal(request.options.redirect, 'error');
62
+ const broken = createMeta({settings: async () => config, fetcher: async () => ({ok: false, status: 400, json: async () => ({error: {code: 190, message: config.accessToken}})})});
63
+ await assert.rejects(broken('calls'), e => e.statusCode === 502 && !e.message.includes(config.accessToken));
64
+ });
65
+
66
+ test('outbound permission is checked server-side and only the owner sees SDP or controls', async () => {
67
+ const denied = createCalls({meta: async () => permission(false)});
68
+ await assert.rejects(denied.dial('alice', '447700900123', offer), e => e.statusCode === 409);
69
+ const {meta, sent} = fake(), calls = createCalls({meta});
70
+ const c = await calls.dial('alice', '447700900123', offer);
71
+ const connect = sent.find(s => s.body?.action === 'connect');
72
+ assert.equal(connect.body.session.sdp_type, 'offer');
73
+ assert.equal(connect.body.biz_opaque_callback_data, c.id);
74
+ assert.equal(calls.list('bob').length, 0);
75
+ assert.throws(() => calls.poll(c.id, 'bob'), e => e.statusCode === 404);
76
+ await assert.rejects(calls.action(c.id, 'bob', 'terminate'), e => e.statusCode === 404);
77
+ calls.webhook(webhook({id: 'wa-out', event: 'connect', session: answer}), '123456');
78
+ assert.equal(calls.poll(c.id, 'alice').session.sdp_type, 'answer');
79
+ calls.webhook(webhook({id: 'wa-out', event: 'terminate'}), '123456');
80
+ calls.webhook(webhook({id: 'wa-out', event: 'connect', session: answer}), '123456');
81
+ assert.equal(calls.poll(c.id, 'alice').status, 'ended');
82
+ assert.equal(calls.poll(c.id, 'alice').session, null);
83
+ });
84
+
85
+ test('incoming claim is exclusive, duplicate webhooks do not duplicate calls, another business number is ignored', async () => {
86
+ const {meta} = fake(), calls = createCalls({meta});
87
+ calls.webhook(webhook(inbound()), '999999');
88
+ assert.equal(calls.list('alice').length, 0);
89
+ calls.webhook(webhook(inbound(), inbound()), '123456');
90
+ const list = calls.list('alice');
91
+ assert.equal(list.length, 1); assert.equal(list[0].session, undefined);
92
+ const c = calls.claim(list[0].id, 'alice');
93
+ assert.equal(c.session.sdp_type, 'offer');
94
+ assert.throws(() => calls.claim(c.id, 'bob'), e => e.statusCode === 404);
95
+ assert.equal(calls.list('bob').length, 0);
96
+ await calls.action(c.id, 'alice', 'accept', answer);
97
+ assert.equal(calls.poll(c.id, 'alice').status, 'connected');
98
+ await assert.rejects(calls.action(c.id, 'alice', 'reject'), e => e.statusCode === 409);
99
+ await calls.action(c.id, 'alice', 'terminate');
100
+ assert.equal(calls.poll(c.id, 'alice').session, null);
101
+ });
102
+
103
+ test('only one outbound call can start per operator, including concurrent requests', async () => {
104
+ const {meta} = fake(), calls = createCalls({meta});
105
+ const results = await Promise.allSettled([calls.dial('alice', '447700900123', offer), calls.dial('alice', '447700900123', offer)]);
106
+ assert.equal(results.filter(r => r.status === 'fulfilled').length, 1);
107
+ assert.equal(results.filter(r => r.status === 'rejected').length, 1);
108
+ });
109
+
110
+ test('webhook connect may precede connect response', async () => {
111
+ let calls;
112
+ const meta = async (endpoint, opts) => {
113
+ if (endpoint === 'call_permissions') return permission(true);
114
+ calls.webhook(webhook({id: 'fast-meta', event: 'connect', session: answer, biz_opaque_callback_data: opts.body.biz_opaque_callback_data}), '123456');
115
+ return {calls: [{id: 'fast-meta'}]};
116
+ };
117
+ calls = createCalls({meta});
118
+ const c = await calls.dial('alice', '447700900123', offer);
119
+ assert.equal(calls.poll(c.id, 'alice').session.sdp_type, 'answer');
120
+ });
121
+
122
+ test('operator departure triggers remote hang-up; failed cleanup retries; history expires', async () => {
123
+ let clock = 1000, fail = true;
124
+ const sent = [];
125
+ const calls = createCalls({now: () => clock, meta: async (endpoint, opts) => {
126
+ if (endpoint === 'call_permissions') return permission(true);
127
+ if (opts.body.action === 'connect') return {calls: [{id: 'orphan'}]};
128
+ sent.push(opts.body.action);
129
+ if (fail) throw new Error('Offline');
130
+ return {success: true};
131
+ }});
132
+ const c = await calls.dial('alice', '447700900123', offer);
133
+ clock += 61000;
134
+ await calls.sweep(); assert.equal(calls.poll(c.id, 'alice').status, 'dialling');
135
+ clock += 61000; fail = false;
136
+ await calls.sweep(); assert.equal(calls.poll(c.id, 'alice').status, 'ended');
137
+ assert.deepEqual(sent, ['terminate', 'terminate']);
138
+ clock += 3600001; await calls.sweep(); assert.equal(calls.list('alice').length, 0);
139
+ });
140
+
141
+ test('HTTP login, permissions and administrative settings protect credentials', async t => {
142
+ const server = await app(); t.after(() => server.close());
143
+ assert.equal((await server.inject({url: url('/calls')})).statusCode, 401);
144
+ assert.equal((await server.inject({url: url('/settings'), headers: alice})).statusCode, 403);
145
+ const c = (await server.inject({url: url('/settings'), headers: {'x-user': 'admin'}})).json();
146
+ assert.equal(c.credentials.accessToken, true);
147
+ assert.equal(JSON.stringify(c).includes('private-'), false);
148
+ const saved = await server.inject({url: url('/settings'), method: 'PUT', headers: {'x-user': 'admin'}, payload: {accessToken: '', phoneNumberId: '654321'}});
149
+ assert.equal(saved.json().credentials.accessToken, true);
150
+ const forbidden = await app({allow: false}); t.after(() => forbidden.close());
151
+ assert.equal((await forbidden.inject({url: url('/calls'), headers: alice})).statusCode, 403);
152
+ });
153
+
154
+ test('HTTP webhook challenge and exact-byte HMAC, malformed JSON and owner access', async t => {
155
+ const server = await app(); t.after(() => server.close());
156
+ assert.equal((await server.inject({url: url('/webhook?hub.mode=subscribe&hub.verify_token=private-verify-token&hub.challenge=challenge')})).body, 'challenge');
157
+ assert.equal((await server.inject({url: url('/webhook?hub.mode=subscribe&hub.verify_token=wrong&hub.challenge=x')})).statusCode, 403);
158
+ const body = JSON.stringify(webhook(inbound()), null, 2);
159
+ const signature = `sha256=${createHmac('sha256', config.appSecret).update(body).digest('hex')}`;
160
+ assert.equal((await server.inject({url: url('/webhook'), method: 'POST', payload: body, headers: {'content-type': 'application/json'}})).statusCode, 403);
161
+ assert.equal((await server.inject({url: url('/webhook'), method: 'POST', payload: body, headers: {'content-type': 'application/json', 'x-hub-signature-256': signature}})).statusCode, 200);
162
+ const list = (await server.inject({url: url('/calls'), headers: alice})).json().calls;
163
+ assert.equal(list.length, 1);
164
+ assert.equal((await server.inject({url: url(`/calls/${list[0].id}/claim`), method: 'POST', headers: alice})).statusCode, 200);
165
+ assert.equal((await server.inject({url: url(`/calls/${list[0].id}`), headers: bob})).statusCode, 404);
166
+ assert.equal((await server.inject({url: url('/calls'), method: 'POST', headers: {...alice, 'content-type': 'application/json'}, payload: '{'})).statusCode, 400);
167
+ });
168
+
169
+ test('HTTP permission requests are interactive messages, never treated as permission grants', async t => {
170
+ const {meta, sent} = fake(), server = await app({meta}); t.after(() => server.close());
171
+ const res = await server.inject({url: url('/permission'), method: 'POST', headers: alice, payload: {to: '+447700900123', text: 'May we call about your enquiry?'}});
172
+ assert.equal(res.statusCode, 200);
173
+ assert.equal(sent.at(-1).body.interactive.type, 'call_permission_request');
174
+ assert.equal(sent.at(-1).body.interactive.action.name, 'call_permission_request');
175
+ const c = await server.inject({url: url('/calls'), method: 'POST', headers: alice, payload: {to: '+447700900123', session: offer}});
176
+ assert.equal(c.statusCode, 201);
177
+ const changed = await server.inject({url: url('/settings'), method: 'PUT', headers: {'x-user': 'admin'}, payload: {phoneNumberId: '999999'}});
178
+ assert.equal(changed.statusCode, 409);
179
+ });
180
+
181
+ test('browser waits for complete ICE and rejects timed-out gathering', async () => {
182
+ class Peer extends EventTarget { iceGatheringState = 'gathering'; }
183
+ const peer = new Peer();
184
+ const pending = gatherIce(peer, 100);
185
+ peer.iceGatheringState = 'complete'; peer.dispatchEvent(new Event('icegatheringstatechange'));
186
+ await pending;
187
+ await assert.rejects(gatherIce(new Peer(), 5), /timed out/);
188
+ });
189
+
190
+ test('out-of-order inbound termination cannot be resurrected by a delayed connect', () => {
191
+ const calls = createCalls(fake());
192
+ calls.webhook(webhook({id: 'wa-in', event: 'terminate'}), '123456');
193
+ calls.webhook(webhook(inbound()), '123456');
194
+ assert.equal(calls.list('alice').length, 0);
195
+ });
196
+
197
+ test('hang-up stays pinned to the original business number if settings change', async () => {
198
+ const {meta, sent} = fake();
199
+ let phoneNumberId = '123456';
200
+ const calls = createCalls({meta, getPhoneNumberId: async () => phoneNumberId});
201
+ const c = await calls.dial('alice', '447700900123', offer);
202
+ phoneNumberId = '999999';
203
+ await calls.action(c.id, 'alice', 'terminate');
204
+ assert.equal(sent.at(-1).phoneNumberId, '123456');
205
+ });
206
+
207
+
208
+ test('an ambiguous connect timeout is correlated with its webhook and terminated, never retried', async () => {
209
+ let opaque, connectCount = 0;
210
+ const actions = [];
211
+ const calls = createCalls({getPhoneNumberId: async () => '123456', meta: async (endpoint, opts) => {
212
+ if (endpoint === 'call_permissions') return permission(true);
213
+ if (opts.body.action === 'connect') {
214
+ connectCount++; opaque = opts.body.biz_opaque_callback_data;
215
+ throw new CallingError('Timed out', 502, true);
216
+ }
217
+ actions.push(opts.body.action); return {success: true};
218
+ }});
219
+ await assert.rejects(calls.dial('alice', '447700900123', offer));
220
+ assert.equal(calls.list('alice')[0].status, 'ending');
221
+ calls.webhook(webhook({id: 'accepted-despite-timeout', event: 'connect', session: answer, biz_opaque_callback_data: opaque}), '123456');
222
+ assert.equal(calls.poll(opaque, 'alice').session, null);
223
+ // Polling normally refreshes an owner's heartbeat; an ending call must still be cleaned up.
224
+ await calls.sweep();
225
+ assert.equal(connectCount, 1);
226
+ assert.deepEqual(actions, ['terminate']);
227
+ assert.equal(calls.list('alice')[0].status, 'ended');
228
+ });
229
+
230
+
231
+ test('recipient lookup matches secondary emails, returns distinct phone choices, and preserves visibility', async () => {
232
+ const {createRecipientLookup} = await import('../lib/recipients.js');
233
+ const entries = [
234
+ {id: 'mine', data: {name: 'Sam', email: 'sam@example.test', emails: [{address: 'work@example.test'}], phone: '+44 7700 900123', phones: [{number: '+447700900123'}, {number: '+447700900124'}]}},
235
+ {id: 'private', data: {name: 'Private', email: 'work@example.test', phone: '+447700900125'}},
236
+ {id: 'shared', data: {name: 'Shared', email: 'shared@example.test', phone: '+447700900126'}}
237
+ ];
238
+ let reads = 0;
239
+ const lookup = createRecipientLookup({canRead: v => v.contacts, list: async () => { reads++; return entries; },
240
+ readable: async () => new Set(['mine', 'shared'])});
241
+ assert.deepEqual(await lookup({contacts: false}, {email: 'work@example.test'}), []);
242
+ assert.equal(reads, 0, 'disabled or forbidden Contacts never fetches records');
243
+ const matches = await lookup({contacts: true}, {email: ' WORK@example.test '});
244
+ assert.deepEqual(matches.map(c => c.phone), ['+447700900123', '+447700900124']);
245
+ assert.deepEqual(await lookup({contacts: true}, {contactId: 'private'}), []);
246
+ assert.equal((await lookup({contacts: true}, {contactId: 'shared'}))[0].name, 'Shared');
247
+ });
248
+
249
+ test('embedding availability requires call permission', async t => {
250
+ const server = await app({allow: false}); t.after(() => server.close());
251
+ for (const path of ['/availability', '/recipients?email=someone@example.test']) {
252
+ assert.equal((await server.inject({url: url(path), headers: alice})).statusCode, 403);
253
+ }
254
+ });
@@ -103,13 +103,13 @@ export async function apiTokensRoutes(fastify, opts = {}) {
103
103
  fastify.get('/api-tokens/_count', canRead, async (request) => apiTokensBadge(await listTokensSanitised(request.user)));
104
104
 
105
105
  fastify.post('/api-tokens', canCreate, async (request, reply) => {
106
- const {name, project, scopes, expiresAt} = request.body || {};
106
+ const {name, project, scopes, expiresAt, draftsOnly} = request.body || {};
107
107
  if (project && !canSeeArtefact(request.user, {meta: {project}})) {
108
108
  return reply.status(403).send({error: 'Access denied for this project'});
109
109
  }
110
110
  try {
111
111
  const creator = request.user?.name || request.user?.email || null;
112
- const {entry, plaintext} = await createToken({name, project, scopes, expiresAt, createdBy: creator});
112
+ const {entry, plaintext} = await createToken({name, project, scopes, expiresAt, draftsOnly, createdBy: creator});
113
113
  // The plaintext appears here and nowhere else - only the hash is stored.
114
114
  return reply.status(201).send({token: entry, plaintext});
115
115
  } catch (err) {
@@ -62,7 +62,7 @@ import {riskyConnectionOptions, signedOnly} from '../../services/codePolicy.js';
62
62
  import {PRESET_COLLECTION_SLUGS} from '../../services/presetCollections.js';
63
63
  import {ensureFormForCollection} from '../../services/forms.js';
64
64
  import {hooks} from '../../services/hooks.js';
65
- import {authenticateApiToken, scopeAllows} from '../../services/apiTokens.js';
65
+ import {DRAFT_STATUS, authenticateApiToken, draftsOnlyDecision, scopeAllows} from '../../services/apiTokens.js';
66
66
  import {isProjectEnabled, resolveArtefactProject} from '../../services/projects.js';
67
67
  import {maskConnections, restoreConnections} from '../../services/connectionSecrets.js';
68
68
  import {
@@ -244,16 +244,29 @@ export function applyReadFieldAllowlist(schema, payload) {
244
244
  }
245
245
 
246
246
  /**
247
- * Check public collection API access.
248
- * Returns an error reply if access is denied, otherwise resolves (returns undefined).
247
+ * Check public collection API access. On a refusal the error reply is SENT
248
+ * here and this resolves false; the caller must stop. True = go ahead.
249
+ *
250
+ * It returns a boolean, never the reply: a Fastify reply is a thenable that
251
+ * resolves to undefined, so `await`ing a helper that returned
252
+ * `reply.status(403).send(...)` gave the caller undefined - and the old
253
+ * `if (denied !== undefined) return;` let every refused create, update and
254
+ * delete go on and write after the 401/403 had been sent. Decide on
255
+ * `reply.sent`, which nothing can turn into a pass by accident.
249
256
  *
250
257
  * @param {object} schema
251
258
  * @param {'create'|'read'|'update'|'delete'} operation
252
259
  * @param {object} request - Fastify request
253
260
  * @param {object} reply - Fastify reply
254
- * @returns {Promise<object|undefined>}
261
+ * @returns {Promise<boolean>} true when the operation may go ahead
255
262
  */
256
263
  export async function checkPublicAccess(schema, operation, request, reply) {
264
+ await publicAccessGate(schema, operation, request, reply);
265
+ return !reply.sent;
266
+ }
267
+
268
+ /** The checks behind checkPublicAccess(); sends the refusal itself. */
269
+ async function publicAccessGate(schema, operation, request, reply) {
257
270
  // Hard kill-switch: if the artefact's project is disabled, the whole
258
271
  // external surface is off - 404 (no oracle). This covers /api/v1
259
272
  // collections, the synthesized-schema custom endpoints (/api/x/*, whose
@@ -739,8 +752,7 @@ export async function collectionsRoutes(fastify) {
739
752
  return reply.status(401).send({ error: 'Authentication required' });
740
753
  }
741
754
  } else {
742
- const denied = await checkPublicAccess(schema, 'read', request, reply);
743
- if (denied !== undefined) return;
755
+ if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
744
756
  }
745
757
  if (nobodysRows(request, reply, filter)) return;
746
758
 
@@ -782,8 +794,7 @@ export async function collectionsRoutes(fastify) {
782
794
  const schema = await getCollection(request.params.slug);
783
795
  if (!schema) return reply.status(404).send({ error: 'Collection not found' });
784
796
 
785
- const denied = await checkPublicAccess(schema, 'read', request, reply);
786
- if (denied !== undefined) return;
797
+ if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
787
798
  if (nobodysRows(request, reply)) return;
788
799
 
789
800
  const entry = await ownRow(request, reply);
@@ -854,8 +865,7 @@ export async function collectionsRoutes(fastify) {
854
865
  const schema = await getCollection(attrs.slug);
855
866
  if (!schema) return reply.status(404).send({ error: 'Collection not found' });
856
867
 
857
- const denied = await checkPublicAccess(schema, 'read', request, reply);
858
- if (denied !== undefined) return;
868
+ if (!(await checkPublicAccess(schema, 'read', request, reply))) return;
859
869
  // A fragment renders every row it is given; a user-data preset has no "everyone's rows" for anyone but root.
860
870
  if (isUserDataPreset(attrs.slug) && !isRoot(request.user)) {
861
871
  return reply.status(403).send({ error: NOT_YOUR_ROWS });
@@ -907,12 +917,16 @@ export async function collectionsRoutes(fastify) {
907
917
  const schema = await getCollection(request.params.slug);
908
918
  if (!schema) return reply.status(404).send({ error: 'Collection not found' });
909
919
 
910
- const denied = await checkPublicAccess(schema, 'create', request, reply);
911
- if (denied !== undefined) return;
920
+ if (!(await checkPublicAccess(schema, 'create', request, reply))) return;
912
921
  if (nobodysRows(request, reply)) return;
922
+ // A drafts-only token's row is held back for a person to publish,
923
+ // whatever status the caller sent.
924
+ const held = draftsOnlyDecision(request.apiToken, schema, 'create');
925
+ if (!held.ok) return reply.status(held.status).send({error: held.error});
913
926
 
914
927
  try {
915
928
  let data = pinOwner(request.params.slug, request.body?.data || {}, request.user);
929
+ if (held.field) data = {...data, [held.field]: DRAFT_STATUS};
916
930
  // A role created in the admin belongs to no plugin; see keepRoleSystemFields.
917
931
  if (request.params.slug === 'roles') {
918
932
  data = {...data};
@@ -932,17 +946,24 @@ export async function collectionsRoutes(fastify) {
932
946
  const schema = await getCollection(request.params.slug);
933
947
  if (!schema) return reply.status(404).send({ error: 'Collection not found' });
934
948
 
935
- const denied = await checkPublicAccess(schema, 'update', request, reply);
936
- if (denied !== undefined) return;
949
+ if (!(await checkPublicAccess(schema, 'update', request, reply))) return;
937
950
  if (nobodysRows(request, reply)) return;
938
951
  let existing = null;
939
952
  if (isUserDataPreset(request.params.slug)) {
940
953
  existing = await ownRow(request, reply, {write: true});
941
954
  if (!existing) return;
942
955
  }
956
+ // A drafts-only token changes drafts only, and leaves them drafts.
957
+ let held = {ok: true, field: null};
958
+ if (request.apiToken?.draftsOnly) {
959
+ held = draftsOnlyDecision(request.apiToken, schema, 'update',
960
+ existing || await getEntry(request.params.slug, request.params.id));
961
+ if (!held.ok) return reply.status(held.status).send({error: held.error});
962
+ }
943
963
 
944
964
  try {
945
- const data = pinOwner(request.params.slug, request.body?.data || {}, request.user, existing);
965
+ let data = pinOwner(request.params.slug, request.body?.data || {}, request.user, existing);
966
+ if (held.field) data = {...data, [held.field]: DRAFT_STATUS};
946
967
  return await updateEntry(request.params.slug, request.params.id, data);
947
968
  } catch (err) {
948
969
  const status = err.message === 'Entry not found' ? 404 : 400;
@@ -954,10 +975,14 @@ export async function collectionsRoutes(fastify) {
954
975
  const schema = await getCollection(request.params.slug);
955
976
  if (!schema) return reply.status(404).send({ error: 'Collection not found' });
956
977
 
957
- const denied = await checkPublicAccess(schema, 'delete', request, reply);
958
- if (denied !== undefined) return;
978
+ if (!(await checkPublicAccess(schema, 'delete', request, reply))) return;
959
979
  if (nobodysRows(request, reply)) return;
960
980
  if (isUserDataPreset(request.params.slug) && !(await ownRow(request, reply, {write: true}))) return;
981
+ if (request.apiToken?.draftsOnly) {
982
+ const held = draftsOnlyDecision(request.apiToken, schema, 'delete',
983
+ await getEntry(request.params.slug, request.params.id));
984
+ if (!held.ok) return reply.status(held.status).send({error: held.error});
985
+ }
961
986
 
962
987
  try {
963
988
  await deleteEntry(request.params.slug, request.params.id);
@@ -51,8 +51,7 @@ export async function endpointsPublicRoutes(fastify) {
51
51
  api: { read: { enabled: true, access: def.auth, fields: def.fields } },
52
52
  meta: { project: def.project }
53
53
  };
54
- const denied = await checkPublicAccess(synth, 'read', request, reply);
55
- if (denied !== undefined) return;
54
+ if (!(await checkPublicAccess(synth, 'read', request, reply))) return;
56
55
 
57
56
  const run = async () => {
58
57
  const result = await executeEndpoint(def, params, request.query);