@clagentic/console 1.7.0 → 1.8.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.js +198 -2542
- package/lib/build-sha.json +4 -0
- package/lib/cli/daemon-launch.js +797 -0
- package/lib/cli/ipc-subcommands.js +186 -0
- package/lib/cli/menus.js +849 -0
- package/lib/cli/net-detect.js +209 -0
- package/lib/cli/tui.js +589 -0
- package/lib/daemon.js +15 -6
- package/lib/memory-shed.js +81 -2
- package/lib/pages.js +13 -17
- package/lib/project-connection.js +13 -0
- package/lib/project-loop.js +4 -0
- package/lib/project-sessions.js +9 -3
- package/lib/project.js +3 -2
- package/lib/public/css/diagnostics.css +29 -1
- package/lib/public/css/home-hub.css +10 -0
- package/lib/public/css/overlays.css +19 -0
- package/lib/public/index.html +12 -11
- package/lib/public/manifest.json +1 -1
- package/lib/public/modules/app-connection.js +150 -4
- package/lib/public/modules/app-history-replay.js +155 -0
- package/lib/public/modules/app-home-hub.js +24 -14
- package/lib/public/modules/app-messages.js +1246 -1469
- package/lib/public/modules/app-notifications.js +4 -4
- package/lib/public/modules/app-rate-limit.js +128 -27
- package/lib/public/modules/command-palette.js +11 -22
- package/lib/public/modules/context-sources.js +1 -6
- package/lib/public/modules/filebrowser.js +25 -13
- package/lib/public/modules/input.js +47 -12
- package/lib/public/modules/mcp-ui.js +2 -2
- package/lib/public/modules/notifications.js +22 -1
- package/lib/public/modules/playbook.js +6 -6
- package/lib/public/modules/project-settings.js +5 -13
- package/lib/public/modules/qrcode.js +2 -2
- package/lib/public/modules/rate-limit-state.js +133 -0
- package/lib/public/modules/relative-time.js +27 -0
- package/lib/public/modules/scheduler-history.js +1 -5
- package/lib/public/modules/server-settings.js +28 -15
- package/lib/public/modules/sidebar-mobile.js +8 -3
- package/lib/public/modules/sidebar-projects.js +1 -1
- package/lib/public/modules/sidebar-sessions.js +1 -15
- package/lib/public/modules/sidebar.js +3 -3
- package/lib/public/modules/utils.js +1 -0
- package/lib/public/sw.js +24 -4
- package/lib/sdk-bridge.js +22 -0
- package/lib/sdk-message-processor.js +27 -1
- package/lib/server-auth.js +48 -2
- package/lib/server-palette.js +17 -1
- package/lib/server-settings.js +70 -4
- package/lib/server.js +200 -4
- package/lib/session-search.js +20 -5
- package/lib/sessions.js +84 -3
- package/lib/smtp.js +6 -6
- package/lib/yoke/adapters/codex.js +1 -1
- package/package.json +4 -2
- package/scripts/install-local-test.js +97 -0
- package/scripts/verify-installed-build.js +80 -0
- package/scripts/write-build-sha.js +53 -0
package/lib/server-auth.js
CHANGED
|
@@ -112,6 +112,50 @@ function attachAuth(ctx) {
|
|
|
112
112
|
return !!getMultiUserFromReq(req);
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
+
// --- WS upgrade ticket (lr-de5fcb) ---
|
|
116
|
+
// The relay_auth_user session cookie is HttpOnly (unreadable by JS) and,
|
|
117
|
+
// per MILLER's diagnosis (lr-de5fcb comment #1), a mobile browser does not
|
|
118
|
+
// reliably attach a SameSite=Lax cookie to a script-initiated WebSocket
|
|
119
|
+
// upgrade. A short-TTL, single-use ticket gives the client a non-cookie
|
|
120
|
+
// credential it CAN read (returned as a JSON body from an authenticated
|
|
121
|
+
// HTTP request, which mobile does attach the cookie to) and pass on the
|
|
122
|
+
// upgrade via Sec-WebSocket-Protocol instead. The ticket is never the
|
|
123
|
+
// session token itself — it is a fresh opaque value bound to a userId,
|
|
124
|
+
// consumed on first use, so a leaked ticket has a small blast radius.
|
|
125
|
+
var WS_TICKET_TTL_MS = 30 * 1000;
|
|
126
|
+
var wsTickets = {}; // ticket -> { userId, expiresAt }
|
|
127
|
+
|
|
128
|
+
function mintWsTicket(userId) {
|
|
129
|
+
var ticket = crypto.randomBytes(24).toString("hex");
|
|
130
|
+
wsTickets[ticket] = { userId: userId, expiresAt: Date.now() + WS_TICKET_TTL_MS };
|
|
131
|
+
return ticket;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Validates and consumes a ticket. Returns the bound user on success, or
|
|
135
|
+
// null on missing/expired/already-used/unknown-user. Single-use: the
|
|
136
|
+
// ticket is deleted unconditionally on first lookup, so a second call
|
|
137
|
+
// with the same ticket always returns null — this bounds replay even
|
|
138
|
+
// within the TTL window, not just after it.
|
|
139
|
+
function consumeWsTicket(ticket) {
|
|
140
|
+
if (!ticket) return null;
|
|
141
|
+
var entry = wsTickets[ticket];
|
|
142
|
+
if (!entry) return null;
|
|
143
|
+
delete wsTickets[ticket]; // single-use regardless of outcome below
|
|
144
|
+
if (Date.now() > entry.expiresAt) return null;
|
|
145
|
+
var user = users.findUserById(entry.userId);
|
|
146
|
+
return user || null;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// Periodic sweep so an unused, expired ticket doesn't linger in memory
|
|
150
|
+
// forever for a client that fetched one and never opened the socket.
|
|
151
|
+
var wsTicketSweepInterval = setInterval(function () {
|
|
152
|
+
var now = Date.now();
|
|
153
|
+
for (var t in wsTickets) {
|
|
154
|
+
if (wsTickets[t].expiresAt < now) delete wsTickets[t];
|
|
155
|
+
}
|
|
156
|
+
}, WS_TICKET_TTL_MS);
|
|
157
|
+
if (wsTicketSweepInterval.unref) wsTicketSweepInterval.unref();
|
|
158
|
+
|
|
115
159
|
function revokeUserTokens(userId) {
|
|
116
160
|
var changed = false;
|
|
117
161
|
for (var token in multiUserTokens) {
|
|
@@ -715,10 +759,10 @@ function attachAuth(ctx) {
|
|
|
715
759
|
var validation = users.validateInvite(inviteCode);
|
|
716
760
|
if (!validation.valid) {
|
|
717
761
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
718
|
-
res.end('<!DOCTYPE html><html><head><title>Clagentic:Console</title>' +
|
|
762
|
+
res.end('<!DOCTYPE html><html><head><title>Clagentic: Console</title>' +
|
|
719
763
|
'<style>body{background:#2F2E2B;color:#E8E5DE;font-family:system-ui;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0}' +
|
|
720
764
|
'.c{text-align:center;max-width:360px;padding:20px}h1{color:#DA7756;margin-bottom:16px}p{color:#908B81}</style></head>' +
|
|
721
|
-
'<body><div class="c"><h1>Clagentic:Console</h1><p>' + (validation.error === "Invite expired" ? "This invite link has expired." : validation.error === "Invite already used" ? "This invite link has already been used." : "Invalid invite link.") + '</p></div></body></html>');
|
|
765
|
+
'<body><div class="c"><h1>Clagentic: Console</h1><p>' + (validation.error === "Invite expired" ? "This invite link has expired." : validation.error === "Invite already used" ? "This invite link has already been used." : "Invalid invite link.") + '</p></div></body></html>');
|
|
722
766
|
return true;
|
|
723
767
|
}
|
|
724
768
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
@@ -741,6 +785,8 @@ function attachAuth(ctx) {
|
|
|
741
785
|
createMultiUserSession: createMultiUserSession,
|
|
742
786
|
isUserLockedOut: isUserLockedOut,
|
|
743
787
|
unlockUser: unlockUser,
|
|
788
|
+
mintWsTicket: mintWsTicket,
|
|
789
|
+
consumeWsTicket: consumeWsTicket,
|
|
744
790
|
};
|
|
745
791
|
}
|
|
746
792
|
|
package/lib/server-palette.js
CHANGED
|
@@ -52,6 +52,15 @@ function attachPalette(ctx) {
|
|
|
52
52
|
} else {
|
|
53
53
|
// Search mode: BM25 ranked search across all sessions
|
|
54
54
|
var projectSessions = [];
|
|
55
|
+
// lr-a3e175: map each accessible session (by object identity) to its
|
|
56
|
+
// owning sm so searchPalette can stream history from disk
|
|
57
|
+
// (readSessionHistoryFromDisk) instead of reading the possibly-
|
|
58
|
+
// unloaded/trimmed session.history heap array directly — mirrors the
|
|
59
|
+
// lr-2ea2a7 streaming-search precedent in
|
|
60
|
+
// sm.searchSessions/searchSessionContent. Keyed by object identity
|
|
61
|
+
// (not localId) since localId is only unique within a single project's
|
|
62
|
+
// sm and would otherwise collide across projects.
|
|
63
|
+
var smBySession = new Map();
|
|
55
64
|
projects.forEach(function (pCtx, pSlug) {
|
|
56
65
|
var status = pCtx.getStatus();
|
|
57
66
|
if (status.isWorktree) return;
|
|
@@ -66,6 +75,7 @@ function attachPalette(ctx) {
|
|
|
66
75
|
var sAccess = onGetProjectAccess ? onGetProjectAccess(pSlug) : null;
|
|
67
76
|
if (!users.canAccessSession(paletteUser.id, session, sAccess)) return;
|
|
68
77
|
}
|
|
78
|
+
smBySession.set(session, pCtx.sm);
|
|
69
79
|
accessibleSessions.push(session);
|
|
70
80
|
});
|
|
71
81
|
if (accessibleSessions.length > 0) {
|
|
@@ -77,7 +87,13 @@ function attachPalette(ctx) {
|
|
|
77
87
|
});
|
|
78
88
|
}
|
|
79
89
|
});
|
|
80
|
-
pResults = sessionSearch.searchPalette(projectSessions, pQuery, {
|
|
90
|
+
pResults = sessionSearch.searchPalette(projectSessions, pQuery, {
|
|
91
|
+
maxResults: 30,
|
|
92
|
+
getHistory: function (session) {
|
|
93
|
+
var ownerSm = smBySession.get(session);
|
|
94
|
+
return ownerSm ? ownerSm.readSessionHistoryFromDisk(session) : session.history;
|
|
95
|
+
}
|
|
96
|
+
});
|
|
81
97
|
}
|
|
82
98
|
|
|
83
99
|
res.writeHead(200, { "Content-Type": "application/json" });
|
package/lib/server-settings.js
CHANGED
|
@@ -3,6 +3,14 @@ var path = require("path");
|
|
|
3
3
|
var audit = require("./audit");
|
|
4
4
|
var projectModule = require("./project");
|
|
5
5
|
|
|
6
|
+
// Action-string convention (see lib/audit.js and lib/server-admin.js):
|
|
7
|
+
// "resource.verb", dot-separated. Logged on BOTH success and failure paths
|
|
8
|
+
// for custom-emoji upload/delete — the class of bug this closes (lr-fc71)
|
|
9
|
+
// is a silent no-op that left zero runtime trace and required a live
|
|
10
|
+
// browser repro to diagnose (MILLER bounce off PR #303).
|
|
11
|
+
var CUSTOM_EMOJI_UPLOAD_ACTION = "custom_emoji.upload";
|
|
12
|
+
var CUSTOM_EMOJI_DELETE_ACTION = "custom_emoji.delete";
|
|
13
|
+
|
|
6
14
|
// Validate a custom-emoji slug: lowercase alphanumeric, hyphen, underscore, 1-64 chars.
|
|
7
15
|
// Must pass BEFORE any filesystem operation (structurally excludes . and /).
|
|
8
16
|
var SLUG_RE = /^[a-z0-9_-]{1,64}$/;
|
|
@@ -469,7 +477,15 @@ function attachSettings(ctx) {
|
|
|
469
477
|
if (postSize <= postMaxSize) postChunks.push(chunk);
|
|
470
478
|
});
|
|
471
479
|
req.on("end", function () {
|
|
480
|
+
// actorId/actorName come from the auth gate above (muPost) —
|
|
481
|
+
// resolved once per request so every audit entry below shares them.
|
|
482
|
+
var postActor = { actorId: muPost.id, actorName: muPost.username };
|
|
483
|
+
|
|
472
484
|
if (postSize > postMaxSize) {
|
|
485
|
+
audit.log(CUSTOM_EMOJI_UPLOAD_ACTION, Object.assign({}, postActor, {
|
|
486
|
+
target: postSlug,
|
|
487
|
+
metadata: { status: 413, size: postSize, reason: "file too large" },
|
|
488
|
+
}));
|
|
473
489
|
res.writeHead(413, { "Content-Type": "application/json" });
|
|
474
490
|
res.end('{"error":"File too large (max 512 KB)"}');
|
|
475
491
|
return;
|
|
@@ -484,6 +500,10 @@ function attachSettings(ctx) {
|
|
|
484
500
|
else if (raw[0] === 0x52 && raw[1] === 0x49) ct = "image/webp";
|
|
485
501
|
|
|
486
502
|
if (!ct) {
|
|
503
|
+
audit.log(CUSTOM_EMOJI_UPLOAD_ACTION, Object.assign({}, postActor, {
|
|
504
|
+
target: postSlug,
|
|
505
|
+
metadata: { status: 400, size: postSize, reason: "unsupported image format" },
|
|
506
|
+
}));
|
|
487
507
|
res.writeHead(400, { "Content-Type": "application/json" });
|
|
488
508
|
res.end('{"error":"Unsupported image format"}');
|
|
489
509
|
return;
|
|
@@ -498,6 +518,10 @@ function attachSettings(ctx) {
|
|
|
498
518
|
var candidatePath = path.join(customEmojiDir, postSlug + "." + ext);
|
|
499
519
|
var resolvedCandidate = path.resolve(customEmojiDir, postSlug + "." + ext);
|
|
500
520
|
if (!resolvedCandidate.startsWith(customEmojiDir + path.sep)) {
|
|
521
|
+
audit.log(CUSTOM_EMOJI_UPLOAD_ACTION, Object.assign({}, postActor, {
|
|
522
|
+
target: postSlug,
|
|
523
|
+
metadata: { status: 400, size: postSize, reason: "invalid path" },
|
|
524
|
+
}));
|
|
501
525
|
res.writeHead(400, { "Content-Type": "application/json" });
|
|
502
526
|
res.end('{"error":"Invalid path"}');
|
|
503
527
|
return;
|
|
@@ -516,9 +540,23 @@ function attachSettings(ctx) {
|
|
|
516
540
|
}
|
|
517
541
|
} catch (e) {}
|
|
518
542
|
|
|
519
|
-
|
|
520
|
-
|
|
543
|
+
try {
|
|
544
|
+
fs.writeFileSync(candidatePath, raw);
|
|
545
|
+
try { fs.chmodSync(candidatePath, 0o644); } catch (e) {}
|
|
546
|
+
} catch (e) {
|
|
547
|
+
audit.log(CUSTOM_EMOJI_UPLOAD_ACTION, Object.assign({}, postActor, {
|
|
548
|
+
target: postSlug,
|
|
549
|
+
metadata: { status: 500, size: postSize, reason: "write failed: " + e.message },
|
|
550
|
+
}));
|
|
551
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
552
|
+
res.end('{"error":"Failed to save image"}');
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
521
555
|
|
|
556
|
+
audit.log(CUSTOM_EMOJI_UPLOAD_ACTION, Object.assign({}, postActor, {
|
|
557
|
+
target: postSlug,
|
|
558
|
+
metadata: { status: 200, size: postSize },
|
|
559
|
+
}));
|
|
522
560
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
523
561
|
res.end(JSON.stringify({ ok: true, slug: postSlug, url: "/api/custom-emoji/" + postSlug }));
|
|
524
562
|
});
|
|
@@ -585,12 +623,24 @@ function attachSettings(ctx) {
|
|
|
585
623
|
return true;
|
|
586
624
|
}
|
|
587
625
|
|
|
626
|
+
var delActor = { actorId: muDel.id, actorName: muDel.username };
|
|
627
|
+
|
|
588
628
|
if (!SLUG_RE.test(delSlug)) {
|
|
629
|
+
audit.log(CUSTOM_EMOJI_DELETE_ACTION, Object.assign({}, delActor, {
|
|
630
|
+
target: delSlug,
|
|
631
|
+
metadata: { status: 400, reason: "invalid slug" },
|
|
632
|
+
}));
|
|
589
633
|
res.writeHead(400, { "Content-Type": "application/json" });
|
|
590
634
|
res.end('{"error":"Invalid slug"}');
|
|
591
635
|
return true;
|
|
592
636
|
}
|
|
593
637
|
|
|
638
|
+
// deletedSize/deletedAny distinguish an actual removal from the
|
|
639
|
+
// no-op case (slug valid but no matching file) — the exact class of
|
|
640
|
+
// silent failure this audit entry exists to make diagnosable (lr-fc71).
|
|
641
|
+
var deletedAny = false;
|
|
642
|
+
var deletedSize = null;
|
|
643
|
+
var delError = null;
|
|
594
644
|
try {
|
|
595
645
|
var delFiles = fs.readdirSync(customEmojiDir);
|
|
596
646
|
for (var dfi = 0; dfi < delFiles.length; dfi++) {
|
|
@@ -599,10 +649,26 @@ function attachSettings(ctx) {
|
|
|
599
649
|
if (!CUSTOM_EMOJI_CT[dfExt]) continue;
|
|
600
650
|
if (path.basename(df, "." + dfExt) === delSlug) {
|
|
601
651
|
var safeDelPath = projectModule.safePath(customEmojiDir, df);
|
|
602
|
-
if (safeDelPath)
|
|
652
|
+
if (safeDelPath) {
|
|
653
|
+
try { deletedSize = fs.statSync(safeDelPath).size; } catch (e2) { /* stat failed — omit size */ }
|
|
654
|
+
fs.unlinkSync(safeDelPath);
|
|
655
|
+
deletedAny = true;
|
|
656
|
+
}
|
|
603
657
|
}
|
|
604
658
|
}
|
|
605
|
-
} catch (e) {
|
|
659
|
+
} catch (e) {
|
|
660
|
+
delError = e.message;
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
audit.log(CUSTOM_EMOJI_DELETE_ACTION, Object.assign({}, delActor, {
|
|
664
|
+
target: delSlug,
|
|
665
|
+
metadata: {
|
|
666
|
+
status: 200,
|
|
667
|
+
size: deletedSize,
|
|
668
|
+
deleted: deletedAny,
|
|
669
|
+
reason: delError ? ("directory read failed: " + delError) : (deletedAny ? null : "no matching file (no-op)"),
|
|
670
|
+
},
|
|
671
|
+
}));
|
|
606
672
|
|
|
607
673
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
608
674
|
res.end('{"ok":true}');
|
package/lib/server.js
CHANGED
|
@@ -122,6 +122,28 @@ function extractSlug(urlPath) {
|
|
|
122
122
|
return match ? match[1] : null;
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
// WS_TICKET_SUBPROTOCOL_PREFIX must match the client (app-connection.js
|
|
126
|
+
// connect()): the client offers ['clagentic.auth.' + ticket] as the
|
|
127
|
+
// Sec-WebSocket-Protocol list; this extracts the raw ticket back out.
|
|
128
|
+
var WS_TICKET_SUBPROTOCOL_PREFIX = "clagentic.auth.";
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Extract a ws-ticket (lr-de5fcb) from a raw Sec-WebSocket-Protocol header
|
|
132
|
+
* value. Returns null if the header is absent or carries no ticket-shaped
|
|
133
|
+
* subprotocol entry.
|
|
134
|
+
*/
|
|
135
|
+
function extractWsTicketFromHeader(headerValue) {
|
|
136
|
+
if (!headerValue) return null;
|
|
137
|
+
var entries = headerValue.split(",");
|
|
138
|
+
for (var i = 0; i < entries.length; i++) {
|
|
139
|
+
var entry = entries[i].trim();
|
|
140
|
+
if (entry.indexOf(WS_TICKET_SUBPROTOCOL_PREFIX) === 0) {
|
|
141
|
+
return entry.slice(WS_TICKET_SUBPROTOCOL_PREFIX.length);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
|
|
125
147
|
/**
|
|
126
148
|
* Strip the /p/{slug} prefix from URL path
|
|
127
149
|
*/
|
|
@@ -131,6 +153,67 @@ function stripPrefix(urlPath, slug) {
|
|
|
131
153
|
return rest || "/";
|
|
132
154
|
}
|
|
133
155
|
|
|
156
|
+
// File extensions that identify a project-scoped sub-resource request
|
|
157
|
+
// (script/style/module/data/font asset) as opposed to a top-level document
|
|
158
|
+
// navigation. Used by isAssetOrApiPath() below.
|
|
159
|
+
var ASSET_EXTENSIONS = [
|
|
160
|
+
".js", ".mjs", ".css", ".map", ".json", ".woff", ".woff2", ".ttf", ".eot",
|
|
161
|
+
".svg", ".png", ".jpg", ".jpeg", ".gif", ".webp", ".ico", ".wasm",
|
|
162
|
+
];
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* lr-e33776: classify a project-scoped request path (already stripped of the
|
|
166
|
+
* /p/{slug} prefix, e.g. "/app.js", "/modules/foo.js", "/api/x") as an
|
|
167
|
+
* asset/module/API request rather than a top-level document navigation.
|
|
168
|
+
*
|
|
169
|
+
* Only document-navigation requests (e.g. "/", "/index.html") should ever
|
|
170
|
+
* receive the 200 text/html login page from the unauthed project-route gate
|
|
171
|
+
* — see server.js appHandler around isRequestAuthed(req). A .js/.css/module/
|
|
172
|
+
* API request that falls through to that gate unauthenticated must never get
|
|
173
|
+
* a 200 text/html body: browsers with X-Content-Type-Options: nosniff hard-
|
|
174
|
+
* reject a <script type="module"> load whose response is HTML, breaking app
|
|
175
|
+
* boot (proven root cause of lr-e33776 / the mobile "reconnecting" bug).
|
|
176
|
+
*/
|
|
177
|
+
function isAssetOrApiPath(projectUrlPath) {
|
|
178
|
+
var pathOnly = projectUrlPath.split("?")[0].split("#")[0];
|
|
179
|
+
if (pathOnly.indexOf("/api/") === 0) return true;
|
|
180
|
+
if (pathOnly.indexOf("/modules/") === 0) return true;
|
|
181
|
+
var ext = path.extname(pathOnly);
|
|
182
|
+
return ASSET_EXTENSIONS.indexOf(ext) !== -1;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* lr-2895ea: classify a project-scoped request path (already stripped of the
|
|
187
|
+
* /p/{slug} prefix) as a PUBLIC shell static asset — app.js, style.css, a
|
|
188
|
+
* /modules/*.js chunk, or any other static file servable from lib/public/
|
|
189
|
+
* (fonts, images, source maps, the manifest, etc). These files are byte-
|
|
190
|
+
* identical for every user and carry no per-user data, so serving them to an
|
|
191
|
+
* unauthenticated request is safe.
|
|
192
|
+
*
|
|
193
|
+
* This is intentionally narrower in one respect and identical in another to
|
|
194
|
+
* isAssetOrApiPath(): it EXCLUDES /api/* (never public — per-user/data
|
|
195
|
+
* endpoints must stay behind the auth gate) but otherwise reuses the same
|
|
196
|
+
* extension/prefix allowlist, since every extension in ASSET_EXTENSIONS
|
|
197
|
+
* (js/mjs/css/map/json/fonts/images/wasm) maps 1:1 to a real file under
|
|
198
|
+
* lib/public/ served by serveStatic() — never to project or user data.
|
|
199
|
+
*
|
|
200
|
+
* MECHANISM (MILLER, lr-2895ea, conf 0.9): mobile browsers withhold the
|
|
201
|
+
* SameSite=Lax session cookie on subresource requests (script/style/module
|
|
202
|
+
* loads) even on an authenticated top-level document navigation. Gating
|
|
203
|
+
* these shell assets behind the auth check made every such subresource 401
|
|
204
|
+
* on mobile, so style.css never applied and app.js was nosniff-rejected —
|
|
205
|
+
* the app never booted past the static "Reconnecting" overlay. Desktop
|
|
206
|
+
* escaped because it does send the cookie on subresources. Serving these
|
|
207
|
+
* public files before the gate removes the cookie dependency entirely.
|
|
208
|
+
*/
|
|
209
|
+
function isPublicShellAssetPath(projectUrlPath) {
|
|
210
|
+
var pathOnly = projectUrlPath.split("?")[0].split("#")[0];
|
|
211
|
+
if (pathOnly.indexOf("/api/") === 0) return false;
|
|
212
|
+
if (pathOnly.indexOf("/modules/") === 0) return true;
|
|
213
|
+
var ext = path.extname(pathOnly);
|
|
214
|
+
return ASSET_EXTENSIONS.indexOf(ext) !== -1;
|
|
215
|
+
}
|
|
216
|
+
|
|
134
217
|
/**
|
|
135
218
|
* Create a multi-project server.
|
|
136
219
|
* opts: { tlsOptions, caPath, pinHash, port, debug, dangerouslySkipPermissions }
|
|
@@ -511,6 +594,25 @@ function createServer(opts) {
|
|
|
511
594
|
return;
|
|
512
595
|
}
|
|
513
596
|
|
|
597
|
+
// WS upgrade ticket (lr-de5fcb): mints a short-TTL, single-use, non-cookie
|
|
598
|
+
// credential the client can pass on the /ws upgrade via
|
|
599
|
+
// Sec-WebSocket-Protocol when the SameSite=Lax session cookie isn't
|
|
600
|
+
// attached to the script-initiated upgrade (mobile browsers). Requires
|
|
601
|
+
// the session cookie on THIS request — the ticket is only handed to a
|
|
602
|
+
// client that is already authenticated.
|
|
603
|
+
if (req.method === "GET" && fullUrl === "/api/ws-ticket") {
|
|
604
|
+
var ticketUser = getMultiUserFromReq(req);
|
|
605
|
+
if (!ticketUser) {
|
|
606
|
+
res.writeHead(401, { "Content-Type": "application/json" });
|
|
607
|
+
res.end('{"error":"unauthorized"}');
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
var ticket = auth.mintWsTicket(ticketUser.id);
|
|
611
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
612
|
+
res.end(JSON.stringify({ ticket: ticket }));
|
|
613
|
+
return;
|
|
614
|
+
}
|
|
615
|
+
|
|
514
616
|
// --- Skills routes (delegated to server-skills) ---
|
|
515
617
|
if (skills.handleRequest(req, res, fullUrl)) return;
|
|
516
618
|
|
|
@@ -632,7 +734,36 @@ function createServer(opts) {
|
|
|
632
734
|
if (projectUrlForAuth === "/api/mcp-bridge") {
|
|
633
735
|
console.log("[server] MCP bridge auth: method=" + req.method + " addr=" + remoteAddr + " bypass=" + isMcpBridgeLocal);
|
|
634
736
|
}
|
|
737
|
+
// lr-2895ea: serve public shell static assets (app.js, style.css,
|
|
738
|
+
// /modules/*.js, fonts, images, maps) AHEAD of the auth gate, bypassing
|
|
739
|
+
// it entirely for GET requests to these paths. These files are public
|
|
740
|
+
// and identical for every user — gating them provided no security and
|
|
741
|
+
// broke mobile app boot (see isPublicShellAssetPath() doc comment
|
|
742
|
+
// above). The document navigation (/p/{slug}/), /api/*, and /ws remain
|
|
743
|
+
// fully gated below; this branch never reaches those paths because
|
|
744
|
+
// isPublicShellAssetPath() explicitly excludes /api/*.
|
|
745
|
+
if (req.method === "GET" && isPublicShellAssetPath(projectUrlForAuth)) {
|
|
746
|
+
if (serveStatic(projectUrlForAuth, res)) return;
|
|
747
|
+
// Not found on disk — fall through to the auth gate below so the
|
|
748
|
+
// existing unauthed-asset 401 behavior (lr-e33776) still applies to
|
|
749
|
+
// nonexistent asset paths instead of silently 404ing pre-auth.
|
|
750
|
+
}
|
|
751
|
+
|
|
635
752
|
if (!isMcpBridgeLocal && !isRequestAuthed(req)) {
|
|
753
|
+
// lr-e33776: an unauthenticated request to a project-scoped asset/
|
|
754
|
+
// module/API path must never receive the 200 text/html login page —
|
|
755
|
+
// that response breaks module-script boot (nosniff + wrong MIME) and
|
|
756
|
+
// caused the mobile "raw HTML flash / reconnecting" bug. Reserve the
|
|
757
|
+
// login page for top-level document navigation.
|
|
758
|
+
if (debug) {
|
|
759
|
+
console.log("[server] unauthed project route: path=" + projectUrlForAuth
|
|
760
|
+
+ " cookiePresent=" + !!(req.headers && req.headers.cookie));
|
|
761
|
+
}
|
|
762
|
+
if (isAssetOrApiPath(projectUrlForAuth)) {
|
|
763
|
+
res.writeHead(401, { "Content-Type": "application/json; charset=utf-8" });
|
|
764
|
+
res.end(JSON.stringify({ error: "unauthenticated" }));
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
636
767
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
637
768
|
res.end(auth.getAuthPage());
|
|
638
769
|
return;
|
|
@@ -746,7 +877,21 @@ function createServer(opts) {
|
|
|
746
877
|
}
|
|
747
878
|
|
|
748
879
|
// --- WebSocket ---
|
|
749
|
-
|
|
880
|
+
// handleProtocols echoes back the offered subprotocol whenever the client
|
|
881
|
+
// offered one and the upgrade authenticated (via ticket OR cookie — see
|
|
882
|
+
// lr-4c58ae): the WS spec requires the 101 response to echo an accepted
|
|
883
|
+
// subprotocol when one was offered, on any auth path. req._clayAcceptedProtocol
|
|
884
|
+
// is set by the upgrade handler below after auth resolves, BEFORE
|
|
885
|
+
// wss.handleUpgrade() is called, so it is available here.
|
|
886
|
+
var wss = new WebSocketServer({
|
|
887
|
+
noServer: true,
|
|
888
|
+
handleProtocols: function (protocols, req) {
|
|
889
|
+
if (req._clayAcceptedProtocol && protocols.has(req._clayAcceptedProtocol)) {
|
|
890
|
+
return req._clayAcceptedProtocol;
|
|
891
|
+
}
|
|
892
|
+
return false;
|
|
893
|
+
},
|
|
894
|
+
});
|
|
750
895
|
|
|
751
896
|
server.on("upgrade", function (req, socket, head) {
|
|
752
897
|
// Origin validation (CSRF prevention)
|
|
@@ -778,11 +923,60 @@ function createServer(opts) {
|
|
|
778
923
|
}
|
|
779
924
|
}
|
|
780
925
|
|
|
781
|
-
|
|
926
|
+
// Auth (lr-de5fcb): primary path is the relay_auth_user session cookie
|
|
927
|
+
// (desktop). Fallback path is a short-TTL single-use ticket offered via
|
|
928
|
+
// Sec-WebSocket-Protocol, for clients (mobile browsers) that do not
|
|
929
|
+
// reliably attach a SameSite=Lax cookie to a script-initiated upgrade —
|
|
930
|
+
// see MILLER's diagnosis, lr-de5fcb comment #1. The ticket is minted by
|
|
931
|
+
// GET /api/ws-ticket, which itself requires the cookie, so a client must
|
|
932
|
+
// already have completed a normal top-level authenticated request.
|
|
933
|
+
//
|
|
934
|
+
// lr-4c58ae: app-connection.js's connect() always fetches a ticket and
|
|
935
|
+
// always offers it as a Sec-WebSocket-Protocol subprotocol — including
|
|
936
|
+
// on desktop, which is cookie-authed. extractWsTicketFromHeader() is a
|
|
937
|
+
// pure parse (no consumption/validation side effect), so it is safe to
|
|
938
|
+
// call unconditionally, purely to learn what the client offered for the
|
|
939
|
+
// echo below. Only the *validating* consumeWsTicket() call stays gated
|
|
940
|
+
// on !wsCookieUser — a cookie-authed request must never burn the
|
|
941
|
+
// client's single-use ticket, since the cookie already authenticated it
|
|
942
|
+
// and consuming would needlessly invalidate a ticket a racing tab might
|
|
943
|
+
// legitimately need.
|
|
944
|
+
var wsCookieUser = getMultiUserFromReq(req);
|
|
945
|
+
var wsTicketUser = null;
|
|
946
|
+
var offeredTicket = extractWsTicketFromHeader(req.headers["sec-websocket-protocol"]);
|
|
947
|
+
if (!wsCookieUser && offeredTicket) {
|
|
948
|
+
wsTicketUser = auth.consumeWsTicket(offeredTicket);
|
|
949
|
+
}
|
|
950
|
+
var wsAuthedUser = wsCookieUser || wsTicketUser;
|
|
951
|
+
|
|
952
|
+
if (!wsAuthedUser) {
|
|
953
|
+
// Observability (DRUMMER-flagged, lr-de5fcb): debug-gated only, never
|
|
954
|
+
// logs the cookie or ticket value itself — just presence/shape, so a
|
|
955
|
+
// future "mobile can't connect" report is diagnosable in one pass
|
|
956
|
+
// instead of the two-pass investigation this task closed out.
|
|
957
|
+
if (debug) {
|
|
958
|
+
console.log(
|
|
959
|
+
"[server] WS upgrade rejected 401: cookiePresent=" + !!(req.headers.cookie) +
|
|
960
|
+
" ticketOffered=" + !!offeredTicket
|
|
961
|
+
);
|
|
962
|
+
}
|
|
782
963
|
socket.write("HTTP/1.1 401 Unauthorized\r\n\r\n");
|
|
783
964
|
socket.destroy();
|
|
784
965
|
return;
|
|
785
966
|
}
|
|
967
|
+
// Echo the accepted subprotocol back in the 101 response whenever the
|
|
968
|
+
// client offered one — the WS spec (RFC 6455 §4.1) requires the server
|
|
969
|
+
// to select one of the offered subprotocols if it accepts any of them;
|
|
970
|
+
// omitting Sec-WebSocket-Protocol from the 101 after the client offered
|
|
971
|
+
// a list forces the browser to fail the connection outright (lr-4c58ae).
|
|
972
|
+
// This must fire on EITHER auth path: wsTicketUser (the offered value
|
|
973
|
+
// was already validated+consumed above) or wsCookieUser (the offered
|
|
974
|
+
// value was merely parsed, never validated/consumed — the cookie is
|
|
975
|
+
// what authenticated this request, so echo it as-is without burning it).
|
|
976
|
+
// See the WebSocketServer handleProtocols hook above.
|
|
977
|
+
if (offeredTicket && (wsTicketUser || wsCookieUser)) {
|
|
978
|
+
req._clayAcceptedProtocol = "clagentic.auth." + offeredTicket;
|
|
979
|
+
}
|
|
786
980
|
|
|
787
981
|
// Drain gate (lr-6b30): reject new sessions while draining so in-flight
|
|
788
982
|
// sessions can complete before the daemon exits.
|
|
@@ -815,8 +1009,10 @@ function createServer(opts) {
|
|
|
815
1009
|
return;
|
|
816
1010
|
}
|
|
817
1011
|
|
|
818
|
-
// Attach user info to the WS connection
|
|
819
|
-
|
|
1012
|
+
// Attach user info to the WS connection. Reuse wsAuthedUser (resolved
|
|
1013
|
+
// above from the cookie or, on mobile, the ticket fallback) rather than
|
|
1014
|
+
// re-deriving from the cookie — a ticket-authed request has no cookie.
|
|
1015
|
+
var wsUser = wsAuthedUser;
|
|
820
1016
|
// Check project access
|
|
821
1017
|
if (wsUser && onGetProjectAccess) {
|
|
822
1018
|
// For worktree projects, inherit access from parent
|
package/lib/session-search.js
CHANGED
|
@@ -220,10 +220,16 @@ function searchIndex(index, query, maxResults) {
|
|
|
220
220
|
* Convert a session's history into searchable documents.
|
|
221
221
|
* Groups consecutive deltas into turns for better context.
|
|
222
222
|
* Each "turn" (user message or assistant response block) becomes one document.
|
|
223
|
+
*
|
|
224
|
+
* lr-a3e175: `history` is passed in explicitly rather than read off
|
|
225
|
+
* session.history so callers can supply a streaming disk-backed read
|
|
226
|
+
* (sm.readSessionHistoryFromDisk) for sessions that are LRU-evicted or never
|
|
227
|
+
* loaded into heap. Falls back to session.history for callers that already
|
|
228
|
+
* have a fully-loaded session (or in tests) and don't pass one.
|
|
223
229
|
*/
|
|
224
|
-
function sessionHistoryToDocs(session) {
|
|
230
|
+
function sessionHistoryToDocs(session, history) {
|
|
225
231
|
var docs = [];
|
|
226
|
-
|
|
232
|
+
history = history || session.history || [];
|
|
227
233
|
var sessionMeta = {
|
|
228
234
|
sessionId: session.localId || session.cliSessionId,
|
|
229
235
|
sessionTitle: session.title || "New Session"
|
|
@@ -291,13 +297,19 @@ function sessionHistoryToDocs(session) {
|
|
|
291
297
|
* @param {Array} projectSessions - [{ projectSlug, projectTitle, projectIcon, isMate, mateId, sessions }]
|
|
292
298
|
* where sessions = [{ localId, title, history, lastActivity, hidden }]
|
|
293
299
|
* @param {string} query
|
|
294
|
-
* @param {object} opts - { maxResults }
|
|
300
|
+
* @param {object} opts - { maxResults, getHistory }
|
|
301
|
+
* getHistory(session) - lr-a3e175: optional per-session history getter. When
|
|
302
|
+
* provided, called instead of reading session.history directly so a caller
|
|
303
|
+
* can supply a streaming disk-backed read (sm.readSessionHistoryFromDisk)
|
|
304
|
+
* for sessions that are LRU-evicted or never loaded into heap. Falls back
|
|
305
|
+
* to session.history when omitted.
|
|
295
306
|
* @returns {Array} [{ projectSlug, projectTitle, projectIcon, sessionId, sessionTitle, lastActivity, matchType, snippet, score, isMate, mateId }]
|
|
296
307
|
*/
|
|
297
308
|
function searchPalette(projectSessions, query, opts) {
|
|
298
309
|
opts = opts || {};
|
|
299
310
|
if (!query || !query.trim()) return [];
|
|
300
311
|
var maxResults = opts.maxResults || 30;
|
|
312
|
+
var getHistory = typeof opts.getHistory === "function" ? opts.getHistory : null;
|
|
301
313
|
|
|
302
314
|
var allDocs = [];
|
|
303
315
|
|
|
@@ -329,8 +341,11 @@ function searchPalette(projectSessions, query, opts) {
|
|
|
329
341
|
}
|
|
330
342
|
});
|
|
331
343
|
|
|
332
|
-
// Content turns as docs
|
|
333
|
-
|
|
344
|
+
// Content turns as docs. lr-a3e175: stream from disk via getHistory
|
|
345
|
+
// when supplied instead of reading the possibly-unloaded/trimmed
|
|
346
|
+
// session.history heap array directly (does not mutate heap/LRU state).
|
|
347
|
+
var sessionHistory = getHistory ? getHistory(session) : session.history;
|
|
348
|
+
var turnDocs = sessionHistoryToDocs(session, sessionHistory);
|
|
334
349
|
for (var td = 0; td < turnDocs.length; td++) {
|
|
335
350
|
var turnDoc = turnDocs[td];
|
|
336
351
|
allDocs.push({
|