@hintergrund/worker 0.3.18 → 0.3.20
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.
- package/dist/api/appointments/admin.d.ts +171 -0
- package/dist/api/appointments/admin.d.ts.map +1 -0
- package/dist/api/appointments/admin.js +275 -0
- package/dist/api/appointments/core.d.ts +114 -0
- package/dist/api/appointments/core.d.ts.map +1 -0
- package/dist/api/appointments/core.js +208 -0
- package/dist/api/appointments/cron.d.ts +9 -0
- package/dist/api/appointments/cron.d.ts.map +1 -0
- package/dist/api/appointments/cron.js +71 -0
- package/dist/api/appointments/emails.d.ts +5 -0
- package/dist/api/appointments/emails.d.ts.map +1 -0
- package/dist/api/appointments/emails.js +53 -0
- package/dist/api/appointments/public.d.ts +104 -0
- package/dist/api/appointments/public.d.ts.map +1 -0
- package/dist/api/appointments/public.js +129 -0
- package/dist/api/appointments/routes.d.ts +7 -0
- package/dist/api/appointments/routes.d.ts.map +1 -0
- package/dist/api/appointments/routes.js +28 -0
- package/dist/api/cms/handlers/agent-provider.handler.d.ts +0 -2
- package/dist/api/cms/handlers/agent-provider.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/agent-provider.handler.js +5 -10
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +3 -17
- package/dist/api/cms/handlers/integrations.handler.d.ts +2 -2
- package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/integrations.handler.js +5 -11
- package/dist/api/cms/handlers/runtime.handler.d.ts +6 -0
- package/dist/api/cms/handlers/runtime.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/runtime.handler.js +42 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -0
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +31 -14
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +6 -6
- package/dist/api/emails/handlers/campaigns.handler.d.ts +10 -6
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +127 -30
- package/dist/api/emails/handlers/public.handler.d.ts +0 -2
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +32 -77
- package/dist/api/emails/handlers/send.handler.js +2 -2
- package/dist/api/emails/handlers/subscribers.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/subscribers.handler.js +9 -0
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +3 -1
- package/dist/api/emails/routes/mail.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/mail.routes.js +19 -17
- package/dist/api/emails/routes/public.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/public.routes.js +1 -2
- package/dist/api/enquiries/routes.d.ts +7 -0
- package/dist/api/enquiries/routes.d.ts.map +1 -0
- package/dist/api/enquiries/routes.js +73 -0
- package/dist/api/members/handlers.d.ts +36 -0
- package/dist/api/members/handlers.d.ts.map +1 -0
- package/dist/api/members/handlers.js +322 -0
- package/dist/api/members/routes.d.ts +5 -0
- package/dist/api/members/routes.d.ts.map +1 -0
- package/dist/api/members/routes.js +20 -0
- package/dist/api/reservations/core.d.ts +25 -0
- package/dist/api/reservations/core.d.ts.map +1 -0
- package/dist/api/reservations/core.js +59 -0
- package/dist/api/reservations/mail.d.ts +7 -0
- package/dist/api/reservations/mail.d.ts.map +1 -0
- package/dist/api/reservations/mail.js +63 -0
- package/dist/api/reservations/routes.d.ts +7 -0
- package/dist/api/reservations/routes.d.ts.map +1 -0
- package/dist/api/reservations/routes.js +186 -0
- package/dist/api/shop/handlers/products.handler.d.ts +1 -1
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/products.handler.js +3 -3
- package/dist/api/shop/handlers/public.handler.d.ts +3 -3
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +25 -28
- package/dist/api/shop/routes.d.ts +2 -4
- package/dist/api/shop/routes.d.ts.map +1 -1
- package/dist/api/shop/routes.js +8 -11
- package/dist/api/stays/actions.d.ts +13 -0
- package/dist/api/stays/actions.d.ts.map +1 -0
- package/dist/api/stays/actions.js +28 -0
- package/dist/api/stays/admin.d.ts +209 -0
- package/dist/api/stays/admin.d.ts.map +1 -0
- package/dist/api/stays/admin.js +228 -0
- package/dist/api/stays/bookings.d.ts +113 -0
- package/dist/api/stays/bookings.d.ts.map +1 -0
- package/dist/api/stays/bookings.js +254 -0
- package/dist/api/stays/core.d.ts +214 -0
- package/dist/api/stays/core.d.ts.map +1 -0
- package/dist/api/stays/core.js +361 -0
- package/dist/api/stays/cron.d.ts +7 -0
- package/dist/api/stays/cron.d.ts.map +1 -0
- package/dist/api/stays/cron.js +56 -0
- package/dist/api/stays/mail.d.ts +8 -0
- package/dist/api/stays/mail.d.ts.map +1 -0
- package/dist/api/stays/mail.js +50 -0
- package/dist/api/stays/offers.d.ts +27 -0
- package/dist/api/stays/offers.d.ts.map +1 -0
- package/dist/api/stays/offers.js +56 -0
- package/dist/api/stays/payments.d.ts +47 -0
- package/dist/api/stays/payments.d.ts.map +1 -0
- package/dist/api/stays/payments.js +148 -0
- package/dist/api/stays/public.d.ts +207 -0
- package/dist/api/stays/public.d.ts.map +1 -0
- package/dist/api/stays/public.js +137 -0
- package/dist/api/stays/routes.d.ts +7 -0
- package/dist/api/stays/routes.d.ts.map +1 -0
- package/dist/api/stays/routes.js +39 -0
- package/dist/api/stripe/webhook.d.ts +5 -0
- package/dist/api/stripe/webhook.d.ts.map +1 -0
- package/dist/api/stripe/webhook.js +45 -0
- package/dist/api/tickets/core.d.ts +40 -0
- package/dist/api/tickets/core.d.ts.map +1 -0
- package/dist/api/tickets/core.js +115 -0
- package/dist/api/tickets/routes.d.ts +5 -0
- package/dist/api/tickets/routes.d.ts.map +1 -0
- package/dist/api/tickets/routes.js +70 -0
- package/dist/index.d.ts +14 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +40 -27
- package/dist/lib/appointments-schema.d.ts +6 -0
- package/dist/lib/appointments-schema.d.ts.map +1 -0
- package/dist/lib/appointments-schema.js +96 -0
- package/dist/lib/config.js +4 -4
- package/dist/lib/email-template.d.ts +2 -2
- package/dist/lib/email-template.d.ts.map +1 -1
- package/dist/lib/email-template.js +3 -3
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +12 -3
- package/dist/lib/features.d.ts +13 -0
- package/dist/lib/features.d.ts.map +1 -0
- package/dist/lib/features.js +19 -0
- package/dist/lib/mail-schema.d.ts +1 -1
- package/dist/lib/mail-schema.d.ts.map +1 -1
- package/dist/lib/mail-schema.js +0 -1
- package/dist/lib/mail.d.ts +23 -3
- package/dist/lib/mail.d.ts.map +1 -1
- package/dist/lib/mail.js +69 -23
- package/dist/lib/members.d.ts +41 -0
- package/dist/lib/members.d.ts.map +1 -0
- package/dist/lib/members.js +92 -0
- package/dist/lib/project-db.d.ts +1 -1
- package/dist/lib/project-db.d.ts.map +1 -1
- package/dist/lib/project-db.js +67 -8
- package/dist/lib/reservations-schema.d.ts +3 -0
- package/dist/lib/reservations-schema.d.ts.map +1 -0
- package/dist/lib/reservations-schema.js +35 -0
- package/dist/lib/stays-schema.d.ts +3 -0
- package/dist/lib/stays-schema.d.ts.map +1 -0
- package/dist/lib/stays-schema.js +247 -0
- package/dist/lib/stripe.d.ts +6 -0
- package/dist/lib/stripe.d.ts.map +1 -0
- package/dist/lib/stripe.js +9 -0
- package/dist/lib/template.d.ts +2 -1
- package/dist/lib/template.d.ts.map +1 -1
- package/dist/lib/template.js +4 -82
- package/dist/lib/user-recovery.d.ts.map +1 -1
- package/dist/lib/user-recovery.js +4 -2
- package/dist/lib/website-i18n.d.ts +17 -0
- package/dist/lib/website-i18n.d.ts.map +1 -1
- package/dist/lib/website-i18n.js +36 -3
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +8 -1
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +1 -0
- package/package.json +2 -2
- package/dist/api/cms/handlers/setup.handler.d.ts +0 -8
- package/dist/api/cms/handlers/setup.handler.d.ts.map +0 -1
- package/dist/api/cms/handlers/setup.handler.js +0 -278
- package/dist/lib/integration-health.d.ts +0 -15
- package/dist/lib/integration-health.d.ts.map +0 -1
- package/dist/lib/integration-health.js +0 -60
|
@@ -1,36 +1,44 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Campaigns
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* Campaigns (both drafts and sent records) live in D1 (`campaigns`).
|
|
3
|
+
* Each campaign stores its message fragment (`body_html`) and outer shell (`layout_html`),
|
|
4
|
+
* seeded from the latest campaign (or `emails/layout.html` when none exists yet).
|
|
5
5
|
*/
|
|
6
|
-
import {
|
|
7
|
-
import { getGitHubConfig } from '../../../lib/config';
|
|
8
|
-
import { createGitHubClient } from '../../../lib/github';
|
|
6
|
+
import { ensureSchema } from '../../../lib/project-db';
|
|
9
7
|
import { assertEmailConfigured, sendEmail } from '../../../lib/email';
|
|
10
8
|
import { unsubscribeUrl } from '../../../lib/email-template';
|
|
11
|
-
import { renderEmail } from '@hintergrund/runtime-contracts';
|
|
9
|
+
import { DEFAULT_EMAIL_LAYOUT, PAYWALL_MARKER_PATTERN, memberAccessSql, memberEmail, renderEmail } from '@hintergrund/runtime-contracts';
|
|
12
10
|
import { readEmailLayout } from './settings.handler';
|
|
13
|
-
import {
|
|
11
|
+
import { readMembersSettings } from '../../../lib/members';
|
|
14
12
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
15
13
|
function rowToCampaign(row) {
|
|
14
|
+
const sentAt = Number(row.sent_at ?? 0);
|
|
16
15
|
return {
|
|
17
16
|
id: row.id,
|
|
18
17
|
name: row.name,
|
|
19
18
|
subject: row.subject,
|
|
20
19
|
bodyHtml: row.body_html,
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
layoutHtml: row.layout_html || '',
|
|
21
|
+
...(row.paid ? { paid: true } : {}),
|
|
22
|
+
recipientCount: Number(row.recipient_count ?? 0),
|
|
23
|
+
...(sentAt > 0 ? { sentAt } : {}),
|
|
23
24
|
};
|
|
24
25
|
}
|
|
25
26
|
function isDraft(value) {
|
|
26
27
|
const draft = value;
|
|
27
28
|
return !!draft && typeof draft.name === 'string' && typeof draft.subject === 'string' && !!draft.subject.trim() && typeof draft.bodyHtml === 'string' && !!draft.bodyHtml.trim();
|
|
28
29
|
}
|
|
29
|
-
|
|
30
|
+
async function resolveDefaultLayout(db, env) {
|
|
31
|
+
const latest = await db
|
|
32
|
+
.prepare("SELECT layout_html FROM campaigns WHERE layout_html != '' ORDER BY CASE WHEN sent_at = 0 THEN 0 ELSE 1 END, sent_at DESC, rowid DESC LIMIT 1")
|
|
33
|
+
.first();
|
|
34
|
+
return latest?.layout_html || (await readEmailLayout(env)) || DEFAULT_EMAIL_LAYOUT;
|
|
35
|
+
}
|
|
36
|
+
/** GET /api/email/admin/campaigns — drafts first, then sent campaigns newest first. */
|
|
30
37
|
export async function getCampaigns(c) {
|
|
31
38
|
try {
|
|
32
|
-
const
|
|
33
|
-
|
|
39
|
+
const db = await ensureSchema(c.env);
|
|
40
|
+
const { results } = await db
|
|
41
|
+
.prepare('SELECT * FROM campaigns ORDER BY CASE WHEN sent_at = 0 THEN 0 ELSE 1 END, sent_at DESC, rowid DESC')
|
|
34
42
|
.all();
|
|
35
43
|
return c.json({ campaigns: (results ?? []).map(rowToCampaign) });
|
|
36
44
|
}
|
|
@@ -39,40 +47,118 @@ export async function getCampaigns(c) {
|
|
|
39
47
|
return c.json({ success: false, message: 'Failed to fetch campaigns' }, 500);
|
|
40
48
|
}
|
|
41
49
|
}
|
|
42
|
-
/**
|
|
50
|
+
/** PUT /api/email/admin/campaigns/:id — create or update an unsent campaign draft in D1. */
|
|
51
|
+
export async function saveCampaign(c) {
|
|
52
|
+
try {
|
|
53
|
+
const id = c.req.param('id') ?? '';
|
|
54
|
+
if (!/^[a-z0-9_-]+$/i.test(id))
|
|
55
|
+
return c.json({ success: false, message: 'Invalid campaign' }, 400);
|
|
56
|
+
const db = await ensureSchema(c.env);
|
|
57
|
+
const existing = await db.prepare('SELECT * FROM campaigns WHERE id = ?').bind(id).first();
|
|
58
|
+
if (existing && Number(existing.sent_at ?? 0) > 0) {
|
|
59
|
+
return c.json({ success: false, message: 'Sent campaigns cannot be edited' }, 400);
|
|
60
|
+
}
|
|
61
|
+
const body = await c.req.json().catch(() => ({}));
|
|
62
|
+
const name = typeof body.name === 'string' && body.name.trim() ? body.name : (existing?.name || 'Untitled campaign');
|
|
63
|
+
const subject = typeof body.subject === 'string' ? body.subject : (existing?.subject ?? '');
|
|
64
|
+
const bodyHtml = typeof body.bodyHtml === 'string' ? body.bodyHtml : (existing?.body_html ?? '');
|
|
65
|
+
const layoutHtml = typeof body.layoutHtml === 'string' && body.layoutHtml.trim()
|
|
66
|
+
? body.layoutHtml
|
|
67
|
+
: (existing?.layout_html || (await resolveDefaultLayout(db, c.env)));
|
|
68
|
+
const paid = body.paid ?? !!existing?.paid;
|
|
69
|
+
await db.prepare(`
|
|
70
|
+
INSERT INTO campaigns (id, name, subject, body_html, layout_html, paid, recipient_count, sent_at)
|
|
71
|
+
VALUES (?, ?, ?, ?, ?, ?, 0, 0)
|
|
72
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
73
|
+
name = excluded.name,
|
|
74
|
+
subject = excluded.subject,
|
|
75
|
+
body_html = excluded.body_html,
|
|
76
|
+
layout_html = excluded.layout_html,
|
|
77
|
+
paid = excluded.paid
|
|
78
|
+
WHERE campaigns.sent_at = 0
|
|
79
|
+
`).bind(id, name, subject, bodyHtml, layoutHtml, paid ? 1 : 0).run();
|
|
80
|
+
return c.json({
|
|
81
|
+
success: true,
|
|
82
|
+
campaign: { id, name, subject, bodyHtml, layoutHtml, ...(paid ? { paid } : {}), recipientCount: 0 },
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
catch (error) {
|
|
86
|
+
console.error('Save campaign error:', error);
|
|
87
|
+
return c.json({ success: false, message: error instanceof Error ? error.message : 'Failed to save campaign' }, 500);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** DELETE /api/email/admin/campaigns/:id — delete an unsent campaign draft. */
|
|
91
|
+
export async function deleteCampaign(c) {
|
|
92
|
+
try {
|
|
93
|
+
const id = c.req.param('id') ?? '';
|
|
94
|
+
if (!/^[a-z0-9_-]+$/i.test(id))
|
|
95
|
+
return c.json({ success: false, message: 'Invalid campaign' }, 400);
|
|
96
|
+
const db = await ensureSchema(c.env);
|
|
97
|
+
const existing = await db.prepare('SELECT sent_at FROM campaigns WHERE id = ?').bind(id).first();
|
|
98
|
+
if (existing && Number(existing.sent_at ?? 0) > 0) {
|
|
99
|
+
return c.json({ success: false, message: 'Sent campaigns cannot be deleted' }, 400);
|
|
100
|
+
}
|
|
101
|
+
await db.prepare('DELETE FROM campaigns WHERE id = ? AND sent_at = 0').bind(id).run();
|
|
102
|
+
return c.json({ success: true });
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
console.error('Delete campaign error:', error);
|
|
106
|
+
return c.json({ success: false, message: 'Failed to delete campaign' }, 500);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** POST /api/email/admin/campaigns/:id/send — sends the draft to every subscriber, or to one segment and/or audience (all, free, paid) when the body names it. */
|
|
43
110
|
export async function sendCampaign(c) {
|
|
44
111
|
try {
|
|
45
112
|
const id = c.req.param('id') ?? '';
|
|
46
113
|
if (!/^[a-z0-9_-]+$/i.test(id))
|
|
47
114
|
return c.json({ success: false, message: 'Invalid campaign' }, 400);
|
|
48
|
-
const db =
|
|
49
|
-
|
|
115
|
+
const db = await ensureSchema(c.env);
|
|
116
|
+
const existing = await db.prepare('SELECT * FROM campaigns WHERE id = ?').bind(id).first();
|
|
117
|
+
if (existing && Number(existing.sent_at ?? 0) > 0) {
|
|
50
118
|
return c.json({ success: false, message: 'Campaign already sent' }, 400);
|
|
51
119
|
}
|
|
52
|
-
const
|
|
53
|
-
const
|
|
54
|
-
|
|
120
|
+
const body = await c.req.json().catch(() => ({}));
|
|
121
|
+
const draft = {
|
|
122
|
+
name: typeof body.name === 'string' && body.name.trim() ? body.name : (existing?.name ?? ''),
|
|
123
|
+
subject: typeof body.subject === 'string' ? body.subject : (existing?.subject ?? ''),
|
|
124
|
+
bodyHtml: typeof body.bodyHtml === 'string' ? body.bodyHtml : (existing?.body_html ?? ''),
|
|
125
|
+
layoutHtml: typeof body.layoutHtml === 'string' && body.layoutHtml.trim() ? body.layoutHtml : (existing?.layout_html || ''),
|
|
126
|
+
};
|
|
55
127
|
if (!isDraft(draft))
|
|
56
|
-
return c.json({ success: false, message: '
|
|
128
|
+
return c.json({ success: false, message: 'Add a subject and message before sending this campaign.' }, 400);
|
|
129
|
+
const audience = body.audience === 'free' || body.audience === 'paid' ? body.audience : 'all';
|
|
130
|
+
const paidPost = body.paid ?? !!existing?.paid;
|
|
131
|
+
const hasPaywall = PAYWALL_MARKER_PATTERN.test(draft.bodyHtml);
|
|
132
|
+
if (paidPost && !hasPaywall && audience !== 'paid') {
|
|
133
|
+
return c.json({ success: false, message: 'This paid post has no paywall divider, so free readers would get all of it. Add the divider or send to paid subscribers only.' }, 400);
|
|
134
|
+
}
|
|
57
135
|
assertEmailConfigured(c.env);
|
|
58
|
-
const segment =
|
|
136
|
+
const segment = body.segment?.trim();
|
|
137
|
+
const access = memberAccessSql(Date.now());
|
|
59
138
|
const { results: subscribers } = await db
|
|
60
|
-
.prepare(`SELECT email, name FROM subscribers WHERE status = 'subscribed'${segment ? " AND EXISTS (SELECT 1 FROM json_each(data_json, '$.segments') WHERE value = ?)" : ''}`)
|
|
139
|
+
.prepare(`SELECT email, name, unsubscribe_token, ${access} AS has_access FROM subscribers WHERE status = 'subscribed'${audience === 'paid' ? ` AND ${access}` : audience === 'free' ? ` AND NOT ${access}` : ''}${segment ? " AND EXISTS (SELECT 1 FROM json_each(data_json, '$.segments') WHERE value = ?)" : ''}`)
|
|
61
140
|
.bind(...(segment ? [segment] : []))
|
|
62
141
|
.all();
|
|
63
142
|
if (!subscribers || subscribers.length === 0) {
|
|
64
|
-
return c.json({ success: false, message: segment ? 'No subscribed contacts
|
|
143
|
+
return c.json({ success: false, message: segment || audience !== 'all' ? 'No subscribed contacts match this audience' : 'No subscribed contacts found' }, 400);
|
|
65
144
|
}
|
|
66
|
-
const layout = await
|
|
145
|
+
const layout = draft.layoutHtml?.trim() || (await resolveDefaultLayout(db, c.env));
|
|
67
146
|
const origin = new URL(c.req.url).origin;
|
|
147
|
+
// Free readers get the part above the paywall and a prompt to subscribe; paid readers the whole post.
|
|
148
|
+
const [preview, rest] = hasPaywall ? draft.bodyHtml.split(PAYWALL_MARKER_PATTERN, 2) : [draft.bodyHtml, ''];
|
|
149
|
+
const members = hasPaywall && audience !== 'paid' ? await readMembersSettings(c.env).catch(() => undefined) : undefined;
|
|
150
|
+
const cta = hasPaywall && audience !== 'paid'
|
|
151
|
+
? memberEmail(members ?? { emails: {} }, 'paywall_cta').bodyHtml.replaceAll('{{subscribe_url}}', `${origin}${members?.subscribePath ?? '/subscribe'}`)
|
|
152
|
+
: '';
|
|
68
153
|
let sentCount = 0;
|
|
69
154
|
for (const subscriber of subscribers) {
|
|
70
155
|
try {
|
|
156
|
+
const bodyHtml = hasPaywall ? (subscriber.has_access ? `${preview}<hr>${rest}` : preview + cta) : draft.bodyHtml;
|
|
71
157
|
await sendEmail(c.env, {
|
|
72
158
|
to: subscriber.email,
|
|
73
159
|
toName: subscriber.name ?? undefined,
|
|
74
160
|
subject: draft.subject,
|
|
75
|
-
html: renderEmail(layout,
|
|
161
|
+
html: renderEmail(layout, bodyHtml, unsubscribeUrl(origin, subscriber.email, subscriber.unsubscribe_token)),
|
|
76
162
|
});
|
|
77
163
|
sentCount++;
|
|
78
164
|
}
|
|
@@ -82,9 +168,19 @@ export async function sendCampaign(c) {
|
|
|
82
168
|
}
|
|
83
169
|
if (sentCount === 0)
|
|
84
170
|
return c.json({ success: false, message: 'No email could be delivered. The draft is unchanged.' }, 502);
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
171
|
+
const sentAt = Date.now();
|
|
172
|
+
await db.prepare(`
|
|
173
|
+
INSERT INTO campaigns (id, name, subject, body_html, layout_html, paid, recipient_count, sent_at)
|
|
174
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
175
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
176
|
+
name = excluded.name,
|
|
177
|
+
subject = excluded.subject,
|
|
178
|
+
body_html = excluded.body_html,
|
|
179
|
+
layout_html = excluded.layout_html,
|
|
180
|
+
paid = excluded.paid,
|
|
181
|
+
recipient_count = excluded.recipient_count,
|
|
182
|
+
sent_at = excluded.sent_at
|
|
183
|
+
`).bind(id, draft.name, draft.subject, draft.bodyHtml, layout, paidPost ? 1 : 0, sentCount, sentAt).run();
|
|
88
184
|
return c.json({ success: true, recipientCount: sentCount });
|
|
89
185
|
}
|
|
90
186
|
catch (error) {
|
|
@@ -92,7 +188,7 @@ export async function sendCampaign(c) {
|
|
|
92
188
|
return c.json({ success: false, message: error instanceof Error ? error.message : 'Failed to send campaign' }, 500);
|
|
93
189
|
}
|
|
94
190
|
}
|
|
95
|
-
/** POST /api/email/admin/campaigns/test — sends the copy being edited
|
|
191
|
+
/** POST /api/email/admin/campaigns/test — sends the copy being edited. */
|
|
96
192
|
export async function testCampaign(c) {
|
|
97
193
|
try {
|
|
98
194
|
const body = await c.req.json();
|
|
@@ -100,7 +196,8 @@ export async function testCampaign(c) {
|
|
|
100
196
|
return c.json({ success: false, message: 'A valid test address is required' }, 400);
|
|
101
197
|
if (!isDraft({ ...body, name: body.name ?? '' }))
|
|
102
198
|
return c.json({ success: false, message: 'A subject and body are required' }, 400);
|
|
103
|
-
const
|
|
199
|
+
const db = await ensureSchema(c.env);
|
|
200
|
+
const layout = body.layoutHtml?.trim() || (await resolveDefaultLayout(db, c.env));
|
|
104
201
|
await sendEmail(c.env, {
|
|
105
202
|
to: body.email,
|
|
106
203
|
subject: `[TEST] ${body.subject}`,
|
|
@@ -8,6 +8,4 @@ export declare function subscribe(c: Context): Promise<Response>;
|
|
|
8
8
|
export declare function confirm(c: Context): Promise<Response>;
|
|
9
9
|
/** POST /api/email/unsubscribe */
|
|
10
10
|
export declare function unsubscribe(c: Context): Promise<Response>;
|
|
11
|
-
/** GET /api/email/unsubscribe — HTML unsubscribe page */
|
|
12
|
-
export declare function showUnsubscribePage(c: Context): Promise<Response>;
|
|
13
11
|
//# sourceMappingURL=public.handler.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/public.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"public.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/public.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAiC/B,gCAAgC;AAChC,wBAAsB,SAAS,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAoD7D;AAiBD,6BAA6B;AAC7B,wBAAsB,OAAO,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAwC3D;AAED,kCAAkC;AAClC,wBAAsB,WAAW,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAsB/D"}
|
|
@@ -2,11 +2,35 @@
|
|
|
2
2
|
* Public Handler — D1-backed subscribe/unsubscribe/confirm, no Plunk
|
|
3
3
|
*/
|
|
4
4
|
import { getProjectDb, createId } from '../../../lib/project-db';
|
|
5
|
-
import { sendEmail } from '../../../lib/email';
|
|
5
|
+
import { assertEmailConfigured, EmailProviderError, sendEmail } from '../../../lib/email';
|
|
6
6
|
import { unsubscribeUrl } from '../../../lib/email-template';
|
|
7
7
|
import { renderEmail } from '@hintergrund/runtime-contracts';
|
|
8
8
|
import { readEmailLayout, readEmailTemplates } from './settings.handler';
|
|
9
9
|
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
|
10
|
+
function formatSubscribeError(error) {
|
|
11
|
+
if (error instanceof EmailProviderError) {
|
|
12
|
+
let detail = error.reason;
|
|
13
|
+
if (detail) {
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(detail);
|
|
16
|
+
detail = parsed.error?.message || parsed.message || detail;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// Keep raw text reason when not JSON
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
status: 502,
|
|
24
|
+
message: detail
|
|
25
|
+
? `Could not send confirmation email (${detail}).`
|
|
26
|
+
: `Could not send confirmation email (provider returned ${error.status}).`
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
if (error instanceof Error && (error.message.includes('Email delivery is not set up') || error.message.includes('No sender address is set'))) {
|
|
30
|
+
return { status: 503, message: error.message };
|
|
31
|
+
}
|
|
32
|
+
return { status: 500, message: 'Failed to subscribe. Please try again later.' };
|
|
33
|
+
}
|
|
10
34
|
/** POST /api/email/subscribe */
|
|
11
35
|
export async function subscribe(c) {
|
|
12
36
|
try {
|
|
@@ -15,6 +39,7 @@ export async function subscribe(c) {
|
|
|
15
39
|
return c.json({ success: false, message: 'Email is required' }, 400);
|
|
16
40
|
if (!EMAIL_REGEX.test(body.email))
|
|
17
41
|
return c.json({ success: false, message: 'Invalid email format' }, 400);
|
|
42
|
+
assertEmailConfigured(c.env);
|
|
18
43
|
const db = getProjectDb(c.env);
|
|
19
44
|
const email = body.email.toLowerCase().trim();
|
|
20
45
|
const now = Date.now();
|
|
@@ -48,7 +73,8 @@ export async function subscribe(c) {
|
|
|
48
73
|
}
|
|
49
74
|
catch (error) {
|
|
50
75
|
console.error('Subscribe error:', error);
|
|
51
|
-
|
|
76
|
+
const formatted = formatSubscribeError(error);
|
|
77
|
+
return c.json({ success: false, message: formatted.message }, formatted.status);
|
|
52
78
|
}
|
|
53
79
|
}
|
|
54
80
|
async function sendConfirmation(c, email, token) {
|
|
@@ -89,7 +115,7 @@ export async function confirm(c) {
|
|
|
89
115
|
await sendEmail(c.env, {
|
|
90
116
|
to: subscriber.email,
|
|
91
117
|
subject: welcome.subject,
|
|
92
|
-
html: renderEmail(layout, welcome.bodyHtml, unsubscribeUrl(new URL(c.req.url).origin, subscriber.email)),
|
|
118
|
+
html: renderEmail(layout, welcome.bodyHtml, unsubscribeUrl(new URL(c.req.url).origin, subscriber.email, subscriber.unsubscribe_token)),
|
|
93
119
|
});
|
|
94
120
|
}
|
|
95
121
|
catch (error) {
|
|
@@ -109,24 +135,9 @@ export async function unsubscribe(c) {
|
|
|
109
135
|
const body = await c.req.json();
|
|
110
136
|
const db = getProjectDb(c.env);
|
|
111
137
|
const now = Date.now();
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
.prepare('SELECT * FROM subscribers WHERE unsubscribe_token = ?')
|
|
116
|
-
.bind(body.token)
|
|
117
|
-
.first();
|
|
118
|
-
}
|
|
119
|
-
else if (body.email) {
|
|
120
|
-
if (!EMAIL_REGEX.test(body.email))
|
|
121
|
-
return c.json({ success: false, message: 'Invalid email format' }, 400);
|
|
122
|
-
subscriber = await db
|
|
123
|
-
.prepare('SELECT * FROM subscribers WHERE email = ?')
|
|
124
|
-
.bind(body.email.toLowerCase().trim())
|
|
125
|
-
.first();
|
|
126
|
-
}
|
|
127
|
-
else {
|
|
128
|
-
return c.json({ success: false, message: 'email or token is required' }, 400);
|
|
129
|
-
}
|
|
138
|
+
if (!body.token)
|
|
139
|
+
return c.json({ success: false, message: 'Please use the unsubscribe link in one of our emails.' }, 400);
|
|
140
|
+
const subscriber = await db.prepare('SELECT * FROM subscribers WHERE unsubscribe_token = ?').bind(body.token).first();
|
|
130
141
|
if (!subscriber) {
|
|
131
142
|
return c.json({ success: true, message: 'If you were subscribed, you have been unsubscribed.' });
|
|
132
143
|
}
|
|
@@ -138,59 +149,3 @@ export async function unsubscribe(c) {
|
|
|
138
149
|
return c.json({ success: false, message: 'Failed to unsubscribe' }, 500);
|
|
139
150
|
}
|
|
140
151
|
}
|
|
141
|
-
/** GET /api/email/unsubscribe — HTML unsubscribe page */
|
|
142
|
-
export async function showUnsubscribePage(c) {
|
|
143
|
-
const email = c.req.query('email') ?? '';
|
|
144
|
-
const token = c.req.query('token') ?? '';
|
|
145
|
-
// If token provided, handle unsubscribe directly
|
|
146
|
-
if (token) {
|
|
147
|
-
try {
|
|
148
|
-
const db = getProjectDb(c.env);
|
|
149
|
-
const now = Date.now();
|
|
150
|
-
const subscriber = await db
|
|
151
|
-
.prepare('SELECT id FROM subscribers WHERE unsubscribe_token = ?')
|
|
152
|
-
.bind(token)
|
|
153
|
-
.first();
|
|
154
|
-
if (subscriber) {
|
|
155
|
-
await db.prepare(`UPDATE subscribers SET status = 'unsubscribed', unsubscribed_at = ?, updated_at = ? WHERE id = ?`).bind(now, now, subscriber.id).run();
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
catch (e) {
|
|
159
|
-
console.error('Token unsubscribe error:', e);
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
const html = `<!DOCTYPE html>
|
|
163
|
-
<html lang="en"><head>
|
|
164
|
-
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
165
|
-
<title>Unsubscribe</title>
|
|
166
|
-
<style>body{font-family:-apple-system,sans-serif;max-width:400px;margin:100px auto;padding:20px;text-align:center}
|
|
167
|
-
h1{font-size:1.5rem;margin-bottom:1rem}p{color:#666;margin-bottom:1.5rem}
|
|
168
|
-
input{width:100%;padding:12px;border:1px solid #ddd;border-radius:4px;margin-bottom:12px;box-sizing:border-box}
|
|
169
|
-
button{width:100%;padding:12px;background:#e74c3c;color:white;border:none;border-radius:4px;cursor:pointer;font-size:1rem}
|
|
170
|
-
.message{padding:12px;border-radius:4px;margin-bottom:1rem;display:none}
|
|
171
|
-
.success{background:#d4edda;color:#155724;display:block}.error{background:#f8d7da;color:#721c24;display:block}
|
|
172
|
-
</style></head><body>
|
|
173
|
-
${token ? '<p style="color:#155724;background:#d4edda;padding:12px;border-radius:4px;">You have been successfully unsubscribed.</p>' : `
|
|
174
|
-
<h1>Unsubscribe</h1>
|
|
175
|
-
<p>Enter your email address to unsubscribe from updates.</p>
|
|
176
|
-
<div id="message" class="message"></div>
|
|
177
|
-
<form id="form">
|
|
178
|
-
<input type="email" id="email" value="${email.replace(/"/g, '')}" placeholder="your@email.com" required>
|
|
179
|
-
<button type="submit">Unsubscribe</button>
|
|
180
|
-
</form>
|
|
181
|
-
<script>
|
|
182
|
-
document.getElementById('form').addEventListener('submit', async (e) => {
|
|
183
|
-
e.preventDefault();
|
|
184
|
-
const email = document.getElementById('email').value;
|
|
185
|
-
const msg = document.getElementById('message');
|
|
186
|
-
try {
|
|
187
|
-
const r = await fetch('/api/email/unsubscribe', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({email}) });
|
|
188
|
-
const d = await r.json();
|
|
189
|
-
msg.textContent = d.message;
|
|
190
|
-
msg.className = 'message ' + (d.success ? 'success' : 'error');
|
|
191
|
-
} catch { msg.textContent = 'An error occurred.'; msg.className = 'message error'; }
|
|
192
|
-
});
|
|
193
|
-
</script>`}
|
|
194
|
-
</body></html>`;
|
|
195
|
-
return c.html(html);
|
|
196
|
-
}
|
|
@@ -43,7 +43,7 @@ export async function sendBulkEmail(c) {
|
|
|
43
43
|
const db = getProjectDb(c.env);
|
|
44
44
|
const layout = await readEmailLayout(c.env);
|
|
45
45
|
const { results: subscribers } = await db
|
|
46
|
-
.prepare("SELECT email, name FROM subscribers WHERE status = 'subscribed'")
|
|
46
|
+
.prepare("SELECT email, name, unsubscribe_token FROM subscribers WHERE status = 'subscribed'")
|
|
47
47
|
.all();
|
|
48
48
|
if (!subscribers || subscribers.length === 0) {
|
|
49
49
|
return c.json({ success: false, message: 'No subscribed contacts found' }, 400);
|
|
@@ -51,7 +51,7 @@ export async function sendBulkEmail(c) {
|
|
|
51
51
|
let sentCount = 0;
|
|
52
52
|
const origin = new URL(c.req.url).origin;
|
|
53
53
|
for (const subscriber of subscribers) {
|
|
54
|
-
const unsubscribe = unsubscribeUrl(origin, subscriber.email);
|
|
54
|
+
const unsubscribe = unsubscribeUrl(origin, subscriber.email, subscriber.unsubscribe_token);
|
|
55
55
|
try {
|
|
56
56
|
await sendEmail(c.env, {
|
|
57
57
|
to: subscriber.email,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subscribers.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/subscribers.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"subscribers.handler.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/handlers/subscribers.handler.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AA2B/B,uCAAuC;AACvC,wBAAsB,cAAc,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAqBlE;AAED,wCAAwC;AACxC,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAuCpE;AAED,6CAA6C;AAC7C,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6CpE;AAED,8CAA8C;AAC9C,wBAAsB,gBAAgB,CAAC,CAAC,EAAE,OAAO,GAAG,OAAO,CAAC,QAAQ,CAAC,CAcpE"}
|
|
@@ -12,6 +12,11 @@ function rowToSubscriber(row) {
|
|
|
12
12
|
source: row.source,
|
|
13
13
|
data: JSON.parse(row.data_json || '{}'),
|
|
14
14
|
confirmedAt: row.confirmed_at,
|
|
15
|
+
paidStatus: row.paid_status ?? undefined,
|
|
16
|
+
paidPlan: row.paid_plan ?? undefined,
|
|
17
|
+
paidUntil: row.paid_until ?? undefined,
|
|
18
|
+
cancelAtPeriodEnd: row.cancel_at_period_end ? true : undefined,
|
|
19
|
+
compUntil: row.comp_until ?? undefined,
|
|
15
20
|
subscribedAt: row.subscribed_at,
|
|
16
21
|
unsubscribedAt: row.unsubscribed_at,
|
|
17
22
|
createdAt: row.created_at,
|
|
@@ -81,6 +86,10 @@ export async function updateSubscriber(c) {
|
|
|
81
86
|
sets.push('name = ?');
|
|
82
87
|
vals.push(body.name);
|
|
83
88
|
}
|
|
89
|
+
if (body.compUntil !== undefined) {
|
|
90
|
+
sets.push('comp_until = ?');
|
|
91
|
+
vals.push(body.compUntil);
|
|
92
|
+
}
|
|
84
93
|
if (body.data !== undefined) {
|
|
85
94
|
sets.push('data_json = ?');
|
|
86
95
|
vals.push(JSON.stringify(body.data));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admin.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/admin.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAkB5B,QAAA,MAAM,WAAW,4EAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"admin.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/admin.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAkB5B,QAAA,MAAM,WAAW,4EAAa,CAAC;AA+B/B,eAAe,WAAW,CAAC"}
|
|
@@ -6,7 +6,7 @@ import { authMiddleware, requirePermission } from '../../../middleware/auth';
|
|
|
6
6
|
// Subscribers
|
|
7
7
|
import { getSubscribers, createSubscriber, updateSubscriber, deleteSubscriber, } from '../handlers/subscribers.handler';
|
|
8
8
|
// Campaigns
|
|
9
|
-
import { getCampaigns, sendCampaign, testCampaign } from '../handlers/campaigns.handler';
|
|
9
|
+
import { getCampaigns, saveCampaign, deleteCampaign, sendCampaign, testCampaign } from '../handlers/campaigns.handler';
|
|
10
10
|
// Transactional send
|
|
11
11
|
import { sendTransactional, sendBulkEmail } from '../handlers/send.handler';
|
|
12
12
|
const adminRoutes = new Hono();
|
|
@@ -23,6 +23,8 @@ adminRoutes.delete('/subscribers/:id', deleteSubscriber);
|
|
|
23
23
|
// =============================================================================
|
|
24
24
|
adminRoutes.get('/campaigns', getCampaigns);
|
|
25
25
|
adminRoutes.post('/campaigns/test', testCampaign);
|
|
26
|
+
adminRoutes.put('/campaigns/:id', saveCampaign);
|
|
27
|
+
adminRoutes.delete('/campaigns/:id', deleteCampaign);
|
|
26
28
|
adminRoutes.post('/campaigns/:id/send', sendCampaign);
|
|
27
29
|
// =============================================================================
|
|
28
30
|
// Transactional send
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mail.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/mail.routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAM9C,QAAA,MAAM,MAAM,sDAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"mail.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/mail.routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAM9C,QAAA,MAAM,MAAM,sDAAsB,CAAC;AA2LnC,eAAe,MAAM,CAAC"}
|
|
@@ -3,7 +3,7 @@ import { bodyLimit } from 'hono/body-limit';
|
|
|
3
3
|
import { authMiddleware, requirePermission } from '../../../middleware/auth';
|
|
4
4
|
import { createId, ensureSchema } from '../../../lib/project-db';
|
|
5
5
|
import { validEmail } from '../../../lib/user-recovery';
|
|
6
|
-
import { publicMessage, processOutbox } from '../../../lib/mail';
|
|
6
|
+
import { publicMessage, processOutbox, defaultForwardAddress } from '../../../lib/mail';
|
|
7
7
|
const routes = new Hono();
|
|
8
8
|
// Mailbox contents are the most sensitive reads in the project, so reject any
|
|
9
9
|
// cross-origin request outright rather than relying on CORS to hide the
|
|
@@ -18,20 +18,28 @@ routes.use('*', authMiddleware, requirePermission('mail'), bodyLimit({ maxSize:
|
|
|
18
18
|
routes.use('*', async (c, next) => { c.header('Cache-Control', 'no-store'); await next(); });
|
|
19
19
|
routes.get('/mailboxes', async (c) => {
|
|
20
20
|
const db = await ensureSchema(c.env);
|
|
21
|
+
const defaultForwardTo = await defaultForwardAddress(c.env, db);
|
|
22
|
+
if (!c.env.MAIL_STORAGE && defaultForwardTo) {
|
|
23
|
+
await db.prepare('UPDATE mailboxes SET forward_to = ? WHERE (forward_to IS NULL OR forward_to = \'\') AND address <> ?')
|
|
24
|
+
.bind(defaultForwardTo, defaultForwardTo).run();
|
|
25
|
+
}
|
|
21
26
|
const { results } = await db.prepare(`SELECT m.*, (SELECT COUNT(*) FROM mail_messages e WHERE e.mailbox = m.address AND e.direction = 'inbound' AND e.read_at IS NULL AND e.archived_at IS NULL AND e.spam = 0) AS unread FROM mailboxes m ORDER BY address`).all();
|
|
22
|
-
return c.json({ mailboxes: results, storageConfigured: !!c.env.MAIL_STORAGE, sendingConfigured: !!(c.env.
|
|
27
|
+
return c.json({ mailboxes: results, storageConfigured: !!c.env.MAIL_STORAGE, sendingConfigured: !!(c.env.PLUNK_SECRET_KEY || c.env.DISABLE_DEPLOYMENTS === 'true'), defaultForwardTo });
|
|
23
28
|
});
|
|
24
29
|
routes.post('/mailboxes', async (c) => {
|
|
25
30
|
const body = await c.req.json();
|
|
26
31
|
const address = typeof body.address === 'string' ? body.address.trim().toLowerCase() : '';
|
|
27
32
|
if (!validEmail(address))
|
|
28
33
|
return c.json({ error: 'Enter a valid mailbox address.' }, 400);
|
|
29
|
-
const
|
|
34
|
+
const db = await ensureSchema(c.env);
|
|
35
|
+
const rawForward = typeof body.forwardTo === 'string' ? body.forwardTo.trim().toLowerCase() : '';
|
|
36
|
+
const forwardTo = rawForward || (!c.env.MAIL_STORAGE ? (await defaultForwardAddress(c.env, db, address)) || '' : '');
|
|
37
|
+
if (!c.env.MAIL_STORAGE && !forwardTo)
|
|
38
|
+
return c.json({ error: 'Enter a forwarding address for attachments.' }, 400);
|
|
30
39
|
if (forwardTo && !validEmail(forwardTo))
|
|
31
40
|
return c.json({ error: 'Enter a valid forwarding address.' }, 400);
|
|
32
41
|
if (forwardTo === address)
|
|
33
42
|
return c.json({ error: 'A mailbox cannot forward to itself.' }, 400);
|
|
34
|
-
const db = await ensureSchema(c.env);
|
|
35
43
|
await db.prepare('INSERT INTO mailboxes (address, name, created_at, forward_to) VALUES (?, ?, ?, ?) ON CONFLICT(address) DO UPDATE SET name = excluded.name, forward_to = excluded.forward_to')
|
|
36
44
|
.bind(address, typeof body.name === 'string' ? body.name.trim().slice(0, 200) : address, Date.now(), forwardTo || null).run();
|
|
37
45
|
// Only one mailbox may hold the flag, so move it rather than adding a second.
|
|
@@ -152,7 +160,7 @@ routes.post('/drafts/:id/send', async (c) => {
|
|
|
152
160
|
return c.json({ error: 'Draft changed or already queued.' }, 409);
|
|
153
161
|
if (!validEmail(row.recipient) || !row.subject.trim() || !row.body_text.trim())
|
|
154
162
|
return c.json({ error: 'Recipient, subject and message are required.' }, 400);
|
|
155
|
-
if (!(c.env.
|
|
163
|
+
if (!(c.env.PLUNK_SECRET_KEY || c.env.DISABLE_DEPLOYMENTS === 'true'))
|
|
156
164
|
return c.json({ error: 'Configure the Plunk sending integration first.' }, 503);
|
|
157
165
|
const now = Date.now();
|
|
158
166
|
const result = await db.prepare("UPDATE mail_messages SET status = 'queued', next_attempt_at = ?, updated_at = ?, created_at = ? WHERE id = ? AND status = 'draft' AND updated_at = ?")
|
|
@@ -168,9 +176,9 @@ routes.delete('/drafts/:id', async (c) => {
|
|
|
168
176
|
const row = await db.prepare("DELETE FROM mail_messages WHERE id = ? AND status = 'draft' AND updated_at = ? RETURNING *").bind(c.req.param('id'), version).first();
|
|
169
177
|
if (!row)
|
|
170
178
|
return c.json({ error: 'Draft changed or already queued.' }, 409);
|
|
171
|
-
const attachments = JSON.parse(row.attachments_json);
|
|
179
|
+
const attachments = JSON.parse(row.attachments_json).map(a => a.key).filter(Boolean);
|
|
172
180
|
if (attachments.length && c.env.MAIL_STORAGE)
|
|
173
|
-
await c.env.MAIL_STORAGE.delete(attachments
|
|
181
|
+
await c.env.MAIL_STORAGE.delete(attachments);
|
|
174
182
|
return c.json({ success: true });
|
|
175
183
|
});
|
|
176
184
|
routes.delete('/messages/:id', async (c) => {
|
|
@@ -179,12 +187,7 @@ routes.delete('/messages/:id', async (c) => {
|
|
|
179
187
|
if (!row)
|
|
180
188
|
return c.json({ error: 'Message not found.' }, 404);
|
|
181
189
|
if (c.env.MAIL_STORAGE) {
|
|
182
|
-
const keys = [];
|
|
183
|
-
if (row.raw_key)
|
|
184
|
-
keys.push(row.raw_key);
|
|
185
|
-
const atts = JSON.parse(row.attachments_json || '[]');
|
|
186
|
-
for (const a of atts)
|
|
187
|
-
keys.push(a.key);
|
|
190
|
+
const keys = JSON.parse(row.attachments_json || '[]').map(a => a.key).filter(Boolean);
|
|
188
191
|
if (keys.length) {
|
|
189
192
|
try {
|
|
190
193
|
await c.env.MAIL_STORAGE.delete(keys);
|
|
@@ -219,15 +222,14 @@ routes.get('/messages/:id/files/:index', async (c) => {
|
|
|
219
222
|
const row = await db.prepare('SELECT * FROM mail_messages WHERE id = ?').bind(c.req.param('id')).first();
|
|
220
223
|
if (!row)
|
|
221
224
|
return c.notFound();
|
|
222
|
-
const
|
|
223
|
-
const
|
|
224
|
-
const key = index === 'raw' ? row.raw_key : attachment?.key;
|
|
225
|
+
const attachment = JSON.parse(row.attachments_json)[Number(c.req.param('index'))];
|
|
226
|
+
const key = attachment?.key;
|
|
225
227
|
if (!key || !c.env.MAIL_STORAGE)
|
|
226
228
|
return c.notFound();
|
|
227
229
|
const object = await c.env.MAIL_STORAGE.get(key);
|
|
228
230
|
if (!object)
|
|
229
231
|
return c.notFound();
|
|
230
|
-
const filename =
|
|
232
|
+
const filename = attachment.filename;
|
|
231
233
|
return new Response(object.body, { headers: { 'Content-Type': 'application/octet-stream', 'X-Content-Type-Options': 'nosniff',
|
|
232
234
|
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(filename).replace(/'/g, '%27')}`, 'Cache-Control': 'no-store', 'Content-Security-Policy': "default-src 'none'; sandbox" } });
|
|
233
235
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/public.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAG5B,QAAA,MAAM,YAAY,4EAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"public.routes.d.ts","sourceRoot":"","sources":["../../../../src/api/emails/routes/public.routes.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAG5B,QAAA,MAAM,YAAY,4EAAa,CAAC;AAMhC,eAAe,YAAY,CAAC"}
|
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
* Public Routes for Email Module — no authentication required
|
|
3
3
|
*/
|
|
4
4
|
import { Hono } from 'hono';
|
|
5
|
-
import { subscribe, confirm, unsubscribe
|
|
5
|
+
import { subscribe, confirm, unsubscribe } from '../handlers/public.handler';
|
|
6
6
|
const publicRoutes = new Hono();
|
|
7
7
|
publicRoutes.post('/subscribe', subscribe);
|
|
8
8
|
publicRoutes.get('/confirm', confirm);
|
|
9
|
-
publicRoutes.get('/unsubscribe', showUnsubscribePage);
|
|
10
9
|
publicRoutes.post('/unsubscribe', unsubscribe);
|
|
11
10
|
export default publicRoutes;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/api/enquiries/routes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAE5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAQ5C,QAAA,MAAM,aAAa;cAAwB,QAAQ;yCAAK,CAAC;AA4DzD,eAAe,aAAa,CAAC"}
|