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,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 {
@@ -919,9 +919,14 @@ export async function collectionsRoutes(fastify) {
919
919
 
920
920
  if (!(await checkPublicAccess(schema, 'create', request, reply))) return;
921
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});
922
926
 
923
927
  try {
924
928
  let data = pinOwner(request.params.slug, request.body?.data || {}, request.user);
929
+ if (held.field) data = {...data, [held.field]: DRAFT_STATUS};
925
930
  // A role created in the admin belongs to no plugin; see keepRoleSystemFields.
926
931
  if (request.params.slug === 'roles') {
927
932
  data = {...data};
@@ -948,9 +953,17 @@ export async function collectionsRoutes(fastify) {
948
953
  existing = await ownRow(request, reply, {write: true});
949
954
  if (!existing) return;
950
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
+ }
951
963
 
952
964
  try {
953
- 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};
954
967
  return await updateEntry(request.params.slug, request.params.id, data);
955
968
  } catch (err) {
956
969
  const status = err.message === 'Entry not found' ? 404 : 400;
@@ -965,6 +978,11 @@ export async function collectionsRoutes(fastify) {
965
978
  if (!(await checkPublicAccess(schema, 'delete', request, reply))) return;
966
979
  if (nobodysRows(request, reply)) return;
967
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
+ }
968
986
 
969
987
  try {
970
988
  await deleteEntry(request.params.slug, request.params.id);
@@ -67,12 +67,13 @@ function hashToken(plaintext) {
67
67
  * @returns {object}
68
68
  */
69
69
  function sanitise(entry) {
70
- const {name, project, tokenHint, scopes, enabled, expiresAt, lastUsedAt, createdBy} = entry.data || {};
70
+ const {name, project, tokenHint, scopes, enabled, draftsOnly, expiresAt, lastUsedAt, createdBy} = entry.data || {};
71
71
  return {
72
72
  id: entry.id,
73
73
  name, project, tokenHint,
74
74
  scopes: Array.isArray(scopes) ? scopes : [],
75
75
  enabled: enabled !== false,
76
+ draftsOnly: draftsOnly === true,
76
77
  expiresAt: expiresAt || null,
77
78
  lastUsedAt: lastUsedAt || null,
78
79
  createdBy: createdBy || null,
@@ -141,6 +142,54 @@ export function contentScopeAllows(scopes, resource) {
141
142
  return scopes.some(s => s.content === resource);
142
143
  }
143
144
 
145
+ /** The status a drafts-only token's writes are held at. */
146
+ export const DRAFT_STATUS = 'draft';
147
+
148
+ /**
149
+ * The field that says whether an entry is a draft: a `status` field whose
150
+ * options include `draft` (the Blog's posts, any collection made the same
151
+ * way). Null when the collection has no such field - a drafts-only token
152
+ * may not write there at all, since nothing would hold its rows back.
153
+ *
154
+ * @param {{fields?: object[]}} schema
155
+ * @returns {string|null}
156
+ */
157
+ export function draftField(schema) {
158
+ const field = (schema?.fields || []).find(f => f?.name === 'status');
159
+ if (!field) return null;
160
+ const options = Array.isArray(field.options) ? field.options : [];
161
+ const values = options.map(o => (o && typeof o === 'object') ? o.value : o);
162
+ return values.includes(DRAFT_STATUS) ? field.name : null;
163
+ }
164
+
165
+ /**
166
+ * What a drafts-only token may do to a collection, decided before the write.
167
+ * Create: the row is held as a draft whatever the caller sent. Update: only a
168
+ * row that is a draft now, and it stays one. Delete: only a draft. Reads are
169
+ * not this flag's business (api.read and the scopes decide them).
170
+ *
171
+ * Pure - the route passes the stored row for update/delete.
172
+ *
173
+ * @param {{draftsOnly?: boolean}|null} token
174
+ * @param {{fields?: object[]}} schema
175
+ * @param {'create'|'read'|'update'|'delete'} operation
176
+ * @param {{data?: object}|null} [existing]
177
+ * @returns {{ok: true, field: string|null} | {ok: false, status: 403|404, error: string}}
178
+ */
179
+ export function draftsOnlyDecision(token, schema, operation, existing = null) {
180
+ if (!token?.draftsOnly || operation === 'read') return {ok: true, field: null};
181
+ const field = draftField(schema);
182
+ if (!field) {
183
+ return {ok: false, status: 403, error: 'This token may only write drafts, and this collection has no draft status'};
184
+ }
185
+ if (operation === 'create') return {ok: true, field};
186
+ if (!existing) return {ok: false, status: 404, error: 'Entry not found'};
187
+ if (existing.data?.[field] !== DRAFT_STATUS) {
188
+ return {ok: false, status: 403, error: 'This token may only change drafts, and this entry is not one'};
189
+ }
190
+ return {ok: true, field};
191
+ }
192
+
144
193
  const BEARER_RE = /^Bearer (dcms_[a-f0-9]{64})$/;
145
194
 
146
195
  /**
@@ -172,17 +221,18 @@ export async function authenticateApiToken(request, {project, allows, projectErr
172
221
  /**
173
222
  * Create a new token. The plaintext is returned ONCE here and never again.
174
223
  *
175
- * @param {{name: string, project: string, scopes?: object[], expiresAt?: string|null, createdBy?: string|null}} input
224
+ * @param {{name: string, project: string, scopes?: object[], expiresAt?: string|null, draftsOnly?: boolean, createdBy?: string|null}} input
176
225
  * @returns {Promise<{entry: object, plaintext: string}>} Sanitised entry + plaintext
177
226
  * @throws {Error} On validation failure
178
227
  */
179
- export async function createToken({name, project, scopes = [], expiresAt = null, createdBy = null}) {
228
+ export async function createToken({name, project, scopes = [], expiresAt = null, draftsOnly = false, createdBy = null}) {
180
229
  if (!name || typeof name !== 'string' || !name.trim()) throw new Error('Token name is required');
181
230
  if (!project || typeof project !== 'string') throw new Error('Token project is required');
182
231
  if (!await getProject(project)) throw new Error(`Unknown project "${project}"`);
183
232
  const scopeError = validateScopes(scopes);
184
233
  if (scopeError) throw new Error(scopeError);
185
234
  if (expiresAt != null && Number.isNaN(Date.parse(expiresAt))) throw new Error('expiresAt must be a valid date');
235
+ if (draftsOnly != null && typeof draftsOnly !== 'boolean') throw new Error('draftsOnly must be true or false');
186
236
 
187
237
  const plaintext = 'dcms_' + crypto.randomBytes(32).toString('hex');
188
238
  const data = {
@@ -192,6 +242,7 @@ export async function createToken({name, project, scopes = [], expiresAt = null,
192
242
  tokenHint: plaintext.slice(-4),
193
243
  scopes: scopes || [],
194
244
  enabled: true,
245
+ draftsOnly: draftsOnly === true,
195
246
  expiresAt: expiresAt || null,
196
247
  lastUsedAt: null,
197
248
  createdBy
@@ -281,7 +332,7 @@ export async function getTokenSanitised(id) {
281
332
  * for the token's lifetime - revoke and re-issue to rebind.
282
333
  *
283
334
  * @param {string} id
284
- * @param {{name?: string, enabled?: boolean, scopes?: object[], expiresAt?: string|null}} patch
335
+ * @param {{name?: string, enabled?: boolean, draftsOnly?: boolean, scopes?: object[], expiresAt?: string|null}} patch
285
336
  * @returns {Promise<object|null>} Sanitised entry, or null when not found
286
337
  * @throws {Error} On validation failure
287
338
  */
@@ -296,6 +347,10 @@ export async function updateToken(id, patch = {}) {
296
347
  data.name = patch.name.trim();
297
348
  }
298
349
  if (patch.enabled != null) data.enabled = patch.enabled !== false;
350
+ if (patch.draftsOnly != null) {
351
+ if (typeof patch.draftsOnly !== 'boolean') throw new Error('draftsOnly must be true or false');
352
+ data.draftsOnly = patch.draftsOnly;
353
+ }
299
354
  if (patch.scopes != null) {
300
355
  const scopeError = validateScopes(patch.scopes);
301
356
  if (scopeError) throw new Error(scopeError);
@@ -87,6 +87,7 @@ const PRESETS = [
87
87
  {name: 'tokenHint', label: 'Hint', type: 'text'},
88
88
  {name: 'scopes', label: 'Scopes', type: 'array', items: 'object', default: []},
89
89
  {name: 'enabled', label: 'Enabled', type: 'boolean', default: true},
90
+ {name: 'draftsOnly', label: 'Drafts Only', type: 'boolean', default: false},
90
91
  {name: 'expiresAt', label: 'Expires At', type: 'datetime'},
91
92
  {name: 'lastUsedAt', label: 'Last Used', type: 'datetime'},
92
93
  {name: 'createdBy', label: 'Created By', type: 'text'}