Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
2346 lines (2315 loc) · 133 KB
/
Copy pathserver.js
File metadata and controls
2346 lines (2315 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// M365-Sphere — local web server + dashboard
const express = require('express');
const fs = require('fs');
const path = require('path');
const { EventEmitter } = require('events');
const { spawn } = require('child_process');
const crypto = require('crypto');
const { Auth } = require('./lib/auth');
const { GraphClient } = require('./lib/graph');
const { EwsClient } = require('./lib/ews');
const { Store } = require('./lib/store');
const { Engine, parseMimeHeaders } = require('./lib/engine');
const { PstExporter } = require('./lib/pst');
const { Setup } = require('./lib/setup');
const { Updater } = require('./lib/updater');
const { Exo } = require('./lib/exo');
const { ExoExport } = require('./lib/exoexport');
const { PstIngest } = require('./lib/pstingest');
const { CopyEngine } = require('./lib/copy');
const { DedupeEngine, fuzzyDupes } = require('./lib/dedupe');
const { CopyEmailEngine } = require('./lib/copyemail');
const { MoveEmailEngine } = require('./lib/moveemail');
const { parseStoredItem, toPreview, readRaw, chainPath, itemFile } = require('./lib/preview');
const { simpleParser } = require('mailparser');
const zlib = require('zlib');
const { pipeline } = require('stream/promises');
const { Readable } = require('stream');
const fsp = require('fs/promises');
const { ftsPreview, ftsAttachment } = require('./lib/fts');
const { safeName, isValidUpn } = require('./lib/util');
const { computeCoverage, refreshCoverage, scopeCoverage } = require('./lib/coverage');
const archiver = require('archiver');
const CONFIG_PATH = path.join(__dirname, 'config.json');
if (!fs.existsSync(CONFIG_PATH)) {
const template = path.join(__dirname, 'config.example.json');
if (!fs.existsSync(template)) {
console.error('config.example.json is missing from the install folder — reinstall or restore it, then start again.');
process.exit(1);
}
fs.copyFileSync(template, CONFIG_PATH);
console.log('Created config.json from template — starting unconfigured; finish setup in the dashboard.');
}
const cfg = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
cfg.dataDir = path.resolve(__dirname, cfg.dataDir || './data');
cfg.pstDir = path.resolve(__dirname, cfg.pstDir || './pst-export');
// Disk-space preflight shared by the backup/PST routes and the EXO export
// loop: returns an Error when the store drive is below the configured reserve
// (default 10 GB), null otherwise. A statfs failure must not block jobs.
function diskCheck() {
try {
const st = fs.statfsSync(cfg.dataDir);
const reserve = cfg.diskReserveBytes || 10 * 1024 ** 3;
if (st.available < reserve) {
return new Error(`insufficient disk space: ${(st.available / 2 ** 30).toFixed(1)} GB free, reserve is ${(reserve / 2 ** 30).toFixed(1)} GB — free space or lower diskReserveBytes`);
}
} catch { }
return null;
}
// The server runs detached with no console — capture fatal errors to a log so
// mid-job crashes (which the dashboard only sees as "Failed to fetch") are
// diagnosable after the fact.
const crashLog = path.join(cfg.dataDir, 'server-crash.log');
const logCrash = (kind, err) => {
try {
fs.appendFileSync(crashLog, `\n=== ${new Date().toISOString()} ${kind} ===\n${(err && err.stack) || err}\n`);
} catch { }
};
process.on('uncaughtException', err => { logCrash('uncaughtException', err); console.error(err); process.exit(1); });
process.on('unhandledRejection', err => { logCrash('unhandledRejection', err); console.error('unhandledRejection:', err); });
// Clean-but-unexpected exits (EADDRINUSE path, updater exit-42, signal kills)
// leave a marker too — V8 fatal errors print to stderr (captured by the
// watchdog's redirected server-err.log since 2026-10-16).
process.on('exit', code => logCrash('exit', `process exiting with code ${code}`));
const store = new Store(cfg.dataDir);
// Startup reconciliation: jobs left 'running' by a crash become 'interrupted';
// prune old events/jobs at startup and then daily.
try { if (store.reconcileJobs) store.reconcileJobs(); } catch (e) { console.error('reconcileJobs failed:', e.message); }
const pruneStore = () => {
try { if (store.pruneEvents) store.pruneEvents(20000); } catch (e) { console.error('pruneEvents failed:', e.message); }
try { if (store.pruneJobs) store.pruneJobs(200); } catch (e) { console.error('pruneJobs failed:', e.message); }
};
pruneStore();
setInterval(pruneStore, 24 * 60 * 60 * 1000).unref();
// Disaster-recovery copy of the state DB (also refreshed after each finished job).
try { if (store.snapshot) store.snapshot(); } catch (e) { console.error('DB snapshot failed:', e.message); }
const bus = new EventEmitter();
bus.setMaxListeners(100);
const log = (level, mailbox, message) => {
store.log(level, mailbox || '', message);
bus.emit('event', { ts: new Date().toISOString(), level, mailbox: mailbox || '', message });
};
// Surface jobs reconcileJobs just marked 'interrupted' (server crash/restart)
// so a dead job is visible in the event log instead of dying silently.
try {
const cutoff = new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString();
const dead = store.db.prepare(`SELECT id, kind, upn FROM jobs WHERE status='interrupted' AND finishedAt >= ?`).all(cutoff);
for (const j of dead) log('warn', j.upn || '', `job "${j.kind}" (#${j.id}) was interrupted by a restart — it can be retried/resumed`);
} catch (e) { console.error('interrupted-jobs check failed:', e.message); }
const auth = new Auth(cfg);
const graph = new GraphClient(auth, log, cfg);
const ews = new EwsClient(auth, log, cfg);
// Graph Mailbox Import/Export (beta) archive provider — read-only; only
// constructed when the feature flag is on. See docs/archive-upgrade-plan.md.
const { GraphIe } = require('./lib/graphie');
const graphie = cfg.graphExchangeExportEnabled ? new GraphIe(cfg, auth, log) : null;
const engine = new Engine({ cfg, store, graph, ews, graphie, log, bus });
const pst = new PstExporter({ cfg, store, log, bus });
const setup = new Setup({ cfg, log, configPath: CONFIG_PATH });
const updater = new Updater({ cfg, log, appRoot: __dirname });
const exo = new Exo({ cfg, log, bus, auth });
const exoExport = new ExoExport({ cfg, store, log, bus, auth, ingest: new PstIngest({ cfg, store, log, bus }), preflight: diskCheck });
const copyEngine = new CopyEngine({ cfg, store, graph, ews, log, bus });
const dedupeEngine = new DedupeEngine({ cfg, store, graph, log, bus });
const copyEmailEngine = new CopyEmailEngine({ cfg, store, graph, ews, engine, log, bus });
const moveEmailEngine = new MoveEmailEngine({ cfg, store, graph, ews, engine, log, bus });
// Copy-email queue rows for /api/status + GET /api/copy-email/queue.
function copyQueueRows() {
return store.copyQueueAll().map(r => {
let cfg = {};
try { cfg = JSON.parse(r.config || '{}'); } catch { }
return {
id: r.id, createdAt: r.createdAt, srcUpn: r.srcUpn, dstUpn: r.dstUpn, target: r.target,
dstLabel: cfg.dstLabel || null,
srcLabel: cfg.srcLabel || null,
dstFolderId: cfg.dst && cfg.dst.folderId || null,
srcMode: cfg.srcMode || 'store',
srcFolderKey: Array.isArray(cfg.folderKeys) && cfg.folderKeys[0] || null,
items: Array.isArray(cfg.items) ? cfg.items.length : 0,
folders: Array.isArray(cfg.folderKeys) ? cfg.folderKeys.length : 0,
retryOf: cfg.retryOf || null
};
});
}
// Device sign-in prompt for an in-flight EXO sizes job, exposed via /api/status
// (same pattern as archiveSignIn in /api/setup/status).
let exoSignIn = null;
const app = express();
app.use(express.json({ limit: '1mb' })); // PST plans can be large folder lists
// Session token guard: all /api/* calls must present the token. Prefer the
// Authorization: Bearer header (or x-session-token); ?token= remains only
// because browser download links and EventSource cannot set headers.
const sessionToken = crypto.randomUUID();
// The token file is written only AFTER the port is bound (see app.listen below) —
// a duplicate instance that dies on EADDRINUSE must not invalidate running clients.
const isLoopbackAddr = ip => ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1';
// LOCAL THREAT MODEL: the dashboard is a local-only app (loopback bind). The token
// exists to stop OTHER local processes/web pages from driving the API (the endpoint
// also rejects cross-site browser fetches via Sec-Fetch-Site), not to protect
// against a malicious process running as the same user — such a process can read
// data/session-token anyway. Never bind this server to a non-loopback address.
app.get('/session-token.js', (req, res) => {
// Cross-site pages (e.g. a malicious website driving localhost from the user's
// browser) send Sec-Fetch-Site: cross-site — refuse them. The dashboard's own
// script tag / fetch come from the same origin and pass. Older clients without
// the header fall back to the loopback check below.
const sfs = req.get('sec-fetch-site');
if (sfs && sfs !== 'same-origin' && sfs !== 'same-site' && sfs !== 'none')
return res.status(403).json({ error: 'session token is only served to same-origin clients' });
if (!isLoopbackAddr(req.socket.remoteAddress || '')) return res.status(403).json({ error: 'session token is only served to loopback clients' });
res.set('Cache-Control', 'no-store');
res.type('application/javascript').send(`window.__SESSION_TOKEN=${JSON.stringify(sessionToken)};`);
});
app.use('/api', (req, res, next) => {
const h = req.get('authorization') || '';
// With allowRemote the token must come via a header only — a ?token= query
// leaks into proxy logs, browser history and referrer headers on network paths.
const t = (h.startsWith('Bearer ') ? h.slice(7) : '') || req.get('x-session-token') || (cfg.allowRemote === true ? undefined : req.query.token);
if (t === sessionToken) return next();
res.status(401).json({ error: 'missing or invalid session token' });
});
// UPNs end up in filesystem paths — validate strictly at the API boundary.
app.param('upn', (req, res, next, val) => {
if (isValidUpn(val)) return next();
res.status(400).json({ error: 'invalid mailbox id' });
});
const wrap = fn => async (req, res) => {
try { res.json(await fn(req) || { ok: true }); }
catch (e) { res.status(e.status || (e.message && e.message.includes('already running') ? 409 : 500)).json({ error: String(e.message || e) }); }
};
app.get('/api/status', wrap(async () => ({
aggregates: store.aggregates(),
jobs: store.listJobs(),
running: engine.running,
pstRunning: pst.running,
compareRunning,
pstDetail: pst.detail(),
copyRunning: copyEngine.running,
dedupeRunning: dedupeEngine.running,
copyEmailRunning: copyEmailEngine.running,
copyEmailRuns: [...copyEmailEngine.runProgress.values()],
copyEmailQueue: copyQueueRows(),
moveEmailRunning: moveEmailEngine.running,
moveEmailRuns: [...moveEmailEngine.runProgress.values()],
dedupeRuns: [...dedupeEngine._runs.keys()],
dedupeChecks: [...dedupeEngine.checkProgress.values()],
sizesRunning,
scanRunning,
exoExport: exoExport.summary(),
liveMove: (() => {
try {
const p = JSON.parse(fs.readFileSync(path.join(cfg.dataDir, 'live-move-progress.json'), 'utf8'));
let running = false;
try { process.kill(p.pid, 0); running = p.state === 'running'; } catch { }
return { ...p, running };
} catch { return null; }
})(),
fixTasks: fixTasks.slice(-60),
exoSignIn,
autoResumeSuppressed,
configured: cfg.clientId && !cfg.clientId.startsWith('your-'),
update: updater.state,
tenant: cfg.tenantName || cfg.tenantId,
archiveGranted: !!cfg.archiveGranted,
scopes: cfg.scopes,
live: engine.live,
jobUpns: engine.jobUpns
})));
app.get('/api/mailboxes', wrap(async () => {
const exoBytes = store.exoExportBytesByUpn();
return store.listMailboxes().map(m => ({ ...m, verifyReport: undefined, exoExportBytes: exoBytes[m.upn] || 0 }));
}));
app.get('/api/mailbox/:upn', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
let report = null;
try { report = m.verifyReport ? JSON.parse(m.verifyReport) : null; } catch { }
// Auto-expanding archive coverage gap: bytes Exchange reports but EWS can never reach.
const ewsArch = m.ewsArchiveBytes != null ? m.ewsArchiveBytes : m.archiveBytes;
const archiveGapBytes = m.autoExpandingArchive && m.serverArchiveBytes != null && ewsArch != null
? Math.max(0, m.serverArchiveBytes - ewsArch) : null;
// EXO supplies archive BYTES only, never an item count, so serverArchiveItems
// stays null and the UI falls back to the main-partition folder counts (~20x
// undercount once aux partitions are ingested). Derive the full archive item
// total instead: main-partition folder counts + auxiliary partition counts.
let serverArchiveItems = m.serverArchiveItems;
if (m.hasArchive) {
const derived = scopeCoverage(store, m.upn, 'archive').serverItems;
if (derived > (serverArchiveItems || 0)) serverArchiveItems = derived;
}
return { ...m, serverArchiveItems, archiveGapBytes, folders: store.listFolders(m.upn), report, events: store.mailboxEvents(m.upn, 100), live: engine.live[m.upn] || null };
}));
app.get('/api/mailbox/:upn/folders', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
let folders = store.folderStats(m.upn);
// Namespace coexistence: once Graph IE ('ie-') archive rows exist, hide plain
// EWS archive rows that hold no local content — they are the same logical
// folders enumerated twice (scan rows vs IE rows).
if (folders.some(f => f.scope === 'archive' && f.folderId.startsWith('ie-'))) {
folders = folders.filter(f => f.scope !== 'archive' || f.folderId.startsWith('ie-') || f.folderId.startsWith('exo') || f.backedUp > 0);
// Keep the ancestor chain of every content-holding EWS folder: dropping
// backedUp=0 EWS parents would mount the child at the tree root.
const keep = new Set(folders.map(f => f.folderId));
const byIdAll = new Map(store.folderStats(m.upn).map(f => [f.folderId, f]));
for (const f of [...folders]) {
let p = f.parentId && byIdAll.get(f.parentId);
while (p && !keep.has(p.folderId)) { keep.add(p.folderId); folders.push(p); p = p.parentId && byIdAll.get(p.parentId); }
}
}
return { upn: m.upn, status: m.status, pstStatus: m.pstStatus, folders, live: engine.live[m.upn] || null, scanLive: scanLive[m.upn] || null };
}));
// Coverage = local verified data vs server-reported data. Separate from job
// status on purpose: a 'done' job can still have PARTIAL coverage.
app.get('/api/mailbox/:upn/coverage', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
// Stale derived rows: once real aux partitions are discovered, drop the
// 'aux-combined' placeholder the sizes job created.
store.db.prepare(`DELETE FROM archive_partitions WHERE upn=? AND partitionId='aux-combined'
AND EXISTS (SELECT 1 FROM archive_partitions WHERE upn=? AND partitionType='aux' AND partitionId != 'aux-combined')`).run(m.upn, m.upn);
// Per-partition local stats, computed live from items in folders attributed to
// each physical partition (folders.physicalMailboxId, learned from redirects).
const byPid = new Map(store.db.prepare(`
SELECT f.physicalMailboxId pid, COUNT(*) n, COALESCE(SUM(i.size),0) bytes
FROM items i JOIN folders f ON f.upn=i.upn AND f.scope=i.scope AND f.folderId=i.folderId
WHERE i.upn=? AND i.scope='archive' AND i.status IN ('done','deduped') AND f.physicalMailboxId IS NOT NULL
GROUP BY f.physicalMailboxId`).all(m.upn).map(r => [r.pid, r]));
const partitions = store.listPartitions(m.upn).map(p => ({
...p,
backedUpItems: byPid.get(p.partitionId)?.n || 0,
backedUpBytes: byPid.get(p.partitionId)?.bytes || 0
}));
const runs = store.listRuns(m.upn, 10);
return { upn: m.upn, coverage: computeCoverage(store, m.upn, { ieEnabled: !!graphie }), partitions, runs };
}));
// PST import recovery stats: per-PST log records + live rebuilt/remaining counts.
app.get('/api/mailbox/:upn/pst-repair', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
const logFile = path.join(cfg.dataDir, 'pst-import-log.json');
let log = [];
try { log = JSON.parse(fs.readFileSync(logFile, 'utf8')); } catch { }
const byFile = new Map();
for (const r of log) byFile.set(r.file, { ...byFile.get(r.file), ...r, replaced: (byFile.get(r.file)?.replaced || 0) + r.replaced });
// Every PST on disk, processed or not.
const pstDir = path.join(__dirname, 'pst-import', m.upn.split('@')[0]);
const onDisk = fs.existsSync(pstDir)
? fs.readdirSync(pstDir).filter(f => f.toLowerCase().endsWith('.pst') && !f.startsWith('~')).sort()
: [];
const verifyResults = pstVerifyState.results();
const psts = onDisk.map(f => {
const rec = byFile.get(f);
const v = verifyResults.get(f);
return {
file: f, size: fs.statSync(path.join(pstDir, f)).size, processed: !!rec,
replaced: rec?.replaced || 0, skipped: rec?.skipped || 0, unmatched: rec?.unmatched || 0, failed: rec?.failed || 0,
verifyFailures: rec?.verifyFailures || 0, finishedAt: rec?.finishedAt || null,
verify: v ? { status: v.status, remark: v.remark || '', checkedAt: v.checkedAt, retry: !!v.retry } : null
};
});
for (const [f, rec] of byFile) if (!onDisk.includes(f)) psts.push({ file: f, size: null, processed: true, replaced: rec.replaced || 0, skipped: rec.skipped || 0, unmatched: rec.unmatched || 0, failed: rec.failed || 0, verifyFailures: rec.verifyFailures || 0, finishedAt: rec.finishedAt || null, missing: true, verify: verifyResults.get(f) ? { status: verifyResults.get(f).status, remark: verifyResults.get(f).remark || '', checkedAt: verifyResults.get(f).checkedAt, retry: !!verifyResults.get(f).retry } : null });
const rebuilt = store.db.prepare(`SELECT COUNT(*) c, COALESCE(SUM(size),0) bytes FROM items WHERE upn=? AND sourceApi='pst-import'`).get(m.upn);
const remaining = store.db.prepare(`SELECT COUNT(*) c FROM items WHERE upn=? AND format='fts' AND status='done'`).get(m.upn);
const totals = log.reduce((a, r) => ({ replaced: a.replaced + r.replaced, skipped: a.skipped + r.skipped, unmatched: a.unmatched + r.unmatched, failed: a.failed + r.failed, verifyFailures: a.verifyFailures + (r.verifyFailures || 0) }),
{ replaced: 0, skipped: 0, unmatched: 0, failed: 0, verifyFailures: 0 });
return { upn: m.upn, psts, totals, rebuiltItems: rebuilt.c, rebuiltBytes: rebuilt.bytes, remainingFts: remaining.c, lastRun: log.length ? log[log.length - 1].finishedAt : null, ...pstRepairState.status(), verifyRunning: pstVerifyState.status().running, verifyLines: pstVerifyState.status().lines };
}));
// Per-folder rebuild report: aggregates folderStats from the latest record of
// each PST file (records from before per-folder tracking contribute nothing).
app.get('/api/mailbox/:upn/pst-repair/report', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
let log = [];
try { log = JSON.parse(fs.readFileSync(path.join(cfg.dataDir, 'pst-import-log.json'), 'utf8')); } catch { }
const latestByFile = new Map();
for (const r of log) latestByFile.set(r.file, r);
const byFolder = new Map();
let withStats = 0, lastRunAt = null;
for (const r of latestByFile.values()) {
if (!Array.isArray(r.folderStats)) continue;
withStats++;
if (!lastRunAt || r.finishedAt > lastRunAt) lastRunAt = r.finishedAt;
for (const fs of r.folderStats) {
const cur = byFolder.get(fs.path) || { path: fs.path, replaced: 0, skipped: 0, unmatched: 0, failed: 0, verifyFailures: 0 };
for (const k of ['replaced', 'skipped', 'unmatched', 'failed', 'verifyFailures']) cur[k] += fs[k] || 0;
byFolder.set(fs.path, cur);
}
}
const folders = [...byFolder.values()].sort((a, b) => b.replaced - a.replaced);
let imageVerify = null;
try { imageVerify = JSON.parse(fs.readFileSync(path.join(cfg.dataDir, 'image-verify-report.json'), 'utf8')); } catch { }
return { upn: m.upn, folders, filesWithStats: withStats, lastRunAt, imageVerify: imageVerify ? { at: imageVerify.at, checked: imageVerify.checked, bad: imageVerify.bad, missingFiles: imageVerify.missingFiles, folders: imageVerify.folders.slice(0, 100), badItems: imageVerify.badItems.slice(0, 200) } : null };
}));
// Run the PST recovery (scripts/pst-repair.js) as a DETACHED background job:
// it survives server restarts, and its state lives in files (job json + log)
// so the panel always shows the truth instead of a stale "running".
const pstRepairState = {
file: () => path.join(cfg.dataDir, 'pst-repair-job.json'),
logFile: () => path.join(cfg.dataDir, 'pst-repair-run.log'),
progressFile: () => path.join(cfg.dataDir, 'pst-repair-progress.json'),
read() { try { return JSON.parse(fs.readFileSync(this.file(), 'utf8')); } catch { return null; } },
alive(pid) { try { process.kill(pid, 0); return true; } catch { return false; } },
tail(n = 60) {
try {
const lines = fs.readFileSync(this.logFile(), 'utf8').trim().split('\n').filter(Boolean);
return lines.slice(-n).map(l => l.slice(0, 300));
} catch { return []; }
},
status() {
const j = this.read();
let progress = null;
try { progress = JSON.parse(fs.readFileSync(this.progressFile(), 'utf8')); } catch { }
if (!j || !j.pid) return { running: false, lastLine: null, lines: [], progress };
const running = this.alive(j.pid);
const lines = this.tail();
return { running, lastLine: lines.length ? lines[lines.length - 1] : null, lines, startedAt: j.startedAt, upn: j.upn, file: j.file || null, progress };
}
};
const spawnPstScript = (script, jobFile, logFile, args) => {
const out = fs.openSync(logFile, 'a');
const child = spawn(process.execPath, [path.join(__dirname, 'scripts', script), ...args], { stdio: ['ignore', out, out], detached: true });
child.unref();
fs.writeFileSync(jobFile, JSON.stringify({ pid: child.pid, startedAt: new Date().toISOString(), args }));
fs.closeSync(out);
return child;
};
app.post('/api/mailbox/:upn/pst-repair', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
if (pstRepairState.status().running) { const e = new Error('PST recovery already running'); e.status = 409; throw e; }
const pstDir = path.join(__dirname, 'pst-import', m.upn.split('@')[0]);
if (!fs.existsSync(pstDir) || !fs.readdirSync(pstDir).some(f => f.toLowerCase().endsWith('.pst')))
throw new Error(`No PSTs found in pst-import/${m.upn.split('@')[0]} — drop the PST files there first`);
const file = req.body && req.body.file;
const args = [m.upn, pstDir];
if (file) {
if (!fs.existsSync(path.join(pstDir, file))) throw new Error(`PST not found: ${file}`);
args.push(`--file=${file}`);
}
const child = spawnPstScript('pst-repair.js', pstRepairState.file(), pstRepairState.logFile(), args);
fs.writeFileSync(pstRepairState.file(), JSON.stringify({ pid: child.pid, upn: m.upn, startedAt: new Date().toISOString(), file: file || null }));
log('info', m.upn, `PST recovery started ${file ? `for ${file} ` : ''}from pst-import/${m.upn.split('@')[0]} (pid ${child.pid})`);
bus.emit('job', { kind: 'pst-repair', upn: m.upn, status: 'running' });
return { ok: true, pid: child.pid };
}));
app.post('/api/mailbox/:upn/pst-repair/stop', wrap(async req => {
const j = pstRepairState.read();
if (!j || !j.pid || !pstRepairState.alive(j.pid)) { const e = new Error('PST recovery is not running'); e.status = 409; throw e; }
try { process.kill(j.pid); } catch { }
log('info', req.params.upn, `PST recovery stopped (pid ${j.pid})`);
return { ok: true };
}));
// PST verification job (scripts/pst-verify.js): per-file ok/failed + remark,
// results land in data/pst-verify-log.json (failed files get retry:true).
const pstVerifyState = {
file: () => path.join(cfg.dataDir, 'pst-verify-job.json'),
logFile: () => path.join(cfg.dataDir, 'pst-verify-run.log'),
resultFile: () => path.join(cfg.dataDir, 'pst-verify-log.json'),
read() { try { return JSON.parse(fs.readFileSync(this.file(), 'utf8')); } catch { return null; } },
results() {
let log = [];
try { log = JSON.parse(fs.readFileSync(this.resultFile(), 'utf8')); } catch { }
const latest = new Map();
for (const r of log) latest.set(r.file, r);
return latest;
},
status() {
const j = this.read();
const running = !!(j && j.pid && pstRepairState.alive(j.pid));
let lines = [];
try { lines = fs.readFileSync(this.logFile(), 'utf8').trim().split('\n').filter(Boolean).slice(-60).map(l => l.slice(0, 300)); } catch { }
return { running, lines, startedAt: j?.startedAt || null };
}
};
app.post('/api/mailbox/:upn/pst-verify', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
if (pstVerifyState.status().running) { const e = new Error('PST verify already running'); e.status = 409; throw e; }
const pstDir = path.join(__dirname, 'pst-import', m.upn.split('@')[0]);
const file = req.body && req.body.file;
const args = [m.upn, pstDir];
if (file) {
if (!fs.existsSync(path.join(pstDir, file))) throw new Error(`PST not found: ${file}`);
args.push(`--file=${file}`);
}
const child = spawnPstScript('pst-verify.js', pstVerifyState.file(), pstVerifyState.logFile(), args);
log('info', m.upn, `PST verify started ${file ? `for ${file} ` : ''}(pid ${child.pid})`);
return { ok: true, pid: child.pid };
}));
const guardIdle = upn => {
if (engine.running || pst.running) throw new Error('already running — stop the current job before deleting');
const m = store.getMailbox(upn);
if (!m) throw new Error('Mailbox not found');
if (m.status === 'syncing') throw new Error('already running — mailbox is syncing');
return m;
};
app.delete('/api/mailbox/:upn/backup', wrap(async req => {
const m = guardIdle(req.params.upn);
const scope = req.query.scope;
if (scope != null && scope !== 'primary' && scope !== 'archive') { const e = new Error('scope must be primary or archive'); e.status = 400; throw e; }
const dir = scope
? path.join(cfg.dataDir, 'store', safeName(m.upn), scope)
: path.join(cfg.dataDir, 'store', safeName(m.upn));
fs.rmSync(dir, { recursive: true, force: true });
store.deleteMailboxData(m.upn, scope);
log('info', m.upn, scope
? `stored ${scope} backup deleted (local .eml.gz files + database rows for that scope)`
: 'stored backup deleted (local .eml.gz store + database rows)');
return { ok: true };
}));
app.delete('/api/mailbox/:upn/folder', wrap(async req => {
const m = guardIdle(req.params.upn);
const { scope, folderId } = req.query;
if (scope !== 'primary' && scope !== 'archive') { const e = new Error('scope must be primary or archive'); e.status = 400; throw e; }
if (!folderId) { const e = new Error('folderId is required'); e.status = 400; throw e; }
const folder = store.getFolder(m.upn, scope, folderId);
if (!folder) { const e = new Error('Folder not found'); e.status = 404; throw e; }
fs.rmSync(engine.folderDir(m.upn, scope, folder.path), { recursive: true, force: true });
const { removedItems, removedFolders } = store.deleteFolder(m.upn, scope, folderId);
log('info', m.upn, `folder "${folder.path}" (${scope}) deleted from local store: ${removedItems} item(s), ${removedFolders} folder(s) — server copy untouched`);
return { ok: true, removedItems, removedFolders };
}));
app.delete('/api/mailbox/:upn/events', wrap(async req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
const removed = store.clearEvents(m.upn);
log('info', '', `events cleared for ${m.upn} (${removed} row(s))`);
return { ok: true, removed };
}));
app.delete('/api/pst/:upn', wrap(async req => {
const m = guardIdle(req.params.upn);
let removed = 0;
const dir = path.join(cfg.pstDir, safeName(m.upn));
if (fs.existsSync(dir)) { removed = fs.readdirSync(dir).length; fs.rmSync(dir, { recursive: true, force: true }); }
const jobsRoot = path.join(cfg.dataDir, 'pstjobs');
if (fs.existsSync(jobsRoot)) {
for (const e of fs.readdirSync(jobsRoot)) {
if (e.startsWith(m.upn + '_') || e.startsWith(safeName(m.upn) + '_')) {
fs.rmSync(path.join(jobsRoot, e), { recursive: true, force: true });
}
}
}
store.patchMailboxFields(m.upn, { pstStatus: '' });
log('info', m.upn, `PST files deleted (${removed} file(s))`);
return { ok: true, removed };
}));
app.get('/api/mailbox/:upn/items', wrap(async req => {
const { scope, folderId } = req.query;
if (!store.getMailbox(req.params.upn)) throw new Error('Mailbox not found');
if (!scope || !folderId) throw new Error('scope and folderId are required');
const limit = Math.min(Math.max(parseInt(req.query.limit || '500', 10) || 500, 1), 100000);
return { items: store.listItems(req.params.upn, scope, folderId, limit) };
}));
const resolveItem = req => {
const { scope, folderId, itemId } = req.query;
const folder = store.getFolder(req.params.upn, scope, folderId);
const item = store.getItem(req.params.upn, scope, folderId, itemId);
if (!item || !item.fileId) throw new Error('Item not found');
const folderMap = new Map(store.listFolders(req.params.upn).filter(f => f.scope === scope).map(f => [f.folderId, f]));
return { scope, folder, fileId: item.fileId, item, folderMap };
};
app.get('/api/mailbox/:upn/item', wrap(async req => {
const { scope, folder, fileId, item, folderMap } = resolveItem(req);
// FTS (Graph IE full-fidelity) items: render a best-effort preview extracted
// from the opaque stream (lib/fts.js — heuristic, preview-only; the .fts.gz
// stays the untouched restore copy).
if (item.format === 'fts') {
const raw = await readRaw(engine.storeRoot, req.params.upn, scope, folder || {}, fileId, folderMap);
if (!raw) throw new Error('Stored file not found on disk');
try {
return ftsPreview(raw);
} catch {
return { fts: true, subject: item.subject, receivedAt: item.receivedAt, size: item.size,
note: 'Full-fidelity restore copy (Exchange FTS format). Preview could not be extracted from this item — download it instead.' };
}
}
const parsed = await parseStoredItem(engine.storeRoot, req.params.upn, scope, folder || {}, fileId, folderMap);
if (!parsed) throw new Error('Stored file not found on disk');
return toPreview(parsed);
}));
app.get('/api/mailbox/:upn/download', async (req, res) => {
try {
const { scope, folder, fileId, item, folderMap } = resolveItem(req);
const raw = await readRaw(engine.storeRoot, req.params.upn, scope, folder || {}, fileId, folderMap);
if (!raw) return res.status(404).json({ error: 'Stored file not found on disk' });
const name = safeName(item.subject || 'email') || 'email';
const fts = item.format === 'fts';
res.set({
'Content-Type': fts ? 'application/octet-stream' : 'message/rfc822',
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}.${fts ? 'fts' : 'eml'}`
});
res.send(raw);
} catch (e) {
res.status(500).json({ error: String(e.message || e) });
}
});
app.get('/api/mailbox/:upn/export-folder', async (req, res) => {
try {
const { scope, folderId } = req.query;
const recursive = req.query.recursive === '1';
const upn = req.params.upn;
const all = store.listFolders(upn).filter(f => f.scope === scope);
const folderMap = new Map(all.map(f => [f.folderId, f]));
const root = folderMap.get(folderId);
if (!root) return res.status(404).json({ error: 'Folder not found' });
const wanted = new Set([folderId]);
if (recursive) {
let grew = true;
while (grew) {
grew = false;
for (const f of all) {
if (f.parentId && wanted.has(f.parentId) && !wanted.has(f.folderId)) { wanted.add(f.folderId); grew = true; }
}
}
}
// Pass 1: plan entry names and estimate total bytes from stored MIME sizes so
// the cap is enforced before any bytes hit the wire.
const maxBytes = cfg.maxExportBytes || 2 * 1024 * 1024 * 1024;
const planned = [];
let total = 0;
for (const fid of wanted) {
const f = folderMap.get(fid);
const prefix = chainPath(folderMap, f).split('/').map(safeName).join('/');
for (const it of store.listItems(upn, scope, fid, 1000000)) {
planned.push({ f, name: `${prefix}/${safeName(it.subject || 'email').slice(0, 60) || 'email'}-${safeName(it.itemId.slice(-8))}.eml`, item: it });
total += it.size || 0;
}
}
if (!planned.length) return res.status(404).json({ error: 'No backed-up emails in this folder' });
if (total > maxBytes) return res.status(413).json({ error: `folder export too large (~${Math.round(total / 1024 / 1024)} MB > ${Math.round(maxBytes / 1024 / 1024)} MB cap, cfg.maxExportBytes)` });
// Pass 2: stream a store-only zip straight to the response — no full-buffer build.
res.set({
'Content-Type': 'application/zip',
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(safeName(root.name || 'folder'))}.zip`
});
const archive = new archiver.ZipArchive({ store: true });
archive.on('error', () => { try { res.socket.destroy(); } catch { } });
archive.pipe(res);
let sent = 0;
for (const p of planned) {
const raw = await readRaw(engine.storeRoot, upn, scope, p.f, p.item.fileId, folderMap);
if (!raw) continue;
sent += raw.length;
if (sent > maxBytes) { archive.abort(); return res.socket.destroy(); }
archive.append(raw, { name: p.name });
}
await archive.finalize();
} catch (e) {
if (res.headersSent) { try { res.socket.destroy(); } catch { } return; }
res.status(500).json({ error: String(e.message || e) });
}
});
app.get('/api/mailbox/:upn/attachment', async (req, res) => {
try {
const { scope, folder, fileId, item, folderMap } = resolveItem(req);
const idx = parseInt(req.query.index || '0', 10);
if (item.format === 'fts') {
const raw = await readRaw(engine.storeRoot, req.params.upn, scope, folder || {}, fileId, folderMap);
const a = raw && ftsAttachment(raw, idx);
if (!a) return res.status(404).json({ error: 'Attachment not found' });
res.set({
'Content-Type': a.contentType,
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(a.filename)}`
});
return res.send(a.data);
}
const parsed = await parseStoredItem(engine.storeRoot, req.params.upn, scope, folder || {}, fileId, folderMap);
const a = parsed && parsed.attachments && parsed.attachments[idx];
if (!a) return res.status(404).json({ error: 'Attachment not found' });
res.set({
'Content-Type': a.contentType || 'application/octet-stream',
'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(a.filename || 'attachment')}`
});
res.send(a.content);
} catch (e) {
res.status(500).json({ error: String(e.message || e) });
}
});
app.post('/api/discover', wrap(() => engine.discover()));
// Per-mailbox backup master switch: paused mailboxes are refused by
// /api/backup and skipped by the auto-resume sweep; pausing also gracefully
// stops this mailbox's currently running backup scopes.
app.post('/api/mailbox/:upn/backup-pause', wrap(req => {
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
const paused = !!(req.body && req.body.paused);
store.patchMailboxFields(m.upn, { backupPaused: paused ? 1 : 0 });
if (paused) { engine.stopScope('primary', m.upn); engine.stopScope('archive', m.upn); }
log('info', m.upn, paused ? 'ALL backups paused for this mailbox (master switch) — auto-resume will skip it' : 'backups resumed for this mailbox');
return { ok: true, paused };
}));
app.post('/api/backup', wrap(req => {
// Backups and PST exports are designed to run concurrently: the engine
// publishes item files atomically (tmp + rename) and the exporter only
// reads local files. Only copy/dedupe (which move files) are excluded.
if (copyEngine.running || dedupeEngine.running) { const e = new Error('a copy/dedupe job is running — stop it before starting a backup'); e.status = 409; throw e; }
// Disk-space preflight: refuse to start when the store drive is below the
// configured reserve (default 10 GB) — never run the disk into the ground.
const dErr = diskCheck();
if (dErr) { dErr.status = 507; throw dErr; }
const scope = req.body && req.body.scope;
if (scope != null && scope !== 'archive' && scope !== 'primary') { const e = new Error('invalid scope: only "primary" and "archive" are supported'); e.status = 400; throw e; }
const provider = req.body && req.body.provider;
if (provider != null && provider !== 'ews' && provider !== 'graphie') { const e = new Error('invalid provider: only "ews" and "graphie" are supported'); e.status = 400; throw e; }
const one = req.body && req.body.upn, many = req.body && req.body.upns;
if ((one && !isValidUpn(one)) || (Array.isArray(many) && many.some(u => !isValidUpn(u)))) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
// Per-mailbox master switch: paused mailboxes can't be backed up.
const isPaused = u => { const m = store.getMailbox(u); return !!(m && m.backupPaused); };
if (one && isPaused(one)) { const e = new Error('backups are paused for this mailbox (master switch is on)'); e.status = 409; throw e; }
const upns = Array.isArray(many) ? many.filter(u => !isPaused(u)) : many;
if (Array.isArray(many) && !upns.length) { const e = new Error('all selected mailboxes have backups paused (master switch is on)'); e.status = 409; throw e; }
autoResumeSuppressed = false; // manual start re-arms the auto-resume sweep
// Engine busy → queue as a background task instead of failing; it starts
// automatically when the current job finishes.
if (engine.running || fixTasks.some(fixActive)) {
const t = { id: ++fixSeq, kind: 'backup', upn: one || null, upns: upns || null, scope: scope || null, provider: provider || null, status: 'queued', queuedAt: new Date().toISOString() };
fixTasks.push(t);
log('info', one || '', `backup queued behind the running job${scope ? ` (${scope} only)` : ''}`);
pumpFixTasks();
return { ok: true, queued: true, task: t };
}
return engine.runBackup(one, upns, { scope, provider });
}));
let sizesRunning = false;
let sizesStop = false;
let sizesAborter = null;
app.post('/api/sizes', wrap(async req => {
if (sizesRunning) { const e = new Error('a sizes scan is already running — stop the current job first'); e.status = 409; throw e; }
const source = ['ews', 'exo', 'both'].includes(req.body && req.body.source) ? req.body.source : 'both';
const upn = req.body && req.body.upn;
const upns = req.body && Array.isArray(req.body.upns) ? req.body.upns.filter(u => typeof u === 'string') : null;
if (upn && !isValidUpn(upn)) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
if (upns && upns.some(u => !isValidUpn(u))) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
// Bulk fetch covers licensed user mailboxes only (shared/guest skipped for now);
// a single-mailbox fetch via {upn} or a selection via {upns} works for any type.
const targets = upns ? upns : upn ? [upn] : store.listMailboxes().filter(m => m.type === 'user').map(m => m.upn);
if ((upn || upns) && targets.some(u => !store.getMailbox(u))) throw new Error('Mailbox not found');
const jobId = store.createJob('sizes', targets.length);
sizesRunning = true; sizesStop = false;
const aborter = new AbortController();
sizesAborter = aborter;
(async () => {
let exoFailed = false;
if (source !== 'ews') {
// Authoritative path: one EXO PowerShell process walks all targets
// (per-chunk processes would re-prompt the device sign-in each chunk).
try {
log('info', '', 'fetching sizes via Exchange Online PowerShell (authoritative)…');
const res = await exo.mailboxStats(targets, si => {
exoSignIn = si;
bus.emit('progress', { job: jobId });
if (si) log('info', '', `EXO sign-in requested — code ${si.code} at microsoft.com/devicelogin`);
});
let done = 0;
for (const u of targets) {
const st = res.stats[u];
const err = res.errors[u];
if (st) {
store.patchMailboxFields(u, {
serverPrimaryBytes: st.primaryBytes,
serverArchiveBytes: st.archiveBytes,
serverPrimaryItems: st.primaryItems,
serverArchiveItems: st.archiveItems,
serverSizeAt: new Date().toISOString(),
hasArchive: st.archiveStatus === 'Active' ? 1 : 0,
autoExpandingArchive: st.autoExpanding ? 1 : 0,
sizeSource: 'exo'
});
log('info', u, `server size (EXO): primary ${st.primaryBytes} bytes` + (st.archiveBytes == null ? '' : `, archive ${st.archiveBytes} bytes`) + (st.autoExpanding ? ', auto-expanding archive' : ''));
// Partition inventory from real reported numbers only: EXO archiveBytes is
// the TOTAL archive (all partitions); the EWS-accessible main partition is
// measured in the EWS phase below. An AEA mailbox with a gap gets a derived
// 'aux-combined' row — never split into fabricated per-partition sizes.
if (st.archiveStatus === 'Active') {
const mbx = store.getMailbox(u);
const mainBytes = mbx && mbx.ewsArchiveBytes != null ? mbx.ewsArchiveBytes : null;
store.upsertPartition({ upn: u, partitionId: 'main', partitionType: 'main', discoveredVia: 'ews', logicalBytes: mainBytes });
if (st.autoExpanding && st.archiveBytes != null && mainBytes != null && st.archiveBytes > mainBytes) {
store.upsertPartition({ upn: u, partitionId: 'aux-combined', partitionType: 'aux', discoveredVia: 'exo-derived', logicalBytes: st.archiveBytes - mainBytes, status: 'unreachable' });
}
}
refreshCoverage(store, u, { ieEnabled: !!graphie });
} else {
log('error', u, 'EXO size fetch failed: ' + (err || 'unknown'));
}
store.updateJob(jobId, { done: ++done, detail: u });
bus.emit('progress', { job: jobId });
}
if (source === 'exo') {
const nErr = Object.keys(res.errors).length;
store.updateJob(jobId, { status: sizesStop ? 'stopped' : nErr ? 'error' : 'done', finishedAt: new Date().toISOString() });
bus.emit('progress', { job: jobId });
}
} catch (e) {
exoFailed = true;
log('error', '', 'EXO sizes job failed: ' + String(e.message || e));
if (source === 'exo') store.updateJob(jobId, { status: 'error', finishedAt: new Date().toISOString() });
else log('warn', '', 'falling back to EWS-only sizes (folder walk) for all mailboxes');
}
if (source === 'exo') return;
}
// EWS phase. After a successful EXO pass ('both'), only the archive-accessible
// portion is missing — primary is fully visible to EWS, so walking it again
// would be wasted time. If EXO failed, fall back to a full EWS walk.
let phaseTargets = targets, archiveOnly = false;
if (source === 'both' && !exoFailed) {
phaseTargets = targets.filter(u => { const m = store.getMailbox(u); return m && m.hasArchive; });
archiveOnly = true;
log('info', '', `EXO totals stored — measuring EWS-accessible archive size for ${phaseTargets.length} archive mailbox(es)…`);
store.updateJob(jobId, { total: targets.length + phaseTargets.length });
if (!phaseTargets.length) {
store.updateJob(jobId, { status: 'done', finishedAt: new Date().toISOString() });
bus.emit('progress', { job: jobId });
return;
}
}
let done = source === 'both' && !exoFailed ? targets.length : 0, failed = false, next = 0;
const conc = engine.running ? 2 : Math.max(1, Math.min(4, parseInt(cfg.sizeScanConcurrency || '3', 10) || 3));
const worker = async () => {
while (next < phaseTargets.length && !sizesStop) {
const u = phaseTargets[next++];
store.updateJob(jobId, { done, detail: u });
bus.emit('progress', { job: jobId });
log('info', u, archiveOnly ? 'measuring accessible archive size…' : 'fetching server sizes…');
let lastPing = 0;
const onProgress = (folders, bytes) => {
const now = Date.now();
if (now - lastPing < 1000) return;
lastPing = now;
store.updateJob(jobId, { done, detail: `${u} — ${folders} folders scanned` });
bus.emit('progress', { job: jobId });
};
try {
if (archiveOnly) {
const ab = await ews.folderSize(u, 'archivemsgfolderroot', onProgress, undefined, aborter.signal);
store.patchMailboxFields(u, { ewsArchiveBytes: ab });
store.upsertPartition({ upn: u, partitionId: 'main', partitionType: 'main', discoveredVia: 'ews', logicalBytes: ab });
const mbx = store.getMailbox(u);
if (mbx && mbx.autoExpandingArchive && mbx.serverArchiveBytes != null && mbx.serverArchiveBytes > ab) {
store.upsertPartition({ upn: u, partitionId: 'aux-combined', partitionType: 'aux', discoveredVia: 'exo-derived', logicalBytes: mbx.serverArchiveBytes - ab, status: 'unreachable' });
}
refreshCoverage(store, u, { ieEnabled: !!graphie });
log('info', u, `accessible archive size: ${ab} bytes`);
} else {
const s = await ews.mailboxSizes(u, onProgress, undefined, aborter.signal);
const fields = {
ewsPrimaryBytes: s.primaryBytes,
ewsArchiveBytes: s.archiveBytes,
serverSizeAt: new Date().toISOString(),
hasArchive: s.archiveBytes != null ? 1 : 0
};
// EXO stats are authoritative (they include auto-expanding archive
// auxiliary storage) — don't let an EWS scan clobber them.
const cur = store.getMailbox(u);
if (!cur || cur.sizeSource !== 'exo') {
fields.serverPrimaryBytes = s.primaryBytes;
fields.serverArchiveBytes = s.archiveBytes;
fields.sizeSource = 'ews';
}
store.patchMailboxFields(u, fields);
log('info', u, `server size: primary ${s.primaryBytes} bytes` + (s.archiveBytes == null ? '' : `, archive ${s.archiveBytes} bytes`));
}
} catch (e) {
if (e.aborted || e.name === 'AbortError') throw e;
failed = true;
log('error', u, 'server size fetch failed: ' + String(e.fault || e.message || e));
}
store.updateJob(jobId, { done: ++done, detail: u });
bus.emit('progress', { job: jobId });
}
};
try {
await Promise.all(Array.from({ length: conc }, worker));
} catch (e) {
if (!(e && (e.aborted || e.name === 'AbortError'))) throw e;
}
if (sizesStop) {
log('info', '', 'sizes job stopped by user');
store.updateJob(jobId, { status: 'stopped', finishedAt: new Date().toISOString() });
bus.emit('progress', { job: jobId });
return;
}
store.updateJob(jobId, { status: failed ? 'error' : 'done', finishedAt: new Date().toISOString() });
bus.emit('progress', { job: jobId });
})().catch(e => {
log('error', '', 'sizes job failed: ' + String(e.message || e));
store.updateJob(jobId, { status: 'error', finishedAt: new Date().toISOString() });
}).finally(() => {
sizesRunning = false;
sizesAborter = null;
exoSignIn = null;
bus.emit('progress', { job: jobId });
});
return { ok: true, jobId, total: targets.length };
}));
// ---------- Count scan: refresh remote item counts without downloading items ----------
// Walks each mailbox's folder tree (Graph primary, EWS archive) and upserts the
// server-side item counts, so "X / Y emails" reflects reality before any backup.
// Cursors (deltaToken/syncState) are passed undefined → COALESCE keeps them.
let scanRunning = false;
let scanStop = false;
let scanAborter = null;
const scanLive = {}; // upn -> { scope, folders } while a count scan walks it
app.post('/api/scan', wrap(async req => {
if (scanRunning) { const e = new Error('a count scan is already running — stop the current job first'); e.status = 409; throw e; }
const upn = req.body && req.body.upn;
const upns = req.body && Array.isArray(req.body.upns) ? req.body.upns.filter(u => typeof u === 'string') : null;
const scope = ['primary', 'archive'].includes(req.body && req.body.scope) ? req.body.scope : null;
if (upn && !isValidUpn(upn)) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
if (upns && upns.some(u => !isValidUpn(u))) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
const targets = upns ? upns : upn ? [upn] : store.listMailboxes().filter(m => m.type === 'user').map(m => m.upn);
if ((upn || upns) && targets.some(u => !store.getMailbox(u))) throw new Error('Mailbox not found');
const jobId = store.createJob('scan', targets.length);
scanRunning = true; scanStop = false;
const aborter = new AbortController();
scanAborter = aborter;
const upsert = (u, sc) => f => store.upsertFolder({ upn: u, scope: sc, ...f, deltaToken: undefined, syncState: undefined });
(async () => {
let done = 0, failed = false, next = 0;
const conc = engine.running ? 2 : Math.max(1, Math.min(4, parseInt(cfg.scanConcurrency || '3', 10) || 3));
const worker = async () => {
while (next < targets.length && !scanStop) {
const u = targets[next++];
store.updateJob(jobId, { done, detail: u });
bus.emit('progress', { job: jobId });
log('info', u, `scanning folder counts${scope ? ` (${scope})` : ''}…`);
let lastPing = 0, lastLogged = 0;
const onProgress = (folders) => {
if (scanLive[u]) scanLive[u].folders = folders;
const now = Date.now();
if (now - lastPing >= 1000) {
lastPing = now;
store.updateJob(jobId, { done, detail: `${u} — ${folders} folders scanned` });
bus.emit('progress', { job: jobId });
}
if (folders - lastLogged >= 250) {
lastLogged = folders;
log('info', u, `count scan: ${folders} folders…`);
}
};
try {
if (!scope || scope === 'primary') {
scanLive[u] = { scope: 'primary', folders: 0 };
await graph.folderTree(u, onProgress, upsert(u, 'primary'));
}
const m = store.getMailbox(u);
// Archive walk when an archive is known/assumed; sizes never fetched
// (EXO grant pending) means unknown, so try anyway — EWS errors
// simply mean there is no accessible archive.
if ((!scope || scope === 'archive') && m && (m.hasArchive || (m.serverArchiveBytes == null && m.ewsArchiveBytes == null))) {
try {
scanLive[u] = { scope: 'archive', folders: 0 };
await ews.folderTree(u, onProgress, aborter.signal, upsert(u, 'archive'));
// The EWS walk upserts EWS-namespace rows — fold them into the IE
// tree immediately or the UI shows a duplicated archive hierarchy.
const mg = store.mergeArchiveNamespaces(u);
if (mg.movedItems || mg.dropped) log('info', u, `EWS archive rows merged into the archive tree (${mg.movedItems} items, ${mg.dropped} folders)`);
} catch (e2) {
if (e2.aborted || e2.name === 'AbortError') throw e2;
log('warn', u, 'archive count scan skipped: ' + String(e2.fault || e2.message || e2));
}
}
log('info', u, 'count scan complete');
} catch (e) {
if (e.aborted || e.name === 'AbortError') throw e;
failed = true;
log('error', u, 'count scan failed: ' + String(e.fault || e.message || e));
}
delete scanLive[u];
store.updateJob(jobId, { done: ++done, detail: u });
bus.emit('progress', { job: jobId });
}
};
try {
await Promise.all(Array.from({ length: conc }, worker));
} catch (e) {
if (!(e && (e.aborted || e.name === 'AbortError'))) throw e;
}
if (scanStop) {
log('info', '', 'count scan stopped by user');
store.updateJob(jobId, { status: 'stopped', finishedAt: new Date().toISOString() });
bus.emit('progress', { job: jobId });
return;
}
store.updateJob(jobId, { status: failed ? 'error' : 'done', finishedAt: new Date().toISOString() });
bus.emit('progress', { job: jobId });
})().catch(e => {
log('error', '', 'count scan failed: ' + String(e.message || e));
store.updateJob(jobId, { status: 'error', finishedAt: new Date().toISOString() });
}).finally(() => {
scanRunning = false;
scanAborter = null;
bus.emit('progress', { job: jobId });
});
return { ok: true, jobId, total: targets.length };
}));
// ---------- EXO compliance-search export (full mailbox incl. archive) ----------
// Independent of backup/PST jobs (network-bound, read-only on local files).
app.post('/api/exo-export', wrap(req => {
if (exoExport.running) { const e = new Error('an EXO export is already running'); e.status = 409; throw e; }
const one = req.body && req.body.upn, many = req.body && req.body.upns;
if ((one && !isValidUpn(one)) || (Array.isArray(many) && many.some(u => !isValidUpn(u)))) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
if ((one || many) && (one ? [one] : many).some(u => !store.getMailbox(u))) { const e = new Error('Mailbox not found'); e.status = 404; throw e; }
const jobId = store.createJob('exoexport', 0);
exoExport.runExport({ upn: one || undefined, upns: Array.isArray(many) && many.length ? many : undefined })
.then(() => store.updateJob(jobId, { status: 'done', finishedAt: new Date().toISOString() }))
.catch(e => {
log('error', '', 'EXO export failed: ' + String(e.message || e));
store.updateJob(jobId, { status: 'error', detail: String(e.message || e).slice(0, 300), finishedAt: new Date().toISOString() });
});
log('info', one || '', `EXO export started${many && many.length > 1 ? ` for ${many.length} mailboxes` : ''} (full mailbox incl. online archive → ${path.join(cfg.dataDir, 'exo-export')})`);
return { ok: true, jobId };
}));
// Manual PST import: ingest .pst files the user dropped into
// data/exo-export/<upn>/ (from a manual Purview portal export) into the
// browsable backup store. Free route for tenants without Purview billing.
app.post('/api/exo-ingest', wrap(async req => {
if (exoExport.running) { const e = new Error('an EXO export/import job is already running'); e.status = 409; throw e; }
const upn = req.body && req.body.upn;
if (!isValidUpn(upn)) { const e = new Error('invalid mailbox id'); e.status = 400; throw e; }
if (!store.getMailbox(upn)) { const e = new Error('Mailbox not found'); e.status = 404; throw e; }
return exoExport.importLocalPsts(upn);
}));
app.delete('/api/mailbox/:upn/exo-export', wrap(req => {
if (exoExport.running) { const e = new Error('an EXO export is running — stop it first'); e.status = 409; throw e; }
const m = store.getMailbox(req.params.upn);
if (!m) throw new Error('Mailbox not found');
const dir = path.join(cfg.dataDir, 'exo-export', safeName(m.upn));
let removed = 0;
if (fs.existsSync(dir)) { removed = fs.readdirSync(dir).length; fs.rmSync(dir, { recursive: true, force: true }); }
store.deleteExoExport(m.upn);
log('info', m.upn, `EXO export PSTs deleted (${removed} file/dir entr${removed === 1 ? 'y' : 'ies'})`);
return { ok: true, removed };
}));
app.post('/api/verify', wrap(req => {
if (pst.running) { const e = new Error('a PST export is running — stop it before starting a verify'); e.status = 409; throw e; }
const vupn = req.body && req.body.upn;