Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·4342 lines (3997 loc) · 181 KB
/
Copy pathserver.js
File metadata and controls
executable file
·4342 lines (3997 loc) · 181 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
import path from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';
import { GoogleGenAI } from '@google/genai';
import fastifyCookie from '@fastify/cookie';
import fastifyCors from '@fastify/cors';
import fastifyMultipart from '@fastify/multipart';
import crypto from 'crypto';
import { SECURITY_CONFIG } from './serverConfig.js';
import { PROMPT_SHAPES, SYSTEM_INSTRUCTION_ANALYSIS, WINDBG_PREFIX, wrapWithEvidence } from './shared/promptTemplates.js';
import fs from 'fs';
import os from 'os';
import JSZip from 'jszip';
import {
ALLOWED_EXTENSIONS,
DUMP_EXTENSIONS,
FILE_LIMITS,
detectArchiveType,
getFileExtension,
sanitizeUploadFileName,
validatePathEntry,
validateUploadedBuffer
} from './shared/ingestPolicy.js';
import {
DEFAULT_WINDBG_API_BASE_URL,
extractWinDbgAnalysisPackage,
getWinDbgJob,
markWinDbgJobsArchived,
mapWinDbgJobStatus,
normalizeWinDbgApiBaseUrl,
submitWinDbgJob,
toLegacyWinDbgStatusResponse,
winDbgJobErrorLogFields
} from './shared/windbgApiClient.js';
import {
mapStructuredSignalToReport,
mergeReportWithWinDbgFields,
parseWinDbgOutput
} from './shared/windbgReportFields.js';
import { isForumIdentityEnabled, resolveForumIdentityFromCookies } from './services/forumIdentity.js';
import { winDbgUpstreamFailureCode, winDbgUpstreamHttpStatus, windbgUploadFailureResponse } from './server/windbgUploadFailure.js';
import { isUnconfirmedSubmitFailure } from './server/windbgSubmitFailure.js';
import { classifyRequestError } from './server/requestErrors.js';
import { analyzeHeldSubmissionResponse, analyzeSubmitFailureResponse, createExternalJobCodec, createExternalJobResolver, createExternalSubmissionReuse, isExternalJobUid } from './server/externalJobs.js';
import {
createFastifyCompatApp,
jsonParser,
staticMiddleware
} from './server/fastifyCompat.js';
import { createMaintenanceMiddleware } from './server/maintenance.js';
import { createShutdownCoordinator } from './server/shutdown.js';
import { createPathShapeMiddleware } from './server/requestPath.js';
import {
createRateLimiterFactory,
jsonRateLimitHandler,
normalizeRateLimitIp
} from './server/rateLimit.js';
import { createUploadHandler } from './server/uploadHandler.js';
import {
CSP_EMBED_HEADER,
CSP_HEADER,
CSP_MODE,
EMBEDDABLE_PATHS,
computeInlineScriptSources,
createSecurityHeadersMiddleware
} from './server/securityHeaders.js';
import { createCspReportCollector, registerCspReportRoute } from './server/cspReport.js';
import {
DEFAULT_DAILY_WINDOW_DAYS,
DEFAULT_SNAPSHOT_TTL_SECONDS,
createStatsStore
} from './server/statsStore.js';
import { extractStatsFacts } from './server/stats.js';
import { createGcsJsonReader } from './server/gcsJson.js';
import { createGcsStatsSource } from './server/statsGcsSource.js';
import { createWinDbgCorpusRecorder } from './server/windbgCorpus.js';
import { windbgFailureLogFields } from './server/windbgFailureLog.js';
import {
createExternalWinDbgSubmit,
createExternalWinDbgSubmitter,
createWinDbgUploadCapGate,
createWinDbgUploadSubmitter,
DEFAULT_WINDBG_UPLOAD_RESPONSE_BUDGET_MS,
resolveUploadResponseBudgetMs
} from './server/windbgUploadSubmit.js';
import { createCrashPriors, extractPromptSignal } from './server/crashPriors.js';
import { createCrashSignalRecorder } from './server/crashSignal.js';
import { createConcurrencyLimiter } from './server/concurrency.js';
import { classifyRequestPath } from './server/blockedPaths.js';
import { MIME_TYPES as STATIC_MIME_TYPES, staticHeadersFor, createStaticRedirectMiddleware } from './server/staticPolicy.js';
import { createCorsOriginCheck } from './server/corsPolicy.js';
import { ALL_SESSION_COOKIES, LEGACY_SESSION_COOKIES, presentedSessionCookies } from './server/sessionCookies.js';
import {
DEFAULT_FORUM_MCP_URL,
createForumMcpClient,
createForumRelatedService,
registerForumRelatedRoute
} from './server/forumRelated.js';
import { requireDataUseTerms } from './server/dataUseTerms.js';
import { registerBsodAiRoutes } from './server/bsodAiRoute.js';
import { redactPublicReportText } from './shared/reportFacts.js';
import { createPassCodec, createStrikeTracker } from './server/bsodAi.js';
import { createHtmlDocuments, normalizeRoutePath, prerenderedRouteKey } from './server/htmlDocuments.js';
import { DATA_USE_TERMS_VERSION } from './shared/dataUseTerms.js';
import {
SERVER_PROMPT_FILE_NAME,
buildServerWinDbgPrompt,
buildWinDbgEvidence,
normalizeAnalysisReport,
parseAndValidateAnalysisReport,
promptCarriesWinDbgSignal,
winDbgPromptFileFacts
} from './server/analysisReport.js';
import { registerStatsRoute } from './server/statsRoute.js';
import { createPeerIpResolver } from './server/peerIp.js';
import { createTurnstileReplayGuard } from './server/turnstile.js';
import { createFileHandleCodec, createSessionCodec } from './server/sessionToken.js';
import { exchangeSession } from './server/ssoSession.js';
import {
createProviderQuotaStore,
createSessionQuotaStore,
providerBackoffFor,
settleFailedProviderReservation,
settleProviderTokenReservation
} from './server/quotaStore.js';
import { createQuotaLedger, createSharedCounterStoreFromEnv } from './server/sharedCounters.js';
import { createOpenAIFreeBudget, openAIFreeUsage } from './server/openaiFreeTier.js';
import { createAIDeadline, aiRequestDeadlineMs } from './server/aiDeadline.js';
import { parsePositiveIntEnv, parseTrustProxyHops, readEnvSwitches, warnRetiredEnv } from './server/envConfig.js';
import { createArchiveDumpExtractor, selectAnalyzableDump } from './server/archiveExtract.js';
import { shouldRefund, refundCapFor, classifyQuotaFailure } from './server/quotaPolicy.js';
import {
createStatsInsightService,
registerStatsInsightRoute
} from './server/statsInsight.js';
import {
AIProviderError,
DEFAULT_DEEPSEEK_API_BASE_URL,
DEFAULT_GEMINI_MODEL,
generateDeepSeekContent,
generateOpenRouterContent,
generateOpenAIContent,
generateExperientialContent,
conservativeChatInputTokenReservation,
isOpenAIFreeTier,
DEFAULT_OPENROUTER_BASE_URL,
DEFAULT_OPENROUTER_FREE_MODEL,
DEFAULT_OPENAI_FREE_MODEL,
DEFAULT_EXPERIENTIAL_MODEL,
getAIProviderForModel,
getCachedAIReportForModel,
isSupportedAIModel
} from './services/aiProvider.js';
import {
initCache,
initCacheCompression,
hashContent,
getPromptCacheKey,
getCachedAnalysis,
setCachedAnalysis,
isAnalysisCached,
isCacheEnabled,
disableRedis,
getRedisDisabledReason,
checkCacheConnection
} from './services/cache.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
function readPackageManager() {
try {
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8'));
return typeof pkg.packageManager === 'string' ? pkg.packageManager : null;
} catch {
return null;
}
}
const PACKAGE_MANAGER = readPackageManager();
const NPM_VERSION = PACKAGE_MANAGER?.startsWith('npm@') ? PACKAGE_MANAGER.slice(4) : null;
// ---------------------------------------------------------------------------
// Structured logging
// Cloud Run auto-parses any JSON line on stdout into Cloud Logging's jsonPayload
// and reads `severity` as the log level. Querying `jsonPayload.event="..."`
// then lets us chart metrics (cache hit rate, token spend, WinDBG failures)
// directly from the log stream — no separate metrics pipeline needed.
// ---------------------------------------------------------------------------
function emitJsonLog(severity, event, fields) {
try {
process.stdout.write(JSON.stringify({ severity, event, ...fields }) + '\n');
} catch {
// Fallback if a field contains a cycle or BigInt.
process.stdout.write(JSON.stringify({ severity, event, message: 'log serialization failed' }) + '\n');
}
}
const log = {
info: (event, fields = {}) => emitJsonLog('INFO', event, fields),
warn: (event, fields = {}) => emitJsonLog('WARNING', event, fields),
error: (event, fields = {}) => emitJsonLog('ERROR', event, fields),
};
const envWarn = ({ event, ...fields }) => log.warn(event, fields);
// On/off switches, parsed once (1/true/yes/on, 0/false/no/off; unknown values
// warn and keep the safe side).
const ENV_SWITCHES = readEnvSwitches(process.env, { warn: envWarn });
// Leftover variables of retired provider legs (issue #323) are ignored; one
// `env.ignored` warning names them.
warnRetiredEnv(process.env, { warn: envWarn });
const PORT = process.env.PORT || 8080;
const ENABLE_H2C = String(process.env.ENABLE_H2C || 'false').toLowerCase() === 'true';
const HTTP2_SESSION_TIMEOUT_MS = readPositiveInt('HTTP2_SESSION_TIMEOUT_MS', 72_000);
// Trust proxy headers (required for Cloud Run). With Cloudflare in front of
// Cloud Run, the X-Forwarded-For chain is [user-ip, cloudflare-edge-ip] as the
// platform appends its view of the connecting peer. TRUST_PROXY_HOPS defaults
// to 2 to walk past both hops.
// Validated once (integer >= 1) and the same value goes to Fastify and the
// peer resolver (issue #292).
const TRUST_PROXY_HOPS = parseTrustProxyHops(process.env, { warn: envWarn });
const TRUST_PROXY_VALUE = TRUST_PROXY_HOPS;
const app = createFastifyCompatApp({
// External API job ids are signed tokens carrying the job metadata (~300-500 chars).
maxParamLength: 1024,
http2: ENABLE_H2C,
http2SessionTimeout: HTTP2_SESSION_TIMEOUT_MS,
trustProxy: TRUST_PROXY_VALUE,
// Small global limit; only the multipart upload routes accept the upload
// cap (issue #288). No body is buffered before the middleware stack anyway.
bodyLimit: SECURITY_CONFIG.api.maxRequestSize,
routeBodyLimits: {
'/api/windbg/upload': SECURITY_CONFIG.api.maxUploadRequestSize,
'/api/extract-archive': SECURITY_CONFIG.api.maxUploadRequestSize,
'/api/analyze': SECURITY_CONFIG.api.maxUploadRequestSize
},
compression: {
enabled: true,
threshold: 1024,
forceThreshold: 0,
forceEncoding: req => isFromCloudflare(req) ? 'zstd' : null
}
});
app.set('trust proxy', TRUST_PROXY_VALUE);
const MAX_RAW_FILE_SIZE = SECURITY_CONFIG.api.maxRawFileSize;
const MAX_UPLOAD_REQUEST_SIZE = SECURITY_CONFIG.api.maxUploadRequestSize;
const MAX_EXTRACTED_ARCHIVE_SIZE = SECURITY_CONFIG.api.maxExtractedArchiveSize;
const MAX_ARCHIVE_FILE_COUNT = FILE_LIMITS.maxArchiveFileCount;
const MAX_ARCHIVE_COMPRESSION_RATIO = FILE_LIMITS.maxCompressionRatio;
// SHA-256 file identity (shared/hash.js, issue #146).
const HASH_RE = /^[a-f0-9]{64}$/i;
const TURNSTILE_ACTION = process.env.TURNSTILE_ACTION || 'file-upload';
const AI_MAX_PROMPT_CHARS = readPositiveInt('AI_MAX_PROMPT_CHARS', 250_000);
// Output budget for an analysis response. On a reasoning model the reasoning trace
// is charged against the same budget as the answer, so a cap sized for the JSON
// alone gets consumed by the reasoning and the object is cut off mid-string —
// surfacing as finishReason "LENGTH" and "AI response was not valid JSON". This is
// a ceiling, not a target: a model that finishes early is billed for what it used.
const AI_MAX_OUTPUT_TOKENS = readPositiveInt('AI_MAX_OUTPUT_TOKENS', 16_384);
const GEMINI_TIMEOUT_MS = readPositiveInt('GEMINI_TIMEOUT_MS', 60_000);
// DeepSeek runs with a reasoning trace, so it is materially slower than a
// straight completion and gets its own budget rather than inheriting Gemini's.
// AI_REQUEST_DEADLINE_MS below caps it, and the chain, per request.
const DEEPSEEK_TIMEOUT_MS = readPositiveInt('DEEPSEEK_TIMEOUT_MS', 120_000);
// Budget for the whole provider chain of one request (default 90 s, under
// Cloudflare's 100 s origin timeout): every leg above is capped by what
// remains of it (server/aiDeadline.js, issue #255).
const AI_REQUEST_DEADLINE_MS = aiRequestDeadlineMs(process.env, { warn: envWarn });
const DEEPSEEK_API_BASE_URL = process.env.DEEPSEEK_API_BASE_URL || DEFAULT_DEEPSEEK_API_BASE_URL;
// OpenRouter free-tier failover: used when the DeepSeek account cannot serve
// requests (out of credits, auth revoked). Unset key = failover disabled.
const OPENROUTER_API_KEY = process.env.OPENROUTER_API_KEY;
const OPENROUTER_BASE_URL = process.env.OPENROUTER_BASE_URL || DEFAULT_OPENROUTER_BASE_URL;
const OPENROUTER_FREE_MODEL = process.env.OPENROUTER_FREE_MODEL || DEFAULT_OPENROUTER_FREE_MODEL;
// OpenAI data-sharing incentive (complimentary tokens): gpt-6-luna is used
// FIRST each UTC day while the free quota lasts, then the chain falls back to
// DeepSeek -> OpenRouter. OPENAI_ADMIN_KEY enables an org-wide usage cross-check.
const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
const OPENAI_ADMIN_KEY = process.env.OPENAI_ADMIN_KEY;
const OPENAI_FREE_MODEL = process.env.OPENAI_FREE_MODEL || DEFAULT_OPENAI_FREE_MODEL;
const OPENAI_BASE_URL = process.env.OPENAI_BASE_URL || 'https://api.openai.com/v1';
const OPENAI_FREE_DAILY_TOKEN_CAP = readPositiveInt('OPENAI_FREE_DAILY_TOKEN_CAP', 10_000_000);
const OPENAI_FREE_SAFETY_BUFFER = readPositiveInt('OPENAI_FREE_SAFETY_BUFFER', 250_000);
// Experiential Cloud is used only for the BSOD analyzer's OpenAI-compatible
// Luna leg. It is enabled when the Secret Manager key is present; the token
// budget is tracked per instance (server/quotaStore.js).
const EXPERIENTIAL_API_KEY = process.env.EXPLABS_API_KEY;
const EXPERIENTIAL_BASE_URL = process.env.EXPLABS_BASE_URL || 'https://api.experientiallabs.ai/v1';
const EXPERIENTIAL_MODEL = process.env.EXPLABS_MODEL || DEFAULT_EXPERIENTIAL_MODEL;
const EXPERIENTIAL_DAILY_INPUT_LIMIT = readPositiveInt('EXPLABS_DAILY_INPUT_LIMIT', 15_000_000);
const EXPERIENTIAL_DAILY_OUTPUT_LIMIT = readPositiveInt('EXPLABS_DAILY_OUTPUT_LIMIT', 3_000_000);
const EXPERIENTIAL_HOURLY_INPUT_LIMIT = readPositiveInt('EXPLABS_HOURLY_INPUT_LIMIT', 3_000_000);
const EXPERIENTIAL_HOURLY_OUTPUT_LIMIT = readPositiveInt('EXPLABS_HOURLY_OUTPUT_LIMIT', 750_000);
const EXPERIENTIAL_DAILY_INPUT_BUFFER = readPositiveInt('EXPLABS_DAILY_INPUT_BUFFER', 250_000);
const EXPERIENTIAL_DAILY_OUTPUT_BUFFER = readPositiveInt('EXPLABS_DAILY_OUTPUT_BUFFER', 50_000);
const EXPERIENTIAL_HOURLY_INPUT_BUFFER = readPositiveInt('EXPLABS_HOURLY_INPUT_BUFFER', 50_000);
const EXPERIENTIAL_HOURLY_OUTPUT_BUFFER = readPositiveInt('EXPLABS_HOURLY_OUTPUT_BUFFER', 12_500);
// BSOD AI chat (server/bsodAiRoute.js). Off unless BSOD_AI_CHAT_ENABLED is set.
// The chat may use only this share of each free-provider budget (scans included),
// so a busy hour of questions cannot starve an analysis.
const BSOD_AI_CHAT_ENABLED = ENV_SWITCHES.bsodAiChatEnabled;
const BSOD_AI_CHAT_BUDGET_FRACTION = Math.min(1, Math.max(0.05, Number(process.env.BSOD_AI_CHAT_BUDGET_FRACTION) || 0.4));
const BSOD_AI_GLOBAL_DAILY_LIMIT = readPositiveInt('BSOD_AI_GLOBAL_DAILY_LIMIT', 3000);
// A chat answer is short; waiting longer than this is worse than resting.
const BSOD_AI_DEADLINE_MS = readPositiveInt('BSOD_AI_DEADLINE_MS', 30_000);
const BSOD_AI_TIER_LIMITS = {
anon: { requests: readPositiveInt('BSOD_AI_ANON_LIMIT', 8), tokens: 60_000 },
forum: { requests: readPositiveInt('BSOD_AI_FORUM_LIMIT', 20), tokens: 150_000 },
premium: { requests: readPositiveInt('BSOD_AI_PREMIUM_LIMIT', 40), tokens: 300_000 }
};
// Cloud Run --max-instances. deploy-with-secret.sh and cloudbuild.yaml pass the
// value they deploy with (the GitHub trigger's inline build does not, so the
// default must match the service's --max-instances).
const MAX_INSTANCES = readPositiveInt('MAX_INSTANCES', 10);
// Free-tier budgets are split into this many per-instance shares; each
// provider's own quota errors still latch its route off (402 / quota 429).
// The default stays 2 until the provider budget itself counts in the shared
// quota store (issue #134 follow-up): binding that store does not share these
// budgets, and 1/MAX_INSTANCES shares would cut the free tier each running
// instance can use five-fold and push peak traffic to the paid legs. Set
// PROVIDER_QUOTA_SHARDS=<max instances> to opt into the hard per-instance bound.
const PROVIDER_QUOTA_SHARDS = readPositiveInt('PROVIDER_QUOTA_SHARDS', 2);
// Effort below 'high' is selectable now, but the default is unchanged: the vendor's
// accepted values are not verified here beyond 'high'/'max', which is all this code
// has ever sent, so a lower setting is opt-in and instantly revertible via env
// rather than something a deploy silently changes underneath the analysis quality.
const DEEPSEEK_REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'max'];
const DEEPSEEK_REASONING_EFFORT = DEEPSEEK_REASONING_EFFORTS.includes(process.env.DEEPSEEK_REASONING_EFFORT)
? process.env.DEEPSEEK_REASONING_EFFORT
: 'high';
const DEEPSEEK_THINKING_ENABLED = !['0', 'false', 'disabled'].includes(
String(process.env.DEEPSEEK_THINKING || 'enabled').toLowerCase()
);
const TURNSTILE_TIMEOUT_MS = readPositiveInt('TURNSTILE_TIMEOUT_MS', 10_000);
// Upstream submit cap. On the browser upload route the response is answered
// within WINDBG_UPLOAD_RESPONSE_BUDGET_MS (default 90 s, clamped below
// Cloudflare's 100 s origin timeout) while the submit itself may run on to
// this cap so a retry can adopt the job it creates (issue #276).
const WINDBG_UPLOAD_TIMEOUT_MS = readPositiveInt('WINDBG_UPLOAD_TIMEOUT_MS', 240_000);
// Parsed strictly like every other integer env (issue #292), then clamped.
const WINDBG_UPLOAD_RESPONSE_BUDGET_MS = resolveUploadResponseBudgetMs(
readPositiveInt('WINDBG_UPLOAD_RESPONSE_BUDGET_MS', DEFAULT_WINDBG_UPLOAD_RESPONSE_BUDGET_MS)
);
const WINDBG_POLL_TIMEOUT_MS = readPositiveInt('WINDBG_POLL_TIMEOUT_MS', 20_000);
const WINDBG_DOWNLOAD_TIMEOUT_MS = readPositiveInt('WINDBG_DOWNLOAD_TIMEOUT_MS', 60_000);
// The JSON output contract is now part of the cache-stable prefixes in
// shared/promptTemplates.js (LOCAL_DUMP_PREFIX / WINDBG_PREFIX), so it no
// longer needs to be appended after the dynamic evidence.
// Strict: digits (optional underscores) only; a malformed value logs
// env.invalid and keeps the default (server/envConfig.js, issue #292).
function readPositiveInt(name, fallback) {
return parsePositiveIntEnv(process.env, name, fallback, { warn: envWarn });
}
function timeoutSignal(ms) {
if (typeof AbortSignal !== 'undefined' && typeof AbortSignal.timeout === 'function') {
return AbortSignal.timeout(ms);
}
const controller = new AbortController();
setTimeout(() => controller.abort(), ms).unref?.();
return controller.signal;
}
async function withTimeout(operation, ms, message) {
let timeoutHandle;
const operationPromise = Promise.resolve().then(operation);
operationPromise.catch(() => {});
const timeoutPromise = new Promise((_, reject) => {
timeoutHandle = setTimeout(() => reject(new Error(message)), ms);
});
try {
return await Promise.race([operationPromise, timeoutPromise]);
} finally {
clearTimeout(timeoutHandle);
}
}
// Cloudflare-published IP ranges live in server/peerIp.js alongside the
// proxy-chain trust rule: the immediate peer is read from the rightmost
// X-Forwarded-For entry ONLY when the chain carries at least TRUST_PROXY_HOPS
// entries (Cloudflare + Cloud Run append one each in production). A shorter
// chain means a proxy was skipped or the header was replaced, so the socket
// address is used instead — no header can spoof that. The ingress gate below
// and every IP-keyed rate limiter hang off these resolvers.
const {
getImmediatePeerIp,
hasTrustedXffChain,
isFromCloudflare,
getClientIp
} = createPeerIpResolver({ trustProxyHops: TRUST_PROXY_HOPS });
// Global security headers middleware (CSP strings + embeddable-path handling
// live in server/securityHeaders.js). The instance handle is kept so startup
// can hand over the inline-script hashes computed from the served HTML.
// Registered first so the ingress 403 and maintenance 503 carry them too.
const securityHeadersMiddleware = createSecurityHeadersMiddleware({
cspHeader: CSP_HEADER,
cspEmbedHeader: CSP_EMBED_HEADER,
embeddablePaths: EMBEDDABLE_PATHS
});
app.use(securityHeadersMiddleware);
// Reject any request whose immediate peer is not a Cloudflare edge IP.
// Combined with --no-default-url on the Cloud Run service, this closes both
// the default *.run.app URL and any direct-Cloud-Run path. /health is exempt
// so Cloud Run's own probes (which arrive without X-Forwarded-For) still pass.
const CLOUDFLARE_ONLY_INGRESS = ENV_SWITCHES.cloudflareOnlyIngress;
if (CLOUDFLARE_ONLY_INGRESS) {
console.log(`Ingress gate: requiring a Cloudflare edge peer and an XFF chain of >= ${TRUST_PROXY_HOPS} entries`);
app.use((req, res, next) => {
if (req.path === '/health') return next();
if (isFromCloudflare(req)) return next();
// chainTrusted=false means the XFF chain was shorter than TRUST_PROXY_HOPS —
// if that shows up for legitimate traffic, production hop count has drifted
// from the configured value (rollback: CLOUDFLARE_ONLY_INGRESS=false and
// retune TRUST_PROXY_HOPS; no redeploy needed).
log.warn('non_cloudflare_request_rejected', {
path: req.path,
peer: getImmediatePeerIp(req),
xff: req.headers['x-forwarded-for'] || null,
xffHops: (String(req.headers['x-forwarded-for'] || '')).split(',').filter(Boolean).length,
chainTrusted: hasTrustedXffChain(req)
});
return res.status(403).send('Forbidden');
});
}
// Maintenance gate: MAINTENANCE_MODE=true serves a 503 page for everything
// except /health. Flip it without a redeploy via
// gcloud run services update bsod-analyzer --region=us-east1 \
// --update-env-vars MAINTENANCE_MODE=true|false
app.use(createMaintenanceMiddleware());
// Path shape (issue #350): req.path is the raw request target, so "//about"
// is not the home page and "..\\health" is not /health. Duplicate slashes
// redirect to the collapsed path; backslashes and dot segments are rejected.
// Registered before every route so their stacks include it.
app.use(createPathShapeMiddleware());
function rateLimitKey(req) {
return normalizeRateLimitIp(getClientIp(req));
}
const makeLimiter = createRateLimiterFactory({
defaultKeyGenerator: rateLimitKey,
defaultHandler: jsonRateLimitHandler
});
function rejectLargeBody(limitBytes) {
return (req, res, next) => {
const contentLength = Number.parseInt(req.headers['content-length'] || '0', 10);
if (Number.isFinite(contentLength) && contentLength > limitBytes) {
return res.status(413).json({
success: false,
error: `Request too large. Maximum size is ${(limitBytes / 1024 / 1024).toFixed(0)}MB`,
code: 'REQUEST_TOO_LARGE'
});
}
next();
};
}
function safeToken(value) {
return crypto.createHash('sha256').update(String(value || '')).digest('hex').slice(0, 16);
}
function timingSafeEqualString(a, b) {
const aHash = crypto.createHash('sha256').update(String(a || '')).digest();
const bHash = crypto.createHash('sha256').update(String(b || '')).digest();
return crypto.timingSafeEqual(aHash, bHash);
}
// Initialize Upstash Redis cache
initCache();
// Secret for session validation
const SESSION_SECRET = process.env.SESSION_SECRET;
if (!SESSION_SECRET) {
if (process.env.NODE_ENV === 'production') {
console.error('FATAL: SESSION_SECRET must be configured in production.');
process.exit(1);
}
}
// Use the secret (either from env or temporary)
const ACTUAL_SESSION_SECRET = process.env.SESSION_SECRET || crypto.randomBytes(32).toString('hex');
// Sessions are stateless HMAC-signed cookies (server/sessionToken.js), valid on
// every Cloud Run instance with no shared store.
const SESSION_EXPIRY = 60 * 60 * 1000; // 1 hour idle
// Absolute cap: the idle window slides on re-issue, so without a hard ceiling
// an actively-used session would never expire.
const SESSION_MAX_AGE_MS = 12 * 60 * 60 * 1000; // 12 hours
// requireSession re-issues the cookie once it is this old, sliding the idle
// window for tabs whose periodic /api/auth/session refresh is paused (hidden).
const SESSION_REISSUE_AFTER_MS = 30 * 60 * 1000;
const sessionCodec = createSessionCodec({
secret: ACTUAL_SESSION_SECRET,
previousSecret: process.env.SESSION_SECRET_PREVIOUS,
idleMs: SESSION_EXPIRY,
maxAgeMs: SESSION_MAX_AGE_MS
});
// Signed per-upload proof of file ownership + upstream WinDBG job id, so poll,
// download and cache reads work on an instance that never saw the upload.
const fileHandleCodec = createFileHandleCodec({
secret: ACTUAL_SESSION_SECRET,
previousSecret: process.env.SESSION_SECRET_PREVIOUS,
ttlMs: SESSION_MAX_AGE_MS
});
// BSOD AI chat: a Turnstile-backed pass bound to the session, and strikes for
// prompt-injection / off-topic attempts (server/bsodAi.js).
const bsodAiPassCodec = createPassCodec({ secret: ACTUAL_SESSION_SECRET, previousSecret: process.env.SESSION_SECRET_PREVIOUS });
const bsodAiStrikes = createStrikeTracker({ maxStrikes: key => (key.startsWith('ip:') ? 12 : 4) });
setInterval(() => bsodAiStrikes.prune(), 60 * 1000).unref?.();
// Per-key counters that must hold across Cloud Run instances (issue #134): the
// AI quota and the cost-bearing limiters. Shared through a dedicated Upstash
// database when QUOTA_REDIS_REST_URL/TOKEN are bound (server/sharedCounters.js),
// per instance otherwise or while that store is failing.
const sharedCounters = createSharedCounterStoreFromEnv(process.env, {
onError: error => log.warn('quota.shared_store_error', { message: error.message?.slice(0, 160) })
});
const quotaLedger = createQuotaLedger({ shared: sharedCounters, local: createSessionQuotaStore() });
const REQUEST_LIMIT_PER_SESSION = 50; // Legacy flat cap; superseded by TIER_LIMITS below.
const TOKEN_LIMIT_PER_SESSION = 500000;
// Tier-based hourly quotas. Anonymous (Turnstile only) gets a functional but
// limited allowance; a logged-in WindowsForum member gets more; a Premium
// Supporter (forum user group 312, established via the SSO bridge) gets the
// most. Enforced at the AI chokepoint. For logged-in users the quota is keyed
// on the stable forum userId (not the ephemeral sessionId) so it cannot be
// reset by re-doing Turnstile or minting a new session.
const TIER_LIMITS = {
anon: { requests: 10, tokens: 100_000 },
forum: { requests: 25, tokens: 250_000 },
premium: { requests: 100, tokens: 1_000_000 },
};
function tierLimits(tier) {
return TIER_LIMITS[tier] || TIER_LIMITS.anon;
}
// Master switch for the WindowsForum SSO + premium-tier upgrade. Default OFF: the
// whole feature stays dormant and the server behaves exactly as before the upgrade
// (flat 50/500K limits, no premium WinDBG gate, no tier in the session response),
// so nothing about the running site reveals it. Flip WF_SSO_ENABLED=true to launch.
const WF_SSO_ENABLED = process.env.WF_SSO_ENABLED === 'true';
// Gated-preview mode: only allow-listed forum users are recognized, and the
// client hides all anonymous UI — so a deployed-but-gated rollout reveals nothing
// to the public. Injected into the served HTML for the client to read.
const WF_SSO_PREVIEW = process.env.WF_SSO_PREVIEW === 'true';
// Optional allow-list of forum user IDs permitted to establish an SSO session
// (defense-in-depth; the forum /sso/whoami also gates token minting). Empty =
// no restriction. e.g. WF_SSO_ALLOWED_UIDS=1 limits SSO to user id 1.
const WF_SSO_ALLOWED_UIDS = (process.env.WF_SSO_ALLOWED_UIDS || '')
.split(',')
.map((s) => s.trim())
// Strict decimal digits only: bare Number() would accept '0x10'/'1e3'/'0b101'
// as UIDs, silently allowlisting ids the operator never typed.
.filter((s) => /^\d+$/.test(s))
.map((s) => Number(s))
.filter((n) => Number.isInteger(n) && n > 0);
// Deny-by-default gate. An unset/blank/typo'd allow-list parses to [] and must NOT
// silently mean "allow everyone" while the feature is gated. With an allow-list
// set, only those UIDs pass; with none set, forum members pass ONLY once preview
// mode is off (i.e. an intentional public launch), never as a side effect of a typo.
function isUidAllowed(uid) {
if (!Number.isInteger(uid) || uid <= 0) return false;
return WF_SSO_ALLOWED_UIDS.length ? WF_SSO_ALLOWED_UIDS.includes(uid) : !WF_SSO_PREVIEW;
}
if (WF_SSO_ENABLED && (process.env.WF_SSO_ALLOWED_UIDS || '').trim() !== '' && WF_SSO_ALLOWED_UIDS.length === 0) {
console.error('[SSO] WF_SSO_ALLOWED_UIDS is set but parsed to ZERO valid UIDs — likely a typo; SSO will deny everyone while preview is on.');
}
// Rewrite the runtime SSO flag defaults in the served HTML so the client reads
// the current env values (window.__WF_SSO_ENABLED__/__WF_SSO_PREVIEW__). Applied
// to both the cached production HTML and the dev dynamic-disk path.
function injectSsoFlags(html) {
return html
.replace('window.__WF_SSO_ENABLED__ = false;', `window.__WF_SSO_ENABLED__ = ${WF_SSO_ENABLED};`)
.replace('window.__WF_SSO_PREVIEW__ = false;', `window.__WF_SSO_PREVIEW__ = ${WF_SSO_PREVIEW};`);
}
// Shared HMAC secret with the WindowsForum /sso/whoami bridge (XenForo
// $config['wfSsoSecret']). Optional: when unset, SSO is disabled and the app
// behaves exactly as before (anonymous Turnstile sessions only).
const WF_SSO_SECRET = process.env.WF_SSO_SECRET || '';
const WF_SSO_ISSUER = 'windowsforum.com';
const WF_SSO_AUDIENCE = 'bsod';
const WF_SSO_MAX_AGE_MS = 5 * 60 * 1000; // reject tokens older than this regardless of exp
const WF_SSO_NONCE_TTL_SECONDS = 10 * 60; // single-use window for a token's jti
const usedSsoNonces = new Map(); // jti -> expiresAt (pruned by the periodic sweep)
// An elevated tier (forum/premium) is only honored for this long after the SSO
// exchange that established it. The session itself may live up to SESSION_EXPIRY,
// but premium privileges expire independently so a cancelled/refunded/expired
// forum membership cannot retain premium indefinitely on a long-open tab. The
// client silently re-verifies (whoami+exchange) on an interval below this.
const PREMIUM_REVERIFY_MS = 30 * 60 * 1000; // 30 minutes
if (process.env.NODE_ENV === 'production' && !WF_SSO_SECRET) {
console.warn('[SSO] WF_SSO_SECRET not configured — WindowsForum single sign-on is disabled.');
}
// Track which hashes/jobs were proven by a session uploading the corresponding file.
const sessionHashOwnership = new Map(); // sessionId -> Map(hash -> timestamp)
const winDbgJobOwnership = new Map(); // uid -> { sessionId, fileHash, timestamp }
const OWNERSHIP_EXPIRY = SESSION_EXPIRY;
// External API jobs are stateless signed tokens (server/externalJobs.js): any
// instance answers a status poll by asking the upstream WinDBG service.
const EXTERNAL_JOB_TTL_MS = readPositiveInt('EXTERNAL_JOB_TTL_SECONDS', 2 * 60 * 60) * 1000;
const EXTERNAL_JOB_DEADLINE_SECONDS = readPositiveInt('EXTERNAL_JOB_DEADLINE_SECONDS',
15 * 60
);
// A forum worker that loses the 202 and resubmits the same dump gets the same
// uid back (per instance; a resubmission landing elsewhere starts another run).
const recentExternalSubmissions = new Map(); // fileHash -> { uid, expiresAt }
async function cacheExternalWinDbgAnalysis(fileHash, analysis) {
return await setCachedAnalysis(fileHash, {
windbgOutput: analysis.analysisText,
analysisSignalText: analysis.analysisSignalText,
structured: analysis.structured,
timestamp: Date.now()
});
}
// File ownership ("this session uploaded bytes hashing to X") gates cached
// analysis reads (issue #40). The proof is the signed file handle the upload
// returned; the per-instance map only serves clients that predate handles.
function markSessionHash(sessionId, hash) {
if (!sessionId || !hash || !HASH_RE.test(hash)) return;
let hashes = sessionHashOwnership.get(sessionId);
if (!hashes) {
hashes = new Map();
sessionHashOwnership.set(sessionId, hashes);
}
hashes.set(hash, Date.now());
}
function sessionOwnsHash(sessionId, hash, handle) {
if (handle && fileHandleCodec.verify(handle, { fileHash: hash, sessionId })) return true;
const timestamp = sessionHashOwnership.get(sessionId)?.get(hash);
return timestamp !== undefined && Date.now() - timestamp <= OWNERSHIP_EXPIRY;
}
function markWinDbgJob(sessionId, uid, upstreamJobId, dumpType, fileSizeBytes) {
if (!sessionId || !uid) return;
const existing = winDbgJobOwnership.get(uid);
const sessions = new Set(existing?.sessions || []);
sessions.add(sessionId);
winDbgJobOwnership.set(uid, { sessions: [...sessions], upstreamJobId, dumpType, fileSizeBytes, timestamp: Date.now() });
markSessionHash(sessionId, uid);
}
// Browser upload submits answer within the response budget (issue #276).
// Submits still running after their 504 hold the dump in memory, so they
// count against the same per-instance cap as the route slots (issue #314).
const WINDBG_UPLOAD_MAX_CONCURRENT = 2;
const windbgUploadSubmitter = createWinDbgUploadSubmitter({
responseBudgetMs: WINDBG_UPLOAD_RESPONSE_BUDGET_MS,
retainMs: OWNERSHIP_EXPIRY,
maxInFlight: WINDBG_UPLOAD_MAX_CONCURRENT,
// An ambiguous submit failure holds the dump for the window (issue #328).
isUnconfirmedFailure: isUnconfirmedSubmitFailure,
onLateResult: (uid, result) => log.warn('windbg.upload.late_job', {
uid: uid.substring(0, 12),
jobId: String(result?.job_id || '').slice(0, 100)
}),
onLateError: (uid, error) => log.warn('windbg.upload.late_fail', {
uid: uid.substring(0, 12),
...windbgFailureLogFields(error)
})
});
// Refuses a new dump at the submit cap before its body is read or a limiter
// slot is spent; a retry joining its own submit passes (issue #338).
const windbgUploadCapGate = createWinDbgUploadCapGate({ submitter: windbgUploadSubmitter });
// /api/analyze submits answer within the same budget; the reuse entry is
// written when the submit settles, even after the timeout answer (issue #315).
const EXTERNAL_ANALYZE_MAX_CONCURRENT = 2;
// An ambiguous submit failure holds the dump for 10 minutes (issue #336).
const externalDumpSubmitter = createExternalWinDbgSubmitter({
responseBudgetMs: WINDBG_UPLOAD_RESPONSE_BUDGET_MS,
maxInFlight: EXTERNAL_ANALYZE_MAX_CONCURRENT,
onLateResult: (fileHash, result) => log.warn('analyze.late_job', {
fileHash: fileHash.substring(0, 12),
upstreamJobId: String(result?.upstreamJobId || '').slice(0, 100)
}),
onLateError: (fileHash, error) => log.warn('analyze.late_fail', {
fileHash: fileHash.substring(0, 12),
...windbgFailureLogFields(error)
})
});
const submitExternalDump = createExternalWinDbgSubmit({
submitter: externalDumpSubmitter,
recent: recentExternalSubmissions,
ttlMs: EXTERNAL_JOB_DEADLINE_SECONDS * 1000
});
// Resolves the upstream WinDBG job for a poll/download: from the signed handle
// on any instance, else from this instance's upload record.
function getOwnedWinDbgJob(sessionId, uid, handle) {
const claims = handle ? fileHandleCodec.verify(handle, { fileHash: uid, sessionId }) : null;
if (claims?.jid) return { upstreamJobId: claims.jid, dumpType: claims.dt, fileSizeBytes: claims.sz };
const job = winDbgJobOwnership.get(uid);
if (!job?.sessions.includes(sessionId) || Date.now() - job.timestamp > OWNERSHIP_EXPIRY) return null;
return job;
}
// ============================================================
// External API Key Authentication
// ============================================================
const BSOD_API_KEY = process.env.BSOD_API_KEY;
if (!BSOD_API_KEY) {
console.warn('WARNING: BSOD_API_KEY not configured - external API access disabled');
}
// Fastify multipart upload compatibility for existing handlers.
const upload = createUploadHandler({
limits: {
fileSize: MAX_RAW_FILE_SIZE,
files: 1
},
fileFilter: (_req, file, cb) => {
// Accept dump files and archives
const ext = getFileExtension(file.originalname);
if (ALLOWED_EXTENSIONS.includes(ext)) {
cb(null, true);
} else {
cb(new Error(`Invalid file type. Allowed: ${ALLOWED_EXTENSIONS.join(', ')}`));
}
}
});
// Bound the per-instance maps periodically
setInterval(() => {
const now = Date.now();
for (const [jti, expiresAt] of usedSsoNonces.entries()) {
if (expiresAt <= now) usedSsoNonces.delete(jti);
}
quotaLedger.prune(now);
providerQuota.prune(now);
for (const [fileHash, entry] of recentExternalSubmissions.entries()) {
if (entry.expiresAt <= now) recentExternalSubmissions.delete(fileHash);
}
externalJobResolver.prune(now);
forumRelated.prune(now);
for (const [sessionId, hashes] of sessionHashOwnership.entries()) {
for (const [hash, timestamp] of hashes.entries()) {
if (now - timestamp > OWNERSHIP_EXPIRY) hashes.delete(hash);
}
if (hashes.size === 0) sessionHashOwnership.delete(sessionId);
}
for (const [uid, data] of winDbgJobOwnership.entries()) {
if (now - data.timestamp > OWNERSHIP_EXPIRY) winDbgJobOwnership.delete(uid);
}
}, 10 * 60 * 1000); // Clean every 10 minutes
// Server-owned AI model selection.
// - getPrimaryModel() re-reads model.cfg per call with a 30s cache so the model can
// be swapped without a redeploy (edit model.cfg in the running container / overlay).
// - FALLBACK_MODEL is a prior-generation stable flash-lite kept as a safety net in case
// a Gemini primary model 404s or is throttled. Provider selection never comes from
// the browser, and DeepSeek never silently crosses over to Gemini.
const FALLBACK_MODEL = 'gemini-2.5-flash-lite';
const MODEL_CFG_PATH = path.join(__dirname, 'model.cfg');
const MODEL_CFG_TTL_MS = 30_000;
function readInitialModel() {
try {
const configured = fs.readFileSync(MODEL_CFG_PATH, 'utf8').trim();
return isSupportedAIModel(configured) ? configured : DEFAULT_GEMINI_MODEL;
} catch {
return DEFAULT_GEMINI_MODEL;
}
}
let _modelCfgCache = { value: readInitialModel(), readAt: 0 };
function getPrimaryModel() {
const now = Date.now();
if (now - _modelCfgCache.readAt >= MODEL_CFG_TTL_MS) {
// Trigger background read so we do not block the Node event loop
_modelCfgCache.readAt = now;
fs.promises.readFile(MODEL_CFG_PATH, 'utf8')
.then(modelConfig => {
const cleaned = modelConfig.trim();
if (isSupportedAIModel(cleaned)) {
_modelCfgCache.value = cleaned;
} else if (cleaned) {
log.warn('ai.model.invalid', { model: cleaned.slice(0, 100) });
}
})
.catch(() => {
// Keep last-good value on error
});
}
return _modelCfgCache.value;
}
// Prime once at startup so the existing startup log is meaningful.
const DEFAULT_MODEL_NAME = getPrimaryModel();
log.info('ai.startup', {
primary: DEFAULT_MODEL_NAME,
provider: getAIProviderForModel(DEFAULT_MODEL_NAME),
geminiFallback: FALLBACK_MODEL
});
// Recognise the error shapes Gemini returns when a model is missing / preview-pulled.
function isModelUnavailableError(err) {
const msg = (err?.message || '') + ' ' + (err?.status || '');
return /\bNOT_FOUND\b|\b404\b|is not found for API version|UNIMPLEMENTED/i.test(msg);
}
function normalizeAIResponse(response, cacheModel) {
return {
text: response?.text ?? '',
usageMetadata: response?.usageMetadata,
modelVersion: response?.modelVersion || cacheModel,
serviceTier: response?.serviceTier ?? null,
candidates: response?.candidates,
cacheModel
};
}
// Dispatch through the provider selected by model.cfg and normalize each provider
// to the response shape already consumed by the rest of the application.
// ---------------------------------------------------------------------------
// OpenAI complimentary-token (free tier) routing helpers.
// Three layers of quota detection: (1) per-response service_tier, (2) the
// org-wide Usage API, (3) this instance's UTC-day token tally when the Usage
// API is unavailable (checked against its share of the daily budget).
// ---------------------------------------------------------------------------
const providerQuota = createProviderQuotaStore({ shards: PROVIDER_QUOTA_SHARDS });
// Local tally, in-flight estimates and the last Usage API read (issue #291).
const openAIFreeBudget = createOpenAIFreeBudget({
dailyCap: OPENAI_FREE_DAILY_TOKEN_CAP,
safetyBuffer: OPENAI_FREE_SAFETY_BUFFER,
shards: PROVIDER_QUOTA_SHARDS
});
function recordOpenAIFreeTokens(tokens) {
openAIFreeBudget.recordTokens(tokens);
}
// Latch the free route off until UTC midnight.
function markOpenAIExhausted() {
providerQuota.markExhausted('openai-free', 'day');
}
// Tally an OpenAI free-tier attempt (returned response or thrown error) and,
// when billed-tier traffic was served, latch the route off: the org quota was
// consumed elsewhere today.
function recordOpenAIFreeAttempt(responseOrError) {
const usage = openAIFreeUsage(responseOrError);
if (usage.used > 0) recordOpenAIFreeTokens(usage.used);
if (usage.billed) {
markOpenAIExhausted();
log.warn('ai.openai.free.billed', { serviceTier: usage.serviceTier });
}
return usage;
}
let openaiUsageApi = { attemptedAt: 0, used: null };
// Org-wide incentive-tier tokens used today via the Usage API. Returns null
// when unavailable (no admin key, API error, throttled) so callers fall back
// to the local tally. Errors are retried at most once per 5 minutes.
async function fetchOpenAIIncentiveTokensUsed() {
if (!OPENAI_ADMIN_KEY) return null;
const now = Date.now();
if (now - openaiUsageApi.attemptedAt < 5 * 60 * 1000) return openaiUsageApi.used;
openaiUsageApi.attemptedAt = now;
// Local spend from here on is not in the total this read returns.
const localAtRefresh = openAIFreeBudget.localUsed();
try {
const startSeconds = Math.floor(Date.UTC(
new Date().getUTCFullYear(), new Date().getUTCMonth(), new Date().getUTCDate()
) / 1000);
const url = `${OPENAI_BASE_URL.replace(/\/+$/, '')}/organization/usage/completions`
+ `?start_time=${startSeconds}&bucket_width=1d&group_by[]=service_tier`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 10_000);
let payload;
try {
const response = await fetch(url, {
headers: { 'Authorization': `Bearer ${OPENAI_ADMIN_KEY}` },
signal: controller.signal
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
payload = await response.json();
} finally {
clearTimeout(timer);
}
let used = 0;
for (const bucket of payload?.data ?? []) {
if (isOpenAIFreeTier(bucket?.service_tier)) {
used += Number(bucket?.input_tokens ?? 0) + Number(bucket?.output_tokens ?? 0);
}
}
openaiUsageApi = { attemptedAt: now, used: Number.isFinite(used) ? used : null };
openAIFreeBudget.setOrgUsage(openaiUsageApi.used, localAtRefresh);
return openaiUsageApi.used;
} catch (error) {
log.warn('ai.openai.free.usage_api_failed', { message: error.message?.slice(0, 120) });
openaiUsageApi.used = null;
openAIFreeBudget.setOrgUsage(null);
return null;
}
}
// Returns a reservation (release it with openAIFreeBudget.release once the
// attempt's usage is recorded) when the free-tier path should be attempted for
// a request with the given projected token usage, else null. The projection
// adds local spend since the last Usage API read and in-flight estimates to
// the cached org total (issue #291).
async function openAIFreeGate(estimatedTokens, fraction = 1) {
if (!OPENAI_API_KEY || providerQuota.isExhausted('openai-free')) return null;
await fetchOpenAIIncentiveTokensUsed();
return openAIFreeBudget.tryReserve(estimatedTokens, { fraction });
}
// Latch the Experiential route off until the end of the UTC hour or day.
function markExperientialExhausted(scope = 'hour') {
providerQuota.markExhausted('experiential-luna', scope);
}
// `fraction` < 1 is how a lower-priority caller yields: the limits are scaled
// down, so it is admitted only while total usage (scans included) is below that
// share of the budget. The scans themselves reserve at 1.
function reserveExperientialQuota(inputTokens, outputTokens, fraction = 1) {
if (!EXPERIENTIAL_API_KEY || EXPERIENTIAL_MODEL !== DEFAULT_EXPERIENTIAL_MODEL) {
return null;
}
const scale = limit => Math.max(1, Math.floor(limit * fraction));
return providerQuota.reserve('experiential-luna', {
inputCost: inputTokens,
outputCost: outputTokens,
dailyInputLimit: scale(EXPERIENTIAL_DAILY_INPUT_LIMIT - EXPERIENTIAL_DAILY_INPUT_BUFFER),
dailyOutputLimit: scale(EXPERIENTIAL_DAILY_OUTPUT_LIMIT - EXPERIENTIAL_DAILY_OUTPUT_BUFFER),
hourlyInputLimit: scale(EXPERIENTIAL_HOURLY_INPUT_LIMIT - EXPERIENTIAL_HOURLY_INPUT_BUFFER),
hourlyOutputLimit: scale(EXPERIENTIAL_HOURLY_OUTPUT_LIMIT - EXPERIENTIAL_HOURLY_OUTPUT_BUFFER)
});
}
function requestTokenEstimate(request) {
const config = request.config || {};
const system = String(config.systemInstruction || '');
const contents = typeof request.contents === 'string'
? request.contents
: JSON.stringify(request.contents ?? '');
const inputTokens = Math.max(1, Math.ceil((system.length + contents.length) / 4));
const configuredMaxOutput = Number(config.maxOutputTokens);
const outputTokens = Number.isFinite(configuredMaxOutput) && configuredMaxOutput > 0
? Math.ceil(configuredMaxOutput)
: AI_MAX_OUTPUT_TOKENS;
return {
inputTokens,
outputTokens,
experientialInputReservation: conservativeChatInputTokenReservation(
config.systemInstruction,
request.contents
)
};
}
// BSOD AI chat (server/bsodAiRoute.js): free providers only. Experiential
// gpt-6-luna first, then the OpenAI free-incentive route; when neither has room
// the chat rests (BSOD_AI_NO_FREE_CAPACITY). It never falls through to the billed
// DeepSeek or OpenRouter legs, and it yields to scans: both legs are admitted
// only while total usage is under BSOD_AI_CHAT_BUDGET_FRACTION of the budget.
// The two legs mirror generateAIContent's; they are kept separate so a change
// here cannot touch the analysis path.
//
// With `onDelta` the answer streams (both providers speak OpenAI-style SSE):
// pieces are passed on as they arrive, `signal` lets the caller stop the
// provider early, and once any text has been delivered a failure ends the call
// instead of falling through to the other provider (its answer would not
// continue the text already on the visitor's screen).
async function generateFreeChat(request, {
deadline = createAIDeadline({ budgetMs: AI_REQUEST_DEADLINE_MS }),
signal: callerSignal,
onDelta
} = {}) {
let delivered = false;
const stream = typeof onDelta === 'function'
? piece => { delivered = true; onDelta(piece); }
: undefined;
const legSignal = signal => (callerSignal ? AbortSignal.any([signal, callerSignal]) : signal);
const estimate = requestTokenEstimate(request);