@pithy-sh/support 0.1.1 → 0.1.3

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 (167) hide show
  1. package/dist/ai/classify.d.ts +90 -0
  2. package/dist/ai/classify.d.ts.map +1 -0
  3. package/dist/ai/classify.js +151 -0
  4. package/dist/attachment/store.d.ts +53 -0
  5. package/dist/attachment/store.d.ts.map +1 -0
  6. package/dist/attachment/store.js +67 -0
  7. package/dist/audit/actions.d.ts +68 -0
  8. package/dist/audit/actions.d.ts.map +1 -0
  9. package/dist/audit/actions.js +68 -0
  10. package/dist/capability.d.ts +93 -0
  11. package/dist/capability.d.ts.map +1 -0
  12. package/dist/capability.js +187 -0
  13. package/dist/client/projection.d.ts +56 -0
  14. package/dist/client/projection.d.ts.map +1 -0
  15. package/dist/client/projection.js +0 -0
  16. package/dist/config/config.d.ts +215 -0
  17. package/dist/config/config.d.ts.map +1 -0
  18. package/dist/config/config.js +169 -0
  19. package/dist/data/attachment.d.ts +30 -0
  20. package/dist/data/attachment.d.ts.map +1 -0
  21. package/dist/data/attachment.js +32 -0
  22. package/dist/data/billingScope.d.ts +30 -0
  23. package/dist/data/billingScope.d.ts.map +1 -0
  24. package/dist/data/billingScope.js +32 -0
  25. package/dist/data/categories.d.ts +54 -0
  26. package/dist/data/categories.d.ts.map +1 -0
  27. package/dist/data/categories.js +97 -0
  28. package/dist/data/classification.d.ts +34 -0
  29. package/dist/data/classification.d.ts.map +1 -0
  30. package/dist/data/classification.js +28 -0
  31. package/dist/data/enums.d.ts +82 -0
  32. package/dist/data/enums.d.ts.map +1 -0
  33. package/dist/data/enums.js +70 -0
  34. package/dist/data/flag.d.ts +25 -0
  35. package/dist/data/flag.d.ts.map +1 -0
  36. package/dist/data/flag.js +27 -0
  37. package/dist/data/message.d.ts +81 -0
  38. package/dist/data/message.d.ts.map +1 -0
  39. package/dist/data/message.js +84 -0
  40. package/dist/data/tables.d.ts +160 -0
  41. package/dist/data/tables.d.ts.map +1 -0
  42. package/dist/data/tables.js +44 -0
  43. package/dist/data/thread.d.ts +77 -0
  44. package/dist/data/thread.d.ts.map +1 -0
  45. package/dist/data/thread.js +65 -0
  46. package/dist/error/errors.d.ts +64 -0
  47. package/dist/error/errors.d.ts.map +1 -0
  48. package/dist/error/errors.js +82 -0
  49. package/dist/http/guards.d.ts +44 -0
  50. package/dist/http/guards.d.ts.map +1 -0
  51. package/dist/http/guards.js +53 -0
  52. package/dist/http/handlers.d.ts +89 -0
  53. package/dist/http/handlers.d.ts.map +1 -0
  54. package/dist/http/handlers.js +248 -0
  55. package/dist/http/resolve.d.ts +44 -0
  56. package/dist/http/resolve.d.ts.map +1 -0
  57. package/dist/http/resolve.js +72 -0
  58. package/dist/http/responses.d.ts +829 -0
  59. package/dist/http/responses.d.ts.map +1 -0
  60. package/dist/http/responses.js +303 -0
  61. package/dist/http/routes.d.ts +109 -0
  62. package/dist/http/routes.d.ts.map +1 -0
  63. package/dist/http/routes.js +62 -0
  64. package/dist/http/schemas.d.ts +121 -0
  65. package/dist/http/schemas.d.ts.map +1 -0
  66. package/dist/http/schemas.js +89 -0
  67. package/dist/http/scopes.d.ts +56 -0
  68. package/dist/http/scopes.d.ts.map +1 -0
  69. package/dist/http/scopes.js +107 -0
  70. package/dist/http/views.d.ts +36 -0
  71. package/dist/http/views.d.ts.map +1 -0
  72. package/dist/http/views.js +144 -0
  73. package/dist/inbound/authenticity.d.ts +81 -0
  74. package/dist/inbound/authenticity.d.ts.map +1 -0
  75. package/dist/inbound/authenticity.js +61 -0
  76. package/dist/inbound/guard.d.ts +74 -0
  77. package/dist/inbound/guard.d.ts.map +1 -0
  78. package/dist/inbound/guard.js +78 -0
  79. package/dist/inbound/handler.d.ts +28 -0
  80. package/dist/inbound/handler.d.ts.map +1 -0
  81. package/dist/inbound/handler.js +82 -0
  82. package/dist/inbound/ingest.d.ts +104 -0
  83. package/dist/inbound/ingest.d.ts.map +1 -0
  84. package/dist/inbound/ingest.js +326 -0
  85. package/dist/inbound/recipient.d.ts +16 -0
  86. package/dist/inbound/recipient.d.ts.map +1 -0
  87. package/dist/inbound/recipient.js +46 -0
  88. package/dist/index.d.ts +20 -0
  89. package/dist/index.d.ts.map +1 -0
  90. package/dist/index.js +14 -0
  91. package/dist/link/sender.d.ts +160 -0
  92. package/dist/link/sender.d.ts.map +1 -0
  93. package/dist/link/sender.js +200 -0
  94. package/dist/migrations/0001_threads.d.ts +26 -0
  95. package/dist/migrations/0001_threads.d.ts.map +1 -0
  96. package/dist/migrations/0001_threads.js +103 -0
  97. package/dist/mime/address.d.ts +22 -0
  98. package/dist/mime/address.d.ts.map +1 -0
  99. package/dist/mime/address.js +28 -0
  100. package/dist/mime/parse.d.ts +96 -0
  101. package/dist/mime/parse.d.ts.map +1 -0
  102. package/dist/mime/parse.js +146 -0
  103. package/dist/mime/sanitize.d.ts +25 -0
  104. package/dist/mime/sanitize.d.ts.map +1 -0
  105. package/dist/mime/sanitize.js +212 -0
  106. package/dist/mime/threading.d.ts +79 -0
  107. package/dist/mime/threading.d.ts.map +1 -0
  108. package/dist/mime/threading.js +111 -0
  109. package/dist/mime/truncate.d.ts +17 -0
  110. package/dist/mime/truncate.d.ts.map +1 -0
  111. package/dist/mime/truncate.js +47 -0
  112. package/dist/provision/provisionSupport.d.ts +158 -0
  113. package/dist/provision/provisionSupport.d.ts.map +1 -0
  114. package/dist/provision/provisionSupport.js +110 -0
  115. package/dist/provision/resolveSupportConfig.d.ts +45 -0
  116. package/dist/provision/resolveSupportConfig.d.ts.map +1 -0
  117. package/dist/provision/resolveSupportConfig.js +22 -0
  118. package/dist/reply/send.d.ts +123 -0
  119. package/dist/reply/send.d.ts.map +1 -0
  120. package/dist/reply/send.js +153 -0
  121. package/dist/reply/snippets.d.ts +79 -0
  122. package/dist/reply/snippets.d.ts.map +1 -0
  123. package/dist/reply/snippets.js +135 -0
  124. package/dist/secret/registry.d.ts +18 -0
  125. package/dist/secret/registry.d.ts.map +1 -0
  126. package/dist/secret/registry.js +21 -0
  127. package/dist/seeds/example.d.ts +3 -0
  128. package/dist/seeds/example.d.ts.map +1 -0
  129. package/dist/seeds/example.js +350 -0
  130. package/dist/store/paging.d.ts +18 -0
  131. package/dist/store/paging.d.ts.map +1 -0
  132. package/dist/store/paging.js +20 -0
  133. package/dist/store/search.d.ts +67 -0
  134. package/dist/store/search.d.ts.map +1 -0
  135. package/dist/store/search.js +160 -0
  136. package/dist/store/searchIndex.d.ts +53 -0
  137. package/dist/store/searchIndex.d.ts.map +1 -0
  138. package/dist/store/searchIndex.js +66 -0
  139. package/dist/store/threads.d.ts +147 -0
  140. package/dist/store/threads.d.ts.map +1 -0
  141. package/dist/store/threads.js +197 -0
  142. package/dist/submission/encoding.d.ts +21 -0
  143. package/dist/submission/encoding.d.ts.map +1 -0
  144. package/dist/submission/encoding.js +55 -0
  145. package/dist/submission/guard.d.ts +71 -0
  146. package/dist/submission/guard.d.ts.map +1 -0
  147. package/dist/submission/guard.js +46 -0
  148. package/dist/submission/submit.d.ts +152 -0
  149. package/dist/submission/submit.d.ts.map +1 -0
  150. package/dist/submission/submit.js +319 -0
  151. package/dist/version.generated.d.ts +5 -0
  152. package/dist/version.generated.d.ts.map +1 -0
  153. package/dist/version.generated.js +7 -0
  154. package/dist/workflows/classify.d.ts +63 -0
  155. package/dist/workflows/classify.d.ts.map +1 -0
  156. package/dist/workflows/classify.js +68 -0
  157. package/dist/workflows/retryPolicy.d.ts +39 -0
  158. package/dist/workflows/retryPolicy.d.ts.map +1 -0
  159. package/dist/workflows/retryPolicy.js +43 -0
  160. package/dist/workflows/specs.d.ts +43 -0
  161. package/dist/workflows/specs.d.ts.map +1 -0
  162. package/dist/workflows/specs.js +46 -0
  163. package/dist/workflows/worker.d.ts +48 -0
  164. package/dist/workflows/worker.d.ts.map +1 -0
  165. package/dist/workflows/worker.js +37 -0
  166. package/package.json +24 -15
  167. package/src/version.generated.ts +1 -1
