diff --git a/docs/7.module-migration.md b/docs/7.module-migration.md index 2eda7f127a..4e5b0fb852 100644 --- a/docs/7.module-migration.md +++ b/docs/7.module-migration.md @@ -310,4 +310,4 @@ The built-in VS Code integration is replaced by the Code Server plugin (`devtool ### Peer dependencies -`@nuxt/devtools` requires Vite `^8.1.5` (was `>=6.0`) and `@nuxt/kit` 4 or 5. Nitro v2 (`nitropack`, Nuxt 4) and Nitro v3 (`nitro`, Nuxt 5) are both optional peers; the one your user's Nuxt installs is the one that gets used. `unstorage` is an optional peer for the same reason: the Storage tab uses the copy that Nitro brings. +`@nuxt/devtools` requires Vite `^8.1.5` (was `>=6.0`) and `@nuxt/kit` 4 or 5. Nitro v2 (`nitropack`, Nuxt 4) and Nitro v3 (`nitro`, Nuxt 5) are both optional peers; the one your user's Nuxt installs is the one that gets used. The Storage tab proxies to the running Nitro server's own `useStorage()`, so `@nuxt/devtools` does not depend on `unstorage` at all. diff --git a/packages/devtools-kit/build.config.ts b/packages/devtools-kit/build.config.ts index 429c4f8476..8c540b5209 100644 --- a/packages/devtools-kit/build.config.ts +++ b/packages/devtools-kit/build.config.ts @@ -18,7 +18,6 @@ export default defineBuildConfig({ 'nitro', 'nitro/types', 'unimport', - 'unstorage', 'ofetch', 'vue', 'vue-router', diff --git a/packages/devtools-kit/src/_types/common.ts b/packages/devtools-kit/src/_types/common.ts index ba4f1dce0e..0c8db1942d 100644 --- a/packages/devtools-kit/src/_types/common.ts +++ b/packages/devtools-kit/src/_types/common.ts @@ -1,3 +1,6 @@ +/** Mirrors unstorage's `StorageValue`, declared locally to avoid a dependency on either unstorage major. */ +export type StorageValue = null | string | number | boolean | object + export type TabCategory = | 'pinned' | 'app' diff --git a/packages/devtools-kit/src/_types/rpc.ts b/packages/devtools-kit/src/_types/rpc.ts index 95f97f9bff..281fa7150f 100644 --- a/packages/devtools-kit/src/_types/rpc.ts +++ b/packages/devtools-kit/src/_types/rpc.ts @@ -1,7 +1,7 @@ import type { Component, NuxtApp, NuxtLayout, NuxtOptions, NuxtPage } from 'nuxt/schema' -import type { StorageValue } from 'unstorage' import type { ResolvedConfig } from 'vite' import type { AnalyzeBuildsInfo } from './analyze-build' +import type { StorageValue } from './common' import type { ModuleCustomTab } from './custom-tabs' import type { AutoImportsWithMetadata, ComponentRelationship, HookInfo, NpmCommandOptions, NpmCommandType, PackageUpdateInfo, ScannedNitroTasks, ServerRouteInfo, VfsData, VfsFile } from './integrations' import type { AnyNitro, AnyStorageMounts } from './nitro-compat' diff --git a/packages/devtools/build.config.ts b/packages/devtools/build.config.ts index 3d5cfe654a..228cf72a4a 100644 --- a/packages/devtools/build.config.ts +++ b/packages/devtools/build.config.ts @@ -24,7 +24,6 @@ export default defineBuildConfig({ // Type only 'vue', 'vue-router', - 'unstorage', 'nitropack', 'vite-plugin-vue-tracer', ], diff --git a/packages/devtools/package.json b/packages/devtools/package.json index c28fd5366b..b5eea93f04 100644 --- a/packages/devtools/package.json +++ b/packages/devtools/package.json @@ -35,7 +35,6 @@ "@nuxt/kit": "^4.0.0-0 || ^5.0.0-0", "nitro": "*", "nitropack": "^2.0.0", - "unstorage": "^1.0.0 || ^2.0.0-0", "vite": "^8.1.5", "vite-plugin-inspect": "catalog:prod" }, @@ -46,9 +45,6 @@ "nitropack": { "optional": true }, - "unstorage": { - "optional": true - }, "vite-plugin-inspect": { "optional": true } @@ -128,7 +124,6 @@ "unocss": "catalog:buildtools", "unplugin-vue": "catalog:buildtools", "unplugin-vue-markdown": "catalog:buildtools", - "unstorage": "catalog:types", "vanilla-jsoneditor": "catalog:frontend", "vis-data": "catalog:frontend", "vis-network": "catalog:frontend", diff --git a/packages/devtools/src/runtime/nitro/storage-bridge.ts b/packages/devtools/src/runtime/nitro/storage-bridge.ts new file mode 100644 index 0000000000..d036ac7599 --- /dev/null +++ b/packages/devtools/src/runtime/nitro/storage-bridge.ts @@ -0,0 +1,167 @@ +export const DEVTOOLS_STORAGE_ROUTE = '/__nuxt_devtools__/storage' + +/** + * Env var carrying the per-process secret shared between the DevTools server + * and the bridge handler inside the Nitro dev worker. + */ +export const DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV = '__NUXT_DEVTOOLS_STORAGE_BRIDGE_TOKEN__' + +/** + * Mounts Nitro adds for its own bookkeeping. + */ +export const IGNORE_STORAGE_MOUNTS = [ + 'root', + 'build', + 'src', + 'cache', + 'assets', +] + +/** + * Same normalisation unstorage applies before routing a key to a mount, so + * `/root:x`, `:root:x`, `root/x` and `\\root\\x` all resolve to `root`. + * Inlined to avoid importing either unstorage major. + */ +export function normalizeStorageKey(key: string) { + return key.split('?')[0]?.replace(/[/\\]/g, ':').replace(/:+/g, ':').replace(/^:|:$/g, '') || '' +} + +// Mounts backed by the project itself (`root`/`src` are the filesystem) stay +// off limits for listing and for every item operation alike. +export function shouldIgnoreStorageKey(key: string) { + return IGNORE_STORAGE_MOUNTS.includes(normalizeStorageKey(key).split(':')[0]!) +} + +function assertAllowedKey(key: unknown): string { + if (typeof key !== 'string' || shouldIgnoreStorageKey(key)) + throw new Error('[nuxt-devtools] Storage key is not allowed') + return key +} + +export type StorageBridgeMethod = 'getKeys' | 'getItem' | 'setItem' | 'removeItem' | 'pullWatchEvents' + +export interface StorageBridgeRequest { + token: string + method: StorageBridgeMethod + args?: unknown[] +} + +export interface StorageBridgeWatchEvent { + event: 'update' | 'remove' + key: string +} + +export interface StorageBridgeWatchBatch { + instance: string + cursor: number + events: StorageBridgeWatchEvent[] +} + +/** + * Structural subset of unstorage's `Storage` shared by the v1 instance Nitro v2 + * bundles and the v2 instance Nitro v3 bundles, so the bridge works against + * whichever `useStorage()` returns without importing either version. + */ +export interface StorageBridgeStorage { + getKeys: (base?: string) => Promise + getItem: (key: string) => Promise + setItem: (key: string, value: any) => Promise + removeItem: (key: string) => Promise + getMounts?: () => Array<{ + base: string + driver: { + watch?: (callback: (event: 'update' | 'remove', key: string) => void) => Promise | unknown + } + }> +} + +const MAX_BUFFERED_EVENTS = 500 + +interface WatchState { + instance: string + events: Array + nextId: number +} + +let watchState: WatchState | undefined + +async function ensureWatcher(storage: StorageBridgeStorage): Promise { + if (watchState) + return watchState + const state: WatchState = { + instance: Math.random().toString(36).slice(2), + events: [], + nextId: 1, + } + watchState = state + + const mounts = storage.getMounts?.() ?? [] + await Promise.all(mounts.map(async ({ base, driver }) => { + if (!driver?.watch || shouldIgnoreStorageKey(base)) + return + try { + await driver.watch((event, key) => { + state.events.push({ id: state.nextId++, event, key: base + key }) + if (state.events.length > MAX_BUFFERED_EVENTS) + state.events.splice(0, state.events.length - MAX_BUFFERED_EVENTS) + }) + } + catch { + // Some drivers don't support watching; polling clients see no events for them. + } + })) + + return state +} + +function isValidToken(expected: string | undefined, actual: unknown): boolean { + if (!expected || typeof actual !== 'string' || actual.length !== expected.length) + return false + let diff = 0 + for (let i = 0; i < expected.length; i++) + diff |= expected.charCodeAt(i) ^ actual.charCodeAt(i) + return diff === 0 +} + +export async function handleStorageBridgeRequest( + storage: StorageBridgeStorage, + body: StorageBridgeRequest | undefined, + token = process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV], +) { + if (!body || !isValidToken(token, body.token)) + throw new Error('[nuxt-devtools] Invalid storage bridge token') + + const args = body.args ?? [] + switch (body.method) { + case 'getKeys': { + const base = args[0] + if (base != null && typeof base !== 'string') + throw new Error('[nuxt-devtools] Storage base must be a string') + const keys = await storage.getKeys(base ?? undefined) + return { + result: keys.filter(key => !shouldIgnoreStorageKey(key)), + } + } + case 'getItem': + return { result: await storage.getItem(assertAllowedKey(args[0])) } + case 'setItem': + return { result: await storage.setItem(assertAllowedKey(args[0]), args[1]) } + case 'removeItem': + return { result: await storage.removeItem(assertAllowedKey(args[0])) } + case 'pullWatchEvents': { + const state = await ensureWatcher(storage) + const [instance, cursor] = args as [string | undefined, number | undefined] + const events = instance === state.instance + ? state.events.filter(e => e.id > (cursor ?? 0)) + : [] + const batch: StorageBridgeWatchBatch = { + instance: state.instance, + cursor: state.events.at(-1)?.id ?? 0, + events: events.map(({ event, key }) => ({ event, key })), + } + return { result: batch } + } + default: + throw new Error(`[nuxt-devtools] Unknown storage bridge method "${(body as StorageBridgeRequest).method}"`) + } +} diff --git a/packages/devtools/src/runtime/nitro/storage-handler-v2.ts b/packages/devtools/src/runtime/nitro/storage-handler-v2.ts new file mode 100644 index 0000000000..db37921af0 --- /dev/null +++ b/packages/devtools/src/runtime/nitro/storage-handler-v2.ts @@ -0,0 +1,7 @@ +import { defineEventHandler, readBody } from 'h3' +import { useStorage } from 'nitropack/runtime' +import { handleStorageBridgeRequest } from './storage-bridge' + +export default defineEventHandler(async (event) => { + return handleStorageBridgeRequest(useStorage(), await readBody(event)) +}) diff --git a/packages/devtools/src/runtime/nitro/storage-handler-v3.ts b/packages/devtools/src/runtime/nitro/storage-handler-v3.ts new file mode 100644 index 0000000000..3755e919a5 --- /dev/null +++ b/packages/devtools/src/runtime/nitro/storage-handler-v3.ts @@ -0,0 +1,7 @@ +import { defineEventHandler, readBody } from 'nitro/h3' +import { useStorage } from 'nitro/storage' +import { handleStorageBridgeRequest } from './storage-bridge' + +export default defineEventHandler(async (event) => { + return handleStorageBridgeRequest(useStorage(), await readBody(event)) +}) diff --git a/packages/devtools/src/server-rpc/storage-watch.ts b/packages/devtools/src/server-rpc/storage-watch.ts deleted file mode 100644 index 1792819a65..0000000000 --- a/packages/devtools/src/server-rpc/storage-watch.ts +++ /dev/null @@ -1,21 +0,0 @@ -import type { Storage } from 'unstorage' - -export type UnwatchStorageMount = () => Promise | void -type WatchEvent = 'update' | 'remove' -type WatchCallback = (event: WatchEvent, key: string) => void - -export async function watchStorageMount(storage: Storage, mountName: string, onChange: WatchCallback): Promise { - const { normalizeBaseKey, normalizeKey } = await import('unstorage') - const mountKey = normalizeBaseKey(mountName) - const mount = storage.getMount(mountKey) - if (!mount || normalizeBaseKey(mount.base) !== mountKey || !mount.driver?.watch) - return () => {} - - const unwatch = await mount.driver.watch((event: WatchEvent, key: string) => { - const fullKey = key.startsWith(mountKey) - ? key - : `${mountKey}${key}` - onChange(event, normalizeKey(fullKey)) - }) - return unwatch ?? (() => {}) -} diff --git a/packages/devtools/src/server-rpc/storage.ts b/packages/devtools/src/server-rpc/storage.ts index e2c3b5d755..4b938a7dc4 100644 --- a/packages/devtools/src/server-rpc/storage.ts +++ b/packages/devtools/src/server-rpc/storage.ts @@ -1,35 +1,29 @@ -import type { Storage, StorageValue } from 'unstorage' -import type { NuxtDevtoolsServerContext, ServerFunctions } from '../types' +import type { StorageBridgeWatchBatch } from '../runtime/nitro/storage-bridge' +import type { NuxtDevtoolsServerContext, ServerFunctions, StorageValue } from '../types' import type { AnyNitro, AnyStorageMounts } from '../utils/nitro-compat' -import { watchStorageMount } from './storage-watch' +import { Buffer } from 'node:buffer' +import { randomBytes } from 'node:crypto' +import { request as httpsRequest } from 'node:https' +import { join } from 'pathe' +import { runtimeDir } from '../dirs' +import { DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV, DEVTOOLS_STORAGE_ROUTE, shouldIgnoreStorageKey } from '../runtime/nitro/storage-bridge' -// Mounts backed by the project itself (`root`/`src` are the filesystem) stay -// off limits for listing and for every item operation alike. Normalise first: -// unstorage routes `/root:x`, `:root:x` and `root/x` to the `root` mount too. -const IGNORE_STORAGE_MOUNTS = ['root', 'build', 'src', 'cache'] +const WATCH_POLL_INTERVAL = 1000 export function setupStorageRPC(ctx: NuxtDevtoolsServerContext) { const { nuxt } = ctx const storageMounts: AnyStorageMounts = {} - let unstorage: typeof import('unstorage') | undefined - let storage: Storage | undefined - let unwatchStorageMounts: Array<() => Promise | void> = [] + let bridgeAvailable = false - function shouldIgnoreStorageKey(key: string) { - return !unstorage || IGNORE_STORAGE_MOUNTS.includes(unstorage.normalizeKey(key).split(':')[0]!) - } - - nuxt.hook('nitro:init', async (nitro: AnyNitro) => { - // `unstorage` is a relaxed optional peer: use the copy the project's Nitro - // brings (v1 with `nitropack`, v2 with `nitro`) instead of shipping our own. - const loaded = await import('unstorage').catch((err) => { - nitro.logger.warn('Failed to load `unstorage`, the DevTools storage browser is disabled:', err) - }) - if (!loaded) - return - unstorage = loaded + // The bridge token travels to the dev server through the environment, which + // both Nitro v2 and v3 copy into their dev workers when spawning them. It + // must never be embedded in generated source: Vite can serve files like + // `.nuxt/dev/index.mjs` to any client that reaches the dev server. + if (nuxt.options.dev) + process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] ||= randomBytes(32).toString('hex') + nuxt.hook('nitro:init', (nitro: AnyNitro) => { // Taken from https://github.com/unjs/nitro/blob/d83f2b65165d7ba996e7ef129ea99ff5b551dccc/src/storage.ts#L7-L10 // Waiting for https://github.com/unjs/unstorage/issues/53 const mounts: AnyStorageMounts = { @@ -37,33 +31,6 @@ export function setupStorageRPC(ctx: NuxtDevtoolsServerContext) { ...nitro.options.devStorage, } - // Nitro v3 dropped the `nitro.storage` runtime instance that Nitro v2 - // (`nitropack`) exposed directly on the Nitro object — storage is now a - // build-time virtual module consumed via `useStorage()` from *inside* the - // built server, not reachable from this orchestrating process. Build our - // own `unstorage` instance from the same mount config instead, mirroring - // what nitropack's own `createStorage()` helper does. This works - // identically on Nitro v2 and v3, though it is a distinct instance from - // whichever one the running server uses — in-memory-driver mounts (e.g. - // the default cache) won't reflect the live server's in-process state, - // only mounts backed by external state (filesystem, redis, ...) will. - const nextStorage = unstorage.createStorage() - for (const [path, opts] of Object.entries(mounts)) { - if (!opts?.driver) { - nitro.logger.warn(`No \`driver\` set for storage mount point "${path}".`) - continue - } - try { - const driverImport = unstorage.builtinDrivers[opts.driver as keyof typeof unstorage.builtinDrivers] || opts.driver - const driverFactory = await import(driverImport).then(r => r.default || r) - nextStorage.mount(path, driverFactory(opts)) - } - catch (err) { - nitro.logger.warn(`Failed to mount storage driver "${opts.driver}" for the DevTools storage browser:`, err) - } - } - storage = nextStorage - for (const key of Object.keys(storageMounts)) delete storageMounts[key] @@ -72,26 +39,92 @@ export function setupStorageRPC(ctx: NuxtDevtoolsServerContext) { continue storageMounts[name] = mounts[name]! } + + if (!nuxt.options.dev) + return + + // Neither engine hands the orchestrating process the storage instance the + // server actually uses: Nitro v3 dropped the `nitro.storage` runtime + // property entirely, and even on Nitro v2 it is a separate build-process + // instance, not the one `useStorage()` returns inside the server. Instead + // of duplicating mounts (and their fs watchers) in this process, register + // a dev-only handler inside the running server that proxies storage + // operations to the real runtime instance — this also makes in-memory + // mounts reflect the live server state. `nitro.meta.majorVersion` tells us + // which engine (and therefore which runtime import) the handler needs; + // older nitropack v2 releases predate `meta`, hence the fallback. + const engine = ((nitro as { meta?: { majorVersion?: number } }).meta?.majorVersion ?? 2) >= 3 + ? 'v3' + : 'v2' + ;(nitro.options.handlers as Array<{ route: string, method?: string, handler: string }>).push({ + route: DEVTOOLS_STORAGE_ROUTE, + method: 'post', + handler: join(runtimeDir, `nitro/storage-handler-${engine}`), + }) + bridgeAvailable = true }) - nuxt.hook('ready', async () => { - const activeStorage = storage - if (!activeStorage) + async function callBridge(method: string, args: unknown[]): Promise { + const url = new URL(DEVTOOLS_STORAGE_ROUTE, nuxt.options.devServer.url) + const body = JSON.stringify({ token: process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV], method, args }) + const { status, text } = url.protocol === 'https:' && isLoopbackHost(url.hostname) + ? await postToLocalHttps(url, body) + : await postWithFetch(url, body, method) + if (status < 200 || status >= 300) + throw new Error(`Storage bridge request "${method}" failed with status ${status}`) + return (JSON.parse(text) as { result: T }).result + } + + let watchInstance: string | undefined + let watchCursor = 0 + let pollTimer: NodeJS.Timeout | undefined + let polling = false + let closed = false + + async function pollWatchEvents() { + if (polling) return - await Promise.all(unwatchStorageMounts.map(unwatch => unwatch())) - unwatchStorageMounts = await Promise.all(Object.keys(storageMounts).map(mountName => - watchStorageMount(activeStorage, mountName, (event, key) => { + polling = true + try { + const batch = await callBridge('pullWatchEvents', [watchInstance, watchCursor]) + const isSameInstance = watchInstance === batch.instance + watchInstance = batch.instance + watchCursor = batch.cursor + if (!isSameInstance) + return + for (const { event, key } of batch.events) { + if (shouldIgnoreStorageKey(key)) + continue ctx.devtoolsKit?.rpc.broadcast({ method: 'callHook', args: ['storage:key:update', key, event], event: true, } as any) - }))) - }) + } + } + catch { + // Dev server not listening yet, or restarting — retry on the next tick. + } + finally { + polling = false + } + } - nuxt.hook('close', async () => { - await Promise.all(unwatchStorageMounts.map(unwatch => unwatch())) - unwatchStorageMounts = [] + // Only poll once the Storage tab has asked for something, so sessions that + // never open it don't hit the dev server every second. + function ensureWatchPolling() { + if (!bridgeAvailable || pollTimer || closed) + return + pollTimer = setInterval(pollWatchEvents, WATCH_POLL_INTERVAL) + pollTimer.unref?.() + } + + nuxt.hook('close', () => { + closed = true + if (pollTimer) { + clearInterval(pollTimer) + pollTimer = undefined + } }) return { @@ -99,32 +132,87 @@ export function setupStorageRPC(ctx: NuxtDevtoolsServerContext) { return storageMounts }, async getStorageKeys(base?: string) { - if (!storage) + if (!bridgeAvailable) return [] + ensureWatchPolling() try { - const keys = await storage.getKeys(base) - + const keys = await callBridge('getKeys', [base]) return keys.filter(key => !shouldIgnoreStorageKey(key)) } catch (err) { - console.error(`Cloud not fetch storage keys for ${base}:`, err) + console.error(`Could not fetch storage keys for ${base}:`, err) return [] } }, async getStorageItem(key: string) { - if (!storage || shouldIgnoreStorageKey(key)) + if (!bridgeAvailable || shouldIgnoreStorageKey(key)) return null - return await storage.getItem(key) + return await callBridge('getItem', [key]) }, async setStorageItem(key: string, value: StorageValue) { - if (!storage || shouldIgnoreStorageKey(key)) + if (!bridgeAvailable || shouldIgnoreStorageKey(key)) return - return await storage.setItem(key, value) + return await callBridge('setItem', [key, value]) }, async removeStorageItem(key: string) { - if (!storage || shouldIgnoreStorageKey(key)) + if (!bridgeAvailable || shouldIgnoreStorageKey(key)) return - return await storage.removeItem(key) + return await callBridge('removeItem', [key]) }, } satisfies Partial } + +const LOOPBACK_HOSTS = new Set([ + 'localhost', + '127.0.0.1', + '::1', + '[::1]', +]) + +function isLoopbackHost(hostname: string) { + return LOOPBACK_HOSTS.has(hostname) || hostname.endsWith('.localhost') || hostname.startsWith('127.') +} + +async function postWithFetch(url: URL, body: string, method: string) { + try { + const res = await fetch(url, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body, + }) + return { status: res.status, text: await res.text() } + } + catch (error) { + const hint = url.protocol === 'https:' + ? ' If the dev server uses a self-signed certificate, make sure Node trusts it (for example with NODE_EXTRA_CA_CERTS).' + : '' + throw new Error(`Storage bridge request "${method}" to ${url.origin} failed.${hint}`, { cause: error }) + } +} + +/** + * The dev server's own HTTPS certificate is often self-signed, which `fetch` + * rejects. The request never leaves this machine, so skip verification here. + */ +function postToLocalHttps(url: URL, body: string) { + return new Promise<{ status: number, text: string }>((resolve, reject) => { + const req = httpsRequest(url, { + method: 'POST', + headers: { + 'content-type': 'application/json', + 'content-length': Buffer.byteLength(body), + }, + rejectUnauthorized: false, + }, (res) => { + const chunks: Buffer[] = [] + res.on('data', chunk => chunks.push(chunk)) + res.on('end', () => resolve({ + status: res.statusCode ?? 0, + text: Buffer.concat(chunks).toString('utf8'), + })) + res.on('error', reject) + }) + req.on('error', reject) + req.end(body) + }) +} diff --git a/packages/devtools/test/storage-denylist.test.ts b/packages/devtools/test/storage-denylist.test.ts index c72440e18e..0c4857213c 100644 --- a/packages/devtools/test/storage-denylist.test.ts +++ b/packages/devtools/test/storage-denylist.test.ts @@ -1,77 +1,225 @@ +import type { StorageBridgeStorage } from '../src/runtime/nitro/storage-bridge' import type { NuxtDevtoolsServerContext } from '../src/types' -import fsp from 'node:fs/promises' -import { tmpdir } from 'node:os' -import { join } from 'node:path' import { createHooks } from 'hookable' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV, handleStorageBridgeRequest } from '../src/runtime/nitro/storage-bridge' import { setupStorageRPC } from '../src/server-rpc/storage' -let root: string -let projectDir: string -let rpc: ReturnType - -// `root` is an fs mount over a stand-in project dir, like Nitro's dev `root` -// mount; `db` is an ordinary user mount. -beforeEach(async () => { - root = await fsp.mkdtemp(join(tmpdir(), 'nuxt-devtools-storage-')) - projectDir = join(root, 'project') - await fsp.mkdir(projectDir) - await fsp.writeFile(join(projectDir, 'nuxt.config.ts'), 'original') - - const hooks = createHooks() - rpc = setupStorageRPC({ - nuxt: { - hook: hooks.hook.bind(hooks), - }, - } as unknown as NuxtDevtoolsServerContext) - await hooks.callHook('nitro:init', { - options: { - storage: { - root: { driver: 'fs', base: projectDir }, - db: { - driver: 'fs', - base: join(root, 'db'), - }, - }, - }, - logger: { - warn: () => {}, - }, +const TOKEN = 'test-token' + +// Every spelling unstorage routes to the `root` mount. +const deniedKeys = [ + 'root:nuxt.config.ts', + '/root:nuxt.config.ts', + ':root:nuxt.config.ts', + 'root/nuxt.config.ts', + '\\root\\nuxt.config.ts', +] + +function createFakeStorage() { + const data = new Map([ + ['root:nuxt.config.ts', 'original'], + ['db:users', 'alice'], + ]) + return { + data, + getKeys: vi.fn(async () => [ + ...data.keys(), + ]), + getItem: vi.fn(async (key: string) => data.get(key) ?? null), + setItem: vi.fn(async (key: string, value: unknown) => { + data.set(key, value) + }), + removeItem: vi.fn(async (key: string) => { + data.delete(key) + }), + } satisfies StorageBridgeStorage & { data: Map } +} + +describe('storage bridge denylist', () => { + let storage: ReturnType + beforeEach(() => { + storage = createFakeStorage() }) -}) -afterEach(() => fsp.rm(root, { recursive: true, force: true })) + const call = (method: any, args: unknown[], token = TOKEN) => + handleStorageBridgeRequest(storage, { token, method, args }, TOKEN) -const readProjectConfig = () => fsp.readFile(join(projectDir, 'nuxt.config.ts'), 'utf-8') + it('rejects requests without the dev auth token', async () => { + await expect(call('getItem', ['db:users'], 'wrong')).rejects.toThrow(/token/) + await expect(handleStorageBridgeRequest(storage, undefined, TOKEN)).rejects.toThrow(/token/) + expect(storage.getItem).not.toHaveBeenCalled() + }) -describe('storage mount denylist', () => { - // Every spelling unstorage routes to the `root` mount. - const deniedKeys = [ - 'root:nuxt.config.ts', - '/root:nuxt.config.ts', - ':root:nuxt.config.ts', - 'root/nuxt.config.ts', - '\\root\\nuxt.config.ts', - ] + it('reads the expected token from the environment by default', async () => { + const previous = process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + try { + delete process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + await expect(handleStorageBridgeRequest(storage, { + token: '', + method: 'getItem', + args: ['db:users'], + })).rejects.toThrow(/token/) + process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] = TOKEN + expect(await handleStorageBridgeRequest(storage, { + token: TOKEN, + method: 'getItem', + args: ['db:users'], + })).toEqual({ result: 'alice' }) + } + finally { + if (previous === undefined) + delete process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + else + process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] = previous + } + }) it.each(deniedKeys)('refuses to read, write or remove %s', async (key) => { - expect(await rpc.getStorageItem(key)).toBeNull() + await expect(call('getItem', [key])).rejects.toThrow(/not allowed/) + await expect(call('setItem', [key, 'overwritten'])).rejects.toThrow(/not allowed/) + await expect(call('removeItem', [key])).rejects.toThrow(/not allowed/) + expect(storage.getItem).not.toHaveBeenCalled() + expect(storage.setItem).not.toHaveBeenCalled() + expect(storage.removeItem).not.toHaveBeenCalled() + expect(storage.data.get('root:nuxt.config.ts')).toBe('original') + }) + + it('lists and serves user mounts only', async () => { + expect(await call('getKeys', [])).toEqual({ + result: ['db:users'], + }) + expect(await call('getItem', ['db:users'])).toEqual({ result: 'alice' }) + }) +}) + +describe('storage bridge token', () => { + it('passes the token through the environment, not generated source', async () => { + const previous = process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + delete process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(Response.json({ result: [] })) + try { + const hooks = createHooks() + const rpc = setupStorageRPC({ + nuxt: { + hook: hooks.hook.bind(hooks), + options: { + dev: true, + devServer: { url: 'http://localhost:3000/' }, + }, + }, + } as unknown as NuxtDevtoolsServerContext) + const config: { virtual?: Record } = {} + await hooks.callHook('nitro:config', config) + await hooks.callHook('nitro:init', { + options: { storage: {}, handlers: [] }, + }) + + expect(config.virtual).toBeUndefined() + const token = process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + expect(token).toMatch(/^[0-9a-f]{64}$/) - await rpc.setStorageItem(key, 'overwritten') - expect(await readProjectConfig()).toBe('original') + await rpc.getStorageKeys() + const body = JSON.parse(fetchSpy.mock.calls[0]![1]!.body as string) + expect(body.token).toBe(token) + } + finally { + fetchSpy.mockRestore() + if (previous === undefined) + delete process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] + else + process.env[DEVTOOLS_STORAGE_BRIDGE_TOKEN_ENV] = previous + } + }) +}) + +describe('storage bridge wiring', () => { + function setup() { + const hooks = createHooks() + const rpc = setupStorageRPC({ + nuxt: { + hook: hooks.hook.bind(hooks), + options: { + dev: true, + devServer: { url: 'http://localhost:3000/' }, + }, + }, + } as unknown as NuxtDevtoolsServerContext) + const nitro = { + options: { storage: {}, handlers: [] as Array> }, + } + return { hooks, rpc, nitro } + } - await rpc.removeStorageItem(key) - expect(await readProjectConfig()).toBe('original') + it('registers the bridge handler for POST only', async () => { + const { hooks, nitro } = setup() + await hooks.callHook('nitro:init', nitro) + expect(nitro.options.handlers).toEqual([ + expect.objectContaining({ route: '/__nuxt_devtools__/storage', method: 'post' }), + ]) }) - it('lists and serves user mounts only', async () => { - await rpc.setStorageItem('db:users', 'alice') + it('starts polling for watch events only after the storage tab is used', async () => { + vi.useFakeTimers() + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => Response.json({ result: [] })) + try { + const { hooks, rpc, nitro } = setup() + await hooks.callHook('nitro:init', nitro) + await hooks.callHook('ready') + await vi.advanceTimersByTimeAsync(5000) + expect(fetchSpy).not.toHaveBeenCalled() + + await rpc.getStorageKeys() + fetchSpy.mockClear() + await vi.advanceTimersByTimeAsync(1000) + expect(JSON.parse(fetchSpy.mock.calls[0]![1]!.body as string).method).toBe('pullWatchEvents') + + await hooks.callHook('close') + fetchSpy.mockClear() + await vi.advanceTimersByTimeAsync(5000) + expect(fetchSpy).not.toHaveBeenCalled() + } + finally { + fetchSpy.mockRestore() + vi.useRealTimers() + } + }) +}) + +describe('storage rpc denylist', () => { + it('never forwards denied keys and hides denied mounts', async () => { + const fetchSpy = vi.spyOn(globalThis, 'fetch') + const hooks = createHooks() + const rpc = setupStorageRPC({ + nuxt: { + hook: hooks.hook.bind(hooks), + options: { + dev: true, + devServer: { url: 'http://localhost:3000/' }, + }, + }, + } as unknown as NuxtDevtoolsServerContext) + await hooks.callHook('nitro:init', { + options: { + storage: { + root: { driver: 'fs', base: '/project' }, + db: { driver: 'fs', base: '/db' }, + }, + handlers: [], + }, + logger: { + warn: () => {}, + }, + }) - expect(await rpc.getStorageItem('db:users')).toBe('alice') - expect(await rpc.getStorageKeys()).toEqual(['db:users']) expect(Object.keys(await rpc.getStorageMounts())).toEqual(['db']) - await rpc.removeStorageItem('db:users') - expect(await rpc.getStorageKeys()).toEqual([]) + for (const key of deniedKeys) { + expect(await rpc.getStorageItem(key)).toBeNull() + await rpc.setStorageItem(key, 'overwritten') + await rpc.removeStorageItem(key) + } + expect(fetchSpy).not.toHaveBeenCalled() + fetchSpy.mockRestore() }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9095a3d467..a74fbf256e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -492,9 +492,6 @@ catalogs: '@types/node': specifier: ^26.6.11 version: 26.6.11 - unstorage: - specifier: ^1.17.6 - version: 1.17.6 overrides: '@devframes/agentic': ^1.4.0 @@ -877,9 +874,6 @@ importers: unplugin-vue-markdown: specifier: catalog:buildtools version: 32.1.1(esbuild@0.28.2)(rolldown@1.2.19)(rollup@4.69.1)(vite@8.3.8)(webpack@5.113.0(cssnano@7.1.9(postcss@8.5.34))(csso@5.0.5)(esbuild@0.28.2)(lightningcss@1.33.0)(postcss@8.5.34)(svgo@4.1.0)) - unstorage: - specifier: catalog:types - version: 1.17.6(db0@0.3.4) vanilla-jsoneditor: specifier: catalog:frontend version: 3.13.1(@typescript-eslint/types@8.74.0) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 5606930d77..1931dc029c 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -251,4 +251,3 @@ catalogs: '@types/node': ^26.6.11 '@vitejs/devtools-kit': *vite-devtools unimport: ^7.0.3 - unstorage: ^1.17.6