sideora 0.0.1-alpha.0 → 0.1.0-alpha.2

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 (221) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +57 -6
  3. package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
  4. package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
  5. package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
  6. package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
  7. package/assets/sounds/nice-chime.mp3 +0 -0
  8. package/bin/sideora.js +2430 -12
  9. package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
  10. package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
  11. package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
  12. package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
  13. package/extension/dist/assets/shell-82MNMljp.css +1 -0
  14. package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
  15. package/extension/dist/icons/icon-128.png +0 -0
  16. package/extension/dist/icons/icon-16.png +0 -0
  17. package/extension/dist/icons/icon-32.png +0 -0
  18. package/extension/dist/icons/icon-48.png +0 -0
  19. package/extension/dist/manifest.json +40 -0
  20. package/extension/dist/service-worker-loader.js +1 -0
  21. package/extension/dist/src/newtab/index.html +14 -0
  22. package/extension/dist/src/panel/index.html +15 -0
  23. package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
  24. package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
  25. package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
  26. package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
  27. package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
  28. package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
  29. package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
  30. package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
  31. package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  32. package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
  33. package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
  34. package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  35. package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
  36. package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
  37. package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
  38. package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  39. package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
  40. package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
  41. package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  42. package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  43. package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  44. package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
  45. package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
  46. package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
  47. package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
  48. package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
  49. package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  50. package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
  51. package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
  52. package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
  53. package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
  54. package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
  55. package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
  56. package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
  57. package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  58. package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
  59. package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
  60. package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
  61. package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
  62. package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
  63. package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
  64. package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
  65. package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
  66. package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
  67. package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
  68. package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
  69. package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
  70. package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
  71. package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
  72. package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
  73. package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
  74. package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
  75. package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
  76. package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
  77. package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
  78. package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
  79. package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
  80. package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
  81. package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
  82. package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
  83. package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
  84. package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
  85. package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
  86. package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
  87. package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
  88. package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
  89. package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
  90. package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
  91. package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
  92. package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
  93. package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
  94. package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
  95. package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
  96. package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
  97. package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
  98. package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
  99. package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
  100. package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
  101. package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
  102. package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
  103. package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
  104. package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
  105. package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
  106. package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
  107. package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
  108. package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
  109. package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
  110. package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
  111. package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  112. package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
  113. package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
  114. package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  115. package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
  116. package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
  117. package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
  118. package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
  119. package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
  120. package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
  121. package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
  122. package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
  123. package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
  124. package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
  125. package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
  126. package/extension/dist-web/icon-192.png +0 -0
  127. package/extension/dist-web/icon-512.png +0 -0
  128. package/extension/dist-web/index.html +25 -0
  129. package/extension/dist-web/manifest.webmanifest +14 -0
  130. package/package.json +64 -12
  131. package/plugin/.claude-plugin/icon.png +0 -0
  132. package/plugin/.claude-plugin/plugin.json +6 -0
  133. package/plugin/.mcp.json +8 -0
  134. package/plugin/README.md +72 -0
  135. package/plugin/mcp-launcher.mjs +48 -0
  136. package/src/account-probe.js +45 -0
  137. package/src/accounts.js +687 -0
  138. package/src/ai.js +269 -0
  139. package/src/assistant-runs.js +32 -0
  140. package/src/attached-mail.js +76 -0
  141. package/src/auth-gate.js +70 -0
  142. package/src/backup-cli.js +158 -0
  143. package/src/backup.js +329 -0
  144. package/src/bimi.js +233 -0
  145. package/src/bridge.js +101 -0
  146. package/src/calendar-alerts.js +56 -0
  147. package/src/chats.js +27 -0
  148. package/src/compose-editor.js +58 -0
  149. package/src/config.js +420 -0
  150. package/src/connections.d.ts +24 -0
  151. package/src/connections.js +37 -0
  152. package/src/core/agent.js +92 -0
  153. package/src/core/assistant.d.ts +13 -0
  154. package/src/core/assistant.js +790 -0
  155. package/src/core/chats.js +323 -0
  156. package/src/core/markdown.d.ts +8 -0
  157. package/src/core/markdown.js +239 -0
  158. package/src/core/notes.js +445 -0
  159. package/src/core/otp.js +152 -0
  160. package/src/core/rules.js +196 -0
  161. package/src/core/runs.d.ts +9 -0
  162. package/src/core/runs.js +211 -0
  163. package/src/core/thread.js +526 -0
  164. package/src/core/write.js +247 -0
  165. package/src/core-db.js +131 -0
  166. package/src/core.js +174 -0
  167. package/src/credentials.js +320 -0
  168. package/src/daemon.js +564 -0
  169. package/src/events.js +213 -0
  170. package/src/extension-id.d.ts +2 -0
  171. package/src/extension-id.js +5 -0
  172. package/src/file-lock.js +27 -0
  173. package/src/files-index.js +154 -0
  174. package/src/google-contacts.js +315 -0
  175. package/src/google-signin.js +306 -0
  176. package/src/host/assistant-html.js +44 -0
  177. package/src/host/chats-files.js +137 -0
  178. package/src/host/file-prep.js +122 -0
  179. package/src/host/notes-files.js +158 -0
  180. package/src/host/office-text.js +224 -0
  181. package/src/host/office-worker.js +8 -0
  182. package/src/host/rules-file.js +20 -0
  183. package/src/host/secrets-file.js +91 -0
  184. package/src/host/systemd.js +90 -0
  185. package/src/hub.js +245 -0
  186. package/src/identity.js +316 -0
  187. package/src/labels.js +5 -0
  188. package/src/mail-port.d.ts +79 -0
  189. package/src/mail-port.js +148 -0
  190. package/src/mcp-server.js +747 -0
  191. package/src/microsoft-app.js +20 -0
  192. package/src/microsoft-signin.js +194 -0
  193. package/src/migrate.js +327 -0
  194. package/src/notes-html.js +450 -0
  195. package/src/notes.js +19 -0
  196. package/src/notify.js +105 -0
  197. package/src/onepassword.js +223 -0
  198. package/src/op-registry.d.ts +14 -0
  199. package/src/op-registry.js +150 -0
  200. package/src/ops.js +1251 -0
  201. package/src/otp.js +6 -0
  202. package/src/panel-ops.js +273 -0
  203. package/src/pictures.js +735 -0
  204. package/src/postinstall.js +25 -0
  205. package/src/relay-passkey.js +122 -0
  206. package/src/relay-request.js +155 -0
  207. package/src/relay-seal.js +56 -0
  208. package/src/relay-settings.js +139 -0
  209. package/src/relay.js +876 -0
  210. package/src/render.js +82 -0
  211. package/src/rules-store.js +8 -0
  212. package/src/safe-fetch.js +215 -0
  213. package/src/sender-auth.js +270 -0
  214. package/src/site-match.js +77 -0
  215. package/src/tui-agenda.js +266 -0
  216. package/src/tui.js +670 -0
  217. package/src/vmc.js +376 -0
  218. package/src/wake.js +96 -0
  219. package/src/web-access.js +185 -0
  220. package/src/web-server.js +241 -0
  221. package/src/web-service.js +152 -0
