@cosmicdrift/kumiko-samples 0.366.0 → 0.367.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.
Files changed (42) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +1 -1
  3. package/packages/bundled-features/src/channel-email/changes.json +6 -0
  4. package/packages/bundled-features/src/channel-email/email-channel.ts +12 -2
  5. package/packages/bundled-features/src/channel-email/feature.ts +1 -1
  6. package/packages/bundled-features/src/delivery/changes.json +12 -0
  7. package/packages/bundled-features/src/delivery/channel-context.ts +1 -0
  8. package/packages/bundled-features/src/delivery/delivery-service.ts +54 -2
  9. package/packages/bundled-features/src/delivery/feature.ts +1 -1
  10. package/packages/bundled-features/src/delivery/handlers/unsubscribe-address.write.ts +10 -5
  11. package/packages/bundled-features/src/delivery/index.ts +6 -0
  12. package/packages/bundled-features/src/delivery/testing.ts +2 -0
  13. package/packages/bundled-features/src/delivery/types.ts +4 -0
  14. package/packages/bundled-features/src/delivery/unsubscribe-link.ts +73 -0
  15. package/packages/bundled-features/src/delivery/unsubscribe-page-strings.ts +17 -0
  16. package/packages/bundled-features/src/delivery/unsubscribe.ts +94 -31
  17. package/packages/bundled-features/src/mail-foundation/feature.ts +50 -9
  18. package/packages/bundled-features/src/mail-foundation/index.ts +3 -0
  19. package/packages/bundled-features/src/template-resolver/changes.json +25 -0
  20. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +61 -9
  21. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +19 -0
  22. package/packages/bundled-features/src/template-resolver/document-schema.ts +33 -0
  23. package/packages/bundled-features/src/template-resolver/handlers/bundle-import.ts +9 -1
  24. package/packages/bundled-features/src/template-resolver/handlers/copy-locale.write.ts +8 -2
  25. package/packages/bundled-features/src/template-resolver/handlers/find-by-id.query.ts +8 -1
  26. package/packages/bundled-features/src/template-resolver/handlers/list.query.ts +6 -1
  27. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +7 -2
  28. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +21 -1
  29. package/packages/bundled-features/src/template-resolver/index.ts +4 -0
  30. package/packages/bundled-features/src/template-resolver/qualified-names.ts +1 -0
  31. package/packages/bundled-features/src/template-resolver/seeding.ts +54 -7
  32. package/packages/bundled-features/src/template-resolver/template-preview.ts +2 -0
  33. package/packages/bundled-features/src/template-resolver/template-system-only.ts +21 -0
  34. package/packages/bundled-features/src/template-resolver/template-validation.ts +48 -24
  35. package/packages/bundled-features/src/template-resolver/web/i18n.ts +2 -0
  36. package/packages/bundled-features/src/user-data-rights/changes.json +6 -0
  37. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  38. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +12 -0
  39. package/samples/apps/ui-walkthrough/src/features/billing/feature.ts +7 -0
  40. package/samples/apps/ui-walkthrough/src/features/billing/i18n.ts +2 -0
  41. package/samples/apps/use-all-bundled/feature-manifest.json +4 -4
  42. package/samples/apps/use-all-bundled/package.json +1 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-samples",
3
- "version": "0.366.0",
3
+ "version": "0.367.0",
4
4
  "description": "Source trees of the Kumiko sample recipes, sample apps and bundled features in repo layout, for tooling such as few-shot corpus builds.",
5
5
  "license": "BUSL-1.1",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmicdrift/kumiko-bundled-features",
3
- "version": "0.366.0",
3
+ "version": "0.367.0",
4
4
  "description": "Built-in features — tenant, user, auth, delivery. The stuff you'd rewrite anyway, already typed.",
5
5
  "license": "BUSL-1.1",
