Repository navigation
Conversation
- shared/ @peershell/protocol: wire protocol (binary framing with peerId, control messages), SessionTransport interface, PIN challenge-response, UTF-8 splitter, room-code/token/tunnel-path validators. Builds via tsc. - clients/tabby (tabby-peershell): self-contained Angular 15 / webpack build (externalizes Angular/RxJS/tabby-*, bundles @peershell/protocol), Stage 0 NgModule skeleton + Node smoke-load test (loads/constructs as Tabby would). - clients/web + server: placeholders (Stage 4 / Stage 5). - PROTOCOL.md spec, README (no-E2E disclaimer + dev workflow), build:all pipeline, copy-web-asset / publish-plugins scripts, .gitignore. build:all green; `npm test` smoke-load PASS.
- root jest (ts-jest, node env) with jest.setup providing Web Crypto for Node 18 - shared tests: binary frame round-trip (peerId/tag/payload, uint32, empty, short-frame throw), control encode/decode + version stamp, PIN challenge- response (deterministic hash, nonce-varies, PIN-not-in-hash, verify ok/ko), UTF-8 splitter reassembly of split multibyte, room-code + tunnel-path validators - root scripts: `test` -> jest, `test:smoke` -> plugin bundle load check 15/15 tests green.
- shared/websocketTransport.ts: SessionTransport over WebSocket (global by default, injectable impl for Node), text=control / binary=framed data - server/dev-relay.cjs: throwaway rendezvous + blind relay (pairs host/guest by room/token, forwards every frame), runnable standalone; @peershell/server precursor - shared/test/transport.integration.test.ts: two transports through the relay do hello -> create/join -> PIN challenge-response -> snapshot-ack barrier -> output/input frames; plus wrong-PIN -> pin-fail 17/17 tests green; build:all green.
- host/shareController.ts: Tabby-agnostic host controller (HostTerminal port + SessionTransport). Creates session, snapshot-ack barrier, mirrors output, injects guest input, forwards resize, tears down on tab close. Unit-tested with mock transport + mock tab. - services/peershell.service.ts: adapts a real BaseTerminalTabComponent to HostTerminal, owns active shares, gates on configured server URL. - providers: toolbar "Share terminal" + tab context-menu Share/Stop. - config.ts: PeershellConfigProvider (peershell.serverUrl, magicLinkTtl). - types/tabby.d.ts: minimal ambient shims so the plugin builds decoupled from Tabby's source tree (real impls come from Tabby at runtime as webpack externals). - shared/base64.ts (snapshot payload). Generic-stub smoke-load resilient to future externals. 19/19 tests green; build:all green; smoke-load PASS.
- guest/mirrorController.ts: Tabby-agnostic guest controller (SessionTransport + MirrorSink port). join, render+ack snapshot (barrier), render live output, forward keystrokes, surface host resize + session end. Unit-tested with mocks. - test/hostGuest.integration.test.ts: real ShareController (mock host tab) <-> dev relay <-> real MirrorController (mock sink); asserts snapshot, live output host->guest, input guest->host, host resize. - jest forceExit (integration tests use real sockets). 22/22 tests green; build:all green; smoke-load PASS.
- guest/mirrorSession.ts: MirrorSession extends BaseSession (7 abstract members; UTF8SplitterMiddleware; delegates wire logic to MirrorController; exposes hostResize$). write()->input frame, resize() no-op (tmate), emitOutput from frames. - guest/mirrorTab.component.ts: MirrorTabComponent extends BaseTerminalTabComponent (reuses base template; onFrontendReady creates MirrorSession + adopts host size via hostResize$; no frontend.resize$ subscription -> no resize loop). - peershell.service.ts: joinShared() (prompt room-code, connect, open mirror tab). - toolbar: "Join shared terminal" button. index.ts: full NgModule (Common/Forms/Ngb/ Toastr/TabbyCore/TabbyTerminal imports + MirrorTabComponent declaration). - expanded tabby.d.ts shim (BaseSession, UTF8SplitterMiddleware, BaseTerminalTabComponent members, LogService, PromptModalComponent, openNewTab, module default exports). build:all green; 22/22 tests green; smoke-load PASS. GUI wiring/profile of the mirror tab needs validation in a real Tabby.
- shared/pinAuth: generatePin (local per-session PIN). websocketTransport: keepalive (ping every 20s, unref'd timer, pong-on-ping handled below the app, cleared on close) + tests. - ShareController: on peer-joined issue pin-challenge (fresh nonce/attempt); verify pin-response; pin-ok -> snapshot/stream; wrong -> pin-fail + re-challenge, rate-limited to 5 then kick (peer-left). Input frames rejected until authenticated. - MirrorController: PinProvider callback; answer pin-challenge with H(pin,nonce); pin-fail(0) -> end. Tests + host<->guest integration now cover PIN (happy + wrong). - Tabby glue: PeershellService generates + shows the PIN (with magic-link) on share; joinShared threads a PIN prompt (PromptModalComponent password) through MirrorTabComponent -> MirrorSession -> MirrorController. 29/29 tests green; build:all green; smoke-load PASS. (magic-link TTL/revocation is server-side, Stage 5; client sends session-close on stop.)
- Move MirrorController (+ MirrorSink/PinProvider) into @peershell/protocol so it is reused by the Tabby plugin (MirrorSession) and the coming web-client. Update plugin imports + relocate its unit test to shared/. - shared/httpTunnelHandler.ts: answers tunneled http-get by serving the embedded web-client HTML; strict path whitelist (only '/'), 403 on traversal/SSRF. Unit-tested. - dev-relay: reverse HTTP tunnel — GET /s/<token> forwards http-get to the host and returns the host's http-response body (intercepted, not forwarded to a peer). - shared/test/tunnel.integration.test.ts: Node HTTP GET of the magic-link returns the host-served page over the tunnel. 32/32 tests green; build:all green; smoke-load PASS.
- clients/web: webpack (target web) -> single self-contained dist/index.html
(JS + xterm CSS inlined via HtmlInlineScriptPlugin + style-loader). Reuses
WebSocketTransport + MirrorController + Utf8Splitter from @peershell/protocol.
- reads the magic-link token from /s/<token> (or ?token=), PIN overlay prompt,
term.onData -> input, adopts host size (tmate), UTF-8 splitter before term.write.
- MirrorController.join now takes { room | token } so the browser can join by token;
desktop still joins by room. Updated call sites/tests.
- build:web output is embedded into the plugin (copy-web-asset) for the host to serve.
32/32 tests green; build:all green (web-client embedded, 307 KB). Browser E2E is
validated in a real browser; the guest logic is covered by @peershell/protocol tests.
- PeershellService.startSharing attaches an HttpTunnelHandler to the host transport, serving the embedded web-client.html (asset/source import) on tunneled http-get. - shim: declare '*.html' module for the asset import. build:all green (plugin bundle embeds the 307 KB web-client); smoke-load PASS.
- server/src/index.cjs (was dev-relay.cjs): rendezvous + blind relay + reverse HTTP tunnel, now with magic-link TTL (15m, link-expired on join / 410 on GET), env config (PORT/BIND/PUBLIC_URL/TOKEN_TTL_MS), GET /health, keepalive (pong reply + idle reaper), host-close tears down the session while guest-close frees the slot for a retry. - env-driven standalone runner + startup log. - repoint the three integration tests to server/src/index.cjs; server/package.json (start=node src/index.cjs, dep ws). 32/32 tests green (integration tests run against the productionized server).
- Accounts in server/src/index.cjs (still single CJS file, stdlib only): atomic JSON store
(data/accounts.json, mode 0600, ephemeral fallback), pbkdf2 password hashing w/ timingSafeEqual,
opaque bearer tokens (sha256-stored, 24h TTL, logout/refresh revocation), inline RFC-6238 TOTP.
- REST: POST /register (+ mock-logged email verify code), /verify-email, /login (needsTotp branch),
/2fa/{setup,verify,enable,disable}, /logout, /session/refresh; GET /sessions dashboard.
- Security: WS create-session GATED on a valid account token (?token= on the upgrade URL) via
requireAuth (default ON); anti-enumeration login, rate-limits (login lockout, register/IP, 2FA
attempts), body-size cap. Rooms tagged w/ accountId for the dashboard. Guests unchanged (PIN).
- Tests: new auth.integration suite (register/verify/login/enum+ratelimit/gate/TOTP/logout);
existing relay/tunnel/hostGuest integration tests pass { requireAuth: false }. 38 tests green.
- AccountService (clients/tabby): fetch-based REST client (register/verify-email/login/verify2fa/ logout), bearer token kept in the Tabby config store (getToken/persist/clearLocal); REST base derived from the ws(s):// server URL. (Vault storage is the documented follow-up hardening.) - LoginModalComponent: inline-template modal with login/register/verify-email/2FA/logout modes, friendly error mapping; resolves with the token on a successful login. - PeershellService.startSharing() now gates on a logged-in account: opens the login modal when there is no token, passes the account token to ShareController.start -> transport ?token=; on an 'unauthorized' error it clears the stale token and asks the user to log in again. - Toolbar gains a "peershell account (log in / out)" button (opens the modal); index.ts declares LoginModalComponent. Webpack build + smoke-load green; 38 tests still pass.
- server/src/index.cjs: deliverVerifyCode() posts the code through the Brevo transactional API (stdlib https, zero deps) when BREVO_API_KEY is set; falls back to logging the code when no key is configured, and to logging on a send failure (registration never blocks on email). Config via env: BREVO_API_KEY, EMAIL_FROM (default noreply@peershell.dev), EMAIL_FROM_NAME. brevoSend takes an injectable sendFn for tests. Relaying through Brevo keeps the VM IP out of the sending path (no blacklist risk) and lets DKIM/SPF authorise the domain. - Wired into POST /register (new + resend paths); exports deliverVerifyCode/brevoSend. - Unit test (email.test.ts): log fallback, injected-mailer send, send-failure fallback. 41 tests green.
- PeershellService.confirmDisclaimer(): one-time warning before the first share (via PlatformService.showMessageBox) that guests get a read-write shell and the relay sees traffic in clear text; acknowledged once (config peershell.disclaimerAck). Blocks the share on Cancel. - tabby.d.ts: shim PlatformService/showMessageBox; config defaults gain disclaimerAck + account. - README: document server env (PORT/PUBLIC_URL/PEERSHELL_DATA/TOKEN_TTL_MS/BREVO_API_KEY/EMAIL_FROM), Brevo relay rationale and the DNS to authorise the domain. Build + smoke green.
- PeershellSettingsTabComponent (+ provider): configure the server URL, log in/out, and see the account's live shares (room / guest connected / magic-link) via GET /sessions. Prominent no-E2E security note at the top. Reachable from Tabby's Settings. - AccountService.getSessions(): GET /sessions (dashboard), clears the local token on 401. - tabby.d.ts: shim tabby-settings (SettingsTabProvider); index.ts wires the provider + declares the component. Webpack build + smoke-load green; 41 tests still pass.
- One toolbar button ("peershell"); click opens a native popup menu (PlatformService.popupContextMenu)
with Share this terminal / Join a shared terminal / Account (label reflects login state). The toolbar
renders provider buttons as Commands and only calls run() on click — it does not open a ToolbarButton
submenu — so the dropdown is built via popupContextMenu instead. tabby.d.ts shims popupContextMenu.
The account endpoints are called cross-origin from the Tabby/Electron renderer (and the browser
web-client), so without CORS headers Chromium blocks the fetch ("cannot reach the server"). Add
Access-Control-Allow-Origin: * (+ allow headers authorization/content-type, methods GET/POST/OPTIONS)
to every response and answer preflight OPTIONS with 204. No cookies are used (bearer token in a
header), so '*' is safe. Verified: OPTIONS -> 204 + headers; POST -> 400 with the CORS header.
On the login form, "Create account" now calls register() with the entered email/password instead of switching to a separate register mode that required a second button press. Drops the standalone register mode; on success it goes straight to the email-verification step.
Ship a working default so the plugin reaches the hosted server out of the box (no manual setup); the
empty `peershell: {}` config now inherits this default. Overridable in Settings for self-hosting.
…ogout menu, password reset
- Server: registration is adaptive — if the verification email cannot be delivered (no SMTP configured
or send fails), the account is auto-verified and a token is returned immediately, so users aren't
stranded behind a code they can't receive; when email works, the verify-then-login flow is kept.
Existing verified email -> { alreadyRegistered }. New endpoints POST /request-password-reset +
/reset-password (code via the same email/log path, 15-min TTL, timing-safe). deliverVerifyCode gains
a 'reset' kind for the message.
- Client: "Create account" now closes the modal and logs in on auto-verify, or goes to verify only when
a code was emailed; "Forgot password?" link + reset-request/reset modes. Toolbar menu shows "Log out
(email)" when signed in and "Log in" otherwise (direct logout); PeershellService.logout() added.
- Tests: auth suite injects a mailer stub (keeps the verify flow) + a new auto-verify-without-email
case. 42 tests green. Live-verified on the box: register -> { token, autoVerified: true }.
…+ unexpected-error catch)
…igning (getter-only)
…ls when focus is null)
There was a problem hiding this comment.
Actionable comments posted: 2
Note
Due to the large number of review comments, Critical severity comments were prioritized as inline comments.
🟠 Major comments (19)
server/src/qrcode.js-1-16 (1)
1-16: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winRestore the upstream draw order in
server/src/qrcode.js. The vendored copy no longer matches the upstream release:renderTo2dContext()swapsrow/colinfillRect, transposing the QR matrix and risking unreadable codes. RestorefillRect(col * cellSize, row * cellSize, ...)or document this fork.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@server/src/qrcode.js` around lines 1 - 16, Restore the upstream draw order in qrcode rendering: the vendored `renderTo2dContext()` implementation is transposing the QR matrix by swapping `row` and `col` in the `fillRect` call. Update that logic back to the upstream ordering in `server/src/qrcode.js` so the QR modules are drawn using column for x and row for y, or explicitly document the fork if the behavior is intentional.PROTOCOL.md-45-49 (1)
45-49: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winAlign the REST examples with the implemented auth flow.
The login docs still use
needs2fa/challenge, but the server currently returnsneedsTotp/sessionKey, and the/sessionspayload also includes more fields than shown here. Please update this section before clients code against the wrong schema.♻️ Proposed fix
- `POST /login { email, password } -> { token } | { needs2fa: true, challenge }` - `POST /2fa/verify { challenge, code } -> { token }` - `GET /sessions -> { sessions: [{ room, magicLink, createdAt }] }` (dashboard, authenticated) + `POST /login { email, password } -> { token } | { needsTotp: true, sessionKey }` + `POST /2fa/verify { sessionKey, code } -> { token }` + `GET /sessions -> { account: { email, totpEnabled, totpEnabledAt }, sessions: [{ room, magicLink, createdAt, endedAt, live, hasGuest }] }` (dashboard, authenticated)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@PROTOCOL.md` around lines 45 - 49, Update the REST auth examples in the protocol docs to match the implemented flow: the `POST /login` response in the auth section should use the actual `needsTotp/sessionKey` shape instead of `needs2fa/challenge`, and the `POST /2fa/verify` example should reflect the corresponding token exchange used by the server. Also expand the `GET /sessions` example to include all fields returned by the current sessions payload, so the documented schema matches what clients will receive.clients/tabby/src/account/account.service.ts-49-74 (1)
49-74: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winAdd a timeout to
fetchcalls to prevent the modal from hanging indefinitely.The
api()method has no timeout on itsfetch()call. If the server is unresponsive, the promise never resolves, leavingbusy = trueinLoginModalComponent. The modal's Close button is bound[disabled]="busy", so the user is trapped with no visible way to dismiss the dialog.Use
AbortControllerwith a reasonable timeout (e.g., 15–30s) and surface atimeouterror so the modal can recover.⏱️ Proposed fix: add AbortController timeout
private async api(method: string, path: string, body?: unknown, auth = false): Promise<AccountApiResult> { const headers: Record<string, string> = { 'content-type': 'application/json' } if (auth) { const t = this.getToken() if (t) { headers.authorization = `Bearer ${t}` } } + const controller = new AbortController() + const timeout = setTimeout(() => controller.abort(), 20_000) let res: Response try { res = await fetch(this.base() + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), + signal: controller.signal, }) } catch (err) { - // eslint-disable-next-line no-console - console.error('[peershell] fetch failed:', method, this.base() + path, err) - return { status: 0, error: 'network-error', detail: String((err as any)?.message ?? err) } + const aborted = (err as Error)?.name === 'AbortError' + // eslint-disable-next-line no-console + console.error('[peershell] fetch failed:', method, this.base() + path, err) + return { status: 0, error: aborted ? 'timeout' : 'network-error', detail: String((err as any)?.message ?? err) } + } finally { + clearTimeout(timeout) } let json: Record<string, unknown> = {} try { json = await res.json() } catch { /* empty/non-json body */ } return { status: res.status, ...json } }Then add
'timeout': 'The server did not respond in time. Try again.'to theERRORSmap inlogin-modal.component.ts.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/account/account.service.ts` around lines 49 - 74, The api() method in AccountService currently awaits fetch() without any deadline, which can leave LoginModalComponent stuck in busy mode if the server never responds. Update api() to use an AbortController with a reasonable timeout around the fetch call, cancel the request on timeout, and return a distinct timeout error from the catch path so callers can recover. Also add the matching timeout entry to the ERRORS map in LoginModalComponent so the UI can display the correct message and allow the modal to close again.clients/tabby/src/host/shareController.ts-87-89 (1)
87-89: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winUnhandled promise rejection in
verifyResponsecan crash the process.
void this.verifyResponse(m.hash)discards the returned promise. IfverifyPinthrows (e.g., crypto failure or malformed hash), the rejection is unhandled. In Node.js this can terminate the process; in browsers it surfaces as a console warning with no error feedback to the user.🛡️ Proposed fix: catch and route to onError hook
case 'pin-response': - void this.verifyResponse(m.hash) + this.verifyResponse(m.hash).catch(err => { + this.hooks.onError?.('pin-verify-failed', err instanceof Error ? err.message : String(err)) + }) breakAlso applies to: 111-128
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/host/shareController.ts` around lines 87 - 89, The `pin-response` path in `shareController.ts` drops the promise returned by `verifyResponse`, so any rejection from `verifyPin` becomes unhandled. Update the `onMessage` handling around `verifyResponse` to await or chain a catch for that promise and route failures through the existing `onError` hook (or equivalent error path) instead of using `void`, so crypto/malformed-hash errors are handled consistently.shared/src/websocketTransport.ts-54-83 (1)
54-83: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
connect()promise can hang ifonclosefires beforeonerrorThe
onerrorhandler only rejects whenthis.state === 'connecting'. Ifonclosefires first,setState('closed')runs andthis.statebecomes'closed'— thenonerrorsees a non-connecting state and does nothing, leaving the promise permanently pending. There is also no connection timeout, so a non-responsive server hangsconnect()indefinitely.🔧 Proposed fix: add a `settled` flag and reject in `onclose` during connect
connect(url: string, token?: string): Promise<void> { return new Promise<void>((resolve, reject) => { this.setState('connecting') + let settled = false const full = token ? `${url}${url.includes('?') ? '&' : '?'}token=${encodeURIComponent(token)}` : url let ws: WebSocketLike try { ws = new this.WS(full) } catch (err) { this.setState('closed') reject(err instanceof Error ? err : new Error(String(err))) return } ws.binaryType = 'arraybuffer' this.ws = ws ws.onopen = () => { + if (settled) return + settled = true this.setState('open') this.startKeepalive() resolve() } ws.onerror = () => { - if (this.state === 'connecting') { + if (!settled) { + settled = true + this.setState('closed') reject(new Error('peershell: WebSocket connection failed')) } } - ws.onclose = () => this.setState('closed') + ws.onclose = () => { + if (!settled) { + settled = true + this.setState('closed') + reject(new Error('peershell: WebSocket closed during connect')) + } else { + this.setState('closed') + } + } ws.onmessage = ev => this.dispatch(ev.data) }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/websocketTransport.ts` around lines 54 - 83, The connect() promise can remain pending if the socket closes before an error is raised, so update websocketTransport.ts’s connect() flow to settle the promise exactly once. Add a local settled flag in connect(), use it to guard resolve/reject in ws.onopen, ws.onerror, and ws.onclose, and reject from onclose while still in the connecting phase instead of relying only on this.state. Also add a connection timeout path so connect() cannot hang indefinitely when the server is unresponsive.shared/src/mirrorController.ts-82-87 (1)
82-87: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winMake
close()end the session.
answerPin()relies onclose(), butclose()only tears down the transport. That leavesMirrorSink.ended(...)uncalled, so a dismissed PIN prompt can strand the guest UI. Delegate this path throughend(...)instead.🔧 Suggested fix
close(): void { - this.transport.close(1000, 'guest-closed') + this.end('guest-closed') }Also applies to: 105-107
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/mirrorController.ts` around lines 82 - 87, `answerPin()` currently calls `close()` when no PIN is provided, but that only tears down transport and does not end the session. Update the dismissal path in `answerPin()` (and any related `close()` usage in `MirrorController`) to route through `end(...)` so `MirrorSink.ended(...)` is invoked and the guest UI is properly released. Keep the existing `answerPin`/`close` behavior for transport teardown, but ensure session termination happens through the `end` flow instead of `close()` alone.shared/src/mirrorController.ts-97-103 (1)
97-103: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winClose the transport when the session ends.
end()currently only notifies the sink. Afterpin-fail,peer-left, orerror, the transport keeps running and can still accept late input or keepalive traffic. Close it here once the sink has been notified.🔒 Proposed fix
private end(reason: string): void { if (this.endedFlag) { return } this.endedFlag = true this.sink.ended(reason) + this.transport.close(1000, reason) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/mirrorController.ts` around lines 97 - 103, The MirrorController end flow only notifies the sink and leaves the transport active, so update the end() method to also close the transport after calling this.sink.ended(reason). Use the existing end(reason) guard with endedFlag, and ensure the transport shutdown happens for all terminal reasons such as pin-fail, peer-left, and error so no late input or keepalive traffic is accepted afterward.clients/tabby/src/services/peershell.service.ts-107-160 (1)
107-160: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winTear down the share on
onError
onErroronly notifies today; it leaves the controller inthis.sharesand the establish/grace timers running, so a failed share can stay alive until a later timeout or manual stop. Forunauthorized, stop the share immediately after clearing local auth.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/services/peershell.service.ts` around lines 107 - 160, The onError handler in ShareController currently only posts notifications, which leaves the share entry and timers active after a failure. Update peershell.service.ts in the ShareController setup so onError also tears down the share state: clear any active graceTimer and establishTimer, remove the controller from this.shares, and call stopSharing for non-recoverable failures. For the unauthorized branch in onError, clear local auth and then stop the share immediately rather than waiting for later cleanup.clients/tabby/src/settings/settings-tab.component.ts-99-113 (1)
99-113: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
refresh()lacks a catch block — network errors propagate unhandled.If
this.account.getSessions()throws (e.g., network failure), the promise rejection is unhandled and the user sees no error message. Thefinallyblock resetsbusy, butthis.errorremains empty. Add acatchblock to surface the failure.🛡️ Proposed fix: add catch block to refresh()
async refresh(): Promise<void> { this.busy = true this.error = '' try { const r = await this.account.getSessions() if (r.error) { this.error = r.error === 'unauthorized' ? 'Session expired — log in again.' : `Could not load shares (${r.error}).` this.sessions = [] } else { this.sessions = (r.sessions as LiveSession[]).filter(s => s.live !== false) } this.loaded = true + } catch { + this.error = 'Could not load shares (network error).' + this.sessions = [] } finally { this.busy = false }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/settings/settings-tab.component.ts` around lines 99 - 113, The refresh() method in settings-tab.component.ts only handles error responses from this.account.getSessions() and misses thrown exceptions, so add a catch branch around the await in refresh() to handle network/runtime failures. Use the existing refresh() flow and related fields this.error, this.sessions, this.loaded, and this.busy to set a user-visible error message, clear sessions on failure, and still allow the finally block to reset busy.clients/web/src/index.ts-96-102 (2)
96-102: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winCached wrong PIN is reused on re-challenge, burning all retry attempts.
When the user enters a wrong PIN,
cachedPinis set. The host sendspin-fail(withleft > 0) and then re-challenges with a new nonce.MirrorController.answerPincallspinProvider()again, which returns the same cached wrong PIN — not prompting the user. This repeats untilleft <= 0, ending the session with "wrong PIN". The user never gets a chance to re-enter.The cache should only be used for reconnects after a session was established, not for re-challenges within the same attempt.
🐛 Proposed fix: only cache after session is established
let stopped = false let cachedPin: string | null = null +let sessionEstablished = false let reconnectTimer: ReturnType<typeof setTimeout> | null = null let reconnectDeadline = 0 const RECONNECT_WINDOW_MS = 12000 const sink: MirrorSink = { emit: data => { + sessionEstablished = true term.write(splitter.write(data)) }, hostResize: (cols, rows) => term.resize(cols, rows), ended: reason => { stopped = true + sessionEstablished = false if (reconnectTimer) { clearTimeout(reconnectTimer) reconnectTimer = null } term.write(`\r\n[peershell] ${reason}\r\n`) setStatus(reason) }, } // Cache the PIN so a reconnect re-authenticates without re-prompting the user. const pinProvider: PinProvider = async () => { - if (cachedPin) { + if (sessionEstablished && cachedPin) { return cachedPin } cachedPin = await askPin() return cachedPin }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/web/src/index.ts` around lines 96 - 102, The pinProvider closure in clients/web/src/index.ts is reusing cachedPin for re-challenges, which causes the same wrong PIN to be resent without prompting again. Update pinProvider (and the cachedPin flow around askPin) so the cache is only used for reconnects after a successful session has been established, not after a pin-fail/re-challenge within the same attempt; make sure a failed PIN entry clears or bypasses the cache before MirrorController.answerPin calls pinProvider again.
96-102: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winCached wrong PIN is reused on re-challenge, burning all retry attempts.
When the user enters a wrong PIN,
cachedPinis set. The host sendspin-fail(withleft > 0) and then re-challenges with a new nonce.MirrorController.answerPincallspinProvider()again, which returns the same cached wrong PIN — not prompting the user. This repeats untilleft <= 0, ending the session with "wrong PIN". The user never gets a chance to re-enter.The cache should only be used for reconnects after a session was established, not for re-challenges within the same attempt.
🐛 Proposed fix: only cache after session is established
let stopped = false let cachedPin: string | null = null +let sessionEstablished = false let reconnectTimer: ReturnType<typeof setTimeout> | null = null let reconnectDeadline = 0 const RECONNECT_WINDOW_MS = 12000 const sink: MirrorSink = { emit: data => { + sessionEstablished = true term.write(splitter.write(data)) }, hostResize: (cols, rows) => term.resize(cols, rows), ended: reason => { stopped = true + sessionEstablished = false if (reconnectTimer) { clearTimeout(reconnectTimer) reconnectTimer = null } term.write(`\r\n[peershell] ${reason}\r\n`) setStatus(reason) }, } // Cache the PIN so a reconnect re-authenticates without re-prompting the user. const pinProvider: PinProvider = async () => { - if (cachedPin) { + if (sessionEstablished && cachedPin) { return cachedPin } cachedPin = await askPin() return cachedPin }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/web/src/index.ts` around lines 96 - 102, The pinProvider in clients/web/src/index.ts is reusing cachedPin too early, causing a wrong PIN to be replayed on re-challenges. Update the pin caching logic so cachedPin is only returned for reconnects after a successful session is established, not during a single PIN retry flow; use the pinProvider/askPin flow to prompt again when the host issues a new challenge after pin-fail..github/workflows/release-guard.yml-23-27 (1)
23-27: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winDisable persisted checkout credentials in this read-only guard.
This job only reads the trusted base policy and validates metadata, so keeping the Actions token in git config is unnecessary exposure.
Proposed fix
- name: Checkout trusted base policy uses: actions/checkout@v5 with: fetch-depth: 0 ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/release-guard.yml around lines 23 - 27, The trusted-base checkout in the release guard workflow is leaving persisted Git credentials enabled unnecessarily. Update the checkout step in the release-guard job that uses actions/checkout@v5 for the base policy so it disables persisted credentials, keeping this read-only validation job from storing the Actions token in git config.Source: Linters/SAST tools
.github/workflows/release.yml-35-36 (1)
35-36: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winDo not fall back to
npm installfor release builds.A release asset must be built from the committed lockfile. Falling back to
npm installcan resolve different dependency versions and publish a non-reproducible artifact.Proposed fix
- name: Install - run: npm ci || npm install + run: npm ci🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/release.yml around lines 35 - 36, The release workflow’s Install step in the release job should not fall back to npm install, because that can bypass the committed lockfile and produce non-reproducible artifacts. Update the release build in the release.yml workflow so the install step uses only npm ci (or otherwise fails fast if the lockfile cannot be honored), keeping the change scoped to the release pipeline and the Install step..github/workflows/ci.yml-34-35 (1)
34-35: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winKeep CI lockfile-strict.
npm ci || npm installlets CI pass after lockfile drift and can test dependencies different from the committed lockfile. Usenpm cionly so release artifacts stay reproducible.Proposed fix
- name: Install - run: npm ci || npm install + run: npm ci🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/ci.yml around lines 34 - 35, The CI install step is too permissive because it falls back from npm ci to npm install, which can hide lockfile drift and produce non-reproducible dependencies. Update the workflow’s Install step in the ci job to use npm ci only, so the pipeline fails when the lockfile and package manifest are out of sync and always installs exactly the committed dependency tree..github/workflows/post-merge-release.yml-51-51 (1)
51-51: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy liftSource the release policy from the pre-merge main parent.
post-merge-releaseruns with write permissions and currently sources.github/scripts/release-policy.shfrom the merged tree. For non-bootstrap releases, load the policy from the squash commit’s parent so a release PR cannot change the policy that finalizes that same release.Proposed direction
- source .github/scripts/release-policy.sh + POLICY="$(mktemp)" + if git show "${MERGE_SHA}^:.github/scripts/release-policy.sh" > "${POLICY}" 2>/dev/null; then + # shellcheck source=/dev/null + source "${POLICY}" + else + echo "::notice::Release policy absent on previous main; bootstrap release, using merged policy." + source .github/scripts/release-policy.sh + fi🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/post-merge-release.yml at line 51, The post-merge release workflow is sourcing release-policy.sh from the merged tree, which can let the release PR influence its own final policy. Update the policy-loading logic in post-merge-release so it reads .github/scripts/release-policy.sh from the squash commit’s pre-merge main parent for non-bootstrap releases, while preserving the current bootstrap path. Use the existing post-merge-release workflow and the release-policy.sh sourcing step as the main points to change..github/workflows/release.yml-20-20 (1)
20-20: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winValidate the release tag and workspace versions before publishing.
startsWith(..., 'v')allows anyv*release event to reach npm publishing. Add the same release-policy version/tag assertion in this workflow so manual or malformed releases cannot publish packages under the wrong release tag.Proposed fix
- name: Build all run: npm run build:all + + - name: Validate release version + env: + RELEASE_TAG: ${{ github.event.release.tag_name }} + run: | + set -euo pipefail + source .github/scripts/release-policy.sh + validate_release_tag "$RELEASE_TAG" + assert_versions_match_tag HEAD "$RELEASE_TAG"🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/release.yml at line 20, The release job currently gates publishing only with startsWith(github.event.release.tag_name, 'v'), which is too permissive. Update the workflow to use the same release-policy assertion already used elsewhere to validate both the release tag and workspace versions before npm publishing, and apply it in the release job so malformed or manual release tags cannot reach the publish step. Reference the release publish condition in the workflow and the shared release-policy check logic to keep the gate consistent.server/src/index.cjs-325-326 (1)
325-326: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
loginFailsandregByIpgrow unbounded — no reaper cleanup.The reaper interval (951-972) prunes
wss.clients,store.tokens, andtotpSessions, but never touchesloginFailsorregByIp. SincerecordLoginFailis called even for nonexistent emails (see/login, line 604) andregByIpkeys on arbitrary client IPs, an attacker can flood either map with unique keys (fake emails / spoofedX-Forwarded-Forvalues) to grow memory without bound — a low-cost DoS/memory-leak vector.🔧 Suggested fix: prune stale entries in the reaper
for (const [k, s] of totpSessions) { if (s.expiresAt < now()) { totpSessions.delete(k) } } + for (const [k, r] of loginFails) { + if (r.until < now() && r.count === 0) { + loginFails.delete(k) + } + } + for (const [k, r] of regByIp) { + if (r.resetAt < now()) { + regByIp.delete(k) + } + } }, 30000)Also applies to: 382-412, 951-972
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@server/src/index.cjs` around lines 325 - 326, The in-memory maps used by the auth flow are never cleaned up, so add stale-entry pruning for both loginFails and regByIp in the existing reaper interval alongside the current cleanup for wss.clients, store.tokens, and totpSessions. Use the same expiration data already stored in recordLoginFail and the reg-by-IP tracking logic to delete entries whose until/resetAt has passed, and ensure the cleanup runs from the reaper code path that periodically maintains server state.server/src/index.cjs-845-851 (1)
845-851: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy liftBearer token exposed via the WS upgrade URL query string.
?token=<accountToken>on the WebSocket URL means the account token can end up in access/proxy logs, Referer-like leakage from any intermediary, and error traces — a broader exposure surface than sending it as a header/first-message. This pattern is also baked into the client/test contract (shared/test/auth.integration.test.ts:64connects viarelay.url + '?token=' + token), so fixing it requires coordinated changes across the relay and both clients (tabby/web).Consider moving the token to the
Sec-WebSocket-Protocolheader or an authenticated first control message immediately afteropen, rather than the URL.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@server/src/index.cjs` around lines 845 - 851, The WebSocket auth flow in the upgrade handler currently reads the bearer token from the URL query via req.url/URL/searchParams and stores it on sock._account, which exposes the token in logs and intermediaries. Change the relay handshake in the upgrade path to accept the token through Sec-WebSocket-Protocol or an authenticated first message instead of ?token=, and update the accountFromToken-based parsing accordingly. Then coordinate the client-side connection logic and the shared auth integration test contract that currently appends relay.url + '?token=' + token so they use the new handshake mechanism consistently.server/src/index.cjs-730-769 (1)
730-769: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick winPassword reset/change doesn't revoke existing bearer tokens.
Neither
/reset-password(741-748) nor/change-password(764-767) revokes the account's outstanding tokens instore.tokens. If an attacker already holds a stolen/leaked bearer token, resetting or changing the password does not end their session — the old token stays valid until its naturalauthTtlMsexpiry (24h by default). Standard practice is to invalidate all other sessions on password change/reset.🔧 Suggested fix
acct.resetCode = null acct.resetExpiresAt = null acct.verified = true + for (const t of store.tokens) { + if (t.accountId === acct.id) { t.revokedAt = now() } + } saveStore() return sendJson(res, 200, { ok: true })Apply the equivalent loop in
/change-password.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@server/src/index.cjs` around lines 730 - 769, The password reset and change flows do not invalidate existing bearer sessions, so update both handlers to revoke outstanding tokens after a successful password update. In the /reset-password and /change-password cases in server/src/index.cjs, use the same account lookup symbols already present (acct, saveStore, store.tokens) to remove any tokens associated with that account before returning success, and apply the same token-revocation loop in /change-password as in /reset-password so old bearer tokens can no longer authenticate.
🟡 Minor comments (10)
shared/src/protocol.ts-53-55 (1)
53-55: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
encodeControlallows caller-suppliedvto override the stamped protocol version.
{ v: PROTOCOL_VERSION, ...msg }spreadsmsgafterv, so anyvproperty inmsg(permitted byBase.v?: number) silently overridesPROTOCOL_VERSION. No current caller setsv, but the type allows it. Reversing the spread order guarantees the stamp always wins.🔧 Proposed fix
export function encodeControl(msg: ControlMessage): string { - return JSON.stringify({ v: PROTOCOL_VERSION, ...msg }) + return JSON.stringify({ ...msg, v: PROTOCOL_VERSION }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/protocol.ts` around lines 53 - 55, The `encodeControl` function currently lets a caller-provided `v` in `ControlMessage` override the stamped `PROTOCOL_VERSION` because `msg` is spread after the version field. Update `encodeControl` in `shared/src/protocol.ts` so the protocol version always wins by reversing the object spread order, keeping the stamped version authoritative regardless of any `v` value on `msg`.shared/src/pinAuth.ts-26-31 (1)
26-31: 🔒 Security & Privacy | 🟡 Minor | ⚡ Quick winModulo bias in
generatePin.
arr[0] % (10 ** digits)introduces a small bias: for 6 digits, PINs 0–967295 are ~0.023% more likely than 967296–999999. Rejection sampling eliminates this entirely with negligible overhead (rejection probability ≈ 0.0225%).🔐 Proposed fix using rejection sampling
export function generatePin(digits = 6): string { + const max = 10 ** digits + const limit = Math.floor(0x100000000 / max) * max const arr = new Uint32Array(1) - globalThis.crypto.getRandomValues(arr) - const n = arr[0] % (10 ** digits) + do { + globalThis.crypto.getRandomValues(arr) + } while (arr[0] >= limit) + const n = arr[0] % max return n.toString().padStart(digits, '0') }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/src/pinAuth.ts` around lines 26 - 31, The PIN generation in generatePin uses a modulo operation on crypto randomness, which introduces bias in the output distribution. Update generatePin to use rejection sampling instead of arr[0] % (10 ** digits), reusing the existing Uint32Array/crypto.getRandomValues flow and looping until the sampled value falls within an unbiased range, so all PINs remain equally likely.clients/tabby/test/hostGuest.integration.test.ts-79-81 (1)
79-81: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winPump interval leaks if
waitFortimes out.If
waitFor(() => sawLive)rejects on timeout,clearInterval(pump)on line 81 is never reached. ThesetIntervalkeeps firingoutput$.next()for the remainder of the test process, potentially interfering with subsequent tests or causing noise.🛡️ Proposed fix: clear pump in a finally block
- const pump = setInterval(() => output$.next(enc('LIVE\r\n')), 15) - await waitFor(() => sawLive) - clearInterval(pump) + const pump = setInterval(() => output$.next(enc('LIVE\r\n')), 15) + try { + await waitFor(() => sawLive) + } finally { + clearInterval(pump) + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/test/hostGuest.integration.test.ts` around lines 79 - 81, The pump interval in hostGuest.integration.test.ts can leak when waitFor(() => sawLive) times out because clearInterval(pump) is skipped. Update the test around the setInterval, waitFor, and clearInterval flow to ensure the interval is always cleared, even on rejection, by wrapping the waitFor call in a try/finally structure tied to the pump variable.clients/tabby/src/host/share-info-modal.component.ts-43-48 (1)
43-48: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
copiedindicator shows even when clipboard write fails.
this.copied = whatis set unconditionally after the fire-and-forgetwriteTextcall. If the clipboard API rejects (permission denied, insecure context), the user sees "Link copied to clipboard" but the text was never copied.🛡️ Proposed fix: only show success on actual write
copy(text: string, what: string): void { if (navigator.clipboard) { - void navigator.clipboard.writeText(text) + navigator.clipboard.writeText(text).then(() => { + this.copied = what + }).catch(() => { + this.copied = 'Copy failed — select and copy manually' + }) + return } - this.copied = what + this.copied = 'Clipboard unavailable — select and copy manually' }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/host/share-info-modal.component.ts` around lines 43 - 48, The copy flow in share-info-modal.component.ts sets the `copied` state unconditionally in `copy()`, so the success indicator can appear even when `navigator.clipboard.writeText()` fails. Update `copy(text, what)` to await or handle the clipboard promise and set `this.copied = what` only after a successful write, leaving the state unchanged on rejection; use the `copy` method and `copied` field as the key places to adjust.shared/package.json-16-16 (1)
16-16: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winReplace the placeholder test script.
This package now has real tests under
shared/test, butnpm teststill just echoes a placeholder. Any package-level verification will silently skip the new coverage.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/package.json` at line 16, The package-level test script in shared/package.json is still a placeholder, so npm test never runs the real coverage under shared/test. Replace the current test script with one that actually executes the shared test suite, and keep the change scoped to the package.json test entry so package-level verification uses the new tests.clients/tabby/src/guest/mirrorTab.component.ts-42-51 (1)
42-51: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick winConsider calling
super.onFrontendReady()beforesession.start().
session.start()sends the join message, which triggers the server to send a snapshot. Ifsuper.onFrontendReady()performs critical xterm/frontend initialization, output data could arrive before the frontend is fully ready. Swapping these two lines ensures the base class setup completes first.💡 Proposed reorder
void session.start() - super.onFrontendReady() + super.onFrontendReady() + void session.start()🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/guest/mirrorTab.component.ts` around lines 42 - 51, The startup order in onFrontendReady is unsafe because session.start() can send the join message before the base frontend setup has completed. Reorder the calls in MirrorTabComponent.onFrontendReady so super.onFrontendReady() runs before session.start(), keeping the session creation, setSession, and hostResize$ subscription intact while ensuring the frontend is fully initialized before any snapshot/output arrives.clients/tabby/src/settings/settings-tab.component.ts-69-69 (1)
69-69: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winInconsistent optional chaining on
peershellconfig access.Line 69 uses
this.config.store.peershell?.serverUrl(safe), but line 76 usesthis.config.store.peershell.serverUrl(unsafe). Ifpeershellis everundefined/nullin the store,saveServerUrl()will throw aTypeError. Use consistent optional chaining or ensure the object exists before writing.🛡️ Proposed fix: ensure peershell object exists before writing
async saveServerUrl(): Promise<void> { + if (!this.config.store.peershell) { + this.config.store.peershell = {} as any + } this.config.store.peershell.serverUrl = this.serverUrl.trim() || null await this.config.save()Also applies to: 75-78
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/tabby/src/settings/settings-tab.component.ts` at line 69, `SettingsTabComponent` reads `this.config.store.peershell` safely in the initialization path, but `saveServerUrl()` writes to `this.config.store.peershell.serverUrl` without guarding against a missing `peershell` object. Update `saveServerUrl()` to use the same optional chaining pattern or ensure `peershell` is initialized before assignment, and keep the access consistent with the existing `serverUrl` setup in `SettingsTabComponent`.clients/web/src/index.ts-12-18 (2)
12-18: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
decodeURIComponentcan throw on malformed token in URL.If the path contains a malformed percent-encoding (e.g.,
/s/%E0%A),decodeURIComponentthrowsURIError, which propagates to the top-level catch and shows a cryptic"error: URIError: URI malformed"status. Wrap in a try/catch to show a user-friendly message.🛡️ Proposed fix
function getToken(): string | null { const m = /\/s\/([^/?#]+)/.exec(location.pathname) if (m) { - return decodeURIComponent(m[1]) + try { + return decodeURIComponent(m[1]) + } catch { + return null + } } return new URLSearchParams(location.search).get('token') }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/web/src/index.ts` around lines 12 - 18, The getToken function in clients/web/src/index.ts can throw on malformed percent-encoding when it calls decodeURIComponent on the /s/ token path segment. Update getToken to guard that decodeURIComponent call with a try/catch and return a safe fallback or null on failure, so the top-level error handling can show a user-friendly message instead of a raw URIError. Keep the fix focused around getToken and the token parsing logic.
12-18: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
decodeURIComponentcan throw on malformed token in URL.If the path contains a malformed percent-encoding (e.g.,
/s/%E0%A),decodeURIComponentthrowsURIError, which propagates to the top-level catch and shows a cryptic"error: URIError: URI malformed"status. Wrap in a try/catch to show a user-friendly message.🛡️ Proposed fix
function getToken(): string | null { const m = /\/s\/([^/?#]+)/.exec(location.pathname) if (m) { - return decodeURIComponent(m[1]) + try { + return decodeURIComponent(m[1]) + } catch { + return null + } } return new URLSearchParams(location.search).get('token') }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@clients/web/src/index.ts` around lines 12 - 18, The getToken helper in clients/web/src/index.ts should handle malformed percent-encoding safely, since decodeURIComponent can throw and bubble up as a cryptic URIError. Update getToken to wrap the decodeURIComponent(m[1]) call in a try/catch, returning a user-friendly failure path or null on bad input so the top-level flow can show a clearer message instead of crashing. Keep the fix scoped to getToken and its token parsing logic..github/workflows/codeql.yml-3-5 (1)
3-5: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winMake the best-effort CodeQL behavior explicit.
The comment says this workflow is non-required/best-effort for private repos without GHAS, but
analyzecan still leave every PR with a failed check. Addcontinue-on-erroruntil CodeQL is intended to be enforced.Proposed fix
- name: Analyze uses: github/codeql-action/analyze@v4 + continue-on-error: trueAlso applies to: 41-42
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In @.github/workflows/codeql.yml around lines 3 - 5, The CodeQL workflow is intended to be best-effort for now, but the current analyze job can still fail PR checks. Update the workflow to make this explicit by setting continue-on-error on the CodeQL analyze job or the relevant step until enforcement is intended. Use the workflow job around the CodeQL analyze configuration so the non-required behavior matches the existing comment.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: f0caff0a-f5db-4d27-9107-39bed7a79b74
⛔ Files ignored due to path filters (2)
.github/keys/peershell_release.pubis excluded by!**/*.pubpackage-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (70)
.eslintrc.cjs.github/scripts/release-policy.sh.github/workflows/ci.yml.github/workflows/codeql.yml.github/workflows/post-merge-release.yml.github/workflows/release-guard.yml.github/workflows/release-intake.yml.github/workflows/release.yml.gitignorePROTOCOL.mdREADME.mdUSER_GUIDE.mdclients/tabby/package.jsonclients/tabby/src/account/account.service.tsclients/tabby/src/account/login-modal.component.tsclients/tabby/src/config.tsclients/tabby/src/guest/mirrorSession.tsclients/tabby/src/guest/mirrorTab.component.tsclients/tabby/src/host/share-info-modal.component.tsclients/tabby/src/host/shareController.tsclients/tabby/src/index.tsclients/tabby/src/providers/tabContextMenu.tsclients/tabby/src/providers/toolbarButtonProvider.tsclients/tabby/src/services/peershell.service.tsclients/tabby/src/settings/settings-tab.component.tsclients/tabby/src/settings/settings-tab.provider.tsclients/tabby/src/types/tabby.d.tsclients/tabby/test/hostGuest.integration.test.tsclients/tabby/test/shareController.test.tsclients/tabby/test/smoke-load.cjsclients/tabby/tsconfig.jsonclients/tabby/webpack.config.mjsclients/web/package.jsonclients/web/src/index.htmlclients/web/src/index.tsclients/web/tsconfig.jsonclients/web/webpack.config.mjsjest.config.cjsjest.setup.cjspackage.jsonscripts/check-version-lockstep.mjsscripts/copy-web-asset.mjsscripts/package-plugin.mjsscripts/publish-plugins.mjsserver/package.jsonserver/src/README.mdserver/src/index.cjsserver/src/qrcode.jsshared/package.jsonshared/src/api.tsshared/src/base64.tsshared/src/httpTunnelHandler.tsshared/src/index.tsshared/src/mirrorController.tsshared/src/pinAuth.tsshared/src/protocol.tsshared/src/utf8Splitter.tsshared/src/websocketTransport.tsshared/test/auth.integration.test.tsshared/test/email.test.tsshared/test/httpTunnelHandler.test.tsshared/test/mirrorController.test.tsshared/test/pinAuth.test.tsshared/test/protocol.test.tsshared/test/transport.integration.test.tsshared/test/tunnel.integration.test.tsshared/test/utf8Splitter.test.tsshared/test/websocketTransport.test.tsshared/tsconfig.jsontsconfig.jest.json
…(+ Origin allowlist) Finding 4 (Greptile P2): the account bearer (host) and the magic-link token (web guest) rode on the WS upgrade URL as ?token=, where reverse-proxy/access logs capture them. - Client (WebSocketTransport): send the credential as a base64url subprotocol peershell.bearer.<...> alongside the non-secret sentinel peershell.v1, instead of appending ?token= to the URL. Widen the injected ctor to (url, protocols?) (satisfied by DOM WebSocket and the ws package). - Web guest: connect without a handshake credential; the magic-link token is already delivered in the join control frame (WS payload, never logged). - Server (ws): read the token from the Sec-WebSocket-Protocol header first, fall back to the legacy ?token= for one release; handleProtocols echoes ONLY the sentinel (never the token); verifyClient adds an Origin allowlist (CSWSH) that permits no-Origin/file:// clients (Node, Electron host) and the publicUrl origin (web guest), with '*' as an escape hatch. - Tests: account token via subprotocol authenticates create-session and the echoed subprotocol is the sentinel; cross-origin upgrade is rejected while the configured origin and no-Origin clients are allowed. Rollout is server-first (backward-compatible), then client.
Review triage: findings that are inaccurate or whose proposed fix would regressThanks for the thorough pass. We independently verified all 31 findings against the current
|
|
Tip For best results, initiate chat on the files or code changes. 🧩 Analysis chain🏁 Script executed: #!/bin/bash
set -euo pipefail
echo "=== mirrorController.ts ==="
cat -n shared/src/mirrorController.ts
echo "=== mirrorTab.component.ts ==="
cat -n clients/tabby/src/guest/mirrorTab.component.ts
echo "=== settings-tab.component.ts ==="
cat -n clients/tabby/src/settings/settings-tab.component.ts
echo "=== account.service.ts refresh (if exists) ==="
rg -n "refresh" clients/tabby/src/account/account.service.ts clients/tabby/src/settings/settings-tab.component.ts -A5 -B5
echo "=== server/src/index.cjs rate limit maps ==="
rg -n "loginFails|regByIp" server/src/index.cjs -A5 -B5
echo "=== qrcode.js renderTo2dContext usage across repo ==="
rg -n "renderTo2dContext" --type=js --type=ts -C3
echo "=== qrcode.js fillRect ==="
rg -n "fillRect" server/src/qrcode.js -B3 -A3Length of output: 20231
I've recorded these as learnings so future reviews on this repo don't resurface the same flawed fixes. Looking forward to the follow-up commits for the valid items. (◕‿◕✿) ✏️ Learnings added
|
…through end()
end() now closes the transport after notifying the sink so the web client's
WebSocket + keepalive no longer leak until the server reaper reclaims them (#9).
answerPin's cancel branch goes through end('guest-closed') so sink.ended fires
(stops the web re-prompt loop, destroys the Tabby tab) while still closing the
transport (#8). close() is unchanged and remains the Tabby kill() teardown entry.
…k token Gate the cached PIN on a sessionEstablished flag so a wrong PIN is re-prompted on the host's re-challenge instead of silently replayed until retries run out (#12); the cache is still reused for a genuine reconnect. Wrap decodeURIComponent in getToken so a malformed %-escape falls through to the missing-token path (#29).
…d error Scope beginStream()'s output$/resize$ forwarders in a per-session Subscription torn down on peer-left, so a re-joining guest no longer stacks duplicate forwarders (also closes the guard-less resize$ leak) (#1). Route pin-response verification failures through onError instead of an unhandled rejection (#6). On an unauthorized onError, clear establishTimer and stopSharing immediately instead of leaving a dead session up until the 5-min timer (#10).
…e-limit maps Password reset revokes all of the account's bearer tokens; password change revokes every token except the caller's current one, so other sessions are invalidated while the active session stays logged in (#21). The reaper now prunes loginFails and regByIp so they cannot grow unbounded (incl. a bogus-email flood), evicting a loginFails entry only when it has no active lock AND has been idle past 4x the lock window, so an in-progress bruteforce and the blocks escalation are never reset (#19).
Use lockfile-strict 'npm ci' (drop the '|| npm install' fallback) in ci and release so lockfile drift fails fast on a signed/published artifact (#15, #16). Add persist-credentials: false to the read-only release-guard checkout (#14). Source the release policy in post-merge-release from the pre-merge parent (MERGE_SHA^), the trusted ancestor, with a bootstrap fallback (#17). Validate the release tag and workspace version-lockstep before publishing (#18). CodeQL: the repo is public and code scanning runs, so keep analyze strict and correct the stale 'private' comment (#31).
connect() now settles exactly once and rejects on a pre-open close or a 15s connection timeout instead of hanging forever (#7). account.service fetch() uses an AbortController with a 20s timeout and returns a distinct 'timeout' error so the login modal recovers instead of staying stuck busy; add the matching ERRORS entry (#5).
There was a problem hiding this comment.
🧹 Nitpick comments (1)
shared/test/auth.integration.test.ts (1)
166-178: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider extracting the
posthelper to avoid duplication.The
posthelper defined here is a near-exact copy of the one defined earlier in the file (lines 32-53), differing only in the base URL (base2vs the shared server's base). Extracting a parameterizedpostTo(base, path, body)would eliminate the duplication and make it easier to add more isolated relay tests in the future.♻️ Optional refactor
-const post = (path: string, body: any): Promise<{ status: number, json: any }> => new Promise((resolve, reject) => { - const data = Buffer.from(JSON.stringify(body)) - const u = new URL(base2 + path) - const req = http.request({ hostname: u.hostname, port: u.port, path: u.pathname, method: 'POST', headers: { 'content-type': 'application/json', 'content-length': data.length } }, res => { - let b = '' - res.setEncoding('utf-8') - res.on('data', c => { b += c }) - res.on('end', () => { try { resolve({ status: res.statusCode ?? 0, json: JSON.parse(b || '{}') }) } catch { resolve({ status: res.statusCode ?? 0, json: {} }) } }) - }) - req.on('error', reject) - req.write(data) - req.end() -}) +// Reuse a shared helper that accepts a base URL, e.g.: +// const postTo = (base: string, path: string, body: any) => { ... } +// Then call: postTo(base2, '/register', { ... })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@shared/test/auth.integration.test.ts` around lines 166 - 178, The local `post` helper in `auth.integration.test.ts` duplicates the earlier request helper almost exactly, so refactor it into a shared parameterized helper like `postTo(base, path, body)` and reuse it from both test sections. Keep the existing HTTP request/JSON parsing behavior intact, but pass the target base URL (`base` or `base2`) through the shared helper so future relay tests can call the same function without copying the implementation.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@shared/test/auth.integration.test.ts`:
- Around line 166-178: The local `post` helper in `auth.integration.test.ts`
duplicates the earlier request helper almost exactly, so refactor it into a
shared parameterized helper like `postTo(base, path, body)` and reuse it from
both test sections. Keep the existing HTTP request/JSON parsing behavior intact,
but pass the target base URL (`base` or `base2`) through the shared helper so
future relay tests can call the same function without copying the
implementation.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: da34e797-03ab-4f9d-8344-0e80ba5cdeaa
📒 Files selected for processing (25)
.github/workflows/ci.yml.github/workflows/codeql.yml.github/workflows/post-merge-release.yml.github/workflows/release-guard.yml.github/workflows/release.ymlPROTOCOL.mdclients/tabby/src/account/account.service.tsclients/tabby/src/account/login-modal.component.tsclients/tabby/src/config.tsclients/tabby/src/host/share-info-modal.component.tsclients/tabby/src/host/shareController.tsclients/tabby/src/services/peershell.service.tsclients/tabby/src/settings/settings-tab.component.tsclients/tabby/test/hostGuest.integration.test.tsclients/tabby/test/shareController.test.tsclients/web/src/index.tsserver/src/index.cjsshared/src/base64.tsshared/src/mirrorController.tsshared/src/pinAuth.tsshared/src/protocol.tsshared/src/websocketTransport.tsshared/test/auth.integration.test.tsshared/test/mirrorController.test.tsshared/test/websocketTransport.test.ts
✅ Files skipped from review due to trivial changes (1)
- PROTOCOL.md
🚧 Files skipped from review as they are similar to previous changes (18)
- clients/tabby/src/config.ts
- .github/workflows/ci.yml
- shared/src/base64.ts
- .github/workflows/codeql.yml
- .github/workflows/release-guard.yml
- clients/tabby/test/hostGuest.integration.test.ts
- .github/workflows/release.yml
- shared/src/mirrorController.ts
- clients/tabby/src/host/share-info-modal.component.ts
- shared/src/pinAuth.ts
- clients/tabby/src/account/login-modal.component.ts
- clients/tabby/src/account/account.service.ts
- shared/src/protocol.ts
- .github/workflows/post-merge-release.yml
- clients/tabby/src/services/peershell.service.ts
- clients/web/src/index.ts
- server/src/index.cjs
- clients/tabby/src/host/shareController.ts
The two isolated-relay test sections each re-implemented the same POST-JSON request logic; consolidate them into a single postTo(base, path, body) so future relay tests reuse it instead of copying. Behavior unchanged.
…state
The web guest reuses one WebSocketTransport across reconnects; connect() overwrote
this.ws without unbinding the previous socket, so a stale onclose/onmessage (e.g.
the async close that follows a connect-timeout ws.close()) kept driving setState()/
dispatch() on the new connection. Add teardownSocket() (detach handlers, then close,
then null this.ws), call it at connect() start and in the timeout branch, and add a
this.ws===ws identity guard on every socket handler. This also removes the duplicate
setState('closed') the timeout branch used to emit. Addresses code-review finding D.
Revoking bearer tokens only blocks FUTURE handshakes; a host WebSocket bound its account at connect time and kept streaming after a security-motivated password reset. Bind the authorizing token hash per socket (sock._tokenHash) and add terminateAccountSessions(): /reset-password drops ALL of the account's live host sessions (a reset is a lockout), /change-password drops all except the caller's current one. The socket's close handler notifies the guest and dropRoom()s. Addresses code-review finding A.
…sh timers The grace and establish timers were local closures, so any teardown that removed a share from the map (onError unauthorized, or either timer firing) could leave the sibling timer armed. Since startSharing() bails while shares.has(tab), the host can re-share the tab and the stale timer then fires stopSharing() on the NEW share. Store both timers per-tab in shareTimers and cancel them via clearShareTimers() from every teardown path (stopSharing, destroyed$, connect-failure catch), so no timer outlives its share. Addresses code-review finding C (and the scattered-timer-ownership nit).
…t just the fetch The AbortController timeout was cleared in a finally wrapping only fetch(), so a server that streamed headers then stalled the body hung forever at res.json(), leaving the login modal stuck with busy=true and its Close button disabled. Move res.json() inside the timed try (a single finally clears the timer) so the signal bounds the body read too, and rethrow an AbortError from the body read as a timeout while still tolerating empty/non-json bodies. Addresses code-review finding B.
…escalation The comment claimed pruning cannot reset the blocks escalation; that only holds for an actively-guessing attacker (r.at refreshed). An entry left idle past the TTL is dropped and its escalation resets, an acceptable bound since the base 5-fail lock re-applies to any renewed attack. Comment only; no behavior change. (review nit E)
… re-enter end() close() (the Tabby tab-kill path) now sets endedFlag before tearing down the transport, so a control frame racing the kill cannot re-enter end() and drive sink.ended() on an already-destroyed guest. Addresses code-review finding F (#11).
…ded session verifyResponse wraps verifyPin in try/catch so a verify error (e.g. crypto unavailable) counts as a failed attempt: the guest is told via pin-fail and eventually kicked instead of hanging on a silently un-joinable session, and the host is not stranded until the 5-min timer. Addresses code-review finding G.
…sever the socket onerror, the reject-before-open onclose, and the connect timeout now all funnel through a single failConnect() that teardownSocket()s the failed socket (detach handlers, close, null this.ws). Previously only the timeout severed it, so a socket rejected before open stayed attached and a late onmessage could still reach dispatch(). Closes the code-review D nit; adds a regression test.
The destroyed$ subscription was created on every startSharing without being stored or unsubscribed, so re-sharing a tab accumulated stale subscribers on its Subject. Store it in the per-tab shareTimers record and unsubscribe it in clearShareTimers, so exactly one live subscription exists per active share. Closes the code-review C nit.
…tocol only) The account token now rides ONLY in the Sec-WebSocket-Protocol subprotocol, never the URL, so it stays out of reverse-proxy/access logs. No client used the URL fallback (the host sends the token in the subprotocol; the web guest sends no token on the handshake and delivers its magic-link token in the join frame). The gate test is migrated to the subprotocol and asserts a token in the URL is now rejected. Closes CodeRabbit #20 (removed after the one-release compat window).
Per the project no-em-dash convention, replace every em/en dash in source (notifications, modal/settings/login UI text, the plugin-loaded log line, and code comments) with plain punctuation. Display/comment-only; no behavior change.
…nd package metadata Complete the no-em-dash sweep beyond source: README, PROTOCOL, USER_GUIDE, the three published package.json descriptions, and the version-lockstep script message. Replace em dashes with plain punctuation (colon/comma/semicolon) and non-breaking hyphens with regular hyphens; arrows (->) left as-is. The repo is now free of em/en/nb dashes.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@README.md`:
- Around line 6-7: Update the README text to replace “in future” with “in the
future” in the sentence describing access from a dedicated mobile app or
terminal.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 01bff2ab-7fd1-4d63-a138-c9ad462db6cc
📒 Files selected for processing (22)
PROTOCOL.mdREADME.mdUSER_GUIDE.mdclients/tabby/package.jsonclients/tabby/src/account/account.service.tsclients/tabby/src/account/login-modal.component.tsclients/tabby/src/host/share-info-modal.component.tsclients/tabby/src/host/shareController.tsclients/tabby/src/index.tsclients/tabby/src/services/peershell.service.tsclients/tabby/src/settings/settings-tab.component.tsclients/web/package.jsonscripts/check-version-lockstep.mjsserver/src/index.cjsshared/package.jsonshared/src/httpTunnelHandler.tsshared/src/mirrorController.tsshared/src/protocol.tsshared/src/websocketTransport.tsshared/test/auth.integration.test.tsshared/test/mirrorController.test.tsshared/test/websocketTransport.test.ts
✅ Files skipped from review due to trivial changes (2)
- clients/tabby/package.json
- PROTOCOL.md
🚧 Files skipped from review as they are similar to previous changes (15)
- clients/web/package.json
- shared/package.json
- scripts/check-version-lockstep.mjs
- shared/src/httpTunnelHandler.ts
- clients/tabby/src/index.ts
- shared/test/mirrorController.test.ts
- clients/tabby/src/host/share-info-modal.component.ts
- shared/src/protocol.ts
- shared/src/mirrorController.ts
- shared/src/websocketTransport.ts
- clients/tabby/src/settings/settings-tab.component.ts
- clients/tabby/src/services/peershell.service.ts
- clients/tabby/src/account/account.service.ts
- clients/tabby/src/account/login-modal.component.ts
- clients/tabby/src/host/shareController.ts
| local: from another **Tabby** (via the `tabby-peershell` plugin), from a **browser** (via a magic-link), | ||
| and, in future, from a dedicated **mobile app** or **our own terminal**. Same wire protocol everywhere. |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use “in the future” for consistent US-English wording.
Replace “in future” with “in the future.”
🧰 Tools
🪛 LanguageTool
[locale-violation] ~7-~7: The phrase ‘in future’ is British English. Did you mean: “in the future”?
Context: ... a browser (via a magic-link), and, in future, from a dedicated mobile app or **o...
(IN_FUTURE)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@README.md` around lines 6 - 7, Update the README text to replace “in future”
with “in the future” in the sentence describing access from a dedicated mobile
app or terminal.
Source: Linters/SAST tools
Automated release PR for
v0.1.0-beta.Summary by CodeRabbit
Greptile Summary
This is the initial
v0.1.0-betarelease of peershell — a live terminal-sharing plugin for Tabby with a matching web guest client, a shared protocol library, and a Node.js relay/auth server. All 72 files are new additions.Sec-WebSocket-Protocol(not the URL), PIN auth uses SHA-256 over a single-use nonce with rejection-sampling PIN generation, and input is gated behind a fullauthenticatedflag./login,/verify-email, and/reset-password.Confidence Score: 5/5
Safe to merge; three minor hardening gaps in the relay server, no blocking defects.
The core security properties — rate-limited auth, rejection-sampling PIN generation, scrypt password hashing, bearer token in WebSocket subprotocol header, per-session nonce PIN challenge, and input gating behind authentication — are all correctly implemented. Previous issues with rate limiting, modulo bias, and token URL exposure have been addressed. The three new findings are hardening opportunities with no practical exploit path in this release.
server/src/index.cjs — three hardening gaps: the http-response dispatch before the role check (line 1002), the unauthenticated /health account count (line 903), and the TOTP anti-replay gap (line 222).
Important Files Changed
Reviews (3): Last reviewed commit: "style(docs): remove em/en dashes and non..." | Re-trigger Greptile