Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
989 lines (896 loc) · 33.3 KB
/
Copy pathserver.js
File metadata and controls
989 lines (896 loc) · 33.3 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
const express = require('express');
const cron = require('node-cron');
const path = require('path');
const fs = require('fs').promises;
const fsSync = require('fs');
const crypto = require('crypto');
const config = require('./config/config');
const paperlessService = require('./services/paperlessService');
const documentModel = require('./models/document');
const setupService = require('./services/setupService');
const { runStartupMigrations } = require('./services/startupMigrations');
const routes = require('./routes');
const tidyUpRoutes = require('./routes/tidyUp');
const oidcRoutes = require('./routes/oidc');
const oidcService = require('./services/oidcService');
const { isAuthenticated } = require('./routes/auth');
const {
readSessionToken,
hasValidApiKey,
callerRateLimitKey,
} = require('./middleware/caller');
const {
isHttpsRequest,
shouldUseSecureCookies,
} = require('./services/sessionCookie');
const mistralOcrService = require('./services/mistralOcrService');
const ocrAutoProcessService = require('./services/ocrAutoProcessService');
const reconciliationService = require('./services/reconciliationService');
const scanHealthService = require('./services/scanHealthService');
const dashboardStatsService = require('./services/dashboardStatsService');
const scanControlService = require('./services/scanControl');
const scanService = require('./services/scanService');
const { RUN_STATUS } = scanHealthService;
const cors = require('cors');
const cookieParser = require('cookie-parser');
const { doubleCsrf } = require('csrf-csrf');
const rateLimit = require('express-rate-limit');
const { ipKeyGenerator } = require('express-rate-limit');
const Logger = require('./services/loggerService');
const dataDir = path.join(process.cwd(), 'data');
const openApiDir = path.join(dataDir, 'OPENAPI');
const openApiPath = path.join(openApiDir, 'openapi.json');
const dataLogsDir = path.join(process.cwd(), 'data', 'logs');
const htmlLogger = new Logger({
logFile: 'logs.html',
logDir: dataLogsDir,
format: 'html',
timestamp: true,
maxFileSize: 1024 * 1024 * 10,
});
const txtLogger = new Logger({
logFile: 'logs.txt',
logDir: dataLogsDir,
format: 'txt',
timestamp: true,
maxFileSize: 1024 * 1024 * 10,
});
const app = express();
// Express 5 changed the default query parser to "simple", which does not parse
// nested bracket parameters (e.g. order[0][column], columns[1][data]) sent by
// DataTables server-side processing. Restore the Express 4 "extended" (qs)
// parser so req.query.order/columns are objects again and table sorting works.
app.set('query parser', 'extended');
// The one scan state, owned by services/scanControl.js: the scan run in
// services/scanService.js writes to it, the cron jobs below read it.
const scanControl = scanControlService.getState();
// The scan itself lives in services/scanService.js; the routes reach its two
// levers through services/scanControl.js.
scanControlService.register({
triggerScanNow: (source) => scanService.triggerScanNow(source),
requestScanStop: () => scanService.requestScanStop(),
});
function persistJwtSecret(secret) {
const runtimeDataDir = path.join(process.cwd(), 'data');
const envFilePath = path.join(runtimeDataDir, '.env');
const runtimeOverridesPath = path.join(
runtimeDataDir,
'runtime-overrides.json'
);
try {
fsSync.mkdirSync(runtimeDataDir, { recursive: true });
let envContent = '';
if (fsSync.existsSync(envFilePath)) {
envContent = fsSync.readFileSync(envFilePath, 'utf8');
}
const hasJwtSecretLine = /^\s*JWT_SECRET\s*=.*$/m.test(envContent);
let updatedEnvContent = envContent;
if (hasJwtSecretLine) {
updatedEnvContent = envContent.replace(
/^\s*JWT_SECRET\s*=.*$/m,
`JWT_SECRET=${secret}`
);
} else {
const trimmed = envContent.trimEnd();
updatedEnvContent = trimmed
? `${trimmed}\nJWT_SECRET=${secret}\n`
: `JWT_SECRET=${secret}\n`;
}
fsSync.writeFileSync(envFilePath, updatedEnvContent, 'utf8');
} catch (error) {
console.warn(
'[WARN] Could not persist generated JWT_SECRET to data/.env:',
error.message
);
}
try {
if (!fsSync.existsSync(runtimeOverridesPath)) {
return;
}
const raw = fsSync.readFileSync(runtimeOverridesPath, 'utf8');
const parsed = raw.trim() ? JSON.parse(raw) : {};
if (!parsed.JWT_SECRET || String(parsed.JWT_SECRET).trim() === '') {
parsed.JWT_SECRET = secret;
fsSync.writeFileSync(
runtimeOverridesPath,
JSON.stringify(parsed, null, 2),
'utf8'
);
}
} catch (error) {
console.warn(
'[WARN] Could not update JWT_SECRET in runtime-overrides.json:',
error.message
);
}
}
function ensureJwtSecret() {
const existingSecret = config.getJwtSecret();
if (existingSecret) {
return existingSecret;
}
const generatedSecret = crypto.randomBytes(64).toString('hex');
process.env.JWT_SECRET = generatedSecret;
persistJwtSecret(generatedSecret);
console.warn(
'[WARN] JWT_SECRET was missing. Generated and persisted a new secret. Existing sessions may require re-login.'
);
return generatedSecret;
}
const JWT_SECRET = ensureJwtSecret();
if (!JWT_SECRET) {
console.error(
'JWT_SECRET environment variable is not set. Refusing to start without a secure JWT secret.'
);
process.exit(1);
}
const trustProxy = config.getTrustProxy();
if (trustProxy !== false) {
app.set('trust proxy', trustProxy);
}
// The CSRF cookie is configured once, without a request: Secure follows
// COOKIE_SECURE_MODE, and in auto mode NODE_ENV=production.
const csrfCookieSecure = shouldUseSecureCookies();
const corsOptions = {
origin: true,
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: [
'Content-Type',
'x-api-key',
'Access-Control-Allow-Private-Network',
],
credentials: false,
};
const apiGlobalLimiter = rateLimit({
windowMs: config.globalRateLimitWindowMs,
max: config.globalRateLimitMax,
message: {
success: false,
error: 'Too many requests. Please try again later.',
},
standardHeaders: true,
legacyHeaders: false,
// The API key or the signed-in user; anyone else by IP.
keyGenerator: (req) => callerRateLimitKey(req) || ipKeyGenerator(req.ip),
});
app.use(cors(corsOptions));
// Chrome Private Network Access: respond to preflight with the required header
app.use((req, res, next) => {
res.header('Access-Control-Allow-Private-Network', 'true');
next();
});
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use((req, res, next) => {
const themeCookie = req.cookies?.theme;
const resolvedTheme = themeCookie === 'dark' ? 'dark' : 'light';
res.locals.theme = resolvedTheme;
res.locals.appVersion = config.PAPERLESS_AI_VERSION || 'unknown';
res.locals.appCommitSha = process.env.PAPERLESS_AI_COMMIT_SHA || 'unknown';
res.locals.appPaperlessNgxVersion =
process.env.PAPERLESS_NGX_VERSION || 'unknown';
res.locals.appAiProvider =
config.aiProvider || process.env.AI_PROVIDER || 'openai';
res.locals.appOcrEnabled = config.mistralOcr?.enabled === 'yes';
res.locals.appOcrProvider = config.mistralOcr?.provider || 'mistral';
res.locals.appNodeEnv = process.env.NODE_ENV || 'production';
res.locals.appNodeVersion = process.version;
res.locals.appPlatform = `${process.platform} (${process.arch})`;
res.locals.appServerTimeUtc = new Date().toISOString();
res.locals.appServerTimezone =
Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
res.locals.appDateFormat = config.dateFormat || 'DD.MM.YYYY';
res.locals.appPaperlessApiUrl = config.paperless?.apiUrl || 'unknown';
res.locals.appOllamaApiUrl = config.ollama?.apiUrl || 'unknown';
res.locals.appOllamaModel = config.ollama?.model || 'unknown';
res.locals.appCustomBaseUrl = config.custom?.apiUrl || 'unknown';
res.locals.appCustomModel = config.custom?.model || 'unknown';
res.locals.appAzureEndpoint = config.azure?.endpoint || 'unknown';
res.locals.appAzureDeploymentName = config.azure?.deploymentName || 'unknown';
res.locals.appAzureApiVersion = config.azure?.apiVersion || 'unknown';
res.locals.appAnthropicModel = config.anthropic?.model || 'unknown';
// Empty means api.anthropic.com, which is worth saying in a bug report.
res.locals.appAnthropicApiUrl = config.anthropic?.apiUrl || 'default';
res.locals.appMistralOcrModel = config.mistralOcr?.model || 'unknown';
res.locals.appScanInterval = config.scanInterval || 'unknown';
res.locals.appTokenLimit = String(config.tokenLimit || 'unknown');
res.locals.appResponseTokens = String(config.responseTokens || 'unknown');
res.locals.appTrustProxy = String(config.trustProxy);
res.locals.appUseExistingData = config.useExistingData || 'no';
res.locals.appRestrictTags = config.restrictToExistingTags || 'no';
res.locals.appRestrictCorrespondents =
config.restrictToExistingCorrespondents || 'no';
res.locals.appRestrictDocumentTypes =
config.restrictToExistingDocumentTypes || 'no';
res.locals.appPaperlessTokenSet = Boolean(config.paperless?.apiToken);
res.locals.appOpenAiKeySet = Boolean(config.openai?.apiKey);
res.locals.appCustomKeySet = Boolean(config.custom?.apiKey);
res.locals.appAzureKeySet = Boolean(config.azure?.apiKey);
res.locals.appAnthropicKeySet = Boolean(config.anthropic?.apiKey);
res.locals.appMistralKeySet = Boolean(config.mistralOcr?.apiKey);
res.locals.appApiKeySet = Boolean(config.getApiKey && config.getApiKey());
res.locals.loginCookieSecurityWarning = null;
if (req.path === '/login' && csrfCookieSecure && !isHttpsRequest(req)) {
res.locals.loginCookieSecurityWarning =
'You are accessing the login page over HTTP while the system is configured to use HTTPS by default. To resolve this, either switch to HTTPS or set COOKIE_SECURE_MODE=never in your .env or docker-compose.yml file and restart the container.';
}
next();
});
// CSRF Protection configuration
const { invalidCsrfTokenError, generateCsrfToken, doubleCsrfProtection } =
doubleCsrf({
getSecret: () => JWT_SECRET,
getSessionIdentifier: (req) => {
// The raw token, verified or not: the CSRF token is bound to it.
const token = readSessionToken(req);
if (token) {
return `jwt:${token}`;
}
if (hasValidApiKey(req)) {
return `api-key:${req.headers['x-api-key']}`;
}
return `ip:${req.ip || 'unknown'}`;
},
cookieName: 'psai.x-csrf-token',
cookieOptions: {
sameSite: 'lax',
path: '/',
secure: csrfCookieSecure,
},
size: 64,
ignoredMethods: ['GET', 'HEAD', 'OPTIONS'],
getCsrfTokenFromRequest: (req) =>
req.headers['x-csrf-token'] || req.body._csrf,
});
// Middleware to skip CSRF for API Key authenticated requests and provide token to EJS
app.use((req, res, next) => {
// If API Key is valid, skip CSRF
if (hasValidApiKey(req)) {
return next();
}
// Handle CSRF protection for other requests
doubleCsrfProtection(req, res, (err) => {
if (err) {
if (err === invalidCsrfTokenError) {
if (req.method === 'POST' && req.path === '/login') {
const baseError =
'Invalid CSRF token. The login page may have expired or your browser did not send the CSRF cookie.';
const guidance = res.locals.loginCookieSecurityWarning
? ' This is commonly caused by HTTP access with secure cookies enabled. Set COOKIE_SECURE_MODE=never for local HTTP and restart, or switch to HTTPS. See: https://zettelrob.be/getting-started/configuration/#cookie-and-proxy-flags-all-supported-values'
: ' Refresh the login page and try again.';
return res.status(403).render('login', {
error: `${baseError}${guidance}`,
mfaRequired: false,
username: String(req.body?.username || ''),
});
}
return res.status(403).json({ error: 'Invalid CSRF token' });
}
return next(err);
}
// Make CSRF token available to EJS templates
res.locals.csrfToken = generateCsrfToken(req, res);
next();
});
});
/**
* @swagger
* /api/csrf-token:
* get:
* summary: Issue a CSRF token for the current browser
* description: |
* Returns a token paired with the CSRF cookie this response sets, for a
* page whose own token has gone stale.
*
* A token is minted per page render and the cookie it pairs with belongs
* to the browser, not the tab — so a second tab, a navigation, or the
* restart after saving settings leaves every older tab holding a token
* the server no longer accepts. /js/csrf.js calls this after a rejected
* request and repeats the request once.
*
* Deliberately unauthenticated: the login form needs the same recovery,
* and a token is only usable together with the cookie sent alongside it.
* tags:
* - System
* responses:
* 200:
* description: A token matching the cookie set on this response
* content:
* application/json:
* schema:
* type: object
* properties:
* csrfToken:
* type: string
* example: "e3b0c44298fc1c14…"
*/
app.get('/api/csrf-token', (req, res) => {
res.json({ csrfToken: generateCsrfToken(req, res) });
});
app.use(['/api', '/manual'], apiGlobalLimiter);
const isApiDocsEnabled = config.exposeApiDocs === 'yes';
let swaggerSpec = null;
if (isApiDocsEnabled) {
const swaggerUi = require('swagger-ui-express');
swaggerSpec = require('./swagger');
// Swagger documentation route (protected)
app.use(
'/api-docs',
isAuthenticated,
swaggerUi.serve,
swaggerUi.setup(swaggerSpec, {
swaggerOptions: {
url: '/api-docs/openapi.json',
},
})
);
/**
* @swagger
* /api-docs/openapi.json:
* get:
* summary: Retrieve the OpenAPI specification
* description: |
* Returns the complete OpenAPI specification for the Zettelrobbe API.
* This endpoint attempts to serve a static OpenAPI JSON file first, falling back
* to dynamically generating the specification if the file cannot be read.
*
* The OpenAPI specification document contains all API endpoints, parameters,
* request bodies, responses, and schemas for the entire application.
* tags: [API, System]
* responses:
* 200:
* description: OpenAPI specification returned successfully
* content:
* application/json:
* schema:
* type: object
* description: The complete OpenAPI specification
* 302:
* description: Redirect to login when authentication is missing or invalid
* headers:
* Location:
* schema:
* type: string
* example: /login
* 404:
* description: OpenAPI specification file not found
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
* 500:
* description: Server error occurred while retrieving the OpenAPI specification
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get('/api-docs/openapi.json', isAuthenticated, (req, res) => {
res.setHeader('Content-Type', 'application/json');
// Try to serve the static file first
fs.readFile(openApiPath)
.then((data) => {
res.send(JSON.parse(data));
})
.catch((err) => {
console.warn(
'Error reading OpenAPI file, generating dynamically:',
err.message
);
// Fallback to generating the spec if file can't be read
res.send(swaggerSpec);
});
});
/**
* @swagger
* /api-docs.json:
* get:
* summary: Redirect to OpenAPI specification endpoint
* description: Backward-compatible redirect to `/api-docs/openapi.json`.
* tags:
* - API
* - System
* security:
* - BearerAuth: []
* - ApiKeyAuth: []
* responses:
* 302:
* description: Redirects to `/api-docs/openapi.json`
*/
// Add a redirect for the old endpoint for backward compatibility
app.get('/api-docs.json', isAuthenticated, (req, res) => {
res.redirect('/api-docs/openapi.json');
});
}
// View engine setup
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
// //Layout middleware
// app.use((req, res, next) => {
// const originalRender = res.render;
// res.render = function (view, locals = {}) {
// originalRender.call(this, view, locals, (err, html) => {
// if (err) return next(err);
// originalRender.call(this, 'layout', { content: html, ...locals });
// });
// };
// next();
// });
// Initialize data directory
async function initializeDataDirectory() {
try {
await fs.access(dataDir);
} catch {
console.log('Creating data directory...');
await fs.mkdir(dataDir, { recursive: true });
}
}
// Save OpenAPI specification to file
async function saveOpenApiSpec() {
if (!isApiDocsEnabled || !swaggerSpec) {
return true;
}
try {
// Ensure the directory exists
try {
await fs.access(openApiDir);
} catch {
console.log('Creating OPENAPI directory...');
await fs.mkdir(openApiDir, { recursive: true });
}
// Write the specification to file
await fs.writeFile(openApiPath, JSON.stringify(swaggerSpec, null, 2));
console.log(`OpenAPI specification saved to ${openApiPath}`);
return true;
} catch (error) {
console.error(`Failed to save OpenAPI specification: ${error.message}`);
console.debug(error);
return false;
}
}
// Routes
// Single sign-on comes first: its callback must be reachable without a
// session, before the authentication guard of routes/index.js runs.
app.use('/', oidcRoutes);
app.use('/', tidyUpRoutes);
app.use('/', routes);
// Development-only reference page for the zr UI framework. It ships no product
// behaviour, only one sample of every component, so it is not registered in a
// production build and is deliberately absent from the navigation.
if (process.env.NODE_ENV !== 'production') {
/**
* @swagger
* /styleguide:
* get:
* summary: UI framework styleguide page (development builds only)
* description: |
* Renders one sample of every zr framework component. The route is only
* registered when `NODE_ENV` is not `production`; a production build
* answers this path with the generic 404 handler.
* tags:
* - Navigation
* security:
* - BearerAuth: []
* - ApiKeyAuth: []
* responses:
* 200:
* description: Styleguide page rendered successfully
* content:
* text/html:
* schema:
* type: string
* 302:
* description: Redirect to login when authentication is missing or invalid
* headers:
* Location:
* schema:
* type: string
* example: /login
* 404:
* description: Route not registered because the app runs in production
* 500:
* description: Server error
*/
app.get('/styleguide', isAuthenticated, async (req, res) => {
try {
return res.render('styleguide', {
version: config.PAPERLESS_AI_VERSION || ' ',
});
} catch (error) {
console.error('[ERROR] Styleguide page:', error);
return res.status(500).json({ success: false, error: error.message });
}
});
}
/**
* @swagger
* /:
* get:
* summary: Root endpoint that redirects to the dashboard
* description: |
* This endpoint serves as the entry point for the application.
* When accessed, it automatically redirects the user to the dashboard page.
* No parameters or authentication are required for this redirection.
* tags: [Navigation, System]
* responses:
* 302:
* description: Redirects to the dashboard page
* content:
* text/html:
* schema:
* type: string
* example: "<html><body>Redirecting to dashboard...</body></html>"
* 500:
* description: Server error occurred during redirection
* content:
* application/json:
* schema:
* $ref: '#/components/schemas/Error'
*/
app.get('/', async (req, res) => {
try {
res.redirect('/dashboard');
} catch (error) {
console.error(`[ERROR] in root route: ${error.message}`);
console.debug(error);
res.status(500).send('Error processing request');
}
});
// /health is served by routes/system.js (through routes/index.js), which is
// mounted above this file's routes. A second handler here was never reachable
// and has been removed so the OpenAPI spec documents the handler that actually
// answers.
// Error handler
// Express detects error middleware by its four-argument signature, so `next`
// must stay even though it is unused.
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
// Backoff schedule for the startup connectivity retry, in milliseconds.
// The last value repeats until the retry window configured via
// STARTUP_PAPERLESS_RETRY_MINUTES is exhausted.
const INITIAL_CONNECT_BACKOFF_MS = [5000, 15000, 30000, 60000, 120000, 300000];
const DEFAULT_STARTUP_RETRY_MINUTES = 30;
function initialConnectDelayMs(attempt) {
const index = Math.min(attempt - 1, INITIAL_CONNECT_BACKOFF_MS.length - 1);
return INITIAL_CONNECT_BACKOFF_MS[Math.max(index, 0)];
}
function startupRetryWindowMs() {
const configured = Number(config.startup?.paperlessRetryMinutes);
const minutes =
Number.isFinite(configured) && configured >= 0
? configured
: DEFAULT_STARTUP_RETRY_MINUTES;
return minutes * 60 * 1000;
}
/**
* Waits for Paperless-ngx to become usable and then runs the initial scan.
*
* Runs detached from startup: the scan scheduler is already armed at this
* point, so giving up here only means the first scan waits for the next cron
* tick instead of never happening (issue #272).
*/
async function runInitialScanWhenReachable() {
const deadlineMs = Date.now() + startupRetryWindowMs();
let attempt = 0;
for (;;) {
const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
console.warn(
'Initial scan skipped: setup is not completed yet. The scheduled scan stays armed.'
);
return;
}
const connection = await paperlessService.checkConnection();
scanHealthService.recordConnectivity(connection);
if (connection.reachable && connection.authorized) {
console.log(`Starting initial scan at ${new Date().toISOString()}`);
await scanService.scanDocuments('initial');
return;
}
attempt += 1;
const delayMs = initialConnectDelayMs(attempt);
if (Date.now() + delayMs > deadlineMs) {
// Count the abandoned initial scan as exactly one failed run. Counting
// every retry would trip the degraded threshold within minutes and make
// /health answer 503 during a perfectly normal slow start.
scanHealthService.recordRunResult({
status: RUN_STATUS.PAPERLESS_UNREACHABLE,
error: connection.error,
});
console.error(
`[STARTUP] Paperless-ngx still not usable after ${attempt} attempt(s): ${connection.error}. ` +
`Skipping the initial scan — the scheduled scan (${config.scanInterval}) stays armed and keeps retrying.`
);
return;
}
console.warn(
`[STARTUP] Paperless-ngx not usable yet: ${connection.error}. ` +
`Retrying in ${Math.round(delayMs / 1000)}s (attempt ${attempt}). ` +
`The scheduled scan (${config.scanInterval}) is armed regardless.`
);
await new Promise((resolve) => setTimeout(resolve, delayMs));
}
}
const DEFAULT_PAPERLESS_PROBE_INTERVAL_SECONDS = 60;
const MIN_PAPERLESS_PROBE_INTERVAL_SECONDS = 10;
function paperlessProbeIntervalMs() {
const configured = Number(config.health?.paperlessProbeIntervalSeconds);
if (!Number.isFinite(configured)) {
return DEFAULT_PAPERLESS_PROBE_INTERVAL_SECONDS * 1000;
}
if (configured <= 0) {
return 0;
}
return Math.max(configured, MIN_PAPERLESS_PROBE_INTERVAL_SECONDS) * 1000;
}
/**
* Probes Paperless-ngx on a fixed interval, independently of the scan loop.
*
* The scan loop only probes when it runs, so between two ticks an outage was
* invisible to the dashboard — and entirely invisible with
* DISABLE_AUTOMATIC_PROCESSING=yes. This keeps `paperless.lastCheckedAt` fresh
* so the UI can warn immediately.
*
* Only connectivity is recorded here; the consecutive-failure counter belongs
* to actual scan runs and must not be moved by a passive probe.
*/
function startConnectivityMonitor() {
const intervalMs = paperlessProbeIntervalMs();
if (intervalMs === 0) {
console.info(
'[HEALTH] Paperless-ngx connectivity probe is disabled (PAPERLESS_PROBE_INTERVAL_SECONDS=0).'
);
return;
}
let probeRunning = false;
const probe = async () => {
// A scan probes on its own and would only duplicate the request here.
if (probeRunning || scanControl.running) {
return;
}
probeRunning = true;
try {
if (!(await setupService.isConfigured())) {
// Nothing configured yet — reporting "not reachable" would warn about
// a connection the user has not set up.
scanHealthService.clearConnectivity();
return;
}
scanHealthService.recordConnectivity(
await paperlessService.checkConnection()
);
} catch (error) {
console.debug(
`[HEALTH] Connectivity probe failed unexpectedly: ${error.message}`
);
} finally {
probeRunning = false;
}
};
const timer = setInterval(probe, intervalMs);
// Never keep the event loop alive just for the probe.
timer.unref?.();
console.info(
`[HEALTH] Paperless-ngx connectivity probe armed (every ${intervalMs / 1000}s).`
);
probe();
}
// Start scanning
async function startScanning() {
try {
const isConfigured = await setupService.isConfigured();
if (!isConfigured) {
console.log(
`Setup not completed. Visit http://your-machine-ip:${process.env.PAPERLESS_AI_PORT || 3000}/setup to complete setup.`
);
}
// Reconciliation: remove stale documents deleted in Paperless-ngx.
// Armed independently of Paperless-ngx reachability so a temporary outage
// cannot leave the app without any scheduled work.
if (config.reconciliationEnabled === 'yes') {
console.log(
'Configured reconciliation interval:',
config.reconciliationInterval
);
cron.schedule(config.reconciliationInterval, async () => {
console.debug(
`[RECONCILIATION] Scheduled run triggered at ${new Date().toISOString()}`
);
await reconciliationService.reconcileAllDocuments();
});
} else {
console.info(
'[RECONCILIATION] Automatic reconciliation is disabled (RECONCILIATION_ENABLED=no).'
);
}
// Dashboard statistics are cached, and the cache is kept warm from here so
// no visitor ever waits for the assembly. Armed before the automatic
// processing kill-switch below on purpose: the dashboard is served (and
// polled) whether or not scanning is enabled.
if (isConfigured) {
dashboardStatsService.refresh().catch((error) => {
console.debug(`[DASHBOARD-STATS] Warmup failed: ${error.message}`);
});
}
cron.schedule('* * * * *', async () => {
// Never compete with a running scan for the Paperless API — the scan
// invalidates the cache per document anyway, and the run end refreshes it.
if (scanControl.running) {
return;
}
if (!(await setupService.isConfigured())) {
return;
}
await dashboardStatsService.refresh().catch((error) => {
console.debug(
`[DASHBOARD-STATS] Scheduled refresh failed: ${error.message}`
);
});
});
if (config.disableAutomaticProcessing === 'yes') {
scanHealthService.markAutomaticProcessingDisabled();
console.info(
'Automatic document processing is disabled (DISABLE_AUTOMATIC_PROCESSING=yes). No scan is scheduled.'
);
return;
}
// OCR auto-processing: drain the pending OCR queue without anyone having
// to press "Process All Pending". Armed after the kill-switch above
// because OCR + AI writes results back to Paperless-ngx, which is exactly
// what DISABLE_AUTOMATIC_PROCESSING is meant to stop.
if (ocrAutoProcessService.isEnabled()) {
const ocrAutoProcessInterval = ocrAutoProcessService.interval;
console.log(
'Configured OCR auto-processing interval:',
ocrAutoProcessInterval
);
cron.schedule(ocrAutoProcessInterval, async () => {
// Never compete with a running scan for the same AI backend.
if (scanControl.running) {
console.debug(
'[OCR] Auto-processing skipped: a document scan is currently running.'
);
return;
}
await ocrAutoProcessService.drainQueue();
});
} else {
console.info(
'[OCR] Automatic OCR queue processing is disabled (OCR_AUTO_PROCESS_ENABLED=no).'
);
}
// Arm the scheduler before talking to Paperless-ngx. A connection failure
// at startup must never leave the app running without a scan loop —
// every scheduled run re-checks connectivity on its own.
console.log('Configured scan interval:', config.scanInterval);
cron.schedule(config.scanInterval, async () => {
console.log(`Starting scheduled scan at ${new Date().toISOString()}`);
if (!(await setupService.isConfigured())) {
console.warn('Scheduled scan skipped: setup is not completed.');
return;
}
await scanService.scanDocuments();
});
scanHealthService.markArmed(config.scanInterval);
// Detached on purpose: startup must not block while Paperless-ngx is still
// coming up. unhandledRejection terminates the process, so catch here.
runInitialScanWhenReachable().catch((error) => {
console.error(`[ERROR] during initial scan: ${error.message}`);
console.debug(error);
});
} catch (error) {
console.error(`[ERROR] in startScanning: ${error.message}`);
console.debug(error);
}
}
// Error handlers
// process.on('SIGTERM', async () => {
// console.log('Received SIGTERM. Starting graceful shutdown...');
// try {
// console.log('Closing database...');
// await documentModel.closeDatabase(); // Jetzt warten wir wirklich auf den Close
// console.log('Database closed successfully');
// process.exit(0);
// } catch (error) {
// console.error('[ERROR] during shutdown:', error);
// process.exit(1);
// }
// });
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
process.exit(1);
});
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
process.exit(1);
});
async function gracefulShutdown(signal) {
console.info(`Received ${signal} signal. Starting graceful shutdown...`);
try {
console.info('Closing database...');
await documentModel.closeDatabase();
console.info('Database closed successfully');
process.exit(0);
} catch (error) {
console.error(`[ERROR] during ${signal} shutdown: ${error.message}`);
console.debug(error);
process.exit(1);
}
}
// Handle both SIGTERM and SIGINT
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
// Start server
async function startServer() {
const port = process.env.PAPERLESS_AI_PORT || 3000;
try {
await initializeDataDirectory();
await runStartupMigrations(console);
await mistralOcrService.recoverInterruptedJobs(console);
await saveOpenApiSpec(); // Save OpenAPI specification on startup
app.listen(port, () => {
console.log(`Server running on port ${port}`);
warnIfRemoteSetupExposed();
oidcService.logStatus();
startScanning();
// Armed separately from the scan scheduler so the dashboard also warns
// when automatic processing is switched off.
startConnectivityMonitor();
});
} catch (error) {
console.error(`Failed to start server: ${error.message}`);
console.debug(error);
process.exit(1);
}
}
/**
* Emits a security warning when the server starts with an incomplete setup
* AND ALLOW_REMOTE_SETUP=yes, meaning the unauthenticated setup endpoints
* are reachable from the network.
*/
async function warnIfRemoteSetupExposed() {
if (process.env.ALLOW_REMOTE_SETUP !== 'yes') {
return;
}
try {
const isConfigured = await setupService.isConfigured();
if (isConfigured) {
return;
}
const msg =
'[SECURITY WARNING] Setup is not yet complete and ALLOW_REMOTE_SETUP=yes. ' +
'The setup endpoints are reachable from the network. ' +
'Disable ALLOW_REMOTE_SETUP or restrict network access until setup is finished.';
console.warn(msg);
htmlLogger.log(`⚠️ ${msg}`);
txtLogger.log(msg);
} catch {
// Non-fatal — warning is best-effort
}
}
startServer();