@pellux/goodvibes-tui 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +5 -3
  2. package/README.md +1 -1
  3. package/docs/foundation-artifacts/operator-contract.json +2419 -1040
  4. package/package.json +2 -2
  5. package/src/daemon/{calendar → handlers/calendar}/caldav-client.ts +28 -24
  6. package/src/daemon/handlers/calendar/index.ts +316 -0
  7. package/src/daemon/handlers/context.ts +29 -0
  8. package/src/daemon/handlers/contracts.ts +77 -0
  9. package/src/daemon/{channels → handlers}/drafts/draft-store.ts +114 -50
  10. package/src/daemon/handlers/drafts/index.ts +17 -0
  11. package/src/daemon/handlers/drafts/register.ts +331 -0
  12. package/src/daemon/handlers/email/config.ts +164 -0
  13. package/src/daemon/handlers/email/index.ts +43 -0
  14. package/src/daemon/handlers/email/read-handlers.ts +80 -0
  15. package/src/daemon/handlers/email/runtime.ts +140 -0
  16. package/src/daemon/handlers/email/validation.ts +147 -0
  17. package/src/daemon/handlers/email/write-handlers.ts +133 -0
  18. package/src/daemon/handlers/errors.ts +18 -0
  19. package/src/daemon/{channels → handlers}/inbox/cursor-store.ts +58 -66
  20. package/src/daemon/handlers/inbox/index.ts +210 -0
  21. package/src/daemon/{channels → handlers}/inbox/mapping.ts +8 -6
  22. package/src/daemon/{channels → handlers}/inbox/poller.ts +4 -4
  23. package/src/daemon/{channels → handlers}/inbox/provider-adapter.ts +14 -10
  24. package/src/daemon/{channels → handlers}/inbox/providers/discord.ts +8 -10
  25. package/src/daemon/{channels → handlers}/inbox/providers/imap-client.ts +1 -1
  26. package/src/daemon/{channels → handlers}/inbox/providers/route-util.ts +2 -2
  27. package/src/daemon/{channels → handlers}/inbox/providers/slack.ts +9 -11
  28. package/src/daemon/handlers/index.ts +107 -0
  29. package/src/daemon/handlers/register.ts +161 -0
  30. package/src/daemon/{remote → handlers/remote}/backends/cloud-terminal.ts +8 -3
  31. package/src/daemon/{remote → handlers/remote}/backends/docker.ts +2 -3
  32. package/src/daemon/handlers/remote/backends/index.ts +40 -0
  33. package/src/daemon/{remote → handlers/remote}/backends/process-runner.ts +16 -40
  34. package/src/daemon/{remote → handlers/remote}/backends/ssh.ts +8 -3
  35. package/src/daemon/{remote → handlers/remote}/backends/types.ts +29 -3
  36. package/src/daemon/{remote → handlers/remote}/dispatcher.ts +27 -6
  37. package/src/daemon/handlers/remote/index.ts +119 -0
  38. package/src/daemon/{remote → handlers/remote}/peer-registry.ts +47 -11
  39. package/src/daemon/handlers/remote/service.ts +191 -0
  40. package/src/daemon/{channels → handlers}/routing/inbox-bridge.ts +33 -20
  41. package/src/daemon/handlers/routing/index.ts +261 -0
  42. package/src/daemon/{channels → handlers}/routing/route-store.ts +57 -16
  43. package/src/daemon/{channels → handlers}/routing/routing-resolver.ts +1 -1
  44. package/src/daemon/{operator → handlers}/sqlite-store.ts +5 -5
  45. package/src/daemon/handlers/triage/index.ts +57 -0
  46. package/src/daemon/handlers/triage/integration.ts +212 -0
  47. package/src/daemon/{triage → handlers/triage}/pipeline.ts +58 -70
  48. package/src/daemon/{triage → handlers/triage}/scorer.ts +21 -21
  49. package/src/daemon/handlers/triage/tagger/discord.ts +186 -0
  50. package/src/daemon/handlers/triage/tagger/imap.ts +383 -0
  51. package/src/daemon/handlers/triage/tagger/index.ts +184 -0
  52. package/src/daemon/handlers/triage/tagger/shared.ts +70 -0
  53. package/src/daemon/handlers/triage/tagger/slack.ts +69 -0
  54. package/src/daemon/handlers/triage/types.ts +50 -0
  55. package/src/runtime/services.ts +48 -35
  56. package/src/version.ts +1 -1
  57. package/src/daemon/calendar/index.ts +0 -52
  58. package/src/daemon/calendar/register.ts +0 -527
  59. package/src/daemon/channels/drafts/index.ts +0 -22
  60. package/src/daemon/channels/drafts/register.ts +0 -449
  61. package/src/daemon/channels/inbox/index.ts +0 -58
  62. package/src/daemon/channels/inbox/register.ts +0 -247
  63. package/src/daemon/channels/routing/index.ts +0 -39
  64. package/src/daemon/channels/routing/register.ts +0 -296
  65. package/src/daemon/email/index.ts +0 -68
  66. package/src/daemon/email/register.ts +0 -715
  67. package/src/daemon/operator/index.ts +0 -43
  68. package/src/daemon/operator/register-helper.ts +0 -150
  69. package/src/daemon/operator/surfaces.ts +0 -137
  70. package/src/daemon/operator/types.ts +0 -207
  71. package/src/daemon/remote/backends/index.ts +0 -34
  72. package/src/daemon/remote/index.ts +0 -74
  73. package/src/daemon/remote/register.ts +0 -411
  74. package/src/daemon/triage/index.ts +0 -59
  75. package/src/daemon/triage/integration.ts +0 -179
  76. package/src/daemon/triage/register.ts +0 -231
  77. package/src/daemon/triage/tagger.ts +0 -777
  78. /package/src/daemon/{calendar → handlers/calendar}/ics.ts +0 -0
  79. /package/src/daemon/{operator/credential-store.ts → handlers/credentials.ts} +0 -0
  80. /package/src/daemon/{email → handlers/email}/imap-connector.ts +0 -0
  81. /package/src/daemon/{email → handlers/email}/imap-parsing.ts +0 -0
  82. /package/src/daemon/{email → handlers/email}/smtp-connector.ts +0 -0
  83. /package/src/daemon/{channels → handlers}/inbox/providers/email.ts +0 -0
  84. /package/src/daemon/{remote → handlers/remote}/backends/local-process.ts +0 -0
