@marktiderman/genesis-notifications 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,7 @@ import {
22
22
  expoPushProvider,
23
23
  resendProvider,
24
24
  supabaseNotificationStore,
25
- } from "npm:@marktiderman/genesis-notifications@^0.1.0/server";
25
+ } from "npm:@marktiderman/genesis-notifications@^0.3.0/server";
26
26
  import { notifications, emailTemplates, secretLinks } from "./notifications.ts";
27
27
 
28
28
  const env = (name: string) => Deno.env.get(name) ?? "";
@@ -4,8 +4,8 @@
4
4
  // This starter list has the one type every app needs: the admin's test,
5
5
  // spread from the package so it stays critical (as the migration seeds it) and
6
6
  // a preference can never silence Admin -> Send a test.
7
- import { GENESIS_TEST_CATEGORY, GENESIS_TEST_TYPE, defineNotifications } from "npm:@marktiderman/genesis-notifications@^0.1.0";
8
- import type { EmailTemplate, SecretLinks } from "npm:@marktiderman/genesis-notifications@^0.1.0/server";
7
+ import { GENESIS_TEST_CATEGORY, GENESIS_TEST_TYPE, defineNotifications } from "npm:@marktiderman/genesis-notifications@^0.3.0";
8
+ import type { EmailTemplate, SecretLinks } from "npm:@marktiderman/genesis-notifications@^0.3.0/server";
9
9
 
