@happyvertical/smrt-messages 0.60.13 → 0.60.15

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 (57) hide show
  1. package/AGENTS.md +13 -0
  2. package/agents/notification-outbox.md +125 -2
  3. package/agents/profile-recipients.md +32 -0
  4. package/agents/scoped-attachment-test-matrix.md +46 -0
  5. package/dist/chunks/{AccountCollection-B7Nen_TO.js → AccountCollection-DBEG6nR7.js} +6 -7
  6. package/dist/chunks/AccountCollection-DBEG6nR7.js.map +1 -0
  7. package/dist/chunks/{Email-CnlwhWa0.js → Email-p5qIyMC5.js} +3 -3
  8. package/dist/chunks/{Email-CnlwhWa0.js.map → Email-p5qIyMC5.js.map} +1 -1
  9. package/dist/chunks/{EmailFolder-ukdMVI0c.js → EmailFolder-Dk4hxikK.js} +3 -3
  10. package/dist/chunks/EmailFolder-Dk4hxikK.js.map +1 -0
  11. package/dist/chunks/{Message-CinnTgyw.js → Message-hIwx07Kt.js} +72 -11
  12. package/dist/chunks/Message-hIwx07Kt.js.map +1 -0
  13. package/dist/chunks/{MessageCollection-BquAmxgU.js → MessageCollection-BwnE4a_L.js} +3 -3
  14. package/dist/chunks/MessageCollection-BwnE4a_L.js.map +1 -0
  15. package/dist/chunks/__smrt-register__-D3kBjvML.js +6 -0
  16. package/dist/chunks/__smrt-register__-D3kBjvML.js.map +1 -0
  17. package/dist/chunks/protected-notification-handoff-mvaEZVp7.js +358 -0
  18. package/dist/chunks/protected-notification-handoff-mvaEZVp7.js.map +1 -0
  19. package/dist/host.browser.d.ts +18 -0
  20. package/dist/host.browser.d.ts.map +1 -0
  21. package/dist/host.browser.js +27 -0
  22. package/dist/host.browser.js.map +1 -0
  23. package/dist/host.d.ts +19 -0
  24. package/dist/host.d.ts.map +1 -0
  25. package/dist/host.js +35 -0
  26. package/dist/host.js.map +1 -0
  27. package/dist/index.d.ts +3 -1
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +589 -67
  30. package/dist/index.js.map +1 -1
  31. package/dist/manifest.json +317 -14
  32. package/dist/migrations/profileRecipients.d.ts +17 -0
  33. package/dist/migrations/profileRecipients.d.ts.map +1 -0
  34. package/dist/models/Account.d.ts.map +1 -1
  35. package/dist/models/Message.d.ts +7 -0
  36. package/dist/models/Message.d.ts.map +1 -1
  37. package/dist/models/NotificationDelivery.d.ts +20 -3
  38. package/dist/models/NotificationDelivery.d.ts.map +1 -1
  39. package/dist/notification-recipient-identity.d.ts +17 -0
  40. package/dist/notification-recipient-identity.d.ts.map +1 -0
  41. package/dist/permissions.d.ts +1 -1
  42. package/dist/permissions.d.ts.map +1 -1
  43. package/dist/protected-notification-handoff.d.ts +31 -0
  44. package/dist/protected-notification-handoff.d.ts.map +1 -0
  45. package/dist/recipes.d.ts +1 -1
  46. package/dist/senders/EmailSender.d.ts.map +1 -1
  47. package/dist/services/NotificationOutboxService.d.ts +51 -3
  48. package/dist/services/NotificationOutboxService.d.ts.map +1 -1
  49. package/dist/smrt-knowledge.json +184 -12
  50. package/dist/smrt-knowledge.okf.md +7 -2
  51. package/package.json +13 -9
  52. package/dist/chunks/AccountCollection-B7Nen_TO.js.map +0 -1
  53. package/dist/chunks/EmailFolder-ukdMVI0c.js.map +0 -1
  54. package/dist/chunks/Message-CinnTgyw.js.map +0 -1
  55. package/dist/chunks/MessageCollection-BquAmxgU.js.map +0 -1
  56. package/dist/chunks/__smrt-register__-Dz163WBB.js +0 -6
  57. package/dist/chunks/__smrt-register__-Dz163WBB.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,16 +1,18 @@
1
1
  import { t as __exportAll } from "./chunks/rolldown-runtime-D7D4PA-g.js";
2
- import "./chunks/__smrt-register__-Dz163WBB.js";
2
+ import "./chunks/__smrt-register__-D3kBjvML.js";
3
3
  import { a as registerMessagingProvider, n as getMessagingProvider, o as ZulipSender, r as listMessagingProviders, s as TelegramSender, t as ensureBuiltinMessagingProvidersRegistered } from "./chunks/providers-4iLula-V.js";
4
- import { r as Account, t as AccountCollection } from "./chunks/AccountCollection-B7Nen_TO.js";
5
- import { t as Message } from "./chunks/Message-CinnTgyw.js";
6
- import { t as MessageCollection } from "./chunks/MessageCollection-BquAmxgU.js";
7
- import { t as Email } from "./chunks/Email-CnlwhWa0.js";
8
- import { t as EmailFolder } from "./chunks/EmailFolder-ukdMVI0c.js";
4
+ import { buildSqliteRebuildStatements, isDeepStrictEqual, normalizeIdentityEmail, queryGlobal, queryWithGlobals, readNotificationProfile, withSystemContext, withTenant } from "./host.js";
5
+ import { r as Account, t as AccountCollection } from "./chunks/AccountCollection-DBEG6nR7.js";
6
+ import { d as withProtectedNotificationHandoff, f as PROFILE_NOTIFICATION_POLICY_PREFIX, l as protectedNotificationMetadata, m as profileNotificationPolicy, n as assertProtectedEmailAdmission, p as assertNotificationRecipientIdentity, r as assertProtectedEmailHandoff, t as ProtectedNotificationHandoffError } from "./chunks/protected-notification-handoff-mvaEZVp7.js";
7
+ import { t as Message } from "./chunks/Message-hIwx07Kt.js";
8
+ import { t as MessageCollection } from "./chunks/MessageCollection-BwnE4a_L.js";
9
+ import { t as Email } from "./chunks/Email-p5qIyMC5.js";
10
+ import { t as EmailFolder } from "./chunks/EmailFolder-Dk4hxikK.js";
9
11
  import { t as SlackSender } from "./chunks/SlackSender-CjSvwY1K.js";
10
12
  import { t as TweetSender } from "./chunks/TweetSender-CcLPNNi1.js";
11
- import { SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, field, foreignKey, importOptionalDependency, isUniqueViolationError, smrt, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue } from "@happyvertical/smrt-core";
12
- import { registerPermissionDefinitions } from "@happyvertical/smrt-users";
13
- import { TenantScoped, queryGlobal, queryWithGlobals, tenantId, withSystemContext, withTenant } from "@happyvertical/smrt-tenancy";
13
+ import { GlobalInterceptors, SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, detectEngine, field, foreignKey, importOptionalDependency, isUniqueViolationError, smrt, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue } from "@happyvertical/smrt-core";
14
+ import { registerPermissionDefinitions } from "@happyvertical/smrt-users/permission-registry";
15
+ import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
14
16
  //#region src/permissions.ts
15
17
  var SEND_MESSAGES_PERMISSION = "messages.send";
16
18
  var MANAGE_MESSAGE_ROUTES_PERMISSION = "messages.manage-routes";
