1+ import * as NodeSocket from "@effect/platform-node/NodeSocket" ;
12import {
23 CONFIGURED_LOCAL_SERVER_URLS_MAX_ITEMS ,
34 PREVIEW_URL_MAX_LENGTH ,
@@ -20,6 +21,7 @@ import * as Schedule from "effect/Schedule";
2021import * as Scope from "effect/Scope" ;
2122import * as Semaphore from "effect/Semaphore" ;
2223import { FetchHttpClient , HttpClient } from "effect/http" ;
24+ import * as Socket from "effect/socket/Socket" ;
2325
2426import * as ProcessRunner from "../processRunner.ts" ;
2527
@@ -73,8 +75,8 @@ export class PortDiscovery extends Context.Service<
7375 readonly listListeners : Effect . Effect < ReadonlyArray < ListeningSocket > | null > ;
7476 /**
7577 * The protocol the port serves a web page over: HTTP on either loopback address, else HTTPS,
76- * else null. Uncached. Only probe ports attributed to a known owner: HTTP or TLS bytes can
77- * crash a binary protocol.
78+ * else null. Uncached. HTTPS accepts any certificate, since dev servers often self-sign. Only
79+ * probe ports attributed to a known owner: HTTP or TLS bytes can crash a binary protocol.
7880 */
7981 readonly probeWeb : ( port : number ) => Effect . Effect < WebProtocol | null > ;
8082 readonly terminalProcessOwners : Effect . Effect <
@@ -97,6 +99,8 @@ const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60));
9799const WINDOWS_PROCESS_NAME_CONCURRENCY = 4 ;
98100const WEB_PROBE_CONCURRENCY = 16 ;
99101const NAVIGATION_REDIRECT_STATUSES = new Set ( [ 301 , 302 , 303 , 307 , 308 ] ) ;
102+ /** Node's default cap on HTTP response headers; a head that grows past it is not a dev server's. */
103+ const WEB_PROBE_HEAD_MAX_BYTES = 16 * 1024 ;
100104
101105type Listener = ( servers : ReadonlyArray < DiscoveredLocalServer > ) => Effect . Effect < void > ;
102106
@@ -480,6 +484,76 @@ const serversEqual = (
480484const isCommandNotFound = ( error : ProcessRunner . ProcessSpawnError ) : boolean =>
481485 PlatformError . isPlatformError ( error . cause ) && error . cause . reason . _tag === "NotFound" ;
482486
487+ /** A page a browser would render, or a redirect to one. */
488+ const isPageResponse = ( response : {
489+ readonly status : number ;
490+ readonly location : string | undefined ;
491+ readonly contentType : string | undefined ;
492+ } ) : boolean => {
493+ if ( NAVIGATION_REDIRECT_STATUSES . has ( response . status ) && response . location ?. trim ( ) ) return true ;
494+ if ( response . status < 200 || response . status >= 300 ) return false ;
495+ if ( response . status === 204 || response . status === 205 ) return false ;
496+ const mediaType = response . contentType ?. split ( ";" , 1 ) [ 0 ] ?. trim ( ) . toLowerCase ( ) ;
497+ return mediaType === "text/html" || mediaType === "application/xhtml+xml" ;
498+ } ;
499+
500+ /** Reads a raw HTTP/1.x response head: the status line, then `name: value` header lines. */
501+ const parseResponseHead = ( head : string ) => {
502+ const [ statusLine = "" , ...lines ] = head . split ( "\r\n" ) ;
503+ const status = / ^ H T T P \/ 1 \. [ 0 1 ] ( \d { 3 } ) (?: | $ ) / . exec ( statusLine ) ?. [ 1 ] ;
504+ if ( status === undefined ) return null ;
505+ const headers = new Map < string , string > ( ) ;
506+ for ( const line of lines ) {
507+ const colon = line . indexOf ( ":" ) ;
508+ const name = line . slice ( 0 , colon ) . trim ( ) . toLowerCase ( ) ;
509+ if ( colon > 0 && ! headers . has ( name ) ) headers . set ( name , line . slice ( colon + 1 ) . trim ( ) ) ;
510+ }
511+ return {
512+ status : Number ( status ) ,
513+ location : headers . get ( "location" ) ,
514+ contentType : headers . get ( "content-type" ) ,
515+ } ;
516+ } ;
517+
518+ /**
519+ * Whether a loopback TLS listener serves a page. Dev servers serve HTTPS with self-signed
520+ * certificates (Vite's basic-ssl, ad-hoc certs) that fetch rejects, so this one connection skips
521+ * verification instead of trusting them process-wide. Nothing is sent but a bodiless `GET /` to a
522+ * loopback address, and the answer only classifies the port.
523+ */
524+ const probeTlsPage = Effect . fn ( "PortDiscovery.probeTlsPage" ) (
525+ function * ( host : "127.0.0.1" | "::1" , port : number ) {
526+ const socket = yield * NodeSocket . makeTls ( {
527+ host,
528+ port,
529+ // The name the preview opens, so SNI-picked certificates and host allowlists answer as
530+ // they will for the browser.
531+ servername : "localhost" ,
532+ rejectUnauthorized : false ,
533+ ALPNProtocols : [ "http/1.1" ] ,
534+ } ) ;
535+ const pull = yield * Socket . readerBytes ( socket ) ;
536+ const writer = yield * socket . writer ;
537+ yield * writer . write ( `GET / HTTP/1.1\r\nHost: localhost:${ port } \r\nConnection: close\r\n\r\n` ) ;
538+ const decoder = new TextDecoder ( ) ;
539+ let received = "" ;
540+ let byteCount = 0 ;
541+ while ( ! received . includes ( "\r\n\r\n" ) ) {
542+ if ( byteCount > WEB_PROBE_HEAD_MAX_BYTES ) return false ;
543+ for ( const chunk of yield * pull ) {
544+ byteCount += chunk . byteLength ;
545+ received += decoder . decode ( chunk , { stream : true } ) ;
546+ }
547+ }
548+ const response = parseResponseHead ( received . slice ( 0 , received . indexOf ( "\r\n\r\n" ) ) ) ;
549+ return response !== null && isPageResponse ( response ) ;
550+ } ,
551+ Effect . scoped ,
552+ Effect . timeoutOption ( WEB_PROBE_TIMEOUT ) ,
553+ Effect . map ( Option . getOrElse ( ( ) => false ) ) ,
554+ Effect . orElseSucceed ( ( ) => false ) ,
555+ ) ;
556+
483557/** @public Service construction is part of the canonical Effect module API. */
484558export const make = Effect . gen ( function * PortDiscoveryMake ( ) {
485559 const processRunner = yield * ProcessRunner . ProcessRunner ;
@@ -603,17 +677,15 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
603677
604678 const probeWebUrl = Effect . fn ( "PortDiscovery.probeWebUrl" ) ( ( url : string ) =>
605679 httpClient . get ( url ) . pipe (
606- Effect . map ( ( response ) => {
607- const location = response . headers . location ?. trim ( ) ;
608- if ( NAVIGATION_REDIRECT_STATUSES . has ( response . status ) && location ) return url ;
609- if ( response . status < 200 || response . status >= 300 ) return null ;
610- if ( response . status === 204 || response . status === 205 ) return null ;
611- const contentType = response . headers [ "content-type" ]
612- ?. split ( ";" , 1 ) [ 0 ]
613- ?. trim ( )
614- . toLowerCase ( ) ;
615- return contentType === "text/html" || contentType === "application/xhtml+xml" ? url : null ;
616- } ) ,
680+ Effect . map ( ( response ) =>
681+ isPageResponse ( {
682+ status : response . status ,
683+ location : response . headers . location ,
684+ contentType : response . headers [ "content-type" ] ,
685+ } )
686+ ? url
687+ : null ,
688+ ) ,
617689 Effect . scoped ,
618690 Effect . timeoutOption ( WEB_PROBE_TIMEOUT ) ,
619691 Effect . map ( Option . getOrNull ) ,
@@ -910,8 +982,13 @@ export const make = Effect.gen(function* PortDiscoveryMake() {
910982 // loopback address is asked directly.
911983 const probeLoopback = ( protocol : WebProtocol , port : number ) =>
912984 Effect . forEach (
913- [ `${ protocol } ://127.0.0.1:${ port } ` , `${ protocol } ://[::1]:${ port } ` ] ,
914- ( url ) => probeWebUrl ( url ) . pipe ( Effect . map ( ( visible ) => visible !== null ) ) ,
985+ [ "127.0.0.1" , "::1" ] as const ,
986+ ( host ) =>
987+ protocol === "https"
988+ ? probeTlsPage ( host , port )
989+ : probeWebUrl ( `http://${ host === "::1" ? "[::1]" : host } :${ port } ` ) . pipe (
990+ Effect . map ( ( visible ) => visible !== null ) ,
991+ ) ,
915992 { concurrency : 2 } ,
916993 ) . pipe ( Effect . map ( ( answers ) => ( answers . some ( Boolean ) ? protocol : null ) ) ) ;
917994
0 commit comments