10
10
  export const notifications = defineNotifications({
11
11
  categories: { ...GENESIS_TEST_CATEGORY },
package/package.json CHANGED
@@ -1,10 +1,25 @@
1
1
  {
2
2
  "name": "@marktiderman/genesis-notifications",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "sideEffects": false,
7
7
  "description": "One notifier for Genesis apps: a domain (chat, forms, sites, support) says who and what; this decides how and when. defineNotifications registers types (category, channels, critical, transactional, device action categories, Android channels); notify() queues them through a security-definer SQL function; the in-app feed is also the outbox; one runner (claim with SKIP LOCKED, retries with jittered backoff, deferrals) sends Expo push (batches of 100, receipts, dead tokens pruned, private previews) and Resend email (rendered once for byte-identical retries, tenant sender identities, RFC 8058 one-click unsubscribe, bounce and complaint suppression); preferences by category and channel with tenant defaults and quiet hours across daylight saving; secret links built at send time; erasure. Hooks for React and React Native, a web bell, feed, preferences matrix and admin views on genesis-ui, a native feed on genesis-ui-native. Part of the Genesis framework.",
8
+ "keywords": [
9
+ "genesis",
10
+ "genesis-framework",
11
+ "notifications",
12
+ "push",
13
+ "email",
14
+ "in-app",
15
+ "inbox",
16
+ "preferences",
17
+ "unsubscribe"
18
+ ],
19
+ "homepage": "https://github.com/marktiderman/genesis/tree/main/packages/notifications#readme",
20
+ "bugs": {
21
+ "url": "https://github.com/marktiderman/genesis/issues"
22
+ },
8
23
  "repository": {
9
24
  "type": "git",
10
25
  "url": "git+https://github.com/marktiderman/genesis.git",
@@ -78,13 +93,13 @@
78
93
  "README.md"
79
94
  ],
80
95
  "dependencies": {
81
- "@marktiderman/genesis-features": "^0.6.1"
96
+ "@marktiderman/genesis-features": "^0.8.0"
82
97
  },
83
98
  "peerDependencies": {
84
99
  "@marktiderman/genesis-core": ">=1.17.0 <3.0.0",
85
100
  "@marktiderman/genesis-native": ">=0.2.0 <1.0.0",
86
101
  "@marktiderman/genesis-supabase": ">=0.7.0 <1.0.0",
87
- "@marktiderman/genesis-ui": "^2.22.0",
102
+ "@marktiderman/genesis-ui": "^2.25.1",
88
103
  "@marktiderman/genesis-ui-native": ">=2.9.0 <4.0.0",
89
104
  "@react-email/components": "^1.0.0",
90
105
  "@tanstack/react-query": "^5.0.0",
@@ -118,26 +133,29 @@
118
133
  }
119
134
  },
120
135
  "devDependencies": {
121
- "@marktiderman/genesis-core": "^2.0.0",
122
- "@marktiderman/genesis-native": "^0.5.1",
123
- "@marktiderman/genesis-supabase": "^0.10.0",
124
- "@marktiderman/genesis-ui": "^2.22.0",
125
- "@marktiderman/genesis-ui-native": "^3.0.0",
136
+ "@marktiderman/genesis-core": "^2.4.0",
137
+ "@marktiderman/genesis-native": "^0.6.0",
138
+ "@marktiderman/genesis-supabase": "^0.11.0",
139
+ "@marktiderman/genesis-ui": "^2.25.1",
140
+ "@marktiderman/genesis-ui-native": "^3.2.2",
126
141
  "@react-email/components": "1.0.12",
127
- "@tanstack/react-query": "^5.75.0",
142
+ "@tanstack/react-query": "^5.104.5",
128
143
  "@testing-library/react": "^16.3.2",
129
144
  "@types/node": "^22",
130
145
  "@types/react": "^19.2.14",
131
146
  "@types/react-dom": "^19.2.3",
132
- "happy-dom": "^20.9.0",
147
+ "happy-dom": "^21.0.4",
133
148
  "lucide-react": "^1.0.0",
134
149
  "react": "^19.2.5",
135
150
  "react-dom": "^19.2.5",
136
151
  "tsup": "^8.3.0",
137
152
  "typescript": "~6.0.3",
138
- "vitest": "^4.1.12"
153
+ "vitest": "^5.0.5"
139
154
  },
140
155
  "genesis": {
156
+ "layer": "primitive",
157
+ "group": "collaboration",
158
+ "owner": "@marktiderman",
141
159
  "blocks": {
142
160
  "notifications": {
143
161
  "feature": {
@@ -184,12 +202,36 @@
184
202
  "@tanstack/react-query@^5.0.0"
185
203
  ],
186
204
  "steps": [
187
- "Mirror your registry on deploy: syncNotificationTypes(adminClient, notifications) from @marktiderman/genesis-notifications/server.",
205
+ "Mirror your registry at migration time: set notifications.registry in genesis.config.json (or pass --notifications <file>) and genesis migrate writes a migration that adds and updates its types whenever they change. Keep syncNotificationTypes(adminClient, notifications) from @marktiderman/genesis-notifications/server on deploy: it retires types left out.",
188
206
  "Say who administers notifications: replace private.genesis_notifications_admin(uuid, uuid) in a migration of your own, after this one (genesis-notifications README, Admins).",
189
207
  "Deploy functions/genesis-notifications and schedule POST …/run every minute and POST …/receipts every 15 minutes, with GENESIS_NOTIFICATIONS_CRON_SECRET as the bearer token; point Resend's webhook at …/webhooks/resend.",
190
208
  "Coming from genesis-supabase's push migration (0005): stop calling genesis-push-send, and remove its pgTAP test (tests/database/*genesis_push.test.sql): two of its assertions describe the token takeover this migration closes."
191
209
  ]
192
210
  }
211
+ },
212
+ "doctor": {
213
+ "prefer": [
214
+ {
215
+ "id": "notify-through-notifier",
216
+ "need": "sending an email or push",
217
+ "level": "warn",
218
+ "forbid": {
219
+ "imports": [
220
+ "resend",
221
+ "@sendgrid/mail",
222
+ "nodemailer",
223
+ "postmark",
224
+ "web-push",
225
+ "firebase-admin/messaging",
226
+ "expo-server-sdk"
227
+ ]
228
+ },
229
+ "use": "notify() with the type registered in defineNotifications",
230
+ "import": "@marktiderman/genesis-notifications/server",
231
+ "docs": "https://github.com/marktiderman/genesis/blob/main/docs/NOTIFICATIONS.md",
232
+ "why": "One notifier decides channels, preferences, quiet hours and delivery; a direct email or push call skips all of them."
233
+ }
234
+ ]
193
235
  }
194
236
  },
195
237
  "scripts": {
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Receiving email: one webhook, many uses. Resend posts `email.received` (signed like its other
3
+ * webhooks); `createInboundEmailHandler` verifies it, fetches the full message
4
+ * (`GET /emails/receiving/{id}`) and hands it to the first route that takes it: support tickets
5
+ * (genesis-support's `supportEmailRoute`), an agent's inbox, an onboarding address, a forward.
6
+ * Sending stays the notifier's (`resendProvider`); this is the way in. SMS will route the same way.
7
+ *
8
+ * ```ts
9
+ * const handle = createInboundEmailHandler({
10
+ * webhookSecret: process.env.RESEND_INBOUND_WEBHOOK_SECRET!,
11
+ * apiKey: process.env.RESEND_API_KEY!,
12
+ * routes: [supportEmailRoute(admin, { addresses: ["support@acme.test"] })],
13
+ * });
14
+ * export const POST = ({ request }) => handle(request);
15
+ * ```
16
+ */
17
+ import { timedFetch, type HttpDeps } from "./errors";
18
+ import { verifyResendWebhook } from "./webhook";
19
+
20
+ export const RESEND_RECEIVING_API = "https://api.resend.com/emails/receiving";
21
+
22
+ /** One received email, as routes see it. Addresses are lowercased; ids have no angle brackets. */
23
+ export interface InboundEmail {
24
+ /** Resend's id for the received email. */
25
+ providerId: string;
26
+ /** The RFC 5322 Message-ID. */
27
+ messageId: string | null;
28
+ inReplyTo: string | null;
29
+ references: string[];
30
+ from: { email: string; name: string | null };
31
+ to: string[];
32
+ cc: string[];
33
+ subject: string;
34
+ text: string;
35
+ html: string | null;
36
+ /** SPF, DKIM and DMARC results as Resend reported them (null for older emails). */
37
+ authentication: Record<string, unknown> | null;
38
+ attachments: Array<{ id: string; filename: string; contentType: string; size: number }>;
39
+ receivedAt: string;
40
+ /**
41
+ * Sent by a machine: Auto-Submitted other than "no", Precedence bulk/junk/list/auto_reply, or an
42
+ * X-Autoreply/X-Autorespond header (out-of-office answers, bounces, lists). Routes should not
43
+ * answer or open work for these.
44
+ */
45
+ autoSubmitted: boolean;
46
+ }
47
+
48
+ /**
49
+ * Takes an email or passes. Return true when it handled it (filed, answered, forwarded): later
50
+ * routes don't see it. Throw to make Resend retry the webhook.
51
+ */
52
+ export type InboundEmailRoute = (email: InboundEmail) => Promise<boolean> | boolean;
53
+
54
+ export interface InboundEmailHandlerOptions extends HttpDeps {
55
+ /** The receiving webhook's signing secret (`whsec_…`). */
56
+ webhookSecret: string;
57
+ /** A Resend key that can read received email. */
58
+ apiKey: string;
59
+ routes: readonly InboundEmailRoute[];
60
+ /** An email no route took. Default: dropped (logged by the caller if it wants). */
61
+ onUnrouted?: (email: InboundEmail) => void | Promise<void>;
62
+ endpoint?: string;
63
+ now?: () => number;
64
+ }
65
+
66
+ const ADDRESS = /<?([^<>\s]+@[^<>\s]+)>?\s*$/;
67
+ const unbracket = (id: unknown) => (typeof id === "string" && id.trim() ? id.trim().replace(/^<|>$/g, "") : null);
68
+
69
+ /** "Pat <Pat@Example.test>" → { email: "pat@example.test", name: "Pat" }. */
70
+ export function parseAddress(value: string): { email: string; name: string | null } | null {
71
+ const m = ADDRESS.exec(value.trim());
72
+ if (!m) return null;
73
+ const name = value.slice(0, value.lastIndexOf(m[0])).trim().replace(/^"|"$/g, "");
74
+ return { email: m[1]!.toLowerCase(), name: name || null };
75
+ }
76
+
77
+ const header = (headers: unknown, name: string): string | null => {
78
+ if (!headers || typeof headers !== "object") return null;
79
+ for (const [k, v] of Object.entries(headers as Record<string, unknown>)) if (k.toLowerCase() === name && typeof v === "string") return v;
80
+ return null;
81
+ };
82
+
83
+ /** Resend's received-email object as an `InboundEmail`; null when it has no usable sender. */
84
+ export function inboundEmailOf(raw: Record<string, unknown>): InboundEmail | null {
85
+ const from = parseAddress(String(raw.from ?? ""));
86
+ if (!from) return null;
87
+ const list = (v: unknown) => (Array.isArray(v) ? v : typeof v === "string" ? [v] : []).map((a) => parseAddress(String(a))?.email).filter((a): a is string => !!a);
88
+ const refs = header(raw.headers, "references");
89
+ return {
90
+ providerId: String(raw.id ?? ""),
91
+ messageId: unbracket(raw.message_id),
92
+ inReplyTo: unbracket(raw.in_reply_to ?? header(raw.headers, "in-reply-to")),
93
+ references: refs ? refs.split(/\s+/).map(unbracket).filter((r): r is string => !!r) : [],
94
+ from,
95
+ to: list(raw.to),
96
+ cc: list(raw.cc),
97
+ subject: typeof raw.subject === "string" ? raw.subject : "",
98
+ text: typeof raw.text === "string" ? raw.text : "",
99
+ html: typeof raw.html === "string" ? raw.html : null,
100
+ authentication: raw.authentication && typeof raw.authentication === "object" ? (raw.authentication as Record<string, unknown>) : null,
101
+ attachments: (Array.isArray(raw.attachments) ? raw.attachments : []).map((a: Record<string, unknown>) => ({
102
+ id: String(a.id ?? ""),
103
+ filename: String(a.filename ?? ""),
104
+ contentType: String(a.content_type ?? ""),
105
+ size: Number(a.size ?? 0),
106
+ })),
107
+ receivedAt: typeof raw.created_at === "string" ? raw.created_at : new Date().toISOString(),
108
+ autoSubmitted:
109
+ (header(raw.headers, "auto-submitted") ?? "no").toLowerCase() !== "no" ||
110
+ /^(bulk|junk|list|auto_reply)$/i.test(header(raw.headers, "precedence") ?? "") ||
111
+ header(raw.headers, "x-autoreply") !== null ||
112
+ header(raw.headers, "x-autorespond") !== null,
113
+ };
114
+ }
115
+
116
+ /** The webhook body is a small event; anything bigger is refused before its signature is checked. */
117
+ const MAX_WEBHOOK_BYTES = 256_000;
118
+
119
+ /**
120
+ * The receiving webhook as a web-standard handler: 401 for an unsigned or stale request, 200 for
121
+ * anything handled or ignored, 502 when the message couldn't be fetched or a route threw (Resend
122
+ * retries).
123
+ *
124
+ * @stability Beta
125
+ */
126
+ export function createInboundEmailHandler(options: InboundEmailHandlerOptions): (request: Request) => Promise<Response> {
127
+ const endpoint = options.endpoint ?? RESEND_RECEIVING_API;
128
+ return async (request) => {
129
+ if (Number(request.headers.get("content-length") ?? 0) > MAX_WEBHOOK_BYTES) return new Response("too large", { status: 413 });
130
+ const body = await request.text();
131
+ if (body.length > MAX_WEBHOOK_BYTES) return new Response("too large", { status: 413 });
132
+ if (!(await verifyResendWebhook(options.webhookSecret, request.headers, body, options.now?.() ?? Date.now()))) {
133
+ return new Response("unsigned", { status: 401 });
134
+ }
135
+ let event: { type?: string; data?: { email_id?: string } };
136
+ try {
137
+ event = JSON.parse(body);
138
+ } catch {
139
+ return new Response("bad json", { status: 400 });
140
+ }
141
+ if (event.type !== "email.received" || !event.data?.email_id) return new Response("ignored", { status: 200 });
142
+ let email: InboundEmail | null;
143
+ try {
144
+ const res = await timedFetch(options, `${endpoint}/${encodeURIComponent(event.data.email_id)}`, {
145
+ headers: { authorization: `Bearer ${options.apiKey}` },
146
+ });
147
+ if (!res.ok) return new Response(`fetch ${res.status}`, { status: 502 });
148
+ email = inboundEmailOf((await res.json()) as Record<string, unknown>);
149
+ } catch {
150
+ return new Response("fetch failed", { status: 502 });
151
+ }
152
+ if (!email) return new Response("no sender", { status: 200 });
153
+ try {
154
+ for (const route of options.routes) if (await route(email)) return new Response("routed", { status: 200 });
155
+ await options.onUnrouted?.(email);
156
+ return new Response("unrouted", { status: 200 });
157
+ } catch {
158
+ return new Response("route failed", { status: 502 });
159
+ }
160
+ };
161
+ }
@@ -42,6 +42,7 @@ export { resendProvider, RESEND_API, RESEND_DEFAULT_PER_SECOND, type EmailMessag
42
42
  export { resolveSecretLink, SecretLinkError, SECRET_LINK_PLACEHOLDER, type SecretLinkRef, type SecretLinks } from "./secret-links";
43
43
  export { createUnsubscribeToken, verifyUnsubscribeToken, unsubscribeHeaders, emailHash, type UnsubscribeClaims } from "./unsubscribe";
44
44
  export { verifyResendWebhook, emailEventOf, WEBHOOK_TOLERANCE_SECONDS } from "./webhook";
45
+ export { createInboundEmailHandler, inboundEmailOf, parseAddress, RESEND_RECEIVING_API, type InboundEmail, type InboundEmailHandlerOptions, type InboundEmailRoute } from "./inbound";
45
46
  export { checkSenderDomain, isReservedDomain, senderOwnershipRecord, SENDER_OWNERSHIP_HOST, type DomainCheck, type DomainCheckOptions } from "./dns";
46
47
  export {
47
48
  canonicalJson,