@@ -107,7 +109,7 @@ var Attachment = class extends SmrtObject {
107
109
  */
108
110
  async getMessage() {
109
111
  if (!this.messageId) return null;
110
- const { MessageCollection } = await import("./chunks/MessageCollection-BquAmxgU.js").then((n) => n.n);
112
+ const { MessageCollection } = await import("./chunks/MessageCollection-BwnE4a_L.js").then((n) => n.n);
111
113
  return await (await MessageCollection.create(this.options)).get({ id: this.messageId });
112
114
  }
113
115
  /**
@@ -432,12 +434,23 @@ var TRANSITION_COLUMNS = {
432
434
  providerMessageId: "provider_message_id",
433
435
  lastError: "last_error"
434
436
  };
437
+ var saveGuards = /* @__PURE__ */ new WeakMap();
438
+ var activeSaves = /* @__PURE__ */ new WeakSet();
439
+ var saveGuardInterceptor = {
440
+ writeGuard: (instance) => saveGuards.get(instance),
441
+ bulkMutation: { compatible: (className) => className !== "NotificationDelivery" && className !== "@happyvertical/smrt-messages:NotificationDelivery" }
442
+ };
435
443
  var NotificationDelivery = class extends SmrtObject {
436
444
  tenantId = "";
437
- recipientUserId = "";
445
+ recipientUserId = null;
446
+ recipientProfileId = null;
447
+ recipientKind = "user";
438
448
  channel = "email";
439
449
  sourceRef = "";
440
450
  kind = "";
451
+ /** Trusted host policy required at every provider handoff; empty is legacy ordinary mail. */
452
+ requiredDispatchPolicy = "";
453
+ dispatchPolicyBinding = "{}";
441
454
  subject = "";
442
455
  textBody = "";
443
456
  href = "";
@@ -477,9 +490,13 @@ var NotificationDelivery = class extends SmrtObject {
477
490
  for (const key of [
478
491
  "tenantId",
479
492
  "recipientUserId",
493
+ "recipientProfileId",
494
+ "recipientKind",
480
495
  "channel",
481
496
  "sourceRef",
482
497
  "kind",
498
+ "requiredDispatchPolicy",
499
+ "dispatchPolicyBinding",
483
500
  "subject",
484
501
  "textBody",
485
502
  "href",
@@ -501,6 +518,73 @@ var NotificationDelivery = class extends SmrtObject {
501
518
  "lastError"
502
519
  ]) assign(key);
503
520
  }
521
+ /** Protected consent and document bindings cannot be downgraded by ordinary saves. */
522
+ async save(options) {
523
+ if (activeSaves.has(this)) throw new Error("Concurrent saves of one notification delivery are not supported.");
524
+ activeSaves.add(this);
525
+ try {
526
+ return await this.saveWithGuard(options);
527
+ } finally {
528
+ saveGuards.delete(this);
529
+ activeSaves.delete(this);
530
+ }
531
+ }
532
+ async saveWithGuard(options) {
533
+ assertNotificationRecipientIdentity(this);
534
+ if (this.kind.startsWith("protected:") && (!this.requiredDispatchPolicy || this.kind !== `protected:${this.requiredDispatchPolicy}`)) throw new Error("Protected notification kinds require their exact dispatch policy.");
535
+ await this.verifyStorageReady();
536
+ let stored;
537
+ if (this.id) {
538
+ const { rows } = await this.db.query("SELECT tenant_id, required_dispatch_policy, dispatch_policy_binding, source_ref, recipient_user_id, recipient_profile_id, recipient_kind, recipient_address, account_id, kind, subject, text_body, href, recipient_name, channel, status, state_version, transition_id, attempts, max_attempts, next_attempt_at, lease_token, lease_expires_at, handed_off_at, delivered_at, provider_message_id, last_error, message_id FROM notification_deliveries WHERE id = ?", this.id);
539
+ stored = rows[0];
540
+ }
541
+ if (!stored) stored = (await this.db.query("SELECT * FROM notification_deliveries WHERE tenant_id=? AND recipient_kind=? AND recipient_user_id IS NOT DISTINCT FROM ? AND recipient_profile_id IS NOT DISTINCT FROM ? AND channel=? AND source_ref=?", this.tenantId, this.recipientKind, this.recipientUserId, this.recipientProfileId, this.channel, this.sourceRef)).rows[0];
542
+ if (stored && (stored.required_dispatch_policy || this.requiredDispatchPolicy)) {
543
+ const binding = (value) => typeof value === "string" ? JSON.parse(value) : value;
544
+ const instant = (value) => value == null ? null : new Date(value).getTime();
545
+ if (stored.status !== this.status || Number(stored.state_version) !== this.stateVersion || stored.transition_id !== this.transitionId || Number(stored.attempts) !== this.attempts || Number(stored.max_attempts) !== this.maxAttempts || stored.lease_token !== this.leaseToken || stored.message_id !== this.messageId || stored.provider_message_id !== this.providerMessageId || stored.last_error !== this.lastError || instant(stored.next_attempt_at) !== instant(this.nextAttemptAt) || instant(stored.lease_expires_at) !== instant(this.leaseExpiresAt) || instant(stored.handed_off_at) !== instant(this.handedOffAt) || instant(stored.delivered_at) !== instant(this.deliveredAt)) throw new Error("Protected notification lifecycle changes require a guarded transition.");
546
+ if (stored.tenant_id !== this.tenantId || stored.required_dispatch_policy !== this.requiredDispatchPolicy || !isDeepStrictEqual(binding(stored.dispatch_policy_binding), binding(this.dispatchPolicyBinding)) || stored.source_ref !== this.sourceRef || stored.recipient_user_id !== this.recipientUserId || stored.recipient_profile_id !== this.recipientProfileId || stored.recipient_kind !== this.recipientKind || stored.recipient_address !== this.recipientAddress || stored.account_id !== this.accountId || stored.channel !== this.channel || stored.recipient_name !== this.recipientName || stored.kind !== this.kind || stored.subject !== this.subject || stored.text_body !== this.textBody || stored.href !== this.href) throw new Error("Protected notification consent and dispatch policy are immutable.");
547
+ }
548
+ const guard = stored?.required_dispatch_policy || this.requiredDispatchPolicy ? Object.fromEntries([
549
+ "tenant_id",
550
+ "required_dispatch_policy",
551
+ "dispatch_policy_binding",
552
+ "source_ref",
553
+ "recipient_user_id",
554
+ "recipient_profile_id",
555
+ "recipient_kind",
556
+ "recipient_address",
557
+ "recipient_name",
558
+ "account_id",
559
+ "kind",
560
+ "channel",
561
+ "subject",
562
+ "text_body",
563
+ "href",
564
+ "status",
565
+ "state_version",
566
+ "transition_id",
567
+ "attempts",
568
+ "max_attempts",
569
+ "lease_token",
570
+ "message_id",
571
+ "provider_message_id",
572
+ "last_error"
573
+ ].map((column) => [column, stored ? stored[column] : this[column.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())]])) : {
574
+ required_dispatch_policy: stored ? stored.required_dispatch_policy : "",
575
+ kind: stored ? stored.kind : this.kind
576
+ };
577
+ if (!stored && this.requiredDispatchPolicy) this.requireInsertOnSave();
578
+ saveGuards.set(this, guard);
579
+ if (!GlobalInterceptors.getAll().includes(saveGuardInterceptor)) GlobalInterceptors.register(saveGuardInterceptor);
580
+ return super.save(options);
581
+ }
582
+ /** Protected history must survive mutable caller flags and uncertain outcomes. */
583
+ async delete() {
584
+ const stored = this.id ? await this.db.get(this.tableName, { id: this.id }) : null;
585
+ if (stored?.required_dispatch_policy || String(stored?.kind ?? "").startsWith("protected:")) throw new Error("Protected notification delivery history cannot be deleted.");
586
+ return super.delete();
587
+ }
504
588
  /** Whether no further automatic work will happen on this row. */
505
589
  get isSettled() {
506
590
  return this.status === "sent" || this.status === "failed" || this.status === "cancelled" || this.status === "uncertain";
@@ -558,10 +642,13 @@ var NotificationDelivery = class extends SmrtObject {
558
642
  };
559
643
  __publicField$12(NotificationDelivery, "__smrtPackage__", "@happyvertical/smrt-messages");
560
644
  __decorateClass$12([tenantId()], NotificationDelivery.prototype, "tenantId", 2);
561
- __decorateClass$12([crossPackageRef("@happyvertical/smrt-users:User", { required: true })], NotificationDelivery.prototype, "recipientUserId", 2);
645
+ __decorateClass$12([crossPackageRef("@happyvertical/smrt-users:User", { nullable: true })], NotificationDelivery.prototype, "recipientUserId", 2);
646
+ __decorateClass$12([crossPackageRef("@happyvertical/smrt-profiles:Profile", { nullable: true })], NotificationDelivery.prototype, "recipientProfileId", 2);
647
+ __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "recipientKind", 2);
562
648
  __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "channel", 2);
563
649
  __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "sourceRef", 2);
