Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"type": "module",
"version": "0.0.0-alpha.19",
"private": true,
"packageManager": "pnpm@10.24.0",
"packageManager": "pnpm@10.25.0",
"scripts": {
"build": "pnpm -r run build",
"build:debug": "NUXT_DEBUG_BUILD=true pnpm -r run build",
Expand Down Expand Up @@ -69,6 +69,7 @@
"@jridgewell/sourcemap-codec": "1.5.0",
"@nuxt/devtools": "catalog:devtools",
"@nuxt/kit": "catalog:build",
"@nuxt/vite-builder": "catalog:build",
"@rolldown/debug": "catalog:deps",
"esbuild": "catalog:build",
"nitropack": "catalog:build",
Expand Down
1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
"ws": "catalog:deps"
},
"devDependencies": {
"@clack/prompts": "catalog:inlined",
"@vitejs/devtools": "workspace:*",
"@vitejs/devtools-vite": "workspace:*",
"@vitejs/plugin-vue": "catalog:build",
Expand Down
12 changes: 2 additions & 10 deletions packages/core/src/client/inject/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,7 @@ export async function init(): Promise<void> {
// eslint-disable-next-line no-console
console.log('[VITE DEVTOOLS] Client injected')

const rpcReturn = await getDevToolsRpcClient()
const { rpc } = rpcReturn

// eslint-disable-next-line no-console
console.log('[VITE DEVTOOLS] RPC', rpc)

const rpcFunctions = await rpc.$call('vite:internal:rpc:server:list')
// eslint-disable-next-line no-console
console.log('[VITE DEVTOOLS] RPC Functions', rpcFunctions)
const rpc = await getDevToolsRpcClient()

const state = useLocalStorage<DockPanelStorage>(
'vite-devtools-dock-state',
Expand All @@ -36,7 +28,7 @@ export async function init(): Promise<void> {

const context = await createDocksContext(
'embedded',
rpcReturn,
rpc,
state,
)

Expand Down
5 changes: 2 additions & 3 deletions packages/core/src/client/standalone/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import ViewEntry from '../webcomponents/components/ViewEntry.vue'
import { createDocksContext } from '../webcomponents/state/context'
import { PersistedDomViewsManager } from '../webcomponents/utils/PersistedDomViewsManager'

const rpcReturn = await getDevToolsRpcClient()
const { rpc } = rpcReturn
const rpc = await getDevToolsRpcClient()

// eslint-disable-next-line no-console
console.log('[VITE DEVTOOLS] RPC', rpc)
Expand All @@ -19,7 +18,7 @@ const persistedDoms = markRaw(new PersistedDomViewsManager(viewsContainer))

const context: DocksContext = await createDocksContext(
'standalone',
rpcReturn,
rpc,
)

context.docks.selectedId ||= context.docks.entries[0]?.id ?? null
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/client/webcomponents/.generated/css.ts

Large diffs are not rendered by default.

17 changes: 16 additions & 1 deletion packages/core/src/client/webcomponents/components/Dock.vue
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ function onPointerDown(e: PointerEvent) {
draggingOffset.y = e.clientY - top - height / 2
}

const isRpcTrusted = ref(context.rpc.isTrusted)
context.rpc.events.on('rpc:is-trusted:updated', (isTrusted) => {
isRpcTrusted.value = isTrusted
})

onMounted(() => {
windowSize.width = window.innerWidth
windowSize.height = window.innerHeight
Expand Down Expand Up @@ -220,7 +225,10 @@ const panelStyle = computed(() => {
})

onMounted(() => {
bringUp()
if (context.panel.store.open && !isRpcTrusted.value)
context.panel.store.open = false
if (isRpcTrusted.value)
bringUp()
recalculateCounter.value++
})
</script>
Expand Down Expand Up @@ -268,6 +276,13 @@ onMounted(() => {
class="w-3 h-3 absolute left-1/2 top-1/2 translate-x--1/2 translate-y--1/2 transition-opacity duration-300"
:class="isMinimized ? 'op100' : 'op0'"
/>
<div
v-if="!isRpcTrusted"
class="p2"
:class="isMinimized ? 'opacity-0 pointer-events-none ws-nowrap flex items-center text-sm text-orange' : 'opacity-100'"
>
IS NOT TRUSTED
</div>
<DockEntries
:entries="context.docks.entries"
class="transition duration-200 flex items-center w-full h-full justify-center"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ onMounted(async () => {
props.terminal.terminal = term

if (props.terminal.buffer == null) {
const { buffer } = await props.context.rpc.$call('vite:internal:terminals:read', props.terminal.info.id)
const { buffer } = await props.context.rpc.call('vite:internal:terminals:read', props.terminal.info.id)
props.terminal.buffer = markRaw(buffer)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const props = defineProps<{
}>()
function onLaunch() {
props.context.rpc.$call('vite:internal:docks:on-launch', props.entry.id)
props.context.rpc.call('vite:internal:docks:on-launch', props.entry.id)
}
const status = computed(() => props.entry.launcher.status || 'idle')
Expand Down
9 changes: 4 additions & 5 deletions packages/core/src/client/webcomponents/state/context.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ClientRpcReturn, DockClientScriptContext, DockEntryState, DockPanelStorage, DocksContext } from '@vitejs/devtools-kit/client'
import type { DevToolsRpcClient, DockClientScriptContext, DockEntryState, DockPanelStorage, DocksContext } from '@vitejs/devtools-kit/client'
import type { Ref } from 'vue'
import { computed, markRaw, reactive, ref, toRefs, watchEffect } from 'vue'
import { createDockEntryState, DEFAULT_DOCK_PANEL_STORE, useDocksEntries } from './docks'
Expand All @@ -7,15 +7,15 @@ import { executeSetupScript } from './setup-script'
let _docksContext: DocksContext | undefined
export async function createDocksContext(
clientType: 'embedded' | 'standalone',
rpcReturn: ClientRpcReturn,
rpc: DevToolsRpcClient,
panelStore?: Ref<DockPanelStorage>,
): Promise<DocksContext> {
if (_docksContext) {
return _docksContext
}

const selectedId = ref<string | null>(null)
const dockEntries = await useDocksEntries(rpcReturn)
const dockEntries = await useDocksEntries(rpc)
const selected = computed(() => dockEntries.value.find(entry => entry.id === selectedId.value) ?? null)

const dockEntryStateMap: Map<string, DockEntryState> = reactive(new Map())
Expand Down Expand Up @@ -76,8 +76,7 @@ export async function createDocksContext(
return true
},
},
rpc: rpcReturn.rpc,
clientRpc: rpcReturn.clientRpc,
rpc,
clientType,
})

Expand Down
16 changes: 12 additions & 4 deletions packages/core/src/client/webcomponents/state/docks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { DevToolsDockEntry, DevToolsRpcClientFunctions } from '@vitejs/devtools-kit'
import type { ClientRpcReturn, DockEntryState, DockEntryStateEvents, DockPanelStorage } from '@vitejs/devtools-kit/client'
import type { DevToolsRpcClient, DockEntryState, DockEntryStateEvents, DockPanelStorage } from '@vitejs/devtools-kit/client'
import type { Ref, ShallowRef } from 'vue'
import { createEventEmitter } from '@vitejs/devtools-kit/utils/events'
import { markRaw, reactive, shallowRef, watch } from 'vue'
Expand Down Expand Up @@ -53,18 +53,26 @@ export function createDockEntryState(
}

let _docksEntriesRef: ShallowRef<DevToolsDockEntry[]> | undefined
export async function useDocksEntries(rpcReturn: ClientRpcReturn): Promise<Ref<DevToolsDockEntry[]>> {
export async function useDocksEntries(rpc: DevToolsRpcClient): Promise<Ref<DevToolsDockEntry[]>> {
if (_docksEntriesRef) {
return _docksEntriesRef
}
const dockEntries = _docksEntriesRef = shallowRef<DevToolsDockEntry[]>([])
async function updateDocksEntries() {
dockEntries.value = (await rpcReturn.rpc.$call('vite:internal:docks:list'))
if (!rpc.isTrusted) {
console.warn('[VITE DEVTOOLS] Untrusted client, skipping docks entries update')
return
}
dockEntries.value = (await rpc.call('vite:internal:docks:list'))
.map(entry => Object.freeze(entry))
// eslint-disable-next-line no-console
console.log('[VITE DEVTOOLS] Docks Entries Updated', [...dockEntries.value])
}
rpcReturn.clientRpc.register({
rpc.events.on('rpc:is-trusted:updated', (isTrusted) => {
if (isTrusted)
updateDocksEntries()
})
rpc.client.register({
name: 'vite:internal:docks:updated' satisfies keyof DevToolsRpcClientFunctions,
type: 'action',
handler: () => updateDocksEntries(),
Expand Down
6 changes: 3 additions & 3 deletions packages/core/src/client/webcomponents/state/terminals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export function useTerminals(context: DocksContext): Reactive<Map<string, Termin
}
const map: Reactive<Map<string, TerminalState>> = _terminalsMap = reactive(new Map())
async function updateTerminals() {
const terminals = await context.rpc.$call('vite:internal:terminals:list')
const terminals = await context.rpc.call('vite:internal:terminals:list')

for (const terminal of terminals) {
if (map.has(terminal.id)) {
Expand All @@ -34,12 +34,12 @@ export function useTerminals(context: DocksContext): Reactive<Map<string, Termin
// eslint-disable-next-line no-console
console.log('[VITE DEVTOOLS] Terminals Updated', [...map.values()])
}
context.clientRpc.register({
context.rpc.client.register({
name: 'vite:internal:terminals:updated' satisfies keyof DevToolsRpcClientFunctions,
type: 'action',
handler: () => updateTerminals(),
})
context.clientRpc.register({
context.rpc.client.register({
name: 'vite:internal:terminals:stream-chunk' satisfies keyof DevToolsRpcClientFunctions,
type: 'action',
handler: (data: DevToolsTerminalSessionStreamChunkEvent) => {
Expand Down
72 changes: 72 additions & 0 deletions packages/core/src/node/rpc/anonymous/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import * as p from '@clack/prompts'
import { defineRpcFunction } from '@vitejs/devtools-kit'
import c from 'ansis'

export interface DevToolsAuthInput {
authId: string
ua: string
}

export interface DevToolsAuthReturn {
isTrusted: boolean
}

const TEMPORARY_STORAGE = new Map<string, {
authId: string
ua: string
timestamp: number
}>()

export const anonymousAuth = defineRpcFunction({
name: 'vite:anonymous:auth',
type: 'action',
setup: () => {
return {
handler: async (query: DevToolsAuthInput): Promise<DevToolsAuthReturn> => {
if (TEMPORARY_STORAGE.has(query.authId)) {
return {
isTrusted: true,
}
}

const message = [
`A browser is requesting permissions to connect to the Vite DevTools.`,

`User Agent: ${c.yellow(c.bold(query.ua || 'Unknown'))}`,
`Identifier: ${c.green(c.bold(query.authId))}`,
'',
'This will allow the browser to interact with the server, make file changes and run commands.',
c.red(c.bold('You should only trust your local development browsers.')),
]

p.note(
c.reset(message.join('\n')),
c.bold(c.yellow(' Vite DevTools Permission Request ')),
)

const answer = await p.confirm({
message: c.bold(`Do you trust this client (${c.green(c.bold(query.authId))})?`),
initialValue: false,
})

if (answer) {
TEMPORARY_STORAGE.set(query.authId, {
authId: query.authId,
ua: query.ua,
timestamp: Date.now(),
})
p.outro(c.green(c.bold('You have granted permissions to this client.')))

return {
isTrusted: true,
}
}

p.outro(c.red(c.bold('You have denied permissions to this client.')))
return {
isTrusted: false,
}
},
}
},
})
6 changes: 6 additions & 0 deletions packages/core/src/node/rpc/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { DevToolsTerminalSessionStreamChunkEvent, RpcDefinitionsFilter, RpcDefinitionsToFunctions } from '@vitejs/devtools-kit'
import { anonymousAuth } from './anonymous/auth'
import { docksList } from './internal/docks-list'
import { docksOnLaunch } from './internal/docks-on-launch'
import { rpcServerList } from './internal/rpc-server-list'
Expand All @@ -13,6 +14,10 @@ export const builtinPublicRpcDecalrations = [
openInFinder,
] as const

export const builtinAnonymousRpcDecalrations = [
anonymousAuth,
] as const

// @keep-sorted
export const builtinInternalRpcDecalrations = [
docksList,
Expand All @@ -24,6 +29,7 @@ export const builtinInternalRpcDecalrations = [

export const builtinRpcDecalrations = [
...builtinPublicRpcDecalrations,
...builtinAnonymousRpcDecalrations,
...builtinInternalRpcDecalrations,
] as const

Expand Down
26 changes: 24 additions & 2 deletions packages/core/src/node/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ export interface CreateWsServerOptions {
context: DevToolsNodeContext
}

const ANONYMOUS_SCOPE = 'vite:anonymous:'

export async function createWsServer(options: CreateWsServerOptions) {
const rpcHost = options.context.rpc
const port = options.portWebSocket ?? await getPort({ port: 7812, random: true })
Expand All @@ -37,10 +39,30 @@ export async function createWsServer(options: CreateWsServerOptions) {
{
preset,
rpcOptions: {
onError(error, name) {
onFunctionError(error, name) {
console.error(c.red`⬢ RPC error on executing "${c.bold(name)}":`)
console.error(error)
throw error
},
resolver(name, fn) {
if (name.startsWith(ANONYMOUS_SCOPE))
return fn

if (!this.$meta.isTrusted) {
return () => {
throw new Error(`Unauthorized access to method ${JSON.stringify(name)}, please trust this client first`)
}
}
return fn
},
onRequest(req, next, resolve) {
if (req.m.startsWith(ANONYMOUS_SCOPE))
return next()

// Do not boardcast to untrusted clients
if (!this.$meta.isTrusted) {
return resolve(undefined)
}
return next()
},
},
},
Expand Down
2 changes: 2 additions & 0 deletions packages/kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
".": "./dist/index.mjs",
"./client": "./dist/client.mjs",
"./utils/events": "./dist/utils/events.mjs",
"./utils/nanoid": "./dist/utils/nanoid.mjs",
"./package.json": "./package.json"
},
"main": "./dist/index.mjs",
Expand All @@ -44,6 +45,7 @@
"birpc-x": "catalog:deps"
},
"devDependencies": {
"my-ua-parser": "catalog:frontend",
"tsdown": "catalog:build",
"vite": "catalog:build"
}
Expand Down
8 changes: 4 additions & 4 deletions packages/kit/src/client/docks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,6 @@ export interface DocksContext extends DevToolsClientContext {
* The docks entries context
*/
readonly docks: DocksEntriesContext
/**
* The client-side RPC functions to be called from the server
*/
readonly clientRpc: DevToolsClientRpcHost
}

export type DevToolsClientRpcHost = RpcFunctionsCollector<DevToolsRpcClientFunctions, DevToolsClientContext>
Expand Down Expand Up @@ -87,3 +83,7 @@ export interface DockEntryStateEvents {
'dom:panel:mounted': (panel: HTMLDivElement) => void
'dom:iframe:mounted': (iframe: HTMLIFrameElement) => void
}

export interface RpcClientEvents {
'rpc:is-trusted:updated': (isTrusted: boolean) => void
}
Loading
Loading