pgkiln 0.31.0 → 0.36.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 (131) hide show
  1. package/README.md +2 -2
  2. package/SECURITY.md +10 -0
  3. package/db/migrations/076_form_lost_update.sql +50 -0
  4. package/db/migrations/077_warn_unsaved.sql +41 -0
  5. package/db/migrations/078_url_region.sql +12 -0
  6. package/db/migrations/079_developer_toolbar.sql +53 -0
  7. package/db/migrations/080_search.sql +326 -0
  8. package/db/migrations/081_mail.sql +621 -0
  9. package/db/migrations/082_app_backups.sql +73 -0
  10. package/db/migrations/083_availability.sql +156 -0
  11. package/db/migrations/084_feedback.sql +46 -0
  12. package/db/migrations/085_page_behaviour.sql +65 -0
  13. package/db/migrations/086_data_settings.sql +599 -0
  14. package/db/migrations/087_login_page.sql +175 -0
  15. package/db/migrations/088_region_templates.sql +18 -0
  16. package/db/migrations/089_page_groups.sql +330 -0
  17. package/docs/apex-feature-parity.md +61 -39
  18. package/docs/guide/01-installation.md +1 -0
  19. package/docs/guide/03-builder.md +154 -4
  20. package/docs/guide/04-pages-and-regions.md +157 -3
  21. package/docs/guide/05-items.md +47 -0
  22. package/docs/guide/06-processing.md +210 -2
  23. package/docs/guide/07-dynamic-actions.md +60 -2
  24. package/docs/guide/08-security.md +56 -4
  25. package/docs/guide/09-reference.md +21 -0
  26. package/docs/guide/11-from-apex.md +9 -2
  27. package/docs/guide/12-development.md +40 -2
  28. package/docs/guide/14-globalization.md +15 -0
  29. package/docs/guide/15-extensions.md +1 -1
  30. package/docs/guide/17-mobile.md +3 -1
  31. package/docs/guide/18-cli.md +32 -1
  32. package/docs/guide/20-ai-agents.md +5 -2
  33. package/examples/hr/hr_50_search.sql +47 -0
  34. package/examples/hr/hr_51_mail.sql +70 -0
  35. package/examples/hr/hr_52_feedback.sql +15 -0
  36. package/examples/hr/hr_53_data_settings.sql +108 -0
  37. package/examples/hr/hr_54_region_templates.sql +67 -0
  38. package/examples/hr/hr_55_page_groups.sql +24 -0
  39. package/package.json +3 -1
  40. package/public/app.css +122 -3
  41. package/public/app.js +496 -13
  42. package/public/builder.css +22 -0
  43. package/public/builder.js +77 -0
  44. package/public/code-editor.css +3 -3
  45. package/public/sw.js +5 -3
  46. package/src/app.ts +10 -0
  47. package/src/appfiles.ts +13 -0
  48. package/src/automations.ts +12 -0
  49. package/src/builder/advisor.ts +68 -14
  50. package/src/builder/arrange.ts +2 -2
  51. package/src/builder/availability.ts +74 -0
  52. package/src/builder/backups.ts +134 -0
  53. package/src/builder/components.ts +123 -16
  54. package/src/builder/ddl-tools.ts +114 -0
  55. package/src/builder/designer.ts +35 -4
  56. package/src/builder/feedback.ts +82 -0
  57. package/src/builder/forms.ts +10 -5
  58. package/src/builder/home.ts +3 -0
  59. package/src/builder/locks.ts +15 -5
  60. package/src/builder/login-page.ts +82 -0
  61. package/src/builder/mail.ts +425 -0
  62. package/src/builder/newapp.ts +1 -1
  63. package/src/builder/region-help.ts +73 -0
  64. package/src/builder/region-settings.ts +19 -3
  65. package/src/builder/routes.ts +60 -5
  66. package/src/builder/search.ts +4 -4
  67. package/src/builder/shared.ts +3 -2
  68. package/src/builder/sql.ts +3 -0
  69. package/src/builder/ui.ts +9 -3
  70. package/src/cli/apps.ts +46 -5
  71. package/src/cli/main.ts +66 -5
  72. package/src/cli/mcp.ts +58 -4
  73. package/src/cli/replace.ts +40 -4
  74. package/src/ddl.ts +509 -0
  75. package/src/geocode.ts +44 -0
  76. package/src/i18n/ar.ts +56 -0
  77. package/src/i18n/cs.ts +56 -0
  78. package/src/i18n/da.ts +56 -0
  79. package/src/i18n/de.ts +56 -0
  80. package/src/i18n/el.ts +56 -0
  81. package/src/i18n/es.ts +56 -0
  82. package/src/i18n/fi.ts +56 -0
  83. package/src/i18n/fr.ts +56 -0
  84. package/src/i18n/he.ts +56 -0
  85. package/src/i18n/it.ts +56 -0
  86. package/src/i18n/ja.ts +56 -0
  87. package/src/i18n/ko.ts +56 -0
  88. package/src/i18n/nb.ts +56 -0
  89. package/src/i18n/pl.ts +56 -0
  90. package/src/i18n/pt.ts +56 -0
  91. package/src/i18n/ru.ts +56 -0
  92. package/src/i18n/sv.ts +56 -0
  93. package/src/i18n/tr.ts +56 -0
  94. package/src/i18n/uk.ts +56 -0
  95. package/src/i18n/zh.ts +56 -0
  96. package/src/i18n.ts +112 -0
  97. package/src/icons.ts +2 -1
  98. package/src/layout.ts +3 -2
  99. package/src/mail/mail.ts +148 -0
  100. package/src/mail/providers.ts +444 -0
  101. package/src/metadata.ts +34 -10
  102. package/src/runtime/ajax.ts +97 -0
  103. package/src/runtime/authz.ts +1 -1
  104. package/src/runtime/availability.ts +37 -0
  105. package/src/runtime/context.ts +46 -6
  106. package/src/runtime/data-export.ts +94 -0
  107. package/src/runtime/data-items.ts +194 -0
  108. package/src/runtime/devbar.ts +184 -0
  109. package/src/runtime/display-selector.ts +12 -4
  110. package/src/runtime/engine.ts +26 -1
  111. package/src/runtime/feedback.ts +128 -0
  112. package/src/runtime/grid.ts +170 -26
  113. package/src/runtime/items.ts +8 -0
  114. package/src/runtime/lists.ts +11 -1
  115. package/src/runtime/password-reset.ts +171 -0
  116. package/src/runtime/processes.ts +83 -2
  117. package/src/runtime/pwa.ts +7 -10
  118. package/src/runtime/regions.ts +41 -0
  119. package/src/runtime/render.ts +48 -7
  120. package/src/runtime/report-views.ts +4 -2
  121. package/src/runtime/report.ts +36 -22
  122. package/src/runtime/rest.ts +4 -0
  123. package/src/runtime/routes.ts +94 -37
  124. package/src/runtime/search.ts +252 -0
  125. package/src/runtime/signin.ts +80 -0
  126. package/src/runtime/url-region.ts +93 -0
  127. package/src/security.ts +11 -1
  128. package/src/server.ts +2 -0
  129. package/src/session.ts +8 -2
  130. package/src/static-version.ts +34 -0
  131. package/src/workingcopy.ts +2 -2