@@ -0,0 +1,25 @@
1
+ /** The largest sanitized body kept, **in bytes**. A dashboard rendering 5 MB of markup has already lost. */
2
+ export declare const MAX_HTML_BYTES: number;
3
+ /** Whether an `href` value is safe to keep. Relative URLs are fine; a bare scheme we do not know is not. */
4
+ export declare function isSafeHref(value: string): boolean;
5
+ /**
6
+ * Sanitize an HTML body for storage and later rendering.
7
+ *
8
+ * **Remote images are stripped, not merely sandboxed.** An `<img src="https://…">` in a support
9
+ * message is a read receipt: it tells the sender the exact moment somebody opened their mail and
10
+ * from which IP, and against a support inbox that is a reconnaissance tool for whoever is probing
11
+ * you. Every mail client blocks them by default and so does this. The `alt` text survives, so a
12
+ * screenshot that mattered leaves a visible trace rather than vanishing silently. The original is
13
+ * still in R2 if an operator genuinely needs to see it.
14
+ */
15
+ export declare function sanitizeHtml(html: string): Promise<string>;
16
+ /**
17
+ * Reduce HTML to readable plain text — the fallback when a message carried no text part.
18
+ *
19
+ * The classifier reads text, never markup: markup is tokens the adopter pays for that carry no
20
+ * meaning, and it is also an injection surface, since `<!-- ignore your instructions -->` reads
21
+ * exactly like prose to a model. Block-level tags become newlines so a paragraph structure survives
22
+ * the trip.
23
+ */
24
+ export declare function htmlToText(html: string): Promise<string>;
25
+ //# sourceMappingURL=sanitize.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sanitize.d.ts","sourceRoot":"","sources":["../../src/mime/sanitize.ts"],"names":[],"mappings":"AAuEA,4GAA4G;AAC5G,eAAO,MAAM,cAAc,QAAa,CAAC;AAsCzC,4GAA4G;AAC5G,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAmBjD;AAED;;;;;;;;;GASG;AACH,wBAAsB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CA4ChE;AAED;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAwD9D"}
@@ -0,0 +1,212 @@
1
+ import { truncateToBytes } from "./truncate.js";
2
+ //#region src/mime/sanitize.ts
3
+ /**
4
+ * HTML sanitization for inbound mail, through the runtime's own streaming parser.
5
+ *
6
+ * This capability ingests attacker-controlled content and a dashboard renders it. That is the
7
+ * highest-risk sentence in the package, so the sanitizer is built on `HTMLRewriter` — workerd's real
8
+ * HTML parser — rather than on regular expressions. A regex sanitizer is a list of the tricks its
9
+ * author thought of; a parser-based one strips what the browser will actually see, which is the only
10
+ * question that matters. It is also why this file has no dependencies: the safest HTML parser
11
+ * available here already ships in the runtime.
12
+ *
13
+ * The policy is an **allowlist on both axes** — a small set of tags survives and a small set of
14
+ * attributes survives — because a denylist is wrong the day a new attribute is invented, and a
15
+ * support inbox will still be running then.
16
+ *
17
+ * `HTMLRewriter` is a Workers global, so it is touched only inside these functions. The module
18
+ * imports cleanly under node (which the `.describe()` meta-test requires); its tests are
19
+ * `.workers.test.ts`, running against the real parser rather than a stand-in for it.
20
+ */
21
+ /**
22
+ * Tags removed together with everything inside them.
23
+ *
24
+ * Two groups. The obvious executables (`script`, `iframe`, `object`, `embed`, `svg` — SVG is a
25
+ * scripting context, not an image format), and the quiet ones: `style` because CSS can position an
26
+ * invisible overlay over a real control, `link`/`base`/`meta` because they retarget or redirect the
27
+ * whole document, `form` and its inputs because a phishing form rendered inside a trusted dashboard
28
+ * is the most convincing phishing form there is, and `noscript`/`template` because their contents
29
+ * are inert to the parser here and live to a browser later.
30
+ */
31
+ const DROPPED_TAGS = /* @__PURE__ */ new Set([
32
+ "script",
33
+ "style",
34
+ "iframe",
35
+ "frame",
36
+ "frameset",
37
+ "object",
38
+ "embed",
39
+ "applet",
40
+ "link",
41
+ "meta",
42
+ "base",
43
+ "form",
44
+ "input",
45
+ "button",
46
+ "select",
47
+ "option",
48
+ "textarea",
49
+ "svg",
50
+ "math",
51
+ "noscript",
52
+ "template",
53
+ "title"
54
+ ]);
55
+ /**
56
+ * Attributes that survive, on any tag.
57
+ *
58
+ * Note what is absent and deliberate: `style` (see above), every `on*` handler, `srcset`/`ping`/
59
+ * `formaction`, and every `data-*`. Nothing needs an allowlist entry to be dropped — anything not on
60
+ * this list goes, which is what makes the policy hold against attributes that do not exist yet.
61
+ */
62
+ const ALLOWED_ATTRIBUTES = /* @__PURE__ */ new Set([
63
+ "href",
64
+ "alt",
65
+ "title",
66
+ "colspan",
67
+ "rowspan",
68
+ "start",
69
+ "type",
70
+ "dir",
71
+ "lang"
72
+ ]);
73
+ /** URL schemes a surviving `href` may use. Everything else — `javascript:`, `data:`, `vbscript:` — is dropped. */
74
+ const ALLOWED_SCHEMES = [
75
+ "http:",
76
+ "https:",
77
+ "mailto:",
78
+ "tel:"
79
+ ];
80
+ /** The largest sanitized body kept, **in bytes**. A dashboard rendering 5 MB of markup has already lost. */
81
+ const MAX_HTML_BYTES = 524288;
82
+ /**
83
+ * Decode the character references a browser would decode before it resolves a scheme.
84
+ *
85
+ * `href="java&#10;script:alert(1)"` is a `javascript:` URL to every browser: the parser decodes the
86
+ * entity into a newline while reading the attribute, and the URL parser then strips it. A check that
87
+ * reads the raw attribute sees `java&#10;script:...`, whose first `#` looks like a fragment marker,
88
+ * and waves it through as relative — which is exactly the bypass this function exists to remove.
89
+ *
90
+ * Numeric, hex, and the three named references that can hide a scheme. Deliberately not a general
91
+ * entity decoder: this value is about to be compared against a scheme allowlist, and the only
92
+ * question worth answering is whether decoding could turn it into something that *is* a scheme.
93
+ */
94
+ function decodeReferences(value) {
95
+ return value.replace(/&#x([0-9a-f]+);?/gi, (_, hex) => codePoint(Number.parseInt(hex, 16))).replace(/&#(\d+);?/g, (_, dec) => codePoint(Number.parseInt(dec, 10))).replace(/&colon;?/gi, ":").replace(/&newline;?/gi, "\n").replace(/&tab;?/gi, " ");
96
+ }
97
+ /**
98
+ * One decoded character, or the replacement character when the reference names nothing.
99
+ *
100
+ * `String.fromCodePoint` throws a `RangeError` above U+10FFFF, and `&#99999999;` in an `href` is a
101
+ * string an attacker chooses. Unguarded it throws out of the attribute walk, rejects the whole
102
+ * `sanitizeHtml` promise, and fails ingest for that message — a mailable denial of service in the
103
+ * decoder that exists to make ingest safe. The HTML spec's own answer is U+FFFD, so this returns what
104
+ * a browser would have shown: a character that names no scheme and so decides nothing.
105
+ */
106
+ function codePoint(value) {
107
+ if (!Number.isInteger(value) || value < 0 || value > 1114111) return "�";
108
+ return value >= 55296 && value <= 57343 ? "�" : String.fromCodePoint(value);
109
+ }
110
+ /** Whether an `href` value is safe to keep. Relative URLs are fine; a bare scheme we do not know is not. */
111
+ function isSafeHref(value) {
112
+ const trimmed = decodeReferences(value).replace(/[\u0000-\u0020]+/g, "").toLowerCase();
113
+ if (trimmed.length === 0) return false;
114
+ const colon = trimmed.indexOf(":");
115
+ if (colon === -1) return true;
116
+ if (colon > Math.min(...[
117
+ "/",
118
+ "?",
119
+ "#"
120
+ ].map((char) => {
121
+ const index = trimmed.indexOf(char);
122
+ return index === -1 ? Number.POSITIVE_INFINITY : index;
123
+ }))) return true;
124
+ return ALLOWED_SCHEMES.includes(trimmed.slice(0, colon + 1));
125
+ }
126
+ /**
127
+ * Sanitize an HTML body for storage and later rendering.
128
+ *
129
+ * **Remote images are stripped, not merely sandboxed.** An `<img src="https://…">` in a support
130
+ * message is a read receipt: it tells the sender the exact moment somebody opened their mail and
131
+ * from which IP, and against a support inbox that is a reconnaissance tool for whoever is probing
132
+ * you. Every mail client blocks them by default and so does this. The `alt` text survives, so a
133
+ * screenshot that mattered leaves a visible trace rather than vanishing silently. The original is
134
+ * still in R2 if an operator genuinely needs to see it.
135
+ */
136
+ async function sanitizeHtml(html) {
137
+ const sanitized = await new HTMLRewriter().onDocument({ comments(comment) {
138
+ comment.remove();
139
+ } }).on("*", { element(element) {
140
+ const tag = element.tagName.toLowerCase();
141
+ if (DROPPED_TAGS.has(tag)) {
142
+ element.remove();
143
+ return;
144
+ }
145
+ for (const pair of [...element.attributes]) {
146
+ const name = pair[0] ?? "";
147
+ const value = pair[1] ?? "";
148
+ const attribute = name.toLowerCase();
149
+ if (!ALLOWED_ATTRIBUTES.has(attribute)) {
150
+ element.removeAttribute(name);
151
+ continue;
152
+ }
153
+ if (attribute === "href" && !isSafeHref(value)) element.removeAttribute(name);
154
+ }
155
+ if (tag === "a" && element.getAttribute("href")) {
156
+ element.setAttribute("rel", "noopener noreferrer nofollow");
157
+ element.setAttribute("target", "_blank");
158
+ }
159
+ } }).transform(new Response(html)).text();
160
+ return truncateToBytes(sanitized, MAX_HTML_BYTES);
161
+ }
162
+ /**
163
+ * Reduce HTML to readable plain text — the fallback when a message carried no text part.
164
+ *
165
+ * The classifier reads text, never markup: markup is tokens the adopter pays for that carry no
166
+ * meaning, and it is also an injection surface, since `<!-- ignore your instructions -->` reads
167
+ * exactly like prose to a model. Block-level tags become newlines so a paragraph structure survives
168
+ * the trip.
169
+ */
170
+ async function htmlToText(html) {
171
+ const parts = [];
172
+ let suppressed = 0;
173
+ await new HTMLRewriter().onDocument({
174
+ comments(comment) {
175
+ comment.remove();
176
+ },
177
+ text(chunk) {
178
+ if (suppressed === 0) parts.push(chunk.text);
179
+ }
180
+ }).on("*", { element(element) {
181
+ const tag = element.tagName.toLowerCase();
182
+ if (DROPPED_TAGS.has(tag)) {
183
+ element.remove();
184
+ suppressed += 1;
185
+ try {
186
+ element.onEndTag(() => {
187
+ suppressed -= 1;
188
+ });
189
+ } catch {
190
+ suppressed -= 1;
191
+ }
192
+ return;
193
+ }
194
+ if ([
195
+ "p",
196
+ "div",
197
+ "br",
198
+ "tr",
199
+ "li",
200
+ "h1",
201
+ "h2",
202
+ "h3",
203
+ "h4",
204
+ "h5",
205
+ "h6",
206
+ "blockquote"
207
+ ].includes(tag)) parts.push("\n");
208
+ } }).transform(new Response(html)).text();
209
+ return parts.join("").replace(/[\t\r ]+/g, " ").replace(/ ?\n ?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
210
+ }
211
+ //#endregion
212
+ export { MAX_HTML_BYTES, htmlToText, isSafeHref, sanitizeHtml };
@@ -0,0 +1,79 @@
1
+ /**
2
+ * RFC 5322 threading — turning `Message-ID`, `In-Reply-To`, and `References` into a conversation.
3
+ *
4
+ * **Threading is done on ids, never on the subject.** Subject matching is what makes two unrelated
5
+ * people who both wrote "Refund" land in one thread, and it is what splits a real conversation the
6
+ * moment somebody's client localizes `Re:` to `Aw:` or `Antw:`. The headers exist precisely so this
7
+ * does not have to be guessed, and every mail client sets them.
8
+ *
9
+ * The chain is tried in the order that goes from most precise to least: `In-Reply-To` names exactly
10
+ * one message, so it is asked first; `References` is the whole ancestry, so it is the fallback for a
11
+ * client that dropped `In-Reply-To` or a reply to a message that reached us out of order. Reading
12
+ * `References` **newest-first** matters — the last entry is the nearest ancestor, and starting at the
13
+ * root would attach a reply to the top of a long thread rather than to the message it answers.
14
+ */
15
+ /** The longest `References` chain kept. Bounded because the header is attacker-controlled and unbounded by spec. */
16
+ export declare const MAX_REFERENCES = 50;
17
+ /**
18
+ * Strip the angle brackets from a message id and bound it.
19
+ *
20
+ * Stored without brackets so a lookup is plain equality: the brackets are transport syntax, and one
21
+ * path storing `<a@b>` while another queries `a@b` is a threading bug that only shows up on replies.
22
+ */
23
+ export declare function normalizeMessageId(value: string | null | undefined): string | undefined;
24
+ /**
25
+ * Parse a `References` (or `In-Reply-To`) header into ids, oldest first, deduplicated and bounded.
26
+ *
27
+ * `postal-mime` hands `references` back as the raw header string, so the splitting is ours. Angle
28
+ * brackets are the delimiter when they are present and whitespace is the fallback when they are not,
29
+ * because a malformed header from a hand-rolled sender is a normal input here.
30
+ *
31
+ * **When the chain is over the cap, the OLDEST entries are dropped, not the newest.** That direction
32
+ * is the whole point: `parentCandidates` reads this list from the newest end backwards, because the
33
+ * nearest ancestor is the message a reply actually answers. Capping from the other end would discard
34
+ * exactly the ids the lookup wants first and keep the ones it would reach last — so a long thread
35
+ * would silently stop threading on `References` and fall back to whatever `In-Reply-To` happened to
36
+ * survive. Same rule `buildReferencesHeader` follows on the way out, and RFC 5322 §3.6.4 says to trim
37
+ * this end for the same reason.
38
+ */
39
+ export declare function parseReferences(value: string | null | undefined): string[];
40
+ /**
41
+ * The ids to look a parent up by, most precise first.
42
+ *
43
+ * The order is the whole content of this function: `In-Reply-To`, then `References` from the newest
44
+ * entry backwards. A caller resolves the first one it recognizes and stops.
45
+ */
46
+ export declare function parentCandidates(inReplyTo: string | undefined, references: readonly string[]): string[];
47
+ /**
48
+ * Build the `References` header value for an outgoing reply.
49
+ *
50
+ * RFC 5322 §3.6.4: a reply's `References` is the parent's `References` followed by the parent's
51
+ * `Message-ID`. Getting this wrong is not cosmetic — it is the difference between the customer
52
+ * seeing one conversation and seeing a new mail every time somebody answers them, which is the
53
+ * single most visible way a support inbox looks broken from the outside. It is also the reason
54
+ * replying belongs in the Worker rather than in a dashboard: only the Worker holds the chain.
55
+ *
56
+ * The result is bracketed and space-separated, ready to be a header value, and bounded from the
57
+ * *front* — RFC 5322 says to drop the oldest entries when a chain has to be trimmed, because the
58
+ * recent ones are what a client threads on.
59
+ */
60
+ export declare function buildReferencesHeader(parentReferences: readonly string[], parentMessageId?: string): string;
61
+ /**
62
+ * Mint a `Message-ID` for an outgoing reply.
63
+ *
64
+ * Ours to generate, because a message we send has to be nameable by the customer's own reply — their
65
+ * client will put this value in its `In-Reply-To`, and that is how the answer comes back to the same
66
+ * thread. The domain half is taken from the address it is sent as, so the id is plausible to a
67
+ * receiving spam filter rather than pointing at a domain we do not control.
68
+ */
69
+ export declare function mintMessageId(fromAddress: string, uuid: string): string;
70
+ /**
71
+ * The subject line for a reply — `Re: ` prefixed exactly once.
72
+ *
73
+ * Match `Re:` case-insensitively and allow the bracketed count some clients add (`Re[2]:`), so
74
+ * answering a long thread does not build `Re: Re: Re: Re:`. Non-English prefixes are deliberately
75
+ * left alone: they are unbounded in practice, and a stray `Aw: Re:` is cosmetic, while stripping a
76
+ * word that happened to look like a prefix would change what the customer wrote.
77
+ */
78
+ export declare function replySubject(subject: string): string;
79
+ //# sourceMappingURL=threading.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"threading.d.ts","sourceRoot":"","sources":["../../src/mime/threading.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;GAaG;AAEH,oHAAoH;AACpH,eAAO,MAAM,cAAc,KAAK,CAAC;AAKjC;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAMvF;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,EAAE,CAW1E;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,EAAE,UAAU,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAGvG;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,EAAE,eAAe,CAAC,EAAE,MAAM,GAAG,MAAM,CAU3G;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAGvE;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGpD"}
@@ -0,0 +1,111 @@
1
+ //#region src/mime/threading.ts
2
+ /**
3
+ * RFC 5322 threading — turning `Message-ID`, `In-Reply-To`, and `References` into a conversation.
4
+ *
5
+ * **Threading is done on ids, never on the subject.** Subject matching is what makes two unrelated
6
+ * people who both wrote "Refund" land in one thread, and it is what splits a real conversation the
7
+ * moment somebody's client localizes `Re:` to `Aw:` or `Antw:`. The headers exist precisely so this
8
+ * does not have to be guessed, and every mail client sets them.
9
+ *
10
+ * The chain is tried in the order that goes from most precise to least: `In-Reply-To` names exactly
11
+ * one message, so it is asked first; `References` is the whole ancestry, so it is the fallback for a
12
+ * client that dropped `In-Reply-To` or a reply to a message that reached us out of order. Reading
13
+ * `References` **newest-first** matters — the last entry is the nearest ancestor, and starting at the
14
+ * root would attach a reply to the top of a long thread rather than to the message it answers.
15
+ */
16
+ /** The longest `References` chain kept. Bounded because the header is attacker-controlled and unbounded by spec. */
17
+ const MAX_REFERENCES = 50;
18
+ /** The longest single message id kept, after unwrapping. Anything longer is not an id a client produced. */
19
+ const MAX_ID_LENGTH = 512;
20
+ /**
21
+ * Strip the angle brackets from a message id and bound it.
22
+ *
23
+ * Stored without brackets so a lookup is plain equality: the brackets are transport syntax, and one
24
+ * path storing `<a@b>` while another queries `a@b` is a threading bug that only shows up on replies.
25
+ */
26
+ function normalizeMessageId(value) {
27
+ if (typeof value !== "string") return void 0;
28
+ const trimmed = value.trim().replace(/^<+/, "").replace(/>+$/, "").trim();
29
+ if (trimmed.length === 0 || trimmed.length > MAX_ID_LENGTH) return void 0;
30
+ return /\s/.test(trimmed) ? void 0 : trimmed;
31
+ }
32
+ /**
33
+ * Parse a `References` (or `In-Reply-To`) header into ids, oldest first, deduplicated and bounded.
34
+ *
35
+ * `postal-mime` hands `references` back as the raw header string, so the splitting is ours. Angle
36
+ * brackets are the delimiter when they are present and whitespace is the fallback when they are not,
37
+ * because a malformed header from a hand-rolled sender is a normal input here.
38
+ *
39
+ * **When the chain is over the cap, the OLDEST entries are dropped, not the newest.** That direction
40
+ * is the whole point: `parentCandidates` reads this list from the newest end backwards, because the
41
+ * nearest ancestor is the message a reply actually answers. Capping from the other end would discard
42
+ * exactly the ids the lookup wants first and keep the ones it would reach last — so a long thread
43
+ * would silently stop threading on `References` and fall back to whatever `In-Reply-To` happened to
44
+ * survive. Same rule `buildReferencesHeader` follows on the way out, and RFC 5322 §3.6.4 says to trim
45
+ * this end for the same reason.
46
+ */
47
+ function parseReferences(value) {
48
+ if (typeof value !== "string") return [];
49
+ const bracketed = [...value.matchAll(/<([^<>]+)>/g)].map((match) => match[1] ?? "");
50
+ const candidates = bracketed.length > 0 ? bracketed : value.split(/\s+/);
51
+ const seen = /* @__PURE__ */ new Set();
52
+ for (const candidate of candidates) {
53
+ const id = normalizeMessageId(candidate);
54
+ if (id) seen.add(id);
55
+ }
56
+ const ids = [...seen];
57
+ return ids.length > 50 ? ids.slice(ids.length - 50) : ids;
58
+ }
59
+ /**
60
+ * The ids to look a parent up by, most precise first.
61
+ *
62
+ * The order is the whole content of this function: `In-Reply-To`, then `References` from the newest
63
+ * entry backwards. A caller resolves the first one it recognizes and stops.
64
+ */
65
+ function parentCandidates(inReplyTo, references) {
66
+ const ordered = [...inReplyTo ? [inReplyTo] : [], ...[...references].reverse()];
67
+ return [...new Set(ordered)];
68
+ }
69
+ /**
70
+ * Build the `References` header value for an outgoing reply.
71
+ *
72
+ * RFC 5322 §3.6.4: a reply's `References` is the parent's `References` followed by the parent's
73
+ * `Message-ID`. Getting this wrong is not cosmetic — it is the difference between the customer
74
+ * seeing one conversation and seeing a new mail every time somebody answers them, which is the
75
+ * single most visible way a support inbox looks broken from the outside. It is also the reason
76
+ * replying belongs in the Worker rather than in a dashboard: only the Worker holds the chain.
77
+ *
78
+ * The result is bracketed and space-separated, ready to be a header value, and bounded from the
79
+ * *front* — RFC 5322 says to drop the oldest entries when a chain has to be trimmed, because the
80
+ * recent ones are what a client threads on.
81
+ */
82
+ function buildReferencesHeader(parentReferences, parentMessageId) {
83
+ const chain = [...parentReferences.filter((id) => id !== parentMessageId), ...parentMessageId ? [parentMessageId] : []];
84
+ const deduped = [...new Set(chain)];
85
+ return (deduped.length > 50 ? deduped.slice(deduped.length - 50) : deduped).map((id) => `<${id}>`).join(" ");
86
+ }
87
+ /**
88
+ * Mint a `Message-ID` for an outgoing reply.
89
+ *
90
+ * Ours to generate, because a message we send has to be nameable by the customer's own reply — their
91
+ * client will put this value in its `In-Reply-To`, and that is how the answer comes back to the same
92
+ * thread. The domain half is taken from the address it is sent as, so the id is plausible to a
93
+ * receiving spam filter rather than pointing at a domain we do not control.
94
+ */
95
+ function mintMessageId(fromAddress, uuid) {
96
+ return `${uuid}@${fromAddress.slice(fromAddress.lastIndexOf("@") + 1) || "localhost"}`;
97
+ }
98
+ /**
99
+ * The subject line for a reply — `Re: ` prefixed exactly once.
100
+ *
101
+ * Match `Re:` case-insensitively and allow the bracketed count some clients add (`Re[2]:`), so
102
+ * answering a long thread does not build `Re: Re: Re: Re:`. Non-English prefixes are deliberately
103
+ * left alone: they are unbounded in practice, and a stray `Aw: Re:` is cosmetic, while stripping a
104
+ * word that happened to look like a prefix would change what the customer wrote.
105
+ */
106
+ function replySubject(subject) {
107
+ const trimmed = subject.trim();
108
+ return /^re(\[\d+\])?:/i.test(trimmed) ? trimmed : `Re: ${trimmed}`;
109
+ }
110
+ //#endregion
111
+ export { MAX_REFERENCES, buildReferencesHeader, mintMessageId, normalizeMessageId, parentCandidates, parseReferences, replySubject };
@@ -0,0 +1,17 @@
1
+ /** How many bytes this string occupies as UTF-8. */
2
+ export declare function byteLength(value: string): number;
3
+ /**
4
+ * `value`, cut to at most `maxBytes` UTF-8 bytes, never mid-code-point.
5
+ *
6
+ * **Binary search, because the obvious loop is quadratic.** Walking down one code unit at a time and
7
+ * re-encoding the prefix each step is O(n) encodes of O(n) bytes, and the starting point makes it
8
+ * worse: `maxBytes` *code units* can be four times `maxBytes` *bytes*, so multi-byte text starts far
9
+ * above the answer and decrements toward it. Measured on the real constants, a 400k-character CJK
10
+ * body took 174,763 iterations and about three minutes of CPU — inside an `email()` handler, which
11
+ * the runtime kills long before that, so the message was never stored and every redelivery hit the
12
+ * same wall. A size bound that loses the message is worse than no bound.
13
+ *
14
+ * The search runs over `[0, min(length, maxBytes)]`: `maxBytes` code units is an upper bound because
15
+ * every code unit is at least one byte, and the predicate is monotone, so O(log n) encodes settle it.
16
+ */ export declare function truncateToBytes(value: string, maxBytes: number): string;
17
+ //# sourceMappingURL=truncate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"truncate.d.ts","sourceRoot":"","sources":["../../src/mime/truncate.ts"],"names":[],"mappings":"AAmBA,oDAAoD;AACpD,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEhD;AAED;;;;;;;;;;;;;GAaG,CAAC,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,CAiB3E"}
@@ -0,0 +1,47 @@
1
+ //#region src/mime/truncate.ts
2
+ /**
3
+ * Truncation that counts **bytes**, because the limits it serves are byte limits.
4
+ *
5
+ * `String.prototype.slice` counts UTF-16 code units, so a bound written as "256 KB" admits 256 K
6
+ * *characters* — three times that in bytes for CJK, four for most emoji. The bounds in this package
7
+ * exist to keep a row under D1's 2,000,000-byte ceiling, and a character-counted bound does not do
8
+ * that: a large CJK message sails through every check and then fails the insert, at which point the
9
+ * inbound handler swallows the error and the customer's mail is gone. Counting the thing the limit is
10
+ * about is the whole fix.
11
+ *
12
+ * Truncation lands on a code-point boundary, so the result is never a lone surrogate — which would be
13
+ * invalid text in the database and could break a JSON encode downstream.
14
+ */
15
+ const encoder = new TextEncoder();
16
+ /** How many bytes this string occupies as UTF-8. */
17
+ function byteLength(value) {
18
+ return encoder.encode(value).byteLength;
19
+ }
20
+ /**
21
+ * `value`, cut to at most `maxBytes` UTF-8 bytes, never mid-code-point.
22
+ *
23
+ * **Binary search, because the obvious loop is quadratic.** Walking down one code unit at a time and
24
+ * re-encoding the prefix each step is O(n) encodes of O(n) bytes, and the starting point makes it
25
+ * worse: `maxBytes` *code units* can be four times `maxBytes` *bytes*, so multi-byte text starts far
26
+ * above the answer and decrements toward it. Measured on the real constants, a 400k-character CJK
27
+ * body took 174,763 iterations and about three minutes of CPU — inside an `email()` handler, which
28
+ * the runtime kills long before that, so the message was never stored and every redelivery hit the
29
+ * same wall. A size bound that loses the message is worse than no bound.
30
+ *
31
+ * The search runs over `[0, min(length, maxBytes)]`: `maxBytes` code units is an upper bound because
32
+ * every code unit is at least one byte, and the predicate is monotone, so O(log n) encodes settle it.
33
+ */ function truncateToBytes(value, maxBytes) {
34
+ if (maxBytes <= 0) return "";
35
+ if (byteLength(value) <= maxBytes) return value;
36
+ let low = 0;
37
+ let high = Math.min(value.length, maxBytes);
38
+ while (low < high) {
39
+ const mid = Math.ceil((low + high) / 2);
40
+ if (byteLength(value.slice(0, mid)) <= maxBytes) low = mid;
41
+ else high = mid - 1;
42
+ }
43
+ const cut = value.slice(0, low);
44
+ return /[\uD800-\uDBFF]$/.test(cut) ? cut.slice(0, -1) : cut;
45
+ }
46
+ //#endregion
47
+ export { byteLength, truncateToBytes };
@@ -0,0 +1,158 @@
1
+ import type { DeclaredEnvironments } from "@pithy-sh/core/src/naming/environment";
2
+ import { type ManagedEnvironment } from "@pithy-sh/secrets/src/scope";
3
+ /**
4
+ * The provisioning orchestration for the support capability — the live counterpart to
5
+ * `pithy add support`'s config wiring.
6
+ *
7
+ * Three things have to exist before a support inbox works, and none of them can be a binding an
8
+ * adopter hand-writes: the R2 bucket attachments and raw messages land in, the prebuilt classification
9
+ * worker per environment, and — the one that actually delivers the mail — an Email Routing rule
10
+ * pointing the support address at the app worker.
11
+ *
12
+ * The live Cloudflare/wrangler steps sit behind the {@link SupportProvisioner} seam, so the
13
+ * orchestration (order, idempotency, per-env fan-out) is unit-tested without touching Cloudflare.
14
+ * Every step is idempotent; re-running is a no-op.
15
+ *
16
+ * ## The routing rule is opt-in, and that is a safety decision
17
+ *
18
+ * `ensureRoutingRule` returns `skipped: true` when no routing config is supplied, exactly as
19
+ * `@pithy-sh/email`'s does — because **enabling Email Routing on a zone points its MX at Cloudflare.**
20
+ * Creating a rule on the wrong zone would move an adopter's real inbound mail off their existing
21
+ * provider, which is not a mistake a provisioning command gets to make on their behalf. So the zone,
22
+ * the address, and the target worker are all explicit flags, and a project that has not decided yet
23
+ * provisions everything else and adds the rule later.
24
+ *
25
+ * The rule name is `<project>-global-support-inbound`, deliberately distinct from `@pithy-sh/email`'s
26
+ * `<project>-global-email-bounce`. Idempotency in `ensureWorkerRoute` keys on the rule *name*, so
27
+ * sharing one would make whichever capability provisioned second silently believe its rule already
28
+ * existed — and the project segment is what stops two Pithy projects on one zone doing the same to
29
+ * each other, with the loser's customer mail delivered to the winner's Worker.
30
+ */
31
+ /**
32
+ * The name of the Email Routing rule this capability creates, for one project. Distinct from the
33
+ * bounce handler's, and `global` in the environment slot because there is one rule per zone: the
34
+ * environments are separated by which app Worker the rule is pointed at, not by the rule.
35
+ *
36
+ * **Still on the generic composer**, and deliberately: an Email Routing rule is not a namespace
37
+ * `@pithy-sh/core/src/naming/limits` carries a verified Cloudflare cap for, and the facade exists so a
38
+ * kind of thing brings its own number rather than borrowing one. It takes the conservative default
39
+ * until that namespace lands — the same call `@pithy-sh/email`'s bounce rule makes.
40
+ */
41
+ export declare function supportRoutingRuleName(project: string): string;
42
+ /**
43
+ * The deployed Worker name for a project's environment — also its resolved config basename. Composed
44
+ * through core's naming facade under the **`worker`** namespace, so it is measured against a Worker
45
+ * script's 63 and the environment is validated on the way through. One source, so the name the CLI
46
+ * audits and deletes under cannot drift from the name it deploys under.
47
+ */
48
+ export declare function supportWorkerName(project: string, env: ManagedEnvironment): string;
49
+ /** The live Cloudflare/wrangler seam. Each step must be idempotent. */
50
+ export interface SupportProvisioner {
51
+ /**
52
+ * Verify account prerequisites before any resource is created — most importantly a registered
53
+ * `workers.dev` subdomain, which Cloudflare requires to deploy the Workflow-hosting worker.
54
+ */
55
+ preflight(): Promise<void>;
56
+ /**
57
+ * Create (or reuse) the R2 bucket attachments and raw messages live in. Idempotent.
58
+ *
59
+ * Returns `skipped: true` when the capability is configured with attachments off — a bucket nobody
60
+ * writes to is a resource an adopter did not ask for.
61
+ */
62
+ ensureBucket(): Promise<{
63
+ bucket: string;
64
+ created: boolean;
65
+ skipped: boolean;
66
+ }>;
67
+ /** Deploy the prebuilt classification worker for this environment. */
68
+ deployWorker(env: ManagedEnvironment): Promise<void>;
69
+ /**
70
+ * Create or drop the full-text index in this environment's app database, to match `search.fts`.
71
+ *
72
+ * A provisioning step rather than a migration, because the index is **derived** — every row in it
73
+ * comes from `pithy_support_messages` and `reindexThread` rebuilds it on demand. That is the line a
74
+ * migration is for: schema whose loss loses data. Keeping it here is also what makes the flag safe
75
+ * to toggle at all, since a config-conditional migration removed from the set is corruption to
76
+ * Kysely and blocks `pithy migrate` for every capability sharing the database.
77
+ */
78
+ ensureSearchIndex(env: ManagedEnvironment): Promise<{
79
+ created: boolean;
80
+ dropped: boolean;
81
+ }>;
82
+ /**
83
+ * Ensure the inbound Email Routing rule that delivers the support address to the app worker.
84
+ * Idempotent, keyed on the rule name. Returns `skipped: true` when no routing config was supplied.
85
+ */
86
+ ensureRoutingRule(): Promise<{
87
+ created: boolean;
88
+ skipped: boolean;
89
+ }>;
90
+ }
91
+ /** What provisioning produced. */
92
+ export interface SupportProvisionResult {
93
+ /** The R2 bucket, and whether it had to be created. */
94
+ bucket: {
95
+ bucket: string;
96
+ created: boolean;
97
+ skipped: boolean;
98
+ };
99
+ /** The environments a classification worker was deployed for. */
100
+ environments: ManagedEnvironment[];
101
+ /** What the full-text index did, per environment — created, dropped, or already correct. */
102
+ search: Array<{
103
+ env: ManagedEnvironment;
104
+ created: boolean;
105
+ dropped: boolean;
106
+ }>;
107
+ /** Whether the inbound routing rule was created, already present, or skipped. */
108
+ routing: {
109
+ created: boolean;
110
+ skipped: boolean;
111
+ };
112
+ }
113
+ /**
114
+ * Provision the support infrastructure.
115
+ *
116
+ * The order matters and is the inverse of how it fails: the bucket exists before a worker that could
117
+ * write to it, and **the routing rule is last** — creating it first would start delivering mail to a
118
+ * Worker whose classification host is not deployed yet, which is a window where real customer
119
+ * messages arrive and stay `uncategorized` with nothing to say why.
120
+ *
121
+ * `environments` is the project's declaration from the root `pithy.config.ts` (#241). Every declared
122
+ * environment is provisioned; an environment this skipped would be one the project deploys to with no
123
+ * resources behind it — the silence the closed `ManagedEnvironment` enum used to produce.
124
+ */
125
+ export declare function provisionSupport(provisioner: SupportProvisioner, environments: DeclaredEnvironments | readonly string[]): Promise<SupportProvisionResult>;
126
+ /** The teardown seam — the inverse of {@link SupportProvisioner}. Every step idempotent. */
127
+ export interface SupportDeprovisioner {
128
+ /** Delete the env's classification worker. Idempotent. */
129
+ deleteWorker(env: ManagedEnvironment): Promise<void>;
130
+ /** Remove the inbound routing rule, so mail stops being delivered here. Idempotent. */
131
+ removeRoutingRule(): Promise<{
132
+ removed: boolean;
133
+ }>;
134
+ /**
135
+ * Delete the R2 bucket **and everything in it** — every attachment and every raw message an adopter's
136
+ * customers ever sent. Destructive, so the orchestration only calls it when explicitly asked.
137
+ */
138
+ deleteBucket(): Promise<void>;
139
+ }
140
+ /** Teardown options. By default the bucket is **kept**: it holds correspondence, not cache. */
141
+ export interface SupportDeprovisionOptions {
142
+ /** Also delete the R2 bucket and its contents. Off by default. */
143
+ deleteStorage?: boolean;
144
+ }
145
+ /**
146
+ * Tear down the support infrastructure, reversing {@link provisionSupport}.
147
+ *
148
+ * The routing rule goes **first**, and that ordering is the whole point: stop new mail arriving before
149
+ * removing the workers that would have handled it, or messages land in a Worker with no classification
150
+ * host during the teardown. Stored correspondence is preserved unless explicitly requested — losing an
151
+ * adopter's support history to a teardown flag would be unrecoverable.
152
+ *
153
+ * `environments` is the project's declaration from the root `pithy.config.ts` (#241). Every declared
154
+ * environment is provisioned; an environment this skipped would be one the project deploys to with no
155
+ * resources behind it — the silence the closed `ManagedEnvironment` enum used to produce.
156
+ */
157
+ export declare function deprovisionSupport(deprovisioner: SupportDeprovisioner, environments: DeclaredEnvironments | readonly string[], options?: SupportDeprovisionOptions): Promise<void>;
158
+ //# sourceMappingURL=provisionSupport.d.ts.map