@happyvertical/smrt-messages 0.62.6 → 0.62.7

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 (63) hide show
  1. package/AGENTS.md +72 -0
  2. package/dist/access-enforcement.d.ts +20 -0
  3. package/dist/access-enforcement.d.ts.map +1 -0
  4. package/dist/access.d.ts +203 -0
  5. package/dist/access.d.ts.map +1 -0
  6. package/dist/chunks/AttachmentCollection-nTqD75n8.js +308 -0
  7. package/dist/chunks/AttachmentCollection-nTqD75n8.js.map +1 -0
  8. package/dist/chunks/{Email-ChfbMCSF.js → Email-DKcIiMxB.js} +6 -6
  9. package/dist/chunks/{Email-ChfbMCSF.js.map → Email-DKcIiMxB.js.map} +1 -1
  10. package/dist/chunks/EmailAccountCollection-DtCuHcB4.js +1224 -0
  11. package/dist/chunks/EmailAccountCollection-DtCuHcB4.js.map +1 -0
  12. package/dist/chunks/EmailCollection-BYeuWWsP.js +181 -0
  13. package/dist/chunks/EmailCollection-BYeuWWsP.js.map +1 -0
  14. package/dist/chunks/{EmailFolder-XH5eH4Ed.js → EmailFolder-UMGpXTQ7.js} +25 -6
  15. package/dist/chunks/EmailFolder-UMGpXTQ7.js.map +1 -0
  16. package/dist/chunks/EmailFolderCollection-DHZKwe1H.js +177 -0
  17. package/dist/chunks/EmailFolderCollection-DHZKwe1H.js.map +1 -0
  18. package/dist/chunks/EmailSender-B-Rtq9du.js +147 -0
  19. package/dist/chunks/EmailSender-B-Rtq9du.js.map +1 -0
  20. package/dist/chunks/{Message-C6P1V5C_.js → Message-M8INXZs5.js} +30 -6
  21. package/dist/chunks/Message-M8INXZs5.js.map +1 -0
  22. package/dist/chunks/{MessageCollection-CjCT06XE.js → MessageCollection-CT0O_7wG.js} +2 -2
  23. package/dist/chunks/{MessageCollection-CjCT06XE.js.map → MessageCollection-CT0O_7wG.js.map} +1 -1
  24. package/dist/chunks/MessagingEndpointCollection-DrNvP8GM.js +97 -0
  25. package/dist/chunks/MessagingEndpointCollection-DrNvP8GM.js.map +1 -0
  26. package/dist/collections/AttachmentCollection.d.ts +6 -0
  27. package/dist/collections/AttachmentCollection.d.ts.map +1 -1
  28. package/dist/connect.d.ts +82 -0
  29. package/dist/connect.d.ts.map +1 -0
  30. package/dist/connect.js +126 -0
  31. package/dist/connect.js.map +1 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +458 -1399
  35. package/dist/index.js.map +1 -1
  36. package/dist/manifest.json +892 -32
  37. package/dist/models/Account.d.ts +23 -0
  38. package/dist/models/Account.d.ts.map +1 -1
  39. package/dist/models/Attachment.d.ts +14 -0
  40. package/dist/models/Attachment.d.ts.map +1 -1
  41. package/dist/models/EmailAccount.d.ts +3 -0
  42. package/dist/models/EmailAccount.d.ts.map +1 -1
  43. package/dist/models/EmailFolder.d.ts +7 -0
  44. package/dist/models/EmailFolder.d.ts.map +1 -1
  45. package/dist/models/Message.d.ts +7 -0
  46. package/dist/models/Message.d.ts.map +1 -1
  47. package/dist/permissions.d.ts +11 -0
  48. package/dist/permissions.d.ts.map +1 -1
  49. package/dist/services/MessagingSettingsService.d.ts +86 -0
  50. package/dist/services/MessagingSettingsService.d.ts.map +1 -1
  51. package/dist/services/NotificationOutboxService.d.ts +3 -0
  52. package/dist/services/NotificationOutboxService.d.ts.map +1 -1
  53. package/dist/smrt-knowledge.json +762 -21
  54. package/dist/smrt-knowledge.okf.md +3 -2
  55. package/dist/types.d.ts +5 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +20 -16
  58. package/dist/chunks/AccountCollection-RP_hLf6L.js +0 -257
  59. package/dist/chunks/AccountCollection-RP_hLf6L.js.map +0 -1
  60. package/dist/chunks/EmailFolder-XH5eH4Ed.js.map +0 -1
  61. package/dist/chunks/Message-C6P1V5C_.js.map +0 -1
  62. package/dist/chunks/__smrt-register__-CfOb1uCN.js +0 -6
  63. package/dist/chunks/__smrt-register__-CfOb1uCN.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,429 +1,174 @@
1
- import { t as __exportAll } from "./chunks/rolldown-runtime-D7D4PA-g.js";
2
- import "./chunks/__smrt-register__-CfOb1uCN.js";
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";
1
+ import { A as messagingPrincipalFromPermissions, C as runWithMailSystemAccess, D as SEND_MESSAGES_PERMISSION, E as MESSAGING_PERMISSION_DEFINITIONS, O as assertMessagingPermission, S as resetMailAccess, T as MANAGE_MESSAGE_ROUTES_PERMISSION, _ as getEffectiveMailAccessConfigs, b as learnMailAccessOptions, c as MAIL_SCOPES, d as assertHydratedMailAccess, f as assertMailAccess, g as deniedMailAccountIds, h as decideMailAccess, i as AccountCollection, k as ensureMessagingPermissionsRegistered, l as MailAccessError, m as configureMailAccess, o as Account, p as canAccessMailAccount, r as EmailAccount, s as MAIL_ACCOUNT_RESOURCE_TYPE, t as EmailAccountCollection, u as MailAccessService, v as inMailSystemAccess, w as MANAGE_MESSAGE_CREDENTIALS_PERMISSION, x as mailScopePermission, y as isMailScope } from "./chunks/EmailAccountCollection-DtCuHcB4.js";
4
2
  import { buildSqliteRebuildStatements, isDeepStrictEqual, normalizeIdentityEmail, queryGlobal, queryWithGlobals, readNotificationProfile, withSystemContext, withTenant } from "./host.js";
5
- import { r as Account, t as AccountCollection } from "./chunks/AccountCollection-RP_hLf6L.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-C6P1V5C_.js";
8
- import { t as MessageCollection } from "./chunks/MessageCollection-CjCT06XE.js";
9
- import { t as Email } from "./chunks/Email-ChfbMCSF.js";
10
- import { t as EmailFolder } from "./chunks/EmailFolder-XH5eH4Ed.js";
3
+ import { r as Attachment, t as AttachmentCollection } from "./chunks/AttachmentCollection-nTqD75n8.js";
4
+ import { t as EmailFolder } from "./chunks/EmailFolder-UMGpXTQ7.js";
5
+ import { d as withProtectedNotificationHandoff, f as PROFILE_NOTIFICATION_POLICY_PREFIX, l as protectedNotificationMetadata, m as profileNotificationPolicy, p as assertNotificationRecipientIdentity, t as ProtectedNotificationHandoffError } from "./chunks/protected-notification-handoff-mvaEZVp7.js";
6
+ import { t as Message } from "./chunks/Message-M8INXZs5.js";
7
+ 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";
8
+ import { t as MessageCollection } from "./chunks/MessageCollection-CT0O_7wG.js";
9
+ import { r as MessagingEndpoint, t as MessagingEndpointCollection } from "./chunks/MessagingEndpointCollection-DrNvP8GM.js";
10
+ import { t as Email } from "./chunks/Email-DKcIiMxB.js";
11
+ import { t as EmailCollection } from "./chunks/EmailCollection-BYeuWWsP.js";
12
+ import { t as EmailFolderCollection } from "./chunks/EmailFolderCollection-DHZKwe1H.js";
13
+ import { t as EmailSender } from "./chunks/EmailSender-B-Rtq9du.js";
11
14
  import { t as SlackSender } from "./chunks/SlackSender-CjSvwY1K.js";
12
15
  import { t as TweetSender } from "./chunks/TweetSender-CcLPNNi1.js";
