@portalshq/capability-email-notifications 0.1.0 → 0.2.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.
- package/README.md +55 -0
- package/dist/crm-outbox.d.ts +9 -0
- package/dist/crm-outbox.js +41 -0
- package/dist/delivery.d.ts +14 -0
- package/dist/delivery.js +113 -0
- package/dist/enqueue.d.ts +7 -0
- package/dist/enqueue.js +38 -0
- package/dist/index.d.ts +17 -0
- package/dist/index.js +14 -1
- package/dist/origin.d.ts +2 -0
- package/dist/origin.js +16 -0
- package/dist/preferences.d.ts +21 -0
- package/dist/preferences.js +49 -0
- package/dist/schedule.d.ts +6 -0
- package/dist/schedule.js +29 -0
- package/dist/unsubscribe.d.ts +18 -0
- package/dist/unsubscribe.js +71 -0
- package/dist/verification.d.ts +33 -0
- package/dist/verification.js +89 -0
- package/dist/worker-config.d.ts +14 -0
- package/dist/worker-config.js +27 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +47 -0
- package/package.json +37 -8
- package/sql/000_program_follows.sql +8 -0
- package/sql/001_notifications.sql +78 -0
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
1
|
# @portalshq/capability-email-notifications
|
|
2
2
|
|
|
3
3
|
Delivers notification messages through Resend with a small `send(message)` interface.
|
|
4
|
+
|
|
5
|
+
Messages may include an `idempotencyKey` for safe retries and custom `headers`
|
|
6
|
+
for provider-supported email metadata, including unsubscribe headers. The
|
|
7
|
+
caller remains responsible for durable delivery records and preference checks.
|
|
8
|
+
|
|
9
|
+
## Show reminders
|
|
10
|
+
|
|
11
|
+
The shared central database stores mailbox proof, independent program follows
|
|
12
|
+
and email choices, the delivery ledger, and the CRM outbox. Apply the shared
|
|
13
|
+
SQL files in `sql/` after the central identity and station schemas, or apply the
|
|
14
|
+
equivalent Bears central migrations through `0008_notification_subscriptions.sql`, before
|
|
15
|
+
starting the service. Existing calendar-invite records are retained and are
|
|
16
|
+
not converted to recurring email consent.
|
|
17
|
+
|
|
18
|
+
Build the package and run `npm run worker` as a supervised long-running
|
|
19
|
+
process. It is disabled unless `NOTIFICATIONS_WORKER_ENABLED=true`, and refuses
|
|
20
|
+
to run when `DRY_RUN` is set. It needs `CENTRAL_DATABASE_URL`, `RESEND_API_KEY`,
|
|
21
|
+
`RESEND_FROM_EMAIL`, `NOTIFICATIONS_PUBLIC_URL` (the Channels origin), and
|
|
22
|
+
`NOTIFICATIONS_UNSUBSCRIBE_SECRET` (at least 32 bytes). HTTPS is the default;
|
|
23
|
+
set `NOTIFICATIONS_ALLOW_PRIVATE_HTTP=true` on both Channels and the worker to
|
|
24
|
+
allow loopback or Tailscale HTTP. `NOTIFICATIONS_POSTAL_ADDRESS` is optional.
|
|
25
|
+
CRM delivery is disabled by default and is not needed for reminders. To enable
|
|
26
|
+
it separately, set `NOTIFICATIONS_CRM_ENABLED=true`,
|
|
27
|
+
`CONSUMER_CRM_INTAKE_URL` and `CONSUMER_CRM_INGEST_SECRET`.
|
|
28
|
+
|
|
29
|
+
The Channels service needs the central database (`CENTRAL_DATABASE_URL`),
|
|
30
|
+
Resend credentials, the public URL and unsubscribe secret above, and the auth
|
|
31
|
+
gateway settings. Set `NOTIFICATIONS_TRUSTED_CLIENT_IP_HEADER` only to a
|
|
32
|
+
header overwritten by the trusted edge; without it verification requests use
|
|
33
|
+
a shared safety limit. Configure `RESEND_WEBHOOK_SECRET` and point the Resend
|
|
34
|
+
webhook to `/api/notifications/webhook` for bounces and complaints. Configure
|
|
35
|
+
the provider's signed webhook in addition to the application route.
|
|
36
|
+
|
|
37
|
+
The reminder dialog detects the viewer's time zone and offers episode reminders
|
|
38
|
+
and a weekly followed-show schedule. Existing general-schedule subscriptions
|
|
39
|
+
are preserved; the dialog does not create new ones. Signed-in viewers use their
|
|
40
|
+
verified notification address, or confirm the account email before activation.
|
|
41
|
+
The current gateway does not expose an email address: if the central user has
|
|
42
|
+
no email on record, the viewer must add and verify one in notification settings
|
|
43
|
+
once. A later signup reuses the verified address.
|
|
44
|
+
|
|
45
|
+
The worker polls every 30 seconds and claims database jobs with leases. It
|
|
46
|
+
sends episode reminders six minutes ahead and separately opted-in weekly
|
|
47
|
+
emails after Monday noon in the recipient's time zone. An expired 23-hour
|
|
48
|
+
retry window is marked failed rather than risking a duplicate beyond Resend's
|
|
49
|
+
idempotency retention. Monitor failed deliveries, pending outbox age, and
|
|
50
|
+
worker health. Unsubscribe links are signed and require a stable secret; rotate
|
|
51
|
+
the secret only with a plan for previously sent links.
|
|
52
|
+
|
|
53
|
+
The Mac-hosted deployment includes a launchd template at
|
|
54
|
+
`infra/mac-bootstrap/launchd/com.portals.notifications.plist` and an environment
|
|
55
|
+
template at `infra/mac-bootstrap/templates/notifications.env.example`. Install
|
|
56
|
+
the launchd job only after the release, migrations, credentials, sender domain,
|
|
57
|
+
and signed webhook have been configured and verified; the template itself does
|
|
58
|
+
not start the worker.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { PreferencesDatabase } from "./preferences.js";
|
|
2
|
+
/** Delivers a verified signup event to the authenticated CRM intake. */
|
|
3
|
+
export declare function deliverOneCrmEvent(options: {
|
|
4
|
+
db: PreferencesDatabase;
|
|
5
|
+
endpoint: string;
|
|
6
|
+
secret: string;
|
|
7
|
+
now?: Date;
|
|
8
|
+
fetcher?: typeof fetch;
|
|
9
|
+
}): Promise<boolean>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
/** Delivers a verified signup event to the authenticated CRM intake. */
|
|
3
|
+
export async function deliverOneCrmEvent(options) {
|
|
4
|
+
const endpoint = new URL(options.endpoint);
|
|
5
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || !options.secret)
|
|
6
|
+
throw new Error("CRM intake requires HTTPS and a secret");
|
|
7
|
+
const now = options.now ?? new Date(), lease = randomUUID();
|
|
8
|
+
const claimed = await options.db.query(`WITH candidate AS (SELECT id FROM notification_crm_outbox
|
|
9
|
+
WHERE delivered_at IS NULL AND next_attempt_at <= $1 AND (lease_until IS NULL OR lease_until < $1)
|
|
10
|
+
ORDER BY created_at FOR UPDATE SKIP LOCKED LIMIT 1)
|
|
11
|
+
UPDATE notification_crm_outbox o SET lease_token = $2, lease_until = $1::timestamptz + interval '2 minutes', attempts = attempts + 1
|
|
12
|
+
FROM candidate WHERE o.id = candidate.id RETURNING o.*`, [now, lease]);
|
|
13
|
+
const job = claimed.rows[0];
|
|
14
|
+
if (!job)
|
|
15
|
+
return false;
|
|
16
|
+
try {
|
|
17
|
+
const payload = job.payload;
|
|
18
|
+
const recipient = await options.db.query(`SELECT r.email, r.general_schedule_enabled, s.episode_enabled, s.weekly_enabled
|
|
19
|
+
FROM notification_recipients r LEFT JOIN program_email_subscriptions s ON s.recipient_id = r.id AND s.program_id = $2
|
|
20
|
+
WHERE r.id = $1 AND r.verified_at IS NOT NULL`, [job.recipient_id, payload.programId]);
|
|
21
|
+
if (!recipient.rows[0])
|
|
22
|
+
throw new Error('Recipient is not verified');
|
|
23
|
+
const response = await (options.fetcher ?? fetch)(endpoint, {
|
|
24
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${options.secret}` },
|
|
25
|
+
body: JSON.stringify({ id: job.id, email: recipient.rows[0].email, payload: { ...payload,
|
|
26
|
+
episode: Boolean(recipient.rows[0].episode_enabled), weekly: Boolean(recipient.rows[0].weekly_enabled),
|
|
27
|
+
generalSchedule: Boolean(recipient.rows[0].general_schedule_enabled) } }),
|
|
28
|
+
signal: AbortSignal.timeout(10_000),
|
|
29
|
+
});
|
|
30
|
+
if (!response.ok)
|
|
31
|
+
throw new Error(`CRM intake returned ${response.status}`);
|
|
32
|
+
await options.db.query('UPDATE notification_crm_outbox SET delivered_at = $3, lease_until = NULL WHERE id = $1 AND lease_token = $2', [job.id, lease, now]);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const seconds = Math.min(3600, 30 * 2 ** Math.min(Number(job.attempts ?? 1), 7));
|
|
36
|
+
await options.db.query(`UPDATE notification_crm_outbox SET lease_until = NULL,
|
|
37
|
+
next_attempt_at = $3::timestamptz + $4 * interval '1 second' WHERE id = $1 AND lease_token = $2`, [job.id, lease, now, seconds]);
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Notifications } from "./index.js";
|
|
2
|
+
import type { PreferencesDatabase } from "./preferences.js";
|
|
3
|
+
/** Claims one delivery with an expiring lease and sends it at most once per
|
|
4
|
+
* Resend idempotency window. Retries retain the exact original payload. */
|
|
5
|
+
export declare function deliverOneNotification(options: {
|
|
6
|
+
db: PreferencesDatabase;
|
|
7
|
+
notifications: Notifications;
|
|
8
|
+
publicBaseUrl: string;
|
|
9
|
+
unsubscribeSecret: string;
|
|
10
|
+
postalAddress?: string;
|
|
11
|
+
allowPrivateHttp?: boolean;
|
|
12
|
+
now?: Date;
|
|
13
|
+
programId?: string;
|
|
14
|
+
}): Promise<boolean>;
|
package/dist/delivery.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { formatOccurrence } from "./schedule.js";
|
|
3
|
+
import { unsubscribeToken } from "./unsubscribe.js";
|
|
4
|
+
import { notificationOrigin } from "./origin.js";
|
|
5
|
+
const escapeHtml = (value) => value.replace(/[&<>"']/g, char => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]);
|
|
6
|
+
const canonical = (value) => {
|
|
7
|
+
if (Array.isArray(value))
|
|
8
|
+
return `[${value.map(canonical).join(",")}]`;
|
|
9
|
+
if (value && typeof value === "object")
|
|
10
|
+
return `{${Object.entries(value).sort(([a], [b]) => a.localeCompare(b)).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item)}`).join(",")}}`;
|
|
11
|
+
return JSON.stringify(value);
|
|
12
|
+
};
|
|
13
|
+
/** Claims one delivery with an expiring lease and sends it at most once per
|
|
14
|
+
* Resend idempotency window. Retries retain the exact original payload. */
|
|
15
|
+
export async function deliverOneNotification(options) {
|
|
16
|
+
const { db, notifications } = options;
|
|
17
|
+
const now = options.now ?? new Date();
|
|
18
|
+
const base = notificationOrigin(options.publicBaseUrl, options.allowPrivateHttp);
|
|
19
|
+
const postalAddress = options.postalAddress?.trim();
|
|
20
|
+
await db.query(`UPDATE notification_deliveries SET status = 'failed', last_error = 'Retry window expired'
|
|
21
|
+
WHERE status IN ('pending','sending') AND first_attempt_at <= $1::timestamptz - interval '23 hours'
|
|
22
|
+
AND (lease_until IS NULL OR lease_until < $1)
|
|
23
|
+
AND ($2::text IS NULL OR (kind = 'confirmation' AND program_id = $2)
|
|
24
|
+
OR (kind = 'episode' AND EXISTS (SELECT 1 FROM station_program_slots slot WHERE slot.id = occurrence_key AND slot.program_id = $2))
|
|
25
|
+
OR (kind IN ('followed_weekly', 'general_weekly') AND EXISTS (SELECT 1 FROM program_email_subscriptions s WHERE s.recipient_id = notification_deliveries.recipient_id AND s.program_id = $2 AND s.weekly_enabled)))`, [now, options.programId ?? null]);
|
|
26
|
+
const lease = randomUUID();
|
|
27
|
+
const claimed = await db.query(`WITH candidate AS (
|
|
28
|
+
SELECT id FROM notification_deliveries
|
|
29
|
+
WHERE (status = 'pending' OR (status = 'sending' AND lease_until < $1))
|
|
30
|
+
AND (first_attempt_at IS NULL OR first_attempt_at > $1::timestamptz - interval '23 hours')
|
|
31
|
+
AND ($3::text IS NULL OR (kind = 'confirmation' AND program_id = $3)
|
|
32
|
+
OR (kind = 'episode' AND EXISTS (SELECT 1 FROM station_program_slots slot WHERE slot.id = occurrence_key AND slot.program_id = $3))
|
|
33
|
+
OR (kind IN ('followed_weekly', 'general_weekly') AND EXISTS (SELECT 1 FROM program_email_subscriptions s WHERE s.recipient_id = notification_deliveries.recipient_id AND s.program_id = $3 AND s.weekly_enabled)))
|
|
34
|
+
ORDER BY CASE WHEN kind = 'episode' THEN 0 ELSE 1 END, created_at, id FOR UPDATE SKIP LOCKED LIMIT 1
|
|
35
|
+
) UPDATE notification_deliveries d SET status = 'sending', lease_token = $2,
|
|
36
|
+
lease_until = $1::timestamptz + interval '2 minutes', attempts = d.attempts + 1,
|
|
37
|
+
first_attempt_at = COALESCE(d.first_attempt_at, $1)
|
|
38
|
+
FROM candidate WHERE d.id = candidate.id RETURNING d.*`, [now, lease, options.programId ?? null]);
|
|
39
|
+
const job = claimed.rows[0];
|
|
40
|
+
if (!job)
|
|
41
|
+
return false;
|
|
42
|
+
try {
|
|
43
|
+
const rows = await db.query(`SELECT r.email, r.timezone, slot.id AS slot_id, p.id AS program_id, slot.channel_id,
|
|
44
|
+
slot.starts_at, p.name AS program_name, s.episode_enabled, s.weekly_enabled
|
|
45
|
+
FROM notification_recipients r JOIN programs p ON ($2 <> 'confirmation' OR p.id = $5)
|
|
46
|
+
LEFT JOIN station_program_slots slot ON slot.program_id = p.id AND slot.status = 'scheduled' AND slot.starts_at > $4
|
|
47
|
+
LEFT JOIN program_email_subscriptions s ON s.recipient_id = r.id AND s.program_id = p.id
|
|
48
|
+
WHERE r.id = $1 AND r.verified_at IS NOT NULL AND r.suppressed_at IS NULL
|
|
49
|
+
AND (($2 = 'episode' AND slot.id = $3 AND s.episode_enabled
|
|
50
|
+
AND slot.starts_at <= $4::timestamptz + interval '6 minutes')
|
|
51
|
+
OR ($2 = 'followed_weekly' AND s.weekly_enabled AND slot.starts_at <= $4::timestamptz + interval '7 days'
|
|
52
|
+
AND (r.user_id IS NULL OR EXISTS (SELECT 1 FROM program_follows f WHERE f.user_id = r.user_id AND f.program_id = slot.program_id)))
|
|
53
|
+
OR ($2 = 'general_weekly' AND r.general_schedule_enabled AND slot.starts_at <= $4::timestamptz + interval '7 days')
|
|
54
|
+
OR ($2 = 'confirmation' AND s.recipient_id IS NOT NULL))
|
|
55
|
+
ORDER BY slot.starts_at NULLS LAST, slot.id`, [job.recipient_id, job.kind, job.occurrence_key, now, job.program_id]);
|
|
56
|
+
if (!rows.rows.length) {
|
|
57
|
+
await db.query("UPDATE notification_deliveries SET status = 'cancelled', lease_until = NULL WHERE id = $1 AND lease_token = $2", [job.id, lease]);
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
const first = rows.rows[0];
|
|
61
|
+
const email = String(first.email), zone = String(first.timezone);
|
|
62
|
+
const scope = job.kind === "episode" || job.kind === "confirmation"
|
|
63
|
+
? { recipientId: job.recipient_id, kind: "program", programId: String(first.program_id) }
|
|
64
|
+
: { recipientId: job.recipient_id, kind: job.kind === "general_weekly" ? "general" : "weekly" };
|
|
65
|
+
const link = new URL("/api/notifications/unsubscribe", base);
|
|
66
|
+
link.searchParams.set("token", unsubscribeToken(options.unsubscribeSecret, scope));
|
|
67
|
+
const manage = new URL("/api/notifications/manage", base);
|
|
68
|
+
manage.searchParams.set("token", unsubscribeToken(options.unsubscribeSecret, { recipientId: job.recipient_id, kind: "manage" }));
|
|
69
|
+
const stopLabel = scope.kind === "program" ? "Stop emails for this show" : scope.kind === "weekly" ? "Stop followed-show schedules" : "Stop the general schedule";
|
|
70
|
+
const selected = job.kind === "confirmation" ? rows.rows.slice(0, 1) : rows.rows;
|
|
71
|
+
const lines = selected.map(row => {
|
|
72
|
+
if (!row.starts_at || !row.channel_id)
|
|
73
|
+
return `${String(row.program_name)} — next episode not yet scheduled`;
|
|
74
|
+
const watch = new URL(`/${encodeURIComponent(String(row.channel_id))}`, base).href;
|
|
75
|
+
return `${String(row.program_name)} — ${formatOccurrence(new Date(String(row.starts_at)), zone)}\n${watch}`;
|
|
76
|
+
});
|
|
77
|
+
if (job.kind === "confirmation")
|
|
78
|
+
lines.push(`Episode reminders: ${first.episode_enabled ? "on" : "off"}\nWeekly followed-show schedule: ${first.weekly_enabled ? "on" : "off"}`);
|
|
79
|
+
const calendar = job.kind === "confirmation" && first.channel_id
|
|
80
|
+
? new URL(`/api/channels/${encodeURIComponent(String(first.channel_id))}/sessions/next.ics`, base).href : null;
|
|
81
|
+
if (calendar)
|
|
82
|
+
lines.push(`Add the next episode to your calendar: ${calendar}`);
|
|
83
|
+
const subject = job.kind === "confirmation" ? `Your ${String(first.program_name)} reminders` : job.kind === "episode" ? `${String(first.program_name)} starts in 5 minutes` :
|
|
84
|
+
job.kind === "general_weekly" ? "Your weekly live schedule" : "Your followed shows this week";
|
|
85
|
+
const text = `${lines.join("\n\n")}\n\nManage reminders: ${manage.href}\n${stopLabel}: ${link.href}${postalAddress ? `\n${postalAddress}` : ""}`;
|
|
86
|
+
const htmlLines = selected.map(row => {
|
|
87
|
+
if (!row.starts_at || !row.channel_id)
|
|
88
|
+
return `<p><strong>${escapeHtml(String(row.program_name))}</strong> — next episode not yet scheduled</p>`;
|
|
89
|
+
const watch = new URL(`/${encodeURIComponent(String(row.channel_id))}`, base).href;
|
|
90
|
+
return `<p><strong>${escapeHtml(String(row.program_name))}</strong> — ${escapeHtml(formatOccurrence(new Date(String(row.starts_at)), zone))}<br><a href="${escapeHtml(watch)}">Watch</a></p>`;
|
|
91
|
+
});
|
|
92
|
+
const message = { to: email, subject, text,
|
|
93
|
+
html: `${htmlLines.join("")}${job.kind === "confirmation" ? `<p>Episode reminders: ${first.episode_enabled ? "on" : "off"}<br>Weekly followed-show schedule: ${first.weekly_enabled ? "on" : "off"}</p>${calendar ? `<p><a href="${escapeHtml(calendar)}">Add next episode to calendar</a></p>` : ""}` : ""}<p><a href="${escapeHtml(manage.href)}">Manage reminders</a> · <a href="${escapeHtml(link.href)}">${stopLabel}</a>${postalAddress ? `<br>${escapeHtml(postalAddress)}` : ""}</p>`, idempotencyKey: `notification/${job.id}`,
|
|
94
|
+
headers: { "List-Unsubscribe": `<${link.href}>`, "List-Unsubscribe-Post": "List-Unsubscribe=One-Click" } };
|
|
95
|
+
// A retry must use identical content. If preferences or slots changed,
|
|
96
|
+
// cancel rather than send a stale or differently scoped message.
|
|
97
|
+
if (job.payload && canonical(job.payload) !== canonical(message)) {
|
|
98
|
+
await db.query("UPDATE notification_deliveries SET status = 'cancelled', lease_until = NULL WHERE id = $1 AND lease_token = $2", [job.id, lease]);
|
|
99
|
+
return true;
|
|
100
|
+
}
|
|
101
|
+
const saved = await db.query(`UPDATE notification_deliveries SET payload = COALESCE(payload, $3::jsonb)
|
|
102
|
+
WHERE id = $1 AND lease_token = $2 AND status = 'sending' RETURNING id`, [job.id, lease, JSON.stringify(message)]);
|
|
103
|
+
if (!saved.rows.length)
|
|
104
|
+
return true;
|
|
105
|
+
const sent = await notifications.send(job.payload ?? message);
|
|
106
|
+
await db.query("UPDATE notification_deliveries SET status = 'sent', provider_message_id = $3, sent_at = $4, lease_until = NULL WHERE id = $1 AND lease_token = $2", [job.id, lease, sent.messageId ?? null, new Date()]);
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
await db.query("UPDATE notification_deliveries SET status = 'pending', lease_until = NULL, last_error = $3 WHERE id = $1 AND lease_token = $2", [job.id, lease, String(error instanceof Error ? error.message : error).slice(0, 500)]);
|
|
111
|
+
throw error;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { PreferencesDatabase } from "./preferences.js";
|
|
2
|
+
/**
|
|
3
|
+
* Queue due mail from materialized production slots. A stable occurrence key
|
|
4
|
+
* and database uniqueness permit multiple worker processes to run this safely.
|
|
5
|
+
* Delivery must recheck slot status and preferences before sending.
|
|
6
|
+
*/
|
|
7
|
+
export declare function enqueueDueNotifications(db: PreferencesDatabase, now: Date, programId?: string): Promise<void>;
|
package/dist/enqueue.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Queue due mail from materialized production slots. A stable occurrence key
|
|
3
|
+
* and database uniqueness permit multiple worker processes to run this safely.
|
|
4
|
+
* Delivery must recheck slot status and preferences before sending.
|
|
5
|
+
*/
|
|
6
|
+
export async function enqueueDueNotifications(db, now, programId) {
|
|
7
|
+
await db.query(`INSERT INTO notification_deliveries (recipient_id, kind, occurrence_key)
|
|
8
|
+
SELECT s.recipient_id, 'episode', slot.id
|
|
9
|
+
FROM program_email_subscriptions s
|
|
10
|
+
JOIN notification_recipients r ON r.id = s.recipient_id
|
|
11
|
+
JOIN station_program_slots slot ON slot.program_id = s.program_id
|
|
12
|
+
WHERE s.episode_enabled AND r.verified_at IS NOT NULL AND r.suppressed_at IS NULL
|
|
13
|
+
AND slot.status = 'scheduled' AND slot.starts_at > $1
|
|
14
|
+
AND slot.starts_at <= $1::timestamptz + interval '6 minutes'
|
|
15
|
+
AND ($2::text IS NULL OR slot.program_id = $2)
|
|
16
|
+
ON CONFLICT (recipient_id, kind, occurrence_key) DO NOTHING`, [now, programId ?? null]);
|
|
17
|
+
await db.query(`INSERT INTO notification_deliveries (recipient_id, kind, occurrence_key)
|
|
18
|
+
SELECT r.id, kind.kind, to_char($1::timestamptz AT TIME ZONE r.timezone, 'YYYY-MM-DD')
|
|
19
|
+
FROM notification_recipients r
|
|
20
|
+
CROSS JOIN (VALUES ('followed_weekly'), ('general_weekly')) AS kind(kind)
|
|
21
|
+
WHERE r.verified_at IS NOT NULL AND r.suppressed_at IS NULL
|
|
22
|
+
AND ($2::text IS NULL OR EXISTS (SELECT 1 FROM program_email_subscriptions own
|
|
23
|
+
WHERE own.recipient_id = r.id AND own.program_id = $2 AND own.weekly_enabled))
|
|
24
|
+
AND extract(isodow FROM $1::timestamptz AT TIME ZONE r.timezone) = 1
|
|
25
|
+
AND extract(hour FROM $1::timestamptz AT TIME ZONE r.timezone) >= 12
|
|
26
|
+
AND EXISTS (
|
|
27
|
+
SELECT 1 FROM station_program_slots slot
|
|
28
|
+
WHERE slot.status = 'scheduled' AND slot.starts_at > $1
|
|
29
|
+
AND slot.starts_at <= $1::timestamptz + interval '7 days'
|
|
30
|
+
AND ((kind.kind = 'general_weekly' AND r.general_schedule_enabled)
|
|
31
|
+
OR (kind.kind = 'followed_weekly' AND EXISTS (
|
|
32
|
+
SELECT 1 FROM program_email_subscriptions s
|
|
33
|
+
WHERE s.recipient_id = r.id AND s.program_id = slot.program_id AND s.weekly_enabled
|
|
34
|
+
AND (r.user_id IS NULL OR EXISTS (SELECT 1 FROM program_follows f WHERE f.user_id = r.user_id AND f.program_id = slot.program_id))
|
|
35
|
+
)))
|
|
36
|
+
)
|
|
37
|
+
ON CONFLICT (recipient_id, kind, occurrence_key) DO NOTHING`, [now, programId ?? null]);
|
|
38
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
export * from "./schedule.js";
|
|
2
|
+
export * from "./preferences.js";
|
|
3
|
+
export * from "./verification.js";
|
|
4
|
+
export * from "./enqueue.js";
|
|
5
|
+
export * from "./unsubscribe.js";
|
|
6
|
+
export * from "./delivery.js";
|
|
7
|
+
export * from "./crm-outbox.js";
|
|
8
|
+
export * from "./origin.js";
|
|
1
9
|
export type NotificationMessage = {
|
|
2
10
|
to: string;
|
|
3
11
|
subject: string;
|
|
@@ -9,6 +17,9 @@ export type NotificationMessage = {
|
|
|
9
17
|
content: string | Buffer;
|
|
10
18
|
contentType?: string;
|
|
11
19
|
}[];
|
|
20
|
+
/** Stable key for retries of the same delivery. Resend retains it for 24 hours. */
|
|
21
|
+
idempotencyKey?: string;
|
|
22
|
+
headers?: Record<string, string>;
|
|
12
23
|
};
|
|
13
24
|
export type DeliveryResult = {
|
|
14
25
|
messageId?: string;
|
|
@@ -16,6 +27,12 @@ export type DeliveryResult = {
|
|
|
16
27
|
export type Notifications = {
|
|
17
28
|
send(message: NotificationMessage): Promise<DeliveryResult>;
|
|
18
29
|
};
|
|
30
|
+
/** Verify provider signatures before consuming delivery events. */
|
|
31
|
+
export declare function verifyResendEvent(payload: string, headers: {
|
|
32
|
+
id: string;
|
|
33
|
+
timestamp: string;
|
|
34
|
+
signature: string;
|
|
35
|
+
}, webhookSecret: string): import("resend").WebhookEventPayload;
|
|
19
36
|
export declare function createResendNotifications(options: {
|
|
20
37
|
apiKey: string;
|
|
21
38
|
from: string;
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,16 @@
|
|
|
1
1
|
import { Resend } from "resend";
|
|
2
|
+
export * from "./schedule.js";
|
|
3
|
+
export * from "./preferences.js";
|
|
4
|
+
export * from "./verification.js";
|
|
5
|
+
export * from "./enqueue.js";
|
|
6
|
+
export * from "./unsubscribe.js";
|
|
7
|
+
export * from "./delivery.js";
|
|
8
|
+
export * from "./crm-outbox.js";
|
|
9
|
+
export * from "./origin.js";
|
|
10
|
+
/** Verify provider signatures before consuming delivery events. */
|
|
11
|
+
export function verifyResendEvent(payload, headers, webhookSecret) {
|
|
12
|
+
return new Resend("webhook-verification").webhooks.verify({ payload, headers, webhookSecret });
|
|
13
|
+
}
|
|
2
14
|
export function createResendNotifications(options) {
|
|
3
15
|
if (!options.apiKey)
|
|
4
16
|
throw new Error("Resend requires an API key.");
|
|
@@ -15,7 +27,8 @@ export function createResendNotifications(options) {
|
|
|
15
27
|
html: message.html ?? message.text.replace(/\n/g, "<br>"),
|
|
16
28
|
scheduledAt: message.scheduledAt,
|
|
17
29
|
attachments: message.attachments?.map((attachment) => ({ ...attachment })),
|
|
18
|
-
|
|
30
|
+
headers: message.headers,
|
|
31
|
+
}, message.idempotencyKey ? { idempotencyKey: message.idempotencyKey } : undefined);
|
|
19
32
|
if (error)
|
|
20
33
|
throw new Error(`Email delivery failed: ${error.message}`);
|
|
21
34
|
return { messageId: data?.id };
|
package/dist/origin.d.ts
ADDED
package/dist/origin.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { isIP } from "node:net";
|
|
2
|
+
/** Require HTTPS unless the operator explicitly opts in to loopback/Tailscale HTTP. */
|
|
3
|
+
export function notificationOrigin(value, allowPrivateHttp = false) {
|
|
4
|
+
const url = new URL(value);
|
|
5
|
+
const host = url.hostname.toLowerCase();
|
|
6
|
+
let privateHost = host === "localhost" || host === "[::1]" || host === "::1";
|
|
7
|
+
if (isIP(host) === 4) {
|
|
8
|
+
const [first, second] = host.split(".").map(Number);
|
|
9
|
+
privateHost = first === 127 || (first === 100 && second >= 64 && second <= 127);
|
|
10
|
+
}
|
|
11
|
+
if ((url.protocol !== "https:" && !(allowPrivateHttp && url.protocol === "http:" && privateHost)) ||
|
|
12
|
+
url.username || url.password || url.pathname !== "/" || url.search || url.hash) {
|
|
13
|
+
throw new Error("Invalid notification origin");
|
|
14
|
+
}
|
|
15
|
+
return url;
|
|
16
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Caller must authorize the recipient before using this server-side store. */
|
|
2
|
+
export interface PreferencesDatabase {
|
|
3
|
+
query(sql: string, values?: unknown[]): Promise<{
|
|
4
|
+
rows: Array<Record<string, unknown>>;
|
|
5
|
+
}>;
|
|
6
|
+
}
|
|
7
|
+
export declare class NotificationPreferencesStore {
|
|
8
|
+
private readonly db;
|
|
9
|
+
constructor(db: PreferencesDatabase);
|
|
10
|
+
/** Changes only the chosen program. A follow is never added or removed here. */
|
|
11
|
+
setProgram(input: {
|
|
12
|
+
recipientId: string;
|
|
13
|
+
programId: string;
|
|
14
|
+
episode: boolean;
|
|
15
|
+
weekly: boolean;
|
|
16
|
+
consentSource: string;
|
|
17
|
+
attribution: Record<string, unknown>;
|
|
18
|
+
}): Promise<void>;
|
|
19
|
+
setGeneralSchedule(recipientId: string, enabled: boolean): Promise<void>;
|
|
20
|
+
setTimeZone(recipientId: string, timeZone: string): Promise<void>;
|
|
21
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { validateTimeZone } from "./schedule.js";
|
|
2
|
+
export class NotificationPreferencesStore {
|
|
3
|
+
db;
|
|
4
|
+
constructor(db) {
|
|
5
|
+
this.db = db;
|
|
6
|
+
}
|
|
7
|
+
/** Changes only the chosen program. A follow is never added or removed here. */
|
|
8
|
+
async setProgram(input) {
|
|
9
|
+
if (!input.recipientId || !input.programId || !input.consentSource)
|
|
10
|
+
throw new Error("Missing subscription fields");
|
|
11
|
+
// The preference and CRM projection are committed in the same statement.
|
|
12
|
+
const result = await this.db.query(`WITH changed AS (
|
|
13
|
+
INSERT INTO program_email_subscriptions
|
|
14
|
+
(recipient_id, program_id, episode_enabled, weekly_enabled, consent_at, consent_source)
|
|
15
|
+
VALUES ($1, $2, $3, $4, now(), $5)
|
|
16
|
+
ON CONFLICT (recipient_id, program_id) DO UPDATE SET
|
|
17
|
+
episode_enabled = EXCLUDED.episode_enabled, weekly_enabled = EXCLUDED.weekly_enabled,
|
|
18
|
+
consent_at = now(), consent_source = EXCLUDED.consent_source, updated_at = now()
|
|
19
|
+
RETURNING recipient_id, program_id
|
|
20
|
+
)
|
|
21
|
+
INSERT INTO notification_crm_outbox (recipient_id, payload)
|
|
22
|
+
SELECT changed.recipient_id, $6::jsonb || jsonb_build_object('generalSchedule', r.general_schedule_enabled)
|
|
23
|
+
FROM changed JOIN notification_recipients r ON r.id = changed.recipient_id RETURNING id`, [input.recipientId, input.programId, input.episode, input.weekly, input.consentSource,
|
|
24
|
+
JSON.stringify({ ...input.attribution, programId: input.programId, episode: input.episode,
|
|
25
|
+
weekly: input.weekly, consentSource: input.consentSource })]);
|
|
26
|
+
if (!result.rows.length)
|
|
27
|
+
throw new Error("Subscription was not saved");
|
|
28
|
+
}
|
|
29
|
+
async setGeneralSchedule(recipientId, enabled) {
|
|
30
|
+
const result = await this.db.query(`WITH prior AS (SELECT id, general_schedule_enabled FROM notification_recipients WHERE id = $1 FOR UPDATE),
|
|
31
|
+
changed AS (UPDATE notification_recipients r SET general_schedule_enabled = $2,
|
|
32
|
+
general_schedule_consent_at = CASE WHEN $2 AND NOT prior.general_schedule_enabled THEN now() ELSE r.general_schedule_consent_at END,
|
|
33
|
+
updated_at = now() FROM prior WHERE r.id = prior.id RETURNING r.id, prior.general_schedule_enabled AS previous),
|
|
34
|
+
projection AS (INSERT INTO notification_crm_outbox (recipient_id, payload)
|
|
35
|
+
SELECT s.recipient_id, jsonb_build_object('programId',s.program_id,'episode',s.episode_enabled,'weekly',s.weekly_enabled,
|
|
36
|
+
'generalSchedule',$2::boolean,'consentSource','settings')
|
|
37
|
+
FROM changed JOIN program_email_subscriptions s ON s.recipient_id = changed.id
|
|
38
|
+
WHERE changed.previous IS DISTINCT FROM $2 RETURNING id)
|
|
39
|
+
SELECT id FROM changed`, [recipientId, enabled]);
|
|
40
|
+
if (!result.rows.length)
|
|
41
|
+
throw new Error("Recipient not found");
|
|
42
|
+
}
|
|
43
|
+
async setTimeZone(recipientId, timeZone) {
|
|
44
|
+
const zone = validateTimeZone(timeZone);
|
|
45
|
+
const result = await this.db.query(`UPDATE notification_recipients SET timezone = $2, updated_at = now() WHERE id = $1 RETURNING id`, [recipientId, zone]);
|
|
46
|
+
if (!result.rows.length)
|
|
47
|
+
throw new Error("Recipient not found");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Returns a validated IANA time zone, or throws rather than guessing a zone. */
|
|
2
|
+
export declare function validateTimeZone(timeZone: string): string;
|
|
3
|
+
/** Stable local-week key from noon until midnight Monday, allowing worker recovery. */
|
|
4
|
+
export declare function weeklyDeliveryKey(now: Date, timeZone: string): string | null;
|
|
5
|
+
/** Format occurrence times in the recipient's zone, including the zone name. */
|
|
6
|
+
export declare function formatOccurrence(startsAt: Date, timeZone: string): string;
|
package/dist/schedule.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** Returns a validated IANA time zone, or throws rather than guessing a zone. */
|
|
2
|
+
export function validateTimeZone(timeZone) {
|
|
3
|
+
if (!timeZone || timeZone.length > 128)
|
|
4
|
+
throw new Error("Invalid time zone");
|
|
5
|
+
try {
|
|
6
|
+
return new Intl.DateTimeFormat("en-US", { timeZone }).resolvedOptions().timeZone;
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
throw new Error("Invalid time zone");
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
/** Stable local-week key from noon until midnight Monday, allowing worker recovery. */
|
|
13
|
+
export function weeklyDeliveryKey(now, timeZone) {
|
|
14
|
+
const formatter = new Intl.DateTimeFormat("en-CA", {
|
|
15
|
+
timeZone: validateTimeZone(timeZone), weekday: "short", year: "numeric",
|
|
16
|
+
month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23",
|
|
17
|
+
});
|
|
18
|
+
const parts = Object.fromEntries(formatter.formatToParts(now).map(({ type, value }) => [type, value]));
|
|
19
|
+
if (parts.weekday !== "Mon" || Number(parts.hour) < 12)
|
|
20
|
+
return null;
|
|
21
|
+
return `${parts.year}-${parts.month}-${parts.day}`;
|
|
22
|
+
}
|
|
23
|
+
/** Format occurrence times in the recipient's zone, including the zone name. */
|
|
24
|
+
export function formatOccurrence(startsAt, timeZone) {
|
|
25
|
+
return new Intl.DateTimeFormat("en-US", {
|
|
26
|
+
timeZone: validateTimeZone(timeZone), weekday: "short", month: "short", day: "numeric",
|
|
27
|
+
hour: "numeric", minute: "2-digit", timeZoneName: "short",
|
|
28
|
+
}).format(startsAt);
|
|
29
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { PreferencesDatabase } from "./preferences.js";
|
|
2
|
+
export type UnsubscribeScope = {
|
|
3
|
+
recipientId: string;
|
|
4
|
+
kind: "program";
|
|
5
|
+
programId: string;
|
|
6
|
+
} | {
|
|
7
|
+
recipientId: string;
|
|
8
|
+
kind: "general" | "weekly" | "all";
|
|
9
|
+
};
|
|
10
|
+
export type NotificationLinkScope = UnsubscribeScope | {
|
|
11
|
+
recipientId: string;
|
|
12
|
+
kind: "manage";
|
|
13
|
+
};
|
|
14
|
+
/** Signed links contain no email address and cannot be modified by a viewer. */
|
|
15
|
+
export declare function unsubscribeToken(secret: string, scope: NotificationLinkScope): string;
|
|
16
|
+
export declare function verifyUnsubscribeToken(secret: string, token: string): NotificationLinkScope | null;
|
|
17
|
+
/** Safe to repeat; does not delete the viewer's app follows. */
|
|
18
|
+
export declare function applyUnsubscribe(db: PreferencesDatabase, scope: UnsubscribeScope): Promise<void>;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
/** Signed links contain no email address and cannot be modified by a viewer. */
|
|
3
|
+
export function unsubscribeToken(secret, scope) {
|
|
4
|
+
if (Buffer.byteLength(secret) < 32)
|
|
5
|
+
throw new Error("Unsubscribe secret must be at least 32 bytes");
|
|
6
|
+
const body = Buffer.from(JSON.stringify(scope)).toString("base64url");
|
|
7
|
+
const signature = createHmac("sha256", secret).update(body).digest("base64url");
|
|
8
|
+
return `${body}.${signature}`;
|
|
9
|
+
}
|
|
10
|
+
export function verifyUnsubscribeToken(secret, token) {
|
|
11
|
+
if (Buffer.byteLength(secret) < 32 || token.length > 2048)
|
|
12
|
+
return null;
|
|
13
|
+
const [body, signature, extra] = token.split(".");
|
|
14
|
+
if (!body || !signature || extra || !/^[A-Za-z0-9_-]+$/.test(body) || !/^[A-Za-z0-9_-]{43}$/.test(signature))
|
|
15
|
+
return null;
|
|
16
|
+
const expected = createHmac("sha256", secret).update(body).digest();
|
|
17
|
+
const actual = Buffer.from(signature, "base64url");
|
|
18
|
+
if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
|
|
19
|
+
return null;
|
|
20
|
+
try {
|
|
21
|
+
const value = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
|
|
22
|
+
if (!value || typeof value !== "object")
|
|
23
|
+
return null;
|
|
24
|
+
const item = value;
|
|
25
|
+
if (typeof item.recipientId !== "string" || !item.recipientId || item.recipientId.length > 256)
|
|
26
|
+
return null;
|
|
27
|
+
if (item.kind === "program" && typeof item.programId === "string" && item.programId && item.programId.length <= 256) {
|
|
28
|
+
return { recipientId: item.recipientId, kind: "program", programId: item.programId };
|
|
29
|
+
}
|
|
30
|
+
if (item.kind === "general" || item.kind === "weekly" || item.kind === "all" || item.kind === "manage")
|
|
31
|
+
return { recipientId: item.recipientId, kind: item.kind };
|
|
32
|
+
}
|
|
33
|
+
catch { /* Invalid token. */ }
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
/** Safe to repeat; does not delete the viewer's app follows. */
|
|
37
|
+
export async function applyUnsubscribe(db, scope) {
|
|
38
|
+
if (scope.kind === "program") {
|
|
39
|
+
await db.query(`WITH changed AS (
|
|
40
|
+
UPDATE program_email_subscriptions SET episode_enabled = false, weekly_enabled = false, updated_at = now()
|
|
41
|
+
WHERE recipient_id = $1 AND program_id = $2 AND (episode_enabled OR weekly_enabled) RETURNING *)
|
|
42
|
+
INSERT INTO notification_crm_outbox (recipient_id,payload)
|
|
43
|
+
SELECT changed.recipient_id, jsonb_build_object('programId',changed.program_id,'episode',false,'weekly',false,
|
|
44
|
+
'generalSchedule',r.general_schedule_enabled,'consentSource','unsubscribe')
|
|
45
|
+
FROM changed JOIN notification_recipients r ON r.id = changed.recipient_id`, [scope.recipientId, scope.programId]);
|
|
46
|
+
}
|
|
47
|
+
else if (scope.kind === "general") {
|
|
48
|
+
await db.query(`WITH recipient AS (UPDATE notification_recipients SET general_schedule_enabled = false, updated_at = now()
|
|
49
|
+
WHERE id = $1 AND general_schedule_enabled RETURNING id)
|
|
50
|
+
INSERT INTO notification_crm_outbox (recipient_id,payload)
|
|
51
|
+
SELECT s.recipient_id, jsonb_build_object('programId',s.program_id,'episode',s.episode_enabled,'weekly',s.weekly_enabled,
|
|
52
|
+
'generalSchedule',false,'consentSource','unsubscribe') FROM program_email_subscriptions s JOIN recipient r ON r.id = s.recipient_id`, [scope.recipientId]);
|
|
53
|
+
}
|
|
54
|
+
else if (scope.kind === "weekly") {
|
|
55
|
+
await db.query(`WITH changed AS (UPDATE program_email_subscriptions SET weekly_enabled = false, updated_at = now()
|
|
56
|
+
WHERE recipient_id = $1 AND weekly_enabled RETURNING *)
|
|
57
|
+
INSERT INTO notification_crm_outbox (recipient_id,payload)
|
|
58
|
+
SELECT changed.recipient_id, jsonb_build_object('programId',changed.program_id,'episode',changed.episode_enabled,'weekly',false,
|
|
59
|
+
'generalSchedule',r.general_schedule_enabled,'consentSource','unsubscribe')
|
|
60
|
+
FROM changed JOIN notification_recipients r ON r.id = changed.recipient_id`, [scope.recipientId]);
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
await db.query(`WITH programs AS (
|
|
64
|
+
UPDATE program_email_subscriptions SET episode_enabled = false, weekly_enabled = false, updated_at = now()
|
|
65
|
+
WHERE recipient_id = $1 AND (episode_enabled OR weekly_enabled) RETURNING *),
|
|
66
|
+
recipient AS (UPDATE notification_recipients SET general_schedule_enabled = false, updated_at = now() WHERE id = $1 RETURNING id)
|
|
67
|
+
INSERT INTO notification_crm_outbox (recipient_id,payload)
|
|
68
|
+
SELECT programs.recipient_id, jsonb_build_object('programId',programs.program_id,'episode',false,'weekly',false,
|
|
69
|
+
'generalSchedule',false,'consentSource','unsubscribe') FROM programs`, [scope.recipientId]);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { PreferencesDatabase } from "./preferences.js";
|
|
2
|
+
export interface VerificationIntent {
|
|
3
|
+
programId: string;
|
|
4
|
+
episode: boolean;
|
|
5
|
+
weekly: boolean;
|
|
6
|
+
generalSchedule: boolean;
|
|
7
|
+
source: string;
|
|
8
|
+
timezone?: string;
|
|
9
|
+
attribution: Record<string, string>;
|
|
10
|
+
}
|
|
11
|
+
/** Mailbox proof tokens are one-time, expire, and are never stored in plaintext. */
|
|
12
|
+
export declare class EmailVerificationStore {
|
|
13
|
+
private readonly db;
|
|
14
|
+
constructor(db: PreferencesDatabase);
|
|
15
|
+
issue(email: string, userId: string | null, now?: Date, intent?: VerificationIntent): Promise<string>;
|
|
16
|
+
}
|
|
17
|
+
export interface VerificationTransaction extends PreferencesDatabase {
|
|
18
|
+
release(): void;
|
|
19
|
+
}
|
|
20
|
+
export interface VerificationPool {
|
|
21
|
+
connect(): Promise<VerificationTransaction>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Consume a mailbox proof and associate its recipient atomically. A verified
|
|
25
|
+
* address already attached to another account is never reassigned. Suppression
|
|
26
|
+
* and existing program choices survive linking.
|
|
27
|
+
*/
|
|
28
|
+
export declare function claimVerifiedEmail(pool: VerificationPool, token: string, timeZone: string, now?: Date, currentUserId?: string | null): Promise<{
|
|
29
|
+
recipientId: string;
|
|
30
|
+
email: string;
|
|
31
|
+
userId: string | null;
|
|
32
|
+
hasIntent: boolean;
|
|
33
|
+
} | null>;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { validateTimeZone } from "./schedule.js";
|
|
3
|
+
const digest = (token) => createHash("sha256").update(token).digest("hex");
|
|
4
|
+
/** Mailbox proof tokens are one-time, expire, and are never stored in plaintext. */
|
|
5
|
+
export class EmailVerificationStore {
|
|
6
|
+
db;
|
|
7
|
+
constructor(db) {
|
|
8
|
+
this.db = db;
|
|
9
|
+
}
|
|
10
|
+
async issue(email, userId, now = new Date(), intent) {
|
|
11
|
+
const normalized = email.trim().toLowerCase();
|
|
12
|
+
if (normalized.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normalized))
|
|
13
|
+
throw new Error("Invalid email");
|
|
14
|
+
const token = randomBytes(32).toString("base64url");
|
|
15
|
+
const expiry = new Date(now.getTime() + 30 * 60_000);
|
|
16
|
+
await this.db.query(`INSERT INTO notification_email_verifications (token_hash, email, user_id, expires_at, intent)
|
|
17
|
+
VALUES ($1, $2, $3, $4, $5::jsonb)`, [digest(token), normalized, userId, expiry, intent ? JSON.stringify(intent) : null]);
|
|
18
|
+
return token;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Consume a mailbox proof and associate its recipient atomically. A verified
|
|
23
|
+
* address already attached to another account is never reassigned. Suppression
|
|
24
|
+
* and existing program choices survive linking.
|
|
25
|
+
*/
|
|
26
|
+
export async function claimVerifiedEmail(pool, token, timeZone, now = new Date(), currentUserId = null) {
|
|
27
|
+
if (!/^[A-Za-z0-9_-]{43}$/.test(token))
|
|
28
|
+
return null;
|
|
29
|
+
const zone = validateTimeZone(timeZone);
|
|
30
|
+
const client = await pool.connect();
|
|
31
|
+
try {
|
|
32
|
+
await client.query("BEGIN");
|
|
33
|
+
const proof = await client.query(`SELECT v.email, v.user_id, v.intent FROM notification_email_verifications v
|
|
34
|
+
LEFT JOIN users u ON u.id = v.user_id
|
|
35
|
+
WHERE v.token_hash = $1 AND v.consumed_at IS NULL AND v.expires_at > $2
|
|
36
|
+
AND (v.user_id IS NULL OR u.status = 'active') FOR UPDATE OF v`, [digest(token), now]);
|
|
37
|
+
const row = proof.rows[0];
|
|
38
|
+
if (!row) {
|
|
39
|
+
await client.query("ROLLBACK");
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const email = String(row.email);
|
|
43
|
+
const userId = row.user_id == null ? null : String(row.user_id);
|
|
44
|
+
if (userId && userId !== currentUserId)
|
|
45
|
+
throw Object.assign(new Error("Sign in to the account that requested this confirmation"), { code: "AUTH_REQUIRED" });
|
|
46
|
+
const recipient = await client.query(`INSERT INTO notification_recipients (email, user_id, timezone, verified_at)
|
|
47
|
+
VALUES ($1, $2, $3, $4)
|
|
48
|
+
ON CONFLICT (lower(email)) DO UPDATE SET
|
|
49
|
+
user_id = COALESCE(notification_recipients.user_id, EXCLUDED.user_id),
|
|
50
|
+
timezone = EXCLUDED.timezone, verified_at = EXCLUDED.verified_at, updated_at = $4
|
|
51
|
+
WHERE notification_recipients.user_id IS NULL OR EXCLUDED.user_id IS NULL
|
|
52
|
+
OR notification_recipients.user_id = EXCLUDED.user_id
|
|
53
|
+
RETURNING id`, [email, userId, zone, now]);
|
|
54
|
+
if (!recipient.rows[0])
|
|
55
|
+
throw new Error("Email is linked to another account");
|
|
56
|
+
const recipientId = String(recipient.rows[0].id);
|
|
57
|
+
if (row.intent) {
|
|
58
|
+
const intent = row.intent;
|
|
59
|
+
if (typeof intent.programId !== "string" || !intent.programId || typeof intent.episode !== "boolean"
|
|
60
|
+
|| typeof intent.weekly !== "boolean" || typeof intent.generalSchedule !== "boolean"
|
|
61
|
+
|| typeof intent.source !== "string")
|
|
62
|
+
throw new Error("Invalid verification intent");
|
|
63
|
+
await client.query(`INSERT INTO program_email_subscriptions (recipient_id, program_id, episode_enabled, weekly_enabled, consent_at, consent_source)
|
|
64
|
+
VALUES ($1,$2,$3,$4,$5,$6) ON CONFLICT (recipient_id,program_id) DO UPDATE SET
|
|
65
|
+
episode_enabled = EXCLUDED.episode_enabled, weekly_enabled = EXCLUDED.weekly_enabled,
|
|
66
|
+
consent_at = EXCLUDED.consent_at, consent_source = EXCLUDED.consent_source, updated_at = $5`, [recipientId, intent.programId, intent.episode, intent.weekly, now, intent.source]);
|
|
67
|
+
if (intent.generalSchedule)
|
|
68
|
+
await client.query("UPDATE notification_recipients SET general_schedule_enabled = true, general_schedule_consent_at = $2 WHERE id = $1", [recipientId, now]);
|
|
69
|
+
if (userId)
|
|
70
|
+
await client.query(`INSERT INTO program_follows (user_id,program_id)
|
|
71
|
+
SELECT $1,$2 WHERE EXISTS (SELECT 1 FROM users WHERE id=$1 AND status='active')
|
|
72
|
+
ON CONFLICT (user_id,program_id) DO NOTHING`, [userId, intent.programId]);
|
|
73
|
+
await client.query("INSERT INTO notification_crm_outbox (recipient_id,payload) VALUES ($1,$2::jsonb)", [recipientId, JSON.stringify({ ...intent.attribution, programId: intent.programId, episode: intent.episode,
|
|
74
|
+
weekly: intent.weekly, generalSchedule: intent.generalSchedule, consentSource: intent.source })]);
|
|
75
|
+
await client.query(`INSERT INTO notification_deliveries (recipient_id,kind,occurrence_key,program_id)
|
|
76
|
+
VALUES ($1,'confirmation',$2,$3) ON CONFLICT (recipient_id,kind,occurrence_key) DO NOTHING`, [recipientId, digest(token), intent.programId]);
|
|
77
|
+
}
|
|
78
|
+
await client.query("UPDATE notification_email_verifications SET consumed_at = $2 WHERE token_hash = $1", [digest(token), now]);
|
|
79
|
+
await client.query("COMMIT");
|
|
80
|
+
return { recipientId, email, userId, hasIntent: Boolean(row.intent) };
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
await client.query("ROLLBACK").catch(() => { });
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
finally {
|
|
87
|
+
client.release();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Only the email path is required. CRM delivery is a separate opt-in. */
|
|
2
|
+
export declare function notificationWorkerConfig(env: NodeJS.ProcessEnv): {
|
|
3
|
+
databaseUrl: string;
|
|
4
|
+
apiKey: string;
|
|
5
|
+
from: string;
|
|
6
|
+
publicBaseUrl: string;
|
|
7
|
+
unsubscribeSecret: string;
|
|
8
|
+
allowPrivateHttp: boolean;
|
|
9
|
+
postalAddress: string | undefined;
|
|
10
|
+
crm: {
|
|
11
|
+
endpoint: string;
|
|
12
|
+
secret: string;
|
|
13
|
+
} | undefined;
|
|
14
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { notificationOrigin } from "./origin.js";
|
|
2
|
+
/** Only the email path is required. CRM delivery is a separate opt-in. */
|
|
3
|
+
export function notificationWorkerConfig(env) {
|
|
4
|
+
const required = (name) => {
|
|
5
|
+
const value = env[name]?.trim();
|
|
6
|
+
if (!value)
|
|
7
|
+
throw new Error(`${name} is required`);
|
|
8
|
+
return value;
|
|
9
|
+
};
|
|
10
|
+
if (env.NOTIFICATIONS_WORKER_ENABLED !== "true" || env.DRY_RUN) {
|
|
11
|
+
throw new Error("Notification worker requires NOTIFICATIONS_WORKER_ENABLED=true and must not run in dry-run mode");
|
|
12
|
+
}
|
|
13
|
+
const allowPrivateHttp = env.NOTIFICATIONS_ALLOW_PRIVATE_HTTP === "true";
|
|
14
|
+
const publicBaseUrl = notificationOrigin(required("NOTIFICATIONS_PUBLIC_URL"), allowPrivateHttp).origin;
|
|
15
|
+
const unsubscribeSecret = required("NOTIFICATIONS_UNSUBSCRIBE_SECRET");
|
|
16
|
+
if (Buffer.byteLength(unsubscribeSecret) < 32)
|
|
17
|
+
throw new Error("Notification secret must be at least 32 bytes");
|
|
18
|
+
const crm = env.NOTIFICATIONS_CRM_ENABLED === "true"
|
|
19
|
+
? { endpoint: required("CONSUMER_CRM_INTAKE_URL"), secret: required("CONSUMER_CRM_INGEST_SECRET") }
|
|
20
|
+
: undefined;
|
|
21
|
+
if (crm && (Buffer.byteLength(crm.secret) < 32 || /\s/.test(crm.secret)))
|
|
22
|
+
throw new Error("CRM secret must be at least 32 bytes without whitespace");
|
|
23
|
+
return {
|
|
24
|
+
databaseUrl: required("CENTRAL_DATABASE_URL"), apiKey: required("RESEND_API_KEY"), from: required("RESEND_FROM_EMAIL"),
|
|
25
|
+
publicBaseUrl, unsubscribeSecret, allowPrivateHttp, postalAddress: env.NOTIFICATIONS_POSTAL_ADDRESS?.trim(), crm,
|
|
26
|
+
};
|
|
27
|
+
}
|
package/dist/worker.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/worker.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import pg from "pg";
|
|
2
|
+
import { createResendNotifications } from "./index.js";
|
|
3
|
+
import { enqueueDueNotifications } from "./enqueue.js";
|
|
4
|
+
import { deliverOneNotification } from "./delivery.js";
|
|
5
|
+
import { deliverOneCrmEvent } from "./crm-outbox.js";
|
|
6
|
+
import { notificationWorkerConfig } from "./worker-config.js";
|
|
7
|
+
async function main() {
|
|
8
|
+
const { databaseUrl, apiKey, from, publicBaseUrl, unsubscribeSecret, postalAddress, allowPrivateHttp, crm } = notificationWorkerConfig(process.env);
|
|
9
|
+
const db = new pg.Pool({ connectionString: databaseUrl, max: 4 });
|
|
10
|
+
const notifications = createResendNotifications({ apiKey, from });
|
|
11
|
+
let stopped = false;
|
|
12
|
+
const stop = () => { stopped = true; };
|
|
13
|
+
process.on("SIGINT", stop);
|
|
14
|
+
process.on("SIGTERM", stop);
|
|
15
|
+
try {
|
|
16
|
+
while (!stopped) {
|
|
17
|
+
try {
|
|
18
|
+
await db.query("DELETE FROM notification_rate_limits WHERE expires_at < now() - interval '1 day'");
|
|
19
|
+
await db.query("DELETE FROM notification_email_verifications WHERE expires_at < now() - interval '7 days'");
|
|
20
|
+
await enqueueDueNotifications(db, new Date());
|
|
21
|
+
for (let i = 0; i < 100 && !stopped; i++) {
|
|
22
|
+
if (!await deliverOneNotification({ db, notifications, publicBaseUrl, unsubscribeSecret, postalAddress, allowPrivateHttp }))
|
|
23
|
+
break;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
catch (error) {
|
|
27
|
+
console.error("[notification worker] delivery failed", error);
|
|
28
|
+
}
|
|
29
|
+
if (crm)
|
|
30
|
+
try {
|
|
31
|
+
for (let i = 0; i < 100 && !stopped; i++) {
|
|
32
|
+
if (!await deliverOneCrmEvent({ db, endpoint: crm.endpoint, secret: crm.secret }))
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
console.error("[notification worker] CRM delivery failed", error);
|
|
38
|
+
}
|
|
39
|
+
if (!stopped)
|
|
40
|
+
await new Promise(resolve => setTimeout(resolve, 30_000));
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
await db.end();
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
main().catch(error => { console.error("[notification worker] startup failed", error); process.exitCode = 1; });
|
package/package.json
CHANGED
|
@@ -1,15 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@portalshq/capability-email-notifications",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"repository": {
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"repository": {
|
|
5
|
+
"type": "git",
|
|
6
|
+
"url": "git+https://github.com/portalshq/portals-cloud.git",
|
|
7
|
+
"directory": "packages/capability-email-notifications"
|
|
8
|
+
},
|
|
5
9
|
"description": "Provider-backed email notification delivery.",
|
|
6
10
|
"type": "module",
|
|
7
11
|
"main": "dist/index.js",
|
|
8
12
|
"types": "dist/index.d.ts",
|
|
9
|
-
"exports": {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"types": "./dist/index.d.ts",
|
|
16
|
+
"default": "./dist/index.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"sql",
|
|
22
|
+
"README.md"
|
|
23
|
+
],
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "rm -rf dist && tsc -p tsconfig.json",
|
|
26
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
27
|
+
"worker": "node dist/worker.js",
|
|
28
|
+
"prepack": "npm run build"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"pg": "^8.16.3",
|
|
32
|
+
"resend": "^6.9.3"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"@electric-sql/pglite": "^0.3.16",
|
|
36
|
+
"@types/node": "^20.0.0",
|
|
37
|
+
"@types/pg": "^8.15.5",
|
|
38
|
+
"typescript": "^5.6.3"
|
|
39
|
+
},
|
|
40
|
+
"publishConfig": {
|
|
41
|
+
"access": "public",
|
|
42
|
+
"registry": "https://registry.npmjs.org/"
|
|
43
|
+
}
|
|
15
44
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
-- Up Migration
|
|
2
|
+
-- App follows are independent of email notification subscriptions.
|
|
3
|
+
CREATE TABLE IF NOT EXISTS program_follows (
|
|
4
|
+
user_id text NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
5
|
+
program_id text NOT NULL REFERENCES programs(id) ON DELETE CASCADE,
|
|
6
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
7
|
+
PRIMARY KEY (user_id, program_id)
|
|
8
|
+
);
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
-- Up Migration
|
|
2
|
+
-- New subscriptions are separate from the legacy calendar-invite signups.
|
|
3
|
+
-- Existing records are deliberately not converted into recurring email consent.
|
|
4
|
+
CREATE TABLE notification_recipients (
|
|
5
|
+
id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
|
6
|
+
email text NOT NULL,
|
|
7
|
+
user_id text REFERENCES users(id) ON DELETE SET NULL,
|
|
8
|
+
timezone text NOT NULL,
|
|
9
|
+
verified_at timestamptz,
|
|
10
|
+
general_schedule_enabled boolean NOT NULL DEFAULT false,
|
|
11
|
+
general_schedule_consent_at timestamptz,
|
|
12
|
+
suppressed_at timestamptz,
|
|
13
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
14
|
+
updated_at timestamptz NOT NULL DEFAULT now()
|
|
15
|
+
);
|
|
16
|
+
CREATE UNIQUE INDEX notification_recipients_email ON notification_recipients (lower(email));
|
|
17
|
+
CREATE UNIQUE INDEX notification_recipients_user ON notification_recipients (user_id) WHERE user_id IS NOT NULL;
|
|
18
|
+
|
|
19
|
+
CREATE TABLE program_email_subscriptions (
|
|
20
|
+
recipient_id text NOT NULL REFERENCES notification_recipients(id) ON DELETE CASCADE,
|
|
21
|
+
program_id text NOT NULL REFERENCES programs(id) ON DELETE CASCADE,
|
|
22
|
+
episode_enabled boolean NOT NULL DEFAULT false,
|
|
23
|
+
weekly_enabled boolean NOT NULL DEFAULT false,
|
|
24
|
+
consent_at timestamptz NOT NULL,
|
|
25
|
+
consent_source text NOT NULL,
|
|
26
|
+
updated_at timestamptz NOT NULL DEFAULT now(),
|
|
27
|
+
PRIMARY KEY (recipient_id, program_id)
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
-- Delivery ledger protects against repeat sends across worker instances and retries.
|
|
31
|
+
CREATE TABLE notification_deliveries (
|
|
32
|
+
id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
|
33
|
+
recipient_id text NOT NULL REFERENCES notification_recipients(id) ON DELETE CASCADE,
|
|
34
|
+
kind text NOT NULL CHECK (kind IN ('episode', 'followed_weekly', 'general_weekly', 'confirmation')),
|
|
35
|
+
occurrence_key text NOT NULL,
|
|
36
|
+
program_id text REFERENCES programs(id) ON DELETE CASCADE,
|
|
37
|
+
status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'sending', 'sent', 'cancelled', 'failed')),
|
|
38
|
+
lease_until timestamptz,
|
|
39
|
+
lease_token text,
|
|
40
|
+
first_attempt_at timestamptz,
|
|
41
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
42
|
+
payload jsonb,
|
|
43
|
+
last_error text,
|
|
44
|
+
provider_message_id text,
|
|
45
|
+
created_at timestamptz NOT NULL DEFAULT now(),
|
|
46
|
+
sent_at timestamptz,
|
|
47
|
+
UNIQUE (recipient_id, kind, occurrence_key)
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
-- Tokens are stored as hashes; linking a mailbox to an account requires proof
|
|
51
|
+
-- of mailbox control and never relies on an unverified profile email.
|
|
52
|
+
CREATE TABLE notification_email_verifications (
|
|
53
|
+
token_hash text PRIMARY KEY,
|
|
54
|
+
email text NOT NULL,
|
|
55
|
+
user_id text REFERENCES users(id) ON DELETE CASCADE,
|
|
56
|
+
intent jsonb,
|
|
57
|
+
expires_at timestamptz NOT NULL,
|
|
58
|
+
consumed_at timestamptz,
|
|
59
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
CREATE TABLE notification_rate_limits (
|
|
63
|
+
key text PRIMARY KEY,
|
|
64
|
+
requests integer NOT NULL,
|
|
65
|
+
expires_at timestamptz NOT NULL
|
|
66
|
+
);
|
|
67
|
+
|
|
68
|
+
CREATE TABLE notification_crm_outbox (
|
|
69
|
+
id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
|
70
|
+
recipient_id text NOT NULL REFERENCES notification_recipients(id) ON DELETE CASCADE,
|
|
71
|
+
payload jsonb NOT NULL,
|
|
72
|
+
attempts integer NOT NULL DEFAULT 0,
|
|
73
|
+
next_attempt_at timestamptz NOT NULL DEFAULT now(),
|
|
74
|
+
lease_token text,
|
|
75
|
+
lease_until timestamptz,
|
|
76
|
+
delivered_at timestamptz,
|
|
77
|
+
created_at timestamptz NOT NULL DEFAULT now()
|
|
78
|
+
);
|