564
650
  __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "kind", 2);
651
+ __decorateClass$12([field({ type: "json" })], NotificationDelivery.prototype, "dispatchPolicyBinding", 2);
565
652
  __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "subject", 2);
566
653
  __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "textBody", 2);
567
654
  __decorateClass$12([field({ required: true })], NotificationDelivery.prototype, "href", 2);
@@ -575,17 +662,42 @@ NotificationDelivery = __decorateClass$12([TenantScoped({ mode: "required" }), s
575
662
  cli: false,
576
663
  conflictColumns: [
577
664
  "tenant_id",
665
+ "recipient_kind",
578
666
  "recipient_user_id",
667
+ "recipient_profile_id",
579
668
  "channel",
580
669
  "source_ref"
581
670
  ],
582
- indexes: [{
583
- name: "notification_deliveries_due_idx",
584
- columns: ["status", "nextAttemptAt"]
585
- }, {
586
- name: "notification_deliveries_lease_idx",
587
- columns: ["status", "leaseExpiresAt"]
588
- }]
671
+ indexes: [
672
+ {
673
+ name: "notification_deliveries_user_identity",
674
+ columns: [
675
+ "tenantId",
676
+ "recipientUserId",
677
+ "channel",
678
+ "sourceRef"
679
+ ],
680
+ unique: true
681
+ },
682
+ {
683
+ name: "notification_deliveries_profile_identity",
684
+ columns: [
685
+ "tenantId",
686
+ "recipientProfileId",
687
+ "channel",
688
+ "sourceRef"
689
+ ],
690
+ unique: true
691
+ },
692
+ {
693
+ name: "notification_deliveries_due_idx",
694
+ columns: ["status", "nextAttemptAt"]
695
+ },
696
+ {
697
+ name: "notification_deliveries_lease_idx",
698
+ columns: ["status", "leaseExpiresAt"]
699
+ }
700
+ ]
589
701
  })], NotificationDelivery);
590
702
  //#endregion
591
703
  //#region src/collections/NotificationDeliveryCollection.ts