13
- import { GlobalInterceptors, ObjectRegistry, 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";
16
+ import { GlobalInterceptors, ObjectRegistry, SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, detectEngine, field, foreignKey, isUniqueViolationError, smrt, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue } from "@happyvertical/smrt-core";
15
17
  import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
16
- //#region src/permissions.ts
17
- var SEND_MESSAGES_PERMISSION = "messages.send";
18
- var MANAGE_MESSAGE_ROUTES_PERMISSION = "messages.manage-routes";
19
- var MANAGE_MESSAGE_CREDENTIALS_PERMISSION = "messages.manage-credentials";
20
- var MESSAGING_PERMISSION_DEFINITIONS = [
21
- {
22
- slug: SEND_MESSAGES_PERMISSION,
23
- category: "messages",
24
- name: "Send Messages",
25
- description: "Allows send on messages"
26
- },
27
- {
28
- slug: MANAGE_MESSAGE_ROUTES_PERMISSION,
29
- category: "messages",
30
- name: "Manage Message Routes",
31
- description: "Manage persona messaging endpoints and route bindings"
32
- },
33
- {
34
- slug: MANAGE_MESSAGE_CREDENTIALS_PERMISSION,
35
- category: "messages",
36
- name: "Manage Message Credentials",
37
- description: "Create accounts and replace write-only provider credentials"
18
+ //#region src/access-enforcement.ts
19
+ var NAME_FALLBACK = {
20
+ Message: "message",
21
+ Email: "message",
22
+ EmailFolder: "folder",
23
+ Attachment: "attachment",
24
+ Account: "account",
25
+ EmailAccount: "account",
26
+ EmailAttachment: "attachment"
27
+ };
28
+ function descends(ctor, base) {
29
+ if (typeof ctor !== "function") return false;
30
+ return ctor === base || ctor.prototype instanceof base;
31
+ }
32
+ function kindOf(className, context) {
33
+ const ctor = (ObjectRegistry.getClass(context.qualifiedClassName ?? className) ?? ObjectRegistry.getClass(className))?.constructor;
34
+ if (ctor) {
35
+ if (descends(ctor, Message)) return "message";
36
+ if (descends(ctor, EmailFolder)) return "folder";
37
+ if (descends(ctor, Attachment)) return "attachment";
38
+ if (descends(ctor, Account)) return "account";
39
+ return null;
38
40
  }
39
- ];
40
- function messagingPrincipalFromPermissions(permissions, options = {}) {
41
- const granted = new Set(permissions);
41
+ return NAME_FALLBACK[className] ?? null;
42
+ }
43
+ var MAX_EXCLUDED_IDS = 900;
44
+ function restrict(where, denied, unaccounted) {
45
+ return (Array.isArray(where) ? where : [[where ?? {}]]).flatMap((group) => [[...group, { "accountId not in": denied }], ...unaccounted.map((extra) => [...group, extra])]);
46
+ }
47
+ async function allowedInstance(kind, instance) {
48
+ const row = instance;
49
+ try {
50
+ await assertHydratedMailAccess(kind === "attachment" ? row : {
51
+ accountId: row.accountId,
52
+ options: row.options
53
+ });
54
+ return true;
55
+ } catch (error) {
56
+ if (error instanceof MailAccessError) return false;
57
+ throw error;
58
+ }
59
+ }
60
+ var MAIL_ACCESS_INTERCEPTOR_NAME = "smrt-messages-account-access";
61
+ function createMailAccessInterceptor() {
42
62
  return {
43
- ...options,
44
- can: (slug) => granted.has(slug)
63
+ name: MAIL_ACCESS_INTERCEPTOR_NAME,
64
+ priority: 50,
65
+ onCollectionReady(className, collection, context) {
66
+ if (!kindOf(className, context)) return;
67
+ learnMailAccessOptions({
68
+ ...collection.options,
69
+ db: collection.db
70
+ });
71
+ },
72
+ async beforeList(className, options, context) {
73
+ if (!getEffectiveMailAccessConfigs().length || inMailSystemAccess()) return options;
74
+ const kind = kindOf(className, context);
75
+ if (!kind || kind === "account") return options;
76
+ const denied = await deniedMailAccountIds("read");
77
+ if (!denied.length) return options;
78
+ if (denied.length > MAX_EXCLUDED_IDS) throw new MailAccessError("read", "denied");
79
+ const unaccounted = kind === "attachment" ? [{
80
+ accountId: null,
81
+ messageId: null
82
+ }, {
83
+ accountId: null,
84
+ messageId: ""
85
+ }] : [{ accountId: null }];
86
+ return {
87
+ ...options,
88
+ where: restrict(options.where, denied, unaccounted)
89
+ };
90
+ },
91
+ async beforeSave(instance, context) {
92
+ const kind = kindOf(instance.constructor.name, context);
93
+ if (kind === "account") {
94
+ learnMailAccessOptions(instance.options);
95
+ return;
96
+ }
97
+ if (kind !== "attachment") return;
98
+ const row = instance;
99
+ row.accountId = null;
100
+ if (!row.messageId || !row.options) return;
101
+ const { MessageCollection } = await import("./chunks/MessageCollection-CT0O_7wG.js").then((n) => n.n);
102
+ row.accountId = (await runWithMailSystemAccess(async () => (await MessageCollection.create(row.options)).get({ id: row.messageId })))?.accountId || null;
103
+ },
104
+ async afterList(className, results, context) {
105
+ if (inMailSystemAccess()) return results;
106
+ const kind = kindOf(className, context);
107
+ if (!kind) return results;
108
+ if (kind === "account") {
109
+ for (const item of results) learnMailAccessOptions(item.options);
110
+ return results;
111
+ }
112
+ const kept = [];
113
+ const cache = /* @__PURE__ */ new Map();
114
+ for (const item of results) {
115
+ const row = item;
116
+ const key = `${kind}:${row.accountId ?? ""}:${row.messageId ?? ""}`;
117
+ let ok = cache.get(key);
118
+ if (ok === void 0) {
119
+ ok = await allowedInstance(kind, item);
120
+ cache.set(key, ok);
121
+ }
122
+ if (ok) kept.push(item);
123
+ }
124
+ return kept;
125
+ },
126
+ async afterGet(className, instance, context) {
127
+ if (!instance || inMailSystemAccess()) return instance;
128
+ const kind = kindOf(className, context);
129
+ if (!kind) return instance;
130
+ if (kind === "account") {
131
+ learnMailAccessOptions(instance.options);
132
+ return instance;
133
+ }
134
+ return await allowedInstance(kind, instance) ? instance : null;
135
+ },
136
+ async beforeQuery(className, options, context) {
137
+ const unchanged = {
138
+ sql: options.sql,
139
+ params: options.params
140
+ };
141
+ if (!getEffectiveMailAccessConfigs().length || inMailSystemAccess()) return unchanged;
142
+ const kind = kindOf(className, context);
143
+ if (!kind || kind === "account") return unchanged;
144
+ if ((await deniedMailAccountIds("read")).length) throw new MailAccessError("read", "denied");
145
+ return unchanged;
146
+ }
45
147
  };
46
148
  }
47
- function assertMessagingPermission(principal, tenantId, permission) {
48
- if (principal.tenantId && principal.tenantId !== tenantId) throw new Error("Messaging principal does not belong to this tenant.");
49
- if (!principal.can(permission)) throw new Error(`Missing required permission '${permission}'.`);
50
- }
51
149
  var registered = false;
52
- function ensureMessagingPermissionsRegistered() {
150
+ function ensureMailAccessEnforcementRegistered() {
53
151
  if (registered) return;
54
152
  registered = true;
55
- registerPermissionDefinitions(MESSAGING_PERMISSION_DEFINITIONS);
153
+ GlobalInterceptors.register(createMailAccessInterceptor());
56
154
  }
57
155
  //#endregion
58
- //#region src/models/Attachment.ts
59
- var __defProp$14 = Object.defineProperty;
60
- var __getOwnPropDesc$14 = Object.getOwnPropertyDescriptor;
61
- var __defNormalProp$14 = (obj, key, value) => key in obj ? __defProp$14(obj, key, {
62
- enumerable: true,
63
- configurable: true,
64
- writable: true,
65
- value
66
- }) : obj[key] = value;
67
- var __decorateClass$14 = (decorators, target, key, kind) => {
68
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$14(target, key) : target;
69
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
70
- if (kind && result) __defProp$14(target, key, result);
71
- return result;
72
- };
73
- var __publicField$14 = (obj, key, value) => __defNormalProp$14(obj, typeof key !== "symbol" ? key + "" : key, value);
74
- function splitAbsolutePath(filePath) {
75
- const windows = /^[A-Za-z]:[\\/]/.test(filePath);
76
- if (!windows && !filePath.startsWith("/")) return null;
77
- const cut = windows ? Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) : filePath.lastIndexOf("/");
78
- return {
79
- dir: filePath.slice(0, cut) || filePath.slice(0, cut + 1),
80
- base: filePath.slice(cut + 1)
81
- };
82
- }
83
- var Attachment = class extends SmrtObject {
84
- tenantId = null;
85
- messageId = "";
86
- filename = "";
87
- contentType = "";
88
- size = 0;
89
- contentId = "";
90
- contentDisposition = "attachment";
91
- filePath = "";
92
- sourceUrl = "";
93
- createdAt = /* @__PURE__ */ new Date();
94
- constructor(options = {}) {
95
- super(options);
96
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
97
- if (options.messageId !== void 0) this.messageId = options.messageId;
98
- if (options.filename !== void 0) this.filename = options.filename;
99
- if (options.contentType !== void 0) this.contentType = options.contentType;
100
- if (options.size !== void 0) this.size = options.size;
101
- if (options.contentId !== void 0) this.contentId = options.contentId;
102
- if (options.contentDisposition !== void 0) this.contentDisposition = options.contentDisposition;
103
- if (options.filePath !== void 0) this.filePath = options.filePath;
104
- if (options.sourceUrl !== void 0) this.sourceUrl = options.sourceUrl;
105
- if (options.createdAt) this.createdAt = options.createdAt;
106
- }
107
- /**
108
- * Get the message this attachment belongs to
109
- */
110
- async getMessage() {
111
- if (!this.messageId) return null;
112
- const { MessageCollection } = await import("./chunks/MessageCollection-CjCT06XE.js").then((n) => n.n);
113
- return await (await MessageCollection.create(this.options)).get({ id: this.messageId });
114
- }
115
- /**
116
- * Check if attachment is an image
117
- */
118
- isImage() {
119
- return this.contentType.startsWith("image/");
120
- }
121
- /**
122
- * Check if attachment is a PDF
123
- */
124
- isPdf() {
125
- return this.contentType === "application/pdf";
126
- }
127
- /**
128
- * Check if attachment is inline (embedded in message body)
129
- */
130
- isInline() {
131
- return this.contentDisposition === "inline";
132
- }
133
- /**
134
- * Get file extension from filename
135
- */
136
- getExtension() {
137
- if (!this.filename) return "";
138
- const parts = this.filename.split(".");
139
- return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
140
- }
141
- /**
142
- * Get human-readable file size
143
- */
144
- getFormattedSize() {
145
- const units = [
146
- "B",
147
- "KB",
148
- "MB",
149
- "GB"
150
- ];
151
- let size = this.size;
152
- let unitIndex = 0;
153
- while (size >= 1024 && unitIndex < units.length - 1) {
154
- size /= 1024;
155
- unitIndex++;
156
- }
157
- return `${size.toFixed(1)} ${units[unitIndex]}`;
158
- }
159
- /**
160
- * Check if file is stored externally
161
- */
162
- hasExternalFile() {
163
- return !!this.filePath;
164
- }
165
- /**
166
- * Read file content (if stored externally)
167
- *
168
- * The files SDK is loaded through core's bundler-invisible optional-import
169
- * boundary so it never enters provider-neutral consumer bundles (#1979).
170
- * Absence of the SDK at runtime degrades to the existing null contract.
171
- *
172
- * The local provider joins every path onto its base path (the process cwd
173
- * by default), so an absolute `filePath` is rooted at its own directory, and
174
- * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).
175
- */
176
- async readContent() {
177
- if (!this.filePath) return null;
178
- try {
179
- const { getFilesystem, initializeProviders } = await importOptionalDependency("@happyvertical/files", "Import '@happyvertical/smrt-core/filesystem' (or '@happyvertical/smrt-assets/filesystem') during server startup to read externally-stored attachments in bundled builds.");
180
- await initializeProviders?.();
181
- const split = splitAbsolutePath(this.filePath);
182
- const data = await (await getFilesystem(split ? {
183
- type: "local",
184
- basePath: split.dir
185
- } : { type: "local" })).read(split ? split.base : this.filePath, { raw: true });
186
- return data instanceof Buffer ? data : Buffer.from(data);
187
- } catch {
188
- return null;
189
- }
190
- }
191
- };
192
- __publicField$14(Attachment, "__smrtPackage__", "@happyvertical/smrt-messages");
193
- __decorateClass$14([tenantId({ nullable: true })], Attachment.prototype, "tenantId", 2);
194
- __decorateClass$14([foreignKey("Message")], Attachment.prototype, "messageId", 2);
195
- Attachment = __decorateClass$14([TenantScoped({ mode: "optional" }), smrt({
196
- api: { include: [
197
- "list",
198
- "get",
199
- "create",
200
- "delete"
201
- ] },
202
- mcp: { include: ["list", "get"] },
203
- cli: { skipApiCheck: true }
204
- })], Attachment);
205
- //#endregion
206
- //#region src/collections/AttachmentCollection.ts
207
- var AttachmentCollection_exports = /* @__PURE__ */ __exportAll({ AttachmentCollection: () => AttachmentCollection });
208
- var AttachmentCollection = class extends SmrtCollection {
209
- static _itemClass = Attachment;
210
- /**
211
- * Get attachments for a message
212
- */
213
- async getByMessage(messageId) {
214
- return await this.list({ where: { messageId } });
215
- }
216
- /**
217
- * Get attachments by content type
218
- */
219
- async getByContentType(contentType) {
220
- return await this.list({ where: { contentType } });
221
- }
222
- /**
223
- * Get image attachments
224
- */
225
- async getImages(messageId) {
226
- return (messageId ? await this.getByMessage(messageId) : await this.list({})).filter((a) => a.isImage());
227
- }
228
- /**
229
- * Get PDF attachments
230
- */
231
- async getPdfs(messageId) {
232
- return (messageId ? await this.getByMessage(messageId) : await this.list({})).filter((a) => a.isPdf());
233
- }
234
- /**
235
- * Get inline attachments (embedded in message body)
236
- */
237
- async getInline(messageId) {
238
- return (await this.getByMessage(messageId)).filter((a) => a.isInline());
239
- }
240
- /**
241
- * Get regular attachments (not inline)
242
- */
243
- async getRegular(messageId) {
244
- return (await this.getByMessage(messageId)).filter((a) => !a.isInline());
245
- }
246
- /**
247
- * Get attachments with external files
248
- */
249
- async getWithExternalFiles() {
250
- return (await this.list({})).filter((a) => a.hasExternalFile());
251
- }
252
- /**
253
- * Get total size of attachments for a message
254
- */
255
- async getTotalSize(messageId) {
256
- return (await this.getByMessage(messageId)).reduce((sum, a) => sum + a.size, 0);
257
- }
258
- /**
259
- * Get largest attachments
260
- */
261
- async getLargest(limit = 10) {
262
- return (await this.list({})).sort((a, b) => b.size - a.size).slice(0, limit);
263
- }
264
- /**
265
- * Search attachments by filename
266
- */
267
- async searchByFilename(query) {
268
- const attachments = await this.list({});
269
- const lowerQuery = query.toLowerCase();
270
- return attachments.filter((a) => a.filename?.toLowerCase().includes(lowerQuery));
271
- }
272
- /**
273
- * Get attachments by extension
274
- */
275
- async getByExtension(extension) {
276
- const attachments = await this.list({});
277
- const lowerExt = extension.toLowerCase().replace(/^\./, "");
278
- return attachments.filter((a) => a.getExtension() === lowerExt);
279
- }
280
- /**
281
- * Get attachment statistics
282
- */
283
- async getStats() {
284
- const attachments = await this.list({});
285
- const byType = {};
286
- for (const attachment of attachments) {
287
- const type = attachment.contentType.split("/")[0] || "other";
288
- byType[type] = (byType[type] || 0) + 1;
289
- }
290
- return {
291
- total: attachments.length,
292
- totalSize: attachments.reduce((sum, a) => sum + a.size, 0),
293
- byType,
294
- inline: attachments.filter((a) => a.isInline()).length,
295
- regular: attachments.filter((a) => !a.isInline()).length
296
- };
297
- }
298
- /**
299
- * Delete all attachments for a message
300
- */
301
- async deleteByMessage(messageId) {
302
- const attachments = await this.getByMessage(messageId);
303
- let count = 0;
304
- for (const attachment of attachments) {
305
- await attachment.delete();
306
- count++;
307
- }
308
- return count;
309
- }
310
- async findByTenant(tenantId) {
311
- return this.list({ where: { tenantId } });
312
- }
313
- async findGlobal() {
314
- return queryGlobal(this);
315
- }
316
- async findWithGlobals(tenantId) {
317
- return queryWithGlobals(this, tenantId, "Attachment.findWithGlobals");
318
- }
319
- };
320
- //#endregion
321
- //#region src/models/MessagingEndpoint.ts
322
- var __defProp$13 = Object.defineProperty;
323
- var __getOwnPropDesc$13 = Object.getOwnPropertyDescriptor;
324
- var __defNormalProp$13 = (obj, key, value) => key in obj ? __defProp$13(obj, key, {
325
- enumerable: true,
326
- configurable: true,
327
- writable: true,
328
- value
329
- }) : obj[key] = value;
330
- var __decorateClass$13 = (decorators, target, key, kind) => {
331
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$13(target, key) : target;
332
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
333
- if (kind && result) __defProp$13(target, key, result);
334
- return result;
335
- };
336
- var __publicField$13 = (obj, key, value) => __defNormalProp$13(obj, typeof key !== "symbol" ? key + "" : key, value);
337
- var MessagingEndpoint = class extends SmrtObject {
338
- tenantId = "";
339
- profileId = null;
340
- label = "";
341
- channel = "email";
342
- address = "{}";
343
- isActive = true;
344
- verifiedAt = null;
345
- createdAt = /* @__PURE__ */ new Date();
346
- updatedAt = /* @__PURE__ */ new Date();
347
- constructor(options = {}) {
348
- super(options);
349
- if (options.tenantId !== void 0) this.tenantId = options.tenantId;
350
- if (options.profileId !== void 0) this.profileId = options.profileId;
351
- if (options.label !== void 0) this.label = options.label;
352
- if (options.channel !== void 0) this.channel = options.channel;
353
- if (options.address !== void 0) this.address = options.address;
354
- if (options.isActive !== void 0) this.isActive = options.isActive;
355
- if (options.verifiedAt !== void 0) this.verifiedAt = options.verifiedAt;
356
- if (options.createdAt !== void 0) this.createdAt = options.createdAt;
357
- if (options.updatedAt !== void 0) this.updatedAt = options.updatedAt;
358
- }
359
- getAddress() {
360
- try {
361
- return JSON.parse(this.address);
362
- } catch {
363
- return {};
364
- }
365
- }
366
- setAddress(address) {
367
- this.address = JSON.stringify(address);
368
- }
369
- getMaskedAddress() {
370
- const address = this.getAddress();
371
- const visible = address.email ?? address.chatId ?? address.to ?? address.stream ?? address.phoneNumber;
372
- if (typeof visible !== "string" && typeof visible !== "number") return "••••";
373
- const value = String(visible);
374
- if (value.includes("@")) {
375
- const [name, domain] = value.split("@");
376
- return `${name.slice(0, 2)}\u2022\u2022\u2022@${domain}`;
377
- }
378
- return value.length <= 4 ? "••••" : `\u2022\u2022\u2022\u2022${value.slice(-4)}`;
379
- }
380
- };
381
- __publicField$13(MessagingEndpoint, "__smrtPackage__", "@happyvertical/smrt-messages");
382
- __decorateClass$13([tenantId()], MessagingEndpoint.prototype, "tenantId", 2);
383
- __decorateClass$13([crossPackageRef("@happyvertical/smrt-profiles:Profile", { nullable: true })], MessagingEndpoint.prototype, "profileId", 2);
384
- __decorateClass$13([field({
385
- required: true,
386
- requiredFor: "identity"
387
- })], MessagingEndpoint.prototype, "label", 2);
388
- __decorateClass$13([field({ required: true })], MessagingEndpoint.prototype, "channel", 2);
389
- __decorateClass$13([field({
390
- required: true,
391
- sensitive: true
392
- })], MessagingEndpoint.prototype, "address", 2);
393
- MessagingEndpoint = __decorateClass$13([TenantScoped({ mode: "required" }), smrt({
394
- tableName: "messaging_endpoints",
395
- api: { include: ["list", "get"] },
396
- mcp: { include: ["list", "get"] },
397
- cli: { include: ["list", "get"] },
398
- conflictColumns: [
399
- "tenant_id",
400
- "channel",
401
- "label"
402
- ]
403
- })], MessagingEndpoint);
404
- //#endregion
405
- //#region src/collections/MessagingEndpointCollection.ts
406
- var MessagingEndpointCollection_exports = /* @__PURE__ */ __exportAll({ MessagingEndpointCollection: () => MessagingEndpointCollection });
407
- var MessagingEndpointCollection = class extends SmrtCollection {
408
- static _itemClass = MessagingEndpoint;
409
- };
410
- //#endregion
411
156
  //#region src/models/NotificationDelivery.ts
412
- var __defProp$12 = Object.defineProperty;
413
- var __getOwnPropDesc$12 = Object.getOwnPropertyDescriptor;
414
- var __defNormalProp$12 = (obj, key, value) => key in obj ? __defProp$12(obj, key, {
157
+ var __defProp$11 = Object.defineProperty;
158
+ var __getOwnPropDesc$11 = Object.getOwnPropertyDescriptor;
159
+ var __defNormalProp$11 = (obj, key, value) => key in obj ? __defProp$11(obj, key, {
415
160
  enumerable: true,
416
161
  configurable: true,
417
162
  writable: true,
418
163
  value
419
164
  }) : obj[key] = value;
420
- var __decorateClass$12 = (decorators, target, key, kind) => {
421
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$12(target, key) : target;
165
+ var __decorateClass$11 = (decorators, target, key, kind) => {
166
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$11(target, key) : target;
422
167
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
423
- if (kind && result) __defProp$12(target, key, result);
168
+ if (kind && result) __defProp$11(target, key, result);
424
169
  return result;
425
170
  };
426
- var __publicField$12 = (obj, key, value) => __defNormalProp$12(obj, typeof key !== "symbol" ? key + "" : key, value);
171
+ var __publicField$11 = (obj, key, value) => __defNormalProp$11(obj, typeof key !== "symbol" ? key + "" : key, value);
427
172
  var NOTIFICATION_DELIVERY_CHANNELS = ["email"];
428
173
  var TRANSITION_COLUMNS = {
429
174
  messageId: "message_id",
@@ -643,37 +388,37 @@ var NotificationDelivery = class extends SmrtObject {
643
388
  return true;
644
389
  }
645
390
  };
646
- __publicField$12(NotificationDelivery, "__smrtPackage__", "@happyvertical/smrt-messages");
647
- __decorateClass$12([tenantId()], NotificationDelivery.prototype, "tenantId", 2);
648
- __decorateClass$12([crossPackageRef("@happyvertical/smrt-users:User", { nullable: true })], NotificationDelivery.prototype, "recipientUserId", 2);
649
- __decorateClass$12([crossPackageRef("@happyvertical/smrt-profiles:Profile", { nullable: true })], NotificationDelivery.prototype, "recipientProfileId", 2);
650
- __decorateClass$12([field({
391
+ __publicField$11(NotificationDelivery, "__smrtPackage__", "@happyvertical/smrt-messages");
392
+ __decorateClass$11([tenantId()], NotificationDelivery.prototype, "tenantId", 2);
393
+ __decorateClass$11([crossPackageRef("@happyvertical/smrt-users:User", { nullable: true })], NotificationDelivery.prototype, "recipientUserId", 2);
394
+ __decorateClass$11([crossPackageRef("@happyvertical/smrt-profiles:Profile", { nullable: true })], NotificationDelivery.prototype, "recipientProfileId", 2);
395
+ __decorateClass$11([field({
651
396
  required: true,
652
397
  requiredFor: "identity"
653
398
  })], NotificationDelivery.prototype, "recipientKind", 2);
654
- __decorateClass$12([field({
399
+ __decorateClass$11([field({
655
400
  required: true,
656
401
  requiredFor: "identity"
657
402
  })], NotificationDelivery.prototype, "channel", 2);
658
- __decorateClass$12([field({
403
+ __decorateClass$11([field({
659
404
  required: true,
660
405
  requiredFor: "idempotency"
661
406
  })], NotificationDelivery.prototype, "sourceRef", 2);
662
- __decorateClass$12([field({
407
+ __decorateClass$11([field({
663
408
  required: true,
664
409
  requiredFor: "identity"
665
410
  })], NotificationDelivery.prototype, "kind", 2);
666
- __decorateClass$12([field({ type: "json" })], NotificationDelivery.prototype, "dispatchPolicyBinding", 2);
667
- __decorateClass$12([field()], NotificationDelivery.prototype, "subject", 2);
668
- __decorateClass$12([field()], NotificationDelivery.prototype, "textBody", 2);
669
- __decorateClass$12([field()], NotificationDelivery.prototype, "href", 2);
670
- __decorateClass$12([field({
411
+ __decorateClass$11([field({ type: "json" })], NotificationDelivery.prototype, "dispatchPolicyBinding", 2);
412
+ __decorateClass$11([field()], NotificationDelivery.prototype, "subject", 2);
413
+ __decorateClass$11([field()], NotificationDelivery.prototype, "textBody", 2);
414
+ __decorateClass$11([field()], NotificationDelivery.prototype, "href", 2);
415
+ __decorateClass$11([field({
671
416
  required: true,
672
417
  requiredFor: "identity"
673
418
  })], NotificationDelivery.prototype, "recipientAddress", 2);
674
- __decorateClass$12([foreignKey("Account")], NotificationDelivery.prototype, "accountId", 2);
675
- __decorateClass$12([foreignKey("Message")], NotificationDelivery.prototype, "messageId", 2);
676
- NotificationDelivery = __decorateClass$12([TenantScoped({ mode: "required" }), smrt({
419
+ __decorateClass$11([foreignKey("Account")], NotificationDelivery.prototype, "accountId", 2);
420
+ __decorateClass$11([foreignKey("Message")], NotificationDelivery.prototype, "messageId", 2);
421
+ NotificationDelivery = __decorateClass$11([TenantScoped({ mode: "required" }), smrt({
677
422
  tableName: "notification_deliveries",
678
423
  api: false,
679
424
  mcp: false,
@@ -724,21 +469,21 @@ var NotificationDeliveryCollection = class extends SmrtCollection {
724
469
  };
725
470
  //#endregion
726
471
  //#region src/models/NotificationOptOut.ts
727
- var __defProp$11 = Object.defineProperty;
728
- var __getOwnPropDesc$11 = Object.getOwnPropertyDescriptor;
729
- var __defNormalProp$11 = (obj, key, value) => key in obj ? __defProp$11(obj, key, {
472
+ var __defProp$10 = Object.defineProperty;
473
+ var __getOwnPropDesc$10 = Object.getOwnPropertyDescriptor;
474
+ var __defNormalProp$10 = (obj, key, value) => key in obj ? __defProp$10(obj, key, {
730
475
  enumerable: true,
731
476
  configurable: true,
732
477
  writable: true,
733
478
  value
734
479
  }) : obj[key] = value;
735
- var __decorateClass$11 = (decorators, target, key, kind) => {
736
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$11(target, key) : target;
480
+ var __decorateClass$10 = (decorators, target, key, kind) => {
481
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$10(target, key) : target;
737
482
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
738
- if (kind && result) __defProp$11(target, key, result);
483
+ if (kind && result) __defProp$10(target, key, result);
739
484
  return result;
740
485
  };
741
- var __publicField$11 = (obj, key, value) => __defNormalProp$11(obj, typeof key !== "symbol" ? key + "" : key, value);
486
+ var __publicField$10 = (obj, key, value) => __defNormalProp$10(obj, typeof key !== "symbol" ? key + "" : key, value);
742
487
  var NOTIFICATION_OPT_OUT_SCOPE_PATTERN = /^(?:\*|[a-z][a-z0-9-]*:[A-Za-z0-9._:-]{1,200})$/;
743
488
  var NOTIFICATION_OPT_OUT_ALL_SCOPE = "*";
744
489
  function isValidNotificationOptOutScope(scope) {
@@ -766,18 +511,18 @@ var NotificationOptOut = class extends SmrtObject {
766
511
  return this.optedOutAt !== null;
767
512
  }
768
513
  };
769
- __publicField$11(NotificationOptOut, "__smrtPackage__", "@happyvertical/smrt-messages");
770
- __decorateClass$11([tenantId()], NotificationOptOut.prototype, "tenantId", 2);
771
- __decorateClass$11([crossPackageRef("@happyvertical/smrt-users:User", {
514
+ __publicField$10(NotificationOptOut, "__smrtPackage__", "@happyvertical/smrt-messages");
515
+ __decorateClass$10([tenantId()], NotificationOptOut.prototype, "tenantId", 2);
516
+ __decorateClass$10([crossPackageRef("@happyvertical/smrt-users:User", {
772
517
  required: true,
773
518
  requiredFor: "identity"
774
519
  })], NotificationOptOut.prototype, "recipientUserId", 2);
775
- __decorateClass$11([field({ required: true })], NotificationOptOut.prototype, "channel", 2);
776
- __decorateClass$11([field({
520
+ __decorateClass$10([field({ required: true })], NotificationOptOut.prototype, "channel", 2);
521
+ __decorateClass$10([field({
777
522
  required: true,
778
523
  requiredFor: "identity"
779
524
  })], NotificationOptOut.prototype, "scope", 2);
780
- NotificationOptOut = __decorateClass$11([TenantScoped({ mode: "required" }), smrt({
525
+ NotificationOptOut = __decorateClass$10([TenantScoped({ mode: "required" }), smrt({
781
526
  tableName: "notification_opt_outs",
782
527
  api: false,
783
528
  mcp: false,
@@ -796,21 +541,21 @@ var NotificationOptOutCollection = class extends SmrtCollection {
796
541
  };
797
542
  //#endregion
798
543
  //#region src/models/PersonaMessageRoute.ts
799
- var __defProp$10 = Object.defineProperty;
800
- var __getOwnPropDesc$10 = Object.getOwnPropertyDescriptor;
801
- var __defNormalProp$10 = (obj, key, value) => key in obj ? __defProp$10(obj, key, {
544
+ var __defProp$9 = Object.defineProperty;
545
+ var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
546
+ var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, {
802
547
  enumerable: true,
803
548
  configurable: true,
804
549
  writable: true,
805
550
  value
806
551
  }) : obj[key] = value;
807
- var __decorateClass$10 = (decorators, target, key, kind) => {
808
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$10(target, key) : target;
552
+ var __decorateClass$9 = (decorators, target, key, kind) => {
553
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
809
554
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
810
- if (kind && result) __defProp$10(target, key, result);
555
+ if (kind && result) __defProp$9(target, key, result);
811
556
  return result;
812
557
  };
813
- var __publicField$10 = (obj, key, value) => __defNormalProp$10(obj, typeof key !== "symbol" ? key + "" : key, value);
558
+ var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
814
559
  var PersonaMessageRoute = class extends SmrtObject {
815
560
  tenantId = "";
816
561
  personaId = "";
@@ -834,22 +579,22 @@ var PersonaMessageRoute = class extends SmrtObject {
834
579
  if (options.updatedAt !== void 0) this.updatedAt = options.updatedAt;
835
580
  }
836
581
  };
837
- __publicField$10(PersonaMessageRoute, "__smrtPackage__", "@happyvertical/smrt-messages");
838
- __decorateClass$10([tenantId()], PersonaMessageRoute.prototype, "tenantId", 2);
839
- __decorateClass$10([crossPackageRef("@happyvertical/smrt-personas:AgentPersona", {
582
+ __publicField$9(PersonaMessageRoute, "__smrtPackage__", "@happyvertical/smrt-messages");
583
+ __decorateClass$9([tenantId()], PersonaMessageRoute.prototype, "tenantId", 2);
584
+ __decorateClass$9([crossPackageRef("@happyvertical/smrt-personas:AgentPersona", {
840
585
  required: true,
841
586
  requiredFor: "identity"
842
587
  })], PersonaMessageRoute.prototype, "personaId", 2);
843
- __decorateClass$10([foreignKey("Account", {
588
+ __decorateClass$9([foreignKey("Account", {
844
589
  required: true,
845
590
  requiredFor: "identity"
846
591
  })], PersonaMessageRoute.prototype, "accountId", 2);
847
- __decorateClass$10([foreignKey("MessagingEndpoint", {
592
+ __decorateClass$9([foreignKey("MessagingEndpoint", {
848
593
  required: true,
849
594
  requiredFor: "identity"
850
595
  })], PersonaMessageRoute.prototype, "endpointId", 2);
851
- __decorateClass$10([field({ required: true })], PersonaMessageRoute.prototype, "purpose", 2);
852
- PersonaMessageRoute = __decorateClass$10([TenantScoped({ mode: "required" }), smrt({
596
+ __decorateClass$9([field({ required: true })], PersonaMessageRoute.prototype, "purpose", 2);
597
+ PersonaMessageRoute = __decorateClass$9([TenantScoped({ mode: "required" }), smrt({
853
598
  tableName: "persona_message_routes",
854
599
  api: { include: ["list", "get"] },
855
600
  mcp: { include: ["list", "get"] },
@@ -875,21 +620,21 @@ var PersonaMessageRouteCollection = class extends SmrtCollection {
875
620
  };
876
621
  //#endregion
877
622
  //#region src/models/UserNotification.ts
878
- var __defProp$9 = Object.defineProperty;
879
- var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
880
- var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, {
623
+ var __defProp$8 = Object.defineProperty;
624
+ var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
625
+ var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, {
881
626
  enumerable: true,
882
627
  configurable: true,
883
628
  writable: true,
884
629
  value
885
630
  }) : obj[key] = value;
886
- var __decorateClass$9 = (decorators, target, key, kind) => {
887
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
631
+ var __decorateClass$8 = (decorators, target, key, kind) => {
632
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
888
633
  for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
889
- if (kind && result) __defProp$9(target, key, result);
634
+ if (kind && result) __defProp$8(target, key, result);
890
635
  return result;
891
636
  };
892
- var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
637
+ var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
893
638
  var USER_NOTIFICATION_SEVERITIES = [
894
639
  "info",
895
640
  "success",
@@ -934,469 +679,41 @@ var UserNotification = class extends SmrtObject {
934
679
  return this.dismissedAt !== null;
935
680
  }
936
681
  };
937
- __publicField$9(UserNotification, "__smrtPackage__", "@happyvertical/smrt-messages");
938
- __decorateClass$9([tenantId()], UserNotification.prototype, "tenantId", 2);
939
- __decorateClass$9([crossPackageRef("@happyvertical/smrt-users:User", {
682
+ __publicField$8(UserNotification, "__smrtPackage__", "@happyvertical/smrt-messages");
683
+ __decorateClass$8([tenantId()], UserNotification.prototype, "tenantId", 2);
684
+ __decorateClass$8([crossPackageRef("@happyvertical/smrt-users:User", {
940
685
  required: true,
941
686
  requiredFor: "identity"
942
687
  })], UserNotification.prototype, "recipientUserId", 2);
943
- __decorateClass$9([field()], UserNotification.prototype, "kind", 2);
944
- __decorateClass$9([field()], UserNotification.prototype, "title", 2);
945
- __decorateClass$9([field({
688
+ __decorateClass$8([field()], UserNotification.prototype, "kind", 2);
689
+ __decorateClass$8([field()], UserNotification.prototype, "title", 2);
690
+ __decorateClass$8([field({
946
691
  required: true,
947
692
  requiredFor: "idempotency"
948
693
  })], UserNotification.prototype, "sourceRef", 2);
949
- UserNotification = __decorateClass$9([TenantScoped({ mode: "required" }), smrt({
694
+ UserNotification = __decorateClass$8([TenantScoped({ mode: "required" }), smrt({
950
695
  tableName: "user_notifications",
951
696
  api: false,
952
697
  mcp: false,
953
698
  cli: false,
954
- conflictColumns: [
955
- "tenant_id",
956
- "recipient_user_id",
957
- "source_ref"
958
- ],
959
- indexes: [{
960
- name: "user_notifications_recipient_occurred_idx",
961
- columns: [
962
- "tenantId",
963
- "recipientUserId",
964
- "occurredAt"
965
- ]
966
- }]
967
- })], UserNotification);
968
- //#endregion
969
- //#region src/collections/UserNotificationCollection.ts
970
- var UserNotificationCollection = class extends SmrtCollection {
971
- static _itemClass = UserNotification;
972
- };
973
- //#endregion
974
- //#region src/models/EmailAccount.ts
975
- var __defProp$8 = Object.defineProperty;
976
- var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
977
- var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, {
978
- enumerable: true,
979
- configurable: true,
980
- writable: true,
981
- value
982
- }) : obj[key] = value;
983
- var __decorateClass$8 = (decorators, target, key, kind) => {
984
- var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
985
- for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
986
- if (kind && result) __defProp$8(target, key, result);
987
- return result;
988
- };
989
- var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
990
- var EmailAccount = class extends Account {
991
- email = "";
992
- syncIntervalMinutes = 60;
993
- constructor(options = {}) {
994
- super(options);
995
- if (options.email !== void 0) this.email = options.email;
996
- if (options.providerType !== void 0) this.providerType = options.providerType;
997
- if (options.syncIntervalMinutes !== void 0) this.syncIntervalMinutes = options.syncIntervalMinutes;
998
- this.channelType = "email";
999
- }
1000
- /**
1001
- * Options for child rows (folders/emails) created during sync: carries the DB
1002
- * connection + tenant context from this account, but strips this account's own
1003
- * identity fields. When this account was hydrated from the DB, `this.options`
1004
- * holds the account row's `id`/`slug`/`_skipLoad`; spreading those into a new
1005
- * child would make every synced row inherit the account's primary key and
1006
- * upsert over each other.
1007
- */
1008
- childOptions() {
1009
- const rest = { ...this.options };
1010
- delete rest.id;
1011
- delete rest.slug;
1012
- delete rest._skipLoad;
1013
- return rest;
1014
- }
1015
- /**
1016
- * Create a sender for this email account
1017
- */
1018
- async createSender() {
1019
- const client = await this.createClient();
1020
- await client.connect();
1021
- const { EmailSender } = await Promise.resolve().then(() => EmailSender_exports);
1022
- return new EmailSender(client, this);
1023
- }
1024
- /**
1025
- * Create an EmailClient from stored settings
1026
- * Retrieves credentials from smrt-secrets if credentialSecretId is set
1027
- *
1028
- * The client factory comes from the messaging provider registry rather than
1029
- * a direct `@happyvertical/email` import so the email SDK
1030
- * (googleapis/nodemailer) never becomes reachable from provider-neutral
1031
- * consumer bundles (#1979). Server code that uses email accounts must
1032
- * import '@happyvertical/smrt-messages/providers/email' (or
1033
- * '/providers/all') once during startup.
1034
- */
1035
- async createClient() {
1036
- const { getMessagingProvider } = await import("./chunks/providers-4iLula-V.js").then((n) => n.i);
1037
- const createEmailClient = getMessagingProvider(this.providerType)?.createEmailClient;
1038
- if (!createEmailClient) throw new Error(`Email provider '${this.providerType}' has no client implementation registered. Import '@happyvertical/smrt-messages/providers/email' (or '/providers/all') during server startup to enable outbound email and mailbox sync.`);
1039
- const settings = {
1040
- ...this.getConfiguration(),
1041
- ...await this.getCredentials() ?? {}
1042
- };
1043
- delete settings.email;
1044
- return await createEmailClient({
1045
- type: this.providerType,
1046
- ...settings
1047
- });
1048
- }
1049
- /**
1050
- * Read an immutable body/attachment-byte snapshot for an authorized intake host.
1051
- * Does not sync, acknowledge, mark read or advance mailbox checkpoints.
1052
- * Metadata-only providers fail explicitly; provider paths are never dereferenced.
1053
- */
1054
- async readIntakeMessage(locator, maxBytes, imapIdentity) {
1055
- if (!this.id || !this.isActive || !locator) throw new Error("Email intake account unavailable");
1056
- const client = await this.createClient();
1057
- try {
1058
- await client.connect();
1059
- if (this.providerType === "imap") {
1060
- if (!imapIdentity?.folder || !imapIdentity.uid || !Number.isSafeInteger(imapIdentity.uidValidity)) throw new Error("IMAP intake requires folder and immutable UID identity");
1061
- if ((await client.selectFolder(imapIdentity.folder)).uidValidity !== imapIdentity.uidValidity) throw new Error("IMAP intake identity changed");
1062
- }
1063
- const message = await client.getMessage(locator);
1064
- if (this.providerType === "imap" && message.id !== imapIdentity?.uid) throw new Error("IMAP intake identity changed");
1065
- const { snapshotEmailForIntake } = await import("./chunks/intake-snapshot-B03bDtSW.js");
1066
- return snapshotEmailForIntake(this.id, message, maxBytes);
1067
- } finally {
1068
- await client.disconnect();
1069
- }
1070
- }
1071
- /**
1072
- * Sync emails from the email server to the database
1073
- */
1074
- async syncFrom(options = {}) {
1075
- const startTime = Date.now();
1076
- const result = {
1077
- folders: [],
1078
- messagesProcessed: 0,
1079
- messagesDownloaded: 0,
1080
- messagesSkipped: 0,
1081
- errors: [],
1082
- duration: 0
1083
- };
1084
- try {
1085
- const client = await this.createClient();
1086
- await client.connect();
1087
- const foldersToSync = options.folders || ["INBOX"];
1088
- result.folders = foldersToSync;
1089
- const { EmailCollection } = await Promise.resolve().then(() => EmailCollection_exports);
1090
- const { EmailFolderCollection } = await Promise.resolve().then(() => EmailFolderCollection_exports);
1091
- const emailCollection = await EmailCollection.create(this.options);
1092
- const folderCollection = await EmailFolderCollection.create(this.options);
1093
- if (!this.id) throw new Error("EmailAccount.syncFrom requires a persisted account (missing id)");
1094
- const accountId = this.id;
1095
- for (const folderName of foldersToSync) try {
1096
- let folder = await folderCollection.getByPath(accountId, folderName);
1097
- if (!folder) {
1098
- const { EmailFolder } = await import("./chunks/EmailFolder-XH5eH4Ed.js").then((n) => n.n);
1099
- folder = new (ObjectRegistry.resolveEffectiveConstructor(EmailFolder))({
1100
- ...this.childOptions(),
1101
- accountId,
1102
- name: folderName,
1103
- path: folderName
1104
- });
1105
- await folder.initialize();
1106
- await folder.save();
1107
- }
1108
- const fetchOptions = {
1109
- folder: folderName,
1110
- limit: options.batchSize || 100
1111
- };
1112
- if (options.since) fetchOptions.since = options.since;
1113
- if (options.before) fetchOptions.before = options.before;
1114
- const messages = await client.fetch(fetchOptions);
1115
- for (const msg of messages) {
1116
- result.messagesProcessed++;
1117
- try {
1118
- const existingEmail = await emailCollection.getByMessageId(accountId, msg.messageId || "");
1119
- if (existingEmail && !options.fullSync) {
1120
- result.messagesSkipped++;
1121
- continue;
1122
- }
1123
- const { Email } = await import("./chunks/Email-ChfbMCSF.js").then((n) => n.n);
1124
- let email = existingEmail;
1125
- if (!email) {
1126
- email = new (ObjectRegistry.resolveEffectiveConstructor(Email))({
1127
- ...this.childOptions(),
1128
- accountId
1129
- });
1130
- await email.initialize();
1131
- }
1132
- email.messageId = msg.messageId || "";
1133
- email.threadId = msg.threadId || "";
1134
- email.inReplyTo = msg.inReplyTo || "";
1135
- email.fromAddress = msg.from?.address || "";
1136
- email.fromName = msg.from?.name || "";
1137
- email.toAddresses = JSON.stringify(msg.to || []);
1138
- email.ccAddresses = JSON.stringify(msg.cc || []);
1139
- email.bccAddresses = JSON.stringify(msg.bcc || []);
1140
- email.replyToAddress = msg.replyTo?.address || "";
1141
- email.replyToName = msg.replyTo?.name || "";
1142
- email.subject = msg.subject || "";
1143
- email.date = msg.date || null;
1144
- email.textBody = msg.text || "";
1145
- email.htmlBody = msg.html || "";
1146
- email.body = msg.text || "";
1147
- email.folderId = folder.id ?? "";
1148
- email.folderPath = folderName;
1149
- email.labels = JSON.stringify(msg.labels || []);
1150
- email.flags = JSON.stringify(msg.flags || []);
1151
- email.hasAttachments = msg.attachments && msg.attachments.length > 0 || false;
1152
- email.size = msg.size || 0;
1153
- email.headers = JSON.stringify(msg.headers || {});
1154
- email.updatedAt = /* @__PURE__ */ new Date();
1155
- await email.save();
1156
- result.messagesDownloaded++;
1157
- if (options.onProgress) options.onProgress({
1158
- folder: folderName,
1159
- processed: result.messagesProcessed,
1160
- total: messages.length,
1161
- downloaded: result.messagesDownloaded,
1162
- skipped: result.messagesSkipped,
1163
- errors: result.errors.length
1164
- });
1165
- } catch (error) {
1166
- const err = error instanceof Error ? error : new Error(String(error));
1167
- result.errors.push(err);
1168
- if (options.onError) options.onError(err, msg);
1169
- }
1170
- }
1171
- const folderId = folder.id ?? "";
1172
- folder.messageCount = await emailCollection.countByFolder(folderId);
1173
- folder.unreadCount = await emailCollection.countUnreadByFolder(folderId);
1174
- await folder.save();
1175
- } catch (error) {
1176
- const err = error instanceof Error ? error : new Error(String(error));
1177
- result.errors.push(err);
1178
- if (options.onError) options.onError(err);
1179
- }
1180
- this.lastSyncAt = /* @__PURE__ */ new Date();
1181
- this.updatedAt = /* @__PURE__ */ new Date();
1182
- await this.save();
1183
- await client.disconnect();
1184
- } catch (error) {
1185
- const err = error instanceof Error ? error : new Error(String(error));
1186
- result.errors.push(err);
1187
- if (options.onError) options.onError(err);
1188
- }
1189
- result.duration = Date.now() - startTime;
1190
- return result;
1191
- }
1192
- /**
1193
- * Get all folders for this account
1194
- */
1195
- async getFolders() {
1196
- const { EmailFolderCollection } = await Promise.resolve().then(() => EmailFolderCollection_exports);
1197
- return await (await EmailFolderCollection.create(this.options)).list({ where: { accountId: this.id } });
1198
- }
1199
- /**
1200
- * Get all emails for this account
1201
- */
1202
- async getEmails(limit) {
1203
- const { EmailCollection } = await Promise.resolve().then(() => EmailCollection_exports);
1204
- const collection = await EmailCollection.create(this.options);
1205
- const options = { where: { accountId: this.id } };
1206
- if (limit) options.limit = limit;
1207
- return await collection.list(options);
1208
- }
1209
- /**
1210
- * Get unread email count
1211
- */
1212
- async getUnreadCount() {
1213
- const { EmailCollection } = await Promise.resolve().then(() => EmailCollection_exports);
1214
- return await (await EmailCollection.create(this.options)).countUnreadByAccount(this.id ?? "");
1215
- }
1216
- /**
1217
- * Store credentials securely using smrt-secrets (email-specific)
1218
- */
1219
- async setCredentials(credentials, options = {}) {
1220
- await super.setCredentials(credentials, {
1221
- description: options.description || `Email credentials for ${this.name}`,
1222
- category: options.category || "email"
1223
- });
1224
- }
1225
- /**
1226
- * Sync all active email accounts (for job runner)
1227
- *
1228
- * NOTE: This is a class-wide operation, not per-instance. It syncs ALL active
1229
- * accounts, ignoring `this` instance. It exists as an instance method because
1230
- * the TaskRunner dispatches via `objectType: 'EmailAccount', method: 'syncAll'`
1231
- * which requires an instance method signature.
1232
- */
1233
- async syncAll(args) {
1234
- const { EmailAccountCollection } = await Promise.resolve().then(() => EmailAccountCollection_exports);
1235
- return (await EmailAccountCollection.create({ db: this.db })).syncAll(args);
1236
- }
1237
- /**
1238
- * Migrate from plain-text settings to secrets
1239
- */
1240
- async migrateToSecrets() {
1241
- if (this.credentialSecretId) return;
1242
- const settings = this.getSettings();
1243
- if (Object.keys(settings).length === 0) return;
1244
- await this.setCredentials(settings, { description: `Migrated IMAP credentials for ${this.name}` });
1245
- }
1246
- };
1247
- __publicField$8(EmailAccount, "__smrtPackage__", "@happyvertical/smrt-messages");
1248
- __decorateClass$8([field({ description: "The email address associated with this mailbox." })], EmailAccount.prototype, "email", 2);
1249
- __decorateClass$8([field({ description: "The time in minutes between scheduled mailbox checks." })], EmailAccount.prototype, "syncIntervalMinutes", 2);
1250
- EmailAccount = __decorateClass$8([smrt({
1251
- tableStrategy: "sti",
1252
- api: { include: ["list", "get"] },
1253
- mcp: { include: ["list", "get"] },
1254
- cli: { include: ["list", "get"] }
1255
- })], EmailAccount);
1256
- //#endregion
1257
- //#region src/collections/EmailAccountCollection.ts
1258
- var EmailAccountCollection_exports = /* @__PURE__ */ __exportAll({ EmailAccountCollection: () => EmailAccountCollection });
1259
- var EmailAccountCollection = class extends AccountCollection {
1260
- static _itemClass = EmailAccount;
1261
- /**
1262
- * Get account by email address
1263
- */
1264
- async getByEmail(email) {
1265
- return (await this.list({ where: { email } }))[0] || null;
1266
- }
1267
- /**
1268
- * Get accounts by email provider type
1269
- */
1270
- async getByEmailProviderType(providerType) {
1271
- return await this.list({ where: { providerType } });
1272
- }
1273
- /**
1274
- * Get active email accounts
1275
- */
1276
- async getActive() {
1277
- return await this.list({ where: { isActive: true } });
1278
- }
1279
- /**
1280
- * Get inactive email accounts
1281
- */
1282
- async getInactive() {
1283
- return await this.list({ where: { isActive: false } });
1284
- }
1285
- /**
1286
- * Get accounts that need syncing
1287
- */
1288
- async getNeedingSync(maxAgeMinutes = 60) {
1289
- const allAccounts = await this.getActive();
1290
- const cutoffTime = /* @__PURE__ */ new Date(Date.now() - maxAgeMinutes * 60 * 1e3);
1291
- return allAccounts.filter((account) => !account.lastSyncAt || account.lastSyncAt < cutoffTime);
1292
- }
1293
- /**
1294
- * Search email accounts with filters.
1295
- * Alias: `search()` for backward compatibility.
1296
- */
1297
- async search(query, filters) {
1298
- return this.searchEmailAccounts(query, filters);
1299
- }
1300
- /**
1301
- * Get accounts by email provider type.
1302
- * Alias: `getByProviderType()` for backward compatibility.
1303
- */
1304
- async getByProviderType(providerType) {
1305
- return this.getByEmailProviderType(providerType);
1306
- }
1307
- /**
1308
- * Get email account statistics.
1309
- * Alias: `getStats()` for backward compatibility.
1310
- */
1311
- async getStats() {
1312
- const stats = await this.getEmailStats();
1313
- return {
1314
- total: stats.total,
1315
- active: stats.active,
1316
- inactive: stats.inactive,
1317
- byType: stats.byProvider
1318
- };
1319
- }
1320
- /**
1321
- * Search email accounts with filters
1322
- */
1323
- async searchEmailAccounts(query, filters) {
1324
- let accounts = await this.list({});
1325
- if (query) {
1326
- const lowerQuery = query.toLowerCase();
1327
- accounts = accounts.filter((a) => a.name?.toLowerCase().includes(lowerQuery) || a.email?.toLowerCase().includes(lowerQuery));
1328
- }
1329
- if (filters) {
1330
- if (filters.providerType) accounts = accounts.filter((a) => a.providerType === filters.providerType);
1331
- if (filters.email) {
1332
- const emailLower = filters.email.toLowerCase();
1333
- accounts = accounts.filter((a) => a.email?.toLowerCase().includes(emailLower));
1334
- }
1335
- if (filters.isActive !== void 0) accounts = accounts.filter((a) => a.isActive === filters.isActive);
1336
- }
1337
- return accounts;
1338
- }
1339
- /**
1340
- * Sync all active email accounts
1341
- */
1342
- async syncAll(options) {
1343
- const results = /* @__PURE__ */ new Map();
1344
- const accounts = await this.getActive();
1345
- for (const account of accounts) {
1346
- const ea = account;
1347
- const accountId = ea.id ?? ea.email ?? "unknown";
1348
- try {
1349
- await ea.syncFrom(options);
1350
- results.set(accountId, { success: true });
1351
- } catch (error) {
1352
- results.set(accountId, {
1353
- success: false,
1354
- error: error instanceof Error ? error : new Error(String(error))
1355
- });
1356
- }
1357
- }
1358
- return results;
1359
- }
1360
- /**
1361
- * Get total unread count across all email accounts
1362
- */
1363
- async getTotalUnreadCount() {
1364
- const accounts = await this.getActive();
1365
- let total = 0;
1366
- for (const account of accounts) total += await account.getUnreadCount();
1367
- return total;
1368
- }
1369
- /**
1370
- * Get email account statistics
1371
- */
1372
- async getEmailStats() {
1373
- const accounts = await this.list({});
1374
- const byProvider = {
1375
- smtp: 0,
1376
- imap: 0,
1377
- pop3: 0,
1378
- gmail: 0
1379
- };
1380
- for (const account of accounts) {
1381
- const pt = account.providerType;
1382
- if (pt in byProvider) byProvider[pt]++;
1383
- }
1384
- return {
1385
- total: accounts.length,
1386
- active: accounts.filter((a) => a.isActive).length,
1387
- inactive: accounts.filter((a) => !a.isActive).length,
1388
- byProvider
1389
- };
1390
- }
1391
- async findByTenant(tenantId) {
1392
- return this.list({ where: { tenantId } });
1393
- }
1394
- async findGlobal() {
1395
- return queryGlobal(this);
1396
- }
1397
- async findWithGlobals(tenantId) {
1398
- return queryWithGlobals(this, tenantId, "EmailAccount.findWithGlobals");
1399
- }
699
+ conflictColumns: [
700
+ "tenant_id",
701
+ "recipient_user_id",
702
+ "source_ref"
703
+ ],
704
+ indexes: [{
705
+ name: "user_notifications_recipient_occurred_idx",
706
+ columns: [
707
+ "tenantId",
708
+ "recipientUserId",
709
+ "occurredAt"
710
+ ]
711
+ }]
712
+ })], UserNotification);
713
+ //#endregion
714
+ //#region src/collections/UserNotificationCollection.ts
715
+ var UserNotificationCollection = class extends SmrtCollection {
716
+ static _itemClass = UserNotification;
1400
717
  };
1401
718
  //#endregion
1402
719
  //#region src/models/EmailAttachment.ts
@@ -1423,7 +740,7 @@ var EmailAttachment = class extends Attachment {
1423
740
  */
1424
741
  async getEmail() {
1425
742
  if (!this.messageId) return null;
1426
- const { EmailCollection } = await Promise.resolve().then(() => EmailCollection_exports);
743
+ const { EmailCollection } = await import("./chunks/EmailCollection-BYeuWWsP.js").then((n) => n.n);
1427
744
  return await (await EmailCollection.create(this.options)).get({ id: this.messageId });
1428
745
  }
1429
746
  };
@@ -1480,350 +797,6 @@ var EmailAttachmentCollection = class extends AttachmentCollection {
1480
797
  }
1481
798
  };
1482
799
  //#endregion
1483
- //#region src/collections/EmailCollection.ts
1484
- var EmailCollection_exports = /* @__PURE__ */ __exportAll({ EmailCollection: () => EmailCollection });
1485
- var EmailCollection = class extends MessageCollection {
1486
- static _itemClass = Email;
1487
- /**
1488
- * Get email by RFC 822 Message-ID
1489
- */
1490
- async getByMessageId(accountId, messageId) {
1491
- return (await this.list({
1492
- where: {
1493
- accountId,
1494
- messageId
1495
- },
1496
- limit: 1
1497
- }))[0] || null;
1498
- }
1499
- /**
1500
- * Get emails by account
1501
- */
1502
- async getByAccount(accountId) {
1503
- return await this.list({ where: { accountId } });
1504
- }
1505
- /**
1506
- * Get emails by folder
1507
- */
1508
- async getByFolder(folderId) {
1509
- return await this.list({ where: { folderId } });
1510
- }
1511
- /**
1512
- * Get emails by thread
1513
- */
1514
- async getByThread(threadId) {
1515
- return await this.list({ where: { threadId } });
1516
- }
1517
- /**
1518
- * Get unread emails
1519
- */
1520
- async getUnread(accountId) {
1521
- const where = { isRead: false };
1522
- if (accountId) where.accountId = accountId;
1523
- return await this.list({ where });
1524
- }
1525
- /**
1526
- * Get flagged emails
1527
- */
1528
- async getFlagged(accountId) {
1529
- const where = { isFlagged: true };
1530
- if (accountId) where.accountId = accountId;
1531
- return await this.list({ where });
1532
- }
1533
- /**
1534
- * Get emails with attachments
1535
- */
1536
- async getWithAttachments(accountId) {
1537
- const where = { hasAttachments: true };
1538
- if (accountId) where.accountId = accountId;
1539
- return await this.list({ where });
1540
- }
1541
- /**
1542
- * Get recent emails
1543
- */
1544
- async getRecent(limit = 20, accountId) {
1545
- return (await this.list({ where: accountId ? { accountId } : void 0 })).sort((a, b) => {
1546
- const dateA = a.date?.getTime() || 0;
1547
- return (b.date?.getTime() || 0) - dateA;
1548
- }).slice(0, limit);
1549
- }
1550
- /**
1551
- * Count emails in a folder
1552
- */
1553
- async countByFolder(folderId) {
1554
- return (await this.list({ where: { folderId } })).length;
1555
- }
1556
- /**
1557
- * Count unread emails in a folder
1558
- */
1559
- async countUnreadByFolder(folderId) {
1560
- return (await this.list({ where: {
1561
- folderId,
1562
- isRead: false
1563
- } })).length;
1564
- }
1565
- /**
1566
- * Count unread emails for an account
1567
- */
1568
- async countUnreadByAccount(accountId) {
1569
- return (await this.list({ where: {
1570
- accountId,
1571
- isRead: false
1572
- } })).length;
1573
- }
1574
- /**
1575
- * Search emails with email-specific filters.
1576
- * Alias: `search()` for backward compatibility.
1577
- */
1578
- async search(query, filters) {
1579
- return this.searchEmails(query, filters);
1580
- }
1581
- /**
1582
- * Search emails with email-specific filters
1583
- */
1584
- async searchEmails(query, filters) {
1585
- let emails = await this.list({});
1586
- if (query) {
1587
- const lowerQuery = query.toLowerCase();
1588
- emails = emails.filter((e) => e.subject?.toLowerCase().includes(lowerQuery) || e.textBody?.toLowerCase().includes(lowerQuery) || e.fromAddress?.toLowerCase().includes(lowerQuery) || e.fromName?.toLowerCase().includes(lowerQuery));
1589
- }
1590
- if (filters) {
1591
- if (filters.accountId) emails = emails.filter((e) => e.accountId === filters.accountId);
1592
- if (filters.folderId) emails = emails.filter((e) => e.folderId === filters.folderId);
1593
- if (filters.threadId) emails = emails.filter((e) => e.threadId === filters.threadId);
1594
- if (filters.from) {
1595
- const fromLower = filters.from.toLowerCase();
1596
- emails = emails.filter((e) => e.fromAddress?.toLowerCase().includes(fromLower) || e.fromName?.toLowerCase().includes(fromLower));
1597
- }
1598
- if (filters.to) {
1599
- const toLower = filters.to.toLowerCase();
1600
- emails = emails.filter((e) => e.toAddresses?.toLowerCase().includes(toLower));
1601
- }
1602
- if (filters.subject) {
1603
- const subjectLower = filters.subject.toLowerCase();
1604
- emails = emails.filter((e) => e.subject?.toLowerCase().includes(subjectLower));
1605
- }
1606
- if (filters.isRead !== void 0) emails = emails.filter((e) => e.isRead === filters.isRead);
1607
- if (filters.isFlagged !== void 0) emails = emails.filter((e) => e.isFlagged === filters.isFlagged);
1608
- if (filters.hasAttachments !== void 0) emails = emails.filter((e) => e.hasAttachments === filters.hasAttachments);
1609
- if (filters.sincDate) emails = emails.filter((e) => e.date && e.date >= filters.sincDate);
1610
- if (filters.beforeDate) emails = emails.filter((e) => e.date && e.date < filters.beforeDate);
1611
- }
1612
- return emails;
1613
- }
1614
- /**
1615
- * Mark all emails in a folder as read
1616
- */
1617
- async markFolderRead(folderId) {
1618
- const folderEmails = (await this.getUnread()).filter((e) => e.folderId === folderId);
1619
- for (const email of folderEmails) await email.markRead();
1620
- }
1621
- /**
1622
- * Delete emails by folder
1623
- */
1624
- async deleteByFolder(folderId) {
1625
- const emails = await this.getByFolder(folderId);
1626
- let count = 0;
1627
- for (const email of emails) {
1628
- await email.delete();
1629
- count++;
1630
- }
1631
- return count;
1632
- }
1633
- /**
1634
- * Get email statistics for an account
1635
- */
1636
- async getAccountStats(accountId) {
1637
- const emails = await this.getByAccount(accountId);
1638
- return {
1639
- total: emails.length,
1640
- unread: emails.filter((e) => !e.isRead).length,
1641
- flagged: emails.filter((e) => e.isFlagged).length,
1642
- withAttachments: emails.filter((e) => e.hasAttachments).length,
1643
- byType: { Email: emails.length }
1644
- };
1645
- }
1646
- async findByTenant(tenantId) {
1647
- return this.list({ where: { tenantId } });
1648
- }
1649
- async findGlobal() {
1650
- return queryGlobal(this);
1651
- }
1652
- async findWithGlobals(tenantId) {
1653
- return queryWithGlobals(this, tenantId, "Email.findWithGlobals");
1654
- }
1655
- };
1656
- //#endregion
1657
- //#region src/collections/EmailFolderCollection.ts
1658
- var EmailFolderCollection_exports = /* @__PURE__ */ __exportAll({ EmailFolderCollection: () => EmailFolderCollection });
1659
- var EmailFolderCollection = class extends SmrtCollection {
1660
- static _itemClass = EmailFolder;
1661
- /**
1662
- * Get folder by path for an account
1663
- */
1664
- async getByPath(accountId, path) {
1665
- return (await this.list({ where: {
1666
- accountId,
1667
- path
1668
- } }))[0] || null;
1669
- }
1670
- /**
1671
- * Get folders by account
1672
- */
1673
- async getByAccount(accountId) {
1674
- return await this.list({ where: { accountId } });
1675
- }
1676
- /**
1677
- * Get inbox folder for an account
1678
- */
1679
- async getInbox(accountId) {
1680
- return (await this.getByAccount(accountId)).find((f) => f.isInbox()) || null;
1681
- }
1682
- /**
1683
- * Get sent folder for an account
1684
- */
1685
- async getSent(accountId) {
1686
- return (await this.getByAccount(accountId)).find((f) => f.isSent()) || null;
1687
- }
1688
- /**
1689
- * Get drafts folder for an account
1690
- */
1691
- async getDrafts(accountId) {
1692
- return (await this.getByAccount(accountId)).find((f) => f.isDrafts()) || null;
1693
- }
1694
- /**
1695
- * Get trash folder for an account
1696
- */
1697
- async getTrash(accountId) {
1698
- return (await this.getByAccount(accountId)).find((f) => f.isTrash()) || null;
1699
- }
1700
- /**
1701
- * Get spam folder for an account
1702
- */
1703
- async getSpam(accountId) {
1704
- return (await this.getByAccount(accountId)).find((f) => f.isSpam()) || null;
1705
- }
1706
- /**
1707
- * Get system folders for an account
1708
- */
1709
- async getSystemFolders(accountId) {
1710
- return (await this.getByAccount(accountId)).filter((f) => f.isSystemFolder());
1711
- }
1712
- /**
1713
- * Get user-created folders for an account
1714
- */
1715
- async getUserFolders(accountId) {
1716
- return (await this.getByAccount(accountId)).filter((f) => !f.isSystemFolder());
1717
- }
1718
- /**
1719
- * Get subscribed folders
1720
- */
1721
- async getSubscribed(accountId) {
1722
- const where = { subscribed: true };
1723
- if (accountId) where.accountId = accountId;
1724
- return await this.list({ where });
1725
- }
1726
- /**
1727
- * Get folders with unread messages
1728
- */
1729
- async getWithUnread(accountId) {
1730
- return (accountId ? await this.getByAccount(accountId) : await this.list({})).filter((f) => f.unreadCount > 0);
1731
- }
1732
- /**
1733
- * Search folders with filters
1734
- */
1735
- async search(query, filters) {
1736
- let folders = await this.list({});
1737
- if (query) {
1738
- const lowerQuery = query.toLowerCase();
1739
- folders = folders.filter((f) => f.name?.toLowerCase().includes(lowerQuery) || f.path?.toLowerCase().includes(lowerQuery));
1740
- }
1741
- if (filters) {
1742
- if (filters.accountId) folders = folders.filter((f) => f.accountId === filters.accountId);
1743
- if (filters.specialUse) folders = folders.filter((f) => f.specialUse === filters.specialUse);
1744
- if (filters.subscribed !== void 0) folders = folders.filter((f) => f.subscribed === filters.subscribed);
1745
- }
1746
- return folders;
1747
- }
1748
- /**
1749
- * Refresh counts for all folders in an account
1750
- */
1751
- async refreshAllCounts(accountId) {
1752
- const folders = await this.getByAccount(accountId);
1753
- for (const folder of folders) await folder.refreshCounts();
1754
- }
1755
- /**
1756
- * Get folder statistics for an account
1757
- */
1758
- async getAccountStats(accountId) {
1759
- const folders = await this.getByAccount(accountId);
1760
- return {
1761
- totalFolders: folders.length,
1762
- totalMessages: folders.reduce((sum, f) => sum + f.messageCount, 0),
1763
- totalUnread: folders.reduce((sum, f) => sum + f.unreadCount, 0),
1764
- systemFolders: folders.filter((f) => f.isSystemFolder()).length,
1765
- userFolders: folders.filter((f) => !f.isSystemFolder()).length
1766
- };
1767
- }
1768
- /**
1769
- * Create standard system folders for an account
1770
- */
1771
- async createSystemFolders(accountId) {
1772
- for (const folderData of [
1773
- {
1774
- name: "INBOX",
1775
- path: "INBOX",
1776
- specialUse: "\\Inbox"
1777
- },
1778
- {
1779
- name: "Sent",
1780
- path: "Sent",
1781
- specialUse: "\\Sent"
1782
- },
1783
- {
1784
- name: "Drafts",
1785
- path: "Drafts",
1786
- specialUse: "\\Drafts"
1787
- },
1788
- {
1789
- name: "Trash",
1790
- path: "Trash",
1791
- specialUse: "\\Trash"
1792
- },
1793
- {
1794
- name: "Spam",
1795
- path: "Spam",
1796
- specialUse: "\\Junk"
1797
- }
1798
- ]) if (!await this.getByPath(accountId, folderData.path)) await (await this.create({
1799
- accountId,
1800
- ...folderData
1801
- })).save();
1802
- }
1803
- /**
1804
- * Find all email folders belonging to a specific tenant
1805
- */
1806
- async findByTenant(tenantId) {
1807
- return this.list({ where: { tenantId } });
1808
- }
1809
- /**
1810
- * Find all global email folders (no tenant).
1811
- *
1812
- * EmailFolder is @TenantScoped (CTI, own `email_folders` table). Under an
1813
- * active tenant context list({ tenantId: null }) throws and unflagged raw SQL
1814
- * is blocked (#1596); route through the raw helpers.
1815
- */
1816
- async findGlobal() {
1817
- return queryGlobal(this);
1818
- }
1819
- /**
1820
- * Find email folders for a tenant including global folders.
1821
- */
1822
- async findWithGlobals(tenantId) {
1823
- return queryWithGlobals(this, tenantId, "EmailFolder.findWithGlobals");
1824
- }
1825
- };
1826
- //#endregion
1827
800
  //#region src/models/Blacklist.ts
1828
801
  var __defProp$7 = Object.defineProperty;
1829
802
  var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
@@ -2330,148 +1303,6 @@ ZulipAccount = __decorateClass([smrt({
2330
1303
  cli: { include: ["list", "get"] }
2331
1304
  })], ZulipAccount);
2332
1305
  //#endregion
2333
- //#region src/senders/EmailSender.ts
2334
- var EmailSender_exports = /* @__PURE__ */ __exportAll({
2335
- EmailSender: () => EmailSender,
2336
- isDefiniteSendRejection: () => isDefiniteSendRejection
2337
- });
2338
- var EmailSender = class {
2339
- providerType = "email";
2340
- client;
2341
- account;
2342
- constructor(client, account) {
2343
- this.client = client;
2344
- this.account = account;
2345
- }
2346
- isReady() {
2347
- return this.client.isConnected();
2348
- }
2349
- async send(message, options) {
2350
- const toAddresses = message.getToAddresses();
2351
- const ccAddresses = message.getCcAddresses();
2352
- const bccAddresses = message.getBccAddresses();
2353
- let attachments;
2354
- try {
2355
- await assertProtectedEmailAdmission(message, options);
2356
- attachments = await this.collectAttachments(message, options);
2357
- } catch (error) {
2358
- return {
2359
- success: false,
2360
- error: error instanceof Error ? error.message : String(error),
2361
- sentAt: /* @__PURE__ */ new Date()
2362
- };
2363
- }
2364
- const emailMessage = {
2365
- from: {
2366
- name: message.fromName || this.account.name,
2367
- address: message.fromAddress || this.account.email
2368
- },
2369
- to: toAddresses.map((r) => ({
2370
- name: r.name,
2371
- address: r.address
2372
- })),
2373
- cc: ccAddresses.length > 0 ? ccAddresses.map((r) => ({
2374
- name: r.name,
2375
- address: r.address
2376
- })) : void 0,
2377
- bcc: bccAddresses.length > 0 ? bccAddresses.map((r) => ({
2378
- name: r.name,
2379
- address: r.address
2380
- })) : void 0,
2381
- subject: message.subject,
2382
- text: message.textBody || message.body,
2383
- html: message.htmlBody || void 0,
2384
- inReplyTo: message.inReplyTo || void 0,
2385
- attachments: attachments.length > 0 ? attachments : void 0
2386
- };
2387
- try {
2388
- await assertProtectedEmailHandoff(message, attachments, options, emailMessage);
2389
- const result = await this.client.send(emailMessage);
2390
- return {
2391
- success: true,
2392
- providerMessageId: result.messageId,
2393
- accepted: result.accepted,
2394
- rejected: result.rejected,
2395
- providerResponse: { response: result.response },
2396
- sentAt: /* @__PURE__ */ new Date()
2397
- };
2398
- } catch (error) {
2399
- return {
2400
- success: false,
2401
- error: error instanceof Error ? error.message : String(error),
2402
- ...error instanceof ProtectedNotificationHandoffError || isDefiniteSendRejection(error) ? {} : { outcomeUnknown: true },
2403
- sentAt: /* @__PURE__ */ new Date()
2404
- };
2405
- }
2406
- }
2407
- /**
2408
- * The message's stored `Attachment` rows followed by the send-time bytes.
2409
- *
2410
- * Stored rows are listed through the message's own options, so the lookup
2411
- * runs under the same tenant context as the message. A row's file is read
2412
- * through `Attachment.readContent()`, the package's one attachment-reading
2413
- * seam, so the bytes are handed to the transport rather than a path it
2414
- * would have to resolve itself.
2415
- */
2416
- async collectAttachments(message, options) {
2417
- const resolved = [];
2418
- const stored = message.isPersisted ? await message.getAttachments() : [];
2419
- for (const attachment of stored) {
2420
- if (message.tenantId && attachment.tenantId && attachment.tenantId !== message.tenantId) throw new Error(`Attachment "${attachment.filename}" belongs to another tenant than its message.`);
2421
- if (!attachment.filePath) throw new Error(`Attachment "${attachment.filename}" has no stored file to send` + (attachment.sourceUrl ? " (a sourceUrl is not fetched at send time)." : "."));
2422
- const content = await attachment.readContent();
2423
- if (!content) throw new Error(`Attachment "${attachment.filename}" could not be read from "${attachment.filePath}": the file is missing or unreadable, or the files SDK is not loaded (see Attachment.readContent()).`);
2424
- resolved.push({
2425
- filename: attachment.filename,
2426
- contentType: attachment.contentType || "application/octet-stream",
2427
- size: content.length,
2428
- content: Buffer.from(content),
2429
- contentId: attachment.contentId || void 0,
2430
- contentDisposition: attachment.contentDisposition
2431
- });
2432
- }
2433
- for (const attachment of options?.attachments ?? []) {
2434
- if (!attachment.filename) throw new Error("A send-time attachment needs a filename.");
2435
- if (!attachment.content) throw new Error(`Send-time attachment "${attachment.filename}" has no content.`);
2436
- const content = Buffer.from(attachment.content);
2437
- resolved.push({
2438
- filename: attachment.filename,
2439
- contentType: attachment.contentType || "application/octet-stream",
2440
- size: content.length,
2441
- content,
2442
- contentId: attachment.contentId,
2443
- contentDisposition: attachment.contentDisposition ?? "attachment"
2444
- });
2445
- }
2446
- return resolved;
2447
- }
2448
- };
2449
- var DEFINITE_EMAIL_ERROR_CODES = /* @__PURE__ */ new Set([
2450
- "AUTHENTICATION_ERROR",
2451
- "AUTHORIZATION_ERROR",
2452
- "INVALID_MESSAGE",
2453
- "ATTACHMENT_ERROR"
2454
- ]);
2455
- var NEVER_CONNECTED_CODES = /* @__PURE__ */ new Set([
2456
- "ECONNREFUSED",
2457
- "ENOTFOUND",
2458
- "EHOSTUNREACH",
2459
- "EAI_AGAIN"
2460
- ]);
2461
- function isDefiniteSendRejection(error) {
2462
- if (!error || typeof error !== "object") return false;
2463
- const candidates = [error, error.cause].filter((value) => !!value && typeof value === "object");
2464
- for (const candidate of candidates) {
2465
- if (typeof candidate.responseCode === "number") return true;
2466
- if (typeof candidate.code === "string") {
2467
- if (DEFINITE_EMAIL_ERROR_CODES.has(candidate.code)) return true;
2468
- if (NEVER_CONNECTED_CODES.has(candidate.code)) return true;
2469
- }
2470
- }
2471
- const sendError = error;
2472
- return sendError.code === "SEND_ERROR" && Array.isArray(sendError.accepted) && sendError.accepted.length === 0;
2473
- }
2474
- //#endregion
2475
1306
  //#region src/services/MessagingSettingsService.ts
2476
1307
  var MessagingSettingsService = class {
2477
1308
  constructor(options) {
@@ -2500,10 +1331,24 @@ var MessagingSettingsService = class {
2500
1331
  };
2501
1332
  });
2502
1333
  }
1334
+ /**
1335
+ * Stores account settings only: it never opens a connection, so it is not an
1336
+ * SSRF vector by itself (connecting goes through `connectMailbox`, which is
1337
+ * allowlisted). The SMTP host/port it stores predate this change and are
1338
+ * used later by the sender; hosts that need an outbound allowlist apply it
1339
+ * there.
1340
+ */
2503
1341
  async saveAccount(input) {
1342
+ return this.persistAccount(input, false);
1343
+ }
1344
+ /**
1345
+ * `receiveOnly` admits providers that are not outbound transports (IMAP,
1346
+ * POP3): a mailbox can be connected for reading without being a sender.
1347
+ */
1348
+ async persistAccount(input, receiveOnly) {
2504
1349
  this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
2505
1350
  const provider = this.requireProvider(input.providerId);
2506
- if (!provider.available) throw new Error(`Provider '${provider.id}' is not available.`);
1351
+ if (!provider.available && !(receiveOnly && provider.channel === "email")) throw new Error(`Provider '${provider.id}' is not available.`);
2507
1352
  this.validateFields(input.configuration, provider.configurationFields, "configuration");
2508
1353
  if (input.credentials) this.validateFields(input.credentials, provider.credentialFields, "credentials");
2509
1354
  return withTenant({ tenantId: this.options.tenantId }, async () => {
@@ -2512,12 +1357,19 @@ var MessagingSettingsService = class {
2512
1357
  const isNew = !account;
2513
1358
  if (account && account.tenantId !== this.options.tenantId) throw new Error("Messaging account belongs to another tenant.");
2514
1359
  if (account && account.providerType !== provider.id) throw new Error("A messaging account provider cannot be changed in place.");
1360
+ if (account) this.assertMayManage(account);
1361
+ if (account && input.ownerUserId !== void 0) {
1362
+ if ((input.ownerUserId ?? null) !== (account.ownerUserId ?? null)) throw new Error("Change a mail account owner with MailAccessService.setOwner.");
1363
+ }
1364
+ if (!account && input.ownerUserId && input.ownerUserId !== this.actingUserId) throw new Error("A new mail account can only be owned by its creator.");
2515
1365
  if (isNew && !input.credentials && provider.credentialFields.some((field) => field.required)) throw new Error(`Credentials are required for new ${provider.label} accounts.`);
2516
1366
  if (!account) {
2517
1367
  account = this.newAccount(provider, input);
2518
1368
  await account.initialize();
2519
1369
  }
2520
1370
  account.name = input.name.trim();
1371
+ if (isNew && input.ownerUserId) account.ownerUserId = input.ownerUserId;
1372
+ if (input.label !== void 0) account.label = input.label?.trim() || null;
2521
1373
  account.isActive = input.active ?? account.isActive;
2522
1374
  account.channelType = provider.channel;
2523
1375
  const configuration = this.normalizeConfiguration(provider, input.configuration);
@@ -2529,6 +1381,80 @@ var MessagingSettingsService = class {
2529
1381
  return this.accountView(account);
2530
1382
  });
2531
1383
  }
1384
+ /**
1385
+ * Connect a mailbox with a write-only secret (an app password). The
1386
+ * credential is validated by opening a session first; a refusal leaves no
1387
+ * account and no secret behind. The connecting user becomes the owner.
1388
+ */
1389
+ async connectMailbox(input) {
1390
+ this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
1391
+ if (!this.actingUserId) throw new Error("Connecting a mailbox needs a signed-in user.");
1392
+ if (input.id) await withTenant({ tenantId: this.options.tenantId }, async () => {
1393
+ this.assertMayManage(await this.loadAccount(input.id));
1394
+ });
1395
+ const provider = this.requireProvider(input.providerId);
1396
+ if (provider.channel !== "email") throw new Error(`Provider '${provider.id}' cannot connect a mailbox.`);
1397
+ this.validateFields(input.configuration, provider.configurationFields, "configuration");
1398
+ this.validateFields(input.credentials, provider.credentialFields, "credentials");
1399
+ const configuration = this.normalizeConfiguration(provider, input.configuration);
1400
+ const credentials = this.normalizeCredentials(provider, input.credentials);
1401
+ await this.validateConnection({
1402
+ provider,
1403
+ configuration,
1404
+ credentials
1405
+ });
1406
+ const view = await this.persistAccount({
1407
+ id: input.id,
1408
+ name: input.name,
1409
+ label: input.label,
1410
+ providerId: input.providerId,
1411
+ configuration: input.configuration,
1412
+ credentials: input.credentials,
1413
+ active: true,
1414
+ ownerUserId: input.id ? void 0 : this.actingUserId ?? null
1415
+ }, true);
1416
+ return withTenant({ tenantId: this.options.tenantId }, async () => {
1417
+ const account = await this.loadAccount(view.id);
1418
+ await account.markConnected();
1419
+ return this.accountView(account);
1420
+ });
1421
+ }
1422
+ /** Pause or resume a mailbox without touching its credential. */
1423
+ async setAccountActive(accountId, active) {
1424
+ this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
1425
+ return withTenant({ tenantId: this.options.tenantId }, async () => {
1426
+ const account = await this.loadAccount(accountId);
1427
+ this.assertMayManage(account);
1428
+ account.isActive = active;
1429
+ account.updatedAt = /* @__PURE__ */ new Date();
1430
+ await account.save();
1431
+ return this.accountView(account);
1432
+ });
1433
+ }
1434
+ /**
1435
+ * Remove a mailbox: its stored credential, its synced emails, folders and
1436
+ * attachments, and the account itself.
1437
+ */
1438
+ async removeAccount(accountId) {
1439
+ this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
1440
+ await withTenant({ tenantId: this.options.tenantId }, async () => {
1441
+ const account = await this.loadAccount(accountId);
1442
+ this.assertMayManage(account);
1443
+ await runWithMailSystemAccess(async () => {
1444
+ const db = this.options.db;
1445
+ const messages = await MessageCollection.create({ db });
1446
+ const attachments = await AttachmentCollection.create({ db });
1447
+ const folders = await EmailFolderCollection.create({ db });
1448
+ for (const message of await messages.list({ where: { accountId } })) {
1449
+ if (message.id) for (const attachment of await attachments.list({ where: { messageId: message.id } })) await attachment.delete();
1450
+ await message.delete();
1451
+ }
1452
+ for (const folder of await folders.list({ where: { accountId } })) await folder.delete();
1453
+ });
1454
+ await account.removeCredentials();
1455
+ await account.delete();
1456
+ });
1457
+ }
2532
1458
  async saveEndpoint(input) {
2533
1459
  this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);
2534
1460
  const provider = this.requireProvider(input.providerId);
@@ -2588,6 +1514,80 @@ var MessagingSettingsService = class {
2588
1514
  return route;
2589
1515
  });
2590
1516
  }
1517
+ /** The user who owns accounts this principal creates; null when unknown. */
1518
+ get actingUserId() {
1519
+ return this.options.principal.userId ?? this.options.principal.id ?? null;
1520
+ }
1521
+ async loadAccount(accountId) {
1522
+ const account = await (await AccountCollection.create({ db: this.options.db })).get({ id: accountId });
1523
+ if (!account || account.tenantId !== this.options.tenantId) throw new Error("Messaging account was not found in this tenant.");
1524
+ return account;
1525
+ }
1526
+ /** An owned mailbox is managed by its owner only; unowned ones by admins. */
1527
+ assertMayManage(account) {
1528
+ if (account.ownerUserId && account.ownerUserId !== this.actingUserId) throw new Error("Only the mail account owner can change this account.");
1529
+ }
1530
+ async validateConnection(request) {
1531
+ try {
1532
+ if (this.options.validateMailbox) {
1533
+ await this.options.validateMailbox(request);
1534
+ return;
1535
+ }
1536
+ this.assertAllowedTarget(request.configuration);
1537
+ const create = request.provider.createEmailClient;
1538
+ if (!create) throw new Error("this provider cannot check a mailbox sign-in");
1539
+ const settings = {
1540
+ ...request.configuration,
1541
+ ...request.credentials
1542
+ };
1543
+ delete settings.email;
1544
+ const client = await create({
1545
+ type: request.provider.id,
1546
+ ...settings
1547
+ });
1548
+ try {
1549
+ await client.connect();
1550
+ } finally {
1551
+ await client.disconnect().catch(() => void 0);
1552
+ }
1553
+ } catch {
1554
+ throw new Error("The mail server did not accept this connection.");
1555
+ }
1556
+ }
1557
+ /**
1558
+ * Host and port allowlist for the built-in validator (SSRF guard).
1559
+ *
1560
+ * Names are checked, not resolved: an allowlisted name that resolves (or is
1561
+ * rebound) to a private address is the host's allowlist responsibility, so
1562
+ * list only names you control, or pass a `validateMailbox` that resolves and
1563
+ * pins the address it connects to.
1564
+ */
1565
+ assertAllowedTarget(configuration) {
1566
+ let host = typeof configuration.host === "string" ? configuration.host : "";
1567
+ let port = typeof configuration.port === "number" ? configuration.port : void 0;
1568
+ if (!host && typeof configuration.endpoint === "string") {
1569
+ const url = new URL(configuration.endpoint);
1570
+ if (url.protocol !== "https:") throw new Error("refused");
1571
+ host = url.hostname;
1572
+ port ??= url.port ? Number(url.port) : 443;
1573
+ }
1574
+ host = host.toLowerCase().replace(/^\[|\]$/g, "");
1575
+ const allowed = this.options.allowedMailHosts ?? [];
1576
+ const ports = this.options.allowedMailPorts ?? [
1577
+ 143,
1578
+ 443,
1579
+ 465,
1580
+ 587,
1581
+ 993,
1582
+ 995
1583
+ ];
1584
+ const listed = allowed.some((entry) => {
1585
+ const pattern = entry.toLowerCase();
1586
+ return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1 : host === pattern;
1587
+ });
1588
+ if (!host || !listed || isPrivateMailHost(host)) throw new Error("refused");
1589
+ if (port !== void 0 && !ports.includes(port)) throw new Error("refused");
1590
+ }
2591
1591
  assert(permission) {
2592
1592
  assertMessagingPermission(this.options.principal, this.options.tenantId, permission);
2593
1593
  }
@@ -2653,7 +1653,11 @@ var MessagingSettingsService = class {
2653
1653
  channel: account.channelType,
2654
1654
  configuration: account.getConfiguration(),
2655
1655
  hasCredentials: account.hasCredentials,
2656
- active: account.isActive
1656
+ active: account.isActive,
1657
+ ownerUserId: account.ownerUserId,
1658
+ label: account.label,
1659
+ connectionStatus: account.connectionStatus,
1660
+ statusMessage: account.statusMessage
2657
1661
  };
2658
1662
  }
2659
1663
  endpointView(endpoint) {
@@ -2668,6 +1672,16 @@ var MessagingSettingsService = class {
2668
1672
  };
2669
1673
  }
2670
1674
  };
1675
+ function isPrivateMailHost(host) {
1676
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
1677
+ const v4 = host.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
1678
+ if (v4) {
1679
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
1680
+ return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168;
1681
+ }
1682
+ if (host.includes(":")) return host === "::" || host === "::1" || /^f[cd]/.test(host) || /^fe[89ab]/.test(host) || host.startsWith("::ffff:");
1683
+ return false;
1684
+ }
2671
1685
  //#endregion
2672
1686
  //#region src/services/NotificationOptOutService.ts
2673
1687
  var NotificationOptOutDeniedError = class extends Error {
@@ -3216,6 +2230,10 @@ var NotificationOutboxService = class {
3216
2230
  const address = recipient?.address?.trim();
3217
2231
  if (!address || /[\s,;<>]/u.test(address) || !address.includes("@")) throw new NotificationOutboxDeniedError("recipient", "The host did not authorize an email recipient for this user.");
3218
2232
  const accountId = await this.requireSenderAccount(tenantId);
2233
+ if (!await this.principalMaySend({
2234
+ tenantId,
2235
+ accountId
2236
+ })) throw new NotificationOutboxDeniedError("permission", "The principal lacks send access on the sender account.");
3219
2237
  const suppressed = await this.isSuppressed({
3220
2238
  tenantId,
3221
2239
  ...recipientUserId ? { recipientUserId } : {},
@@ -3319,7 +2337,17 @@ var NotificationOutboxService = class {
3319
2337
  });
3320
2338
  continue;
3321
2339
  }
3322
- const outcome = await withTenant({ tenantId: candidate.tenantId }, () => this.dispatchOne(candidate));
2340
+ if (!await this.principalMaySend(candidate)) {
2341
+ const lastError = "Blocked: mail access denied for scope send";
2342
+ if (candidate.lastError !== lastError) await withTenant({ tenantId: candidate.tenantId }, () => candidate.transition({ lastError }));
2343
+ report.outcomes.push({
2344
+ deliveryId: candidate.id,
2345
+ tenantId: candidate.tenantId,
2346
+ outcome: "blocked"
2347
+ });
2348
+ continue;
2349
+ }
2350
+ const outcome = await withTenant({ tenantId: candidate.tenantId }, () => runWithMailSystemAccess(() => this.dispatchOne(candidate)));
3323
2351
  if (!outcome) continue;
3324
2352
  report.leased += 1;
3325
2353
  report.outcomes.push({
@@ -3355,6 +2383,36 @@ var NotificationOutboxService = class {
3355
2383
  this.authorize(tenantId);
3356
2384
  if (!UUID_PATTERN$1.test(input.deliveryId ?? "")) return false;
3357
2385
  return withTenant({ tenantId }, async () => {
2386
+ if (this.options.principal) {
2387
+ const delivery = (await (await this.collection()).list({
2388
+ where: {
2389
+ tenantId,
2390
+ id: input.deliveryId
2391
+ },
2392
+ limit: 1
2393
+ }))[0];
2394
+ if (!delivery || !await this.principalMaySend(delivery)) return false;
2395
+ }
2396
+ return runWithMailSystemAccess(() => this.reconcileImpl(tenantId, input));
2397
+ });
2398
+ }
2399
+ /** True without a principal (trusted worker); else needs `send` on the account. */
2400
+ async principalMaySend(delivery) {
2401
+ const principal = this.options.principal;
2402
+ if (!principal) return true;
2403
+ const tenantId = delivery.tenantId;
2404
+ const userId = principal.userId ?? principal.id;
2405
+ if (!delivery.accountId) return false;
2406
+ const account = await withTenant({ tenantId }, () => runWithMailSystemAccess(async () => (await AccountCollection.create({ db: this.options.db })).get({ id: delivery.accountId })));
2407
+ if (!account || account.tenantId !== tenantId) return false;
2408
+ return (await withTenant({ tenantId }, () => decideMailAccess(account, "send", userId ? {
2409
+ id: principal.id ?? userId,
2410
+ tenantId,
2411
+ userId
2412
+ } : null))).allowed;
2413
+ }
2414
+ async reconcileImpl(tenantId, input) {
2415
+ {
3358
2416
  const delivery = (await (await this.collection()).list({
3359
2417
  where: {
3360
2418
  tenantId,
@@ -3389,7 +2447,7 @@ var NotificationOutboxService = class {
3389
2447
  }
3390
2448
  default: throw new Error(`Unknown reconcile outcome '${input.outcome}'.`);
3391
2449
  }
3392
- });
2450
+ }
3393
2451
  }
3394
2452
  async requireSenderAccount(tenantId) {
3395
2453
  const accountId = (await this.options.resolveSenderAccountId({ tenantId }))?.trim();
@@ -4271,7 +3329,8 @@ var SlackRecipe = class extends SmrtRecipe {
4271
3329
  //#region src/index.ts
4272
3330
  ensureBuiltinMessagingProvidersRegistered();
4273
3331
  ensureMessagingPermissionsRegistered();
3332
+ ensureMailAccessEnforcementRegistered();
4274
3333
  //#endregion
4275
- 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 };
3334
+ export { Account, AccountCollection, Attachment, AttachmentCollection, Blacklist, BlacklistCollection, Email, EmailAccount, EmailAccountCollection, EmailAttachment, EmailAttachmentCollection, EmailCollection, EmailFolder, EmailFolderCollection, EmailSender, MAIL_ACCOUNT_RESOURCE_TYPE, MAIL_SCOPES, MANAGE_MESSAGE_CREDENTIALS_PERMISSION, MANAGE_MESSAGE_ROUTES_PERMISSION, MESSAGING_PERMISSION_DEFINITIONS, MailAccessError, MailAccessService, 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, assertMailAccess, assertMessagingPermission, assertNotificationProfileRecipientSchema, buildNotificationLink, canAccessMailAccount, configureMailAccess, decideMailAccess, deniedMailAccountIds, ensureBuiltinMessagingProvidersRegistered, ensureMessagingPermissionsRegistered, getMessagingProvider, isMailScope, isValidNotificationOptOutScope, listMessagingProviders, mailScopePermission, messageSendTransport, messagingPrincipalFromPermissions, migrateNotificationProfileRecipients, notificationDeliveryCorrelationId, notificationDeliveryMessageId, optOutSuppression, planNotificationProfileRecipients, profileNotificationPolicy, registerMessagingProvider, resetMailAccess, runWithMailSystemAccess };
4276
3335
 
4277
3336
  //# sourceMappingURL=index.js.map