-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathserver.js
More file actions
1718 lines (1542 loc) · 55.5 KB
/
Copy pathserver.js
File metadata and controls
1718 lines (1542 loc) · 55.5 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
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 AIServiceFactory = require('./services/aiServiceFactory');
const documentModel = require('./models/document');
const setupService = require('./services/setupService');
const { runStartupMigrations } = require('./services/startupMigrations');
const setupRoutes = require('./routes/setup');
const { isAuthenticated } = require('./routes/auth');
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 { 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 jwt = require('jsonwebtoken');
const Logger = require('./services/loggerService');
const {
validateCustomFieldValue,
shouldQueueForOcrOnAiError,
classifyOcrQueueReasonFromAiError,
isTimeoutError,
buildTimeoutErrorMessage,
} = require('./services/serviceUtils');
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');
const scanControl = global.__paperlessAiScanControl || {
running: false,
stopRequested: false,
source: null,
startedAt: null,
stopRequestedAt: null,
};
global.__paperlessAiScanControl = scanControl;
function requestScanStop() {
if (!scanControl.running) {
return false;
}
scanControl.stopRequested = true;
scanControl.stopRequestedAt = new Date().toISOString();
return true;
}
async function triggerScanNow(source = 'manual') {
if (scanControl.running) {
return {
started: false,
running: true,
stopRequested: scanControl.stopRequested,
message: 'Scan is already running.',
};
}
// The OCR drain works on the same documents through the same AI backend.
// Letting a scan start next to it is what bought a second paid OCR run for a
// document the drain had just finished (issue #322).
if (ocrAutoProcessService.running) {
return {
started: false,
running: false,
message: 'OCR auto-processing is currently running.',
};
}
scanDocuments(source).catch((error) => {
console.error(
`[ERROR] scanDocuments() failed in triggerScanNow: ${error.message}`
);
console.debug(error);
});
return {
started: true,
running: true,
stopRequested: false,
message: 'Scan started.',
};
}
global.__paperlessAiTriggerScanNow = triggerScanNow;
global.__paperlessAiRequestScanStop = 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);
}
function getCookieSecureMode() {
return typeof config.getCookieSecureMode === 'function'
? config.getCookieSecureMode()
: String(process.env.COOKIE_SECURE_MODE || 'auto')
.trim()
.toLowerCase();
}
function shouldUseSecureCookies(req) {
const mode = getCookieSecureMode();
if (mode === 'always') {
return true;
}
if (mode === 'never') {
return false;
}
if (req) {
const forwardedProto = String(req.headers['x-forwarded-proto'] || '')
.split(',')[0]
.trim()
.toLowerCase();
return Boolean(req.secure || forwardedProto === 'https');
}
return String(process.env.NODE_ENV || '').toLowerCase() === 'production';
}
function isHttpsRequest(req) {
const forwardedProto = String(req.headers['x-forwarded-proto'] || '')
.split(',')[0]
.trim()
.toLowerCase();
return Boolean(req.secure || forwardedProto === 'https');
}
const csrfCookieSecure = shouldUseSecureCookies();
// Retry tracking to prevent infinite retry loops
const retryTracker = new Map();
// Configurable minimum content length (default: 10 characters)
const MIN_CONTENT_LENGTH = config.minContentLength;
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,
keyGenerator: (req) => {
const apiKey = req.headers['x-api-key'];
const currentApiKey = config.getApiKey();
if (currentApiKey && apiKey && apiKey === currentApiKey) {
return `api-key:${apiKey}`;
}
const token = req.cookies?.jwt || req.headers.authorization?.split(' ')[1];
if (token) {
try {
const decoded = jwt.verify(token, JWT_SECRET);
const userIdentifier =
decoded?.id || decoded?.userId || decoded?.username || decoded?.sub;
if (userIdentifier) {
return `user:${userIdentifier}`;
}
} catch {
// Ignore invalid token and fallback to IP
}
}
return 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.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.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) => {
const token =
req.cookies?.jwt || req.headers.authorization?.split(' ')[1];
if (token) {
return `jwt:${token}`;
}
const apiKey = req.headers['x-api-key'];
const currentApiKey = config.getApiKey();
if (currentApiKey && apiKey && apiKey === currentApiKey) {
return `api-key:${apiKey}`;
}
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) => {
const apiKey = req.headers['x-api-key'];
const currentApiKey = config.getApiKey();
// If API Key is valid, skip CSRF
if (currentApiKey && apiKey && apiKey === currentApiKey) {
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;
}
}
// Document processing functions
async function processDocument(
doc,
existingTags,
existingCorrespondentList,
existingDocumentTypesList,
context = {}
) {
const isProcessed = await documentModel.isDocumentProcessed(doc.id);
if (isProcessed) return null;
// A document that waits in the OCR queue, or sits inside an OCR run right
// now, gets both its text and its analysis from that path. Analysing it here
// would work on the very text the OCR run is about to replace, and the three
// Paperless-ngx calls below would be spent for nothing.
const queuedForOcrIds = context.ocrQueuedDocumentIds;
if (
(queuedForOcrIds && queuedForOcrIds.has(Number(doc.id))) ||
mistralOcrService.isDocumentActivelyProcessing(doc.id)
) {
console.debug(
`Document ${doc.id} is waiting for Mistral OCR, skipping analysis this round`
);
return null;
}
const isIgnored = await documentModel.isDocumentIgnored(doc.id);
if (isIgnored) {
console.debug(
`Document ${doc.id} is marked as ignored, skipping permanently`
);
return null;
}
const isFailed = await documentModel.isDocumentFailed(doc.id);
if (isFailed) {
console.debug(
`Document ${doc.id} is marked as permanently failed, skipping until reset`
);
return null;
}
await documentModel.setProcessingStatus(doc.id, doc.title, 'processing');
// Check if the document can be edited.
const documentEditable = await paperlessService.getPermissionOfDocument(
doc.id
);
if (!documentEditable) {
console.debug(
`Document ${doc.id} is not editable by the Zettelrobbe user, skipping analysis`
);
return null;
}
console.debug(`Document ${doc.id} is editable by the Paperless-AI user`);
let [content, originalData] = await Promise.all([
paperlessService.getDocumentContent(doc.id),
paperlessService.getDocument(doc.id),
]);
// Both automatic queue points share this helper. The Paperless-ngx calls
// above take long enough for a running OCR job to finish in between, delete
// its queue row and put the document into processed_documents — the scan
// then used to insert a fresh pending row and buy a second paid OCR run
// (issue #322). The checks here keep that out of the log and off the wire;
// skipIfProcessed is the atomic safety net inside the insert itself.
const queueForOcr = async (queueReason) => {
if (await documentModel.isDocumentProcessed(doc.id)) {
console.debug(
`Document ${doc.id} was processed while this scan was running, not queued for Mistral OCR (already processed)`
);
return false;
}
if (mistralOcrService.isDocumentActivelyProcessing(doc.id)) {
console.debug(
`Document ${doc.id} is inside an OCR run, not queued for Mistral OCR (currently processing)`
);
return false;
}
const queued = await documentModel.addToOcrQueue(
doc.id,
doc.title,
queueReason,
{ skipIfProcessed: true }
);
if (!queued) {
const queueItem = await documentModel.getOcrQueueItem(doc.id);
let state = 'already processed';
if (queueItem?.status === 'done') {
state = 'already done';
} else if (queueItem?.status === 'processing') {
state = 'currently processing';
}
console.debug(
`Document ${doc.id} was not queued for Mistral OCR (${state})`
);
}
return queued;
};
if (!content || content.length < MIN_CONTENT_LENGTH) {
console.debug(
`Document ${doc.id} has insufficient content (${content?.length || 0} chars, minimum: ${MIN_CONTENT_LENGTH}), skipping analysis`
);
// Queue for Mistral OCR if enabled.
if (mistralOcrService.isEnabled()) {
const added = await queueForOcr(`short_content_lt_${MIN_CONTENT_LENGTH}`);
if (added) {
console.info(
`Document ${doc.id} queued for Mistral OCR (short_content)`
);
}
} else {
await documentModel.setProcessingStatus(doc.id, doc.title, 'failed');
await documentModel.addFailedDocument(
doc.id,
doc.title,
`insufficient_content_lt_${MIN_CONTENT_LENGTH}`,
'ai'
);
retryTracker.delete(doc.id);
}
return null;
}
// Check retry limit to prevent infinite retry loops
const docRetries = retryTracker.get(doc.id) || 0;
if (docRetries >= 3) {
console.warn(
`Document ${doc.id} has failed ${docRetries} times, skipping to prevent infinite retry loop`
);
await documentModel.setProcessingStatus(doc.id, doc.title, 'failed');
retryTracker.delete(doc.id);
return null;
}
if (content.length > 50000) {
content = content.substring(0, 50000);
}
const aiService = AIServiceFactory.getService();
const analysis = await aiService.analyzeDocument(
content,
existingTags,
existingCorrespondentList,
existingDocumentTypesList,
doc.id
);
console.debug('Response from AI service:', analysis);
if (analysis.error) {
const aiErrorMessage = isTimeoutError(analysis.error)
? `${buildTimeoutErrorMessage('AI')} Original error: ${analysis.error}`
: analysis.error;
if (isTimeoutError(analysis.error)) {
console.error(`[TIMEOUT][AI] Document ${doc.id}: ${analysis.error}`);
}
let queuedForOcr = false;
let markedTerminalFailed = false;
// Queue for Mistral OCR on OCR-relevant AI errors (e.g. low content, invalid response structure)
if (
mistralOcrService.isEnabled() &&
shouldQueueForOcrOnAiError(aiErrorMessage)
) {
const queueReason = classifyOcrQueueReasonFromAiError(aiErrorMessage);
const added = await queueForOcr(queueReason);
if (added) {
console.log(
`[OCR] Document ${doc.id} queued for Mistral OCR (ai_failed: ${aiErrorMessage})`
);
}
// The OCR path stays responsible for this document even when nothing was
// queued: a refusal means it is already processed, already done or inside
// a run, and none of those is a terminal AI failure worth recording.
queuedForOcr = true;
}
if (!mistralOcrService.isEnabled()) {
await documentModel.setProcessingStatus(doc.id, doc.title, 'failed');
await documentModel.addFailedDocument(
doc.id,
doc.title,
// A service that knows exactly why it gave up says so; everything else
// keeps the generic reason this branch has always recorded.
analysis.errorCode || 'ai_failed_ocr_disabled',
'ai'
);
retryTracker.delete(doc.id);
markedTerminalFailed = true;
} else if (!queuedForOcr) {
await documentModel.setProcessingStatus(doc.id, doc.title, 'failed');
await documentModel.addFailedDocument(
doc.id,
doc.title,
analysis.errorCode || 'ai_failed_without_ocr_fallback',
'ai'
);
retryTracker.delete(doc.id);
markedTerminalFailed = true;
}
// Increment retry count on error
if (!markedTerminalFailed) {
retryTracker.set(doc.id, docRetries + 1);
}
throw new Error(`[ERROR] Document analysis failed: ${aiErrorMessage}`);
}
// Clear retry count on success
retryTracker.delete(doc.id);
return { analysis, originalData };
}
async function buildUpdateData(analysis, doc) {
const updateData = {};
const options = {
restrictToExistingTags: config.restrictToExistingTags === 'yes',
restrictToExistingCorrespondents:
config.restrictToExistingCorrespondents === 'yes',
restrictToExistingDocumentTypes:
config.restrictToExistingDocumentTypes === 'yes',
};
// Only process tags if tagging is activated
if (config.limitFunctions?.activateTagging !== 'no') {
const { tagIds, errors } = await paperlessService.processTags(
analysis.document.tags,
options
);
if (errors.length > 0) {
console.warn('[ERROR] Some tags could not be processed:', errors);
}
updateData.tags = tagIds;
} else if (
config.limitFunctions?.activateTagging === 'no' &&
config.addAIProcessedTag === 'yes'
) {
// Add AI processed tags to the document (processTags function awaits a tags array)
// get tags from .env file and split them by comma and make an array
console.debug(
'Tagging is deactivated but the AI processed tag will still be added'
);
const tags = config.addAIProcessedTags.split(',');
const { tagIds, errors } = await paperlessService.processTags(
tags,
options
);
if (errors.length > 0) {
console.warn('[ERROR] Some tags could not be processed:', errors);
}
updateData.tags = tagIds;
console.debug('Tagging is deactivated');
}
// Only process title if title generation is activated
if (config.limitFunctions?.activateTitle !== 'no') {
updateData.title = analysis.document.title || doc.title;
}
// Add created date regardless of settings as it's a core field
updateData.created = analysis.document.document_date || doc.created;
// Only process document type if document type classification is activated
if (
config.limitFunctions?.activateDocumentType !== 'no' &&
analysis.document.document_type
) {
try {
const documentType = await paperlessService.getOrCreateDocumentType(
analysis.document.document_type,
options
);
if (documentType) {
updateData.document_type = documentType.id;
}
} catch (error) {
console.error(`[ERROR] Error processing document type: ${error.message}`);
console.debug(error);
}
}
// Only process custom fields if custom fields detection is activated
if (
config.limitFunctions?.activateCustomFields !== 'no' &&
analysis.document.custom_fields
) {
const customFields = analysis.document.custom_fields;
const processedFields = [];
const customFieldsForHistory = [];
// Get existing custom fields
const existingFields = await paperlessService.getExistingCustomFields(
doc.id
);
console.debug('Found existing fields:', existingFields);
// Keep track of which fields we've processed to avoid duplicates
const processedFieldIds = new Set();
// First, add any new/updated fields
for (const key in customFields) {
const customField = customFields[key];
if (
!customField.field_name ||
customField.value === null ||
customField.value === undefined ||
String(customField.value).trim() === ''
) {
console.debug('Skipping empty or invalid custom field');
continue;
}
const fieldDetails = await paperlessService.findExistingCustomField(
customField.field_name
);
if (fieldDetails?.id) {
const validation = validateCustomFieldValue(
customField.field_name,
customField.value,
fieldDetails.data_type
);
if (validation.skip) {
if (validation.warn) console.warn(validation.warn);
continue;
}
processedFields.push({
field: fieldDetails.id,
value: validation.value,
});
// Capture name + validated value for history at the point where we have both
customFieldsForHistory.push({
field_name: customField.field_name,
value: validation.value,
});
processedFieldIds.add(fieldDetails.id);
}
}
// Then add any existing fields that weren't updated
for (const existingField of existingFields) {
if (!processedFieldIds.has(existingField.field)) {
processedFields.push(existingField);
}
}
if (processedFields.length > 0) {
updateData.custom_fields = processedFields;
}
if (customFieldsForHistory.length > 0) {
updateData._customFieldsForHistory = customFieldsForHistory;
}
}
// Only process correspondent if correspondent detection is activated
if (
config.limitFunctions?.activateCorrespondents !== 'no' &&
analysis.document.correspondent
) {
try {
const correspondent = await paperlessService.getOrCreateCorrespondent(
analysis.document.correspondent,
options
);