@@ -944,7 +1056,7 @@ var EmailAccount = class extends Account {
944
1056
  for (const folderName of foldersToSync) try {
945
1057
  let folder = await folderCollection.getByPath(accountId, folderName);
946
1058
  if (!folder) {
947
- const { EmailFolder } = await import("./chunks/EmailFolder-ukdMVI0c.js").then((n) => n.n);
1059
+ const { EmailFolder } = await import("./chunks/EmailFolder-Dk4hxikK.js").then((n) => n.n);
948
1060
  folder = new EmailFolder({
949
1061
  ...this.childOptions(),
950
1062
  accountId,
@@ -969,7 +1081,7 @@ var EmailAccount = class extends Account {
969
1081
  result.messagesSkipped++;
970
1082
  continue;
971
1083
  }
972
- const { Email } = await import("./chunks/Email-CnlwhWa0.js").then((n) => n.n);
1084
+ const { Email } = await import("./chunks/Email-p5qIyMC5.js").then((n) => n.n);
973
1085
  let email = existingEmail;
974
1086
  if (!email) {
975
1087
  email = new Email({
@@ -2201,6 +2313,7 @@ var EmailSender = class {
2201
2313
  const bccAddresses = message.getBccAddresses();
2202
2314
  let attachments;
2203
2315
  try {
2316
+ await assertProtectedEmailAdmission(message, options);
2204
2317
  attachments = await this.collectAttachments(message, options);
2205
2318
  } catch (error) {
2206
2319
  return {
@@ -2233,6 +2346,7 @@ var EmailSender = class {
2233
2346
  attachments: attachments.length > 0 ? attachments : void 0
2234
2347
  };
2235
2348
  try {
2349
+ await assertProtectedEmailHandoff(message, attachments, options, emailMessage);
2236
2350
  const result = await this.client.send(emailMessage);
2237
2351
  return {
2238
2352
  success: true,
@@ -2246,7 +2360,7 @@ var EmailSender = class {
2246
2360
  return {
2247
2361
  success: false,
2248
2362
  error: error instanceof Error ? error.message : String(error),
2249
- ...isDefiniteSendRejection(error) ? {} : { outcomeUnknown: true },
2363
+ ...error instanceof ProtectedNotificationHandoffError || isDefiniteSendRejection(error) ? {} : { outcomeUnknown: true },
2250
2364
  sentAt: /* @__PURE__ */ new Date()
2251
2365
  };
2252
2366
  }
@@ -2272,7 +2386,7 @@ var EmailSender = class {
2272
2386
  filename: attachment.filename,
2273
2387
  contentType: attachment.contentType || "application/octet-stream",
2274
2388
  size: content.length,
2275
- content,
2389
+ content: Buffer.from(content),
2276
2390
  contentId: attachment.contentId || void 0,
2277
2391
  contentDisposition: attachment.contentDisposition
2278
2392
  });
@@ -2280,7 +2394,7 @@ var EmailSender = class {
2280
2394
  for (const attachment of options?.attachments ?? []) {
2281
2395
  if (!attachment.filename) throw new Error("A send-time attachment needs a filename.");
2282
2396
  if (!attachment.content) throw new Error(`Send-time attachment "${attachment.filename}" has no content.`);
2283
- const content = Buffer.isBuffer(attachment.content) ? attachment.content : Buffer.from(attachment.content.buffer, attachment.content.byteOffset, attachment.content.byteLength);
2397
+ const content = Buffer.from(attachment.content);
2284
2398
  resolved.push({
2285
2399
  filename: attachment.filename,
2286
2400
  contentType: attachment.contentType || "application/octet-stream",
@@ -2659,12 +2773,214 @@ function optOutSuppression(service, scopeOf) {
2659
2773
  };
2660
2774
  }
2661
2775
  //#endregion
2776
+ //#region src/migrations/profileRecipients.ts
2777
+ var table = "notification_deliveries";
2778
+ var checkName = "notification_deliveries_recipient_identity_check";
2779
+ var userIndex = "notification_deliveries_user_identity";
2780
+ var profileIndex = "notification_deliveries_profile_identity";
2781
+ var typedIndex = "notification_deliveries_typed_identity";
2782
+ var identityCheck = `(recipient_kind IS NOT NULL AND ((recipient_kind = 'user' AND recipient_user_id IS NOT NULL AND length(trim(CAST(recipient_user_id AS TEXT))) > 0 AND recipient_profile_id IS NULL AND (required_dispatch_policy IS NULL OR required_dispatch_policy NOT LIKE 'profile:%') AND kind NOT LIKE 'protected:profile:%') OR (recipient_kind = 'profile' AND recipient_user_id IS NULL AND recipient_profile_id IS NOT NULL AND length(trim(CAST(recipient_profile_id AS TEXT))) > 0 AND channel = 'email' AND required_dispatch_policy IS NOT NULL AND length(trim(required_dispatch_policy)) > 8 AND required_dispatch_policy LIKE 'profile:%' AND kind = 'protected:' || required_dispatch_policy)))`;
2783
+ function canonicalCheck(sql) {
2784
+ const value = sql.trim().replace(/^CHECK\s*/i, "").replace(/::text\b/gi, "").replace(/!~~/g, " NOT LIKE ").replace(/~~/g, " LIKE ").replace(/CAST\(\s*([a-z_]+)\s+AS\s+TEXT\s*\)/gi, "$1").replace(/TRIM\(\s*BOTH\s+FROM\s+/gi, "trim(");
2785
+ function outer(text) {
2786
+ text = text.trim();
2787
+ while (text.startsWith("(") && text.endsWith(")")) {
2788
+ let depth = 0, quoted = false, complete = true;
2789
+ for (let i = 0; i < text.length - 1; i++) {
2790
+ if (text[i] === "'") quoted = !quoted;
2791
+ if (quoted) continue;
2792
+ if (text[i] === "(") depth++;
2793
+ if (text[i] === ")" && --depth === 0) {
2794
+ complete = false;
2795
+ break;
2796
+ }
2797
+ }
2798
+ if (!complete) break;
2799
+ text = text.slice(1, -1).trim();
2800
+ }
2801
+ return text;
2802
+ }
2803
+ function parse(text) {
2804
+ text = outer(text);
2805
+ for (const op of ["OR", "AND"]) {
2806
+ let depth = 0, quoted = false, start = 0;
2807
+ const terms = [];
2808
+ for (let i = 0; i < text.length; i++) {
2809
+ if (text[i] === "'") quoted = !quoted;
2810
+ if (quoted) continue;
2811
+ if (text[i] === "(") depth++;
2812
+ if (text[i] === ")") depth--;
2813
+ if (!depth && text.slice(i).match(new RegExp("^" + op + "\\b", "i")) && (i === 0 || /\s/.test(text[i - 1]))) {
2814
+ terms.push(text.slice(start, i));
2815
+ start = i + op.length;
2816
+ i += op.length - 1;
2817
+ }
2818
+ }
2819
+ if (terms.length) return [op, ...[...terms, text.slice(start)].map(parse)];
2820
+ }
2821
+ return text.toLowerCase().replace(/[\s()"]/g, "");
2822
+ }
2823
+ return JSON.stringify(parse(value));
2824
+ }
2825
+ var quote = (name) => {
2826
+ if (!/^[a-z_][a-z0-9_]*$/i.test(name)) throw new Error("Unsafe notification schema identifier.");
2827
+ return `"${name}"`;
2828
+ };
2829
+ function indexColumns(sql) {
2830
+ const match = /\(([^()]+)\)\s*(?:NULLS\s+NOT\s+DISTINCT)?\s*$/i.exec(sql);
2831
+ return match ? match[1].split(",").map((s) => s.trim().replaceAll("\"", "")) : [];
2832
+ }
2833
+ function same(a, b) {
2834
+ return a.length === b.length && a.every((v, i) => v === b[i]);
2835
+ }
2836
+ var userColumns = [
2837
+ "tenant_id",
2838
+ "recipient_user_id",
2839
+ "channel",
2840
+ "source_ref"
2841
+ ];
2842
+ var profileColumns = [
2843
+ "tenant_id",
2844
+ "recipient_profile_id",
2845
+ "channel",
2846
+ "source_ref"
2847
+ ];
2848
+ var typedColumns = [
2849
+ "tenant_id",
2850
+ "recipient_kind",
2851
+ "recipient_user_id",
2852
+ "recipient_profile_id",
2853
+ "channel",
2854
+ "source_ref"
2855
+ ];
2856
+ async function inspect(db, engine) {
2857
+ if (engine !== "sqlite" && engine !== "postgres") throw new Error("Profile recipients require SQLite or PostgreSQL maintenance.");
2858
+ const columns = engine === "sqlite" ? (await db.query(`PRAGMA table_info(${quote(table)})`)).rows : (await db.query("SELECT column_name AS name, CASE WHEN is_nullable='NO' THEN 1 ELSE 0 END AS notnull FROM information_schema.columns WHERE table_schema=current_schema() AND table_name=?", table)).rows;
2859
+ if (!columns.length) throw new Error("Migrate the notification outbox table before profile recipient maintenance.");
2860
+ const indexes = engine === "sqlite" ? (await db.query("SELECT name, sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND sql IS NOT NULL", table)).rows : (await db.query("SELECT indexname AS name, indexdef AS sql FROM pg_indexes WHERE schemaname=current_schema() AND tablename=?", table)).rows;
2861
+ const ddl = engine === "sqlite" ? String((await db.query("SELECT sql FROM sqlite_master WHERE type='table' AND name=?", table)).rows[0]?.sql ?? "") : String((await db.query("SELECT pg_get_constraintdef(oid) AS sql FROM pg_constraint WHERE conrelid=?::regclass AND conname=?", table, checkName)).rows[0]?.sql ?? "");
2862
+ const obsolete = indexes.filter((i) => /NULLS\s+NOT\s+DISTINCT/i.test(i.sql) && same(indexColumns(i.sql), userColumns));
2863
+ const validIndex = (name, expected) => indexes.some((i) => i.name === name && /CREATE\s+UNIQUE\s+INDEX/i.test(i.sql) && same(indexColumns(i.sql), expected) && !(/NULLS\s+NOT\s+DISTINCT/i.test(i.sql) && name !== typedIndex));
2864
+ const hasColumns = ["recipient_kind", "recipient_profile_id"].every((name) => columns.some((c) => c.name === name));
2865
+ const hasCheck = engine === "sqlite" ? ddl.includes(checkName) && ddl.includes(identityCheck) : !ddl.includes("NOT VALID") && canonicalCheck(ddl) === canonicalCheck(identityCheck);
2866
+ return {
2867
+ columns,
2868
+ indexes,
2869
+ ddl,
2870
+ obsolete,
2871
+ ready: hasColumns && !Number(columns.find((c) => c.name === "recipient_user_id")?.notnull) && hasCheck && !obsolete.length && validIndex(userIndex, userColumns) && validIndex(profileIndex, profileColumns) && validIndex(typedIndex, typedColumns),
2872
+ hasColumns,
2873
+ hasCheck,
2874
+ validIndex
2875
+ };
2876
+ }
2877
+ async function planNotificationProfileRecipients(db, engine) {
2878
+ const state = await inspect(db, engine);
2879
+ const result = {
2880
+ engine,
2881
+ ready: state.ready,
2882
+ statements: [],
2883
+ invalidRowIds: [],
2884
+ obsoleteIndexes: state.obsolete.map((i) => i.name)
2885
+ };
2886
+ if (state.ready) return result;
2887
+ const kind = state.columns.some((c) => c.name === "recipient_kind") ? "recipient_kind" : "'user'";
2888
+ const profile = state.columns.some((c) => c.name === "recipient_profile_id") ? "recipient_profile_id" : "NULL";
2889
+ const rows = (await db.query(`SELECT id, tenant_id, recipient_user_id, ${kind} AS recipient_kind, ${profile} AS recipient_profile_id, channel, source_ref, kind, required_dispatch_policy FROM ${quote(table)}`)).rows;
2890
+ const identities = /* @__PURE__ */ new Set();
2891
+ for (const row of rows) {
2892
+ const user = row.recipient_kind === "user" && row.recipient_user_id != null && String(row.recipient_user_id).trim() !== "" && row.recipient_profile_id == null;
2893
+ const contact = row.recipient_kind === "profile" && row.recipient_user_id == null && row.recipient_profile_id != null && String(row.recipient_profile_id).trim() !== "" && row.channel === "email" && typeof row.required_dispatch_policy === "string" && Boolean(row.required_dispatch_policy.trim()) && row.kind === `protected:${row.required_dispatch_policy}`;
2894
+ const key = JSON.stringify([
2895
+ row.tenant_id,
2896
+ row.recipient_kind,
2897
+ row.recipient_user_id,
2898
+ row.recipient_profile_id,
2899
+ row.channel,
2900
+ row.source_ref
2901
+ ]);
2902
+ if (!(user || contact) || identities.has(key)) result.invalidRowIds.push(String(row.id));
2903
+ identities.add(key);
2904
+ }
2905
+ if (result.invalidRowIds.length) return result;
2906
+ for (const [name, columns] of [
2907
+ [userIndex, userColumns],
2908
+ [profileIndex, profileColumns],
2909
+ [typedIndex, typedColumns]
2910
+ ]) if (state.indexes.find((i) => i.name === name) && !state.validIndex(name, [...columns])) throw new Error(`Unexpected notification index drift: ${name}`);
2911
+ if (engine === "postgres") {
2912
+ if (!state.columns.some((c) => c.name === "recipient_kind")) result.statements.push(`ALTER TABLE ${quote(table)} ADD COLUMN recipient_kind TEXT NOT NULL DEFAULT 'user'`);
2913
+ if (!state.columns.some((c) => c.name === "recipient_profile_id")) result.statements.push(`ALTER TABLE ${quote(table)} ADD COLUMN recipient_profile_id UUID REFERENCES profiles(id)`);
2914
+ result.statements.push(`ALTER TABLE ${quote(table)} ALTER COLUMN recipient_user_id DROP NOT NULL`);
2915
+ if (!state.hasCheck) {
2916
+ if (state.ddl) throw new Error("Unexpected notification identity CHECK drift.");
2917
+ result.statements.push(`ALTER TABLE ${quote(table)} ADD CONSTRAINT ${quote(checkName)} CHECK ${identityCheck}`);
2918
+ }
2919
+ for (const index of state.obsolete) result.statements.push(`DROP INDEX ${quote(index.name)}`);
2920
+ } else if (!state.hasColumns || Number(state.columns.find((c) => c.name === "recipient_user_id")?.notnull) || !state.hasCheck) {
2921
+ const incoming = (await db.query("SELECT name, sql FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name<>?", table)).rows;
2922
+ for (const row of incoming) if ((await db.query(`PRAGMA foreign_key_list(${quote(String(row.name))})`)).rows.some((r) => r.table === table)) throw new Error("SQLite profile maintenance requires an explicit inbound-FK-safe migration window.");
2923
+ if (!/\)\s*;?\s*$/.test(state.ddl)) throw new Error("Unsupported SQLite notification table shape.");
2924
+ if (state.ddl.includes(checkName) && !state.hasCheck) throw new Error("Unexpected notification identity CHECK drift.");
2925
+ const ddl = state.hasCheck ? state.ddl : state.ddl.replace(/\)\s*;?\s*$/, `, CONSTRAINT ${quote(checkName)} CHECK ${identityCheck})`);
2926
+ const triggers = (await db.query("SELECT name,sql FROM sqlite_master WHERE type='trigger' AND tbl_name=?", table)).rows;
2927
+ const plan = buildSqliteRebuildStatements({
2928
+ tableName: table,
2929
+ createTableSql: ddl,
2930
+ columnTypes: /* @__PURE__ */ new Map(),
2931
+ columns: state.columns.map((c) => c.name),
2932
+ objects: [...state.indexes, ...triggers],
2933
+ legacyAlterTable: Boolean((await db.query("PRAGMA legacy_alter_table")).rows[0]?.legacy_alter_table),
2934
+ nullableColumns: new Set(Number(state.columns.find((c) => c.name === "recipient_user_id")?.notnull) ? ["recipient_user_id"] : []),
2935
+ appendColumns: [...!state.columns.some((c) => c.name === "recipient_kind") ? [{
2936
+ name: "recipient_kind",
2937
+ definition: "recipient_kind TEXT NOT NULL DEFAULT 'user'",
2938
+ copyExpression: "'user'"
2939
+ }] : [], ...!state.columns.some((c) => c.name === "recipient_profile_id") ? [{
2940
+ name: "recipient_profile_id",
2941
+ definition: "recipient_profile_id UUID REFERENCES profiles(id)",
2942
+ copyExpression: "NULL"
2943
+ }] : []]
2944
+ });
2945
+ if (!plan) throw new Error("SQLite profile identity rebuild requires manual schema reconciliation.");
2946
+ if (plan.statements.some((s) => /PRAGMA foreign_keys\s*=\s*OFF/i.test(s))) throw new Error("SQLite profile maintenance cannot disable foreign keys.");
2947
+ result.statements.push(...plan.statements);
2948
+ }
2949
+ for (const [name, columns] of [
2950
+ [userIndex, userColumns],
2951
+ [profileIndex, profileColumns],
2952
+ [typedIndex, typedColumns]
2953
+ ]) if (!state.validIndex(name, [...columns])) result.statements.push(`CREATE UNIQUE INDEX ${quote(name)} ON ${quote(table)} (${columns.map(quote).join(", ")})${engine === "postgres" && name === typedIndex ? " NULLS NOT DISTINCT" : ""}`);
2954
+ return result;
2955
+ }
2956
+ async function migrateNotificationProfileRecipients(db, engine) {
2957
+ if (!db.transaction) throw new Error("Notification profile migration requires transactions.");
2958
+ let result;
2959
+ await db.transaction(async (tx) => {
2960
+ if (engine === "postgres") await tx.query(`LOCK TABLE ${quote(table)} IN ACCESS EXCLUSIVE MODE`);
2961
+ const plan = await planNotificationProfileRecipients(tx, engine);
2962
+ if (plan.invalidRowIds.length) throw new Error(`Invalid notification recipient rows: ${plan.invalidRowIds.join(", ")}`);
2963
+ for (const statement of plan.statements) await tx.query(statement);
2964
+ if (!(await planNotificationProfileRecipients(tx, engine)).ready) throw new Error("Notification profile schema did not reach verified constraints.");
2965
+ result = plan;
2966
+ });
2967
+ if (!result) throw new Error("Notification profile migration transaction did not execute.");
2968
+ return result;
2969
+ }
2970
+ async function assertNotificationProfileRecipientSchema(db) {
2971
+ const hint = Reflect.get(db, "type");
2972
+ const engine = detectEngine(db.url, typeof hint === "string" ? hint : void 0);
2973
+ if (engine !== "sqlite" && engine !== "postgres") throw new Error("Profile recipients require explicit supported schema maintenance.");
2974
+ if (!(await inspect(db, engine)).ready) throw new Error("Profile recipient schema maintenance is required.");
2975
+ }
2976
+ //#endregion
2662
2977
  //#region src/services/NotificationOutboxService.ts
2663
2978
  var messageSendTransport = {
2664
2979
  name: "message-send",
2665
2980
  idempotent: false,
2666
- async send({ message }) {
2667
- const result = await message.send();
2981
+ async send({ message, attachments }) {
2982
+ const options = attachments ? { attachments } : void 0;
2983
+ const result = await message.send(options);
2668
2984
  if (result.success) return {
2669
2985
  status: "accepted",
2670
2986
  ...result.providerMessageId ? { providerMessageId: result.providerMessageId } : {}
@@ -2773,6 +3089,14 @@ var NotificationOutboxService = class {
2773
3089
  if (!Number.isInteger(this.maxAttempts) || this.maxAttempts < 1) throw new Error("Notification maxAttempts must be a positive integer.");
2774
3090
  }
2775
3091
  options;
3092
+ /** Additive dispatch contracts hosts can require before activating a sender. */
3093
+ static capabilities = Object.freeze({
3094
+ deliverySelection: true,
3095
+ attachments: true,
3096
+ requiredPolicy: true,
3097
+ protectedCanonicalSend: true,
3098
+ profileRecipients: true
3099
+ });
2776
3100
  transport;
2777
3101
  leaseMs;
2778
3102
  maxAttempts;
@@ -2792,7 +3116,24 @@ var NotificationOutboxService = class {
2792
3116
  /** Store one email delivery for the event unless `sourceRef` already has one. */
2793
3117
  async enqueueEmail(input) {
2794
3118
  const tenantId = requireText$1(input.tenantId, "tenant");
2795
- const recipientUserId = requireText$1(input.recipientUserId, "recipient");
3119
+ if (input.kind?.startsWith("protected:") && input.kind !== `protected:${input.requiredDispatchPolicy}`) throw new Error("Protected notification kinds require their exact dispatch policy.");
3120
+ const requiredDispatchPolicy = input.requiredDispatchPolicy === void 0 ? "" : requireText$1(input.requiredDispatchPolicy, "dispatch policy");
3121
+ if (requiredDispatchPolicy && !this.dispatchPolicy(requiredDispatchPolicy)) throw new NotificationOutboxDeniedError("permission", "Required notification dispatch policy is unavailable.");
3122
+ if (requiredDispatchPolicy && (!input.dispatchPolicyBinding || typeof input.dispatchPolicyBinding !== "object" || Array.isArray(input.dispatchPolicyBinding) || !Object.keys(input.dispatchPolicyBinding).length)) throw new Error("Protected notification requires an approved dispatch policy binding.");
3123
+ const dispatchPolicyBinding = JSON.stringify(input.dispatchPolicyBinding ?? {});
3124
+ const profilePath = input.recipientProfileId !== void 0;
3125
+ if (profilePath === (input.recipientUserId !== void 0)) throw new NotificationOutboxDeniedError("recipient", "Choose exactly one typed recipient.");
3126
+ const recipientUserId = profilePath ? null : requireText$1(input.recipientUserId, "recipient");
3127
+ const recipientProfileId = profilePath ? requireText$1(input.recipientProfileId, "profile recipient") : null;
3128
+ const recipientKind = profilePath ? "profile" : "user";
3129
+ assertNotificationRecipientIdentity({
3130
+ recipientKind,
3131
+ recipientUserId,
3132
+ recipientProfileId,
3133
+ channel: "email",
3134
+ kind: input.kind,
3135
+ requiredDispatchPolicy
3136
+ });
2796
3137
  const sourceRef = requireText$1(input.sourceRef, "sourceRef");
2797
3138
  const kind = requireText$1(input.kind, "kind");
2798
3139
  const subject = requireText$1(input.subject, "subject");
@@ -2800,24 +3141,34 @@ var NotificationOutboxService = class {
2800
3141
  if (/[\r\n]/u.test(subject)) throw new Error("A notification subject must be a single line.");
2801
3142
  const channel = "email";
2802
3143
  this.authorize(tenantId);
3144
+ if (profilePath) await assertNotificationProfileRecipientSchema((await this.collection()).db);
2803
3145
  const href = buildNotificationLink(this.options.linkBaseUrl, input.path);
2804
3146
  return withTenant({ tenantId }, async () => {
2805
3147
  const deliveries = await this.collection();
2806
3148
  const findExisting = async () => (await deliveries.list({
2807
3149
  where: {
2808
3150
  tenantId,
3151
+ recipientKind,
2809
3152
  recipientUserId,
3153
+ recipientProfileId,
2810
3154
  channel,
2811
3155
  sourceRef
2812
3156
  },
2813
3157
  limit: 1
2814
3158
  }))[0];
2815
3159
  const existing = await findExisting();
2816
- if (existing) return {
2817
- delivery: existing,
2818
- created: false
2819
- };
2820
- const recipient = await this.options.resolveRecipient({
3160
+ if (existing) {
3161
+ if (recipientProfileId) await this.validateProfileDelivery(existing);
3162
+ return {
3163
+ delivery: existing,
3164
+ created: false
3165
+ };
3166
+ }
3167
+ const recipient = recipientProfileId ? await this.resolveProfile({
3168
+ tenantId,
3169
+ recipientProfileId,
3170
+ channel
3171
+ }) : await this.options.resolveRecipient({
2821
3172
  tenantId,
2822
3173
  recipientUserId,
2823
3174
  channel
@@ -2827,7 +3178,11 @@ var NotificationOutboxService = class {
2827
3178
  const accountId = await this.requireSenderAccount(tenantId);
2828
3179
  const suppressed = await this.isSuppressed({
2829
3180
  tenantId,
2830
- recipientUserId,
3181
+ ...recipientUserId ? { recipientUserId } : {},
3182
+ ...recipientProfileId ? {
3183
+ recipientProfileId,
3184
+ recipientKind: "profile"
3185
+ } : {},
2831
3186
  channel,
2832
3187
  kind,
2833
3188
  sourceRef
@@ -2838,9 +3193,13 @@ var NotificationOutboxService = class {
2838
3193
  _insertOnly: true,
2839
3194
  tenantId,
2840
3195
  recipientUserId,
3196
+ recipientProfileId,
3197
+ recipientKind,
2841
3198
  channel,
2842
3199
  sourceRef,
2843
3200
  kind,
3201
+ requiredDispatchPolicy,
3202
+ dispatchPolicyBinding,
2844
3203
  subject,
2845
3204
  textBody: text,
2846
3205
  href,
@@ -2878,13 +3237,48 @@ var NotificationOutboxService = class {
2878
3237
  async dispatchDue(options = {}) {
2879
3238
  const limit = Math.min(options.limit ?? DEFAULT_LIMIT$1, MAX_LIMIT$1);
2880
3239
  if (!Number.isInteger(limit) || limit < 1) throw new Error("Notification dispatch limit must be a positive integer.");
2881
- const candidates = await this.findDue(options.tenantIds, limit);
3240
+ let tenantIds = options.tenantIds;
3241
+ if (this.options.principal && tenantIds === void 0) {
3242
+ const tenantId = this.options.principal.tenantId;
3243
+ if (!tenantId) throw new NotificationOutboxDeniedError("permission", "A messaging principal must select explicit dispatch tenants.");
3244
+ tenantIds = [tenantId];
3245
+ }
3246
+ if (tenantIds !== void 0) {
3247
+ tenantIds = [...new Set(tenantIds.map((id) => requireText$1(id, "tenant")))];
3248
+ for (const tenantId of tenantIds) this.authorize(tenantId);
3249
+ }
3250
+ const deliveryIds = options.deliveryIds === void 0 ? void 0 : [...new Set(options.deliveryIds)];
3251
+ if (deliveryIds?.some((id) => typeof id !== "string" || !UUID_PATTERN$1.test(id))) throw new Error("Notification dispatch delivery ids must be UUIDs.");
2882
3252
  const report = {
2883
3253
  leased: 0,
2884
3254
  outcomes: []
2885
3255
  };
2886
- for (const candidate of candidates) {
3256
+ if (tenantIds?.length === 0 || deliveryIds?.length === 0) return report;
3257
+ for await (const candidate of this.findDue(tenantIds, limit, deliveryIds)) {
2887
3258
  if (report.leased >= limit) break;
3259
+ this.authorize(candidate.tenantId);
3260
+ if (candidate.kind.startsWith("protected:") && candidate.kind !== `protected:${candidate.requiredDispatchPolicy}` || candidate.requiredDispatchPolicy && !this.dispatchPolicy(candidate.requiredDispatchPolicy)) {
3261
+ const lastError = "Blocked: required notification dispatch policy is unavailable.";
3262
+ if (candidate.lastError !== lastError) await withTenant({ tenantId: candidate.tenantId }, () => candidate.transition({ lastError }));
3263
+ report.outcomes.push({
3264
+ deliveryId: candidate.id,
3265
+ tenantId: candidate.tenantId,
3266
+ outcome: "blocked"
3267
+ });
3268
+ continue;
3269
+ }
3270
+ try {
3271
+ await withTenant({ tenantId: candidate.tenantId }, () => this.validateProfileDelivery(candidate));
3272
+ } catch (cause) {
3273
+ const lastError = `Blocked: ${errorText(cause)}`;
3274
+ if (candidate.lastError !== lastError) await withTenant({ tenantId: candidate.tenantId }, () => candidate.transition({ lastError }));
3275
+ report.outcomes.push({
3276
+ deliveryId: candidate.id,
3277
+ tenantId: candidate.tenantId,
3278
+ outcome: "blocked"
3279
+ });
3280
+ continue;
3281
+ }
2888
3282
  const outcome = await withTenant({ tenantId: candidate.tenantId }, () => this.dispatchOne(candidate));
2889
3283
  if (!outcome) continue;
2890
3284
  report.leased += 1;
@@ -2964,32 +3358,115 @@ var NotificationOutboxService = class {
2964
3358
  return account.id;
2965
3359
  }
2966
3360
  async isSuppressed(request) {
2967
- return Boolean(await this.options.isSuppressed?.(request));
3361
+ if (request.recipientProfileId) return Boolean(await this.options.isProfileSuppressed?.({
3362
+ tenantId: request.tenantId,
3363
+ recipientProfileId: request.recipientProfileId,
3364
+ channel: "email",
3365
+ kind: request.kind,
3366
+ sourceRef: request.sourceRef
3367
+ }));
3368
+ if (!request.recipientUserId) throw new NotificationOutboxDeniedError("recipient", "Missing typed suppression recipient.");
3369
+ return Boolean(await this.options.isSuppressed?.({
3370
+ tenantId: request.tenantId,
3371
+ recipientUserId: request.recipientUserId,
3372
+ channel: request.channel,
3373
+ kind: request.kind,
3374
+ sourceRef: request.sourceRef
3375
+ }));
2968
3376
  }
2969
- async findDue(tenantIds, limit) {
2970
- const now = this.now();
2971
- const read = async (tenantFilter) => {
2972
- const deliveries = await this.collection();
2973
- const [due, expired] = await Promise.all([deliveries.list({
2974
- where: {
2975
- ...tenantFilter,
2976
- status: "pending",
2977
- "nextAttemptAt <=": now
2978
- },
2979
- orderBy: "nextAttemptAt ASC",
2980
- limit
2981
- }), deliveries.list({
2982
- where: {
2983
- ...tenantFilter,
2984
- status: "sending",
2985
- "leaseExpiresAt <=": now
2986
- },
2987
- orderBy: "leaseExpiresAt ASC",
2988
- limit
2989
- })]);
2990
- return [...expired, ...due];
3377
+ async resolveProfile(request) {
3378
+ const db = (await this.collection()).db;
3379
+ const profile = await readNotificationProfile(db, request.tenantId, request.recipientProfileId);
3380
+ const resolved = await this.options.resolveProfileRecipient?.(request);
3381
+ const address = profile?.email ? normalizeIdentityEmail(profile.email) : "";
3382
+ if (!profile || profile.tenantId !== request.tenantId || !address || containsControlCharacter(address) || !/^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/u.test(address) || !resolved?.address || normalizeIdentityEmail(resolved.address) !== address) throw new NotificationOutboxDeniedError("recipient", "Current tenant-owned profile email is not authorized.");
3383
+ if (resolved.name && containsControlCharacter(resolved.name)) throw new NotificationOutboxDeniedError("recipient", "Malformed profile recipient display name.");
3384
+ return {
3385
+ address,
3386
+ name: resolved.name?.trim() ?? ""
2991
3387
  };
2992
- return (tenantIds === void 0 ? await withSystemContext(() => read({})) : (await Promise.all([...new Set(tenantIds.filter(Boolean))].map((tenantId) => withTenant({ tenantId }, () => read({ tenantId }))))).flat()).slice(0, limit * 2);
3388
+ }
3389
+ async validateProfileDelivery(delivery) {
3390
+ assertNotificationRecipientIdentity(delivery);
3391
+ if (delivery.recipientKind !== "profile") return;
3392
+ await assertNotificationProfileRecipientSchema((await this.collection()).db);
3393
+ const current = await this.resolveProfile({
3394
+ tenantId: delivery.tenantId,
3395
+ recipientProfileId: delivery.recipientProfileId,
3396
+ channel: "email"
3397
+ });
3398
+ if (current.address !== delivery.recipientAddress || (current.name ?? "") !== delivery.recipientName) throw new NotificationOutboxDeniedError("recipient", "Approved profile recipient changed; review again.");
3399
+ }
3400
+ dispatchPolicy(id) {
3401
+ const policies = this.options.dispatchPolicies;
3402
+ if (!policies || !Object.hasOwn(policies, id)) return void 0;
3403
+ const policy = policies[id];
3404
+ return typeof policy?.resolveAttachments === "function" ? policy : void 0;
3405
+ }
3406
+ async *findDue(tenantIds, limit, deliveryIds) {
3407
+ const now = this.now();
3408
+ const visited = /* @__PURE__ */ new Set();
3409
+ for (const phase of [{
3410
+ status: "sending",
3411
+ column: "lease_expires_at"
3412
+ }, {
3413
+ status: "pending",
3414
+ column: "next_attempt_at"
3415
+ }]) for (const tenantId of tenantIds ?? [void 0]) {
3416
+ let cursor;
3417
+ for (;;) {
3418
+ const read = async () => {
3419
+ const deliveries = await this.collection();
3420
+ const table = `"${deliveries.tableName.replaceAll("\"", "\"\"")}"`;
3421
+ const conditions = ["status = ?", `${phase.column} <= ?`];
3422
+ const values = [phase.status, now.toISOString()];
3423
+ if (tenantId !== void 0) {
3424
+ conditions.push("tenant_id = ?");
3425
+ values.push(tenantId);
3426
+ }
3427
+ if (deliveryIds) {
3428
+ conditions.push(`id IN (${deliveryIds.map(() => "?").join(",")})`);
3429
+ values.push(...deliveryIds);
3430
+ }
3431
+ if (cursor) {
3432
+ conditions.push(`(${phase.column} > ? OR (${phase.column} = ? AND id > ?))`);
3433
+ values.push(cursor.cursor_at, cursor.cursor_at, cursor.id);
3434
+ }
3435
+ const positions = (await deliveries.db.query(`SELECT id, CAST(${phase.column} AS TEXT) AS cursor_at FROM ${table}
3436
+ WHERE ${conditions.join(" AND ")}
3437
+ ORDER BY ${phase.column} ASC, id ASC LIMIT ?`, ...values, limit)).rows;
3438
+ if (positions.some((row) => typeof row.id !== "string" || !UUID_PATTERN$1.test(row.id) || typeof row.cursor_at !== "string" || !row.cursor_at)) throw new Error("Invalid notification dispatch cursor.");
3439
+ if (!positions.length) return {
3440
+ positions,
3441
+ rows: []
3442
+ };
3443
+ const rows = await deliveries.list({
3444
+ where: {
3445
+ ...tenantId === void 0 ? {} : { tenantId },
3446
+ id: positions.map((row) => row.id)
3447
+ },
3448
+ limit: positions.length
3449
+ });
3450
+ const byId = new Map(rows.map((row) => [row.id, row]));
3451
+ return {
3452
+ positions,
3453
+ rows: positions.flatMap((row) => {
3454
+ const delivery = byId.get(row.id);
3455
+ return delivery ? [delivery] : [];
3456
+ })
3457
+ };
3458
+ };
3459
+ const page = tenantId === void 0 ? await withSystemContext(read) : await withTenant({ tenantId }, read);
3460
+ if (!page.positions.length) break;
3461
+ cursor = page.positions[page.positions.length - 1];
3462
+ for (const row of page.rows) {
3463
+ if (!row.id || visited.has(row.id)) continue;
3464
+ visited.add(row.id);
3465
+ yield row;
3466
+ }
3467
+ if (page.positions.length < limit) break;
3468
+ }
3469
+ }
2993
3470
  }
2994
3471
  /** Lease one candidate and carry it to an outcome; null when not leased. */
2995
3472
  async dispatchOne(candidate) {
@@ -3022,7 +3499,11 @@ var NotificationOutboxService = class {
3022
3499
  }
3023
3500
  if (await this.isSuppressed({
3024
3501
  tenantId: delivery.tenantId,
3025
- recipientUserId: delivery.recipientUserId,
3502
+ ...delivery.recipientUserId ? { recipientUserId: delivery.recipientUserId } : {},
3503
+ ...delivery.recipientProfileId ? {
3504
+ recipientProfileId: delivery.recipientProfileId,
3505
+ recipientKind: "profile"
3506
+ } : {},
3026
3507
  channel: delivery.channel,
3027
3508
  kind: delivery.kind,
3028
3509
  sourceRef: delivery.sourceRef
@@ -3030,18 +3511,37 @@ var NotificationOutboxService = class {
3030
3511
  status: "cancelled",
3031
3512
  lastError: "Suppressed by recipient preference."
3032
3513
  });
3514
+ await this.validateProfileDelivery(delivery);
3033
3515
  const message = await this.ensureMessage(delivery, leaseToken);
3034
3516
  if (!message) return "lease-lost";
3517
+ const request = {
3518
+ delivery,
3519
+ message,
3520
+ idempotencyKey: notificationDeliveryCorrelationId(delivery.id)
3521
+ };
3522
+ const resolver = delivery.requiredDispatchPolicy ? this.dispatchPolicy(delivery.requiredDispatchPolicy)?.resolveAttachments : this.options.resolveAttachments;
3523
+ if (delivery.requiredDispatchPolicy && !resolver) throw new Error("Required notification dispatch policy is unavailable.");
3524
+ if (resolver) {
3525
+ const attachments = await resolver(request);
3526
+ if (!Array.isArray(attachments) || delivery.requiredDispatchPolicy && attachments.length === 0 || attachments.some((attachment) => !attachment || typeof attachment.filename !== "string" || !attachment.filename.trim() || /[\r\n\0]/.test(attachment.filename) || !(attachment.content instanceof Uint8Array) || attachment.contentType !== void 0 && (typeof attachment.contentType !== "string" || !attachment.contentType.trim() || /[\r\n\0]/.test(attachment.contentType)) || attachment.contentId !== void 0 && (typeof attachment.contentId !== "string" || /[\r\n\0]/.test(attachment.contentId)) || attachment.contentDisposition !== void 0 && !["attachment", "inline"].includes(attachment.contentDisposition))) throw new Error("Notification attachment resolver returned malformed bytes or metadata.");
3527
+ request.attachments = attachments.map((attachment) => ({
3528
+ ...attachment,
3529
+ content: Uint8Array.from(attachment.content)
3530
+ }));
3531
+ }
3035
3532
  if (!await delivery.transition({ handedOffAt: this.now() }, { leaseToken })) return "lease-lost";
3036
3533
  let outcome;
3037
3534
  try {
3038
- outcome = await this.transport.send({
3039
- delivery,
3040
- message,
3041
- idempotencyKey: notificationDeliveryCorrelationId(delivery.id)
3535
+ outcome = await withProtectedNotificationHandoff(request, this.now, async () => {
3536
+ await this.validateProfileDelivery(delivery);
3537
+ return this.transport.send(request);
3042
3538
  });
3043
3539
  } catch (error) {
3044
- outcome = {
3540
+ outcome = error instanceof ProtectedNotificationHandoffError ? {
3541
+ status: "rejected",
3542
+ retryable: true,
3543
+ error: errorText(error)
3544
+ } : {
3045
3545
  status: "unknown",
3046
3546
  error: errorText(error)
3047
3547
  };
@@ -3142,7 +3642,7 @@ var NotificationOutboxService = class {
3142
3642
  async ensureMessage(delivery, leaseToken) {
3143
3643
  if (delivery.messageId) {
3144
3644
  const message2 = await this.loadMessage(delivery.messageId);
3145
- if (message2) return message2;
3645
+ if (message2) return this.protectCanonicalMessage(delivery, message2);
3146
3646
  }
3147
3647
  const messageId = await notificationDeliveryMessageId(delivery.id);
3148
3648
  let message = await this.loadMessage(messageId);
@@ -3166,6 +3666,7 @@ ${delivery.href}
3166
3666
  address: delivery.recipientAddress,
3167
3667
  ...delivery.recipientName ? { name: delivery.recipientName } : {}
3168
3668
  }]),
3669
+ ...delivery.requiredDispatchPolicy ? { metadata: protectedNotificationMetadata(delivery.id, delivery.requiredDispatchPolicy) } : {},
3169
3670
  sendStatus: "pending",
3170
3671
  maxRetries: 0
3171
3672
  });
@@ -3178,9 +3679,30 @@ ${delivery.href}
3178
3679
  if (delivery.messageId !== message.id) {
3179
3680
  if (!await delivery.transition({ messageId: message.id }, { leaseToken })) return null;
3180
3681
  }
3682
+ return this.protectCanonicalMessage(delivery, message);
3683
+ }
3684
+ /** Backfill the non-authorizing durable marker on an existing protected canonical row. */
3685
+ async protectCanonicalMessage(delivery, message) {
3686
+ if (delivery.requiredDispatchPolicy) {
3687
+ const existing = message.getMetadata();
3688
+ const protectedMarker = JSON.parse(protectedNotificationMetadata(delivery.id, delivery.requiredDispatchPolicy));
3689
+ if (!existing.__smrtProtectedOutbox) {
3690
+ message.setMetadata({
3691
+ ...existing,
3692
+ ...protectedMarker
3693
+ });
3694
+ await message.save();
3695
+ }
3696
+ }
3181
3697
  return message;
3182
3698
  }
3183
3699
  };
3700
+ function containsControlCharacter(value) {
3701
+ return [...value].some((char) => {
3702
+ const code = char.codePointAt(0);
3703
+ return code < 32 || code === 127;
3704
+ });
3705
+ }
3184
3706
  //#endregion
3185
3707
  //#region src/services/PersonaMessagingService.ts
3186
3708
  var PersonaMessagingService = class {
@@ -3710,6 +4232,6 @@ var SlackRecipe = class extends SmrtRecipe {
3710
4232
  ensureBuiltinMessagingProvidersRegistered();
3711
4233
  ensureMessagingPermissionsRegistered();
3712
4234
  //#endregion
3713
- export { Account, AccountCollection, Attachment, AttachmentCollection, Blacklist, BlacklistCollection, Email, EmailAccount, EmailAccountCollection, EmailAttachment, EmailAttachmentCollection, EmailCollection, EmailFolder, EmailFolderCollection, EmailSender, MANAGE_MESSAGE_CREDENTIALS_PERMISSION, MANAGE_MESSAGE_ROUTES_PERMISSION, MESSAGING_PERMISSION_DEFINITIONS, MailboxRecipe, Message, MessageCollection, MessagingEndpoint, MessagingEndpointCollection, MessagingSettingsService, NOTIFICATION_DELIVERY_CHANNELS, NOTIFICATION_OPT_OUT_ALL_SCOPE, NOTIFICATION_OPT_OUT_SCOPE_PATTERN, NotificationDelivery, NotificationDeliveryCollection, NotificationOptOut, NotificationOptOutCollection, NotificationOptOutDeniedError, NotificationOptOutService, NotificationOutboxDeniedError, NotificationOutboxService, NotificationsRecipe, PersonaMessageRoute, PersonaMessageRouteCollection, PersonaMessagingService, SEND_MESSAGES_PERMISSION, SlackAccount, SlackMessage, SlackRecipe, SlackSender, TelegramAccount, TelegramSender, Tweet, TweetSender, TwitterAccount, USER_NOTIFICATION_SEVERITIES, UserNotification, UserNotificationCollection, UserNotificationService, Whitelist, WhitelistCollection, ZulipAccount, ZulipSender, AttachmentCollection_exports as a, assertMessagingPermission, buildNotificationLink, ensureBuiltinMessagingProvidersRegistered, ensureMessagingPermissionsRegistered, getMessagingProvider, MessagingEndpointCollection_exports as i, isValidNotificationOptOutScope, listMessagingProviders, messageSendTransport, messagingPrincipalFromPermissions, EmailCollection_exports as n, notificationDeliveryCorrelationId, notificationDeliveryMessageId, optOutSuppression, EmailAccountCollection_exports as r, registerMessagingProvider, EmailFolderCollection_exports as t };
4235
+ export { Account, AccountCollection, Attachment, AttachmentCollection, Blacklist, BlacklistCollection, Email, EmailAccount, EmailAccountCollection, EmailAttachment, EmailAttachmentCollection, EmailCollection, EmailFolder, EmailFolderCollection, EmailSender, MANAGE_MESSAGE_CREDENTIALS_PERMISSION, MANAGE_MESSAGE_ROUTES_PERMISSION, MESSAGING_PERMISSION_DEFINITIONS, MailboxRecipe, Message, MessageCollection, MessagingEndpoint, MessagingEndpointCollection, MessagingSettingsService, NOTIFICATION_DELIVERY_CHANNELS, NOTIFICATION_OPT_OUT_ALL_SCOPE, NOTIFICATION_OPT_OUT_SCOPE_PATTERN, NotificationDelivery, NotificationDeliveryCollection, NotificationOptOut, NotificationOptOutCollection, NotificationOptOutDeniedError, NotificationOptOutService, NotificationOutboxDeniedError, NotificationOutboxService, NotificationsRecipe, PROFILE_NOTIFICATION_POLICY_PREFIX, PersonaMessageRoute, PersonaMessageRouteCollection, PersonaMessagingService, SEND_MESSAGES_PERMISSION, SlackAccount, SlackMessage, SlackRecipe, SlackSender, TelegramAccount, TelegramSender, Tweet, TweetSender, TwitterAccount, USER_NOTIFICATION_SEVERITIES, UserNotification, UserNotificationCollection, UserNotificationService, Whitelist, WhitelistCollection, ZulipAccount, ZulipSender, AttachmentCollection_exports as a, assertMessagingPermission, assertNotificationProfileRecipientSchema, buildNotificationLink, ensureBuiltinMessagingProvidersRegistered, ensureMessagingPermissionsRegistered, getMessagingProvider, MessagingEndpointCollection_exports as i, isValidNotificationOptOutScope, listMessagingProviders, messageSendTransport, messagingPrincipalFromPermissions, migrateNotificationProfileRecipients, EmailCollection_exports as n, notificationDeliveryCorrelationId, notificationDeliveryMessageId, optOutSuppression, planNotificationProfileRecipients, profileNotificationPolicy, EmailAccountCollection_exports as r, registerMessagingProvider, EmailFolderCollection_exports as t };
3714
4236
 
3715
4237
  //# sourceMappingURL=index.js.map