@@ -0,0 +1,444 @@
1
+ // Mail providers (migration 081): one way to hand a message over per
2
+ // provider, behind one interface.
3
+ //
4
+ // - smtp: any SMTP server (nodemailer), with a user name and password
5
+ // or OAuth2 (SASL XOAUTH2; a client-credentials token, e.g. from
6
+ // Microsoft Entra for Exchange Online, or Google Workspace);
7
+ // - graph: Microsoft Graph sendMail, with an Entra application's client
8
+ // credentials (application permission Mail.Send);
9
+ // - ses: Amazon SES (API v2, the raw MIME message), signed with
10
+ // Signature Version 4;
11
+ // - resend, postmark, sendgrid, mailgun: their HTTP APIs with an API key;
12
+ // - log: sends nothing: the server's log shows the message (development).
13
+ //
14
+ // Secrets (password, client secret, API key, AWS secret key) come decrypted
15
+ // from service.ts and never appear in errors. A MailError says whether trying
16
+ // again later may help (network problems, 429, 5xx) or not (rejected).
17
+ import { createHash } from 'node:crypto';
18
+ import nodemailer from 'nodemailer';
19
+ import MailComposer from 'nodemailer/lib/mail-composer/index.js';
20
+ import { signV4 } from '../objectstore.ts';
21
+
22
+ export const PROVIDERS = ['smtp', 'graph', 'ses', 'resend', 'postmark', 'sendgrid', 'mailgun', 'log'] as const;
23
+ export type Provider = (typeof PROVIDERS)[number];
24
+
25
+ export const PROVIDER_LABELS: Record<Provider, string> = {
26
+ smtp: 'SMTP (password or OAuth2)',
27
+ graph: 'Microsoft 365 (Graph API)',
28
+ ses: 'Amazon SES',
29
+ resend: 'Resend',
30
+ postmark: 'Postmark',
31
+ sendgrid: 'SendGrid',
32
+ mailgun: 'Mailgun',
33
+ log: 'Log only (development: nothing is sent)',
34
+ };
35
+
36
+ export interface Attachment {
37
+ filename: string;
38
+ mime: string;
39
+ content: Buffer;
40
+ }
41
+
42
+ export interface OutgoingMail {
43
+ from: string;
44
+ to: string[];
45
+ cc: string[];
46
+ bcc: string[];
47
+ replyTo: string | null;
48
+ subject: string;
49
+ text: string | null;
50
+ html: string | null;
51
+ attachments: Attachment[];
52
+ }
53
+
54
+ export interface ServiceSettings {
55
+ // smtp
56
+ host?: string;
57
+ port?: number;
58
+ security?: 'tls' | 'starttls' | 'none';
59
+ auth?: 'none' | 'password' | 'oauth2';
60
+ username?: string;
61
+ tls_verify?: boolean;
62
+ // OAuth2 client credentials (smtp with auth oauth2, graph)
63
+ tenant_id?: string;
64
+ client_id?: string;
65
+ token_url?: string;
66
+ scope?: string;
67
+ // graph
68
+ save_to_sent_items?: boolean;
69
+ // ses
70
+ region?: string;
71
+ access_key_id?: string;
72
+ // mailgun
73
+ domain?: string;
74
+ mailgun_region?: 'us' | 'eu';
75
+ // postmark
76
+ message_stream?: string;
77
+ // the API's address instead of the provider's own (administrators only; a proxy, or tests)
78
+ base_url?: string;
79
+ default_from?: string;
80
+ }
81
+
82
+ export class MailError extends Error {
83
+ constructor(message: string, readonly retry: boolean) {
84
+ super(message);
85
+ }
86
+ }
87
+
88
+ const TIMEOUT_MS = 30_000;
89
+ const base = (s: ServiceSettings, own: string) => (s.base_url || own).replace(/\/+$/, '');
90
+
91
+ /** The problems of a service's settings for its provider (the builder shows them). */
92
+ export function settingsProblems(provider: Provider, s: ServiceSettings, hasSecret: boolean): string[] {
93
+ const out: string[] = [];
94
+ const need = (v: unknown, what: string) => (typeof v === 'string' && v.trim() ? null : out.push(`${what} is required.`));
95
+ if (s.base_url && !/^https?:\/\/[^\s]+$/i.test(s.base_url)) out.push('The base URL starts with http:// or https://.');
96
+ switch (provider) {
97
+ case 'smtp':
98
+ need(s.host, 'The SMTP host');
99
+ if (s.port !== undefined && !(Number.isInteger(s.port) && s.port > 0 && s.port < 65536)) out.push('The port is 1 to 65535.');
100
+ if ((s.auth ?? 'password') !== 'none') need(s.username, 'The user name');
101
+ if (s.auth === 'oauth2') {
102
+ need(s.client_id, 'The client (application) ID');
103
+ if (!s.token_url && !s.tenant_id) out.push('The tenant ID (Microsoft Entra) or a token URL is required.');
104
+ }
105
+ if ((s.auth ?? 'password') !== 'none' && !hasSecret) out.push(s.auth === 'oauth2' ? 'The client secret is required.' : 'The password is required.');
106
+ break;
107
+ case 'graph':
108
+ need(s.tenant_id, 'The tenant ID');
109
+ need(s.client_id, 'The client (application) ID');
110
+ if (!hasSecret) out.push('The client secret is required.');
111
+ break;
112
+ case 'ses':
113
+ need(s.region, 'The AWS region');
114
+ need(s.access_key_id, 'The access key ID');
115
+ if (s.region && !/^[a-z]{2}(-[a-z]+)+-\d$/.test(s.region)) out.push('The region is like eu-west-1.');
116
+ if (!hasSecret) out.push('The secret access key is required.');
117
+ break;
118
+ case 'mailgun':
119
+ need(s.domain, 'The sending domain');
120
+ if (!hasSecret) out.push('The API key is required.');
121
+ break;
122
+ case 'resend':
123
+ case 'postmark':
124
+ case 'sendgrid':
125
+ if (!hasSecret) out.push(provider === 'postmark' ? 'The server token is required.' : 'The API key is required.');
126
+ break;
127
+ }
128
+ return out;
129
+ }
130
+
131
+ // ---------------------------------------------------------------- HTTP
132
+
133
+ async function http(url: string, init: { method?: string; headers: Record<string, string>; body?: string | FormData }) {
134
+ let res: Response;
135
+ try {
136
+ res = await fetch(url, { method: init.method ?? 'POST', headers: init.headers, body: init.body, redirect: 'error', signal: AbortSignal.timeout(TIMEOUT_MS) });
137
+ } catch (e) {
138
+ throw new MailError(`The mail service did not answer (${(e as Error).name === 'TimeoutError' ? 'timed out' : (e as Error).message}).`, true);
139
+ }
140
+ const text = (await res.text().catch(() => '')).slice(0, 2000);
141
+ if (!res.ok) {
142
+ let detail = text;
143
+ try {
144
+ const j = JSON.parse(text);
145
+ detail = j.message ?? j.Message ?? j.error?.message ?? j.errors?.[0]?.message ?? j.error_description ?? j.error ?? text;
146
+ } catch {
147
+ // not JSON
148
+ }
149
+ throw new MailError(`The mail service refused the message (HTTP ${res.status}): ${String(detail).slice(0, 500)}`, res.status === 408 || res.status === 429 || res.status >= 500);
150
+ }
151
+ return { res, text };
152
+ }
153
+
154
+ const json = (text: string) => {
155
+ try {
156
+ return JSON.parse(text);
157
+ } catch {
158
+ return {};
159
+ }
160
+ };
161
+
162
+ // ---------------------------------------------------------------- OAuth2 client credentials
163
+
164
+ const tokens = new Map<string, { token: string; until: number }>();
165
+
166
+ /** An access token by the client credentials grant, cached until shortly before it expires. */
167
+ export async function clientCredentialsToken(tokenUrl: string, clientId: string, secret: string, scope: string): Promise<string> {
168
+ const key = createHash('sha256').update(JSON.stringify([tokenUrl, clientId, secret, scope])).digest('hex');
169
+ const hit = tokens.get(key);
170
+ if (hit && hit.until > Date.now()) return hit.token;
171
+ const body = new URLSearchParams({ grant_type: 'client_credentials', client_id: clientId, client_secret: secret, scope }).toString();
172
+ let r;
173
+ try {
174
+ r = await http(tokenUrl, { headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, body });
175
+ } catch (e) {
176
+ throw new MailError(`No access token: ${(e as Error).message}`, (e as MailError).retry ?? true);
177
+ }
178
+ const j = json(r.text);
179
+ if (typeof j.access_token !== 'string') throw new MailError('No access token: the token endpoint answered without one.', false);
180
+ tokens.set(key, { token: j.access_token, until: Date.now() + Math.max(60, Number(j.expires_in) || 3600) * 1000 - 60_000 });
181
+ return j.access_token;
182
+ }
183
+
184
+ /** Forget cached tokens (tests; a changed secret gets a new key anyway). */
185
+ export const clearTokens = () => tokens.clear();
186
+
187
+ const entraTokenUrl = (s: ServiceSettings) => s.token_url || `https://login.microsoftonline.com/${encodeURIComponent(s.tenant_id ?? '')}/oauth2/v2.0/token`;
188
+
189
+ // ---------------------------------------------------------------- providers
190
+
191
+ const b64 = (b: Buffer) => b.toString('base64');
192
+
193
+ async function smtp(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
194
+ const security = s.security ?? 'starttls';
195
+ const auth = s.auth ?? 'password';
196
+ let authOpt: Record<string, unknown> | undefined;
197
+ if (auth === 'password') authOpt = { user: s.username, pass: secret ?? '' };
198
+ else if (auth === 'oauth2')
199
+ authOpt = {
200
+ type: 'OAuth2',
201
+ user: s.username,
202
+ accessToken: await clientCredentialsToken(entraTokenUrl(s), s.client_id ?? '', secret ?? '', s.scope || 'https://outlook.office365.com/.default'),
203
+ };
204
+ const transport = nodemailer.createTransport({
205
+ host: s.host,
206
+ port: s.port ?? (security === 'tls' ? 465 : 587),
207
+ secure: security === 'tls',
208
+ requireTLS: security === 'starttls',
209
+ ignoreTLS: security === 'none',
210
+ auth: authOpt as never,
211
+ tls: { rejectUnauthorized: s.tls_verify !== false },
212
+ connectionTimeout: 15_000,
213
+ greetingTimeout: 15_000,
214
+ socketTimeout: TIMEOUT_MS,
215
+ disableFileAccess: true,
216
+ disableUrlAccess: true,
217
+ } as never);
218
+ try {
219
+ const info = await transport.sendMail({
220
+ from: m.from, to: m.to, cc: m.cc, bcc: m.bcc, replyTo: m.replyTo ?? undefined, subject: m.subject,
221
+ text: m.text ?? undefined, html: m.html ?? undefined,
222
+ attachments: m.attachments.map((a) => ({ filename: a.filename, content: a.content, contentType: a.mime })),
223
+ disableFileAccess: true, disableUrlAccess: true,
224
+ });
225
+ return info.messageId as string;
226
+ } catch (e) {
227
+ const err = e as { responseCode?: number; code?: string; response?: string; message: string };
228
+ // 4xx: try again later; 5xx and authentication: rejected
229
+ const retry = err.responseCode ? err.responseCode < 500 : !['EAUTH', 'EENVELOPE', 'EMESSAGE'].includes(err.code ?? '');
230
+ throw new MailError(`The SMTP server refused the message: ${(err.response ?? err.message).slice(0, 500)}`, retry);
231
+ } finally {
232
+ transport.close();
233
+ }
234
+ }
235
+
236
+ async function graph(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
237
+ const token = await clientCredentialsToken(entraTokenUrl(s), s.client_id ?? '', secret ?? '', s.scope || 'https://graph.microsoft.com/.default');
238
+ const who = (list: string[]) => list.map((address) => ({ emailAddress: { address } }));
239
+ const message = {
240
+ subject: m.subject,
241
+ body: m.html !== null ? { contentType: 'HTML', content: m.html } : { contentType: 'Text', content: m.text ?? '' },
242
+ toRecipients: who(m.to),
243
+ ccRecipients: who(m.cc),
244
+ bccRecipients: who(m.bcc),
245
+ ...(m.replyTo ? { replyTo: who([m.replyTo]) } : {}),
246
+ attachments: m.attachments.map((a) => ({ '@odata.type': '#microsoft.graph.fileAttachment', name: a.filename, contentType: a.mime, contentBytes: b64(a.content) })),
247
+ };
248
+ await http(`${base(s, 'https://graph.microsoft.com')}/v1.0/users/${encodeURIComponent(m.from)}/sendMail`, {
249
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
250
+ body: JSON.stringify({ message, saveToSentItems: s.save_to_sent_items === true }),
251
+ });
252
+ // Graph answers 202 without an id
253
+ return null;
254
+ }
255
+
256
+ /** The message as MIME (SES raw messages). Bcc stays out of the headers; the envelope carries it. */
257
+ export async function mime(m: OutgoingMail): Promise<Buffer> {
258
+ const composer = new MailComposer({
259
+ from: m.from, to: m.to, cc: m.cc, replyTo: m.replyTo ?? undefined, subject: m.subject,
260
+ text: m.text ?? undefined, html: m.html ?? undefined,
261
+ attachments: m.attachments.map((a) => ({ filename: a.filename, content: a.content, contentType: a.mime })),
262
+ disableFileAccess: true, disableUrlAccess: true,
263
+ } as never);
264
+ return new Promise((resolve, reject) => composer.compile().build((err: Error | null, out: Buffer) => (err ? reject(err) : resolve(out))));
265
+ }
266
+
267
+ async function ses(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
268
+ const region = s.region ?? '';
269
+ const url = new URL(`${base(s, `https://email.${region}.amazonaws.com`)}/v2/email/outbound-emails`);
270
+ const body = JSON.stringify({
271
+ FromEmailAddress: m.from,
272
+ Destination: { ToAddresses: m.to, CcAddresses: m.cc, BccAddresses: m.bcc },
273
+ ...(m.replyTo ? { ReplyToAddresses: [m.replyTo] } : {}),
274
+ Content: { Raw: { Data: b64(await mime(m)) } },
275
+ });
276
+ const amzDate = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
277
+ const headers: Record<string, string> = { host: url.host, 'x-amz-date': amzDate, 'content-type': 'application/json' };
278
+ headers.authorization = signV4({
279
+ method: 'POST', url, headers, payloadHash: createHash('sha256').update(body).digest('hex'),
280
+ accessKey: s.access_key_id ?? '', secretKey: secret ?? '', region, service: 'ses', amzDate,
281
+ });
282
+ delete headers.host;
283
+ const r = await http(url.toString(), { headers, body });
284
+ return (json(r.text).MessageId as string | undefined) ?? null;
285
+ }
286
+
287
+ async function resend(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
288
+ const r = await http(`${base(s, 'https://api.resend.com')}/emails`, {
289
+ headers: { authorization: `Bearer ${secret ?? ''}`, 'content-type': 'application/json' },
290
+ body: JSON.stringify({
291
+ from: m.from, to: m.to, cc: m.cc.length ? m.cc : undefined, bcc: m.bcc.length ? m.bcc : undefined,
292
+ reply_to: m.replyTo ?? undefined, subject: m.subject, html: m.html ?? undefined, text: m.text ?? undefined,
293
+ attachments: m.attachments.length ? m.attachments.map((a) => ({ filename: a.filename, content: b64(a.content), content_type: a.mime })) : undefined,
294
+ }),
295
+ });
296
+ return (json(r.text).id as string | undefined) ?? null;
297
+ }
298
+
299
+ async function postmark(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
300
+ const r = await http(`${base(s, 'https://api.postmarkapp.com')}/email`, {
301
+ headers: { 'x-postmark-server-token': secret ?? '', 'content-type': 'application/json', accept: 'application/json' },
302
+ body: JSON.stringify({
303
+ From: m.from, To: m.to.join(','), Cc: m.cc.join(',') || undefined, Bcc: m.bcc.join(',') || undefined, ReplyTo: m.replyTo ?? undefined,
304
+ Subject: m.subject, HtmlBody: m.html ?? undefined, TextBody: m.text ?? undefined, MessageStream: s.message_stream || 'outbound',
305
+ Attachments: m.attachments.map((a) => ({ Name: a.filename, Content: b64(a.content), ContentType: a.mime })),
306
+ }),
307
+ });
308
+ return (json(r.text).MessageID as string | undefined) ?? null;
309
+ }
310
+
311
+ async function sendgrid(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
312
+ const who = (list: string[]) => (list.length ? list.map((email) => ({ email })) : undefined);
313
+ const content = [
314
+ ...(m.text !== null ? [{ type: 'text/plain', value: m.text }] : []),
315
+ ...(m.html !== null ? [{ type: 'text/html', value: m.html }] : []),
316
+ ];
317
+ const r = await http(`${base(s, 'https://api.sendgrid.com')}/v3/mail/send`, {
318
+ headers: { authorization: `Bearer ${secret ?? ''}`, 'content-type': 'application/json' },
319
+ body: JSON.stringify({
320
+ personalizations: [{ to: who(m.to), cc: who(m.cc), bcc: who(m.bcc) }],
321
+ from: { email: m.from }, reply_to: m.replyTo ? { email: m.replyTo } : undefined, subject: m.subject, content,
322
+ attachments: m.attachments.length ? m.attachments.map((a) => ({ content: b64(a.content), filename: a.filename, type: a.mime, disposition: 'attachment' })) : undefined,
323
+ }),
324
+ });
325
+ return r.res.headers.get('x-message-id');
326
+ }
327
+
328
+ async function mailgun(m: OutgoingMail, s: ServiceSettings, secret: string | null) {
329
+ const form = new FormData();
330
+ form.append('from', m.from);
331
+ for (const a of m.to) form.append('to', a);
332
+ for (const a of m.cc) form.append('cc', a);
333
+ for (const a of m.bcc) form.append('bcc', a);
334
+ form.append('subject', m.subject);
335
+ if (m.text !== null) form.append('text', m.text);
336
+ if (m.html !== null) form.append('html', m.html);
337
+ if (m.replyTo) form.append('h:Reply-To', m.replyTo);
338
+ for (const a of m.attachments) form.append('attachment', new Blob([new Uint8Array(a.content)], { type: a.mime }), a.filename);
339
+ const own = s.mailgun_region === 'eu' ? 'https://api.eu.mailgun.net' : 'https://api.mailgun.net';
340
+ const r = await http(`${base(s, own)}/v3/${encodeURIComponent(s.domain ?? '')}/messages`, {
341
+ headers: { authorization: `Basic ${Buffer.from(`api:${secret ?? ''}`).toString('base64')}` },
342
+ body: form,
343
+ });
344
+ return (json(r.text).id as string | undefined) ?? null;
345
+ }
346
+
347
+ /** Hand the message to the provider; returns the provider's id of it (when it gives one). */
348
+ export async function deliver(provider: Provider, settings: ServiceSettings, secret: string | null, m: OutgoingMail): Promise<string | null> {
349
+ switch (provider) {
350
+ case 'smtp': return smtp(m, settings, secret);
351
+ case 'graph': return graph(m, settings, secret);
352
+ case 'ses': return ses(m, settings, secret);
353
+ case 'resend': return resend(m, settings, secret);
354
+ case 'postmark': return postmark(m, settings, secret);
355
+ case 'sendgrid': return sendgrid(m, settings, secret);
356
+ case 'mailgun': return mailgun(m, settings, secret);
357
+ case 'log':
358
+ console.log(`mail (log only): from ${m.from} to ${[...m.to, ...m.cc, ...m.bcc].join(', ')}: ${m.subject} (${m.attachments.length} attachment(s))`);
359
+ return null;
360
+ }
361
+ }
362
+
363
+ // ---------------------------------------------------------------- connection checks
364
+
365
+ /** A signed GET to the SES API (the account, to check a key without sending). */
366
+ async function sesGet(s: ServiceSettings, secret: string | null, path: string) {
367
+ const region = s.region ?? '';
368
+ const url = new URL(`${base(s, `https://email.${region}.amazonaws.com`)}${path}`);
369
+ const amzDate = new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d{3}/, '');
370
+ const headers: Record<string, string> = { host: url.host, 'x-amz-date': amzDate };
371
+ headers.authorization = signV4({
372
+ method: 'GET', url, headers, payloadHash: createHash('sha256').update('').digest('hex'),
373
+ accessKey: s.access_key_id ?? '', secretKey: secret ?? '', region, service: 'ses', amzDate,
374
+ });
375
+ delete headers.host;
376
+ return http(url.toString(), { method: 'GET', headers });
377
+ }
378
+
379
+ /**
380
+ * Check a service's settings without sending: connect and sign in (SMTP), get a
381
+ * token (Graph), or make a read-only call that needs the key (the HTTP APIs).
382
+ * Returns what was checked; throws a MailError with the reason.
383
+ */
384
+ export async function verifyConnection(provider: Provider, s: ServiceSettings, secret: string | null): Promise<string> {
385
+ switch (provider) {
386
+ case 'smtp': {
387
+ const security = s.security ?? 'starttls';
388
+ const auth = s.auth ?? 'password';
389
+ const transport = nodemailer.createTransport({
390
+ host: s.host, port: s.port ?? (security === 'tls' ? 465 : 587), secure: security === 'tls', requireTLS: security === 'starttls', ignoreTLS: security === 'none',
391
+ auth: (auth === 'password' ? { user: s.username, pass: secret ?? '' }
392
+ : auth === 'oauth2' ? { type: 'OAuth2', user: s.username, accessToken: await clientCredentialsToken(entraTokenUrl(s), s.client_id ?? '', secret ?? '', s.scope || 'https://outlook.office365.com/.default') }
393
+ : undefined) as never,
394
+ tls: { rejectUnauthorized: s.tls_verify !== false }, connectionTimeout: 15_000, greetingTimeout: 15_000, socketTimeout: TIMEOUT_MS,
395
+ } as never);
396
+ try {
397
+ await transport.verify();
398
+ } catch (e) {
399
+ const err = e as { response?: string; message: string; code?: string };
400
+ throw new MailError(`The SMTP server ${s.host}: ${(err.response ?? err.message).slice(0, 500)}`, false);
401
+ } finally {
402
+ transport.close();
403
+ }
404
+ return `Connected to ${s.host}:${s.port ?? (security === 'tls' ? 465 : 587)}${security === 'none' ? '' : ` with ${security === 'tls' ? 'TLS' : 'STARTTLS'}`}${
405
+ auth === 'none' ? '' : ` and signed in as ${s.username}${auth === 'oauth2' ? ' with OAuth2' : ''}`}.`;
406
+ }
407
+ case 'graph':
408
+ await clientCredentialsToken(entraTokenUrl(s), s.client_id ?? '', secret ?? '', s.scope || 'https://graph.microsoft.com/.default');
409
+ return 'Microsoft Entra issued an access token for Microsoft Graph. Whether the application may send as a mailbox (Mail.Send) shows when you send a test mail.';
410
+ case 'ses': {
411
+ const j = json((await sesGet(s, secret, '/v2/email/account')).text);
412
+ const quota = j.SendQuota ? ` ${j.SendQuota.SentLast24Hours ?? 0} of ${j.SendQuota.Max24HourSend ?? '?'} mails sent in the last 24 hours.` : '';
413
+ return `Signed in to Amazon SES in ${s.region}: sending is ${j.SendingEnabled === false ? 'DISABLED' : 'enabled'}, ${
414
+ j.ProductionAccessEnabled ? 'production access' : 'sandbox (only to verified addresses)'}.${quota}`;
415
+ }
416
+ case 'resend': {
417
+ try {
418
+ const j = json((await http(`${base(s, 'https://api.resend.com')}/domains`, { method: 'GET', headers: { authorization: `Bearer ${secret ?? ''}` } })).text);
419
+ return `The API key is valid; ${Array.isArray(j.data) ? `${j.data.length} domain(s): ${j.data.map((d: { name: string; status: string }) => `${d.name} (${d.status})`).join(', ')}` : 'its domains could not be listed'}.`;
420
+ } catch (e) {
421
+ // a key that may only send can't list domains: it is valid all the same
422
+ if (/restricted/i.test((e as Error).message)) return 'The API key is valid (it may only send mail).';
423
+ throw e;
424
+ }
425
+ }
426
+ case 'postmark': {
427
+ const j = json((await http(`${base(s, 'https://api.postmarkapp.com')}/server`, { method: 'GET', headers: { 'x-postmark-server-token': secret ?? '', accept: 'application/json' } })).text);
428
+ return `The server token is valid: Postmark server "${j.Name ?? '?'}".`;
429
+ }
430
+ case 'sendgrid': {
431
+ const j = json((await http(`${base(s, 'https://api.sendgrid.com')}/v3/scopes`, { method: 'GET', headers: { authorization: `Bearer ${secret ?? ''}` } })).text);
432
+ if (Array.isArray(j.scopes) && !j.scopes.includes('mail.send')) throw new MailError('The API key is valid but may not send mail (it lacks the mail.send scope).', false);
433
+ return 'The API key is valid and may send mail.';
434
+ }
435
+ case 'mailgun': {
436
+ const own = s.mailgun_region === 'eu' ? 'https://api.eu.mailgun.net' : 'https://api.mailgun.net';
437
+ const j = json((await http(`${base(s, own)}/v3/domains/${encodeURIComponent(s.domain ?? '')}`, {
438
+ method: 'GET', headers: { authorization: `Basic ${Buffer.from(`api:${secret ?? ''}`).toString('base64')}` } })).text);
439
+ return `The API key is valid: domain ${s.domain} is ${j.domain?.state ?? 'known'}.`;
440
+ }
441
+ case 'log':
442
+ return 'Log only: there is nothing to connect to; mail goes to the server\'s log.';
443
+ }
444
+ }
package/src/metadata.ts CHANGED
@@ -40,7 +40,7 @@ export interface StaticInclude {
40
40
  export interface AppProcess {
41
41
  id: number;
42
42
  name: string;
43
- point: 'after_login' | 'before_page';
43
+ point: 'after_login' | 'before_page' | 'ajax';
44
44
  code: string;
45
45
  authz: string | null;
46
46
  }
@@ -72,6 +72,10 @@ export interface App {
72
72
  local_login: boolean;
73
73
  /** days a "Remember me" sign-in lasts; null = off */
74
74
  remember_me_days: number | null;
75
+ /** (087) the page that replaces the built-in sign-in page */
76
+ login_page: number | null;
77
+ /** (087) offer "Forgot password?" (with an enabled mail service) */
78
+ password_reset: boolean;
75
79
  /** (067) session sharing group (src/sharedlogin.ts) */
76
80
  session_group: string | null;
77
81
  /** LDAP directories the password form checks after local accounts */
@@ -88,6 +92,15 @@ export interface App {
88
92
  debug: boolean;
89
93
  /** debug messages: 0 off, else the APEX level 1–9 of what requests record (src/debug.ts) */
90
94
  debug_level: number;
95
+ /** (083) who may use the application, and the message when it is unavailable */
96
+ availability: import('./runtime/availability.ts').Availability;
97
+ availability_message: string | null;
98
+ availability_users: string[];
99
+ /** (084) users can send feedback from the navigation bar */
100
+ feedback: boolean;
101
+ /** (085) schema.function(jsonb) returns jsonb that rewrites error messages; seconds of the session timeout warning */
102
+ error_function: string | null;
103
+ session_warning_seconds: number;
91
104
  pages: PageSummary[];
92
105
  nav: NavEntry[];
93
106
  authz_schemes: AuthzScheme[];
@@ -127,13 +140,13 @@ export interface Region {
127
140
  title: string | null;
128
141
  /** (0.31, 073) optional, unique on the page */
129
142
  static_id?: string | null;
130
- type: 'report' | 'form' | 'chart' | 'cards' | 'static' | 'grid' | 'calendar' | 'dynamic' | 'facets' | 'tasks' | 'workflows' | 'map' | 'tree' | 'template_component' | 'smart_filters' | 'display_selector' | 'list' | 'data_reporter' | 'ai_assistant' | 'plugin';
143
+ type: 'login' | 'report' | 'form' | 'chart' | 'cards' | 'static' | 'grid' | 'calendar' | 'dynamic' | 'facets' | 'tasks' | 'workflows' | 'map' | 'tree' | 'template_component' | 'smart_filters' | 'display_selector' | 'list' | 'data_reporter' | 'ai_assistant' | 'plugin' | 'url' | 'search';
131
144
  source: string | null;
132
145
  table_name: string | null;
133
146
  pk_column: string | null;
134
147
  pk_item: string | null;
135
148
  columns: number;
136
- template: 'standard' | 'plain' | 'collapsible';
149
+ template: 'standard' | 'plain' | 'collapsible' | 'hero' | 'title_bar' | 'buttons_container' | 'inline_dialog' | 'inline_drawer' | 'wizard';
137
150
  condition: string | null;
138
151
  authz: string | null;
139
152
  config: Record<string, any>;
@@ -147,7 +160,9 @@ export type ItemType =
147
160
  | 'text' | 'textarea' | 'number' | 'date' | 'datetime' | 'select' | 'radio'
148
161
  | 'checkbox' | 'switch' | 'hidden' | 'display' | 'password'
149
162
  | 'checkbox_group' | 'multiselect' | 'popup_lov' | 'email' | 'tel' | 'url' | 'color' | 'file' | 'location'
150
- | 'richtext' | 'markdown' | 'rating' | 'combobox' | 'daterange' | 'qrcode' | 'plugin';
163
+ | 'richtext' | 'markdown' | 'rating' | 'combobox' | 'daterange' | 'qrcode' | 'plugin'
164
+ // (086) display image, geocoded address
165
+ | 'image' | 'address';
151
166
 
152
167
  export interface Item {
153
168
  id: number;
@@ -240,7 +255,9 @@ export interface DynamicAction {
240
255
  id: number;
241
256
  seq: number;
242
257
  name: string;
243
- event: 'change' | 'click' | 'load' | 'dialog_closed';
258
+ event: 'change' | 'click' | 'load' | 'dialog_closed'
259
+ /** (085) */
260
+ | 'after_refresh' | 'selection_change' | 'focus' | 'blur' | 'key_release' | 'before_submit' | 'custom';
244
261
  trigger_element: string | null;
245
262
  condition_type: 'equals' | 'not_equals' | 'in_list' | 'is_null' | 'is_not_null' | null;
246
263
  condition_value: string | null;
@@ -251,7 +268,9 @@ export interface DynamicAction {
251
268
  /** (074) turn on push notifications on this device (app.js) */
252
269
  | 'push_subscribe'
253
270
  /** (069) code: the name of a dynamic action plug-in; config.attributes its attribute values */
254
- | 'plugin';
271
+ | 'plugin'
272
+ /** (085) */
273
+ | 'confirm' | 'close_dialog' | 'cancel_dialog' | 'clear' | 'open_region' | 'close_region' | 'download' | 'print' | 'current_position' | 'share';
255
274
  affected_items: string | null;
256
275
  affected_region_id: number | null;
257
276
  code: string | null;
@@ -277,11 +296,11 @@ export interface Validation {
277
296
  export interface Process {
278
297
  id: number;
279
298
  name: string;
280
- type: 'form_dml' | 'grid_dml' | 'sql' | 'data_load' | 'invoke_api' | 'download' | 'chain' | 'workflow' | 'ai_generate' | 'plugin' | 'send_push';
299
+ type: 'form_dml' | 'grid_dml' | 'sql' | 'data_load' | 'invoke_api' | 'download' | 'chain' | 'workflow' | 'ai_generate' | 'plugin' | 'send_push' | 'send_email';
281
300
  region_id: number | null;
282
301
  code: string | null;
283
302
  config: Record<string, unknown> | null;
284
- point: 'submit' | 'load';
303
+ point: 'submit' | 'load' | 'ajax';
285
304
  when_button: string | null;
286
305
  authz: string | null;
287
306
  success_message: string | null;
@@ -306,6 +325,10 @@ export interface Page extends PageSummary {
306
325
  branches: Branch[];
307
326
  /** (068) static files (.js, .css) this page loads after the application's */
308
327
  static_includes: StaticInclude[];
328
+ /** (077) ask before leaving the page with unsaved changes */
329
+ warn_unsaved: boolean;
330
+ /** (087) 'minimal': no header and navigation */
331
+ page_template: 'standard' | 'minimal';
309
332
  }
310
333
 
311
334
  /** The static files a list of names refers to, in that order, with their version. */
@@ -321,7 +344,8 @@ const agg = (table: string, fk: string, parent: string, appId: string) =>
321
344
  // No caching on purpose: edits made in the builder show up on the next request.
322
345
  export async function loadApp(alias: string) {
323
346
  return runtime.one<App>(
324
- `select a.id, a.alias, a.name, a.home_page, a.authentication, a.access_control, a.sso_providers, a.local_login, a.remember_me_days, a.session_group, a.ldap_directories, a.header_name, a.header_auto_create, a.logout_url, a.db_auth_roles, a.db_auth_member_of, a.custom_auth_function, a.custom_auth_code, a.custom_auth_post_code, a.nav_list, a.navbar_list, a.pwa, a.pwa_short_name, a.pwa_icon is not null as pwa_has_icon, a.pwa_offline_pages, a.pwa_offline_submit, a.pwa_push, a.db_role, a.debug, a.debug_level, a.theme,
347
+ `select a.id, a.alias, a.name, a.home_page, a.authentication, a.access_control, a.sso_providers, a.local_login, a.remember_me_days, a.login_page, a.password_reset, a.session_group, a.ldap_directories, a.header_name, a.header_auto_create, a.logout_url, a.db_auth_roles, a.db_auth_member_of, a.custom_auth_function, a.custom_auth_code, a.custom_auth_post_code, a.nav_list, a.navbar_list, a.pwa, a.pwa_short_name, a.pwa_icon is not null as pwa_has_icon, a.pwa_offline_pages, a.pwa_offline_submit, a.pwa_push, a.db_role, a.debug, a.debug_level, a.theme,
348
+ a.availability, a.availability_message, a.availability_users, a.feedback, a.error_function, a.session_warning_seconds,
325
349
  a.language, a.languages, a.language_from, a.date_format, a.timestamp_format, a.time_zone, a.time_zone_auto, a.currency,
326
350
  coalesce((select jsonb_agg(jsonb_build_object('name', l.name, 'query', l.query, 'rest_source', l.rest_source)) from meta.lov l where l.app_id = a.id), '[]') as lovs,
327
351
  coalesce((select jsonb_agg(jsonb_build_object('page_no', p.page_no, 'name', p.name, 'title', p.title,
@@ -346,7 +370,7 @@ export async function loadApp(alias: string) {
346
370
  export async function loadPage(appId: number, pageNo: number) {
347
371
  return runtime.one<Page>(
348
372
  `select p.id, p.app_id, p.page_no, p.name, p.title, p.requires_auth, p.parent_page, p.mode,
349
- p.protection, p.authz,
373
+ p.protection, p.authz, p.warn_unsaved, p.page_template,
350
374
  ${agg('meta.region', 'page_id', 'p', 'p.app_id')} as regions,
351
375
  ${agg('meta.item', 'page_id', 'p', 'p.app_id')} as items,
352
376
  ${agg('meta.button', 'page_id', 'p', 'p.app_id')} as buttons,