coremail-desktop-mcp 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Coremail Mail MCP contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/PRIVACY.md ADDED
@@ -0,0 +1,14 @@
1
+ # Privacy
2
+
3
+ This package runs as a local stdio MCP process. It connects only to the mail
4
+ servers configured by the user and, for the optional Windows directory feature,
5
+ to the Coremail desktop loopback SDK on the same computer.
6
+
7
+ Depending on the tools invoked, the MCP client may receive message metadata,
8
+ message bodies, recipient addresses, attachment metadata, contact details, and
9
+ verified organization-directory fields. The user should review the MCP host's
10
+ own model and data-processing policy before enabling the connector.
11
+
12
+ The package does not include telemetry. Verified job-title data is cached only
13
+ at the local path selected by the user. Credentials, mail, contacts, logs, and
14
+ cache files must never be included in a public release or support bundle.
package/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # Coremail Desktop MCP (Unofficial)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An unofficial, local-first MCP server for Coremail-compatible mailboxes. It
4
+ uses standard IMAP/SMTP for mail and can optionally read the organization
5
+ directory exposed by a signed-in Coremail Windows desktop client.
6
+
7
+ It is not affiliated with or endorsed by Coremail. No Coremail binaries,
8
+ logos, credentials, company directories, or customer data are included.
9
+
10
+ ## Features
11
+
12
+ - Search and read IMAP mail
13
+ - MIME-preserving reply, reply-all, and inline/attached forwarding
14
+ - Original and additional attachments
15
+ - Preview-before-send workflow with explicit confirmation
16
+ - Sent-copy handling through the configured server
17
+ - Original MIME/HTML PDF export
18
+ - Local CSV/JSON/vCard contact search
19
+ - Optional Windows Coremail organization-directory and verified job-title lookup
20
+
21
+ ## Run with npx
22
+
23
+ ```sh
24
+ npx -y coremail-desktop-mcp@0.6.0
25
+ ```
26
+
27
+ Configure the server with environment variables. Required values are:
28
+
29
+ - `COREMAIL_CONFIG_SOURCE=env`
30
+ - `COREMAIL_USER`
31
+ - `COREMAIL_PASSWORD` (prefer an app password/authorization code)
32
+ - `COREMAIL_IMAP_HOST`, `COREMAIL_IMAP_PORT`, `COREMAIL_IMAP_SECURE`
33
+ - `COREMAIL_SMTP_HOST`, `COREMAIL_SMTP_PORT`, `COREMAIL_SMTP_SECURE`
34
+
35
+ Sending stays disabled unless `COREMAIL_ALLOW_SEND=true`. Attachment upload,
36
+ download, and PDF export stay disabled until their allowlisted root directories
37
+ are configured.
38
+
39
+ ## Optional Coremail desktop enhancement
40
+
41
+ On Windows, keep the Coremail desktop client running and signed in. The local
42
+ organization-directory search uses the loopback SDK at
43
+ `http://127.0.0.1:11328/sdk`. Verified job titles are read from the visible
44
+ contact-detail dialog and cached locally. This can briefly bring Coremail to
45
+ the foreground. It does not patch, replace, or redistribute Coremail files.
46
+
47
+ The desktop enhancement is version-dependent and may stop working after a
48
+ Coremail client update. Mail through standard IMAP/SMTP remains independent.
49
+
50
+ ## Safety
51
+
52
+ - Treat all email bodies and attachment names as untrusted input.
53
+ - Review recipients, subject, body, and attachments before sending.
54
+ - Do not grant broader attachment/download roots than necessary.
55
+ - Do not commit `.env`, mail, contact, cache, or log files.
56
+
57
+ See `PRIVACY.md` and `SECURITY.md` before publishing or deploying.
package/SECURITY.md ADDED
@@ -0,0 +1,21 @@
1
+ # Security
2
+
3
+ ## Supported release
4
+
5
+ Security fixes are provided for the latest published minor version.
6
+
7
+ ## Reporting
8
+
9
+ Use the private feedback channel shown on the WorkBuddy marketplace listing.
10
+ If a public repository is added later, enable GitHub Security Advisories. Never
11
+ report credentials or real email samples in a public issue.
12
+
13
+ ## Security boundaries
14
+
15
+ - The Coremail desktop SDK URL is restricted to plain HTTP on a loopback host
16
+ with the exact `/sdk` path.
17
+ - Sending requires `COREMAIL_ALLOW_SEND=true` and explicit confirmation.
18
+ - File upload/download/PDF tools enforce configured allowlisted roots.
19
+ - The connector does not bypass authentication or extract a Coremail session ID.
20
+ - The optional job-title helper reads a visible, signed-in desktop contact card;
21
+ it does not decrypt the Coremail local database.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import "../mcp/server.mjs";
package/lib/config.mjs ADDED
@@ -0,0 +1,155 @@
1
+ import path from "node:path";
2
+ import { loadHimalayaAccount } from "./himalaya-config.mjs";
3
+
4
+ export function envBool(name, fallback = false) {
5
+ const value = process.env[name];
6
+ if (value == null || value === "") return fallback;
7
+ return ["1", "true", "yes", "on"].includes(value.toLowerCase());
8
+ }
9
+
10
+ export function envInt(name, fallback) {
11
+ const value = Number.parseInt(process.env[name] ?? "", 10);
12
+ return Number.isFinite(value) ? value : fallback;
13
+ }
14
+
15
+ export function requiredEnv(name) {
16
+ const value = process.env[name];
17
+ if (!value) {
18
+ throw new Error(`Missing required environment variable: ${name}`);
19
+ }
20
+ return value;
21
+ }
22
+
23
+ export function envPathList(name) {
24
+ const value = process.env[name];
25
+ if (!value) return [];
26
+ return value
27
+ .split(path.delimiter)
28
+ .map((item) => item.trim())
29
+ .filter(Boolean)
30
+ .map((item) => path.resolve(item));
31
+ }
32
+
33
+ export function configSource() {
34
+ const source = (process.env.COREMAIL_CONFIG_SOURCE || "env").trim().toLowerCase();
35
+ if (!["env", "himalaya"].includes(source)) {
36
+ throw new Error("COREMAIL_CONFIG_SOURCE must be 'env' or 'himalaya'.");
37
+ }
38
+ return source;
39
+ }
40
+
41
+ function encryptionOptions(encryption, protocol) {
42
+ const normalized = String(encryption || "tls").toLowerCase().replace(/_/g, "-");
43
+ const startTls = ["starttls", "start-tls"].includes(normalized);
44
+ const directTls = ["tls", "ssl", "ssl-tls", "tls-wrapper"].includes(normalized);
45
+ if (!startTls && !directTls && !["none", "plain"].includes(normalized)) {
46
+ throw new Error(`Unsupported ${protocol.toUpperCase()} encryption type in Himalaya configuration: ${encryption}`);
47
+ }
48
+ if (protocol === "imap") return { secure: directTls, ...(startTls ? { doSTARTTLS: true } : {}) };
49
+ return { secure: directTls, ...(startTls ? { requireTLS: true } : {}) };
50
+ }
51
+
52
+ export function imapConfig() {
53
+ if (configSource() === "himalaya") {
54
+ const account = loadHimalayaAccount();
55
+ return {
56
+ host: account.imap.host,
57
+ port: account.imap.port,
58
+ ...encryptionOptions(account.imap.encryption, "imap"),
59
+ auth: { user: account.imap.login, pass: account.imap.password },
60
+ tls: { rejectUnauthorized: envBool("COREMAIL_TLS_REJECT_UNAUTHORIZED", true) },
61
+ logger: false
62
+ };
63
+ }
64
+ return {
65
+ host: requiredEnv("COREMAIL_IMAP_HOST"),
66
+ port: envInt("COREMAIL_IMAP_PORT", 993),
67
+ secure: envBool("COREMAIL_IMAP_SECURE", true),
68
+ auth: {
69
+ user: requiredEnv("COREMAIL_USER"),
70
+ pass: requiredEnv("COREMAIL_PASSWORD")
71
+ },
72
+ tls: {
73
+ rejectUnauthorized: envBool("COREMAIL_TLS_REJECT_UNAUTHORIZED", true)
74
+ },
75
+ logger: false
76
+ };
77
+ }
78
+
79
+ export function smtpConfig() {
80
+ if (configSource() === "himalaya") {
81
+ const account = loadHimalayaAccount();
82
+ return {
83
+ host: account.smtp.host,
84
+ port: account.smtp.port,
85
+ ...encryptionOptions(account.smtp.encryption, "smtp"),
86
+ auth: { user: account.smtp.login, pass: account.smtp.password },
87
+ tls: { rejectUnauthorized: envBool("COREMAIL_TLS_REJECT_UNAUTHORIZED", true) }
88
+ };
89
+ }
90
+ return {
91
+ host: requiredEnv("COREMAIL_SMTP_HOST"),
92
+ port: envInt("COREMAIL_SMTP_PORT", 465),
93
+ secure: envBool("COREMAIL_SMTP_SECURE", true),
94
+ auth: {
95
+ user: requiredEnv("COREMAIL_USER"),
96
+ pass: requiredEnv("COREMAIL_PASSWORD")
97
+ },
98
+ tls: {
99
+ rejectUnauthorized: envBool("COREMAIL_TLS_REJECT_UNAUTHORIZED", true)
100
+ }
101
+ };
102
+ }
103
+
104
+ export function mailFrom() {
105
+ if (process.env.COREMAIL_FROM) return process.env.COREMAIL_FROM;
106
+ if (configSource() === "himalaya") {
107
+ const account = loadHimalayaAccount();
108
+ return account.displayName ? `${account.displayName} <${account.email}>` : account.email;
109
+ }
110
+ return requiredEnv("COREMAIL_USER");
111
+ }
112
+
113
+ function extractEmail(value) {
114
+ const text = String(value || "").trim();
115
+ const bracketed = text.match(/<([^<>\s]+@[^<>\s]+)>/);
116
+ if (bracketed) return bracketed[1];
117
+ const plain = text.match(/[^\s<>]+@[^\s<>]+/);
118
+ return plain?.[0] || null;
119
+ }
120
+
121
+ export function mailIdentityAddresses() {
122
+ const values = [];
123
+ if (configSource() === "himalaya") {
124
+ const account = loadHimalayaAccount();
125
+ values.push(account.email, account.imap.login, account.smtp.login);
126
+ } else {
127
+ values.push(process.env.COREMAIL_USER);
128
+ }
129
+ values.push(extractEmail(process.env.COREMAIL_FROM));
130
+ return [...new Set(values.filter(Boolean).map((value) => String(value).trim().toLowerCase()))];
131
+ }
132
+
133
+ export function configuredSentMailbox() {
134
+ if (process.env.COREMAIL_SENT_MAILBOX) return process.env.COREMAIL_SENT_MAILBOX;
135
+ if (configSource() === "himalaya") return loadHimalayaAccount().sentMailbox;
136
+ return null;
137
+ }
138
+
139
+ export function mailConfigSummary() {
140
+ const source = configSource();
141
+ if (source === "himalaya") {
142
+ const account = loadHimalayaAccount();
143
+ return { source, account: account.accountName, sentMailboxConfigured: Boolean(configuredSentMailbox()) };
144
+ }
145
+ return { source, account: null, sentMailboxConfigured: Boolean(configuredSentMailbox()) };
146
+ }
147
+
148
+ export function messageLimits() {
149
+ return {
150
+ maxBytes: envInt("COREMAIL_MAX_MESSAGE_BYTES", 25 * 1024 * 1024),
151
+ maxAttachments: envInt("COREMAIL_MAX_ATTACHMENTS", 30),
152
+ preparedTtlMs: envInt("COREMAIL_PREPARED_TTL_SECONDS", 1800) * 1000,
153
+ maxPrepared: envInt("COREMAIL_MAX_PREPARED", 20)
154
+ };
155
+ }
@@ -0,0 +1,119 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+
4
+ function parseCsvRows(text) {
5
+ const rows = [];
6
+ let row = [];
7
+ let field = "";
8
+ let quoted = false;
9
+ for (let index = 0; index < text.length; index += 1) {
10
+ const char = text[index];
11
+ if (quoted) {
12
+ if (char === '"' && text[index + 1] === '"') {
13
+ field += '"';
14
+ index += 1;
15
+ } else if (char === '"') {
16
+ quoted = false;
17
+ } else {
18
+ field += char;
19
+ }
20
+ } else if (char === '"') {
21
+ quoted = true;
22
+ } else if (char === ",") {
23
+ row.push(field);
24
+ field = "";
25
+ } else if (char === "\n") {
26
+ row.push(field.replace(/\r$/, ""));
27
+ if (row.some((value) => value !== "")) rows.push(row);
28
+ row = [];
29
+ field = "";
30
+ } else {
31
+ field += char;
32
+ }
33
+ }
34
+ row.push(field.replace(/\r$/, ""));
35
+ if (row.some((value) => value !== "")) rows.push(row);
36
+ return rows;
37
+ }
38
+
39
+ function normalizeContact(contact) {
40
+ const aliases = Array.isArray(contact.aliases)
41
+ ? contact.aliases
42
+ : String(contact.aliases || contact.alias || "").split(/[;,,]/);
43
+ return {
44
+ name: String(contact.name || contact.fullName || contact.fn || contact["姓名"] || contact["名称"] || "").trim(),
45
+ email: String(contact.email || contact.mail || contact["邮箱"] || contact["电子邮箱"] || "").trim(),
46
+ department: String(contact.department || contact.org || contact.organization || contact["部门"] || contact["组织"] || "").trim(),
47
+ title: String(contact.title || contact.jobTitle || contact["职务"] || contact["职位"] || "").trim(),
48
+ phone: String(contact.phone || contact.mobile || contact.tel || contact["手机"] || contact["电话"] || "").trim(),
49
+ aliases: aliases.map((value) => String(value).trim()).filter(Boolean)
50
+ };
51
+ }
52
+
53
+ export function parseCsvContacts(text) {
54
+ const rows = parseCsvRows(text.replace(/^\uFEFF/, ""));
55
+ if (!rows.length) return [];
56
+ const headers = rows[0].map((value) => value.trim());
57
+ return rows.slice(1).map((row) => {
58
+ const item = Object.fromEntries(headers.map((header, index) => [header, row[index] ?? ""]));
59
+ return normalizeContact(item);
60
+ }).filter((contact) => contact.name || contact.email);
61
+ }
62
+
63
+ export function parseVcardContacts(text) {
64
+ const unfolded = text.replace(/\r?\n[ \t]/g, "");
65
+ const cards = unfolded.match(/BEGIN:VCARD[\s\S]*?END:VCARD/gi) || [];
66
+ return cards.map((card) => {
67
+ const values = {};
68
+ for (const line of card.split(/\r?\n/)) {
69
+ const separator = line.indexOf(":");
70
+ if (separator < 0) continue;
71
+ const rawKey = line.slice(0, separator);
72
+ const key = rawKey.split(";")[0].toUpperCase();
73
+ const value = line.slice(separator + 1).replaceAll("\\,", ",").replaceAll("\\;", ";");
74
+ if (key === "FN") values.name = value;
75
+ if (key === "EMAIL" && !values.email) values.email = value;
76
+ if (key === "ORG") values.department = value.replaceAll(";", " / ");
77
+ if (key === "TITLE") values.title = value;
78
+ if (key === "TEL" && !values.phone) values.phone = value;
79
+ if (key === "NICKNAME") values.aliases = value;
80
+ }
81
+ return normalizeContact(values);
82
+ }).filter((contact) => contact.name || contact.email);
83
+ }
84
+
85
+ export async function loadContacts(filePath) {
86
+ if (!filePath) throw new Error("COREMAIL_CONTACTS_FILE is not configured.");
87
+ const resolved = path.resolve(filePath);
88
+ const content = await fs.readFile(resolved, "utf8");
89
+ const extension = path.extname(resolved).toLowerCase();
90
+ if (extension === ".json") {
91
+ const parsed = JSON.parse(content);
92
+ const items = Array.isArray(parsed) ? parsed : parsed.contacts;
93
+ if (!Array.isArray(items)) throw new Error("Contacts JSON must be an array or contain a contacts array.");
94
+ return items.map(normalizeContact).filter((contact) => contact.name || contact.email);
95
+ }
96
+ if (extension === ".vcf" || extension === ".vcard") return parseVcardContacts(content);
97
+ return parseCsvContacts(content);
98
+ }
99
+
100
+ export function searchContacts(contacts, query, limit = 20) {
101
+ const needle = String(query || "").trim().toLocaleLowerCase();
102
+ if (!needle) return [];
103
+ return contacts
104
+ .map((contact) => {
105
+ const fields = [contact.name, contact.email, contact.department, contact.title, contact.phone, ...(contact.aliases || [])]
106
+ .map((value) => String(value || "").toLocaleLowerCase());
107
+ let score = 0;
108
+ for (const value of fields) {
109
+ if (value === needle) score = Math.max(score, 100);
110
+ else if (value.startsWith(needle)) score = Math.max(score, 70);
111
+ else if (value.includes(needle)) score = Math.max(score, 40);
112
+ }
113
+ return { contact, score };
114
+ })
115
+ .filter((item) => item.score > 0)
116
+ .sort((a, b) => b.score - a.score || a.contact.name.localeCompare(b.contact.name, "zh-CN"))
117
+ .slice(0, limit)
118
+ .map((item) => item.contact);
119
+ }
@@ -0,0 +1,163 @@
1
+ import path from "node:path";
2
+
3
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
4
+
5
+ export function validateSdkUrl(value) {
6
+ const url = new URL(value || "http://127.0.0.1:11328/sdk");
7
+ if (url.protocol !== "http:" || !LOOPBACK_HOSTS.has(url.hostname)) {
8
+ throw new Error("Coremail SDK URL must use plain HTTP on a loopback host.");
9
+ }
10
+ if (url.pathname !== "/sdk") {
11
+ throw new Error("Coremail SDK URL path must be /sdk.");
12
+ }
13
+ url.search = "";
14
+ url.hash = "";
15
+ return url.toString();
16
+ }
17
+
18
+ export async function callCoremailSdk(func, data, options = {}) {
19
+ const baseUrl = validateSdkUrl(options.baseUrl || "http://127.0.0.1:11328/sdk");
20
+ const fetchImpl = options.fetchImpl || globalThis.fetch;
21
+ const timeoutMs = options.timeoutMs || 15000;
22
+ if (typeof fetchImpl !== "function") throw new Error("fetch is not available.");
23
+
24
+ const url = new URL(baseUrl);
25
+ url.searchParams.set("func", func);
26
+ const controller = new AbortController();
27
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
28
+ try {
29
+ const response = await fetchImpl(url, {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json" },
32
+ body: data === undefined ? undefined : JSON.stringify(data),
33
+ signal: controller.signal
34
+ });
35
+ if (!response.ok) throw new Error(`Coremail SDK HTTP ${response.status}.`);
36
+ const payload = await response.json();
37
+ if (!payload || payload.code !== 0) {
38
+ const detail = payload?.msg ? `: ${String(payload.msg).slice(0, 300)}` : "";
39
+ throw new Error(`Coremail SDK ${func} failed (code ${payload?.code ?? "unknown"})${detail}`);
40
+ }
41
+ return payload.var;
42
+ } finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+
47
+ export function selectSharedAccount(accounts, configuredAccount) {
48
+ const wanted = String(configuredAccount || "").trim().toLowerCase();
49
+ if (!wanted) throw new Error("COREMAIL_SHARED_ACCOUNT is required.");
50
+ const account = (Array.isArray(accounts) ? accounts : []).find(
51
+ (item) => String(item?.AccountName || "").trim().toLowerCase() === wanted
52
+ );
53
+ if (!account) throw new Error(`Configured shared mailbox is not available: ${configuredAccount}`);
54
+ if (account.SharedAccount !== true) {
55
+ throw new Error(`Configured mailbox is not marked as a shared account: ${configuredAccount}`);
56
+ }
57
+ return {
58
+ accountId: account.AccountID,
59
+ accountName: account.AccountName,
60
+ displayName: account.DisplayName || account.AccountName,
61
+ protocolType: account.ProtocolType || null,
62
+ sharedAccount: true,
63
+ offline: Boolean(account.Offline)
64
+ };
65
+ }
66
+
67
+ function folderSpecialUse(type) {
68
+ return ({ 1: "inbox", 2: "drafts", 3: "sent", 4: "trash", 5: "junk" })[Number(type)] || null;
69
+ }
70
+
71
+ export function flattenFolders(folders, parentPath = "") {
72
+ const result = [];
73
+ for (const folder of Array.isArray(folders) ? folders : []) {
74
+ const name = String(folder?.Name || "");
75
+ const path = parentPath && name ? `${parentPath}/${name}` : name || parentPath;
76
+ result.push({
77
+ folderId: folder?.FID,
78
+ name,
79
+ path,
80
+ parentId: folder?.ParentID ?? null,
81
+ type: folder?.Type ?? null,
82
+ specialUse: folderSpecialUse(folder?.Type),
83
+ attributes: folder?.Atts ?? null
84
+ });
85
+ if (Array.isArray(folder?.children) && folder.children.length) {
86
+ result.push(...flattenFolders(folder.children, path));
87
+ }
88
+ }
89
+ return result;
90
+ }
91
+
92
+ export function epochToIso(value) {
93
+ if (value === undefined || value === null || value === "") return null;
94
+ const numeric = Number(value);
95
+ if (!Number.isFinite(numeric)) return null;
96
+ const milliseconds = numeric > 10_000_000_000 ? numeric : numeric * 1000;
97
+ const date = new Date(milliseconds);
98
+ return Number.isNaN(date.getTime()) ? null : date.toISOString();
99
+ }
100
+
101
+ export function toEpochSeconds(value) {
102
+ if (value === undefined || value === null || value === "") return undefined;
103
+ const date = new Date(value);
104
+ if (Number.isNaN(date.getTime())) throw new Error(`Invalid date/time: ${value}`);
105
+ return Math.floor(date.getTime() / 1000);
106
+ }
107
+
108
+ export function compactMessage(mail) {
109
+ const flags = BigInt(mail?.Flags ?? 0);
110
+ return {
111
+ mid: mail?.ID ?? mail?.MID ?? null,
112
+ folderId: mail?.FID ?? null,
113
+ receivedAt: epochToIso(mail?.RecTime),
114
+ sentAt: epochToIso(mail?.MailTime ?? mail?.Date),
115
+ subject: mail?.Subject || "",
116
+ from: mail?.From || mail?.Sender || "",
117
+ to: mail?.To || mail?.Rcpt || "",
118
+ cc: mail?.Cc || "",
119
+ unread: mail?.Unread !== undefined ? Boolean(mail.Unread) : (flags & 1n) === 0n,
120
+ hasAttachment: mail?.HasAttach !== undefined ? Boolean(mail.HasAttach) : (flags & 128n) !== 0n,
121
+ size: mail?.Size ?? null,
122
+ summary: mail?.Summary || ""
123
+ };
124
+ }
125
+
126
+ export function normalizeMailResult(payload) {
127
+ const mails = Array.isArray(payload?.Mails) ? payload.Mails.map(compactMessage) : [];
128
+ return {
129
+ total: Number(payload?.Total ?? mails.length),
130
+ returned: mails.length,
131
+ messages: mails
132
+ };
133
+ }
134
+
135
+ export function normalizeExportedAttachments(exported) {
136
+ const items = Array.isArray(exported?.mailAttachments) ? exported.mailAttachments : [];
137
+ return items.map((item, index) => {
138
+ const object = item && typeof item === "object" ? item : {};
139
+ const sourcePath = typeof item === "string"
140
+ ? item
141
+ : object.path || object.filePath || object.localPath || object.tempPath || "";
142
+ const fallbackName = sourcePath ? path.basename(sourcePath) : `attachment-${index + 1}.bin`;
143
+ const filename = String(object.name || object.filename || fallbackName).trim() || fallbackName;
144
+ const numericSize = Number(object.size);
145
+ return {
146
+ index,
147
+ filename,
148
+ sourcePath: String(sourcePath || ""),
149
+ size: Number.isFinite(numericSize) && numericSize >= 0 ? numericSize : null,
150
+ contentType: object.contentType || object.mimeType || null
151
+ };
152
+ });
153
+ }
154
+
155
+ export function buildTimeRange(since, before) {
156
+ const begin = toEpochSeconds(since);
157
+ const end = toEpochSeconds(before);
158
+ if (begin === undefined && end === undefined) return undefined;
159
+ if (begin !== undefined && end !== undefined && begin >= end) {
160
+ throw new Error("since must be earlier than before.");
161
+ }
162
+ return { Begin: begin ?? 0, End: end ?? 2147483647 };
163
+ }
@@ -0,0 +1,72 @@
1
+ const PERIODS = new Set([
2
+ "today",
3
+ "yesterday",
4
+ "day-before-yesterday",
5
+ "this-week",
6
+ "last-week",
7
+ "recent-days"
8
+ ]);
9
+
10
+ function startOfLocalDay(value) {
11
+ return new Date(value.getFullYear(), value.getMonth(), value.getDate());
12
+ }
13
+
14
+ function addDays(value, days) {
15
+ const result = new Date(value);
16
+ result.setDate(result.getDate() + days);
17
+ return result;
18
+ }
19
+
20
+ function formatLocalDate(value) {
21
+ const year = value.getFullYear();
22
+ const month = String(value.getMonth() + 1).padStart(2, "0");
23
+ const day = String(value.getDate()).padStart(2, "0");
24
+ return `${year}-${month}-${day}`;
25
+ }
26
+
27
+ export function resolveRelativeDateRange(period, days = 1, now = new Date()) {
28
+ if (!PERIODS.has(period)) throw new Error(`Unsupported relative date period: ${period}`);
29
+ if (!Number.isInteger(days) || days < 1 || days > 365) {
30
+ throw new Error("days must be an integer between 1 and 365");
31
+ }
32
+
33
+ const today = startOfLocalDay(now);
34
+ const mondayOffset = (today.getDay() + 6) % 7;
35
+ const thisMonday = addDays(today, -mondayOffset);
36
+ let since;
37
+ let before;
38
+
39
+ switch (period) {
40
+ case "yesterday":
41
+ since = addDays(today, -1);
42
+ before = today;
43
+ break;
44
+ case "day-before-yesterday":
45
+ since = addDays(today, -2);
46
+ before = addDays(today, -1);
47
+ break;
48
+ case "this-week":
49
+ since = thisMonday;
50
+ before = addDays(today, 1);
51
+ break;
52
+ case "last-week":
53
+ since = addDays(thisMonday, -7);
54
+ before = thisMonday;
55
+ break;
56
+ case "recent-days":
57
+ since = addDays(today, -(days - 1));
58
+ before = addDays(today, 1);
59
+ break;
60
+ default:
61
+ since = today;
62
+ before = addDays(today, 1);
63
+ }
64
+
65
+ return {
66
+ observedAt: now.toISOString(),
67
+ localDate: formatLocalDate(today),
68
+ period,
69
+ since: formatLocalDate(since),
70
+ before: formatLocalDate(before)
71
+ };
72
+ }