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
@@ -0,0 +1,735 @@
1
+ // Sender pictures: what the panel shows in place of a sender's initials,
2
+ // looked up here (the bridge or the daemon, never the browser), cached, and
3
+ // handed over as small data: URLs. For each sender, the first that is found:
4
+ //
5
+ // 1. the organisation's photo of the address (Exchange: GetUserPhoto),
6
+ // for an address of an Exchange account's own domain or of its
7
+ // contacts; else the photo of a Google contact with that address (one
8
+ // someone chose, never Google's placeholder; google-contacts.js), from
9
+ // googleusercontent.com only;
10
+ // 2. the BIMI logo of the sender's organisational domain: DNS TXT
11
+ // <selector>._bimi.<domain>, the selector the message's BIMI-Selector
12
+ // header names (a DNS label; else, or when that record is missing,
13
+ // default). With a= naming a valid mark certificate (vmc.js), the logo
14
+ // inside the certificate; else the l= SVG; cleaned either way (bimi.js);
15
+ // 3. Gravatar, then Libravatar, by a SHA-256 of the address: only when the
16
+ // setting is on (off by default: they learn a hash of the address);
17
+ // Libravatar's server is the one the sender's domain names (DNS SRV) only
18
+ // for a domain the person corresponds with, the default one otherwise;
19
+ // 4. the organisational domain's own icon (/apple-touch-icon.png,
20
+ // /favicon.ico, or the icon its home page names), for a domain the person
21
+ // corresponds with; for another one, its icon through DuckDuckGo's icon
22
+ // service (never the domain itself; a setting, on by default);
23
+ // 5. nothing: the panel keeps the initials.
24
+ // Brand pictures (2 and 4) need a message whose DMARC passed as the account's
25
+ // own receiving server says (sender-auth.js): a forged mail never shows one.
26
+ // Then a logo with a valid mark certificate is shown for any such sender (a
27
+ // VMC ties it to a registered trademark; a CMC, accepted too, only to a mark in
28
+ // prior use or a government's, and proves less; either way a CA checked who
29
+ // holds the domain); an l= logo or an icon only for a domain the
30
+ // person corresponds with (exactly: one they sent mail to, To only, twice or
31
+ // two weeks ago; one of their contacts', Exchange or Google — saved contacts,
32
+ // not Google's "other contacts"; their own). DMARC proves the domain,
33
+ // not the brand: paypa1-secure.com can pass and publish PayPal's logo. Free-mail
34
+ // domains (gmail.com…: people, not brands) never have one. For a passing
35
+ // message of a stranger's domain only its BIMI record is read (and the
36
+ // certificate it names): one DNS question a week per organisational domain.
37
+ // A person's picture (1, 3) beside a message needs that message to have passed
38
+ // for that very domain, or to be internal Exchange mail; without a message (People) it is shown for whom it is.
39
+ // Every fetch goes through safe-fetch.js. Each external request checks the
40
+ // settings as they are at that moment: turned off, what is queued stops.
41
+ //
42
+ // The cache: the core's encrypted database (src/core-db.js: two tables,
43
+ // keys hashed), in memory when there is none. A picture found is kept 7
44
+ // days, none found 1 day. The DMARC verdict of a message is kept with it:
45
+ // recorded by the daemon when it fetches new mail whole, or asked for here
46
+ // (headers only) when a picture needs it.
47
+
48
+ import crypto from 'node:crypto';
49
+ import { idParts } from 'mailcore';
50
+ import { canJudge, dmarcVerdict, ruleOf, isInternal, domainOf } from './sender-auth.js';
51
+ import { MAX_PEM, checkMarkCertificate } from './vmc.js';
52
+ import { bimiSelectorOf, parseBimiRecord, sanitizeSvg, MAX_SVG } from './bimi.js';
53
+
54
+ export const FOUND_DAYS = 7;
55
+ export const NONE_DAYS = 1;
56
+ const AUTH_DAYS = 60;
57
+ const MAX_RASTER = 256 * 1024;
58
+ const MAX_PAGE = 64 * 1024;
59
+ const MAX_ITEMS = 60;
60
+ const EMAIL = /^[^\s@<>"(),;:\\]{1,64}@[a-z0-9.-]{1,253}\.[a-z]{2,63}$/i;
61
+
62
+ // --- settings ------------------------------------------------------------------------
63
+
64
+ /** config.json's "pictures": { enabled (default on), gravatar (default off) }. */
65
+ export function pictureSettings(config) {
66
+ const p = config?.pictures && typeof config.pictures === 'object' ? config.pictures : {};
67
+ return { enabled: p.enabled !== false, gravatar: p.gravatar === true, otherIcons: p.otherIcons !== false };
68
+ }
69
+
70
+ // --- shared platforms ----------------------------------------------------------------
71
+ // Domains whose subdomains are their customers' (anyone can have one), which the Public Suffix List does not list
72
+ // apart: a sender at x.zendesk.com is not Zendesk.
73
+ export const SHARED_PLATFORMS = new Set(['zendesk.com', 'freshdesk.com', 'salesforce.com', 'force.com', 'my.salesforce.com', 'sendgrid.net', 'mailgun.org',
74
+ 'mailgun.net', 'atlassian.net', 'onmicrosoft.com', 'sharepoint.com', 'service-now.com', 'appspotmail.com', 'godaddysites.com', 'slack.com', 'hubspotemail.net',
75
+ 'mailchimpapp.com', 'mcsv.net', 'amazonses.com', 'helpscoutapp.com', 'intercom-mail.com', 'zohodesk.com', 'myshopify.com', 'wixsite.com', 'squarespace.com',
76
+ 'webflow.io', 'notion.site', 'substack.com', 'beehiiv.com', 'ghost.io', 'freshservice.com', 'zendesk.eu', 'kustomerapp.com', 'gorgias.help']);
77
+
78
+ // --- free mail -----------------------------------------------------------------------
79
+
80
+ const FREE_MAIL = new Set(['gmail.com', 'googlemail.com', 'outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'passport.com', 'icloud.com', 'me.com', 'mac.com',
81
+ 'aol.com', 'aim.com', 'proton.me', 'protonmail.com', 'protonmail.ch', 'pm.me', 'mail.com', 'email.com', 'zoho.com', 'zohomail.com', 'fastmail.com', 'fastmail.fm',
82
+ 'tutanota.com', 'tutanota.de', 'tuta.io', 'tuta.com', 'hey.com', 'mail.ru', 'inbox.ru', 'bk.ru', 'list.ru', 'qq.com', '163.com', '126.com', 'yeah.net', 'sina.com',
83
+ 'web.de', 'laposte.net', 'orange.fr', 'wanadoo.fr', 'free.fr', 'sfr.fr', 'libero.it', 'virgilio.it', 't-online.de', 'freenet.de', 'btinternet.com', 'sky.com',
84
+ 'comcast.net', 'att.net', 'sbcglobal.net', 'verizon.net', 'cox.net', 'hushmail.com', 'posteo.de', 'posteo.net', 'mailbox.org', 'seznam.cz', 'naver.com',
85
+ 'daum.net', 'rediffmail.com', 'ya.ru', 'rambler.ru', 'skiff.com', 'duck.com', 'mailfence.com', 'runbox.com', 'disroot.org', 'riseup.net', 'bluewin.ch', 'telenet.be']);
86
+ const FREE_MAIL_NAMES = /^(yahoo|ymail|rocketmail|gmx|yandex|hotmail|outlook|live|windowslive|aol|msn|googlemail|gmail)\./;
87
+
88
+ /** A domain whose addresses are people's, not a brand's (the domain, or the one it belongs to). */
89
+ export function isFreeMail(domain, orgDomain = domain) {
90
+ const d = String(domain || '').toLowerCase();
91
+ const o = String(orgDomain || d).toLowerCase();
92
+ return FREE_MAIL.has(d) || FREE_MAIL.has(o) || FREE_MAIL_NAMES.test(o) || FREE_MAIL_NAMES.test(d);
93
+ }
94
+
95
+ // --- the cache -----------------------------------------------------------------------
96
+
97
+ const SCHEMA = `
98
+ CREATE TABLE IF NOT EXISTS mw_pictures (key TEXT PRIMARY KEY, at INTEGER NOT NULL, mime TEXT, data BLOB);
99
+ CREATE TABLE IF NOT EXISTS mw_sender_auth (id TEXT PRIMARY KEY, at INTEGER NOT NULL, domain TEXT, dmarc TEXT NOT NULL, rule TEXT NOT NULL, internal INTEGER NOT NULL DEFAULT 0, selector TEXT NOT NULL DEFAULT 'default');
100
+ `;
101
+ const hashed = (key) => crypto.createHash('sha256').update(key).digest('hex');
102
+
103
+ /**
104
+ * Where pictures and verdicts are kept: the database `open()` returns (the
105
+ * encrypted cache), else memory. get → { at, mime, data } (mime null: none
106
+ * found) | null; put(key, { mime, data }); drop(key); getAuth(id) → { at, domain, dmarc, rule, internal } | null; putAuth(id, rec).
107
+ */
108
+ export function pictureStore({ open = () => null, now = Date.now } = {}) {
109
+ const mem = { pics: new Map(), auth: new Map() };
110
+ const ready = new WeakSet();
111
+ let writes = 0;
112
+ const db = () => {
113
+ try {
114
+ const d = open();
115
+ if (d && !ready.has(d)) {
116
+ d.exec(SCHEMA);
117
+ // a table made by an earlier version: the column it lacks (its rows carry an older rule, and are judged again)
118
+ for (const col of ["internal INTEGER NOT NULL DEFAULT 0", "selector TEXT NOT NULL DEFAULT 'default'"]) {
119
+ try { d.exec(`ALTER TABLE mw_sender_auth ADD COLUMN ${col}`); } catch (e) { if (!/duplicate column/i.test(e.message)) throw e; }
120
+ }
121
+ ready.add(d);
122
+ }
123
+ return d || null;
124
+ } catch { return null; }
125
+ };
126
+ const prune = (d) => {
127
+ if (++writes % 50) return;
128
+ try {
129
+ d.prepare('DELETE FROM mw_pictures WHERE at < ?').run(now() - FOUND_DAYS * 86400e3);
130
+ d.prepare('DELETE FROM mw_sender_auth WHERE at < ?').run(now() - AUTH_DAYS * 86400e3);
131
+ } catch { /* next time */ }
132
+ };
133
+ return {
134
+ get(key) {
135
+ const k = hashed(key);
136
+ const d = db();
137
+ if (!d) return mem.pics.get(k) ?? null;
138
+ try { const r = d.prepare('SELECT at, mime, data FROM mw_pictures WHERE key = ?').get(k); return r ? { at: r.at, mime: r.mime, data: r.data } : null; } catch { return mem.pics.get(k) ?? null; }
139
+ },
140
+ put(key, { mime = null, data = null } = {}) {
141
+ const k = hashed(key);
142
+ const row = { at: now(), mime: mime || null, data: mime ? data : null };
143
+ const d = db();
144
+ if (!d) { mem.pics.set(k, row); return; }
145
+ try {
146
+ d.prepare('INSERT INTO mw_pictures (key, at, mime, data) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET at = excluded.at, mime = excluded.mime, data = excluded.data').run(k, row.at, row.mime, row.data);
147
+ prune(d);
148
+ } catch { mem.pics.set(k, row); }
149
+ },
150
+ drop(key) {
151
+ const k = hashed(key);
152
+ mem.pics.delete(k);
153
+ const d = db();
154
+ if (d) { try { d.prepare('DELETE FROM mw_pictures WHERE key = ?').run(k); } catch { /* pruned later */ } }
155
+ },
156
+ getAuth(id) {
157
+ const d = db();
158
+ if (!d) return mem.auth.get(id) ?? null;
159
+ try { const r = d.prepare('SELECT at, domain, dmarc, rule, internal, selector FROM mw_sender_auth WHERE id = ?').get(id); return r ? { ...r, internal: !!r.internal } : null; } catch { return mem.auth.get(id) ?? null; }
160
+ },
161
+ putAuth(id, { domain = '', dmarc, rule, internal = false, selector = 'default' }) {
162
+ const row = { at: now(), domain, dmarc, rule: String(rule || ''), internal: !!internal, selector: String(selector || 'default') };
163
+ const d = db();
164
+ if (!d) { mem.auth.set(id, row); return; }
165
+ try {
166
+ d.prepare('INSERT INTO mw_sender_auth (id, at, domain, dmarc, rule, internal, selector) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET at = excluded.at, domain = excluded.domain, dmarc = excluded.dmarc, rule = excluded.rule, internal = excluded.internal, selector = excluded.selector').run(id, row.at, domain, dmarc, row.rule, row.internal ? 1 : 0, row.selector);
167
+ prune(d);
168
+ } catch { mem.auth.set(id, row); }
169
+ }
170
+ };
171
+ }
172
+
173
+ /** A kept picture still worth its word: found within FOUND_DAYS, or none found within NONE_DAYS. */
174
+ export function fresh(entry, now = Date.now()) {
175
+ if (!entry) return false;
176
+ return now - entry.at < (entry.mime ? FOUND_DAYS : NONE_DAYS) * 86400e3;
177
+ }
178
+
179
+ // --- images --------------------------------------------------------------------------
180
+
181
+ /** What a raster file is, by its first bytes (never by what the server says): a MIME type, or null. */
182
+ export function sniffRaster(buf) {
183
+ if (!Buffer.isBuffer(buf) || buf.length < 12) return null;
184
+ if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'image/png';
185
+ if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
186
+ const head = buf.subarray(0, 6).toString('latin1');
187
+ if (head === 'GIF87a' || head === 'GIF89a') return 'image/gif';
188
+ if (buf.subarray(0, 4).toString('latin1') === 'RIFF' && buf.subarray(8, 12).toString('latin1') === 'WEBP') return 'image/webp';
189
+ if (buf.readUInt32BE(0) === 0x00000100 && buf.readUInt16LE(4) > 0) return 'image/x-icon';
190
+ return null;
191
+ }
192
+
193
+ const RASTER_TYPES = new Set(['image/png', 'image/jpeg', 'image/jpg', 'image/pjpeg', 'image/gif', 'image/webp', 'image/x-icon', 'image/vnd.microsoft.icon', 'image/ico', 'image/icon']);
194
+ const isRasterType = (ct) => RASTER_TYPES.has(ct);
195
+
196
+ /** The <link rel=…icon…> a home page names, best first (apple-touch-icon, then the largest icon); SVG left out. */
197
+ export function iconLinks(html, base) {
198
+ const out = [];
199
+ for (const tag of String(html).match(/<link\b[^>]*>/gi) || []) {
200
+ const attr = (n) => { const m = new RegExp(`\\s${n}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i').exec(tag); return m ? (m[1] ?? m[2] ?? m[3] ?? '').trim() : ''; };
201
+ const rel = attr('rel').toLowerCase().split(/\s+/);
202
+ const href = attr('href');
203
+ if (!href || /\.svg(\?|#|$)/i.test(href) || /svg/i.test(attr('type'))) continue;
204
+ const apple = rel.includes('apple-touch-icon') || rel.includes('apple-touch-icon-precomposed');
205
+ if (!apple && !rel.includes('icon')) continue;
206
+ let url;
207
+ try { url = new URL(href, base); } catch { continue; }
208
+ if (url.protocol !== 'https:') continue;
209
+ const size = Math.max(0, ...attr('sizes').split(/\s+/).map((s) => Number(s.split('x')[0]) || 0));
210
+ out.push({ url: url.toString(), rank: (apple ? 10000 : 0) + Math.min(size, 512) });
211
+ }
212
+ return out.sort((a, b) => b.rank - a.rank).map((x) => x.url).filter((u, i, all) => all.indexOf(u) === i).slice(0, 3);
213
+ }
214
+
215
+ // --- small tools ---------------------------------------------------------------------
216
+
217
+ /**
218
+ * At most `n` at once. A job is started inside a promise (Promise.resolve().then(fn)), so one that throws at
219
+ * once, before any await, still settles its caller's promise and frees its slot; nothing is left unhandled.
220
+ */
221
+ export function limiter(n) {
222
+ let active = 0;
223
+ const queue = [];
224
+ const next = () => {
225
+ while (active < n && queue.length) {
226
+ active++;
227
+ const { fn, resolve, reject } = queue.shift();
228
+ Promise.resolve().then(fn).then(resolve, reject).finally(() => { active--; next(); });
229
+ }
230
+ };
231
+ return (fn) => new Promise((resolve, reject) => { queue.push({ fn, resolve, reject }); next(); });
232
+ }
233
+
234
+ /** One run per key at a time: a second ask waits for the first. */
235
+ function onceAtATime() {
236
+ const running = new Map();
237
+ return (key, fn) => {
238
+ if (running.has(key)) return running.get(key);
239
+ const p = Promise.resolve().then(fn);
240
+ running.set(key, p);
241
+ p.then(() => running.delete(key), () => running.delete(key)); // handled here; the caller handles p
242
+ return p;
243
+ };
244
+ }
245
+
246
+ const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
247
+ const dataUrl = (mime, data) => `data:${mime};base64,${Buffer.from(data).toString('base64')}`;
248
+
249
+ // --- the lookups ---------------------------------------------------------------------
250
+
251
+ const AUTH_CODES = new Set(['EWS_AUTH', 'MAIL_AUTH', 'PICTURES_AUTH']);
252
+ const isAuth = (e) => AUTH_CODES.has(e?.code);
253
+ const CONNECTION_CODES = new Set(['ECONNREFUSED', 'ECONNRESET', 'ETIMEDOUT', 'EHOSTUNREACH', 'ENETUNREACH', 'ENOTFOUND', 'EAI_AGAIN', 'EPIPE', 'ECONNABORTED', 'ESOCKETTIMEDOUT', 'ETIMEOUT', 'NoConnection']);
254
+ const isConnection = (e) => CONNECTION_CODES.has(e?.code) || /socket hang up|timed? ?out|connection (?:closed|lost|refused)|getaddrinfo/i.test(String(e?.message || ''));
255
+ const TLS_ERROR = /^(ERR_TLS_|ERR_SSL_|ERR_OSSL_|CERT_|UNABLE_TO_|DEPTH_ZERO_|SELF_SIGNED_|HOSTNAME_MISMATCH)/;
256
+ /**
257
+ * An answer that there is nothing, kept a day: a refusal (404, not an image, too large…), an SVG or a mark
258
+ * certificate refused, a name that does not exist, a server that refuses the connection or whose TLS is wrong.
259
+ * A timeout, a 5xx, a dropped connection, a turned-off setting: not kept, asked again next time.
260
+ */
261
+ export const definitiveMiss = (e) => ['SvgRefused', 'VmcRefused'].includes(e?.name) || (e?.name === 'FetchRefused' && !e.transient)
262
+ || ['ENOTFOUND', 'ENODATA', 'NXDOMAIN', 'ECONNREFUSED'].includes(e?.code) || TLS_ERROR.test(String(e?.code || ''));
263
+ const skipped = () => Object.assign(new Error('not asked'), { name: 'Skipped' });
264
+ const KNOWN_SENT_TIMES = 2; // a domain mailed this many times…
265
+ const KNOWN_SENT_DAYS = 14; // …or once, this long ago, is one the person corresponds with
266
+
267
+ /**
268
+ * A picture finder over its dependencies (all injected, for tests):
269
+ * config() config.json, read (accounts, pictures)
270
+ * withClient(account, fn) fn(client) for a mail account (mailcore)
271
+ * store pictureStore()
272
+ * fetch(url, opts) safeFetch
273
+ * resolveTxt(name), resolveSrv(name) DNS
274
+ * verifyVmc(pem, { domain, orgDomain }) the logo SVG of a valid mark certificate, or a throw (vmc.js)
275
+ * orgDomain(domain) the organisational domain (Public Suffix List, private domains too)
276
+ * googleContacts() → { byEmail: Map<lower email, { kind, photo? }> }: the Google contacts kept (google-contacts.js)
277
+ * log(msg)
278
+ */
279
+ export function createPictures({ config, withClient, store, fetch, resolveTxt, resolveSrv, verifyVmc = checkMarkCertificate, orgDomain = (d) => d, googleContacts = null, now = Date.now, log = () => {} }) {
280
+ const netLimit = limiter(6); // fetches and DNS, all senders together
281
+ const photoLimit = limiter(3); // GetUserPhoto, all lookups and accounts together
282
+ const once = onceAtATime();
283
+ const accountMemo = new Map(); // key → { at, ms, value }
284
+ const memo = (key, ms, fn, failMs = 10 * 60e3, empty = () => new Set()) => once(`memo:${key}`, async () => {
285
+ const m = accountMemo.get(key);
286
+ if (m && now() - m.at < m.ms) return m.value;
287
+ try {
288
+ const value = await fn();
289
+ accountMemo.set(key, { at: now(), ms, value });
290
+ return value;
291
+ } catch (e) {
292
+ accountMemo.set(key, { at: now(), ms: failMs, value: empty() });
293
+ if (e?.name !== 'Skipped') log(`pictures: ${key}: ${e?.message || e}`);
294
+ return empty();
295
+ }
296
+ });
297
+ // a customer's subdomain of a shared platform (x.zendesk.com, x.onmicrosoft.com…) is its own organisation: never the
298
+ // platform's, whose logo, certificate or icon it must not borrow
299
+ const org = (d) => {
300
+ let o;
301
+ try { o = (orgDomain(d) || d).toLowerCase(); } catch { return d; }
302
+ return o !== d && SHARED_PLATFORMS.has(o) ? d : o;
303
+ };
304
+
305
+ // the settings as they are now: read again every two seconds, at once after a change made here (invalidate);
306
+ // every request, to a mail server or elsewhere, checks them first
307
+ let settingsAt = -Infinity;
308
+ let settingsKept = { enabled: true, gravatar: false };
309
+ const settingsNow = () => {
310
+ if (now() - settingsAt > 2000) { try { settingsKept = pictureSettings(config()); } catch { /* the last ones */ } settingsAt = now(); }
311
+ return settingsKept;
312
+ };
313
+ const invalidate = () => { settingsAt = -Infinity; };
314
+ /** One external request (DNS or a fetch), only while the settings still allow it. */
315
+ const net = (kind, fn) => netLimit(() => {
316
+ const st = settingsNow();
317
+ if (!st.enabled || (kind === 'gravatar' && !st.gravatar) || (kind === 'other-icon' && !st.otherIcons)) throw skipped();
318
+ return fn();
319
+ });
320
+
321
+ // Pictures are asked for as rows come on screen, not by a person: an account whose server refuses the sign-in is
322
+ // left alone for half an hour, one that cannot be reached for five minutes, so that scrolling never becomes a
323
+ // stream of sign-ins. A refused sign-in inside the work is not retried by mailcore (that retries twice, once with
324
+ // the password read again).
325
+ const pausedUntil = new Map();
326
+ const paused = (account) => (pausedUntil.get(account) || 0) > now();
327
+ const pause = (account, e) => { if (isAuth(e)) pausedUntil.set(account, now() + 30 * 60e3); else if (isConnection(e)) pausedUntil.set(account, now() + 5 * 60e3); };
328
+ const client = async (account, fn) => {
329
+ if (paused(account) || !settingsNow().enabled) throw skipped();
330
+ try {
331
+ return await withClient(account, async (c) => {
332
+ if (!settingsNow().enabled) throw skipped();
333
+ try { return await fn(c); } catch (e) {
334
+ if (isAuth(e) && e.code !== 'PICTURES_AUTH') { pause(account, e); throw Object.assign(new Error(e.message), { code: 'PICTURES_AUTH' }); }
335
+ throw e;
336
+ }
337
+ });
338
+ } catch (e) { pause(account, e); throw e; }
339
+ };
340
+
341
+ /** A cached entry, or run `find` (→ { mime, data } | null); keep what it says when it is an answer (found, or a definitive miss). */
342
+ const cached = (key, find) => once(key, async () => {
343
+ const hit = store.get(key);
344
+ if (fresh(hit, now())) return hit.mime ? { mime: hit.mime, data: hit.data } : null;
345
+ let found;
346
+ try { found = await find(); } catch (e) {
347
+ if (definitiveMiss(e)) { store.put(key, {}); return null; }
348
+ if (e?.name !== 'Skipped') log(`pictures: ${key.split(':')[0]}: ${e?.message || e}`);
349
+ return null; // not kept: asked again next time
350
+ }
351
+ store.put(key, found || {});
352
+ return found;
353
+ });
354
+
355
+ const raster = async (kind, url, more = {}) => {
356
+ const { body } = await net(kind, () => fetch(url, { maxBytes: MAX_RASTER, accept: isRasterType, acceptHeader: 'image/png,image/x-icon,image/*;q=0.8', ...more }));
357
+ const mime = sniffRaster(body);
358
+ return mime ? { mime, data: body } : null;
359
+ };
360
+
361
+ // --- who the person corresponds with: exact domains ------------------------------------------------
362
+ // their accounts' domains, their contacts' (Exchange), and those of people they wrote to (To only, no automatic
363
+ // answers) at least twice, or once at least two weeks ago: a reply-all to a stranger's list does not make a brand
364
+ // known. Kept exact: a sibling tenant of a shared platform (another *.onmicrosoft.com, zendesk.com…) is not in.
365
+ const mailAccounts = () => Object.values(config().accounts || {}).filter((a) => ['ews', 'imap', 'jmap'].includes(a.provider));
366
+ const ewsAccounts = () => mailAccounts().filter((a) => a.provider === 'ews');
367
+ const ownDomains = (acct) => memo(`domains:${acct.name}`, 86400e3, async () => {
368
+ const known = [acct.email, acct.username, ...(Array.isArray(acct.aliases) ? acct.aliases : [])].map(domainOf).filter(Boolean);
369
+ if (known.length) return new Set(known);
370
+ return new Set([domainOf(await client(acct.name, (c) => c.selfEmail()))].filter(Boolean));
371
+ });
372
+ const contactsOf = (acct) => memo(`contacts:${acct.name}`, 30 * 60e3, async () =>
373
+ new Set((await client(acct.name, (c) => c.contacts({ limit: 5000 }))).flatMap((c) => c.emails || [c.email]).map((e) => String(e).toLowerCase())));
374
+ const sentDomains = (acct) => memo(`sent:${acct.name}`, 6 * 3600e3, async () => {
375
+ const by = new Map(); // domain → { n, oldest }
376
+ for (const m of await client(acct.name, (c) => c.sentTo({ limit: 200 }))) {
377
+ const at = Date.parse(m.sent) || now();
378
+ for (const d of new Set((m.to || []).map(domainOf).filter(Boolean))) {
379
+ const cur = by.get(d) || { n: 0, oldest: Infinity };
380
+ by.set(d, { n: cur.n + 1, oldest: Math.min(cur.oldest, at) });
381
+ }
382
+ }
383
+ return new Set([...by].filter(([, v]) => v.n >= KNOWN_SENT_TIMES || now() - v.oldest >= KNOWN_SENT_DAYS * 86400e3).map(([d]) => d));
384
+ });
385
+ /** The Google contacts kept ({ byEmail }), or none: they never hold a lookup up (what is due is read in the background). */
386
+ const google = async () => {
387
+ if (typeof googleContacts !== 'function') return new Map();
388
+ try { return (await googleContacts())?.byEmail || new Map(); } catch { return new Map(); }
389
+ };
390
+ /** The domains of the Google contacts the person saved (not Google's "other contacts": anyone written with once), exact, no free mail. */
391
+ const googleDomains = async () => {
392
+ const out = new Set();
393
+ for (const [email, c] of await google()) {
394
+ if (c.kind !== 'saved') continue;
395
+ const d = domainOf(email);
396
+ if (d && !isFreeMail(d, org(d))) out.add(d);
397
+ }
398
+ return out;
399
+ };
400
+ async function knownDomains() {
401
+ const out = new Set();
402
+ await Promise.all([...mailAccounts().map(async (acct) => {
403
+ const [own, sent, contacts] = await Promise.all([ownDomains(acct), sentDomains(acct), acct.provider === 'ews' ? contactsOf(acct) : new Set()]);
404
+ for (const d of [...own, ...sent]) out.add(d);
405
+ for (const e of contacts) { const d = domainOf(e); if (d) out.add(d); }
406
+ }), googleDomains().then((ds) => { for (const d of ds) out.add(d); })]);
407
+ return out;
408
+ }
409
+ /** news.brand.com is known when brand.com is (or news.brand.com itself); a sibling under a shared parent is not. */
410
+ const isKnown = (known, domain) => known.has(domain) || known.has(org(domain));
411
+
412
+ // --- 1. the organisation's photo (Exchange) ---------------------------------------------------
413
+ const unsupported = new Map(); // account → until when GetUserPhoto is not asked again
414
+ const verifiedAt = new Map(); // account → when a request to it last went through (its sign-in works)
415
+ const probes = new Map(); // account → the request that finds out whether it does
416
+ /** The first request to an account whose sign-in is not known to work goes alone: a refused one makes one attempt, not one per address. */
417
+ const gated = async (account, run) => {
418
+ for (;;) {
419
+ if (paused(account)) throw skipped();
420
+ if (now() - (verifiedAt.get(account) ?? -Infinity) < 30 * 60e3) return run();
421
+ if (!probes.has(account)) break;
422
+ await probes.get(account).catch(() => {});
423
+ }
424
+ const p = Promise.resolve().then(run);
425
+ probes.set(account, p);
426
+ try { const r = await p; verifiedAt.set(account, now()); return r; } finally { probes.delete(account); }
427
+ };
428
+ const photoOf = (acct, c, e) => cached(`photo:${acct}:${e}`, async () => {
429
+ try {
430
+ const p = await gated(acct, () => photoLimit(() => {
431
+ // checked again just before it goes: a pause or a setting turned off since it was queued stops it
432
+ if (paused(acct) || (unsupported.get(acct) || 0) > now() || !settingsNow().enabled) throw skipped();
433
+ return c.userPhoto(e, { size: 'HR96x96' });
434
+ }));
435
+ return p && sniffRaster(p.data) && p.data.length <= MAX_RASTER ? { mime: sniffRaster(p.data), data: p.data } : null;
436
+ } catch (err) {
437
+ if (isAuth(err)) { pause(acct, err); verifiedAt.delete(acct); log(`pictures: ${acct}: sign-in refused, left alone for half an hour`); throw skipped(); }
438
+ if (err?.unsupported) { unsupported.set(acct, now() + 6 * 3600e3); log(`pictures: ${acct} has no directory photos (${err.message})`); throw skipped(); }
439
+ if (isConnection(err)) { pause(acct, err); throw skipped(); } // the server, not the photo: not kept as "none"
440
+ throw err;
441
+ }
442
+ });
443
+
444
+ /** The organisation photos of these addresses (those of an Exchange account's own domains or contacts): Map email → picture. */
445
+ async function photos(emails) {
446
+ const out = new Map();
447
+ for (const acct of ewsAccounts()) {
448
+ if ((unsupported.get(acct.name) || 0) > now() || paused(acct.name)) continue;
449
+ const left = emails.filter((e) => !out.get(e));
450
+ if (!left.length) break;
451
+ const mine = await ownDomains(acct);
452
+ const strangers = left.filter((e) => !mine.has(domainOf(e)));
453
+ const contacts = strangers.length ? await contactsOf(acct) : new Set();
454
+ const ours = left.filter((e) => mine.has(domainOf(e)) || contacts.has(e));
455
+ if (!ours.length) continue;
456
+ // what the cache already answers needs no sign-in
457
+ const ask = [];
458
+ for (const e of ours) {
459
+ const hit = store.get(`photo:${acct.name}:${e}`);
460
+ if (fresh(hit, now())) { if (hit.mime) out.set(e, { mime: hit.mime, data: hit.data, fit: 'cover' }); } else ask.push(e);
461
+ }
462
+ if (!ask.length || paused(acct.name)) continue;
463
+ try {
464
+ await client(acct.name, (c) => Promise.all(ask.map((e) => photoOf(acct.name, c, e).then((p) => { if (p && !out.get(e)) out.set(e, { ...p, fit: 'cover' }); }))));
465
+ } catch (e) { if (e?.name !== 'Skipped') log(`pictures: ${acct.name}: ${e?.message || e}`); }
466
+ }
467
+ // a Google contact's photo, for what is still without one
468
+ const left = emails.filter((e) => !out.get(e));
469
+ if (left.length) {
470
+ const byEmail = await google();
471
+ await Promise.all(left.map(async (e) => {
472
+ const url = byEmail.get(e)?.photo;
473
+ if (!url || !isGooglePhoto(url)) return;
474
+ const p = await contactPhoto(url);
475
+ if (p && !out.get(e)) out.set(e, { ...p, fit: 'cover' });
476
+ }));
477
+ }
478
+ return out;
479
+ }
480
+ /** A Google contact's photo, by the address of the image (kept like any picture, under a hash of it); a redirect, too, stays on googleusercontent.com. */
481
+ const contactPhoto = (url) => cached(photoKey(url), () => raster('contact', url, { allowUrl: isGooglePhoto }));
482
+ /** Contact photos let go of (their contacts dropped, or no longer allowed): taken out of the cache. */
483
+ function forgetContactPhotos(urls) {
484
+ for (const url of urls || []) { try { store.drop?.(photoKey(url)); } catch { /* pruned with the rest, at worst */ } }
485
+ }
486
+
487
+ // --- the verdict of a message: DMARC as its account's server says, and whether it is internal mail ------------
488
+ // no BIMI record (so no certificate, no logo) and no icon: nothing a passing message could show
489
+ const domainHasNoBrand = (o) => ['bimirec', 'icon'].every((k) => { const h = store.get(`${k}:${o}`); return fresh(h, now()) && !h.mime; });
490
+ /** The message id, when it is one this account's server could have given (an IMAP id that parses, an Exchange id). */
491
+ const goodId = (name, acct, id) => {
492
+ const raw = String(id).slice(name.length + 1);
493
+ if (!raw || raw.length > 1500) return false;
494
+ return acct.provider === 'imap' ? !!idParts(raw) : /^[A-Za-z0-9+/=_-]+$/.test(raw);
495
+ };
496
+ const recordOf = (h, acct) => ({ domain: domainOf(h.fromEmail), dmarc: dmarcVerdict(h, acct, h.fromEmail), internal: isInternal(h, acct), rule: ruleOf(acct), selector: bimiSelectorOf(h.bimiSelector) });
497
+
498
+ /** Verdicts of these messages ([{ email, id }]): kept ones under the rule as it is now, else asked of the server (headers only). */
499
+ async function verdicts(items) {
500
+ const out = new Map(); // id → { dmarc, domain, internal }
501
+ const byAccount = new Map();
502
+ const cfg = config();
503
+ for (const { id } of items) {
504
+ const account = String(id).slice(0, Math.max(0, String(id).indexOf(':')));
505
+ const acct = cfg.accounts?.[account];
506
+ if (!acct || !['ews', 'imap', 'jmap'].includes(acct.provider) || !goodId(account, acct, id)) continue;
507
+ const rec = store.getAuth(id);
508
+ if (rec && rec.rule === ruleOf(acct)) { out.set(id, rec); continue; }
509
+ byAccount.set(account, [...new Set([...(byAccount.get(account) || []), id])]);
510
+ }
511
+ await Promise.all([...byAccount].map(async ([account, ids]) => {
512
+ const acct = cfg.accounts[account];
513
+ try {
514
+ const found = await client(account, (c) => c.authHeadersOf(ids.slice(0, 50)));
515
+ for (const [id, h] of found) {
516
+ const rec = recordOf(h, acct);
517
+ store.putAuth(id, rec);
518
+ out.set(id, rec);
519
+ }
520
+ } catch (e) { if (e?.name !== 'Skipped') log(`pictures: headers of ${account}: ${e?.message || e}${e?.responseText ? ` (${String(e.responseText).slice(0, 160)})` : ''}${e?.serverResponseCode ? ` [${e.serverResponseCode}]` : ''}`); } // (the server's own words: what "Command failed" was)
521
+ }));
522
+ return out;
523
+ }
524
+
525
+ // --- 2. BIMI: the organisational domain's record (the message's selector, else default), its certificate, its logo ---
526
+ const bimiRecordAt = async (o, sel) => {
527
+ const got = await cached(sel === 'default' ? `bimirec:${o}` : `bimirec:${o}:${sel}`, async () => {
528
+ const rec = parseBimiRecord(await net('brand', () => resolveTxt(`${sel}._bimi.${o}`)));
529
+ return rec ? { mime: 'application/x-bimi-record', data: Buffer.from(JSON.stringify(rec)) } : null;
530
+ });
531
+ try { return got ? JSON.parse(Buffer.from(got.data).toString('utf8')) : null; } catch { return null; }
532
+ };
533
+ /** The record a message names (BIMI-Selector), falling back to the default one when it names none or that one is missing. */
534
+ const bimiRecord = async (o, sel = 'default') => (sel !== 'default' && (await bimiRecordAt(o, sel))) || bimiRecordAt(o, 'default');
535
+ /** The logo of a valid mark certificate (a=), with the names it is valid for, or null. */
536
+ const markLogo = async (o, url) => {
537
+ // (vmc2: what was kept under vmc: may be a refusal of a certificate served under a type not listed then)
538
+ const got = await cached(`vmc2:${o}:${sha256(url).slice(0, 16)}`, async () => {
539
+ const { body } = await net('brand', () => fetch(url, { maxBytes: MAX_PEM, accept: pemType, acceptHeader: 'application/pem-certificate-chain, application/x-pem-file, */*;q=0.1' }));
540
+ const checked = verifyVmc(body.toString('utf8'), { now: new Date(now()) });
541
+ return { mime: 'application/x-vmc-logo', data: Buffer.from(JSON.stringify(checked)) };
542
+ });
543
+ try { return got ? JSON.parse(Buffer.from(got.data).toString('utf8')) : null; } catch { return null; }
544
+ };
545
+ const bimiLogo = (o, url) => cached(`bimi:${o}:${sha256(url).slice(0, 16)}`, async () => {
546
+ const { body } = await net('brand', () => fetch(url, { maxBytes: MAX_SVG, accept: (ct) => ct === 'image/svg+xml', acceptHeader: 'image/svg+xml' }));
547
+ return { mime: 'image/svg+xml', data: Buffer.from(sanitizeSvg(body.toString('utf8')), 'utf8') };
548
+ });
549
+
550
+ // --- 3. Gravatar, Libravatar ------------------------------------------------------------------------
551
+ const gravatar = (hash) => cached(`gravatar:${hash}`, () => raster('gravatar', `https://gravatar.com/avatar/${hash}?d=404&s=96`));
552
+ /** Libravatar: the server the sender's domain names (DNS SRV) only for a domain the person corresponds with; the default one otherwise. */
553
+ const libravatar = (hash, domain, ownServer) => cached(`libravatar:${ownServer ? domain : ''}:${hash}`, async () => {
554
+ let host = 'seccdn.libravatar.org';
555
+ if (ownServer) {
556
+ try {
557
+ const srv = (await net('gravatar', () => resolveSrv(`_avatars-sec._tcp.${domain}`))).filter((r) => r.port === 443 && r.name);
558
+ srv.sort((a, b) => a.priority - b.priority || b.weight - a.weight);
559
+ if (srv.length) host = srv[0].name.replace(/\.$/, '');
560
+ } catch (e) { if (e?.name === 'Skipped') throw e; /* the default server, then */ }
561
+ }
562
+ return raster('gravatar', `https://${host}/avatar/${hash}?d=404&s=96`);
563
+ });
564
+
565
+ // --- 4b. the icon of a domain the person does not correspond with: asked of DuckDuckGo's icon service, never of
566
+ // the domain itself (its website would learn the person's address and when the mail was shown); DuckDuckGo learns
567
+ // only the organisational domain. Its 404 (a domain without one) is a definitive miss, never its placeholder.
568
+ const otherIcon = (o) => cached(`ddgicon:${o}`, () => raster('other-icon', `https://icons.duckduckgo.com/ip3/${encodeURIComponent(o)}.ico`));
569
+
570
+ // --- 4. the organisational domain's icon -------------------------------------------------------------
571
+ const icon = (o) => cached(`icon:${o}`, async () => {
572
+ let transient = null;
573
+ const attempt = async (fn) => { try { return await fn(); } catch (e) { if (e?.name === 'Skipped') throw e; if (!definitiveMiss(e)) transient = e; return null; } };
574
+ for (const path of ['/apple-touch-icon.png', '/favicon.ico']) {
575
+ const got = await attempt(() => raster('brand', `https://${o}${path}`));
576
+ if (got) return got;
577
+ }
578
+ const page = await attempt(() => net('brand', () => fetch(`https://${o}/`, { maxBytes: MAX_PAGE, truncate: true, accept: (ct) => ct === 'text/html' || ct === 'application/xhtml+xml', acceptHeader: 'text/html' })));
579
+ for (const url of page ? iconLinks(page.body.toString('utf8'), page.url) : []) {
580
+ const got = await attempt(() => raster('brand', url));
581
+ if (got) return got;
582
+ }
583
+ if (transient) throw transient; // not a definitive miss: asked again next time
584
+ return null;
585
+ });
586
+
587
+ /**
588
+ * Pictures for the senders asked for: items [{ email, id? }] (`id`: the
589
+ * message the picture is shown beside).
590
+ * → { pictures: { [email\nid]: imageKey | null }, images: { [imageKey]: { src, fit } }, pending?: keys, off?: true (turned off) }
591
+ * What is not found within `deadlineMs` goes on in the background (and is
592
+ * kept): those keys are `pending`, worth asking again a little later.
593
+ */
594
+ async function lookup(rawItems, { deadlineMs = 12000 } = {}) {
595
+ invalidate();
596
+ const settings = settingsNow();
597
+ const items = cleanItems(rawItems);
598
+ const result = { pictures: {}, images: {} };
599
+ if (!settings.enabled) return { ...result, off: true };
600
+ if (!items.length) return result;
601
+ const done = new Map(); // key → { mime, data, fit } | null
602
+ const keyOf = (it) => `${it.email}\n${it.id || ''}`;
603
+
604
+ const work = (async () => {
605
+ const found = await photos([...new Set(items.map((i) => i.email))]);
606
+ const cfg = config();
607
+ const judgeable = (it) => { const acct = cfg.accounts?.[it.id.slice(0, it.id.indexOf(':'))]; return !!acct && canJudge(acct); };
608
+ const brandCandidate = (it) => !!it.id && !isFreeMail(domainOf(it.email), org(domainOf(it.email))) && judgeable(it);
609
+ // the verdict is needed beside a message for a person's picture (photo found, or Gravatar on) and for a brand's:
610
+ // asked of the server only when the domain may have one; one already kept is used anyway (its selector may name a
611
+ // record the default one's absence says nothing of)
612
+ const needVerdict = items.filter((it) => it.id && (found.get(it.email) || settingsNow().gravatar || (brandCandidate(it) && (!domainHasNoBrand(org(domainOf(it.email))) || !!store.getAuth(it.id)))));
613
+ const passed = needVerdict.length ? await verdicts(needVerdict) : new Map();
614
+ const brandItems = items.filter((it) => brandCandidate(it) && passed.get(it.id)?.dmarc === 'pass' && passed.get(it.id)?.domain === domainOf(it.email));
615
+ // whether the person corresponds with a domain: asked only when a brand could be shown, or for Libravatar's server
616
+ const known = brandItems.length || settingsNow().gravatar ? await knownDomains() : new Set();
617
+ await Promise.all(items.map(async (it) => {
618
+ const domain = domainOf(it.email);
619
+ const o = org(domain);
620
+ const v = it.id ? passed.get(it.id) : null;
621
+ // a person's picture beside a message: only when that message proved its sender (DMARC passed for this very
622
+ // domain), or is internal mail; without a message (People), for whom it is
623
+ const personOk = !it.id || (!!v && ((v.dmarc === 'pass' && v.domain === domain) || v.internal));
624
+ const brand = brandItems.includes(it);
625
+ const knownDomain = isKnown(known, domain);
626
+ let pic = null;
627
+ if (found.get(it.email) && personOk) pic = found.get(it.email);
628
+ let rec = null;
629
+ if (!pic && brand) {
630
+ rec = await bimiRecord(o, v?.selector || 'default');
631
+ // a logo with a valid mark certificate: for any sender that proved this domain
632
+ if (rec?.a) {
633
+ const mark = await markLogo(o, rec.a);
634
+ // its subjectAltName names this domain or the one the record is at, and it has not expired since it was checked
635
+ if (mark && mark.notAfter > now() && (mark.names || []).some((n) => n === domain || n === o)) pic = { mime: 'image/svg+xml', data: Buffer.from(mark.svg, 'utf8'), fit: 'cover', verified: true };
636
+ }
637
+ // without one, only for a domain the person corresponds with
638
+ if (!pic && rec?.l && knownDomain) { const l = await bimiLogo(o, rec.l); if (l) pic = { ...l, fit: 'cover' }; }
639
+ }
640
+ if (!pic && settingsNow().gravatar && personOk) {
641
+ const hash = sha256(it.email.trim().toLowerCase());
642
+ pic = (await gravatar(hash)) || (await libravatar(hash, domain, knownDomain));
643
+ if (pic) pic = { ...pic, fit: 'cover' };
644
+ }
645
+ if (!pic && brand && knownDomain) { pic = await icon(o); if (pic) pic = { ...pic, fit: 'contain' }; }
646
+ // a domain the person does not correspond with: its icon through DuckDuckGo (setting, on by default)
647
+ if (!pic && brand && !knownDomain && settingsNow().otherIcons) { pic = await otherIcon(o); if (pic) pic = { ...pic, fit: 'contain' }; }
648
+ done.set(keyOf(it), pic);
649
+ }));
650
+ })().catch((e) => log(`pictures: ${e?.message || e}`));
651
+
652
+ let timer;
653
+ await Promise.race([work, new Promise((r) => { timer = setTimeout(r, deadlineMs); })]);
654
+ clearTimeout(timer);
655
+ const pending = [];
656
+ for (const it of items) {
657
+ const k = keyOf(it);
658
+ if (!done.has(k)) { pending.push(k); continue; }
659
+ const p = done.get(k);
660
+ if (!p) { result.pictures[k] = null; continue; }
661
+ const imageKey = crypto.createHash('sha256').update(`${p.fit}:${p.verified ? 'v' : ''}:${p.mime}:`).update(p.data).digest('hex').slice(0, 20);
662
+ result.images[imageKey] = { src: dataUrl(p.mime, p.data), fit: p.fit, ...(p.verified ? { verified: true } : {}) };
663
+ result.pictures[k] = imageKey;
664
+ }
665
+ if (pending.length) result.pending = pending;
666
+ return result;
667
+ }
668
+
669
+ /** The verdict of a message the daemon just fetched whole (getMessage, newSince): kept for when its picture is asked for. */
670
+ function noteMessage(account, msg) {
671
+ try {
672
+ const acct = config().accounts?.[account];
673
+ if (!msg?.id || !msg.authHeaders || !acct) return;
674
+ store.putAuth(msg.id, recordOf({ ...msg.authHeaders, fromEmail: msg.fromEmail }, acct));
675
+ } catch { /* a picture without its brand, at worst */ }
676
+ }
677
+
678
+ return { lookup, noteMessage, invalidate, forgetContactPhotos };
679
+ }
680
+
681
+ const photoKey = (url) => `gphoto:${crypto.createHash('sha256').update(url).digest('hex').slice(0, 32)}`;
682
+
683
+ /** A Google contact photo's address: https on googleusercontent.com, nothing else (the address comes from Google, and is checked anyway). */
684
+ export function isGooglePhoto(url) {
685
+ try {
686
+ const u = new URL(url);
687
+ return u.protocol === 'https:' && !u.port && !u.username && !u.password && /(^|\.)googleusercontent\.com$/i.test(u.hostname);
688
+ } catch { return false; }
689
+ }
690
+
691
+ // The type a certificate file is served under says little: Amazon's CDN serves its chain as
692
+ // application/x-www-form-urlencoded, and Gmail shows its logo. What the file holds is read strictly anyway
693
+ // (PEM blocks, a mark certificate, a chain to a pinned root): only what is plainly something else is refused.
694
+ const pemType = (ct) => PEM_TYPES.has(ct) || !/^(text\/html|image\/|audio\/|video\/|font\/|application\/(json|javascript|pdf|zip))/.test(ct);
695
+ const PEM_TYPES = new Set(['application/pem-certificate-chain', 'application/x-pem-file', 'application/x-x509-ca-cert', 'application/x-x509-user-cert', 'application/pkix-cert', 'text/plain', 'application/octet-stream', 'application/x-pem', 'binary/octet-stream']);
696
+
697
+ /** The items the panel asks for, checked: a real address (lower case), a message id that is a short string; at most MAX_ITEMS. */
698
+ export function cleanItems(raw) {
699
+ const out = [];
700
+ const seen = new Set();
701
+ for (const it of Array.isArray(raw) ? raw : []) {
702
+ const email = typeof it?.email === 'string' ? it.email.trim().toLowerCase() : '';
703
+ if (!EMAIL.test(email) || email.length > 254) continue;
704
+ const id = typeof it?.id === 'string' && it.id.length <= 2000 && it.id.includes(':') ? it.id : undefined;
705
+ const k = `${email}\n${id || ''}`;
706
+ if (seen.has(k)) continue;
707
+ seen.add(k);
708
+ out.push(id ? { email, id } : { email });
709
+ if (out.length >= MAX_ITEMS) break;
710
+ }
711
+ return out;
712
+ }
713
+
714
+ // --- the instance Sideora uses ------------------------------------------------------
715
+
716
+ let instance = null;
717
+ /** The finder over Sideora's own config and accounts, kept in the core's database (src/core-db.js; built on first use). */
718
+ export async function pictures() {
719
+ if (instance) return instance;
720
+ const [{ loadConfig }, core, dns, { safeFetch }, { getDomain }, coreDb] = await Promise.all([
721
+ import('./config.js'), import('./core.js'), import('node:dns/promises'), import('./safe-fetch.js'), import('tldts'), import('./core-db.js').then((m) => m.theCoreDb())
722
+ ]);
723
+ instance = createPictures({
724
+ config: loadConfig,
725
+ withClient: (account, fn) => core.withAuthRetry(fn, null, account),
726
+ store: pictureStore({ open: () => coreDb.open() }),
727
+ fetch: safeFetch,
728
+ resolveTxt: (name) => dns.resolveTxt(name),
729
+ resolveSrv: (name) => dns.resolveSrv(name),
730
+ orgDomain: (d) => getDomain(d, { allowPrivateDomains: true }) || d,
731
+ googleContacts: async () => (await import('./google-contacts.js')).googleContacts().then((g) => g.contacts()),
732
+ log: (m) => console.error(m)
733
+ });
734
+ return instance;
735
+ }