@hintergrund/worker 0.2.3 → 0.3.1
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/cms/handlers/admin-users.handler.d.ts +1 -0
- package/dist/api/cms/handlers/admin-users.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/admin-users.handler.js +60 -79
- package/dist/api/cms/handlers/auth.handler.d.ts +1 -1
- package/dist/api/cms/handlers/auth.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/auth.handler.js +13 -94
- package/dist/api/cms/handlers/dashboard.handler.d.ts +1 -1
- package/dist/api/cms/handlers/dashboard.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/dashboard.handler.js +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/github-secrets.handler.js +8 -1
- package/dist/api/cms/handlers/integrations.handler.d.ts +5 -0
- package/dist/api/cms/handlers/integrations.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/integrations.handler.js +24 -0
- package/dist/api/cms/handlers/recovery.handler.d.ts +5 -0
- package/dist/api/cms/handlers/recovery.handler.d.ts.map +1 -0
- package/dist/api/cms/handlers/recovery.handler.js +53 -0
- package/dist/api/cms/handlers/setup.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/setup.handler.js +97 -35
- package/dist/api/cms/handlers/website-repo.handler.d.ts +2 -1
- package/dist/api/cms/handlers/website-repo.handler.d.ts.map +1 -1
- package/dist/api/cms/handlers/website-repo.handler.js +64 -55
- package/dist/api/cms/routes/auth.routes.d.ts +1 -1
- package/dist/api/cms/routes/auth.routes.d.ts.map +1 -1
- package/dist/api/cms/routes/auth.routes.js +7 -2
- package/dist/api/cms/routes/index.d.ts +1 -1
- package/dist/api/cms/routes/index.d.ts.map +1 -1
- package/dist/api/cms/routes/index.js +7 -11
- package/dist/api/emails/handlers/campaigns.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/campaigns.handler.js +3 -4
- package/dist/api/emails/handlers/invoice.handler.d.ts +8 -15
- package/dist/api/emails/handlers/invoice.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/invoice.handler.js +142 -170
- package/dist/api/emails/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/public.handler.js +27 -8
- package/dist/api/emails/handlers/send.handler.d.ts +1 -3
- package/dist/api/emails/handlers/send.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/send.handler.js +18 -65
- package/dist/api/emails/handlers/settings.handler.d.ts +60 -12
- package/dist/api/emails/handlers/settings.handler.d.ts.map +1 -1
- package/dist/api/emails/handlers/settings.handler.js +35 -94
- package/dist/api/emails/routes/admin.routes.d.ts.map +1 -1
- package/dist/api/emails/routes/admin.routes.js +5 -6
- package/dist/api/emails/routes/mail.routes.d.ts +5 -0
- package/dist/api/emails/routes/mail.routes.d.ts.map +1 -0
- package/dist/api/emails/routes/mail.routes.js +188 -0
- package/dist/api/shop/handlers/products.handler.d.ts +2 -2
- package/dist/api/shop/handlers/products.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/products.handler.js +21 -8
- package/dist/api/shop/handlers/public.handler.d.ts.map +1 -1
- package/dist/api/shop/handlers/public.handler.js +17 -66
- package/dist/index.d.ts +10 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +26 -18
- package/dist/lib/auth/crypto.d.ts +0 -1
- package/dist/lib/auth/crypto.d.ts.map +1 -1
- package/dist/lib/auth/crypto.js +1 -4
- package/dist/lib/brand.d.ts +6 -0
- package/dist/lib/brand.d.ts.map +1 -0
- package/dist/lib/brand.js +31 -0
- package/dist/lib/config.d.ts +1 -2
- package/dist/lib/config.d.ts.map +1 -1
- package/dist/lib/config.js +1 -8
- package/dist/lib/email-template.d.ts +4 -7
- package/dist/lib/email-template.d.ts.map +1 -1
- package/dist/lib/email-template.js +9 -31
- package/dist/lib/email.d.ts +20 -11
- package/dist/lib/email.d.ts.map +1 -1
- package/dist/lib/email.js +29 -19
- package/dist/lib/github.d.ts +1 -1
- package/dist/lib/github.d.ts.map +1 -1
- package/dist/lib/github.js +13 -4
- package/dist/lib/integration-health.d.ts +18 -0
- package/dist/lib/integration-health.d.ts.map +1 -0
- package/dist/lib/integration-health.js +51 -0
- package/dist/lib/invoice.d.ts +13 -0
- package/dist/lib/invoice.d.ts.map +1 -0
- package/dist/lib/invoice.js +41 -0
- package/dist/lib/mail-schema.d.ts +2 -0
- package/dist/lib/mail-schema.d.ts.map +1 -0
- package/dist/lib/mail-schema.js +56 -0
- package/dist/lib/mail.d.ts +83 -0
- package/dist/lib/mail.d.ts.map +1 -0
- package/dist/lib/mail.js +211 -0
- package/dist/lib/project-db.d.ts +3 -4
- package/dist/lib/project-db.d.ts.map +1 -1
- package/dist/lib/project-db.js +14 -43
- package/dist/lib/template.d.ts.map +1 -1
- package/dist/lib/template.js +28 -0
- package/dist/lib/user-recovery.d.ts +9 -0
- package/dist/lib/user-recovery.d.ts.map +1 -0
- package/dist/lib/user-recovery.js +42 -0
- package/dist/lib/website-i18n.d.ts +10 -0
- package/dist/lib/website-i18n.d.ts.map +1 -0
- package/dist/lib/website-i18n.js +195 -0
- package/dist/middleware/auth.d.ts +3 -1
- package/dist/middleware/auth.d.ts.map +1 -1
- package/dist/middleware/auth.js +8 -4
- package/package.json +4 -2
- package/dist/api/cms/handlers/agent-conversations.handler.d.ts +0 -6
- package/dist/api/cms/handlers/agent-conversations.handler.d.ts.map +0 -1
- package/dist/api/cms/handlers/agent-conversations.handler.js +0 -87
- package/dist/api/cms/handlers/website-templates.handler.d.ts +0 -6
- package/dist/api/cms/handlers/website-templates.handler.d.ts.map +0 -1
- package/dist/api/cms/handlers/website-templates.handler.js +0 -53
- package/dist/api/shop/handlers/prices.handler.d.ts +0 -4
- package/dist/api/shop/handlers/prices.handler.d.ts.map +0 -1
- package/dist/api/shop/handlers/prices.handler.js +0 -6
- package/dist/hintergrund-assets.d.ts +0 -5
- package/dist/hintergrund-assets.d.ts.map +0 -1
- package/dist/hintergrund-assets.js +0 -11
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
import { getEmailsConfig
|
|
2
|
-
import { createGitHubClient } from '../../../lib/github';
|
|
1
|
+
import { getEmailsConfig } from '../../../lib/config';
|
|
3
2
|
import Stripe from 'stripe';
|
|
4
|
-
import {
|
|
3
|
+
import { renderInvoice } from '../../../lib/invoice';
|
|
4
|
+
import { base64 } from '../../../lib/brand';
|
|
5
5
|
import { sendEmail } from '../../../lib/email';
|
|
6
|
+
import { DEFAULT_SHOP_EMAIL_TEMPLATES } from '@hintergrund/runtime-contracts';
|
|
6
7
|
import { renderEmailTemplate } from '../../../lib/email-template';
|
|
7
8
|
import { readShopCatalog, readShopSettings } from './products.handler';
|
|
8
|
-
import {
|
|
9
|
+
import { readEmailTemplateData } from '../../emails/handlers/settings.handler';
|
|
9
10
|
import { ensureSchema } from '../../../lib/project-db';
|
|
10
11
|
const EUROPEAN_STRIPE_COUNTRIES = [
|
|
11
12
|
'AL', 'AD', 'AT', 'BY', 'BE', 'BA', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE',
|
|
@@ -76,14 +77,6 @@ async function getOrderByStripeSession(env, sessionId) {
|
|
|
76
77
|
const row = await db.prepare('SELECT * FROM shop_orders WHERE stripe_session_id = ?').bind(sessionId).first();
|
|
77
78
|
return row ? rowToOrder(row) : null;
|
|
78
79
|
}
|
|
79
|
-
function uint8ToBase64(bytes) {
|
|
80
|
-
let binary = '';
|
|
81
|
-
const chunkSize = 0x8000;
|
|
82
|
-
for (let i = 0; i < bytes.length; i += chunkSize) {
|
|
83
|
-
binary += String.fromCharCode(...bytes.slice(i, i + chunkSize));
|
|
84
|
-
}
|
|
85
|
-
return btoa(binary);
|
|
86
|
-
}
|
|
87
80
|
function calculateItems(request, catalogProducts) {
|
|
88
81
|
return request.items.map((requestItem) => {
|
|
89
82
|
const product = catalogProducts.find((item) => item.id === requestItem.productId || item.slug === requestItem.slug);
|
|
@@ -366,7 +359,7 @@ function orderToInvoiceData(order) {
|
|
|
366
359
|
}
|
|
367
360
|
return {
|
|
368
361
|
invoiceNumber: order.invoiceNumber || order.orderNumber,
|
|
369
|
-
invoiceDate: new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }),
|
|
362
|
+
invoiceDate: new Date(order.createdAt * 1000).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' }),
|
|
370
363
|
customerName: order.customer.name || order.customer.email,
|
|
371
364
|
customerEmail: order.customer.email,
|
|
372
365
|
customerAddress: order.customer.address,
|
|
@@ -389,18 +382,17 @@ async function tryGetEmailsConfig(env) {
|
|
|
389
382
|
async function sendInvoiceEmail(env, order, bankInstructions) {
|
|
390
383
|
const emailsConfig = await tryGetEmailsConfig(env);
|
|
391
384
|
if (!emailsConfig)
|
|
392
|
-
|
|
393
|
-
const { invoiceConfig, branding } = await loadInvoiceSettings(env);
|
|
385
|
+
throw new Error('Configure email delivery before sending invoices.');
|
|
394
386
|
const { settings, logoDataUrl } = await readEmailTemplateData(env);
|
|
395
387
|
const { settings: shopSettings } = await readShopSettings(env);
|
|
396
388
|
order.invoiceNumber ||= numberWithPrefix(shopSettings.invoiceNumberPrefix);
|
|
397
389
|
const invoiceData = orderToInvoiceData(order);
|
|
398
|
-
const pdfBytes = await
|
|
390
|
+
const pdfBytes = await renderInvoice(env, invoiceData);
|
|
399
391
|
const purchaseTemplate = shopSettings.emailTemplates?.purchase;
|
|
400
392
|
const formattedAmount = new Intl.NumberFormat('en-US', { style: 'currency', currency: order.totals.currency.toUpperCase() }).format(order.totals.total / 100);
|
|
401
393
|
const vars = { order_number: order.orderNumber, invoice_number: order.invoiceNumber ?? '', amount: formattedAmount };
|
|
402
|
-
let subject = applyTemplateVars(purchaseTemplate?.subject ||
|
|
403
|
-
let htmlBody = applyTemplateVars(purchaseTemplate?.bodyHtml ||
|
|
394
|
+
let subject = applyTemplateVars(purchaseTemplate?.subject || DEFAULT_SHOP_EMAIL_TEMPLATES.purchase.subject, vars);
|
|
395
|
+
let htmlBody = applyTemplateVars(purchaseTemplate?.bodyHtml || DEFAULT_SHOP_EMAIL_TEMPLATES.purchase.bodyHtml, vars);
|
|
404
396
|
if (bankInstructions) {
|
|
405
397
|
const lines = [
|
|
406
398
|
`Please transfer ${new Intl.NumberFormat('en-US', { style: 'currency', currency: order.totals.currency.toUpperCase() }).format(order.totals.total / 100)} to:`,
|
|
@@ -421,7 +413,9 @@ async function sendInvoiceEmail(env, order, bankInstructions) {
|
|
|
421
413
|
toName: order.customer.name ?? undefined,
|
|
422
414
|
subject,
|
|
423
415
|
html: renderEmailTemplate({ bodyHtml: htmlBody, template: settings.emailTemplate, logoDataUrl }),
|
|
416
|
+
attachments: [{ filename: `${(order.invoiceNumber ?? order.orderNumber ?? 'invoice').replace(/[^a-zA-Z0-9_-]/g, '_')}.pdf`, content: base64(pdfBytes), contentType: 'application/pdf', disposition: 'attachment' }],
|
|
424
417
|
});
|
|
418
|
+
order.invoiceSentAt = nowSeconds();
|
|
425
419
|
await updateOrder(env, order);
|
|
426
420
|
}
|
|
427
421
|
async function sendPaymentConfirmationEmail(env, order) {
|
|
@@ -436,8 +430,8 @@ async function sendPaymentConfirmationEmail(env, order) {
|
|
|
436
430
|
}).format(order.totals.total / 100);
|
|
437
431
|
const confirmTemplate = shopSettings.emailTemplates?.paymentConfirmed;
|
|
438
432
|
const vars = { order_number: order.orderNumber, amount };
|
|
439
|
-
const subject = applyTemplateVars(confirmTemplate?.subject ||
|
|
440
|
-
const html = applyTemplateVars(confirmTemplate?.bodyHtml ||
|
|
433
|
+
const subject = applyTemplateVars(confirmTemplate?.subject || DEFAULT_SHOP_EMAIL_TEMPLATES.paymentConfirmed.subject, vars);
|
|
434
|
+
const html = applyTemplateVars(confirmTemplate?.bodyHtml || DEFAULT_SHOP_EMAIL_TEMPLATES.paymentConfirmed.bodyHtml, vars);
|
|
441
435
|
try {
|
|
442
436
|
await sendEmail(env, {
|
|
443
437
|
to: order.customer.email,
|
|
@@ -450,58 +444,16 @@ async function sendPaymentConfirmationEmail(env, order) {
|
|
|
450
444
|
console.error('Failed to send payment confirmation email:', error);
|
|
451
445
|
}
|
|
452
446
|
}
|
|
453
|
-
function guessLogoMime(path) {
|
|
454
|
-
const ext = path.split('.').pop()?.toLowerCase();
|
|
455
|
-
if (ext === 'png')
|
|
456
|
-
return 'image/png';
|
|
457
|
-
if (ext === 'jpg' || ext === 'jpeg')
|
|
458
|
-
return 'image/jpeg';
|
|
459
|
-
if (ext === 'gif')
|
|
460
|
-
return 'image/gif';
|
|
461
|
-
if (ext === 'svg')
|
|
462
|
-
return 'image/svg+xml';
|
|
463
|
-
return 'image/png';
|
|
464
|
-
}
|
|
465
|
-
async function loadInvoiceSettings(env) {
|
|
466
|
-
try {
|
|
467
|
-
const { settings } = await readEmailSettings(env);
|
|
468
|
-
let logoDataUrl;
|
|
469
|
-
if (settings.logoPath) {
|
|
470
|
-
try {
|
|
471
|
-
const github = createGitHubClient(getGitHubConfig(env));
|
|
472
|
-
const file = await github.readFileBinary(settings.logoPath);
|
|
473
|
-
if (file)
|
|
474
|
-
logoDataUrl = `data:${guessLogoMime(settings.logoPath)};base64,${file.content}`;
|
|
475
|
-
}
|
|
476
|
-
catch (error) {
|
|
477
|
-
console.error('Failed to load logo from GitHub:', error);
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
return {
|
|
481
|
-
invoiceConfig: settings.invoice,
|
|
482
|
-
branding: {
|
|
483
|
-
logo: logoDataUrl,
|
|
484
|
-
companyName: settings.invoice.companyName,
|
|
485
|
-
primaryColor: settings.invoice.primaryColor,
|
|
486
|
-
},
|
|
487
|
-
};
|
|
488
|
-
}
|
|
489
|
-
catch (error) {
|
|
490
|
-
console.error('Failed to load invoice settings from GitHub:', error);
|
|
491
|
-
}
|
|
492
|
-
return { invoiceConfig: {} };
|
|
493
|
-
}
|
|
494
447
|
export async function generateOrderInvoice(c) {
|
|
495
448
|
try {
|
|
496
449
|
const order = await getOrderById(c.env, c.req.param('id') ?? '');
|
|
497
450
|
if (!order)
|
|
498
451
|
return c.json({ success: false, error: 'Order not found' }, 404);
|
|
499
|
-
const
|
|
500
|
-
const pdfBytes = await generateInvoicePdf(invoiceConfig, orderToInvoiceData(order), branding);
|
|
452
|
+
const pdfBytes = await renderInvoice(c.env, orderToInvoiceData(order));
|
|
501
453
|
return new Response(pdfBytes, {
|
|
502
454
|
headers: {
|
|
503
455
|
'Content-Type': 'application/pdf',
|
|
504
|
-
'Content-Disposition': `attachment; filename="${order.invoiceNumber || order.orderNumber}.pdf"`
|
|
456
|
+
'Content-Disposition': `attachment; filename="${(order.invoiceNumber || order.orderNumber).replace(/[^a-zA-Z0-9_-]/g, '_')}.pdf"`
|
|
505
457
|
}
|
|
506
458
|
});
|
|
507
459
|
}
|
|
@@ -515,9 +467,8 @@ export async function sendOrderInvoice(c) {
|
|
|
515
467
|
const order = await getOrderById(c.env, c.req.param('id') ?? '');
|
|
516
468
|
if (!order)
|
|
517
469
|
return c.json({ success: false, error: 'Order not found' }, 404);
|
|
470
|
+
// sendInvoiceEmail marks the order as sent only after the provider accepted delivery.
|
|
518
471
|
await sendInvoiceEmail(c.env, order);
|
|
519
|
-
order.invoiceSentAt = nowSeconds();
|
|
520
|
-
await updateOrder(c.env, order);
|
|
521
472
|
return c.json({ success: true, order });
|
|
522
473
|
}
|
|
523
474
|
catch (error) {
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Hono } from 'hono';
|
|
2
|
+
import { receiveEmail } from './lib/mail';
|
|
2
3
|
export type Bindings = {
|
|
3
4
|
SECRET?: string;
|
|
4
5
|
SETUP_TOKEN?: string;
|
|
@@ -19,12 +20,13 @@ export type Bindings = {
|
|
|
19
20
|
FROM_NAME?: string;
|
|
20
21
|
REPLY_TO?: string;
|
|
21
22
|
PLUNK_SECRET_KEY?: string;
|
|
23
|
+
/** Canonical project origin for account recovery links. */
|
|
24
|
+
PUBLIC_ORIGIN?: string;
|
|
25
|
+
MAIL_STORAGE?: R2Bucket;
|
|
22
26
|
STRIPE_SECRET_KEY?: string;
|
|
23
27
|
STRIPE_WEBHOOK_SECRET?: string;
|
|
24
|
-
STRIPE_PUBLISHABLE_KEY?: string;
|
|
25
28
|
GEMINI_API_KEY?: string;
|
|
26
29
|
DEEPSEEK_API_KEY?: string;
|
|
27
|
-
TEMPLATE_REGISTRY_URL?: string;
|
|
28
30
|
UI_BASE_URL: string;
|
|
29
31
|
ASSETS: Fetcher;
|
|
30
32
|
PROJECT_DB?: D1Database;
|
|
@@ -41,6 +43,12 @@ export type HonoEnv = {
|
|
|
41
43
|
Variables: Variables;
|
|
42
44
|
};
|
|
43
45
|
export declare function createApp(): Hono<HonoEnv, import("hono/types").BlankSchema, "/">;
|
|
46
|
+
/** Project entrypoint with HTTP, incoming email and D1 outbox processing. No Durable Objects. */
|
|
47
|
+
export declare function createWorker(): {
|
|
48
|
+
fetch: (request: Request, env?: {} | Bindings | undefined, executionCtx?: import("hono").ExecutionContext) => Response | Promise<Response>;
|
|
49
|
+
email: typeof receiveEmail;
|
|
50
|
+
scheduled(_controller: ScheduledController, env: Bindings): Promise<void>;
|
|
51
|
+
};
|
|
44
52
|
export * from './lib/auth/jwt';
|
|
45
53
|
export * from './lib/auth/crypto';
|
|
46
54
|
export * from './lib/template';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAK5B,OAAO,EAAE,YAAY,EAAiB,MAAM,YAAY,CAAC;AAQzD,MAAM,MAAM,QAAQ,GAAG;IAEtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iFAAiF;IACjF,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,4EAA4E;IAC5E,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAG7B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,sBAAsB,CAAC,EAAE,MAAM,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAG1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,2DAA2D;IAC3D,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,YAAY,CAAC,EAAE,QAAQ,CAAC;IAGxB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAG/B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAG1B,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,OAAO,CAAC;IAChB,UAAU,CAAC,EAAE,UAAU,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACvB,IAAI,CAAC,EAAE;QACN,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;KACrB,CAAC;CACF,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IAAE,QAAQ,EAAE,QAAQ,CAAC;IAAC,SAAS,EAAE,SAAS,CAAA;CAAE,CAAC;AAEnE,wBAAgB,SAAS,yDA0GxB;AAED,iGAAiG;AACjG,wBAAgB,YAAY;;;2BAKG,mBAAmB,OAAO,QAAQ;EAEhE;AAGD,cAAc,gBAAgB,CAAC;AAC/B,cAAc,mBAAmB,CAAC;AAClC,cAAc,gBAAgB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -2,10 +2,11 @@ import { Hono } from 'hono';
|
|
|
2
2
|
import { cors } from 'hono/cors';
|
|
3
3
|
import cmsRoutes from './api/cms/routes';
|
|
4
4
|
import emailRoutes from './api/emails/routes';
|
|
5
|
+
import mailRoutes from './api/emails/routes/mail.routes';
|
|
6
|
+
import { receiveEmail, processOutbox } from './lib/mail';
|
|
5
7
|
import shopRoutes from './api/shop/routes';
|
|
6
8
|
import { authMiddleware } from './middleware/auth';
|
|
7
9
|
import { getTemplate } from './lib/template';
|
|
8
|
-
import { ensureSchema } from './lib/project-db';
|
|
9
10
|
import { hasValidSetupToken, projectNeedsSetup } from './api/cms/handlers/setup.handler';
|
|
10
11
|
export function createApp() {
|
|
11
12
|
const app = new Hono();
|
|
@@ -38,26 +39,13 @@ export function createApp() {
|
|
|
38
39
|
app.get('/login', async (c) => {
|
|
39
40
|
if (await projectNeedsSetup(c))
|
|
40
41
|
return c.redirect('/setup');
|
|
41
|
-
|
|
42
|
-
try {
|
|
43
|
-
if (c.env.PROJECT_DB) {
|
|
44
|
-
const db = await ensureSchema(c.env);
|
|
45
|
-
const methods = await db
|
|
46
|
-
.prepare('SELECT login_method, COUNT(*) AS count FROM admin_users WHERE disabled_at IS NULL GROUP BY login_method ORDER BY count DESC')
|
|
47
|
-
.all();
|
|
48
|
-
const loginMethod = methods.results?.[0]?.login_method === 'otp' ? 'otp' : 'password';
|
|
49
|
-
configParams = `config='${JSON.stringify({ loginMethod })}'`;
|
|
50
|
-
}
|
|
51
|
-
}
|
|
52
|
-
catch (error) {
|
|
53
|
-
console.error('Failed to load project login config:', error);
|
|
54
|
-
}
|
|
55
|
-
return c.html(getTemplate('login', c.env.UI_BASE_URL, configParams));
|
|
42
|
+
return c.html(getTemplate('login', c.env.UI_BASE_URL));
|
|
56
43
|
});
|
|
57
44
|
// Mount CMS routes under /api/admin
|
|
58
45
|
app.route('/api/admin', cmsRoutes);
|
|
59
46
|
// Mount email routes under /api/email
|
|
60
47
|
app.route('/api/email', emailRoutes);
|
|
48
|
+
app.route('/api/mail', mailRoutes);
|
|
61
49
|
// Mount shop routes under /api/shop
|
|
62
50
|
app.route('/api/shop', shopRoutes);
|
|
63
51
|
// Admin main page (protected)
|
|
@@ -77,7 +65,6 @@ export function createApp() {
|
|
|
77
65
|
const adminConfig = getAdminConfig();
|
|
78
66
|
adminConfig.canManageAdminUsers = true;
|
|
79
67
|
adminConfig.integrations = {
|
|
80
|
-
stripePublishableKeySet: !!c.env.STRIPE_PUBLISHABLE_KEY,
|
|
81
68
|
stripeSecretKeySet: !!c.env.STRIPE_SECRET_KEY && c.env.STRIPE_SECRET_KEY !== 'NOT_CONFIGURED',
|
|
82
69
|
stripeWebhookSecretSet: !!c.env.STRIPE_WEBHOOK_SECRET && c.env.STRIPE_WEBHOOK_SECRET !== 'NOT_CONFIGURED',
|
|
83
70
|
emailProviderApiKeySet: !!(c.env.API_KEY || c.env.PLUNK_SECRET_KEY),
|
|
@@ -88,10 +75,22 @@ export function createApp() {
|
|
|
88
75
|
}
|
|
89
76
|
catch (error) {
|
|
90
77
|
// Fallback to default config if parsing fails
|
|
91
|
-
const configParams = 'config=\'{
|
|
78
|
+
const configParams = 'config=\'{}\'';
|
|
92
79
|
return c.html(getTemplate('admin', c.env.UI_BASE_URL, configParams));
|
|
93
80
|
}
|
|
94
81
|
});
|
|
82
|
+
// Standalone mail client (protected). Live D1 correspondence for the project's
|
|
83
|
+
// domain addresses — no Git staging, no Save, no agent, so it deliberately does
|
|
84
|
+
// not load the admin bundle. Authentication is the shared admin session.
|
|
85
|
+
app.get('/mail', async (c) => {
|
|
86
|
+
let authPassed = false;
|
|
87
|
+
const authResult = await authMiddleware(c, async () => {
|
|
88
|
+
authPassed = true;
|
|
89
|
+
});
|
|
90
|
+
if (!authPassed)
|
|
91
|
+
return authResult;
|
|
92
|
+
return c.html(getTemplate('mail', c.env.UI_BASE_URL));
|
|
93
|
+
});
|
|
95
94
|
// Serve static assets from the app build
|
|
96
95
|
app.get('*', async (c) => {
|
|
97
96
|
const url = new URL(c.req.url);
|
|
@@ -108,6 +107,15 @@ export function createApp() {
|
|
|
108
107
|
});
|
|
109
108
|
return app;
|
|
110
109
|
}
|
|
110
|
+
/** Project entrypoint with HTTP, incoming email and D1 outbox processing. No Durable Objects. */
|
|
111
|
+
export function createWorker() {
|
|
112
|
+
const app = createApp();
|
|
113
|
+
return {
|
|
114
|
+
fetch: app.fetch,
|
|
115
|
+
email: receiveEmail,
|
|
116
|
+
async scheduled(_controller, env) { await processOutbox(env); },
|
|
117
|
+
};
|
|
118
|
+
}
|
|
111
119
|
// Export individual utilities if needed
|
|
112
120
|
export * from './lib/auth/jwt';
|
|
113
121
|
export * from './lib/auth/crypto';
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { decrypt, readRequestBody } from '@hintergrund/auth';
|
|
2
2
|
export { decrypt, readRequestBody };
|
|
3
|
-
export declare function generateRandomToken(): string;
|
|
4
3
|
export declare function hashPw(password: string, pepper: string): Promise<string>;
|
|
5
4
|
/**
|
|
6
5
|
* Verify a password against an encrypted password
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../../src/lib/auth/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,OAAO,
|
|
1
|
+
{"version":3,"file":"crypto.d.ts","sourceRoot":"","sources":["../../../src/lib/auth/crypto.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,OAAO,EAEP,eAAe,EAEf,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,OAAO,EAAE,eAAe,EAAE,CAAC;AAGpC,wBAAsB,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAE9E;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAAC,iBAAiB,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAU5G"}
|
package/dist/lib/auth/crypto.js
CHANGED
|
@@ -1,8 +1,5 @@
|
|
|
1
|
-
import { decrypt,
|
|
1
|
+
import { decrypt, hashPassword, readRequestBody, verifyPassword } from '@hintergrund/auth';
|
|
2
2
|
export { decrypt, readRequestBody };
|
|
3
|
-
export function generateRandomToken() {
|
|
4
|
-
return generateRandomSecret();
|
|
5
|
-
}
|
|
6
3
|
export async function hashPw(password, pepper) {
|
|
7
4
|
return hashPassword(password, pepper);
|
|
8
5
|
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Bindings } from '../index';
|
|
2
|
+
export declare function readBrand(env: Bindings): Promise<import("@hintergrund/runtime-contracts").Brand>;
|
|
3
|
+
export declare function readInvoiceDesign(env: Bindings): Promise<import("@hintergrund/runtime-contracts").InvoiceDesign>;
|
|
4
|
+
export declare function readBrandAsset(env: Bindings, path: string): Promise<Uint8Array>;
|
|
5
|
+
export declare function base64(bytes: Uint8Array): string;
|
|
6
|
+
//# sourceMappingURL=brand.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"brand.d.ts","sourceRoot":"","sources":["../../src/lib/brand.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKzC,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,2DAK5C;AACD,wBAAsB,iBAAiB,CAAC,GAAG,EAAE,QAAQ,mEAIpD;AACD,wBAAsB,cAAc,CAAC,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAMrF;AACD,wBAAgB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAIhD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { BRAND_PATH, validateBrand, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN, validateInvoiceDesign, publicAssetPath } from '@hintergrund/runtime-contracts';
|
|
2
|
+
import { createGitHubClient } from './github';
|
|
3
|
+
import { getGitHubConfig } from './config';
|
|
4
|
+
import { readJsonConfig } from './github-config';
|
|
5
|
+
export async function readBrand(env) {
|
|
6
|
+
const github = createGitHubClient(getGitHubConfig(env));
|
|
7
|
+
const file = await github.readJsonFileIfExists(BRAND_PATH);
|
|
8
|
+
if (!file)
|
|
9
|
+
throw new Error(`Missing ${BRAND_PATH}. Every website template ships one.`);
|
|
10
|
+
return validateBrand(file.data);
|
|
11
|
+
}
|
|
12
|
+
export async function readInvoiceDesign(env) {
|
|
13
|
+
const github = createGitHubClient(getGitHubConfig(env));
|
|
14
|
+
const { data } = await readJsonConfig(github, INVOICE_DESIGN_PATH, DEFAULT_INVOICE_DESIGN);
|
|
15
|
+
return validateInvoiceDesign(data);
|
|
16
|
+
}
|
|
17
|
+
export async function readBrandAsset(env, path) {
|
|
18
|
+
publicAssetPath(path);
|
|
19
|
+
const file = await createGitHubClient(getGitHubConfig(env)).readFileBinary(path);
|
|
20
|
+
if (!file)
|
|
21
|
+
throw new Error(`Brand asset not found: ${path}`);
|
|
22
|
+
if (file.content.length > 8 * 1024 * 1024)
|
|
23
|
+
throw new Error('Brand asset exceeds 6 MB.');
|
|
24
|
+
return Uint8Array.from(atob(file.content), char => char.charCodeAt(0));
|
|
25
|
+
}
|
|
26
|
+
export function base64(bytes) {
|
|
27
|
+
let result = '';
|
|
28
|
+
for (let i = 0; i < bytes.length; i += 8192)
|
|
29
|
+
result += String.fromCharCode(...bytes.subarray(i, i + 8192));
|
|
30
|
+
return btoa(result);
|
|
31
|
+
}
|
package/dist/lib/config.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AppConfig, AdminConfig, EmailsModuleConfig
|
|
1
|
+
import type { AppConfig, AdminConfig, EmailsModuleConfig } from '@hintergrund/runtime-contracts';
|
|
2
2
|
/**
|
|
3
3
|
* Load application configuration from environment variables
|
|
4
4
|
* Reads the modular Worker environment bindings.
|
|
@@ -12,7 +12,6 @@ export declare function getAdminConfig(): AdminConfig;
|
|
|
12
12
|
/** Get Emails module configuration. */
|
|
13
13
|
export declare function getEmailsConfig(env: Record<string, string | undefined> | any): EmailsModuleConfig;
|
|
14
14
|
/** Get Shop module configuration. */
|
|
15
|
-
export declare function getShopConfig(env: Record<string, string | undefined> | any): ShopModuleConfig;
|
|
16
15
|
/**
|
|
17
16
|
* Get GitHub configuration from environment variables
|
|
18
17
|
* Used by CMS, emails and other modules for GitHub storage
|
package/dist/lib/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/lib/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,kBAAkB,EAAE,
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/lib/config.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEjG;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,SAAS,CAMnF;AAwCD;;;GAGG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAE5C;AAED,uCAAuC;AACvC,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG,GAAG,kBAAkB,CAEjG;AAED,qCAAqC;AAErC;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,GAAG,GAAG;oBAUX,MAAM;mBAA+B,MAAM;cANhF,MAAM;aACR,MAAM;;;iBAWG,MAAM;0BACY,MAAM;sBACV,MAAM;cAd3B,MAAM;aACR,MAAM;;EAehC"}
|
package/dist/lib/config.js
CHANGED
|
@@ -3,7 +3,6 @@
|
|
|
3
3
|
* Reads the modular Worker environment bindings.
|
|
4
4
|
*/
|
|
5
5
|
export function loadConfig(env) {
|
|
6
|
-
// Try new env vars first - need either legacy password or new auth config
|
|
7
6
|
if (env.SECRET) {
|
|
8
7
|
return loadFromEnvVars(env);
|
|
9
8
|
}
|
|
@@ -41,7 +40,6 @@ function loadFromEnvVars(env) {
|
|
|
41
40
|
paymentProvider: env.STRIPE_SECRET_KEY ? 'stripe' : 'bank_transfer',
|
|
42
41
|
stripeSecretKey: env.STRIPE_SECRET_KEY,
|
|
43
42
|
stripeWebhookSecret: env.STRIPE_WEBHOOK_SECRET,
|
|
44
|
-
stripePublishableKey: env.STRIPE_PUBLISHABLE_KEY,
|
|
45
43
|
},
|
|
46
44
|
};
|
|
47
45
|
}
|
|
@@ -50,18 +48,13 @@ function loadFromEnvVars(env) {
|
|
|
50
48
|
* is toggled in email settings.
|
|
51
49
|
*/
|
|
52
50
|
export function getAdminConfig() {
|
|
53
|
-
return {
|
|
54
|
-
loginMethod: 'password',
|
|
55
|
-
};
|
|
51
|
+
return {};
|
|
56
52
|
}
|
|
57
53
|
/** Get Emails module configuration. */
|
|
58
54
|
export function getEmailsConfig(env) {
|
|
59
55
|
return loadConfig(env).emails;
|
|
60
56
|
}
|
|
61
57
|
/** Get Shop module configuration. */
|
|
62
|
-
export function getShopConfig(env) {
|
|
63
|
-
return loadConfig(env).shop;
|
|
64
|
-
}
|
|
65
58
|
/**
|
|
66
59
|
* Get GitHub configuration from environment variables
|
|
67
60
|
* Used by CMS, emails and other modules for GitHub storage
|
|
@@ -1,15 +1,12 @@
|
|
|
1
|
+
import type { EmailTemplateConfig } from '@hintergrund/runtime-contracts';
|
|
1
2
|
export interface RenderEmailTemplateOptions {
|
|
2
3
|
bodyHtml: string;
|
|
3
|
-
|
|
4
|
+
/** Always derived from the project's brand via emailTemplateFromBrand. */
|
|
5
|
+
template: EmailTemplateConfig;
|
|
4
6
|
logoDataUrl?: string;
|
|
5
7
|
unsubscribeUrl?: string;
|
|
6
8
|
footerHtml?: string;
|
|
7
9
|
}
|
|
8
|
-
export
|
|
9
|
-
html: string;
|
|
10
|
-
primaryColor: string;
|
|
11
|
-
footerHtml: string;
|
|
12
|
-
}
|
|
13
|
-
export declare const DEFAULT_EMAIL_TEMPLATE: EmailTemplateConfig;
|
|
10
|
+
export type { EmailTemplateConfig } from '@hintergrund/runtime-contracts';
|
|
14
11
|
export declare function renderEmailTemplate(options: RenderEmailTemplateOptions): string;
|
|
15
12
|
//# sourceMappingURL=email-template.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-template.d.ts","sourceRoot":"","sources":["../../src/lib/email-template.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,
|
|
1
|
+
{"version":3,"file":"email-template.d.ts","sourceRoot":"","sources":["../../src/lib/email-template.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAE1E,MAAM,WAAW,0BAA0B;IAC1C,QAAQ,EAAE,MAAM,CAAC;IACjB,0EAA0E;IAC1E,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,UAAU,CAAC,EAAE,MAAM,CAAC;CACpB;AAED,YAAY,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AAqB1E,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,0BAA0B,GAAG,MAAM,CAkB/E"}
|
|
@@ -1,36 +1,14 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
html: `<!doctype html>
|
|
5
|
-
<html>
|
|
6
|
-
<head>
|
|
7
|
-
<meta charset="utf-8">
|
|
8
|
-
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
9
|
-
</head>
|
|
10
|
-
<body style="margin:0;padding:0;background:#f6f8fa;">
|
|
11
|
-
<div style="background:#f6f8fa;padding:40px 0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Arial,sans-serif;font-size:14px;line-height:1.5;color:#24292f;">
|
|
12
|
-
<div style="max-width:580px;margin:0 auto;background:#ffffff;border:1px solid #d0d7de;border-radius:8px;padding:32px;">
|
|
13
|
-
{{logo}}
|
|
14
|
-
{{content}}
|
|
15
|
-
</div>
|
|
16
|
-
<div style="max-width:580px;margin:20px auto 0;padding:0 32px;font-size:12px;color:#6e7781;text-align:center;">
|
|
17
|
-
{{footer}}
|
|
18
|
-
{{unsubscribe}}
|
|
19
|
-
</div>
|
|
20
|
-
</div>
|
|
21
|
-
</body>
|
|
22
|
-
</html>`,
|
|
23
|
-
};
|
|
24
|
-
function cleanCssValue(value, fallback) {
|
|
25
|
-
return value && !/[<>"']/.test(value) ? value : fallback;
|
|
1
|
+
/** Brand colors are validated as #rrggbb; refuse anything else rather than interpolate it into style="". */
|
|
2
|
+
function safeColor(value) {
|
|
3
|
+
return value && /^#[\da-f]{6}$/i.test(value) ? value : 'inherit';
|
|
26
4
|
}
|
|
27
|
-
function styleEmailBody(bodyHtml, primaryColor) {
|
|
5
|
+
function styleEmailBody(bodyHtml, primaryColor, headingFont) {
|
|
28
6
|
return bodyHtml
|
|
29
7
|
.replace(/<(h[1-4])([^>]*)>/gi, (match, tag, attributes) => {
|
|
30
8
|
if (/style=/i.test(attributes)) {
|
|
31
|
-
return match.replace(/style=(["'])(.*?)\1/i, `style=$1color:${primaryColor};$2$1`);
|
|
9
|
+
return match.replace(/style=(["'])(.*?)\1/i, `style=$1color:${primaryColor};font-family:${headingFont.replaceAll("'", '')};$2$1`);
|
|
32
10
|
}
|
|
33
|
-
return `<${tag}${attributes} style="color:${primaryColor};">`;
|
|
11
|
+
return `<${tag}${attributes} style="color:${primaryColor};font-family:${headingFont};">`;
|
|
34
12
|
})
|
|
35
13
|
.replace(/<img([^>]*)>/gi, (match) => {
|
|
36
14
|
if (/style=/i.test(match))
|
|
@@ -39,9 +17,9 @@ function styleEmailBody(bodyHtml, primaryColor) {
|
|
|
39
17
|
});
|
|
40
18
|
}
|
|
41
19
|
export function renderEmailTemplate(options) {
|
|
42
|
-
const template =
|
|
43
|
-
const primaryColor =
|
|
44
|
-
const bodyHtml = styleEmailBody(options.bodyHtml, primaryColor);
|
|
20
|
+
const template = options.template;
|
|
21
|
+
const primaryColor = safeColor(template.primaryColor);
|
|
22
|
+
const bodyHtml = styleEmailBody(options.bodyHtml, primaryColor, template.headingFont);
|
|
45
23
|
const logoHtml = options.logoDataUrl
|
|
46
24
|
? `<div style="text-align:center;margin:0 0 20px 0;"><img src="${options.logoDataUrl}" alt="Logo" style="max-width:120px;max-height:80px;height:auto;"></div>`
|
|
47
25
|
: '';
|
package/dist/lib/email.d.ts
CHANGED
|
@@ -2,7 +2,14 @@
|
|
|
2
2
|
* Provider-agnostic email sending utility using Plunk.
|
|
3
3
|
* Reads the API key from the Worker and sender details from GitHub-backed email settings.
|
|
4
4
|
*/
|
|
5
|
-
|
|
5
|
+
import type { Bindings } from '../index';
|
|
6
|
+
export interface SendEmailParams {
|
|
7
|
+
attachments?: Array<{
|
|
8
|
+
filename: string;
|
|
9
|
+
content: string;
|
|
10
|
+
contentType: string;
|
|
11
|
+
disposition?: 'attachment' | 'inline';
|
|
12
|
+
}>;
|
|
6
13
|
to: string;
|
|
7
14
|
toName?: string;
|
|
8
15
|
subject: string;
|
|
@@ -10,15 +17,17 @@ interface SendEmailParams {
|
|
|
10
17
|
from?: string;
|
|
11
18
|
fromName?: string;
|
|
12
19
|
replyTo?: string;
|
|
20
|
+
text?: string;
|
|
21
|
+
headers?: Record<string, string>;
|
|
22
|
+
idempotencyKey?: string;
|
|
13
23
|
}
|
|
14
|
-
export declare
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
export {};
|
|
24
|
+
export declare class EmailProviderError extends Error {
|
|
25
|
+
status: number;
|
|
26
|
+
reason?: string;
|
|
27
|
+
constructor(status: number, reason?: string);
|
|
28
|
+
}
|
|
29
|
+
export interface EmailReceipt {
|
|
30
|
+
providerId?: string;
|
|
31
|
+
}
|
|
32
|
+
export declare function sendEmail(env: Bindings, params: SendEmailParams): Promise<EmailReceipt>;
|
|
24
33
|
//# sourceMappingURL=email.d.ts.map
|
package/dist/lib/email.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAAA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"email.d.ts","sourceRoot":"","sources":["../../src/lib/email.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAGzC,MAAM,WAAW,eAAe;IAC/B,WAAW,CAAC,EAAE,KAAK,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAC;QAAC,WAAW,CAAC,EAAE,YAAY,GAAG,QAAQ,CAAA;KAAE,CAAC,CAAC;IACvH,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,cAAc,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,qBAAa,kBAAmB,SAAQ,KAAK;IAC5C,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,MAAM,CAAC;gBACJ,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM;CAI3C;AACD,MAAM,WAAW,YAAY;IAAG,UAAU,CAAC,EAAE,MAAM,CAAA;CAAE;AAErD,wBAAsB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,eAAe,GAAG,OAAO,CAAC,YAAY,CAAC,CAW7F"}
|
package/dist/lib/email.js
CHANGED
|
@@ -3,7 +3,13 @@
|
|
|
3
3
|
* Reads the API key from the Worker and sender details from GitHub-backed email settings.
|
|
4
4
|
*/
|
|
5
5
|
import { readEmailSettings } from '../api/emails/handlers/settings.handler';
|
|
6
|
-
|
|
6
|
+
export class EmailProviderError extends Error {
|
|
7
|
+
constructor(status, reason) {
|
|
8
|
+
super(reason ? `Email provider returned ${status}: ${reason}` : `Email provider returned ${status}`);
|
|
9
|
+
this.status = status;
|
|
10
|
+
this.reason = reason;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
7
13
|
export async function sendEmail(env, params) {
|
|
8
14
|
const apiKey = env.API_KEY || env.PLUNK_SECRET_KEY;
|
|
9
15
|
const { settings } = await readEmailSettings(env);
|
|
@@ -14,7 +20,7 @@ export async function sendEmail(env, params) {
|
|
|
14
20
|
throw new Error('Plunk API key (API_KEY or PLUNK_SECRET_KEY) is not configured');
|
|
15
21
|
if (!fromEmail)
|
|
16
22
|
throw new Error('Email sender address is not configured');
|
|
17
|
-
|
|
23
|
+
return sendViaPlunk(apiKey, fromEmail, fromName, { ...params, replyTo });
|
|
18
24
|
}
|
|
19
25
|
async function sendViaPlunk(apiKey, fromEmail, fromName, params) {
|
|
20
26
|
const body = {
|
|
@@ -22,35 +28,39 @@ async function sendViaPlunk(apiKey, fromEmail, fromName, params) {
|
|
|
22
28
|
subject: params.subject,
|
|
23
29
|
body: params.html,
|
|
24
30
|
type: 'html',
|
|
25
|
-
|
|
26
|
-
from: fromName ?
|
|
31
|
+
// Transactional messages must not change the recipient's marketing consent.
|
|
32
|
+
from: fromName ? { name: fromName, email: fromEmail } : fromEmail,
|
|
27
33
|
};
|
|
28
34
|
if (params.toName)
|
|
29
|
-
body.
|
|
35
|
+
body.to = { name: params.toName, email: params.to };
|
|
36
|
+
if (params.attachments?.length)
|
|
37
|
+
body.attachments = params.attachments;
|
|
30
38
|
if (params.replyTo)
|
|
31
39
|
body.reply = params.replyTo;
|
|
40
|
+
if (params.headers)
|
|
41
|
+
body.headers = params.headers;
|
|
32
42
|
const response = await fetch('https://next-api.useplunk.com/v1/send', {
|
|
33
43
|
method: 'POST',
|
|
34
44
|
headers: {
|
|
35
45
|
Authorization: `Bearer ${apiKey}`,
|
|
36
46
|
'Content-Type': 'application/json',
|
|
47
|
+
...(params.idempotencyKey ? { 'Idempotency-Key': params.idempotencyKey } : {}),
|
|
37
48
|
},
|
|
49
|
+
signal: AbortSignal.timeout(20000),
|
|
38
50
|
body: JSON.stringify(body),
|
|
39
51
|
});
|
|
40
52
|
if (!response.ok) {
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
// Rejection reasons (e.g. suppressed or unsubscribed recipient) are small API
|
|
54
|
+
// error bodies. Bound the read so a misbehaving upstream cannot exhaust memory.
|
|
55
|
+
let reason;
|
|
56
|
+
if (Number(response.headers.get('content-length') || 0) <= 8192) {
|
|
57
|
+
reason = (await response.text()).slice(0, 300) || undefined;
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
await response.body?.cancel();
|
|
61
|
+
}
|
|
62
|
+
throw new EmailProviderError(response.status, reason);
|
|
43
63
|
}
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
export async function sendEmailOtp(params) {
|
|
47
|
-
const html = renderEmailTemplate({
|
|
48
|
-
bodyHtml: `
|
|
49
|
-
<h1 style="font-size:24px;font-weight:600;text-align:center;margin-bottom:24px;">Sign in to Hintergrund</h1>
|
|
50
|
-
<p style="margin-bottom:16px;text-align:center;color:#57606a;">Enter this one-time code to sign in. It expires in 15 minutes.</p>
|
|
51
|
-
<p style="margin:0 0 32px;text-align:center;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:32px;font-weight:700;letter-spacing:0.2em;color:#1f2328;">${params.code}</p>
|
|
52
|
-
<p style="font-size:14px;color:#57606a;text-align:center;">If you didn't request this code, you can safely ignore this email.</p>`,
|
|
53
|
-
template: { primaryColor: '#1f883d', footerHtml: '' },
|
|
54
|
-
});
|
|
55
|
-
await sendEmail({ API_KEY: params.apiKey, FROM_EMAIL: params.fromEmail, FROM_NAME: params.fromName }, { to: params.to, subject: `${params.code} is your Hintergrund sign-in code`, html });
|
|
64
|
+
const result = await response.json();
|
|
65
|
+
return { providerId: result.data?.emails?.[0]?.email };
|
|
56
66
|
}
|