@@ -10,9 +10,9 @@
10
10
  // pipeline can persist stable triageScore/triageTags values across polls.
11
11
  // ---------------------------------------------------------------------------
12
12
 
13
- import type { InboundChannelItem } from '../operator/index.ts';
13
+ import type { InboundChannelItem, TriageLabel } from './types.ts';
14
14
 
15
- export type TriageLabel = 'spam' | 'priority' | 'normal';
15
+ export type { TriageLabel } from './types.ts';
16
16
 
17
17
  export interface TriageScore {
18
18
  /** Confidence in the assigned label, 0..1 (2-decimal rounded). */
@@ -127,6 +127,10 @@ function normalizeText(item: InboundChannelItem): string {
127
127
  return `${subject} ${subject} ${snippet}`.trim();
128
128
  }
129
129
 
130
+ function escapeRegExp(value: string): string {
131
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
132
+ }
133
+
130
134
  function countLexicon(text: string, lexicon: ReadonlyMap<string, number>): number {
131
135
  let total = 0;
132
136
  for (const [term, weight] of lexicon) {
@@ -149,10 +153,6 @@ function countLexicon(text: string, lexicon: ReadonlyMap<string, number>): numbe
149
153
  return total;
150
154
  }
151
155
 
152
- function escapeRegExp(value: string): string {
153
- return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
154
- }
155
-
156
156
  function upperCaseRatio(text: string): number {
157
157
  const letters = text.replace(/[^a-zA-Z]/g, '');
158
158
  if (letters.length < 8) return 0;
@@ -186,6 +186,21 @@ function clamp01(value: number): number {
186
186
  return value;
187
187
  }
188
188
 
189
+ function mergeLexicon(
190
+ base: ReadonlyMap<string, number>,
191
+ extra: readonly string[] | undefined,
192
+ extraWeight: number,
193
+ ): ReadonlyMap<string, number> {
194
+ if (!extra || extra.length === 0) return base;
195
+ const merged = new Map(base);
196
+ for (const term of extra) {
197
+ const key = term.trim().toLowerCase();
198
+ if (key.length === 0) continue;
199
+ merged.set(key, Math.max(merged.get(key) ?? 0, extraWeight));
200
+ }
201
+ return merged;
202
+ }
203
+
189
204
  /**
190
205
  * Score a single inbound item for spam likelihood and priority likelihood,
191
206
  * then resolve a single label. Deterministic and side-effect free.
@@ -259,21 +274,6 @@ export function scoreInboundItem(
259
274
  };
260
275
  }
261
276
 
262
- function mergeLexicon(
263
- base: ReadonlyMap<string, number>,
264
- extra: readonly string[] | undefined,
265
- extraWeight: number,
266
- ): ReadonlyMap<string, number> {
267
- if (!extra || extra.length === 0) return base;
268
- const merged = new Map(base);
269
- for (const term of extra) {
270
- const key = term.trim().toLowerCase();
271
- if (key.length === 0) continue;
272
- merged.set(key, Math.max(merged.get(key) ?? 0, extraWeight));
273
- }
274
- return merged;
275
- }
276
-
277
277
  /** Map a label to the canonical provider-side tag string applied by the tagger. */
278
278
  export function labelToTag(label: TriageLabel): string {
279
279
  switch (label) {
@@ -0,0 +1,186 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Triage tagger — Discord provider.
3
+ //
4
+ // Two paths, in priority order:
5
+ // 1. REAL thread tags: when the item targets a forum/media-channel thread and
6
+ // a forum-tag mapping resolves >=1 tag id, PATCH the thread's applied_tags
7
+ // (read-then-merge — never blind overwrite). Exact fidelity to the
8
+ // contract's "Discord thread tags".
9
+ // 2. Reaction analog: Discord has no arbitrary per-message tags, so otherwise
10
+ // add a unicode reaction (PUT .../reactions/{emoji}/@me).
11
+ //
12
+ // The bot token is resolved per-apply from the daemon credential store and is
13
+ // never logged or returned.
14
+ // ---------------------------------------------------------------------------
15
+
16
+ import type { HandlerContext } from '../../context.ts';
17
+ import type { DaemonCredentialStore } from '../../credentials.ts';
18
+ import { HandlerError } from '../../errors.ts';
19
+ import type { InboundChannelItem } from '../types.ts';
20
+ import type { ApplyTagsResult, TaggerProviderConfig } from './shared.ts';
21
+ import { discordEmojiForTag, stringMeta } from './shared.ts';
22
+
23
+ export async function applyDiscord(
24
+ item: InboundChannelItem,
25
+ tags: string[],
26
+ providers: TaggerProviderConfig,
27
+ credentials: DaemonCredentialStore,
28
+ fetchImpl: typeof fetch,
29
+ ctx: HandlerContext,
30
+ base: ApplyTagsResult,
31
+ ): Promise<ApplyTagsResult> {
32
+ const cfg = providers.discord;
33
+ if (!cfg) return { ...base, reason: 'discord-not-configured' };
34
+ const channelId = stringMeta(item, 'channelId') ?? item.conversationId;
35
+ const messageId = stringMeta(item, 'messageId') ?? item.id;
36
+ if (!channelId || !messageId) return { ...base, reason: 'discord-missing-target' };
37
+ if (tags.length === 0) return { ...base, reason: 'no-tags' };
38
+
39
+ const token = await credentials.resolveConfigSecret(cfg.tokenConfigKey);
40
+ if (!token) return { ...base, reason: 'discord-no-credentials' };
41
+
42
+ // Exact-fidelity path: when the item targets a forum/media-channel thread and
43
+ // a forum-tag mapping resolves at least one tag, apply REAL Discord thread
44
+ // tags (PATCH the thread's applied_tags). A forum post's thread id is the
45
+ // thread's own channel id; accept an explicit metadata.threadId or fall back
46
+ // to channelId for that case.
47
+ const threadId = stringMeta(item, 'threadId') ?? channelId;
48
+ const tagIds = resolveDiscordTagIds(tags, cfg.forumTagIds);
49
+ if (tagIds.length > 0) {
50
+ return applyDiscordThreadTags(item, threadId, tags, tagIds, token, fetchImpl, ctx);
51
+ }
52
+
53
+ // Analog fallback: Discord has no arbitrary per-message tags, so apply a
54
+ // unicode reaction on the source message instead.
55
+ const applied: string[] = [];
56
+ for (const tag of tags) {
57
+ const emoji = encodeURIComponent(discordEmojiForTag(tag));
58
+ const url = `https://discord.com/api/v10/channels/${channelId}/messages/${messageId}/reactions/${emoji}/@me`;
59
+ const response = await fetchImpl(url, {
60
+ method: 'PUT',
61
+ headers: {
62
+ Authorization: `Bot ${token}`,
63
+ 'Content-Length': '0',
64
+ },
65
+ });
66
+ // 204 No Content is the success case for adding a reaction.
67
+ if (response.status !== 204 && response.status !== 200) {
68
+ const detail = await response.text().catch(() => '');
69
+ ctx.logger.warn('triage: discord reaction rejected', { status: response.status });
70
+ throw new HandlerError(
71
+ `Discord reaction HTTP ${response.status}${detail ? `: ${detail.slice(0, 120)}` : ''}`,
72
+ 'TRIAGE_DISCORD_TAG_FAILED',
73
+ 502,
74
+ );
75
+ }
76
+ applied.push(tag);
77
+ }
78
+ return { surface: item.surface, itemId: item.id, appliedTags: applied, skipped: false };
79
+ }
80
+
81
+ /**
82
+ * Map GoodVibes triage tags to configured Discord forum-tag snowflake ids,
83
+ * preserving order and dropping unmapped tags. De-duplicates ids.
84
+ */
85
+ function resolveDiscordTagIds(
86
+ tags: readonly string[],
87
+ forumTagIds: Record<string, string> | undefined,
88
+ ): string[] {
89
+ if (!forumTagIds) return [];
90
+ const ids: string[] = [];
91
+ for (const tag of tags) {
92
+ const id = forumTagIds[tag];
93
+ if (typeof id === 'string' && id.length > 0 && !ids.includes(id)) ids.push(id);
94
+ }
95
+ return ids;
96
+ }
97
+
98
+ /**
99
+ * Apply real Discord thread tags by merging the resolved forum-tag ids into the
100
+ * thread's existing applied_tags via PATCH /channels/{thread.id}. Idempotent:
101
+ * already-present tag ids are kept and not duplicated.
102
+ */
103
+ async function applyDiscordThreadTags(
104
+ item: InboundChannelItem,
105
+ threadId: string,
106
+ tags: readonly string[],
107
+ tagIds: readonly string[],
108
+ token: string,
109
+ fetchImpl: typeof fetch,
110
+ ctx: HandlerContext,
111
+ ): Promise<ApplyTagsResult> {
112
+ const url = `https://discord.com/api/v10/channels/${threadId}`;
113
+ // DATA-LOSS GUARD: we PATCH the thread's full applied_tags array, so we must
114
+ // first read the EXISTING tags and merge. If that read fails (network error
115
+ // OR a non-ok HTTP status), we have no idea what tags are currently on the
116
+ // thread — PATCHing with only our new ids would silently destroy whatever
117
+ // forum tags were already applied. Abort instead of overwriting.
118
+ const existing = await fetchDiscordAppliedTags(url, token, fetchImpl, ctx);
119
+ if (existing === null) {
120
+ throw new HandlerError(
121
+ 'Discord thread tag read failed; aborting to avoid overwriting existing applied_tags.',
122
+ 'TRIAGE_DISCORD_TAG_FAILED',
123
+ 502,
124
+ );
125
+ }
126
+ const merged = [...new Set([...existing, ...tagIds])];
127
+ const response = await fetchImpl(url, {
128
+ method: 'PATCH',
129
+ headers: {
130
+ Authorization: `Bot ${token}`,
131
+ 'Content-Type': 'application/json',
132
+ },
133
+ body: JSON.stringify({ applied_tags: merged }),
134
+ });
135
+ if (response.status !== 200 && response.status !== 204) {
136
+ const detail = await response.text().catch(() => '');
137
+ ctx.logger.warn('triage: discord thread tag rejected', { status: response.status });
138
+ throw new HandlerError(
139
+ `Discord thread tag HTTP ${response.status}${detail ? `: ${detail.slice(0, 120)}` : ''}`,
140
+ 'TRIAGE_DISCORD_TAG_FAILED',
141
+ 502,
142
+ );
143
+ }
144
+ return { surface: item.surface, itemId: item.id, appliedTags: [...tags], skipped: false };
145
+ }
146
+
147
+ /**
148
+ * Read a thread's current applied_tags.
149
+ *
150
+ * Returns:
151
+ * - string[] -> the read SUCCEEDED; the array is the current applied_tags
152
+ * (possibly empty when the thread genuinely has no tags, or
153
+ * when applied_tags is absent/malformed in a 2xx body).
154
+ * - null -> the read FAILED (thrown error OR non-ok HTTP status). The
155
+ * caller MUST NOT proceed with a PATCH in this case, because a
156
+ * failed read means the existing tag set is unknown and a
157
+ * PATCH would overwrite it (data loss).
158
+ */
159
+ async function fetchDiscordAppliedTags(
160
+ url: string,
161
+ token: string,
162
+ fetchImpl: typeof fetch,
163
+ ctx: HandlerContext,
164
+ ): Promise<string[] | null> {
165
+ try {
166
+ const response = await fetchImpl(url, {
167
+ method: 'GET',
168
+ headers: { Authorization: `Bot ${token}` },
169
+ });
170
+ if (!response.ok) {
171
+ ctx.logger.warn('triage: discord thread tag read failed', { status: response.status });
172
+ return null;
173
+ }
174
+ const payload = (await response.json().catch(() => null)) as
175
+ | { applied_tags?: unknown }
176
+ | null;
177
+ const current = payload?.applied_tags;
178
+ if (!Array.isArray(current)) return [];
179
+ return current.filter((t): t is string => typeof t === 'string');
180
+ } catch (error) {
181
+ ctx.logger.warn('triage: discord thread tag read errored', {
182
+ message: error instanceof Error ? error.message : String(error),
183
+ });
184
+ return null;
185
+ }
186
+ }
@@ -0,0 +1,383 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Triage tagger — IMAP provider.
3
+ //
4
+ // Applies a triage label as an IMAP keyword flag (STORE +FLAGS) over a minimal
5
+ // IMAP4rev1-over-TLS client. Credentials are resolved per-apply from the daemon
6
+ // credential store and are NEVER logged or returned. CRLF/control characters in
7
+ // any interpolated command value are rejected (CRLF-injection guard). Transient
8
+ // network failures are retried with bounded exponential backoff; protocol-level
9
+ // NO/BAD rejections are deterministic and never retried.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import { connect as tlsConnect } from 'node:tls';
13
+ import type { DaemonCredentialStore } from '../../credentials.ts';
14
+ import type { InboundChannelItem } from '../types.ts';
15
+ import type { ApplyTagsResult, TaggerProviderConfig } from './shared.ts';
16
+ import { imapKeywordForTag } from './shared.ts';
17
+
18
+ export interface ImapStoreArgs {
19
+ host: string;
20
+ port: number;
21
+ user: string;
22
+ password: string;
23
+ mailbox: string;
24
+ uid: string;
25
+ flag: string;
26
+ }
27
+
28
+ export interface ImapRetryOptions {
29
+ /** Total attempts including the first (default 3). Values < 1 disable retry. */
30
+ maxAttempts?: number;
31
+ /** Base backoff in ms for the first retry (default 250). */
32
+ baseDelayMs?: number;
33
+ /** Cap on any single backoff delay in ms (default 2000). */
34
+ maxDelayMs?: number;
35
+ /** Injectable sleep (tests). Defaults to a real timer. */
36
+ sleep?: (ms: number) => Promise<void>;
37
+ }
38
+
39
+ export type ImapStoreFlag = (args: ImapStoreArgs) => Promise<void>;
40
+
41
+ /**
42
+ * The minimal subset of a node:tls TLSSocket that imapStoreFlagOverTls drives.
43
+ * Declaring it explicitly (rather than depending on the full TLSSocket surface)
44
+ * gives the data-pump a precise injection seam: tests can supply an in-memory
45
+ * duplex that exercises the protocol state machine without a real network
46
+ * socket, while the production path passes the real tlsConnect result.
47
+ */
48
+ export interface ImapSocketLike {
49
+ setEncoding(encoding: string): void;
50
+ setTimeout(ms: number, callback: () => void): void;
51
+ write(data: string): void;
52
+ on(event: 'data', listener: (chunk: string) => void): void;
53
+ on(event: 'error', listener: (err: Error) => void): void;
54
+ on(event: 'close', listener: () => void): void;
55
+ destroy(): void;
56
+ }
57
+
58
+ /** Connector seam: opens an ImapSocketLike for the given host/port. */
59
+ export type ImapConnect = (opts: {
60
+ host: string;
61
+ port: number;
62
+ servername: string;
63
+ }) => ImapSocketLike;
64
+
65
+ /** Production connector — a real IMAP4rev1-over-TLS socket via node:tls. */
66
+ export const tlsImapConnect: ImapConnect = (opts) =>
67
+ tlsConnect(opts, () => {
68
+ /* greeting handled in the data pump */
69
+ }) as unknown as ImapSocketLike;
70
+
71
+ export async function applyImap(
72
+ item: InboundChannelItem,
73
+ tags: string[],
74
+ providers: TaggerProviderConfig,
75
+ credentials: DaemonCredentialStore,
76
+ storeFlag: ImapStoreFlag,
77
+ base: ApplyTagsResult,
78
+ ): Promise<ApplyTagsResult> {
79
+ const cfg = providers.imap;
80
+ if (!cfg) return { ...base, reason: 'imap-not-configured' };
81
+ const uid = imapUidFromItem(item);
82
+ if (!uid) return { ...base, reason: 'imap-missing-uid' };
83
+ if (tags.length === 0) return { ...base, reason: 'no-tags' };
84
+
85
+ const password = await credentials.resolveConfigSecret(cfg.passwordConfigKey);
86
+ if (!password) return { ...base, reason: 'imap-no-credentials' };
87
+
88
+ const applied: string[] = [];
89
+ for (const tag of tags) {
90
+ await storeFlag({
91
+ host: cfg.host,
92
+ port: cfg.port ?? 993,
93
+ user: cfg.user,
94
+ password,
95
+ mailbox: cfg.mailbox ?? 'INBOX',
96
+ uid,
97
+ flag: imapKeywordForTag(tag),
98
+ });
99
+ applied.push(tag);
100
+ }
101
+ return { surface: item.surface, itemId: item.id, appliedTags: applied, skipped: false };
102
+ }
103
+
104
+ function imapUidFromItem(item: InboundChannelItem): string | null {
105
+ const meta = item.metadata ?? {};
106
+ const uid = meta.imapUid ?? meta.uid;
107
+ if (typeof uid === 'string' && uid.length > 0) return uid;
108
+ if (typeof uid === 'number' && Number.isFinite(uid)) return String(uid);
109
+ return null;
110
+ }
111
+
112
+ /**
113
+ * Error subclass carrying whether a failure is transient (worth retrying) or a
114
+ * deterministic protocol rejection (NO/BAD) that must not be retried.
115
+ */
116
+ export class ImapStoreError extends Error {
117
+ readonly transient: boolean;
118
+ constructor(message: string, transient: boolean) {
119
+ super(message);
120
+ this.name = 'ImapStoreError';
121
+ this.transient = transient;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Reject CR, LF, NUL and any other ASCII control character (0x00-0x1F, 0x7F)
127
+ * in a value destined for an IMAP command line. CR/LF are the dangerous ones:
128
+ * an unescaped CRLF would terminate the current command and let an attacker
129
+ * inject a second IMAP command (CRLF injection). IMAP's quoted-string syntax
130
+ * has no escape for these control chars — backslash only escapes `\` and `"` —
131
+ * so the only safe handling is to refuse the value outright.
132
+ */
133
+ function assertImapSafe(value: string, field: string): void {
134
+ // eslint-disable-next-line no-control-regex -- intentional control-char guard
135
+ if (/[\x00-\x1F\x7F]/.test(value)) {
136
+ throw new ImapStoreError(
137
+ `IMAP ${field} contains illegal control characters (possible CRLF injection)`,
138
+ false,
139
+ );
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Wrap a value as an IMAP quoted string. Backslash and double-quote are escaped
145
+ * per RFC 3501; control characters are NOT escapable in the quoted-string
146
+ * grammar, so callers MUST validate with assertImapSafe first. quoteImap
147
+ * re-asserts as defense-in-depth so no future caller can bypass the guard.
148
+ */
149
+ function quoteImap(value: string): string {
150
+ assertImapSafe(value, 'value');
151
+ return `"${value.replace(/([\\"])/g, '\\$1')}"`;
152
+ }
153
+
154
+ // A concrete UID sequence-set: one or more comma-separated single UIDs or
155
+ // numeric ranges (`12`, `3:9`, `1,4,7:9`). RFC 3501 also permits `*` (the
156
+ // largest UID in the mailbox) and ranges to `*`, but a wildcard would let a
157
+ // single value like `1:*` apply the flag to the ENTIRE mailbox — never the
158
+ // intent when tagging one triaged item — so `*` is rejected outright.
159
+ const IMAP_UID_SET = /^[0-9]+(:[0-9]+)?(,[0-9]+(:[0-9]+)?)*$/;
160
+
161
+ // An IMAP flag: an optional leading `\` (system flag, e.g. `\Seen`) followed by
162
+ // atom characters only. The atom grammar excludes SP and the list/quoting
163
+ // specials `(){%*"\` and `]`, so a flag cannot contain a space (which would
164
+ // otherwise inject a second flag atom into the `+FLAGS (...)` list) or close
165
+ // the parenthesised list early.
166
+ // eslint-disable-next-line no-control-regex -- atom grammar excludes controls
167
+ const IMAP_FLAG = /^\\?[^\s(){%*"\\\]\x00-\x1F\x7F]+$/;
168
+
169
+ /**
170
+ * Validate an IMAP UID value as a concrete sequence-set before it is
171
+ * interpolated UNQUOTED into `UID STORE`. assertImapSafe only blocks control
172
+ * chars; a control-char-free wildcard like `1:*` would still pass that guard
173
+ * and mutate the whole mailbox. This is the boundary check that prevents it.
174
+ */
175
+ function assertImapUid(value: string): void {
176
+ if (!IMAP_UID_SET.test(value)) {
177
+ throw new ImapStoreError(
178
+ `IMAP uid is not a valid numeric sequence-set: ${JSON.stringify(value)}`,
179
+ false,
180
+ );
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Validate an IMAP flag against the flag/atom grammar before it is interpolated
186
+ * UNQUOTED into the `+FLAGS (...)` list. assertImapSafe only blocks control
187
+ * chars; a flag containing a space (e.g. `\Seen Junk`) would still pass that
188
+ * guard and inject a second flag atom. This is the boundary check that
189
+ * prevents it — independent of any upstream normalizer.
190
+ */
191
+ function assertImapFlag(value: string): void {
192
+ if (!IMAP_FLAG.test(value)) {
193
+ throw new ImapStoreError(
194
+ `IMAP flag is not a valid flag-keyword atom: ${JSON.stringify(value)}`,
195
+ false,
196
+ );
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Minimal IMAP4rev1 client: connect over TLS, LOGIN, SELECT, UID STORE +FLAGS,
202
+ * LOGOUT. Uses only node:tls (Bun-compatible).
203
+ *
204
+ * Tagged-command sequencing uses an explicit completion flag rather than a line
205
+ * heuristic: the LOGOUT step is tracked by reference, so its tagged OK (or an
206
+ * untagged `* BYE`) cleanly completes the operation and tells the `close`
207
+ * handler the disconnect was expected. Connection/timeout/socket failures are
208
+ * surfaced as transient ImapStoreError; NO/BAD protocol responses as
209
+ * non-transient.
210
+ */
211
+ export function imapStoreFlagOverTls(
212
+ args: ImapStoreArgs,
213
+ connect: ImapConnect = tlsImapConnect,
214
+ ): Promise<void> {
215
+ return new Promise<void>((resolve, reject) => {
216
+ try {
217
+ assertImapSafe(args.user, 'user');
218
+ assertImapSafe(args.password, 'password');
219
+ assertImapSafe(args.mailbox, 'mailbox');
220
+ assertImapSafe(args.uid, 'uid');
221
+ assertImapSafe(args.flag, 'flag');
222
+ // uid and flag are interpolated UNQUOTED below; the control-char guard
223
+ // alone is insufficient, so enforce the structural grammar here too.
224
+ assertImapUid(args.uid);
225
+ assertImapFlag(args.flag);
226
+ } catch (err) {
227
+ reject(
228
+ err instanceof ImapStoreError
229
+ ? err
230
+ : new ImapStoreError(err instanceof Error ? err.message : String(err), false),
231
+ );
232
+ return;
233
+ }
234
+ type Step = { tag: string; isLogout: boolean; resolve: () => void; reject: (e: Error) => void };
235
+
236
+ let done = false;
237
+ let completed = false; // LOGOUT acknowledged (or BYE seen) — close is expected.
238
+ let buffer = '';
239
+ let pending: Step | null = null;
240
+ let counter = 0;
241
+ let greeted = false;
242
+
243
+ const finish = (err?: Error): void => {
244
+ if (done) return;
245
+ done = true;
246
+ try {
247
+ socket.destroy();
248
+ } catch {
249
+ /* ignore */
250
+ }
251
+ if (err) reject(err);
252
+ else resolve();
253
+ };
254
+
255
+ const socket: ImapSocketLike = connect({
256
+ host: args.host,
257
+ port: args.port,
258
+ servername: args.host,
259
+ });
260
+ socket.setEncoding('utf-8');
261
+ socket.setTimeout(20_000, () =>
262
+ finish(new ImapStoreError('IMAP connection timed out', true)),
263
+ );
264
+
265
+ const send = (command: string, isLogout = false): Promise<void> =>
266
+ new Promise<void>((res, rej) => {
267
+ counter += 1;
268
+ const tag = `A${counter}`;
269
+ pending = { tag, isLogout, resolve: res, reject: rej };
270
+ socket.write(`${tag} ${command}\r\n`);
271
+ });
272
+
273
+ const runSequence = async (): Promise<void> => {
274
+ await send(`LOGIN ${quoteImap(args.user)} ${quoteImap(args.password)}`);
275
+ await send(`SELECT ${quoteImap(args.mailbox)}`);
276
+ await send(`UID STORE ${args.uid} +FLAGS (${args.flag})`);
277
+ await send('LOGOUT', true);
278
+ };
279
+
280
+ const handleLine = (line: string): void => {
281
+ if (!greeted) {
282
+ greeted = true;
283
+ if (!/^\* (OK|PREAUTH)/i.test(line)) {
284
+ finish(new ImapStoreError(`IMAP server rejected connection: ${line}`, true));
285
+ return;
286
+ }
287
+ runSequence().catch((err) =>
288
+ finish(
289
+ err instanceof ImapStoreError
290
+ ? err
291
+ : new ImapStoreError(err instanceof Error ? err.message : String(err), false),
292
+ ),
293
+ );
294
+ return;
295
+ }
296
+
297
+ // An untagged BYE during LOGOUT is the server announcing a clean close.
298
+ if (/^\* BYE/i.test(line) && pending?.isLogout) {
299
+ completed = true;
300
+ return;
301
+ }
302
+
303
+ if (!pending) return;
304
+ if (!line.startsWith(`${pending.tag} `)) return; // untagged data line
305
+ const status = line.slice(pending.tag.length + 1);
306
+ const current = pending;
307
+ pending = null;
308
+ if (/^OK/i.test(status)) {
309
+ current.resolve();
310
+ if (current.isLogout) {
311
+ completed = true;
312
+ finish();
313
+ }
314
+ } else {
315
+ // NO/BAD: deterministic protocol rejection — do not retry.
316
+ current.reject(new ImapStoreError(`IMAP command failed: ${status}`, false));
317
+ }
318
+ };
319
+
320
+ socket.on('error', (err) =>
321
+ finish(new ImapStoreError(err instanceof Error ? err.message : String(err), true)),
322
+ );
323
+ socket.on('close', () => {
324
+ if (completed) finish();
325
+ else finish(new ImapStoreError('IMAP connection closed unexpectedly', true));
326
+ });
327
+ socket.on('data', (chunk: string) => {
328
+ buffer += chunk;
329
+ let newlineIdx = buffer.indexOf('\n');
330
+ while (newlineIdx !== -1) {
331
+ const line = buffer.slice(0, newlineIdx).replace(/\r$/, '');
332
+ buffer = buffer.slice(newlineIdx + 1);
333
+ handleLine(line);
334
+ newlineIdx = buffer.indexOf('\n');
335
+ }
336
+ });
337
+ });
338
+ }
339
+
340
+ /** True when an error is worth retrying (network/connection, not protocol). */
341
+ function isTransientImapError(error: unknown): boolean {
342
+ if (error instanceof ImapStoreError) return error.transient;
343
+ const code = (error as { code?: unknown })?.code;
344
+ if (typeof code === 'string') {
345
+ return ['ECONNRESET', 'ETIMEDOUT', 'EPIPE', 'ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAI_AGAIN']
346
+ .includes(code);
347
+ }
348
+ return false;
349
+ }
350
+
351
+ const defaultSleep = (ms: number): Promise<void> =>
352
+ new Promise((res) => setTimeout(res, ms));
353
+
354
+ /**
355
+ * Wrap an IMAP store function with bounded exponential-backoff retry on
356
+ * transient failures only. Protocol-level (NO/BAD) errors are surfaced on the
357
+ * first attempt without retry.
358
+ */
359
+ export function makeRetryingImapStoreFlag(
360
+ inner: ImapStoreFlag,
361
+ retry: ImapRetryOptions = {},
362
+ ): ImapStoreFlag {
363
+ const maxAttempts = Math.max(1, retry.maxAttempts ?? 3);
364
+ const baseDelayMs = Math.max(0, retry.baseDelayMs ?? 250);
365
+ const maxDelayMs = Math.max(baseDelayMs, retry.maxDelayMs ?? 2_000);
366
+ const sleep = retry.sleep ?? defaultSleep;
367
+
368
+ return async (args: ImapStoreArgs): Promise<void> => {
369
+ let lastError: unknown;
370
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
371
+ try {
372
+ await inner(args);
373
+ return;
374
+ } catch (error) {
375
+ lastError = error;
376
+ if (attempt >= maxAttempts || !isTransientImapError(error)) throw error;
377
+ const delay = Math.min(maxDelayMs, baseDelayMs * 2 ** (attempt - 1));
378
+ await sleep(delay);
379
+ }
380
+ }
381
+ throw lastError;
382
+ };
383
+ }