A full-featured download manager.
fix: enforce plugin host permissions, per-line task creation, safe remove default (#1888)
Dr_rOota8ed7c3ae7f8
diff --git a/scripts/server-package-utils.mjs b/scripts/server-package-utils.mjsindex 4a21734f..9d1b6254 100644--- a/scripts/server-package-utils.mjs+++ b/scripts/server-package-utils.mjs@@ -307,6 +307,65 @@ function readStringToken(source, start) {return undefined}+// Keywords after which a `/` starts a regex literal rather than division.+const REGEX_PRECEDING_KEYWORDS = new Set([+ 'return',+ 'typeof',+ 'instanceof',+ 'in',+ 'of',+ 'new',+ 'delete',+ 'void',+ 'throw',+ 'case',+ 'do',+ 'else',+ 'yield',+ 'await',+])++// Standard lexer heuristic: a `/` is division only when the previous token+// can terminate an operand (identifier, string, `)`, `]`, or a digit —+// numbers tokenize as digit punctuation here). Everything else, including+// the start of input, puts the slash in expression position where it must+// begin a regex literal.+function regexLiteralAllowed(previous) {+ if (!previous) return true+ if (previous.type === 'string') return false+ if (previous.type === 'identifier') {+ return REGEX_PRECEDING_KEYWORDS.has(previous.value)+ }+ return !/[)\]\w.]/.test(previous.value)+}++// Returns the index just past the regex literal (including flags), or -1+// when no well-formed regex starts at `start` (an unescaped newline or EOF+// before the closing slash).+function readRegexEnd(source, start) {+ let index = start + 1+ let inClass = false+ while (index < source.length) {+ const character = source[index]+ if (character === '\\') {+ index += 2+ continue+ }+ if (character === '\n' || character === '\r') return -1+ if (inClass) {+ if (character === ']') inClass = false+ } else if (character === '[') {+ inClass = true+ } else if (character === '/') {+ index += 1+ while (/[a-z]/i.test(source[index] ?? '')) index += 1+ return index+ }+ index += 1+ }+ return -1+}+function tokenizeJavaScript(source) {const tokens = []let index = 0@@ -327,6 +386,13 @@ function tokenizeJavaScript(source) {index = end === -1 ? source.length : end + 2continue}+ if (character === '/' && regexLiteralAllowed(tokens[tokens.length - 1])) {+ const end = readRegexEnd(source, index)+ if (end !== -1) {+ index = end+ continue+ }+ }if (character === '"' || character === "'" || character === '`') {const token = readStringToken(source, index)if (!token) breakdiff --git a/src/core/plugin/capabilities/http.test.ts b/src/core/plugin/capabilities/http.test.tsindex 240c962c..a00fe00c 100644--- a/src/core/plugin/capabilities/http.test.ts+++ b/src/core/plugin/capabilities/http.test.ts@@ -60,6 +60,12 @@ function createTestServer(): Promise<{return}+ if (url === '/redirect-external') {+ res.writeHead(302, { Location: 'https://elsewhere.example/file' })+ res.end()+ return+ }+if (url === '/large') {res.writeHead(200, { 'Content-Type': 'text/plain' })// Stream in chunks to simulate streaming response.@@ -301,3 +307,64 @@ describe('HttpCapabilityHost', () => {}})})++// ---------------------------------------------------------------------------+// Host permissions enforcement+// ---------------------------------------------------------------------------++describe('HttpCapabilityHost host permissions', () => {+ let server: http.Server+ let baseUrl: string++ beforeEach(async () => {+ const created = await createTestServer()+ server = created.server+ baseUrl = created.baseUrl+ })++ afterEach(+ () =>+ new Promise<void>((resolve) => {+ server.close(() => resolve())+ })+ )++ it('rejects a URL outside the declared hostPermissions without a request', async () => {+ const host = new HttpCapabilityHost({+ hostPermissions: ['https://allowed.example/*'],+ })+ await expect(host.get(`${baseUrl}/text`)).rejects.toMatchObject({+ code: 'plugin.http.host_not_permitted',+ })+ })++ it('allows a URL matching the declared hostPermissions', async () => {+ const host = new HttpCapabilityHost({+ hostPermissions: ['http://127.0.0.1:*/*'],+ })+ const resp = await host.get(`${baseUrl}/text`)+ expect(resp.body).toBe('hello')+ })++ it('denies every URL when hostPermissions is empty', async () => {+ const host = new HttpCapabilityHost({ hostPermissions: [] })+ await expect(host.get(`${baseUrl}/text`)).rejects.toMatchObject({+ code: 'plugin.http.host_not_permitted',+ })+ })++ it('re-checks hostPermissions on every redirect hop', async () => {+ const host = new HttpCapabilityHost({+ hostPermissions: ['http://127.0.0.1:*/*'],+ })+ await expect(+ host.get(`${baseUrl}/redirect-external`)+ ).rejects.toMatchObject({ code: 'plugin.http.host_not_permitted' })+ })++ it('leaves hosts unrestricted when hostPermissions is not provided', async () => {+ const host = new HttpCapabilityHost()+ const resp = await host.get(`${baseUrl}/text`)+ expect(resp.body).toBe('hello')+ })+})diff --git a/src/core/plugin/capabilities/http.ts b/src/core/plugin/capabilities/http.tsindex 5637f68d..70510594 100644--- a/src/core/plugin/capabilities/http.ts+++ b/src/core/plugin/capabilities/http.ts@@ -20,6 +20,7 @@import type { Dispatcher } from 'undici'import { Agent, ProxyAgent, request as undiciRequest } from 'undici'+import { urlMatchesHostPermissions } from '../hooks/eligibility'import type { CookieJar } from './http-cookies'// ---------------------------------------------------------------------------@@ -104,6 +105,14 @@ export interface HttpCapabilityHostOptions {cookieJar?: CookieJardefaultTimeoutMs?: numberdefaultMaxBodyBytes?: number+ /**+ * Manifest hostPermissions patterns this instance is confined to. When+ * present, the initial URL and every redirect hop must match one pattern+ * (empty array denies everything, mirroring eligibility rule I29).+ * Undefined skips host confinement — only for host-agnostic instances in+ * tests; the capability bridge always passes the manifest's list.+ */+ hostPermissions?: ReadonlyArray<string>}// ---------------------------------------------------------------------------@@ -223,12 +232,23 @@ export class HttpCapabilityHost {private readonly cookieJar: CookieJar | undefinedprivate readonly defaultTimeoutMs: numberprivate readonly defaultMaxBodyBytes: number+ private readonly hostPermissions: ReadonlyArray<string> | undefinedconstructor(opts?: HttpCapabilityHostOptions) {this.cookieJar = opts?.cookieJarthis.defaultTimeoutMs = opts?.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MSthis.defaultMaxBodyBytes =opts?.defaultMaxBodyBytes ?? DEFAULT_MAX_BODY_BYTES+ this.hostPermissions = opts?.hostPermissions+ }++ private checkHostPermitted(url: string): void {+ if (this.hostPermissions === undefined) return+ if (urlMatchesHostPermissions(this.hostPermissions, url)) return+ throw new HttpError(+ 'plugin.http.host_not_permitted',+ `URL is outside the plugin's hostPermissions: ${url}`+ )}// -------------------------------------------------------------------------@@ -247,6 +267,7 @@ export class HttpCapabilityHost {const parsed = parseUrl(opts.url)checkScheme(parsed)+ this.checkHostPermitted(parsed.toString())const timeoutMs = clampTimeout(opts.timeoutMs, this.defaultTimeoutMs)const maxBodyBytes = clampMaxBody(@@ -409,10 +430,11 @@ export class HttpCapabilityHost {await response.body.dump?.()const loc = Array.isArray(location) ? (location[0] ?? '') : locationconst nextUrl = new URL(loc, currentUrl)- // Re-validate the scheme on every hop. checkScheme only ran on the- // initial URL, so a 3xx Location to file:// (or any non-http scheme)- // would otherwise escape the allowlist.+ // Re-validate the scheme and host confinement on every hop. Both+ // only ran on the initial URL, so a 3xx Location to file:// (or to+ // a host outside hostPermissions) would otherwise escape.checkScheme(nextUrl)+ this.checkHostPermitted(nextUrl.toString())currentUrl = nextUrl.toString()redirected = truehops += 1diff --git a/src/core/plugin/host/capability-bridge.dispatch.test.ts b/src/core/plugin/host/capability-bridge.dispatch.test.tsindex 97a92d98..dcf1e06c 100644--- a/src/core/plugin/host/capability-bridge.dispatch.test.ts+++ b/src/core/plugin/host/capability-bridge.dispatch.test.ts@@ -182,12 +182,15 @@ interface BridgeWithSpy {posted: unknown[]}-function makeBridge(capHost: CapabilityHost): BridgeWithSpy {+function makeBridge(+ capHost: CapabilityHost,+ manifest: PluginManifest = STUB_MANIFEST+): BridgeWithSpy {const posted: unknown[] = []const bridge = new CapabilityBridge({pluginId: PLUGIN_ID,- manifest: STUB_MANIFEST,+ manifest,bundleSource: '',capabilityHost: capHost,workerScriptPath: getStubWorkerPath(),@@ -344,6 +347,27 @@ describe('CapabilityBridge dispatch table', () => {expect(getStub).toHaveBeenCalledWith('https://example.com', undefined)})+ // 6b. http requests are confined to the manifest's hostPermissions+ it('http.get outside the manifest hostPermissions fails with host_not_permitted', async () => {+ const scoped = makeBridge(capHost, {+ ...STUB_MANIFEST,+ permissions: ['http'],+ hostPermissions: ['https://allowed.example/*'],+ })+ await new Promise((r) => setTimeout(r, 5))+ scoped.posted.length = 0++ await scoped.bridge.dispatchCall(+ makeCall('http', 'get', ['https://blocked.example/file'])+ )+ const resp = lastPosted(scoped.posted) as {+ ok: boolean+ error: { code: string }+ }+ expect(resp.ok).toBe(false)+ expect(resp.error.code).toBe('plugin.http.host_not_permitted')+ })+// 7. fs.storage.exists returns false for non-existent fileit('fs.storage.exists returns false for a non-existent file', async () => {await bridge.dispatchCall(diff --git a/src/core/plugin/host/capability-bridge.ts b/src/core/plugin/host/capability-bridge.tsindex 7500a2b0..9e82b2c2 100644--- a/src/core/plugin/host/capability-bridge.ts+++ b/src/core/plugin/host/capability-bridge.ts@@ -659,7 +659,13 @@ export class CapabilityBridge {private getPluginHttpHost(): HttpCapabilityHost {if (!this.pluginHttpHost) {const jar = this.opts.capabilityHost.cookieJarFor(this.opts.pluginId)- this.pluginHttpHost = new HttpCapabilityHost({ cookieJar: jar })+ this.pluginHttpHost = new HttpCapabilityHost({+ cookieJar: jar,+ // Confine outbound requests to the manifest's declared hosts — the+ // consent screen presents hostPermissions as the plugin's reach, so+ // the runtime must enforce it (no declaration ⇒ no hosts, rule I29).+ hostPermissions: this.opts.manifest.hostPermissions ?? [],+ })}return this.pluginHttpHost}diff --git a/src/renderer/components/add-task/add-task-form.test.tsx b/src/renderer/components/add-task/add-task-form.test.tsxindex 5031d7f8..da1caf28 100644--- a/src/renderer/components/add-task/add-task-form.test.tsx+++ b/src/renderer/components/add-task/add-task-form.test.tsx@@ -86,4 +86,60 @@ describe('AddTaskForm', () => {)expect(onSubmitSuccess).toHaveBeenCalledWith('test-gid')})++ it('submits one createTask per link line', async () => {+ const onSubmitSuccess = vi.fn()+ const user = userEvent.setup()+ const { transport } = await import('@renderer/lib/transport')+ renderForm({ onSubmitSuccess })++ await user.type(+ screen.getByRole('textbox'),+ 'https://a/1{Enter}https://b/2'+ )+ await user.click(screen.getByRole('button', { name: /download/i }))++ await waitFor(() =>+ expect(transport.invoke).toHaveBeenCalledWith(+ 'command:createTask',+ expect.objectContaining({ type: 'http', uris: ['https://b/2'] })+ )+ )+ expect(transport.invoke).toHaveBeenCalledWith(+ 'command:createTask',+ expect.objectContaining({ type: 'http', uris: ['https://a/1'] })+ )+ expect(onSubmitSuccess).toHaveBeenCalledWith('test-gid')+ expect(mockServices.notify).toHaveBeenCalledWith('info', 'task.add.created')+ })++ it('reports a partial failure when some lines fail', async () => {+ const onSubmitSuccess = vi.fn()+ const user = userEvent.setup()+ const { transport } = await import('@renderer/lib/transport')+ vi.mocked(transport.invoke).mockImplementation(+ async (channel: string, payload?: unknown) => {+ if (channel !== 'command:createTask') return {}+ const req = payload as { uris?: string[] }+ if (req.uris?.[0] === 'https://bad/2') throw new Error('boom')+ return { gid: 'ok-gid' }+ }+ )+ renderForm({ onSubmitSuccess })++ await user.type(+ screen.getByRole('textbox'),+ 'https://a/1{Enter}https://bad/2'+ )+ await user.click(screen.getByRole('button', { name: /download/i }))++ await waitFor(() =>+ expect(mockServices.notify).toHaveBeenCalledWith(+ 'warn',+ 'task.add.createdPartial',+ { ok: 1, failed: 1 }+ )+ )+ expect(onSubmitSuccess).toHaveBeenCalledWith('ok-gid')+ })})diff --git a/src/renderer/components/add-task/add-task-form.tsx b/src/renderer/components/add-task/add-task-form.tsxindex 016301ca..9d352297 100644--- a/src/renderer/components/add-task/add-task-form.tsx+++ b/src/renderer/components/add-task/add-task-form.tsx@@ -12,7 +12,7 @@ import { Queries } from '@shared/protocol/queries'import {type AddTaskFormValues,addTaskFormSchema,- formValuesToTaskCreateRequest,+ formValuesToTaskCreateRequests,} from '@shared/schemas/add-task'import { useCallback, useEffect, useState } from 'react'import {@@ -90,16 +90,32 @@ export function AddTaskForm({async (values: AddTaskFormValues) => {setSubmitting(true)try {- const request = formValuesToTaskCreateRequest(values)- const result = (await transport.invoke(- Commands.CreateTask,- request- )) as { gid: string }- platform.notify('info', 'task.add.created')- onSubmitSuccess?.(result.gid)- } catch (err) {- platform.notify('error', 'task.add.createFailed')- console.error(err)+ const requests = formValuesToTaskCreateRequests(values)+ const gids: string[] = []+ let failed = 0+ for (const request of requests) {+ try {+ const result = (await transport.invoke(+ Commands.CreateTask,+ request+ )) as { gid: string }+ gids.push(result.gid)+ } catch (err) {+ failed += 1+ console.error(err)+ }+ }+ if (failed === 0) {+ platform.notify('info', 'task.add.created')+ } else if (gids.length > 0) {+ platform.notify('warn', 'task.add.createdPartial', {+ ok: gids.length,+ failed,+ })+ } else {+ platform.notify('error', 'task.add.createFailed')+ }+ if (gids.length > 0) onSubmitSuccess?.(gids[0])} finally {setSubmitting(false)}diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsxindex 8894ca74..9672bdad 100644--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.test.tsx@@ -80,7 +80,9 @@ describe('RemoveTasksDialog', () => {expect(screen.getByText(/Remove 2 tasks/)).toBeDefined()})- it('defaults deleteFiles to true for all-Error selection', () => {+ it('defaults deleteFiles to false for all-Error selection', () => {+ // Error tasks can still hold partial data on disk; deleting must always+ // be an explicit opt-in, never a status-based default.render(<RemoveTasksDialogopen={true}@@ -94,7 +96,7 @@ describe('RemoveTasksDialog', () => {/>)const checkbox = screen.getByRole('checkbox')- expect(checkbox.getAttribute('aria-checked')).toBe('true')+ expect(checkbox.getAttribute('aria-checked')).toBe('false')})it('defaults deleteFiles to false for all-Completed selection', () => {diff --git a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsxindex 84f16b18..a057ec15 100644--- a/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx+++ b/src/renderer/routes/downloads/inspector/remove-tasks-dialog.tsx@@ -22,12 +22,6 @@ export interface RemoveTasksDialogProps {onConfirm: (deleteFiles: boolean) => void}-const NO_OUTPUT_STATES: ReadonlySet<TaskStatus> = new Set([- TaskStatus.Error,- TaskStatus.Removed,- TaskStatus.Queued,-])-const HAS_OUTPUT_STATES: ReadonlySet<TaskStatus> = new Set([TaskStatus.Completed,TaskStatus.Seeding,@@ -71,15 +65,6 @@ function buildTitle(})}-function defaultDeleteFiles(- selected: readonly DownloadTask[],- preCheck: boolean-): boolean {- if (preCheck) return true- if (selected.length === 0) return false- return selected.every((task) => NO_OUTPUT_STATES.has(task.status))-}-function hasOutput(selected: readonly DownloadTask[]): boolean {return selected.some((task) => task.downloadedBytes > 0 || HAS_OUTPUT_STATES.has(task.status)@@ -102,15 +87,16 @@ export function RemoveTasksDialog({}: RemoveTasksDialogProps) {const { t } = useTranslation()const checkboxId = useId()- const [deleteFiles, setDeleteFiles] = useState(() =>- defaultDeleteFiles(selected, preCheckDeleteFiles)- )+ // Deleting files is always an explicit opt-in (or the Shift shortcut via+ // preCheckDeleteFiles) — even Error/Queued selections may hold partial+ // data on disk, so no task status ever pre-checks the box.+ const [deleteFiles, setDeleteFiles] = useState(preCheckDeleteFiles)useEffect(() => {if (open) {- setDeleteFiles(defaultDeleteFiles(selected, preCheckDeleteFiles))+ setDeleteFiles(preCheckDeleteFiles)}- }, [open, selected, preCheckDeleteFiles])+ }, [open, preCheckDeleteFiles])const showEstimate = deleteFiles && hasOutput(selected)const title = buildTitle(selected, t)diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.jsonindex c0dd733c..9c83b9aa 100644--- a/src/shared/locales/en-US.json+++ b/src/shared/locales/en-US.json@@ -803,6 +803,7 @@"saveDirEmpty": "Choose a folder…","changeSaveDir": "Change save directory","created": "Task added",+ "createdPartial": "{{ok}} added · {{failed}} failed","adding": "Adding…","interpretedMagnet": "Magnet link detected","interpretedCurl": "cURL command parsed",diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.jsonindex d61e570f..ff46e912 100644--- a/src/shared/locales/zh-CN.json+++ b/src/shared/locales/zh-CN.json@@ -791,6 +791,7 @@"saveDirEmpty": "选择文件夹…","changeSaveDir": "更改保存目录","created": "任务已添加",+ "createdPartial": "已添加 {{ok}} 个,{{failed}} 个失败","adding": "添加中…","interpretedMagnet": "已识别磁力链接","interpretedCurl": "已解析 cURL 命令",diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.jsonindex a116687d..d7e0c07e 100644--- a/src/shared/locales/zh-TW.json+++ b/src/shared/locales/zh-TW.json@@ -791,6 +791,7 @@"saveDirEmpty": "選擇資料夾...","changeSaveDir": "變更儲存目錄","created": "已新增任務",+ "createdPartial": "已新增 {{ok}} 個,{{failed}} 個失敗","adding": "正在新增...","interpretedMagnet": "已偵測到 Magnet 連結","interpretedCurl": "已解析 cURL 命令",diff --git a/src/shared/schemas/add-task.test.ts b/src/shared/schemas/add-task.test.tsindex 2015a6fb..150fd705 100644--- a/src/shared/schemas/add-task.test.ts+++ b/src/shared/schemas/add-task.test.ts@@ -4,6 +4,7 @@ import {addTaskUrlParamsSchema,encodeUrlParams,formValuesToTaskCreateRequest,+ formValuesToTaskCreateRequests,taskCreateRequestSchema,urlParamsToFormDefaults,} from './add-task'@@ -152,6 +153,73 @@ describe('taskCreateRequestSchema', () => {})})+describe('formValuesToTaskCreateRequests', () => {+ it('creates one request per link line', () => {+ const reqs = formValuesToTaskCreateRequests({+ tab: 'links',+ urls: 'https://a/b\nhttps://c/d',+ saveDir: '/d',+ split: 5,+ })+ expect(reqs).toHaveLength(2)+ expect(reqs[0]).toMatchObject({ type: 'http', uris: ['https://a/b'] })+ expect(reqs[1]).toMatchObject({ type: 'http', uris: ['https://c/d'] })+ })++ it('converts a magnet line into its own bt request', () => {+ const magnet = `magnet:?xt=urn:btih:${'a'.repeat(40)}`+ const reqs = formValuesToTaskCreateRequests({+ tab: 'links',+ urls: `${magnet}\nhttps://c/d`,+ saveDir: '/d',+ split: 5,+ })+ expect(reqs[0]).toMatchObject({+ type: 'bt',+ payload: { kind: 'magnet', uri: magnet },+ })+ expect(reqs[1]).toMatchObject({ type: 'http', uris: ['https://c/d'] })+ })++ it('applies the filename override only for a single line', () => {+ const multi = formValuesToTaskCreateRequests({+ tab: 'links',+ urls: 'https://a/b\nhttps://c/d',+ saveDir: '/d',+ split: 5,+ filename: 'x.zip',+ }) as Array<{ filename?: string }>+ expect(multi.map((r) => r.filename)).toEqual([undefined, undefined])++ const single = formValuesToTaskCreateRequests({+ tab: 'links',+ urls: 'https://a/b',+ saveDir: '/d',+ split: 5,+ filename: 'x.zip',+ })+ expect(single[0]).toMatchObject({ filename: 'x.zip' })+ })++ it('wraps a torrent submission in a single request', () => {+ const reqs = formValuesToTaskCreateRequests({+ tab: 'torrent',+ source: 'file',+ base64: 'AAAA',+ torrentMeta: {+ name: 't',+ infoHash: 'a'.repeat(40),+ totalSize: 0,+ files: [],+ },+ selectedFiles: [0],+ saveDir: '/d',+ })+ expect(reqs).toHaveLength(1)+ expect(reqs[0]).toMatchObject({ type: 'bt' })+ })+})+describe('formValuesToTaskCreateRequest', () => {it('converts minimal links form', () => {const req = formValuesToTaskCreateRequest({diff --git a/src/shared/schemas/add-task.ts b/src/shared/schemas/add-task.tsindex 281ad0e8..d8ea9579 100644--- a/src/shared/schemas/add-task.ts+++ b/src/shared/schemas/add-task.ts@@ -187,6 +187,25 @@ function splitUrlLines(raw: string): string[] {.filter((l) => l.length > 0)}+/**+ * One request per pasted link line. Each line is an independent download —+ * a magnet line becomes its own bt request, everything else an http request+ * with the shared advanced options. The filename override only applies when+ * exactly one line is present (the same name on several tasks would collide).+ * Mirror semantics (several uris feeding one task) remain available to API+ * callers via the singular converter below.+ */+export function formValuesToTaskCreateRequests(+ v: AddTaskFormValues+): TaskCreateRequest[] {+ if (v.tab !== 'links') return [formValuesToTaskCreateRequest(v)]+ const lines = splitUrlLines(v.urls)+ const filename = lines.length === 1 ? v.filename : undefined+ return lines.map((line) =>+ formValuesToTaskCreateRequest({ ...v, urls: line, filename })+ )+}+export function formValuesToTaskCreateRequest(v: AddTaskFormValues): TaskCreateRequest {diff --git a/tests/scripts/audit-server-runtime.test.ts b/tests/scripts/audit-server-runtime.test.tsindex 5da9e392..43fbb154 100644--- a/tests/scripts/audit-server-runtime.test.ts+++ b/tests/scripts/audit-server-runtime.test.ts@@ -293,6 +293,25 @@ describe('Server built external audit', () => {).toEqual(['@scope/gamma', 'alpha', 'beta', 'delta', 'epsilon'])})+ it('does not lose imports after a regex literal containing quotes', () => {+ // Regression: bundle order shuffles could place guest-code rewrite+ // helpers (whose regex literals contain quote characters) before real+ // import statements; a tokenizer without regex-literal support started+ // a phantom string at the quote and desynchronized, dropping every+ // later specifier and mis-flagging pinned runtime roots as stale.+ const source = [+ String.raw`const stripped = code.replace(/\}\s*from\s*['"]motrix:plugin-api['"]\s*;?/g, patch);`,+ 'const ratio = total / 2 / count;',+ 'const halved = width() / 2;',+ 'import * as schema from "@motrix/plugin-manifest-schema";',+ 'export { audit } from "zeta/audit";',+ ].join('\n')+ expect(scanStaticModuleSpecifiers(source)).toEqual([+ '@motrix/plugin-manifest-schema',+ 'zeta/audit',+ ])+ })+it('measures reviewed inputs and rejects root drift', async () => {const root = await createFixture()const report = await auditServerRuntime({