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,20 @@
|
|
|
1
|
+
// Sideora's app in Microsoft Entra (multitenant and personal accounts, a public client: no secret), apart from the
|
|
2
|
+
// sign-in itself: what lists the accounts asks whether Microsoft mailboxes can be added without loading the mail
|
|
3
|
+
// library. config.microsoft.clientId overrides it.
|
|
4
|
+
import { loadConfig } from './config.js';
|
|
5
|
+
|
|
6
|
+
export const DEFAULT_MICROSOFT_CLIENT_ID = 'c1d5283a-6954-4334-a2a0-41f737892301';
|
|
7
|
+
|
|
8
|
+
export function microsoftClient(config = (() => { try { return loadConfig(); } catch { return {}; } })()) {
|
|
9
|
+
return { clientId: config.microsoft?.clientId || DEFAULT_MICROSOFT_CLIENT_ID };
|
|
10
|
+
}
|
|
11
|
+
export const microsoftReady = () => !!microsoftClient().clientId;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* The relays Microsoft may send a sign-in back to (each registered in the app as https://<host>/oauth/microsoft): a
|
|
15
|
+
* sign-in started from afar, or from a browser on another computer, comes back through one of these.
|
|
16
|
+
*/
|
|
17
|
+
export const MICROSOFT_RELAY_HOSTS = ['my.sideora.com'];
|
|
18
|
+
export const microsoftRelayReturn = (relayUrl) => {
|
|
19
|
+
try { const u = new URL(relayUrl); return u.protocol === 'https:' && MICROSOFT_RELAY_HOSTS.includes(u.host) ? `${u.origin}/oauth/microsoft` : null; } catch { return null; }
|
|
20
|
+
};
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
// Microsoft 365 and Outlook.com mailboxes, signed in with Microsoft (they accept no password since Microsoft turned
|
|
2
|
+
// basic authentication off): mail over IMAP and SMTP with a token (mailcore's microsoftAuth), the token kept in the
|
|
3
|
+
// Keychain (microsoft:<account>) and never shown to the panel.
|
|
4
|
+
//
|
|
5
|
+
// A sign-in from the panel adds the mailbox: who signed in is only known once Microsoft says so, so the tokens wait
|
|
6
|
+
// in memory until then, and the account is made of the address (its name, its servers). Signing in as an address
|
|
7
|
+
// already here as a Microsoft account renews that account's sign-in instead.
|
|
8
|
+
|
|
9
|
+
import { microsoftAuth, microsoftServers } from 'mailcore';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { HOME_DIR, updateConfig, keychainGet, keychainSet, keychainDelete, KEYCHAIN_SERVICE } from './config.js';
|
|
12
|
+
import { withFileLock } from './file-lock.js';
|
|
13
|
+
import { microsoftClient, microsoftReady, microsoftRelayReturn } from './microsoft-app.js';
|
|
14
|
+
export { microsoftClient, microsoftReady };
|
|
15
|
+
|
|
16
|
+
export const SIGN_IN_WINDOW_MS = 5 * 60e3;
|
|
17
|
+
const KEEP_MS = 10 * 60e3;
|
|
18
|
+
const key = (account) => `microsoft:${account}`;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The tokens of a Microsoft account, as the Keychain keeps them: read and written under one lock across processes
|
|
22
|
+
* (the daemon renewing a token while the web app signs in again, or the account is removed).
|
|
23
|
+
*/
|
|
24
|
+
const LOCK = path.join(HOME_DIR, 'microsoft-tokens');
|
|
25
|
+
const read = (account) => { try { return JSON.parse(keychainGet(key(account)) || 'null'); } catch { return null; } };
|
|
26
|
+
const keychainStore = {
|
|
27
|
+
get: (account) => read(account),
|
|
28
|
+
set: (account, tokens) => withFileLock(LOCK, () => keychainSet(key(account), JSON.stringify(tokens))),
|
|
29
|
+
update: (account, fn) => withFileLock(LOCK, () => {
|
|
30
|
+
const next = fn(read(account));
|
|
31
|
+
if (next !== undefined) keychainSet(key(account), JSON.stringify(next));
|
|
32
|
+
return next;
|
|
33
|
+
}),
|
|
34
|
+
};
|
|
35
|
+
export const microsoft = microsoftAuth({ store: keychainStore, client: () => microsoftClient(), signInHint: () => 'sign in to Microsoft again from Settings, Accounts' });
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* What getCredentials gives mailcore for a Microsoft account: the address, and a token asked for at each connection.
|
|
39
|
+
* `force`: asked again after the server refused one (a session ended before its token did): renewed once, then as usual.
|
|
40
|
+
*/
|
|
41
|
+
export function microsoftCredentials(acct, { force = false } = {}) {
|
|
42
|
+
const name = acct.name;
|
|
43
|
+
let renew = !!force;
|
|
44
|
+
return { username: acct.email, domain: '', oauth: () => { const f = renew; renew = false; return microsoft.accessToken(name, { force: f }); } };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** An account removed: its tokens go with it. */
|
|
48
|
+
export function forgetMicrosoft(account) {
|
|
49
|
+
try { withFileLock(LOCK, () => keychainDelete(KEYCHAIN_SERVICE, key(account))); } catch { /* none */ }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The domains of Microsoft's own mailboxes: a personal account of another address (a Gmail one) has no mailbox there. */
|
|
53
|
+
const OUTLOOK_DOMAIN = /@(outlook|hotmail|live|msn|passport)\.[a-z.]+$/i;
|
|
54
|
+
|
|
55
|
+
/** The account a signed-in address becomes: its name (free here), its servers, a Microsoft sign-in. */
|
|
56
|
+
export function accountFor(email, { personal, label } = {}, accounts = {}) {
|
|
57
|
+
const local = String(email).split('@')[0].toLowerCase().replace(/[^a-z0-9._-]/g, '') || 'outlook';
|
|
58
|
+
const base = personal ? 'outlook' : (String(email).split('@')[1] || '').split('.')[0].toLowerCase().replace(/[^a-z0-9-]/g, '') || local;
|
|
59
|
+
let name = base;
|
|
60
|
+
for (let k = 2; Object.hasOwn(accounts, name); k++) name = `${base}${k}`;
|
|
61
|
+
const { imap, smtp } = microsoftServers(!!personal);
|
|
62
|
+
return { name, account: { provider: 'imap', email: String(email).toLowerCase(), ...(label ? { label: String(label).slice(0, 80) } : {}), imap, smtp, credentials: { source: 'microsoft' } } };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// --- a sign-in from the panel: one at a time ---------------------------------
|
|
66
|
+
let current = null; // { gen, flow, startedAt, expiresAt, result?, endedAt? }
|
|
67
|
+
let serial = 0;
|
|
68
|
+
const ended = (entry, result) => { if (!entry.result) { entry.result = result; entry.endedAt = Date.now(); } };
|
|
69
|
+
const reasonOf = (e) => String(e?.message || e || 'the sign-in failed').slice(0, 300);
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Where a signed-in address would go, or why it cannot: { renew: name } (the account it already is), { add: true },
|
|
73
|
+
* or { refused: reason }. Asked before the sign-in says it worked, and again when the account is written.
|
|
74
|
+
*/
|
|
75
|
+
function placeOf(tokens, accounts = {}) {
|
|
76
|
+
// matched by who signed in (Microsoft's ids, kept with its tokens), never by the address alone: an address can
|
|
77
|
+
// be another sign-in's too. The same address under another Microsoft identity is refused, not replaced.
|
|
78
|
+
const ours = Object.entries(accounts).filter(([, a]) => a?.credentials?.source === 'microsoft');
|
|
79
|
+
const same = ours.find(([n]) => read(n)?.identity && read(n).identity === tokens.identity);
|
|
80
|
+
if (same) return { renew: same[0] };
|
|
81
|
+
if (tokens.personal && !OUTLOOK_DOMAIN.test(tokens.email)) return { refused: `${tokens.email} is a Microsoft account without an Outlook.com mailbox: add it as the mailbox it is (its provider's server), or sign in with your Outlook.com address.` };
|
|
82
|
+
const clash = Object.entries(accounts).find(([, a]) => String(a?.email || '').toLowerCase() === tokens.email);
|
|
83
|
+
if (clash) return { refused: `${tokens.email} is here already (${clash[0]}), signed in another way: remove it first to add it with this Microsoft sign-in.` };
|
|
84
|
+
return { add: true };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Start a sign-in that adds a mailbox (or renews the sign-in of the account with that address). { url, expiresAt, via }:
|
|
89
|
+
* the page to open; then signInStatus says how it went. `label`: the name it is shown by. `via`: 'local' (the browser is
|
|
90
|
+
* on this computer: Microsoft answers a one-time server here, on `port` if given, one a tunnel can forward) or 'relay'
|
|
91
|
+
* (the browser is anywhere: Microsoft answers at the relay, which hands it here; see relayReturn).
|
|
92
|
+
*/
|
|
93
|
+
export async function startSignIn({ label, via = 'local', port } = {}, opts = {}) {
|
|
94
|
+
if (!microsoftReady()) throw new Error('Sideora has no Microsoft app configured yet (config.microsoft.clientId)');
|
|
95
|
+
const timeoutMs = opts.timeoutMs ?? SIGN_IN_WINDOW_MS;
|
|
96
|
+
const auth = opts.auth ?? microsoftAuth({ store: { get: () => null, set: () => {} }, client: () => microsoftClient() });
|
|
97
|
+
const restart = opts.restart ?? (async () => (await import('./accounts.js')).restartDaemon());
|
|
98
|
+
let where = {};
|
|
99
|
+
let expect = null;
|
|
100
|
+
if (via === 'relay') {
|
|
101
|
+
const relayMod = opts.relay !== undefined ? null : await import('./relay.js');
|
|
102
|
+
const relay = opts.relay !== undefined ? opts.relay : relayMod.readState();
|
|
103
|
+
expect = opts.expect ?? ((state, until) => relayMod.relayExpect(state, until));
|
|
104
|
+
if (!relay) throw new Error('This computer is not on a relay: Microsoft can only send the sign-in back to a browser here. Sign in where Sideora runs, or join the relay first.');
|
|
105
|
+
const back = microsoftRelayReturn(relay.url);
|
|
106
|
+
if (!back) throw new Error(`Microsoft only sends Sideora's sign-ins back to Sideora's own relay, not to ${relay.url}: sign in on the computer Sideora runs on.`);
|
|
107
|
+
// (Microsoft's answer arrives where the relay's connection is kept: the web app's process, not the extension's bridge)
|
|
108
|
+
if (relayMod && !relayMod.relayHere()) throw new Error('A sign-in through the relay is started from Sideora\'s web app (or a paired device): the relay\'s connection is kept there.');
|
|
109
|
+
where = { redirectUri: back, stateTag: relay.instance };
|
|
110
|
+
} else if (via !== 'local') {
|
|
111
|
+
throw new Error('via is local or relay');
|
|
112
|
+
} else if (port !== undefined) {
|
|
113
|
+
const n = Number(port);
|
|
114
|
+
if (!Number.isInteger(n) || n < 1024 || n > 65535) throw new Error('the port is a number from 1024 to 65535');
|
|
115
|
+
where = { port: n };
|
|
116
|
+
}
|
|
117
|
+
const gen = ++serial;
|
|
118
|
+
if (current && !current.result) { try { current.flow?.cancel(); } catch { /* ended */ } ended(current, { state: 'cancelled' }); }
|
|
119
|
+
const startedAt = Date.now();
|
|
120
|
+
const entry = { gen, flow: null, startedAt, expiresAt: startedAt + timeoutMs };
|
|
121
|
+
current = entry;
|
|
122
|
+
// what Microsoft's page says at the end is only said once Sideora kept the account (or said why it would not)
|
|
123
|
+
let kept = null; // { name, renewed }
|
|
124
|
+
const accept = async (tokens) => {
|
|
125
|
+
if (current !== entry) return 'This sign-in was replaced by another one.';
|
|
126
|
+
try {
|
|
127
|
+
let name, renewed = false;
|
|
128
|
+
updateConfig((raw) => {
|
|
129
|
+
raw.accounts ??= {};
|
|
130
|
+
const place = placeOf(tokens, raw.accounts);
|
|
131
|
+
if (place.refused) throw new Error(place.refused);
|
|
132
|
+
if (place.renew) { name = place.renew; renewed = true; return; }
|
|
133
|
+
const made = accountFor(tokens.email, { personal: tokens.personal, label }, raw.accounts);
|
|
134
|
+
name = made.name;
|
|
135
|
+
raw.accounts[name] = made.account;
|
|
136
|
+
if (!raw.defaultAccount) raw.defaultAccount = name;
|
|
137
|
+
});
|
|
138
|
+
try { keychainStore.set(name, tokens); } catch (e) {
|
|
139
|
+
// the tokens could not be kept: an account made just now goes again, rather than stay without its sign-in
|
|
140
|
+
if (!renewed) try { updateConfig((raw) => { if (raw.accounts?.[name]?.credentials?.source !== 'microsoft') return; delete raw.accounts[name]; if (raw.defaultAccount === name) delete raw.defaultAccount; }); } catch { /* said below */ }
|
|
141
|
+
throw new Error(`the sign-in could not be kept in the Keychain (${reasonOf(e)})`);
|
|
142
|
+
}
|
|
143
|
+
kept = { name, renewed };
|
|
144
|
+
return true;
|
|
145
|
+
} catch (e) {
|
|
146
|
+
return reasonOf(e);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
let flow;
|
|
150
|
+
try {
|
|
151
|
+
// the tokens are not stored by the flow (its store keeps nothing): they are kept below, once the account is known
|
|
152
|
+
flow = await auth.beginLogin('new', { timeoutMs, appName: 'Sideora', accept, ...where });
|
|
153
|
+
} catch (e) { ended(entry, { state: 'failed', reason: reasonOf(e) }); throw e; }
|
|
154
|
+
if (current !== entry || entry.result) { flow.cancel(); throw new Error('the sign-in was ended meanwhile'); }
|
|
155
|
+
entry.flow = flow;
|
|
156
|
+
if (expect && expect(flow.state, entry.expiresAt) === false) { flow.cancel(); ended(entry, { state: 'failed', reason: 'the relay connection is not kept here' }); throw new Error('A sign-in through the relay is started from Sideora\'s web app: the relay\'s connection is kept there.'); }
|
|
157
|
+
flow.done.then(async (tokens) => {
|
|
158
|
+
if (!kept) return ended(entry, { state: 'failed', reason: 'the sign-in was not kept' });
|
|
159
|
+
const { name, renewed } = kept;
|
|
160
|
+
let restarted = false;
|
|
161
|
+
try { restarted = !!(await restart()); } catch { restarted = false; }
|
|
162
|
+
ended(entry, { state: 'done', account: name, email: tokens.email, renewed, restarted });
|
|
163
|
+
}, (e) => ended(entry, e?.code === 'SIGN_IN_TIMEOUT' ? { state: 'expired' } : e?.code === 'SIGN_IN_CANCELLED' ? { state: 'cancelled' } : { state: 'failed', reason: reasonOf(e) }));
|
|
164
|
+
return { url: flow.url, expiresAt: new Date(entry.expiresAt).toISOString(), via };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* What Microsoft sent to the relay for a sign-in started here: { ok, status, text } for the page the relay shows. Only
|
|
169
|
+
* the sign-in waiting now, with its very state, takes it: anything else is told it is not waited for.
|
|
170
|
+
*/
|
|
171
|
+
export async function relayReturn(body) {
|
|
172
|
+
const q = body && typeof body === 'object' ? body : {};
|
|
173
|
+
const pick = (k) => (typeof q[k] === 'string' ? q[k].slice(0, 4096) : undefined);
|
|
174
|
+
const entry = current;
|
|
175
|
+
if (!entry || entry.result || !entry.flow?.complete) return { ok: false, status: 410, text: 'No Microsoft sign-in is waiting on this computer now: start it again from Sideora.' };
|
|
176
|
+
const a = await entry.flow.complete({ code: pick('code'), state: pick('state'), error: pick('error'), error_description: pick('error_description') });
|
|
177
|
+
return { ok: !!a.ok, status: a.status, text: String(a.text) };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** none | pending (expiresAt) | done (account, email, renewed, restarted) | failed (reason) | expired | cancelled. */
|
|
181
|
+
export function signInStatus() {
|
|
182
|
+
const entry = current;
|
|
183
|
+
if (!entry) return { state: 'none' };
|
|
184
|
+
if (entry.result) {
|
|
185
|
+
if (Date.now() - entry.endedAt > KEEP_MS) { current = null; return { state: 'none' }; }
|
|
186
|
+
return entry.result;
|
|
187
|
+
}
|
|
188
|
+
return { state: 'pending', expiresAt: new Date(entry.expiresAt).toISOString() };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function cancelSignIn() {
|
|
192
|
+
if (current && !current.result) { if (current.flow?.cancel() !== false) ended(current, { state: 'cancelled' }); }
|
|
193
|
+
return signInStatus();
|
|
194
|
+
}
|
package/src/migrate.js
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
// An install from before the rename (when Sideora was called MailWatcher), moved over to Sideora's names:
|
|
2
|
+
// `sideora migrate`, and `sideora install` first when it finds one. Every name below that still says mailwatcher
|
|
3
|
+
// is the old install's, looked for in order to move it: nothing else in Sideora uses them.
|
|
4
|
+
//
|
|
5
|
+
// refused, nothing changed: both folders hold data; the old services ran on another data folder (MAILWATCHER_HOME)
|
|
6
|
+
// than the one this would use; a program of the old install still runs (Claude Code's MCP server, Chrome's
|
|
7
|
+
// native host, a `watch` or `web` in a terminal); its services cannot be confirmed stopped
|
|
8
|
+
// a. the old background services stopped (confirmed), then their definitions removed
|
|
9
|
+
// b. ~/.mailwatcher moved to ~/.sideora in one rename, then the paths written in its files made the new folder's
|
|
10
|
+
// c. each secret moved from the old Keychain services to the new ones: its bytes read, kept under the new name,
|
|
11
|
+
// read back the same, and only then taken from the old one (never shown); the secrets file likewise
|
|
12
|
+
// d. the new native messaging host written in each browser, then the old one removed
|
|
13
|
+
// e. the MCP server registered in Claude Code as "sideora", then "mail" removed; the Claude Code plugin likewise
|
|
14
|
+
// f. the background services set up again from this program, only once every secret has moved
|
|
15
|
+
//
|
|
16
|
+
// What is left to do is kept in a journal (migrate-pending.json, in the folder that moves) before anything is
|
|
17
|
+
// changed, and each step is taken off it only once it is done and checked: run again, it does what is left.
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import os from 'node:os';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { execFileSync, spawnSync } from 'node:child_process';
|
|
23
|
+
import { HOME_DIR, keychainList, keychainReadBytes, keychainWrite, keychainDelete } from './config.js';
|
|
24
|
+
import * as systemd from './host/systemd.js';
|
|
25
|
+
|
|
26
|
+
/** The old install's names. */
|
|
27
|
+
export const OLD = {
|
|
28
|
+
home: path.join(os.homedir(), '.mailwatcher'),
|
|
29
|
+
labels: { daemon: 'com.mailwatcher.daemon', web: 'com.mailwatcher.web' },
|
|
30
|
+
units: { daemon: 'mailwatcher-daemon.service', web: 'mailwatcher-web.service' },
|
|
31
|
+
host: 'com.mailwatcher.bridge',
|
|
32
|
+
mcp: 'mail',
|
|
33
|
+
plugin: /^mailwatcher@[\w.-]+$/,
|
|
34
|
+
marketplace: 'mailwatcher',
|
|
35
|
+
/** the command line of one of its programs (by its file, or by the names npm linked it as) */
|
|
36
|
+
process: 'bin/(mailwatcher|mw|rmail)(\\.js)?( |$)'
|
|
37
|
+
};
|
|
38
|
+
export const JOURNAL = 'migrate-pending.json';
|
|
39
|
+
|
|
40
|
+
/** The Keychain service an old one moves to, or null when it is not one of the old install's. */
|
|
41
|
+
export function newService(old) {
|
|
42
|
+
if (old === 'mailwatcher-ews') return 'sideora';
|
|
43
|
+
return /^mailwatcher-[\w.-]+$/.test(old) ? `sideora-${old.slice('mailwatcher-'.length)}` : null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Something in it that is not a folder (a file, a link), however deep. */
|
|
47
|
+
export function hasContent(dir) {
|
|
48
|
+
let names;
|
|
49
|
+
try { names = fs.readdirSync(dir, { withFileTypes: true }); } catch { return false; }
|
|
50
|
+
return names.some((n) => !n.isDirectory() || hasContent(path.join(dir, n.name)));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const launchAgent = (label) => path.join(os.homedir(), 'Library/LaunchAgents', `${label}.plist`);
|
|
54
|
+
const unitFile = (unit) => path.join(systemd.UNIT_DIR, unit);
|
|
55
|
+
const readJson = (file) => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } };
|
|
56
|
+
|
|
57
|
+
/** The old services' definitions there: [{ kind, via: 'launchd' | 'systemd', name, file, text }]. */
|
|
58
|
+
function oldServices() {
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const [kind, label] of Object.entries(OLD.labels)) { const file = launchAgent(label); if (fs.existsSync(file)) out.push({ kind, via: 'launchd', name: label, file, text: fs.readFileSync(file, 'utf8') }); }
|
|
61
|
+
for (const [kind, unit] of Object.entries(OLD.units)) { const file = unitFile(unit); if (fs.existsSync(file)) out.push({ kind, via: 'systemd', name: unit, file, text: fs.readFileSync(file, 'utf8') }); }
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** The journal of a move begun and not finished, wherever it is (the old folder until it moves, then the new). */
|
|
66
|
+
export const journalFile = () => [path.join(OLD.home, JOURNAL), path.join(HOME_DIR, JOURNAL)].find((f) => fs.existsSync(f)) || null;
|
|
67
|
+
|
|
68
|
+
/** What is there of an old install: { home, services: [files], journal }. */
|
|
69
|
+
export function findOld() {
|
|
70
|
+
return { home: hasContent(OLD.home), services: oldServices().map((s) => s.file), journal: journalFile() };
|
|
71
|
+
}
|
|
72
|
+
export const oldFound = () => { const o = findOld(); return o.home || o.services.length > 0 || !!o.journal; };
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* An old install, and nothing yet under the new name: what every command says rather than start empty. Not with a
|
|
76
|
+
* data folder named (SIDEORA_HOME): that one is the one asked for.
|
|
77
|
+
*/
|
|
78
|
+
export const pendingMigration = () => !process.env.SIDEORA_HOME && hasContent(OLD.home) && !hasContent(HOME_DIR);
|
|
79
|
+
export const PENDING_MESSAGE = 'an install from before the rename was found (~/.mailwatcher): run `sideora migrate`';
|
|
80
|
+
|
|
81
|
+
/** How the old web app was started (its service file's --port, --no-admin). */
|
|
82
|
+
function webArgs(text) {
|
|
83
|
+
const port = /--port(?:<\/string>\s*<string>|"?\s+"?)(\d{1,5})/.exec(text)?.[1];
|
|
84
|
+
return { ...(port ? { port: Number(port) } : {}), admin: !/--no-admin/.test(text) };
|
|
85
|
+
}
|
|
86
|
+
/** The data folder an old service was given (MAILWATCHER_HOME), or null. */
|
|
87
|
+
function serviceHome(text) {
|
|
88
|
+
const plist = /<key>MAILWATCHER_HOME<\/key>\s*<string>([^<]*)<\/string>/.exec(text)?.[1];
|
|
89
|
+
if (plist !== undefined) return plist.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&');
|
|
90
|
+
const unit = /^Environment="?MAILWATCHER_HOME=(.*?)"?$/m.exec(text)?.[1];
|
|
91
|
+
return unit !== undefined ? unit.replace(/%%/g, '%').replace(/\$\$/g, '$').replace(/\\(["\\])/g, '$1') : null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A file written whole, beside it then moved over it, with the mode it had. */
|
|
95
|
+
function rewrite(file, text) {
|
|
96
|
+
const mode = fs.statSync(file).mode & 0o777;
|
|
97
|
+
const tmp = `${file}.migrate-${process.pid}`;
|
|
98
|
+
fs.writeFileSync(tmp, text, { mode });
|
|
99
|
+
fs.chmodSync(tmp, mode);
|
|
100
|
+
fs.renameSync(tmp, file);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** The bytes of a secret as text that is kept again as exactly those bytes (UTF-8, one line, no NUL), or null. */
|
|
104
|
+
function asText(bytes) {
|
|
105
|
+
let s;
|
|
106
|
+
try { s = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { return null; }
|
|
107
|
+
return !s || /[\r\n\0]/.test(s) || !Buffer.from(s, 'utf8').equals(bytes) ? null : s;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const defaultRun = (cmd, args) => execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 20_000 });
|
|
111
|
+
const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
112
|
+
|
|
113
|
+
/** The processes of the old install still running, but those excluded: [{ pid, command }]. */
|
|
114
|
+
function oldProcesses(exclude) {
|
|
115
|
+
let out = '';
|
|
116
|
+
const r = spawnSync('pgrep', ['-fl', OLD.process], { encoding: 'utf8', timeout: 10_000 });
|
|
117
|
+
if (r.error?.code === 'ENOENT') {
|
|
118
|
+
const ps = spawnSync('ps', ['ax', '-o', 'pid=,command='], { encoding: 'utf8', timeout: 10_000 });
|
|
119
|
+
if (ps.status !== 0) throw new Error('the running programs could not be listed');
|
|
120
|
+
const re = new RegExp(OLD.process);
|
|
121
|
+
out = String(ps.stdout || '').split('\n').filter((l) => re.test(l)).join('\n');
|
|
122
|
+
} else if (r.status === 0) out = r.stdout;
|
|
123
|
+
else if (r.status !== 1) throw new Error('the running programs could not be listed');
|
|
124
|
+
return out.split('\n').map((l) => /^\s*(\d+)\s+(.*)$/.exec(l)).filter(Boolean)
|
|
125
|
+
.map((m) => ({ pid: Number(m[1]), command: m[2] })).filter((p) => !exclude.includes(p.pid));
|
|
126
|
+
}
|
|
127
|
+
const listed = (ps) => ps.map((p) => ` ${p.pid} ${p.command.slice(0, 160)}`).join('\n');
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* The move, step by step. `steps` are the command line's own: hostDirs(), installExtension(), writeMcpConfig(),
|
|
131
|
+
* mcpRegistered(name), installMcp() (adds "sideora"), removeMcp(name), plugins() → ids installed, installPlugin()
|
|
132
|
+
* (throws when it cannot be done here), removePlugin(id), removeMarketplace(name), installDaemon(),
|
|
133
|
+
* installWeb({ port, admin }). `log(line)`; `run(cmd, args)` (launchctl, systemctl); `wait(ms)`.
|
|
134
|
+
* → { done: [lines], problems: [lines] }. Throws, with nothing changed, when it cannot be done at all.
|
|
135
|
+
*/
|
|
136
|
+
export function migrate({ steps, log = () => {}, run = defaultRun, wait = sleep }) {
|
|
137
|
+
const done = []; const problems = [];
|
|
138
|
+
const did = (line) => { done.push(line); log(`✓ ${line}`); };
|
|
139
|
+
const failed = (line) => { problems.push(line); log(`✗ ${line}`); };
|
|
140
|
+
const shown = (p) => (p.startsWith(os.homedir() + path.sep) ? `~${p.slice(os.homedir().length)}` : p);
|
|
141
|
+
const OLD_SHOWN = shown(OLD.home); const NEW_SHOWN = shown(HOME_DIR);
|
|
142
|
+
|
|
143
|
+
// --- refused, with nothing changed ---
|
|
144
|
+
const services = oldServices();
|
|
145
|
+
const moving = hasContent(OLD.home);
|
|
146
|
+
if (path.resolve(OLD.home) === path.resolve(HOME_DIR)) throw new Error('the data folder asked for (SIDEORA_HOME) is the old one: point it elsewhere');
|
|
147
|
+
const elsewhere = services.map((s) => serviceHome(s.text)).find((h) => h && path.resolve(h) !== path.resolve(OLD.home));
|
|
148
|
+
if (elsewhere && path.resolve(elsewhere) !== path.resolve(HOME_DIR)) {
|
|
149
|
+
throw new Error(`the old services ran on the data folder ${elsewhere} (MAILWATCHER_HOME), not ${OLD_SHOWN}: nothing was changed. `
|
|
150
|
+
+ `Move that one over by naming it: SIDEORA_HOME="${elsewhere}" sideora migrate (and keep SIDEORA_HOME set so for Sideora from then on), `
|
|
151
|
+
+ `or move it to ${NEW_SHOWN} first (mv "${elsewhere}" ${NEW_SHOWN}) and run \`sideora migrate\` again`);
|
|
152
|
+
}
|
|
153
|
+
if (moving && hasContent(HOME_DIR)) {
|
|
154
|
+
throw new Error(`both ${OLD_SHOWN} (from before the rename) and ${NEW_SHOWN} hold data: nothing was changed. Keep the one you want: `
|
|
155
|
+
+ `to move the old one over, put the new one aside (mv ${NEW_SHOWN} ${NEW_SHOWN}.aside) and run \`sideora migrate\` again; `
|
|
156
|
+
+ `to keep the new one, put the old one aside (mv ${OLD_SHOWN} ${OLD_SHOWN}.aside)`);
|
|
157
|
+
}
|
|
158
|
+
// any program of the old install but its services' own would write to the old folder as it moves (or make it
|
|
159
|
+
// again): closed first
|
|
160
|
+
const isLoaded = (s) => {
|
|
161
|
+
if (s.via === 'launchd') { try { const out = run('launchctl', ['list', s.name]); return { loaded: true, pid: Number(/"PID"\s*=\s*(\d+)/.exec(String(out))?.[1]) || null }; } catch { return { loaded: false }; } }
|
|
162
|
+
try { run('systemctl', ['--user', 'is-active', '--quiet', s.name]); return { loaded: true, pid: null }; } catch (e) { if (e.code === 'ENOENT') throw new Error('systemctl was not found: the old services cannot be confirmed stopped'); return { loaded: false }; }
|
|
163
|
+
};
|
|
164
|
+
const servicePids = services.map((s) => isLoaded(s).pid).filter(Boolean);
|
|
165
|
+
const others = oldProcesses([process.pid, process.ppid, ...servicePids]);
|
|
166
|
+
if (others.length) {
|
|
167
|
+
throw new Error('programs of the install from before the rename are still running: nothing was changed. Close them, then run `sideora migrate` again '
|
|
168
|
+
+ `(Claude Code sessions run its MCP server; Chrome runs its native host; a \`watch\` or \`web\` may be open in a terminal):\n${listed(others)}`);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// --- a. the old services stopped, and confirmed so, before anything else is changed ---
|
|
172
|
+
for (const s of services) {
|
|
173
|
+
let said = '';
|
|
174
|
+
const note = (e) => { said ||= String(e.stderr || e.message || '').trim(); };
|
|
175
|
+
if (s.via === 'launchd') {
|
|
176
|
+
try { run('launchctl', ['unload', s.file]); } catch (e) { note(e); }
|
|
177
|
+
if (isLoaded(s).loaded) { try { run('launchctl', ['remove', s.name]); } catch (e) { note(e); } }
|
|
178
|
+
} else {
|
|
179
|
+
try { run('systemctl', ['--user', 'disable', '--now', s.name]); } catch (e) { note(e); }
|
|
180
|
+
}
|
|
181
|
+
let still = isLoaded(s).loaded;
|
|
182
|
+
for (let i = 0; still && i < 10; i++) { wait(300); still = isLoaded(s).loaded; }
|
|
183
|
+
if (still) throw new Error(`the old service ${s.name} could not be stopped${said ? ` (${said.slice(0, 200)})` : ''}: nothing was moved or removed. Stop it (${s.via === 'launchd' ? `launchctl unload ${s.file}` : `systemctl --user disable --now ${s.name}`}), then run \`sideora migrate\` again`);
|
|
184
|
+
}
|
|
185
|
+
let left = oldProcesses([process.pid, process.ppid]);
|
|
186
|
+
for (let i = 0; left.length && i < 10; i++) { wait(500); left = oldProcesses([process.pid, process.ppid]); }
|
|
187
|
+
if (left.length) throw new Error(`the old services are stopped, and programs of theirs still run: nothing was moved or removed. End them, then run \`sideora migrate\` again:\n${listed(left)}`);
|
|
188
|
+
|
|
189
|
+
// the journal, before anything is removed: what is to be done
|
|
190
|
+
const journalAt = moving ? path.join(OLD.home, JOURNAL) : path.join(HOME_DIR, JOURNAL);
|
|
191
|
+
const journal = readJson(journalFile() || journalAt) || {};
|
|
192
|
+
for (const s of services) journal[s.kind] = s.kind === 'web' ? webArgs(s.text) : true;
|
|
193
|
+
if (moving) { journal.paths = true; if (fs.existsSync(path.join(OLD.home, 'mcp.json'))) journal.mcpConfig = true; }
|
|
194
|
+
if (steps.hostDirs().some((d) => fs.existsSync(path.join(d, `${OLD.host}.json`))) || (moving && fs.existsSync(path.join(OLD.home, 'native-host.sh')))) journal.nativeHost = true;
|
|
195
|
+
try { if (steps.mcpRegistered(OLD.mcp)) journal.mcp = true; } catch { /* asked again next time */ }
|
|
196
|
+
try { if ((steps.plugins() || []).some((id) => OLD.plugin.test(id))) journal.plugin = true; } catch { /* asked again next time */ }
|
|
197
|
+
const save = (at) => {
|
|
198
|
+
if (Object.keys(journal).length) { fs.mkdirSync(path.dirname(at), { recursive: true, mode: 0o700 }); fs.writeFileSync(at, JSON.stringify(journal) + '\n', { mode: 0o600 }); } else { try { fs.unlinkSync(at); } catch { /* none */ } }
|
|
199
|
+
};
|
|
200
|
+
save(journalAt);
|
|
201
|
+
|
|
202
|
+
for (const s of services) {
|
|
203
|
+
try { fs.unlinkSync(s.file); did(`the old ${s.kind === 'web' ? 'web app\'s service' : 'background watcher'} stopped and removed (${shown(s.file)})`); } catch (e) { failed(`${shown(s.file)} could not be removed: ${e.message}`); }
|
|
204
|
+
}
|
|
205
|
+
if (services.some((s) => s.via === 'systemd')) { try { run('systemctl', ['--user', 'daemon-reload']); } catch { /* none to reload */ } }
|
|
206
|
+
|
|
207
|
+
// --- b. the folder: one rename (all of it or none of it) ---
|
|
208
|
+
if (moving) {
|
|
209
|
+
try {
|
|
210
|
+
if (fs.existsSync(HOME_DIR)) fs.rmSync(HOME_DIR, { recursive: true }); // (folders alone: hasContent said so)
|
|
211
|
+
fs.mkdirSync(path.dirname(HOME_DIR), { recursive: true });
|
|
212
|
+
fs.renameSync(OLD.home, HOME_DIR);
|
|
213
|
+
did(`${OLD_SHOWN} moved to ${NEW_SHOWN}`);
|
|
214
|
+
} catch (e) {
|
|
215
|
+
failed(`${OLD_SHOWN} could not be moved to ${NEW_SHOWN} (${e.code === 'EXDEV' ? 'they are on different disks: move it by hand' : e.message}): it is left as it was; run \`sideora migrate\` again once that is fixed`);
|
|
216
|
+
return { done, problems };
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
const at = path.join(HOME_DIR, JOURNAL);
|
|
220
|
+
if (journal.paths) {
|
|
221
|
+
// the paths written in its own files (a link, a sound, a wrapper): the new folder's
|
|
222
|
+
try {
|
|
223
|
+
let n = 0;
|
|
224
|
+
for (const ent of fs.readdirSync(HOME_DIR, { withFileTypes: true })) {
|
|
225
|
+
const file = path.join(HOME_DIR, ent.name);
|
|
226
|
+
if (ent.isSymbolicLink()) {
|
|
227
|
+
const to = fs.readlinkSync(file);
|
|
228
|
+
const hit = [OLD.home, OLD_SHOWN].find((o) => to === o || to.startsWith(o + '/'));
|
|
229
|
+
if (hit) { fs.unlinkSync(file); fs.symlinkSync(HOME_DIR + to.slice(hit.length), file); n++; }
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (!ent.isFile() || ent.name === 'secrets.json' || ent.name === JOURNAL || !/\.(json|ya?ml|sh)$/.test(ent.name)) continue;
|
|
233
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
234
|
+
let next = text.split(OLD.home + '/').join(HOME_DIR + '/').split(`${OLD.home}"`).join(`${HOME_DIR}"`).split(`${OLD.home}'`).join(`${HOME_DIR}'`);
|
|
235
|
+
if (OLD_SHOWN !== OLD.home) next = next.split(OLD_SHOWN + '/').join(NEW_SHOWN + '/');
|
|
236
|
+
if (next !== text) { rewrite(file, next); n++; }
|
|
237
|
+
}
|
|
238
|
+
delete journal.paths; save(at);
|
|
239
|
+
if (n) did(`the paths in ${n} of its file${n === 1 ? '' : 's'} now say ${NEW_SHOWN}`);
|
|
240
|
+
} catch (e) { failed(`the paths written in ${NEW_SHOWN}'s files could not all be changed: ${e.message}`); }
|
|
241
|
+
}
|
|
242
|
+
if (journal.mcpConfig) {
|
|
243
|
+
try { steps.writeMcpConfig(); delete journal.mcpConfig; save(at); did('mcp.json written again for this program'); } catch (e) { failed(`mcp.json could not be written again: ${e.message}`); }
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// --- c. the secrets: each one's bytes read, kept under its new name, read back the same, then taken from the old ---
|
|
247
|
+
const before = problems.length;
|
|
248
|
+
const pairs = new Map();
|
|
249
|
+
const add = (service, account) => { if (newService(service)) pairs.set(`${service}\u0000${account}`, [service, account]); };
|
|
250
|
+
try { for (const [s, a] of keychainList((s) => newService(s) !== null)) add(s, a); } catch { /* looked for by name below */ }
|
|
251
|
+
const config = readJson(path.join(HOME_DIR, 'config.json')) || {};
|
|
252
|
+
for (const n of new Set([...Object.keys(config.accounts || {}), 'default'])) for (const a of [n, `google:${n}`, `microsoft:${n}`]) add('mailwatcher-ews', a);
|
|
253
|
+
for (const [s, a] of [['mailwatcher-cache', 'key'], ['mailwatcher-1password', 'service-account-token'], ['mailwatcher-ai', 'connections-key'], ['mailwatcher-relay', 'membership'], ['mailwatcher-relay', 'request'], ['mailwatcher-elevenlabs', 'default']]) add(s, a);
|
|
254
|
+
let moved = 0;
|
|
255
|
+
for (const [service, account] of pairs.values()) {
|
|
256
|
+
const to = newService(service);
|
|
257
|
+
const what = `the secret "${account.slice(0, 80)}" of ${service}`;
|
|
258
|
+
try {
|
|
259
|
+
const bytes = keychainReadBytes(service, account);
|
|
260
|
+
if (bytes === null) continue;
|
|
261
|
+
const there = keychainReadBytes(to, account);
|
|
262
|
+
if (there !== null && !there.equals(bytes)) { failed(`${what}: ${to} holds another one under that name; both are kept (remove the one you do not want)`); continue; }
|
|
263
|
+
if (there === null) {
|
|
264
|
+
const text = asText(bytes);
|
|
265
|
+
if (text === null) { failed(`${what} is not text that can be kept again byte for byte: it is kept where it was (move it by hand, in Keychain Access, to the service ${to})`); continue; }
|
|
266
|
+
keychainWrite(to, account, text);
|
|
267
|
+
const back = keychainReadBytes(to, account);
|
|
268
|
+
if (!back || !back.equals(bytes)) { failed(`${what} did not read back the same under ${to}: the old one is kept`); continue; }
|
|
269
|
+
}
|
|
270
|
+
keychainDelete(service, account);
|
|
271
|
+
moved++;
|
|
272
|
+
} catch (e) { failed(`${what} could not be moved (${e.message}): it is kept where it was`); }
|
|
273
|
+
}
|
|
274
|
+
if (moved) did(`${moved} secret${moved === 1 ? '' : 's'} moved to the new Keychain names`);
|
|
275
|
+
const secretsLeft = problems.length > before;
|
|
276
|
+
|
|
277
|
+
// --- d. the browsers' native host: the new one written, and there, then the old one removed ---
|
|
278
|
+
if (journal.nativeHost) {
|
|
279
|
+
try {
|
|
280
|
+
steps.installExtension();
|
|
281
|
+
if (!steps.hostDirs().some((d) => fs.existsSync(path.join(d, 'com.sideora.bridge.json')))) throw new Error('no browser holds it');
|
|
282
|
+
let gone = 0;
|
|
283
|
+
for (const d of steps.hostDirs()) { try { fs.unlinkSync(path.join(d, `${OLD.host}.json`)); gone++; } catch (e) { if (e.code !== 'ENOENT') throw e; } }
|
|
284
|
+
delete journal.nativeHost; save(at);
|
|
285
|
+
did(`the browsers' native host is now com.sideora.bridge${gone ? ` (the old one removed from ${gone})` : ''}: rebuild and reload the extension`);
|
|
286
|
+
} catch (e) { failed(`the new native host could not be set up (${e.message}): the old one is kept; run \`sideora migrate\` again`); }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// --- e. Claude Code: the MCP server and the plugin under their new names, checked, then the old ones removed ---
|
|
290
|
+
if (journal.mcp) {
|
|
291
|
+
try {
|
|
292
|
+
steps.installMcp();
|
|
293
|
+
if (!steps.mcpRegistered('sideora')) throw new Error('Claude Code does not list it');
|
|
294
|
+
steps.removeMcp(OLD.mcp);
|
|
295
|
+
delete journal.mcp; save(at);
|
|
296
|
+
did('the MCP server is registered in Claude Code as "sideora" (no longer "mail")');
|
|
297
|
+
} catch (e) { failed(`the MCP server could not be registered as "sideora" (${e.message}): "mail" is kept; run \`sideora migrate\` again`); }
|
|
298
|
+
}
|
|
299
|
+
if (journal.plugin) {
|
|
300
|
+
let old = [];
|
|
301
|
+
try { old = (steps.plugins() || []).filter((id) => OLD.plugin.test(id)); } catch { /* the usual name below */ }
|
|
302
|
+
try {
|
|
303
|
+
steps.installPlugin();
|
|
304
|
+
for (const id of old) steps.removePlugin(id);
|
|
305
|
+
try { steps.removeMarketplace(OLD.marketplace); } catch { /* not there */ }
|
|
306
|
+
delete journal.plugin; save(at);
|
|
307
|
+
did('the Claude Code plugin is now "sideora" (no longer "mailwatcher")');
|
|
308
|
+
} catch (e) {
|
|
309
|
+
failed(`the Claude Code plugin could not be installed as "sideora" here (${e.message}); the old one is kept. In a terminal:\n`
|
|
310
|
+
+ ' claude plugin marketplace add sideorahq/sideora && claude plugin install sideora@sideora\n'
|
|
311
|
+
+ ` ${(old.length ? old : ['mailwatcher@mailwatcher']).map((id) => `claude plugin uninstall ${id}`).join(' && ')} && claude plugin marketplace remove mailwatcher`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// --- f. the services, from this program: not while secrets are left under their old names, nor on an empty folder ---
|
|
316
|
+
if (journal.daemon || journal.web) {
|
|
317
|
+
if (secretsLeft) failed('the background services are not set up again while secrets are left under their old names (said above): run `sideora migrate` again once they can move');
|
|
318
|
+
else if (!fs.existsSync(path.join(HOME_DIR, 'config.json'))) failed(`the background services are not set up again: ${NEW_SHOWN} holds no config.json (is the data elsewhere? SIDEORA_HOME names it)`);
|
|
319
|
+
else {
|
|
320
|
+
if (journal.daemon) { try { steps.installDaemon(); delete journal.daemon; save(at); did('the background watcher set up again (com.sideora.daemon)'); } catch (e) { failed(`the background watcher could not be set up (${e.message}): run \`sideora migrate\` again`); } }
|
|
321
|
+
if (journal.web) { try { steps.installWeb(typeof journal.web === 'object' ? journal.web : {}); delete journal.web; save(at); did('the web app\'s service set up again (com.sideora.web)'); } catch (e) { failed(`the web app's service could not be set up (${e.message}): run \`sideora migrate\` again`); } }
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
try { save(at); } catch { /* said next time */ }
|
|
325
|
+
if (!done.length && !problems.length) log('nothing to move: no install from before the rename was found');
|
|
326
|
+
return { done, problems };
|
|
327
|
+
}
|