@clagentic/console 1.7.1-beta.1 → 1.8.0-beta.2

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.
Files changed (46) hide show
  1. package/bin/cli.js +199 -2545
  2. package/lib/build-sha.json +2 -2
  3. package/lib/cli/daemon-launch.js +797 -0
  4. package/lib/cli/ipc-subcommands.js +186 -0
  5. package/lib/cli/menus.js +847 -0
  6. package/lib/cli/net-detect.js +209 -0
  7. package/lib/cli/tui.js +589 -0
  8. package/lib/pages.js +13 -17
  9. package/lib/project-loop.js +10 -2
  10. package/lib/project.js +6 -0
  11. package/lib/public/css/base.css +14 -1
  12. package/lib/public/css/diagnostics.css +15 -0
  13. package/lib/public/css/home-hub.css +32 -15
  14. package/lib/public/css/overlays.css +19 -0
  15. package/lib/public/index.html +12 -11
  16. package/lib/public/manifest.json +1 -1
  17. package/lib/public/modules/app-connection.js +187 -4
  18. package/lib/public/modules/app-history-replay.js +155 -0
  19. package/lib/public/modules/app-home-hub.js +33 -30
  20. package/lib/public/modules/app-messages.js +1245 -1489
  21. package/lib/public/modules/app-notifications.js +4 -4
  22. package/lib/public/modules/command-palette.js +11 -22
  23. package/lib/public/modules/context-sources.js +1 -6
  24. package/lib/public/modules/filebrowser.js +25 -13
  25. package/lib/public/modules/mcp-ui.js +2 -2
  26. package/lib/public/modules/notifications.js +22 -1
  27. package/lib/public/modules/playbook.js +6 -6
  28. package/lib/public/modules/project-settings.js +5 -13
  29. package/lib/public/modules/qrcode.js +2 -2
  30. package/lib/public/modules/relative-time.js +27 -0
  31. package/lib/public/modules/scheduler-history.js +1 -5
  32. package/lib/public/modules/server-settings.js +28 -15
  33. package/lib/public/modules/sidebar-projects.js +1 -1
  34. package/lib/public/modules/sidebar-sessions.js +1 -15
  35. package/lib/public/modules/sidebar.js +3 -3
  36. package/lib/public/modules/utils.js +6 -1
  37. package/lib/public/sw.js +24 -4
  38. package/lib/server-auth.js +48 -2
  39. package/lib/server-settings.js +70 -4
  40. package/lib/server.js +269 -15
  41. package/lib/sessions.js +9 -2
  42. package/lib/smtp.js +6 -6
  43. package/lib/users.js +19 -10
  44. package/lib/worktree.js +73 -1
  45. package/lib/yoke/adapters/codex.js +1 -1
  46. package/package.json +1 -1
@@ -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
 
@@ -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
- fs.writeFileSync(candidatePath, raw);
520
- try { fs.chmodSync(candidatePath, 0o644); } catch (e) {}
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) fs.unlinkSync(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
- var wss = new WebSocketServer({ noServer: true });
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
- if (!isRequestAuthed(req)) {
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
- var wsUser = getMultiUserFromReq(req);
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
@@ -870,32 +1066,82 @@ function createServer(opts) {
870
1066
  ws._clayUser = wsUser; // attach user context
871
1067
  var remoteAddr = req.socket.remoteAddress || "";
872
1068
  ws._clayLocal = (remoteAddr === "127.0.0.1" || remoteAddr === "::1" || remoteAddr === "::ffff:127.0.0.1");
873
- // Clear cross-project unread for this project when client connects
1069
+ // Clear cross-project unread for this project when client connects.
1070
+ // lr-0aa7b6: map is keyed per-session ("slug::localId") now, so clear
1071
+ // every entry whose slug prefix matches the project just connected to.
874
1072
  var unreadMap = getCrossProjectUnread(ws);
875
- if (unreadMap[wsSlug]) {
876
- unreadMap[wsSlug] = 0;
1073
+ var unreadPrefix = wsSlug + "::";
1074
+ var unreadKeys = Object.keys(unreadMap);
1075
+ for (var ui = 0; ui < unreadKeys.length; ui++) {
1076
+ if (unreadKeys[ui].indexOf(unreadPrefix) === 0) unreadMap[unreadKeys[ui]] = 0;
877
1077
  }
878
1078
  ctx.handleConnection(ws, wsUser);
879
1079
  });
880
1080
  });
881
1081
 
882
1082
  // --- Cross-project unread tracking ---
