@happyvertical/smrt-messages 0.62.6 → 0.62.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +102 -0
- package/dist/access-enforcement.d.ts +20 -0
- package/dist/access-enforcement.d.ts.map +1 -0
- package/dist/access.d.ts +203 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/chunks/AttachmentCollection-DhCoruwp.js +308 -0
- package/dist/chunks/AttachmentCollection-DhCoruwp.js.map +1 -0
- package/dist/chunks/{Email-ChfbMCSF.js → Email-CmNoK1lj.js} +9 -6
- package/dist/chunks/Email-CmNoK1lj.js.map +1 -0
- package/dist/chunks/EmailAccountCollection-CHizpsxL.js +1555 -0
- package/dist/chunks/EmailAccountCollection-CHizpsxL.js.map +1 -0
- package/dist/chunks/EmailCollection-Yo2wBv_1.js +181 -0
- package/dist/chunks/EmailCollection-Yo2wBv_1.js.map +1 -0
- package/dist/chunks/{EmailFolder-XH5eH4Ed.js → EmailFolder-Dks5clxA.js} +25 -6
- package/dist/chunks/EmailFolder-Dks5clxA.js.map +1 -0
- package/dist/chunks/EmailFolderCollection-nIR4Kpcr.js +177 -0
- package/dist/chunks/EmailFolderCollection-nIR4Kpcr.js.map +1 -0
- package/dist/chunks/EmailSender-B-Rtq9du.js +147 -0
- package/dist/chunks/EmailSender-B-Rtq9du.js.map +1 -0
- package/dist/chunks/{Message-C6P1V5C_.js → Message-e99HkbG8.js} +30 -6
- package/dist/chunks/Message-e99HkbG8.js.map +1 -0
- package/dist/chunks/{MessageCollection-CjCT06XE.js → MessageCollection-t8cLUSNJ.js} +2 -2
- package/dist/chunks/{MessageCollection-CjCT06XE.js.map → MessageCollection-t8cLUSNJ.js.map} +1 -1
- package/dist/chunks/MessagingEndpointCollection-CGtAL77R.js +97 -0
- package/dist/chunks/MessagingEndpointCollection-CGtAL77R.js.map +1 -0
- package/dist/chunks/{SlackSender-CjSvwY1K.js → SlackSender-CetlSe6D.js} +2 -2
- package/dist/chunks/{SlackSender-CjSvwY1K.js.map → SlackSender-CetlSe6D.js.map} +1 -1
- package/dist/chunks/{TweetSender-CcLPNNi1.js → TweetSender-Dw-TDxIB.js} +2 -2
- package/dist/chunks/{TweetSender-CcLPNNi1.js.map → TweetSender-Dw-TDxIB.js.map} +1 -1
- package/dist/chunks/{providers-4iLula-V.js → providers-Bz_F_ywF.js} +36 -1
- package/dist/chunks/{providers-4iLula-V.js.map → providers-Bz_F_ywF.js.map} +1 -1
- package/dist/collections/AttachmentCollection.d.ts +6 -0
- package/dist/collections/AttachmentCollection.d.ts.map +1 -1
- package/dist/collections/EmailAccountCollection.d.ts.map +1 -1
- package/dist/connect.d.ts +82 -0
- package/dist/connect.d.ts.map +1 -0
- package/dist/connect.js +126 -0
- package/dist/connect.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +507 -1402
- package/dist/index.js.map +1 -1
- package/dist/mail-sync-jobs.d.ts +48 -0
- package/dist/mail-sync-jobs.d.ts.map +1 -0
- package/dist/mail-sync.d.ts +58 -0
- package/dist/mail-sync.d.ts.map +1 -0
- package/dist/manifest.json +1040 -56
- package/dist/models/Account.d.ts +23 -0
- package/dist/models/Account.d.ts.map +1 -1
- package/dist/models/Attachment.d.ts +14 -0
- package/dist/models/Attachment.d.ts.map +1 -1
- package/dist/models/Email.d.ts +1 -0
- package/dist/models/Email.d.ts.map +1 -1
- package/dist/models/EmailAccount.d.ts +32 -2
- package/dist/models/EmailAccount.d.ts.map +1 -1
- package/dist/models/EmailFolder.d.ts +7 -0
- package/dist/models/EmailFolder.d.ts.map +1 -1
- package/dist/models/Message.d.ts +7 -0
- package/dist/models/Message.d.ts.map +1 -1
- package/dist/permissions.d.ts +11 -0
- package/dist/permissions.d.ts.map +1 -1
- package/dist/providers/email.js +3 -2
- package/dist/providers/email.js.map +1 -1
- package/dist/providers/slack.js +2 -2
- package/dist/providers/twitter.js +2 -2
- package/dist/providers.d.ts.map +1 -1
- package/dist/recipes.d.ts +1 -1
- package/dist/services/MessagingSettingsService.d.ts +86 -0
- package/dist/services/MessagingSettingsService.d.ts.map +1 -1
- package/dist/services/NotificationOutboxService.d.ts +3 -0
- package/dist/services/NotificationOutboxService.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +826 -29
- package/dist/smrt-knowledge.okf.md +4 -2
- package/dist/types.d.ts +10 -1
- package/dist/types.d.ts.map +1 -1
- package/package.json +21 -16
- package/dist/chunks/AccountCollection-RP_hLf6L.js +0 -257
- package/dist/chunks/AccountCollection-RP_hLf6L.js.map +0 -1
- package/dist/chunks/Email-ChfbMCSF.js.map +0 -1
- package/dist/chunks/EmailFolder-XH5eH4Ed.js.map +0 -1
- package/dist/chunks/Message-C6P1V5C_.js.map +0 -1
- package/dist/chunks/__smrt-register__-CfOb1uCN.js +0 -6
- package/dist/chunks/__smrt-register__-CfOb1uCN.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,429 +1,219 @@
|
|
|
1
|
-
import { t as
|
|
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-CHizpsxL.js";
|
|
4
2
|
import { buildSqliteRebuildStatements, isDeepStrictEqual, normalizeIdentityEmail, queryGlobal, queryWithGlobals, readNotificationProfile, withSystemContext, withTenant } from "./host.js";
|
|
5
|
-
import { r as
|
|
6
|
-
import {
|
|
7
|
-
import { t as
|
|
8
|
-
import { t as
|
|
9
|
-
import { t as
|
|
10
|
-
import { t as
|
|
11
|
-
import { t as
|
|
12
|
-
import { t as
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
3
|
+
import { r as Attachment, t as AttachmentCollection } from "./chunks/AttachmentCollection-DhCoruwp.js";
|
|
4
|
+
import { t as EmailFolder } from "./chunks/EmailFolder-Dks5clxA.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-e99HkbG8.js";
|
|
7
|
+
import { a as registerMessagingProvider, n as getMessagingProvider, o as ZulipSender, r as listMessagingProviders, s as TelegramSender, t as ensureBuiltinMessagingProvidersRegistered } from "./chunks/providers-Bz_F_ywF.js";
|
|
8
|
+
import { t as MessageCollection } from "./chunks/MessageCollection-t8cLUSNJ.js";
|
|
9
|
+
import { r as MessagingEndpoint, t as MessagingEndpointCollection } from "./chunks/MessagingEndpointCollection-CGtAL77R.js";
|
|
10
|
+
import { t as Email } from "./chunks/Email-CmNoK1lj.js";
|
|
11
|
+
import { t as EmailCollection } from "./chunks/EmailCollection-Yo2wBv_1.js";
|
|
12
|
+
import { t as EmailFolderCollection } from "./chunks/EmailFolderCollection-nIR4Kpcr.js";
|
|
13
|
+
import { t as EmailSender } from "./chunks/EmailSender-B-Rtq9du.js";
|
|
14
|
+
import { t as SlackSender } from "./chunks/SlackSender-CetlSe6D.js";
|
|
15
|
+
import { t as TweetSender } from "./chunks/TweetSender-Dw-TDxIB.js";
|
|
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/
|
|
17
|
-
var
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
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
|
-
|
|
41
|
-
|
|
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
|
-
|
|
44
|
-
|
|
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-t8cLUSNJ.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
|
|
150
|
+
function ensureMailAccessEnforcementRegistered() {
|
|
53
151
|
if (registered) return;
|
|
54
152
|
registered = true;
|
|
55
|
-
|
|
153
|
+
GlobalInterceptors.register(createMailAccessInterceptor());
|
|
56
154
|
}
|
|
57
155
|
//#endregion
|
|
58
|
-
//#region src/
|
|
59
|
-
var
|
|
60
|
-
var
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
if (
|
|
71
|
-
return
|
|
72
|
-
};
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
return {
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
156
|
+
//#region src/mail-sync-jobs.ts
|
|
157
|
+
var MAIL_SYNC_QUEUE = "mail-sync";
|
|
158
|
+
var CHANGE_FEED_PROVIDERS = ["jmap"];
|
|
159
|
+
function mailSyncDedupeKey(accountId) {
|
|
160
|
+
return `mail-sync:${accountId}`;
|
|
161
|
+
}
|
|
162
|
+
function accountClassName() {
|
|
163
|
+
const registered = ObjectRegistry.getClass("EmailAccount") ?? ObjectRegistry.getClassByQualifiedName("@happyvertical/smrt-messages:EmailAccount");
|
|
164
|
+
return registered?.qualifiedName ?? registered?.name ?? "EmailAccount";
|
|
165
|
+
}
|
|
166
|
+
async function enqueueMailSync(account, options = {}) {
|
|
167
|
+
if (!account.id) throw new Error("enqueueMailSync needs a persisted account");
|
|
168
|
+
if (!account.isActive || account.needsReconnect) return null;
|
|
169
|
+
if (!CHANGE_FEED_PROVIDERS.includes(account.providerType)) return null;
|
|
170
|
+
const { SmrtJobCollection } = await import("@happyvertical/smrt-jobs");
|
|
171
|
+
const db = account.db;
|
|
172
|
+
const jobs = await SmrtJobCollection.create({ db });
|
|
173
|
+
const args = {};
|
|
174
|
+
if (options.limit !== void 0) args.limit = options.limit;
|
|
175
|
+
if (options.maxBatches !== void 0) args.maxBatches = options.maxBatches;
|
|
176
|
+
return jobs.enqueueJob({
|
|
177
|
+
dedupeKey: mailSyncDedupeKey(account.id),
|
|
178
|
+
tenantId: account.tenantId ?? null,
|
|
179
|
+
queue: MAIL_SYNC_QUEUE,
|
|
180
|
+
objectType: accountClassName(),
|
|
181
|
+
objectId: account.id,
|
|
182
|
+
method: "syncChanges",
|
|
183
|
+
args,
|
|
184
|
+
runAt: options.runAt,
|
|
185
|
+
priority: options.priority,
|
|
186
|
+
maxAttempts: options.maxAttempts ?? 3,
|
|
187
|
+
timeout: options.timeout ?? 900 * 1e3
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
async function enqueueDueMailSyncs(accounts, options = {}) {
|
|
191
|
+
const now = (options.now ?? /* @__PURE__ */ new Date()).getTime();
|
|
192
|
+
const queued = [];
|
|
193
|
+
for (const account of accounts) {
|
|
194
|
+
if (!(!account.lastSyncAt || now - account.lastSyncAt.getTime() >= (account.syncIntervalMinutes || 0) * 6e4)) continue;
|
|
195
|
+
const job = await enqueueMailSync(account, options);
|
|
196
|
+
if (job?.id) queued.push(String(job.id));
|
|
197
|
+
}
|
|
198
|
+
return queued;
|
|
82
199
|
}
|
|
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
200
|
//#endregion
|
|
411
201
|
//#region src/models/NotificationDelivery.ts
|
|
412
|
-
var __defProp$
|
|
413
|
-
var __getOwnPropDesc$
|
|
414
|
-
var __defNormalProp$
|
|
202
|
+
var __defProp$11 = Object.defineProperty;
|
|
203
|
+
var __getOwnPropDesc$11 = Object.getOwnPropertyDescriptor;
|
|
204
|
+
var __defNormalProp$11 = (obj, key, value) => key in obj ? __defProp$11(obj, key, {
|
|
415
205
|
enumerable: true,
|
|
416
206
|
configurable: true,
|
|
417
207
|
writable: true,
|
|
418
208
|
value
|
|
419
209
|
}) : obj[key] = value;
|
|
420
|
-
var __decorateClass$
|
|
421
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$
|
|
210
|
+
var __decorateClass$11 = (decorators, target, key, kind) => {
|
|
211
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$11(target, key) : target;
|
|
422
212
|
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$
|
|
213
|
+
if (kind && result) __defProp$11(target, key, result);
|
|
424
214
|
return result;
|
|
425
215
|
};
|
|
426
|
-
var __publicField$
|
|
216
|
+
var __publicField$11 = (obj, key, value) => __defNormalProp$11(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
427
217
|
var NOTIFICATION_DELIVERY_CHANNELS = ["email"];
|
|
428
218
|
var TRANSITION_COLUMNS = {
|
|
429
219
|
messageId: "message_id",
|
|
@@ -643,37 +433,37 @@ var NotificationDelivery = class extends SmrtObject {
|
|
|
643
433
|
return true;
|
|
644
434
|
}
|
|
645
435
|
};
|
|
646
|
-
__publicField$
|
|
647
|
-
__decorateClass$
|
|
648
|
-
__decorateClass$
|
|
649
|
-
__decorateClass$
|
|
650
|
-
__decorateClass$
|
|
436
|
+
__publicField$11(NotificationDelivery, "__smrtPackage__", "@happyvertical/smrt-messages");
|
|
437
|
+
__decorateClass$11([tenantId()], NotificationDelivery.prototype, "tenantId", 2);
|
|
438
|
+
__decorateClass$11([crossPackageRef("@happyvertical/smrt-users:User", { nullable: true })], NotificationDelivery.prototype, "recipientUserId", 2);
|
|
439
|
+
__decorateClass$11([crossPackageRef("@happyvertical/smrt-profiles:Profile", { nullable: true })], NotificationDelivery.prototype, "recipientProfileId", 2);
|
|
440
|
+
__decorateClass$11([field({
|
|
651
441
|
required: true,
|
|
652
442
|
requiredFor: "identity"
|
|
653
443
|
})], NotificationDelivery.prototype, "recipientKind", 2);
|
|
654
|
-
__decorateClass$
|
|
444
|
+
__decorateClass$11([field({
|
|
655
445
|
required: true,
|
|
656
446
|
requiredFor: "identity"
|
|
657
447
|
})], NotificationDelivery.prototype, "channel", 2);
|
|
658
|
-
__decorateClass$
|
|
448
|
+
__decorateClass$11([field({
|
|
659
449
|
required: true,
|
|
660
450
|
requiredFor: "idempotency"
|
|
661
451
|
})], NotificationDelivery.prototype, "sourceRef", 2);
|
|
662
|
-
__decorateClass$
|
|
452
|
+
__decorateClass$11([field({
|
|
663
453
|
required: true,
|
|
664
454
|
requiredFor: "identity"
|
|
665
455
|
})], NotificationDelivery.prototype, "kind", 2);
|
|
666
|
-
__decorateClass$
|
|
667
|
-
__decorateClass$
|
|
668
|
-
__decorateClass$
|
|
669
|
-
__decorateClass$
|
|
670
|
-
__decorateClass$
|
|
456
|
+
__decorateClass$11([field({ type: "json" })], NotificationDelivery.prototype, "dispatchPolicyBinding", 2);
|
|
457
|
+
__decorateClass$11([field()], NotificationDelivery.prototype, "subject", 2);
|
|
458
|
+
__decorateClass$11([field()], NotificationDelivery.prototype, "textBody", 2);
|
|
459
|
+
__decorateClass$11([field()], NotificationDelivery.prototype, "href", 2);
|
|
460
|
+
__decorateClass$11([field({
|
|
671
461
|
required: true,
|
|
672
462
|
requiredFor: "identity"
|
|
673
463
|
})], NotificationDelivery.prototype, "recipientAddress", 2);
|
|
674
|
-
__decorateClass$
|
|
675
|
-
__decorateClass$
|
|
676
|
-
NotificationDelivery = __decorateClass$
|
|
464
|
+
__decorateClass$11([foreignKey("Account")], NotificationDelivery.prototype, "accountId", 2);
|
|
465
|
+
__decorateClass$11([foreignKey("Message")], NotificationDelivery.prototype, "messageId", 2);
|
|
466
|
+
NotificationDelivery = __decorateClass$11([TenantScoped({ mode: "required" }), smrt({
|
|
677
467
|
tableName: "notification_deliveries",
|
|
678
468
|
api: false,
|
|
679
469
|
mcp: false,
|
|
@@ -724,21 +514,21 @@ var NotificationDeliveryCollection = class extends SmrtCollection {
|
|
|
724
514
|
};
|
|
725
515
|
//#endregion
|
|
726
516
|
//#region src/models/NotificationOptOut.ts
|
|
727
|
-
var __defProp$
|
|
728
|
-
var __getOwnPropDesc$
|
|
729
|
-
var __defNormalProp$
|
|
517
|
+
var __defProp$10 = Object.defineProperty;
|
|
518
|
+
var __getOwnPropDesc$10 = Object.getOwnPropertyDescriptor;
|
|
519
|
+
var __defNormalProp$10 = (obj, key, value) => key in obj ? __defProp$10(obj, key, {
|
|
730
520
|
enumerable: true,
|
|
731
521
|
configurable: true,
|
|
732
522
|
writable: true,
|
|
733
523
|
value
|
|
734
524
|
}) : obj[key] = value;
|
|
735
|
-
var __decorateClass$
|
|
736
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$
|
|
525
|
+
var __decorateClass$10 = (decorators, target, key, kind) => {
|
|
526
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$10(target, key) : target;
|
|
737
527
|
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$
|
|
528
|
+
if (kind && result) __defProp$10(target, key, result);
|
|
739
529
|
return result;
|
|
740
530
|
};
|
|
741
|
-
var __publicField$
|
|
531
|
+
var __publicField$10 = (obj, key, value) => __defNormalProp$10(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
742
532
|
var NOTIFICATION_OPT_OUT_SCOPE_PATTERN = /^(?:\*|[a-z][a-z0-9-]*:[A-Za-z0-9._:-]{1,200})$/;
|
|
743
533
|
var NOTIFICATION_OPT_OUT_ALL_SCOPE = "*";
|
|
744
534
|
function isValidNotificationOptOutScope(scope) {
|
|
@@ -766,18 +556,18 @@ var NotificationOptOut = class extends SmrtObject {
|
|
|
766
556
|
return this.optedOutAt !== null;
|
|
767
557
|
}
|
|
768
558
|
};
|
|
769
|
-
__publicField$
|
|
770
|
-
__decorateClass$
|
|
771
|
-
__decorateClass$
|
|
559
|
+
__publicField$10(NotificationOptOut, "__smrtPackage__", "@happyvertical/smrt-messages");
|
|
560
|
+
__decorateClass$10([tenantId()], NotificationOptOut.prototype, "tenantId", 2);
|
|
561
|
+
__decorateClass$10([crossPackageRef("@happyvertical/smrt-users:User", {
|
|
772
562
|
required: true,
|
|
773
563
|
requiredFor: "identity"
|
|
774
564
|
})], NotificationOptOut.prototype, "recipientUserId", 2);
|
|
775
|
-
__decorateClass$
|
|
776
|
-
__decorateClass$
|
|
565
|
+
__decorateClass$10([field({ required: true })], NotificationOptOut.prototype, "channel", 2);
|
|
566
|
+
__decorateClass$10([field({
|
|
777
567
|
required: true,
|
|
778
568
|
requiredFor: "identity"
|
|
779
569
|
})], NotificationOptOut.prototype, "scope", 2);
|
|
780
|
-
NotificationOptOut = __decorateClass$
|
|
570
|
+
NotificationOptOut = __decorateClass$10([TenantScoped({ mode: "required" }), smrt({
|
|
781
571
|
tableName: "notification_opt_outs",
|
|
782
572
|
api: false,
|
|
783
573
|
mcp: false,
|
|
@@ -796,21 +586,21 @@ var NotificationOptOutCollection = class extends SmrtCollection {
|
|
|
796
586
|
};
|
|
797
587
|
//#endregion
|
|
798
588
|
//#region src/models/PersonaMessageRoute.ts
|
|
799
|
-
var __defProp$
|
|
800
|
-
var __getOwnPropDesc$
|
|
801
|
-
var __defNormalProp$
|
|
589
|
+
var __defProp$9 = Object.defineProperty;
|
|
590
|
+
var __getOwnPropDesc$9 = Object.getOwnPropertyDescriptor;
|
|
591
|
+
var __defNormalProp$9 = (obj, key, value) => key in obj ? __defProp$9(obj, key, {
|
|
802
592
|
enumerable: true,
|
|
803
593
|
configurable: true,
|
|
804
594
|
writable: true,
|
|
805
595
|
value
|
|
806
596
|
}) : obj[key] = value;
|
|
807
|
-
var __decorateClass$
|
|
808
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$
|
|
597
|
+
var __decorateClass$9 = (decorators, target, key, kind) => {
|
|
598
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$9(target, key) : target;
|
|
809
599
|
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$
|
|
600
|
+
if (kind && result) __defProp$9(target, key, result);
|
|
811
601
|
return result;
|
|
812
602
|
};
|
|
813
|
-
var __publicField$
|
|
603
|
+
var __publicField$9 = (obj, key, value) => __defNormalProp$9(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
814
604
|
var PersonaMessageRoute = class extends SmrtObject {
|
|
815
605
|
tenantId = "";
|
|
816
606
|
personaId = "";
|
|
@@ -834,22 +624,22 @@ var PersonaMessageRoute = class extends SmrtObject {
|
|
|
834
624
|
if (options.updatedAt !== void 0) this.updatedAt = options.updatedAt;
|
|
835
625
|
}
|
|
836
626
|
};
|
|
837
|
-
__publicField$
|
|
838
|
-
__decorateClass$
|
|
839
|
-
__decorateClass$
|
|
627
|
+
__publicField$9(PersonaMessageRoute, "__smrtPackage__", "@happyvertical/smrt-messages");
|
|
628
|
+
__decorateClass$9([tenantId()], PersonaMessageRoute.prototype, "tenantId", 2);
|
|
629
|
+
__decorateClass$9([crossPackageRef("@happyvertical/smrt-personas:AgentPersona", {
|
|
840
630
|
required: true,
|
|
841
631
|
requiredFor: "identity"
|
|
842
632
|
})], PersonaMessageRoute.prototype, "personaId", 2);
|
|
843
|
-
__decorateClass$
|
|
633
|
+
__decorateClass$9([foreignKey("Account", {
|
|
844
634
|
required: true,
|
|
845
635
|
requiredFor: "identity"
|
|
846
636
|
})], PersonaMessageRoute.prototype, "accountId", 2);
|
|
847
|
-
__decorateClass$
|
|
637
|
+
__decorateClass$9([foreignKey("MessagingEndpoint", {
|
|
848
638
|
required: true,
|
|
849
639
|
requiredFor: "identity"
|
|
850
640
|
})], PersonaMessageRoute.prototype, "endpointId", 2);
|
|
851
|
-
__decorateClass$
|
|
852
|
-
PersonaMessageRoute = __decorateClass$
|
|
641
|
+
__decorateClass$9([field({ required: true })], PersonaMessageRoute.prototype, "purpose", 2);
|
|
642
|
+
PersonaMessageRoute = __decorateClass$9([TenantScoped({ mode: "required" }), smrt({
|
|
853
643
|
tableName: "persona_message_routes",
|
|
854
644
|
api: { include: ["list", "get"] },
|
|
855
645
|
mcp: { include: ["list", "get"] },
|
|
@@ -875,21 +665,21 @@ var PersonaMessageRouteCollection = class extends SmrtCollection {
|
|
|
875
665
|
};
|
|
876
666
|
//#endregion
|
|
877
667
|
//#region src/models/UserNotification.ts
|
|
878
|
-
var __defProp$
|
|
879
|
-
var __getOwnPropDesc$
|
|
880
|
-
var __defNormalProp$
|
|
668
|
+
var __defProp$8 = Object.defineProperty;
|
|
669
|
+
var __getOwnPropDesc$8 = Object.getOwnPropertyDescriptor;
|
|
670
|
+
var __defNormalProp$8 = (obj, key, value) => key in obj ? __defProp$8(obj, key, {
|
|
881
671
|
enumerable: true,
|
|
882
672
|
configurable: true,
|
|
883
673
|
writable: true,
|
|
884
674
|
value
|
|
885
675
|
}) : obj[key] = value;
|
|
886
|
-
var __decorateClass$
|
|
887
|
-
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$
|
|
676
|
+
var __decorateClass$8 = (decorators, target, key, kind) => {
|
|
677
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$8(target, key) : target;
|
|
888
678
|
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$
|
|
679
|
+
if (kind && result) __defProp$8(target, key, result);
|
|
890
680
|
return result;
|
|
891
681
|
};
|
|
892
|
-
var __publicField$
|
|
682
|
+
var __publicField$8 = (obj, key, value) => __defNormalProp$8(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
893
683
|
var USER_NOTIFICATION_SEVERITIES = [
|
|
894
684
|
"info",
|
|
895
685
|
"success",
|
|
@@ -934,469 +724,41 @@ var UserNotification = class extends SmrtObject {
|
|
|
934
724
|
return this.dismissedAt !== null;
|
|
935
725
|
}
|
|
936
726
|
};
|
|
937
|
-
__publicField$
|
|
938
|
-
__decorateClass$
|
|
939
|
-
__decorateClass$
|
|
727
|
+
__publicField$8(UserNotification, "__smrtPackage__", "@happyvertical/smrt-messages");
|
|
728
|
+
__decorateClass$8([tenantId()], UserNotification.prototype, "tenantId", 2);
|
|
729
|
+
__decorateClass$8([crossPackageRef("@happyvertical/smrt-users:User", {
|
|
940
730
|
required: true,
|
|
941
731
|
requiredFor: "identity"
|
|
942
732
|
})], UserNotification.prototype, "recipientUserId", 2);
|
|
943
|
-
__decorateClass$
|
|
944
|
-
__decorateClass$
|
|
945
|
-
__decorateClass$
|
|
733
|
+
__decorateClass$8([field()], UserNotification.prototype, "kind", 2);
|
|
734
|
+
__decorateClass$8([field()], UserNotification.prototype, "title", 2);
|
|
735
|
+
__decorateClass$8([field({
|
|
946
736
|
required: true,
|
|
947
737
|
requiredFor: "idempotency"
|
|
948
738
|
})], UserNotification.prototype, "sourceRef", 2);
|
|
949
|
-
UserNotification = __decorateClass$
|
|
739
|
+
UserNotification = __decorateClass$8([TenantScoped({ mode: "required" }), smrt({
|
|
950
740
|
tableName: "user_notifications",
|
|
951
741
|
api: false,
|
|
952
742
|
mcp: false,
|
|
953
743
|
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
|
-
}
|
|
744
|
+
conflictColumns: [
|
|
745
|
+
"tenant_id",
|
|
746
|
+
"recipient_user_id",
|
|
747
|
+
"source_ref"
|
|
748
|
+
],
|
|
749
|
+
indexes: [{
|
|
750
|
+
name: "user_notifications_recipient_occurred_idx",
|
|
751
|
+
columns: [
|
|
752
|
+
"tenantId",
|
|
753
|
+
"recipientUserId",
|
|
754
|
+
"occurredAt"
|
|
755
|
+
]
|
|
756
|
+
}]
|
|
757
|
+
})], UserNotification);
|
|
758
|
+
//#endregion
|
|
759
|
+
//#region src/collections/UserNotificationCollection.ts
|
|
760
|
+
var UserNotificationCollection = class extends SmrtCollection {
|
|
761
|
+
static _itemClass = UserNotification;
|
|
1400
762
|
};
|
|
1401
763
|
//#endregion
|
|
1402
764
|
//#region src/models/EmailAttachment.ts
|
|
@@ -1423,7 +785,7 @@ var EmailAttachment = class extends Attachment {
|
|
|
1423
785
|
*/
|
|
1424
786
|
async getEmail() {
|
|
1425
787
|
if (!this.messageId) return null;
|
|
1426
|
-
const { EmailCollection } = await
|
|
788
|
+
const { EmailCollection } = await import("./chunks/EmailCollection-Yo2wBv_1.js").then((n) => n.n);
|
|
1427
789
|
return await (await EmailCollection.create(this.options)).get({ id: this.messageId });
|
|
1428
790
|
}
|
|
1429
791
|
};
|
|
@@ -1480,350 +842,6 @@ var EmailAttachmentCollection = class extends AttachmentCollection {
|
|
|
1480
842
|
}
|
|
1481
843
|
};
|
|
1482
844
|
//#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
845
|
//#region src/models/Blacklist.ts
|
|
1828
846
|
var __defProp$7 = Object.defineProperty;
|
|
1829
847
|
var __getOwnPropDesc$7 = Object.getOwnPropertyDescriptor;
|
|
@@ -2028,7 +1046,7 @@ var SlackAccount = class extends Account {
|
|
|
2028
1046
|
* Create a sender for this Slack account
|
|
2029
1047
|
*/
|
|
2030
1048
|
async createSender() {
|
|
2031
|
-
const { SlackSender } = await import("./chunks/SlackSender-
|
|
1049
|
+
const { SlackSender } = await import("./chunks/SlackSender-CetlSe6D.js").then((n) => n.n);
|
|
2032
1050
|
return new SlackSender(this);
|
|
2033
1051
|
}
|
|
2034
1052
|
};
|
|
@@ -2287,7 +1305,7 @@ var TwitterAccount = class extends Account {
|
|
|
2287
1305
|
* Create a sender for this Twitter account
|
|
2288
1306
|
*/
|
|
2289
1307
|
async createSender() {
|
|
2290
|
-
const { TweetSender } = await import("./chunks/TweetSender-
|
|
1308
|
+
const { TweetSender } = await import("./chunks/TweetSender-Dw-TDxIB.js").then((n) => n.n);
|
|
2291
1309
|
return new TweetSender(this);
|
|
2292
1310
|
}
|
|
2293
1311
|
};
|
|
@@ -2330,148 +1348,6 @@ ZulipAccount = __decorateClass([smrt({
|
|
|
2330
1348
|
cli: { include: ["list", "get"] }
|
|
2331
1349
|
})], ZulipAccount);
|
|
2332
1350
|
//#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
1351
|
//#region src/services/MessagingSettingsService.ts
|
|
2476
1352
|
var MessagingSettingsService = class {
|
|
2477
1353
|
constructor(options) {
|
|
@@ -2500,10 +1376,24 @@ var MessagingSettingsService = class {
|
|
|
2500
1376
|
};
|
|
2501
1377
|
});
|
|
2502
1378
|
}
|
|
1379
|
+
/**
|
|
1380
|
+
* Stores account settings only: it never opens a connection, so it is not an
|
|
1381
|
+
* SSRF vector by itself (connecting goes through `connectMailbox`, which is
|
|
1382
|
+
* allowlisted). The SMTP host/port it stores predate this change and are
|
|
1383
|
+
* used later by the sender; hosts that need an outbound allowlist apply it
|
|
1384
|
+
* there.
|
|
1385
|
+
*/
|
|
2503
1386
|
async saveAccount(input) {
|
|
1387
|
+
return this.persistAccount(input, false);
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* `receiveOnly` admits providers that are not outbound transports (IMAP,
|
|
1391
|
+
* POP3): a mailbox can be connected for reading without being a sender.
|
|
1392
|
+
*/
|
|
1393
|
+
async persistAccount(input, receiveOnly) {
|
|
2504
1394
|
this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
|
|
2505
1395
|
const provider = this.requireProvider(input.providerId);
|
|
2506
|
-
if (!provider.available) throw new Error(`Provider '${provider.id}' is not available.`);
|
|
1396
|
+
if (!provider.available && !(receiveOnly && provider.channel === "email")) throw new Error(`Provider '${provider.id}' is not available.`);
|
|
2507
1397
|
this.validateFields(input.configuration, provider.configurationFields, "configuration");
|
|
2508
1398
|
if (input.credentials) this.validateFields(input.credentials, provider.credentialFields, "credentials");
|
|
2509
1399
|
return withTenant({ tenantId: this.options.tenantId }, async () => {
|
|
@@ -2512,12 +1402,19 @@ var MessagingSettingsService = class {
|
|
|
2512
1402
|
const isNew = !account;
|
|
2513
1403
|
if (account && account.tenantId !== this.options.tenantId) throw new Error("Messaging account belongs to another tenant.");
|
|
2514
1404
|
if (account && account.providerType !== provider.id) throw new Error("A messaging account provider cannot be changed in place.");
|
|
1405
|
+
if (account) this.assertMayManage(account);
|
|
1406
|
+
if (account && input.ownerUserId !== void 0) {
|
|
1407
|
+
if ((input.ownerUserId ?? null) !== (account.ownerUserId ?? null)) throw new Error("Change a mail account owner with MailAccessService.setOwner.");
|
|
1408
|
+
}
|
|
1409
|
+
if (!account && input.ownerUserId && input.ownerUserId !== this.actingUserId) throw new Error("A new mail account can only be owned by its creator.");
|
|
2515
1410
|
if (isNew && !input.credentials && provider.credentialFields.some((field) => field.required)) throw new Error(`Credentials are required for new ${provider.label} accounts.`);
|
|
2516
1411
|
if (!account) {
|
|
2517
1412
|
account = this.newAccount(provider, input);
|
|
2518
1413
|
await account.initialize();
|
|
2519
1414
|
}
|
|
2520
1415
|
account.name = input.name.trim();
|
|
1416
|
+
if (isNew && input.ownerUserId) account.ownerUserId = input.ownerUserId;
|
|
1417
|
+
if (input.label !== void 0) account.label = input.label?.trim() || null;
|
|
2521
1418
|
account.isActive = input.active ?? account.isActive;
|
|
2522
1419
|
account.channelType = provider.channel;
|
|
2523
1420
|
const configuration = this.normalizeConfiguration(provider, input.configuration);
|
|
@@ -2529,6 +1426,80 @@ var MessagingSettingsService = class {
|
|
|
2529
1426
|
return this.accountView(account);
|
|
2530
1427
|
});
|
|
2531
1428
|
}
|
|
1429
|
+
/**
|
|
1430
|
+
* Connect a mailbox with a write-only secret (an app password). The
|
|
1431
|
+
* credential is validated by opening a session first; a refusal leaves no
|
|
1432
|
+
* account and no secret behind. The connecting user becomes the owner.
|
|
1433
|
+
*/
|
|
1434
|
+
async connectMailbox(input) {
|
|
1435
|
+
this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
|
|
1436
|
+
if (!this.actingUserId) throw new Error("Connecting a mailbox needs a signed-in user.");
|
|
1437
|
+
if (input.id) await withTenant({ tenantId: this.options.tenantId }, async () => {
|
|
1438
|
+
this.assertMayManage(await this.loadAccount(input.id));
|
|
1439
|
+
});
|
|
1440
|
+
const provider = this.requireProvider(input.providerId);
|
|
1441
|
+
if (provider.channel !== "email") throw new Error(`Provider '${provider.id}' cannot connect a mailbox.`);
|
|
1442
|
+
this.validateFields(input.configuration, provider.configurationFields, "configuration");
|
|
1443
|
+
this.validateFields(input.credentials, provider.credentialFields, "credentials");
|
|
1444
|
+
const configuration = this.normalizeConfiguration(provider, input.configuration);
|
|
1445
|
+
const credentials = this.normalizeCredentials(provider, input.credentials);
|
|
1446
|
+
await this.validateConnection({
|
|
1447
|
+
provider,
|
|
1448
|
+
configuration,
|
|
1449
|
+
credentials
|
|
1450
|
+
});
|
|
1451
|
+
const view = await this.persistAccount({
|
|
1452
|
+
id: input.id,
|
|
1453
|
+
name: input.name,
|
|
1454
|
+
label: input.label,
|
|
1455
|
+
providerId: input.providerId,
|
|
1456
|
+
configuration: input.configuration,
|
|
1457
|
+
credentials: input.credentials,
|
|
1458
|
+
active: true,
|
|
1459
|
+
ownerUserId: input.id ? void 0 : this.actingUserId ?? null
|
|
1460
|
+
}, true);
|
|
1461
|
+
return withTenant({ tenantId: this.options.tenantId }, async () => {
|
|
1462
|
+
const account = await this.loadAccount(view.id);
|
|
1463
|
+
await account.markConnected();
|
|
1464
|
+
return this.accountView(account);
|
|
1465
|
+
});
|
|
1466
|
+
}
|
|
1467
|
+
/** Pause or resume a mailbox without touching its credential. */
|
|
1468
|
+
async setAccountActive(accountId, active) {
|
|
1469
|
+
this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
|
|
1470
|
+
return withTenant({ tenantId: this.options.tenantId }, async () => {
|
|
1471
|
+
const account = await this.loadAccount(accountId);
|
|
1472
|
+
this.assertMayManage(account);
|
|
1473
|
+
account.isActive = active;
|
|
1474
|
+
account.updatedAt = /* @__PURE__ */ new Date();
|
|
1475
|
+
await account.save();
|
|
1476
|
+
return this.accountView(account);
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Remove a mailbox: its stored credential, its synced emails, folders and
|
|
1481
|
+
* attachments, and the account itself.
|
|
1482
|
+
*/
|
|
1483
|
+
async removeAccount(accountId) {
|
|
1484
|
+
this.assert(MANAGE_MESSAGE_CREDENTIALS_PERMISSION);
|
|
1485
|
+
await withTenant({ tenantId: this.options.tenantId }, async () => {
|
|
1486
|
+
const account = await this.loadAccount(accountId);
|
|
1487
|
+
this.assertMayManage(account);
|
|
1488
|
+
await runWithMailSystemAccess(async () => {
|
|
1489
|
+
const db = this.options.db;
|
|
1490
|
+
const messages = await MessageCollection.create({ db });
|
|
1491
|
+
const attachments = await AttachmentCollection.create({ db });
|
|
1492
|
+
const folders = await EmailFolderCollection.create({ db });
|
|
1493
|
+
for (const message of await messages.list({ where: { accountId } })) {
|
|
1494
|
+
if (message.id) for (const attachment of await attachments.list({ where: { messageId: message.id } })) await attachment.delete();
|
|
1495
|
+
await message.delete();
|
|
1496
|
+
}
|
|
1497
|
+
for (const folder of await folders.list({ where: { accountId } })) await folder.delete();
|
|
1498
|
+
});
|
|
1499
|
+
await account.removeCredentials();
|
|
1500
|
+
await account.delete();
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
2532
1503
|
async saveEndpoint(input) {
|
|
2533
1504
|
this.assert(MANAGE_MESSAGE_ROUTES_PERMISSION);
|
|
2534
1505
|
const provider = this.requireProvider(input.providerId);
|
|
@@ -2588,6 +1559,80 @@ var MessagingSettingsService = class {
|
|
|
2588
1559
|
return route;
|
|
2589
1560
|
});
|
|
2590
1561
|
}
|
|
1562
|
+
/** The user who owns accounts this principal creates; null when unknown. */
|
|
1563
|
+
get actingUserId() {
|
|
1564
|
+
return this.options.principal.userId ?? this.options.principal.id ?? null;
|
|
1565
|
+
}
|
|
1566
|
+
async loadAccount(accountId) {
|
|
1567
|
+
const account = await (await AccountCollection.create({ db: this.options.db })).get({ id: accountId });
|
|
1568
|
+
if (!account || account.tenantId !== this.options.tenantId) throw new Error("Messaging account was not found in this tenant.");
|
|
1569
|
+
return account;
|
|
1570
|
+
}
|
|
1571
|
+
/** An owned mailbox is managed by its owner only; unowned ones by admins. */
|
|
1572
|
+
assertMayManage(account) {
|
|
1573
|
+
if (account.ownerUserId && account.ownerUserId !== this.actingUserId) throw new Error("Only the mail account owner can change this account.");
|
|
1574
|
+
}
|
|
1575
|
+
async validateConnection(request) {
|
|
1576
|
+
try {
|
|
1577
|
+
if (this.options.validateMailbox) {
|
|
1578
|
+
await this.options.validateMailbox(request);
|
|
1579
|
+
return;
|
|
1580
|
+
}
|
|
1581
|
+
this.assertAllowedTarget(request.configuration);
|
|
1582
|
+
const create = request.provider.createEmailClient;
|
|
1583
|
+
if (!create) throw new Error("this provider cannot check a mailbox sign-in");
|
|
1584
|
+
const settings = {
|
|
1585
|
+
...request.configuration,
|
|
1586
|
+
...request.credentials
|
|
1587
|
+
};
|
|
1588
|
+
delete settings.email;
|
|
1589
|
+
const client = await create({
|
|
1590
|
+
type: request.provider.id,
|
|
1591
|
+
...settings
|
|
1592
|
+
});
|
|
1593
|
+
try {
|
|
1594
|
+
await client.connect();
|
|
1595
|
+
} finally {
|
|
1596
|
+
await client.disconnect().catch(() => void 0);
|
|
1597
|
+
}
|
|
1598
|
+
} catch {
|
|
1599
|
+
throw new Error("The mail server did not accept this connection.");
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
/**
|
|
1603
|
+
* Host and port allowlist for the built-in validator (SSRF guard).
|
|
1604
|
+
*
|
|
1605
|
+
* Names are checked, not resolved: an allowlisted name that resolves (or is
|
|
1606
|
+
* rebound) to a private address is the host's allowlist responsibility, so
|
|
1607
|
+
* list only names you control, or pass a `validateMailbox` that resolves and
|
|
1608
|
+
* pins the address it connects to.
|
|
1609
|
+
*/
|
|
1610
|
+
assertAllowedTarget(configuration) {
|
|
1611
|
+
let host = typeof configuration.host === "string" ? configuration.host : "";
|
|
1612
|
+
let port = typeof configuration.port === "number" ? configuration.port : void 0;
|
|
1613
|
+
if (!host && typeof configuration.endpoint === "string") {
|
|
1614
|
+
const url = new URL(configuration.endpoint);
|
|
1615
|
+
if (url.protocol !== "https:") throw new Error("refused");
|
|
1616
|
+
host = url.hostname;
|
|
1617
|
+
port ??= url.port ? Number(url.port) : 443;
|
|
1618
|
+
}
|
|
1619
|
+
host = host.toLowerCase().replace(/^\[|\]$/g, "");
|
|
1620
|
+
const allowed = this.options.allowedMailHosts ?? [];
|
|
1621
|
+
const ports = this.options.allowedMailPorts ?? [
|
|
1622
|
+
143,
|
|
1623
|
+
443,
|
|
1624
|
+
465,
|
|
1625
|
+
587,
|
|
1626
|
+
993,
|
|
1627
|
+
995
|
|
1628
|
+
];
|
|
1629
|
+
const listed = allowed.some((entry) => {
|
|
1630
|
+
const pattern = entry.toLowerCase();
|
|
1631
|
+
return pattern.startsWith("*.") ? host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1 : host === pattern;
|
|
1632
|
+
});
|
|
1633
|
+
if (!host || !listed || isPrivateMailHost(host)) throw new Error("refused");
|
|
1634
|
+
if (port !== void 0 && !ports.includes(port)) throw new Error("refused");
|
|
1635
|
+
}
|
|
2591
1636
|
assert(permission) {
|
|
2592
1637
|
assertMessagingPermission(this.options.principal, this.options.tenantId, permission);
|
|
2593
1638
|
}
|
|
@@ -2653,7 +1698,11 @@ var MessagingSettingsService = class {
|
|
|
2653
1698
|
channel: account.channelType,
|
|
2654
1699
|
configuration: account.getConfiguration(),
|
|
2655
1700
|
hasCredentials: account.hasCredentials,
|
|
2656
|
-
active: account.isActive
|
|
1701
|
+
active: account.isActive,
|
|
1702
|
+
ownerUserId: account.ownerUserId,
|
|
1703
|
+
label: account.label,
|
|
1704
|
+
connectionStatus: account.connectionStatus,
|
|
1705
|
+
statusMessage: account.statusMessage
|
|
2657
1706
|
};
|
|
2658
1707
|
}
|
|
2659
1708
|
endpointView(endpoint) {
|
|
@@ -2668,6 +1717,16 @@ var MessagingSettingsService = class {
|
|
|
2668
1717
|
};
|
|
2669
1718
|
}
|
|
2670
1719
|
};
|
|
1720
|
+
function isPrivateMailHost(host) {
|
|
1721
|
+
if (host === "localhost" || host.endsWith(".localhost")) return true;
|
|
1722
|
+
const v4 = host.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
|
|
1723
|
+
if (v4) {
|
|
1724
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
1725
|
+
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;
|
|
1726
|
+
}
|
|
1727
|
+
if (host.includes(":")) return host === "::" || host === "::1" || /^f[cd]/.test(host) || /^fe[89ab]/.test(host) || host.startsWith("::ffff:");
|
|
1728
|
+
return false;
|
|
1729
|
+
}
|
|
2671
1730
|
//#endregion
|
|
2672
1731
|
//#region src/services/NotificationOptOutService.ts
|
|
2673
1732
|
var NotificationOptOutDeniedError = class extends Error {
|
|
@@ -3216,6 +2275,10 @@ var NotificationOutboxService = class {
|
|
|
3216
2275
|
const address = recipient?.address?.trim();
|
|
3217
2276
|
if (!address || /[\s,;<>]/u.test(address) || !address.includes("@")) throw new NotificationOutboxDeniedError("recipient", "The host did not authorize an email recipient for this user.");
|
|
3218
2277
|
const accountId = await this.requireSenderAccount(tenantId);
|
|
2278
|
+
if (!await this.principalMaySend({
|
|
2279
|
+
tenantId,
|
|
2280
|
+
accountId
|
|
2281
|
+
})) throw new NotificationOutboxDeniedError("permission", "The principal lacks send access on the sender account.");
|
|
3219
2282
|
const suppressed = await this.isSuppressed({
|
|
3220
2283
|
tenantId,
|
|
3221
2284
|
...recipientUserId ? { recipientUserId } : {},
|
|
@@ -3319,7 +2382,17 @@ var NotificationOutboxService = class {
|
|
|
3319
2382
|
});
|
|
3320
2383
|
continue;
|
|
3321
2384
|
}
|
|
3322
|
-
|
|
2385
|
+
if (!await this.principalMaySend(candidate)) {
|
|
2386
|
+
const lastError = "Blocked: mail access denied for scope send";
|
|
2387
|
+
if (candidate.lastError !== lastError) await withTenant({ tenantId: candidate.tenantId }, () => candidate.transition({ lastError }));
|
|
2388
|
+
report.outcomes.push({
|
|
2389
|
+
deliveryId: candidate.id,
|
|
2390
|
+
tenantId: candidate.tenantId,
|
|
2391
|
+
outcome: "blocked"
|
|
2392
|
+
});
|
|
2393
|
+
continue;
|
|
2394
|
+
}
|
|
2395
|
+
const outcome = await withTenant({ tenantId: candidate.tenantId }, () => runWithMailSystemAccess(() => this.dispatchOne(candidate)));
|
|
3323
2396
|
if (!outcome) continue;
|
|
3324
2397
|
report.leased += 1;
|
|
3325
2398
|
report.outcomes.push({
|
|
@@ -3355,6 +2428,36 @@ var NotificationOutboxService = class {
|
|
|
3355
2428
|
this.authorize(tenantId);
|
|
3356
2429
|
if (!UUID_PATTERN$1.test(input.deliveryId ?? "")) return false;
|
|
3357
2430
|
return withTenant({ tenantId }, async () => {
|
|
2431
|
+
if (this.options.principal) {
|
|
2432
|
+
const delivery = (await (await this.collection()).list({
|
|
2433
|
+
where: {
|
|
2434
|
+
tenantId,
|
|
2435
|
+
id: input.deliveryId
|
|
2436
|
+
},
|
|
2437
|
+
limit: 1
|
|
2438
|
+
}))[0];
|
|
2439
|
+
if (!delivery || !await this.principalMaySend(delivery)) return false;
|
|
2440
|
+
}
|
|
2441
|
+
return runWithMailSystemAccess(() => this.reconcileImpl(tenantId, input));
|
|
2442
|
+
});
|
|
2443
|
+
}
|
|
2444
|
+
/** True without a principal (trusted worker); else needs `send` on the account. */
|
|
2445
|
+
async principalMaySend(delivery) {
|
|
2446
|
+
const principal = this.options.principal;
|
|
2447
|
+
if (!principal) return true;
|
|
2448
|
+
const tenantId = delivery.tenantId;
|
|
2449
|
+
const userId = principal.userId ?? principal.id;
|
|
2450
|
+
if (!delivery.accountId) return false;
|
|
2451
|
+
const account = await withTenant({ tenantId }, () => runWithMailSystemAccess(async () => (await AccountCollection.create({ db: this.options.db })).get({ id: delivery.accountId })));
|
|
2452
|
+
if (!account || account.tenantId !== tenantId) return false;
|
|
2453
|
+
return (await withTenant({ tenantId }, () => decideMailAccess(account, "send", userId ? {
|
|
2454
|
+
id: principal.id ?? userId,
|
|
2455
|
+
tenantId,
|
|
2456
|
+
userId
|
|
2457
|
+
} : null))).allowed;
|
|
2458
|
+
}
|
|
2459
|
+
async reconcileImpl(tenantId, input) {
|
|
2460
|
+
{
|
|
3358
2461
|
const delivery = (await (await this.collection()).list({
|
|
3359
2462
|
where: {
|
|
3360
2463
|
tenantId,
|
|
@@ -3389,7 +2492,7 @@ var NotificationOutboxService = class {
|
|
|
3389
2492
|
}
|
|
3390
2493
|
default: throw new Error(`Unknown reconcile outcome '${input.outcome}'.`);
|
|
3391
2494
|
}
|
|
3392
|
-
}
|
|
2495
|
+
}
|
|
3393
2496
|
}
|
|
3394
2497
|
async requireSenderAccount(tenantId) {
|
|
3395
2498
|
const accountId = (await this.options.resolveSenderAccountId({ tenantId }))?.trim();
|
|
@@ -4031,7 +3134,8 @@ var MailboxRecipe = class extends SmrtRecipe {
|
|
|
4031
3134
|
options: [
|
|
4032
3135
|
"imap",
|
|
4033
3136
|
"pop3",
|
|
4034
|
-
"gmail"
|
|
3137
|
+
"gmail",
|
|
3138
|
+
"jmap"
|
|
4035
3139
|
],
|
|
4036
3140
|
required: true
|
|
4037
3141
|
}, {
|
|
@@ -4271,7 +3375,8 @@ var SlackRecipe = class extends SmrtRecipe {
|
|
|
4271
3375
|
//#region src/index.ts
|
|
4272
3376
|
ensureBuiltinMessagingProvidersRegistered();
|
|
4273
3377
|
ensureMessagingPermissionsRegistered();
|
|
3378
|
+
ensureMailAccessEnforcementRegistered();
|
|
4274
3379
|
//#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,
|
|
3380
|
+
export { Account, AccountCollection, Attachment, AttachmentCollection, Blacklist, BlacklistCollection, CHANGE_FEED_PROVIDERS, Email, EmailAccount, EmailAccountCollection, EmailAttachment, EmailAttachmentCollection, EmailCollection, EmailFolder, EmailFolderCollection, EmailSender, MAIL_ACCOUNT_RESOURCE_TYPE, MAIL_SCOPES, MAIL_SYNC_QUEUE, 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, enqueueDueMailSyncs, enqueueMailSync, ensureBuiltinMessagingProvidersRegistered, ensureMessagingPermissionsRegistered, getMessagingProvider, isMailScope, isValidNotificationOptOutScope, listMessagingProviders, mailScopePermission, mailSyncDedupeKey, messageSendTransport, messagingPrincipalFromPermissions, migrateNotificationProfileRecipients, notificationDeliveryCorrelationId, notificationDeliveryMessageId, optOutSuppression, planNotificationProfileRecipients, profileNotificationPolicy, registerMessagingProvider, resetMailAccess, runWithMailSystemAccess };
|
|
4276
3381
|
|
|
4277
3382
|
//# sourceMappingURL=index.js.map
|