@marktiderman/genesis-notifications 0.3.2 → 0.4.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/README.md CHANGED
@@ -71,8 +71,14 @@ test, and the `functions/genesis-notifications` Edge Function template.
71
71
  });
72
72
  ```
73
73
 
74
- 4. Mirror it on deploy: `await syncNotificationTypes(admin, notifications)` (types left out are
75
- retired, never deleted).
74
+ 4. Mirror it at migration time: name the registry in `genesis.config.json`
75
+ (`"notifications": { "registry": "src/notifications.ts" }`) or pass `--notifications <file>`, and
76
+ `genesis migrate` writes a `<timestamp>_genesis_notification_types.sql` that adds and updates the
77
+ types whenever they change. They are in place once every migration has run, so a trigger never
78
+ meets an unknown type before the deploy. The module is imported, so keep it free of side effects.
79
+ Run it after changing the registry, and commit the file. Keep
80
+ `await syncNotificationTypes(admin, notifications)` on deploy: it is what retires types left out
81
+ (never deleted); the migrations never retire one.
76
82
  5. Deploy `functions/genesis-notifications` (`--no-verify-jwt`), and schedule `POST …/run`
77
83
  every minute and `POST …/receipts` every 15 minutes with
78
84
  `Authorization: Bearer <GENESIS_NOTIFICATIONS_CRON_SECRET>`, and
@@ -204,6 +210,16 @@ before the job settles still finds it.
204
210
  The provider is chosen per job (`email.providerFor`), so a tenant-owned Resend key kept in
205
211
  Vault can be added later without changing the runner. It isn't built.
206
212
 
213
+ ## Receiving email
214
+
215
+ `createInboundEmailHandler` (`/server`) is the way in: it verifies Resend's `email.received`
216
+ webhook (signed like its other webhooks), fetches the full message (`GET /emails/receiving/{id}`)
217
+ and hands an `InboundEmail` (Message-ID, In-Reply-To, References, from, to, subject, text, SPF,
218
+ DKIM and DMARC results, attachment names) to the first route that returns true. Routes are
219
+ plain functions: genesis-support's `supportEmailRoute` files tickets; an agent's inbox, an
220
+ onboarding address or a forward are routes of your own. A route that throws answers 502 so
221
+ Resend retries; an email no route takes goes to `onUnrouted`.
222
+
207
223
  ## Push
208
224
 
209
225
  The device side stays in genesis-native's push block: registration, the permission, routing, the
package/dist/server.d.ts CHANGED
@@ -597,6 +597,89 @@ declare function emailEventOf(payload: unknown): {
597
597
  permanent: boolean;
598
598
  } | null;
599
599
 
600
+ /**
601
+ * Receiving email: one webhook, many uses. Resend posts `email.received` (signed like its other
602
+ * webhooks); `createInboundEmailHandler` verifies it, fetches the full message
603
+ * (`GET /emails/receiving/{id}`) and hands it to the first route that takes it: support tickets
604
+ * (genesis-support's `supportEmailRoute`), an agent's inbox, an onboarding address, a forward.
605
+ * Sending stays the notifier's (`resendProvider`); this is the way in. SMS will route the same way.
606
+ *
607
+ * ```ts
608
+ * const handle = createInboundEmailHandler({
609
+ * webhookSecret: process.env.RESEND_INBOUND_WEBHOOK_SECRET!,
610
+ * apiKey: process.env.RESEND_API_KEY!,
611
+ * routes: [supportEmailRoute(admin, { addresses: ["support@acme.test"] })],
612
+ * });
613
+ * export const POST = ({ request }) => handle(request);
614
+ * ```
615
+ */
616
+
617
+ declare const RESEND_RECEIVING_API = "https://api.resend.com/emails/receiving";
618
+ /** One received email, as routes see it. Addresses are lowercased; ids have no angle brackets. */
619
+ interface InboundEmail {
620
+ /** Resend's id for the received email. */
621
+ providerId: string;
622
+ /** The RFC 5322 Message-ID. */
623
+ messageId: string | null;
624
+ inReplyTo: string | null;
625
+ references: string[];
626
+ from: {
627
+ email: string;
628
+ name: string | null;
629
+ };
630
+ to: string[];
631
+ cc: string[];
632
+ subject: string;
633
+ text: string;
634
+ html: string | null;
635
+ /** SPF, DKIM and DMARC results as Resend reported them (null for older emails). */
636
+ authentication: Record<string, unknown> | null;
637
+ attachments: Array<{
638
+ id: string;
639
+ filename: string;
640
+ contentType: string;
641
+ size: number;
642
+ }>;
643
+ receivedAt: string;
644
+ /**
645
+ * Sent by a machine: Auto-Submitted other than "no", Precedence bulk/junk/list/auto_reply, or an
646
+ * X-Autoreply/X-Autorespond header (out-of-office answers, bounces, lists). Routes should not
647
+ * answer or open work for these.
648
+ */
649
+ autoSubmitted: boolean;
650
+ }
651
+ /**
652
+ * Takes an email or passes. Return true when it handled it (filed, answered, forwarded): later
653
+ * routes don't see it. Throw to make Resend retry the webhook.
654
+ */
655
+ type InboundEmailRoute = (email: InboundEmail) => Promise<boolean> | boolean;
656
+ interface InboundEmailHandlerOptions extends HttpDeps {
657
+ /** The receiving webhook's signing secret (`whsec_…`). */
658
+ webhookSecret: string;
659
+ /** A Resend key that can read received email. */
660
+ apiKey: string;
661
+ routes: readonly InboundEmailRoute[];
662
+ /** An email no route took. Default: dropped (logged by the caller if it wants). */
663
+ onUnrouted?: (email: InboundEmail) => void | Promise<void>;
664
+ endpoint?: string;
665
+ now?: () => number;
666
+ }
667
+ /** "Pat <Pat@Example.test>" → { email: "pat@example.test", name: "Pat" }. */
668
+ declare function parseAddress(value: string): {
669
+ email: string;
670
+ name: string | null;
671
+ } | null;
672
+ /** Resend's received-email object as an `InboundEmail`; null when it has no usable sender. */
673
+ declare function inboundEmailOf(raw: Record<string, unknown>): InboundEmail | null;
674
+ /**
675
+ * The receiving webhook as a web-standard handler: 401 for an unsigned or stale request, 200 for
676
+ * anything handled or ignored, 502 when the message couldn't be fetched or a route threw (Resend
677
+ * retries).
678
+ *
679
+ * @stability Beta
680
+ */
681
+ declare function createInboundEmailHandler(options: InboundEmailHandlerOptions): (request: Request) => Promise<Response>;
682
+
600
683
  /**
601
684
  * Is a sender domain the tenant's, and ready to send from? An ownership TXT
602
685
  * record holding the tenant's own token (so one tenant can't verify another's
@@ -655,4 +738,4 @@ declare function isReservedDomain(domain: string, reserved: readonly (string | u
655
738
  */
656
739
  declare function checkSenderDomain(domain: string, options: DomainCheckOptions): Promise<DomainCheck>;
657
740
 
658
- export { type CancelInput, type ClaimedDevice, type ClaimedJob, type DomainCheck, type DomainCheckOptions, EXPO_RECEIPTS_BATCH, EXPO_RECEIPTS_URL, EXPO_SEND_BATCH, EXPO_SEND_URL, type EmailMessage, type EmailOptions, type EmailProvider, type EmailSendResult, EmailTemplate, type ExpoOptions, type HttpDeps, type NotificationRunner, type NotificationRunnerOptions, type NotificationStore, NotificationStoreError, type NotificationsHandlerOptions, type NotifyOptions, type PushMessage, type PushProvider, type PushReceipt, type PushTicket, type PushTicketRow, REQUEST_TIMEOUT_MS, RESEND_API, RESEND_DEFAULT_PER_SECOND, type RateLimiter, type RateLimiterOptions, type RenderedEmail, type ResendOptions, type RpcClient, SECRET_LINK_PLACEHOLDER, SENDER_OWNERSHIP_HOST, SecretLinkError, type SecretLinkRef, type SecretLinks, SendError, type SenderIdentity, type SettleOutcome, type UnsubscribeClaims, WEBHOOK_TOLERANCE_SECONDS, cancelNotification, checkSenderDomain, createNotificationRunner, createNotificationsHandler, createRateLimiter, createUnsubscribeToken, emailEventOf, emailHash, expoErrorCode, expoPushProvider, isReservedDomain, isRetryableStatus, notify, refusedOutright, resendProvider, resolveSecretLink, retryAfterSeconds, senderOwnershipRecord, supabaseNotificationStore, syncNotificationTypes, unsubscribeHeaders, verifyResendWebhook, verifyUnsubscribeToken };
741
+ export { type CancelInput, type ClaimedDevice, type ClaimedJob, type DomainCheck, type DomainCheckOptions, EXPO_RECEIPTS_BATCH, EXPO_RECEIPTS_URL, EXPO_SEND_BATCH, EXPO_SEND_URL, type EmailMessage, type EmailOptions, type EmailProvider, type EmailSendResult, EmailTemplate, type ExpoOptions, type HttpDeps, type InboundEmail, type InboundEmailHandlerOptions, type InboundEmailRoute, type NotificationRunner, type NotificationRunnerOptions, type NotificationStore, NotificationStoreError, type NotificationsHandlerOptions, type NotifyOptions, type PushMessage, type PushProvider, type PushReceipt, type PushTicket, type PushTicketRow, REQUEST_TIMEOUT_MS, RESEND_API, RESEND_DEFAULT_PER_SECOND, RESEND_RECEIVING_API, type RateLimiter, type RateLimiterOptions, type RenderedEmail, type ResendOptions, type RpcClient, SECRET_LINK_PLACEHOLDER, SENDER_OWNERSHIP_HOST, SecretLinkError, type SecretLinkRef, type SecretLinks, SendError, type SenderIdentity, type SettleOutcome, type UnsubscribeClaims, WEBHOOK_TOLERANCE_SECONDS, cancelNotification, checkSenderDomain, createInboundEmailHandler, createNotificationRunner, createNotificationsHandler, createRateLimiter, createUnsubscribeToken, emailEventOf, emailHash, expoErrorCode, expoPushProvider, inboundEmailOf, isReservedDomain, isRetryableStatus, notify, parseAddress, refusedOutright, resendProvider, resolveSecretLink, retryAfterSeconds, senderOwnershipRecord, supabaseNotificationStore, syncNotificationTypes, unsubscribeHeaders, verifyResendWebhook, verifyUnsubscribeToken };
package/dist/server.js CHANGED
@@ -135,9 +135,9 @@ var SendError = class extends Error {
135
135
  function isRetryableStatus(status) {
136
136
  return status === 408 || status === 425 || status === 429 || status >= 500;
137
137
  }
138
- function retryAfterSeconds(header, fallback = 60, now = Date.now()) {
138
+ function retryAfterSeconds(header2, fallback = 60, now = Date.now()) {
139
139
  const clamp = (s) => Math.min(86400, Math.max(1, s));
140
- const value = header?.trim();
140
+ const value = header2?.trim();
141
141
  if (value && /^\d+$/.test(value)) return clamp(Number(value));
142
142
  if (value && /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} [A-Z][a-z]{2} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)) {
143
143
  const at = Date.parse(value);
@@ -823,8 +823,8 @@ function createNotificationsHandler(options) {
823
823
  const copy = { ...COPY, ...options.copy };
824
824
  const enc = new TextEncoder();
825
825
  const authorized = (request) => {
826
- const header = request.headers.get("authorization") ?? "";
827
- const given = header.startsWith("Bearer ") ? header.slice(7) : "";
826
+ const header2 = request.headers.get("authorization") ?? "";
827
+ const given = header2.startsWith("Bearer ") ? header2.slice(7) : "";
828
828
  return timingSafeEqual(enc.encode(given), enc.encode(options.cronSecret));
829
829
  };
830
830
  const log = (m) => {
@@ -990,6 +990,86 @@ function resendProvider(options) {
990
990
  };
991
991
  }
992
992
 
993
- export { EXPO_RECEIPTS_BATCH, EXPO_RECEIPTS_URL, EXPO_SEND_BATCH, EXPO_SEND_URL, NotificationStoreError, REQUEST_TIMEOUT_MS, RESEND_API, RESEND_DEFAULT_PER_SECOND, SECRET_LINK_PLACEHOLDER, SENDER_OWNERSHIP_HOST, SecretLinkError, SendError, WEBHOOK_TOLERANCE_SECONDS, cancelNotification, canonicalJson, checkSenderDomain, createNotificationRunner, createNotificationsHandler, createRateLimiter, createUnsubscribeToken, defaultEmailTemplate, displayName, emailEventOf, emailHash, escapeHtml, expoErrorCode, expoPushProvider, headerSafe, isReservedDomain, isRetryableStatus, isSafeAddress, notify, refusedOutright, resendProvider, resolveSecretLink, retryAfterSeconds, senderOwnershipRecord, supabaseNotificationStore, syncNotificationTypes, unsubscribeHeaders, verifyResendWebhook, verifyUnsubscribeToken };
993
+ // src/server/inbound.ts
994
+ var RESEND_RECEIVING_API = "https://api.resend.com/emails/receiving";
995
+ var ADDRESS = /<?([^<>\s]+@[^<>\s]+)>?\s*$/;
996
+ var unbracket = (id) => typeof id === "string" && id.trim() ? id.trim().replace(/^<|>$/g, "") : null;
997
+ function parseAddress(value) {
998
+ const m = ADDRESS.exec(value.trim());
999
+ if (!m) return null;
1000
+ const name = value.slice(0, value.lastIndexOf(m[0])).trim().replace(/^"|"$/g, "");
1001
+ return { email: m[1].toLowerCase(), name: name || null };
1002
+ }
1003
+ var header = (headers, name) => {
1004
+ if (!headers || typeof headers !== "object") return null;
1005
+ for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === name && typeof v === "string") return v;
1006
+ return null;
1007
+ };
1008
+ function inboundEmailOf(raw) {
1009
+ const from = parseAddress(String(raw.from ?? ""));
1010
+ if (!from) return null;
1011
+ const list = (v) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).map((a) => parseAddress(String(a))?.email).filter((a) => !!a);
1012
+ const refs = header(raw.headers, "references");
1013
+ return {
1014
+ providerId: String(raw.id ?? ""),
1015
+ messageId: unbracket(raw.message_id),
1016
+ inReplyTo: unbracket(raw.in_reply_to ?? header(raw.headers, "in-reply-to")),
1017
+ references: refs ? refs.split(/\s+/).map(unbracket).filter((r) => !!r) : [],
1018
+ from,
1019
+ to: list(raw.to),
1020
+ cc: list(raw.cc),
1021
+ subject: typeof raw.subject === "string" ? raw.subject : "",
1022
+ text: typeof raw.text === "string" ? raw.text : "",
1023
+ html: typeof raw.html === "string" ? raw.html : null,
1024
+ authentication: raw.authentication && typeof raw.authentication === "object" ? raw.authentication : null,
1025
+ attachments: (Array.isArray(raw.attachments) ? raw.attachments : []).map((a) => ({
1026
+ id: String(a.id ?? ""),
1027
+ filename: String(a.filename ?? ""),
1028
+ contentType: String(a.content_type ?? ""),
1029
+ size: Number(a.size ?? 0)
1030
+ })),
1031
+ receivedAt: typeof raw.created_at === "string" ? raw.created_at : (/* @__PURE__ */ new Date()).toISOString(),
1032
+ autoSubmitted: (header(raw.headers, "auto-submitted") ?? "no").toLowerCase() !== "no" || /^(bulk|junk|list|auto_reply)$/i.test(header(raw.headers, "precedence") ?? "") || header(raw.headers, "x-autoreply") !== null || header(raw.headers, "x-autorespond") !== null
1033
+ };
1034
+ }
1035
+ var MAX_WEBHOOK_BYTES = 256e3;
1036
+ function createInboundEmailHandler(options) {
1037
+ const endpoint = options.endpoint ?? RESEND_RECEIVING_API;
1038
+ return async (request) => {
1039
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_WEBHOOK_BYTES) return new Response("too large", { status: 413 });
1040
+ const body = await request.text();
1041
+ if (body.length > MAX_WEBHOOK_BYTES) return new Response("too large", { status: 413 });
1042
+ if (!await verifyResendWebhook(options.webhookSecret, request.headers, body, options.now?.() ?? Date.now())) {
1043
+ return new Response("unsigned", { status: 401 });
1044
+ }
1045
+ let event;
1046
+ try {
1047
+ event = JSON.parse(body);
1048
+ } catch {
1049
+ return new Response("bad json", { status: 400 });
1050
+ }
1051
+ if (event.type !== "email.received" || !event.data?.email_id) return new Response("ignored", { status: 200 });
1052
+ let email;
1053
+ try {
1054
+ const res = await timedFetch(options, `${endpoint}/${encodeURIComponent(event.data.email_id)}`, {
1055
+ headers: { authorization: `Bearer ${options.apiKey}` }
1056
+ });
1057
+ if (!res.ok) return new Response(`fetch ${res.status}`, { status: 502 });
1058
+ email = inboundEmailOf(await res.json());
1059
+ } catch {
1060
+ return new Response("fetch failed", { status: 502 });
1061
+ }
1062
+ if (!email) return new Response("no sender", { status: 200 });
1063
+ try {
1064
+ for (const route of options.routes) if (await route(email)) return new Response("routed", { status: 200 });
1065
+ await options.onUnrouted?.(email);
1066
+ return new Response("unrouted", { status: 200 });
1067
+ } catch {
1068
+ return new Response("route failed", { status: 502 });
1069
+ }
1070
+ };
1071
+ }
1072
+
1073
+ export { EXPO_RECEIPTS_BATCH, EXPO_RECEIPTS_URL, EXPO_SEND_BATCH, EXPO_SEND_URL, NotificationStoreError, REQUEST_TIMEOUT_MS, RESEND_API, RESEND_DEFAULT_PER_SECOND, RESEND_RECEIVING_API, SECRET_LINK_PLACEHOLDER, SENDER_OWNERSHIP_HOST, SecretLinkError, SendError, WEBHOOK_TOLERANCE_SECONDS, cancelNotification, canonicalJson, checkSenderDomain, createInboundEmailHandler, createNotificationRunner, createNotificationsHandler, createRateLimiter, createUnsubscribeToken, defaultEmailTemplate, displayName, emailEventOf, emailHash, escapeHtml, expoErrorCode, expoPushProvider, headerSafe, inboundEmailOf, isReservedDomain, isRetryableStatus, isSafeAddress, notify, parseAddress, refusedOutright, resendProvider, resolveSecretLink, retryAfterSeconds, senderOwnershipRecord, supabaseNotificationStore, syncNotificationTypes, unsubscribeHeaders, verifyResendWebhook, verifyUnsubscribeToken };
994
1074
  //# sourceMappingURL=server.js.map
995
1075
  //# sourceMappingURL=server.js.map