883
- // WeakMap<ws, { slug: count }> tracks how many done events happened in other projects
1083
+ // WeakMap<ws, { "slug::localId": count }> tracks how many done events
1084
+ // happened in other projects, keyed per SESSION rather than per project
1085
+ // (lr-0aa7b6). A slug-only key made every session in a notifying project
1086
+ // look equally "unread" — the Home Hub Recent Sessions row for a sibling,
1087
+ // non-notifying session in the same project would light up too. localId
1088
+ // alone is not sufficient either: each project's SessionManager keeps its
1089
+ // own nextLocalId counter (see lib/sessions.js), so localId 3 in project A
1090
+ // and localId 3 in project B are unrelated sessions that would collide if
1091
+ // used as a bare key — hence the composite "slug::localId" key below.
884
1092
  var crossProjectUnread = new WeakMap();
885
1093
 
1094
+ function crossUnreadKey(slug, localId) {
1095
+ return slug + "::" + localId;
1096
+ }
1097
+
886
1098
  function getCrossProjectUnread(ws) {
887
1099
  var map = crossProjectUnread.get(ws);
888
1100
  if (!map) { map = {}; crossProjectUnread.set(ws, map); }
889
1101
  return map;
890
1102
  }
891
1103
 
892
- function onSessionDone(sourceSlug) {
893
- // Increment unread for all clients NOT connected to sourceSlug
1104
+ // Sum of all per-session unread entries belonging to a given project slug,
1105
+ // for a given client. Preserves the pre-lr-0aa7b6 project-badge contract
1106
+ // (proj.unread on the Projects-list) now that the underlying map is keyed
1107
+ // per-session rather than per-project — the badge is a rollup over the
1108
+ // restructured map, not a separate counter.
1109
+ function getCrossProjectUnreadForSlug(ws, projSlug) {
1110
+ var map = getCrossProjectUnread(ws);
1111
+ var prefix = projSlug + "::";
1112
+ var total = 0;
1113
+ var keys = Object.keys(map);
1114
+ for (var i = 0; i < keys.length; i++) {
1115
+ if (keys[i].indexOf(prefix) === 0) total += map[keys[i]] || 0;
1116
+ }
1117
+ return total;
1118
+ }
1119
+
1120
+ // Per-session unread lookup used by the Home Hub Recent Sessions data path
1121
+ // (lib/project-loop.js hub_recent_sessions_list) to attribute the alert
1122
+ // state to the individual notifying session rather than the whole project.
1123
+ // ownSlug is the slug of the project ws is connected to: for that project,
1124
+ // unread is tracked per-session via ws._clayUnread[localId] (the existing
1125
+ // same-project mechanism in lib/sessions.js doSendAndRecord); for every
1126
+ // other project, unread is tracked via the composite crossProjectUnread map.
1127
+ function getSessionUnread(ws, ownSlug, sessSlug, localId) {
1128
+ if (sessSlug === ownSlug) {
1129
+ var ownMap = ws._clayUnread || {};
1130
+ return ownMap[localId] || 0;
1131
+ }
1132
+ var map = getCrossProjectUnread(ws);
1133
+ return map[crossUnreadKey(sessSlug, localId)] || 0;
1134
+ }
1135
+
1136
+ function onSessionDone(sourceSlug, sourceLocalId) {
1137
+ // Increment unread for all clients NOT connected to sourceSlug, keyed to
1138
+ // the specific session that finished (lr-0aa7b6).
1139
+ var key = crossUnreadKey(sourceSlug, sourceLocalId);
894
1140
  projects.forEach(function (ctx, projSlug) {
895
1141
  if (projSlug === sourceSlug) return;
896
1142
  ctx.forEachClient(function (ws) {
897
1143
  var map = getCrossProjectUnread(ws);
898
- map[sourceSlug] = (map[sourceSlug] || 0) + 1;
1144
+ map[key] = (map[key] || 0) + 1;
899
1145
  });
900
1146
  });
901
1147
  // Trigger a projects_updated broadcast so clients get updated unread counts
@@ -923,8 +1169,11 @@ function createServer(opts) {
923
1169
  });
924
1170
  }
925
1171
  }
