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,241 @@
|
|
|
1
|
+
// The web app's server: the panel as a page in any browser on this computer
|
|
2
|
+
// (`sideora web`), asking the same ops as the extension (src/panel-ops.js)
|
|
3
|
+
// over HTTP instead of Chrome's native messaging.
|
|
4
|
+
//
|
|
5
|
+
// On this computer only: it listens on 127.0.0.1, and answers only requests
|
|
6
|
+
// that name it so (a page of another site whose name was made to point here
|
|
7
|
+
// is refused by its Host). A browser is let in once paired (src/web-access.js)
|
|
8
|
+
// and says so with every request: `Authorization: Bearer <token>`, a header a
|
|
9
|
+
// page of another site cannot send here (no cross-origin request is allowed).
|
|
10
|
+
//
|
|
11
|
+
// GET /api/session → { paired }
|
|
12
|
+
// POST /api/pair { code } → { token } | 403 (a pairing code, once)
|
|
13
|
+
// POST /api/op { op, args } → { ok: true, result } | { ok: false, error }
|
|
14
|
+
// GET /api/events[?after=] → server-sent events, one `data:` line of JSON per push; `id:` is the queue's cursor
|
|
15
|
+
// POST /api/signout → { ok } (this browser's session ends)
|
|
16
|
+
// anything else → the web app's files (extension/dist-web)
|
|
17
|
+
//
|
|
18
|
+
// The same shape as a relay would carry later (a request answered, a stream of
|
|
19
|
+
// what changed), so the page does not change when the Mac is reached from afar.
|
|
20
|
+
|
|
21
|
+
import { EXTENSION_ORIGIN } from './extension-id.js';
|
|
22
|
+
import fs from 'node:fs';
|
|
23
|
+
import http from 'node:http';
|
|
24
|
+
import path from 'node:path';
|
|
25
|
+
import { fileURLToPath } from 'node:url';
|
|
26
|
+
import { OPS, runOp, follow } from './panel-ops.js';
|
|
27
|
+
import * as access from './web-access.js';
|
|
28
|
+
|
|
29
|
+
export const DEFAULT_PORT = 6245; // (M-A-I-L on a phone's keys)
|
|
30
|
+
export const WEB_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'extension', 'dist-web');
|
|
31
|
+
const MAX_BODY = 80 * 1024 * 1024; // a file attached to a draft comes as base64 in one request
|
|
32
|
+
const BEAT_MS = 25_000;
|
|
33
|
+
const STREAM_BACKLOG = 8 * 1024 * 1024;
|
|
34
|
+
const PAIR_PER_MINUTE = 10;
|
|
35
|
+
|
|
36
|
+
// What the page is served, what a server started with --no-admin does not serve (accounts: a page in a browser is not kept
|
|
37
|
+
// apart as an extension's is), and what it never is: src/op-registry.js, where each op is named once.
|
|
38
|
+
import { ADMIN_OPS, NOT_ON_WEB, WEB_OPS } from './op-registry.js';
|
|
39
|
+
export { ADMIN_OPS, NOT_ON_WEB, WEB_OPS };
|
|
40
|
+
|
|
41
|
+
const TYPES = {
|
|
42
|
+
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8',
|
|
43
|
+
'.webmanifest': 'application/manifest+json', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif', '.ico': 'image/x-icon',
|
|
44
|
+
'.woff2': 'font/woff2', '.woff': 'font/woff', '.webmanifest': 'application/manifest+json', '.map': 'application/json; charset=utf-8'
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// What the page may load. Shown in a frame only by the Sideora extension's own pages (src/extension-id.js): its side
|
|
48
|
+
// panel, its tab and the new tab are a frame around this page (extension/src/shell/shell.ts); by no other page.
|
|
49
|
+
// Scripts: its own files only (a mail's HTML is shown in a frame with a stricter policy of
|
|
50
|
+
// its own, and can run none either way). Pictures: its own, a mail's (remote ones only once the person allowed
|
|
51
|
+
// them, which the frame's own policy decides), those it made (blob:). Requests: this server, and the weather.
|
|
52
|
+
const CSP = [
|
|
53
|
+
"default-src 'none'", "script-src 'self'", "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https: http:", "font-src 'self' data:",
|
|
54
|
+
"media-src 'self' blob: data:", "connect-src 'self' data: blob: https://api.open-meteo.com https://geocoding-api.open-meteo.com", "frame-src 'self' blob:",
|
|
55
|
+
"manifest-src 'self'", "base-uri 'none'", "form-action 'none'", `frame-ancestors ${EXTENSION_ORIGIN}`, "object-src 'none'"
|
|
56
|
+
].join('; ');
|
|
57
|
+
const HEADERS = {
|
|
58
|
+
'Content-Security-Policy': CSP,
|
|
59
|
+
'X-Content-Type-Options': 'nosniff',
|
|
60
|
+
'Referrer-Policy': 'no-referrer',
|
|
61
|
+
'Cross-Origin-Opener-Policy': 'same-origin',
|
|
62
|
+
'Cross-Origin-Resource-Policy': 'same-origin'
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
const NOT_BUILT = `<!doctype html><meta charset="utf-8"><title>Sideora</title><body style="font:15px system-ui;margin:3rem auto;max-width:34rem;line-height:1.5">
|
|
66
|
+
<h1 style="font-size:1.2rem">The web app is not built yet</h1><p>On this Mac, in the app's source folder:</p><pre>cd extension && npm install && npm run build:web</pre><p>then load this page again.</p></body>`;
|
|
67
|
+
|
|
68
|
+
function readBody(req, limit) {
|
|
69
|
+
return new Promise((resolve, reject) => {
|
|
70
|
+
const chunks = [];
|
|
71
|
+
let size = 0;
|
|
72
|
+
req.on('data', (c) => {
|
|
73
|
+
size += c.length;
|
|
74
|
+
if (size > limit) { chunks.length = 0; req.removeAllListeners('data'); req.resume(); reject(Object.assign(new Error('too large'), { status: 413 })); return; } // (the rest is let through unread: the answer can then be read)
|
|
75
|
+
chunks.push(c);
|
|
76
|
+
});
|
|
77
|
+
req.on('end', () => resolve(Buffer.concat(chunks)));
|
|
78
|
+
req.on('error', reject);
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Start it. `port` 0: any free one. `dir`: the built web app. `admin`: whether the ops that change accounts are
|
|
84
|
+
* served (ADMIN_OPS). `ops`, `served`, `followFn`, `accessFns`: what it serves (the tests give their own).
|
|
85
|
+
* Resolves { url, port, close }.
|
|
86
|
+
*/
|
|
87
|
+
export function startWebServer({ port = DEFAULT_PORT, dir = WEB_DIR, ops = OPS, followFn = follow, accessFns = access, admin = false, served = WEB_OPS } = {}) {
|
|
88
|
+
const streams = new Set();
|
|
89
|
+
let pairTries = [];
|
|
90
|
+
let origin = '';
|
|
91
|
+
let names = new Set();
|
|
92
|
+
|
|
93
|
+
const send = (res, status, body, headers = {}) => {
|
|
94
|
+
const data = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body);
|
|
95
|
+
res.writeHead(status, { ...HEADERS, 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', ...headers });
|
|
96
|
+
res.end(data);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** The session of a request, by its bearer token; null: not paired. */
|
|
100
|
+
const sessionFor = (req) => {
|
|
101
|
+
const m = /^Bearer ([A-Za-z0-9_-]{20,200})$/.exec(req.headers.authorization || '');
|
|
102
|
+
return m ? accessFns.sessionOf(m[1]) : null;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/** A request this page itself made: said so by the browser when it says anything (a page of another site is refused). */
|
|
106
|
+
const ownRequest = (req) => {
|
|
107
|
+
const site = req.headers['sec-fetch-site'];
|
|
108
|
+
if (site && site !== 'same-origin') return false;
|
|
109
|
+
const from = req.headers.origin;
|
|
110
|
+
if (from && from !== origin && !names.has(from.replace(/^http:\/\//, ''))) return false;
|
|
111
|
+
return req.method === 'GET' || !!from || site === 'same-origin';
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
async function api(req, res, url) {
|
|
115
|
+
if (!ownRequest(req)) return send(res, 403, { error: 'not from this page' });
|
|
116
|
+
const route = `${req.method} ${url.pathname}`;
|
|
117
|
+
if (route === 'GET /api/session') { const s = sessionFor(req); return send(res, 200, { paired: !!s, admin: admin || !!s?.admin }); }
|
|
118
|
+
|
|
119
|
+
if (route === 'GET /api/events') {
|
|
120
|
+
const session = sessionFor(req);
|
|
121
|
+
if (!session) return send(res, 401, { error: 'not paired' });
|
|
122
|
+
res.writeHead(200, { ...HEADERS, 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-store', 'X-Accel-Buffering': 'no' });
|
|
123
|
+
res.write(': open\n\n'); // the first bytes at once: the page sees the line open before the first push
|
|
124
|
+
let open = true;
|
|
125
|
+
const end = () => { if (!open) return; open = false; clearInterval(beat); stop(); streams.delete(end); res.end(); };
|
|
126
|
+
const write = (text) => {
|
|
127
|
+
if (!open) return;
|
|
128
|
+
if (res.writableLength > STREAM_BACKLOG) return end(); // a page that stopped reading does not fill this memory
|
|
129
|
+
res.write(text);
|
|
130
|
+
};
|
|
131
|
+
// (`id:`: the cursor of a push out of the daemon's queue; the page gives the last one back as ?after= when it connects again)
|
|
132
|
+
// forgotten on the Mac meanwhile (sideora web forget): its stream ends with it, before anything more is told
|
|
133
|
+
const still = () => { if (sessionFor(req)) return true; write('event: refused\ndata: 401\n\n'); end(); return false; };
|
|
134
|
+
// (`id:`: the cursor of the daemon's queue, with a push out of it or alone; the page gives the last one back as ?after= when it connects again)
|
|
135
|
+
const stop = followFn(
|
|
136
|
+
(push, cursor) => { if (still()) write(`${Number.isFinite(cursor) ? `id: ${cursor}\n` : ''}data: ${JSON.stringify(push)}\n\n`); },
|
|
137
|
+
url.searchParams.get('after') ?? undefined,
|
|
138
|
+
{ checkpoint: (cursor) => write(`id: ${cursor}\n: at\n\n`) }
|
|
139
|
+
);
|
|
140
|
+
const beat = setInterval(() => { if (still()) write(': beat\n\n'); }, BEAT_MS);
|
|
141
|
+
streams.add(end);
|
|
142
|
+
req.on('close', end);
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
if (req.method !== 'POST') return send(res, 404, { error: 'no such thing here' });
|
|
147
|
+
if (!/^application\/json\b/i.test(req.headers['content-type'] || '')) return send(res, 415, { error: 'JSON only' });
|
|
148
|
+
// who is asking, before anything of what is asked is read (pairing aside: it is how one gets in)
|
|
149
|
+
const session = sessionFor(req);
|
|
150
|
+
if (!session && route !== 'POST /api/pair') return send(res, 401, { error: 'not paired' }, { Connection: 'close' });
|
|
151
|
+
let body;
|
|
152
|
+
try { body = JSON.parse((await readBody(req, route === 'POST /api/op' ? MAX_BODY : 4096)).toString('utf8') || '{}'); } catch (e) {
|
|
153
|
+
return send(res, e?.status || 400, { error: e?.status === 413 ? 'too large' : 'not JSON' }, { Connection: 'close' });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
if (route === 'POST /api/pair') {
|
|
157
|
+
const now = Date.now();
|
|
158
|
+
pairTries = pairTries.filter((t) => now - t < 60_000);
|
|
159
|
+
if (pairTries.length >= PAIR_PER_MINUTE) return send(res, 429, { error: 'too many tries: wait a minute' });
|
|
160
|
+
pairTries.push(now);
|
|
161
|
+
// (paired again: the session this browser had ends with the new one)
|
|
162
|
+
const was = /^Bearer ([A-Za-z0-9_-]{20,200})$/.exec(req.headers.authorization || '')?.[1];
|
|
163
|
+
const made = accessFns.pair(body?.code, req.headers['user-agent'], undefined, was);
|
|
164
|
+
return made ? send(res, 200, { token: made.token }) : send(res, 403, { error: 'this code is not good (used already, or more than ten minutes old)' });
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if (route === 'POST /api/signout') { accessFns.endSessions(session.id); return send(res, 200, { ok: true }); }
|
|
168
|
+
if (route === 'POST /api/op') {
|
|
169
|
+
const op = body?.op;
|
|
170
|
+
// (accounts: unless the server was started with --no-admin; the Chrome extension's own frame, always)
|
|
171
|
+
if (ADMIN_OPS.has(op) ? !(admin || session?.admin) : !served.has(op)) {
|
|
172
|
+
return send(res, 200, { ok: false, error: ADMIN_OPS.has(op) ? 'this web app was started with --no-admin: accounts are set up on the computer itself (`sideora setup`, or the extension)' : `unknown op "${op}"` });
|
|
173
|
+
}
|
|
174
|
+
// (the page let go before the answer, a model turn stopped: the op is told, and stops waiting)
|
|
175
|
+
const gone = new AbortController();
|
|
176
|
+
res.on('close', () => { if (!res.writableEnded) gone.abort(); });
|
|
177
|
+
const answer = await runOp(op, body?.args, ops, { signal: gone.signal });
|
|
178
|
+
return gone.signal.aborted ? undefined : send(res, 200, answer);
|
|
179
|
+
}
|
|
180
|
+
return send(res, 404, { error: 'no such thing here' });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function file(req, res, url) {
|
|
184
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, { error: 'GET only' });
|
|
185
|
+
// Sent here by a page of another site (a link, a redirect): the place it names after the # is not followed, the
|
|
186
|
+
// app opens on Home. A place opened that way would act as the person (a mail opened is a mail read). Typed, a
|
|
187
|
+
// bookmark, a link from a terminal or another program (the pairing link) come from no site, and are followed.
|
|
188
|
+
const from = req.headers['sec-fetch-site'];
|
|
189
|
+
if (req.headers['sec-fetch-dest'] === 'document' && from && from !== 'same-origin' && from !== 'none') {
|
|
190
|
+
res.writeHead(303, { ...HEADERS, Location: '/#/', 'Cache-Control': 'no-store' });
|
|
191
|
+
return res.end();
|
|
192
|
+
}
|
|
193
|
+
let rel;
|
|
194
|
+
try { rel = decodeURIComponent(url.pathname); } catch { return send(res, 400, { error: 'bad address' }); }
|
|
195
|
+
if (rel.includes('\0')) return send(res, 400, { error: 'bad address' });
|
|
196
|
+
if (rel.endsWith('/')) rel += 'index.html';
|
|
197
|
+
const full = path.join(dir, path.normalize(rel));
|
|
198
|
+
if (full !== dir && !full.startsWith(dir + path.sep)) return send(res, 403, { error: 'no' });
|
|
199
|
+
fs.readFile(full, (err, data) => {
|
|
200
|
+
if (err) {
|
|
201
|
+
if (rel === '/index.html') return send(res, 503, NOT_BUILT, { 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'" });
|
|
202
|
+
return send(res, 404, { error: 'no such file' });
|
|
203
|
+
}
|
|
204
|
+
const type = TYPES[path.extname(full).toLowerCase()] || 'application/octet-stream';
|
|
205
|
+
// files named by their content (assets/) never change; the page itself is asked for each time
|
|
206
|
+
const cache = /\/assets\//.test(rel) ? 'public, max-age=31536000, immutable' : 'no-cache';
|
|
207
|
+
res.writeHead(200, { ...HEADERS, 'Content-Type': type, 'Cache-Control': cache, 'Content-Length': data.length });
|
|
208
|
+
res.end(req.method === 'HEAD' ? undefined : data);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const failed = (res) => { try { send(res, 500, { error: 'that did not work' }); } catch { try { res.destroy(); } catch { /* gone */ } } };
|
|
213
|
+
const server = http.createServer((req, res) => {
|
|
214
|
+
// nothing a request holds may stop the server: whatever it throws is that request's answer
|
|
215
|
+
try {
|
|
216
|
+
// asked for by this computer's own name only: a name made to point at 127.0.0.1 is another site's page reaching in
|
|
217
|
+
if (!names.has(String(req.headers.host || '').toLowerCase())) return send(res, 421, { error: 'not this server' });
|
|
218
|
+
let url;
|
|
219
|
+
try { url = new URL(req.url, origin); } catch { return send(res, 400, { error: 'bad address' }); }
|
|
220
|
+
if (url.pathname.startsWith('/api/')) return void api(req, res, url).catch(() => failed(res));
|
|
221
|
+
return file(req, res, url);
|
|
222
|
+
} catch {
|
|
223
|
+
failed(res);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
server.on('clientError', (_e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n'); } catch { /* gone */ } });
|
|
227
|
+
|
|
228
|
+
return new Promise((resolve, reject) => {
|
|
229
|
+
server.once('error', (e) => reject(e.code === 'EADDRINUSE' ? new Error(`port ${port} is taken (another \`sideora web\`? or try --port)`) : e));
|
|
230
|
+
server.listen(port, '127.0.0.1', () => {
|
|
231
|
+
const at = server.address().port;
|
|
232
|
+
origin = `http://127.0.0.1:${at}`;
|
|
233
|
+
names = new Set([`127.0.0.1:${at}`, `localhost:${at}`]);
|
|
234
|
+
resolve({
|
|
235
|
+
url: origin,
|
|
236
|
+
port: at,
|
|
237
|
+
close: () => new Promise((done) => { for (const end of [...streams]) end(); server.close(() => done()); server.closeAllConnections?.(); })
|
|
238
|
+
});
|
|
239
|
+
});
|
|
240
|
+
});
|
|
241
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// The web app's server as a service of this Mac (launchd): started when the person logs in, started again when it
|
|
2
|
+
// stops, its words in ~/.sideora/logs/web.log. Without it, `sideora web` lives as long as the terminal that
|
|
3
|
+
// started it, and every device paired through the relay loses the Mac with it.
|
|
4
|
+
//
|
|
5
|
+
// sideora web install [--port N] [--no-admin] set it up and start it (--no-admin: no account changes from the page)
|
|
6
|
+
// sideora web restart after an update
|
|
7
|
+
// sideora web uninstall stop it and take it away
|
|
8
|
+
//
|
|
9
|
+
// A LaunchAgent of the person's own (~/Library/LaunchAgents/com.sideora.web.plist), like the watcher's: it runs
|
|
10
|
+
// as them, in their session, where their Keychain is (the mail passwords, the key of the AI connections, the
|
|
11
|
+
// relay's secrets). On Linux, a systemd user unit of theirs (src/host/systemd.js).
|
|
12
|
+
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { execFileSync } from 'node:child_process';
|
|
17
|
+
import { HOME_ENV, LOG_DIR } from './config.js';
|
|
18
|
+
import * as systemd from './host/systemd.js';
|
|
19
|
+
|
|
20
|
+
export const WEB_LABEL = 'com.sideora.web';
|
|
21
|
+
export const WEB_PLIST = path.join(os.homedir(), 'Library/LaunchAgents', `${WEB_LABEL}.plist`);
|
|
22
|
+
export const WEB_LOG = path.join(LOG_DIR, 'web.log');
|
|
23
|
+
|
|
24
|
+
const xml = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Where node is, as it will still be after it is updated: Homebrew keeps each version in a folder of its own
|
|
28
|
+
* (…/Cellar/node/26.7.0/bin/node), which goes with the version, and a name that follows the one in use
|
|
29
|
+
* (/opt/homebrew/bin/node). The second, when it is the same program now.
|
|
30
|
+
*/
|
|
31
|
+
export function stableNode(execPath = process.execPath, { realpath = fs.realpathSync } = {}) {
|
|
32
|
+
if (!/\/Cellar\//.test(execPath)) return execPath;
|
|
33
|
+
for (const name of ['/opt/homebrew/bin/node', '/usr/local/bin/node']) {
|
|
34
|
+
try { if (realpath(name) === realpath(execPath)) return name; } catch { /* not there */ }
|
|
35
|
+
}
|
|
36
|
+
return execPath;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Its log, kept small: past MAX_LOG it keeps its last part (a service started again and again writes a line each time). */
|
|
40
|
+
export const MAX_LOG = 4 * 1024 * 1024;
|
|
41
|
+
export function trimLog(file = WEB_LOG, max = MAX_LOG) {
|
|
42
|
+
try {
|
|
43
|
+
const { size } = fs.statSync(file);
|
|
44
|
+
if (size <= max) return false;
|
|
45
|
+
const fd = fs.openSync(file, 'r');
|
|
46
|
+
const keep = Buffer.alloc(Math.floor(max / 4));
|
|
47
|
+
try { fs.readSync(fd, keep, 0, keep.length, size - keep.length); } finally { fs.closeSync(fd); }
|
|
48
|
+
fs.writeFileSync(file, Buffer.concat([Buffer.from(`(the log was longer: its last part is kept, ${new Date().toISOString()})\n`), keep.subarray(keep.indexOf(10) + 1)]));
|
|
49
|
+
return true;
|
|
50
|
+
} catch { return false; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Why the program at `self` is not one to run a service from, or null: a git worktree (removed when its work is
|
|
55
|
+
* done, and the service would be started again and again from a place that is gone), a node of a version manager
|
|
56
|
+
* (it goes with the version).
|
|
57
|
+
*/
|
|
58
|
+
export function unfitToStay(self, node = process.execPath) {
|
|
59
|
+
const root = path.dirname(path.dirname(self));
|
|
60
|
+
try { if (fs.statSync(path.join(root, '.git')).isFile()) return `${root} is a git worktree: install the service from the main checkout`; } catch { /* no .git: an install */ }
|
|
61
|
+
if (/\/\.(nvm|asdf|volta|fnm)\//.test(node)) return `node is ${node}, of a version manager: the service would stop working when that version goes (\`--here\` installs it all the same)`;
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The LaunchAgent, as text. `port`, `admin` (false: --no-admin, the page changes no account): as `sideora web` takes them. */
|
|
66
|
+
export function webPlist({ node, self, port, admin = true, logFile = WEB_LOG, env = HOME_ENV } = {}) {
|
|
67
|
+
if (!node || !self) throw new Error('webPlist needs node and the program');
|
|
68
|
+
if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error('--port must be a port number');
|
|
69
|
+
const args = [node, self, 'web', ...(port !== undefined ? ['--port', String(port)] : []), ...(admin ? [] : ['--no-admin'])];
|
|
70
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
71
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
72
|
+
<plist version="1.0">
|
|
73
|
+
<dict>
|
|
74
|
+
<key>Label</key><string>${WEB_LABEL}</string>
|
|
75
|
+
<key>ProgramArguments</key>
|
|
76
|
+
<array>${args.map((a) => `
|
|
77
|
+
<string>${xml(a)}</string>`).join('')}
|
|
78
|
+
</array>
|
|
79
|
+
<key>RunAtLoad</key><true/>
|
|
80
|
+
<key>KeepAlive</key>
|
|
81
|
+
<dict>
|
|
82
|
+
<key>SuccessfulExit</key><false/>
|
|
83
|
+
</dict>
|
|
84
|
+
<key>ThrottleInterval</key><integer>30</integer>
|
|
85
|
+
<key>ProcessType</key><string>Interactive</string>
|
|
86
|
+
<key>StandardOutPath</key><string>${xml(logFile)}</string>
|
|
87
|
+
<key>StandardErrorPath</key><string>${xml(logFile)}</string>
|
|
88
|
+
<key>EnvironmentVariables</key>
|
|
89
|
+
<dict>
|
|
90
|
+
<key>PATH</key><string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
|
|
91
|
+
<key>SIDEORA_WEB_SERVICE</key><string>1</string>${Object.entries(env).map(([k, v]) => `
|
|
92
|
+
<key>${xml(k)}</key><string>${xml(v)}</string>`).join('')}
|
|
93
|
+
</dict>
|
|
94
|
+
</dict>
|
|
95
|
+
</plist>
|
|
96
|
+
`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const launchctl = (args, opts = {}) => execFileSync('launchctl', args, { encoding: 'utf8', timeout: 15_000, ...opts });
|
|
100
|
+
|
|
101
|
+
/** How it stands: not set up, set up and running (its process), set up and not running, or set up and not loaded. */
|
|
102
|
+
export function webServiceState({ plist = WEB_PLIST, run = launchctl, linux = systemd.isLinux } = {}) {
|
|
103
|
+
if (linux) return systemd.state('web');
|
|
104
|
+
if (!fs.existsSync(plist)) return { installed: false };
|
|
105
|
+
try {
|
|
106
|
+
const out = run(['list', WEB_LABEL]);
|
|
107
|
+
const pid = Number(out.match(/"PID"\s*=\s*(\d+)/)?.[1]) || null;
|
|
108
|
+
const exit = out.match(/"LastExitStatus"\s*=\s*(-?\d+)/)?.[1];
|
|
109
|
+
return { installed: true, loaded: true, pid, ...(exit !== undefined ? { lastExit: Number(exit) } : {}) };
|
|
110
|
+
} catch {
|
|
111
|
+
return { installed: true, loaded: false, pid: null };
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Set it up and start it (set up already: as asked now, started again). */
|
|
116
|
+
export function installWebService({ node = stableNode(), self, port, admin = true, plist = WEB_PLIST, run = launchctl, linux = systemd.isLinux } = {}) {
|
|
117
|
+
if (linux) {
|
|
118
|
+
if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) throw new Error('--port must be a port number');
|
|
119
|
+
fs.mkdirSync(LOG_DIR, { recursive: true });
|
|
120
|
+
const args = [node, self, 'web', ...(port !== undefined ? ['--port', String(port)] : []), ...(admin ? [] : ['--no-admin'])];
|
|
121
|
+
systemd.install('web', systemd.unitText({ description: 'Sideora: the web app', args, env: { SIDEORA_WEB_SERVICE: '1', ...HOME_ENV }, log: WEB_LOG, restart: 'on-failure', restartSec: 30 }));
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const text = webPlist({ node, self, port, admin });
|
|
125
|
+
fs.mkdirSync(path.dirname(plist), { recursive: true });
|
|
126
|
+
fs.mkdirSync(LOG_DIR, { recursive: true });
|
|
127
|
+
try { run(['unload', plist], { stdio: 'ignore' }); } catch { /* not loaded */ }
|
|
128
|
+
fs.writeFileSync(plist, text);
|
|
129
|
+
run(['load', plist]);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function uninstallWebService({ plist = WEB_PLIST, run = launchctl, linux = systemd.isLinux } = {}) {
|
|
133
|
+
if (linux) return systemd.uninstall('web');
|
|
134
|
+
const was = fs.existsSync(plist);
|
|
135
|
+
try { run(['unload', plist], { stdio: 'ignore' }); } catch { /* not loaded */ }
|
|
136
|
+
if (was) fs.unlinkSync(plist);
|
|
137
|
+
return was;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** Stopped and started again (after an update): launchd does both. Throws when it is not set up. */
|
|
141
|
+
export function restartWebService({ plist = WEB_PLIST, run = launchctl, uid = process.getuid(), linux = systemd.isLinux } = {}) {
|
|
142
|
+
if (linux) {
|
|
143
|
+
if (!systemd.state('web').installed) throw new Error('the web app is not set up as a service: `sideora web install`');
|
|
144
|
+
systemd.restart('web');
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (!fs.existsSync(plist)) throw new Error('the web app is not set up as a service: `sideora web install`');
|
|
148
|
+
try { run(['kickstart', '-k', `gui/${uid}/${WEB_LABEL}`], { stdio: 'ignore' }); } catch {
|
|
149
|
+
// (set up and not loaded: loaded now, which starts it)
|
|
150
|
+
run(['load', plist]);
|
|
151
|
+
}
|
|
152
|
+
}
|