diff --git a/.docs/remote-architecture.md b/.docs/remote-architecture.md new file mode 100644 index 0000000000..32e35d7caf --- /dev/null +++ b/.docs/remote-architecture.md @@ -0,0 +1,302 @@ +# Remote Architecture + +This document describes the target architecture for first-class remote environments in T3 Code. + +It is intentionally architecture-first. It does not define a complete implementation plan or user-facing rollout checklist. The goal is to establish the core model so remote support can be added without another broad rewrite. + +## Goals + +- Treat remote environments as first-class product primitives, not special cases. +- Support multiple ways to reach the same environment. +- Keep the T3 server as the execution boundary. +- Let desktop, mobile, and web all share the same conceptual model. +- Avoid introducing a local control plane unless product pressure proves it is necessary. + +## Non-goals + +- Replacing the existing WebSocket server boundary with a custom transport protocol. +- Making SSH the only remote story. +- Syncing provider auth across machines. +- Shipping every access method in the first iteration. + +## High-level architecture + +T3 already has a clean runtime boundary: the client talks to a T3 server over HTTP/WebSocket, and the server owns orchestration, providers, terminals, git, and filesystem operations. + +Remote support should preserve that boundary. + +```text +┌──────────────────────────────────────────────┐ +│ Client (desktop / mobile / web) │ +│ │ +│ - known environments │ +│ - connection manager │ +│ - environment-aware routing │ +└───────────────┬──────────────────────────────┘ + │ + │ resolves one access endpoint + │ +┌───────────────▼──────────────────────────────┐ +│ Access method │ +│ │ +│ - direct ws / wss │ +│ - tunneled ws / wss │ +│ - desktop-managed ssh bootstrap + forward │ +└───────────────┬──────────────────────────────┘ + │ + │ connects to one T3 server + │ +┌───────────────▼──────────────────────────────┐ +│ Execution environment = one T3 server │ +│ │ +│ - environment identity │ +│ - provider state │ +│ - projects / threads / terminals │ +│ - git / filesystem / process runtime │ +└──────────────────────────────────────────────┘ +``` + +The important decision is that remoteness is expressed at the environment connection layer, not by splitting the T3 runtime itself. + +## Domain model + +### ExecutionEnvironment + +An `ExecutionEnvironment` is one running T3 server instance. + +It is the unit that owns: + +- provider availability and auth state +- model availability +- projects and threads +- terminal processes +- filesystem access +- git operations +- server settings + +It is identified by a stable `environmentId`. + +This is the shared cross-client primitive. Desktop, mobile, and web should all reason about the same concept here. + +### KnownEnvironment + +A `KnownEnvironment` is a client-side saved entry for an environment the client knows how to reach. + +It is not server-authored. It is local to a device or client profile. + +Examples: + +- a saved LAN URL +- a saved public `wss://` endpoint +- a desktop-managed SSH host entry +- a saved tunneled environment + +A known environment may or may not know the target `environmentId` before first successful connect. + +### AccessEndpoint + +An `AccessEndpoint` is one concrete way to reach a known environment. + +This is the key abstraction that keeps SSH from taking over the model. + +A single environment may have many endpoints: + +- `wss://t3.example.com` +- `ws://10.0.0.25:3773` +- a tunneled relay URL +- a desktop-managed SSH tunnel that resolves to a local forwarded WebSocket URL + +The environment stays the same. Only the access path changes. + +### RepositoryIdentity + +`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments. + +It is not used for routing. It is only used for UI grouping and correlation between local and remote clones of the same repository. + +### Workspace / Project + +The current `Project` model remains environment-local. + +That means: + +- a local clone and a remote clone are different projects +- they may share a `RepositoryIdentity` +- threads still bind to one project in one environment + +## Access methods + +Access methods answer one question: + +How does the client speak WebSocket to a T3 server? + +They do not answer: + +- how the server got started +- who manages the server process +- whether the environment is local or remote + +### 1. Direct WebSocket access + +Examples: + +- `ws://10.0.0.15:3773` +- `wss://t3.example.com` + +This is the base model and should be the first-class default. + +Benefits: + +- works for desktop, mobile, and web +- no client-specific process management required +- best fit for hosted or self-managed remote T3 deployments + +### 2. Tunneled WebSocket access + +Examples: + +- public relay URLs +- private network relay URLs +- local tunnel products such as pipenet + +This is still direct WebSocket access from the client's perspective. The difference is that the route is mediated by a tunnel or relay. + +For T3, tunnels are best modeled as another `AccessEndpoint`, not as a different kind of environment. + +This is especially useful when: + +- the host is behind NAT +- inbound ports are unavailable +- mobile must reach a desktop-hosted environment +- a machine should be reachable without exposing raw LAN or public ports + +### 3. Desktop-managed SSH access + +SSH is an access and launch helper, not a separate environment type. + +The desktop main process can use SSH to: + +- reach a machine +- probe it +- launch or reuse a remote T3 server +- establish a local port forward + +After that, the renderer should still connect using an ordinary WebSocket URL against the forwarded local port. + +This keeps the renderer transport model consistent with every other access method. + +## Launch methods + +Launch methods answer a different question: + +How does a T3 server come to exist on the target machine? + +Launch and access should stay separate in the design. + +### 1. Pre-existing server + +The simplest launch method is no launch at all. + +The user or operator already runs T3 on the target machine, and the client connects through a direct or tunneled WebSocket endpoint. + +This should be the first remote mode shipped because it validates the environment model with minimal extra machinery. + +### 2. Desktop-managed remote launch over SSH + +This is the main place where Zed is a useful reference. + +Useful ideas to borrow from Zed: + +- remote probing +- platform detection +- session directories with pid/log metadata +- reconnect-friendly launcher behavior +- desktop-owned connection UX + +What should be different in T3: + +- no custom stdio/socket proxy protocol between renderer and remote runtime +- no attempt to make the remote runtime look like an editor transport +- keep the final client-to-server connection as WebSocket + +The recommended T3 flow is: + +1. Desktop connects over SSH. +2. Desktop probes the remote machine and verifies T3 availability. +3. Desktop launches or reuses a remote T3 server. +4. Desktop establishes local port forwarding. +5. Renderer connects to the forwarded WebSocket endpoint as a normal environment. + +### 3. Client-managed local publish + +This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel. + +This is useful for: + +- exposing a desktop-hosted environment to mobile +- temporary remote access without changing router or firewall settings + +This is still a launch concern, not a new environment kind. + +## Why access and launch must stay separate + +These concerns are easy to conflate, but separating them prevents architectural drift. + +Examples: + +- A manually hosted T3 server might be reached through direct `wss`. +- The same server might also be reachable through a tunnel. +- An SSH-managed server might be launched over SSH but then reached through forwarded WebSocket. +- A local desktop server might be published through a tunnel for mobile. + +In all of those cases, the `ExecutionEnvironment` is the same kind of thing. + +Only the launch and access paths differ. + +## Security model + +Remote support must assume that some environments will be reachable over untrusted networks. + +That means: + +- remote-capable environments should require explicit authentication +- tunnel exposure should not rely on obscurity +- client-saved endpoints should carry enough auth metadata to reconnect safely + +T3 already supports a WebSocket auth token on the server. That should become a first-class part of environment access rather than remaining an incidental query parameter convention. + +For publicly reachable environments, authenticated access should be treated as required. + +## Relationship to Zed + +Zed is a useful reference implementation for managed remote launch and reconnect behavior. + +The relevant lessons are: + +- remote bootstrap should be explicit +- reconnect should be first-class +- connection UX belongs in the client shell +- runtime ownership should stay clearly on the remote host + +The important mismatch is transport shape. + +Zed needs a custom proxy/server protocol because its remote boundary sits below the editor and project runtime. + +T3 should not copy that part. + +T3 already has the right runtime boundary: + +- one T3 server per environment +- ordinary HTTP/WebSocket between client and environment + +So T3 should borrow Zed's launch discipline, not its transport protocol. + +## Recommended rollout + +1. First-class known environments and access endpoints. +2. Direct `ws` / `wss` remote environments. +3. Authenticated tunnel-backed environments. +4. Desktop-managed SSH launch and forwarding. +5. Multi-environment UI improvements after the base runtime path is proven. + +This ordering keeps the architecture network-first and transport-agnostic while still leaving room for richer managed remote flows. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f521ced14c..5c2d2c8381 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,7 +72,7 @@ jobs: - name: Verify preload bundle output run: | test -f apps/desktop/dist-electron/preload.js - grep -nE "desktopBridge|getWsUrl|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js + grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js release_smoke: name: Release Smoke diff --git a/.oxfmtrc.json b/.oxfmtrc.json index a3e32c9797..776d11b803 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -9,7 +9,8 @@ "bun.lock", "*.tsbuildinfo", "**/routeTree.gen.ts", - "apps/web/public/mockServiceWorker.js" + "apps/web/public/mockServiceWorker.js", + "apps/web/src/lib/vendor/qrcodegen.ts" ], "sortPackageJson": {} } diff --git a/.plans/18-server-auth-model.md b/.plans/18-server-auth-model.md new file mode 100644 index 0000000000..9f8ba8a05d --- /dev/null +++ b/.plans/18-server-auth-model.md @@ -0,0 +1,823 @@ +# Server Auth Model Plan + +## Purpose + +Define the long-term server auth architecture for T3 Code before first-class remote environments ship. + +This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods. + +This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code. + +## Primary goals + +- Make auth server-wide, not WebSocket-only. +- Make insecure exposure hard to do accidentally. +- Preserve zero-login local desktop UX for desktop-managed environments. +- Support browser-native pairing and session auth. +- Leave room for native/mobile credentials later without rewriting the server boundary. +- Keep auth separate from transport and launch method. + +## Non-goals + +- Full multi-user authorization and RBAC. +- OAuth / SSO / enterprise identity. +- Passkeys or biometric UX in v1. +- Syncing auth state across environments. +- Designing the full remote environment product in this document. + +## Core decisions + +### 1. Auth is a server concern + +Every privileged surface of the T3 server must go through the same auth policy engine: + +- HTTP routes +- WebSocket upgrades +- RPC methods reached through WebSocket + +The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product. + +### 2. Pairing and session are different things + +The system should distinguish: + +- bootstrap credentials +- session credentials + +Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated. + +Session credentials are the durable credentials used after pairing. + +Bootstrap should never become the long-lived request credential. + +### 3. Auth and transport are separate + +Auth must not be defined by how the client reached the server. + +Examples: + +- local desktop-managed server +- LAN `ws://` +- public `wss://` +- tunneled `wss://` +- SSH-forwarded `ws://127.0.0.1:` + +All of these should feed into the same auth model. + +### 4. Exposure level changes defaults + +The more exposed an environment is, the narrower the safe default should be. + +Safe default expectations: + +- local desktop-managed: auto-pair allowed +- loopback browser access: explicit bootstrap allowed +- non-loopback bind: auth required +- tunnel/public endpoint: auth required, explicit enablement required + +### 5. Browser and native clients may use different session credentials + +The auth model should support more than one session credential type even if only one ships first. + +Examples: + +- browser session cookie +- native bearer/device token + +This should be represented in the model now, even if browser cookies are the first implementation. + +## Target auth domain + +### Route classes + +Every route or transport entrypoint should be classified as one of: + +1. `public` +2. `bootstrap` +3. `authenticated` + +#### `public` + +Unauthenticated by definition. + +Should be extremely small. Examples: + +- static shell needed to render the pairing/login UI +- favicon/assets required for the pairing screen +- a minimal server health/version endpoint if needed + +#### `bootstrap` + +Used only to exchange a bootstrap credential for a session. + +Examples: + +- Initial bootstrap envelope over file descriptor at startup +- `POST /api/auth/bootstrap` +- `GET /api/auth/session` if unauthenticated checks are part of bootstrap UX + +#### `authenticated` + +Everything that reveals machine state or mutates it. + +Examples: + +- WebSocket upgrade +- orchestration snapshot and events +- terminal open/write/close +- project search and file writes +- git routes +- attachments +- project favicon lookup +- server settings + +The default stance should be: if it touches the machine, it is authenticated. + +## Credential model + +### Bootstrap credentials + +Initial credential types to model: + +- `desktop-bootstrap` +- `one-time-token` + +Possible future credential types: + +- `device-code` +- `passkey-assertion` +- `external-identity` + +#### `desktop-bootstrap` + +Used when the desktop shell manages the server and should be the only default pairing method for desktop-local environments. + +Properties: + +- launcher-provided +- short-lived +- one-time or bounded-use +- never shown to the user as a reusable password + +#### `one-time-token` + +Used for explicit browser/mobile pairing flows. + +Properties: + +- short TTL +- one-time use +- safe to embed in a pairing URL fragment +- exchanged for a session credential + +### Session credentials + +Initial credential types to model: + +- `browser-session-cookie` +- `bearer-session-token` + +#### `browser-session-cookie` + +Primary browser credential. + +Properties: + +- signed +- `HttpOnly` +- bounded lifetime +- revocable by server key rotation or session invalidation + +#### `bearer-session-token` + +Reserved for native/mobile or non-browser clients. + +Properties: + +- opaque token, not a bootstrap secret +- long enough lifetime to survive reconnects +- stored in secure client storage when available + +## Auth policy model + +Auth behavior should be driven by an explicit environment auth policy, not route-local heuristics. + +### Policy examples + +#### `DesktopManagedLocalPolicy` + +Default for desktop-managed local server. + +Allowed bootstrap methods: + +- `desktop-bootstrap` + +Allowed session methods: + +- `browser-session-cookie` + +Disabled by default: + +- `one-time-token` +- `bearer-session-token` +- password login +- public pairing + +#### `LoopbackBrowserPolicy` + +Used for browser access on localhost without desktop-managed bootstrap. + +Allowed bootstrap methods: + +- `one-time-token` + +Allowed session methods: + +- `browser-session-cookie` + +#### `RemoteReachablePolicy` + +Used when binding non-loopback or using an explicit remote/tunnel workflow. + +Allowed bootstrap methods: + +- `one-time-token` +- possibly `desktop-bootstrap` when a desktop shell is brokering access + +Allowed session methods: + +- `browser-session-cookie` +- `bearer-session-token` + +#### `UnsafeNoAuthPolicy` + +Should exist only as an explicit escape hatch. + +Requirements: + +- explicit opt-in flag +- loud startup warnings +- never defaulted automatically + +## Effect-native service model + +### `ServerAuth` + +The main auth facade used by HTTP routes and WebSocket upgrade handling. + +Responsibilities: + +- classify requests +- authenticate requests +- authorize bootstrap attempts +- create sessions from bootstrap credentials +- enforce policy by environment mode + +Sketch: + +```ts +export interface ServerAuthShape { + readonly getCapabilities: Effect.Effect; + readonly authenticateHttpRequest: ( + request: HttpServerRequest.HttpServerRequest, + routeClass: RouteAuthClass, + ) => Effect.Effect; + readonly authenticateWebSocketUpgrade: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly exchangeBootstrapCredential: ( + input: BootstrapExchangeInput, + ) => Effect.Effect; +} + +export class ServerAuth extends ServiceMap.Service()( + "t3/ServerAuth", +) {} +``` + +### `BootstrapCredentialService` + +Owns issuance, storage, validation, and consumption of bootstrap credentials. + +Responsibilities: + +- issue desktop bootstrap grants +- issue one-time pairing tokens +- validate TTL and single-use semantics +- consume bootstrap grants atomically + +Sketch: + +```ts +export interface BootstrapCredentialServiceShape { + readonly issueDesktopBootstrap: ( + input: IssueDesktopBootstrapInput, + ) => Effect.Effect; + readonly issueOneTimeToken: ( + input: IssueOneTimeTokenInput, + ) => Effect.Effect; + readonly consume: ( + presented: PresentedBootstrapCredential, + ) => Effect.Effect; +} +``` + +### `SessionCredentialService` + +Owns creation and validation of authenticated sessions. + +Responsibilities: + +- mint cookie sessions +- mint bearer sessions +- validate active session credentials +- revoke sessions if needed later + +Sketch: + +```ts +export interface SessionCredentialServiceShape { + readonly createBrowserSession: ( + input: CreateSessionFromBootstrapInput, + ) => Effect.Effect; + readonly createBearerSession: ( + input: CreateSessionFromBootstrapInput, + ) => Effect.Effect; + readonly authenticateCookie: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly authenticateBearer: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; +} +``` + +### `ServerAuthPolicy` + +Pure policy/config service that decides which credential types are allowed. + +Responsibilities: + +- map runtime mode and bind/exposure settings to allowed auth methods +- answer whether a route can be public +- answer whether remote exposure requires auth + +This should stay mostly pure and cheap to test. + +### `ServerSecretStore` + +Owns long-lived server signing keys and secrets. + +Responsibilities: + +- get or create signing key +- rotate signing key +- abstract secure OS-backed storage vs filesystem fallback + +Important: + +- prefer platform secure storage when available +- support hardened filesystem fallback for headless/server-only environments + +### `BrowserSessionCookieCodec` + +Focused utility service for cookie encode/decode/signing behavior. + +This should not own policy. It should only own the cookie format. + +### `AuthRouteGuards` + +Thin helper layer used by routes to enforce auth consistently. + +Responsibilities: + +- require auth for HTTP route handlers +- classify route auth mode +- convert auth failures into `401` / `403` + +This prevents every route from re-implementing the same pattern. + +Integrates with `HttpRouter.middleware` to enforce auth consistently. + +## Suggested layer graph + +```text +ServerSecretStore + ├─> BootstrapCredentialService + ├─> BrowserSessionCookieCodec + └─> SessionCredentialService + +ServerAuthPolicy + ├─> BootstrapCredentialService + ├─> SessionCredentialService + └─> ServerAuth + +ServerAuth + └─> AuthRouteGuards +``` + +Layer naming should follow existing repo style: + +- `ServerSecretStoreLive` +- `BootstrapCredentialServiceLive` +- `SessionCredentialServiceLive` +- `ServerAuthPolicyLive` +- `ServerAuthLive` +- `AuthRouteGuardsLive` + +## High-level implementation examples + +### Example: WebSocket upgrade auth + +Current state: + +- `authToken` query param is checked in [`ws.ts`](../apps/server/src/ws.ts) + +Target shape: + +```ts +const websocketUpgradeAuth = HttpMiddleware.make((httpApp) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + yield* serverAuth.authenticateWebSocketUpgrade(request); + return yield* httpApp; + }), +); +``` + +Then the `/ws` route becomes: + +```ts +export const websocketRpcRouteLayer = HttpRouter.add( + "GET", + "/ws", + rpcWebSocketHttpEffect.pipe( + websocketUpgradeAuth, + Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)), + ), +); +``` + +This keeps the route itself declarative and makes auth compose like normal HTTP middleware. + +### Example: authenticated HTTP route + +For routes like attachments or project favicon: + +```ts +const authenticatedRoute = (routeClass: RouteAuthClass) => + HttpMiddleware.make((httpApp) => + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + yield* serverAuth.authenticateHttpRequest(request, routeClass); + return yield* httpApp; + }), + ); +``` + +Then: + +```ts +export const attachmentsRouteLayer = HttpRouter.add( + "GET", + `${ATTACHMENTS_ROUTE_PREFIX}/*`, + serveAttachment.pipe( + authenticatedRoute(RouteAuthClass.Authenticated), + Effect.catchTag("AuthError", (error) => toUnauthorizedResponse(error)), + ), +); +``` + +### Example: desktop bootstrap exchange + +The desktop shell launches the local server and gets a short-lived bootstrap grant through a trusted side channel. + +That grant is then exchanged for a browser cookie session when the renderer loads. + +Sketch: + +```ts +const pairDesktopRenderer = Effect.gen(function* () { + const bootstrapService = yield* BootstrapCredentialService; + const credential = yield* bootstrapService.issueDesktopBootstrap({ + audience: "desktop-renderer", + ttlMs: 30_000, + }); + return credential; +}); +``` + +The renderer then calls a bootstrap endpoint and receives a cookie session. The bootstrap credential is consumed and becomes invalid. + +### Example: one-time pairing URL + +For browser-driven pairing: + +```ts +const createPairingToken = Effect.gen(function* () { + const bootstrapService = yield* BootstrapCredentialService; + return yield* bootstrapService.issueOneTimeToken({ + ttlMs: 5 * 60_000, + audience: "browser", + }); +}); +``` + +The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it. + +## Sequence diagrams + +These flows are meant to anchor the auth model in concrete user journeys. + +The important invariant across all of them is: + +- access method is not the auth method +- launch method is not the auth method +- bootstrap credential is not the session credential + +### Normal desktop user + +This is the default desktop-managed local flow. + +The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie. + +```text +Participants: + DesktopMain = Electron main + SecretStore = secure local secret backend + T3Server = local backend child process + Frontend = desktop renderer + +DesktopMain -> SecretStore : getOrCreate("server-signing-key") +SecretStore --> DesktopMain : signing key available + +DesktopMain -> T3Server : spawn server (--bootstrap-fd ...) +DesktopMain -> T3Server : send desktop bootstrap envelope +note over T3Server : policy = DesktopManagedLocalPolicy +note over T3Server : allowed pairing = desktop-bootstrap only + +Frontend -> DesktopMain : request local bootstrap grant +DesktopMain --> Frontend : short-lived desktop bootstrap grant + +Frontend -> T3Server : POST /api/auth/bootstrap +T3Server -> T3Server : validate desktop bootstrap grant +T3Server -> T3Server : create browser session +T3Server --> Frontend : Set-Cookie: session=... + +Frontend -> T3Server : GET /ws + authenticated cookie +T3Server -> T3Server : validate cookie session +T3Server --> Frontend : websocket accepted +``` + +### `npx t3` user + +This is the standalone local server flow. + +There is no trusted desktop shell here, so pairing should be explicit. + +```text +Participants: + UserShell = npx t3 launcher + T3Server = standalone local server + Browser = browser tab + +UserShell -> T3Server : start server +T3Server -> T3Server : getOrCreate("server-signing-key") +note over T3Server : policy = LoopbackBrowserPolicy + +UserShell -> T3Server : issue one-time pairing token +T3Server --> UserShell : pairing URL or pairing token + +UserShell --> Browser : open /pair?token=... + +Browser -> T3Server : GET /pair?token=... +T3Server -> T3Server : validate one-time token +T3Server -> T3Server : create browser session +T3Server --> Browser : Set-Cookie: session=... +T3Server --> Browser : redirect to app + +Browser -> T3Server : GET /ws + authenticated cookie +T3Server --> Browser : websocket accepted +``` + +### Phone user with tunneled host + +This is the explicit remote access flow for a browser on another device. + +The tunnel only provides reachability. It must not imply trust. + +Recommended UX: + +- desktop shows a QR code +- desktop also shows a copyable pairing URL +- if the phone opens the host URL without a valid token, the server should render a login or pairing screen rather than granting access + +```text +Participants: + DesktopUser = user at the host machine + DesktopMain = desktop app + Tunnel = tunnel provider + T3Server = T3 server + PhoneBrowser = mobile browser + +DesktopUser -> DesktopMain : enable remote access via tunnel +DesktopMain -> T3Server : switch policy to RemoteReachablePolicy +DesktopMain -> Tunnel : publish local T3 endpoint +Tunnel --> DesktopMain : public https/wss URL + +DesktopMain -> T3Server : issue one-time pairing token +T3Server --> DesktopMain : pairing token +DesktopMain -> DesktopUser : show QR code / shareable URL + +DesktopUser -> PhoneBrowser : scan QR / open URL +PhoneBrowser -> Tunnel : GET https://public-host/pair?token=... +Tunnel -> T3Server : forward request +T3Server -> T3Server : validate one-time token +T3Server -> T3Server : create mobile browser session +T3Server --> PhoneBrowser : Set-Cookie: session=... +T3Server --> PhoneBrowser : redirect to app + +PhoneBrowser -> Tunnel : GET /ws + authenticated cookie +Tunnel -> T3Server : forward websocket upgrade +T3Server --> PhoneBrowser : websocket accepted +``` + +### Phone user with private network + +This is operationally similar to the tunnel flow, but the access endpoint is on a private network such as Tailscale. + +The auth flow should stay the same. + +```text +Participants: + DesktopUser = user at the host machine + T3Server = T3 server + PrivateNet = tailscale / private LAN + PhoneBrowser = mobile browser + +DesktopUser -> T3Server : enable private-network access +T3Server -> T3Server : switch policy to RemoteReachablePolicy +DesktopUser -> T3Server : issue one-time pairing token +T3Server --> DesktopUser : pairing URL / QR + +DesktopUser -> PhoneBrowser : open private-network URL +PhoneBrowser -> PrivateNet : GET http(s)://private-host/pair?token=... +PrivateNet -> T3Server : route request +T3Server -> T3Server : validate one-time token +T3Server -> T3Server : create mobile browser session +T3Server --> PhoneBrowser : Set-Cookie: session=... +T3Server --> PhoneBrowser : redirect to app + +PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie +PrivateNet -> T3Server : websocket upgrade +T3Server --> PhoneBrowser : websocket accepted +``` + +### Desktop user adding new SSH hosts + +SSH should be treated as launch and reachability plumbing, not as the long-term auth model. + +The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment. + +```text +Participants: + DesktopUser = local desktop user + DesktopMain = desktop app + SSH = ssh transport/session + RemoteHost = remote machine + RemoteT3 = remote T3 server + Frontend = desktop renderer + +DesktopUser -> DesktopMain : add SSH host +DesktopMain -> SSH : connect to remote host +SSH -> RemoteHost : probe environment / verify t3 availability +DesktopMain -> SSH : run remote launch command +SSH -> RemoteHost : t3 remote launch --json +RemoteHost -> RemoteT3 : start or reuse server +RemoteT3 --> RemoteHost : port + environment metadata +RemoteHost --> SSH : launch result JSON +SSH --> DesktopMain : remote server details + +DesktopMain -> SSH : establish local port forward +SSH --> DesktopMain : localhost:FORWARDED_PORT ready + +note over RemoteT3 : policy = RemoteReachablePolicy +note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here + +Frontend -> DesktopMain : request bootstrap for selected environment +DesktopMain --> Frontend : short-lived bootstrap grant + +Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port +RemoteT3 -> RemoteT3 : validate bootstrap grant +RemoteT3 -> RemoteT3 : create browser session +RemoteT3 --> Frontend : Set-Cookie: session=... + +Frontend -> RemoteT3 : GET /ws + authenticated cookie +RemoteT3 --> Frontend : websocket accepted +``` + +## Storage decisions + +### Server secrets + +Use a `ServerSecretStore` abstraction. + +Preferred order (use a layer for each, resolve on startup): + +1. OS secure storage if available +2. hardened filesystem fallback if not + +The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials. + +### Client credentials + +Client-side credential persistence should prefer secure storage when available: + +- desktop: OS keychain / secure store +- mobile: platform secure storage +- browser: cookie session for browser auth + +This concern should stay in the client shell/runtime layer, not the server auth layer. + +## What to build now + +These are the parts worth building before remote environments ship: + +1. `ServerAuth` service boundary. +2. route classification and route guards. +3. `ServerSecretStore` abstraction. +4. bootstrap vs session credential split. +5. browser session cookie codec as one session method. +6. explicit auth capabilities/config surfaced in contracts. + +Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained. + +## What to add as part of first remote-capable auth + +1. Browser pairing flow using one-time bootstrap token and cookie session. +2. Desktop-managed auto-bootstrap for the local desktop-managed environment. +3. Auth-required defaults for any non-loopback or explicitly published server. +4. Explicit environment auth policy selection instead of scattered `if (host !== localhost)` checks. + +## What to defer + +- passkeys / WebAuthn +- iCloud Keychain / Face ID-specific UX +- multi-user permissions +- collaboration roles +- OAuth / SSO +- polished session management UI +- complex device approval flows + +These can all sit on top of the same bootstrap/session/service split. + +## Relationship to future remote environments + +Remote access is one reason this auth model matters, but the auth model should not be remote-shaped. + +Keep the design focused on: + +- one T3 server +- one auth policy +- multiple credential types +- multiple future access methods + +That keeps the server auth model stable even as access methods expand later. + +## Recommended implementation order + +### Phase 1 + +- Introduce route auth classes. +- Add `ServerAuth` and `AuthRouteGuards`. +- Move existing `authToken` check behind `ServerAuth`. +- Require auth for all privileged HTTP routes as well as WebSocket. + +### Phase 2 + +- Add `ServerSecretStore` service with platform-specific layer implementations. + - `layerOSXKeychain`, `layer +- Add bootstrap/session split. +- Add browser session cookie support. +- Add one-time bootstrap exchange endpoint. + +### Phase 3 + +- Add desktop bootstrap flow on top of the same services. +- Make desktop-managed local environments default to bootstrap-only pairing. +- Surface auth capabilities in shared contracts and renderer bootstrap. + +### Phase 4 + +- Add non-browser bearer session support if mobile/native needs it. +- Add richer policy modes for remote-reachable environments. + +## Acceptance criteria + +- No privileged HTTP or WebSocket path bypasses auth policy. +- Local desktop-managed flows still avoid a visible login screen. +- Non-loopback or published environments require explicit authenticated pairing by default. +- Bootstrap and session credentials are distinct in code and in behavior. +- Auth logic is centralized in Effect services/layers rather than route-local branching. diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 5244d51dbf..7c0d55ac9a 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -5,8 +5,17 @@ import { join } from "node:path"; import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs"; import { waitForResources } from "./wait-for-resources.mjs"; -const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733); -const devServerUrl = `http://localhost:${port}`; +const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim(); +if (!devServerUrl) { + throw new Error("VITE_DEV_SERVER_URL is required for desktop development."); +} + +const devServer = new URL(devServerUrl); +const port = Number.parseInt(devServer.port, 10); +if (!Number.isInteger(port) || port <= 0) { + throw new Error(`VITE_DEV_SERVER_URL must include an explicit port: ${devServerUrl}`); +} + const requiredFiles = [ "dist-electron/main.js", "dist-electron/preload.js", @@ -23,6 +32,7 @@ const childTreeGracePeriodMs = 1_200; await waitForResources({ baseDir: desktopDir, files: requiredFiles, + tcpHost: devServer.hostname, tcpPort: port, }); @@ -62,10 +72,7 @@ function startApp() { [`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"], { cwd: desktopDir, - env: { - ...childEnv, - VITE_DEV_SERVER_URL: devServerUrl, - }, + env: childEnv, stdio: "inherit", }, ); diff --git a/apps/desktop/src/backendReadiness.test.ts b/apps/desktop/src/backendReadiness.test.ts new file mode 100644 index 0000000000..fd6180b5da --- /dev/null +++ b/apps/desktop/src/backendReadiness.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + BackendReadinessAbortedError, + isBackendReadinessAborted, + waitForHttpReady, +} from "./backendReadiness"; + +describe("waitForHttpReady", () => { + it("returns once the backend reports a successful session endpoint", async () => { + const fetchImpl = vi + .fn() + .mockResolvedValueOnce(new Response(null, { status: 503 })) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + + await waitForHttpReady("http://127.0.0.1:3773", { + fetchImpl, + timeoutMs: 1_000, + intervalMs: 0, + }); + + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("retries after a readiness request stalls past the per-request timeout", async () => { + const fetchImpl = vi + .fn() + .mockImplementationOnce( + (_input, init) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener( + "abort", + () => { + reject(new Error("request timed out")); + }, + { once: true }, + ); + }) as ReturnType, + ) + .mockResolvedValueOnce(new Response(null, { status: 200 })); + + await waitForHttpReady("http://127.0.0.1:3773", { + fetchImpl, + timeoutMs: 100, + intervalMs: 0, + requestTimeoutMs: 1, + }); + + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it("aborts an in-flight readiness wait", async () => { + const controller = new AbortController(); + const fetchImpl = vi.fn().mockImplementation( + () => + new Promise((_resolve, reject) => { + controller.signal.addEventListener( + "abort", + () => { + reject(new BackendReadinessAbortedError()); + }, + { once: true }, + ); + }) as ReturnType, + ); + + const waitPromise = waitForHttpReady("http://127.0.0.1:3773", { + fetchImpl, + timeoutMs: 1_000, + intervalMs: 0, + signal: controller.signal, + }); + + controller.abort(); + + await expect(waitPromise).rejects.toBeInstanceOf(BackendReadinessAbortedError); + }); + + it("recognizes aborted readiness errors", () => { + expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true); + expect(isBackendReadinessAborted(new Error("nope"))).toBe(false); + }); +}); diff --git a/apps/desktop/src/backendReadiness.ts b/apps/desktop/src/backendReadiness.ts new file mode 100644 index 0000000000..cd5a3c023e --- /dev/null +++ b/apps/desktop/src/backendReadiness.ts @@ -0,0 +1,103 @@ +export interface WaitForHttpReadyOptions { + readonly timeoutMs?: number; + readonly intervalMs?: number; + readonly requestTimeoutMs?: number; + readonly fetchImpl?: typeof fetch; + readonly signal?: AbortSignal; +} + +const DEFAULT_TIMEOUT_MS = 10_000; +const DEFAULT_INTERVAL_MS = 100; +const DEFAULT_REQUEST_TIMEOUT_MS = 1_000; + +export class BackendReadinessAbortedError extends Error { + constructor() { + super("Backend readiness wait was aborted."); + this.name = "BackendReadinessAbortedError"; + } +} + +function delay(ms: number, signal: AbortSignal | undefined): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + cleanup(); + resolve(); + }, ms); + + const onAbort = () => { + cleanup(); + reject(new BackendReadinessAbortedError()); + }; + + const cleanup = () => { + clearTimeout(timer); + signal?.removeEventListener("abort", onAbort); + }; + + if (signal?.aborted) { + cleanup(); + reject(new BackendReadinessAbortedError()); + return; + } + + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} + +export function isBackendReadinessAborted(error: unknown): error is BackendReadinessAbortedError { + return error instanceof BackendReadinessAbortedError; +} + +export async function waitForHttpReady( + baseUrl: string, + options?: WaitForHttpReadyOptions, +): Promise { + const fetchImpl = options?.fetchImpl ?? fetch; + const signal = options?.signal; + const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS; + const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS; + const deadline = Date.now() + timeoutMs; + + for (;;) { + if (signal?.aborted) { + throw new BackendReadinessAbortedError(); + } + + const requestController = new AbortController(); + const requestTimeout = setTimeout(() => { + requestController.abort(); + }, requestTimeoutMs); + const abortRequest = () => { + requestController.abort(); + }; + signal?.addEventListener("abort", abortRequest, { once: true }); + + try { + const response = await fetchImpl(`${baseUrl}/api/auth/session`, { + redirect: "manual", + signal: requestController.signal, + }); + if (response.ok) { + return; + } + } catch (error) { + if (isBackendReadinessAborted(error)) { + throw error; + } + if (signal?.aborted) { + throw new BackendReadinessAbortedError(); + } + // Retry until the backend becomes reachable or the deadline expires. + } finally { + clearTimeout(requestTimeout); + signal?.removeEventListener("abort", abortRequest); + } + + if (Date.now() >= deadline) { + throw new Error(`Timed out waiting for backend readiness at ${baseUrl}.`); + } + + await delay(intervalMs, signal); + } +} diff --git a/apps/desktop/src/desktopSettings.test.ts b/apps/desktop/src/desktopSettings.test.ts new file mode 100644 index 0000000000..e687bf544e --- /dev/null +++ b/apps/desktop/src/desktopSettings.test.ts @@ -0,0 +1,64 @@ +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + DEFAULT_DESKTOP_SETTINGS, + readDesktopSettings, + setDesktopServerExposurePreference, + writeDesktopSettings, +} from "./desktopSettings"; + +const tempDirectories: string[] = []; + +afterEach(() => { + for (const directory of tempDirectories.splice(0)) { + fs.rmSync(directory, { recursive: true, force: true }); + } +}); + +function makeSettingsPath() { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-desktop-settings-test-")); + tempDirectories.push(directory); + return path.join(directory, "desktop-settings.json"); +} + +describe("desktopSettings", () => { + it("returns defaults when no settings file exists", () => { + expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS); + }); + + it("persists and reloads the configured server exposure mode", () => { + const settingsPath = makeSettingsPath(); + + writeDesktopSettings(settingsPath, { + serverExposureMode: "network-accessible", + }); + + expect(readDesktopSettings(settingsPath)).toEqual({ + serverExposureMode: "network-accessible", + }); + }); + + it("preserves the requested network-accessible preference across temporary fallback", () => { + expect( + setDesktopServerExposurePreference( + { + serverExposureMode: "local-only", + }, + "network-accessible", + ), + ).toEqual({ + serverExposureMode: "network-accessible", + }); + }); + + it("falls back to defaults when the settings file is malformed", () => { + const settingsPath = makeSettingsPath(); + fs.writeFileSync(settingsPath, "{not-json", "utf8"); + + expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS); + }); +}); diff --git a/apps/desktop/src/desktopSettings.ts b/apps/desktop/src/desktopSettings.ts new file mode 100644 index 0000000000..80ef229ea2 --- /dev/null +++ b/apps/desktop/src/desktopSettings.ts @@ -0,0 +1,51 @@ +import * as FS from "node:fs"; +import * as Path from "node:path"; +import type { DesktopServerExposureMode } from "@t3tools/contracts"; + +export interface DesktopSettings { + readonly serverExposureMode: DesktopServerExposureMode; +} + +export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = { + serverExposureMode: "local-only", +}; + +export function setDesktopServerExposurePreference( + settings: DesktopSettings, + requestedMode: DesktopServerExposureMode, +): DesktopSettings { + return settings.serverExposureMode === requestedMode + ? settings + : { + ...settings, + serverExposureMode: requestedMode, + }; +} + +export function readDesktopSettings(settingsPath: string): DesktopSettings { + try { + if (!FS.existsSync(settingsPath)) { + return DEFAULT_DESKTOP_SETTINGS; + } + + const raw = FS.readFileSync(settingsPath, "utf8"); + const parsed = JSON.parse(raw) as { + readonly serverExposureMode?: unknown; + }; + + return { + serverExposureMode: + parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only", + }; + } catch { + return DEFAULT_DESKTOP_SETTINGS; + } +} + +export function writeDesktopSettings(settingsPath: string, settings: DesktopSettings): void { + const directory = Path.dirname(settingsPath); + const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`; + FS.mkdirSync(directory, { recursive: true }); + FS.writeFileSync(tempPath, `${JSON.stringify(settings, null, 2)}\n`, "utf8"); + FS.renameSync(tempPath, settingsPath); +} diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index de327d0ff8..9377752e6c 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -19,6 +19,8 @@ import type { MenuItemConstructorOptions } from "electron"; import * as Effect from "effect/Effect"; import type { DesktopTheme, + DesktopServerExposureMode, + DesktopServerExposureState, DesktopUpdateActionResult, DesktopUpdateCheckResult, DesktopUpdateState, @@ -29,7 +31,15 @@ import type { ContextMenuItem } from "@t3tools/contracts"; import { NetService } from "@t3tools/shared/Net"; import { RotatingFileSink } from "@t3tools/shared/logging"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; +import { + DEFAULT_DESKTOP_SETTINGS, + readDesktopSettings, + setDesktopServerExposurePreference, + writeDesktopSettings, +} from "./desktopSettings"; +import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness"; import { showDesktopConfirmDialog } from "./confirmDialog"; +import { resolveDesktopServerExposure } from "./serverExposure"; import { syncShellEnvironment } from "./syncShellEnvironment"; import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState"; import { @@ -59,10 +69,12 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; const UPDATE_CHECK_CHANNEL = "desktop:update-check"; -const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap"; +const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; +const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3"); const STATE_DIR = Path.join(BASE_DIR, "userdata"); +const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json"); const DESKTOP_SCHEME = "t3"; const ROOT_DIR = Path.resolve(__dirname, "../../.."); const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL); @@ -83,6 +95,7 @@ const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000; const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000; const DESKTOP_UPDATE_CHANNEL = "latest"; const DESKTOP_UPDATE_ALLOW_PRERELEASE = false; +const DESKTOP_LOOPBACK_HOST = "127.0.0.1"; type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"]; type LinuxDesktopNamedApp = Electron.App & { @@ -92,8 +105,13 @@ type LinuxDesktopNamedApp = Electron.App & { let mainWindow: BrowserWindow | null = null; let backendProcess: ChildProcess.ChildProcess | null = null; let backendPort = 0; -let backendAuthToken = ""; +let backendBindHost = DESKTOP_LOOPBACK_HOST; +let backendBootstrapToken = ""; +let backendHttpUrl = ""; let backendWsUrl = ""; +let backendEndpointUrl: string | null = null; +let backendAdvertisedHost: string | null = null; +let backendReadinessAbortController: AbortController | null = null; let restartAttempt = 0; let restartTimer: ReturnType | null = null; let isQuitting = false; @@ -103,6 +121,8 @@ let desktopLogSink: RotatingFileSink | null = null; let backendLogSink: RotatingFileSink | null = null; let restoreStdIoCapture: (() => void) | null = null; let backendObservabilitySettings = readPersistedBackendObservabilitySettings(); +let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH); +let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode; let destructiveMenuIconCache: Electron.NativeImage | null | undefined; const expectedBackendExitChildren = new WeakSet(); @@ -141,17 +161,120 @@ function readPersistedBackendObservabilitySettings(): { } } +function resolveConfiguredDesktopBackendPort(rawPort: string | undefined): number | undefined { + if (!rawPort) { + return undefined; + } + + const parsedPort = Number.parseInt(rawPort, 10); + if (!Number.isInteger(parsedPort) || parsedPort < 1 || parsedPort > 65_535) { + return undefined; + } + + return parsedPort; +} + +function resolveDesktopDevServerUrl(): string { + const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim(); + if (!devServerUrl) { + throw new Error("VITE_DEV_SERVER_URL is required in desktop development."); + } + + return devServerUrl; +} + function backendChildEnv(): NodeJS.ProcessEnv { const env = { ...process.env }; delete env.T3CODE_PORT; - delete env.T3CODE_AUTH_TOKEN; delete env.T3CODE_MODE; delete env.T3CODE_NO_BROWSER; delete env.T3CODE_HOST; delete env.T3CODE_DESKTOP_WS_URL; + delete env.T3CODE_DESKTOP_LAN_ACCESS; + delete env.T3CODE_DESKTOP_LAN_HOST; return env; } +function getDesktopServerExposureState(): DesktopServerExposureState { + return { + mode: desktopServerExposureMode, + endpointUrl: backendEndpointUrl, + advertisedHost: backendAdvertisedHost, + }; +} + +function resolveAdvertisedHostOverride(): string | undefined { + const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim(); + return override && override.length > 0 ? override : undefined; +} + +async function applyDesktopServerExposureMode( + mode: DesktopServerExposureMode, + options?: { readonly persist?: boolean; readonly rejectIfUnavailable?: boolean }, +): Promise { + const advertisedHostOverride = resolveAdvertisedHostOverride(); + const requestedMode = mode; + let exposure = resolveDesktopServerExposure({ + mode, + port: backendPort, + networkInterfaces: OS.networkInterfaces(), + ...(advertisedHostOverride ? { advertisedHostOverride } : {}), + }); + + if (requestedMode === "network-accessible" && exposure.endpointUrl === null) { + if (options?.rejectIfUnavailable) { + throw new Error("No reachable network address is available for this desktop right now."); + } + exposure = resolveDesktopServerExposure({ + mode: "local-only", + port: backendPort, + networkInterfaces: OS.networkInterfaces(), + ...(advertisedHostOverride ? { advertisedHostOverride } : {}), + }); + } + + desktopServerExposureMode = exposure.mode; + desktopSettings = setDesktopServerExposurePreference(desktopSettings, requestedMode); + backendBindHost = exposure.bindHost; + backendHttpUrl = exposure.localHttpUrl; + backendWsUrl = exposure.localWsUrl; + backendEndpointUrl = exposure.endpointUrl; + backendAdvertisedHost = exposure.advertisedHost; + + if (options?.persist) { + writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings); + } + + return getDesktopServerExposureState(); +} + +function relaunchDesktopApp(reason: string): void { + writeDesktopLogHeader(`desktop relaunch requested reason=${reason}`); + setImmediate(() => { + isQuitting = true; + clearUpdatePollTimer(); + cancelBackendReadinessWait(); + void stopBackendAndWaitForExit() + .catch((error) => { + writeDesktopLogHeader( + `desktop relaunch backend shutdown warning message=${formatErrorMessage(error)}`, + ); + }) + .finally(() => { + restoreStdIoCapture?.(); + if (isDevelopment) { + app.exit(75); + return; + } + app.relaunch({ + execPath: process.execPath, + args: process.argv.slice(1), + }); + app.exit(0); + }); + }); +} + function writeDesktopLogHeader(message: string): void { if (!desktopLogSink) return; desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`); @@ -199,6 +322,27 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null { return null; } +async function waitForBackendHttpReady(baseUrl: string): Promise { + cancelBackendReadinessWait(); + const controller = new AbortController(); + backendReadinessAbortController = controller; + + try { + await waitForHttpReady(baseUrl, { + signal: controller.signal, + }); + } finally { + if (backendReadinessAbortController === controller) { + backendReadinessAbortController = null; + } + } +} + +function cancelBackendReadinessWait(): void { + backendReadinessAbortController?.abort(); + backendReadinessAbortController = null; +} + function writeDesktopStreamChunk( streamName: "stdout" | "stderr", chunk: unknown, @@ -543,10 +687,7 @@ function dispatchMenuAction(action: string): void { const send = () => { if (targetWindow.isDestroyed()) return; targetWindow.webContents.send(MENU_ACTION_CHANNEL, action); - if (!targetWindow.isVisible()) { - targetWindow.show(); - } - targetWindow.focus(); + revealWindow(targetWindow); }; if (targetWindow.webContents.isLoadingMainFrame()) { @@ -767,6 +908,26 @@ function clearUpdatePollTimer(): void { } } +function revealWindow(window: BrowserWindow): void { + if (window.isDestroyed()) { + return; + } + + if (window.isMinimized()) { + window.restore(); + } + + if (!window.isVisible()) { + window.show(); + } + + if (process.platform === "darwin") { + app.focus({ steal: true }); + } + + window.focus(); +} + function emitUpdateState(): void { for (const window of BrowserWindow.getAllWindows()) { if (window.isDestroyed()) continue; @@ -1036,7 +1197,8 @@ function startBackend(): void { noBrowser: true, port: backendPort, t3Home: BASE_DIR, - authToken: backendAuthToken, + host: backendBindHost, + desktopBootstrapToken: backendBootstrapToken, ...(backendObservabilitySettings.otlpTracesUrl ? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl } : {}), @@ -1095,6 +1257,7 @@ function startBackend(): void { } function stopBackend(): void { + cancelBackendReadinessWait(); if (restartTimer) { clearTimeout(restartTimer); restartTimer = null; @@ -1116,6 +1279,7 @@ function stopBackend(): void { } async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { + cancelBackendReadinessWait(); if (restartTimer) { clearTimeout(restartTimer); restartTimer = null; @@ -1168,19 +1332,38 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise { } function registerIpcHandlers(): void { - ipcMain.removeAllListeners(GET_WS_URL_CHANNEL); - ipcMain.on(GET_WS_URL_CHANNEL, (event) => { - event.returnValue = backendWsUrl; - }); - ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL); ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => { event.returnValue = { label: "Local environment", - wsUrl: backendWsUrl || null, + httpBaseUrl: backendHttpUrl || null, + wsBaseUrl: backendWsUrl || null, + bootstrapToken: backendBootstrapToken || undefined, } as const; }); + ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL); + ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState()); + + ipcMain.removeHandler(SET_SERVER_EXPOSURE_MODE_CHANNEL); + ipcMain.handle(SET_SERVER_EXPOSURE_MODE_CHANNEL, async (_event, rawMode: unknown) => { + if (rawMode !== "local-only" && rawMode !== "network-accessible") { + throw new Error("Invalid desktop server exposure input."); + } + + const nextMode = rawMode as DesktopServerExposureMode; + if (nextMode === desktopServerExposureMode) { + return getDesktopServerExposureState(); + } + + const nextState = await applyDesktopServerExposureMode(nextMode, { + persist: true, + rejectIfUnavailable: true, + }); + relaunchDesktopApp(`serverExposureMode=${nextMode}`); + return nextState; + }); + ipcMain.removeHandler(PICK_FOLDER_CHANNEL); ipcMain.handle(PICK_FOLDER_CHANNEL, async () => { const owner = BrowserWindow.getFocusedWindow() ?? mainWindow; @@ -1346,14 +1529,19 @@ function getIconOption(): { icon: string } | Record { return iconPath ? { icon: iconPath } : {}; } +function getInitialWindowBackgroundColor(): string { + return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff"; +} + function createWindow(): BrowserWindow { const window = new BrowserWindow({ width: 1100, height: 780, minWidth: 840, minHeight: 620, - show: false, + show: isDevelopment, autoHideMenuBar: true, + backgroundColor: getInitialWindowBackgroundColor(), ...getIconOption(), title: APP_DISPLAY_NAME, titleBarStyle: "hiddenInset", @@ -1410,15 +1598,20 @@ function createWindow(): BrowserWindow { window.setTitle(APP_DISPLAY_NAME); emitUpdateState(); }); - window.once("ready-to-show", () => { - window.show(); - }); + if (!isDevelopment) { + window.once("ready-to-show", () => { + revealWindow(window); + }); + } if (isDevelopment) { - void window.loadURL(process.env.VITE_DEV_SERVER_URL as string); + void window.loadURL(resolveDesktopDevServerUrl()); window.webContents.openDevTools({ mode: "detach" }); + setImmediate(() => { + revealWindow(window); + }); } else { - void window.loadURL(`${DESKTOP_SCHEME}://app/index.html`); + void window.loadURL(resolveDesktopWindowUrl()); } window.on("closed", () => { @@ -1430,6 +1623,14 @@ function createWindow(): BrowserWindow { return window; } +function resolveDesktopWindowUrl(): string { + if (backendHttpUrl) { + return backendHttpUrl; + } + + return `${DESKTOP_SCHEME}://app`; +} + // Override Electron's userData path before the `ready` event so that // Chromium session data uses a filesystem-friendly directory name. // Must be called synchronously at the top level — before `app.whenReady()`. @@ -1439,21 +1640,72 @@ configureAppIdentity(); async function bootstrap(): Promise { writeDesktopLogHeader("bootstrap start"); - backendPort = await Effect.service(NetService).pipe( - Effect.flatMap((net) => net.reserveLoopbackPort()), - Effect.provide(NetService.layer), - Effect.runPromise, + const configuredBackendPort = resolveConfiguredDesktopBackendPort(process.env.T3CODE_PORT); + if (isDevelopment && configuredBackendPort === undefined) { + throw new Error("T3CODE_PORT is required in desktop development."); + } + + backendPort = + configuredBackendPort ?? + (await Effect.service(NetService).pipe( + Effect.flatMap((net) => net.reserveLoopbackPort(DESKTOP_LOOPBACK_HOST)), + Effect.provide(NetService.layer), + Effect.runPromise, + )); + writeDesktopLogHeader( + configuredBackendPort === undefined + ? `reserved backend port via NetService port=${backendPort}` + : `using configured backend port port=${backendPort}`, ); - writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`); - backendAuthToken = Crypto.randomBytes(24).toString("hex"); - const baseUrl = `ws://127.0.0.1:${backendPort}`; - backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`; - writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`); + backendBootstrapToken = Crypto.randomBytes(24).toString("hex"); + if (desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode) { + writeDesktopLogHeader( + `bootstrap restoring persisted server exposure mode mode=${desktopSettings.serverExposureMode}`, + ); + } + const serverExposureState = await applyDesktopServerExposureMode( + desktopSettings.serverExposureMode, + { + persist: desktopSettings.serverExposureMode !== DEFAULT_DESKTOP_SETTINGS.serverExposureMode, + }, + ); + writeDesktopLogHeader(`bootstrap resolved backend endpoint baseUrl=${backendHttpUrl}`); + if (serverExposureState.endpointUrl) { + writeDesktopLogHeader( + `bootstrap enabled network access endpointUrl=${serverExposureState.endpointUrl}`, + ); + } else if (desktopSettings.serverExposureMode === "network-accessible") { + writeDesktopLogHeader( + "bootstrap fell back to local-only because no advertised network host was available", + ); + } registerIpcHandlers(); writeDesktopLogHeader("bootstrap ipc handlers registered"); startBackend(); writeDesktopLogHeader("bootstrap backend start requested"); + + if (isDevelopment) { + mainWindow = createWindow(); + writeDesktopLogHeader("bootstrap main window created"); + void waitForBackendHttpReady(backendHttpUrl) + .then(() => { + writeDesktopLogHeader("bootstrap backend ready"); + }) + .catch((error) => { + if (isBackendReadinessAborted(error)) { + return; + } + writeDesktopLogHeader( + `bootstrap backend readiness warning message=${formatErrorMessage(error)}`, + ); + console.warn("[desktop] backend readiness check timed out during dev bootstrap", error); + }); + return; + } + + await waitForBackendHttpReady(backendHttpUrl); + writeDesktopLogHeader("bootstrap backend ready"); mainWindow = createWindow(); writeDesktopLogHeader("bootstrap main window created"); } @@ -1463,6 +1715,7 @@ app.on("before-quit", () => { updateInstallInFlight = false; writeDesktopLogHeader("before-quit received"); clearUpdatePollTimer(); + cancelBackendReadinessWait(); stopBackend(); restoreStdIoCapture?.(); }); @@ -1476,13 +1729,19 @@ app registerDesktopProtocol(); configureAutoUpdater(); void bootstrap().catch((error) => { + if (isBackendReadinessAborted(error) && isQuitting) { + return; + } handleFatalStartupError("bootstrap", error); }); app.on("activate", () => { - if (BrowserWindow.getAllWindows().length === 0) { - mainWindow = createWindow(); + const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0]; + if (existingWindow) { + revealWindow(existingWindow); + return; } + mainWindow = createWindow(); }); }) .catch((error) => { @@ -1501,6 +1760,7 @@ if (process.platform !== "win32") { isQuitting = true; writeDesktopLogHeader("SIGINT received"); clearUpdatePollTimer(); + cancelBackendReadinessWait(); stopBackend(); restoreStdIoCapture?.(); app.quit(); diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index bd678844ef..60392f7dba 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -12,14 +12,11 @@ const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; const UPDATE_CHECK_CHANNEL = "desktop:update-check"; const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; -const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap"; +const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state"; +const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode"; contextBridge.exposeInMainWorld("desktopBridge", { - getWsUrl: () => { - const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL); - return typeof result === "string" ? result : null; - }, getLocalEnvironmentBootstrap: () => { const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL); if (typeof result !== "object" || result === null) { @@ -27,6 +24,8 @@ contextBridge.exposeInMainWorld("desktopBridge", { } return result as ReturnType; }, + getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL), + setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode), pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL), confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message), setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme), diff --git a/apps/desktop/src/serverExposure.test.ts b/apps/desktop/src/serverExposure.test.ts new file mode 100644 index 0000000000..b1ae4bef4f --- /dev/null +++ b/apps/desktop/src/serverExposure.test.ts @@ -0,0 +1,139 @@ +import { describe, expect, it } from "vitest"; + +import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure"; + +describe("resolveLanAdvertisedHost", () => { + it("prefers an explicit host override", () => { + expect( + resolveLanAdvertisedHost( + { + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + "10.0.0.9", + ), + ).toBe("10.0.0.9"); + }); + + it("returns the first usable non-internal IPv4 address", () => { + expect( + resolveLanAdvertisedHost( + { + lo0: [ + { + address: "127.0.0.1", + family: "IPv4", + internal: true, + netmask: "255.0.0.0", + cidr: "127.0.0.1/8", + mac: "00:00:00:00:00:00", + }, + ], + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + undefined, + ), + ).toBe("192.168.1.44"); + }); + + it("returns null when no usable network address is available", () => { + expect( + resolveLanAdvertisedHost( + { + lo0: [ + { + address: "127.0.0.1", + family: "IPv4", + internal: true, + netmask: "255.0.0.0", + cidr: "127.0.0.1/8", + mac: "00:00:00:00:00:00", + }, + ], + }, + undefined, + ), + ).toBeNull(); + }); +}); + +describe("resolveDesktopServerExposure", () => { + it("keeps the desktop server loopback-only when local-only mode is selected", () => { + expect( + resolveDesktopServerExposure({ + mode: "local-only", + port: 3773, + networkInterfaces: {}, + }), + ).toEqual({ + mode: "local-only", + bindHost: "127.0.0.1", + localHttpUrl: "http://127.0.0.1:3773", + localWsUrl: "ws://127.0.0.1:3773", + endpointUrl: null, + advertisedHost: null, + }); + }); + + it("binds to all interfaces in network-accessible mode", () => { + expect( + resolveDesktopServerExposure({ + mode: "network-accessible", + port: 3773, + networkInterfaces: { + en0: [ + { + address: "192.168.1.44", + family: "IPv4", + internal: false, + netmask: "255.255.255.0", + cidr: "192.168.1.44/24", + mac: "00:00:00:00:00:00", + }, + ], + }, + }), + ).toEqual({ + mode: "network-accessible", + bindHost: "0.0.0.0", + localHttpUrl: "http://127.0.0.1:3773", + localWsUrl: "ws://127.0.0.1:3773", + endpointUrl: "http://192.168.1.44:3773", + advertisedHost: "192.168.1.44", + }); + }); + + it("stays network-accessible even when no LAN address is currently detectable", () => { + expect( + resolveDesktopServerExposure({ + mode: "network-accessible", + port: 3773, + networkInterfaces: {}, + }), + ).toEqual({ + mode: "network-accessible", + bindHost: "0.0.0.0", + localHttpUrl: "http://127.0.0.1:3773", + localWsUrl: "ws://127.0.0.1:3773", + endpointUrl: null, + advertisedHost: null, + }); + }); +}); diff --git a/apps/desktop/src/serverExposure.ts b/apps/desktop/src/serverExposure.ts new file mode 100644 index 0000000000..65c99b60e1 --- /dev/null +++ b/apps/desktop/src/serverExposure.ts @@ -0,0 +1,80 @@ +import type { NetworkInterfaceInfo } from "node:os"; +import type { DesktopServerExposureMode } from "@t3tools/contracts"; + +const DESKTOP_LOOPBACK_HOST = "127.0.0.1"; +const DESKTOP_LAN_BIND_HOST = "0.0.0.0"; + +export interface DesktopServerExposure { + readonly mode: DesktopServerExposureMode; + readonly bindHost: string; + readonly localHttpUrl: string; + readonly localWsUrl: string; + readonly endpointUrl: string | null; + readonly advertisedHost: string | null; +} + +const normalizeOptionalHost = (value: string | undefined): string | undefined => { + const normalized = value?.trim(); + return normalized && normalized.length > 0 ? normalized : undefined; +}; + +const isUsableLanIpv4Address = (address: string): boolean => + !address.startsWith("127.") && !address.startsWith("169.254."); + +export function resolveLanAdvertisedHost( + networkInterfaces: NodeJS.Dict, + explicitHost: string | undefined, +): string | null { + const normalizedExplicitHost = normalizeOptionalHost(explicitHost); + if (normalizedExplicitHost) { + return normalizedExplicitHost; + } + + for (const interfaceAddresses of Object.values(networkInterfaces)) { + if (!interfaceAddresses) continue; + + for (const address of interfaceAddresses) { + if (address.internal) continue; + if (address.family !== "IPv4") continue; + if (!isUsableLanIpv4Address(address.address)) continue; + return address.address; + } + } + + return null; +} + +export function resolveDesktopServerExposure(input: { + readonly mode: DesktopServerExposureMode; + readonly port: number; + readonly networkInterfaces: NodeJS.Dict; + readonly advertisedHostOverride?: string; +}): DesktopServerExposure { + const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`; + const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`; + + if (input.mode === "local-only") { + return { + mode: input.mode, + bindHost: DESKTOP_LOOPBACK_HOST, + localHttpUrl, + localWsUrl, + endpointUrl: null, + advertisedHost: null, + }; + } + + const advertisedHost = resolveLanAdvertisedHost( + input.networkInterfaces, + input.advertisedHostOverride, + ); + + return { + mode: input.mode, + bindHost: DESKTOP_LAN_BIND_HOST, + localHttpUrl, + localWsUrl, + endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null, + advertisedHost, + }; +} diff --git a/apps/server/src/auth/Layers/AuthControlPlane.test.ts b/apps/server/src/auth/Layers/AuthControlPlane.test.ts new file mode 100644 index 0000000000..9fc091124b --- /dev/null +++ b/apps/server/src/auth/Layers/AuthControlPlane.test.ts @@ -0,0 +1,111 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; +import { SessionCredentialServiceLive } from "./SessionCredentialService.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { AuthControlPlane } from "../Services/AuthControlPlane.ts"; +import { makeAuthControlPlane } from "./AuthControlPlane.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; + +const makeServerConfigLayer = ( + overrides?: Partial>, +) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-control-plane-test-" })), + ); + +const makeAuthControlPlaneLayer = ( + overrides?: Partial>, +) => + Layer.effect(AuthControlPlane, makeAuthControlPlane).pipe( + Layer.provideMerge(BootstrapCredentialServiceLive), + Layer.provideMerge(SessionCredentialServiceLive), + Layer.provideMerge(ServerSecretStoreLive), + Layer.provideMerge(SqlitePersistenceMemory), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +it.layer(NodeServices.layer)("AuthControlPlane", (it) => { + it.effect("creates, lists, and revokes client pairing links", () => + Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + + const created = yield* authControlPlane.createPairingLink({ + role: "client", + subject: "one-time-token", + label: "CI phone", + }); + const listedBeforeRevoke = yield* authControlPlane.listPairingLinks({ role: "client" }); + const revoked = yield* authControlPlane.revokePairingLink(created.id); + const listedAfterRevoke = yield* authControlPlane.listPairingLinks({ role: "client" }); + + expect(created.role).toBe("client"); + expect(created.credential.length).toBeGreaterThan(0); + expect(listedBeforeRevoke).toHaveLength(1); + expect(listedBeforeRevoke[0]?.id).toBe(created.id); + expect(listedBeforeRevoke[0]?.label).toBe("CI phone"); + expect(listedBeforeRevoke[0]?.credential).toBe(created.credential); + expect(revoked).toBe(true); + expect(listedAfterRevoke).toHaveLength(0); + }).pipe(Effect.provide(makeAuthControlPlaneLayer())), + ); + + it.effect("issues bearer sessions and lists them without exposing raw tokens", () => + Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + const sessionCredentials = yield* SessionCredentialService; + + const issued = yield* authControlPlane.issueSession({ + label: "deploy-bot", + }); + const verified = yield* sessionCredentials.verify(issued.token); + const listedBeforeRevoke = yield* authControlPlane.listSessions(); + const revoked = yield* authControlPlane.revokeSession(issued.sessionId); + const listedAfterRevoke = yield* authControlPlane.listSessions(); + + expect(issued.method).toBe("bearer-session-token"); + expect(issued.role).toBe("owner"); + expect(issued.client.deviceType).toBe("bot"); + expect(issued.client.label).toBe("deploy-bot"); + expect(verified.sessionId).toBe(issued.sessionId); + expect(verified.role).toBe("owner"); + expect(verified.method).toBe("bearer-session-token"); + expect(listedBeforeRevoke).toHaveLength(1); + expect(listedBeforeRevoke[0]?.sessionId).toBe(issued.sessionId); + expect("token" in (listedBeforeRevoke[0] ?? {})).toBe(false); + expect(revoked).toBe(true); + expect(listedAfterRevoke).toHaveLength(0); + }).pipe(Effect.provide(makeAuthControlPlaneLayer())), + ); + + it.effect("surfaces lastConnectedAt through the listed session view", () => + Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + const sessionCredentials = yield* SessionCredentialService; + + const issued = yield* authControlPlane.issueSession({ + label: "remote-ipad", + }); + const beforeConnect = yield* authControlPlane.listSessions(); + yield* sessionCredentials.markConnected(issued.sessionId); + const afterConnect = yield* authControlPlane.listSessions(); + + expect(beforeConnect[0]?.lastConnectedAt).toBeNull(); + expect(afterConnect[0]?.lastConnectedAt).not.toBeNull(); + }).pipe(Effect.provide(makeAuthControlPlaneLayer())), + ); +}); diff --git a/apps/server/src/auth/Layers/AuthControlPlane.ts b/apps/server/src/auth/Layers/AuthControlPlane.ts new file mode 100644 index 0000000000..98b2107800 --- /dev/null +++ b/apps/server/src/auth/Layers/AuthControlPlane.ts @@ -0,0 +1,176 @@ +import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts"; +import { DateTime, Effect, Layer } from "effect"; + +import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; +import { SessionCredentialServiceLive } from "./SessionCredentialService.ts"; +import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; +import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Layers/Sqlite.ts"; +import { + AuthControlPlane, + AuthControlPlaneError, + AuthControlPlaneShape, + DEFAULT_SESSION_SUBJECT, + IssuedBearerSession, + IssuedPairingLink, +} from "../Services/AuthControlPlane.ts"; + +const bySessionPriority = (left: AuthClientSession, right: AuthClientSession) => { + if (left.role !== right.role) { + return left.role === "owner" ? -1 : 1; + } + if (left.connected !== right.connected) { + return left.connected ? -1 : 1; + } + return right.issuedAt.epochMilliseconds - left.issuedAt.epochMilliseconds; +}; + +const toAuthControlPlaneError = + (message: string) => + (cause: unknown): AuthControlPlaneError => + new AuthControlPlaneError({ + message, + cause, + }); + +export const makeAuthControlPlane = Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const sessions = yield* SessionCredentialService; + + const createPairingLink: AuthControlPlaneShape["createPairingLink"] = (input) => + Effect.gen(function* () { + const createdAt = yield* DateTime.now; + const issued = yield* bootstrapCredentials.issueOneTimeToken({ + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + ...(input?.ttl ? { ttl: input.ttl } : {}), + ...(input?.label ? { label: input.label } : {}), + }); + return { + id: issued.id, + credential: issued.credential, + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + ...(issued.label ? { label: issued.label } : {}), + createdAt: DateTime.toUtc(createdAt), + expiresAt: DateTime.toUtc(issued.expiresAt), + } satisfies IssuedPairingLink; + }).pipe(Effect.mapError(toAuthControlPlaneError("Failed to create pairing link."))); + + const listPairingLinks: AuthControlPlaneShape["listPairingLinks"] = (input) => + bootstrapCredentials.listActive().pipe( + Effect.map((pairingLinks) => + pairingLinks + .filter((pairingLink) => (input?.role ? pairingLink.role === input.role : true)) + .filter((pairingLink) => !input?.excludeSubjects?.includes(pairingLink.subject)) + .map((pairingLink) => + pairingLink.label + ? ({ + id: pairingLink.id, + credential: pairingLink.credential, + role: pairingLink.role, + subject: pairingLink.subject, + label: pairingLink.label, + createdAt: pairingLink.createdAt, + expiresAt: pairingLink.expiresAt, + } satisfies AuthPairingLink) + : ({ + id: pairingLink.id, + credential: pairingLink.credential, + role: pairingLink.role, + subject: pairingLink.subject, + createdAt: pairingLink.createdAt, + expiresAt: pairingLink.expiresAt, + } satisfies AuthPairingLink), + ) + .toSorted( + (left, right) => right.createdAt.epochMilliseconds - left.createdAt.epochMilliseconds, + ), + ), + Effect.mapError(toAuthControlPlaneError("Failed to list pairing links.")), + ); + + const revokePairingLink: AuthControlPlaneShape["revokePairingLink"] = (id) => + bootstrapCredentials + .revoke(id) + .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke pairing link."))); + + const issueSession: AuthControlPlaneShape["issueSession"] = (input) => + sessions + .issue({ + subject: input?.subject ?? DEFAULT_SESSION_SUBJECT, + method: "bearer-session-token", + role: input?.role ?? "owner", + client: { + ...(input?.label ? { label: input.label } : {}), + deviceType: "bot", + }, + ...(input?.ttl ? { ttl: input.ttl } : {}), + }) + .pipe( + Effect.flatMap((issued) => { + if (issued.method !== "bearer-session-token") { + return Effect.fail( + new AuthControlPlaneError({ + message: "CLI session issuance produced an unexpected session method.", + }), + ); + } + + return Effect.succeed({ + sessionId: issued.sessionId, + token: issued.token, + method: "bearer-session-token" as const, + role: issued.role, + subject: input?.subject ?? DEFAULT_SESSION_SUBJECT, + client: issued.client, + expiresAt: DateTime.toUtc(issued.expiresAt), + } satisfies IssuedBearerSession); + }), + Effect.mapError(toAuthControlPlaneError("Failed to issue session token.")), + ); + + const listSessions: AuthControlPlaneShape["listSessions"] = () => + sessions.listActive().pipe( + Effect.map((activeSessions) => activeSessions.toSorted(bySessionPriority)), + Effect.mapError(toAuthControlPlaneError("Failed to list sessions.")), + ); + + const revokeSession: AuthControlPlaneShape["revokeSession"] = (sessionId) => + sessions + .revoke(sessionId) + .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke session."))); + + const revokeOtherSessionsExcept: AuthControlPlaneShape["revokeOtherSessionsExcept"] = ( + sessionId, + ) => + sessions + .revokeAllExcept(sessionId) + .pipe(Effect.mapError(toAuthControlPlaneError("Failed to revoke other sessions."))); + + return { + createPairingLink, + listPairingLinks, + revokePairingLink, + issueSession, + listSessions, + revokeSession, + revokeOtherSessionsExcept, + } satisfies AuthControlPlaneShape; +}); + +export const AuthCoreLive = Layer.mergeAll( + BootstrapCredentialServiceLive, + SessionCredentialServiceLive, +); + +export const AuthStorageLive = Layer.mergeAll(ServerSecretStoreLive, SqlitePersistenceLayerLive); + +export const AuthRuntimeLive = AuthCoreLive.pipe(Layer.provideMerge(AuthStorageLive)); + +export const AuthControlPlaneLive = Layer.effect(AuthControlPlane, makeAuthControlPlane); + +export const AuthControlPlaneRuntimeLive = AuthControlPlaneLive.pipe( + Layer.provideMerge(AuthRuntimeLive), +); diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts b/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts new file mode 100644 index 0000000000..ec110ee96f --- /dev/null +++ b/apps/server/src/auth/Layers/BootstrapCredentialService.test.ts @@ -0,0 +1,151 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Duration, Effect, Layer } from "effect"; +import { TestClock } from "effect/testing"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts"; +import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts"; + +const makeServerConfigLayer = ( + overrides?: Partial>, +) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-bootstrap-test-" })), + ); + +const makeBootstrapCredentialLayer = ( + overrides?: Partial>, +) => + BootstrapCredentialServiceLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +it.layer(NodeServices.layer)("BootstrapCredentialServiceLive", (it) => { + it.effect("issues pairing tokens in a short manual-entry format", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const issued = yield* bootstrapCredentials.issueOneTimeToken(); + + expect(issued.credential).toMatch(/^[23456789ABCDEFGHJKLMNPQRSTUVWXYZ]{12}$/); + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); + + it.effect("issues one-time bootstrap tokens that can only be consumed once", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const issued = yield* bootstrapCredentials.issueOneTimeToken({ label: "Julius iPhone" }); + const first = yield* bootstrapCredentials.consume(issued.credential); + const second = yield* Effect.flip(bootstrapCredentials.consume(issued.credential)); + + expect(first.method).toBe("one-time-token"); + expect(first.role).toBe("client"); + expect(first.subject).toBe("one-time-token"); + expect(first.label).toBe("Julius iPhone"); + expect(issued.label).toBe("Julius iPhone"); + expect(second._tag).toBe("BootstrapCredentialError"); + expect(second.message).toContain("Unknown bootstrap credential"); + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); + + it.effect("atomically consumes a one-time token when multiple requests race", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const token = yield* bootstrapCredentials.issueOneTimeToken(); + const results = yield* Effect.all( + Array.from({ length: 8 }, () => + Effect.result(bootstrapCredentials.consume(token.credential)), + ), + { + concurrency: "unbounded", + }, + ); + + const successes = results.filter((result) => result._tag === "Success"); + const failures = results.filter((result) => result._tag === "Failure"); + + expect(successes).toHaveLength(1); + expect(failures).toHaveLength(7); + for (const failure of failures) { + expect(failure.failure._tag).toBe("BootstrapCredentialError"); + expect(failure.failure.message).toContain("Unknown bootstrap credential"); + } + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); + + it.effect("seeds the desktop bootstrap credential as a one-time grant", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const first = yield* bootstrapCredentials.consume("desktop-bootstrap-token"); + const second = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token")); + + expect(first.method).toBe("desktop-bootstrap"); + expect(first.role).toBe("owner"); + expect(first.subject).toBe("desktop-bootstrap"); + expect(second._tag).toBe("BootstrapCredentialError"); + expect(second.status).toBe(401); + }).pipe( + Effect.provide( + makeBootstrapCredentialLayer({ + desktopBootstrapToken: "desktop-bootstrap-token", + }), + ), + ), + ); + + it.effect("reports seeded desktop bootstrap credentials as expired after their ttl", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + + yield* TestClock.adjust(Duration.minutes(6)); + const expired = yield* Effect.flip(bootstrapCredentials.consume("desktop-bootstrap-token")); + + expect(expired._tag).toBe("BootstrapCredentialError"); + expect(expired.status).toBe(401); + expect(expired.message).toContain("Bootstrap credential expired"); + }).pipe( + Effect.provide( + Layer.merge( + makeBootstrapCredentialLayer({ + desktopBootstrapToken: "desktop-bootstrap-token", + }), + TestClock.layer(), + ), + ), + ), + ); + + it.effect("lists and revokes active pairing links", () => + Effect.gen(function* () { + const bootstrapCredentials = yield* BootstrapCredentialService; + const first = yield* bootstrapCredentials.issueOneTimeToken(); + const second = yield* bootstrapCredentials.issueOneTimeToken({ role: "owner" }); + + const activeBeforeRevoke = yield* bootstrapCredentials.listActive(); + expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(first.id); + expect(activeBeforeRevoke.map((entry) => entry.id)).toContain(second.id); + + const revoked = yield* bootstrapCredentials.revoke(first.id); + const activeAfterRevoke = yield* bootstrapCredentials.listActive(); + const revokedConsume = yield* Effect.flip(bootstrapCredentials.consume(first.credential)); + + expect(revoked).toBe(true); + expect(activeAfterRevoke.map((entry) => entry.id)).not.toContain(first.id); + expect(activeAfterRevoke.map((entry) => entry.id)).toContain(second.id); + expect(revokedConsume.message).toContain("no longer available"); + expect(revokedConsume.status).toBe(401); + }).pipe(Effect.provide(makeBootstrapCredentialLayer())), + ); +}); diff --git a/apps/server/src/auth/Layers/BootstrapCredentialService.ts b/apps/server/src/auth/Layers/BootstrapCredentialService.ts new file mode 100644 index 0000000000..5539f62c70 --- /dev/null +++ b/apps/server/src/auth/Layers/BootstrapCredentialService.ts @@ -0,0 +1,296 @@ +import type { AuthPairingLink } from "@t3tools/contracts"; +import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect"; +import { Option } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts"; +import { AuthPairingLinkRepository } from "../../persistence/Services/AuthPairingLinks.ts"; +import { + BootstrapCredentialError, + BootstrapCredentialService, + type BootstrapCredentialChange, + type BootstrapCredentialServiceShape, + type BootstrapGrant, + type IssuedBootstrapCredential, +} from "../Services/BootstrapCredentialService.ts"; + +interface StoredBootstrapGrant extends BootstrapGrant { + readonly remainingUses: number | "unbounded"; +} + +type ConsumeResult = + | { + readonly _tag: "error"; + readonly reason: "not-found" | "expired"; + readonly error: BootstrapCredentialError; + } + | { + readonly _tag: "success"; + readonly grant: BootstrapGrant; + }; + +const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5); +const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"; +const PAIRING_TOKEN_LENGTH = 12; + +const generatePairingToken = (): string => { + const randomBytes = crypto.getRandomValues(new Uint8Array(PAIRING_TOKEN_LENGTH)); + + return Array.from(randomBytes, (value) => PAIRING_TOKEN_ALPHABET[value & 31]).join(""); +}; + +export const makeBootstrapCredentialService = Effect.gen(function* () { + const config = yield* ServerConfig; + const pairingLinks = yield* AuthPairingLinkRepository; + const seededGrantsRef = yield* Ref.make(new Map()); + const changesPubSub = yield* PubSub.unbounded(); + + const invalidBootstrapCredentialError = (message: string) => + new BootstrapCredentialError({ + message, + status: 401, + }); + + const internalBootstrapCredentialError = (message: string, cause: unknown) => + new BootstrapCredentialError({ + message, + status: 500, + cause, + }); + + const seedGrant = (credential: string, grant: StoredBootstrapGrant) => + Ref.update(seededGrantsRef, (current) => { + const next = new Map(current); + next.set(credential, grant); + return next; + }); + + const emitUpsert = (pairingLink: AuthPairingLink) => + PubSub.publish(changesPubSub, { + type: "pairingLinkUpserted", + pairingLink, + }).pipe(Effect.asVoid); + + const emitRemoved = (id: string) => + PubSub.publish(changesPubSub, { + type: "pairingLinkRemoved", + id, + }).pipe(Effect.asVoid); + + if (config.desktopBootstrapToken) { + const now = yield* DateTime.now; + yield* seedGrant(config.desktopBootstrapToken, { + method: "desktop-bootstrap", + role: "owner", + subject: "desktop-bootstrap", + expiresAt: DateTime.add(now, { + milliseconds: Duration.toMillis(DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES), + }), + remainingUses: 1, + }); + } + + const toBootstrapCredentialError = (message: string) => (cause: unknown) => + internalBootstrapCredentialError(message, cause); + + const listActive: BootstrapCredentialServiceShape["listActive"] = () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const rows = yield* pairingLinks.listActive({ now }); + + return rows.map((row) => + row.label + ? ({ + id: row.id, + credential: row.credential, + role: row.role, + subject: row.subject, + label: row.label, + createdAt: row.createdAt, + expiresAt: row.expiresAt, + } satisfies AuthPairingLink) + : ({ + id: row.id, + credential: row.credential, + role: row.role, + subject: row.subject, + createdAt: row.createdAt, + expiresAt: row.expiresAt, + } satisfies AuthPairingLink), + ); + }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to load active pairing links."))); + + const revoke: BootstrapCredentialServiceShape["revoke"] = (id) => + Effect.gen(function* () { + const revokedAt = yield* DateTime.now; + const revoked = yield* pairingLinks.revoke({ + id, + revokedAt, + }); + if (revoked) { + yield* emitRemoved(id); + } + return revoked; + }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to revoke pairing link."))); + + const issueOneTimeToken: BootstrapCredentialServiceShape["issueOneTimeToken"] = (input) => + Effect.gen(function* () { + const id = crypto.randomUUID(); + const credential = generatePairingToken(); + const ttl = input?.ttl ?? DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES; + const now = yield* DateTime.now; + const expiresAt = DateTime.add(now, { milliseconds: Duration.toMillis(ttl) }); + const issued: IssuedBootstrapCredential = { + id, + credential, + ...(input?.label ? { label: input.label } : {}), + expiresAt, + }; + yield* pairingLinks.create({ + id, + credential, + method: "one-time-token", + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + label: input?.label ?? null, + createdAt: now, + expiresAt: expiresAt, + }); + yield* emitUpsert({ + id, + credential, + role: input?.role ?? "client", + subject: input?.subject ?? "one-time-token", + ...(input?.label ? { label: input.label } : {}), + createdAt: now, + expiresAt, + }); + return issued; + }).pipe(Effect.mapError(toBootstrapCredentialError("Failed to issue pairing credential."))); + + const consume: BootstrapCredentialServiceShape["consume"] = (credential) => + Effect.gen(function* () { + const now = yield* DateTime.now; + const seededResult: ConsumeResult = yield* Ref.modify( + seededGrantsRef, + (current): readonly [ConsumeResult, Map] => { + const grant = current.get(credential); + if (!grant) { + return [ + { + _tag: "error", + reason: "not-found", + error: invalidBootstrapCredentialError("Unknown bootstrap credential."), + }, + current, + ]; + } + + const next = new Map(current); + if (DateTime.isGreaterThanOrEqualTo(now, grant.expiresAt)) { + next.delete(credential); + return [ + { + _tag: "error", + reason: "expired", + error: invalidBootstrapCredentialError("Bootstrap credential expired."), + }, + next, + ]; + } + + const remainingUses = grant.remainingUses; + if (typeof remainingUses === "number") { + if (remainingUses <= 1) { + next.delete(credential); + } else { + next.set(credential, { + ...grant, + remainingUses: remainingUses - 1, + }); + } + } + + return [ + { + _tag: "success", + grant: { + method: grant.method, + role: grant.role, + subject: grant.subject, + ...(grant.label ? { label: grant.label } : {}), + expiresAt: grant.expiresAt, + } satisfies BootstrapGrant, + }, + next, + ]; + }, + ); + + if (seededResult._tag === "success") { + return seededResult.grant; + } + if (seededResult.reason !== "not-found") { + return yield* seededResult.error; + } + + const consumed = yield* pairingLinks.consumeAvailable({ + credential, + consumedAt: now, + now, + }); + + if (Option.isSome(consumed)) { + yield* emitRemoved(consumed.value.id); + return { + method: consumed.value.method, + role: consumed.value.role, + subject: consumed.value.subject, + ...(consumed.value.label ? { label: consumed.value.label } : {}), + expiresAt: consumed.value.expiresAt, + } satisfies BootstrapGrant; + } + + const matching = yield* pairingLinks.getByCredential({ credential }); + if (Option.isNone(matching)) { + return yield* invalidBootstrapCredentialError("Unknown bootstrap credential."); + } + + if (matching.value.revokedAt !== null) { + return yield* invalidBootstrapCredentialError( + "Bootstrap credential is no longer available.", + ); + } + + if (matching.value.consumedAt !== null) { + return yield* invalidBootstrapCredentialError("Unknown bootstrap credential."); + } + + if (DateTime.isGreaterThanOrEqualTo(now, matching.value.expiresAt)) { + return yield* invalidBootstrapCredentialError("Bootstrap credential expired."); + } + + return yield* invalidBootstrapCredentialError("Bootstrap credential is no longer available."); + }).pipe( + Effect.mapError((cause) => + cause instanceof BootstrapCredentialError + ? cause + : internalBootstrapCredentialError("Failed to consume bootstrap credential.", cause), + ), + ); + + return { + issueOneTimeToken, + listActive, + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + revoke, + consume, + } satisfies BootstrapCredentialServiceShape; +}); + +export const BootstrapCredentialServiceLive = Layer.effect( + BootstrapCredentialService, + makeBootstrapCredentialService, +).pipe(Layer.provideMerge(AuthPairingLinkRepositoryLive)); diff --git a/apps/server/src/auth/Layers/ServerAuth.test.ts b/apps/server/src/auth/Layers/ServerAuth.test.ts new file mode 100644 index 0000000000..0c3d71cc9f --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuth.test.ts @@ -0,0 +1,182 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts"; +import { ServerAuth, type ServerAuthShape } from "../Services/ServerAuth.ts"; +import { ServerAuthLive, toBootstrapExchangeAuthError } from "./ServerAuth.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; + +const makeServerConfigLayer = (overrides?: Partial) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-server-test-" }))); + +const makeServerAuthLayer = (overrides?: Partial) => + ServerAuthLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStoreLive), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +const makeCookieRequest = ( + sessionToken: string, +): Parameters[0] => + ({ + cookies: { + t3_session: sessionToken, + }, + headers: {}, + }) as unknown as Parameters[0]; + +const requestMetadata = { + deviceType: "desktop" as const, + os: "macOS", + browser: "Chrome", + ipAddress: "192.168.1.23", +}; + +it.layer(NodeServices.layer)("ServerAuthLive", (it) => { + it.effect("maps invalid bootstrap credential failures to 401", () => + Effect.sync(() => { + const error = toBootstrapExchangeAuthError( + new BootstrapCredentialError({ + message: "Unknown bootstrap credential.", + status: 401, + }), + ); + + expect(error.status).toBe(401); + expect(error.message).toBe("Invalid bootstrap credential."); + }), + ); + + it.effect("maps unexpected bootstrap failures to 500", () => + Effect.sync(() => { + const error = toBootstrapExchangeAuthError( + new BootstrapCredentialError({ + message: "Failed to consume bootstrap credential.", + status: 500, + cause: new Error("sqlite is unavailable"), + }), + ); + + expect(error.status).toBe(500); + expect(error.message).toBe("Failed to validate bootstrap credential."); + }), + ); + + it.effect("issues client pairing credentials by default", () => + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + + const pairingCredential = yield* serverAuth.issuePairingCredential(); + const exchanged = yield* serverAuth.exchangeBootstrapCredential( + pairingCredential.credential, + requestMetadata, + ); + const verified = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(exchanged.sessionToken), + ); + + expect(verified.sessionId.length).toBeGreaterThan(0); + expect(verified.role).toBe("client"); + expect(verified.subject).toBe("one-time-token"); + }).pipe(Effect.provide(makeServerAuthLayer())), + ); + + it.effect("issues startup pairing URLs that bootstrap owner sessions", () => + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + + const pairingUrl = yield* serverAuth.issueStartupPairingUrl("http://127.0.0.1:3773"); + const token = new URLSearchParams(new URL(pairingUrl).hash.slice(1)).get("token"); + const listedPairingLinks = yield* serverAuth.listPairingLinks(); + expect(token).toBeTruthy(); + expect( + listedPairingLinks.some((pairingLink) => pairingLink.subject === "owner-bootstrap"), + ).toBe(false); + + const exchanged = yield* serverAuth.exchangeBootstrapCredential(token ?? "", requestMetadata); + const verified = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(exchanged.sessionToken), + ); + + expect(verified.role).toBe("owner"); + expect(verified.subject).toBe("owner-bootstrap"); + }).pipe(Effect.provide(makeServerAuthLayer())), + ); + + it.effect("lists pairing links and revokes other client sessions while keeping the owner", () => + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + + const ownerExchange = yield* serverAuth.exchangeBootstrapCredential( + "desktop-bootstrap-token", + requestMetadata, + ); + const ownerSession = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(ownerExchange.sessionToken), + ); + const pairingCredential = yield* serverAuth.issuePairingCredential({ + label: "Julius iPhone", + }); + const listedPairingLinks = yield* serverAuth.listPairingLinks(); + const clientExchange = yield* serverAuth.exchangeBootstrapCredential( + pairingCredential.credential, + { + ...requestMetadata, + deviceType: "mobile", + os: "iOS", + browser: "Safari", + ipAddress: "192.168.1.88", + }, + ); + const clientSession = yield* serverAuth.authenticateHttpRequest( + makeCookieRequest(clientExchange.sessionToken), + ); + const clientsBeforeRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId); + const revokedCount = yield* serverAuth.revokeOtherClientSessions(ownerSession.sessionId); + const clientsAfterRevoke = yield* serverAuth.listClientSessions(ownerSession.sessionId); + + expect(listedPairingLinks.map((entry) => entry.id)).toContain(pairingCredential.id); + expect(listedPairingLinks.find((entry) => entry.id === pairingCredential.id)?.label).toBe( + "Julius iPhone", + ); + expect(clientsBeforeRevoke).toHaveLength(2); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === ownerSession.sessionId)?.current, + ).toBe(true); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.current, + ).toBe(false); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client + .label, + ).toBe("Julius iPhone"); + expect( + clientsBeforeRevoke.find((entry) => entry.sessionId === clientSession.sessionId)?.client + .deviceType, + ).toBe("mobile"); + expect(revokedCount).toBe(1); + expect(clientsAfterRevoke).toHaveLength(1); + expect(clientsAfterRevoke[0]?.sessionId).toBe(ownerSession.sessionId); + }).pipe( + Effect.provide( + makeServerAuthLayer({ + desktopBootstrapToken: "desktop-bootstrap-token", + }), + ), + ), + ); +}); diff --git a/apps/server/src/auth/Layers/ServerAuth.ts b/apps/server/src/auth/Layers/ServerAuth.ts new file mode 100644 index 0000000000..fa7191110a --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuth.ts @@ -0,0 +1,385 @@ +import { + type AuthBearerBootstrapResult, + type AuthClientSession, + type AuthBootstrapResult, + type AuthPairingCredentialResult, + type AuthSessionState, + type AuthWebSocketTokenResult, +} from "@t3tools/contracts"; +import { DateTime, Effect, Layer, Option } from "effect"; +import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; + +import { AuthControlPlane } from "../Services/AuthControlPlane.ts"; +import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts"; +import { BootstrapCredentialService } from "../Services/BootstrapCredentialService.ts"; +import { BootstrapCredentialError } from "../Services/BootstrapCredentialService.ts"; +import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts"; +import { + ServerAuth, + type AuthenticatedSession, + AuthError, + type ServerAuthShape, +} from "../Services/ServerAuth.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; +import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts"; + +type BootstrapExchangeResult = { + readonly response: AuthBootstrapResult; + readonly sessionToken: string; +}; + +const AUTHORIZATION_PREFIX = "Bearer "; +const WEBSOCKET_TOKEN_QUERY_PARAM = "wsToken"; + +export function toBootstrapExchangeAuthError(cause: BootstrapCredentialError): AuthError { + if (cause.status === 500) { + return new AuthError({ + message: "Failed to validate bootstrap credential.", + status: 500, + cause, + }); + } + + return new AuthError({ + message: "Invalid bootstrap credential.", + status: 401, + cause, + }); +} + +function parseBearerToken(request: HttpServerRequest.HttpServerRequest): string | null { + const header = request.headers["authorization"]; + if (typeof header !== "string" || !header.startsWith(AUTHORIZATION_PREFIX)) { + return null; + } + const token = header.slice(AUTHORIZATION_PREFIX.length).trim(); + return token.length > 0 ? token : null; +} + +export const makeServerAuth = Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const bootstrapCredentials = yield* BootstrapCredentialService; + const authControlPlane = yield* AuthControlPlane; + const sessions = yield* SessionCredentialService; + const descriptor = yield* policy.getDescriptor(); + + const authenticateToken = (token: string): Effect.Effect => + sessions.verify(token).pipe( + Effect.map((session) => ({ + sessionId: session.sessionId, + subject: session.subject, + method: session.method, + role: session.role, + ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}), + })), + Effect.mapError( + (cause) => + new AuthError({ + message: "Unauthorized request.", + status: 401, + cause, + }), + ), + ); + + const authenticateRequest = (request: HttpServerRequest.HttpServerRequest) => { + const cookieToken = request.cookies[sessions.cookieName]; + const bearerToken = parseBearerToken(request); + const credential = cookieToken ?? bearerToken; + if (!credential) { + return Effect.fail( + new AuthError({ + message: "Authentication required.", + status: 401, + }), + ); + } + return authenticateToken(credential); + }; + + const getSessionState: ServerAuthShape["getSessionState"] = (request) => + authenticateRequest(request).pipe( + Effect.map( + (session) => + ({ + authenticated: true, + auth: descriptor, + role: session.role, + sessionMethod: session.method, + ...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}), + }) satisfies AuthSessionState, + ), + Effect.catchTag("AuthError", () => + Effect.succeed({ + authenticated: false, + auth: descriptor, + } satisfies AuthSessionState), + ), + ); + + const exchangeBootstrapCredential: ServerAuthShape["exchangeBootstrapCredential"] = ( + credential, + requestMetadata, + ) => + bootstrapCredentials.consume(credential).pipe( + Effect.mapError(toBootstrapExchangeAuthError), + Effect.flatMap((grant) => + sessions + .issue({ + method: "browser-session-cookie", + subject: grant.subject, + role: grant.role, + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue authenticated session.", + cause, + }), + ), + ), + ), + Effect.map( + (session) => + ({ + response: { + authenticated: true, + role: session.role, + sessionMethod: session.method, + expiresAt: DateTime.toUtc(session.expiresAt), + } satisfies AuthBootstrapResult, + sessionToken: session.token, + }) satisfies BootstrapExchangeResult, + ), + ); + + const exchangeBootstrapCredentialForBearerSession: ServerAuthShape["exchangeBootstrapCredentialForBearerSession"] = + (credential, requestMetadata) => + bootstrapCredentials.consume(credential).pipe( + Effect.mapError(toBootstrapExchangeAuthError), + Effect.flatMap((grant) => + sessions + .issue({ + method: "bearer-session-token", + subject: grant.subject, + role: grant.role, + client: { + ...requestMetadata, + ...(grant.label ? { label: grant.label } : {}), + }, + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue authenticated session.", + cause, + }), + ), + ), + ), + Effect.map( + (session) => + ({ + authenticated: true, + role: session.role, + sessionMethod: "bearer-session-token", + expiresAt: DateTime.toUtc(session.expiresAt), + sessionToken: session.token, + }) satisfies AuthBearerBootstrapResult, + ), + ); + + const issuePairingCredential: ServerAuthShape["issuePairingCredential"] = (input) => + authControlPlane + .createPairingLink({ + role: input?.role ?? "client", + subject: input?.role === "owner" ? "owner-bootstrap" : "one-time-token", + ...(input?.label ? { label: input.label } : {}), + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue pairing credential.", + cause, + }), + ), + Effect.map( + (issued) => + ({ + id: issued.id, + credential: issued.credential, + ...(issued.label ? { label: issued.label } : {}), + expiresAt: issued.expiresAt, + }) satisfies AuthPairingCredentialResult, + ), + ); + + const listPairingLinks: ServerAuthShape["listPairingLinks"] = () => + authControlPlane + .listPairingLinks({ + role: "client", + excludeSubjects: ["owner-bootstrap"], + }) + .pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to load pairing links.", + cause, + }), + ), + ); + + const revokePairingLink: ServerAuthShape["revokePairingLink"] = (id) => + authControlPlane.revokePairingLink(id).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to revoke pairing link.", + cause, + }), + ), + ); + + const listClientSessions: ServerAuthShape["listClientSessions"] = (currentSessionId) => + authControlPlane.listSessions().pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to load paired clients.", + cause, + }), + ), + Effect.map((clientSessions) => + clientSessions.map( + (clientSession): AuthClientSession => ({ + ...clientSession, + current: clientSession.sessionId === currentSessionId, + }), + ), + ), + ); + + const revokeClientSession: ServerAuthShape["revokeClientSession"] = ( + currentSessionId, + targetSessionId, + ) => + Effect.gen(function* () { + if (currentSessionId === targetSessionId) { + return yield* new AuthError({ + message: "Use revoke other clients to keep the current owner session active.", + status: 403, + }); + } + return yield* authControlPlane.revokeSession(targetSessionId).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to revoke client session.", + cause, + }), + ), + ); + }); + + const revokeOtherClientSessions: ServerAuthShape["revokeOtherClientSessions"] = ( + currentSessionId, + ) => + authControlPlane.revokeOtherSessionsExcept(currentSessionId).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to revoke other client sessions.", + cause, + }), + ), + ); + + const issueStartupPairingUrl: ServerAuthShape["issueStartupPairingUrl"] = (baseUrl) => + issuePairingCredential({ role: "owner" }).pipe( + Effect.map((issued) => { + const url = new URL(baseUrl); + url.pathname = "/pair"; + url.searchParams.delete("token"); + url.hash = new URLSearchParams([["token", issued.credential]]).toString(); + return url.toString(); + }), + ); + + const issueWebSocketToken: ServerAuthShape["issueWebSocketToken"] = (session) => + sessions.issueWebSocketToken(session.sessionId).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Failed to issue websocket token.", + cause, + }), + ), + Effect.map( + (issued) => + ({ + token: issued.token, + expiresAt: DateTime.toUtc(issued.expiresAt), + }) satisfies AuthWebSocketTokenResult, + ), + ); + + const authenticateWebSocketUpgrade: ServerAuthShape["authenticateWebSocketUpgrade"] = (request) => + Effect.gen(function* () { + const requestUrl = HttpServerRequest.toURL(request); + if (Option.isSome(requestUrl)) { + const websocketToken = requestUrl.value.searchParams.get(WEBSOCKET_TOKEN_QUERY_PARAM); + if (websocketToken && websocketToken.trim().length > 0) { + return yield* sessions.verifyWebSocketToken(websocketToken).pipe( + Effect.map((session) => ({ + sessionId: session.sessionId, + subject: session.subject, + method: session.method, + role: session.role, + ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}), + })), + Effect.mapError( + (cause) => + new AuthError({ + message: "Unauthorized request.", + status: 401, + cause, + }), + ), + ); + } + } + + return yield* authenticateRequest(request); + }); + + return { + getDescriptor: () => Effect.succeed(descriptor), + getSessionState, + exchangeBootstrapCredential, + exchangeBootstrapCredentialForBearerSession, + issuePairingCredential, + listPairingLinks, + revokePairingLink, + listClientSessions, + revokeClientSession, + revokeOtherClientSessions, + authenticateHttpRequest: authenticateRequest, + authenticateWebSocketUpgrade, + issueWebSocketToken, + issueStartupPairingUrl, + } satisfies ServerAuthShape; +}); + +export const ServerAuthLive = Layer.effect(ServerAuth, makeServerAuth).pipe( + Layer.provideMerge(AuthControlPlaneLive), + Layer.provideMerge(AuthCoreLive), + Layer.provideMerge(ServerAuthPolicyLive), +); diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts b/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts new file mode 100644 index 0000000000..640cc030f8 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuthPolicy.test.ts @@ -0,0 +1,111 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Effect, Layer } from "effect"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { ServerAuthPolicy } from "../Services/ServerAuthPolicy.ts"; +import { ServerAuthPolicyLive } from "./ServerAuthPolicy.ts"; + +const makeServerAuthPolicyLayer = (overrides?: Partial) => + ServerAuthPolicyLive.pipe( + Layer.provide( + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe( + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-policy-test-" })), + ), + ), + ); + +it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => { + it.effect("uses desktop-managed-local policy for desktop mode", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("desktop-managed-local"); + expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "desktop", + }), + ), + ), + ); + + it.effect("uses remote-reachable policy for desktop mode when bound beyond loopback", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap", "one-time-token"]); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "desktop", + host: "0.0.0.0", + }), + ), + ), + ); + + it.effect("uses loopback-browser policy for loopback web hosts", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("loopback-browser"); + expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "web", + host: "127.0.0.1", + }), + ), + ), + ); + + it.effect("uses remote-reachable policy for wildcard web hosts", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "web", + host: "0.0.0.0", + }), + ), + ), + ); + + it.effect("uses remote-reachable policy for non-loopback web hosts", () => + Effect.gen(function* () { + const policy = yield* ServerAuthPolicy; + const descriptor = yield* policy.getDescriptor(); + + expect(descriptor.policy).toBe("remote-reachable"); + }).pipe( + Effect.provide( + makeServerAuthPolicyLayer({ + mode: "web", + host: "192.168.1.50", + }), + ), + ), + ); +}); diff --git a/apps/server/src/auth/Layers/ServerAuthPolicy.ts b/apps/server/src/auth/Layers/ServerAuthPolicy.ts new file mode 100644 index 0000000000..eaddf968f3 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerAuthPolicy.ts @@ -0,0 +1,57 @@ +import type { ServerAuthDescriptor } from "@t3tools/contracts"; +import { Effect, Layer } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts"; +import { SESSION_COOKIE_NAME } from "../utils.ts"; + +const isWildcardHost = (host: string | undefined): boolean => + host === "0.0.0.0" || host === "::" || host === "[::]"; + +const isLoopbackHost = (host: string | undefined): boolean => { + if (!host || host.length === 0) { + return true; + } + + return ( + host === "localhost" || + host === "127.0.0.1" || + host === "::1" || + host === "[::1]" || + host.startsWith("127.") + ); +}; + +export const makeServerAuthPolicy = Effect.gen(function* () { + const config = yield* ServerConfig; + const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host); + + const policy = + config.mode === "desktop" + ? isRemoteReachable + ? "remote-reachable" + : "desktop-managed-local" + : isRemoteReachable + ? "remote-reachable" + : "loopback-browser"; + + const bootstrapMethods: ServerAuthDescriptor["bootstrapMethods"] = + policy === "desktop-managed-local" + ? ["desktop-bootstrap"] + : config.mode === "desktop" && policy === "remote-reachable" + ? ["desktop-bootstrap", "one-time-token"] + : ["one-time-token"]; + + const descriptor: ServerAuthDescriptor = { + policy, + bootstrapMethods, + sessionMethods: ["browser-session-cookie", "bearer-session-token"], + sessionCookieName: SESSION_COOKIE_NAME, + }; + + return { + getDescriptor: () => Effect.succeed(descriptor), + } satisfies ServerAuthPolicyShape; +}); + +export const ServerAuthPolicyLive = Layer.effect(ServerAuthPolicy, makeServerAuthPolicy); diff --git a/apps/server/src/auth/Layers/ServerSecretStore.test.ts b/apps/server/src/auth/Layers/ServerSecretStore.test.ts new file mode 100644 index 0000000000..7e6352eec2 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerSecretStore.test.ts @@ -0,0 +1,263 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect"; +import * as PlatformError from "effect/PlatformError"; + +import { ServerConfig } from "../../config.ts"; +import { SecretStoreError, ServerSecretStore } from "../Services/ServerSecretStore.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; + +const makeServerConfigLayer = () => + ServerConfig.layerTest(process.cwd(), { prefix: "t3-secret-store-test-" }); + +const makeServerSecretStoreLayer = () => + Layer.provide(ServerSecretStoreLive, makeServerConfigLayer()); + +const PermissionDeniedFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + readFile: (path) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "readFile", + pathOrDescriptor: path, + description: "Permission denied while reading secret file.", + }), + ), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makePermissionDeniedSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(PermissionDeniedFileSystemLayer), + ); + +const RenameFailureFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + rename: (from, to) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "rename", + pathOrDescriptor: `${String(from)} -> ${String(to)}`, + description: "Permission denied while persisting secret file.", + }), + ), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makeRenameFailureSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(RenameFailureFileSystemLayer), + ); + +const RemoveFailureFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + remove: (path, options) => + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "remove", + pathOrDescriptor: String(path), + description: `Permission denied while removing secret file.${options ? " options-set" : ""}`, + }), + ), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makeRemoveFailureSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(RemoveFailureFileSystemLayer), + ); + +const ConcurrentReadMissFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const readCountRef = yield* Ref.make(0); + const readBarrier = yield* Deferred.make(); + + return { + ...fileSystem, + readFile: (path) => + String(path).endsWith("/session-signing-key.bin") + ? Ref.updateAndGet(readCountRef, (count) => count + 1).pipe( + Effect.flatMap((count) => { + if (count > 2) { + return fileSystem.readFile(path); + } + return Effect.gen(function* () { + if (count === 2) { + yield* Deferred.succeed(readBarrier, void 0); + } + yield* Deferred.await(readBarrier); + return yield* Effect.failCause( + Cause.fail( + PlatformError.systemError({ + _tag: "NotFound", + module: "FileSystem", + method: "readFile", + pathOrDescriptor: String(path), + description: "Secret file does not exist yet.", + }), + ), + ); + }); + }), + ) + : fileSystem.readFile(path), + } satisfies FileSystem.FileSystem; + }), +).pipe(Layer.provide(NodeServices.layer)); + +const makeConcurrentCreateSecretStoreLayer = () => + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(ConcurrentReadMissFileSystemLayer), + ); + +it.layer(NodeServices.layer)("ServerSecretStoreLive", (it) => { + it.effect("returns null when a secret file does not exist", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const secret = yield* secretStore.get("missing-secret"); + + expect(secret).toBeNull(); + }).pipe(Effect.provide(makeServerSecretStoreLayer())), + ); + + it.effect("reuses an existing secret instead of regenerating it", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const first = yield* secretStore.getOrCreateRandom("session-signing-key", 32); + const second = yield* secretStore.getOrCreateRandom("session-signing-key", 32); + + expect(Array.from(second)).toEqual(Array.from(first)); + }).pipe(Effect.provide(makeServerSecretStoreLayer())), + ); + + it.effect("returns the persisted secret when concurrent creators race", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const [first, second] = yield* Effect.all( + [ + secretStore.getOrCreateRandom("session-signing-key", 32), + secretStore.getOrCreateRandom("session-signing-key", 32), + ], + { concurrency: "unbounded" }, + ); + const persisted = yield* secretStore.get("session-signing-key"); + + expect(persisted).not.toBeNull(); + expect(Array.from(first)).toEqual(Array.from(persisted ?? new Uint8Array())); + expect(Array.from(second)).toEqual(Array.from(persisted ?? new Uint8Array())); + }).pipe(Effect.provide(makeConcurrentCreateSecretStoreLayer())), + ); + + it.effect("uses restrictive permissions for the secret directory and files", () => + Effect.gen(function* () { + const chmodCalls: Array<{ readonly path: string; readonly mode: number }> = []; + const recordingFileSystemLayer = Layer.effect( + FileSystem.FileSystem, + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + + return { + ...fileSystem, + makeDirectory: () => Effect.void, + writeFile: () => Effect.void, + rename: () => Effect.void, + chmod: (path, mode) => + Effect.sync(() => { + chmodCalls.push({ path: String(path), mode }); + }), + } satisfies FileSystem.FileSystem; + }), + ).pipe(Layer.provide(NodeServices.layer)); + + const secretStore = yield* Effect.service(ServerSecretStore).pipe( + Effect.provide( + ServerSecretStoreLive.pipe( + Layer.provide(makeServerConfigLayer()), + Layer.provideMerge(recordingFileSystemLayer), + ), + ), + ); + + yield* secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])); + + expect(chmodCalls.some((call) => call.mode === 0o700 && call.path.endsWith("/secrets"))).toBe( + true, + ); + expect(chmodCalls.filter((call) => call.mode === 0o600).length).toBeGreaterThanOrEqual(2); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("propagates read failures other than missing-file errors", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const error = yield* Effect.flip(secretStore.getOrCreateRandom("session-signing-key", 32)); + + expect(error).toBeInstanceOf(SecretStoreError); + expect(error.message).toContain("Failed to read secret session-signing-key."); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied"); + }).pipe(Effect.provide(makePermissionDeniedSecretStoreLayer())), + ); + + it.effect("propagates write failures instead of treating them as success", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const error = yield* Effect.flip( + secretStore.set("session-signing-key", Uint8Array.from([1, 2, 3])), + ); + + expect(error).toBeInstanceOf(SecretStoreError); + expect(error.message).toContain("Failed to persist secret session-signing-key."); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied"); + }).pipe(Effect.provide(makeRenameFailureSecretStoreLayer())), + ); + + it.effect("propagates remove failures other than missing-file errors", () => + Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + + const error = yield* Effect.flip(secretStore.remove("session-signing-key")); + + expect(error).toBeInstanceOf(SecretStoreError); + expect(error.message).toContain("Failed to remove secret session-signing-key."); + expect(error.cause).toBeInstanceOf(PlatformError.PlatformError); + expect((error.cause as PlatformError.PlatformError).reason._tag).toBe("PermissionDenied"); + }).pipe(Effect.provide(makeRemoveFailureSecretStoreLayer())), + ); +}); diff --git a/apps/server/src/auth/Layers/ServerSecretStore.ts b/apps/server/src/auth/Layers/ServerSecretStore.ts new file mode 100644 index 0000000000..a106d15fd5 --- /dev/null +++ b/apps/server/src/auth/Layers/ServerSecretStore.ts @@ -0,0 +1,151 @@ +import * as Crypto from "node:crypto"; + +import { Effect, FileSystem, Layer, Path } from "effect"; +import * as PlatformError from "effect/PlatformError"; + +import { ServerConfig } from "../../config.ts"; +import { + SecretStoreError, + ServerSecretStore, + type ServerSecretStoreShape, +} from "../Services/ServerSecretStore.ts"; + +export const makeServerSecretStore = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + + yield* fileSystem.makeDirectory(serverConfig.secretsDir, { recursive: true }); + yield* fileSystem.chmod(serverConfig.secretsDir, 0o700).pipe( + Effect.mapError( + (cause) => + new SecretStoreError({ + message: `Failed to secure secrets directory ${serverConfig.secretsDir}.`, + cause, + }), + ), + ); + + const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`); + + const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError => + cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound"; + + const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError => + cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists"; + + const get: ServerSecretStoreShape["get"] = (name) => + fileSystem.readFile(resolveSecretPath(name)).pipe( + Effect.map((bytes) => Uint8Array.from(bytes)), + Effect.catch((cause) => + isMissingSecretFileError(cause) + ? Effect.succeed(null) + : Effect.fail( + new SecretStoreError({ + message: `Failed to read secret ${name}.`, + cause, + }), + ), + ), + ); + + const set: ServerSecretStoreShape["set"] = (name, value) => { + const secretPath = resolveSecretPath(name); + const tempPath = `${secretPath}.${Crypto.randomUUID()}.tmp`; + return Effect.gen(function* () { + yield* fileSystem.writeFile(tempPath, value); + yield* fileSystem.chmod(tempPath, 0o600); + yield* fileSystem.rename(tempPath, secretPath); + yield* fileSystem.chmod(secretPath, 0o600); + }).pipe( + Effect.catch((cause) => + fileSystem.remove(tempPath).pipe( + Effect.ignore, + Effect.flatMap(() => + Effect.fail( + new SecretStoreError({ + message: `Failed to persist secret ${name}.`, + cause, + }), + ), + ), + ), + ), + ); + }; + + const create: ServerSecretStoreShape["set"] = (name, value) => { + const secretPath = resolveSecretPath(name); + return Effect.scoped( + Effect.gen(function* () { + const file = yield* fileSystem.open(secretPath, { + flag: "wx", + mode: 0o600, + }); + yield* file.writeAll(value); + yield* file.sync; + yield* fileSystem.chmod(secretPath, 0o600); + }), + ).pipe( + Effect.mapError( + (cause) => + new SecretStoreError({ + message: `Failed to persist secret ${name}.`, + cause, + }), + ), + ); + }; + + const getOrCreateRandom: ServerSecretStoreShape["getOrCreateRandom"] = (name, bytes) => + get(name).pipe( + Effect.flatMap((existing) => { + if (existing) { + return Effect.succeed(existing); + } + + const generated = Crypto.randomBytes(bytes); + return create(name, generated).pipe( + Effect.as(Uint8Array.from(generated)), + Effect.catchTag("SecretStoreError", (error) => + isAlreadyExistsSecretFileError(error.cause) + ? get(name).pipe( + Effect.flatMap((created) => + created !== null + ? Effect.succeed(created) + : Effect.fail( + new SecretStoreError({ + message: `Failed to read secret ${name} after concurrent creation.`, + }), + ), + ), + ) + : Effect.fail(error), + ), + ); + }), + ); + + const remove: ServerSecretStoreShape["remove"] = (name) => + fileSystem.remove(resolveSecretPath(name)).pipe( + Effect.catch((cause) => + isMissingSecretFileError(cause) + ? Effect.void + : Effect.fail( + new SecretStoreError({ + message: `Failed to remove secret ${name}.`, + cause, + }), + ), + ), + ); + + return { + get, + set, + getOrCreateRandom, + remove, + } satisfies ServerSecretStoreShape; +}); + +export const ServerSecretStoreLive = Layer.effect(ServerSecretStore, makeServerSecretStore); diff --git a/apps/server/src/auth/Layers/SessionCredentialService.test.ts b/apps/server/src/auth/Layers/SessionCredentialService.test.ts new file mode 100644 index 0000000000..bafd9c85c2 --- /dev/null +++ b/apps/server/src/auth/Layers/SessionCredentialService.test.ts @@ -0,0 +1,191 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import { Duration, Effect, Layer } from "effect"; +import { TestClock } from "effect/testing"; + +import type { ServerConfigShape } from "../../config.ts"; +import { ServerConfig } from "../../config.ts"; +import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts"; +import { SessionCredentialService } from "../Services/SessionCredentialService.ts"; +import { ServerSecretStoreLive } from "./ServerSecretStore.ts"; +import { SessionCredentialServiceLive } from "./SessionCredentialService.ts"; + +const makeServerConfigLayer = ( + overrides?: Partial>, +) => + Layer.effect( + ServerConfig, + Effect.gen(function* () { + const config = yield* ServerConfig; + return { + ...config, + ...overrides, + } satisfies ServerConfigShape; + }), + ).pipe(Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-auth-session-test-" }))); + +const makeSessionCredentialLayer = ( + overrides?: Partial>, +) => + SessionCredentialServiceLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStoreLive), + Layer.provide(makeServerConfigLayer(overrides)), + ); + +it.layer(NodeServices.layer)("SessionCredentialServiceLive", (it) => { + it.effect("issues and verifies signed browser session tokens", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + subject: "desktop-bootstrap", + role: "owner", + client: { + label: "Desktop app", + deviceType: "desktop", + os: "macOS", + browser: "Electron", + ipAddress: "127.0.0.1", + }, + }); + const verified = yield* sessions.verify(issued.token); + + expect(verified.method).toBe("browser-session-cookie"); + expect(verified.subject).toBe("desktop-bootstrap"); + expect(verified.role).toBe("owner"); + expect(verified.client.label).toBe("Desktop app"); + expect(verified.client.browser).toBe("Electron"); + expect(verified.expiresAt?.toString()).toBe(issued.expiresAt.toString()); + }).pipe(Effect.provide(makeSessionCredentialLayer())), + ); + it.effect("rejects malformed session tokens", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const error = yield* Effect.flip(sessions.verify("not-a-session-token")); + + expect(error._tag).toBe("SessionCredentialError"); + expect(error.message).toContain("Malformed session token"); + }).pipe(Effect.provide(makeSessionCredentialLayer())), + ); + it.effect("verifies session tokens against the Effect clock", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + method: "bearer-session-token", + subject: "test-clock", + }); + const verified = yield* sessions.verify(issued.token); + + expect(verified.method).toBe("bearer-session-token"); + expect(verified.subject).toBe("test-clock"); + expect(verified.role).toBe("client"); + }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))), + ); + + it.effect("rejects websocket tokens once the parent session has expired", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + method: "bearer-session-token", + subject: "short-lived", + ttl: Duration.seconds(1), + }); + const websocket = yield* sessions.issueWebSocketToken(issued.sessionId); + + yield* TestClock.adjust(Duration.seconds(2)); + + const error = yield* Effect.flip(sessions.verifyWebSocketToken(websocket.token)); + expect(error.message).toContain("expired"); + }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))), + ); + + it.effect("lists active sessions, tracks connectivity, and revokes other sessions", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const owner = yield* sessions.issue({ + subject: "desktop-bootstrap", + role: "owner", + client: { + label: "Desktop app", + deviceType: "desktop", + os: "macOS", + browser: "Electron", + }, + }); + const client = yield* sessions.issue({ + subject: "one-time-token", + role: "client", + client: { + label: "Julius iPhone", + deviceType: "mobile", + os: "iOS", + browser: "Safari", + ipAddress: "192.168.1.88", + }, + }); + + yield* sessions.markConnected(client.sessionId); + const beforeRevoke = yield* sessions.listActive(); + const revokedCount = yield* sessions.revokeAllExcept(owner.sessionId); + const afterRevoke = yield* sessions.listActive(); + const revokedClient = yield* Effect.flip(sessions.verify(client.token)); + + expect(beforeRevoke).toHaveLength(2); + expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.connected).toBe( + true, + ); + expect(beforeRevoke.find((entry) => entry.sessionId === client.sessionId)?.client.label).toBe( + "Julius iPhone", + ); + expect( + beforeRevoke.find((entry) => entry.sessionId === owner.sessionId)?.client.deviceType, + ).toBe("desktop"); + expect(revokedCount).toBe(1); + expect(afterRevoke).toHaveLength(1); + expect(afterRevoke[0]?.sessionId).toBe(owner.sessionId); + expect(revokedClient.message).toContain("revoked"); + }).pipe(Effect.provide(makeSessionCredentialLayer())), + ); + + it.effect("persists lastConnectedAt on first connect and updates it after reconnect", () => + Effect.gen(function* () { + const sessions = yield* SessionCredentialService; + const issued = yield* sessions.issue({ + subject: "reconnect-test", + method: "bearer-session-token", + }); + + const beforeConnect = yield* sessions.listActive(); + expect(beforeConnect[0]?.lastConnectedAt).toBeNull(); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* sessions.markConnected(issued.sessionId); + const firstConnect = yield* sessions.listActive(); + const firstConnectedAt = firstConnect[0]?.lastConnectedAt; + + expect(firstConnect[0]?.connected).toBe(true); + expect(firstConnectedAt).not.toBeNull(); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* sessions.markConnected(issued.sessionId); + const stillConnected = yield* sessions.listActive(); + + expect(stillConnected[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString()); + + yield* sessions.markDisconnected(issued.sessionId); + yield* sessions.markDisconnected(issued.sessionId); + const afterDisconnect = yield* sessions.listActive(); + + expect(afterDisconnect[0]?.connected).toBe(false); + expect(afterDisconnect[0]?.lastConnectedAt?.toString()).toBe(firstConnectedAt?.toString()); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* sessions.markConnected(issued.sessionId); + const afterReconnect = yield* sessions.listActive(); + + expect(afterReconnect[0]?.connected).toBe(true); + expect(afterReconnect[0]?.lastConnectedAt).not.toBeNull(); + expect(afterReconnect[0]?.lastConnectedAt?.toString()).not.toBe(firstConnectedAt?.toString()); + }).pipe(Effect.provide(Layer.merge(makeSessionCredentialLayer(), TestClock.layer()))), + ); +}); diff --git a/apps/server/src/auth/Layers/SessionCredentialService.ts b/apps/server/src/auth/Layers/SessionCredentialService.ts new file mode 100644 index 0000000000..e8d034aff2 --- /dev/null +++ b/apps/server/src/auth/Layers/SessionCredentialService.ts @@ -0,0 +1,493 @@ +import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts"; +import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect"; +import { Option } from "effect"; + +import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts"; +import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts"; +import { ServerSecretStore } from "../Services/ServerSecretStore.ts"; +import { SESSION_COOKIE_NAME } from "../utils.ts"; +import { + SessionCredentialError, + SessionCredentialService, + type IssuedSession, + type SessionCredentialChange, + type SessionCredentialServiceShape, + type VerifiedSession, +} from "../Services/SessionCredentialService.ts"; +import { + base64UrlDecodeUtf8, + base64UrlEncode, + signPayload, + timingSafeEqualBase64Url, +} from "../utils.ts"; + +const SIGNING_SECRET_NAME = "server-signing-key"; +const DEFAULT_SESSION_TTL = Duration.days(30); +const DEFAULT_WEBSOCKET_TOKEN_TTL = Duration.minutes(5); + +const SessionClaims = Schema.Struct({ + v: Schema.Literal(1), + kind: Schema.Literal("session"), + sid: AuthSessionId, + sub: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + iat: Schema.Number, + exp: Schema.Number, +}); +type SessionClaims = typeof SessionClaims.Type; + +const WebSocketClaims = Schema.Struct({ + v: Schema.Literal(1), + kind: Schema.Literal("websocket"), + sid: AuthSessionId, + iat: Schema.Number, + exp: Schema.Number, +}); +type WebSocketClaims = typeof WebSocketClaims.Type; + +function createDefaultClientMetadata(): AuthClientMetadata { + return { + deviceType: "unknown", + }; +} + +function toClientMetadata(record: { + readonly label: string | null; + readonly ipAddress: string | null; + readonly userAgent: string | null; + readonly deviceType: AuthClientMetadata["deviceType"]; + readonly os: string | null; + readonly browser: string | null; +}): AuthClientMetadata { + return { + ...(record.label ? { label: record.label } : {}), + ...(record.ipAddress ? { ipAddress: record.ipAddress } : {}), + ...(record.userAgent ? { userAgent: record.userAgent } : {}), + deviceType: record.deviceType, + ...(record.os ? { os: record.os } : {}), + ...(record.browser ? { browser: record.browser } : {}), + }; +} + +function toAuthClientSession(input: Omit): AuthClientSession { + return { + ...input, + current: false, + }; +} + +export const makeSessionCredentialService = Effect.gen(function* () { + const secretStore = yield* ServerSecretStore; + const authSessions = yield* AuthSessionRepository; + const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32); + const connectedSessionsRef = yield* Ref.make(new Map()); + const changesPubSub = yield* PubSub.unbounded(); + + const toSessionCredentialError = (message: string) => (cause: unknown) => + new SessionCredentialError({ + message, + cause, + }); + + const emitUpsert = (clientSession: AuthClientSession) => + PubSub.publish(changesPubSub, { + type: "clientUpserted", + clientSession, + }).pipe(Effect.asVoid); + + const emitRemoved = (sessionId: AuthSessionId) => + PubSub.publish(changesPubSub, { + type: "clientRemoved", + sessionId, + }).pipe(Effect.asVoid); + + const loadActiveSession = (sessionId: AuthSessionId) => + Effect.gen(function* () { + const row = yield* authSessions.getById({ sessionId }); + if (Option.isNone(row) || row.value.revokedAt !== null) { + return Option.none(); + } + + const connectedSessions = yield* Ref.get(connectedSessionsRef); + return Option.some( + toAuthClientSession({ + sessionId: row.value.sessionId, + subject: row.value.subject, + role: row.value.role, + method: row.value.method, + client: toClientMetadata(row.value.client), + issuedAt: row.value.issuedAt, + expiresAt: row.value.expiresAt, + lastConnectedAt: row.value.lastConnectedAt, + connected: connectedSessions.has(row.value.sessionId), + }), + ); + }); + + const markConnected: SessionCredentialServiceShape["markConnected"] = (sessionId) => + Ref.modify(connectedSessionsRef, (current) => { + const next = new Map(current); + const wasDisconnected = !next.has(sessionId); + next.set(sessionId, (next.get(sessionId) ?? 0) + 1); + return [wasDisconnected, next] as const; + }).pipe( + Effect.flatMap((wasDisconnected) => + wasDisconnected + ? DateTime.now.pipe( + Effect.flatMap((lastConnectedAt) => + authSessions.setLastConnectedAt({ + sessionId, + lastConnectedAt, + }), + ), + ) + : Effect.void, + ), + Effect.flatMap(() => loadActiveSession(sessionId)), + Effect.flatMap((session) => + Option.isSome(session) ? emitUpsert(session.value) : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logError("Failed to publish connected-session auth update.").pipe( + Effect.annotateLogs({ + sessionId, + cause, + }), + ), + ), + ); + + const markDisconnected: SessionCredentialServiceShape["markDisconnected"] = (sessionId) => + Ref.update(connectedSessionsRef, (current) => { + const next = new Map(current); + const remaining = (next.get(sessionId) ?? 0) - 1; + if (remaining > 0) { + next.set(sessionId, remaining); + } else { + next.delete(sessionId); + } + return next; + }).pipe( + Effect.flatMap(() => loadActiveSession(sessionId)), + Effect.flatMap((session) => + Option.isSome(session) ? emitUpsert(session.value) : Effect.void, + ), + Effect.catchCause((cause) => + Effect.logError("Failed to publish disconnected-session auth update.").pipe( + Effect.annotateLogs({ + sessionId, + cause, + }), + ), + ), + ); + + const issue: SessionCredentialServiceShape["issue"] = (input) => + Effect.gen(function* () { + const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID()); + const issuedAt = yield* DateTime.now; + const expiresAt = DateTime.add(issuedAt, { + milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL), + }); + const claims: SessionClaims = { + v: 1, + kind: "session", + sid: sessionId, + sub: input?.subject ?? "browser", + role: input?.role ?? "client", + method: input?.method ?? "browser-session-cookie", + iat: issuedAt.epochMilliseconds, + exp: expiresAt.epochMilliseconds, + }; + const encodedPayload = base64UrlEncode(JSON.stringify(claims)); + const signature = signPayload(encodedPayload, signingSecret); + const client = input?.client ?? createDefaultClientMetadata(); + yield* authSessions.create({ + sessionId, + subject: claims.sub, + role: claims.role, + method: claims.method, + client: { + label: client.label ?? null, + ipAddress: client.ipAddress ?? null, + userAgent: client.userAgent ?? null, + deviceType: client.deviceType, + os: client.os ?? null, + browser: client.browser ?? null, + }, + issuedAt, + expiresAt, + }); + yield* emitUpsert( + toAuthClientSession({ + sessionId, + subject: claims.sub, + role: claims.role, + method: claims.method, + client, + issuedAt, + expiresAt, + lastConnectedAt: null, + connected: false, + }), + ); + + return { + sessionId, + token: `${encodedPayload}.${signature}`, + method: claims.method, + client, + expiresAt: expiresAt, + role: claims.role, + } satisfies IssuedSession; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue session credential."))); + + const verify: SessionCredentialServiceShape["verify"] = (token) => + Effect.gen(function* () { + const [encodedPayload, signature] = token.split("."); + if (!encodedPayload || !signature) { + return yield* new SessionCredentialError({ + message: "Malformed session token.", + }); + } + + const expectedSignature = signPayload(encodedPayload, signingSecret); + if (!timingSafeEqualBase64Url(signature, expectedSignature)) { + return yield* new SessionCredentialError({ + message: "Invalid session token signature.", + }); + } + + const claims = yield* Effect.try({ + try: () => + Schema.decodeUnknownSync(SessionClaims)(JSON.parse(base64UrlDecodeUtf8(encodedPayload))), + catch: (cause) => + new SessionCredentialError({ + message: "Invalid session token payload.", + cause, + }), + }); + + const now = yield* Clock.currentTimeMillis; + if (claims.exp <= now) { + return yield* new SessionCredentialError({ + message: "Session token expired.", + }); + } + + const row = yield* authSessions.getById({ sessionId: claims.sid }); + if (Option.isNone(row)) { + return yield* new SessionCredentialError({ + message: "Unknown session token.", + }); + } + if (row.value.revokedAt !== null) { + return yield* new SessionCredentialError({ + message: "Session token revoked.", + }); + } + + return { + sessionId: claims.sid, + token, + method: claims.method, + client: toClientMetadata(row.value.client), + expiresAt: DateTime.makeUnsafe(claims.exp), + subject: claims.sub, + role: claims.role, + } satisfies VerifiedSession; + }).pipe( + Effect.mapError((cause) => + cause instanceof SessionCredentialError + ? cause + : new SessionCredentialError({ + message: "Failed to verify session credential.", + cause, + }), + ), + ); + + const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = ( + sessionId, + input, + ) => + Effect.gen(function* () { + const issuedAt = yield* DateTime.now; + const expiresAt = DateTime.add(issuedAt, { + milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_WEBSOCKET_TOKEN_TTL), + }); + const claims: WebSocketClaims = { + v: 1, + kind: "websocket", + sid: sessionId, + iat: issuedAt.epochMilliseconds, + exp: expiresAt.epochMilliseconds, + }; + const encodedPayload = base64UrlEncode(JSON.stringify(claims)); + const signature = signPayload(encodedPayload, signingSecret); + return { + token: `${encodedPayload}.${signature}`, + expiresAt, + }; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to issue websocket token."))); + + const verifyWebSocketToken: SessionCredentialServiceShape["verifyWebSocketToken"] = (token) => + Effect.gen(function* () { + const [encodedPayload, signature] = token.split("."); + if (!encodedPayload || !signature) { + return yield* new SessionCredentialError({ + message: "Malformed websocket token.", + }); + } + + const expectedSignature = signPayload(encodedPayload, signingSecret); + if (!timingSafeEqualBase64Url(signature, expectedSignature)) { + return yield* new SessionCredentialError({ + message: "Invalid websocket token signature.", + }); + } + + const claims = yield* Effect.try({ + try: () => + Schema.decodeUnknownSync(WebSocketClaims)( + JSON.parse(base64UrlDecodeUtf8(encodedPayload)), + ), + catch: (cause) => + new SessionCredentialError({ + message: "Invalid websocket token payload.", + cause, + }), + }); + + const now = yield* Clock.currentTimeMillis; + if (claims.exp <= now) { + return yield* new SessionCredentialError({ + message: "Websocket token expired.", + }); + } + + const row = yield* authSessions.getById({ sessionId: claims.sid }); + if (Option.isNone(row)) { + return yield* new SessionCredentialError({ + message: "Unknown websocket session.", + }); + } + if (row.value.expiresAt.epochMilliseconds <= now) { + return yield* new SessionCredentialError({ + message: "Websocket session expired.", + }); + } + if (row.value.revokedAt !== null) { + return yield* new SessionCredentialError({ + message: "Websocket session revoked.", + }); + } + + return { + sessionId: row.value.sessionId, + token, + method: row.value.method, + client: toClientMetadata(row.value.client), + expiresAt: row.value.expiresAt, + subject: row.value.subject, + role: row.value.role, + } satisfies VerifiedSession; + }).pipe( + Effect.mapError((cause) => + cause instanceof SessionCredentialError + ? cause + : new SessionCredentialError({ + message: "Failed to verify websocket token.", + cause, + }), + ), + ); + + const listActive: SessionCredentialServiceShape["listActive"] = () => + Effect.gen(function* () { + const now = yield* DateTime.now; + const connectedSessions = yield* Ref.get(connectedSessionsRef); + const rows = yield* authSessions.listActive({ now }); + + return rows.map((row) => + toAuthClientSession({ + sessionId: row.sessionId, + subject: row.subject, + role: row.role, + method: row.method, + client: toClientMetadata(row.client), + issuedAt: row.issuedAt, + expiresAt: row.expiresAt, + lastConnectedAt: row.lastConnectedAt, + connected: connectedSessions.has(row.sessionId), + }), + ); + }).pipe(Effect.mapError(toSessionCredentialError("Failed to list active sessions."))); + + const revoke: SessionCredentialServiceShape["revoke"] = (sessionId) => + Effect.gen(function* () { + const revokedAt = yield* DateTime.now; + const revoked = yield* authSessions.revoke({ + sessionId, + revokedAt, + }); + if (revoked) { + yield* Ref.update(connectedSessionsRef, (current) => { + const next = new Map(current); + next.delete(sessionId); + return next; + }); + yield* emitRemoved(sessionId); + } + return revoked; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke session."))); + + const revokeAllExcept: SessionCredentialServiceShape["revokeAllExcept"] = (sessionId) => + Effect.gen(function* () { + const revokedAt = yield* DateTime.now; + const revokedSessionIds = yield* authSessions.revokeAllExcept({ + currentSessionId: sessionId, + revokedAt, + }); + if (revokedSessionIds.length > 0) { + yield* Ref.update(connectedSessionsRef, (current) => { + const next = new Map(current); + for (const revokedSessionId of revokedSessionIds) { + next.delete(revokedSessionId); + } + return next; + }); + yield* Effect.forEach( + revokedSessionIds, + (revokedSessionId) => emitRemoved(revokedSessionId), + { + concurrency: "unbounded", + discard: true, + }, + ); + } + return revokedSessionIds.length; + }).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions."))); + + return { + cookieName: SESSION_COOKIE_NAME, + issue, + verify, + issueWebSocketToken, + verifyWebSocketToken, + listActive, + get streamChanges() { + return Stream.fromPubSub(changesPubSub); + }, + revoke, + revokeAllExcept, + markConnected, + markDisconnected, + } satisfies SessionCredentialServiceShape; +}); + +export const SessionCredentialServiceLive = Layer.effect( + SessionCredentialService, + makeSessionCredentialService, +).pipe(Layer.provideMerge(AuthSessionRepositoryLive)); diff --git a/apps/server/src/auth/Services/AuthControlPlane.ts b/apps/server/src/auth/Services/AuthControlPlane.ts new file mode 100644 index 0000000000..cbaaf98fd3 --- /dev/null +++ b/apps/server/src/auth/Services/AuthControlPlane.ts @@ -0,0 +1,69 @@ +import type { + AuthClientMetadata, + AuthClientSession, + AuthPairingLink, + AuthSessionId, +} from "@t3tools/contracts"; +import { Data, DateTime, Duration, Effect, ServiceMap } from "effect"; +import { SessionRole } from "./SessionCredentialService"; + +export const DEFAULT_SESSION_SUBJECT = "cli-issued-session"; + +export interface IssuedPairingLink { + readonly id: string; + readonly credential: string; + readonly role: SessionRole; + readonly subject: string; + readonly label?: string; + readonly createdAt: DateTime.Utc; + readonly expiresAt: DateTime.Utc; +} + +export interface IssuedBearerSession { + readonly sessionId: AuthSessionId; + readonly token: string; + readonly method: "bearer-session-token"; + readonly role: SessionRole; + readonly subject: string; + readonly client: AuthClientMetadata; + readonly expiresAt: DateTime.Utc; +} + +export class AuthControlPlaneError extends Data.TaggedError("AuthControlPlaneError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface AuthControlPlaneShape { + readonly createPairingLink: (input?: { + readonly ttl?: Duration.Duration; + readonly label?: string; + readonly role?: SessionRole; + readonly subject?: string; + }) => Effect.Effect; + readonly listPairingLinks: (input?: { + readonly role?: SessionRole; + readonly excludeSubjects?: ReadonlyArray; + }) => Effect.Effect, AuthControlPlaneError>; + readonly revokePairingLink: (id: string) => Effect.Effect; + readonly issueSession: (input?: { + readonly ttl?: Duration.Duration; + readonly subject?: string; + readonly role?: SessionRole; + readonly label?: string; + }) => Effect.Effect; + readonly listSessions: () => Effect.Effect< + ReadonlyArray, + AuthControlPlaneError + >; + readonly revokeSession: ( + sessionId: AuthSessionId, + ) => Effect.Effect; + readonly revokeOtherSessionsExcept: ( + sessionId: AuthSessionId, + ) => Effect.Effect; +} + +export class AuthControlPlane extends ServiceMap.Service()( + "t3/AuthControlPlane", +) {} diff --git a/apps/server/src/auth/Services/BootstrapCredentialService.ts b/apps/server/src/auth/Services/BootstrapCredentialService.ts new file mode 100644 index 0000000000..4f5cf4fdab --- /dev/null +++ b/apps/server/src/auth/Services/BootstrapCredentialService.ts @@ -0,0 +1,57 @@ +import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts"; +import { Data, DateTime, Duration, ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +export type BootstrapCredentialRole = "owner" | "client"; + +export interface BootstrapGrant { + readonly method: ServerAuthBootstrapMethod; + readonly role: BootstrapCredentialRole; + readonly subject: string; + readonly label?: string; + readonly expiresAt: DateTime.DateTime; +} + +export class BootstrapCredentialError extends Data.TaggedError("BootstrapCredentialError")<{ + readonly message: string; + readonly status?: 401 | 500; + readonly cause?: unknown; +}> {} + +export interface IssuedBootstrapCredential { + readonly id: string; + readonly credential: string; + readonly label?: string; + readonly expiresAt: DateTime.Utc; +} + +export type BootstrapCredentialChange = + | { + readonly type: "pairingLinkUpserted"; + readonly pairingLink: AuthPairingLink; + } + | { + readonly type: "pairingLinkRemoved"; + readonly id: string; + }; + +export interface BootstrapCredentialServiceShape { + readonly issueOneTimeToken: (input?: { + readonly ttl?: Duration.Duration; + readonly role?: BootstrapCredentialRole; + readonly subject?: string; + readonly label?: string; + }) => Effect.Effect; + readonly listActive: () => Effect.Effect< + ReadonlyArray, + BootstrapCredentialError + >; + readonly streamChanges: Stream.Stream; + readonly revoke: (id: string) => Effect.Effect; + readonly consume: (credential: string) => Effect.Effect; +} + +export class BootstrapCredentialService extends ServiceMap.Service< + BootstrapCredentialService, + BootstrapCredentialServiceShape +>()("t3/auth/Services/BootstrapCredentialService") {} diff --git a/apps/server/src/auth/Services/ServerAuth.ts b/apps/server/src/auth/Services/ServerAuth.ts new file mode 100644 index 0000000000..0e38679b85 --- /dev/null +++ b/apps/server/src/auth/Services/ServerAuth.ts @@ -0,0 +1,84 @@ +import type { + AuthBearerBootstrapResult, + AuthBootstrapResult, + AuthClientMetadata, + AuthClientSession, + AuthCreatePairingCredentialInput, + AuthPairingLink, + AuthPairingCredentialResult, + AuthSessionId, + AuthSessionState, + ServerAuthDescriptor, + ServerAuthSessionMethod, + AuthWebSocketTokenResult, +} from "@t3tools/contracts"; +import { Data, DateTime, ServiceMap } from "effect"; +import type { Effect } from "effect"; +import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; +import type { SessionRole } from "./SessionCredentialService.ts"; + +export interface AuthenticatedSession { + readonly sessionId: AuthSessionId; + readonly subject: string; + readonly method: ServerAuthSessionMethod; + readonly role: SessionRole; + readonly expiresAt?: DateTime.DateTime; +} + +export class AuthError extends Data.TaggedError("AuthError")<{ + readonly message: string; + readonly status?: 400 | 401 | 403 | 500; + readonly cause?: unknown; +}> {} + +export interface ServerAuthShape { + readonly getDescriptor: () => Effect.Effect; + readonly getSessionState: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly exchangeBootstrapCredential: ( + credential: string, + requestMetadata: AuthClientMetadata, + ) => Effect.Effect< + { + readonly response: AuthBootstrapResult; + readonly sessionToken: string; + }, + AuthError + >; + readonly exchangeBootstrapCredentialForBearerSession: ( + credential: string, + requestMetadata: AuthClientMetadata, + ) => Effect.Effect; + readonly issuePairingCredential: ( + input?: AuthCreatePairingCredentialInput & { + readonly role?: SessionRole; + }, + ) => Effect.Effect; + readonly listPairingLinks: () => Effect.Effect, AuthError>; + readonly revokePairingLink: (id: string) => Effect.Effect; + readonly listClientSessions: ( + currentSessionId: AuthSessionId, + ) => Effect.Effect, AuthError>; + readonly revokeClientSession: ( + currentSessionId: AuthSessionId, + targetSessionId: AuthSessionId, + ) => Effect.Effect; + readonly revokeOtherClientSessions: ( + currentSessionId: AuthSessionId, + ) => Effect.Effect; + readonly authenticateHttpRequest: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly authenticateWebSocketUpgrade: ( + request: HttpServerRequest.HttpServerRequest, + ) => Effect.Effect; + readonly issueWebSocketToken: ( + session: AuthenticatedSession, + ) => Effect.Effect; + readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect; +} + +export class ServerAuth extends ServiceMap.Service()( + "t3/auth/Services/ServerAuth", +) {} diff --git a/apps/server/src/auth/Services/ServerAuthPolicy.ts b/apps/server/src/auth/Services/ServerAuthPolicy.ts new file mode 100644 index 0000000000..43dae6ca69 --- /dev/null +++ b/apps/server/src/auth/Services/ServerAuthPolicy.ts @@ -0,0 +1,11 @@ +import type { ServerAuthDescriptor } from "@t3tools/contracts"; +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export interface ServerAuthPolicyShape { + readonly getDescriptor: () => Effect.Effect; +} + +export class ServerAuthPolicy extends ServiceMap.Service()( + "t3/auth/Services/ServerAuthPolicy", +) {} diff --git a/apps/server/src/auth/Services/ServerSecretStore.ts b/apps/server/src/auth/Services/ServerSecretStore.ts new file mode 100644 index 0000000000..376527aea3 --- /dev/null +++ b/apps/server/src/auth/Services/ServerSecretStore.ts @@ -0,0 +1,22 @@ +import { Data, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface ServerSecretStoreShape { + readonly get: (name: string) => Effect.Effect; + readonly set: (name: string, value: Uint8Array) => Effect.Effect; + readonly getOrCreateRandom: ( + name: string, + bytes: number, + ) => Effect.Effect; + readonly remove: (name: string) => Effect.Effect; +} + +export class ServerSecretStore extends ServiceMap.Service< + ServerSecretStore, + ServerSecretStoreShape +>()("t3/auth/Services/ServerSecretStore") {} diff --git a/apps/server/src/auth/Services/SessionCredentialService.ts b/apps/server/src/auth/Services/SessionCredentialService.ts new file mode 100644 index 0000000000..591504766e --- /dev/null +++ b/apps/server/src/auth/Services/SessionCredentialService.ts @@ -0,0 +1,87 @@ +import type { + AuthClientMetadata, + AuthClientSession, + AuthSessionId, + ServerAuthSessionMethod, +} from "@t3tools/contracts"; +import { Data, DateTime, Duration, ServiceMap } from "effect"; +import type { Effect, Stream } from "effect"; + +export type SessionRole = "owner" | "client"; + +export interface IssuedSession { + readonly sessionId: AuthSessionId; + readonly token: string; + readonly method: ServerAuthSessionMethod; + readonly client: AuthClientMetadata; + readonly expiresAt: DateTime.DateTime; + readonly role: SessionRole; +} + +export interface VerifiedSession { + readonly sessionId: AuthSessionId; + readonly token: string; + readonly method: ServerAuthSessionMethod; + readonly client: AuthClientMetadata; + readonly expiresAt?: DateTime.DateTime; + readonly subject: string; + readonly role: SessionRole; +} + +export type SessionCredentialChange = + | { + readonly type: "clientUpserted"; + readonly clientSession: AuthClientSession; + } + | { + readonly type: "clientRemoved"; + readonly sessionId: AuthSessionId; + }; + +export class SessionCredentialError extends Data.TaggedError("SessionCredentialError")<{ + readonly message: string; + readonly cause?: unknown; +}> {} + +export interface SessionCredentialServiceShape { + readonly cookieName: string; + readonly issue: (input?: { + readonly ttl?: Duration.Duration; + readonly subject?: string; + readonly method?: ServerAuthSessionMethod; + readonly role?: SessionRole; + readonly client?: AuthClientMetadata; + }) => Effect.Effect; + readonly verify: (token: string) => Effect.Effect; + readonly issueWebSocketToken: ( + sessionId: AuthSessionId, + input?: { + readonly ttl?: Duration.Duration; + }, + ) => Effect.Effect< + { + readonly token: string; + readonly expiresAt: DateTime.DateTime; + }, + SessionCredentialError + >; + readonly verifyWebSocketToken: ( + token: string, + ) => Effect.Effect; + readonly listActive: () => Effect.Effect< + ReadonlyArray, + SessionCredentialError + >; + readonly streamChanges: Stream.Stream; + readonly revoke: (sessionId: AuthSessionId) => Effect.Effect; + readonly revokeAllExcept: ( + sessionId: AuthSessionId, + ) => Effect.Effect; + readonly markConnected: (sessionId: AuthSessionId) => Effect.Effect; + readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect; +} + +export class SessionCredentialService extends ServiceMap.Service< + SessionCredentialService, + SessionCredentialServiceShape +>()("t3/auth/Services/SessionCredentialService") {} diff --git a/apps/server/src/auth/http.ts b/apps/server/src/auth/http.ts new file mode 100644 index 0000000000..76c14646e9 --- /dev/null +++ b/apps/server/src/auth/http.ts @@ -0,0 +1,254 @@ +import { + type AuthBearerBootstrapResult, + AuthBootstrapInput, + AuthCreatePairingCredentialInput, + AuthRevokeClientSessionInput, + AuthRevokePairingLinkInput, + type AuthWebSocketTokenResult, +} from "@t3tools/contracts"; +import { DateTime, Effect, Schema } from "effect"; +import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; + +import { AuthError, ServerAuth } from "./Services/ServerAuth.ts"; +import { SessionCredentialService } from "./Services/SessionCredentialService.ts"; +import { deriveAuthClientMetadata } from "./utils.ts"; + +export const respondToAuthError = (error: AuthError) => + Effect.gen(function* () { + if ((error.status ?? 500) >= 500) { + yield* Effect.logError("auth route failed", { + message: error.message, + cause: error.cause, + }); + } + return HttpServerResponse.jsonUnsafe( + { + error: error.message, + }, + { status: error.status ?? 500 }, + ); + }); + +export const authSessionRouteLayer = HttpRouter.add( + "GET", + "/api/auth/session", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.getSessionState(request); + return HttpServerResponse.jsonUnsafe(session, { status: 200 }); + }), +); + +const PairingCredentialRequestHeaders = Schema.Struct({ + "content-length": Schema.optionalKey(Schema.String), + "content-type": Schema.optionalKey(Schema.String), + "transfer-encoding": Schema.optionalKey(Schema.String), +}); + +function hasRequestBody(headers: typeof PairingCredentialRequestHeaders.Type) { + const contentLengthHeader = headers["content-length"]; + if (typeof contentLengthHeader === "string") { + const contentLength = Number.parseInt(contentLengthHeader, 10); + if (Number.isFinite(contentLength)) { + return contentLength > 0; + } + } + return typeof headers["transfer-encoding"] === "string"; +} + +export const authBootstrapRouteLayer = HttpRouter.add( + "POST", + "/api/auth/bootstrap", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const sessions = yield* SessionCredentialService; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid bootstrap payload.", + status: 400, + cause, + }), + ), + ); + const result = yield* serverAuth.exchangeBootstrapCredential( + payload.credential, + deriveAuthClientMetadata({ request }), + ); + + return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe( + HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, { + expires: DateTime.toDate(result.response.expiresAt), + httpOnly: true, + path: "/", + sameSite: "lax", + }), + ); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authBearerBootstrapRouteLayer = HttpRouter.add( + "POST", + "/api/auth/bootstrap/bearer", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthBootstrapInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid bootstrap payload.", + status: 400, + cause, + }), + ), + ); + const result = yield* serverAuth.exchangeBootstrapCredentialForBearerSession( + payload.credential, + deriveAuthClientMetadata({ request }), + ); + return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, { + status: 200, + }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authWebSocketTokenRouteLayer = HttpRouter.add( + "POST", + "/api/auth/ws-token", + Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.authenticateHttpRequest(request); + const result = yield* serverAuth.issueWebSocketToken(session); + return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, { + status: 200, + }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authPairingCredentialRouteLayer = HttpRouter.add( + "POST", + "/api/auth/pairing-token", + Effect.gen(function* () { + const serverAuth = yield* ServerAuth; + const request = yield* HttpServerRequest.HttpServerRequest; + const session = yield* serverAuth.authenticateHttpRequest(request); + if (session.role !== "owner") { + return yield* new AuthError({ + message: "Only owner sessions can create pairing credentials.", + status: 403, + }); + } + const headers = yield* HttpServerRequest.schemaHeaders(PairingCredentialRequestHeaders).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid pairing credential request headers.", + status: 400, + cause, + }), + ), + ); + const payload = hasRequestBody(headers) + ? yield* HttpServerRequest.schemaBodyJson(AuthCreatePairingCredentialInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid pairing credential payload.", + status: 400, + cause, + }), + ), + ) + : {}; + const result = yield* serverAuth.issuePairingCredential(payload); + return HttpServerResponse.jsonUnsafe(result, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +const authenticateOwnerSession = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + const session = yield* serverAuth.authenticateHttpRequest(request); + if (session.role !== "owner") { + return yield* new AuthError({ + message: "Only owner sessions can manage network access.", + status: 403, + }); + } + return { serverAuth, session } as const; +}); + +export const authPairingLinksRouteLayer = HttpRouter.add( + "GET", + "/api/auth/pairing-links", + Effect.gen(function* () { + const { serverAuth } = yield* authenticateOwnerSession; + const pairingLinks = yield* serverAuth.listPairingLinks(); + return HttpServerResponse.jsonUnsafe(pairingLinks, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authPairingLinksRevokeRouteLayer = HttpRouter.add( + "POST", + "/api/auth/pairing-links/revoke", + Effect.gen(function* () { + const { serverAuth } = yield* authenticateOwnerSession; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokePairingLinkInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid revoke pairing link payload.", + status: 400, + cause, + }), + ), + ); + const revoked = yield* serverAuth.revokePairingLink(payload.id); + return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authClientsRouteLayer = HttpRouter.add( + "GET", + "/api/auth/clients", + Effect.gen(function* () { + const { serverAuth, session } = yield* authenticateOwnerSession; + const clients = yield* serverAuth.listClientSessions(session.sessionId); + return HttpServerResponse.jsonUnsafe(clients, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authClientsRevokeRouteLayer = HttpRouter.add( + "POST", + "/api/auth/clients/revoke", + Effect.gen(function* () { + const { serverAuth, session } = yield* authenticateOwnerSession; + const payload = yield* HttpServerRequest.schemaBodyJson(AuthRevokeClientSessionInput).pipe( + Effect.mapError( + (cause) => + new AuthError({ + message: "Invalid revoke client payload.", + status: 400, + cause, + }), + ), + ); + const revoked = yield* serverAuth.revokeClientSession(session.sessionId, payload.sessionId); + return HttpServerResponse.jsonUnsafe({ revoked }, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); + +export const authClientsRevokeOthersRouteLayer = HttpRouter.add( + "POST", + "/api/auth/clients/revoke-others", + Effect.gen(function* () { + const { serverAuth, session } = yield* authenticateOwnerSession; + const revokedCount = yield* serverAuth.revokeOtherClientSessions(session.sessionId); + return HttpServerResponse.jsonUnsafe({ revokedCount }, { status: 200 }); + }).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))), +); diff --git a/apps/server/src/auth/utils.test.ts b/apps/server/src/auth/utils.test.ts new file mode 100644 index 0000000000..a767b77de1 --- /dev/null +++ b/apps/server/src/auth/utils.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; + +import { deriveAuthClientMetadata } from "./utils"; + +describe("deriveAuthClientMetadata", () => { + it("labels Electron user agents as Electron instead of Chrome", () => { + const metadata = deriveAuthClientMetadata({ + request: { + headers: { + "user-agent": + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) t3code/0.0.15 Chrome/136.0.7103.93 Electron/36.3.2 Safari/537.36", + }, + source: { + remoteAddress: "::ffff:127.0.0.1", + }, + } as never, + }); + + expect(metadata).toMatchObject({ + browser: "Electron", + deviceType: "desktop", + ipAddress: "127.0.0.1", + os: "macOS", + }); + }); +}); diff --git a/apps/server/src/auth/utils.ts b/apps/server/src/auth/utils.ts new file mode 100644 index 0000000000..e87c66c6b9 --- /dev/null +++ b/apps/server/src/auth/utils.ts @@ -0,0 +1,121 @@ +import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/contracts"; +import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest"; +import * as Crypto from "node:crypto"; + +export const SESSION_COOKIE_NAME = "t3_session"; + +export function base64UrlEncode(input: string | Uint8Array): string { + const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input); + return buffer.toString("base64url"); +} + +export function base64UrlDecodeUtf8(input: string): string { + return Buffer.from(input, "base64url").toString("utf8"); +} + +export function signPayload(payload: string, secret: Uint8Array): string { + return Crypto.createHmac("sha256", Buffer.from(secret)).update(payload).digest("base64url"); +} + +export function timingSafeEqualBase64Url(left: string, right: string): boolean { + const leftBuffer = Buffer.from(left, "base64url"); + const rightBuffer = Buffer.from(right, "base64url"); + if (leftBuffer.length !== rightBuffer.length) { + return false; + } + return Crypto.timingSafeEqual(leftBuffer, rightBuffer); +} + +function normalizeNonEmptyString(value: string | null | undefined): string | undefined { + if (typeof value !== "string") { + return undefined; + } + const trimmed = value.trim(); + return trimmed.length > 0 ? trimmed : undefined; +} + +function normalizeIpAddress(value: string | null | undefined): string | undefined { + const normalized = normalizeNonEmptyString(value); + if (!normalized) { + return undefined; + } + return normalized.startsWith("::ffff:") ? normalized.slice("::ffff:".length) : normalized; +} + +function inferDeviceType(userAgent: string | undefined): AuthClientMetadataDeviceType { + if (!userAgent) { + return "unknown"; + } + + const normalized = userAgent.toLowerCase(); + if (/bot|crawler|spider|slurp|curl|wget/.test(normalized)) { + return "bot"; + } + if (/ipad|tablet/.test(normalized)) { + return "tablet"; + } + if (/iphone|android.+mobile|mobile/.test(normalized)) { + return "mobile"; + } + return "desktop"; +} + +function inferBrowser(userAgent: string | undefined): string | undefined { + if (!userAgent) { + return undefined; + } + const normalized = userAgent.toLowerCase(); + if (/edg\//.test(normalized)) return "Edge"; + if (/opr\//.test(normalized)) return "Opera"; + if (/firefox\//.test(normalized)) return "Firefox"; + if (/electron\//.test(normalized)) return "Electron"; + if (/chrome\//.test(normalized) || /crios\//.test(normalized)) return "Chrome"; + if (/safari\//.test(normalized) && !/chrome\//.test(normalized)) return "Safari"; + return undefined; +} + +function inferOs(userAgent: string | undefined): string | undefined { + if (!userAgent) { + return undefined; + } + const normalized = userAgent.toLowerCase(); + if (/iphone|ipad|ipod/.test(normalized)) return "iOS"; + if (/android/.test(normalized)) return "Android"; + if (/mac os x|macintosh/.test(normalized)) return "macOS"; + if (/windows nt/.test(normalized)) return "Windows"; + if (/linux/.test(normalized)) return "Linux"; + return undefined; +} + +function readRemoteAddressFromSource(source: unknown): string | undefined { + if (!source || typeof source !== "object") { + return undefined; + } + + const candidate = source as { + readonly remoteAddress?: string | null; + readonly socket?: { + readonly remoteAddress?: string | null; + }; + }; + + return normalizeIpAddress(candidate.socket?.remoteAddress ?? candidate.remoteAddress); +} + +export function deriveAuthClientMetadata(input: { + readonly request: HttpServerRequest.HttpServerRequest; + readonly label?: string; +}): AuthClientMetadata { + const userAgent = normalizeNonEmptyString(input.request.headers["user-agent"]); + const ipAddress = readRemoteAddressFromSource(input.request.source); + const os = inferOs(userAgent); + const browser = inferBrowser(userAgent); + return { + ...(input.label ? { label: input.label } : {}), + ...(ipAddress ? { ipAddress } : {}), + ...(userAgent ? { userAgent } : {}), + deviceType: inferDeviceType(userAgent), + ...(os ? { os } : {}), + ...(browser ? { browser } : {}), + }; +} diff --git a/apps/server/src/cli-config.test.ts b/apps/server/src/cli-config.test.ts index ef2f9f55d8..6dd48c5d25 100644 --- a/apps/server/src/cli-config.test.ts +++ b/apps/server/src/cli-config.test.ts @@ -43,7 +43,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { cwd: Option.none(), devUrl: Option.none(), noBrowser: Option.none(), - authToken: Option.none(), bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), @@ -62,7 +61,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { T3CODE_HOME: baseDir, VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", T3CODE_NO_BROWSER: "true", - T3CODE_AUTH_TOKEN: "env-token", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", T3CODE_LOG_WS_EVENTS: "true", }, @@ -85,7 +83,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { staticDir: undefined, devUrl: new URL("http://127.0.0.1:5173"), noBrowser: true, - authToken: "env-token", + desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, }); @@ -106,7 +104,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { cwd: Option.none(), devUrl: Option.some(new URL("http://127.0.0.1:4173")), noBrowser: Option.some(true), - authToken: Option.some("flag-token"), bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.some(true), logWebSocketEvents: Option.some(true), @@ -125,7 +122,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { T3CODE_HOME: join(os.tmpdir(), "ignored-base"), VITE_DEV_SERVER_URL: "http://127.0.0.1:5173", T3CODE_NO_BROWSER: "false", - T3CODE_AUTH_TOKEN: "ignored-token", T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false", T3CODE_LOG_WS_EVENTS: "false", }, @@ -148,7 +144,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { staticDir: undefined, devUrl: new URL("http://127.0.0.1:4173"), noBrowser: true, - authToken: "flag-token", + desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: true, logWebSocketEvents: true, }); @@ -166,7 +162,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { t3Home: baseDir, devUrl: "http://127.0.0.1:5173", noBrowser: true, - authToken: "bootstrap-token", autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, otlpTracesUrl: "http://localhost:4318/v1/traces", @@ -183,7 +178,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { cwd: Option.none(), devUrl: Option.none(), noBrowser: Option.none(), - authToken: Option.none(), bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), @@ -218,7 +212,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { staticDir: undefined, devUrl: new URL("http://127.0.0.1:5173"), noBrowser: true, - authToken: "bootstrap-token", + desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: true, }); @@ -242,7 +236,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { cwd: Option.some(customCwd), devUrl: Option.some(new URL("http://127.0.0.1:5173")), noBrowser: Option.none(), - authToken: Option.none(), bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), @@ -285,7 +278,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { t3Home: "/tmp/t3-bootstrap-home", devUrl: "http://127.0.0.1:5173", noBrowser: false, - authToken: "bootstrap-token", autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, }); @@ -300,7 +292,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { cwd: Option.none(), devUrl: Option.some(new URL("http://127.0.0.1:4173")), noBrowser: Option.none(), - authToken: Option.some("flag-token"), bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), @@ -338,7 +329,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { staticDir: undefined, devUrl: new URL("http://127.0.0.1:4173"), noBrowser: true, - authToken: "flag-token", + desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: true, logWebSocketEvents: true, }); @@ -371,7 +362,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { cwd: Option.none(), devUrl: Option.none(), noBrowser: Option.none(), - authToken: Option.none(), bootstrapFd: Option.none(), autoBootstrapProjectFromCwd: Option.none(), logWebSocketEvents: Option.none(), @@ -402,7 +392,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => { staticDir: resolved.staticDir, devUrl: undefined, noBrowser: true, - authToken: undefined, + desktopBootstrapToken: undefined, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, }); diff --git a/apps/server/src/cli.test.ts b/apps/server/src/cli.test.ts index fbbe26e6cf..4840fecc9a 100644 --- a/apps/server/src/cli.test.ts +++ b/apps/server/src/cli.test.ts @@ -1,28 +1,41 @@ +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + import * as NodeServices from "@effect/platform-node/NodeServices"; import { NetService } from "@t3tools/shared/Net"; import { assert, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as CliError from "effect/unstable/cli/CliError"; +import * as TestConsole from "effect/testing/TestConsole"; import { Command } from "effect/unstable/cli"; import { cli } from "./cli.ts"; const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer); +const runCli = (args: ReadonlyArray) => Command.runWith(cli, { version: "0.0.0" })(args); +const runCliWithRuntime = (args: ReadonlyArray) => + runCli(args).pipe(Effect.provide(CliRuntimeLayer)); + +const captureStdout = (effect: Effect.Effect) => + Effect.gen(function* () { + const result = yield* effect; + const output = + (yield* TestConsole.logLines).findLast((line): line is string => typeof line === "string") ?? + ""; + return { result, output }; + }).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))); + it.layer(NodeServices.layer)("cli log-level parsing", (it) => { it.effect("accepts the built-in lowercase log-level flag values", () => - Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe( - Effect.provide(CliRuntimeLayer), - ), + runCliWithRuntime(["--log-level", "debug", "--version"]), ); it.effect("rejects invalid log-level casing before launching the server", () => Effect.gen(function* () { - const error = yield* Command.runWith(cli, { version: "0.0.0" })([ - "--log-level", - "Debug", - ]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip); + const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip); if (!CliError.isCliError(error)) { assert.fail(`Expected CliError, got ${String(error)}`); @@ -34,4 +47,87 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => { assert.equal(error.value, "Debug"); }), ); + + it.effect("executes auth pairing subcommands and redacts secrets from list output", () => + Effect.gen(function* () { + const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-pairing-test-")); + + const createdOutput = yield* captureStdout( + runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]), + ); + const created = JSON.parse(createdOutput.output) as { + readonly id: string; + readonly credential: string; + }; + const listedOutput = yield* captureStdout( + runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]), + ); + const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{ + readonly id: string; + readonly credential?: string; + }>; + + assert.equal(typeof created.id, "string"); + assert.equal(typeof created.credential, "string"); + assert.equal(created.credential.length > 0, true); + assert.equal(listed.length, 1); + assert.equal(listed[0]?.id, created.id); + assert.equal("credential" in (listed[0] ?? {}), false); + }), + ); + + it.effect("executes auth session subcommands and redacts secrets from list output", () => + Effect.gen(function* () { + const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-auth-session-test-")); + + const issuedOutput = yield* captureStdout( + runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]), + ); + const issued = JSON.parse(issuedOutput.output) as { + readonly sessionId: string; + readonly token: string; + readonly role: string; + }; + const listedOutput = yield* captureStdout( + runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]), + ); + const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{ + readonly sessionId: string; + readonly token?: string; + readonly role: string; + }>; + + assert.equal(typeof issued.sessionId, "string"); + assert.equal(typeof issued.token, "string"); + assert.equal(issued.role, "owner"); + assert.equal(listed.length, 1); + assert.equal(listed[0]?.sessionId, issued.sessionId); + assert.equal(listed[0]?.role, "owner"); + assert.equal("token" in (listed[0] ?? {}), false); + }), + ); + + it.effect("rejects invalid ttl values before running auth commands", () => + Effect.gen(function* () { + const error = yield* runCliWithRuntime(["auth", "pairing", "create", "--ttl", "soon"]).pipe( + Effect.flip, + ); + + if (!CliError.isCliError(error)) { + assert.fail(`Expected CliError, got ${String(error)}`); + } + if (error._tag !== "ShowHelp") { + assert.fail(`Expected ShowHelp, got ${error._tag}`); + } + assert.deepEqual(error.commandPath, ["t3", "auth", "pairing", "create"]); + const ttlError = error.errors[0] as CliError.CliError | undefined; + if (!ttlError || ttlError._tag !== "InvalidValue") { + assert.fail(`Expected InvalidValue, got ${String(ttlError?._tag)}`); + } + assert.equal(ttlError.option, "ttl"); + assert.equal(ttlError.value, "soon"); + assert.isTrue(ttlError.message.includes("Invalid duration")); + assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes")); + }), + ); }); diff --git a/apps/server/src/cli.ts b/apps/server/src/cli.ts index 9ece02a0d3..01fd300542 100644 --- a/apps/server/src/cli.ts +++ b/apps/server/src/cli.ts @@ -1,6 +1,20 @@ import { NetService } from "@t3tools/shared/Net"; import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings"; -import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect"; +import { AuthSessionId } from "@t3tools/contracts"; +import { + Config, + Console, + Duration, + Effect, + FileSystem, + LogLevel, + Option, + Path, + References, + Schema, + SchemaIssue, + SchemaTransformation, +} from "effect"; import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli"; import { @@ -15,6 +29,14 @@ import { import { readBootstrapEnvelope } from "./bootstrap"; import { expandHomePath, resolveBaseDir } from "./os-jank"; import { runServer } from "./server"; +import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts"; +import { + formatIssuedPairingCredential, + formatIssuedSession, + formatPairingCredentialList, + formatSessionList, +} from "./cliAuthFormat"; +import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts"; const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })); @@ -25,7 +47,7 @@ const BootstrapEnvelopeSchema = Schema.Struct({ t3Home: Schema.optional(Schema.String), devUrl: Schema.optional(Schema.URLFromString), noBrowser: Schema.optional(Schema.Boolean), - authToken: Schema.optional(Schema.String), + desktopBootstrapToken: Schema.optional(Schema.String), autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean), logWebSocketEvents: Schema.optional(Schema.Boolean), otlpTracesUrl: Schema.optional(Schema.String), @@ -58,11 +80,6 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe( Flag.withDescription("Disable automatic browser opening."), Flag.optional, ); -const authTokenFlag = Flag.string("auth-token").pipe( - Flag.withDescription("Auth token required for WebSocket connections."), - Flag.withAlias("token"), - Flag.optional, -); const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe( Flag.withSchema(Schema.Int), Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."), @@ -117,10 +134,6 @@ const EnvServerConfig = Config.all({ Config.option, Config.map(Option.getOrUndefined), ), - authToken: Config.string("T3CODE_AUTH_TOKEN").pipe( - Config.option, - Config.map(Option.getOrUndefined), - ), bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe( Config.option, Config.map(Option.getOrUndefined), @@ -143,12 +156,16 @@ interface CliServerFlags { readonly cwd: Option.Option; readonly devUrl: Option.Option; readonly noBrowser: Option.Option; - readonly authToken: Option.Option; readonly bootstrapFd: Option.Option; readonly autoBootstrapProjectFromCwd: Option.Option; readonly logWebSocketEvents: Option.Option; } +interface CliAuthLocationFlags { + readonly baseDir: Option.Option; + readonly devUrl: Option.Option; +} + const resolveBooleanFlag = (flag: Option.Option, envValue: boolean) => Option.getOrElse(Option.filter(flag, Boolean), () => envValue); @@ -248,13 +265,9 @@ export const resolveServerConfig = ( () => mode === "desktop", ), ); - const authToken = Option.getOrUndefined( - resolveOptionPrecedence( - flags.authToken, - Option.fromUndefinedOr(env.authToken), - Option.flatMap(bootstrapEnvelope, (bootstrap) => - Option.fromUndefinedOr(bootstrap.authToken), - ), + const desktopBootstrapToken = Option.getOrUndefined( + Option.flatMap(bootstrapEnvelope, (bootstrap) => + Option.fromUndefinedOr(bootstrap.desktopBootstrapToken), ), ); const autoBootstrapProjectFromCwd = resolveBooleanFlag( @@ -327,7 +340,7 @@ export const resolveServerConfig = ( staticDir, devUrl, noBrowser, - authToken, + desktopBootstrapToken, autoBootstrapProjectFromCwd, logWebSocketEvents, }; @@ -335,6 +348,110 @@ export const resolveServerConfig = ( return config; }); +const resolveCliAuthConfig = ( + flags: CliAuthLocationFlags, + cliLogLevel: Option.Option, +) => + resolveServerConfig( + { + mode: Option.none(), + port: Option.none(), + host: Option.none(), + baseDir: flags.baseDir, + cwd: Option.none(), + devUrl: flags.devUrl, + noBrowser: Option.none(), + bootstrapFd: Option.none(), + autoBootstrapProjectFromCwd: Option.none(), + logWebSocketEvents: Option.none(), + }, + cliLogLevel, + ); + +const DurationShorthandPattern = /^(?\d+)(?ms|s|m|h|d|w)$/i; + +const parseDurationInput = (value: string): Duration.Duration | null => { + const trimmed = value.trim(); + if (trimmed.length === 0) return null; + + const shorthand = DurationShorthandPattern.exec(trimmed); + const normalizedInput = shorthand?.groups + ? (() => { + const amountText = shorthand.groups.value; + const unitText = shorthand.groups.unit; + if (typeof amountText !== "string" || typeof unitText !== "string") { + return null; + } + + const amount = Number.parseInt(amountText, 10); + if (!Number.isFinite(amount)) return null; + + switch (unitText.toLowerCase()) { + case "ms": + return `${amount} millis`; + case "s": + return `${amount} seconds`; + case "m": + return `${amount} minutes`; + case "h": + return `${amount} hours`; + case "d": + return `${amount} days`; + case "w": + return `${amount} weeks`; + default: + return null; + } + })() + : (trimmed as Duration.Input); + + if (normalizedInput === null) return null; + + const decoded = Duration.fromInput(normalizedInput as Duration.Input); + return Option.isSome(decoded) ? decoded.value : null; +}; + +const DurationFromString = Schema.String.pipe( + Schema.decodeTo( + Schema.Duration, + SchemaTransformation.transformOrFail({ + decode: (value) => { + const duration = parseDurationInput(value); + if (duration !== null) { + return Effect.succeed(duration); + } + return Effect.fail( + new SchemaIssue.InvalidValue(Option.some(value), { + message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.", + }), + ); + }, + encode: (duration) => Effect.succeed(Duration.format(duration)), + }), + ), +); + +const runWithAuthControlPlane = ( + flags: CliAuthLocationFlags, + run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect, + options?: { + readonly quietLogs?: boolean; + }, +) => + Effect.gen(function* () { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveCliAuthConfig(flags, logLevel); + const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel; + return yield* Effect.gen(function* () { + const authControlPlane = yield* AuthControlPlane; + return yield* run(authControlPlane); + }).pipe( + Effect.provide(AuthControlPlaneRuntimeLive), + Effect.provideService(ServerConfig, config), + Effect.provideService(References.MinimumLogLevel, minimumLogLevel), + ); + }); + const commandFlags = { mode: modeFlag, port: portFlag, @@ -348,13 +465,216 @@ const commandFlags = { ), devUrl: devUrlFlag, noBrowser: noBrowserFlag, - authToken: authTokenFlag, bootstrapFd: bootstrapFdFlag, autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag, logWebSocketEvents: logWebSocketEventsFlag, } as const; -const rootCommand = Command.make("t3", commandFlags).pipe( +const authLocationFlags = { + baseDir: baseDirFlag, + devUrl: devUrlFlag, +} as const; + +const ttlFlag = Flag.string("ttl").pipe( + Flag.withSchema(DurationFromString), + Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."), + Flag.optional, +); + +const jsonFlag = Flag.boolean("json").pipe( + Flag.withDescription("Emit JSON instead of human-readable output."), + Flag.withDefault(false), +); + +const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe( + Flag.withDescription("Role for the issued bearer session."), + Flag.withDefault("owner"), +); + +const labelFlag = Flag.string("label").pipe( + Flag.withDescription("Optional human-readable label."), + Flag.optional, +); + +const subjectFlag = Flag.string("subject").pipe( + Flag.withDescription("Optional session subject."), + Flag.optional, +); + +const baseUrlFlag = Flag.string("base-url").pipe( + Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."), + Flag.optional, +); + +const tokenOnlyFlag = Flag.boolean("token-only").pipe( + Flag.withDescription("Print only the issued bearer token."), + Flag.withDefault(false), +); + +const pairingCreateCommand = Command.make("create", { + ...authLocationFlags, + ttl: ttlFlag, + label: labelFlag, + baseUrl: baseUrlFlag, + json: jsonFlag, +}).pipe( + Command.withDescription("Issue a new client pairing token."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const issued = yield* authControlPlane.createPairingLink({ + role: "client", + subject: "one-time-token", + ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), + ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}), + }); + const output = formatIssuedPairingCredential(issued, { + json: flags.json, + ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}), + }); + yield* Console.log(output); + }), + { + quietLogs: flags.json, + }, + ), + ), +); + +const pairingListCommand = Command.make("list", { + ...authLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription("List active client pairing tokens without revealing their secrets."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" }); + yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json })); + }), + { + quietLogs: flags.json, + }, + ), + ), +); + +const pairingRevokeCommand = Command.make("revoke", { + ...authLocationFlags, + id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")), +}).pipe( + Command.withDescription("Revoke an active client pairing token."), + Command.withHandler((flags) => + runWithAuthControlPlane(flags, (authControlPlane) => + Effect.gen(function* () { + const revoked = yield* authControlPlane.revokePairingLink(flags.id); + yield* Console.log( + revoked + ? `Revoked pairing credential ${flags.id}.\n` + : `No active pairing credential found for ${flags.id}.\n`, + ); + }), + ), + ), +); + +const pairingCommand = Command.make("pairing").pipe( + Command.withDescription("Manage one-time client pairing tokens."), + Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]), +); + +const sessionIssueCommand = Command.make("issue", { + ...authLocationFlags, + ttl: ttlFlag, + role: sessionRoleFlag, + label: labelFlag, + subject: subjectFlag, + tokenOnly: tokenOnlyFlag, + json: jsonFlag, +}).pipe( + Command.withDescription("Issue a bearer session token for headless or remote clients."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const issued = yield* authControlPlane.issueSession({ + role: flags.role, + ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}), + ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}), + ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}), + }); + yield* Console.log( + formatIssuedSession(issued, { + json: flags.json, + tokenOnly: flags.tokenOnly, + }), + ); + }), + { + quietLogs: flags.json || flags.tokenOnly, + }, + ), + ), +); + +const sessionListCommand = Command.make("list", { + ...authLocationFlags, + json: jsonFlag, +}).pipe( + Command.withDescription("List active sessions without revealing bearer tokens."), + Command.withHandler((flags) => + runWithAuthControlPlane( + flags, + (authControlPlane) => + Effect.gen(function* () { + const sessions = yield* authControlPlane.listSessions(); + yield* Console.log(formatSessionList(sessions, { json: flags.json })); + }), + { + quietLogs: flags.json, + }, + ), + ), +); + +const sessionRevokeCommand = Command.make("revoke", { + ...authLocationFlags, + sessionId: Argument.string("session-id").pipe( + Argument.withDescription("Session id to revoke."), + Argument.withSchema(AuthSessionId), + ), +}).pipe( + Command.withDescription("Revoke an active session."), + Command.withHandler((flags) => + runWithAuthControlPlane(flags, (authControlPlane) => + Effect.gen(function* () { + const revoked = yield* authControlPlane.revokeSession(flags.sessionId); + yield* Console.log( + revoked + ? `Revoked session ${flags.sessionId}.\n` + : `No active session found for ${flags.sessionId}.\n`, + ); + }), + ), + ), +); + +const sessionCommand = Command.make("session").pipe( + Command.withDescription("Manage bearer sessions."), + Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]), +); + +const authCommand = Command.make("auth").pipe( + Command.withDescription("Manage the local auth control plane for headless deployments."), + Command.withSubcommands([pairingCommand, sessionCommand]), +); + +const startCommand = Command.make("start", commandFlags).pipe( Command.withDescription("Run the T3 Code server."), Command.withHandler((flags) => Effect.gen(function* () { @@ -365,4 +685,14 @@ const rootCommand = Command.make("t3", commandFlags).pipe( ), ); -export const cli = rootCommand; +export const cli = Command.make("t3", commandFlags).pipe( + Command.withDescription("Run the T3 Code server."), + Command.withHandler((flags) => + Effect.gen(function* () { + const logLevel = yield* GlobalFlag.LogLevel; + const config = yield* resolveServerConfig(flags, logLevel); + return yield* runServer.pipe(Effect.provideService(ServerConfig, config)); + }), + ), + Command.withSubcommands([startCommand, authCommand]), +); diff --git a/apps/server/src/cliAuthFormat.test.ts b/apps/server/src/cliAuthFormat.test.ts new file mode 100644 index 0000000000..017ced97e8 --- /dev/null +++ b/apps/server/src/cliAuthFormat.test.ts @@ -0,0 +1,88 @@ +import { expect, it } from "@effect/vitest"; +import { DateTime } from "effect"; + +import { + formatIssuedPairingCredential, + formatIssuedSession, + formatPairingCredentialList, + formatSessionList, +} from "./cliAuthFormat.ts"; + +it("formats issued pairing credentials with the secret and optional pair URL", () => { + const output = formatIssuedPairingCredential( + { + id: "pairing-1", + credential: "secret-pairing-token", + role: "client", + subject: "one-time-token", + createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")), + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + }, + { baseUrl: "https://example.com", json: false }, + ); + + expect(output).toContain("secret-pairing-token"); + expect(output).toContain("https://example.com/pair#token=secret-pairing-token"); +}); + +it("formats pairing listings without exposing the secret token", () => { + const output = formatPairingCredentialList( + [ + { + id: "pairing-1", + credential: "secret-pairing-token", + subject: "one-time-token", + label: "Phone", + role: "client", + createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")), + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + }, + ], + { json: false }, + ); + + expect(output).toContain("pairing-1"); + expect(output).not.toContain("secret-pairing-token"); +}); + +it("formats issued sessions with the bearer token but omits tokens from listings", () => { + const issuedOutput = formatIssuedSession( + { + sessionId: "session-1" as never, + token: "secret-session-token", + method: "bearer-session-token", + role: "owner", + subject: "cli-issued-session", + client: { + label: "deploy-bot", + deviceType: "bot", + }, + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + }, + { json: false }, + ); + + const listedOutput = formatSessionList( + [ + { + sessionId: "session-1" as never, + method: "bearer-session-token", + role: "owner", + subject: "cli-issued-session", + client: { + label: "deploy-bot", + deviceType: "bot", + }, + connected: false, + current: false, + issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")), + expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")), + lastConnectedAt: null, + }, + ], + { json: false }, + ); + + expect(issuedOutput).toContain("secret-session-token"); + expect(listedOutput).not.toContain("secret-session-token"); +}); diff --git a/apps/server/src/cliAuthFormat.ts b/apps/server/src/cliAuthFormat.ts new file mode 100644 index 0000000000..44356c5a8a --- /dev/null +++ b/apps/server/src/cliAuthFormat.ts @@ -0,0 +1,190 @@ +import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts"; +import { DateTime } from "effect"; + +import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts"; + +const newline = "\n"; + +function serializeOptionalFields(values: ReadonlyArray) { + return values.filter((value): value is string => typeof value === "string" && value.length > 0); +} + +function formatClientMetadata(metadata: AuthClientMetadata): string { + const details = serializeOptionalFields([ + metadata.label, + metadata.deviceType !== "unknown" ? metadata.deviceType : undefined, + metadata.os, + metadata.browser, + metadata.ipAddress, + ]); + return details.length > 0 ? details.join(" | ") : "unlabeled client"; +} + +function toIsoString(value: DateTime.DateTime | DateTime.Utc): string { + return DateTime.formatIso(DateTime.toUtc(value)); +} + +export function formatIssuedPairingCredential( + credential: IssuedPairingLink, + options?: { + readonly json?: boolean; + readonly baseUrl?: string; + }, +): string { + const pairUrl = + options?.baseUrl != null && options.baseUrl.length > 0 + ? (() => { + const url = new URL("/pair", options.baseUrl); + url.searchParams.delete("token"); + url.hash = new URLSearchParams([["token", credential.credential]]).toString(); + return url.toString(); + })() + : undefined; + + if (options?.json) { + return `${JSON.stringify( + { + id: credential.id, + credential: credential.credential, + ...(credential.label ? { label: credential.label } : {}), + role: credential.role, + expiresAt: toIsoString(credential.expiresAt), + ...(pairUrl ? { pairUrl } : {}), + }, + null, + 2, + )}${newline}`; + } + + return ( + [ + `Issued client pairing token ${credential.id}.`, + `Token: ${credential.credential}`, + ...(pairUrl ? [`Pair URL: ${pairUrl}`] : []), + `Expires at: ${credential.expiresAt}`, + ].join(newline) + newline + ); +} + +export function formatPairingCredentialList( + credentials: ReadonlyArray, + options?: { + readonly json?: boolean; + }, +): string { + if (options?.json) { + return `${JSON.stringify( + credentials.map((credential) => ({ + id: credential.id, + ...(credential.label ? { label: credential.label } : {}), + role: credential.role, + createdAt: toIsoString(credential.createdAt), + expiresAt: toIsoString(credential.expiresAt), + })), + null, + 2, + )}${newline}`; + } + + if (credentials.length === 0) { + return `No active pairing credentials.${newline}`; + } + + return ( + credentials + .map((credential) => + [ + `${credential.id}${credential.label ? ` (${credential.label})` : ""}`, + ` role: ${credential.role}`, + ` created: ${toIsoString(credential.createdAt)}`, + ` expires: ${toIsoString(credential.expiresAt)}`, + ].join(newline), + ) + .join(`${newline}${newline}`) + newline + ); +} + +export function formatIssuedSession( + session: IssuedBearerSession, + options?: { + readonly json?: boolean; + readonly tokenOnly?: boolean; + }, +): string { + if (options?.tokenOnly) { + return `${session.token}${newline}`; + } + + if (options?.json) { + return `${JSON.stringify( + { + sessionId: session.sessionId, + token: session.token, + method: session.method, + role: session.role, + subject: session.subject, + client: session.client, + expiresAt: toIsoString(session.expiresAt), + }, + null, + 2, + )}${newline}`; + } + + return ( + [ + `Issued ${session.role} bearer session ${session.sessionId}.`, + `Token: ${session.token}`, + `Subject: ${session.subject}`, + `Client: ${formatClientMetadata(session.client)}`, + `Expires at: ${toIsoString(session.expiresAt)}`, + ].join(newline) + newline + ); +} + +export function formatSessionList( + sessions: ReadonlyArray, + options?: { + readonly json?: boolean; + }, +): string { + if (options?.json) { + return `${JSON.stringify( + sessions.map((session) => ({ + sessionId: session.sessionId, + method: session.method, + role: session.role, + subject: session.subject, + client: session.client, + connected: session.connected, + issuedAt: toIsoString(session.issuedAt), + expiresAt: toIsoString(session.expiresAt), + lastConnectedAt: session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : null, + })), + null, + 2, + )}${newline}`; + } + + if (sessions.length === 0) { + return `No active sessions.${newline}`; + } + + return ( + sessions + .map((session) => + [ + `${session.sessionId} [${session.role}]${session.connected ? " connected" : ""}`, + ` method: ${session.method}`, + ` subject: ${session.subject}`, + ` client: ${formatClientMetadata(session.client)}`, + ` issued: ${toIsoString(session.issuedAt)}`, + ` last connected: ${ + session.lastConnectedAt ? toIsoString(session.lastConnectedAt) : "never" + }`, + ` expires: ${toIsoString(session.expiresAt)}`, + ].join(newline), + ) + .join(`${newline}${newline}`) + newline + ); +} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index 887eb11c4f..14c34b8336 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -31,6 +31,7 @@ export interface ServerDerivedPaths { readonly terminalLogsDir: string; readonly anonymousIdPath: string; readonly environmentIdPath: string; + readonly secretsDir: string; } /** @@ -55,7 +56,7 @@ export interface ServerConfigShape extends ServerDerivedPaths { readonly staticDir: string | undefined; readonly devUrl: URL | undefined; readonly noBrowser: boolean; - readonly authToken: string | undefined; + readonly desktopBootstrapToken: string | undefined; readonly autoBootstrapProjectFromCwd: boolean; readonly logWebSocketEvents: boolean; } @@ -85,6 +86,7 @@ export const deriveServerPaths = Effect.fn(function* ( terminalLogsDir: join(logsDir, "terminals"), anonymousIdPath: join(stateDir, "anonymous-id"), environmentIdPath: join(stateDir, "environment-id"), + secretsDir: join(stateDir, "secrets"), }; }); @@ -147,7 +149,7 @@ export class ServerConfig extends ServiceMap.Service 0 - ? cwdBaseName - : "T3 environment"; + const label = yield* resolveServerEnvironmentLabel({ + cwdBaseName, + }); const descriptor: ExecutionEnvironmentDescriptor = { environmentId, diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts new file mode 100644 index 0000000000..3d44713510 --- /dev/null +++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.test.ts @@ -0,0 +1,150 @@ +import { afterEach, describe, expect, it } from "@effect/vitest"; +import { Effect, FileSystem } from "effect"; +import { vi } from "vitest"; + +vi.mock("../../processRunner.ts", () => ({ + runProcess: vi.fn(), +})); + +import { runProcess } from "../../processRunner.ts"; +import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts"; + +const mockedRunProcess = vi.mocked(runProcess); +const NoopFileSystemLayer = FileSystem.layerNoop({}); + +afterEach(() => { + mockedRunProcess.mockReset(); +}); + +describe("resolveServerEnvironmentLabel", () => { + it.effect("uses hostname fallback regardless of launch mode", () => + Effect.gen(function* () { + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "win32", + hostname: "macbook-pro", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("macbook-pro"); + }), + ); + + it.effect("prefers the macOS ComputerName", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: " Julius's MacBook Pro \n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "darwin", + hostname: "macbook-pro", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("Julius's MacBook Pro"); + expect(mockedRunProcess).toHaveBeenCalledWith( + "scutil", + ["--get", "ComputerName"], + expect.objectContaining({ allowNonZeroExit: true }), + ); + }), + ); + + it.effect("prefers Linux PRETTY_HOSTNAME from machine-info", () => + Effect.gen(function* () { + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "linux", + hostname: "buildbox", + }).pipe( + Effect.provide( + FileSystem.layerNoop({ + exists: (path) => Effect.succeed(path === "/etc/machine-info"), + readFileString: (path) => + path === "/etc/machine-info" + ? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n') + : Effect.succeed(""), + }), + ), + ); + + expect(result).toBe("Build Agent 01"); + expect(mockedRunProcess).not.toHaveBeenCalled(); + }), + ); + + it.effect("falls back to hostnamectl pretty hostname on Linux", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: "CI Runner\n", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "linux", + hostname: "runner-01", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("CI Runner"); + expect(mockedRunProcess).toHaveBeenCalledWith( + "hostnamectl", + ["--pretty"], + expect.objectContaining({ allowNonZeroExit: true }), + ); + }), + ); + + it.effect("falls back to the hostname when friendly labels are unavailable", () => + Effect.gen(function* () { + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "win32", + hostname: "JULIUS-LAPTOP", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("JULIUS-LAPTOP"); + }), + ); + + it.effect("falls back to the hostname when the friendly-label command is missing", () => + Effect.gen(function* () { + mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT")); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "darwin", + hostname: "macbook-pro", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("macbook-pro"); + }), + ); + + it.effect("falls back to the cwd basename when the hostname is blank", () => + Effect.gen(function* () { + mockedRunProcess.mockResolvedValueOnce({ + stdout: " ", + stderr: "", + code: 0, + signal: null, + timedOut: false, + }); + + const result = yield* resolveServerEnvironmentLabel({ + cwdBaseName: "t3code", + platform: "linux", + hostname: " ", + }).pipe(Effect.provide(NoopFileSystemLayer)); + + expect(result).toBe("t3code"); + }), + ); +}); diff --git a/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts new file mode 100644 index 0000000000..a5f77c5093 --- /dev/null +++ b/apps/server/src/environment/Layers/ServerEnvironmentLabel.ts @@ -0,0 +1,104 @@ +import * as OS from "node:os"; + +import { Effect, FileSystem } from "effect"; + +import { runProcess } from "../../processRunner.ts"; + +interface ResolveServerEnvironmentLabelInput { + readonly cwdBaseName: string; + readonly platform?: NodeJS.Platform; + readonly hostname?: string | null; +} + +function normalizeLabel(value: string | null | undefined): string | null { + const trimmed = value?.trim(); + return trimmed && trimmed.length > 0 ? trimmed : null; +} + +function parseMachineInfoValue(raw: string, key: string): string | null { + for (const line of raw.split(/\r?\n/g)) { + const trimmed = line.trim(); + if (trimmed.length === 0 || trimmed.startsWith("#") || !trimmed.startsWith(`${key}=`)) { + continue; + } + const value = trimmed.slice(key.length + 1).trim(); + if ( + (value.startsWith('"') && value.endsWith('"')) || + (value.startsWith("'") && value.endsWith("'")) + ) { + return normalizeLabel(value.slice(1, -1)); + } + return normalizeLabel(value); + } + return null; +} + +const readLinuxMachineInfo = Effect.fn("readLinuxMachineInfo")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const exists = yield* fileSystem + .exists("/etc/machine-info") + .pipe(Effect.orElseSucceed(() => false)); + if (!exists) { + return null; + } + + return yield* fileSystem + .readFileString("/etc/machine-info") + .pipe(Effect.orElseSucceed(() => null)); +}); + +const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* ( + command: string, + args: readonly string[], +) { + const result = yield* Effect.tryPromise(() => + runProcess(command, args, { + allowNonZeroExit: true, + }), + ).pipe(Effect.orElseSucceed(() => null)); + + if (!result || result.code !== 0) { + return null; + } + + return normalizeLabel(result.stdout); +}); + +const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* ( + platform: NodeJS.Platform, +) { + if (platform === "darwin") { + return yield* runFriendlyLabelCommand("scutil", ["--get", "ComputerName"]); + } + + if (platform === "linux") { + const machineInfo = normalizeLabel(yield* readLinuxMachineInfo()); + if (machineInfo) { + const prettyHostname = parseMachineInfoValue(machineInfo, "PRETTY_HOSTNAME"); + if (prettyHostname) { + return prettyHostname; + } + } + + return yield* runFriendlyLabelCommand("hostnamectl", ["--pretty"]); + } + + return null; +}); + +export const resolveServerEnvironmentLabel = Effect.fn("resolveServerEnvironmentLabel")(function* ( + input: ResolveServerEnvironmentLabelInput, +) { + const platform = input.platform ?? process.platform; + const friendlyHostLabel = yield* resolveFriendlyHostLabel(platform); + if (friendlyHostLabel) { + return friendlyHostLabel; + } + + const hostname = normalizeLabel(input.hostname ?? OS.hostname()); + if (hostname) { + return hostname; + } + + return normalizeLabel(input.cwdBaseName) ?? "T3 environment"; +}); diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.ts new file mode 100644 index 0000000000..de861cc664 --- /dev/null +++ b/apps/server/src/http.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; + +import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts"; + +describe("http dev routing", () => { + it("treats localhost and loopback addresses as local", () => { + expect(isLoopbackHostname("127.0.0.1")).toBe(true); + expect(isLoopbackHostname("localhost")).toBe(true); + expect(isLoopbackHostname("::1")).toBe(true); + expect(isLoopbackHostname("[::1]")).toBe(true); + }); + + it("does not treat LAN addresses as local", () => { + expect(isLoopbackHostname("192.168.86.35")).toBe(false); + expect(isLoopbackHostname("10.0.0.24")).toBe(false); + expect(isLoopbackHostname("example.local")).toBe(false); + }); + + it("preserves path and query when redirecting to the dev server", () => { + const devUrl = new URL("http://127.0.0.1:5173/"); + const requestUrl = new URL("http://127.0.0.1:3774/pair?token=test-token"); + + expect(resolveDevRedirectUrl(devUrl, requestUrl)).toBe( + "http://127.0.0.1:5173/pair?token=test-token", + ); + }); +}); diff --git a/apps/server/src/http.ts b/apps/server/src/http.ts index ca4a2c22ef..ed40389429 100644 --- a/apps/server/src/http.ts +++ b/apps/server/src/http.ts @@ -1,5 +1,5 @@ import Mime from "@effect/platform-node/Mime"; -import { Data, Effect, FileSystem, Layer, Option, Path } from "effect"; +import { Data, Effect, FileSystem, Option, Path } from "effect"; import { cast } from "effect/Function"; import { HttpBody, @@ -17,14 +17,57 @@ import { resolveAttachmentRelativePath, } from "./attachmentPaths"; import { resolveAttachmentPathById } from "./attachmentStore"; -import { ServerConfig } from "./config"; +import { resolveStaticDir, ServerConfig } from "./config"; import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts"; import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts"; import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver"; +import { ServerAuth } from "./auth/Services/ServerAuth.ts"; +import { respondToAuthError } from "./auth/http.ts"; +import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts"; const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600"; const FALLBACK_PROJECT_FAVICON_SVG = ``; const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces"; +const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]); + +export const browserApiCorsLayer = HttpRouter.cors({ + allowedMethods: ["GET", "POST", "OPTIONS"], + allowedHeaders: ["authorization", "b3", "traceparent", "content-type"], + maxAge: 600, +}); + +export function isLoopbackHostname(hostname: string): boolean { + const normalizedHostname = hostname + .trim() + .toLowerCase() + .replace(/^\[(.*)\]$/, "$1"); + return LOOPBACK_HOSTNAMES.has(normalizedHostname); +} + +export function resolveDevRedirectUrl(devUrl: URL, requestUrl: URL): string { + const redirectUrl = new URL(devUrl.toString()); + redirectUrl.pathname = requestUrl.pathname; + redirectUrl.search = requestUrl.search; + redirectUrl.hash = requestUrl.hash; + return redirectUrl.toString(); +} + +const requireAuthenticatedRequest = Effect.gen(function* () { + const request = yield* HttpServerRequest.HttpServerRequest; + const serverAuth = yield* ServerAuth; + yield* serverAuth.authenticateHttpRequest(request); +}); + +export const serverEnvironmentRouteLayer = HttpRouter.add( + "GET", + "/.well-known/t3/environment", + Effect.gen(function* () { + const descriptor = yield* Effect.service(ServerEnvironment).pipe( + Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor), + ); + return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 }); + }), +); class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{ readonly cause: unknown; @@ -35,6 +78,7 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add( "POST", OTLP_TRACES_PROXY_PATH, Effect.gen(function* () { + yield* requireAuthenticatedRequest; const request = yield* HttpServerRequest.HttpServerRequest; const config = yield* ServerConfig; const otlpTracesUrl = config.otlpTracesUrl; @@ -76,21 +120,14 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add( Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })), ), ); - }), -).pipe( - Layer.provide( - HttpRouter.cors({ - allowedMethods: ["POST", "OPTIONS"], - allowedHeaders: ["content-type"], - maxAge: 600, - }), - ), + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), ); export const attachmentsRouteLayer = HttpRouter.add( "GET", `${ATTACHMENTS_ROUTE_PREFIX}/*`, Effect.gen(function* () { + yield* requireAuthenticatedRequest; const request = yield* HttpServerRequest.HttpServerRequest; const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { @@ -139,13 +176,14 @@ export const attachmentsRouteLayer = HttpRouter.add( Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), ), ); - }), + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), ); export const projectFaviconRouteLayer = HttpRouter.add( "GET", "/api/project-favicon", Effect.gen(function* () { + yield* requireAuthenticatedRequest; const request = yield* HttpServerRequest.HttpServerRequest; const url = HttpServerRequest.toURL(request); if (Option.isNone(url)) { @@ -179,7 +217,7 @@ export const projectFaviconRouteLayer = HttpRouter.add( Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })), ), ); - }), + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), ); export const staticAndDevRouteLayer = HttpRouter.add( @@ -193,11 +231,14 @@ export const staticAndDevRouteLayer = HttpRouter.add( } const config = yield* ServerConfig; - if (config.devUrl) { - return HttpServerResponse.redirect(config.devUrl.href, { status: 302 }); + if (config.devUrl && isLoopbackHostname(url.value.hostname)) { + return HttpServerResponse.redirect(resolveDevRedirectUrl(config.devUrl, url.value), { + status: 302, + }); } - if (!config.staticDir) { + const staticDir = config.staticDir ?? (config.devUrl ? yield* resolveStaticDir() : undefined); + if (!staticDir) { return HttpServerResponse.text("No static directory configured and no dev URL set.", { status: 503, }); @@ -205,7 +246,7 @@ export const staticAndDevRouteLayer = HttpRouter.add( const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; - const staticRoot = path.resolve(config.staticDir); + const staticRoot = path.resolve(staticDir); const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname; const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, ""); const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith(".."); diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 8eda0ca85d..e3f190ff06 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -2,7 +2,7 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import { assertFailure } from "@effect/vitest/utils"; -import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; +import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect"; import { ServerConfig } from "./config"; import { @@ -149,6 +149,23 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }), ); + it.effect("formats invalid resolved keybinding rules with the custom message", () => + Effect.sync(() => { + const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({ + key: "mod+shift+d+o", + command: "terminal.new", + }); + + if (result._tag !== "Failure") { + assert.fail("Expected invalid keybinding decode to fail"); + } + + const detail = Cause.pretty(result.cause); + assert.isTrue(detail.includes("Invalid keybinding rule")); + assert.isFalse(detail.includes("Invalid data")); + }), + ); + it.effect("bootstraps default keybindings when config file is missing", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 086d795c0c..1d0ab812f2 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -322,7 +322,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( Predicate.isNotNull, () => new SchemaIssue.InvalidValue(Option.some(rule), { - title: "Invalid keybinding rule", + message: "Invalid keybinding rule", }), ), Effect.map((resolved) => resolved), @@ -334,7 +334,7 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe( if (!key) { return yield* Effect.fail( new SchemaIssue.InvalidValue(Option.some(resolved), { - title: "Resolved shortcut cannot be encoded to key string", + message: "Resolved shortcut cannot be encoded to key string", }), ); } diff --git a/apps/server/src/persistence/Errors.ts b/apps/server/src/persistence/Errors.ts index cb1cb2f3f8..eb05bf5ae9 100644 --- a/apps/server/src/persistence/Errors.ts +++ b/apps/server/src/persistence/Errors.ts @@ -101,5 +101,7 @@ export type OrchestrationCommandReceiptRepositoryError = | PersistenceDecodeError; export type ProviderSessionRuntimeRepositoryError = PersistenceSqlError | PersistenceDecodeError; +export type AuthPairingLinkRepositoryError = PersistenceSqlError | PersistenceDecodeError; +export type AuthSessionRepositoryError = PersistenceSqlError | PersistenceDecodeError; export type ProjectionRepositoryError = PersistenceSqlError | PersistenceDecodeError; diff --git a/apps/server/src/persistence/Layers/AuthPairingLinks.ts b/apps/server/src/persistence/Layers/AuthPairingLinks.ts new file mode 100644 index 0000000000..9767f24993 --- /dev/null +++ b/apps/server/src/persistence/Layers/AuthPairingLinks.ts @@ -0,0 +1,209 @@ +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Schema } from "effect"; + +import { + toPersistenceDecodeError, + toPersistenceSqlError, + type AuthPairingLinkRepositoryError, +} from "../Errors.ts"; +import { + AuthPairingLinkRecord, + AuthPairingLinkRepository, + type AuthPairingLinkRepositoryShape, + ConsumeAuthPairingLinkInput, + CreateAuthPairingLinkInput, + GetAuthPairingLinkByCredentialInput, + ListActiveAuthPairingLinksInput, + RevokeAuthPairingLinkInput, +} from "../Services/AuthPairingLinks.ts"; + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): AuthPairingLinkRepositoryError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeAuthPairingLinkRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const createPairingLinkRow = SqlSchema.void({ + Request: CreateAuthPairingLinkInput, + execute: (input) => + sql` + INSERT INTO auth_pairing_links ( + id, + credential, + method, + role, + subject, + label, + created_at, + expires_at, + consumed_at, + revoked_at + ) + VALUES ( + ${input.id}, + ${input.credential}, + ${input.method}, + ${input.role}, + ${input.subject}, + ${input.label}, + ${input.createdAt}, + ${input.expiresAt}, + NULL, + NULL + ) + `, + }); + + const consumeAvailablePairingLinkRow = SqlSchema.findOneOption({ + Request: ConsumeAuthPairingLinkInput, + Result: AuthPairingLinkRecord, + execute: ({ credential, consumedAt, now }) => + sql` + UPDATE auth_pairing_links + SET consumed_at = ${consumedAt} + WHERE credential = ${credential} + AND revoked_at IS NULL + AND consumed_at IS NULL + AND expires_at > ${now} + RETURNING + id AS "id", + credential AS "credential", + method AS "method", + role AS "role", + subject AS "subject", + label AS "label", + created_at AS "createdAt", + expires_at AS "expiresAt", + consumed_at AS "consumedAt", + revoked_at AS "revokedAt" + `, + }); + + const listActivePairingLinkRows = SqlSchema.findAll({ + Request: ListActiveAuthPairingLinksInput, + Result: AuthPairingLinkRecord, + execute: ({ now }) => + sql` + SELECT + id AS "id", + credential AS "credential", + method AS "method", + role AS "role", + subject AS "subject", + label AS "label", + created_at AS "createdAt", + expires_at AS "expiresAt", + consumed_at AS "consumedAt", + revoked_at AS "revokedAt" + FROM auth_pairing_links + WHERE revoked_at IS NULL + AND consumed_at IS NULL + AND expires_at > ${now} + ORDER BY created_at DESC, id DESC + `, + }); + + const revokePairingLinkRow = SqlSchema.findAll({ + Request: RevokeAuthPairingLinkInput, + Result: Schema.Struct({ id: Schema.String }), + execute: ({ id, revokedAt }) => + sql` + UPDATE auth_pairing_links + SET revoked_at = ${revokedAt} + WHERE id = ${id} + AND revoked_at IS NULL + AND consumed_at IS NULL + RETURNING id AS "id" + `, + }); + + const getPairingLinkRowByCredential = SqlSchema.findOneOption({ + Request: GetAuthPairingLinkByCredentialInput, + Result: AuthPairingLinkRecord, + execute: ({ credential }) => + sql` + SELECT + id AS "id", + credential AS "credential", + method AS "method", + role AS "role", + subject AS "subject", + label AS "label", + created_at AS "createdAt", + expires_at AS "expiresAt", + consumed_at AS "consumedAt", + revoked_at AS "revokedAt" + FROM auth_pairing_links + WHERE credential = ${credential} + `, + }); + + const create: AuthPairingLinkRepositoryShape["create"] = (input) => + createPairingLinkRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.create:query", + "AuthPairingLinkRepository.create:encodeRequest", + ), + ), + ); + + const consumeAvailable: AuthPairingLinkRepositoryShape["consumeAvailable"] = (input) => + consumeAvailablePairingLinkRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.consumeAvailable:query", + "AuthPairingLinkRepository.consumeAvailable:decodeRow", + ), + ), + ); + + const listActive: AuthPairingLinkRepositoryShape["listActive"] = (input) => + listActivePairingLinkRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.listActive:query", + "AuthPairingLinkRepository.listActive:decodeRows", + ), + ), + ); + + const revoke: AuthPairingLinkRepositoryShape["revoke"] = (input) => + revokePairingLinkRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.revoke:query", + "AuthPairingLinkRepository.revoke:decodeRows", + ), + ), + Effect.map((rows) => rows.length > 0), + ); + + const getByCredential: AuthPairingLinkRepositoryShape["getByCredential"] = (input) => + getPairingLinkRowByCredential(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthPairingLinkRepository.getByCredential:query", + "AuthPairingLinkRepository.getByCredential:decodeRow", + ), + ), + ); + + return { + create, + consumeAvailable, + listActive, + revoke, + getByCredential, + } satisfies AuthPairingLinkRepositoryShape; +}); + +export const AuthPairingLinkRepositoryLive = Layer.effect( + AuthPairingLinkRepository, + makeAuthPairingLinkRepository, +); diff --git a/apps/server/src/persistence/Layers/AuthSessions.ts b/apps/server/src/persistence/Layers/AuthSessions.ts new file mode 100644 index 0000000000..66e02ed2a7 --- /dev/null +++ b/apps/server/src/persistence/Layers/AuthSessions.ts @@ -0,0 +1,279 @@ +import { AuthSessionId } from "@t3tools/contracts"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; +import * as SqlSchema from "effect/unstable/sql/SqlSchema"; +import { Effect, Layer, Option, Schema } from "effect"; + +import { + toPersistenceDecodeError, + toPersistenceSqlError, + type AuthSessionRepositoryError, +} from "../Errors.ts"; +import { + AuthSessionRecord, + AuthSessionRepository, + type AuthSessionRepositoryShape, + CreateAuthSessionInput, + GetAuthSessionByIdInput, + ListActiveAuthSessionsInput, + RevokeAuthSessionInput, + RevokeOtherAuthSessionsInput, + SetAuthSessionLastConnectedAtInput, +} from "../Services/AuthSessions.ts"; + +const AuthSessionDbRow = Schema.Struct({ + sessionId: AuthSessionId, + subject: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + clientLabel: Schema.NullOr(Schema.String), + clientIpAddress: Schema.NullOr(Schema.String), + clientUserAgent: Schema.NullOr(Schema.String), + clientDeviceType: Schema.Literals(["desktop", "mobile", "tablet", "bot", "unknown"]), + clientOs: Schema.NullOr(Schema.String), + clientBrowser: Schema.NullOr(Schema.String), + issuedAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, + lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}); + +function toAuthSessionRecord(row: typeof AuthSessionDbRow.Type): typeof AuthSessionRecord.Type { + return { + sessionId: row.sessionId, + subject: row.subject, + role: row.role, + method: row.method, + client: { + label: row.clientLabel, + ipAddress: row.clientIpAddress, + userAgent: row.clientUserAgent, + deviceType: row.clientDeviceType, + os: row.clientOs, + browser: row.clientBrowser, + }, + issuedAt: row.issuedAt, + expiresAt: row.expiresAt, + lastConnectedAt: row.lastConnectedAt, + revokedAt: row.revokedAt, + }; +} + +function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) { + return (cause: unknown): AuthSessionRepositoryError => + Schema.isSchemaError(cause) + ? toPersistenceDecodeError(decodeOperation)(cause) + : toPersistenceSqlError(sqlOperation)(cause); +} + +const makeAuthSessionRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const createSessionRow = SqlSchema.void({ + Request: CreateAuthSessionInput, + execute: (input) => + sql` + INSERT INTO auth_sessions ( + session_id, + subject, + role, + method, + client_label, + client_ip_address, + client_user_agent, + client_device_type, + client_os, + client_browser, + issued_at, + expires_at, + revoked_at + ) + VALUES ( + ${input.sessionId}, + ${input.subject}, + ${input.role}, + ${input.method}, + ${input.client.label}, + ${input.client.ipAddress}, + ${input.client.userAgent}, + ${input.client.deviceType}, + ${input.client.os}, + ${input.client.browser}, + ${input.issuedAt}, + ${input.expiresAt}, + NULL + ) + `, + }); + + const getSessionRowById = SqlSchema.findOneOption({ + Request: GetAuthSessionByIdInput, + Result: AuthSessionDbRow, + execute: ({ sessionId }) => + sql` + SELECT + session_id AS "sessionId", + subject AS "subject", + role AS "role", + method AS "method", + client_label AS "clientLabel", + client_ip_address AS "clientIpAddress", + client_user_agent AS "clientUserAgent", + client_device_type AS "clientDeviceType", + client_os AS "clientOs", + client_browser AS "clientBrowser", + issued_at AS "issuedAt", + expires_at AS "expiresAt", + last_connected_at AS "lastConnectedAt", + revoked_at AS "revokedAt" + FROM auth_sessions + WHERE session_id = ${sessionId} + `, + }); + + const listActiveSessionRows = SqlSchema.findAll({ + Request: ListActiveAuthSessionsInput, + Result: AuthSessionDbRow, + execute: ({ now }) => + sql` + SELECT + session_id AS "sessionId", + subject AS "subject", + role AS "role", + method AS "method", + client_label AS "clientLabel", + client_ip_address AS "clientIpAddress", + client_user_agent AS "clientUserAgent", + client_device_type AS "clientDeviceType", + client_os AS "clientOs", + client_browser AS "clientBrowser", + issued_at AS "issuedAt", + expires_at AS "expiresAt", + last_connected_at AS "lastConnectedAt", + revoked_at AS "revokedAt" + FROM auth_sessions + WHERE revoked_at IS NULL + AND expires_at > ${now} + ORDER BY issued_at DESC, session_id DESC + `, + }); + + const setLastConnectedAtRow = SqlSchema.void({ + Request: SetAuthSessionLastConnectedAtInput, + execute: ({ sessionId, lastConnectedAt }) => + sql` + UPDATE auth_sessions + SET last_connected_at = ${lastConnectedAt} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + `, + }); + + const revokeSessionRows = SqlSchema.findAll({ + Request: RevokeAuthSessionInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ sessionId, revokedAt }) => + sql` + UPDATE auth_sessions + SET revoked_at = ${revokedAt} + WHERE session_id = ${sessionId} + AND revoked_at IS NULL + RETURNING session_id AS "sessionId" + `, + }); + + const revokeOtherSessionRows = SqlSchema.findAll({ + Request: RevokeOtherAuthSessionsInput, + Result: Schema.Struct({ sessionId: AuthSessionId }), + execute: ({ currentSessionId, revokedAt }) => + sql` + UPDATE auth_sessions + SET revoked_at = ${revokedAt} + WHERE session_id <> ${currentSessionId} + AND revoked_at IS NULL + RETURNING session_id AS "sessionId" + `, + }); + + const create: AuthSessionRepositoryShape["create"] = (input) => + createSessionRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.create:query", + "AuthSessionRepository.create:encodeRequest", + ), + ), + ); + + const getById: AuthSessionRepositoryShape["getById"] = (input) => + getSessionRowById(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.getById:query", + "AuthSessionRepository.getById:decodeRow", + ), + ), + Effect.flatMap((rowOption) => + Option.match(rowOption, { + onNone: () => Effect.succeed(Option.none()), + onSome: (row) => Effect.succeed(Option.some(toAuthSessionRecord(row))), + }), + ), + ); + + const listActive: AuthSessionRepositoryShape["listActive"] = (input) => + listActiveSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.listActive:query", + "AuthSessionRepository.listActive:decodeRows", + ), + ), + Effect.flatMap((rows) => Effect.succeed(rows.map((row) => toAuthSessionRecord(row)))), + ); + + const revoke: AuthSessionRepositoryShape["revoke"] = (input) => + revokeSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.revoke:query", + "AuthSessionRepository.revoke:decodeRows", + ), + ), + Effect.map((rows) => rows.length > 0), + ); + + const revokeAllExcept: AuthSessionRepositoryShape["revokeAllExcept"] = (input) => + revokeOtherSessionRows(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.revokeAllExcept:query", + "AuthSessionRepository.revokeAllExcept:decodeRows", + ), + ), + Effect.map((rows) => rows.map((row) => row.sessionId)), + ); + + const setLastConnectedAt: AuthSessionRepositoryShape["setLastConnectedAt"] = (input) => + setLastConnectedAtRow(input).pipe( + Effect.mapError( + toPersistenceSqlOrDecodeError( + "AuthSessionRepository.setLastConnectedAt:query", + "AuthSessionRepository.setLastConnectedAt:encodeRequest", + ), + ), + ); + + return { + create, + getById, + listActive, + revoke, + revokeAllExcept, + setLastConnectedAt, + } satisfies AuthSessionRepositoryShape; +}); + +export const AuthSessionRepositoryLive = Layer.effect( + AuthSessionRepository, + makeAuthSessionRepository, +); diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index a03c3c2d18..8c9fe4d9fd 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -32,6 +32,9 @@ import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts"; import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts"; import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts"; import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts"; +import Migration0020 from "./Migrations/020_AuthAccessManagement.ts"; +import Migration0021 from "./Migrations/021_AuthSessionClientMetadata.ts"; +import Migration0022 from "./Migrations/022_AuthSessionLastConnectedAt.ts"; /** * Migration loader with all migrations defined inline. @@ -63,6 +66,9 @@ export const migrationEntries = [ [17, "ProjectionThreadsArchivedAt", Migration0017], [18, "ProjectionThreadsArchivedAtIndex", Migration0018], [19, "ProjectionSnapshotLookupIndexes", Migration0019], + [20, "AuthAccessManagement", Migration0020], + [21, "AuthSessionClientMetadata", Migration0021], + [22, "AuthSessionLastConnectedAt", Migration0022], ] as const; export const makeMigrationLoader = (throughId?: number) => diff --git a/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts b/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts new file mode 100644 index 0000000000..1be7fa80ff --- /dev/null +++ b/apps/server/src/persistence/Migrations/020_AuthAccessManagement.ts @@ -0,0 +1,42 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS auth_pairing_links ( + id TEXT PRIMARY KEY, + credential TEXT NOT NULL UNIQUE, + method TEXT NOT NULL, + role TEXT NOT NULL, + subject TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + consumed_at TEXT, + revoked_at TEXT + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_auth_pairing_links_active + ON auth_pairing_links(revoked_at, consumed_at, expires_at) + `; + + yield* sql` + CREATE TABLE IF NOT EXISTS auth_sessions ( + session_id TEXT PRIMARY KEY, + subject TEXT NOT NULL, + role TEXT NOT NULL, + method TEXT NOT NULL, + issued_at TEXT NOT NULL, + expires_at TEXT NOT NULL, + revoked_at TEXT + ) + `; + + yield* sql` + CREATE INDEX IF NOT EXISTS idx_auth_sessions_active + ON auth_sessions(revoked_at, expires_at, issued_at) + `; +}); diff --git a/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts b/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts new file mode 100644 index 0000000000..3b387fdcfd --- /dev/null +++ b/apps/server/src/persistence/Migrations/021_AuthSessionClientMetadata.ts @@ -0,0 +1,62 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const pairingLinkColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_pairing_links) + `; + if (!pairingLinkColumns.some((column) => column.name === "label")) { + yield* sql` + ALTER TABLE auth_pairing_links + ADD COLUMN label TEXT + `; + } + + const sessionColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_sessions) + `; + + if (!sessionColumns.some((column) => column.name === "client_label")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_label TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_ip_address")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_ip_address TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_user_agent")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_user_agent TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_device_type")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_device_type TEXT NOT NULL DEFAULT 'unknown' + `; + } + + if (!sessionColumns.some((column) => column.name === "client_os")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_os TEXT + `; + } + + if (!sessionColumns.some((column) => column.name === "client_browser")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN client_browser TEXT + `; + } +}); diff --git a/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts b/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts new file mode 100644 index 0000000000..e806a073a5 --- /dev/null +++ b/apps/server/src/persistence/Migrations/022_AuthSessionLastConnectedAt.ts @@ -0,0 +1,17 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/unstable/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const sessionColumns = yield* sql<{ readonly name: string }>` + PRAGMA table_info(auth_sessions) + `; + + if (!sessionColumns.some((column) => column.name === "last_connected_at")) { + yield* sql` + ALTER TABLE auth_sessions + ADD COLUMN last_connected_at TEXT + `; + } +}); diff --git a/apps/server/src/persistence/Services/AuthPairingLinks.ts b/apps/server/src/persistence/Services/AuthPairingLinks.ts new file mode 100644 index 0000000000..76c14a6586 --- /dev/null +++ b/apps/server/src/persistence/Services/AuthPairingLinks.ts @@ -0,0 +1,76 @@ +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { AuthPairingLinkRepositoryError } from "../Errors.ts"; + +export const AuthPairingLinkRecord = Schema.Struct({ + id: Schema.String, + credential: Schema.String, + method: Schema.Literals(["desktop-bootstrap", "one-time-token"]), + role: Schema.Literals(["owner", "client"]), + subject: Schema.String, + label: Schema.NullOr(Schema.String), + createdAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, + consumedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}); +export type AuthPairingLinkRecord = typeof AuthPairingLinkRecord.Type; + +export const CreateAuthPairingLinkInput = Schema.Struct({ + id: Schema.String, + credential: Schema.String, + method: Schema.Literals(["desktop-bootstrap", "one-time-token"]), + role: Schema.Literals(["owner", "client"]), + subject: Schema.String, + label: Schema.NullOr(Schema.String), + createdAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, +}); +export type CreateAuthPairingLinkInput = typeof CreateAuthPairingLinkInput.Type; + +export const ConsumeAuthPairingLinkInput = Schema.Struct({ + credential: Schema.String, + consumedAt: Schema.DateTimeUtcFromString, + now: Schema.DateTimeUtcFromString, +}); +export type ConsumeAuthPairingLinkInput = typeof ConsumeAuthPairingLinkInput.Type; + +export const ListActiveAuthPairingLinksInput = Schema.Struct({ + now: Schema.DateTimeUtcFromString, +}); +export type ListActiveAuthPairingLinksInput = typeof ListActiveAuthPairingLinksInput.Type; + +export const RevokeAuthPairingLinkInput = Schema.Struct({ + id: Schema.String, + revokedAt: Schema.DateTimeUtcFromString, +}); +export type RevokeAuthPairingLinkInput = typeof RevokeAuthPairingLinkInput.Type; + +export const GetAuthPairingLinkByCredentialInput = Schema.Struct({ + credential: Schema.String, +}); +export type GetAuthPairingLinkByCredentialInput = typeof GetAuthPairingLinkByCredentialInput.Type; + +export interface AuthPairingLinkRepositoryShape { + readonly create: ( + input: CreateAuthPairingLinkInput, + ) => Effect.Effect; + readonly consumeAvailable: ( + input: ConsumeAuthPairingLinkInput, + ) => Effect.Effect, AuthPairingLinkRepositoryError>; + readonly listActive: ( + input: ListActiveAuthPairingLinksInput, + ) => Effect.Effect, AuthPairingLinkRepositoryError>; + readonly revoke: ( + input: RevokeAuthPairingLinkInput, + ) => Effect.Effect; + readonly getByCredential: ( + input: GetAuthPairingLinkByCredentialInput, + ) => Effect.Effect, AuthPairingLinkRepositoryError>; +} + +export class AuthPairingLinkRepository extends ServiceMap.Service< + AuthPairingLinkRepository, + AuthPairingLinkRepositoryShape +>()("t3/persistence/Services/AuthPairingLinks/AuthPairingLinkRepository") {} diff --git a/apps/server/src/persistence/Services/AuthSessions.ts b/apps/server/src/persistence/Services/AuthSessions.ts new file mode 100644 index 0000000000..a4410fa379 --- /dev/null +++ b/apps/server/src/persistence/Services/AuthSessions.ts @@ -0,0 +1,93 @@ +import { AuthClientMetadataDeviceType, AuthSessionId } from "@t3tools/contracts"; +import { Option, Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { AuthSessionRepositoryError } from "../Errors.ts"; + +export const AuthSessionClientMetadataRecord = Schema.Struct({ + label: Schema.NullOr(Schema.String), + ipAddress: Schema.NullOr(Schema.String), + userAgent: Schema.NullOr(Schema.String), + deviceType: AuthClientMetadataDeviceType, + os: Schema.NullOr(Schema.String), + browser: Schema.NullOr(Schema.String), +}); +export type AuthSessionClientMetadataRecord = typeof AuthSessionClientMetadataRecord.Type; + +export const AuthSessionRecord = Schema.Struct({ + sessionId: AuthSessionId, + subject: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + client: AuthSessionClientMetadataRecord, + issuedAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, + lastConnectedAt: Schema.NullOr(Schema.DateTimeUtcFromString), + revokedAt: Schema.NullOr(Schema.DateTimeUtcFromString), +}); +export type AuthSessionRecord = typeof AuthSessionRecord.Type; + +export const CreateAuthSessionInput = Schema.Struct({ + sessionId: AuthSessionId, + subject: Schema.String, + role: Schema.Literals(["owner", "client"]), + method: Schema.Literals(["browser-session-cookie", "bearer-session-token"]), + client: AuthSessionClientMetadataRecord, + issuedAt: Schema.DateTimeUtcFromString, + expiresAt: Schema.DateTimeUtcFromString, +}); +export type CreateAuthSessionInput = typeof CreateAuthSessionInput.Type; + +export const GetAuthSessionByIdInput = Schema.Struct({ + sessionId: AuthSessionId, +}); +export type GetAuthSessionByIdInput = typeof GetAuthSessionByIdInput.Type; + +export const ListActiveAuthSessionsInput = Schema.Struct({ + now: Schema.DateTimeUtcFromString, +}); +export type ListActiveAuthSessionsInput = typeof ListActiveAuthSessionsInput.Type; + +export const RevokeAuthSessionInput = Schema.Struct({ + sessionId: AuthSessionId, + revokedAt: Schema.DateTimeUtcFromString, +}); +export type RevokeAuthSessionInput = typeof RevokeAuthSessionInput.Type; + +export const RevokeOtherAuthSessionsInput = Schema.Struct({ + currentSessionId: AuthSessionId, + revokedAt: Schema.DateTimeUtcFromString, +}); +export type RevokeOtherAuthSessionsInput = typeof RevokeOtherAuthSessionsInput.Type; + +export const SetAuthSessionLastConnectedAtInput = Schema.Struct({ + sessionId: AuthSessionId, + lastConnectedAt: Schema.DateTimeUtcFromString, +}); +export type SetAuthSessionLastConnectedAtInput = typeof SetAuthSessionLastConnectedAtInput.Type; + +export interface AuthSessionRepositoryShape { + readonly create: ( + input: CreateAuthSessionInput, + ) => Effect.Effect; + readonly getById: ( + input: GetAuthSessionByIdInput, + ) => Effect.Effect, AuthSessionRepositoryError>; + readonly listActive: ( + input: ListActiveAuthSessionsInput, + ) => Effect.Effect, AuthSessionRepositoryError>; + readonly revoke: ( + input: RevokeAuthSessionInput, + ) => Effect.Effect; + readonly revokeAllExcept: ( + input: RevokeOtherAuthSessionsInput, + ) => Effect.Effect, AuthSessionRepositoryError>; + readonly setLastConnectedAt: ( + input: SetAuthSessionLastConnectedAtInput, + ) => Effect.Effect; +} + +export class AuthSessionRepository extends ServiceMap.Service< + AuthSessionRepository, + AuthSessionRepositoryShape +>()("t3/persistence/Services/AuthSessions/AuthSessionRepository") {} diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 125cfd103a..4e683637e7 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -43,6 +43,7 @@ import { } from "effect/unstable/http"; import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability"; import { RpcClient, RpcSerialization } from "effect/unstable/rpc"; +import * as Socket from "effect/unstable/socket/Socket"; import { vi } from "vitest"; import type { ServerConfigShape } from "./config.ts"; @@ -68,6 +69,7 @@ import { type ProjectionSnapshotQueryShape, } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import { PersistenceSqlError } from "./persistence/Errors.ts"; +import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts"; import { ProviderRegistry, type ProviderRegistryShape, @@ -96,9 +98,12 @@ import { import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; +import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts"; +import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts"; const defaultProjectId = ProjectId.makeUnsafe("project-default"); const defaultThreadId = ThreadId.makeUnsafe("thread-default"); +const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token"; const defaultModelSelection = { provider: "codex", model: "gpt-5-codex", @@ -115,7 +120,6 @@ const testEnvironmentDescriptor = { repositoryIdentity: true, }, }; - const makeDefaultOrchestrationReadModel = () => { const now = new Date().toISOString(); return { @@ -174,6 +178,11 @@ const browserOtlpTracingLayer = Layer.mergeAll( Layer.succeed(HttpClient.TracerDisabledWhen, () => true), ); +const authTestLayer = ServerAuthLive.pipe( + Layer.provide(SqlitePersistenceMemory), + Layer.provide(ServerSecretStoreLive), +); + const makeBrowserOtlpPayload = (spanName: string) => Effect.gen(function* () { const collector = yield* Effect.acquireRelease( @@ -313,7 +322,7 @@ const buildAppUnderTest = (options?: { otlpMetricsUrl: undefined, otlpExportIntervalMs: 10_000, otlpServiceName: "t3-server", - mode: "web", + mode: "desktop", port: 0, host: "127.0.0.1", cwd: process.cwd(), @@ -322,7 +331,7 @@ const buildAppUnderTest = (options?: { staticDir: undefined, devUrl, noBrowser: true, - authToken: undefined, + desktopBootstrapToken: defaultDesktopBootstrapToken, autoBootstrapProjectFromCwd: false, logWebSocketEvents: false, ...options?.config, @@ -333,12 +342,16 @@ const buildAppUnderTest = (options?: { }); const gitStatusBroadcasterLayer = GitStatusBroadcasterLive.pipe(Layer.provide(gitManagerLayer)); - const appLayer = HttpRouter.serve(makeRoutesLayer, { + const servedRoutesLayer = HttpRouter.serve(makeRoutesLayer, { disableListenLog: true, disableLogger: true, }).pipe( Layer.provide( Layer.mock(Keybindings)({ + loadConfigState: Effect.succeed({ + keybindings: [], + issues: [], + }), streamChanges: Stream.empty, ...options?.layers?.keybindings, }), @@ -418,6 +431,9 @@ const buildAppUnderTest = (options?: { ...options?.layers?.checkpointDiffQuery, }), ), + ); + + const appLayer = servedRoutesLayer.pipe( Layer.provide( Layer.mock(BrowserTraceCollector)({ record: () => Effect.void, @@ -453,6 +469,7 @@ const buildAppUnderTest = (options?: { ...options?.layers?.repositoryIdentityResolver, }), ), + Layer.provideMerge(authTestLayer), Layer.provide(workspaceAndProjectServicesLayer), Layer.provideMerge(FetchHttpClient.layer), Layer.provide(layerConfig), @@ -462,11 +479,37 @@ const buildAppUnderTest = (options?: { return config; }); -const wsRpcProtocolLayer = (wsUrl: string) => - RpcClient.layerProtocolSocket().pipe( - Layer.provide(NodeSocket.layerWebSocket(wsUrl)), +const parseSessionCookieFromWsUrl = ( + wsUrl: string, +): { readonly cookie: string | null; readonly url: string } => { + const next = new URL(wsUrl); + const cookie = next.hash.startsWith("#cookie=") + ? decodeURIComponent(next.hash.slice("#cookie=".length)) + : null; + next.hash = ""; + return { + cookie, + url: next.toString(), + }; +}; + +const wsRpcProtocolLayer = (wsUrl: string) => { + const { cookie, url } = parseSessionCookieFromWsUrl(wsUrl); + const webSocketConstructorLayer = Layer.succeed( + Socket.WebSocketConstructor, + (socketUrl, protocols) => + new NodeSocket.NodeWS.WebSocket( + socketUrl, + protocols, + cookie ? { headers: { cookie } } : undefined, + ) as unknown as globalThis.WebSocket, + ); + + return RpcClient.layerProtocolSocket().pipe( + Layer.provide(Socket.layerWebSocket(url).pipe(Layer.provide(webSocketConstructorLayer))), Layer.provide(RpcSerialization.layerJson), ); +}; const makeWsRpcClient = RpcClient.make(WsRpcGroup); type WsRpcClient = @@ -477,6 +520,13 @@ const withWsRpcClient = ( f: (client: WsRpcClient) => Effect.Effect, ) => makeWsRpcClient.pipe(Effect.flatMap(f), Effect.provide(wsRpcProtocolLayer(wsUrl))); +const appendSessionCookieToWsUrl = (url: string, sessionCookieHeader: string) => { + const isAbsoluteUrl = /^[a-zA-Z][a-zA-Z\d+.-]*:/.test(url); + const next = new URL(url, "http://localhost"); + next.hash = `cookie=${encodeURIComponent(sessionCookieHeader)}`; + return isAbsoluteUrl ? next.toString() : `${next.pathname}${next.search}${next.hash}`; +}; + const getHttpServerUrl = (pathname = "") => Effect.gen(function* () { const server = yield* HttpServer.HttpServer; @@ -484,11 +534,130 @@ const getHttpServerUrl = (pathname = "") => return `http://127.0.0.1:${address.port}${pathname}`; }); -const getWsServerUrl = (pathname = "") => +const bootstrapBrowserSession = ( + credential = defaultDesktopBootstrapToken, + options?: { + readonly headers?: Record; + }, +) => + Effect.gen(function* () { + const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap"); + const response = yield* Effect.promise(() => + fetch(bootstrapUrl, { + method: "POST", + headers: { + "content-type": "application/json", + ...options?.headers, + }, + body: JSON.stringify({ + credential, + }), + }), + ); + const body = (yield* Effect.promise(() => response.json())) as { + readonly authenticated: boolean; + readonly sessionMethod: string; + readonly expiresAt: string; + }; + return { + response, + body, + cookie: response.headers.get("set-cookie"), + }; + }); + +const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) => + Effect.gen(function* () { + const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer"); + const response = yield* Effect.promise(() => + fetch(bootstrapUrl, { + method: "POST", + headers: { + "content-type": "application/json", + }, + body: JSON.stringify({ + credential, + }), + }), + ); + const body = (yield* Effect.promise(() => response.json())) as { + readonly authenticated: boolean; + readonly sessionMethod: string; + readonly expiresAt: string; + readonly sessionToken?: string; + readonly error?: string; + }; + return { + response, + body, + }; + }); + +const getAuthenticatedSessionCookieHeader = (credential = defaultDesktopBootstrapToken) => + Effect.gen(function* () { + const { response, cookie } = yield* bootstrapBrowserSession(credential); + if (!response.ok) { + return yield* Effect.fail( + new Error(`Expected bootstrap session response to succeed, got ${response.status}`), + ); + } + + if (!cookie) { + return yield* Effect.fail(new Error("Expected bootstrap session response to set a cookie.")); + } + + return cookie.split(";")[0] ?? cookie; + }); + +const getAuthenticatedBearerSessionToken = (credential = defaultDesktopBootstrapToken) => + Effect.gen(function* () { + const { response, body } = yield* bootstrapBearerSession(credential); + if (!response.ok) { + return yield* Effect.fail( + new Error(`Expected bearer bootstrap response to succeed, got ${response.status}`), + ); + } + + if (!body.sessionToken) { + return yield* Effect.fail( + new Error("Expected bearer bootstrap response to include a session token."), + ); + } + + return body.sessionToken; + }); + +const extractSessionTokenFromSetCookie = (cookieHeader: string): string => { + const [nameValue] = cookieHeader.split(";", 1); + const token = nameValue?.split("=", 2)[1]; + if (!token) { + throw new Error("Expected session cookie header to contain a token value."); + } + return token; +}; + +const splitHeaderTokens = (value: string | null) => + (value ?? "") + .split(",") + .map((token) => token.trim()) + .filter((token) => token.length > 0) + .toSorted(); + +const getWsServerUrl = ( + pathname = "", + options?: { authenticated?: boolean; credential?: string }, +) => Effect.gen(function* () { const server = yield* HttpServer.HttpServer; const address = server.address as HttpServer.TcpAddress; - return `ws://127.0.0.1:${address.port}${pathname}`; + const baseUrl = `ws://127.0.0.1:${address.port}${pathname}`; + if (options?.authenticated === false) { + return baseUrl; + } + return appendSessionCookieToWsUrl( + baseUrl, + yield* getAuthenticatedSessionCookieHeader(options?.credential), + ); }); it.layer(NodeServices.layer)("server router seam", (it) => { @@ -514,11 +683,14 @@ it.layer(NodeServices.layer)("server router seam", (it) => { config: { devUrl: new URL("http://127.0.0.1:5173") }, }); - const url = yield* getHttpServerUrl("/foo/bar"); + const url = yield* getHttpServerUrl("/foo/bar?token=test-token"); const response = yield* Effect.promise(() => fetch(url, { redirect: "manual" })); assert.equal(response.status, 302); - assert.equal(response.headers.get("location"), "http://127.0.0.1:5173/"); + assert.equal( + response.headers.get("location"), + "http://127.0.0.1:5173/foo/bar?token=test-token", + ); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); @@ -540,6 +712,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const response = yield* HttpClient.get( `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, ); assert.equal(response.status, 200); @@ -560,6 +737,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const response = yield* HttpClient.get( `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`, + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, ); assert.equal(response.status, 200); @@ -567,6 +749,597 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect("serves the public environment descriptor without requiring auth", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const url = yield* getHttpServerUrl("/.well-known/t3/environment"); + const response = yield* Effect.promise(() => fetch(url)); + const body = (yield* Effect.promise(() => + response.json(), + )) as typeof testEnvironmentDescriptor; + + assert.equal(response.status, 200); + assert.deepEqual(body, testEnvironmentDescriptor); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("reports unauthenticated session state without requiring auth", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const url = yield* getHttpServerUrl("/api/auth/session"); + const response = yield* Effect.promise(() => fetch(url)); + const body = (yield* Effect.promise(() => response.json())) as { + readonly authenticated: boolean; + readonly auth: { + readonly policy: string; + readonly bootstrapMethods: ReadonlyArray; + readonly sessionMethods: ReadonlyArray; + readonly sessionCookieName: string; + }; + }; + + assert.equal(response.status, 200); + assert.equal(body.authenticated, false); + assert.equal(body.auth.policy, "desktop-managed-local"); + assert.deepEqual(body.auth.bootstrapMethods, ["desktop-bootstrap"]); + assert.deepEqual(body.auth.sessionMethods, [ + "browser-session-cookie", + "bearer-session-token", + ]); + assert.equal(body.auth.sessionCookieName, "t3_session"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("bootstraps a browser session and authenticates the session endpoint via cookie", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { + response: bootstrapResponse, + body: bootstrapBody, + cookie: setCookie, + } = yield* bootstrapBrowserSession(); + + assert.equal(bootstrapResponse.status, 200); + assert.equal(bootstrapBody.authenticated, true); + assert.equal(bootstrapBody.sessionMethod, "browser-session-cookie"); + assert.isUndefined((bootstrapBody as { readonly sessionToken?: string }).sessionToken); + assert.isDefined(setCookie); + + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* Effect.promise(() => + fetch(sessionUrl, { + headers: { + cookie: setCookie?.split(";")[0] ?? "", + }, + }), + ); + const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as { + readonly authenticated: boolean; + readonly sessionMethod?: string; + }; + + assert.equal(sessionResponse.status, 200); + assert.equal(sessionBody.authenticated, true); + assert.equal(sessionBody.sessionMethod, "browser-session-cookie"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "bootstraps a bearer session and authenticates the session endpoint via authorization header", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { response: bootstrapResponse, body: bootstrapBody } = + yield* bootstrapBearerSession(); + + assert.equal(bootstrapResponse.status, 200); + assert.equal(bootstrapBody.authenticated, true); + assert.equal(bootstrapBody.sessionMethod, "bearer-session-token"); + assert.equal(typeof bootstrapBody.sessionToken, "string"); + assert.isTrue((bootstrapBody.sessionToken?.length ?? 0) > 0); + + const sessionUrl = yield* getHttpServerUrl("/api/auth/session"); + const sessionResponse = yield* Effect.promise(() => + fetch(sessionUrl, { + headers: { + authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`, + }, + }), + ); + const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as { + readonly authenticated: boolean; + readonly sessionMethod?: string; + }; + + assert.equal(sessionResponse.status, 200); + assert.equal(sessionBody.authenticated, true); + assert.equal(sessionBody.sessionMethod, "bearer-session-token"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("issues short-lived websocket tokens for authenticated bearer sessions", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const bearerToken = yield* getAuthenticatedBearerSessionToken(); + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const wsTokenResponse = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "POST", + headers: { + authorization: `Bearer ${bearerToken}`, + }, + }), + ); + const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as { + readonly token: string; + readonly expiresAt: string; + }; + + assert.equal(wsTokenResponse.status, 200); + assert.equal(typeof wsTokenBody.token, "string"); + assert.isTrue(wsTokenBody.token.length > 0); + assert.equal(typeof wsTokenBody.expiresAt, "string"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "responds to remote auth websocket-token preflight requests with authorization CORS headers", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const response = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "OPTIONS", + headers: { + origin: "http://192.168.86.35:3773", + "access-control-request-method": "POST", + "access-control-request-headers": "authorization", + }, + }), + ); + + assert.equal(response.status, 204); + assert.equal(response.headers.get("access-control-allow-origin"), "*"); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [ + "GET", + "OPTIONS", + "POST", + ]); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [ + "authorization", + "b3", + "content-type", + "traceparent", + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("includes CORS headers on remote websocket-token auth failures", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const response = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "POST", + headers: { + origin: "http://192.168.86.35:3773", + }, + }), + ); + const body = (yield* Effect.promise(() => response.json())) as { + readonly error?: string; + }; + + assert.equal(response.status, 401); + assert.equal(response.headers.get("access-control-allow-origin"), "*"); + assert.equal(body.error, "Authentication required."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("issues authenticated one-time pairing credentials for additional clients", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const response = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }); + const body = (yield* response.json) as { + readonly credential: string; + readonly expiresAt: string; + }; + + assert.equal(response.status, 200); + assert.equal(typeof body.credential, "string"); + assert.isTrue(body.credential.length > 0); + assert.equal(typeof body.expiresAt, "string"); + + const bootstrapResult = yield* bootstrapBrowserSession(body.credential); + assert.equal(bootstrapResult.response.status, 200); + + const reusedResult = yield* bootstrapBrowserSession(body.credential); + assert.equal(reusedResult.response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects unauthenticated pairing credential requests", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const response = yield* HttpClient.post("/api/auth/pairing-token"); + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("lists and revokes pairing links for owner sessions", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const createdResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + }); + const createdBody = (yield* createdResponse.json) as { + readonly id: string; + readonly credential: string; + }; + + const listResponse = yield* HttpClient.get("/api/auth/pairing-links", { + headers: { + cookie: ownerCookie, + }, + }); + const listedLinks = (yield* listResponse.json) as ReadonlyArray<{ + readonly id: string; + readonly credential: string; + }>; + + const revokeUrl = yield* getHttpServerUrl("/api/auth/pairing-links/revoke"); + const revokeResponse = yield* Effect.promise(() => + fetch(revokeUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: JSON.stringify({ id: createdBody.id }), + }), + ); + const revokedBootstrap = yield* bootstrapBrowserSession(createdBody.credential); + + assert.equal(createdResponse.status, 200); + assert.equal(listResponse.status, 200); + assert.isTrue(listedLinks.some((entry) => entry.id === createdBody.id)); + assert.equal(revokeResponse.status, 200); + assert.equal(revokedBootstrap.response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects pairing credential requests from non-owner paired sessions", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }); + const ownerBody = (yield* ownerResponse.json) as { + readonly credential: string; + }; + assert.equal(ownerResponse.status, 200); + + const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader(ownerBody.credential); + const pairedResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: pairedSessionCookie, + }, + }); + const pairedBody = (yield* pairedResponse.json) as { + readonly error: string; + }; + + assert.equal(pairedResponse.status, 403); + assert.equal(pairedBody.error, "Only owner sessions can create pairing credentials."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("lists paired clients and revokes other sessions while keeping the owner", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const pairingTokenUrl = yield* getHttpServerUrl("/api/auth/pairing-token"); + const ownerPairingResponse = yield* Effect.promise(() => + fetch(pairingTokenUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: JSON.stringify({ + label: "Julius iPhone", + }), + }), + ); + const ownerPairingBody = (yield* Effect.promise(() => ownerPairingResponse.json())) as { + readonly credential: string; + readonly label?: string; + }; + assert.equal(ownerPairingResponse.status, 200); + const pairedSessionBootstrap = yield* bootstrapBrowserSession(ownerPairingBody.credential, { + headers: { + "user-agent": + "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Mobile/15E148 Safari/604.1", + }, + }); + const pairedSessionCookie = pairedSessionBootstrap.cookie?.split(";")[0]; + assert.isDefined(pairedSessionCookie); + + const pairedSessionCookieHeader = pairedSessionCookie ?? ""; + const listClientsUrl = yield* getHttpServerUrl("/api/auth/clients"); + const listBeforeResponse = yield* Effect.promise(() => + fetch(listClientsUrl, { + headers: { + cookie: ownerCookie, + }, + }), + ); + const clientsBefore = (yield* Effect.promise(() => + listBeforeResponse.json(), + )) as ReadonlyArray<{ + readonly sessionId: string; + readonly current: boolean; + readonly client: { + readonly label?: string; + readonly deviceType: string; + readonly ipAddress?: string; + readonly os?: string; + readonly browser?: string; + }; + }>; + const pairedClientBefore = clientsBefore.find((entry) => !entry.current); + const pairedSessionId = clientsBefore.find((entry) => !entry.current)?.sessionId; + + const revokeOthersResponse = yield* HttpClient.post("/api/auth/clients/revoke-others", { + headers: { + cookie: ownerCookie, + }, + }); + const revokeOthersBody = (yield* revokeOthersResponse.json) as { + readonly revokedCount: number; + }; + + const listAfterResponse = yield* HttpClient.get("/api/auth/clients", { + headers: { + cookie: ownerCookie, + }, + }); + const clientsAfter = (yield* listAfterResponse.json) as ReadonlyArray<{ + readonly sessionId: string; + readonly current: boolean; + }>; + + const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: pairedSessionCookieHeader, + }, + }); + const pairedClientPairingBody = (yield* pairedClientPairingResponse.json) as { + readonly error: string; + }; + + assert.equal(listBeforeResponse.status, 200); + assert.equal(ownerPairingBody.label, "Julius iPhone"); + assert.lengthOf(clientsBefore, 2); + assert.isDefined(pairedSessionId); + assert.isDefined(pairedClientBefore); + assert.deepInclude(pairedClientBefore?.client, { + label: "Julius iPhone", + deviceType: "mobile", + os: "iOS", + browser: "Safari", + ipAddress: "127.0.0.1", + }); + assert.equal(revokeOthersResponse.status, 200); + assert.equal(revokeOthersBody.revokedCount, 1); + assert.equal(listAfterResponse.status, 200); + assert.lengthOf(clientsAfter, 1); + assert.equal(clientsAfter[0]?.current, true); + assert.equal(pairedClientPairingResponse.status, 401); + assert.equal(pairedClientPairingBody.error, "Unauthorized request."); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("revokes an individual paired client session", () => + Effect.gen(function* () { + yield* buildAppUnderTest({ + config: { + host: "0.0.0.0", + }, + }); + + const ownerCookie = yield* getAuthenticatedSessionCookieHeader(); + const pairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: ownerCookie, + }, + }); + const pairingBody = (yield* pairingResponse.json) as { + readonly credential: string; + }; + const pairedSessionCookie = yield* getAuthenticatedSessionCookieHeader( + pairingBody.credential, + ); + + const clientsResponse = yield* HttpClient.get("/api/auth/clients", { + headers: { + cookie: ownerCookie, + }, + }); + const clients = (yield* clientsResponse.json) as ReadonlyArray<{ + readonly sessionId: string; + readonly current: boolean; + }>; + const pairedSessionId = clients.find((entry) => !entry.current)?.sessionId; + assert.isDefined(pairedSessionId); + + const revokeUrl = yield* getHttpServerUrl("/api/auth/clients/revoke"); + const revokeResponse = yield* Effect.promise(() => + fetch(revokeUrl, { + method: "POST", + headers: { + cookie: ownerCookie, + "content-type": "application/json", + }, + body: JSON.stringify({ sessionId: pairedSessionId }), + }), + ); + const pairedClientPairingResponse = yield* HttpClient.post("/api/auth/pairing-token", { + headers: { + cookie: pairedSessionCookie, + }, + }); + + assert.equal(revokeResponse.status, 200); + assert.equal(pairedClientPairingResponse.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("rejects reusing the same bootstrap credential after it has been exchanged", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const first = yield* bootstrapBrowserSession(); + const second = yield* bootstrapBrowserSession(); + + assert.equal(first.response.status, 200); + assert.equal(second.response.status, 401); + assert.equal( + (second.body as { readonly error?: string }).error, + "Invalid bootstrap credential.", + ); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "does not accept session tokens via query parameters on authenticated HTTP routes", + () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const projectDir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3-router-project-favicon-query-token-", + }); + + yield* buildAppUnderTest(); + + const { cookie } = yield* bootstrapBrowserSession(); + assert.isDefined(cookie); + const sessionToken = extractSessionTokenFromSetCookie(cookie ?? ""); + + const response = yield* HttpClient.get( + `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}&token=${encodeURIComponent(sessionToken)}`, + ); + + assert.equal(response.status, 401); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect("accepts websocket rpc handshake with a bootstrapped browser session cookie", () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { response: bootstrapResponse, cookie } = yield* bootstrapBrowserSession(); + + assert.equal(bootstrapResponse.status, 200); + assert.isDefined(cookie); + + const wsUrl = appendSessionCookieToWsUrl( + yield* getWsServerUrl("/ws", { authenticated: false }), + cookie?.split(";")[0] ?? "", + ); + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), + ); + + assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); + assert.equal(response.auth.policy, "desktop-managed-local"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "rejects websocket rpc handshake when a session token is only provided via query string", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const { cookie } = yield* bootstrapBrowserSession(); + assert.isDefined(cookie); + const sessionToken = extractSessionTokenFromSetCookie(cookie ?? ""); + const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?token=${encodeURIComponent(sessionToken)}`; + + const error = yield* Effect.flip( + Effect.scoped(withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({}))), + ); + + assert.equal(error._tag, "RpcClientError"); + assertInclude(String(error), "401"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + + it.effect( + "accepts websocket rpc handshake with a dedicated websocket token in the query string", + () => + Effect.gen(function* () { + yield* buildAppUnderTest(); + + const bearerToken = yield* getAuthenticatedBearerSessionToken(); + const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token"); + const wsTokenResponse = yield* Effect.promise(() => + fetch(wsTokenUrl, { + method: "POST", + headers: { + authorization: `Bearer ${bearerToken}`, + }, + }), + ); + const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as { + readonly token: string; + }; + const wsUrl = `${yield* getWsServerUrl("/ws", { authenticated: false })}?wsToken=${encodeURIComponent(wsTokenBody.token)}`; + + const response = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.serverGetConfig]({})), + ); + + assert.equal(response.environment.environmentId, testEnvironmentDescriptor.environmentId); + assert.equal(response.auth.policy, "desktop-managed-local"); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("serves attachment files from state dir", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; @@ -583,7 +1356,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => { yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }); yield* fileSystem.writeFileString(attachmentPath, "attachment-ok"); - const response = yield* HttpClient.get(`/attachments/${attachmentId}`); + const response = yield* HttpClient.get(`/attachments/${attachmentId}`, { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }); assert.equal(response.status, 200); assert.equal(yield* response.text, "attachment-ok"); }).pipe(Effect.provide(NodeHttpServer.layerTest)), @@ -606,6 +1383,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const response = yield* HttpClient.get( "/attachments/thread%20folder/message%20folder/file%20name.png", + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, ); assert.equal(response.status, 200); assert.equal(yield* response.text, "attachment-encoded-ok"); @@ -742,6 +1524,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const response = yield* HttpClient.post("/api/observability/v1/traces", { headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), "content-type": "application/json", origin: "http://localhost:5733", }, @@ -815,8 +1598,17 @@ it.layer(NodeServices.layer)("server router seam", (it) => { assert.equal(response.status, 204); assert.equal(response.headers.get("access-control-allow-origin"), "*"); - assert.equal(response.headers.get("access-control-allow-methods"), "POST, OPTIONS"); - assert.equal(response.headers.get("access-control-allow-headers"), "content-type"); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [ + "GET", + "OPTIONS", + "POST", + ]); + assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [ + "authorization", + "b3", + "content-type", + "traceparent", + ]); }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); @@ -850,6 +1642,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const response = yield* HttpClient.post("/api/observability/v1/traces", { headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), "content-type": "application/json", }, body: HttpBody.text(JSON.stringify(payload), "application/json"), @@ -897,6 +1690,11 @@ it.layer(NodeServices.layer)("server router seam", (it) => { const response = yield* HttpClient.get( "/attachments/missing-11111111-1111-4111-8111-111111111111", + { + headers: { + cookie: yield* getAuthenticatedSessionCookieHeader(), + }, + }, ); assert.equal(response.status, 404); }).pipe(Effect.provide(NodeHttpServer.layerTest)), @@ -938,7 +1736,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - it.effect("rejects websocket rpc handshake when auth token is missing", () => + it.effect("rejects websocket rpc handshake when session authentication is missing", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -948,13 +1746,9 @@ it.layer(NodeServices.layer)("server router seam", (it) => { "export const needle = 1;", ); - yield* buildAppUnderTest({ - config: { - authToken: "secret-token", - }, - }); + yield* buildAppUnderTest(); - const wsUrl = yield* getWsServerUrl("/ws"); + const wsUrl = yield* getWsServerUrl("/ws", { authenticated: false }); const result = yield* Effect.scoped( withWsRpcClient(wsUrl, (client) => client[WS_METHODS.projectsSearchEntries]({ @@ -970,38 +1764,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); - it.effect("accepts websocket rpc handshake when auth token is provided", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const workspaceDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-ws-auth-ok-" }); - yield* fs.writeFileString( - path.join(workspaceDir, "needle-file.ts"), - "export const needle = 1;", - ); - - yield* buildAppUnderTest({ - config: { - authToken: "secret-token", - }, - }); - - const wsUrl = yield* getWsServerUrl("/ws?token=secret-token"); - const response = yield* Effect.scoped( - withWsRpcClient(wsUrl, (client) => - client[WS_METHODS.projectsSearchEntries]({ - cwd: workspaceDir, - query: "needle", - limit: 10, - }), - ), - ); - - assert.isAtLeast(response.entries.length, 1); - assert.equal(response.truncated, false); - }).pipe(Effect.provide(NodeHttpServer.layerTest)), - ); - it.effect("routes websocket rpc subscribeServerConfig streams snapshot then update", () => Effect.gen(function* () { const providers = [] as const; diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d706d79b44..c1581b9382 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -6,7 +6,9 @@ import { attachmentsRouteLayer, otlpTracesProxyRouteLayer, projectFaviconRouteLayer, + serverEnvironmentRouteLayer, staticAndDevRouteLayer, + browserApiCorsLayer, } from "./http"; import { fixPath } from "./os-jank"; import { websocketRpcRouteLayer } from "./ws"; @@ -51,6 +53,20 @@ import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths"; import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner"; import { ObservabilityLive } from "./observability/Layers/Observability"; import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment"; +import { + authBearerBootstrapRouteLayer, + authBootstrapRouteLayer, + authClientsRevokeOthersRouteLayer, + authClientsRevokeRouteLayer, + authClientsRouteLayer, + authPairingLinksRevokeRouteLayer, + authPairingLinksRouteLayer, + authPairingCredentialRouteLayer, + authSessionRouteLayer, + authWebSocketTokenRouteLayer, +} from "./auth/http"; +import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore"; +import { ServerAuthLive } from "./auth/Layers/ServerAuth"; const PtyAdapterLive = Layer.unwrap( Effect.gen(function* () { @@ -188,6 +204,11 @@ const WorkspaceLayerLive = Layer.mergeAll( ), ); +const AuthLayerLive = ServerAuthLive.pipe( + Layer.provideMerge(PersistenceLayerLive), + Layer.provide(ServerSecretStoreLive), +); + const RuntimeDependenciesLive = ReactorLayerLive.pipe( // Core Services Layer.provideMerge(CheckpointingLayerLive), @@ -203,6 +224,7 @@ const RuntimeDependenciesLive = ReactorLayerLive.pipe( Layer.provideMerge(ProjectFaviconResolverLive), Layer.provideMerge(RepositoryIdentityResolverLive), Layer.provideMerge(ServerEnvironmentLive), + Layer.provideMerge(AuthLayerLive), // Misc. Layer.provideMerge(AnalyticsServiceLayerLive), @@ -215,12 +237,23 @@ const RuntimeServicesLive = ServerRuntimeStartupLive.pipe( ); export const makeRoutesLayer = Layer.mergeAll( + authBearerBootstrapRouteLayer, + authBootstrapRouteLayer, + authClientsRevokeOthersRouteLayer, + authClientsRevokeRouteLayer, + authClientsRouteLayer, + authPairingLinksRevokeRouteLayer, + authPairingLinksRouteLayer, + authPairingCredentialRouteLayer, + authSessionRouteLayer, + authWebSocketTokenRouteLayer, attachmentsRouteLayer, otlpTracesProxyRouteLayer, projectFaviconRouteLayer, + serverEnvironmentRouteLayer, staticAndDevRouteLayer, websocketRpcRouteLayer, -); +).pipe(Layer.provide(browserApiCorsLayer)); export const makeServerLayer = Layer.unwrap( Effect.gen(function* () { diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.ts index fc06d77566..c3159cc9d8 100644 --- a/apps/server/src/serverRuntimeStartup.test.ts +++ b/apps/server/src/serverRuntimeStartup.test.ts @@ -1,14 +1,23 @@ +import { DEFAULT_MODEL_BY_PROVIDER } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import { Deferred, Effect, Fiber, Option, Ref } from "effect"; import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts"; import { + getAutoBootstrapDefaultModelSelection, launchStartupHeartbeat, makeCommandGate, ServerRuntimeStartupError, } from "./serverRuntimeStartup.ts"; +it("uses the canonical Codex default for auto-bootstrapped model selection", () => { + assert.deepStrictEqual(getAutoBootstrapDefaultModelSelection(), { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }); +}); + it.effect("enqueueCommand waits for readiness and then drains queued work", () => Effect.scoped( Effect.gen(function* () { diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.ts index e94c322225..fd43c6b359 100644 --- a/apps/server/src/serverRuntimeStartup.ts +++ b/apps/server/src/serverRuntimeStartup.ts @@ -1,5 +1,6 @@ import { CommandId, + DEFAULT_MODEL_BY_PROVIDER, DEFAULT_PROVIDER_INTERACTION_MODE, type ModelSelection, ProjectId, @@ -29,6 +30,7 @@ import { ServerLifecycleEvents } from "./serverLifecycleEvents"; import { ServerSettingsService } from "./serverSettings"; import { ServerEnvironment } from "./environment/Services/ServerEnvironment"; import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; +import { ServerAuth } from "./auth/Services/ServerAuth"; const isWildcardHost = (host: string | undefined): boolean => host === "0.0.0.0" || host === "::" || host === "[::]"; @@ -149,6 +151,11 @@ export const launchStartupHeartbeat = recordStartupHeartbeat.pipe( Effect.asVoid, ); +export const getAutoBootstrapDefaultModelSelection = (): ModelSelection => ({ + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, +}); + const autoBootstrapWelcome = Effect.gen(function* () { const serverConfig = yield* ServerConfig; const projectionReadModelQuery = yield* ProjectionSnapshotQuery; @@ -170,10 +177,7 @@ const autoBootstrapWelcome = Effect.gen(function* () { const createdAt = new Date().toISOString(); nextProjectId = ProjectId.makeUnsafe(crypto.randomUUID()); const bootstrapProjectTitle = path.basename(serverConfig.cwd) || "project"; - nextProjectDefaultModelSelection = { - provider: "codex", - model: "gpt-5-codex", - }; + nextProjectDefaultModelSelection = getAutoBootstrapDefaultModelSelection(); yield* orchestrationEngine.dispatch({ type: "project.create", commandId: CommandId.makeUnsafe(crypto.randomUUID()), @@ -185,10 +189,8 @@ const autoBootstrapWelcome = Effect.gen(function* () { }); } else { nextProjectId = existingProject.value.id; - nextProjectDefaultModelSelection = existingProject.value.defaultModelSelection ?? { - provider: "codex", - model: "gpt-5-codex", - }; + nextProjectDefaultModelSelection = + existingProject.value.defaultModelSelection ?? getAutoBootstrapDefaultModelSelection(); } const existingThreadId = @@ -229,28 +231,39 @@ const autoBootstrapWelcome = Effect.gen(function* () { } as const; }); -const maybeOpenBrowser = Effect.gen(function* () { +const resolveStartupBrowserTarget = Effect.gen(function* () { const serverConfig = yield* ServerConfig; - if (serverConfig.noBrowser) { - return; - } - const { openBrowser } = yield* Open; + const serverAuth = yield* ServerAuth; const localUrl = `http://localhost:${serverConfig.port}`; const bindUrl = serverConfig.host && !isWildcardHost(serverConfig.host) ? `http://${formatHostForUrl(serverConfig.host)}:${serverConfig.port}` : localUrl; - const target = serverConfig.devUrl?.toString() ?? bindUrl; - - yield* openBrowser(target).pipe( - Effect.catch(() => - Effect.logInfo("browser auto-open unavailable", { - hint: `Open ${target} in your browser.`, - }), + const baseTarget = serverConfig.devUrl?.toString() ?? bindUrl; + return yield* Effect.succeed(serverConfig.mode === "desktop" ? baseTarget : undefined).pipe( + Effect.flatMap((target) => + target ? Effect.succeed(target) : serverAuth.issueStartupPairingUrl(baseTarget), ), ); }); +const maybeOpenBrowser = (target: string) => + Effect.gen(function* () { + const serverConfig = yield* ServerConfig; + if (serverConfig.noBrowser) { + return; + } + const { openBrowser } = yield* Open; + + yield* openBrowser(target).pipe( + Effect.catch(() => + Effect.logInfo("browser auto-open unavailable", { + hint: `Open ${target} in your browser.`, + }), + ), + ); + }); + const runStartupPhase = (phase: string, effect: Effect.Effect) => effect.pipe( Effect.annotateSpans({ "startup.phase": phase }), @@ -371,7 +384,13 @@ const makeServerRuntimeStartup = Effect.gen(function* () { yield* Effect.logDebug("startup phase: recording startup heartbeat"); yield* launchStartupHeartbeat; yield* Effect.logDebug("startup phase: browser open check"); - yield* runStartupPhase("browser.open", maybeOpenBrowser); + const startupBrowserTarget = yield* resolveStartupBrowserTarget; + if (serverConfig.mode !== "desktop") { + yield* Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe( + Effect.annotateLogs({ pairingUrl: startupBrowserTarget }), + ); + } + yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget)); yield* Effect.logDebug("startup phase: complete"); }), ); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 16e8531386..8d4f946691 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1,5 +1,7 @@ -import { Cause, Effect, Layer, Option, Queue, Ref, Schema, Stream } from "effect"; +import { Cause, Effect, Layer, Queue, Ref, Schema, Stream } from "effect"; import { + type AuthAccessStreamEvent, + AuthSessionId, CommandId, EventId, type OrchestrationCommand, @@ -20,7 +22,7 @@ import { WsRpcGroup, } from "@t3tools/contracts"; import { clamp } from "effect/Number"; -import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http"; +import { HttpRouter, HttpServerRequest } from "effect/unstable/http"; import { RpcSerialization, RpcServer } from "effect/unstable/rpc"; import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery"; @@ -49,791 +51,894 @@ import { WorkspacePathOutsideRootError } from "./workspace/Services/WorkspacePat import { ProjectSetupScriptRunner } from "./project/Services/ProjectSetupScriptRunner"; import { RepositoryIdentityResolver } from "./project/Services/RepositoryIdentityResolver"; import { ServerEnvironment } from "./environment/Services/ServerEnvironment"; +import { ServerAuth } from "./auth/Services/ServerAuth"; +import { + BootstrapCredentialService, + type BootstrapCredentialChange, +} from "./auth/Services/BootstrapCredentialService"; +import { + SessionCredentialService, + type SessionCredentialChange, +} from "./auth/Services/SessionCredentialService"; +import { respondToAuthError } from "./auth/http"; -const WsRpcLayer = WsRpcGroup.toLayer( - Effect.gen(function* () { - const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; - const orchestrationEngine = yield* OrchestrationEngineService; - const checkpointDiffQuery = yield* CheckpointDiffQuery; - const keybindings = yield* Keybindings; - const open = yield* Open; - const gitManager = yield* GitManager; - const git = yield* GitCore; - const gitStatusBroadcaster = yield* GitStatusBroadcaster; - const terminalManager = yield* TerminalManager; - const providerRegistry = yield* ProviderRegistry; - const config = yield* ServerConfig; - const lifecycleEvents = yield* ServerLifecycleEvents; - const serverSettings = yield* ServerSettingsService; - const startup = yield* ServerRuntimeStartup; - const workspaceEntries = yield* WorkspaceEntries; - const workspaceFileSystem = yield* WorkspaceFileSystem; - const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; - const repositoryIdentityResolver = yield* RepositoryIdentityResolver; - const serverEnvironment = yield* ServerEnvironment; - const serverCommandId = (tag: string) => - CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); - - const appendSetupScriptActivity = (input: { - readonly threadId: ThreadId; - readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; - readonly summary: string; - readonly createdAt: string; - readonly payload: Record; - readonly tone: "info" | "error"; - }) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId: serverCommandId("setup-script-activity"), - threadId: input.threadId, - activity: { - id: EventId.makeUnsafe(crypto.randomUUID()), - tone: input.tone, - kind: input.kind, - summary: input.summary, - payload: input.payload, - turnId: null, - createdAt: input.createdAt, +function toAuthAccessStreamEvent( + change: BootstrapCredentialChange | SessionCredentialChange, + revision: number, + currentSessionId: AuthSessionId, +): AuthAccessStreamEvent { + switch (change.type) { + case "pairingLinkUpserted": + return { + version: 1, + revision, + type: "pairingLinkUpserted", + payload: change.pairingLink, + }; + case "pairingLinkRemoved": + return { + version: 1, + revision, + type: "pairingLinkRemoved", + payload: { id: change.id }, + }; + case "clientUpserted": + return { + version: 1, + revision, + type: "clientUpserted", + payload: { + ...change.clientSession, + current: change.clientSession.sessionId === currentSessionId, }, - createdAt: input.createdAt, - }); + }; + case "clientRemoved": + return { + version: 1, + revision, + type: "clientRemoved", + payload: { sessionId: change.sessionId }, + }; + } +} - const toDispatchCommandError = (cause: unknown, fallbackMessage: string) => - Schema.is(OrchestrationDispatchCommandError)(cause) - ? cause - : new OrchestrationDispatchCommandError({ - message: cause instanceof Error ? cause.message : fallbackMessage, - cause, - }); +const makeWsRpcLayer = (currentSessionId: AuthSessionId) => + WsRpcGroup.toLayer( + Effect.gen(function* () { + const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; + const orchestrationEngine = yield* OrchestrationEngineService; + const checkpointDiffQuery = yield* CheckpointDiffQuery; + const keybindings = yield* Keybindings; + const open = yield* Open; + const gitManager = yield* GitManager; + const git = yield* GitCore; + const gitStatusBroadcaster = yield* GitStatusBroadcaster; + const terminalManager = yield* TerminalManager; + const providerRegistry = yield* ProviderRegistry; + const config = yield* ServerConfig; + const lifecycleEvents = yield* ServerLifecycleEvents; + const serverSettings = yield* ServerSettingsService; + const startup = yield* ServerRuntimeStartup; + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + const projectSetupScriptRunner = yield* ProjectSetupScriptRunner; + const repositoryIdentityResolver = yield* RepositoryIdentityResolver; + const serverEnvironment = yield* ServerEnvironment; + const serverAuth = yield* ServerAuth; + const bootstrapCredentials = yield* BootstrapCredentialService; + const sessions = yield* SessionCredentialService; + const serverCommandId = (tag: string) => + CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`); - const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause) => { - const error = Cause.squash(cause); - return Schema.is(OrchestrationDispatchCommandError)(error) - ? error - : new OrchestrationDispatchCommandError({ - message: - error instanceof Error ? error.message : "Failed to bootstrap thread turn start.", - cause, - }); - }; - - const enrichProjectEvent = ( - event: OrchestrationEvent, - ): Effect.Effect => { - switch (event.type) { - case "project.created": - return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe( - Effect.map((repositoryIdentity) => ({ - ...event, - payload: { - ...event.payload, - repositoryIdentity, - }, - })), - ); - case "project.meta-updated": - return Effect.gen(function* () { - const workspaceRoot = - event.payload.workspaceRoot ?? - (yield* orchestrationEngine.getReadModel()).projects.find( - (project) => project.id === event.payload.projectId, - )?.workspaceRoot ?? - null; - if (workspaceRoot === null) { - return event; - } + const loadAuthAccessSnapshot = () => + Effect.all({ + pairingLinks: serverAuth.listPairingLinks().pipe(Effect.orDie), + clientSessions: serverAuth.listClientSessions(currentSessionId).pipe(Effect.orDie), + }); - const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot); - return { - ...event, - payload: { - ...event.payload, - repositoryIdentity, - }, - } satisfies OrchestrationEvent; - }); - default: - return Effect.succeed(event); - } - }; + const appendSetupScriptActivity = (input: { + readonly threadId: ThreadId; + readonly kind: "setup-script.requested" | "setup-script.started" | "setup-script.failed"; + readonly summary: string; + readonly createdAt: string; + readonly payload: Record; + readonly tone: "info" | "error"; + }) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: serverCommandId("setup-script-activity"), + threadId: input.threadId, + activity: { + id: EventId.makeUnsafe(crypto.randomUUID()), + tone: input.tone, + kind: input.kind, + summary: input.summary, + payload: input.payload, + turnId: null, + createdAt: input.createdAt, + }, + createdAt: input.createdAt, + }); - const enrichOrchestrationEvents = (events: ReadonlyArray) => - Effect.forEach(events, enrichProjectEvent, { concurrency: 4 }); + const toDispatchCommandError = (cause: unknown, fallbackMessage: string) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: cause instanceof Error ? cause.message : fallbackMessage, + cause, + }); - const dispatchBootstrapTurnStart = ( - command: Extract, - ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => - Effect.gen(function* () { - const bootstrap = command.bootstrap; - const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command; - let createdThread = false; - let targetProjectId = bootstrap?.createThread?.projectId; - let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd; - let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null; - - const cleanupCreatedThread = () => - createdThread - ? orchestrationEngine - .dispatch({ - type: "thread.delete", - commandId: serverCommandId("bootstrap-thread-delete"), - threadId: command.threadId, - }) - .pipe(Effect.ignoreCause({ log: true })) - : Effect.void; - - const recordSetupScriptLaunchFailure = (input: { - readonly error: unknown; - readonly requestedAt: string; - readonly worktreePath: string; - }) => { - const detail = - input.error instanceof Error ? input.error.message : "Unknown setup failure."; - return appendSetupScriptActivity({ - threadId: command.threadId, - kind: "setup-script.failed", - summary: "Setup script failed to start", - createdAt: input.requestedAt, - payload: { - detail, - worktreePath: input.worktreePath, - }, - tone: "error", - }).pipe( - Effect.ignoreCause({ log: false }), - Effect.flatMap(() => - Effect.logWarning("bootstrap turn start failed to launch setup script", { - threadId: command.threadId, - worktreePath: input.worktreePath, - detail, - }), - ), - ); - }; + const toBootstrapDispatchCommandCauseError = (cause: Cause.Cause) => { + const error = Cause.squash(cause); + return Schema.is(OrchestrationDispatchCommandError)(error) + ? error + : new OrchestrationDispatchCommandError({ + message: + error instanceof Error ? error.message : "Failed to bootstrap thread turn start.", + cause, + }); + }; - const recordSetupScriptStarted = (input: { - readonly requestedAt: string; - readonly worktreePath: string; - readonly scriptId: string; - readonly scriptName: string; - readonly terminalId: string; - }) => { - const payload = { - scriptId: input.scriptId, - scriptName: input.scriptName, - terminalId: input.terminalId, - worktreePath: input.worktreePath, - }; - return Effect.all([ - appendSetupScriptActivity({ + const enrichProjectEvent = ( + event: OrchestrationEvent, + ): Effect.Effect => { + switch (event.type) { + case "project.created": + return repositoryIdentityResolver.resolve(event.payload.workspaceRoot).pipe( + Effect.map((repositoryIdentity) => ({ + ...event, + payload: { + ...event.payload, + repositoryIdentity, + }, + })), + ); + case "project.meta-updated": + return Effect.gen(function* () { + const workspaceRoot = + event.payload.workspaceRoot ?? + (yield* orchestrationEngine.getReadModel()).projects.find( + (project) => project.id === event.payload.projectId, + )?.workspaceRoot ?? + null; + if (workspaceRoot === null) { + return event; + } + + const repositoryIdentity = yield* repositoryIdentityResolver.resolve(workspaceRoot); + return { + ...event, + payload: { + ...event.payload, + repositoryIdentity, + }, + } satisfies OrchestrationEvent; + }); + default: + return Effect.succeed(event); + } + }; + + const enrichOrchestrationEvents = (events: ReadonlyArray) => + Effect.forEach(events, enrichProjectEvent, { concurrency: 4 }); + + const dispatchBootstrapTurnStart = ( + command: Extract, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => + Effect.gen(function* () { + const bootstrap = command.bootstrap; + const { bootstrap: _bootstrap, ...finalTurnStartCommand } = command; + let createdThread = false; + let targetProjectId = bootstrap?.createThread?.projectId; + let targetProjectCwd = bootstrap?.prepareWorktree?.projectCwd; + let targetWorktreePath = bootstrap?.createThread?.worktreePath ?? null; + + const cleanupCreatedThread = () => + createdThread + ? orchestrationEngine + .dispatch({ + type: "thread.delete", + commandId: serverCommandId("bootstrap-thread-delete"), + threadId: command.threadId, + }) + .pipe(Effect.ignoreCause({ log: true })) + : Effect.void; + + const recordSetupScriptLaunchFailure = (input: { + readonly error: unknown; + readonly requestedAt: string; + readonly worktreePath: string; + }) => { + const detail = + input.error instanceof Error ? input.error.message : "Unknown setup failure."; + return appendSetupScriptActivity({ threadId: command.threadId, - kind: "setup-script.requested", - summary: "Starting setup script", + kind: "setup-script.failed", + summary: "Setup script failed to start", createdAt: input.requestedAt, - payload, - tone: "info", - }), - appendSetupScriptActivity({ - threadId: command.threadId, - kind: "setup-script.started", - summary: "Setup script started", - createdAt: new Date().toISOString(), - payload, - tone: "info", - }), - ]).pipe( - Effect.asVoid, - Effect.catch((error) => - Effect.logWarning( - "bootstrap turn start launched setup script but failed to record setup activity", - { + payload: { + detail, + worktreePath: input.worktreePath, + }, + tone: "error", + }).pipe( + Effect.ignoreCause({ log: false }), + Effect.flatMap(() => + Effect.logWarning("bootstrap turn start failed to launch setup script", { threadId: command.threadId, worktreePath: input.worktreePath, - scriptId: input.scriptId, - terminalId: input.terminalId, - detail: - error instanceof Error - ? error.message - : "Unknown setup activity dispatch failure.", - }, + detail, + }), ), - ), - ); - }; + ); + }; - const runSetupProgram = () => - bootstrap?.runSetupScript && targetWorktreePath - ? (() => { - const worktreePath = targetWorktreePath; - const requestedAt = new Date().toISOString(); - return projectSetupScriptRunner - .runForThread({ + const recordSetupScriptStarted = (input: { + readonly requestedAt: string; + readonly worktreePath: string; + readonly scriptId: string; + readonly scriptName: string; + readonly terminalId: string; + }) => { + const payload = { + scriptId: input.scriptId, + scriptName: input.scriptName, + terminalId: input.terminalId, + worktreePath: input.worktreePath, + }; + return Effect.all([ + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.requested", + summary: "Starting setup script", + createdAt: input.requestedAt, + payload, + tone: "info", + }), + appendSetupScriptActivity({ + threadId: command.threadId, + kind: "setup-script.started", + summary: "Setup script started", + createdAt: new Date().toISOString(), + payload, + tone: "info", + }), + ]).pipe( + Effect.asVoid, + Effect.catch((error) => + Effect.logWarning( + "bootstrap turn start launched setup script but failed to record setup activity", + { threadId: command.threadId, - ...(targetProjectId ? { projectId: targetProjectId } : {}), - ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}), - worktreePath, - }) - .pipe( - Effect.matchEffect({ - onFailure: (error) => - recordSetupScriptLaunchFailure({ - error, - requestedAt, - worktreePath, - }), - onSuccess: (setupResult) => { - if (setupResult.status !== "started") { - return Effect.void; - } - return recordSetupScriptStarted({ - requestedAt, - worktreePath, - scriptId: setupResult.scriptId, - scriptName: setupResult.scriptName, - terminalId: setupResult.terminalId, - }); - }, - }), - ); - })() - : Effect.void; - - const bootstrapProgram = Effect.gen(function* () { - if (bootstrap?.createThread) { - yield* orchestrationEngine.dispatch({ - type: "thread.create", - commandId: serverCommandId("bootstrap-thread-create"), - threadId: command.threadId, - projectId: bootstrap.createThread.projectId, - title: bootstrap.createThread.title, - modelSelection: bootstrap.createThread.modelSelection, - runtimeMode: bootstrap.createThread.runtimeMode, - interactionMode: bootstrap.createThread.interactionMode, - branch: bootstrap.createThread.branch, - worktreePath: bootstrap.createThread.worktreePath, - createdAt: bootstrap.createThread.createdAt, - }); - createdThread = true; - } - - if (bootstrap?.prepareWorktree) { - const worktree = yield* git.createWorktree({ - cwd: bootstrap.prepareWorktree.projectCwd, - branch: bootstrap.prepareWorktree.baseBranch, - newBranch: bootstrap.prepareWorktree.branch, - path: null, - }); - targetWorktreePath = worktree.worktree.path; - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: serverCommandId("bootstrap-thread-meta-update"), - threadId: command.threadId, - branch: worktree.worktree.branch, - worktreePath: targetWorktreePath, - }); - } + worktreePath: input.worktreePath, + scriptId: input.scriptId, + terminalId: input.terminalId, + detail: + error instanceof Error + ? error.message + : "Unknown setup activity dispatch failure.", + }, + ), + ), + ); + }; - yield* runSetupProgram(); + const runSetupProgram = () => + bootstrap?.runSetupScript && targetWorktreePath + ? (() => { + const worktreePath = targetWorktreePath; + const requestedAt = new Date().toISOString(); + return projectSetupScriptRunner + .runForThread({ + threadId: command.threadId, + ...(targetProjectId ? { projectId: targetProjectId } : {}), + ...(targetProjectCwd ? { projectCwd: targetProjectCwd } : {}), + worktreePath, + }) + .pipe( + Effect.matchEffect({ + onFailure: (error) => + recordSetupScriptLaunchFailure({ + error, + requestedAt, + worktreePath, + }), + onSuccess: (setupResult) => { + if (setupResult.status !== "started") { + return Effect.void; + } + return recordSetupScriptStarted({ + requestedAt, + worktreePath, + scriptId: setupResult.scriptId, + scriptName: setupResult.scriptName, + terminalId: setupResult.terminalId, + }); + }, + }), + ); + })() + : Effect.void; - return yield* orchestrationEngine.dispatch(finalTurnStartCommand); - }); + const bootstrapProgram = Effect.gen(function* () { + if (bootstrap?.createThread) { + yield* orchestrationEngine.dispatch({ + type: "thread.create", + commandId: serverCommandId("bootstrap-thread-create"), + threadId: command.threadId, + projectId: bootstrap.createThread.projectId, + title: bootstrap.createThread.title, + modelSelection: bootstrap.createThread.modelSelection, + runtimeMode: bootstrap.createThread.runtimeMode, + interactionMode: bootstrap.createThread.interactionMode, + branch: bootstrap.createThread.branch, + worktreePath: bootstrap.createThread.worktreePath, + createdAt: bootstrap.createThread.createdAt, + }); + createdThread = true; + } - return yield* bootstrapProgram.pipe( - Effect.catchCause((cause) => { - const dispatchError = toBootstrapDispatchCommandCauseError(cause); - if (Cause.hasInterruptsOnly(cause)) { - return Effect.fail(dispatchError); + if (bootstrap?.prepareWorktree) { + const worktree = yield* git.createWorktree({ + cwd: bootstrap.prepareWorktree.projectCwd, + branch: bootstrap.prepareWorktree.baseBranch, + newBranch: bootstrap.prepareWorktree.branch, + path: null, + }); + targetWorktreePath = worktree.worktree.path; + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("bootstrap-thread-meta-update"), + threadId: command.threadId, + branch: worktree.worktree.branch, + worktreePath: targetWorktreePath, + }); } - return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError))); - }), - ); - }); - const dispatchNormalizedCommand = ( - normalizedCommand: OrchestrationCommand, - ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => { - const dispatchEffect = - normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap - ? dispatchBootstrapTurnStart(normalizedCommand) - : orchestrationEngine - .dispatch(normalizedCommand) - .pipe( - Effect.mapError((cause) => - toDispatchCommandError(cause, "Failed to dispatch orchestration command"), - ), - ); + yield* runSetupProgram(); - return startup - .enqueueCommand(dispatchEffect) - .pipe( - Effect.mapError((cause) => - toDispatchCommandError(cause, "Failed to dispatch orchestration command"), - ), - ); - }; + return yield* orchestrationEngine.dispatch(finalTurnStartCommand); + }); - const loadServerConfig = Effect.gen(function* () { - const keybindingsConfig = yield* keybindings.loadConfigState; - const providers = yield* providerRegistry.getProviders; - const settings = yield* serverSettings.getSettings; - const environment = yield* serverEnvironment.getDescriptor; + return yield* bootstrapProgram.pipe( + Effect.catchCause((cause) => { + const dispatchError = toBootstrapDispatchCommandCauseError(cause); + if (Cause.hasInterruptsOnly(cause)) { + return Effect.fail(dispatchError); + } + return cleanupCreatedThread().pipe(Effect.flatMap(() => Effect.fail(dispatchError))); + }), + ); + }); - return { - environment, - cwd: config.cwd, - keybindingsConfigPath: config.keybindingsConfigPath, - keybindings: keybindingsConfig.keybindings, - issues: keybindingsConfig.issues, - providers, - availableEditors: resolveAvailableEditors(), - observability: { - logsDirectoryPath: config.logsDir, - localTracingEnabled: true, - ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}), - otlpTracesEnabled: config.otlpTracesUrl !== undefined, - ...(config.otlpMetricsUrl !== undefined ? { otlpMetricsUrl: config.otlpMetricsUrl } : {}), - otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, - }, - settings, - }; - }); - - const refreshGitStatus = (cwd: string) => - gitStatusBroadcaster - .refreshStatus(cwd) - .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); - - return WsRpcGroup.of({ - [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getSnapshot, - projectionSnapshotQuery.getSnapshot().pipe( - Effect.mapError( - (cause) => - new OrchestrationGetSnapshotError({ - message: "Failed to load orchestration snapshot", - cause, - }), - ), - ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.dispatchCommand, - Effect.gen(function* () { - const normalizedCommand = yield* normalizeDispatchCommand(command); - const result = yield* dispatchNormalizedCommand(normalizedCommand); - if (normalizedCommand.type === "thread.archive") { - yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( - Effect.catch((error) => - Effect.logWarning("failed to close thread terminals after archive", { - threadId: normalizedCommand.threadId, - error: error.message, - }), - ), - ); - } - return result; - }).pipe( + const dispatchNormalizedCommand = ( + normalizedCommand: OrchestrationCommand, + ): Effect.Effect<{ readonly sequence: number }, OrchestrationDispatchCommandError> => { + const dispatchEffect = + normalizedCommand.type === "thread.turn.start" && normalizedCommand.bootstrap + ? dispatchBootstrapTurnStart(normalizedCommand) + : orchestrationEngine + .dispatch(normalizedCommand) + .pipe( + Effect.mapError((cause) => + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + + return startup + .enqueueCommand(dispatchEffect) + .pipe( Effect.mapError((cause) => - Schema.is(OrchestrationDispatchCommandError)(cause) - ? cause - : new OrchestrationDispatchCommandError({ - message: "Failed to dispatch orchestration command", + toDispatchCommandError(cause, "Failed to dispatch orchestration command"), + ), + ); + }; + + const loadServerConfig = Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.loadConfigState; + const providers = yield* providerRegistry.getProviders; + const settings = yield* serverSettings.getSettings; + const environment = yield* serverEnvironment.getDescriptor; + const auth = yield* serverAuth.getDescriptor(); + + return { + environment, + auth, + cwd: config.cwd, + keybindingsConfigPath: config.keybindingsConfigPath, + keybindings: keybindingsConfig.keybindings, + issues: keybindingsConfig.issues, + providers, + availableEditors: resolveAvailableEditors(), + observability: { + logsDirectoryPath: config.logsDir, + localTracingEnabled: true, + ...(config.otlpTracesUrl !== undefined ? { otlpTracesUrl: config.otlpTracesUrl } : {}), + otlpTracesEnabled: config.otlpTracesUrl !== undefined, + ...(config.otlpMetricsUrl !== undefined + ? { otlpMetricsUrl: config.otlpMetricsUrl } + : {}), + otlpMetricsEnabled: config.otlpMetricsUrl !== undefined, + }, + settings, + }; + }); + + const refreshGitStatus = (cwd: string) => + gitStatusBroadcaster + .refreshStatus(cwd) + .pipe(Effect.ignoreCause({ log: true }), Effect.forkDetach, Effect.asVoid); + + return WsRpcGroup.of({ + [ORCHESTRATION_WS_METHODS.getSnapshot]: (_input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getSnapshot, + projectionSnapshotQuery.getSnapshot().pipe( + Effect.mapError( + (cause) => + new OrchestrationGetSnapshotError({ + message: "Failed to load orchestration snapshot", cause, }), + ), ), + { "rpc.aggregate": "orchestration" }, ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getTurnDiff, - checkpointDiffQuery.getTurnDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetTurnDiffError({ - message: "Failed to load turn diff", - cause, - }), + [ORCHESTRATION_WS_METHODS.dispatchCommand]: (command) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.dispatchCommand, + Effect.gen(function* () { + const normalizedCommand = yield* normalizeDispatchCommand(command); + const result = yield* dispatchNormalizedCommand(normalizedCommand); + if (normalizedCommand.type === "thread.archive") { + yield* terminalManager.close({ threadId: normalizedCommand.threadId }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to close thread terminals after archive", { + threadId: normalizedCommand.threadId, + error: error.message, + }), + ), + ); + } + return result; + }).pipe( + Effect.mapError((cause) => + Schema.is(OrchestrationDispatchCommandError)(cause) + ? cause + : new OrchestrationDispatchCommandError({ + message: "Failed to dispatch orchestration command", + cause, + }), + ), ), + { "rpc.aggregate": "orchestration" }, ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.getFullThreadDiff, - checkpointDiffQuery.getFullThreadDiff(input).pipe( - Effect.mapError( - (cause) => - new OrchestrationGetFullThreadDiffError({ - message: "Failed to load full thread diff", - cause, - }), + [ORCHESTRATION_WS_METHODS.getTurnDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getTurnDiff, + checkpointDiffQuery.getTurnDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetTurnDiffError({ + message: "Failed to load turn diff", + cause, + }), + ), ), + { "rpc.aggregate": "orchestration" }, ), - { "rpc.aggregate": "orchestration" }, - ), - [ORCHESTRATION_WS_METHODS.replayEvents]: (input) => - observeRpcEffect( - ORCHESTRATION_WS_METHODS.replayEvents, - Stream.runCollect( - orchestrationEngine.readEvents( - clamp(input.fromSequenceExclusive, { maximum: Number.MAX_SAFE_INTEGER, minimum: 0 }), - ), - ).pipe( - Effect.map((events) => Array.from(events)), - Effect.flatMap(enrichOrchestrationEvents), - Effect.mapError( - (cause) => - new OrchestrationReplayEventsError({ - message: "Failed to replay orchestration events", - cause, - }), + [ORCHESTRATION_WS_METHODS.getFullThreadDiff]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.getFullThreadDiff, + checkpointDiffQuery.getFullThreadDiff(input).pipe( + Effect.mapError( + (cause) => + new OrchestrationGetFullThreadDiffError({ + message: "Failed to load full thread diff", + cause, + }), + ), ), + { "rpc.aggregate": "orchestration" }, ), - { "rpc.aggregate": "orchestration" }, - ), - [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) => - observeRpcStreamEffect( - WS_METHODS.subscribeOrchestrationDomainEvents, - Effect.gen(function* () { - const snapshot = yield* orchestrationEngine.getReadModel(); - const fromSequenceExclusive = snapshot.snapshotSequence; - const replayEvents: Array = yield* Stream.runCollect( - orchestrationEngine.readEvents(fromSequenceExclusive), + [ORCHESTRATION_WS_METHODS.replayEvents]: (input) => + observeRpcEffect( + ORCHESTRATION_WS_METHODS.replayEvents, + Stream.runCollect( + orchestrationEngine.readEvents( + clamp(input.fromSequenceExclusive, { + maximum: Number.MAX_SAFE_INTEGER, + minimum: 0, + }), + ), ).pipe( Effect.map((events) => Array.from(events)), Effect.flatMap(enrichOrchestrationEvents), - Effect.catch(() => Effect.succeed([] as Array)), - ); - const replayStream = Stream.fromIterable(replayEvents); - const liveStream = orchestrationEngine.streamDomainEvents.pipe( - Stream.mapEffect(enrichProjectEvent), - ); - const source = Stream.merge(replayStream, liveStream); - type SequenceState = { - readonly nextSequence: number; - readonly pendingBySequence: Map; - }; - const state = yield* Ref.make({ - nextSequence: fromSequenceExclusive + 1, - pendingBySequence: new Map(), - }); + Effect.mapError( + (cause) => + new OrchestrationReplayEventsError({ + message: "Failed to replay orchestration events", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestration" }, + ), + [WS_METHODS.subscribeOrchestrationDomainEvents]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeOrchestrationDomainEvents, + Effect.gen(function* () { + const snapshot = yield* orchestrationEngine.getReadModel(); + const fromSequenceExclusive = snapshot.snapshotSequence; + const replayEvents: Array = yield* Stream.runCollect( + orchestrationEngine.readEvents(fromSequenceExclusive), + ).pipe( + Effect.map((events) => Array.from(events)), + Effect.flatMap(enrichOrchestrationEvents), + Effect.catch(() => Effect.succeed([] as Array)), + ); + const replayStream = Stream.fromIterable(replayEvents); + const liveStream = orchestrationEngine.streamDomainEvents.pipe( + Stream.mapEffect(enrichProjectEvent), + ); + const source = Stream.merge(replayStream, liveStream); + type SequenceState = { + readonly nextSequence: number; + readonly pendingBySequence: Map; + }; + const state = yield* Ref.make({ + nextSequence: fromSequenceExclusive + 1, + pendingBySequence: new Map(), + }); - return source.pipe( - Stream.mapEffect((event) => - Ref.modify( - state, - ({ - nextSequence, - pendingBySequence, - }): [Array, SequenceState] => { - if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) { - return [[], { nextSequence, pendingBySequence }]; - } - - const updatedPending = new Map(pendingBySequence); - updatedPending.set(event.sequence, event); - - const emit: Array = []; - let expected = nextSequence; - for (;;) { - const expectedEvent = updatedPending.get(expected); - if (!expectedEvent) { - break; + return source.pipe( + Stream.mapEffect((event) => + Ref.modify( + state, + ({ + nextSequence, + pendingBySequence, + }): [Array, SequenceState] => { + if (event.sequence < nextSequence || pendingBySequence.has(event.sequence)) { + return [[], { nextSequence, pendingBySequence }]; } - emit.push(expectedEvent); - updatedPending.delete(expected); - expected += 1; - } - return [emit, { nextSequence: expected, pendingBySequence: updatedPending }]; - }, + const updatedPending = new Map(pendingBySequence); + updatedPending.set(event.sequence, event); + + const emit: Array = []; + let expected = nextSequence; + for (;;) { + const expectedEvent = updatedPending.get(expected); + if (!expectedEvent) { + break; + } + emit.push(expectedEvent); + updatedPending.delete(expected); + expected += 1; + } + + return [emit, { nextSequence: expected, pendingBySequence: updatedPending }]; + }, + ), ), - ), - Stream.flatMap((events) => Stream.fromIterable(events)), - ); + Stream.flatMap((events) => Stream.fromIterable(events)), + ); + }), + { "rpc.aggregate": "orchestration" }, + ), + [WS_METHODS.serverGetConfig]: (_input) => + observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { + "rpc.aggregate": "server", }), - { "rpc.aggregate": "orchestration" }, - ), - [WS_METHODS.serverGetConfig]: (_input) => - observeRpcEffect(WS_METHODS.serverGetConfig, loadServerConfig, { - "rpc.aggregate": "server", - }), - [WS_METHODS.serverRefreshProviders]: (_input) => - observeRpcEffect( - WS_METHODS.serverRefreshProviders, - providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), - { "rpc.aggregate": "server" }, - ), - [WS_METHODS.serverUpsertKeybinding]: (rule) => - observeRpcEffect( - WS_METHODS.serverUpsertKeybinding, - Effect.gen(function* () { - const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); - return { keybindings: keybindingsConfig, issues: [] }; + [WS_METHODS.serverRefreshProviders]: (_input) => + observeRpcEffect( + WS_METHODS.serverRefreshProviders, + providerRegistry.refresh().pipe(Effect.map((providers) => ({ providers }))), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverUpsertKeybinding]: (rule) => + observeRpcEffect( + WS_METHODS.serverUpsertKeybinding, + Effect.gen(function* () { + const keybindingsConfig = yield* keybindings.upsertKeybindingRule(rule); + return { keybindings: keybindingsConfig, issues: [] }; + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.serverGetSettings]: (_input) => + observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, { + "rpc.aggregate": "server", + }), + [WS_METHODS.serverUpdateSettings]: ({ patch }) => + observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), { + "rpc.aggregate": "server", }), - { "rpc.aggregate": "server" }, - ), - [WS_METHODS.serverGetSettings]: (_input) => - observeRpcEffect(WS_METHODS.serverGetSettings, serverSettings.getSettings, { - "rpc.aggregate": "server", - }), - [WS_METHODS.serverUpdateSettings]: ({ patch }) => - observeRpcEffect(WS_METHODS.serverUpdateSettings, serverSettings.updateSettings(patch), { - "rpc.aggregate": "server", - }), - [WS_METHODS.projectsSearchEntries]: (input) => - observeRpcEffect( - WS_METHODS.projectsSearchEntries, - workspaceEntries.search(input).pipe( - Effect.mapError( - (cause) => - new ProjectSearchEntriesError({ - message: `Failed to search workspace entries: ${cause.detail}`, + [WS_METHODS.projectsSearchEntries]: (input) => + observeRpcEffect( + WS_METHODS.projectsSearchEntries, + workspaceEntries.search(input).pipe( + Effect.mapError( + (cause) => + new ProjectSearchEntriesError({ + message: `Failed to search workspace entries: ${cause.detail}`, + cause, + }), + ), + ), + { "rpc.aggregate": "workspace" }, + ), + [WS_METHODS.projectsWriteFile]: (input) => + observeRpcEffect( + WS_METHODS.projectsWriteFile, + workspaceFileSystem.writeFile(input).pipe( + Effect.mapError((cause) => { + const message = Schema.is(WorkspacePathOutsideRootError)(cause) + ? "Workspace file path must stay within the project root." + : "Failed to write workspace file"; + return new ProjectWriteFileError({ + message, cause, - }), + }); + }), ), + { "rpc.aggregate": "workspace" }, ), - { "rpc.aggregate": "workspace" }, - ), - [WS_METHODS.projectsWriteFile]: (input) => - observeRpcEffect( - WS_METHODS.projectsWriteFile, - workspaceFileSystem.writeFile(input).pipe( - Effect.mapError((cause) => { - const message = Schema.is(WorkspacePathOutsideRootError)(cause) - ? "Workspace file path must stay within the project root." - : "Failed to write workspace file"; - return new ProjectWriteFileError({ - message, - cause, - }); - }), + [WS_METHODS.shellOpenInEditor]: (input) => + observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), { + "rpc.aggregate": "workspace", + }), + [WS_METHODS.subscribeGitStatus]: (input) => + observeRpcStream( + WS_METHODS.subscribeGitStatus, + gitStatusBroadcaster.streamStatus(input), + { + "rpc.aggregate": "git", + }, ), - { "rpc.aggregate": "workspace" }, - ), - [WS_METHODS.shellOpenInEditor]: (input) => - observeRpcEffect(WS_METHODS.shellOpenInEditor, open.openInEditor(input), { - "rpc.aggregate": "workspace", - }), - [WS_METHODS.subscribeGitStatus]: (input) => - observeRpcStream(WS_METHODS.subscribeGitStatus, gitStatusBroadcaster.streamStatus(input), { - "rpc.aggregate": "git", - }), - [WS_METHODS.gitRefreshStatus]: (input) => - observeRpcEffect( - WS_METHODS.gitRefreshStatus, - gitStatusBroadcaster.refreshStatus(input.cwd), - { - "rpc.aggregate": "git", - }, - ), - [WS_METHODS.gitPull]: (input) => - observeRpcEffect( - WS_METHODS.gitPull, - git.pullCurrentBranch(input.cwd).pipe( - Effect.matchCauseEffect({ - onFailure: (cause) => Effect.failCause(cause), - onSuccess: (result) => - refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)), - }), + [WS_METHODS.gitRefreshStatus]: (input) => + observeRpcEffect( + WS_METHODS.gitRefreshStatus, + gitStatusBroadcaster.refreshStatus(input.cwd), + { + "rpc.aggregate": "git", + }, + ), + [WS_METHODS.gitPull]: (input) => + observeRpcEffect( + WS_METHODS.gitPull, + git.pullCurrentBranch(input.cwd).pipe( + Effect.matchCauseEffect({ + onFailure: (cause) => Effect.failCause(cause), + onSuccess: (result) => + refreshGitStatus(input.cwd).pipe(Effect.ignore({ log: true }), Effect.as(result)), + }), + ), + { "rpc.aggregate": "git" }, ), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitRunStackedAction]: (input) => - observeRpcStream( - WS_METHODS.gitRunStackedAction, - Stream.callback((queue) => + [WS_METHODS.gitRunStackedAction]: (input) => + observeRpcStream( + WS_METHODS.gitRunStackedAction, + Stream.callback((queue) => + gitManager + .runStackedAction(input, { + actionId: input.actionId, + progressReporter: { + publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), + }, + }) + .pipe( + Effect.matchCauseEffect({ + onFailure: (cause) => Queue.failCause(queue, cause), + onSuccess: () => + refreshGitStatus(input.cwd).pipe( + Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)), + ), + }), + ), + ), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitResolvePullRequest]: (input) => + observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitPreparePullRequestThread]: (input) => + observeRpcEffect( + WS_METHODS.gitPreparePullRequestThread, gitManager - .runStackedAction(input, { - actionId: input.actionId, - progressReporter: { - publish: (event) => Queue.offer(queue, event).pipe(Effect.asVoid), - }, - }) - .pipe( - Effect.matchCauseEffect({ - onFailure: (cause) => Queue.failCause(queue, cause), - onSuccess: () => - refreshGitStatus(input.cwd).pipe( - Effect.andThen(Queue.end(queue).pipe(Effect.asVoid)), - ), - }), - ), + .preparePullRequestThread(input) + .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitListBranches]: (input) => + observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), { + "rpc.aggregate": "git", + }), + [WS_METHODS.gitCreateWorktree]: (input) => + observeRpcEffect( + WS_METHODS.gitCreateWorktree, + git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.gitRemoveWorktree]: (input) => + observeRpcEffect( + WS_METHODS.gitRemoveWorktree, + git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, ), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitResolvePullRequest]: (input) => - observeRpcEffect(WS_METHODS.gitResolvePullRequest, gitManager.resolvePullRequest(input), { - "rpc.aggregate": "git", - }), - [WS_METHODS.gitPreparePullRequestThread]: (input) => - observeRpcEffect( - WS_METHODS.gitPreparePullRequestThread, - gitManager - .preparePullRequestThread(input) - .pipe(Effect.tap(() => refreshGitStatus(input.cwd))), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitListBranches]: (input) => - observeRpcEffect(WS_METHODS.gitListBranches, git.listBranches(input), { - "rpc.aggregate": "git", - }), - [WS_METHODS.gitCreateWorktree]: (input) => - observeRpcEffect( - WS_METHODS.gitCreateWorktree, - git.createWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitRemoveWorktree]: (input) => - observeRpcEffect( - WS_METHODS.gitRemoveWorktree, - git.removeWorktree(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitCreateBranch]: (input) => - observeRpcEffect( - WS_METHODS.gitCreateBranch, - git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitCheckout]: (input) => - observeRpcEffect( - WS_METHODS.gitCheckout, - Effect.scoped(git.checkoutBranch(input)).pipe( - Effect.tap(() => refreshGitStatus(input.cwd)), + [WS_METHODS.gitCreateBranch]: (input) => + observeRpcEffect( + WS_METHODS.gitCreateBranch, + git.createBranch(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, ), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.gitInit]: (input) => - observeRpcEffect( - WS_METHODS.gitInit, - git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), - { "rpc.aggregate": "git" }, - ), - [WS_METHODS.terminalOpen]: (input) => - observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { - "rpc.aggregate": "terminal", - }), - [WS_METHODS.terminalWrite]: (input) => - observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), { - "rpc.aggregate": "terminal", - }), - [WS_METHODS.terminalResize]: (input) => - observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), { - "rpc.aggregate": "terminal", - }), - [WS_METHODS.terminalClear]: (input) => - observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), { - "rpc.aggregate": "terminal", - }), - [WS_METHODS.terminalRestart]: (input) => - observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), { - "rpc.aggregate": "terminal", - }), - [WS_METHODS.terminalClose]: (input) => - observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), { - "rpc.aggregate": "terminal", - }), - [WS_METHODS.subscribeTerminalEvents]: (_input) => - observeRpcStream( - WS_METHODS.subscribeTerminalEvents, - Stream.callback((queue) => - Effect.acquireRelease( - terminalManager.subscribe((event) => Queue.offer(queue, event)), - (unsubscribe) => Effect.sync(unsubscribe), + [WS_METHODS.gitCheckout]: (input) => + observeRpcEffect( + WS_METHODS.gitCheckout, + Effect.scoped(git.checkoutBranch(input)).pipe( + Effect.tap(() => refreshGitStatus(input.cwd)), ), + { "rpc.aggregate": "git" }, ), - { "rpc.aggregate": "terminal" }, - ), - [WS_METHODS.subscribeServerConfig]: (_input) => - observeRpcStreamEffect( - WS_METHODS.subscribeServerConfig, - Effect.gen(function* () { - const keybindingsUpdates = keybindings.streamChanges.pipe( - Stream.map((event) => ({ - version: 1 as const, - type: "keybindingsUpdated" as const, - payload: { - issues: event.issues, - }, - })), - ); - const providerStatuses = providerRegistry.streamChanges.pipe( - Stream.map((providers) => ({ - version: 1 as const, - type: "providerStatuses" as const, - payload: { providers }, - })), - ); - const settingsUpdates = serverSettings.streamChanges.pipe( - Stream.map((settings) => ({ - version: 1 as const, - type: "settingsUpdated" as const, - payload: { settings }, - })), - ); - - return Stream.concat( - Stream.make({ - version: 1 as const, - type: "snapshot" as const, - config: yield* loadServerConfig, - }), - Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)), - ); + [WS_METHODS.gitInit]: (input) => + observeRpcEffect( + WS_METHODS.gitInit, + git.initRepo(input).pipe(Effect.tap(() => refreshGitStatus(input.cwd))), + { "rpc.aggregate": "git" }, + ), + [WS_METHODS.terminalOpen]: (input) => + observeRpcEffect(WS_METHODS.terminalOpen, terminalManager.open(input), { + "rpc.aggregate": "terminal", }), - { "rpc.aggregate": "server" }, - ), - [WS_METHODS.subscribeServerLifecycle]: (_input) => - observeRpcStreamEffect( - WS_METHODS.subscribeServerLifecycle, - Effect.gen(function* () { - const snapshot = yield* lifecycleEvents.snapshot; - const snapshotEvents = Array.from(snapshot.events).toSorted( - (left, right) => left.sequence - right.sequence, - ); - const liveEvents = lifecycleEvents.stream.pipe( - Stream.filter((event) => event.sequence > snapshot.sequence), - ); - return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents); + [WS_METHODS.terminalWrite]: (input) => + observeRpcEffect(WS_METHODS.terminalWrite, terminalManager.write(input), { + "rpc.aggregate": "terminal", }), - { "rpc.aggregate": "server" }, - ), - }); - }), -); + [WS_METHODS.terminalResize]: (input) => + observeRpcEffect(WS_METHODS.terminalResize, terminalManager.resize(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClear]: (input) => + observeRpcEffect(WS_METHODS.terminalClear, terminalManager.clear(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalRestart]: (input) => + observeRpcEffect(WS_METHODS.terminalRestart, terminalManager.restart(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.terminalClose]: (input) => + observeRpcEffect(WS_METHODS.terminalClose, terminalManager.close(input), { + "rpc.aggregate": "terminal", + }), + [WS_METHODS.subscribeTerminalEvents]: (_input) => + observeRpcStream( + WS_METHODS.subscribeTerminalEvents, + Stream.callback((queue) => + Effect.acquireRelease( + terminalManager.subscribe((event) => Queue.offer(queue, event)), + (unsubscribe) => Effect.sync(unsubscribe), + ), + ), + { "rpc.aggregate": "terminal" }, + ), + [WS_METHODS.subscribeServerConfig]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeServerConfig, + Effect.gen(function* () { + const keybindingsUpdates = keybindings.streamChanges.pipe( + Stream.map((event) => ({ + version: 1 as const, + type: "keybindingsUpdated" as const, + payload: { + issues: event.issues, + }, + })), + ); + const providerStatuses = providerRegistry.streamChanges.pipe( + Stream.map((providers) => ({ + version: 1 as const, + type: "providerStatuses" as const, + payload: { providers }, + })), + ); + const settingsUpdates = serverSettings.streamChanges.pipe( + Stream.map((settings) => ({ + version: 1 as const, + type: "settingsUpdated" as const, + payload: { settings }, + })), + ); + + return Stream.concat( + Stream.make({ + version: 1 as const, + type: "snapshot" as const, + config: yield* loadServerConfig, + }), + Stream.merge(keybindingsUpdates, Stream.merge(providerStatuses, settingsUpdates)), + ); + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.subscribeServerLifecycle]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeServerLifecycle, + Effect.gen(function* () { + const snapshot = yield* lifecycleEvents.snapshot; + const snapshotEvents = Array.from(snapshot.events).toSorted( + (left, right) => left.sequence - right.sequence, + ); + const liveEvents = lifecycleEvents.stream.pipe( + Stream.filter((event) => event.sequence > snapshot.sequence), + ); + return Stream.concat(Stream.fromIterable(snapshotEvents), liveEvents); + }), + { "rpc.aggregate": "server" }, + ), + [WS_METHODS.subscribeAuthAccess]: (_input) => + observeRpcStreamEffect( + WS_METHODS.subscribeAuthAccess, + Effect.gen(function* () { + const initialSnapshot = yield* loadAuthAccessSnapshot(); + const revisionRef = yield* Ref.make(1); + const accessChanges: Stream.Stream< + BootstrapCredentialChange | SessionCredentialChange + > = Stream.merge(bootstrapCredentials.streamChanges, sessions.streamChanges); + + const liveEvents: Stream.Stream = accessChanges.pipe( + Stream.mapEffect((change) => + Ref.updateAndGet(revisionRef, (revision) => revision + 1).pipe( + Effect.map((revision) => + toAuthAccessStreamEvent(change, revision, currentSessionId), + ), + ), + ), + ); + + return Stream.concat( + Stream.make({ + version: 1 as const, + revision: 1, + type: "snapshot" as const, + payload: initialSnapshot, + }), + liveEvents, + ); + }), + { "rpc.aggregate": "auth" }, + ), + }); + }), + ); export const websocketRpcRouteLayer = Layer.unwrap( - Effect.gen(function* () { - const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { - spanPrefix: "ws.rpc", - spanAttributes: { - "rpc.transport": "websocket", - "rpc.system": "effect-rpc", - }, - }).pipe(Effect.provide(Layer.mergeAll(WsRpcLayer, RpcSerialization.layerJson))); - return HttpRouter.add( + Effect.succeed( + HttpRouter.add( "GET", "/ws", Effect.gen(function* () { const request = yield* HttpServerRequest.HttpServerRequest; - const config = yield* ServerConfig; - if (config.authToken) { - const url = HttpServerRequest.toURL(request); - if (Option.isNone(url)) { - return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 }); - } - const token = url.value.searchParams.get("token"); - if (token !== config.authToken) { - return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 }); - } - } - return yield* rpcWebSocketHttpEffect; - }), - ); - }), + const serverAuth = yield* ServerAuth; + const sessions = yield* SessionCredentialService; + const session = yield* serverAuth.authenticateWebSocketUpgrade(request); + const rpcWebSocketHttpEffect = yield* RpcServer.toHttpEffectWebsocket(WsRpcGroup, { + spanPrefix: "ws.rpc", + spanAttributes: { + "rpc.transport": "websocket", + "rpc.system": "effect-rpc", + }, + }).pipe( + Effect.provide( + makeWsRpcLayer(session.sessionId).pipe(Layer.provideMerge(RpcSerialization.layerJson)), + ), + ); + return yield* Effect.acquireUseRelease( + sessions.markConnected(session.sessionId), + () => rpcWebSocketHttpEffect, + () => sessions.markDisconnected(session.sessionId), + ); + }).pipe(Effect.catchTag("AuthError", respondToAuthError)), + ), + ), ); diff --git a/apps/web/index.html b/apps/web/index.html index 45f30f7164..9f0329b602 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -2,9 +2,84 @@ - + + + + + + T3 Code (Alpha) - -
+
+
+
+ +
+
+
diff --git a/apps/web/src/authBootstrap.test.ts b/apps/web/src/authBootstrap.test.ts new file mode 100644 index 0000000000..2e12e00f45 --- /dev/null +++ b/apps/web/src/authBootstrap.test.ts @@ -0,0 +1,460 @@ +import type { DesktopBridge } from "@t3tools/contracts"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +function jsonResponse(body: unknown, init?: ResponseInit) { + return new Response(JSON.stringify(body), { + headers: { + "content-type": "application/json", + }, + status: 200, + ...init, + }); +} + +type TestWindow = { + location: URL; + history: { + replaceState: (_data: unknown, _unused: string, url: string) => void; + }; + desktopBridge?: DesktopBridge; +}; + +function installTestBrowser(url: string) { + const testWindow: TestWindow = { + location: new URL(url), + history: { + replaceState: (_data, _unused, nextUrl) => { + testWindow.location = new URL(nextUrl, testWindow.location.href); + }, + }, + }; + + vi.stubGlobal("window", testWindow); + vi.stubGlobal("document", { title: "T3 Code" }); + + return testWindow; +} + +function sessionResponse(body: unknown, init?: ResponseInit) { + return jsonResponse(body, init); +} + +describe("resolveInitialServerAuthGateState", () => { + beforeEach(() => { + vi.restoreAllMocks(); + vi.useRealTimers(); + installTestBrowser("http://localhost/"); + }); + + afterEach(async () => { + const { __resetServerAuthBootstrapForTests } = await import("./environments/primary"); + __resetServerAuthBootstrapForTests(); + vi.unstubAllEnvs(); + vi.useRealTimers(); + vi.restoreAllMocks(); + }); + + it("reuses an in-flight silent bootstrap attempt", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + jsonResponse({ + authenticated: true, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const testWindow = installTestBrowser("http://localhost/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstrap: () => ({ + label: "Local environment", + httpBaseUrl: "http://localhost:3773", + wsBaseUrl: "ws://localhost:3773", + bootstrapToken: "desktop-bootstrap-token", + }), + } as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await Promise.all([resolveInitialServerAuthGateState(), resolveInitialServerAuthGateState()]); + + expect(fetchMock).toHaveBeenCalledTimes(3); + expect(fetchMock.mock.calls[0]?.[0]).toBe("http://localhost:3773/api/auth/session"); + expect(fetchMock.mock.calls[1]?.[0]).toBe("http://localhost:3773/api/auth/bootstrap"); + expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session"); + }); + + it("uses https fetch urls when the primary environment uses wss", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com"); + vi.stubEnv("VITE_WS_URL", "wss://remote.example.com"); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + + expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/api/auth/session", { + credentials: "include", + }); + }); + + it("uses the current origin as an auth proxy base for local dev environments", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + installTestBrowser("http://localhost:5735/"); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + + expect(fetchMock).toHaveBeenCalledWith("http://localhost:5735/api/auth/session", { + credentials: "include", + }); + }); + + it("returns a requires-auth state instead of throwing when no bootstrap credential exists", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + }); + + it("retries transient auth session bootstrap failures after restart", async () => { + vi.useFakeTimers(); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })) + .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })) + .mockResolvedValueOnce(new Response("Bad Gateway", { status: 502 })) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + const gateStatePromise = resolveInitialServerAuthGateState(); + await vi.advanceTimersByTimeAsync(2_000); + + await expect(gateStatePromise).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + expect(fetchMock).toHaveBeenCalledTimes(4); + }); + + it("takes a pairing token from the location hash and strips it immediately", async () => { + const testWindow = installTestBrowser("http://localhost/#token=pairing-token"); + const { takePairingTokenFromUrl } = await import("./environments/primary"); + + expect(takePairingTokenFromUrl()).toBe("pairing-token"); + expect(testWindow.location.hash).toBe(""); + expect(testWindow.location.searchParams.get("token")).toBeNull(); + }); + + it("accepts query-string pairing tokens as a backward-compatible fallback", async () => { + const testWindow = installTestBrowser("http://localhost/?token=pairing-token"); + const { takePairingTokenFromUrl } = await import("./environments/primary"); + + expect(takePairingTokenFromUrl()).toBe("pairing-token"); + expect(testWindow.location.searchParams.get("token")).toBeNull(); + }); + + it("allows manual token submission after the initial auth check requires pairing", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + jsonResponse({ + authenticated: true, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + installTestBrowser("http://localhost/"); + + const { resolveInitialServerAuthGateState, submitServerAuthCredential } = + await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + await expect(submitServerAuthCredential("retry-token")).resolves.toBeUndefined(); + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "authenticated", + }); + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + it("waits for the authenticated session to become observable after silent desktop bootstrap", async () => { + vi.useFakeTimers(); + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + jsonResponse({ + authenticated: true, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "desktop-managed-local", + bootstrapMethods: ["desktop-bootstrap"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const testWindow = installTestBrowser("http://localhost/"); + testWindow.desktopBridge = { + getLocalEnvironmentBootstrap: () => ({ + label: "Local environment", + httpBaseUrl: "http://localhost:3773", + wsBaseUrl: "ws://localhost:3773", + bootstrapToken: "desktop-bootstrap-token", + }), + } as DesktopBridge; + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + const gateStatePromise = resolveInitialServerAuthGateState(); + await vi.advanceTimersByTimeAsync(100); + + await expect(gateStatePromise).resolves.toEqual({ + status: "authenticated", + }); + expect(fetchMock).toHaveBeenCalledTimes(4); + expect(fetchMock.mock.calls[2]?.[0]).toBe("http://localhost:3773/api/auth/session"); + expect(fetchMock.mock.calls[3]?.[0]).toBe("http://localhost:3773/api/auth/session"); + }); + + it("revalidates the server session state after a previous authenticated result", async () => { + const fetchMock = vi + .fn() + .mockResolvedValueOnce( + sessionResponse({ + authenticated: true, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + sessionMethod: "browser-session-cookie", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ) + .mockResolvedValueOnce( + sessionResponse({ + authenticated: false, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { resolveInitialServerAuthGateState } = await import("./environments/primary"); + + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "authenticated", + }); + await expect(resolveInitialServerAuthGateState()).resolves.toEqual({ + status: "requires-auth", + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3_session", + }, + }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + it("creates a pairing credential from the authenticated auth endpoint", async () => { + const fetchMock = vi.fn().mockResolvedValueOnce( + jsonResponse({ + id: "pairing-link-1", + credential: "pairing-token", + label: "Julius iPhone", + expiresAt: "2026-04-05T00:00:00.000Z", + }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { createServerPairingCredential } = await import("./environments/primary"); + + await expect(createServerPairingCredential("Julius iPhone")).resolves.toEqual({ + id: "pairing-link-1", + credential: "pairing-token", + label: "Julius iPhone", + expiresAt: "2026-04-05T00:00:00.000Z", + }); + expect(fetchMock).toHaveBeenCalledWith("http://localhost/api/auth/pairing-token", { + body: JSON.stringify({ label: "Julius iPhone" }), + credentials: "include", + headers: { + "content-type": "application/json", + }, + method: "POST", + }); + }); +}); diff --git a/apps/web/src/components/BranchToolbar.logic.ts b/apps/web/src/components/BranchToolbar.logic.ts index c9e336bf48..adc6495953 100644 --- a/apps/web/src/components/BranchToolbar.logic.ts +++ b/apps/web/src/components/BranchToolbar.logic.ts @@ -1,10 +1,17 @@ -import type { GitBranch } from "@t3tools/contracts"; +import type { EnvironmentId, GitBranch, ProjectId } from "@t3tools/contracts"; import { Schema } from "effect"; export { dedupeRemoteBranchesWithLocalMatches, deriveLocalBranchNameFromRemoteRef, } from "@t3tools/shared/git"; +export interface EnvironmentOption { + environmentId: EnvironmentId; + projectId: ProjectId; + label: string; + isPrimary: boolean; +} + export const EnvMode = Schema.Literals(["local", "worktree"]); export type EnvMode = typeof EnvMode.Type; diff --git a/apps/web/src/components/BranchToolbar.tsx b/apps/web/src/components/BranchToolbar.tsx index cbcaf6f2fe..94d11ae7bd 100644 --- a/apps/web/src/components/BranchToolbar.tsx +++ b/apps/web/src/components/BranchToolbar.tsx @@ -1,25 +1,19 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; -import { FolderIcon, GitForkIcon } from "lucide-react"; -import { useCallback, useMemo } from "react"; +import { useMemo } from "react"; import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; -import { readEnvironmentApi } from "../environmentApi"; -import { newCommandId } from "../lib/utils"; import { useStore } from "../store"; import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { - EnvMode, - resolveDraftEnvModeAfterBranchChange, + type EnvMode, + type EnvironmentOption, resolveEffectiveEnvMode, } from "./BranchToolbar.logic"; import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector"; -import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; - -const envModeItems = [ - { value: "local", label: "Local" }, - { value: "worktree", label: "New worktree" }, -] as const; +import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector"; +import { BranchToolbarEnvModeSelector } from "./BranchToolbarEnvModeSelector"; +import { Separator } from "./ui/separator"; interface BranchToolbarProps { environmentId: EnvironmentId; @@ -29,9 +23,11 @@ interface BranchToolbarProps { envLocked: boolean; onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; + availableEnvironments?: readonly EnvironmentOption[]; + onEnvironmentChange?: (environmentId: EnvironmentId) => void; } -export default function BranchToolbar({ +export function BranchToolbar({ environmentId, threadId, draftId, @@ -39,6 +35,8 @@ export default function BranchToolbar({ envLocked, onCheckoutPullRequestRequest, onComposerFocusRequest, + availableEnvironments, + onEnvironmentChange, }: BranchToolbarProps) { const threadRef = useMemo( () => scopeThreadRef(environmentId, threadId), @@ -46,10 +44,7 @@ export default function BranchToolbar({ ); const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]); const serverThread = useStore(serverThreadSelector); - const serverSession = serverThread?.session ?? null; - const setThreadBranchAction = useStore((store) => store.setThreadBranch); const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); - const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const activeProjectRef = serverThread ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) : draftThread @@ -60,131 +55,46 @@ export default function BranchToolbar({ [activeProjectRef], ); const activeProject = useStore(activeProjectSelector); - const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined); - const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null; + const hasActiveThread = serverThread !== undefined || draftThread !== null; const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; - const branchCwd = activeWorktreePath ?? activeProject?.cwd ?? null; - const hasServerThread = serverThread !== undefined; const effectiveEnvMode = resolveEffectiveEnvMode({ activeWorktreePath, - hasServerThread, + hasServerThread: serverThread !== undefined, draftThreadEnvMode: draftThread?.envMode, }); - const setThreadBranch = useCallback( - (branch: string | null, worktreePath: string | null) => { - if (!activeThreadId || !activeProject) return; - const api = readEnvironmentApi(environmentId); - // If the effective cwd is about to change, stop the running session so the - // next message creates a new one with the correct cwd. - if (serverSession && worktreePath !== activeWorktreePath && api) { - void api.orchestration - .dispatchCommand({ - type: "thread.session.stop", - commandId: newCommandId(), - threadId: activeThreadId, - createdAt: new Date().toISOString(), - }) - .catch(() => undefined); - } - if (api && hasServerThread) { - void api.orchestration.dispatchCommand({ - type: "thread.meta.update", - commandId: newCommandId(), - threadId: activeThreadId, - branch, - worktreePath, - }); - } - if (hasServerThread) { - setThreadBranchAction(activeThreadId, branch, worktreePath); - return; - } - const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({ - nextWorktreePath: worktreePath, - currentWorktreePath: activeWorktreePath, - effectiveEnvMode, - }); - setDraftThreadContext(draftId ?? threadRef, { - branch, - worktreePath, - envMode: nextDraftEnvMode, - projectRef: scopeProjectRef(environmentId, activeProject.id), - }); - }, - [ - activeThreadId, - activeProject, - serverSession, - activeWorktreePath, - hasServerThread, - setThreadBranchAction, - setDraftThreadContext, - draftId, - threadRef, - environmentId, - effectiveEnvMode, - ], - ); + const showEnvironmentPicker = + availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange; - if (!activeThreadId || !activeProject) return null; + if (!hasActiveThread || !activeProject) return null; return (
- {envLocked || activeWorktreePath ? ( - - {activeWorktreePath ? ( - <> - - Worktree - - ) : ( - <> - - Local - - )} - - ) : ( - - )} +
+ {showEnvironmentPicker && ( + <> + + + + )} + +
diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 61a97866ff..11c458bbe9 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -1,4 +1,5 @@ -import type { EnvironmentId, GitBranch } from "@t3tools/contracts"; +import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime"; +import type { EnvironmentId, GitBranch, ThreadId } from "@t3tools/contracts"; import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query"; import { useVirtualizer } from "@tanstack/react-virtual"; import { ChevronDownIcon } from "lucide-react"; @@ -14,15 +15,20 @@ import { useTransition, } from "react"; +import { useComposerDraftStore, type DraftId } from "../composerDraftStore"; +import { readEnvironmentApi } from "../environmentApi"; import { gitBranchSearchInfiniteQueryOptions, gitQueryKeys } from "../lib/gitReactQuery"; import { useGitStatus } from "../lib/gitStatusState"; -import { readEnvironmentApi } from "../environmentApi"; +import { newCommandId } from "../lib/utils"; import { parsePullRequestReference } from "../pullRequestReference"; +import { useStore } from "../store"; +import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { deriveLocalBranchNameFromRemoteRef, - EnvMode, resolveBranchSelectionTarget, resolveBranchToolbarValue, + resolveDraftEnvModeAfterBranchChange, + resolveEffectiveEnvMode, shouldIncludeBranchPickerItem, } from "./BranchToolbar.logic"; import { Button } from "./ui/button"; @@ -40,13 +46,9 @@ import { toastManager } from "./ui/toast"; interface BranchToolbarBranchSelectorProps { environmentId: EnvironmentId; - activeProjectCwd: string; - activeThreadBranch: string | null; - activeWorktreePath: string | null; - branchCwd: string | null; - effectiveEnvMode: EnvMode; + threadId: ThreadId; + draftId?: DraftId; envLocked: boolean; - onSetThreadBranch: (branch: string | null, worktreePath: string | null) => void; onCheckoutPullRequestRequest?: (reference: string) => void; onComposerFocusRequest?: () => void; } @@ -57,7 +59,7 @@ function toBranchActionErrorMessage(error: unknown): string { function getBranchTriggerLabel(input: { activeWorktreePath: string | null; - effectiveEnvMode: EnvMode; + effectiveEnvMode: "local" | "worktree"; resolvedActiveBranch: string | null; }): string { const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input; @@ -72,16 +74,109 @@ function getBranchTriggerLabel(input: { export function BranchToolbarBranchSelector({ environmentId, - activeProjectCwd, - activeThreadBranch, - activeWorktreePath, - branchCwd, - effectiveEnvMode, + threadId, + draftId, envLocked, - onSetThreadBranch, onCheckoutPullRequestRequest, onComposerFocusRequest, }: BranchToolbarBranchSelectorProps) { + // --------------------------------------------------------------------------- + // Thread / project state (pushed down from parent to colocate with mutation) + // --------------------------------------------------------------------------- + const threadRef = useMemo( + () => scopeThreadRef(environmentId, threadId), + [environmentId, threadId], + ); + const serverThreadSelector = useMemo(() => createThreadSelectorByRef(threadRef), [threadRef]); + const serverThread = useStore(serverThreadSelector); + const serverSession = serverThread?.session ?? null; + const setThreadBranchAction = useStore((store) => store.setThreadBranch); + const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef)); + const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); + + const activeProjectRef = serverThread + ? scopeProjectRef(serverThread.environmentId, serverThread.projectId) + : draftThread + ? scopeProjectRef(draftThread.environmentId, draftThread.projectId) + : null; + const activeProjectSelector = useMemo( + () => createProjectSelectorByRef(activeProjectRef), + [activeProjectRef], + ); + const activeProject = useStore(activeProjectSelector); + + const activeThreadId = serverThread?.id ?? (draftThread ? threadId : undefined); + const activeThreadBranch = serverThread?.branch ?? draftThread?.branch ?? null; + const activeWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null; + const activeProjectCwd = activeProject?.cwd ?? null; + const branchCwd = activeWorktreePath ?? activeProjectCwd; + const hasServerThread = serverThread !== undefined; + const effectiveEnvMode = resolveEffectiveEnvMode({ + activeWorktreePath, + hasServerThread, + draftThreadEnvMode: draftThread?.envMode, + }); + + // --------------------------------------------------------------------------- + // Thread branch mutation (colocated — only this component calls it) + // --------------------------------------------------------------------------- + const setThreadBranch = useCallback( + (branch: string | null, worktreePath: string | null) => { + if (!activeThreadId || !activeProject) return; + const api = readEnvironmentApi(environmentId); + if (serverSession && worktreePath !== activeWorktreePath && api) { + void api.orchestration + .dispatchCommand({ + type: "thread.session.stop", + commandId: newCommandId(), + threadId: activeThreadId, + createdAt: new Date().toISOString(), + }) + .catch(() => undefined); + } + if (api && hasServerThread) { + void api.orchestration.dispatchCommand({ + type: "thread.meta.update", + commandId: newCommandId(), + threadId: activeThreadId, + branch, + worktreePath, + }); + } + if (hasServerThread) { + setThreadBranchAction(activeThreadId, branch, worktreePath); + return; + } + const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({ + nextWorktreePath: worktreePath, + currentWorktreePath: activeWorktreePath, + effectiveEnvMode, + }); + setDraftThreadContext(draftId ?? threadRef, { + branch, + worktreePath, + envMode: nextDraftEnvMode, + projectRef: scopeProjectRef(environmentId, activeProject.id), + }); + }, + [ + activeThreadId, + activeProject, + serverSession, + activeWorktreePath, + hasServerThread, + setThreadBranchAction, + setDraftThreadContext, + draftId, + threadRef, + environmentId, + effectiveEnvMode, + ], + ); + + // --------------------------------------------------------------------------- + // Git branch queries + // --------------------------------------------------------------------------- const queryClient = useQueryClient(); const [isBranchMenuOpen, setIsBranchMenuOpen] = useState(false); const [branchQuery, setBranchQuery] = useState(""); @@ -183,6 +278,9 @@ export function BranchToolbarBranchSelector({ ? `Showing ${branches.length} of ${totalBranchCount} branches` : null; + // --------------------------------------------------------------------------- + // Branch actions + // --------------------------------------------------------------------------- const runBranchAction = (action: () => Promise) => { startBranchActionTransition(async () => { await action().catch(() => undefined); @@ -194,11 +292,10 @@ export function BranchToolbarBranchSelector({ const selectBranch = (branch: GitBranch) => { const api = readEnvironmentApi(environmentId); - if (!api || !branchCwd || isBranchActionPending) return; + if (!api || !branchCwd || !activeProjectCwd || isBranchActionPending) return; - // In new-worktree mode, selecting a branch sets the base branch. if (isSelectingWorktreeBase) { - onSetThreadBranch(branch.name, null); + setThreadBranch(branch.name, null); setIsBranchMenuOpen(false); onComposerFocusRequest?.(); return; @@ -210,9 +307,8 @@ export function BranchToolbarBranchSelector({ branch, }); - // If the branch already lives in a worktree, point the thread there. if (selectionTarget.reuseExistingWorktree) { - onSetThreadBranch(branch.name, selectionTarget.nextWorktreePath); + setThreadBranch(branch.name, selectionTarget.nextWorktreePath); setIsBranchMenuOpen(false); onComposerFocusRequest?.(); return; @@ -237,7 +333,7 @@ export function BranchToolbarBranchSelector({ ? (checkoutResult.branch ?? selectedBranchName) : selectedBranchName; setOptimisticBranch(nextBranchName); - onSetThreadBranch(nextBranchName, selectionTarget.nextWorktreePath); + setThreadBranch(nextBranchName, selectionTarget.nextWorktreePath); } catch (error) { setOptimisticBranch(previousBranch); toastManager.add({ @@ -267,7 +363,7 @@ export function BranchToolbarBranchSelector({ checkout: true, }); setOptimisticBranch(createBranchResult.branch); - onSetThreadBranch(createBranchResult.branch, activeWorktreePath); + setThreadBranch(createBranchResult.branch, activeWorktreePath); } catch (error) { setOptimisticBranch(previousBranch); toastManager.add({ @@ -288,15 +384,12 @@ export function BranchToolbarBranchSelector({ ) { return; } - onSetThreadBranch(currentGitBranch, null); - }, [ - activeThreadBranch, - activeWorktreePath, - currentGitBranch, - effectiveEnvMode, - onSetThreadBranch, - ]); + setThreadBranch(currentGitBranch, null); + }, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]); + // --------------------------------------------------------------------------- + // Combobox / virtualizer plumbing + // --------------------------------------------------------------------------- const handleOpenChange = useCallback( (open: boolean) => { setIsBranchMenuOpen(open); @@ -437,7 +530,7 @@ export function BranchToolbarBranchSelector({ style={style} onClick={() => createBranch(trimmedBranchQuery)} > - Create new branch "{trimmedBranchQuery}" + Create new branch "{trimmedBranchQuery}" ); } @@ -445,7 +538,8 @@ export function BranchToolbarBranchSelector({ const branch = branchByName.get(itemValue); if (!branch) return null; - const hasSecondaryWorktree = branch.worktreePath && branch.worktreePath !== activeProjectCwd; + const hasSecondaryWorktree = + branch.worktreePath && activeProjectCwd && branch.worktreePath !== activeProjectCwd; const badge = branch.current ? "current" : hasSecondaryWorktree diff --git a/apps/web/src/components/BranchToolbarEnvModeSelector.tsx b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx new file mode 100644 index 0000000000..e1145f65f4 --- /dev/null +++ b/apps/web/src/components/BranchToolbarEnvModeSelector.tsx @@ -0,0 +1,73 @@ +import { FolderIcon, GitForkIcon } from "lucide-react"; +import { memo } from "react"; + +import type { EnvMode } from "./BranchToolbar.logic"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; + +const envModeItems = [ + { value: "local", label: "Local" }, + { value: "worktree", label: "New worktree" }, +] as const; + +interface BranchToolbarEnvModeSelectorProps { + envLocked: boolean; + effectiveEnvMode: EnvMode; + activeWorktreePath: string | null; + onEnvModeChange: (mode: EnvMode) => void; +} + +export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSelector({ + envLocked, + effectiveEnvMode, + activeWorktreePath, + onEnvModeChange, +}: BranchToolbarEnvModeSelectorProps) { + if (envLocked || activeWorktreePath) { + return ( + + {activeWorktreePath ? ( + <> + + Worktree + + ) : ( + <> + + Local + + )} + + ); + } + + return ( + + ); +}); diff --git a/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx new file mode 100644 index 0000000000..1725e8e909 --- /dev/null +++ b/apps/web/src/components/BranchToolbarEnvironmentSelector.tsx @@ -0,0 +1,65 @@ +import type { EnvironmentId } from "@t3tools/contracts"; +import { CloudIcon, FolderIcon, ServerIcon } from "lucide-react"; +import { memo, useMemo } from "react"; + +import type { EnvironmentOption } from "./BranchToolbar.logic"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select"; + +interface BranchToolbarEnvironmentSelectorProps { + envLocked: boolean; + environmentId: EnvironmentId; + availableEnvironments: readonly EnvironmentOption[]; + onEnvironmentChange: (environmentId: EnvironmentId) => void; +} + +export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({ + envLocked, + environmentId, + availableEnvironments, + onEnvironmentChange, +}: BranchToolbarEnvironmentSelectorProps) { + const activeEnvironmentLabel = useMemo(() => { + return availableEnvironments.find((env) => env.environmentId === environmentId)?.label ?? null; + }, [availableEnvironments, environmentId]); + + const environmentItems = useMemo( + () => + availableEnvironments.map((env) => ({ + value: env.environmentId, + label: env.label, + })), + [availableEnvironments], + ); + + if (envLocked) { + return ( + + + {activeEnvironmentLabel ?? "Environment"} + + ); + } + + return ( + + ); +}); diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index f0c4a52c5f..24de35959e 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -44,6 +44,7 @@ import { getRouter } from "../router"; import { selectBootstrapCompleteForActiveEnvironment, useStore } from "../store"; import { useTerminalStateStore } from "../terminalStateStore"; import { useUiStateStore } from "../uiStateStore"; +import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers"; import { BrowserWsRpcHarness, type NormalizedWsRpcRequestBody } from "../../test/wsRpcHarness"; import { estimateTimelineMessageHeight } from "./timelineHeight"; import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; @@ -148,6 +149,12 @@ function createBaseServerConfig(): ServerConfig { serverVersion: "0.0.0-test", capabilities: { repositoryIdentity: true }, }, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie", "bearer-session-token"], + sessionCookieName: "t3_session", + }, cwd: "/repo/project", keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", keybindings: [], @@ -821,6 +828,7 @@ const worker = setupWorker( void rpcHarness.onMessage(rawData); }); }), + ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth), http.get("*/attachments/:attachmentId", () => HttpResponse.text(ATTACHMENT_SVG, { headers: { @@ -2629,10 +2637,9 @@ describe("ChatView timeline estimator parity (full app)", () => { "Promoted drafts should canonicalize to the server thread route.", ); - // The empty thread view and composer should still be visible. - await expect - .element(page.getByText("Send a message to start the conversation.")) - .toBeInTheDocument(); + // The composer should remain usable after canonicalization, regardless of + // whether the promoted thread is still visibly empty or has already + // entered the running state. await expect.element(page.getByTestId("composer-editor")).toBeInTheDocument(); } finally { await mounted.cleanup(); @@ -2992,6 +2999,17 @@ describe("ChatView timeline estimator parity (full app)", () => { const promotedThreadId = draftThreadIdFor(promotedDraftId); await promoteDraftThreadViaDomainEvent(promotedThreadId); + await waitForURL( + mounted.router, + (path) => path === serverThreadPath(promotedThreadId), + "Promoted drafts should canonicalize to the server thread route before a fresh draft is created.", + ); + await vi.waitFor( + () => { + expect(useComposerDraftStore.getState().getDraftThread(promotedDraftId)).toBeNull(); + }, + { timeout: 8_000, interval: 16 }, + ); const freshThreadPath = await triggerChatNewShortcutUntilPath( mounted.router, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index cf09dd8a38..53bfe2324b 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -38,6 +38,7 @@ import { useNavigate, useSearch } from "@tanstack/react-router"; import { useShallow } from "zustand/react/shallow"; import { useGitStatus } from "~/lib/gitStatusState"; import { projectSearchEntriesQueryOptions } from "~/lib/projectReactQuery"; +import { usePrimaryEnvironmentId } from "../environments/primary"; import { readEnvironmentApi } from "../environmentApi"; import { isElectron } from "../env"; import { readLocalApi } from "../localApi"; @@ -75,7 +76,11 @@ import { togglePendingUserInputOptionSelection, type PendingUserInputDraftAnswer, } from "../pendingUserInput"; -import { selectThreadsAcrossEnvironments, useStore } from "../store"; +import { + selectProjectsAcrossEnvironments, + selectThreadsAcrossEnvironments, + useStore, +} from "../store"; import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { useUiStateStore } from "../uiStateStore"; import { @@ -97,7 +102,7 @@ import { import { basenameOfPath } from "../vscode-icons"; import { useTheme } from "../hooks/useTheme"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; -import BranchToolbar from "./BranchToolbar"; +import { BranchToolbar } from "./BranchToolbar"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; @@ -124,7 +129,6 @@ import { nextProjectScriptId, projectScriptIdFromCommand, } from "~/projectScripts"; -import { SidebarTrigger } from "./ui/sidebar"; import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils"; import { getProviderModelCapabilities, @@ -135,6 +139,10 @@ import { useSettings } from "../hooks/useSettings"; import { resolveAppModelSelection } from "../modelSelection"; import { isTerminalFocused } from "../lib/terminalFocus"; import { deriveLogicalProjectKey } from "../logicalProject"; +import { + useSavedEnvironmentRegistryStore, + useSavedEnvironmentRuntimeStore, +} from "../environments/runtime"; import { buildDraftThreadRouteParams } from "../threadRoutes"; import { type ComposerImageAttachment, @@ -167,6 +175,7 @@ import { MessagesTimeline } from "./chat/MessagesTimeline"; import { ChatHeader } from "./chat/ChatHeader"; import { ContextWindowMeter } from "./chat/ContextWindowMeter"; import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/ExpandedImagePreview"; +import { NoActiveThreadState } from "./NoActiveThreadState"; import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker"; import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions"; @@ -212,7 +221,6 @@ import { } from "~/rpc/serverState"; import { sanitizeThreadErrorMessage } from "~/rpc/transportError"; -const ATTACHMENT_PREVIEW_HANDOFF_TTL_MS = 5000; const IMAGE_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; @@ -813,7 +821,7 @@ export default function ChatView(props: ChatViewProps) { const composerMenuItemsRef = useRef([]); const activeComposerMenuItemRef = useRef(null); const attachmentPreviewHandoffByMessageIdRef = useRef>({}); - const attachmentPreviewHandoffTimeoutByMessageIdRef = useRef>({}); + const attachmentPreviewPromotionInFlightByMessageIdRef = useRef>({}); const sendInFlightRef = useRef(false); const dragDepthRef = useRef(0); const terminalOpenByThreadRef = useRef>({}); @@ -998,6 +1006,54 @@ export default function ChatView(props: ChatViewProps) { useMemo(() => createProjectSelectorByRef(activeProjectRef), [activeProjectRef]), ); + // Compute the list of environments this logical project spans, used to + // drive the environment picker in BranchToolbar. + const allProjects = useStore(useShallow(selectProjectsAcrossEnvironments)); + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId); + const logicalProjectEnvironments = useMemo(() => { + if (!activeProject) return []; + const logicalKey = deriveLogicalProjectKey(activeProject); + const memberProjects = allProjects.filter((p) => deriveLogicalProjectKey(p) === logicalKey); + const seen = new Set(); + const envs: Array<{ + environmentId: EnvironmentId; + projectId: ProjectId; + label: string; + isPrimary: boolean; + }> = []; + for (const p of memberProjects) { + if (seen.has(p.environmentId)) continue; + seen.add(p.environmentId); + const isPrimary = p.environmentId === primaryEnvironmentId; + const savedRecord = savedEnvironmentRegistry[p.environmentId]; + const runtimeState = savedEnvironmentRuntimeById[p.environmentId]; + const label = isPrimary + ? "Local" + : (runtimeState?.descriptor?.label ?? savedRecord?.label ?? p.environmentId); + envs.push({ + environmentId: p.environmentId, + projectId: p.id, + label, + isPrimary, + }); + } + // Sort: primary first, then alphabetical + envs.sort((a, b) => { + if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1; + return a.label.localeCompare(b.label); + }); + return envs; + }, [ + activeProject, + allProjects, + primaryEnvironmentId, + savedEnvironmentRegistry, + savedEnvironmentRuntimeById, + ]); + const hasMultipleEnvironments = logicalProjectEnvironments.length > 1; + const openPullRequestDialog = useCallback( (reference?: string) => { if (!canCheckoutPullRequestIntoThread) { @@ -1127,7 +1183,17 @@ export default function ChatView(props: ChatViewProps) { const lockedProvider: ProviderKind | null = hasThreadStarted ? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null) : null; - const serverConfig = useServerConfig(); + const primaryServerConfig = useServerConfig(); + const activeEnvRuntimeState = useSavedEnvironmentRuntimeStore((s) => + activeThread?.environmentId ? s.byId[activeThread.environmentId] : null, + ); + // Use the server config for the thread's environment. For the primary + // environment fall back to the global atom; for remote environments use + // the runtime state stored by the environment manager. + const serverConfig = + primaryEnvironmentId && activeThread?.environmentId === primaryEnvironmentId + ? primaryServerConfig + : (activeEnvRuntimeState?.serverConfig ?? primaryServerConfig); const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, @@ -1338,11 +1404,28 @@ export default function ChatView(props: ChatViewProps) { useEffect(() => { attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId; }, [attachmentPreviewHandoffByMessageId]); + const clearAttachmentPreviewHandoff = useCallback( + (messageId: MessageId, previewUrls?: ReadonlyArray) => { + delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; + const currentPreviewUrls = + previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? []; + setAttachmentPreviewHandoffByMessageId((existing) => { + if (!(messageId in existing)) { + return existing; + } + const next = { ...existing }; + delete next[messageId]; + attachmentPreviewHandoffByMessageIdRef.current = next; + return next; + }); + for (const previewUrl of currentPreviewUrls) { + revokeBlobPreviewUrl(previewUrl); + } + }, + [], + ); const clearAttachmentPreviewHandoffs = useCallback(() => { - for (const timeoutId of Object.values(attachmentPreviewHandoffTimeoutByMessageIdRef.current)) { - window.clearTimeout(timeoutId); - } - attachmentPreviewHandoffTimeoutByMessageIdRef.current = {}; + attachmentPreviewPromotionInFlightByMessageIdRef.current = {}; for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) { for (const previewUrl of previewUrls) { revokeBlobPreviewUrl(previewUrl); @@ -1376,29 +1459,89 @@ export default function ChatView(props: ChatViewProps) { attachmentPreviewHandoffByMessageIdRef.current = next; return next; }); - - const existingTimeout = attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId]; - if (typeof existingTimeout === "number") { - window.clearTimeout(existingTimeout); + }, []); + const serverMessages = activeThread?.messages; + useEffect(() => { + if (typeof Image === "undefined" || !serverMessages || serverMessages.length === 0) { + return; } - attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId] = window.setTimeout(() => { - const currentPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId]; - if (currentPreviewUrls) { - for (const previewUrl of currentPreviewUrls) { - revokeBlobPreviewUrl(previewUrl); - } + + const cleanups: Array<() => void> = []; + + for (const [messageId, handoffPreviewUrls] of Object.entries( + attachmentPreviewHandoffByMessageId, + )) { + if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) { + continue; } - setAttachmentPreviewHandoffByMessageId((existing) => { - if (!(messageId in existing)) return existing; - const next = { ...existing }; - delete next[messageId]; - attachmentPreviewHandoffByMessageIdRef.current = next; - return next; + + const serverMessage = serverMessages.find( + (message) => message.id === messageId && message.role === "user", + ); + if (!serverMessage?.attachments || serverMessage.attachments.length === 0) { + continue; + } + + const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) => + attachment.type === "image" && attachment.previewUrl ? [attachment.previewUrl] : [], + ); + if ( + serverPreviewUrls.length === 0 || + serverPreviewUrls.length !== handoffPreviewUrls.length || + serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:")) + ) { + continue; + } + + attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true; + + let cancelled = false; + const imageInstances: HTMLImageElement[] = []; + + const preloadServerPreviews = Promise.all( + serverPreviewUrls.map( + (previewUrl) => + new Promise((resolve, reject) => { + const image = new Image(); + imageInstances.push(image); + const handleLoad = () => resolve(); + const handleError = () => + reject(new Error(`Failed to load server preview for ${messageId}.`)); + image.addEventListener("load", handleLoad, { once: true }); + image.addEventListener("error", handleError, { once: true }); + image.src = previewUrl; + }), + ), + ); + + void preloadServerPreviews + .then(() => { + if (cancelled) { + return; + } + clearAttachmentPreviewHandoff(messageId as MessageId, handoffPreviewUrls); + }) + .catch(() => { + if (!cancelled) { + delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; + } + }); + + cleanups.push(() => { + cancelled = true; + delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]; + for (const image of imageInstances) { + image.src = ""; + } }); - delete attachmentPreviewHandoffTimeoutByMessageIdRef.current[messageId]; - }, ATTACHMENT_PREVIEW_HANDOFF_TTL_MS); - }, []); - const serverMessages = activeThread?.messages; + } + + return () => { + for (const cleanup of cleanups) { + cleanup(); + } + }; + }, [attachmentPreviewHandoffByMessageId, clearAttachmentPreviewHandoff, serverMessages]); const timelineMessages = useMemo(() => { const messages = serverMessages ?? []; const serverMessagesWithPreviewHandoff = @@ -1537,7 +1680,9 @@ export default function ChatView(props: ChatViewProps) { const gitStatusQuery = useGitStatus({ environmentId, cwd: gitCwd }); const keybindings = useServerKeybindings(); const availableEditors = useServerAvailableEditors(); - const modelOptionsByProvider = useMemo( + const modelOptionsByProvider = useMemo< + Record> + >( () => ({ codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [], claudeAgent: @@ -1730,6 +1875,47 @@ export default function ChatView(props: ChatViewProps) { (activeThread.messages.length > 0 || (activeThread.session !== null && activeThread.session.status !== "closed")), ); + + // Handle environment change for draft threads. When the user picks a + // different environment we update the draft context to point at the physical + // project in that environment while keeping the same logical project. + const onEnvironmentChange = useCallback( + (nextEnvironmentId: EnvironmentId) => { + if (envLocked || !draftId) return; + const target = logicalProjectEnvironments.find( + (env) => env.environmentId === nextEnvironmentId, + ); + if (!target) return; + setDraftThreadContext(draftId, { + projectRef: scopeProjectRef(target.environmentId, target.projectId), + }); + }, + [draftId, envLocked, logicalProjectEnvironments, setDraftThreadContext], + ); + + // Auto-correct the draft model selection when the environment changes and + // the previously-selected provider/model is no longer available. This keeps + // the stored draft state consistent with the resolved picker values and + // prevents stale model references when the user sends a message. + const prevEnvironmentIdRef = useRef(activeThread?.environmentId); + useEffect(() => { + const currentEnvId = activeThread?.environmentId; + if (!currentEnvId || envLocked || prevEnvironmentIdRef.current === currentEnvId) { + prevEnvironmentIdRef.current = currentEnvId; + return; + } + prevEnvironmentIdRef.current = currentEnvId; + + // The resolved provider/model already account for the new environment's + // provider list. Persist that resolved selection into the draft. + if (activeThread) { + setComposerDraftModelSelection(scopeThreadRef(activeThread.environmentId, activeThread.id), { + provider: selectedProvider, + model: selectedModel, + }); + } + }, [activeThread, envLocked, selectedModel, selectedProvider, setComposerDraftModelSelection]); + const activeTerminalGroup = terminalState.terminalGroups.find( (group) => group.id === terminalState.activeTerminalGroupId, @@ -4113,28 +4299,7 @@ export default function ChatView(props: ChatViewProps) { // Empty state: no active thread if (!activeThread) { - return ( -
- {!isElectron && ( -
-
- - Threads -
-
- )} - {isElectron && ( -
- No active thread -
- )} -
-
-

Select a thread or create a new one to get started.

-
-
-
- ); + return ; } return ( @@ -4636,6 +4801,12 @@ export default function ChatView(props: ChatViewProps) { {...(canCheckoutPullRequestIntoThread ? { onCheckoutPullRequestRequest: openPullRequestDialog } : {})} + {...(hasMultipleEnvironments + ? { + availableEnvironments: logicalProjectEnvironments, + onEnvironmentChange, + } + : {})} /> )} {pullRequestDialogState ? ( diff --git a/apps/web/src/components/GitActionsControl.browser.tsx b/apps/web/src/components/GitActionsControl.browser.tsx index 1a1bd714f3..29a2f178ac 100644 --- a/apps/web/src/components/GitActionsControl.browser.tsx +++ b/apps/web/src/components/GitActionsControl.browser.tsx @@ -44,8 +44,12 @@ const { toastUpdateSpy: vi.fn(), })); -vi.mock("@tanstack/react-query", () => { +vi.mock("@tanstack/react-query", async () => { + const actual = + await vi.importActual("@tanstack/react-query"); + return { + ...actual, useIsMutating: vi.fn(() => 0), useMutation: vi.fn((options: { __kind?: string }) => { if (options.__kind === "run-stacked-action") { @@ -133,6 +137,19 @@ vi.mock("~/store", () => ({ } return environmentState; }, + selectProjectsForEnvironment: () => [], + selectProjectsAcrossEnvironments: () => [], + selectThreadsForEnvironment: () => [], + selectThreadsAcrossEnvironments: () => [], + selectThreadShellsAcrossEnvironments: () => [], + selectSidebarThreadsAcrossEnvironments: () => [], + selectSidebarThreadsForProjectRef: () => [], + selectSidebarThreadsForProjectRefs: () => [], + selectBootstrapCompleteForActiveEnvironment: () => true, + selectProjectByRef: () => null, + selectThreadByRef: () => null, + selectSidebarThreadSummaryByRef: () => null, + selectThreadIdsByProjectRef: () => [], useStore: (selector: (state: unknown) => unknown) => selector({ setThreadBranch: setThreadBranchSpy, diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 6ec450d662..f1239ffecb 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -22,8 +22,10 @@ import { useComposerDraftStore } from "../composerDraftStore"; import { __resetLocalApiForTests } from "../localApi"; import { AppAtomRegistryProvider } from "../rpc/atomRegistry"; import { getServerConfig } from "../rpc/serverState"; +import { getWsConnectionStatus } from "../rpc/wsConnectionState"; import { getRouter } from "../router"; import { useStore } from "../store"; +import { createAuthenticatedSessionHandlers } from "../../test/authHttpHandlers"; import { BrowserWsRpcHarness } from "../../test/wsRpcHarness"; vi.mock("../lib/gitStatusState", () => ({ @@ -58,6 +60,12 @@ function createBaseServerConfig(): ServerConfig { serverVersion: "0.0.0-test", capabilities: { repositoryIdentity: true }, }, + auth: { + policy: "loopback-browser", + bootstrapMethods: ["one-time-token"], + sessionMethods: ["browser-session-cookie", "bearer-session-token"], + sessionCookieName: "t3_session", + }, cwd: "/repo/project", keybindingsConfigPath: "/repo/project/.t3code-keybindings.json", keybindings: [], @@ -210,6 +218,7 @@ const worker = setupWorker( void rpcHarness.onMessage(rawData); }); }), + ...createAuthenticatedSessionHandlers(() => fixture.serverConfig.auth), http.get("*/attachments/:attachmentId", () => new HttpResponse(null, { status: 204 })), http.get("*/api/project-favicon", () => new HttpResponse(null, { status: 204 })), ); @@ -250,6 +259,22 @@ async function waitForComposerEditor(): Promise { ); } +async function waitForToastViewport(): Promise { + return waitForElement( + () => document.querySelector('[data-slot="toast-viewport"]'), + "App should render the toast viewport before server config updates are pushed", + ); +} + +async function waitForWsConnection(): Promise { + await vi.waitFor( + () => { + expect(getWsConnectionStatus().phase).toBe("connected"); + }, + { timeout: 8_000, interval: 16 }, + ); +} + async function waitForToast(title: string, count = 1): Promise { await vi.waitFor( () => { @@ -269,6 +294,20 @@ async function waitForNoToast(title: string): Promise { ); } +async function waitForNoToasts(): Promise { + await vi.waitFor( + () => { + expect(queryToastTitles()).toHaveLength(0); + }, + { timeout: 8_000, interval: 16 }, + ); +} + +async function warmServerConfigUpdateStream(): Promise { + sendServerConfigUpdatedPush([]); + await new Promise((resolve) => setTimeout(resolve, 50)); +} + async function waitForInitialWsSubscriptions(): Promise { await vi.waitFor( () => { @@ -313,8 +352,11 @@ async function mountApp(): Promise<{ cleanup: () => Promise }> { { container: host }, ); await waitForComposerEditor(); + await waitForToastViewport(); await waitForInitialWsSubscriptions(); + await waitForWsConnection(); await waitForServerConfigSnapshot(); + await waitForNoToasts(); return { cleanup: async () => { @@ -387,6 +429,8 @@ describe("Keybindings update toast", () => { const mounted = await mountApp(); try { + await warmServerConfigUpdateStream(); + sendServerConfigUpdatedPush([]); await waitForToast("Keybindings updated", 1); diff --git a/apps/web/src/components/NoActiveThreadState.tsx b/apps/web/src/components/NoActiveThreadState.tsx new file mode 100644 index 0000000000..39aa4e2f72 --- /dev/null +++ b/apps/web/src/components/NoActiveThreadState.tsx @@ -0,0 +1,41 @@ +import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "./ui/empty"; +import { SidebarInset, SidebarTrigger } from "./ui/sidebar"; +import { isElectron } from "../env"; +import { cn } from "~/lib/utils"; + +export function NoActiveThreadState() { + return ( + +
+
+ {isElectron ? ( + No active thread + ) : ( +
+ + + No active thread + +
+ )} +
+ + +
+ + Pick a thread to continue + + Select an existing thread or create a new one to get started. + + +
+
+
+
+ ); +} diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index 58426f50ba..38e07f59ce 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -1,14 +1,19 @@ +import type { EnvironmentId } from "@t3tools/contracts"; import { FolderIcon } from "lucide-react"; import { useState } from "react"; -import { resolveServerUrl } from "~/lib/utils"; +import { resolveEnvironmentHttpUrl } from "../environments/runtime"; const loadedProjectFaviconSrcs = new Set(); -export function ProjectFavicon({ cwd, className }: { cwd: string; className?: string }) { - const src = resolveServerUrl({ - protocol: "http", +export function ProjectFavicon(input: { + environmentId: EnvironmentId; + cwd: string; + className?: string; +}) { + const src = resolveEnvironmentHttpUrl({ + environmentId: input.environmentId, pathname: "/api/project-favicon", - searchParams: { cwd }, + searchParams: { cwd: input.cwd }, }); const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", @@ -17,12 +22,14 @@ export function ProjectFavicon({ cwd, className }: { cwd: string; className?: st return ( <> {status !== "loaded" ? ( - + ) : null} { loadedProjectFaviconSrcs.add(src); setStatus("loaded"); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 9181434547..6dbd5605c3 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -2,6 +2,7 @@ import { ArchiveIcon, ArrowUpDownIcon, ChevronRightIcon, + CloudIcon, FolderIcon, GitPullRequestIcon, PlusIcon, @@ -34,6 +35,7 @@ import { type DesktopUpdateState, type EnvironmentId, ProjectId, + type ScopedProjectRef, type ScopedThreadRef, type ThreadEnvMode, ThreadId, @@ -50,13 +52,16 @@ import { type SidebarProjectSortOrder, type SidebarThreadSortOrder, } from "@t3tools/contracts/settings"; +import { usePrimaryEnvironmentId } from "../environments/primary"; import { isElectron } from "../env"; import { APP_STAGE_LABEL, APP_VERSION } from "../branding"; import { isTerminalFocused } from "../lib/terminalFocus"; import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils"; import { + selectProjectByRef, selectProjectsAcrossEnvironments, selectSidebarThreadsForProjectRef, + selectSidebarThreadsForProjectRefs, selectSidebarThreadsAcrossEnvironments, selectThreadByRef, useStore, @@ -103,7 +108,6 @@ import { SidebarFooter, SidebarGroup, SidebarHeader, - SidebarMenuAction, SidebarMenu, SidebarMenuButton, SidebarMenuItem, @@ -135,6 +139,11 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { readEnvironmentApi } from "../environmentApi"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; import { useServerKeybindings } from "../rpc/serverState"; +import { deriveLogicalProjectKey } from "../logicalProject"; +import { + useSavedEnvironmentRegistryStore, + useSavedEnvironmentRuntimeStore, +} from "../environments/runtime"; import type { Project, SidebarThreadSummary } from "../types"; const THREAD_PREVIEW_LIMIT = 6; const SIDEBAR_SORT_LABELS: Record = { @@ -200,8 +209,14 @@ function buildThreadJumpLabelMap(input: { return mapping.size > 0 ? mapping : EMPTY_THREAD_JUMP_LABELS; } +type EnvironmentPresence = "local-only" | "remote-only" | "mixed"; + type SidebarProjectSnapshot = Project & { projectKey: string; + environmentPresence: EnvironmentPresence; + memberProjectRefs: readonly ScopedProjectRef[]; + /** Labels for remote environments this project lives in. */ + remoteEnvironmentLabels: readonly string[]; }; interface TerminalStatusIndicator { label: "Terminal process running"; @@ -381,7 +396,30 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP (state) => selectThreadTerminalState(state.terminalStateByThreadKey, threadRef).runningTerminalIds, ); - const gitCwd = thread.worktreePath ?? props.projectCwd; + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const isRemoteThread = + primaryEnvironmentId !== null && thread.environmentId !== primaryEnvironmentId; + const remoteEnvLabel = useSavedEnvironmentRuntimeStore( + (s) => s.byId[thread.environmentId]?.descriptor?.label ?? null, + ); + const remoteEnvSavedLabel = useSavedEnvironmentRegistryStore( + (s) => s.byId[thread.environmentId]?.label ?? null, + ); + const threadEnvironmentLabel = isRemoteThread + ? (remoteEnvLabel ?? remoteEnvSavedLabel ?? "Remote") + : null; + // For grouped projects, the thread may belong to a different environment + // than the representative project. Look up the thread's own project cwd + // so git status (and thus PR detection) queries the correct path. + const threadProjectCwd = useStore( + useMemo( + () => (state: import("../store").AppState) => + selectProjectByRef(state, scopeProjectRef(thread.environmentId, thread.projectId))?.cwd ?? + null, + [thread.environmentId, thread.projectId], + ), + ); + const gitCwd = thread.worktreePath ?? threadProjectCwd ?? props.projectCwd; const gitStatus = useGitStatus({ environmentId: thread.environmentId, cwd: thread.branch != null ? gitCwd : null, @@ -673,24 +711,41 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ) ) : null} - {jumpLabel ? ( - - {jumpLabel} - - ) : ( - - {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} - - )} + + {isRemoteThread && ( + + + } + > + + + {threadEnvironmentLabel} + + )} + {jumpLabel ? ( + + {jumpLabel} + + ) : ( + + {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} + + )} +
@@ -998,7 +1053,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const sidebarThreads = useStore( useShallow( useMemo( - () => (state) => + () => (state: import("../store").AppState) => selectSidebarThreadsForProjectRef( state, scopeProjectRef(project.environmentId, project.id), @@ -1007,25 +1062,45 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec ), ), ); + // For grouped projects that span multiple environments, also fetch + // threads from the other member project refs. + const otherMemberRefs = useMemo( + () => + project.memberProjectRefs.filter( + (ref) => ref.environmentId !== project.environmentId || ref.projectId !== project.id, + ), + [project.memberProjectRefs, project.environmentId, project.id], + ); + const otherMemberThreads = useStore( + useShallow( + useMemo( + () => + otherMemberRefs.length === 0 + ? () => [] as SidebarThreadSummary[] + : (state: import("../store").AppState) => + selectSidebarThreadsForProjectRefs(state, otherMemberRefs), + [otherMemberRefs], + ), + ), + ); + const allSidebarThreads = useMemo( + () => + otherMemberThreads.length === 0 ? sidebarThreads : [...sidebarThreads, ...otherMemberThreads], + [sidebarThreads, otherMemberThreads], + ); const sidebarThreadByKey = useMemo( () => new Map( - sidebarThreads.map( + allSidebarThreads.map( (thread) => [scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), thread] as const, ), ), - [sidebarThreads], - ); - const projectThreads = useMemo( - () => - sidebarThreads.filter( - (thread) => - scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)) === - project.projectKey, - ), - [project.projectKey, sidebarThreads], + [allSidebarThreads], ); + // All threads from the representative + other member environments are + // already fetched into allSidebarThreads, so we can use them directly. + const projectThreads = allSidebarThreads; const projectExpanded = useUiStateStore( (state) => state.projectExpandedById[project.projectKey] ?? true, ); @@ -1639,28 +1714,49 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec }`} /> )} - + {project.name} + {/* Environment badge – visible by default, crossfades with the + "new thread" button on hover using the same pointer-events + + opacity pattern as the thread row archive/timestamp swap. */} + {project.environmentPresence === "remote-only" && ( + + + } + > + + + + Remote environment: {project.remoteEnvironmentLabels.join(", ")} + + + )} - } - showOnHover - className="top-1 right-1.5 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" - onClick={handleCreateThreadClick} - > - - +
+ +
} /> @@ -2238,7 +2334,9 @@ export default function Sidebar() { const navigate = useNavigate(); const pathname = useLocation({ select: (loc) => loc.pathname }); const isOnSettings = pathname.startsWith("/settings"); - const appSettings = useSettings(); + const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder); + const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder); + const defaultThreadEnvMode = useSettings((s) => s.defaultThreadEnvMode); const { updateSettings } = useUpdateSettings(); const { handleNewThread } = useHandleNewThread(); const { archiveThread, deleteThread } = useThreadActions(); @@ -2269,6 +2367,9 @@ export default function Sidebar() { const platform = navigator.platform; const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop; const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately; + const primaryEnvironmentId = usePrimaryEnvironmentId(); + const savedEnvironmentRegistry = useSavedEnvironmentRegistryStore((s) => s.byId); + const savedEnvironmentRuntimeById = useSavedEnvironmentRuntimeStore((s) => s.byId); const orderedProjects = useMemo(() => { return orderItemsByPreferredIds({ items: projects, @@ -2276,14 +2377,89 @@ export default function Sidebar() { getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), }); }, [projectOrder, projects]); - const sidebarProjects = useMemo( - () => - orderedProjects.map((project) => ({ - ...project, - projectKey: scopedProjectKey(scopeProjectRef(project.environmentId, project.id)), - })), - [orderedProjects], - ); + + // Build a mapping from physical project key → logical project key for + // cross-environment grouping. Projects that share a repositoryIdentity + // canonicalKey are treated as one logical project in the sidebar. + const physicalToLogicalKey = useMemo(() => { + const mapping = new Map(); + for (const project of orderedProjects) { + const physicalKey = scopedProjectKey(scopeProjectRef(project.environmentId, project.id)); + mapping.set(physicalKey, deriveLogicalProjectKey(project)); + } + return mapping; + }, [orderedProjects]); + + const sidebarProjects = useMemo(() => { + // Group projects by logical key while preserving insertion order from + // orderedProjects. + const groupedMembers = new Map(); + for (const project of orderedProjects) { + const logicalKey = deriveLogicalProjectKey(project); + const existing = groupedMembers.get(logicalKey); + if (existing) { + existing.push(project); + } else { + groupedMembers.set(logicalKey, [project]); + } + } + + const result: SidebarProjectSnapshot[] = []; + const seen = new Set(); + for (const project of orderedProjects) { + const logicalKey = deriveLogicalProjectKey(project); + if (seen.has(logicalKey)) continue; + seen.add(logicalKey); + + const members = groupedMembers.get(logicalKey)!; + // Prefer the primary environment's project as the representative. + const representative: Project | undefined = + (primaryEnvironmentId + ? members.find((p) => p.environmentId === primaryEnvironmentId) + : undefined) ?? members[0]; + if (!representative) continue; + const hasLocal = + primaryEnvironmentId !== null && + members.some((p) => p.environmentId === primaryEnvironmentId); + const hasRemote = + primaryEnvironmentId !== null + ? members.some((p) => p.environmentId !== primaryEnvironmentId) + : false; + + const refs = members.map((p) => scopeProjectRef(p.environmentId, p.id)); + const remoteLabels = members + .filter((p) => primaryEnvironmentId !== null && p.environmentId !== primaryEnvironmentId) + .map((p) => { + const rt = savedEnvironmentRuntimeById[p.environmentId]; + const saved = savedEnvironmentRegistry[p.environmentId]; + return rt?.descriptor?.label ?? saved?.label ?? p.environmentId; + }); + const snapshot: SidebarProjectSnapshot = { + id: representative.id, + environmentId: representative.environmentId, + name: representative.name, + cwd: representative.cwd, + repositoryIdentity: representative.repositoryIdentity ?? null, + defaultModelSelection: representative.defaultModelSelection, + createdAt: representative.createdAt, + updatedAt: representative.updatedAt, + scripts: representative.scripts, + projectKey: logicalKey, + environmentPresence: + hasLocal && hasRemote ? "mixed" : hasRemote ? "remote-only" : "local-only", + memberProjectRefs: refs, + remoteEnvironmentLabels: remoteLabels, + }; + result.push(snapshot); + } + return result; + }, [ + orderedProjects, + primaryEnvironmentId, + savedEnvironmentRegistry, + savedEnvironmentRuntimeById, + ]); + const sidebarProjectByKey = useMemo( () => new Map(sidebarProjects.map((project) => [project.projectKey, project] as const)), [sidebarProjects], @@ -2298,28 +2474,36 @@ export default function Sidebar() { ), [sidebarThreads], ); + // Resolve the active route's project key to a logical key so it matches the + // sidebar's grouped project entries. const activeRouteProjectKey = useMemo(() => { if (!routeThreadKey) { return null; } const activeThread = sidebarThreadByKey.get(routeThreadKey); - return activeThread - ? scopedProjectKey(scopeProjectRef(activeThread.environmentId, activeThread.projectId)) - : null; - }, [routeThreadKey, sidebarThreadByKey]); + if (!activeThread) return null; + const physicalKey = scopedProjectKey( + scopeProjectRef(activeThread.environmentId, activeThread.projectId), + ); + return physicalToLogicalKey.get(physicalKey) ?? physicalKey; + }, [routeThreadKey, sidebarThreadByKey, physicalToLogicalKey]); + + // Group threads by logical project key so all threads from grouped projects + // are displayed together. const threadsByProjectKey = useMemo(() => { const next = new Map(); for (const thread of sidebarThreads) { - const projectKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); - const existing = next.get(projectKey); + const physicalKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); + const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey; + const existing = next.get(logicalKey); if (existing) { existing.push(thread); } else { - next.set(projectKey, [thread]); + next.set(logicalKey, [thread]); } } return next; - }, [sidebarThreads]); + }, [sidebarThreads, physicalToLogicalKey]); const getCurrentSidebarShortcutContext = useCallback( () => ({ terminalFocus: isTerminalFocused(), @@ -2347,12 +2531,13 @@ export default function Sidebar() { shortcutLabelForCommand(keybindings, "chat.new", newThreadShortcutLabelOptions); const focusMostRecentThreadForProject = useCallback( (projectRef: { environmentId: EnvironmentId; projectId: ProjectId }) => { - const projectKey = scopedProjectKey( + const physicalKey = scopedProjectKey( scopeProjectRef(projectRef.environmentId, projectRef.projectId), ); + const logicalKey = physicalToLogicalKey.get(physicalKey) ?? physicalKey; const latestThread = sortThreadsForSidebar( - (threadsByProjectKey.get(projectKey) ?? []).filter((thread) => thread.archivedAt === null), - appSettings.sidebarThreadSortOrder, + (threadsByProjectKey.get(logicalKey) ?? []).filter((thread) => thread.archivedAt === null), + sidebarThreadSortOrder, )[0]; if (!latestThread) return; @@ -2361,7 +2546,7 @@ export default function Sidebar() { params: buildThreadRouteParams(scopeThreadRef(latestThread.environmentId, latestThread.id)), }); }, - [appSettings.sidebarThreadSortOrder, navigate, threadsByProjectKey], + [sidebarThreadSortOrder, navigate, threadsByProjectKey, physicalToLogicalKey], ); const addProjectFromPath = useCallback( @@ -2407,7 +2592,7 @@ export default function Sidebar() { }); if (activeEnvironmentId !== null) { await handleNewThread(scopeProjectRef(activeEnvironmentId, projectId), { - envMode: appSettings.defaultThreadEnvMode, + envMode: defaultThreadEnvMode, }).catch(() => undefined); } } catch (error) { @@ -2434,7 +2619,7 @@ export default function Sidebar() { isAddingProject, projects, shouldBrowseForProjectImmediately, - appSettings.defaultThreadEnvMode, + defaultThreadEnvMode, ], ); @@ -2501,7 +2686,7 @@ export default function Sidebar() { const handleProjectDragEnd = useCallback( (event: DragEndEvent) => { - if (appSettings.sidebarProjectSortOrder !== "manual") { + if (sidebarProjectSortOrder !== "manual") { dragInProgressRef.current = false; return; } @@ -2513,18 +2698,18 @@ export default function Sidebar() { if (!activeProject || !overProject) return; reorderProjects(activeProject.projectKey, overProject.projectKey); }, - [appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects], + [sidebarProjectSortOrder, reorderProjects, sidebarProjects], ); const handleProjectDragStart = useCallback( (_event: DragStartEvent) => { - if (appSettings.sidebarProjectSortOrder !== "manual") { + if (sidebarProjectSortOrder !== "manual") { return; } dragInProgressRef.current = true; suppressProjectClickAfterDragRef.current = true; }, - [appSettings.sidebarProjectSortOrder], + [sidebarProjectSortOrder], ); const handleProjectDragCancel = useCallback((_event: DragCancelEvent) => { @@ -2558,22 +2743,29 @@ export default function Sidebar() { ...project, id: project.projectKey, })); - const sortableThreads = visibleThreads.map((thread) => ({ - ...thread, - projectId: scopedProjectKey( - scopeProjectRef(thread.environmentId, thread.projectId), - ) as ProjectId, - })); + const sortableThreads = visibleThreads.map((thread) => { + const physicalKey = scopedProjectKey(scopeProjectRef(thread.environmentId, thread.projectId)); + return { + ...thread, + projectId: (physicalToLogicalKey.get(physicalKey) ?? physicalKey) as ProjectId, + }; + }); return sortProjectsForSidebar( sortableProjects, sortableThreads, - appSettings.sidebarProjectSortOrder, + sidebarProjectSortOrder, ).flatMap((project) => { const resolvedProject = sidebarProjectByKey.get(project.id); return resolvedProject ? [resolvedProject] : []; }); - }, [appSettings.sidebarProjectSortOrder, sidebarProjectByKey, sidebarProjects, visibleThreads]); - const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual"; + }, [ + sidebarProjectSortOrder, + physicalToLogicalKey, + sidebarProjectByKey, + sidebarProjects, + visibleThreads, + ]); + const isManualProjectSorting = sidebarProjectSortOrder === "manual"; const visibleSidebarThreadKeys = useMemo( () => sortedProjects.flatMap((project) => { @@ -2581,7 +2773,7 @@ export default function Sidebar() { (threadsByProjectKey.get(project.projectKey) ?? []).filter( (thread) => thread.archivedAt === null, ), - appSettings.sidebarThreadSortOrder, + sidebarThreadSortOrder, ); const projectExpanded = projectExpandedById[project.projectKey] ?? true; const activeThreadKey = routeThreadKey ?? undefined; @@ -2609,7 +2801,7 @@ export default function Sidebar() { ); }), [ - appSettings.sidebarThreadSortOrder, + sidebarThreadSortOrder, expandedThreadListsByProject, projectExpandedById, routeThreadKey, @@ -2910,8 +3102,8 @@ export default function Sidebar() { desktopUpdateButtonAction={desktopUpdateButtonAction} desktopUpdateButtonDisabled={desktopUpdateButtonDisabled} handleDesktopUpdateButtonClick={handleDesktopUpdateButtonClick} - projectSortOrder={appSettings.sidebarProjectSortOrder} - threadSortOrder={appSettings.sidebarThreadSortOrder} + projectSortOrder={sidebarProjectSortOrder} + threadSortOrder={sidebarThreadSortOrder} updateSettings={updateSettings} shouldShowProjectPathEntry={shouldShowProjectPathEntry} handleStartAddProject={handleStartAddProject} diff --git a/apps/web/src/components/SplashScreen.tsx b/apps/web/src/components/SplashScreen.tsx new file mode 100644 index 0000000000..a0b593a950 --- /dev/null +++ b/apps/web/src/components/SplashScreen.tsx @@ -0,0 +1,9 @@ +export function SplashScreen() { + return ( +
+
+ T3 Code +
+
+ ); +} diff --git a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx index 5f01e53af4..d35f4602a8 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.browser.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.browser.tsx @@ -141,11 +141,25 @@ function createEnvironmentApi() { }; } -async function mountTerminalViewport(props: { threadRef: ReturnType }) { +async function mountTerminalViewport(props: { + threadRef: ReturnType; + drawerBackgroundColor?: string; + drawerTextColor?: string; +}) { + const drawer = document.createElement("div"); + drawer.className = "thread-terminal-drawer"; + if (props.drawerBackgroundColor) { + drawer.style.backgroundColor = props.drawerBackgroundColor; + } + if (props.drawerTextColor) { + drawer.style.color = props.drawerTextColor; + } + const host = document.createElement("div"); host.style.width = "800px"; host.style.height = "400px"; - document.body.append(host); + drawer.append(host); + document.body.append(drawer); const screen = await render( { await screen.unmount(); - host.remove(); + drawer.remove(); }, }; } @@ -244,4 +258,32 @@ describe("TerminalViewport", () => { await mounted.cleanup(); } }); + + it("uses the drawer surface colors for the terminal theme", async () => { + const environment = createEnvironmentApi(); + environmentApiById.set("environment-a", environment); + + const mounted = await mountTerminalViewport({ + threadRef: scopeThreadRef("environment-a" as never, THREAD_ID), + drawerBackgroundColor: "rgb(24, 28, 36)", + drawerTextColor: "rgb(228, 232, 240)", + }); + + try { + await vi.waitFor(() => { + expect(terminalConstructorSpy).toHaveBeenCalledTimes(1); + }); + + expect(terminalConstructorSpy).toHaveBeenCalledWith( + expect.objectContaining({ + theme: expect.objectContaining({ + background: "rgb(24, 28, 36)", + foreground: "rgb(228, 232, 240)", + }), + }), + ); + } finally { + await mounted.cleanup(); + } + }); }); diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsx index de40cc0bf8..9aac8ad6cc 100644 --- a/apps/web/src/components/ThreadTerminalDrawer.tsx +++ b/apps/web/src/components/ThreadTerminalDrawer.tsx @@ -76,12 +76,37 @@ export function selectPendingTerminalEventEntries( return entries.filter((entry) => entry.id > lastAppliedTerminalEventId); } -function terminalThemeFromApp(): ITheme { +function normalizeComputedColor(value: string | null | undefined, fallback: string): string { + const normalizedValue = value?.trim().toLowerCase(); + if ( + !normalizedValue || + normalizedValue === "transparent" || + normalizedValue === "rgba(0, 0, 0, 0)" || + normalizedValue === "rgba(0 0 0 / 0)" + ) { + return fallback; + } + return value ?? fallback; +} + +function terminalThemeFromApp(mountElement?: HTMLElement | null): ITheme { const isDark = document.documentElement.classList.contains("dark"); + const fallbackBackground = isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)"; + const fallbackForeground = isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)"; + const drawerSurface = + mountElement?.closest(".thread-terminal-drawer") ?? + document.querySelector(".thread-terminal-drawer") ?? + document.body; + const drawerStyles = getComputedStyle(drawerSurface); const bodyStyles = getComputedStyle(document.body); - const background = - bodyStyles.backgroundColor || (isDark ? "rgb(14, 18, 24)" : "rgb(255, 255, 255)"); - const foreground = bodyStyles.color || (isDark ? "rgb(237, 241, 247)" : "rgb(28, 33, 41)"); + const background = normalizeComputedColor( + drawerStyles.backgroundColor, + normalizeComputedColor(bodyStyles.backgroundColor, fallbackBackground), + ); + const foreground = normalizeComputedColor( + drawerStyles.color, + normalizeComputedColor(bodyStyles.color, fallbackForeground), + ); if (isDark) { return { @@ -275,7 +300,7 @@ export function TerminalViewport({ fontSize: 12, scrollback: 5_000, fontFamily: '"SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace', - theme: terminalThemeFromApp(), + theme: terminalThemeFromApp(mount), }); terminal.loadAddon(fitAddon); terminal.open(mount); @@ -488,7 +513,7 @@ export function TerminalViewport({ const themeObserver = new MutationObserver(() => { const activeTerminal = terminalRef.current; if (!activeTerminal) return; - activeTerminal.options.theme = terminalThemeFromApp(); + activeTerminal.options.theme = terminalThemeFromApp(containerRef.current); activeTerminal.refresh(0, activeTerminal.rows - 1); }); themeObserver.observe(document.documentElement, { @@ -720,7 +745,10 @@ export function TerminalViewport({ }; }, [drawerHeight, resizeEpoch, terminalId, threadId, threadRef]); return ( -
+
); } diff --git a/apps/web/src/components/WebSocketConnectionSurface.tsx b/apps/web/src/components/WebSocketConnectionSurface.tsx index 1855046a62..17d514ae70 100644 --- a/apps/web/src/components/WebSocketConnectionSurface.tsx +++ b/apps/web/src/components/WebSocketConnectionSurface.tsx @@ -1,9 +1,6 @@ -import { AlertTriangle, CloudOff, LoaderCircle, RotateCw } from "lucide-react"; import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react"; -import { APP_DISPLAY_NAME } from "../branding"; import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState"; -import { useServerConfig } from "../rpc/serverState"; import { exhaustWsReconnectIfStillWaiting, getWsConnectionStatus, @@ -14,9 +11,8 @@ import { useWsConnectionStatus, WS_RECONNECT_MAX_ATTEMPTS, } from "../rpc/wsConnectionState"; -import { Button } from "./ui/button"; import { toastManager } from "./ui/toast"; -import { getWsRpcClient } from "~/wsRpcClient"; +import { getPrimaryEnvironmentConnection } from "../environments/runtime"; const FORCED_WS_RECONNECT_DEBOUNCE_MS = 5_000; type WsAutoReconnectTrigger = "focus" | "online"; @@ -58,11 +54,7 @@ function describeExhaustedToast(): string { return "Retries exhausted trying to reconnect"; } -function buildReconnectTitle(status: WsConnectionStatus): string { - if (status.nextRetryAt === null) { - return "Disconnected from T3 Server"; - } - +function buildReconnectTitle(_status: WsConnectionStatus): string { return "Disconnected from T3 Server"; } @@ -113,155 +105,6 @@ export function shouldAutoReconnect( ); } -function buildBlockingCopy( - uiState: WsConnectionUiState, - status: WsConnectionStatus, -): { - readonly description: string; - readonly eyebrow: string; - readonly title: string; -} { - if (uiState === "connecting") { - return { - description: `Opening the WebSocket connection to the ${APP_DISPLAY_NAME} server and waiting for the initial config snapshot.`, - eyebrow: "Starting Session", - title: `Connecting to ${APP_DISPLAY_NAME}`, - }; - } - - if (uiState === "offline") { - return { - description: - "Your browser is offline, so the web client cannot reach the T3 server. Reconnect to the network and the app will retry automatically.", - eyebrow: "Offline", - title: "WebSocket connection unavailable", - }; - } - - if (status.lastError?.trim()) { - return { - description: `${status.lastError} Verify that the T3 server is running and reachable, then reload the app if needed.`, - eyebrow: "Connection Error", - title: "Cannot reach the T3 server", - }; - } - - return { - description: - "The web client could not complete its initial WebSocket connection to the T3 server. It will keep retrying in the background.", - eyebrow: "Connection Error", - title: "Cannot reach the T3 server", - }; -} - -function buildConnectionDetails(status: WsConnectionStatus, uiState: WsConnectionUiState): string { - const details = [ - `state: ${uiState}`, - `online: ${status.online ? "yes" : "no"}`, - `attempts: ${status.attemptCount}`, - ]; - - if (status.socketUrl) { - details.push(`socket: ${status.socketUrl}`); - } - if (status.connectedAt) { - details.push(`connectedAt: ${status.connectedAt}`); - } - if (status.disconnectedAt) { - details.push(`disconnectedAt: ${status.disconnectedAt}`); - } - if (status.lastErrorAt) { - details.push(`lastErrorAt: ${status.lastErrorAt}`); - } - if (status.lastError) { - details.push(`lastError: ${status.lastError}`); - } - if (status.closeCode !== null) { - details.push(`closeCode: ${status.closeCode}`); - } - if (status.closeReason) { - details.push(`closeReason: ${status.closeReason}`); - } - - return details.join("\n"); -} - -function WebSocketBlockingState({ - status, - uiState, -}: { - readonly status: WsConnectionStatus; - readonly uiState: WsConnectionUiState; -}) { - const copy = buildBlockingCopy(uiState, status); - const disconnectedAt = formatConnectionMoment(status.disconnectedAt ?? status.lastErrorAt); - const Icon = - uiState === "connecting" ? LoaderCircle : uiState === "offline" ? CloudOff : AlertTriangle; - - return ( -
-
-
-
-
- -
-
-
-

- {copy.eyebrow} -

-

{copy.title}

-
-
- -
-
- -

{copy.description}

- -
-
-

- Connection -

-

- {uiState === "connecting" - ? "Opening WebSocket" - : uiState === "offline" - ? "Waiting for network" - : "Retrying server connection"} -

-
-
-

- Latest Event -

-

{disconnectedAt ?? "Pending"}

-
-
- -
- -
- -
- - Show connection details - Hide connection details - -
-            {buildConnectionDetails(status, uiState)}
-          
-
-
-
- ); -} - export function WebSocketConnectionCoordinator() { const status = useWsConnectionStatus(); const [nowMs, setNowMs] = useState(() => Date.now()); @@ -277,7 +120,7 @@ export function WebSocketConnectionCoordinator() { toastResetTimerRef.current = null; } lastForcedReconnectAtRef.current = Date.now(); - void getWsRpcClient() + void getPrimaryEnvironmentConnection() .reconnect() .catch((error) => { if (!showFailureToast) { @@ -527,18 +370,5 @@ export function SlowRpcAckToastCoordinator() { } export function WebSocketConnectionSurface({ children }: { readonly children: ReactNode }) { - const serverConfig = useServerConfig(); - const status = useWsConnectionStatus(); - - if (serverConfig === null) { - const uiState = getWsConnectionUiState(status); - return ( - - ); - } - return children; } diff --git a/apps/web/src/components/auth/PairingRouteSurface.tsx b/apps/web/src/components/auth/PairingRouteSurface.tsx new file mode 100644 index 0000000000..f583af72ec --- /dev/null +++ b/apps/web/src/components/auth/PairingRouteSurface.tsx @@ -0,0 +1,195 @@ +import type { AuthSessionState } from "@t3tools/contracts"; +import React, { startTransition, useEffect, useRef, useState, useCallback } from "react"; + +import { APP_DISPLAY_NAME } from "../../branding"; +import { + peekPairingTokenFromUrl, + stripPairingTokenFromUrl, + submitServerAuthCredential, +} from "../../environments/primary"; +import { Button } from "../ui/button"; +import { Input } from "../ui/input"; + +export function PairingPendingSurface() { + return ( +
+
+
+
+
+
+ +
+

+ {APP_DISPLAY_NAME} +

+

+ Pairing with this environment +

+

+ Validating the pairing link and preparing your session. +

+
+
+ ); +} + +export function PairingRouteSurface({ + auth, + initialErrorMessage, + onAuthenticated, +}: { + auth: AuthSessionState["auth"]; + initialErrorMessage?: string; + onAuthenticated: () => void; +}) { + const autoPairTokenRef = useRef(peekPairingTokenFromUrl()); + const [credential, setCredential] = useState(() => autoPairTokenRef.current ?? ""); + const [errorMessage, setErrorMessage] = useState(initialErrorMessage ?? ""); + const [isSubmitting, setIsSubmitting] = useState(false); + const autoSubmitAttemptedRef = useRef(false); + + const submitCredential = useCallback( + async (nextCredential: string) => { + setIsSubmitting(true); + setErrorMessage(""); + + const submitError = await submitServerAuthCredential(nextCredential).then( + () => null, + (error) => errorMessageFromUnknown(error), + ); + + setIsSubmitting(false); + + if (submitError) { + setErrorMessage(submitError); + return; + } + + startTransition(() => { + onAuthenticated(); + }); + }, + [onAuthenticated], + ); + + const handleSubmit = useCallback( + async (event?: React.SubmitEvent) => { + event?.preventDefault(); + await submitCredential(credential); + }, + [submitCredential, credential], + ); + + useEffect(() => { + const token = autoPairTokenRef.current; + if (!token || autoSubmitAttemptedRef.current) { + return; + } + + autoSubmitAttemptedRef.current = true; + stripPairingTokenFromUrl(); + void submitCredential(token); + }, [submitCredential]); + + return ( +
+
+
+
+
+
+ +
+

+ {APP_DISPLAY_NAME} +

+

+ Pair with this environment +

+

+ {describeAuthGate(auth.bootstrapMethods)} +

+ +
void handleSubmit(event)}> +
+ + setCredential(event.currentTarget.value)} + placeholder="Paste a one-time token or pairing secret" + spellCheck={false} + value={credential} + /> +
+ + {errorMessage ? ( +
+ {errorMessage} +
+ ) : null} + +
+ + +
+
+ +
+ {describeSupportedMethods(auth.bootstrapMethods)} +
+
+
+ ); +} + +function errorMessageFromUnknown(error: unknown): string { + if (error instanceof Error && error.message.trim().length > 0) { + return error.message; + } + + if (typeof error === "string" && error.trim().length > 0) { + return error; + } + + return "Authentication failed."; +} + +function describeAuthGate(bootstrapMethods: ReadonlyArray): string { + if (bootstrapMethods.includes("desktop-bootstrap")) { + return "This environment expects a trusted pairing credential before the app can connect."; + } + + return "Enter a pairing token to start a session with this environment."; +} + +function describeSupportedMethods(bootstrapMethods: ReadonlyArray): string { + if ( + bootstrapMethods.includes("desktop-bootstrap") && + bootstrapMethods.includes("one-time-token") + ) { + return "Desktop-managed pairing and one-time pairing tokens are both accepted for this environment."; + } + + if (bootstrapMethods.includes("desktop-bootstrap")) { + return "This environment is desktop-managed. Open it from the desktop app or paste a bootstrap credential if one was issued explicitly."; + } + + return "This environment accepts one-time pairing tokens. Pairing links can open this page directly, or you can paste the token here."; +} diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsx new file mode 100644 index 0000000000..396f255f79 --- /dev/null +++ b/apps/web/src/components/settings/ConnectionsSettings.tsx @@ -0,0 +1,1441 @@ +import { PlusIcon, QrCodeIcon } from "lucide-react"; +import { memo, useCallback, useEffect, useMemo, useState } from "react"; +import { + type AuthClientSession, + type AuthPairingLink, + type DesktopServerExposureState, + type EnvironmentId, +} from "@t3tools/contracts"; +import { DateTime } from "effect"; + +import { useCopyToClipboard } from "../../hooks/useCopyToClipboard"; +import { cn } from "../../lib/utils"; +import { formatElapsedDurationLabel, formatExpiresInLabel } from "../../timestampFormat"; +import { + SettingsPageContainer, + SettingsRow, + SettingsSection, + useRelativeTimeTick, +} from "./settingsLayout"; +import { Input } from "../ui/input"; +import { + Dialog, + DialogFooter, + DialogDescription, + DialogHeader, + DialogPanel, + DialogPopup, + DialogTitle, + DialogTrigger, +} from "../ui/dialog"; +import { + AlertDialog, + AlertDialogClose, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogPopup, + AlertDialogTitle, +} from "../ui/alert-dialog"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { QRCodeSvg } from "../ui/qr-code"; +import { Spinner } from "../ui/spinner"; +import { Switch } from "../ui/switch"; +import { toastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { Button } from "../ui/button"; +import { Textarea } from "../ui/textarea"; +import { setPairingTokenOnUrl } from "../../pairingUrl"; +import { + createServerPairingCredential, + fetchSessionState, + revokeOtherServerClientSessions, + revokeServerClientSession, + revokeServerPairingLink, + type ServerClientSessionRecord, + type ServerPairingLinkRecord, +} from "../../environments/primary"; +import type { WsRpcClient } from "~/rpc/wsRpcClient"; +import { + type SavedEnvironmentRecord, + type SavedEnvironmentRuntimeState, + useSavedEnvironmentRegistryStore, + useSavedEnvironmentRuntimeStore, + addSavedEnvironment, + getPrimaryEnvironmentConnection, + reconnectSavedEnvironment, + removeSavedEnvironment, +} from "../../environments/runtime"; + +const accessTimestampFormatter = new Intl.DateTimeFormat(undefined, { + dateStyle: "medium", + timeStyle: "short", +}); + +function formatAccessTimestamp(value: string): string { + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) { + return value; + } + return accessTimestampFormatter.format(parsed); +} + +type ConnectionStatusDotProps = { + tooltipText?: string | null; + dotClassName: string; + pingClassName?: string | null; +}; + +function ConnectionStatusDot({ + tooltipText, + dotClassName, + pingClassName, +}: ConnectionStatusDotProps) { + const dotContent = ( + <> + {pingClassName ? ( + + ) : null} + + + ); + + if (!tooltipText) { + return ( + + {dotContent} + + ); + } + + const dot = ( + + ); + + return ( + + + + {tooltipText} + + + ); +} + +function getSavedBackendStatusTooltip( + runtime: SavedEnvironmentRuntimeState | null, + record: SavedEnvironmentRecord, + nowMs: number, +) { + const connectionState = runtime?.connectionState ?? "disconnected"; + + if (connectionState === "connected") { + const connectedAt = runtime?.connectedAt ?? record.lastConnectedAt; + return connectedAt ? `Connected for ${formatElapsedDurationLabel(connectedAt, nowMs)}` : null; + } + + if (connectionState === "connecting") { + return null; + } + + if (connectionState === "error") { + return runtime?.lastError ?? "An unknown connection error occurred."; + } + + return record.lastConnectedAt + ? `Last connected at ${formatAccessTimestamp(record.lastConnectedAt)}` + : "Not connected yet."; +} + +/** Direct row in the card – same pattern as the Provider / ACP-agent list rows. */ +const ITEM_ROW_CLASSNAME = "border-t border-border/60 px-4 py-4 first:border-t-0 sm:px-5"; + +const ITEM_ROW_INNER_CLASSNAME = + "flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"; + +function sortDesktopPairingLinks(links: ReadonlyArray) { + return [...links].toSorted( + (left, right) => new Date(right.createdAt).getTime() - new Date(left.createdAt).getTime(), + ); +} + +function sortDesktopClientSessions(sessions: ReadonlyArray) { + return [...sessions].toSorted((left, right) => { + if (left.current !== right.current) { + return left.current ? -1 : 1; + } + if (left.connected !== right.connected) { + return left.connected ? -1 : 1; + } + return new Date(right.issuedAt).getTime() - new Date(left.issuedAt).getTime(); + }); +} + +function toDesktopPairingLinkRecord(pairingLink: AuthPairingLink): ServerPairingLinkRecord { + return { + ...pairingLink, + createdAt: DateTime.formatIso(pairingLink.createdAt), + expiresAt: DateTime.formatIso(pairingLink.expiresAt), + }; +} + +function toDesktopClientSessionRecord(clientSession: AuthClientSession): ServerClientSessionRecord { + return { + ...clientSession, + issuedAt: DateTime.formatIso(clientSession.issuedAt), + expiresAt: DateTime.formatIso(clientSession.expiresAt), + lastConnectedAt: + clientSession.lastConnectedAt === null + ? null + : DateTime.formatIso(clientSession.lastConnectedAt), + }; +} + +function upsertDesktopPairingLink( + current: ReadonlyArray, + next: ServerPairingLinkRecord, +) { + const existingIndex = current.findIndex((pairingLink) => pairingLink.id === next.id); + if (existingIndex === -1) { + return sortDesktopPairingLinks([...current, next]); + } + const updated = [...current]; + updated[existingIndex] = next; + return sortDesktopPairingLinks(updated); +} + +function removeDesktopPairingLink(current: ReadonlyArray, id: string) { + return current.filter((pairingLink) => pairingLink.id !== id); +} + +function upsertDesktopClientSession( + current: ReadonlyArray, + next: ServerClientSessionRecord, +) { + const existingIndex = current.findIndex( + (clientSession) => clientSession.sessionId === next.sessionId, + ); + if (existingIndex === -1) { + return sortDesktopClientSessions([...current, next]); + } + const updated = [...current]; + updated[existingIndex] = next; + return sortDesktopClientSessions(updated); +} + +function removeDesktopClientSession( + current: ReadonlyArray, + sessionId: ServerClientSessionRecord["sessionId"], +) { + return current.filter((clientSession) => clientSession.sessionId !== sessionId); +} + +function resolveDesktopPairingUrl(endpointUrl: string, credential: string): string { + const url = new URL(endpointUrl); + url.pathname = "/pair"; + return setPairingTokenOnUrl(url, credential).toString(); +} + +function resolveCurrentOriginPairingUrl(credential: string): string { + const url = new URL("/pair", window.location.href); + return setPairingTokenOnUrl(url, credential).toString(); +} + +function isLoopbackHostname(hostname: string): boolean { + const normalized = hostname.trim().toLowerCase(); + return ( + normalized === "localhost" || + normalized === "127.0.0.1" || + normalized === "::1" || + normalized === "[::1]" + ); +} + +type PairingLinkListRowProps = { + pairingLink: ServerPairingLinkRecord; + endpointUrl: string | null | undefined; + revokingPairingLinkId: string | null; + onRevoke: (id: string) => void; +}; + +const PairingLinkListRow = memo(function PairingLinkListRow({ + pairingLink, + endpointUrl, + revokingPairingLinkId, + onRevoke, +}: PairingLinkListRowProps) { + const nowMs = useRelativeTimeTick(1_000); + const expiresAtMs = useMemo( + () => new Date(pairingLink.expiresAt).getTime(), + [pairingLink.expiresAt], + ); + const [isRevealDialogOpen, setIsRevealDialogOpen] = useState(false); + + const currentOriginPairingUrl = useMemo( + () => resolveCurrentOriginPairingUrl(pairingLink.credential), + [pairingLink.credential], + ); + const shareablePairingUrl = + endpointUrl != null && endpointUrl !== "" + ? resolveDesktopPairingUrl(endpointUrl, pairingLink.credential) + : isLoopbackHostname(window.location.hostname) + ? null + : currentOriginPairingUrl; + const copyValue = shareablePairingUrl ?? pairingLink.credential; + const canCopyToClipboard = + typeof window !== "undefined" && + window.isSecureContext && + navigator.clipboard?.writeText != null; + + const { copyToClipboard, isCopied } = useCopyToClipboard({ + onCopy: () => { + toastManager.add({ + type: "success", + title: shareablePairingUrl ? "Pairing URL copied" : "Pairing token copied", + description: shareablePairingUrl + ? "Open it in the client you want to pair to this environment." + : "Paste it into another client with this backend's reachable host.", + }); + }, + onError: (error) => { + setIsRevealDialogOpen(true); + toastManager.add({ + type: "error", + title: canCopyToClipboard ? "Could not copy pairing URL" : "Clipboard copy unavailable", + description: canCopyToClipboard ? error.message : "Showing the full value instead.", + }); + }, + }); + + const handleCopy = useCallback(() => { + copyToClipboard(copyValue, undefined); + }, [copyToClipboard, copyValue]); + + const expiresAbsolute = formatAccessTimestamp(pairingLink.expiresAt); + + const roleLabel = pairingLink.role === "owner" ? "Owner" : "Client"; + const primaryLabel = pairingLink.label ?? `${roleLabel} link`; + + if (expiresAtMs <= nowMs) { + return null; + } + + return ( +
+
+
+
+ +

{primaryLabel}

+ + {shareablePairingUrl ? ( + <> + + } + > + + + + + + + ) : null} + +
+

+ {[roleLabel, formatExpiresInLabel(pairingLink.expiresAt, nowMs)].join(" · ")} +

+ {shareablePairingUrl === null ? ( +

+ Copy the token and pair from another client using this backend's reachable host. +

+ ) : null} +
+
+ + {canCopyToClipboard ? ( + + ) : ( + }> + {shareablePairingUrl ? "Show link" : "Show token"} + + )} + + + {shareablePairingUrl ? "Pairing link" : "Pairing token"} + + {shareablePairingUrl + ? "Clipboard copy is unavailable here. Open or manually copy this full pairing URL on the device you want to connect." + : "Clipboard copy is unavailable here. Manually copy this token and pair from another client using this backend's reachable host."} + + + +