926
- // Attach per-project unread counts for this client
927
- var unreadMap = getCrossProjectUnread(ws);
1172
+ // Attach per-project unread counts for this client. lr-0aa7b6:
1173
+ // crossProjectUnread is now keyed per-session ("slug::localId"),
1174
+ // not per-project — the Projects-list badge total is a rollup
1175
+ // (sum) over that client's per-session entries for the project,
1176
+ // preserving the pre-restructure proj.unread contract.
928
1177
  var projectsWithUnread = filtered.map(function (p) {
929
1178
  var copy = {};
930
1179
  var keys = Object.keys(p);
@@ -933,7 +1182,7 @@ function createServer(opts) {
933
1182
  if (p.slug === projSlug) {
934
1183
  copy.unread = ctx.sm.getTotalUnread(ws);
935
1184
  } else {
936
- copy.unread = unreadMap[p.slug] || 0;
1185
+ copy.unread = getCrossProjectUnreadForSlug(ws, p.slug);
937
1186
  }
938
1187
  return copy;
939
1188
  });
@@ -1079,7 +1328,12 @@ function createServer(opts) {
1079
1328
  },
1080
1329
  onPresenceChange: broadcastPresenceChange,
1081
1330
  onProcessingChanged: broadcastProcessingChange,
1082
- onSessionDone: function () { onSessionDone(slug); },
1331
+ onSessionDone: function (localId) { onSessionDone(slug, localId); },
1332
+ // lr-0aa7b6: per-session unread lookup for the Home Hub Recent
1333
+ // Sessions data path — see getSessionUnread's header above for why
1334
+ // this must distinguish "own project" (ws._clayUnread) from
1335
+ // "other project" (composite crossProjectUnread map).
1336
+ getSessionUnread: function (ws, sessSlug, localId) { return getSessionUnread(ws, slug, sessSlug, localId); },
1083
1337
  onAddProject: onAddProject,
1084
1338
  onCreateProject: onCreateProject,
1085
1339
  onCloneProject: onCloneProject,
package/lib/sessions.js CHANGED
@@ -1259,8 +1259,15 @@ function createSessionManager(opts) {
1259
1259
  } else if (session.localId === activeSessionId) {
1260
1260
  send(obj);
1261
1261
  }
1262
- // Notify server for cross-project unread tracking
1263
- if (obj.type === "done") onSessionDone();
1262
+ // Notify server for cross-project unread tracking. Pass the session's
1263
+ // own localId (lr-0aa7b6) so cross-project unread can be attributed to
1264
+ // the SPECIFIC session that finished, not just "this project has an
1265
+ // unread somewhere" — localId alone is only unique within this
1266
+ // project's SessionManager (nextLocalId is a per-project counter), so
1267
+ // the receiving side must pair it with the source project's slug
1268
+ // (already known to the caller wired in server.js) to form a globally
1269
+ // unique key.
1270
+ if (obj.type === "done") onSessionDone(session.localId);
1264
1271
  }
1265
1272
 
1266
1273
  function resumeSession(cliSessionId, opts, targetWs) {
package/lib/smtp.js CHANGED
@@ -78,9 +78,9 @@ function sendTestEmail(cfg, toEmail) {
78
78
  return t.sendMail({
79
79
  from: cfg.from,
80
80
  to: toEmail,
81
- subject: "Clagentic:Console SMTP Test",
81
+ subject: "Clagentic: Console SMTP Test",
82
82
  html: '<div style="font-family:system-ui,sans-serif;max-width:400px;margin:0 auto;padding:24px">' +
83
- '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic:Console</h2>' +
83
+ '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic: Console</h2>' +
84
84
  '<p style="color:#333;margin:0">SMTP is configured correctly. You will receive login codes and invite emails at this address.</p>' +
85
85
  '</div>',
86
86
  }).then(function (info) {
@@ -160,7 +160,7 @@ function verifyOtp(email, code) {
160
160
  function sendOtpEmail(email, code) {
161
161
  var subject = "Your Clagentic login code: " + code;
162
162
  var html = '<div style="font-family:system-ui,sans-serif;max-width:400px;margin:0 auto;padding:24px">' +
163
- '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic:Console</h2>' +
163
+ '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic: Console</h2>' +
164
164
  '<p style="color:#333;margin:0 0 16px">Your verification code is:</p>' +
165
165
  '<div style="font-size:32px;font-weight:700;letter-spacing:8px;padding:16px 0;text-align:center;' +
166
166
  'background:#f5f5f5;border-radius:8px;color:#333;font-family:monospace">' + code + '</div>' +
@@ -170,10 +170,10 @@ function sendOtpEmail(email, code) {
170
170
  }
171
171
 
172
172
  function sendInviteEmail(email, inviteUrl, inviterName) {
173
- var subject = "You've been invited to Clagentic:Console";
173
+ var subject = "You've been invited to Clagentic: Console";
174
174
  var html = '<div style="font-family:system-ui,sans-serif;max-width:400px;margin:0 auto;padding:24px">' +
175
- '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic:Console</h2>' +
176
- '<p style="color:#333;margin:0 0 16px">' + (inviterName || "An admin") + ' has invited you to join Clagentic:Console.</p>' +
175
+ '<h2 style="color:#DA7756;margin:0 0 16px">Clagentic: Console</h2>' +
176
+ '<p style="color:#333;margin:0 0 16px">' + (inviterName || "An admin") + ' has invited you to join Clagentic: Console.</p>' +
177
177
  '<p style="margin:0 0 16px"><a href="' + inviteUrl + '" style="display:inline-block;padding:12px 24px;' +
178
178
  'background:#DA7756;color:#fff;text-decoration:none;border-radius:8px;font-weight:600">Accept Invite</a></p>' +
179
179
  '<p style="color:#999;font-size:13px;margin:0">This invite link expires in 24 hours.</p>' +