6
6
  "author": "Marc Frost <marc@cosmicdriftgamestudio.com>",
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.367.0",
4
+ "type": "improvement",
5
+ "title": "Email channel can send through the tenant's own mail provider",
6
+ "detail": "EmailChannelOptions gets tenantTransport, a resolver called per send with the delivery channel context. mail-foundation exports tenantMailTransport for it: a tenant with a provider configured sends through its own transport, a broken provider fails the send, a tenant without a provider uses the app transport. The transport is built per send and never cached, and the tenant comes from the server-side delivery context only. ChannelContext now carries the tenant's config accessor as config. Without tenantTransport nothing changes."
7
+ },
2
8
  {
3
9
  "version": "0.365.0",
4
10
  "type": "fix",
@@ -164,7 +164,11 @@ async function resolveAttachments(
164
164
  }
165
165
 
166
166
  export type EmailChannelOptions = {
167
+ /** The app-wide transport, used for every tenant `tenantTransport` returns null for. */
167
168
  readonly transport: EmailTransport;
169
+ /** Resolves the sending tenant's own transport, null when it has none. Built per send and
170
+ * never cached, so a provider change applies to the next mail; a throw fails the send. */
171
+ readonly tenantTransport?: (ctx: ChannelContext) => Promise<EmailTransport | null>;
168
172
  readonly resolveEmail: (
169
173
  userId: string,
170
174
  ctx: { db: unknown; tenantId: TenantId },
@@ -172,7 +176,7 @@ export type EmailChannelOptions = {
172
176
  };
173
177
 
174
178
  export function createEmailChannel(options: EmailChannelOptions): DeliveryChannel {
175
- const { transport, resolveEmail } = options;
179
+ const { transport, resolveEmail, tenantTransport } = options;
176
180
 
177
181
  // Render runs in the delivery.render job, decoupled from the SMTP send so
178
182
  // each can retry independently. Extracted so the inline path (no job runner)
@@ -209,6 +213,11 @@ export function createEmailChannel(options: EmailChannelOptions): DeliveryChanne
209
213
  };
210
214
  }
211
215
 
216
+ async function transportFor(ctx: ChannelContext): Promise<EmailTransport> {
217
+ if (tenantTransport === undefined) return transport;
218
+ return (await tenantTransport(ctx)) ?? transport;
219
+ }
220
+
212
221
  return {
213
222
  name: EMAIL_CHANNEL_NAME,
214
223
  mode: "queued",
@@ -251,7 +260,8 @@ export function createEmailChannel(options: EmailChannelOptions): DeliveryChanne
251
260
  return { status: "failed", error: "send_failed", address };
252
261
  }
253
262
  const resolvedAttachments = resolution.attachments;
254
- await transport.send(
263
+ const sendTransport = await transportFor(ctx);
264
+ await sendTransport.send(
255
265
  guardEmailMessage({
256
266
  to: address,
257
267
  subject,
@@ -10,7 +10,7 @@ export function createChannelEmailFeature(options: EmailChannelOptions): Feature
10
10
 
11
11
  return defineFeature("channel-email", (r) => {
12
12
  r.describe(
13
- "Wires an `EmailTransport` (typically `mail-transport-smtp` in production, `createInMemoryTransport()` in tests) into the delivery system as the `email` channel. Requires `delivery`; pass an `EmailChannelOptions` with a `transport` and a `resolveEmail` function that maps a user ID to their email address. Mails render from stored templates (`renderer-mail-html`): a notification routed to this channel needs `template` + `meta` on `r.notification`, otherwise its delivery fails.",
13
+ "Wires an `EmailTransport` (typically `mail-transport-smtp` in production, `createInMemoryTransport()` in tests) into the delivery system as the `email` channel. Requires `delivery`; pass an `EmailChannelOptions` with a `transport` and a `resolveEmail` function that maps a user ID to their email address. Mails render from stored templates (`renderer-mail-html`): a notification routed to this channel needs `template` + `meta` on `r.notification`, otherwise its delivery fails. Pass `tenantTransport: tenantMailTransport` (from `mail-foundation`) to send each tenant's mail through its own configured provider: a broken provider fails the send, a tenant without one uses the app `transport`. Notifications declared with `unsubscribe: true` get a signed `data.unsubscribeUrl` from delivery, which turns into the `List-Unsubscribe` headers.",
14
14
  );
15
15
  r.uiHints({
16
16
  displayLabel: "Email Channel",
@@ -1,4 +1,16 @@
1
1
  [
2
+ {
3
+ "version": "0.367.0",
4
+ "type": "improvement",
5
+ "title": "Delivery signs unsubscribe links itself",
6
+ "detail": "r.notification(name, { unsubscribe: true }) makes delivery put a signed data.unsubscribeUrl into every email of that notification when the service has unsubscribeLinks. User recipients get a user token, route recipients an address token (only with a blind-index key, otherwise no link). The token is scoped to tenant, notification and channel; a link the caller passes in data.unsubscribeUrl wins. runProdApp option unsubscribe: { secret } mounts createUnsubscribeRoutes and wires the links; the base URL comes from auth.publicOrigin, auth.mail.baseUrl or APP_BASE_URL, and without one boot warns and no link is added."
7
+ },
8
+ {
9
+ "version": "0.367.0",
10
+ "type": "improvement",
11
+ "title": "Unsubscribe links use the tenant's host and the mail's language, apps learn about address opt-outs",
12
+ "detail": "unsubscribeLinks and the runProdApp option unsubscribe take tenantOrigin, an app callback that returns the sending tenant's own origin (subdomain or custom domain) per send; null, a throw or a non-https value fall back to the app origin and never fail the send. The signed token now carries the mail's locale (notify option locale), so the confirmation, result and undo pages render in that language; tokens without it keep working and show English. A form post to the resubscribe route now answers with an HTML page, JSON callers are unchanged. After a committed address opt-out an app job declared with trigger on DeliveryHandlers.unsubscribeAddress receives addressHash, notificationType and channel (unsubscribeAddressPayloadSchema) with the tenant in ctx.triggeredBy.tenantId; hashUnsubscribeAddress(email) matches it to the app's own subscriber. UNSUBSCRIBE_PAGE_EN exports the English page texts, German and Spanish come with the locale packages."
13
+ },
2
14
  {
3
15
  "version": "0.366.0",
4
16
  "type": "improvement",
@@ -153,6 +153,7 @@ export function buildChannelContext(
153
153
  sseBroker,
154
154
  tenantId,
155
155
  secrets,
156
+ config: tenantConfig,
156
157
  renderMail: createTemplateMailRenderer(db, registry, tenantId, tenantConfig),
157
158
  ...(filesForTenant !== undefined && {
158
159
  readAttachment: createEmailAttachmentReader(
@@ -37,6 +37,7 @@ import {
37
37
  DeliveryJobs,
38
38
  deliveryIdempotencyRedisKey,
39
39
  deliveryPriorityRank,
40
+ EMAIL_CHANNEL_NAME,
40
41
  } from "./constants.js";
41
42
  import {
42
43
  type AddressOptOutKey,
@@ -55,6 +56,12 @@ import {
55
56
  isDeliveryChannelPlugin,
56
57
  type RenderedMessage,
57
58
  } from "./types.js";
59
+ import {
60
+ buildUnsubscribeUrl,
61
+ type UnsubscribeLinkConfig,
62
+ type UnsubscribeLinkRecipient,
63
+ unsubscribeLinkOrigin,
64
+ } from "./unsubscribe-link.js";
58
65
 
59
66
  export function redactedMessageOf(err: unknown): string {
60
67
  return redactErrorText(err instanceof Error ? err.message : String(err));
@@ -97,6 +104,9 @@ export type DeliveryServiceOptions = {
97
104
  // absent means an unattributed warn log (see fallbackEscapeHatchReporter).
98
105
  readonly escapeHatchAuditSink?: EscapeHatchAuditSink;
99
106
  readonly log?: Logger;
107
+ // Signs `data.unsubscribeUrl` for email notifications declared with `unsubscribe: true`.
108
+ // The secret must be the one `createUnsubscribeRoutes` verifies with.
109
+ readonly unsubscribeLinks?: UnsubscribeLinkConfig;
100
110
  };
101
111
 
102
112
  // Build channel list from registry extension usages
@@ -128,6 +138,7 @@ export function createDeliveryService(options: DeliveryServiceOptions): Delivery
128
138
  tenantConfigFor,
129
139
  escapeHatchAuditSink,
130
140
  log,
141
+ unsubscribeLinks,
131
142
  } = options;
132
143
  const idemRedis = idempotencyRedis ?? rateLimit?.redis;
133
144
  const logError = createFallbackLogger("delivery", log);
@@ -454,6 +465,37 @@ export function createDeliveryService(options: DeliveryServiceOptions): Delivery
454
465
  }
455
466
  }
456
467
 
468
+ // A caller-supplied unsubscribeUrl wins; the recipient comes from the server-side notify
469
+ // context, never from the notification data.
470
+ async function withUnsubscribeUrl(
471
+ message: ChannelMessage,
472
+ channelName: string,
473
+ recipient: UnsubscribeLinkRecipient,
474
+ channelCtx: ChannelContext,
475
+ ): Promise<ChannelMessage> {
476
+ if (!unsubscribeLinks || channelName !== EMAIL_CHANNEL_NAME) return message;
477
+ if (registry.getAllNotifications().get(message.notificationType)?.unsubscribe !== true) {
478
+ return message;
479
+ }
480
+ const supplied = message.data?.["unsubscribeUrl"];
481
+ if (typeof supplied === "string" && supplied !== "") return message;
482
+ const origin = await unsubscribeLinkOrigin(unsubscribeLinks, channelCtx, (reason) =>
483
+ logError.warn(`unsubscribe link falls back to the app origin: ${reason}`, {
484
+ tenantId: channelCtx.tenantId,
485
+ notificationType: message.notificationType,
486
+ }),
487
+ );
488
+ const unsubscribeUrl = await buildUnsubscribeUrl(unsubscribeLinks, origin, recipient, {
489
+ tenantId: channelCtx.tenantId,
490
+ notificationType: message.notificationType,
491
+ channel: channelName,
492
+ locale: message.locale,
493
+ });
494
+ return unsubscribeUrl === undefined
495
+ ? message
496
+ : { ...message, data: { ...message.data, unsubscribeUrl } };
497
+ }
498
+
457
499
  function buildMessage(
458
500
  notificationType: string,
459
501
  data: Readonly<Record<string, unknown>> | undefined,
@@ -744,7 +786,12 @@ export function createDeliveryService(options: DeliveryServiceOptions): Delivery
744
786
  run,
745
787
  channel,
746
788
  address,
747
- message,
789
+ message: await withUnsubscribeUrl(
790
+ message,
791
+ channel.name,
792
+ { kind: "user", userId },
793
+ channelCtx,
794
+ ),
748
795
  channelCtx,
749
796
  tenantId,
750
797
  recipientId: userId,
@@ -842,7 +889,12 @@ export function createDeliveryService(options: DeliveryServiceOptions): Delivery
842
889
  run,
843
890
  channel,
844
891
  address,
845
- message,
892
+ message: await withUnsubscribeUrl(
893
+ message,
894
+ channel.name,
895
+ { kind: "address", address },
896
+ channelCtx,
897
+ ),
846
898
  channelCtx,
847
899
  tenantId,
848
900
  recipientId,
@@ -61,7 +61,7 @@ export function createDeliveryFeature(options?: DeliveryFeatureOptions): Feature
61
61
  const attemptLogRetentionDays = resolveAttemptLogRetentionDays(options?.attemptLogRetentionDays);
62
62
  return defineFeature("delivery", (r) => {
63
63
  r.describe(
64
- 'The notification dispatch core: call `ctx.notify(notificationType, { to, route, data, priority, idempotencyKey })` from any handler to fan out a notification across all registered channels (email, in-app, push). Inside a write handler the delivery runs after the write has committed (the call returns `{ kind: "deferred" }`, a rolled-back write sends nothing); `immediate: true` delivers synchronously and returns `{ kind: "dispatched", deliveries }`. It stores per-user channel preferences in the `notification-preference` entity, opt-outs for no-account recipient addresses in `notification-address-opt-out` (keyed by a blind-index hash, never the plaintext address), logs every attempt to `store_delivery_attempts`, and enforces idempotency and rate-limiting \u2014 add `channel-email`, `channel-in-app`, or `channel-push` on top to actually send anything. Unsubscribe/resubscribe links are served by `createUnsubscribeRoutes({ secret })` mounted via the app\'s `extraRoutes` at `/api/delivery/unsubscribe` and `/api/delivery/resubscribe`: `GET /unsubscribe?token=` renders a confirmation page (no write), `POST /unsubscribe` performs the opt-out (RFC 8058 one-click, token from the form body or query), `POST /resubscribe` undoes it (JSON `{token}` or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with `signUnsubscribeToken` / `signAddressUnsubscribeToken` using the same secret. `channel-email` sets `List-Unsubscribe` / `List-Unsubscribe-Post` automatically when a message\'s `data.unsubscribeUrl` points at the unsubscribe route.',
64
+ "The notification dispatch core: call `ctx.notify(notificationType, { to, route, data, priority, idempotencyKey })` from any handler to fan out a notification across all registered channels (email, in-app, push). Inside a write handler the delivery runs after the write has committed (the call returns `{ kind: \"deferred\" }`, a rolled-back write sends nothing); `immediate: true` delivers synchronously and returns `{ kind: \"dispatched\", deliveries }`. It stores per-user channel preferences in the `notification-preference` entity, opt-outs for no-account recipient addresses in `notification-address-opt-out` (keyed by a blind-index hash, never the plaintext address), logs every attempt to `store_delivery_attempts`, and enforces idempotency and rate-limiting \u2014 add `channel-email`, `channel-in-app`, or `channel-push` on top to actually send anything. Unsubscribe/resubscribe links are served by `createUnsubscribeRoutes({ secret })` mounted via the app's `extraRoutes` at `/api/delivery/unsubscribe` and `/api/delivery/resubscribe`: `GET /unsubscribe?token=` renders a confirmation page (no write), `POST /unsubscribe` performs the opt-out (RFC 8058 one-click, token from the form body or query), `POST /resubscribe` undoes it (JSON `{token}` or form body only, never the query — reachable by a mail-client link prefetcher) — sign links with `signUnsubscribeToken` / `signAddressUnsubscribeToken` using the same secret. `channel-email` sets `List-Unsubscribe` / `List-Unsubscribe-Post` automatically when a message's `data.unsubscribeUrl` points at the unsubscribe route. A notification declared with `unsubscribe: true` gets that link from delivery itself when the service has `unsubscribeLinks` (`runProdApp` option `unsubscribe: { secret }` mounts the routes and wires it; base URL from `auth.publicOrigin`, `auth.mail.baseUrl` or `APP_BASE_URL`): user recipients get a user token, `route` recipients an address token (needs a blind-index key, otherwise no link); a `data.unsubscribeUrl` from the caller wins. `unsubscribe.tenantOrigin: (ctx) => origin | null` points the link at the tenant's own host (subdomain or custom domain, must serve this app's `/api`); null, a throw or a non-https value fall back to the app origin. The token carries the mail's locale, so the confirmation and result pages render in the mail's language. To react to a no-account opt-out (e.g. remove the app's own subscriber row), declare `r.job(name, { trigger: { on: DeliveryHandlers.unsubscribeAddress } }, handler)` on a lane the app consumes: it runs after each committed opt-out, also an idempotent repeat, with `unsubscribeAddressPayloadSchema` (`addressHash`, `notificationType`, `channel`) as payload and the tenant in `ctx.triggeredBy.tenantId`; match the subscriber via `hashUnsubscribeAddress(email)`. Declare `unsubscribeUrl` as an optional template variable if the mail body shows it.",
65
65
  );
66
66
  r.uiHints({
67
67
  displayLabel: "Notifications \u00b7 Dispatch Core",
@@ -4,13 +4,18 @@ import * as z from "zod";
4
4
  import { upsertAddressOptOut } from "../address-opt-out.js";
5
5
  import { currentNotificationType } from "../notification-type-aliases.js";
6
6
 
7
+ // Also the payload an app job receives with `trigger: { on: DeliveryHandlers.unsubscribeAddress }`
8
+ // after a committed address opt-out (the tenant is the job's `ctx.triggeredBy.tenantId`).
9
+ export const unsubscribeAddressPayloadSchema = z.object({
10
+ addressHash: z.string().min(1),
11
+ notificationType: z.string().min(1),
12
+ channel: z.string().min(1),
13
+ });
14
+ export type UnsubscribeAddressPayload = z.infer<typeof unsubscribeAddressPayloadSchema>;
15
+
7
16
  export const unsubscribeAddressWrite = defineWriteHandler({
8
17
  name: "unsubscribeAddress",
9
- schema: z.object({
10
- addressHash: z.string().min(1),
11
- notificationType: z.string().min(1),
12
- channel: z.string().min(1),
13
- }),
18
+ schema: unsubscribeAddressPayloadSchema,
14
19
  access: { roles: access.systemAdmin },
15
20
  // Only reachable via createUnsubscribeRoutes' POST dispatchSystemWrite, once
16
21
  // verify() has already proven the address-token signature — not a surface
@@ -63,6 +63,10 @@ export {
63
63
  type RateLimitConfig,
64
64
  } from "./delivery-service.js";
65
65
  export { createDeliveryFeature, type DeliveryFeatureOptions } from "./feature.js";
66
+ export {
67
+ type UnsubscribeAddressPayload,
68
+ unsubscribeAddressPayloadSchema,
69
+ } from "./handlers/unsubscribe-address.write.js";
66
70
  export { createDeliveryNotifyFactory } from "./notify-factory.js";
67
71
  export {
68
72
  deliveryAttemptsTable,
@@ -94,3 +98,5 @@ export {
94
98
  type UnsubscribeRouteOptions,
95
99
  type UnsubscribeTokenPayload,
96
100
  } from "./unsubscribe.js";
101
+ export type { UnsubscribeLinkConfig } from "./unsubscribe-link.js";
102
+ export { UNSUBSCRIBE_PAGE_EN } from "./unsubscribe-page-strings.js";
@@ -15,6 +15,7 @@ import type { KillSwitchResolver, RateLimitConfig } from "./delivery-service.js"
15
15
  import { collectChannels, createDeliveryService } from "./delivery-service.js";
16
16
  import { createDeliveryNotifyFactory } from "./notify-factory.js";
17
17
  import type { DeliveryService } from "./types.js";
18
+ import type { UnsubscribeLinkConfig } from "./unsubscribe-link.js";
18
19
 
19
20
  export type CreateDeliveryTestContextOptions = {
20
21
  readonly tenantUserIdsQuery?: string;
@@ -27,6 +28,7 @@ export type CreateDeliveryTestContextOptions = {
27
28
  readonly idempotencyRedis?: Redis;
28
29
  readonly filesForTenant?: (tenantId: string) => FileContext | undefined;
29
30
  readonly tenantConfigFor?: (tenantId: TenantId) => ConfigAccessor;
31
+ readonly unsubscribeLinks?: UnsubscribeLinkConfig;
30
32
  };
31
33
 
32
34
  /**
@@ -1,6 +1,7 @@
1
1
  import type { SseBroker } from "@cosmicdrift/kumiko-framework/api";
2
2
  import type { DbConnection, TenantDb } from "@cosmicdrift/kumiko-framework/db";
3
3
  import type {
4
+ ConfigAccessor,
4
5
  DeliveryErrorCode,
5
6
  NotifyDeliveryStatus,
6
7
  NotifyDispatched,
@@ -39,6 +40,9 @@ export type ChannelContext = {
39
40
  // Chat channels read their per-tenant webhook URL / bot token from it.
40
41
  // Absent when no secrets feature/KEK is wired.
41
42
  readonly secrets?: SecretsContext | undefined;
43
+ // The tenant's own config accessor, built server-side for this tenantId. Absent when the
44
+ // delivery service has no tenantConfigFor and the job context carries no config.
45
+ readonly config?: ConfigAccessor | undefined;
42
46
  // Renders a stored mail template, the tenant's own or the system fallback.
43
47
  readonly renderMail?: (payload: MailPayload) => Promise<RenderedMail>;
44
48
  // Reads the bytes behind an attachment ref at send time. Absent when no file storage is wired.
@@ -0,0 +1,73 @@
1
+ import { publicOriginOf } from "@cosmicdrift/kumiko-framework/api";
2
+ import type { TenantId } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { hashUnsubscribeAddress } from "./address-opt-out.js";
4
+ import { DELIVERY_UNSUBSCRIBE_PATH } from "./constants.js";
5
+ import type { ChannelContext } from "./types.js";
6
+ import { signAddressUnsubscribeToken, signUnsubscribeToken } from "./unsubscribe.js";
7
+
8
+ /** Secret shared with `createUnsubscribeRoutes` plus the public origin the links point at. */
9
+ export type UnsubscribeLinkConfig = {
10
+ readonly secret: string;
11
+ readonly baseUrl: string;
12
+ /** The sending tenant's own public origin (subdomain or custom domain), null when it has
13
+ * none. The host must serve this app's `/api` routes. Null, a throw or an unusable value
14
+ * fall back to `baseUrl`, so a missing tenant origin never fails a send. */
15
+ readonly tenantOrigin?: (ctx: ChannelContext) => Promise<string | null | undefined>;
16
+ };
17
+
18
+ export type UnsubscribeLinkRecipient =
19
+ | { readonly kind: "user"; readonly userId: string }
20
+ | { readonly kind: "address"; readonly address: string };
21
+
22
+ // https only, unless the app itself runs on plain http (local dev): a tenant origin must not
23
+ // downgrade the link that carries the token.
24
+ function isUsableTenantOrigin(origin: string, baseUrl: string): boolean {
25
+ return (
26
+ origin.startsWith("https://") || (baseUrl.startsWith("http://") && origin.startsWith("http://"))
27
+ );
28
+ }
29
+
30
+ export async function unsubscribeLinkOrigin(
31
+ config: UnsubscribeLinkConfig,
32
+ ctx: ChannelContext,
33
+ onFallback: (reason: string) => void,
34
+ ): Promise<string> {
35
+ if (config.tenantOrigin === undefined) return config.baseUrl;
36
+ let resolved: string | null | undefined;
37
+ try {
38
+ resolved = await config.tenantOrigin(ctx);
39
+ } catch (err) {
40
+ onFallback(`tenantOrigin threw (${err instanceof Error ? err.name : typeof err})`);
41
+ return config.baseUrl;
42
+ }
43
+ if (resolved === null || resolved === undefined) return config.baseUrl;
44
+ const origin = publicOriginOf(resolved);
45
+ if (origin === undefined || !isUsableTenantOrigin(origin, config.baseUrl)) {
46
+ onFallback("tenantOrigin returned no usable https origin");
47
+ return config.baseUrl;
48
+ }
49
+ return origin;
50
+ }
51
+
52
+ // Undefined means "no link": without a blind-index key an address opt-out could never be
53
+ // matched again, and a mail without a link is better than a failed send.
54
+ export async function buildUnsubscribeUrl(
55
+ config: UnsubscribeLinkConfig,
56
+ origin: string,
57
+ recipient: UnsubscribeLinkRecipient,
58
+ scope: {
59
+ tenantId: TenantId;
60
+ notificationType: string;
61
+ channel: string;
62
+ locale: string | undefined;
63
+ },
64
+ ): Promise<string | undefined> {
65
+ if (recipient.kind === "address" && hashUnsubscribeAddress(recipient.address) === undefined) {
66
+ return undefined;
67
+ }
68
+ const token =
69
+ recipient.kind === "user"
70
+ ? await signUnsubscribeToken({ ...scope, userId: recipient.userId }, config.secret)
71
+ : await signAddressUnsubscribeToken({ ...scope, address: recipient.address }, config.secret);
72
+ return `${origin}${DELIVERY_UNSUBSCRIBE_PATH}?token=${encodeURIComponent(token)}`;
73
+ }
@@ -0,0 +1,17 @@
1
+ import { registerMailTranslations } from "@cosmicdrift/kumiko-framework/i18n";
2
+
3
+ // The pages behind a mailed unsubscribe link speak the mail's language, so their texts live in
4
+ // the mail translations: English here, other languages in the locale packages.
5
+ export const UNSUBSCRIBE_PAGE_EN = {
6
+ "mail.unsubscribe.confirmTitle": "Unsubscribe",
7
+ "mail.unsubscribe.confirmQuestion": "Unsubscribe from these emails?",
8
+ "mail.unsubscribe.confirmButton": "Unsubscribe",
9
+ "mail.unsubscribe.doneTitle": "Unsubscribed",
10
+ "mail.unsubscribe.doneMessage": "You have been unsubscribed.",
11
+ "mail.unsubscribe.undoButton": "Undo",
12
+ "mail.unsubscribe.resubscribedTitle": "Subscribed again",
13
+ "mail.unsubscribe.resubscribedMessage": "You have been subscribed again.",
14
+ "mail.unsubscribe.failed": "That did not work. Please try again later.",
15
+ } as const;
16
+
17
+ registerMailTranslations("en", UNSUBSCRIBE_PAGE_EN);