-
Notifications
You must be signed in to change notification settings - Fork 22
fix(vite): share an https dev server for the hub WebSocket #419
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e54fde6
fix(vite): share an https dev server for the hub WebSocket
erkamyaman c4b6aef
fix(devframe): advertise wss for a shared TLS server
erkamyaman d18d2e2
test(vite): open a real wss handshake on the https hub server
erkamyaman 7222527
chore: let knip accept the openssl binary in the vite hub test
erkamyaman e324dd3
fix(devframe): publish a shared server's WS endpoint once it listens
erkamyaman 8c10677
test(vite): configure the hub before the https server listens
erkamyaman 3940156
refactor(devframe): trim the shared-server wss endpoint change
antfubot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| import type { DevframeHubContext } from '@devframes/hub/node' | ||
| import type { IncomingMessage, ServerResponse } from 'node:http' | ||
| import type { Http2SecureServer } from 'node:http2' | ||
| import type { Socket } from 'node:net' | ||
| import type { ViteDevServer } from 'vite' | ||
| import { execFileSync } from 'node:child_process' | ||
| import { mkdtempSync, readFileSync } from 'node:fs' | ||
| import { createSecureServer } from 'node:http2' | ||
| import { request } from 'node:https' | ||
| import { tmpdir } from 'node:os' | ||
| import { join } from 'node:path' | ||
| import { getInternalContext } from 'devframe/node/hub-internals' | ||
| import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest' | ||
| import { WebSocket } from 'ws' | ||
| import { viteDevframeHub } from '../src/hub' | ||
|
|
||
| type ConnectMiddleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void | ||
|
|
||
| function hasOpenssl(): boolean { | ||
| try { | ||
| execFileSync('openssl', ['version'], { stdio: 'ignore' }) | ||
| return true | ||
| } | ||
| catch { | ||
| return false | ||
| } | ||
| } | ||
|
|
||
| const opensslAvailable = hasOpenssl() | ||
| if (!opensslAvailable) | ||
| console.warn('[vite hub test] openssl not found, skipping the https dev server test') | ||
|
|
||
| /** | ||
| * Vite on `server.https` hands plugins an `Http2SecureServer` with | ||
| * `allowHTTP1`, which is not a `node:http` `Server`. This one runs the | ||
| * plugin's connect middlewares like Vite does. | ||
| */ | ||
| function fakeHttpsViteServer(tls: { key: string, cert: string }) { | ||
| const stack: ConnectMiddleware[] = [] | ||
| const httpServer: Http2SecureServer = createSecureServer({ ...tls, allowHTTP1: true }) | ||
| httpServer.on('request', (req: IncomingMessage, res: ServerResponse) => { | ||
| let i = 0 | ||
| const next = (): void => { | ||
| const handler = stack[i++] | ||
| if (!handler) { | ||
| res.statusCode = 404 | ||
| res.end() | ||
| return | ||
| } | ||
| handler(req, res, next) | ||
| } | ||
| next() | ||
| }) | ||
| const sockets = new Set<Socket>() | ||
| httpServer.on('secureConnection', (socket: Socket) => { | ||
| sockets.add(socket) | ||
| socket.once('close', () => sockets.delete(socket)) | ||
| }) | ||
| const server = { | ||
| httpServer, | ||
| resolvedUrls: null, | ||
| middlewares: { use: (handler: ConnectMiddleware) => stack.push(handler) }, | ||
| } | ||
| const close = async (): Promise<void> => { | ||
| for (const socket of sockets) | ||
| socket.destroy() | ||
| await new Promise<void>(resolve => httpServer.close(() => resolve())) | ||
| } | ||
| return { server, httpServer, close } | ||
| } | ||
|
|
||
| function getInsecure(url: string): Promise<{ status: number, body: string }> { | ||
| return new Promise((resolve, reject) => { | ||
| request(url, { rejectUnauthorized: false }, (res) => { | ||
| let body = '' | ||
| res.setEncoding('utf8') | ||
| res.on('data', (chunk: string) => body += chunk) | ||
| res.on('end', () => resolve({ status: res.statusCode ?? 0, body })) | ||
| }).on('error', reject).end() | ||
| }) | ||
| } | ||
|
|
||
| function openWs(url: string): Promise<WebSocket> { | ||
| return new Promise((resolve, reject) => { | ||
| const ws = new WebSocket(url, { rejectUnauthorized: false }) | ||
| ws.once('open', () => resolve(ws)) | ||
| ws.once('error', reject) | ||
| }) | ||
| } | ||
|
|
||
| describe.skipIf(!opensslAvailable)('viteDevframeHub', () => { | ||
| let tls: { key: string, cert: string } | ||
| let cleanup: (() => Promise<void>) | undefined | ||
|
|
||
| beforeAll(() => { | ||
| const dir = mkdtempSync(join(tmpdir(), 'devframe-vite-hub-tls-')) | ||
| const keyPath = join(dir, 'key.pem') | ||
| const certPath = join(dir, 'cert.pem') | ||
| execFileSync('openssl', [ | ||
| 'req', | ||
| '-x509', | ||
| '-newkey', | ||
| 'rsa:2048', | ||
| '-nodes', | ||
| '-keyout', | ||
| keyPath, | ||
| '-out', | ||
| certPath, | ||
| '-days', | ||
| '1', | ||
| '-subj', | ||
| '/CN=localhost', | ||
| ], { stdio: 'ignore' }) | ||
| tls = { key: readFileSync(keyPath, 'utf8'), cert: readFileSync(certPath, 'utf8') } | ||
| }) | ||
|
|
||
| afterEach(async () => { | ||
| await cleanup?.() | ||
| cleanup = undefined | ||
| }) | ||
|
|
||
| it('shares an https (http2) dev server for the WebSocket upgrade', async () => { | ||
| const host = '127.0.0.1' | ||
| const { server, httpServer, close } = fakeHttpsViteServer(tls) | ||
| let context: DevframeHubContext | undefined | ||
|
|
||
| const plugin = viteDevframeHub({ | ||
| ui: false, | ||
| auth: false, | ||
| quiet: true, | ||
| cwd: mkdtempSync(join(tmpdir(), 'devframe-vite-hub-')), | ||
| configure: (ctx) => { | ||
| context = ctx | ||
| }, | ||
| }) | ||
| let ws: WebSocket | undefined | ||
| cleanup = async () => { | ||
| ws?.terminate() | ||
| await (plugin.closeBundle as () => Promise<void>)() | ||
| await close() | ||
| } | ||
| await (plugin.configureServer as (s: ViteDevServer) => Promise<void>)(server as any) | ||
| await vi.waitFor(() => expect(httpServer.listenerCount('upgrade')).toBeGreaterThan(0)) | ||
| await new Promise<void>(resolve => httpServer.listen(0, host, resolve)) | ||
| const { port } = httpServer.address() as { port: number } | ||
|
|
||
| const res = await getInsecure(`https://${host}:${port}/__devframes/__connection.json`) | ||
| expect(res.status).toBe(200) | ||
| expect((JSON.parse(res.body) as { websocket?: unknown }).websocket).toEqual({ path: '/__devframes/__ws' }) | ||
|
|
||
| ws = await openWs(`wss://${host}:${port}/__devframes/__ws`) | ||
| expect(ws.readyState).toBe(WebSocket.OPEN) | ||
|
|
||
| expect(context).toBeDefined() | ||
| expect(getInternalContext(context!).wsEndpoint).toEqual({ url: `wss://localhost:${port}/__devframes/__ws` }) | ||
| }) | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.