package/src/render.js ADDED
@@ -0,0 +1,82 @@
1
+ // HTML mail → terminal text. Marketing mail is nested layout tables; html-to-
2
+ // text flattens those into readable blocks and wraps to the given width.
3
+ // Links are kept mutt-style: "[n]" after the link text, numbered list at the
4
+ // end (so a sign-in button or a tracking-wrapped URL is still reachable).
5
+
6
+ import { convert } from 'html-to-text';
7
+
8
+ /** Returns { text, links: [{ n, href, text }] }. */
9
+ export function renderHtmlWithLinks(html, { width = 100 } = {}) {
10
+ const links = [];
11
+ const byHref = new Map();
12
+ const text = convert(String(html || ''), {
13
+ wordwrap: Math.max(40, width),
14
+ preserveNewlines: false,
15
+ formatters: {
16
+ numberedLink(elem, walk, builder) {
17
+ const href = String(elem.attribs?.href || '').trim();
18
+ walk(elem.children, builder);
19
+ if (!href || /^(javascript:|#)/i.test(href)) return;
20
+ let label = textOf(elem);
21
+ if (!label) {
22
+ // image-only link (logo, social icon): use the image's alt, else drop it
23
+ label = altOf(elem);
24
+ if (!label) return;
25
+ builder.addInline(label, { noWordTransform: true });
26
+ }
27
+ let n = byHref.get(href);
28
+ if (!n) {
29
+ n = links.length + 1;
30
+ byHref.set(href, n);
31
+ links.push({ n, href, text: label.slice(0, 60) });
32
+ }
33
+ builder.addInline(`[${n}]`, { noWordTransform: true });
34
+ }
35
+ },
36
+ selectors: [
37
+ { selector: 'a', format: 'numberedLink' },
38
+ { selector: 'img', format: 'skip' },
39
+ { selector: 'table', format: 'block' },
40
+ { selector: 'tr', format: 'block' },
41
+ { selector: 'td', format: 'block' },
42
+ { selector: 'th', format: 'block' },
43
+ { selector: 'h1', options: { uppercase: false } },
44
+ { selector: 'h2', options: { uppercase: false } },
45
+ { selector: 'h3', options: { uppercase: false } },
46
+ { selector: 'hr', format: 'skip' },
47
+ { selector: 'style', format: 'skip' },
48
+ { selector: 'script', format: 'skip' }
49
+ ]
50
+ });
51
+ // drop preheader spacer lines (zero-width / non-breaking space runs) and trailing spaces
52
+ const invisible = /^[\s ​-‍⁠͏]*$/;
53
+ const body = text
54
+ .split('\n')
55
+ .map((l) => l.replace(/[​-‍⁠͏]/g, '').replace(/[ \t ]+$/g, ''))
56
+ .map((l) => (invisible.test(l) ? '' : l))
57
+ .join('\n')
58
+ .replace(/\n{3,}/g, '\n\n')
59
+ .replace(/^\n+|\n+$/g, '');
60
+ return { text: body, links };
61
+ }
62
+
63
+ /** Body text followed by the numbered link list. */
64
+ export function renderHtml(html, opts) {
65
+ const { text, links } = renderHtmlWithLinks(html, opts);
66
+ if (links.length === 0) return text;
67
+ const pad = String(links.length).length;
68
+ return text + '\n\nLinks:\n' + links.map((l) => ` [${String(l.n).padStart(pad)}] ${l.href}`).join('\n');
69
+ }
70
+
71
+ function altOf(elem) {
72
+ if (!elem) return '';
73
+ if (elem.name === 'img') return String(elem.attribs?.alt || '').replace(/\s+/g, ' ').trim();
74
+ for (const c of elem.children || []) { const a = altOf(c); if (a) return a; }
75
+ return '';
76
+ }
77
+
78
+ function textOf(elem) {
79
+ if (!elem) return '';
80
+ if (elem.type === 'text') return elem.data || '';
81
+ return (elem.children || []).map(textOf).join('').replace(/\s+/g, ' ').trim();
82
+ }
@@ -0,0 +1,8 @@
1
+ // Programmatic rule management on this Mac: the core's rules (src/core/rules.js) over rules.yaml
2
+ // (src/host/rules-file.js). The CLI, the MCP server and the panel's ops use these.
3
+
4
+ import { makeRules } from './core/rules.js';
5
+ import { rulesFile } from './host/rules-file.js';
6
+
7
+ export { SOUNDS, RUNS, CHANGED, revOf } from './core/rules.js';
8
+ export const { listRules, addRule, removeRule, updateRule, moveRule, setRuleEnabled, setQuietHours } = makeRules(rulesFile());
@@ -0,0 +1,215 @@
1
+ // Fetching a picture from a server named in mail (a BIMI logo's address, a
2
+ // sender's domain, Gravatar or Libravatar) without letting mail aim this
3
+ // machine at itself or at the network it is on:
4
+ //
5
+ // - https only, on the usual port, to a host named by a DNS name (no
6
+ // address typed in, no localhost, no .local);
7
+ // - every address the name resolves to must be public (not this machine,
8
+ // not a private, link-local, carrier-grade NAT, documentation, multicast
9
+ // or reserved range; IPv6 only within 2000::/3), and the connection goes
10
+ // to the address that was checked, not to a second lookup of the name
11
+ // (no DNS rebinding between the check and the connection);
12
+ // - a redirect is followed only to an address that passes the same checks,
13
+ // three at most;
14
+ // - one deadline for all of it (5 s), and a cap on the bytes read, checked
15
+ // against Content-Length first and then as they come;
16
+ // - the answer must be 200 and of a content type the caller accepts;
17
+ // - no cookies, no credentials, no Referer, a User-Agent that says nothing
18
+ // about who asks.
19
+
20
+ import https from 'node:https';
21
+ import net from 'node:net';
22
+ import { lookup as dnsLookup } from 'node:dns/promises';
23
+
24
+ const USER_AGENT = 'Mozilla/5.0';
25
+ const HOST = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z][a-z0-9-]{0,61}[a-z0-9]$/i;
26
+ const LOCAL_NAMES = /(^|\.)(localhost|local|localdomain|internal|intranet|lan|home|corp|home\.arpa|in-addr\.arpa|ip6\.arpa|test|invalid|example|onion)$/i;
27
+
28
+ /** A refusal. `transient`: it says nothing about the file (a timeout, a server error, no network): worth asking again later. */
29
+ export class FetchRefused extends Error {
30
+ constructor(message, transient = false) { super(message); this.name = 'FetchRefused'; this.transient = transient; }
31
+ }
32
+
33
+ /** An IPv4 address in dotted form → its four numbers, or null. */
34
+ function v4(ip) {
35
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
36
+ if (!m) return null;
37
+ const n = m.slice(1).map(Number);
38
+ return n.every((x) => x <= 255) ? n : null;
39
+ }
40
+
41
+ function publicV4([a, b, c]) {
42
+ if (a === 0 || a === 10 || a === 127) return false; // this network, private, loopback
43
+ if (a === 100 && b >= 64 && b <= 127) return false; // carrier-grade NAT
44
+ if (a === 169 && b === 254) return false; // link-local (cloud metadata lives here)
45
+ if (a === 172 && b >= 16 && b <= 31) return false;
46
+ if (a === 192 && b === 168) return false;
47
+ if (a === 192 && b === 0 && (c === 0 || c === 2)) return false; // IETF assignments, documentation
48
+ if (a === 192 && b === 88 && c === 99) return false; // 6to4 relay
49
+ if (a === 198 && (b === 18 || b === 19)) return false; // benchmarking
50
+ if (a === 198 && b === 51 && c === 100) return false;
51
+ if (a === 203 && b === 0 && c === 113) return false;
52
+ if (a >= 224) return false; // multicast, reserved, broadcast
53
+ return true;
54
+ }
55
+
56
+ /** An IPv6 address → its eight 16-bit groups, or null. */
57
+ function v6(ip) {
58
+ let s = String(ip).toLowerCase().replace(/^\[|\]$/g, '').replace(/%.*$/, '');
59
+ const tail = /^(.*:)(\d{1,3}(?:\.\d{1,3}){3})$/.exec(s);
60
+ if (tail) {
61
+ const q = v4(tail[2]);
62
+ if (!q) return null;
63
+ s = `${tail[1]}${((q[0] << 8) | q[1]).toString(16)}:${((q[2] << 8) | q[3]).toString(16)}`;
64
+ }
65
+ const halves = s.split('::');
66
+ if (halves.length > 2) return null;
67
+ const head = halves[0] ? halves[0].split(':') : [];
68
+ const rest = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
69
+ const fill = halves.length === 2 ? 8 - head.length - rest.length : 0;
70
+ if (fill < 0 || (halves.length === 1 && head.length !== 8)) return null;
71
+ const groups = [...head, ...Array(fill).fill('0'), ...rest];
72
+ if (groups.length !== 8 || groups.some((g) => !/^[0-9a-f]{1,4}$/.test(g))) return null;
73
+ return groups.map((g) => parseInt(g, 16));
74
+ }
75
+
76
+ /** Whether an address (v4 or v6) is on the public internet: not this machine, not a private or special range. */
77
+ export function isPublicAddress(ip) {
78
+ const four = v4(String(ip));
79
+ if (four) return publicV4(four);
80
+ const g = v6(ip);
81
+ if (!g) return false;
82
+ // an IPv4 address mapped into IPv6 (::ffff:a.b.c.d) is judged as that address
83
+ if (g.slice(0, 5).every((x) => x === 0) && g[5] === 0xffff) return publicV4([g[6] >> 8, g[6] & 255, g[7] >> 8]);
84
+ if ((g[0] & 0xe000) !== 0x2000) return false; // only global unicast (2000::/3): no ::1, fc00::/7, fe80::/10, ff00::/8, 64:ff9b::/96…
85
+ if (g[0] === 0x2001 && g[1] < 0x200) return false; // 2001::/23 (Teredo, benchmarking, ORCHID…)
86
+ if (g[0] === 0x2001 && g[1] === 0xdb8) return false; // documentation
87
+ if (g[0] === 0x2002) return false; // 6to4: an IPv4 address of any kind inside
88
+ if (g[0] === 0x3fff && g[1] < 0x1000) return false; // documentation (3fff::/20)
89
+ return true;
90
+ }
91
+
92
+ /** A URL a picture may be fetched from: https, the usual port, a DNS name that is not of a local network, no user or password. */
93
+ export function checkUrl(raw) {
94
+ let u;
95
+ try { u = new URL(raw); } catch { throw new FetchRefused('not a URL'); }
96
+ if (u.protocol !== 'https:') throw new FetchRefused('not https');
97
+ if (u.username || u.password) throw new FetchRefused('a URL with credentials');
98
+ if (u.port && u.port !== '443') throw new FetchRefused('not the usual port');
99
+ const host = u.hostname.toLowerCase().replace(/\.$/, '');
100
+ if (net.isIP(host.replace(/^\[|\]$/g, ''))) throw new FetchRefused('an address, not a name');
101
+ if (!HOST.test(host) || LOCAL_NAMES.test(host)) throw new FetchRefused('not a public host name');
102
+ return u;
103
+ }
104
+
105
+ /** Every address a name resolves to (as a connection would find them). */
106
+ async function resolveAll(host) {
107
+ return (await dnsLookup(host, { all: true, verbatim: true })).map((a) => ({ address: a.address, family: a.family }));
108
+ }
109
+
110
+ /**
111
+ * GET `url` → { body: Buffer, contentType, url } under the rules above.
112
+ * maxBytes the most it may weigh
113
+ * accept (contentType) => boolean: whether that kind of answer is wanted
114
+ * acceptHeader what the request says it accepts
115
+ * truncate past maxBytes, stop and keep what came (a page read for its <head>) instead of refusing
116
+ * timeoutMs for everything, redirects included (default 5000)
117
+ * allowUrl (url) => boolean: the addresses it may go to, the first and every redirect's (default: any that passes the checks)
118
+ * resolve, request for tests: the name lookup and https.request
119
+ * Throws (FetchRefused for what was refused; any error otherwise).
120
+ */
121
+ export async function safeFetch(url, { maxBytes, accept, acceptHeader = 'image/*', truncate = false, timeoutMs = 5000, maxRedirects = 3, allowUrl = null, resolve = resolveAll, request = https.request } = {}) {
122
+ if (!(maxBytes > 0) || typeof accept !== 'function') throw new TypeError('safeFetch needs maxBytes and accept');
123
+ const deadline = Date.now() + timeoutMs;
124
+ let current = url;
125
+ for (let hop = 0; ; hop++) {
126
+ const u = checkUrl(current);
127
+ if (allowUrl && !allowUrl(u.toString())) throw new FetchRefused(hop ? 'a redirect to an address it may not go to' : 'an address it may not go to');
128
+ const host = u.hostname.toLowerCase().replace(/\.$/, '');
129
+ const left = () => Math.max(1, deadline - Date.now());
130
+ let found;
131
+ try { found = await within(resolve(host), left(), 'the name did not resolve in time'); } catch (e) {
132
+ if (e instanceof FetchRefused) throw e;
133
+ // a name that does not exist is an answer; any other failure to resolve (no network) says nothing of the file
134
+ throw new FetchRefused('the name does not resolve', !['ENOTFOUND', 'ENODATA', 'NXDOMAIN'].includes(e?.code));
135
+ }
136
+ if (!found?.length) throw new FetchRefused('the name resolves to nothing');
137
+ const bad = found.find((a) => !isPublicAddress(a.address));
138
+ if (bad) throw new FetchRefused(`${host} resolves to an address that is not public`);
139
+ const target = found[0];
140
+ const res = await get(request, u, host, target, acceptHeader, left());
141
+ try {
142
+ if ([301, 302, 303, 307, 308].includes(res.statusCode)) {
143
+ const to = res.headers.location;
144
+ if (!to) throw new FetchRefused('a redirect to nowhere');
145
+ if (hop >= maxRedirects) throw new FetchRefused('too many redirects');
146
+ current = new URL(String(to), u).toString();
147
+ continue;
148
+ }
149
+ if (res.statusCode !== 200) throw new FetchRefused(`answered ${res.statusCode}`, res.statusCode >= 500 || res.statusCode === 429 || res.statusCode === 408);
150
+ const contentType = String(res.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
151
+ if (!accept(contentType)) throw new FetchRefused(`not a wanted kind of file (${contentType || 'none said'})`);
152
+ const declared = Number(res.headers['content-length']);
153
+ if (!truncate && Number.isFinite(declared) && declared > maxBytes) throw new FetchRefused('too large');
154
+ const body = await readCapped(res, maxBytes, left(), truncate);
155
+ return { body, contentType, url: u.toString() };
156
+ } finally {
157
+ res.destroy();
158
+ }
159
+ }
160
+ }
161
+
162
+ function within(promise, ms, why) {
163
+ let t;
164
+ return Promise.race([promise, new Promise((_, reject) => { t = setTimeout(() => reject(new FetchRefused(why, true)), ms); })]).finally(() => clearTimeout(t));
165
+ }
166
+
167
+ /** One request to the address that was checked (the name still goes to TLS, so the certificate is the name's). */
168
+ function get(request, u, host, target, acceptHeader, ms) {
169
+ return new Promise((resolve, reject) => {
170
+ let done = false;
171
+ const req = request({
172
+ protocol: 'https:',
173
+ hostname: host,
174
+ servername: host,
175
+ port: 443,
176
+ path: `${u.pathname}${u.search}`,
177
+ method: 'GET',
178
+ agent: false,
179
+ headers: { 'User-Agent': USER_AGENT, Accept: acceptHeader, 'Accept-Encoding': 'identity' },
180
+ // never a second lookup: the connection goes where the check said
181
+ lookup: (_name, opts, cb) => {
182
+ if (typeof opts === 'function') cb = opts;
183
+ if (opts && opts.all) cb(null, [{ address: target.address, family: target.family }]);
184
+ else cb(null, target.address, target.family);
185
+ }
186
+ }, (res) => { done = true; clearTimeout(timer); resolve(res); });
187
+ const timer = setTimeout(() => { if (!done) { req.destroy(new FetchRefused('no answer in time', true)); } }, ms);
188
+ req.on('error', (e) => { clearTimeout(timer); if (!done) reject(e); });
189
+ req.end();
190
+ });
191
+ }
192
+
193
+ function readCapped(res, maxBytes, ms, truncate = false) {
194
+ return new Promise((resolve, reject) => {
195
+ const parts = [];
196
+ let size = 0;
197
+ let ended = false;
198
+ const timer = setTimeout(() => { res.destroy(); reject(new FetchRefused('too slow', true)); }, ms);
199
+ res.on('data', (chunk) => {
200
+ size += chunk.length;
201
+ if (size > maxBytes) {
202
+ clearTimeout(timer);
203
+ ended = true;
204
+ if (truncate) { parts.push(chunk.subarray(0, chunk.length - (size - maxBytes))); resolve(Buffer.concat(parts)); } else reject(new FetchRefused('too large'));
205
+ res.destroy();
206
+ return;
207
+ }
208
+ parts.push(chunk);
209
+ });
210
+ res.on('end', () => { ended = true; clearTimeout(timer); resolve(Buffer.concat(parts)); });
211
+ res.on('error', (e) => { clearTimeout(timer); reject(e); });
212
+ // closed before its end: what came is not the whole file
213
+ res.on('close', () => { clearTimeout(timer); if (!ended) reject(new FetchRefused('cut short', true)); });
214
+ });
215
+ }
@@ -0,0 +1,270 @@
1
+ // Whether a message really comes from the domain in its From, as the
2
+ // person's OWN receiving server judged it: its DMARC verdict, read from the
3
+ // message's topmost Authentication-Results header, and only when that header
4
+ // is the receiving server's.
5
+ //
6
+ // A sender can write any Authentication-Results header it likes into a
7
+ // message: those sit below the ones the receiving servers add on the way in,
8
+ // so only the topmost counts, and only when its authserv-id names the
9
+ // account's own receiving server:
10
+ // - Gmail (an IMAP account on imap.gmail.com): mx.google.com;
11
+ // - Microsoft 365 / Outlook.com (Exchange or IMAP on outlook.office365.com,
12
+ // outlook.office.com, *.outlook.com): Exchange Online's own header, which
13
+ // has no authserv-id ("spf=pass …; dmarc=pass … header.from=…"), or one
14
+ // whose authserv-id is under outlook.com or office365.com — and either only
15
+ // on a message Exchange says came in from outside (X-MS-Exchange-
16
+ // Organization-AuthAs: Anonymous, a header Exchange strips from what
17
+ // arrives and sets itself): that mail it always stamps, so its header is
18
+ // the topmost; mail from inside the organisation it may not;
19
+ // - any other server: only the authserv-id(s) set for the account in
20
+ // config.json (accounts.<name>.authServId: "mx.example.org" or a list),
21
+ // each an exact host or, with a leading dot, every host under a domain
22
+ // (".mailhop.org": a filtering gateway's servers). On an Exchange account
23
+ // (not Microsoft 365) trusted this way the header counts only on mail
24
+ // Exchange marks as coming in the way the gateway's does
25
+ // (X-MS-Exchange-Organization-AuthAs; accounts.<name>.gatewayAuthAs,
26
+ // 'internal' by default: a gateway on an ExternalAuthoritative connector
27
+ // delivers as Internal, while a sender delivering straight to Exchange
28
+ // from the internet is Anonymous, its own AuthAs header stripped). This
29
+ // assumes only the gateway can deliver as Internal: an internal relay
30
+ // connector or an authenticated user could still forge the header, and
31
+ // Exchange should take internet mail from the gateway alone. Mail marked
32
+ // Internal that carries no Authentication-Results at all is internal mail,
33
+ // judged 'none'.
34
+ // X-MS-Exchange-Organization-AuthAs means something only on Exchange (and
35
+ // Microsoft 365 / Outlook.com): an IMAP account elsewhere never reads it.
36
+ // Gmail marks mail it fetched from another mailbox (X-Gmail-Fetch-Info): its
37
+ // servers did not receive that mail, so no header in it is theirs.
38
+ // Then the header must parse (RFC 8601: quoted strings, nested comments; a
39
+ // `;` or `dmarc=` inside either is text), hold exactly one dmarc result, and
40
+ // say dmarc=pass with header.from the sender's own domain (or, for a sender
41
+ // on a subdomain, its organisational domain, as Gmail reports it), given
42
+ // once. Anything else is not a pass: a brand picture (BIMI logo, the domain's
43
+ // icon) is never shown for it.
44
+ //
45
+ // Not covered: mail put into the mailbox without passing its receiving
46
+ // server (an import, an IMAP APPEND by another program) carries whatever
47
+ // headers it was given, a forged topmost one included.
48
+
49
+ import { getDomain } from 'tldts';
50
+
51
+ const GMAIL_IMAP = /^imap\.(gmail|googlemail)\.com$/i;
52
+ const MS_HOST = /^(outlook\.office365\.com|outlook\.office\.com|(?:[a-z0-9-]+\.)*outlook\.com)$/i;
53
+ const MS_SERV = /(^|\.)(outlook\.com|office365\.com)$/i;
54
+
55
+ /** What a server named in an account's settings is called: the host, lower case. */
56
+ function hostOf(v) {
57
+ const s = String(v || '').trim();
58
+ if (!s) return '';
59
+ try { return new URL(/^[a-z]+:\/\//i.test(s) ? s : `https://${s}`).hostname.toLowerCase(); } catch { return ''; }
60
+ }
61
+
62
+ /**
63
+ * Which Authentication-Results an account's receiving server writes:
64
+ * { ids: Set<string> (exact authserv-ids), microsoft: boolean }.
65
+ */
66
+ const jmapHost = (a) => { try { return new URL(a?.jmap?.session || '').hostname; } catch { return ''; } };
67
+ const PATTERN = /^\.?[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
68
+ export function trustOf(acct) {
69
+ const ids = new Set(); // exact hosts, and ".domain" for every host under it
70
+ const own = acct?.authServId;
71
+ for (const v of Array.isArray(own) ? own : own ? [own] : []) if (typeof v === 'string' && PATTERN.test(v.trim().toLowerCase())) ids.add(v.trim().toLowerCase());
72
+ const server = hostOf(acct?.provider === 'imap' ? acct?.imap?.host : acct?.provider === 'jmap' ? jmapHost(acct) : acct?.host);
73
+ const gmail = acct?.provider === 'imap' && GMAIL_IMAP.test(server);
74
+ if (gmail) ids.add('mx.google.com');
75
+ return { ids, microsoft: MS_HOST.test(server), gmail };
76
+ }
77
+
78
+ /** Whether an authserv-id is one of the account's: equal to an exact one, or under a ".domain" one. */
79
+ export function servIdTrusted(ids, servId) {
80
+ const id = String(servId || '').toLowerCase();
81
+ if (!id) return false;
82
+ for (const p of ids) if (p.startsWith('.') ? id.endsWith(p) && id.length > p.length : id === p) return true;
83
+ return false;
84
+ }
85
+
86
+ /** Whether X-MS-Exchange-Organization-AuthAs is the server's word on this account: Exchange, or Microsoft's own servers (elsewhere it is whatever the sender wrote). */
87
+ export function authAsMeaningful(acct) {
88
+ return acct?.provider === 'ews' || trustOf(acct).microsoft;
89
+ }
90
+
91
+ /** What AuthAs a gateway's mail must carry on an Exchange account trusted through authServId: 'internal' (default), another value, or null for no requirement ('any'). */
92
+ export function gatewayAuthAsOf(acct) {
93
+ if (acct?.provider !== 'ews' || trustOf(acct).microsoft) return null;
94
+ const v = typeof acct?.gatewayAuthAs === 'string' ? acct.gatewayAuthAs.trim().toLowerCase() : '';
95
+ if (v === 'any') return null;
96
+ return /^[a-z]{1,40}$/.test(v) ? v : 'internal';
97
+ }
98
+
99
+ /** Mail Exchange says came from inside the organisation, with no Authentication-Results at all: internal mail (on an account where AuthAs means something). */
100
+ export function isInternal(auth, acct) {
101
+ return authAsMeaningful(acct) && String(auth?.msAuthAs || '').trim().toLowerCase() === 'internal' && !(Array.isArray(auth?.results) && auth.results.length);
102
+ }
103
+
104
+ /** The version of the rule a verdict was given under: the code's, and the account's authserv-ids. A verdict of another is judged again. */
105
+ const RULE_VERSION = 6; // 6: verdicts also keep the message's BIMI selector
106
+ export function ruleOf(acct) {
107
+ const t = trustOf(acct);
108
+ return `${RULE_VERSION}:${[...t.ids].sort().join(',')}:${t.microsoft ? 'ms' : ''}:${gatewayAuthAsOf(acct) ?? 'any'}:${authAsMeaningful(acct) ? 'authas' : ''}`;
109
+ }
110
+
111
+ /** Whether anything an account receives can be judged at all (no header worth reading otherwise). */
112
+ export function canJudge(acct) {
113
+ const t = trustOf(acct);
114
+ return t.ids.size > 0 || t.microsoft;
115
+ }
116
+
117
+ /**
118
+ * The tokens of a header value (RFC 5322 / 8601): words, '=' and ';'.
119
+ * Comments ("(…)", nested, with \-escapes; a quote means nothing inside one)
120
+ * are dropped; a quoted string (with \-escapes) is text, joined to what touches
121
+ * it into one word (`"a;b"@c` is the word a;b@c), marked `q`. A ';' or '='
122
+ * counts only outside both. null when anything is left open or a ')' closes
123
+ * nothing.
124
+ */
125
+ export function tokenize(value) {
126
+ const s = String(value ?? '');
127
+ const out = [];
128
+ let word = null;
129
+ const end = () => { if (word) { out.push(word); word = null; } };
130
+ let i = 0;
131
+ while (i < s.length) {
132
+ const ch = s[i];
133
+ if (ch === '(') {
134
+ end();
135
+ let depth = 1;
136
+ i++;
137
+ while (i < s.length && depth) {
138
+ const c = s[i];
139
+ if (c === '\\') { i += 2; continue; }
140
+ if (c === '(') depth++;
141
+ else if (c === ')') depth--;
142
+ i++;
143
+ }
144
+ if (depth) return null;
145
+ continue;
146
+ }
147
+ if (ch === ')') return null;
148
+ if (ch === '"') {
149
+ let v = '';
150
+ let closed = false;
151
+ i++;
152
+ while (i < s.length) {
153
+ const c = s[i];
154
+ if (c === '\\') { if (i + 1 >= s.length) return null; v += s[i + 1]; i += 2; continue; }
155
+ if (c === '"') { closed = true; i++; break; }
156
+ v += c;
157
+ i++;
158
+ }
159
+ if (!closed) return null;
160
+ word = word ? { t: 'word', v: word.v + v, q: true } : { t: 'word', v, q: true };
161
+ continue;
162
+ }
163
+ if (/\s/.test(ch)) { end(); i++; continue; }
164
+ if (ch === ';' || ch === '=') { end(); out.push({ t: ch }); i++; continue; }
165
+ word = word ? { ...word, v: word.v + ch } : { t: 'word', v: ch, q: false };
166
+ i++;
167
+ }
168
+ end();
169
+ return out;
170
+ }
171
+
172
+ const KEY = /^[a-z0-9][a-z0-9_.-]*$/i;
173
+ const METHOD = /^([a-z0-9][a-z0-9_-]*)(?:\/\d+)?$/i;
174
+
175
+ /**
176
+ * One Authentication-Results value → { servId: string | null, results: [{ method, result, props }], dmarcCount },
177
+ * or null when it does not parse. servId is null where the header starts with a result (Exchange Online's form).
178
+ * Strict: each result is method=result followed by key=value pairs, a key never twice.
179
+ */
180
+ export function parseAuthResults(value) {
181
+ const tokens = tokenize(value);
182
+ if (!tokens || !tokens.length) return null;
183
+ // every dmarc= outside quotes and comments, wherever it stands
184
+ let dmarcCount = 0;
185
+ tokens.forEach((t, k) => { if (t.t === 'word' && !t.q && /^dmarc(\/\d+)?$/i.test(t.v) && tokens[k + 1]?.t === '=') dmarcCount++; });
186
+ const segments = [[]];
187
+ for (const t of tokens) { if (t.t === ';') segments.push([]); else segments[segments.length - 1].push(t); }
188
+ let servId = null;
189
+ const first = segments[0];
190
+ if (!first.length) return null;
191
+ if (!first.some((t) => t.t === '=')) {
192
+ // authserv-id [version]
193
+ if (first.length > 2 || first.some((t) => t.t !== 'word' || t.q) || !KEY.test(first[0].v) || (first[1] && !/^\d+$/.test(first[1].v))) return null;
194
+ servId = first[0].v.toLowerCase();
195
+ segments.shift();
196
+ }
197
+ const results = [];
198
+ for (const seg of segments) {
199
+ if (!seg.length) continue;
200
+ if (seg.length === 1 && seg[0].t === 'word' && !seg[0].q && seg[0].v.toLowerCase() === 'none') continue;
201
+ if (seg.length % 3) return null;
202
+ const pairs = [];
203
+ for (let k = 0; k < seg.length; k += 3) {
204
+ const [a, eq, b] = seg.slice(k, k + 3);
205
+ if (a.t !== 'word' || a.q || eq.t !== '=' || b.t !== 'word') return null;
206
+ pairs.push([a.v, b]);
207
+ }
208
+ const [[methodWord, resultTok], ...rest] = pairs;
209
+ const m = METHOD.exec(methodWord);
210
+ if (!m || resultTok.q || !/^[a-z0-9_-]+$/i.test(resultTok.v)) return null;
211
+ const props = {};
212
+ for (const [k, v] of rest) {
213
+ const key = k.toLowerCase();
214
+ if (!KEY.test(key) || Object.hasOwn(props, key)) return null;
215
+ props[key] = v.v.toLowerCase();
216
+ }
217
+ results.push({ method: m[1].toLowerCase(), result: resultTok.v.toLowerCase(), props });
218
+ }
219
+ return { servId, results, dmarcCount };
220
+ }
221
+
222
+ const domainOf = (email) => { const s = String(email || '').trim().toLowerCase(); const at = s.lastIndexOf('@'); return at > 0 ? s.slice(at + 1).replace(/\.$/, '') : ''; };
223
+
224
+ /**
225
+ * The DMARC verdict of a message for an account:
226
+ * 'pass' its receiving server says dmarc=pass for the sender's own domain
227
+ * 'fail' | 'none' | 'temperror' | 'permerror' | … what that server said otherwise
228
+ * 'mismatch' a pass, but for another domain than the From's
229
+ * 'absent' no Authentication-Results at all, or none that says dmarc
230
+ * 'untrusted' the topmost header is not the account's receiving server's, does not parse, or is ambiguous
231
+ * `auth`: { results: [topmost first], msAuthAs, gmailFetchInfo } (mailcore's authHeaders).
232
+ */
233
+ export function dmarcVerdict(auth, acct, fromEmail) {
234
+ const list = Array.isArray(auth?.results) ? auth.results : [];
235
+ const t = trustOf(acct);
236
+ if (t.gmail && String(auth?.gmailFetchInfo || '').trim()) return 'untrusted'; // fetched by Gmail from elsewhere: not received by it
237
+ if (!list.length) return isInternal(auth, acct) ? 'none' : 'absent';
238
+ const top = parseAuthResults(list[0]);
239
+ if (!top) return 'untrusted';
240
+ const authAs = String(auth?.msAuthAs || '').trim().toLowerCase();
241
+ const fromOutside = authAs === 'anonymous';
242
+ const gateway = gatewayAuthAsOf(acct);
243
+ const trusted = top.servId != null
244
+ ? (servIdTrusted(t.ids, top.servId) && (gateway == null || authAs === gateway)) || (t.microsoft && fromOutside && MS_SERV.test(top.servId))
245
+ : t.microsoft && fromOutside;
246
+ if (!trusted) return 'untrusted';
247
+ const dmarcs = top.results.filter((r) => r.method === 'dmarc');
248
+ if (top.dmarcCount === 0 && dmarcs.length === 0) return 'absent';
249
+ if (top.dmarcCount !== 1 || dmarcs.length !== 1) return 'untrusted';
250
+ const dmarc = dmarcs[0];
251
+ if (dmarc.result !== 'pass') return dmarc.result;
252
+ const from = domainOf(fromEmail);
253
+ return from && fromMatches(String(dmarc.props['header.from'] || '').toLowerCase(), from) ? 'pass' : 'mismatch';
254
+ }
255
+
256
+ /**
257
+ * The domain DMARC was judged for, as the receiving server names it, is the
258
+ * From's own, or (Gmail names the organisational domain whose policy covered a
259
+ * subdomain: From @email.api.x.ai, header.from=x.ai) the From's organisational
260
+ * domain, when the From is a subdomain of it. Never a sibling, nor anything
261
+ * between the two.
262
+ */
263
+ export function fromMatches(headerFrom, from) {
264
+ if (!headerFrom || !from) return false;
265
+ if (headerFrom === from) return true;
266
+ const org = getDomain(from, { allowPrivateDomains: true });
267
+ return !!org && headerFrom === org && from.endsWith(`.${org}`);
268
+ }
269
+
270
+ export { domainOf };
@@ -0,0 +1,77 @@
1
+ // Whether a website of a 1Password item is the site of a mail server: what
2
+ // lets the panel link an item to an account (src/accounts.js). The rule:
3
+ //
4
+ // - the same host; or
5
+ // - the same registrable domain, by the full Public Suffix List, its
6
+ // private section included (tldts): imap.example.com ~ www.example.com,
7
+ // mail.example.co.uk ~ example.co.uk; never victim.uk.com ~ evil.uk.com,
8
+ // a.synology.me ~ b.synology.me, x.eu.org ~ y.eu.org (each is someone's own); or
9
+ // - two registrable domains of the same provider (gmail.com ~ google.com …, below).
10
+ //
11
+ // A host with no registrable domain (an address, a bare suffix, a name the
12
+ // list does not know) matches only itself, as does one under a wildcard-DNS
13
+ // service the list leaves out (nip.io, sslip.io …): anyone can have a name there.
14
+ //
15
+ // Item websites are http(s) addresses or bare host names; any other scheme
16
+ // (android://, ios-app://, mailto: …) is not a website and matches nothing.
17
+
18
+ import { parse } from 'tldts';
19
+
20
+ // wildcard DNS: every name resolves to the address it spells, under one registrable domain
21
+ const SHARED_DOMAINS = new Set(['nip.io', 'sslip.io', 'xip.io', 'nip.direct', 'traefik.me', 'localtest.me', 'lvh.me', 'local.gd', 'vcap.me', 'lacolhost.com']);
22
+ // one provider's domains, signed in to with the same account (each a registrable domain of its own: test/credentials.test.js checks)
23
+ export const SAME_PROVIDER = [
24
+ ['gmail.com', 'googlemail.com', 'google.com'],
25
+ ['icloud.com', 'me.com', 'mac.com', 'apple.com'],
26
+ ['outlook.com', 'hotmail.com', 'live.com', 'office365.com', 'microsoft.com', 'microsoftonline.com', 'office.com'],
27
+ ['yahoo.com', 'ymail.com', 'rocketmail.com']
28
+ ];
29
+ const PROVIDER_OF = new Map(SAME_PROVIDER.flatMap((group, i) => group.map((d) => [d, `provider:${i}`])));
30
+
31
+ const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
32
+
33
+ /**
34
+ * The host of a website or server as typed ("https://mail.x.com/owa",
35
+ * "imap.x.com", "x.com:993", "user@host"): lowercased, trailing dot gone,
36
+ * IDN as punycode, port and user info stripped. '' when it is none, or an
37
+ * address of another scheme than http(s).
38
+ */
39
+ export function hostOf(v) {
40
+ let s = String(v ?? '').trim();
41
+ if (!s) return '';
42
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(s);
43
+ if (scheme) {
44
+ if (!/^https?$/i.test(scheme[1])) return '';
45
+ } else if (/^[a-z][a-z0-9+.-]*:(?!\d+(?:[/?#]|$))/i.test(s)) {
46
+ return ''; // mailto:, android-app:, tel: … — not a website
47
+ } else {
48
+ s = `https://${s}`;
49
+ }
50
+ let host;
51
+ try { host = new URL(s).hostname; } catch { return ''; }
52
+ host = host.toLowerCase().replace(/\.+$/, '');
53
+ if (!host || host.includes(':') || host.startsWith('[')) return ''; // IPv6: never a site of an item here
54
+ return host;
55
+ }
56
+
57
+ /** The registrable domain of a host by the Public Suffix List (private section included); null when it has none. */
58
+ export function registrableDomain(host) {
59
+ const h = hostOf(host);
60
+ if (!h || IPV4.test(h)) return null;
61
+ const r = parse(h, { allowPrivateDomains: true });
62
+ // a suffix the list does not know (matched by its default rule only) is no ground for a domain
63
+ if (!r.domain || (!r.isIcann && !r.isPrivate) || SHARED_DOMAINS.has(r.domain)) return null;
64
+ return r.domain;
65
+ }
66
+
67
+ /** Whether a website's host and a server's (or an address's domain) are the same site, by the rule above. */
68
+ export function sameSite(a, b) {
69
+ const x = hostOf(a);
70
+ const y = hostOf(b);
71
+ if (!x || !y) return false;
72
+ if (x === y) return true;
73
+ const dx = registrableDomain(x);
74
+ const dy = registrableDomain(y);
75
+ if (!dx || !dy) return false; // no registrable domain: the exact host only
76
+ return (PROVIDER_OF.get(dx) ?? dx) === (PROVIDER_OF.get(dy) ?? dy);
77
+ }