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.
- package/LICENSE.md +9 -0
- package/README.md +57 -6
- package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
- package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
- package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
- package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
- package/assets/sounds/nice-chime.mp3 +0 -0
- package/bin/sideora.js +2430 -12
- package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
- package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
- package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
- package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
- package/extension/dist/assets/shell-82MNMljp.css +1 -0
- package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
- package/extension/dist/icons/icon-128.png +0 -0
- package/extension/dist/icons/icon-16.png +0 -0
- package/extension/dist/icons/icon-32.png +0 -0
- package/extension/dist/icons/icon-48.png +0 -0
- package/extension/dist/manifest.json +40 -0
- package/extension/dist/service-worker-loader.js +1 -0
- package/extension/dist/src/newtab/index.html +14 -0
- package/extension/dist/src/panel/index.html +15 -0
- package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
- package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
- package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
- package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
- package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
- package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
- package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
- package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
- package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
- package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
- package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
- package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
- package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
- package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
- package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
- package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
- package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
- package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
- package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
- package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
- package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
- package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
- package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
- package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
- package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
- package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
- package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
- package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
- package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
- package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
- package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
- package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
- package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
- package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
- package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
- package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
- package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
- package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
- package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
- package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
- package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
- package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
- package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
- package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
- package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
- package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
- package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
- package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
- package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
- package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
- package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
- package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
- package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
- package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
- package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
- package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
- package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
- package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
- package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
- package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
- package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
- package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
- package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
- package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
- package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
- package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
- package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
- package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
- package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
- package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
- package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
- package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
- package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
- package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
- package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
- package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
- package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
- package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
- package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
- package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
- package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
- package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
- package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
- package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
- package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
- package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
- package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
- package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
- package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
- package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
- package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
- package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
- package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
- package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
- package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
- package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
- package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
- package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
- package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
- package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
- package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
- package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
- package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
- package/extension/dist-web/icon-192.png +0 -0
- package/extension/dist-web/icon-512.png +0 -0
- package/extension/dist-web/index.html +25 -0
- package/extension/dist-web/manifest.webmanifest +14 -0
- package/package.json +64 -12
- package/plugin/.claude-plugin/icon.png +0 -0
- package/plugin/.claude-plugin/plugin.json +6 -0
- package/plugin/.mcp.json +8 -0
- package/plugin/README.md +72 -0
- package/plugin/mcp-launcher.mjs +48 -0
- package/src/account-probe.js +45 -0
- package/src/accounts.js +687 -0
- package/src/ai.js +269 -0
- package/src/assistant-runs.js +32 -0
- package/src/attached-mail.js +76 -0
- package/src/auth-gate.js +70 -0
- package/src/backup-cli.js +158 -0
- package/src/backup.js +329 -0
- package/src/bimi.js +233 -0
- package/src/bridge.js +101 -0
- package/src/calendar-alerts.js +56 -0
- package/src/chats.js +27 -0
- package/src/compose-editor.js +58 -0
- package/src/config.js +420 -0
- package/src/connections.d.ts +24 -0
- package/src/connections.js +37 -0
- package/src/core/agent.js +92 -0
- package/src/core/assistant.d.ts +13 -0
- package/src/core/assistant.js +790 -0
- package/src/core/chats.js +323 -0
- package/src/core/markdown.d.ts +8 -0
- package/src/core/markdown.js +239 -0
- package/src/core/notes.js +445 -0
- package/src/core/otp.js +152 -0
- package/src/core/rules.js +196 -0
- package/src/core/runs.d.ts +9 -0
- package/src/core/runs.js +211 -0
- package/src/core/thread.js +526 -0
- package/src/core/write.js +247 -0
- package/src/core-db.js +131 -0
- package/src/core.js +174 -0
- package/src/credentials.js +320 -0
- package/src/daemon.js +564 -0
- package/src/events.js +213 -0
- package/src/extension-id.d.ts +2 -0
- package/src/extension-id.js +5 -0
- package/src/file-lock.js +27 -0
- package/src/files-index.js +154 -0
- package/src/google-contacts.js +315 -0
- package/src/google-signin.js +306 -0
- package/src/host/assistant-html.js +44 -0
- package/src/host/chats-files.js +137 -0
- package/src/host/file-prep.js +122 -0
- package/src/host/notes-files.js +158 -0
- package/src/host/office-text.js +224 -0
- package/src/host/office-worker.js +8 -0
- package/src/host/rules-file.js +20 -0
- package/src/host/secrets-file.js +91 -0
- package/src/host/systemd.js +90 -0
- package/src/hub.js +245 -0
- package/src/identity.js +316 -0
- package/src/labels.js +5 -0
- package/src/mail-port.d.ts +79 -0
- package/src/mail-port.js +148 -0
- package/src/mcp-server.js +747 -0
- package/src/microsoft-app.js +20 -0
- package/src/microsoft-signin.js +194 -0
- package/src/migrate.js +327 -0
- package/src/notes-html.js +450 -0
- package/src/notes.js +19 -0
- package/src/notify.js +105 -0
- package/src/onepassword.js +223 -0
- package/src/op-registry.d.ts +14 -0
- package/src/op-registry.js +150 -0
- package/src/ops.js +1251 -0
- package/src/otp.js +6 -0
- package/src/panel-ops.js +273 -0
- package/src/pictures.js +735 -0
- package/src/postinstall.js +25 -0
- package/src/relay-passkey.js +122 -0
- package/src/relay-request.js +155 -0
- package/src/relay-seal.js +56 -0
- package/src/relay-settings.js +139 -0
- package/src/relay.js +876 -0
- package/src/render.js +82 -0
- package/src/rules-store.js +8 -0
- package/src/safe-fetch.js +215 -0
- package/src/sender-auth.js +270 -0
- package/src/site-match.js +77 -0
- package/src/tui-agenda.js +266 -0
- package/src/tui.js +670 -0
- package/src/vmc.js +376 -0
- package/src/wake.js +96 -0
- package/src/web-access.js +185 -0
- package/src/web-server.js +241 -0
- package/src/web-service.js +152 -0
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
// Notes, in the core: what a note is and how it changes, over a store the host gives (makeNotes({ store })): on
|
|
2
|
+
// this Mac, one file a note (src/host/notes-files.js). This module touches no file, no setting and no mail.
|
|
3
|
+
//
|
|
4
|
+
// a note { id, title, html, rev, created, updated, pinned, links, journal }
|
|
5
|
+
// the trash a note removed (it is moved there, never deleted)
|
|
6
|
+
// a picture its bytes, named by what they hold
|
|
7
|
+
//
|
|
8
|
+
// A picture is not in a note's text: the text names it, `<img src="picture:
|
|
9
|
+
// 3f9a…">` (32 hex of the SHA-256 of its bytes), and the bytes are kept on
|
|
10
|
+
// their own, once however many notes show it. Only PNG, JPEG, GIF or WebP,
|
|
11
|
+
// known by how the file starts, never by what it is called; never a link to
|
|
12
|
+
// a picture elsewhere: one named by what is pasted into a note is fetched
|
|
13
|
+
// once (fetchNotePicture) and kept here like any other. A picture no note
|
|
14
|
+
// names any more stays where it is: nothing here is deleted.
|
|
15
|
+
//
|
|
16
|
+
// `html` is the side panel editor's (headings, lists, tables, and to-dos: see
|
|
17
|
+
// notes-html.js). `links` are what the note is about: a conversation of the
|
|
18
|
+
// mail ({ kind: 'mail', id, account, conversationId, subject, from }).
|
|
19
|
+
//
|
|
20
|
+
// A note changes often, and from several places at once: the editor in a tab,
|
|
21
|
+
// the same note in the side panel, a to-do ticked on Home, a line added from a
|
|
22
|
+
// mail, a tool. So there are two ways to change one:
|
|
23
|
+
//
|
|
24
|
+
// saveNote the whole text, by the editor. It says which revision (`rev`)
|
|
25
|
+
// it started from: when the note moved on since, nothing is
|
|
26
|
+
// written (CHANGED), so one writer never wipes another.
|
|
27
|
+
// addToNote one thing added at the end (a to-do, a line, a block of HTML,
|
|
28
|
+
// tickNote a link), one to-do ticked, or a link taken off (unlinkNote):
|
|
29
|
+
// unlinkNote applied to the note as it is
|
|
30
|
+
// now, whatever revision the caller last saw.
|
|
31
|
+
//
|
|
32
|
+
// Each of the second kind is kept in the note's `journal` with the revision it
|
|
33
|
+
// made. An editor that is open asks noteChanges({ since }) when the note
|
|
34
|
+
// changes under it: while everything since was of that kind it gets the
|
|
35
|
+
// changes themselves, and makes them in the text being typed; otherwise (the
|
|
36
|
+
// whole text was saved elsewhere) it gets the note.
|
|
37
|
+
//
|
|
38
|
+
// Every change is read, made and written while the store has this writer as
|
|
39
|
+
// its only one (store.locked), and written whole or not at all (store.write).
|
|
40
|
+
// Whoever shows a note's HTML cleans it first (the editor does, by reading it
|
|
41
|
+
// into its own kinds of text): nothing here trusts it.
|
|
42
|
+
//
|
|
43
|
+
// The store (src/host/notes-files.js is this Mac's):
|
|
44
|
+
// locked(fn) fn's result, run as the only writer (sync)
|
|
45
|
+
// ids(where) the ids kept ('notes' or 'trash')
|
|
46
|
+
// read(id, where) a note as written (parsed), or null
|
|
47
|
+
// has(id, where) whether there is one by that id
|
|
48
|
+
// stamp(id) what changes whenever the note is written; null when it is not there
|
|
49
|
+
// write(note) the note, whole (inside locked only)
|
|
50
|
+
// move(id, from, to) between 'notes' and 'trash'
|
|
51
|
+
// pictures.size(name) bytes kept under name ("<id>.<ext>"), or -1
|
|
52
|
+
// pictures.get(name, max) the bytes, or null (none, or more than max)
|
|
53
|
+
// pictures.put(name, bytes) kept, whole or not at all
|
|
54
|
+
// watch(onChange) onChange(id) at each write, whoever made it; returns how to stop
|
|
55
|
+
|
|
56
|
+
import crypto from 'node:crypto';
|
|
57
|
+
import { appendTodo, plainText, setChecked, textHtml, todoItems, withoutEmptyEnd } from '../notes-html.js';
|
|
58
|
+
|
|
59
|
+
export const CHANGED = 'the note was changed elsewhere';
|
|
60
|
+
export const GONE = 'that note is no longer there';
|
|
61
|
+
export const MAX_PICTURE = 8 * 1024 * 1024; // bytes, one picture
|
|
62
|
+
const ID = /^[a-z0-9]{6,24}$/;
|
|
63
|
+
const MAX_HTML = 400_000;
|
|
64
|
+
const MAX_ADDED = 200_000; // bytes of HTML added to a note in one go
|
|
65
|
+
const MAX_TITLE = 200;
|
|
66
|
+
const MAX_NOTES = 5000;
|
|
67
|
+
const MAX_LINKS = 20;
|
|
68
|
+
const JOURNAL = 40; // changes kept: an editor further behind than this takes the whole note
|
|
69
|
+
const OPEN_SHOWN = 6; // to-dos still open that a row names
|
|
70
|
+
|
|
71
|
+
const str = (v) => (typeof v === 'string' ? v : '');
|
|
72
|
+
const oneLine = (v, max) => str(v).replace(/[\x00-\x1f\x7f\u2028\u2029]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
73
|
+
const newId = (n = 5) => crypto.randomBytes(n).toString('hex');
|
|
74
|
+
|
|
75
|
+
function checkId(id) {
|
|
76
|
+
if (!ID.test(str(id))) throw new Error('which note?');
|
|
77
|
+
return id;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** What a note is about, as it is kept; null for what is not one. */
|
|
81
|
+
function linkOf(v) {
|
|
82
|
+
if (!v || typeof v !== 'object' || v.kind !== 'mail') return null;
|
|
83
|
+
const id = oneLine(v.id, 600);
|
|
84
|
+
if (!id) return null;
|
|
85
|
+
const link = { kind: 'mail', id, subject: oneLine(v.subject, 300) };
|
|
86
|
+
for (const k of ['account', 'conversationId', 'from']) { const s = oneLine(v[k], 600); if (s) link[k] = s; }
|
|
87
|
+
return link;
|
|
88
|
+
}
|
|
89
|
+
const sameLink = (a, b) => a.kind === b.kind && (a.conversationId && b.conversationId ? a.conversationId === b.conversationId && a.account === b.account : a.id === b.id);
|
|
90
|
+
|
|
91
|
+
function checkHtml(html, max = MAX_HTML) {
|
|
92
|
+
if (typeof html !== 'string') throw new Error('a note\'s text is HTML');
|
|
93
|
+
if (Buffer.byteLength(html) > max) throw new Error(max === MAX_HTML ? `that is more than a note holds (${Math.round(max / 1000)} KB)` : `that is more than is added to a note at once (${Math.round(max / 1000)} KB): add it in parts`);
|
|
94
|
+
return html;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The note as an editor is given it. */
|
|
98
|
+
const whole = (n) => ({ id: n.id, title: n.title, html: n.html, rev: n.rev, created: n.created, updated: n.updated, pinned: n.pinned, links: n.links });
|
|
99
|
+
|
|
100
|
+
/** The note as a list shows it: its first words, and how its to-dos stand. */
|
|
101
|
+
function row(n) {
|
|
102
|
+
const todos = todoItems(n.html);
|
|
103
|
+
const text = plainText(n.html);
|
|
104
|
+
return {
|
|
105
|
+
id: n.id,
|
|
106
|
+
title: n.title,
|
|
107
|
+
excerpt: text.slice(0, 180) || (/<img\b/i.test(n.html) ? 'A picture' : ''),
|
|
108
|
+
rev: n.rev,
|
|
109
|
+
updated: n.updated,
|
|
110
|
+
pinned: n.pinned,
|
|
111
|
+
links: n.links,
|
|
112
|
+
todos: { open: todos.filter((t) => !t.checked).length, done: todos.filter((t) => t.checked).length },
|
|
113
|
+
open: todos.filter((t) => !t.checked && t.id && t.text).slice(0, OPEN_SHOWN).map((t) => ({ id: t.id, text: t.text.slice(0, 200) }))
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// --- pictures: known by what they hold ------------------------------------------
|
|
118
|
+
|
|
119
|
+
const PICTURE_ID = /^[0-9a-f]{32}$/;
|
|
120
|
+
// A picture is known by what it holds, never by what it is called: how it starts, how it is laid out, and how it
|
|
121
|
+
// ends (so that nothing rides behind a picture). What only starts like one is not one. This is not a decoder: the
|
|
122
|
+
// side panel shows a picture before it hands it over, and whatever is kept here is only ever shown as a picture.
|
|
123
|
+
const MAX_SIDE = 20000; // pixels, either way
|
|
124
|
+
const side = (n) => n > 0 && n <= MAX_SIDE;
|
|
125
|
+
const PNG_END = Buffer.from([0, 0, 0, 0, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82]);
|
|
126
|
+
const PICTURE_TYPES = {
|
|
127
|
+
png: { type: 'image/png', is: (b) => b.length >= 45 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
|
|
128
|
+
&& b.readUInt32BE(8) === 13 && b.toString('latin1', 12, 16) === 'IHDR' && side(b.readUInt32BE(16)) && side(b.readUInt32BE(20)) && b.subarray(b.length - 12).equals(PNG_END) },
|
|
129
|
+
jpg: { type: 'image/jpeg', is: (b) => b.length >= 20 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff && b[b.length - 2] === 0xff && b[b.length - 1] === 0xd9 },
|
|
130
|
+
gif: { type: 'image/gif', is: (b) => b.length >= 14 && /^GIF8[79]a$/.test(b.toString('latin1', 0, 6)) && side(b.readUInt16LE(6)) && side(b.readUInt16LE(8)) && b[b.length - 1] === 0x3b },
|
|
131
|
+
webp: { type: 'image/webp', is: (b) => b.length >= 20 && b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP'
|
|
132
|
+
&& b.readUInt32LE(4) === b.length - 8 && /^VP8[ LX]$/.test(b.toString('latin1', 12, 16)) }
|
|
133
|
+
};
|
|
134
|
+
const mb = (n) => `${Math.round(n / 1024 / 1024)} MB`;
|
|
135
|
+
const FETCH_AT_ONCE = 4;
|
|
136
|
+
const FETCH_WAITING = 60;
|
|
137
|
+
// (one for the process, however many cores it makes: a few fetches at once in all, not a few each)
|
|
138
|
+
const fetching = { now: 0, waiting: 0, line: [] };
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The notes over `store` (above): one core a store (each keeps what it worked out of the notes it listed). `fetch(url, opts)`: how a picture is brought in from the web (the host's safe
|
|
142
|
+
* outbound access: { body: Buffer }).
|
|
143
|
+
*/
|
|
144
|
+
export function makeNotes({ store, fetch } = {}) {
|
|
145
|
+
/** A note as the store holds it, made whole (one written by hand may lack fields); null when there is none or it cannot be read. */
|
|
146
|
+
function load(id, where = 'notes') {
|
|
147
|
+
const raw = store.read(id, where);
|
|
148
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
|
|
149
|
+
const now = new Date().toISOString();
|
|
150
|
+
const note = {
|
|
151
|
+
id,
|
|
152
|
+
title: oneLine(raw.title, MAX_TITLE),
|
|
153
|
+
html: str(raw.html),
|
|
154
|
+
rev: Number.isInteger(raw.rev) && raw.rev > 0 ? raw.rev : 1,
|
|
155
|
+
created: str(raw.created) || now,
|
|
156
|
+
updated: str(raw.updated) || str(raw.created) || now,
|
|
157
|
+
pinned: raw.pinned === true,
|
|
158
|
+
links: Array.isArray(raw.links) ? raw.links.map(linkOf).filter(Boolean).slice(0, MAX_LINKS) : [],
|
|
159
|
+
journal: []
|
|
160
|
+
};
|
|
161
|
+
// (a revision set back by hand: what the journal says of later ones is of another text)
|
|
162
|
+
if (Array.isArray(raw.journal)) note.journal = raw.journal.filter((j) => j && Number.isInteger(j.rev) && j.rev <= note.rev && j.op && typeof j.op === 'object');
|
|
163
|
+
return note;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function need(id) {
|
|
167
|
+
const note = load(checkId(id));
|
|
168
|
+
if (!note) throw new Error(GONE);
|
|
169
|
+
return note;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// a note as the list shows it, kept while the store's stamp of it is the same: a list is asked for at every change
|
|
173
|
+
// of any note, by every page that shows one
|
|
174
|
+
const listed = new Map(); // id -> { stamp, row, hay }
|
|
175
|
+
function listing(id) {
|
|
176
|
+
const stamp = store.stamp(id);
|
|
177
|
+
if (stamp == null) { listed.delete(id); return null; }
|
|
178
|
+
const had = listed.get(id);
|
|
179
|
+
if (had?.stamp === stamp) return had;
|
|
180
|
+
const n = load(id);
|
|
181
|
+
if (!n) { listed.delete(id); return null; }
|
|
182
|
+
const entry = { stamp, row: row(n), hay: `${n.title} ${plainText(n.html)} ${n.links.map((l) => `${l.subject} ${l.from || ''}`).join(' ')}`.toLowerCase() };
|
|
183
|
+
listed.set(id, entry);
|
|
184
|
+
return entry;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Every note, pinned ones first, then the last changed first; `q` keeps those holding each of its words. */
|
|
188
|
+
function listNotes({ q } = {}) {
|
|
189
|
+
const words = str(q).toLowerCase().split(/\s+/).filter(Boolean);
|
|
190
|
+
const notes = [];
|
|
191
|
+
const there = store.ids('notes');
|
|
192
|
+
for (const id of listed.keys()) if (!there.includes(id)) listed.delete(id);
|
|
193
|
+
for (const id of there) {
|
|
194
|
+
const entry = listing(id);
|
|
195
|
+
if (!entry || !words.every((w) => entry.hay.includes(w))) continue;
|
|
196
|
+
notes.push(entry.row);
|
|
197
|
+
}
|
|
198
|
+
notes.sort((a, b) => Number(b.pinned) - Number(a.pinned) || b.updated.localeCompare(a.updated));
|
|
199
|
+
return { notes };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function readNote({ id } = {}) {
|
|
203
|
+
return whole(need(id));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Without `id`: a new note (all of title, html, pinned and links optional).
|
|
208
|
+
* With it: only what is passed changes. The text and the title are the
|
|
209
|
+
* editor's: they need `rev`, the revision they were read at, and are refused
|
|
210
|
+
* (CHANGED) when the note has moved on. `pinned` needs none. What a note is
|
|
211
|
+
* about changes one link at a time (addToNote, unlinkNote), never as a list:
|
|
212
|
+
* a list would drop a link added elsewhere meanwhile.
|
|
213
|
+
*/
|
|
214
|
+
function saveNote(a = {}) {
|
|
215
|
+
return store.locked(() => {
|
|
216
|
+
const now = new Date().toISOString();
|
|
217
|
+
if (a.id === undefined) {
|
|
218
|
+
if (store.ids('notes').length >= MAX_NOTES) throw new Error('that is more notes than are kept');
|
|
219
|
+
const note = {
|
|
220
|
+
id: newId(),
|
|
221
|
+
title: oneLine(a.title, MAX_TITLE),
|
|
222
|
+
html: a.html === undefined ? '' : checkHtml(a.html),
|
|
223
|
+
rev: 1,
|
|
224
|
+
created: now,
|
|
225
|
+
updated: now,
|
|
226
|
+
pinned: a.pinned === true,
|
|
227
|
+
links: (Array.isArray(a.links) ? a.links : []).map(linkOf).filter(Boolean).slice(0, MAX_LINKS),
|
|
228
|
+
journal: []
|
|
229
|
+
};
|
|
230
|
+
store.write(note);
|
|
231
|
+
return whole(note);
|
|
232
|
+
}
|
|
233
|
+
const note = need(a.id);
|
|
234
|
+
if (a.links !== undefined) throw new Error('what a note is about is changed one link at a time');
|
|
235
|
+
const text = a.html !== undefined || a.title !== undefined;
|
|
236
|
+
let changed = false;
|
|
237
|
+
if (text) {
|
|
238
|
+
if (a.rev !== note.rev) throw new Error(CHANGED);
|
|
239
|
+
const html = a.html === undefined ? note.html : checkHtml(a.html);
|
|
240
|
+
const title = a.title === undefined ? note.title : oneLine(a.title, MAX_TITLE);
|
|
241
|
+
if (html !== note.html || title !== note.title) { note.html = html; note.title = title; note.rev++; note.updated = now; changed = true; }
|
|
242
|
+
}
|
|
243
|
+
if (a.pinned !== undefined && note.pinned !== (a.pinned === true)) { note.pinned = a.pinned === true; changed = true; }
|
|
244
|
+
if (changed) store.write(note); // the same again is no write: nobody is told of a change that is none
|
|
245
|
+
return whole(note);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* Changes of the second kind, made and kept in the journal. `change(note)` returns the op, several of them, or
|
|
251
|
+
* null when the text stays as it is (what it changed besides the text, a link, is then written without a revision).
|
|
252
|
+
*/
|
|
253
|
+
function atomic(id, change) {
|
|
254
|
+
return store.locked(() => {
|
|
255
|
+
const note = need(id);
|
|
256
|
+
const links = note.links;
|
|
257
|
+
const made = change(note);
|
|
258
|
+
const ops = Array.isArray(made) ? made : made ? [made] : [];
|
|
259
|
+
if (!ops.length) {
|
|
260
|
+
if (note.links !== links) store.write(note);
|
|
261
|
+
return { ...row(note), op: null, ops: [] };
|
|
262
|
+
}
|
|
263
|
+
checkHtml(note.html);
|
|
264
|
+
// each change is a revision of its own (an editor behind is told them one by one), written in one go: all of
|
|
265
|
+
// them, or none
|
|
266
|
+
for (const op of ops) { note.rev++; note.journal.push({ rev: note.rev, op }); }
|
|
267
|
+
note.journal = note.journal.slice(-JOURNAL);
|
|
268
|
+
note.updated = new Date().toISOString();
|
|
269
|
+
store.write(note);
|
|
270
|
+
return { ...row(note), op: ops[ops.length - 1], ops };
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Add at the end of a note, as it is now: a block (`text`, plain lines, or
|
|
276
|
+
* `html`, the editor's HTML) and to-dos (`todo`, the words of one, or `todos`,
|
|
277
|
+
* of several), the block first; and `link`, what the note is about, when it
|
|
278
|
+
* is not about it already. All of it or none. The row of the note comes back,
|
|
279
|
+
* with `ops`: what was added, as noteChanges tells it (`op`: the last).
|
|
280
|
+
*/
|
|
281
|
+
function addToNote({ id, todo, todos, text, html, link } = {}) {
|
|
282
|
+
if (text !== undefined && html !== undefined) throw new Error('one block at a time: text or HTML');
|
|
283
|
+
if (todo !== undefined && todos !== undefined) throw new Error('to-dos one way: `todo` or `todos`');
|
|
284
|
+
// (fewer than the journal holds, the block counted: an editor behind is told them all, not handed the whole note)
|
|
285
|
+
if (todos !== undefined && (!Array.isArray(todos) || todos.length > JOURNAL - 2)) throw new Error(`to-dos are a list of lines, ${JOURNAL - 2} at most`);
|
|
286
|
+
const lines = todos !== undefined ? todos : todo !== undefined ? [todo] : [];
|
|
287
|
+
const about = link === undefined ? null : linkOf(link);
|
|
288
|
+
if (link !== undefined && !about) throw new Error('that is not something a note can be about');
|
|
289
|
+
if (text === undefined && html === undefined && !lines.length && !about) throw new Error('nothing to add');
|
|
290
|
+
return atomic(id, (note) => {
|
|
291
|
+
// what a note is about is not its text: no revision of its own
|
|
292
|
+
if (about && !note.links.some((l) => sameLink(l, about))) {
|
|
293
|
+
if (note.links.length >= MAX_LINKS) throw new Error(`a note can be about ${MAX_LINKS} mails at most`);
|
|
294
|
+
note.links = [...note.links, about];
|
|
295
|
+
}
|
|
296
|
+
const ops = [];
|
|
297
|
+
if (text !== undefined || html !== undefined) {
|
|
298
|
+
const block = checkHtml(text !== undefined ? textHtml(str(text).trim()) : html, MAX_ADDED);
|
|
299
|
+
if (!(text !== undefined ? str(text) : block).trim()) throw new Error('nothing to add');
|
|
300
|
+
note.html = withoutEmptyEnd(note.html) + block;
|
|
301
|
+
ops.push({ kind: 'append', html: block });
|
|
302
|
+
}
|
|
303
|
+
for (const line of lines) {
|
|
304
|
+
const words = oneLine(line, 500);
|
|
305
|
+
if (!words) throw new Error('a to-do needs words');
|
|
306
|
+
const item = newId(4);
|
|
307
|
+
note.html = appendTodo(note.html, { id: item, text: words });
|
|
308
|
+
ops.push({ kind: 'todo', item, text: words });
|
|
309
|
+
}
|
|
310
|
+
return ops;
|
|
311
|
+
});
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** The note is no longer about this mail: that link is taken off the note as it is now, the others kept. */
|
|
315
|
+
function unlinkNote({ id, link } = {}) {
|
|
316
|
+
const about = linkOf(link);
|
|
317
|
+
if (!about) throw new Error('that is not something a note can be about');
|
|
318
|
+
return store.locked(() => {
|
|
319
|
+
const note = need(id);
|
|
320
|
+
const links = note.links.filter((l) => !sameLink(l, about));
|
|
321
|
+
if (links.length !== note.links.length) { note.links = links; store.write(note); }
|
|
322
|
+
return row(note);
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Tick one to-do of a note, or clear it (`checked: false`), as the note is now. */
|
|
327
|
+
function tickNote({ id, item, checked = true } = {}) {
|
|
328
|
+
return atomic(id, (note) => {
|
|
329
|
+
const same = todoItems(note.html).filter((t) => t.id && t.id === item);
|
|
330
|
+
const now = same[0];
|
|
331
|
+
if (!now) throw new Error('that to-do is no longer in the note');
|
|
332
|
+
// a note written by hand may name two to-dos alike: which one is meant cannot be told
|
|
333
|
+
if (same.length > 1) throw new Error('two to-dos of this note cannot be told apart: tick it in the note');
|
|
334
|
+
if (now.checked === (checked === true)) return null;
|
|
335
|
+
const html = setChecked(note.html, item, checked === true);
|
|
336
|
+
if (html === null) throw new Error('that to-do is no longer in the note');
|
|
337
|
+
note.html = html;
|
|
338
|
+
return { kind: 'tick', item, checked: checked === true };
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* What happened to a note since the revision an editor holds. { rev, ops }
|
|
344
|
+
* while every change since was an addition or a tick: the changes, oldest
|
|
345
|
+
* first. Otherwise { rev, note }: the whole note, to take in their place.
|
|
346
|
+
*/
|
|
347
|
+
function noteChanges({ id, since } = {}) {
|
|
348
|
+
const note = need(id);
|
|
349
|
+
if (!Number.isInteger(since) || since > note.rev) return { rev: note.rev, note: whole(note) };
|
|
350
|
+
const ops = [];
|
|
351
|
+
for (let r = since + 1; r <= note.rev; r++) {
|
|
352
|
+
const j = note.journal.find((e) => e.rev === r);
|
|
353
|
+
if (!j) return { rev: note.rev, note: whole(note) };
|
|
354
|
+
ops.push(j.op);
|
|
355
|
+
}
|
|
356
|
+
return { rev: note.rev, ops, links: note.links, pinned: note.pinned };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Out of the notes: moved to the trash, where restoreNote finds it. Nothing is deleted. */
|
|
360
|
+
function removeNote({ id } = {}) {
|
|
361
|
+
return store.locked(() => {
|
|
362
|
+
need(id);
|
|
363
|
+
store.move(id, 'notes', 'trash');
|
|
364
|
+
return { ok: true };
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function restoreNote({ id } = {}) {
|
|
369
|
+
return store.locked(() => {
|
|
370
|
+
checkId(id);
|
|
371
|
+
if (!load(id, 'trash')) throw new Error(GONE);
|
|
372
|
+
if (store.has(id, 'notes')) throw new Error('a note of that name is there already');
|
|
373
|
+
store.move(id, 'trash', 'notes');
|
|
374
|
+
return whole(need(id));
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Keep a picture for the notes: `data`, its bytes in base64. It is named by
|
|
380
|
+
* what it holds, so the same picture kept twice is kept once. { id,
|
|
381
|
+
* contentType, size }: the id is what a note's text names it by.
|
|
382
|
+
*/
|
|
383
|
+
function addNotePicture({ data } = {}) {
|
|
384
|
+
if (typeof data !== 'string' || !data) throw new Error('a picture is its bytes, in base64');
|
|
385
|
+
if (data.length > Math.ceil(MAX_PICTURE / 3) * 4 + 4) throw new Error(`that picture is more than ${mb(MAX_PICTURE)}`);
|
|
386
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(data)) throw new Error('a picture is its bytes, in base64');
|
|
387
|
+
const bytes = Buffer.from(data, 'base64');
|
|
388
|
+
if (bytes.length > MAX_PICTURE) throw new Error(`that picture is more than ${mb(MAX_PICTURE)}`);
|
|
389
|
+
const kind = Object.entries(PICTURE_TYPES).find(([, k]) => k.is(bytes));
|
|
390
|
+
if (!kind) throw new Error('a picture is a whole PNG, JPEG, GIF or WebP');
|
|
391
|
+
const id = crypto.createHash('sha256').update(bytes).digest('hex').slice(0, 32);
|
|
392
|
+
const name = `${id}.${kind[0]}`;
|
|
393
|
+
// there already, whole: not written again. (One cut short, or changed by hand, is put right.)
|
|
394
|
+
if (store.pictures.size(name) !== bytes.length) store.pictures.put(name, bytes);
|
|
395
|
+
return { id, contentType: kind[1].type, size: bytes.length };
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Bring a picture in from the web, once: what was pasted into a note named it
|
|
400
|
+
* (a page's picture, a Markdown ``), and the note is to hold a
|
|
401
|
+
* copy, so that it never asks that site again. Fetched as mail's pictures are
|
|
402
|
+
* (the host's safe fetch: https only, to a public address, a deadline, a cap
|
|
403
|
+
* on the bytes, no cookies, no Referer), then kept as any picture: { id, … }.
|
|
404
|
+
*/
|
|
405
|
+
async function fetchNotePicture({ url } = {}, get = fetch) {
|
|
406
|
+
if (typeof get !== 'function') throw new Error('pictures cannot be fetched here');
|
|
407
|
+
if (typeof url !== 'string' || !/^https:\/\//i.test(url) || url.length > 2000) throw new Error('a picture is fetched from an https address');
|
|
408
|
+
// a few at a time, and not a crowd waiting: whoever asks (a paste of many pictures) does not make this process fetch them all at once
|
|
409
|
+
if (fetching.waiting >= FETCH_WAITING) throw new Error('that picture could not be fetched: too many are being fetched at once');
|
|
410
|
+
if (fetching.now >= FETCH_AT_ONCE) { fetching.waiting++; try { await new Promise((go) => fetching.line.push(go)); } finally { fetching.waiting--; } }
|
|
411
|
+
fetching.now++;
|
|
412
|
+
let got;
|
|
413
|
+
try {
|
|
414
|
+
got = await get(url, { maxBytes: MAX_PICTURE, accept: (type) => /^image\/(png|jpeg|gif|webp)\b/i.test(type), acceptHeader: 'image/png,image/jpeg,image/gif,image/webp', timeoutMs: 10_000 });
|
|
415
|
+
} catch (e) {
|
|
416
|
+
throw new Error(`that picture could not be fetched: ${e?.message || e}`);
|
|
417
|
+
} finally {
|
|
418
|
+
fetching.now--;
|
|
419
|
+
fetching.line.shift()?.();
|
|
420
|
+
}
|
|
421
|
+
return addNotePicture({ data: got.body.toString('base64') });
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** A picture of the notes, by its id: { data (base64), contentType, size }. */
|
|
425
|
+
function notePicture({ id } = {}) {
|
|
426
|
+
if (!PICTURE_ID.test(str(id))) throw new Error('which picture?');
|
|
427
|
+
for (const [ext, kind] of Object.entries(PICTURE_TYPES)) {
|
|
428
|
+
const name = `${id}.${ext}`;
|
|
429
|
+
const size = store.pictures.size(name);
|
|
430
|
+
if (size < 0) continue;
|
|
431
|
+
if (size > MAX_PICTURE) break; // (not read at all: no picture of the notes is that large)
|
|
432
|
+
const bytes = store.pictures.get(name, MAX_PICTURE);
|
|
433
|
+
if (!bytes) continue;
|
|
434
|
+
// (one put there by hand under a picture's name: what it holds decides, not its name)
|
|
435
|
+
if (!kind.is(bytes)) break;
|
|
436
|
+
return { data: bytes.toString('base64'), contentType: kind.type, size: bytes.length };
|
|
437
|
+
}
|
|
438
|
+
throw new Error('that picture is no longer there');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/** Tell `onChange(id)` each time a note changes, whoever changed it. Returns the function that stops it. */
|
|
442
|
+
const watchNotes = (onChange) => store.watch(onChange);
|
|
443
|
+
|
|
444
|
+
return { listNotes, readNote, saveNote, addToNote, unlinkNote, tickNote, noteChanges, removeNote, restoreNote, addNotePicture, fetchNotePicture, notePicture, watchNotes };
|
|
445
|
+
}
|
package/src/core/otp.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// A verification code in a mail: the six digits a site sends to prove an
|
|
2
|
+
// address is yours ("Your verification code is 585026").
|
|
3
|
+
//
|
|
4
|
+
// The rule is caution. A wrong "code" offered for copying is worse than none,
|
|
5
|
+
// and mail is full of numbers that are not codes: amounts, years, order,
|
|
6
|
+
// account and phone numbers, meeting ids. Being near the word "code" is not
|
|
7
|
+
// enough (the number nearest it is as often an order number): a number is
|
|
8
|
+
// taken only when the sentence gives it as the code. One of:
|
|
9
|
+
//
|
|
10
|
+
// named "Security code 930155" the words, then the number
|
|
11
|
+
// given "…verification code for your account is 585026", "Use this code to sign in: 482913"
|
|
12
|
+
// leading "585026 is your verification code"
|
|
13
|
+
// told "Enter 118822 to continue" in a mail that names a code
|
|
14
|
+
// alone the number on a line of its own, under words that name a code
|
|
15
|
+
//
|
|
16
|
+
// and never a number that reads as something else (see `numbers`).
|
|
17
|
+
//
|
|
18
|
+
// A detector of the core: it works on any message, whichever connector brought it. How a body becomes plain text is
|
|
19
|
+
// the connector's (makeFindCode(plainText)); src/otp.js gives mail's.
|
|
20
|
+
|
|
21
|
+
// words that name a code, in the languages of the mail read here
|
|
22
|
+
const STRONG = new RegExp([
|
|
23
|
+
String.raw`(?:verification|verify|security|secure|log[- ]?in|sign[- ]?in|sign[- ]?up|authentication|confirmation|access|activation|one[- ]time|single[- ]use|temporary|two[- ]factor|2fa|mfa|reset|recovery|guard)\s+(?:pass)?(?:code|pin|password|passcode)`,
|
|
24
|
+
String.raw`\botp\b|\bpasscode\b|one[- ]time\s+pass(?:word|code)|\d[- ]digit\s+code`,
|
|
25
|
+
String.raw`code\s+(?:de|d['’])\s*(?:v[ée]rification|s[ée]curit[ée]|confirmation|connexion|validation|acc[èe]s|authentification|activation)|code\s+[àa]\s+(?:usage\s+unique|\d\s+chiffres)|mot\s+de\s+passe\s+[àa]\s+usage\s+unique`,
|
|
26
|
+
String.raw`c[oó]digo\s+de\s+(?:verificaci[oó]n|seguridad|acceso|confirmaci[oó]n|inicio|activaci[oó]n|verifica[cç][aã]o|seguran[cç]a|acesso|confirma[cç][aã]o)`,
|
|
27
|
+
String.raw`codice\s+di\s+(?:verifica|sicurezza|accesso|conferma)`,
|
|
28
|
+
String.raw`(?:best[äa]tigungs|sicherheits|verifizierungs|anmelde|zugangs|einmal)-?code|(?:verificatie|beveiligings|bevestigings|inlog)code`
|
|
29
|
+
].join('|'), 'gi');
|
|
30
|
+
|
|
31
|
+
// the bare word counts with "your" before it ("your code"), with "the/this" ("this code", which then has to
|
|
32
|
+
// lead to the number), or at the start of a line ("Code: 482913"); never "order code", "post code", "error code"
|
|
33
|
+
const MINE = String.raw`your|votre|ton|ihr|dein|tu|su|seu|uw|je`;
|
|
34
|
+
const THE = String.raw`the|this|le|ce|un|der|dieser|el|este|il|o`;
|
|
35
|
+
const BARE = new RegExp(String.raw`(?:\b(${MINE})\s+|\b(${THE})\s+|(?<=(?:^|\n|[(\[–—])\s?))(?:code|c[oó]digo|codice|pin|otp)\b`, 'gi');
|
|
36
|
+
|
|
37
|
+
// invitations to a call carry ids and passcodes of their own: not this kind of code
|
|
38
|
+
const MEETING = /meeting\s+(?:id|number)|id\s+de\s+(?:la\s+)?r[ée]union|zoom\.us|teams\.microsoft|meet\.google|webex|dial[- ]in|conference\s+(?:id|call)|join\s+(?:the\s+|this\s+|zoom\s+|microsoft\s+teams\s+)?meeting/i;
|
|
39
|
+
// a booking's "confirmation code" is a reference, not something to type back within ten minutes
|
|
40
|
+
const BOOKING = /flight|booking|reservation|r[ée]servation|itinerary|boarding|check-in|hotel|your\s+table|table\s+for|order\s+(?:number|no\b|#)/i;
|
|
41
|
+
|
|
42
|
+
const YEAR = /^(?:19|20)\d\d$/;
|
|
43
|
+
// what says "here it is" right before the number
|
|
44
|
+
const GIVES = /(?:(?<![A-Za-zÀ-ÿ])(?:is|est(?:\s+le)?|es|é|è|ist|lautet)|[:=–—]|\s-)\s*$/i;
|
|
45
|
+
// what a number before it is called makes it: an order, an account, a card, a phone number, an amount
|
|
46
|
+
const LABEL = /(?:order|commande|pedido|bestellung|ending(?:\s+in)?|ends\s+in|terminant\s+par|card|carte|account|acct|compte|ref(?:erence)?\.?|r[ée]f(?:[ée]rence)?\.?|invoice|facture|ticket|case|dossier|booking|r[ée]servation|customer|client|member|\bid|n°|nº|\bno\.|number|num[ée]ro|t[ée]l\.?|phone|t[ée]l[ée]phone|call|appelez|fax|zip|postal|\bof|\bde|\bdu|after|\bfor|pour|©|\(c\)|EUR|USD|GBP|CAD|FCFA|CFA|XOF|XAF|[€$£])\s*[:#]?\s*$/i;
|
|
47
|
+
const UNIT = /^\s?(?:(?:EUR|USD|GBP|CAD|FCFA|CFA|XOF|XAF|kg|km|seconds?|secondes?|secs?|minutes?|mins?|hours?|heures?|days?|jours?|points?|pts)\b|[€$£])/i;
|
|
48
|
+
const TOLD = /\b(?:enter|use|type|input|saisissez|entrez|utilisez|tapez|introduce|ingresa|usa|gib|geben\s+sie)\s+(?:(?:the|this|le|ce)\s+code\s+)?$/i;
|
|
49
|
+
const LEADS = /^\s*(?:is|est|es|ist|é)\s+(?:your|votre|ton|tu|su|ihr|dein|the|le|o\s+seu|il\s+tuo|uw|je)\b[^.!?\n]{0,60}?\b(?:code|c[oó]digo|codice|pin|otp|passcode|password|mot\s+de\s+passe)\b/i;
|
|
50
|
+
|
|
51
|
+
/** Links and addresses out (their digits are nobody's code), lines kept: a number alone on its line means something. */
|
|
52
|
+
function clean(text) {
|
|
53
|
+
return String(text || '')
|
|
54
|
+
// word by word (one pass): a pattern looking for an "@" from every letter of a long word would take the square of its length
|
|
55
|
+
.replace(/\S+/g, (word) => (word.includes('@') || word.includes('://') || /^\W*www\./i.test(word) ? ' ' : word))
|
|
56
|
+
.replace(/\r\n?/g, '\n')
|
|
57
|
+
.replace(/[ \t ]+/g, ' ')
|
|
58
|
+
.replace(/ ?\n ?/g, '\n')
|
|
59
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
60
|
+
.trim();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The numbers of a text that could be a code at all: 4 to 8 digits in one
|
|
65
|
+
* run, in two equal groups ("482 913") or spelled out ("4 8 2 9 1 3"), and
|
|
66
|
+
* capitals with digits ("K7XM9Q"). A longer or oddly grouped run is a phone
|
|
67
|
+
* number or an id and is left whole, never cut to a part of it; so is
|
|
68
|
+
* anything written as an amount, a time, a reference or a measure.
|
|
69
|
+
*/
|
|
70
|
+
function numbers(text) {
|
|
71
|
+
const out = [];
|
|
72
|
+
for (const m of text.matchAll(/\d+(?:[ -]\d+)*/g)) {
|
|
73
|
+
const groups = m[0].split(/[ -]/);
|
|
74
|
+
const code = groups.join('');
|
|
75
|
+
const one = groups.length === 1;
|
|
76
|
+
const pair = groups.length === 2 && groups[0].length === groups[1].length && groups[0].length >= 3;
|
|
77
|
+
const spelled = groups.length >= 4 && groups.every((g) => g.length === 1);
|
|
78
|
+
if (!(one || pair || spelled) || code.length < 4 || code.length > 8) continue;
|
|
79
|
+
const at = m.index;
|
|
80
|
+
const end = at + m[0].length;
|
|
81
|
+
const before = text.slice(Math.max(0, at - 3), at);
|
|
82
|
+
const prefixed = /(?:^|[^A-Za-z0-9])[A-Z]-$/.test(before); // "G-482913": the letter is the sender's mark
|
|
83
|
+
if (!prefixed && /[A-Za-z0-9$€£#@/.,+=&?_-]$/.test(before)) continue;
|
|
84
|
+
const after = text.slice(end, end + 14);
|
|
85
|
+
// (a capital that starts a word may follow at once: text made from HTML loses the break, "751157Ce code expirera")
|
|
86
|
+
if (/^(?:[#%]|[.,:/]\d|[a-z]|[A-Z](?![a-z]))/.test(after) || UNIT.test(after)) continue;
|
|
87
|
+
if (LABEL.test(text.slice(Math.max(0, at - 30), at).replace(/\n/g, ' '))) continue;
|
|
88
|
+
out.push({ at, end, code, mixed: false });
|
|
89
|
+
}
|
|
90
|
+
for (const m of text.matchAll(/(?<![A-Za-z0-9-])(?=[A-Z0-9]*\d)(?=[A-Z0-9]*[A-Z])[A-Z0-9]{5,8}(?![A-Za-z0-9-])/g)) {
|
|
91
|
+
out.push({ at: m.index, end: m.index + m[0].length, code: m[0], mixed: true });
|
|
92
|
+
}
|
|
93
|
+
return out.sort((a, b) => a.at - b.at);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Where the text names a code: [{ end, kind }] with kind strong | mine | the | line. */
|
|
97
|
+
function mentions(text, booking) {
|
|
98
|
+
const out = [];
|
|
99
|
+
for (const m of text.matchAll(STRONG)) {
|
|
100
|
+
if (booking && /^confirm/i.test(m[0])) continue;
|
|
101
|
+
out.push({ end: m.index + m[0].length, kind: 'strong' });
|
|
102
|
+
}
|
|
103
|
+
for (const m of text.matchAll(BARE)) out.push({ end: m.index + m[0].length, kind: m[1] ? 'mine' : m[2] ? 'the' : 'line' });
|
|
104
|
+
return out.sort((a, b) => a.end - b.end);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The code one text gives, or null. `named`: the mail names a code somewhere; `titled`: its subject does. */
|
|
108
|
+
function codeIn(text, { named, titled, booking }) {
|
|
109
|
+
const found = numbers(text);
|
|
110
|
+
if (!found.length) return null;
|
|
111
|
+
const said = mentions(text, booking);
|
|
112
|
+
for (const c of found) {
|
|
113
|
+
const year = YEAR.test(c.code);
|
|
114
|
+
const lead = text.slice(Math.max(0, c.at - 40), c.at);
|
|
115
|
+
const gives = GIVES.test(lead);
|
|
116
|
+
const last = said.filter((m) => m.end <= c.at).pop();
|
|
117
|
+
if (last) {
|
|
118
|
+
const gap = text.slice(last.end, c.at);
|
|
119
|
+
// named: the words, then the number ("Security code 930155"); "the code 1234 at checkout" is not that
|
|
120
|
+
if (!year && !gap.trim() && (last.kind === 'strong' || last.kind === 'mine')) return c.code;
|
|
121
|
+
// given: the words lead to it within the sentence ("…code for your account is 585026", "this code to sign in: 482913")
|
|
122
|
+
// (a break before the number itself is layout: "…votre code à 6 chiffres :" and the code under it)
|
|
123
|
+
if (gives && gap.length <= (c.mixed ? 40 : 90) && !/[.!?](?:\s|$)|\n\n/.test(gap.trimEnd())) return c.code;
|
|
124
|
+
}
|
|
125
|
+
if (year) continue;
|
|
126
|
+
// alone on its line, under words that name a code (or in a mail whose subject does);
|
|
127
|
+
// letters and digits only where both the subject and the mail say so
|
|
128
|
+
const alone = /(?:^|\n) ?$/.test(text.slice(Math.max(0, c.at - 2), c.at)) && /^ ?(?:\n|$)/.test(text.slice(c.end, c.end + 2));
|
|
129
|
+
if (alone && (c.mixed ? titled && named : titled || (last && c.at - last.end <= 250))) return c.code;
|
|
130
|
+
if (c.mixed) continue;
|
|
131
|
+
// leading: "585026 is your verification code"
|
|
132
|
+
if (LEADS.test(text.slice(c.end, c.end + 90))) return c.code;
|
|
133
|
+
// told: "Enter 118822 to continue", in a mail that names a code
|
|
134
|
+
if (named && TOLD.test(lead)) return c.code;
|
|
135
|
+
}
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* findCode(subject, body): the verification code a mail carries, or null: looked for in the subject first, then in
|
|
141
|
+
* the start of the body (`body` is the mail's text part; `plainText(body)` its words, as the connector reads them).
|
|
142
|
+
*/
|
|
143
|
+
export const makeFindCode = (plainText) => function findCode(subject, body) {
|
|
144
|
+
const title = clean(subject).replace(/\n/g, ' ');
|
|
145
|
+
const text = clean(plainText(String(body || '').slice(0, 12000))).slice(0, 4000);
|
|
146
|
+
const all = `${title}\n${text}`;
|
|
147
|
+
if (MEETING.test(`${String(subject || '')}\n${String(body || '').slice(0, 12000)}`)) return null;
|
|
148
|
+
const booking = BOOKING.test(all);
|
|
149
|
+
const named = mentions(all, booking).some((m) => m.kind === 'strong');
|
|
150
|
+
const titled = mentions(title, booking).some((m) => m.kind === 'strong' || m.kind === 'mine' || m.kind === 'line');
|
|
151
|
+
return codeIn(title, { named, titled: false, booking }) ?? codeIn(text, { named, titled, booking });
|
|
152
|
+
};
|