-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1652 lines (1456 loc) · 59.6 KB
/
Copy pathserver.js
File metadata and controls
1652 lines (1456 loc) · 59.6 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 session = require('express-session');
const http = require('http');
const { rateLimit, ipKeyGenerator } = require('express-rate-limit');
const cors = require('cors');
const https = require('https');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const dns = require("dns");
require('dotenv').config();
const { GatewayWsManager } = require('./lib/gateway-ws');
const securityMiddleware = require('./security');
const { reactions } = require('./lib/db');
const { requireSessionAccess } = require('./lib/session-auth');
const { createReactionsRoutes } = require('./lib/routes/reactions');
const { isForbiddenLinkPreviewHost } = require('./lib/ssrf-validation');
const { validateManifest } = require('./lib/mobile-manifest-validator');
const { buildSessionConfig, setupPassport, registerAuthRoutes, buildIsAuthenticated, getOidcLabel, getReturnTo } = require('./lib/auth-session');
const app = express();
const server = http.createServer(app);
const oidcEnabledByEnv = process.env.OIDC_ENABLED === 'true';
const localAuthEnabledByEnv = process.env.LOCAL_AUTH_ENABLED !== 'false';
const explicitAuthMode = String(process.env.AUTH_MODE || '').trim().toLowerCase();
const authMode = (() => {
if (explicitAuthMode === 'none' || explicitAuthMode === 'local' || explicitAuthMode === 'oidc') {
return explicitAuthMode;
}
if (oidcEnabledByEnv) return 'oidc';
if (localAuthEnabledByEnv) return 'local';
return 'none';
})();
const oidcEnabled = authMode === 'oidc';
const localAuthEnabled = authMode === 'local';
const MAX_CHAT_MESSAGE_LENGTH = (() => {
const parsed = Number(process.env.MAX_CHAT_MESSAGE_LENGTH || 4000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 4000;
})();
const APP_VERSION = (() => {
if (typeof process.env.APP_VERSION === 'string' && process.env.APP_VERSION.trim()) {
return process.env.APP_VERSION.trim();
}
try {
const pkg = require('./package.json');
if (typeof pkg?.version === 'string' && pkg.version.trim()) {
return pkg.version.trim();
}
} catch (error) {
console.warn('Unable to resolve app version from package.json:', error.message);
}
return 'unknown';
})();
const CHAT_DISPLAY_NAME = process.env.CHAT_DISPLAY_NAME || process.env.ASSISTANT_NAME || 'Miso';
const APP_TITLE = process.env.APP_TITLE || `${CHAT_DISPLAY_NAME} Chat`;
const DEFAULT_SESSION_KEY = process.env.OPENCLAW_SESSION_KEY || process.env.MISO_CHAT_SESSION_KEY || process.env.DEFAULT_SESSION_KEY || 'agent:main:main';
const PUSH_NOTIFICATIONS_ENABLED = process.env.PUSH_NOTIFICATIONS_ENABLED === 'true';
const PUSH_VAPID_PUBLIC_KEY = String(process.env.PUSH_VAPID_PUBLIC_KEY || process.env.VAPID_PUBLIC_KEY || '').trim();
const LINK_PREVIEW_TIMEOUT_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_TIMEOUT_MS || 5000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 5000;
})();
const LINK_PREVIEW_MAX_HTML_CHARS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_MAX_HTML_CHARS || 250000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 250000;
})();
const LINK_PREVIEW_USER_AGENT =
process.env.LINK_PREVIEW_USER_AGENT ||
`miso-chat-link-preview/${APP_VERSION} (+https://github.com/misospace/miso-chat)`;
// Per-phase timeout controls for link preview fetches (stricter than overall timeout)
const LINK_PREVIEW_DNS_TIMEOUT_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_DNS_TIMEOUT_MS || 3000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 3000;
})();
const LINK_PREVIEW_CONNECT_TIMEOUT_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_CONNECT_TIMEOUT_MS || 5000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 5000;
})();
const LINK_PREVIEW_HEADERS_TIMEOUT_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_HEADERS_TIMEOUT_MS || 10000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 10000;
})();
const LINK_PREVIEW_BODY_READ_TIMEOUT_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_BODY_READ_TIMEOUT_MS || 30000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 30000;
})();
// Bounded in-memory cache for link preview results (process-level, not shared across instances).
const LINK_PREVIEW_CACHE_MAX_SIZE = (() => {
const parsed = Number(process.env.LINK_PREVIEW_CACHE_MAX_SIZE || 256);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 256;
})();
const LINK_PREVIEW_CACHE_TTL_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_CACHE_TTL_MS || 300000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 300000;
})();
// Per-host concurrency limit for link preview fetches (prevents DNS/network saturation)
const LINK_PREVIEW_MAX_CONCURRENT_PER_HOST = (() => {
const parsed = Number(process.env.LINK_PREVIEW_MAX_CONCURRENT_PER_HOST || 2);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 2;
})();
// Jittered retry on 5xx for link preview fetches
const LINK_PREVIEW_RETRY_MAX_ATTEMPTS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_RETRY_MAX_ATTEMPTS || 2);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 2;
})();
const LINK_PREVIEW_RETRY_BASE_DELAY_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_RETRY_BASE_DELAY_MS || 200);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 200;
})();
const LINK_PREVIEW_RETRY_MAX_DELAY_MS = (() => {
const parsed = Number(process.env.LINK_PREVIEW_RETRY_MAX_DELAY_MS || 1000);
return Number.isFinite(parsed) && parsed > 0 ? parsed : 1000;
})();
const { PreviewCache, PreviewCoalescer, HostConcurrencyLimiter } = require('./lib/link-preview-cache');
const linkPreviewCache = new PreviewCache({ maxSize: LINK_PREVIEW_CACHE_MAX_SIZE, ttlMs: LINK_PREVIEW_CACHE_TTL_MS });
const linkPreviewCoalescer = new PreviewCoalescer();
const linkPreviewHostLimiter = new HostConcurrencyLimiter({ maxConcurrentPerHost: LINK_PREVIEW_MAX_CONCURRENT_PER_HOST });
// Periodic cache cleanup (every 60 seconds) — prevents unbounded memory growth from expired entries.
setInterval(() => {
const removed = linkPreviewCache.cleanup();
if (removed > 0) console.debug(`Link preview cache cleaned up ${removed} expired entries`);
const stats = linkPreviewCache.stats();
console.debug(`Link preview cache: ${stats.activeCount}/${stats.maxSize} active, ${stats.expiredCount} expired`);
}, 60_000).unref?.();
// Mobile OTA update configuration
const MOBILE_UPDATE_REPO_OWNER = process.env.MOBILE_UPDATE_REPO_OWNER || "misospace";
const MOBILE_UPDATE_REPO_NAME = process.env.MOBILE_UPDATE_REPO_NAME || "miso-chat";
const MOBILE_UPDATE_GITHUB_API_URL = "https://api.github.com";
const MOBILE_UPDATE_CACHE_TTL_MS = Number(process.env.MOBILE_UPDATE_CACHE_TTL_MS || 300000); // 5 min default
// In-memory cache: process-level only (not shared across multiple server instances behind LB).
// Each instance maintains its own mobileUpdateCache and TTL independently, so multi-instance
// deployments can serve stale manifests for up to MOBILE_UPDATE_CACHE_TTL_MS (default 5 min).
// For multi-instance deployments, consider using a Redis-backed cache for this path.
let mobileUpdateCache = null;
let mobileUpdateCacheTime = 0;
function decodeHtmlEntities(value) {
return String(value || '')
.replace(/&/gi, '&')
.replace(/"/gi, '"')
.replace(/'/gi, "'")
.replace(/'/gi, "'")
.replace(/</gi, '<')
.replace(/>/gi, '>');
}
function normalizePreviewText(value) {
return decodeHtmlEntities(value).replace(/\s+/g, ' ').trim();
}
function parseTagAttributes(tag) {
const attributes = {};
const attrRegex = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;
let match;
while ((match = attrRegex.exec(tag)) !== null) {
const key = String(match[1] || '').toLowerCase();
const value = match[2] ?? match[3] ?? match[4] ?? '';
if (key && !(key in attributes)) {
attributes[key] = value;
}
}
return attributes;
}
function resolveRelativeUrl(candidate, baseUrl) {
if (!candidate) return '';
try {
return new URL(candidate, baseUrl).toString();
} catch {
return '';
}
}
function extractLinkPreviewData(html, pageUrl) {
const metaMap = new Map();
const metaRegex = /<meta\s+[^>]*>/gi;
let metaMatch;
while ((metaMatch = metaRegex.exec(html)) !== null) {
const attrs = parseTagAttributes(metaMatch[0]);
const key = String(attrs.property || attrs.name || '').toLowerCase().trim();
const rawContent = attrs.content;
if (!key || !rawContent || metaMap.has(key)) continue;
const normalized = normalizePreviewText(rawContent);
if (normalized) metaMap.set(key, normalized);
}
const titleMatch = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
const titleFromTag = titleMatch ? normalizePreviewText(titleMatch[1]) : '';
const canonicalUrl =
resolveRelativeUrl(metaMap.get('og:url') || '', pageUrl)
|| pageUrl;
const imageUrl =
resolveRelativeUrl(metaMap.get('og:image') || '', canonicalUrl)
|| resolveRelativeUrl(metaMap.get('twitter:image') || '', canonicalUrl)
|| '';
const title =
metaMap.get('og:title')
|| metaMap.get('twitter:title')
|| titleFromTag;
const description =
metaMap.get('og:description')
|| metaMap.get('twitter:description')
|| metaMap.get('description')
|| '';
let domain = '';
try {
domain = new URL(canonicalUrl).hostname;
} catch {
domain = '';
}
return {
url: canonicalUrl,
title,
description,
image: imageUrl,
domain,
twitterCard: metaMap.get('twitter:card') || '',
};
}
// SSE clients for real-time gateway event forwarding
const sseClients = new Set();
// Trust proxy for rate limiting behind Envoy
app.set('trust proxy', 1);
const configuredCorsOrigins = String(process.env.CORS_ORIGIN || process.env.ALLOWED_ORIGINS || '')
.split(',')
.map((value) => value.trim())
.filter(Boolean);
const defaultCorsOrigins = [
'capacitor://localhost',
'ionic://localhost',
'app://localhost',
'http://localhost',
'https://localhost',
'http://127.0.0.1',
'https://127.0.0.1',
'http://localhost:3000',
'http://127.0.0.1:3000',
'null',
];
const allowedCorsOrigins = new Set([
...defaultCorsOrigins,
...configuredCorsOrigins,
]);
// Enable CORS for frontend connection
const corsOptions = {
origin(origin, callback) {
// Allow same-origin/server-to-server requests with no Origin header.
if (!origin) return callback(null, true);
if (allowedCorsOrigins.has(origin)) {
return callback(null, true);
}
return callback(new Error('Origin not allowed by CORS'));
},
credentials: true,
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
};
app.use(cors(corsOptions));
// Apply security middleware
securityMiddleware.forEach(middleware => app.use(middleware));
// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
const cfIp = req.headers['cf-connecting-ip'];
if (typeof cfIp === 'string' && cfIp.trim()) {
return ipKeyGenerator(cfIp.trim());
}
const forwarded = req.headers['x-forwarded-for'];
if (typeof forwarded === 'string' && forwarded.trim()) {
return ipKeyGenerator(forwarded.split(',')[0].trim());
}
return ipKeyGenerator(req.ip);
},
skip: (req) => {
// Never rate-limit realtime/bootstrap reads; this can deadlock the UI.
if (req.path === '/events' || req.path === '/health' || req.path === '/config' || req.path === '/auth') {
return true;
}
// Session list/history bootstrap calls are read-paths and must stay available.
if (req.method === 'GET' && (req.path === '/sessions' || req.path.startsWith('/sessions/'))) {
return true;
}
return false;
},
message: { error: 'Too many requests, please try again later.' },
});
const sseLimiter = rateLimit({
windowMs: 60 * 1000,
max: 10,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
const cfIp = req.headers['cf-connecting-ip'];
if (typeof cfIp === 'string' && cfIp.trim()) {
return ipKeyGenerator(cfIp.trim());
}
const forwarded = req.headers['x-forwarded-for'];
if (typeof forwarded === 'string' && forwarded.trim()) {
return ipKeyGenerator(forwarded.split(',')[0].trim());
}
return ipKeyGenerator(req.ip);
},
message: { error: 'Too many SSE connections, please try again later.' },
});
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 20,
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => {
const cfIp = req.headers['cf-connecting-ip'];
if (typeof cfIp === 'string' && cfIp.trim()) {
return ipKeyGenerator(cfIp.trim());
}
const forwarded = req.headers['x-forwarded-for'];
if (typeof forwarded === 'string' && forwarded.trim()) {
return ipKeyGenerator(forwarded.split(',')[0].trim());
}
return ipKeyGenerator(req.ip);
},
skip: () => {
// Skip for auth modes that don't use local auth
return !localAuthEnabled;
},
message: { error: 'Too many authentication attempts, please try again later.' },
});
app.use('/api/', limiter);
// Middleware
app.use(express.json({ limit: '10kb', type: 'application/json' }));
app.use(express.urlencoded({ extended: false, limit: '1kb', type: 'application/x-www-form-urlencoded' }));
// Validate Content-Type for POST/PUT/PATCH requests
const validateContentType = require('./lib/middleware/validate-content-type');
app.use(validateContentType);
// Protect direct access to index file
app.use((req, res, next) => {
if (req.path === '/index.html' && !req.isAuthenticated?.()) {
return res.redirect('/login');
}
next();
});
// Serve static assets, but do NOT auto-serve /index.html at root (keeps auth gate on /)
app.use(express.static('public', { index: false }));
// Serve lib/ JS modules as browser-accessible scripts (e.g. /lib/render-utils.js)
app.use('/lib', express.static(path.join(__dirname, 'lib'), { index: false, extensions: ['js'] }));
// Session configuration (delegated to lib/auth-session.js)
const sessionConfig = buildSessionConfig({ authMode });
const sessionMiddleware = session(sessionConfig);
app.use(sessionMiddleware);
// Passport initialization and strategy setup (delegated to lib/auth-session.js)
const passportInstance = setupPassport({ localAuthEnabled });
app.use(passportInstance.initialize());
app.use(passportInstance.session());
// Auth helpers and routes (delegated to lib/auth-session.js)
const isAuthenticated = buildIsAuthenticated(authMode);
registerAuthRoutes(app, { authMode, localAuthEnabled, oidcEnabled, authLimiter });
// GET /api/mobile/update-manifest - Serve update manifest from latest GitHub release (hardened)
app.get("/api/mobile/update-manifest", async (req, res) => {
const now = Date.now();
if (
mobileUpdateCache
&& mobileUpdateCacheTime
&& (now - mobileUpdateCacheTime) < MOBILE_UPDATE_CACHE_TTL_MS
) {
return res.json(mobileUpdateCache);
}
try {
const resp = await fetch(
`${MOBILE_UPDATE_GITHUB_API_URL}/repos/${MOBILE_UPDATE_REPO_OWNER}/${MOBILE_UPDATE_REPO_NAME}/releases/latest`,
{ headers: { "Accept": "application/vnd.github.v3+json", "User-Agent": `miso-chat-update/${APP_VERSION}` } },
);
if (!resp.ok) {
return res.status(resp.status).json({ error: "Failed to fetch latest release" });
}
const release = await resp.json();
const manifestAsset = (release.assets || []).find((a) => a.name === "update-manifest.json");
if (!manifestAsset) {
return res.status(404).json({ error: "update-manifest.json not found in latest release" });
}
const manifestResp = await fetch(manifestAsset.browser_download_url, { headers: { Accept: "application/json" } });
if (!manifestResp.ok) {
return res.status(manifestResp.status).json({ error: "Failed to fetch update manifest" });
}
const manifest = await manifestResp.json();
// Validate manifest before serving — schema, tag consistency, asset host trust
const validation = validateManifest(manifest, {
releaseTagName: release.tag_name,
repoOwner: MOBILE_UPDATE_REPO_OWNER,
repoName: MOBILE_UPDATE_REPO_NAME,
});
if (!validation.valid) {
console.error("Mobile update manifest validation failed:", validation.errors);
return res.status(400).json({ error: "Invalid update manifest", details: validation.errors });
}
mobileUpdateCache = manifest;
mobileUpdateCacheTime = now;
return res.json(manifest);
} catch (error) {
console.error("Mobile update manifest fetch failed:", error.message || error);
return res.status(502).json({ error: "Unable to retrieve update manifest" });
}
});
// Protected routes
app.get('/', isAuthenticated, (req, res) => res.sendFile(__dirname + '/public/index.html'));
app.get('/api/auth', (req, res) => {
res.setHeader('Cache-Control', 'no-store');
return res.json({
authenticated: authMode === 'none' ? true : req.isAuthenticated(),
user: req.user,
oidc: oidcEnabled,
authMode,
requiresAuth: authMode !== 'none',
});
});
// GET /api/csrf-token — Return current per-session CSRF token (generate if missing).
app.get('/api/csrf-token', isAuthenticated, (req, res) => {
res.setHeader('Cache-Control', 'no-store');
const { generateCsrfToken } = require('./security');
const token = generateCsrfToken(req);
return res.json({ csrfToken: token });
});
let gatewayWsLastError = '';
let gatewayWsLastClose = null;
const GATEWAY_WS_CLIENT_ID = process.env.GATEWAY_WS_CLIENT_ID || 'webchat-ui';
const GATEWAY_WS_CLIENT_MODE = process.env.GATEWAY_WS_CLIENT_MODE || 'webchat';
const GATEWAY_DEVICE_IDENTITY_PATH = process.env.GATEWAY_DEVICE_IDENTITY_PATH || path.join(process.env.HOME || '/home/node', '.openclaw', 'identity', 'device.json');
const GATEWAY_WS_WAIT_CHALLENGE_MS = Number(process.env.GATEWAY_WS_WAIT_CHALLENGE_MS || 1200);
// Minimal default scopes for normal chat/session UI behavior.
// Admin and pairing scopes require explicit opt-in via GATEWAY_ADMIN_SCOPES.
const REQUESTED_GATEWAY_SCOPES = [
'operator.read',
'operator.write',
...(process.env.GATEWAY_ADMIN_SCOPES === 'true'
? ['operator.admin', 'operator.pairing']
: []),
];
const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
let cachedGatewayDeviceIdentity = null;
function base64UrlEncode(buffer) {
return Buffer.from(buffer).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
}
function derivePublicKeyRawFromPem(publicKeyPem) {
const spki = crypto.createPublicKey(publicKeyPem).export({ type: 'spki', format: 'der' });
if (spki.length === ED25519_SPKI_PREFIX.length + 32 && spki.subarray(0, ED25519_SPKI_PREFIX.length).equals(ED25519_SPKI_PREFIX)) {
return spki.subarray(ED25519_SPKI_PREFIX.length);
}
return spki;
}
function buildDeviceAuthPayload({ deviceId, clientId, clientMode, role, scopes, signedAtMs, token, nonce }) {
const scopesList = Array.isArray(scopes) ? scopes : [];
return ['v2', deviceId, clientId, clientMode, role, scopesList.join(','), String(signedAtMs), token || '', nonce].join('|');
}
function fingerprintPublicKeyPem(publicKeyPem) {
const raw = derivePublicKeyRawFromPem(publicKeyPem);
return crypto.createHash('sha256').update(raw).digest('hex');
}
function persistGatewayDeviceIdentity(identity) {
try {
fs.mkdirSync(path.dirname(GATEWAY_DEVICE_IDENTITY_PATH), { recursive: true });
fs.writeFileSync(GATEWAY_DEVICE_IDENTITY_PATH, `${JSON.stringify(identity, null, 2)}\n`, { mode: 0o600 });
try { fs.chmodSync(GATEWAY_DEVICE_IDENTITY_PATH, 0o600); } catch {}
} catch {}
}
function ensureGatewayDeviceIdentity() {
if (cachedGatewayDeviceIdentity !== null) return cachedGatewayDeviceIdentity;
try {
if (fs.existsSync(GATEWAY_DEVICE_IDENTITY_PATH)) {
const raw = fs.readFileSync(GATEWAY_DEVICE_IDENTITY_PATH, 'utf8');
const parsed = JSON.parse(raw);
if (parsed?.deviceId && parsed?.publicKeyPem && parsed?.privateKeyPem) {
const derivedDeviceId = fingerprintPublicKeyPem(parsed.publicKeyPem);
const publicKey = base64UrlEncode(derivePublicKeyRawFromPem(parsed.publicKeyPem));
const deviceId = typeof derivedDeviceId === 'string' && derivedDeviceId ? derivedDeviceId : parsed.deviceId;
if (deviceId !== parsed.deviceId) {
persistGatewayDeviceIdentity({
...parsed,
version: parsed?.version === 1 ? parsed.version : 1,
deviceId,
createdAtMs: typeof parsed?.createdAtMs === 'number' ? parsed.createdAtMs : Date.now(),
});
}
cachedGatewayDeviceIdentity = { deviceId, publicKey, privateKeyPem: parsed.privateKeyPem };
return cachedGatewayDeviceIdentity;
}
}
} catch {}
const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
const publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString();
const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
const deviceId = fingerprintPublicKeyPem(publicKeyPem);
const identity = { version: 1, deviceId, publicKeyPem, privateKeyPem, createdAtMs: Date.now() };
persistGatewayDeviceIdentity(identity);
cachedGatewayDeviceIdentity = { deviceId, publicKey: base64UrlEncode(derivePublicKeyRawFromPem(publicKeyPem)), privateKeyPem };
return cachedGatewayDeviceIdentity;
}
function buildGatewayDeviceAuth({ nonce, scopes }) {
const identity = ensureGatewayDeviceIdentity();
if (!identity || !nonce) return null;
const signedAt = Date.now();
const payload = buildDeviceAuthPayload({
deviceId: identity.deviceId,
clientId: GATEWAY_WS_CLIENT_ID,
clientMode: GATEWAY_WS_CLIENT_MODE,
role: 'operator',
scopes,
signedAtMs: signedAt,
token: GATEWAY_TOKEN,
nonce,
});
const signature = base64UrlEncode(crypto.sign(null, Buffer.from(payload, 'utf8'), crypto.createPrivateKey(identity.privateKeyPem)));
return { id: identity.deviceId, publicKey: identity.publicKey, signature, signedAt, nonce };
}
// Infer GATEWAY_WS_ORIGIN from CORS_ORIGIN if not explicitly set
const configuredGatewayWsOrigin = process.env.GATEWAY_WS_ORIGIN;
const corsOrigin = process.env.CORS_ORIGIN || process.env.ALLOWED_ORIGINS || '';
const firstCorsOrigin = corsOrigin.split(',')[0].trim();
const gatewayWsOrigin = configuredGatewayWsOrigin || firstCorsOrigin || 'http://localhost:3000';
const GATEWAY_URL = process.env.GATEWAY_URL || process.env.OPENCLAW_API_URL || 'http://openclaw.llm.svc.cluster.local:18789';
const GATEWAY_TOKEN = process.env.GATEWAY_TOKEN || process.env.GATEWAY_AUTH_TOKEN || '';
const gatewayWsManager = new GatewayWsManager({
wsUrl: process.env.GATEWAY_WS_URL || 'ws://openclaw.llm.svc.cluster.local:18789',
clientId: GATEWAY_WS_CLIENT_ID,
clientVersion: `miso-chat/${APP_VERSION}`,
clientMode: GATEWAY_WS_CLIENT_MODE,
token: GATEWAY_TOKEN,
role: 'operator',
scopes: REQUESTED_GATEWAY_SCOPES,
waitChallengeMs: GATEWAY_WS_WAIT_CHALLENGE_MS,
buildDeviceAuth: ({ nonce, scopes }) => buildGatewayDeviceAuth({ nonce, scopes }),
headers: {
...(GATEWAY_TOKEN ? { Authorization: `Bearer ${GATEWAY_TOKEN}` } : {}),
...(gatewayWsOrigin ? { Origin: gatewayWsOrigin } : {}),
},
});
gatewayWsManager.on('error', (err) => {
gatewayWsLastError = String(err?.message || err || 'unknown error');
console.error('⚠️ Gateway WS error:', err?.message || err);
});
async function waitForGatewayWsReady(timeoutMs = 1500) {
if (gatewayWsManager?.isConnected?.()) return true;
await new Promise((resolve) => {
let settled = false;
const done = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
gatewayWsManager?.off?.('connected', onConnected);
gatewayWsManager?.off?.('error', onError);
resolve();
};
const onConnected = () => done();
const onError = () => done();
const timer = setTimeout(done, Math.max(50, timeoutMs));
gatewayWsManager?.once?.('connected', onConnected);
gatewayWsManager?.once?.('error', onError);
});
return gatewayWsManager?.isConnected?.() || false;
}
app.get('/api/health', (req, res) => {
const isWsConnected = gatewayWsManager?.isConnected?.() || false;
const reconnectAttempts = gatewayWsManager?.reconnectAttempts || 0;
const pendingRequests = gatewayWsManager?.getPendingRequestCount?.() || 0;
const pendingForRecovery = gatewayWsManager?.getPendingForRecoveryCount?.() || 0;
// Determine realtime health state
let realtimeState = 'disconnected';
if (isWsConnected) {
realtimeState = 'healthy';
} else if (reconnectAttempts > 0) {
realtimeState = 'reconnecting';
} else if (gatewayWsLastError) {
realtimeState = 'degraded';
}
const healthPayload = {
status: 'healthy',
version: APP_VERSION,
timestamp: new Date().toISOString(),
gatewayWs: {
connected: isWsConnected,
connecting: gatewayWsManager?.connecting || false,
reconnectAttempts,
pendingRequests,
pendingForRecovery,
lastError: gatewayWsLastError || null,
lastClose: gatewayWsLastClose || null,
},
realtime: {
state: realtimeState,
message: isWsConnected
? 'Gateway WebSocket connected'
: reconnectAttempts > 0
? `Reconnecting (attempt ${reconnectAttempts})`
: gatewayWsLastError
? `Error: ${gatewayWsLastError}`
: 'Gateway WebSocket not connected',
},
};
res.json(healthPayload);
});
function extractTextParts(parts) {
return (Array.isArray(parts) ? parts : [])
.map((part) => {
if (typeof part === 'string') return part;
if (!part || typeof part !== 'object') return '';
// Gateways use several spellings for these internal messages. Never
// surface their arguments or results as though they were chat text.
const type = String(part.type || '').replace(/[\s_-]/g, '').toLowerCase();
if (type === 'toolcall' || type === 'toolresult' || type === 'tooluse' || type === 'functioncall' || type === 'functionresult') return '';
if (part?.type === 'text' && typeof part?.text === 'string') return part.text;
if (typeof part?.text === 'string') return part.text;
if (typeof part?.content === 'string') return part.content;
return '';
})
.filter(Boolean)
.join('\n')
.trim();
}
function extractUserFacingAssistantText(value) {
if (typeof value === 'string') return value.trim();
if (!value || typeof value !== 'object') return '';
if (Array.isArray(value)) return extractTextParts(value);
if (Array.isArray(value.content)) return extractTextParts(value.content);
if (Array.isArray(value.parts)) return extractTextParts(value.parts);
if (typeof value.content === 'string') return value.content.trim();
if (typeof value.text === 'string') return value.text.trim();
if (typeof value.message === 'string') return value.message.trim();
if (value.response && typeof value.response === 'object') {
const nested = extractUserFacingAssistantText(value.response);
if (nested) return nested;
}
if (typeof value.responseText === 'string') return value.responseText.trim();
return '';
}
function normalizeSessionItems(...sources) {
const candidates = [];
for (const source of sources) {
if (Array.isArray(source)) candidates.push(...source);
}
return candidates
.map((item) => {
if (typeof item === 'string') {
return {
sessionKey: item,
displayName: inferAgentNameFromKey(item) || item,
provider: 'openclaw',
};
}
const sessionKey = String(
item?.sessionKey
|| item?.key
|| item?.id
|| item?.session
|| ''
).trim();
if (!sessionKey) return null;
const inferredAgentName = inferAgentNameFromKey(sessionKey);
const title = String(item?.title || item?.name || '').trim();
const agentName = String(item?.agentName || item?.agent?.name || inferredAgentName || '').trim();
const displayName = String(
item?.displayName
|| title
|| agentName
|| inferredAgentName
|| sessionKey
).trim();
return {
...item,
sessionKey,
title,
agentName,
displayName,
provider: item?.provider || 'openclaw',
};
})
.filter(Boolean)
.filter((item, index, arr) => arr.findIndex((other) => other.sessionKey === item.sessionKey) === index);
}
app.get('/api/assistant-identity', isAuthenticated, async (req, res) => {
try {
const sessionKey = String(req.query.sessionKey || '').trim();
if (!sessionKey) return res.status(400).json({ error: 'sessionKey required' });
const result = await gatewayInvoke('agent_identity_get', { sessionKey });
const payload = unwrapToolResult(result);
return res.json({
assistantName: payload?.name || payload?.assistantName || payload?.identity?.name || null,
assistantAvatar: payload?.avatarUrl || payload?.assistantAvatar || payload?.identity?.avatarUrl || null,
assistantAgentId: payload?.agentId || payload?.assistantAgentId || payload?.id || null,
});
} catch (error) {
console.error('Error fetching assistant identity:', error.message);
return res.status(502).json({ error: error.message || 'Failed to fetch assistant identity' });
}
});
app.get('/api/agents', isAuthenticated, async (_req, res) => {
try {
const result = await gatewayInvoke('agents_list', {});
const payload = unwrapToolResult(result);
const agents = Array.isArray(payload?.agents) ? payload.agents : Array.isArray(payload) ? payload : [];
return res.json({ agents });
} catch (error) {
console.error('Error fetching agents list:', error.message);
return res.status(502).json({ error: error.message || 'Failed to fetch agents list' });
}
});
app.get('/api/sessions', isAuthenticated, async (req, res) => {
res.setHeader('Cache-Control', 'no-cache, must-revalidate');
try {
if (await waitForGatewayWsReady()) {
try {
const frame = await gatewayWsManager.send('sessions.list', { includeLastMessage: true, includeDerivedTitles: true }, 10);
const payload = frame?.result ?? frame?.payload ?? frame?.data ?? frame;
const sessions = normalizeSessionItems(
payload,
payload?.sessions,
payload?.items,
frame?.sessions,
frame?.items,
);
if (sessions.length > 0) {
return res.json({ sessions });
}
} catch (wsErr) {
console.warn('sessions.list via WS failed, trying HTTP fallback:', wsErr.message || wsErr);
}
}
const listSessionsResult = await gatewayInvoke('sessions_list', { includeLastMessage: true, includeDerivedTitles: true });
const payload = unwrapToolResult(listSessionsResult);
const sessions = normalizeSessionItems(
payload,
payload?.sessions,
payload?.items,
listSessionsResult?.sessions,
listSessionsResult?.items,
);
return res.json({ sessions });
} catch (error) {
if (process.env.NODE_ENV === 'development') {
return res.json({
sessions: [{
sessionKey: DEFAULT_SESSION_KEY,
displayName: inferAgentNameFromKey(DEFAULT_SESSION_KEY) || DEFAULT_SESSION_KEY,
provider: 'openclaw',
fallback: true,
}],
});
}
console.error('Error listing sessions:', error.message || error);
return res.status(500).json({ error: 'Failed to list sessions' });
}
});
app.get('/api/sessions/:key/history', isAuthenticated, requireSessionAccess(authMode), async (req, res) => {
res.setHeader('Cache-Control', 'no-cache, must-revalidate');
try {
const sessionKey = String(req.params.key || '').trim();
if (!sessionKey) {
return res.status(400).json({ error: 'session key is required' });
}
let payload = null;
let historyResult = null;
if (await waitForGatewayWsReady()) {
try {
const frame = await gatewayWsManager.send('chat.history', { sessionKey, limit: 100 }, 10);
payload = frame?.result ?? frame?.payload ?? frame?.data ?? frame;
} catch (wsErr) {
console.warn('sessions.history via WS failed, trying HTTP fallback:', wsErr.message || wsErr);
}
}
if (!payload) {
historyResult = await gatewayInvoke('sessions_history', { sessionKey, limit: 100 });
payload = unwrapToolResult(historyResult);
}
const messages = (Array.isArray(payload?.messages)
? payload.messages
: Array.isArray(payload)
? payload
: Array.isArray(historyResult?.messages)
? historyResult.messages
: []).map((msg) => {
const role = String(msg?.role || msg?.sender || 'assistant').toLowerCase();
const content = extractUserFacingAssistantText(msg);
return {
...msg,
role,
content,
timestamp: msg?.timestamp || msg?.createdAt || msg?.time || null,
model: msg?.model || msg?.response?.model || null,
toolCalls: [],
};
}).filter((msg) => {
if (msg.role !== 'assistant') return true;
return Boolean(String(msg.content || '').trim());
});
return res.json({ sessionKey, messages });
} catch (error) {
console.error('Error fetching session history:', error.message || error);
return res.status(500).json({ error: 'Failed to fetch session history' });
}
});
app.post('/api/sessions/:key/send', isAuthenticated, requireSessionAccess(authMode), async (req, res) => {
try {
const sessionKey = String(req.params.key || '').trim();
const text = String(req.body?.text || req.body?.message || '').trim();
if (!sessionKey) {
return res.status(400).json({ error: 'session key is required' });
}
if (!text) {
return res.status(400).json({ error: 'text is required' });
}
if (text.length > MAX_CHAT_MESSAGE_LENGTH) {
return res.status(400).json({ error: `message exceeds max length (${MAX_CHAT_MESSAGE_LENGTH})` });
}
let payload = null;
let result = null;
if (await waitForGatewayWsReady()) {
try {
const frame = await gatewayWsManager.send('chat.send', { sessionKey, message: text, deliver: false, idempotencyKey: gatewayWsManager.createRequestId('msg') }, 30);
payload = frame?.result ?? frame?.payload ?? frame?.data ?? frame;
} catch (wsErr) {
console.warn('chat.send via WS failed, trying HTTP fallback:', wsErr.message || wsErr);
}
}
if (!payload) {
result = await gatewayInvoke('sessions_send', { sessionKey, message: text });
payload = unwrapToolResult(result);
}
const body = payload && typeof payload === 'object' ? payload : { result: payload ?? result };
const responseText = extractUserFacingAssistantText(body?.response) || extractUserFacingAssistantText(body);
return res.json({ ok: true, success: true, ...body, responseText });
} catch (error) {
console.error('Error sending chat message:', error.message || error);
return res.status(500).json({ error: 'Failed to send message' });
}
});
app.post('/api/sessions/:key/send-stream', isAuthenticated, requireSessionAccess(authMode), async (req, res) => {
try {
const sessionKey = String(req.params.key || '').trim();
const text = String(req.body?.text || req.body?.message || '').trim();
if (!sessionKey) return res.status(400).json({ error: 'session key is required' });
if (!text) return res.status(400).json({ error: 'text is required' });
let payload = null;
let result = null;
if (gatewayWsManager?.isConnected?.()) {
try {
const frame = await gatewayWsManager.send('chat.send', { sessionKey, message: text, deliver: false, idempotencyKey: gatewayWsManager.createRequestId('msg') }, 30);
payload = frame?.result ?? frame?.payload ?? frame?.data ?? frame;
} catch (wsErr) {
console.warn('chat.send stream shim via WS failed, trying HTTP fallback:', wsErr.message || wsErr);
}
}
if (!payload) {
result = await gatewayInvoke('sessions_send', { sessionKey, message: text });
payload = unwrapToolResult(result);
}
const responseText = extractUserFacingAssistantText(payload?.response) || extractUserFacingAssistantText(payload);
const toolCalls = Array.isArray(payload?.toolCalls) ? payload.toolCalls : [];
const model = payload?.response?.model || payload?.model || null;
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.setHeader('X-Accel-Buffering', 'no');
if (typeof res.flushHeaders === 'function') res.flushHeaders();
res.write(`data: ${JSON.stringify({ type: 'message', text: responseText, toolCalls, model })}\n\n`);
res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
res.end();
} catch (error) {
console.error('Error streaming chat message:', error.message || error);
res.setHeader('Content-Type', 'text/event-stream');
res.write(`data: ${JSON.stringify({ type: 'error', error: error.message || 'Failed to send message' })}\n\n`);
res.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
res.end();
}
});
// GET /api/link-preview?url=https://example.com - Fetch OG metadata for inline link cards
app.get('/api/link-preview', isAuthenticated, async (req, res) => {
const rawUrl = typeof req.query?.url === 'string' ? req.query.url.trim() : '';
if (!rawUrl) {
return res.status(400).json({ error: 'url query parameter is required' });
}
let targetUrl;
try {
targetUrl = new URL(rawUrl);
} catch {
return res.status(400).json({ error: 'Invalid URL' });
}
if (!['http:', 'https:'].includes(targetUrl.protocol)) {
return res.status(400).json({ error: 'Only http(s) URLs are supported' });
}