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
package/src/backup.js
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
// Export and import: what lives only on this Mac, as one encrypted file, from the terminal alone (no page asks for
|
|
2
|
+
// it, the relay carries none of it, no agent's tool reaches it).
|
|
3
|
+
//
|
|
4
|
+
// sideora export <file> [--no-secrets] [--with-relay]
|
|
5
|
+
// sideora import <file> [--replace] [--dry-run] [--yes]
|
|
6
|
+
//
|
|
7
|
+
// What a file holds: the settings (config.json: the accounts, the signatures, what is shown), the rules, the notes
|
|
8
|
+
// with their pictures, the assistant's chats with the files attached to them, the AI connections, the sounds; and,
|
|
9
|
+
// unless left out (--no-secrets), what the Keychain holds for them: the accounts' passwords, their Google sign-ins,
|
|
10
|
+
// the 1Password token, the key of the AI connections. Not the mail's cache (it is read again), nor the logs, nor
|
|
11
|
+
// which browsers are paired; and not this Mac's place at the relay with its paired devices, unless asked for
|
|
12
|
+
// (--with-relay: to move the hub to another Mac; two Macs under one place would take it from each other).
|
|
13
|
+
//
|
|
14
|
+
// The file: "MWX1", a header (how the key is made of the passphrase: scrypt, its salt; the nonce), then everything
|
|
15
|
+
// else gzipped and sealed with AES-256-GCM under that key, the header being part of what is sealed. Nothing of it
|
|
16
|
+
// is used before the whole has opened: a wrong passphrase, or a file changed by one byte, opens nothing.
|
|
17
|
+
//
|
|
18
|
+
// Importing adds what is missing and leaves what is there: an account of a name not here, a rule of a name not
|
|
19
|
+
// here, a note or a chat of an id not here, a signature not here. `replace`: what the file holds takes the place
|
|
20
|
+
// of what is here, where both have it (nothing else is removed). The plan is made first (planImport), shown, and
|
|
21
|
+
// only then applied.
|
|
22
|
+
|
|
23
|
+
import crypto from 'node:crypto';
|
|
24
|
+
import fs from 'node:fs';
|
|
25
|
+
import path from 'node:path';
|
|
26
|
+
import zlib from 'node:zlib';
|
|
27
|
+
import YAML from 'yaml';
|
|
28
|
+
|
|
29
|
+
const MAGIC = Buffer.from('MWX1');
|
|
30
|
+
const SCRYPT = { N: 1 << 17, r: 8, p: 1 };
|
|
31
|
+
const MAX_PLAIN = 1024 * 1024 * 1024; // of what one file holds, before it is sealed
|
|
32
|
+
const MIN_PASSPHRASE = 8;
|
|
33
|
+
|
|
34
|
+
/** Where each secret is in the Keychain: [service, account]. */
|
|
35
|
+
export const SECRETS = {
|
|
36
|
+
password: (name) => ['sideora', name],
|
|
37
|
+
google: (name) => ['sideora', `google:${name}`],
|
|
38
|
+
microsoft: (name) => ['sideora', `microsoft:${name}`],
|
|
39
|
+
onePassword: () => ['sideora-1password', 'service-account-token'],
|
|
40
|
+
ai: () => ['sideora-ai', 'connections-key'],
|
|
41
|
+
relay: () => ['sideora-relay', 'membership']
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** The files of a data folder that an export holds: as paths from it, with forward slashes. */
|
|
45
|
+
const HELD = [
|
|
46
|
+
/^config\.json$/, /^rules\.yaml$/, /^ai\.json$/,
|
|
47
|
+
/^notes\/[a-z0-9]{6,24}\.json$/, /^notes\/trash\/[\w.-]{1,120}\.json$/, /^notes\/pictures\/[0-9a-f]{32}\.(png|jpg|gif|webp)$/,
|
|
48
|
+
/^chats\/[a-z0-9]{6,24}\.json$/, /^chats\/trash\/[\w.-]{1,120}\.json$/, /^chats\/files\/[0-9a-f]{32}$/,
|
|
49
|
+
/^sounds\/(?!\.)[\w. -]{1,120}$/
|
|
50
|
+
];
|
|
51
|
+
const RELAY_FILE = /^relay\.json$/;
|
|
52
|
+
const held = (p, relay) => HELD.some((r) => r.test(p)) || (relay && RELAY_FILE.test(p));
|
|
53
|
+
|
|
54
|
+
function walk(dir, under = '') {
|
|
55
|
+
let names;
|
|
56
|
+
try { names = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
|
|
57
|
+
return names.flatMap((n) => {
|
|
58
|
+
const rel = under ? `${under}/${n.name}` : n.name;
|
|
59
|
+
if (n.isDirectory()) return walk(path.join(dir, n.name), rel);
|
|
60
|
+
return n.isFile() ? [rel] : []; // (no link is followed, nothing that is not a file is taken)
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const json = (text) => { try { return JSON.parse(text); } catch { return null; } };
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Everything an export holds, read from the data folder and the Keychain.
|
|
68
|
+
* `keychain`: { get(service, account) → string | null }. → { meta, files: [{ path, mode, data }], secrets }
|
|
69
|
+
*/
|
|
70
|
+
export function collect({ home, keychain, secrets = true, relay = false, label = '' }) {
|
|
71
|
+
const files = [];
|
|
72
|
+
for (const top of ['config.json', 'rules.yaml', 'ai.json', ...(relay ? ['relay.json'] : [])]) {
|
|
73
|
+
try { files.push({ path: top, mode: 0o600, data: fs.readFileSync(path.join(home, top)) }); } catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
74
|
+
}
|
|
75
|
+
for (const dir of ['notes', 'chats', 'sounds']) {
|
|
76
|
+
for (const rel of walk(path.join(home, dir), dir)) {
|
|
77
|
+
if (!held(rel, relay)) continue; // (a lock, a file half written, anything this does not know)
|
|
78
|
+
files.push({ path: rel, mode: 0o600, data: fs.readFileSync(path.join(home, rel)) });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const kept = { passwords: {}, google: {}, microsoft: {}, onePassword: null, ai: null, relay: null };
|
|
82
|
+
if (secrets) {
|
|
83
|
+
const config = json(files.find((f) => f.path === 'config.json')?.data.toString('utf8') ?? '') ?? {};
|
|
84
|
+
for (const name of Object.keys(config.accounts ?? {})) {
|
|
85
|
+
const password = keychain.get(...SECRETS.password(name)); // (throws when the Keychain refused: said, rather than a file made without it)
|
|
86
|
+
if (password) kept.passwords[name] = password;
|
|
87
|
+
const google = keychain.get(...SECRETS.google(name));
|
|
88
|
+
if (google) kept.google[name] = google;
|
|
89
|
+
const microsoft = keychain.get(...SECRETS.microsoft(name));
|
|
90
|
+
if (microsoft) kept.microsoft[name] = microsoft;
|
|
91
|
+
}
|
|
92
|
+
kept.onePassword = keychain.get(...SECRETS.onePassword());
|
|
93
|
+
if (files.some((f) => f.path === 'ai.json')) kept.ai = keychain.get(...SECRETS.ai());
|
|
94
|
+
if (relay && files.some((f) => f.path === 'relay.json')) kept.relay = keychain.get(...SECRETS.relay());
|
|
95
|
+
}
|
|
96
|
+
return { meta: { v: 1, created: new Date().toISOString(), label, secrets: !!secrets, relay: !!relay }, files, secrets: kept };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A bundle as one run of bytes: an index (what it is, its secrets, each file's path and size), then the files' bytes. */
|
|
100
|
+
function pack(bundle) {
|
|
101
|
+
const index = Buffer.from(JSON.stringify({ meta: bundle.meta, secrets: bundle.secrets, files: bundle.files.map((f) => ({ path: f.path, mode: f.mode, size: f.data.length })) }));
|
|
102
|
+
const head = Buffer.alloc(4);
|
|
103
|
+
head.writeUInt32BE(index.length);
|
|
104
|
+
const all = Buffer.concat([head, index, ...bundle.files.map((f) => f.data)]);
|
|
105
|
+
if (all.length > MAX_PLAIN) throw new Error('there is too much to export in one file (over 1 GB): the chats\' files are the likely weight');
|
|
106
|
+
return all;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function unpack(all) {
|
|
110
|
+
if (all.length < 4) throw new Error('this is not an export of Sideora');
|
|
111
|
+
const n = all.readUInt32BE(0);
|
|
112
|
+
const index = json(all.subarray(4, 4 + n).toString('utf8'));
|
|
113
|
+
if (!index || index.meta?.v !== 1 || !Array.isArray(index.files)) throw new Error('this export is of a kind this version does not read');
|
|
114
|
+
let at = 4 + n;
|
|
115
|
+
const files = index.files.map((f) => {
|
|
116
|
+
if (typeof f.path !== 'string' || !Number.isInteger(f.size) || f.size < 0 || at + f.size > all.length) throw new Error('this export is damaged');
|
|
117
|
+
const data = all.subarray(at, at + f.size);
|
|
118
|
+
at += f.size;
|
|
119
|
+
return { path: f.path, mode: 0o600, data };
|
|
120
|
+
});
|
|
121
|
+
const s = index.secrets && typeof index.secrets === 'object' ? index.secrets : {};
|
|
122
|
+
const texts = (o) => Object.fromEntries(Object.entries(o && typeof o === 'object' ? o : {}).filter(([, v]) => typeof v === 'string' && v));
|
|
123
|
+
const text = (v) => (typeof v === 'string' && v ? v : null);
|
|
124
|
+
return { meta: index.meta, files, secrets: { passwords: texts(s.passwords), google: texts(s.google), microsoft: texts(s.microsoft ?? {}), onePassword: text(s.onePassword), ai: text(s.ai), relay: text(s.relay) } };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const keyOf = (passphrase, salt, { N, r, p }) => crypto.scryptSync(passphrase.normalize('NFKC'), salt, 32, { N, r, p, maxmem: 256 * 1024 * 1024 });
|
|
128
|
+
|
|
129
|
+
/** A bundle, sealed under a passphrase: the bytes of the file. */
|
|
130
|
+
export function seal(bundle, passphrase) {
|
|
131
|
+
if (typeof passphrase !== 'string' || passphrase.length < MIN_PASSPHRASE) throw new Error(`the passphrase is ${MIN_PASSPHRASE} characters at least`);
|
|
132
|
+
const salt = crypto.randomBytes(16);
|
|
133
|
+
const iv = crypto.randomBytes(12);
|
|
134
|
+
const header = Buffer.from(JSON.stringify({ v: 1, kdf: 'scrypt', ...SCRYPT, salt: salt.toString('base64'), iv: iv.toString('base64'), created: bundle.meta.created }));
|
|
135
|
+
const size = Buffer.alloc(4);
|
|
136
|
+
size.writeUInt32BE(header.length);
|
|
137
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', keyOf(passphrase, salt, SCRYPT), iv);
|
|
138
|
+
cipher.setAAD(Buffer.concat([MAGIC, size, header]));
|
|
139
|
+
const body = Buffer.concat([cipher.update(zlib.gzipSync(pack(bundle))), cipher.final()]);
|
|
140
|
+
return Buffer.concat([MAGIC, size, header, body, cipher.getAuthTag()]);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The bundle of a file, opened with its passphrase. Throws when it is not one, when the passphrase is another, or when it was changed. */
|
|
144
|
+
export function open(file, passphrase) {
|
|
145
|
+
if (!Buffer.isBuffer(file) || file.length < 8 + 16 || !file.subarray(0, 4).equals(MAGIC)) throw new Error('this is not an export of Sideora');
|
|
146
|
+
const n = file.readUInt32BE(4);
|
|
147
|
+
const header = n > 0 && n < 4096 ? json(file.subarray(8, 8 + n).toString('utf8')) : null;
|
|
148
|
+
const ok = (v, max) => Number.isInteger(v) && v > 0 && v <= max;
|
|
149
|
+
if (!header || header.v !== 1 || header.kdf !== 'scrypt' || !ok(header.N, 1 << 20) || !ok(header.r, 16) || !ok(header.p, 4)) throw new Error('this export is of a kind this version does not read');
|
|
150
|
+
const salt = Buffer.from(String(header.salt), 'base64');
|
|
151
|
+
const iv = Buffer.from(String(header.iv), 'base64');
|
|
152
|
+
if (salt.length < 8 || iv.length !== 12) throw new Error('this export is damaged');
|
|
153
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', keyOf(String(passphrase ?? ''), salt, header), iv);
|
|
154
|
+
decipher.setAAD(file.subarray(0, 8 + n));
|
|
155
|
+
decipher.setAuthTag(file.subarray(file.length - 16));
|
|
156
|
+
let plain;
|
|
157
|
+
try { plain = Buffer.concat([decipher.update(file.subarray(8 + n, file.length - 16)), decipher.final()]); } catch { throw new Error('the passphrase is not this file\'s, or the file was changed'); }
|
|
158
|
+
let all;
|
|
159
|
+
try { all = zlib.gunzipSync(plain, { maxOutputLength: MAX_PLAIN }); } catch { throw new Error('this export is damaged'); }
|
|
160
|
+
return unpack(all);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// --- importing ---------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
const exists = (p) => { try { fs.statSync(p); return true; } catch { return false; } };
|
|
166
|
+
const idOf = (o) => (o && typeof o === 'object' && typeof o.id === 'string' ? o.id : null);
|
|
167
|
+
|
|
168
|
+
/** The settings of the file put into those here: what is missing added; with `replace`, what both have taken from the file. → { config, did } */
|
|
169
|
+
function mergeConfig(here, theirs, replace) {
|
|
170
|
+
const out = structuredClone(here ?? {});
|
|
171
|
+
const did = [];
|
|
172
|
+
out.accounts ??= {};
|
|
173
|
+
for (const [name, account] of Object.entries(theirs.accounts ?? {})) {
|
|
174
|
+
if (!(name in out.accounts)) { out.accounts[name] = account; did.push({ kind: 'account', what: name, action: 'add' }); }
|
|
175
|
+
else if (replace) { out.accounts[name] = account; did.push({ kind: 'account', what: name, action: 'replace' }); }
|
|
176
|
+
else did.push({ kind: 'account', what: name, action: 'skip' });
|
|
177
|
+
}
|
|
178
|
+
if (!out.defaultAccount && theirs.defaultAccount && out.accounts[theirs.defaultAccount]) out.defaultAccount = theirs.defaultAccount;
|
|
179
|
+
let changed = 0;
|
|
180
|
+
for (const [key, value] of Object.entries(theirs)) {
|
|
181
|
+
if (key === 'accounts' || key === 'defaultAccount') continue;
|
|
182
|
+
const mine = out[key];
|
|
183
|
+
if (mine === undefined || replace) { if (JSON.stringify(mine) !== JSON.stringify(value)) { out[key] = value; changed++; } continue; }
|
|
184
|
+
// a list of things with an id (the signatures): those not here; a table (a signature's details by account): the entries not here
|
|
185
|
+
if (Array.isArray(mine) && Array.isArray(value) && value.every(idOf)) {
|
|
186
|
+
const have = new Set(mine.map(idOf));
|
|
187
|
+
const more = value.filter((v) => !have.has(idOf(v)));
|
|
188
|
+
if (more.length) { out[key] = [...mine, ...more]; changed++; }
|
|
189
|
+
} else if (mine && value && typeof mine === 'object' && typeof value === 'object' && !Array.isArray(mine) && !Array.isArray(value)) {
|
|
190
|
+
const more = Object.entries(value).filter(([k]) => !(k in mine));
|
|
191
|
+
if (more.length) { out[key] = { ...mine, ...Object.fromEntries(more) }; changed++; }
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (changed) did.push({ kind: 'settings', what: `${changed} ${changed === 1 ? 'setting' : 'settings'} (signatures, what is shown…)`, action: replace ? 'replace' : 'add' });
|
|
195
|
+
return { config: out, did };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** The rules of the file put among those here, by name (what the person wrote in their file stays as written). → { text, did } */
|
|
199
|
+
function mergeRules(hereText, theirText, replace) {
|
|
200
|
+
const theirs = YAML.parse(theirText) || {};
|
|
201
|
+
const rules = Array.isArray(theirs.rules) ? theirs.rules.filter((r) => r && typeof r === 'object') : [];
|
|
202
|
+
if (hereText == null) return { text: theirText, did: rules.map((r, i) => ({ kind: 'rule', what: String(r.name || `rule ${i + 1}`), action: 'add' })) };
|
|
203
|
+
const doc = YAML.parseDocument(hereText);
|
|
204
|
+
const here = YAML.parse(hereText) || {};
|
|
205
|
+
const names = new Map((Array.isArray(here.rules) ? here.rules : []).map((r, i) => [String(r?.name ?? ''), i]));
|
|
206
|
+
const did = [];
|
|
207
|
+
if (!doc.has('rules') || !YAML.isSeq(doc.get('rules'))) doc.set('rules', doc.createNode([]));
|
|
208
|
+
const list = doc.get('rules');
|
|
209
|
+
for (const [i, r] of rules.entries()) {
|
|
210
|
+
const name = String(r.name || '');
|
|
211
|
+
const what = name || `rule ${i + 1}`;
|
|
212
|
+
if (name && names.has(name)) {
|
|
213
|
+
if (replace) { list.set(names.get(name), doc.createNode(r)); did.push({ kind: 'rule', what, action: 'replace' }); } else did.push({ kind: 'rule', what, action: 'skip' });
|
|
214
|
+
} else if (!name && !replace && (here.rules ?? []).some((x) => JSON.stringify(x) === JSON.stringify(r))) did.push({ kind: 'rule', what, action: 'skip' });
|
|
215
|
+
else { list.add(doc.createNode(r)); did.push({ kind: 'rule', what, action: 'add' }); }
|
|
216
|
+
}
|
|
217
|
+
if (theirs.quietHours && (!doc.has('quietHours') || replace)) doc.set('quietHours', doc.createNode(theirs.quietHours));
|
|
218
|
+
return { text: did.some((d) => d.action !== 'skip') || (theirs.quietHours && replace) ? String(doc) : hereText, did };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* What importing a bundle here would do, and how to do it. Nothing is written. `keychain`: { get, set }.
|
|
223
|
+
* → { actions: [{ kind, what, action: 'add' | 'replace' | 'skip', why? }], apply() }
|
|
224
|
+
*/
|
|
225
|
+
export function planImport(bundle, { home, keychain, replace = false }) {
|
|
226
|
+
const actions = [];
|
|
227
|
+
const writes = []; // [path from home, bytes]
|
|
228
|
+
const secrets = []; // [[service, account], value]
|
|
229
|
+
const at = (rel) => path.join(home, ...rel.split('/'));
|
|
230
|
+
const fileOf = (rel) => bundle.files.find((f) => f.path === rel);
|
|
231
|
+
for (const f of bundle.files) if (!held(f.path, true) || f.path.includes('..') || path.isAbsolute(f.path)) throw new Error(`this export names a file it should not hold (${f.path.slice(0, 60)}): nothing is imported`);
|
|
232
|
+
const had = (place) => { try { return keychain.get(...place) != null; } catch { return false; } };
|
|
233
|
+
|
|
234
|
+
// the settings and the accounts, each account with what the Keychain held for it
|
|
235
|
+
const theirConfig = fileOf('config.json') ? json(fileOf('config.json').data.toString('utf8')) : null;
|
|
236
|
+
if (theirConfig) {
|
|
237
|
+
const here = exists(at('config.json')) ? json(fs.readFileSync(at('config.json'), 'utf8')) : null;
|
|
238
|
+
if (exists(at('config.json')) && !here) throw new Error('the settings here (config.json) cannot be read: nothing is imported');
|
|
239
|
+
const { config, did } = mergeConfig(here, theirConfig, replace);
|
|
240
|
+
actions.push(...did);
|
|
241
|
+
if (did.some((d) => d.action !== 'skip')) writes.push(['config.json', Buffer.from(JSON.stringify(config, null, 2) + '\n')]);
|
|
242
|
+
// (an account's secrets: with the account when it comes from the file, and wherever the Keychain lacks them, an
|
|
243
|
+
// account kept as it is here included: a Keychain that lost them, or an import that stopped before them)
|
|
244
|
+
for (const d of did.filter((x) => x.kind === 'account')) {
|
|
245
|
+
for (const [place, value] of [[SECRETS.password(d.what), bundle.secrets.passwords[d.what]], [SECRETS.google(d.what), bundle.secrets.google[d.what]], [SECRETS.microsoft(d.what), bundle.secrets.microsoft?.[d.what]]]) {
|
|
246
|
+
if (!value) continue;
|
|
247
|
+
if (d.action !== 'skip') secrets.push([place, value]);
|
|
248
|
+
else if (!had(place)) { secrets.push([place, value]); actions.push({ kind: 'secret', what: `the ${place[1].startsWith('google:') ? 'Google sign-in' : place[1].startsWith('microsoft:') ? 'Microsoft sign-in' : 'password'} of ${d.what}, missing here`, action: 'add' }); }
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (bundle.secrets.onePassword) {
|
|
253
|
+
const there = had(SECRETS.onePassword());
|
|
254
|
+
if (!there || replace) secrets.push([SECRETS.onePassword(), bundle.secrets.onePassword]);
|
|
255
|
+
actions.push({ kind: 'secret', what: 'the 1Password token', action: there ? (replace ? 'replace' : 'skip') : 'add' });
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const theirRules = fileOf('rules.yaml');
|
|
259
|
+
if (theirRules) {
|
|
260
|
+
const hereText = exists(at('rules.yaml')) ? fs.readFileSync(at('rules.yaml'), 'utf8') : null;
|
|
261
|
+
const { text, did } = mergeRules(hereText, theirRules.data.toString('utf8'), replace);
|
|
262
|
+
actions.push(...did);
|
|
263
|
+
if (text !== hereText) writes.push(['rules.yaml', Buffer.from(text)]);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// one file a thing: a note, a chat, a picture, an attached file, a sound
|
|
267
|
+
const counted = (kind, re, name) => {
|
|
268
|
+
const all = bundle.files.filter((f) => re.test(f.path));
|
|
269
|
+
const n = { add: 0, replace: 0, skip: 0 };
|
|
270
|
+
for (const f of all) {
|
|
271
|
+
const there = exists(at(f.path));
|
|
272
|
+
const same = there && Buffer.compare(fs.readFileSync(at(f.path)), f.data) === 0;
|
|
273
|
+
const action = !there ? 'add' : same || !replace ? 'skip' : 'replace';
|
|
274
|
+
n[action]++;
|
|
275
|
+
if (action !== 'skip') writes.push([f.path, f.data]);
|
|
276
|
+
}
|
|
277
|
+
for (const action of ['add', 'replace', 'skip']) if (n[action]) actions.push({ kind, what: `${n[action]} ${n[action] === 1 ? name[0] : name[1]}`, action });
|
|
278
|
+
};
|
|
279
|
+
counted('note', /^notes\/[a-z0-9]+\.json$/, ['note', 'notes']);
|
|
280
|
+
counted('note', /^notes\/pictures\//, ['picture of the notes', 'pictures of the notes']);
|
|
281
|
+
counted('note', /^notes\/trash\//, ['removed note', 'removed notes']);
|
|
282
|
+
counted('chat', /^chats\/[a-z0-9]+\.json$/, ['chat', 'chats']);
|
|
283
|
+
counted('chat', /^chats\/files\//, ['file attached to a chat', 'files attached to chats']);
|
|
284
|
+
counted('chat', /^chats\/trash\//, ['removed chat', 'removed chats']);
|
|
285
|
+
counted('sound', /^sounds\//, ['sound', 'sounds']);
|
|
286
|
+
|
|
287
|
+
// the AI connections: a file whose secrets open with one key. Both, or neither: they are not put among others.
|
|
288
|
+
const theirAi = fileOf('ai.json');
|
|
289
|
+
if (theirAi) {
|
|
290
|
+
const hereAi = exists(at('ai.json')) ? json(fs.readFileSync(at('ai.json'), 'utf8')) : null;
|
|
291
|
+
const some = !!hereAi?.local && Object.values(hereAi.local).some((v) => Array.isArray(v?.connections) && v.connections.length);
|
|
292
|
+
const n = Object.values(json(theirAi.data.toString('utf8'))?.local ?? {}).reduce((sum, v) => sum + (Array.isArray(v?.connections) ? v.connections.length : 0), 0);
|
|
293
|
+
const what = `${n} AI ${n === 1 ? 'connection' : 'connections'}`;
|
|
294
|
+
if (!bundle.secrets.ai && n) actions.push({ kind: 'ai', what, action: 'skip', why: 'the file was made without secrets: their keys are not in it' });
|
|
295
|
+
else if (some && !replace) actions.push({ kind: 'ai', what, action: 'skip', why: 'there are AI connections here already (--replace takes the file\'s instead)' });
|
|
296
|
+
else if (n) { writes.push(['ai.json', theirAi.data]); if (bundle.secrets.ai) secrets.push([SECRETS.ai(), bundle.secrets.ai]); actions.push({ kind: 'ai', what, action: some ? 'replace' : 'add' }); }
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// this Mac's place at the relay, when the file holds it (made --with-relay)
|
|
300
|
+
const theirRelay = fileOf('relay.json');
|
|
301
|
+
if (theirRelay) {
|
|
302
|
+
const there = exists(at('relay.json'));
|
|
303
|
+
const what = 'the place at the relay, with its paired devices';
|
|
304
|
+
if (!bundle.secrets.relay) actions.push({ kind: 'relay', what, action: 'skip', why: 'the file was made without secrets: its key is not in it' });
|
|
305
|
+
else if (there && !replace) actions.push({ kind: 'relay', what, action: 'skip', why: 'this computer has a place at a relay already (--replace takes the file\'s instead)' });
|
|
306
|
+
else { writes.push(['relay.json', theirRelay.data]); secrets.push([SECRETS.relay(), bundle.secrets.relay]); actions.push({ kind: 'relay', what, action: there ? 'replace' : 'add' }); }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
return {
|
|
310
|
+
actions,
|
|
311
|
+
/** Do it: the files (each whole or not at all; what a settings file was is kept beside it once), then the Keychain. → { files, secrets } */
|
|
312
|
+
apply() {
|
|
313
|
+
fs.mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
314
|
+
// the Keychain first: settings that name an account are not written before what signs it in
|
|
315
|
+
for (const [place, value] of secrets) keychain.set(...place, value);
|
|
316
|
+
for (const [rel, data] of writes) {
|
|
317
|
+
let file = at(rel);
|
|
318
|
+
// (a settings file kept elsewhere and linked here is written where it is: the link stays)
|
|
319
|
+
try { if (fs.lstatSync(file).isSymbolicLink()) file = fs.realpathSync(file); } catch { /* not there yet */ }
|
|
320
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
321
|
+
if (['config.json', 'rules.yaml', 'ai.json', 'relay.json'].includes(rel) && exists(file)) fs.copyFileSync(file, `${file}.before-import`);
|
|
322
|
+
const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
323
|
+
fs.writeFileSync(tmp, data, { mode: 0o600 });
|
|
324
|
+
fs.renameSync(tmp, file);
|
|
325
|
+
}
|
|
326
|
+
return { files: writes.length, secrets: secrets.length };
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
}
|
package/src/bimi.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
// BIMI: the logo a domain publishes for its mail (DNS TXT at
|
|
2
|
+
// default._bimi.<domain>: "v=BIMI1; l=https://…/logo.svg; a=…"), and the
|
|
3
|
+
// cleaning an SVG goes through before the panel may show it. The a= mark
|
|
4
|
+
// certificate (VMC or CMC) is checked in vmc.js; a logo without a valid one is
|
|
5
|
+
// only the domain's own word, which is why pictures.js shows such a logo only
|
|
6
|
+
// for domains the person corresponds with.
|
|
7
|
+
//
|
|
8
|
+
// The panel only ever shows an SVG as <img src="data:image/svg+xml;base64,…">:
|
|
9
|
+
// an image runs no script and loads nothing from elsewhere. It is cleaned all
|
|
10
|
+
// the same, by rebuilding it from what is known to be harmless: an <svg> root,
|
|
11
|
+
// the shape, paint and text elements of SVG (Tiny PS and a little more),
|
|
12
|
+
// their attributes without event handlers, links only within the file
|
|
13
|
+
// (href="#…"), url() only to the file's own ids. Script, foreignObject,
|
|
14
|
+
// metadata and editor elements are dropped; a DOCTYPE or entity declaration,
|
|
15
|
+
// a processing instruction, an element not on the list, or anything that does
|
|
16
|
+
// not parse is a refusal.
|
|
17
|
+
|
|
18
|
+
export const MAX_SVG = 32 * 1024;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The TXT strings of one name → { l, a } of its BIMI record, or null when it
|
|
22
|
+
* has none (or more than one, which is no record either). `l` is '' when the
|
|
23
|
+
* domain declines to show a logo.
|
|
24
|
+
*/
|
|
25
|
+
/**
|
|
26
|
+
* The selector a message's BIMI-Selector header names ("v=BIMI1; s=nyt;"), or
|
|
27
|
+
* 'default'. Only DNS labels (letters, digits, hyphens; up to 4 of them, each at
|
|
28
|
+
* most 63 long): the record read is always <selector>._bimi.<the domain that
|
|
29
|
+
* passed DMARC>, so a selector can only pick among that domain's own records.
|
|
30
|
+
*/
|
|
31
|
+
export function bimiSelectorOf(header) {
|
|
32
|
+
const v = String(header || '');
|
|
33
|
+
if (!v || v.length > 300) return 'default';
|
|
34
|
+
const tags = new Map();
|
|
35
|
+
for (const part of v.split(';')) {
|
|
36
|
+
const m = /^\s*([A-Za-z]+)\s*=\s*(.*?)\s*$/.exec(part);
|
|
37
|
+
if (!m) { if (part.trim()) return 'default'; continue; }
|
|
38
|
+
const k = m[1].toLowerCase();
|
|
39
|
+
if (tags.has(k)) return 'default';
|
|
40
|
+
tags.set(k, m[2]);
|
|
41
|
+
}
|
|
42
|
+
if (tags.get('v') !== 'BIMI1') return 'default';
|
|
43
|
+
const s = String(tags.get('s') || '').toLowerCase();
|
|
44
|
+
const labels = s.split('.');
|
|
45
|
+
// short enough that <selector>._bimi.<domain> stays a valid DNS name whatever the domain
|
|
46
|
+
if (!s || s.length > 63 || labels.length > 4 || !labels.every((l) => /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(l))) return 'default';
|
|
47
|
+
return s;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function parseBimiRecord(records) {
|
|
51
|
+
const texts = (records || []).map((r) => (Array.isArray(r) ? r.join('') : String(r ?? ''))).filter((t) => /^\s*v\s*=\s*BIMI1\s*(;|$)/i.test(t));
|
|
52
|
+
if (texts.length !== 1) return null;
|
|
53
|
+
const tags = {};
|
|
54
|
+
for (const part of texts[0].split(';')) {
|
|
55
|
+
const at = part.indexOf('=');
|
|
56
|
+
if (at <= 0) continue;
|
|
57
|
+
const k = part.slice(0, at).trim().toLowerCase();
|
|
58
|
+
if (!(k in tags)) tags[k] = part.slice(at + 1).trim();
|
|
59
|
+
}
|
|
60
|
+
if (!('l' in tags)) return null;
|
|
61
|
+
const l = tags.l.split(',')[0].trim();
|
|
62
|
+
return { l, a: tags.a || '' };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- SVG -------------------------------------------------------------------------
|
|
66
|
+
|
|
67
|
+
const ELEMENTS = new Set(['svg', 'g', 'defs', 'title', 'desc', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon',
|
|
68
|
+
'lineargradient', 'radialgradient', 'stop', 'use', 'symbol', 'clippath', 'mask', 'pattern', 'text', 'tspan', 'textpath', 'style', 'solidcolor', 'switch', 'filter',
|
|
69
|
+
'fegaussianblur', 'feoffset', 'feblend', 'fecolormatrix', 'fecomposite', 'feflood', 'femerge', 'femergenode', 'femorphology', 'fedropshadow']);
|
|
70
|
+
// dropped with all they hold: what can run, embed or only describe
|
|
71
|
+
const DROP = new Set(['script', 'foreignobject', 'metadata', 'sodipodi:namedview']);
|
|
72
|
+
const NAME = /^[a-zA-Z_][\w.-]*(?::[a-zA-Z_][\w.-]*)?$/;
|
|
73
|
+
const KEEP_PREFIXES = new Set(['xlink', 'xml', 'xmlns']);
|
|
74
|
+
|
|
75
|
+
export class SvgRefused extends Error {
|
|
76
|
+
constructor(message) { super(message); this.name = 'SvgRefused'; }
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
80
|
+
|
|
81
|
+
/** Text of the file, its entities decoded (only the five of XML and numeric ones; any other is a refusal). */
|
|
82
|
+
function decode(s) {
|
|
83
|
+
return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);?/gi, (m, e) => {
|
|
84
|
+
if (!m.endsWith(';')) throw new SvgRefused('a stray &');
|
|
85
|
+
const k = e.toLowerCase();
|
|
86
|
+
const named = { lt: '<', gt: '>', amp: '&', quot: '"', apos: "'" };
|
|
87
|
+
if (k in named) return named[k];
|
|
88
|
+
const n = k.startsWith('#x') ? parseInt(k.slice(2), 16) : k.startsWith('#') ? Number(k.slice(1)) : NaN;
|
|
89
|
+
if (!Number.isFinite(n) || n <= 0 || n > 0x10ffff) throw new SvgRefused(`an entity: ${m}`);
|
|
90
|
+
return String.fromCodePoint(n);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A url() in a value points only within the file. */
|
|
95
|
+
const onlyLocalUrls = (v) => !/url\s*\(\s*(?!['"]?#)/i.test(v);
|
|
96
|
+
// a backslash is CSS's escape: it could spell what the rest of the check looks for (u\72l(…)), so a style with one is refused
|
|
97
|
+
const harmlessCss = (v) => !v.includes('\\') && onlyLocalUrls(v) && !/@import|expression\s*\(|javascript:|behaviou?r\s*:|-moz-binding|<\/?[a-z]/i.test(v);
|
|
98
|
+
|
|
99
|
+
/** One attribute, kept as it is, or null to drop it. */
|
|
100
|
+
function attribute(name, value) {
|
|
101
|
+
const lower = name.toLowerCase();
|
|
102
|
+
const prefix = lower.includes(':') ? lower.split(':')[0] : '';
|
|
103
|
+
if (prefix && !KEEP_PREFIXES.has(prefix)) return null; // editor attributes (inkscape:, sodipodi:, …)
|
|
104
|
+
if (lower.startsWith('on')) return null;
|
|
105
|
+
if (/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(value)) return null;
|
|
106
|
+
if (lower === 'href' || lower === 'xlink:href') return /^#[\w.:-]+$/.test(value.trim()) ? value.trim() : null;
|
|
107
|
+
if (lower === 'xmlns' || lower.startsWith('xmlns:')) return /^https?:\/\/[\w./-]+$/.test(value) ? value : null;
|
|
108
|
+
if (/javascript:|data:|vbscript:/i.test(value)) return null;
|
|
109
|
+
if (lower === 'style') {
|
|
110
|
+
if (value.includes('\\')) throw new SvgRefused('a backslash in a style');
|
|
111
|
+
return harmlessCss(value) ? value : null;
|
|
112
|
+
}
|
|
113
|
+
if (!onlyLocalUrls(value)) return null;
|
|
114
|
+
return value;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* An SVG cleaned as said above → its text, or a thrown SvgRefused. `text` is
|
|
119
|
+
* the file as served (UTF-8).
|
|
120
|
+
*/
|
|
121
|
+
export function sanitizeSvg(text) {
|
|
122
|
+
const src = String(text ?? '').replace(/^/, '');
|
|
123
|
+
if (!src.trim() || src.length > MAX_SVG) throw new SvgRefused('empty or too large');
|
|
124
|
+
const out = [];
|
|
125
|
+
const stack = []; // open elements: { name, keep }
|
|
126
|
+
let dropDepth = 0; // inside an element that is dropped with what it holds
|
|
127
|
+
let rootSeen = false;
|
|
128
|
+
let rootClosed = false;
|
|
129
|
+
let i = 0;
|
|
130
|
+
const keeping = () => dropDepth === 0;
|
|
131
|
+
// a <style>'s text is gathered whole (text and CDATA together) and judged once, at </style>: split in pieces it
|
|
132
|
+
// could spell what no piece does
|
|
133
|
+
let style = null;
|
|
134
|
+
const inStyle = () => stack.length && stack[stack.length - 1].name === 'style' && !stack[stack.length - 1].drop;
|
|
135
|
+
while (i < src.length) {
|
|
136
|
+
if (src.startsWith('<!--', i)) {
|
|
137
|
+
if (inStyle()) throw new SvgRefused('a comment inside a style');
|
|
138
|
+
const end = src.indexOf('-->', i + 4);
|
|
139
|
+
if (end < 0) throw new SvgRefused('a comment left open');
|
|
140
|
+
i = end + 3;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (src.startsWith('<![CDATA[', i)) {
|
|
144
|
+
const end = src.indexOf(']]>', i + 9);
|
|
145
|
+
if (end < 0) throw new SvgRefused('CDATA left open');
|
|
146
|
+
const inner = src.slice(i + 9, end);
|
|
147
|
+
i = end + 3;
|
|
148
|
+
if (!keeping()) continue;
|
|
149
|
+
const parent = stack[stack.length - 1];
|
|
150
|
+
if (!parent || parent.name !== 'style') { if (inner.trim()) throw new SvgRefused('CDATA outside a style'); continue; }
|
|
151
|
+
style += inner;
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
if (src.startsWith('<?', i)) {
|
|
155
|
+
const end = src.indexOf('?>', i + 2);
|
|
156
|
+
if (end < 0) throw new SvgRefused('a declaration left open');
|
|
157
|
+
if (rootSeen || !/^<\?xml\s/i.test(src.slice(i, end + 2))) throw new SvgRefused('a processing instruction');
|
|
158
|
+
i = end + 2;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (src.startsWith('<!', i)) throw new SvgRefused('a DOCTYPE or declaration');
|
|
162
|
+
if (src.startsWith('</', i)) {
|
|
163
|
+
const m = /^<\/([^\s>]+)\s*>/.exec(src.slice(i, i + 300));
|
|
164
|
+
if (!m) throw new SvgRefused('a closing tag that does not parse');
|
|
165
|
+
const name = m[1].toLowerCase();
|
|
166
|
+
const open = stack.pop();
|
|
167
|
+
if (!open || open.name !== name) throw new SvgRefused('tags that do not match');
|
|
168
|
+
i += m[0].length;
|
|
169
|
+
if (open.drop) dropDepth--;
|
|
170
|
+
else if (keeping()) {
|
|
171
|
+
if (open.name === 'style') {
|
|
172
|
+
if (!harmlessCss(style)) throw new SvgRefused('a style that loads or runs something');
|
|
173
|
+
out.push(esc(style));
|
|
174
|
+
style = null;
|
|
175
|
+
}
|
|
176
|
+
out.push(`</${open.raw}>`);
|
|
177
|
+
}
|
|
178
|
+
if (!stack.length) rootClosed = true;
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (src[i] === '<') {
|
|
182
|
+
const m = /^<([^\s/>]+)((?:\s+[^\s=/>]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>/.exec(src.slice(i, i + 8192));
|
|
183
|
+
if (!m) throw new SvgRefused('a tag that does not parse');
|
|
184
|
+
const raw = m[1];
|
|
185
|
+
const name = raw.toLowerCase();
|
|
186
|
+
if (!NAME.test(raw)) throw new SvgRefused('an element name that does not parse');
|
|
187
|
+
if (rootClosed) throw new SvgRefused('more than one root');
|
|
188
|
+
if (inStyle()) throw new SvgRefused('an element inside a style');
|
|
189
|
+
if (!rootSeen) {
|
|
190
|
+
if (name !== 'svg') throw new SvgRefused('the root is not <svg>');
|
|
191
|
+
rootSeen = true;
|
|
192
|
+
}
|
|
193
|
+
const selfClosing = m[3] === '/';
|
|
194
|
+
i += m[0].length;
|
|
195
|
+
const drop = DROP.has(name) || (name.includes(':') && name.split(':')[0] !== 'svg');
|
|
196
|
+
if (drop || !keeping()) {
|
|
197
|
+
if (!selfClosing) { stack.push({ name, raw, drop: true }); dropDepth++; }
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (!ELEMENTS.has(name)) throw new SvgRefused(`an element that has no place in a logo: <${raw}>`);
|
|
201
|
+
const attrs = [];
|
|
202
|
+
const seen = new Set();
|
|
203
|
+
for (const a of m[2].matchAll(/([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) {
|
|
204
|
+
const an = a[1];
|
|
205
|
+
if (!NAME.test(an)) throw new SvgRefused('an attribute name that does not parse');
|
|
206
|
+
if (seen.has(an.toLowerCase())) throw new SvgRefused('an attribute given twice');
|
|
207
|
+
seen.add(an.toLowerCase());
|
|
208
|
+
const value = attribute(an, decode(a[2] ?? a[3] ?? ''));
|
|
209
|
+
if (value != null) attrs.push(` ${an}="${esc(value)}"`);
|
|
210
|
+
}
|
|
211
|
+
out.push(`<${raw}${attrs.join('')}${selfClosing ? '/' : ''}>`);
|
|
212
|
+
if (!selfClosing) { stack.push({ name, raw, drop: false }); if (name === 'style') style = ''; }
|
|
213
|
+
else if (stack.length === 0) rootClosed = true;
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
// text
|
|
217
|
+
const next = src.indexOf('<', i);
|
|
218
|
+
const chunk = src.slice(i, next < 0 ? src.length : next);
|
|
219
|
+
i = next < 0 ? src.length : next;
|
|
220
|
+
if (!stack.length) { if (chunk.trim()) throw new SvgRefused('text outside the root'); continue; }
|
|
221
|
+
if (!keeping()) continue;
|
|
222
|
+
const textValue = decode(chunk);
|
|
223
|
+
if (inStyle()) style += textValue;
|
|
224
|
+
else out.push(esc(textValue));
|
|
225
|
+
}
|
|
226
|
+
if (!rootSeen || stack.length) throw new SvgRefused('no complete <svg>');
|
|
227
|
+
const clean = out.join('');
|
|
228
|
+
// what was dropped is gone; what is left is checked once more as a whole
|
|
229
|
+
if (/<script|<foreignobject|<[^>]*\son[a-z]+\s*=|<[^>]*javascript:|<!entity|<!doctype|@import/i.test(clean)) throw new SvgRefused('something unexpected is left');
|
|
230
|
+
// a url() anywhere, attribute or text, points within the file (quotes are " by now)
|
|
231
|
+
if (/url\s*\(\s*(?!(?:['"]|"|'|')?#)/i.test(clean)) throw new SvgRefused('a url() outside the file is left');
|
|
232
|
+
return clean;
|
|
233
|
+
}
|