Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(security): resolve the code-scanning and Dependabot alert backlog (#226)

Ruben Lütkebcf49f10c39a
diff --git a/jarvis/agentic_ide/clarify.py b/jarvis/agentic_ide/clarify.py
index a813c88588..446971c6fb 100644
--- a/jarvis/agentic_ide/clarify.py
+++ b/jarvis/agentic_ide/clarify.py
@@ -206,7 +206,21 @@ def addresses_workspace(text: str) -> bool:
#: ``names`` so the two cannot disagree about where a name starts and ends.
_WORD_RE = CALL_SIGN_WORD_RE
-_SENTENCE_START_RE = re.compile(r"(?:^|[.!?:;]\s*|\n\s*)$")
+def _opens_sentence(prefix: str) -> bool:
+ """True when whatever follows ``prefix`` stands at the start of a sentence.
+
+ That holds when ``prefix`` is empty, when its last non-blank character is
+ sentence punctuation (``.!?:;``), or when its trailing blank run contains
+ a line break. A plain string scan on purpose: the equivalent searched
+ regex ``(?:^|[.!?:;]\\s*|\\n\\s*)$`` retried every start position and went
+ quadratic on long whitespace runs (CodeQL py/polynomial-redos).
+ """
+ core = prefix.rstrip()
+ if "\n" in prefix[len(core) :]:
+ return True
+ if not core:
+ return not prefix
+ return core[-1] in ".!?:;"
#: Function words that are never a call-sign, however close they score. This is
#: matching *input vocabulary*, not prose.
@@ -377,7 +391,7 @@ def is_part_of_full_name(text: str, start: int, end: int) -> bool:
# read "Ist Blake fertig?" as a person called Ist Blake, because "Ist" is
# capitalized for grammar and stands at the very beginning — which silently
# withdrew the pane from every question opening with a verb.
- return not _SENTENCE_START_RE.search(preceding[: leading.start()])
+ return not _opens_sentence(preceding[: leading.start()])
#: Two capitalized words in a row, the second not opening a sentence — a person
@@ -474,11 +488,15 @@ class ClarificationNeeded:
#: enumeration punctuation and the supported languages' "and" — anything else
#: means the two words are in different clauses and say nothing about each
#: other. Matching *input vocabulary*, not prose.
+#: The separator runs are possessive and the second one only follows a
+#: conjunction: two adjacent optional runs let the engine try every split of a
+#: long blank gap, which is quadratic (CodeQL py/polynomial-redos). The accepted
+#: language is unchanged.
_ENUMERATION_GAP_RE = re.compile(
- r"^[\s,;&]*"
+ r"^[\s,;&]*+"
# i18n-allow: input vocabulary — the supported languages' "and"
- r"(?:und|and|y|e|sowie|plus|as\s+well\s+as|together\s+with|junto\s+con)?"
- r"[\s,;&]*$",
+ r"(?:(?:und|and|y|e|sowie|plus|as\s+well\s+as|together\s+with|junto\s+con)"
+ r"[\s,;&]*+)?$",
re.IGNORECASE,
)
diff --git a/jarvis/agentic_ide/intent.py b/jarvis/agentic_ide/intent.py
index db8a31ca55..531516e7d6 100644
--- a/jarvis/agentic_ide/intent.py
+++ b/jarvis/agentic_ide/intent.py
@@ -74,7 +74,7 @@ _DIRECTIVE_TEMPLATES: tuple[str, ...] = (
# nothing was typed into Alex, and the live model filled the silence by
# claiming the agent had been briefed. Every neighbouring module already
# knew this vocabulary (``clarify._WORKSPACE_NOUN_RE``,
- # ``_FLEET_BRIEF_RE``, ``_CLOSE_BRIEFING_RE``); only the list that decides
+ # ``_fleet_brief_search``, ``_CLOSE_BRIEFING_RE``); only the list that decides
# who gets the work did not.
#
# Stems, so "prompting" / "prompte" / "anprompten" / "promptea" all land.
@@ -392,9 +392,12 @@ def _strip_addressing(text: str, *names: str) -> str:
# fan-out, whereas two names each carrying their own directive are two separate
# assignments and are found on their own. Anything else is not an enumeration.
# The alternative conjunction ("oder" / "or") is left out on purpose — offering
-# a choice between two panes is not an address list.
+# a choice between two panes is not an address list. The runs are possessive
+# and the second one only follows a conjunction: two adjacent optional runs
+# let the engine try every split of a long blank gap (CodeQL
+# py/polynomial-redos). The accepted language is unchanged.
_COORDINATION_RE = re.compile(
- r"^[\s,]*(?:und|and|sowie|plus|y|&|\+)?[\s,]*$",
+ r"^[\s,]*+(?:(?:und|and|sowie|plus|y|&|\+)[\s,]*+)?$",
re.IGNORECASE,
)
@@ -480,8 +483,10 @@ _NO_WORK_AFTER_NAME_RE = re.compile(
re.IGNORECASE,
)
+# Possessive runs: ``\s*[.!?]?\s*`` let the engine try every split of a long
+# blank run (CodeQL py/polynomial-redos). The accepted language is unchanged.
_TRAILING_NEGATION_RE = re.compile(
- r"^[\s,:\-]*(?:aber\s+)?(?:nicht|not|no)\s*[.!?]?\s*$",
+ r"^[\s,:\-]*+(?:aber\s++)?(?:nicht|not|no)\s*+[.!?]?+\s*+$",
re.IGNORECASE,
)
@@ -1162,8 +1167,12 @@ _QUESTION_OPENER_RE = re.compile(
# clause ("Und was passiert, wenn ...?"). Ignore only these bounded discourse
# words when deciding whether that clause is an information question; second-
# person requests such as "Und kannst du ...?" remain commands.
+#
+# The blank runs are possessive and the second one only follows the "¿": two
+# adjacent ``\s*`` let the engine try every split of a long blank run
+# (CodeQL py/polynomial-redos). The matched prefix is unchanged.
_QUESTION_DISCOURSE_PREFIX_RE = re.compile(
- r"^\s*¿?\s*(?:(?:und|and|y)\b[\s,;:–—-]*)+", # i18n-allow: input vocab
+ r"^\s*+(?:¿\s*+)?(?:(?:und|and|y)\b[\s,;:–—-]*+)+", # i18n-allow: input vocab
re.IGNORECASE,
)
@@ -1897,7 +1906,12 @@ def _span_gap(left: re.Match[str], right: re.Match[str]) -> int:
return 0
-_FLEET_BRIEF_RE = re.compile(
+# The briefing vocabulary that hands a fleet its work. Always searched through
+# ``_fleet_brief_search``, which adds the one multi-word form ("gib ihnen die
+# Aufgabe"): as a regex alternative, ``gib\w*\s+.*\baufgabe`` rescanned the
+# rest of the line from every "gib" and went quadratic on long input (CodeQL
+# py/polynomial-redos).
+_FLEET_BRIEF_VERB_RE = re.compile(
r"\b(?:jede\w*\s+(?:davon|dieser)|each\s+(?:one|of\s+them)|"
r"prompt\w*|brief\w*|instruct\w*|assign\w*|tell\w*|"
# "sag ihnen, …" / "diles que …" — the plain-speech handover verbs. They
@@ -1905,9 +1919,51 @@ _FLEET_BRIEF_RE = re.compile(
# was parsed as MORE FLEET: the counts inside it opened extra panes
# (live 2026-08-12 17:40, four billed panes for a spoken "two").
r"sag\w*|diles?|d[ií]gale|" # i18n-allow: input vocab
- r"anweis\w*|beauftrag\w*|gib\w*\s+.*\baufgabe\w*)\b", # i18n-allow: input vocab
+ r"anweis\w*|beauftrag\w*)\b", # i18n-allow: input vocab
+ re.IGNORECASE,
+)
+# "gib <…> Aufgabe" on one line. Only ever ``match``-ed at a start that
+# ``_fleet_brief_search`` has already proven to succeed, so it never fails
+# and never backtracks across the line more than once.
+_FLEET_BRIEF_GIVE_TASK_RE = re.compile(
+ r"\bgib\w*\s++.*\baufgabe\w*\b", # i18n-allow: input vocab
re.IGNORECASE,
)
+_GIVE_LEAD_RE = re.compile(r"\bgib\w*\s++", re.IGNORECASE) # i18n-allow: input vocab
+_TASK_NOUN_RE = re.compile(r"\baufgabe", re.IGNORECASE) # i18n-allow: input vocab
+
+
+def _fleet_brief_search(text: str, pos: int = 0, endpos: int | None = None) -> re.Match[str] | None:
+ """Leftmost briefing phrase in ``text[pos:endpos]``, or ``None``.
+
+ Same result as searching the single pattern
+ ``\\b(?:<verbs>|gib\\w*\\s+.*\\baufgabe\\w*)\\b``, in linear time. A "gib"
+ counts when an "aufgabe" word follows on the line its blank run ends on
+ (``.`` stops at a line break); both are located with one forward pass
+ each, then the winning "gib" is re-matched once for a real ``Match``.
+ """
+ if endpos is None:
+ endpos = len(text)
+ verb = _FLEET_BRIEF_VERB_RE.search(text, pos, endpos)
+ limit = verb.start() if verb is not None else endpos
+ nouns = _TASK_NOUN_RE.finditer(text, pos, endpos)
+ noun = next(nouns, None)
+ line_break = -1
+ for lead in _GIVE_LEAD_RE.finditer(text, pos, endpos):
+ if lead.start() >= limit:
+ break
+ landing = lead.end()
+ while noun is not None and noun.start() < landing:
+ noun = next(nouns, None)
+ if noun is None:
+ break
+ if line_break < landing:
+ line_break = text.find("\n", landing, endpos)
+ if line_break == -1:
+ line_break = endpos
+ if noun.start() < line_break:
+ return _FLEET_BRIEF_GIVE_TASK_RE.match(text, lead.start(), endpos)
+ return verb
#: Coding CLIs that exist in the world but not as a terminal kind here.
@@ -2194,7 +2250,7 @@ def _spawn_span(text: str) -> _SpawnSpan | None:
for pane in panes
for actor in actors
if _span_gap(pane, actor) <= _SPAWN_PAIR_MAX_GAP
- and _FLEET_BRIEF_RE.search(
+ and _fleet_brief_search(
clause,
min(pane.end(), actor.end()),
max(pane.start(), actor.start()),
@@ -2214,7 +2270,7 @@ def _spawn_span(text: str) -> _SpawnSpan | None:
# as the SUBJECT of their own work ("and the two terminals should …",
# "one terminal takes macOS …") — see ``_task_subject_cut``.
parse_end = len(clause)
- briefing = _FLEET_BRIEF_RE.search(clause, anchor_end)
+ briefing = _fleet_brief_search(clause, anchor_end)
if briefing is not None:
parse_end = briefing.start()
subject = _task_subject_cut(clause, anchor_end)
@@ -2235,7 +2291,7 @@ def _task_subject_cut(clause: str, from_pos: int) -> int | None:
The verbless handover: after the fleet is asked for, the panes come back
as the SUBJECT of a job — "… and the two terminals should do a deep
dive", "… one terminal takes macOS and one terminal takes Linux". No
- briefing verb marks the turn, so ``_FLEET_BRIEF_RE`` sails past it and
+ briefing verb marks the turn, so ``_fleet_brief_search`` sails past it and
every count in that job was read as MORE fleet: a spoken "two" opened
four billed panes (live 2026-08-12 17:40).
@@ -2305,7 +2361,7 @@ def _spawn_regions(text: str) -> list[_SpawnSpan]:
)
if regions:
previous_end = regions[-1].start + len(regions[-1].parse_text)
- if _FLEET_BRIEF_RE.search(text, previous_end, absolute.end) is not None:
+ if _fleet_brief_search(text, previous_end, absolute.end) is not None:
break
regions.append(absolute)
if absolute.truncated:
@@ -2432,7 +2488,7 @@ def spawn_includes_task(user_text: str) -> bool:
# briefed to open terminals (live 2026-08-12, see ``_spawn_regions``).
last = regions[-1]
remainder = text[last.start + len(last.parse_text) :]
- if _FLEET_BRIEF_RE.search(remainder) or _INSTRUCTION_VERB_RE.search(remainder):
+ if _fleet_brief_search(remainder) or _INSTRUCTION_VERB_RE.search(remainder):
return True
return bool(_leading_task(text, regions[0]))
@@ -2558,10 +2614,16 @@ _GROUP_BRIEF_CONNECTIVE_RE = re.compile(
#: Trailing debris once the next group's clause is cut away: the conjunction
#: and the article that belonged to the NEXT addressee ("… fixen und der ").
+#:
+#: Linear by construction (CodeQL py/polynomial-redos): the match may only
+#: start where no separator precedes it — the leftmost match never does, since
+#: a separator in front would simply join the first run — and every run and
+#: word is possessive, so a long blank tail is scanned once instead of being
+#: split three ways at every start position. The trimmed result is unchanged.
_GROUP_TASK_TRIM_RE = re.compile(
- r"[\s,;.]*(?:\b(?:und|and|y|sowie|plus)\b)?" # i18n-allow: input vocab
- r"[\s,;.]*(?:\b(?:the|die|der|das|den|dem|el|la|los|las)\b)?" # i18n-allow: input vocab
- r"[\s,;.]*$",
+ r"(?<![\s,;.])[\s,;.]*+(?:\b(?:und|and|y|sowie|plus)\b)?+" # i18n-allow: input vocab
+ r"[\s,;.]*+(?:\b(?:the|die|der|das|den|dem|el|la|los|las)\b)?+" # i18n-allow: input vocab
+ r"[\s,;.]*+$",
re.IGNORECASE,
)
@@ -2936,7 +2998,7 @@ def _briefed_position_only(parse_text: str) -> bool:
doubles as a number ("dass es EIN deep dive machen soll") shows none of
those shapes and vetoes nothing.
""" # i18n-allow: quoted spoken input
- if _FLEET_BRIEF_RE.search(parse_text) is None:
+ if _fleet_brief_search(parse_text) is None:
return False
positions = spoken_positions(parse_text)
if not positions:
diff --git a/jarvis/agentic_ide/library.py b/jarvis/agentic_ide/library.py
index d1eeaf48cc..abb9cbb2db 100644
--- a/jarvis/agentic_ide/library.py
+++ b/jarvis/agentic_ide/library.py
@@ -63,6 +63,8 @@ from uuid import uuid4
from loguru import logger
+from jarvis.core.path_safety import UnsafePathError, safe_child
+
#: Saves arrive from several request handlers at once; the last writer has to be
#: the one that lands rather than the one that finished its rename first.
_WRITE_LOCK = threading.RLock()
@@ -159,8 +161,17 @@ def _projects_path() -> Path:
return _root() / "projects.json"
-def _threads_path(project_id: str) -> Path:
- return _root() / "threads" / f"{project_id}.json"
+def _threads_path(project_id: str) -> Path | None:
+ """The chat file of one project, or None when the id is not a plain name.
+
+ Project ids reach this from HTTP routes, so the file name is checked to stay
+ inside the threads folder before anything reads, writes or deletes it.
+ """
+ try:
+ return safe_child(_root() / "threads", f"{project_id}.json")
+ except UnsafePathError:
+ logger.warning("Chat library: refusing project id {!r}", project_id)
+ return None
def _read_json(path: Path) -> Any:
@@ -437,8 +448,10 @@ def delete_project(project_id: str) -> bool:
if len(kept) == len(projects):
return False
_save_projects(kept)
+ threads_file = _threads_path(project_id)
try:
- _threads_path(project_id).unlink(missing_ok=True)
+ if threads_file is not None:
+ threads_file.unlink(missing_ok=True)
except OSError as exc:
logger.warning("Chat library: could not drop chats of {}: {}", project_id, exc)
return True
@@ -451,7 +464,10 @@ def delete_project(project_id: str) -> bool:
def _load_threads(project_id: str) -> list[Thread]:
out: list[Thread] = []
- for item in _unwrap(_read_json(_threads_path(project_id)), "threads"):
+ path = _threads_path(project_id)
+ if path is None:
+ return out
+ for item in _unwrap(_read_json(path), "threads"):
tid = str(item.get("id") or "").strip()
if not tid:
continue
@@ -477,9 +493,10 @@ def _load_threads(project_id: str) -> list[Thread]:
def _save_threads(project_id: str, threads: list[Thread]) -> bool:
- return _write_json(
- _threads_path(project_id), _envelope("threads", [t.to_dict() for t in threads])
- )
+ path = _threads_path(project_id)
+ if path is None:
+ return False
+ return _write_json(path, _envelope("threads", [t.to_dict() for t in threads]))
def list_threads(project_id: str, *, include_archived: bool = False) -> list[Thread]:
diff --git a/jarvis/brain/ack_generator.py b/jarvis/brain/ack_generator.py
index 54782ed418..c6d9f3f8ad 100644
--- a/jarvis/brain/ack_generator.py
+++ b/jarvis/brain/ack_generator.py
@@ -91,7 +91,9 @@ _VOICE_CONTROL_PATTERN = re.compile(
r")"
# Optional trailing politeness / acknowledgment modifier
r"(?:\s+(?:bitte|mal|jetzt|please|now|please\s+now))?"
- r"\s*[!.?]?\s*$",
+ # Possessive tail: ``\s*[!.?]?\s*`` let the engine try every split of a
+ # long blank run before failing (CodeQL py/polynomial-redos). Same language.
+ r"\s*+[!.?]?+\s*+$",
re.IGNORECASE,
)
diff --git a/jarvis/brain/local_outcome_gate.py b/jarvis/brain/local_outcome_gate.py
index 3816e891ca..44ac608bf9 100644
--- a/jarvis/brain/local_outcome_gate.py
+++ b/jarvis/brain/local_outcome_gate.py
@@ -48,6 +48,7 @@ Stand-downs (each defers to the flow that owns the turn):
from __future__ import annotations
import re
+from collections.abc import Callable
from jarvis.brain.local_action_gate import requires_external_integration
from jarvis.core.capabilities import _normalize
@@ -202,9 +203,71 @@ _TASK_CLAUSE_RE = re.compile(
r",\s+(?:and|und)\s+(?=(?:please\s+|bitte\s+)?" # i18n-allow
+ _FS_VERB_RE.pattern + r")"
)
-_QUOTED_LITERAL_RE = re.compile(
- r'''(?<!\w)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`]*`)'''
-)
+_QUOTE_CHAR_RE = re.compile(r"[\"'`]")
+
+
+def _scan_quoted_literal(text: str, start: int) -> tuple[bool, int]:
+ """Scan the literal opened by the quote at ``start``.
+
+ Returns ``(True, end)`` with ``end`` just past the closing quote, or
+ ``(False, stop)`` with the index where the scan gave up. Inside ``"…"``
+ and ``'…'`` a backslash escapes any next character except a line break
+ (a backslash before a line break, or at the end, ends the scan); a
+ backtick literal runs to the next backtick.
+ """
+ kind = text[start]
+ size = len(text)
+ if kind == "`":
+ close = text.find("`", start + 1)
+ return (False, size) if close < 0 else (True, close + 1)
+ pos = start + 1
+ while pos < size:
+ char = text[pos]
+ if char == "\\":
+ if pos + 1 < size and text[pos + 1] != "\n":
+ pos += 2
+ continue
+ return False, pos
+ if char == kind:
+ return True, pos + 1
+ pos += 1
+ return False, size
+
+
+def _sub_quoted_literals(repl: Callable[[int, str], str], text: str) -> str:
+ """Replace every quoted literal with ``repl(start, literal)``, in linear time.
+
+ Same matches as ``re.sub`` with the pattern
+ ``(?<!\\w)(?:"(?:\\\\.|[^"\\\\])*"|'(?:\\\\.|[^'\\\\])*'|`[^`]*`)``. That
+ regex retried at every quote character, and an unclosed literal — or a run
+ of escaped quotes (``"\\"\\"\\"…``) — rescanned the rest of the text from
+ each of them: quadratic on long input (CodeQL py/polynomial-redos). Here a
+ quote of the same kind inside a failed scan is skipped: that scan consumed
+ it as an escaped pair, so a scan opened there would resume in step and fail
+ at the same place.
+ """
+ pieces: list[str] = []
+ consumed = 0
+ dead_until = {'"': -1, "'": -1, "`": -1}
+ for quote in _QUOTE_CHAR_RE.finditer(text):
+ start = quote.start()
+ kind = quote.group()
+ if start < consumed or start < dead_until[kind]:
+ continue
+ closed, stop = _scan_quoted_literal(text, start)
+ if not closed:
+ dead_until[kind] = stop
+ continue
+ before = text[start - 1] if start else ""
+ if before.isalnum() or before == "_":
+ continue # the ``(?<!\w)`` guard: a quote inside a word ("don't")
+ pieces.append(text[consumed:start])
+ pieces.append(repl(start, text[start:stop]))
+ consumed = stop
+ pieces.append(text[consumed:])
+ return "".join(pieces)
+
+
_COMMAND_LITERAL_PREFIX_RE = re.compile(
r"\b(?:run|execute|launch|fuehre|starte)\s+(?:(?:the|this|following)\s+)?$", # i18n-allow
re.IGNORECASE,
@@ -252,13 +315,13 @@ def resolve_local_outcome_mandate(utterance: str) -> tuple[str, str] | None:
return None
# A quoted filename or example is a literal, not an instruction/context
# marker. Preserve apostrophes inside words such as "don't".
- def mask_literal(match: re.Match[str]) -> str:
+ def mask_literal(start: int, _literal: str) -> str:
# An explicit "run <quoted command>" still names an executable object.
# Its contents remain shielded from negation and vehicle detection.
- prefix = _normalize(raw[:match.start()])
+ prefix = _normalize(raw[:start])
return " command " if _COMMAND_LITERAL_PREFIX_RE.search(prefix) else " quoted_literal "
- normalized = _normalize(_QUOTED_LITERAL_RE.sub(mask_literal, raw))
+ normalized = _normalize(_sub_quoted_literals(mask_literal, raw))
tasks = [_positive_task_prefix(clause).strip() for clause in _TASK_CLAUSE_RE.split(normalized)]
# An explicitly selected vehicle governs the subsequent action, even
# across a sentence boundary ("Use the mouse. Create a folder.").
diff --git a/jarvis/brain/mission_command_gate.py b/jarvis/brain/mission_command_gate.py
index 5c5a9e8ae0..6c8acf09c0 100644
--- a/jarvis/brain/mission_command_gate.py
+++ b/jarvis/brain/mission_command_gate.py
@@ -56,14 +56,17 @@ _STATUS_PATTERN_DE = re.compile(
# bare 'wie weit' at sentence start or before '?'/end — asks about progress.
# NOT 'wie weit ist Berlin' etc. (qualifier-free only matches when
# the question character is recognisable via '?'/end).
- ^\s*(?:jarvis[,\s]+)?wie\s+weit\s*\??\s*$
+ # Blank runs are possessive throughout this module: adjacent optional
+ # runs let the engine try every split of a long blank run before
+ # failing (CodeQL py/polynomial-redos). Same language.
+ ^\s*+(?:jarvis[,\s]+)?wie\s++weit\s*+\??+\s*+$
|
# 'wie weit' + person/mission qualifier
\bwie\s+weit\s+(?:bist\s+du|sind\s+wir|sind\s+sie|sind\s+die\s+mission|ist\s+(?:die\s+mission|der\s+sub|claw|openclaw))\b # i18n-allow
|
# 'status' alone (at start or after 'jarvis,'); MUST have question/end
# character, otherwise it matches 'Status der Wirtschaft' incorrectly.
- ^(?:jarvis[,\s]+)?status\s*[?.!]*\s*$
+ ^(?:jarvis[,\s]+)?status\s*+[?.!]*+\s*+$
|
# 'status der mission' / 'status vom sub' / 'status von openclaw' # i18n-allow
\bstatus\s+(?:der\s+mission|vom\s+sub|von\s+(?:openclaw|claw)|bei\s+(?:openclaw|claw))\b # i18n-allow
@@ -91,7 +94,10 @@ _STATUS_PATTERN_EN = re.compile(
what(?:'s|\s+is)\s+the\s+status
|
# 'status?' as standalone or after 'jarvis,' — same restriction as DE
- ^(?:jarvis[,\s]+)?status\s*[?.!]*\s*$
+ # (Two branches rather than possessive runs: the closing \b may only
+ # hold at the '$' in front of a final line break, so the blank-only
+ # branch has to be able to give that break back.)
+ ^(?:jarvis[,\s]+)?status(?:\s*+[?.!]++\s*+$|\s*$)
|
# 'how far (are we|along|is it)'
how\s+far\s+(?:are|is|along)
@@ -120,7 +126,7 @@ _CANCEL_PATTERN_DE = re.compile(
r"""
(
# 'brich (das|die|den|alles) ab' # i18n-allow
- \bbrich\s+(?:das|die\s+mission|den\s+auftrag|alles|openclaw|claw|sub|den)\s*\w*\s*ab\b # i18n-allow
+ \bbrich\s+(?:das|die\s+mission|den\s+auftrag|alles|openclaw|claw|sub|den)\s*+(?:\w+\s*+)?ab\b # i18n-allow
|
# 'brich ab' — short form
^(?:jarvis[,\s]+)?brich\s+ab\b
diff --git a/jarvis/brain/output_filter.py b/jarvis/brain/output_filter.py
index 658f417261..1b66bd8386 100644
--- a/jarvis/brain/output_filter.py
+++ b/jarvis/brain/output_filter.py
@@ -229,10 +229,85 @@ TOOL_XML_RE = re.compile(
# format. The brain occasionally leaks this verbatim into the output. The
# pattern matches the whole block, greedy up to the closing tag. Also a
# standalone ``<invoke>`` in case the ``</function_calls>`` wrapper is missing.
-ANTHROPIC_FUNCTION_CALLS_RE = re.compile(
- r"<function_calls>.*?</function_calls>",
- re.DOTALL | re.IGNORECASE,
-)
+_FUNCTION_CALLS_TAG_RE = re.compile(r"<function_calls>|</function_calls>", re.IGNORECASE)
+
+
+def _strip_function_call_blocks(text: str) -> str:
+ """Remove every ``<function_calls>…</function_calls>`` block, in linear time.
+
+ Same result as ``re.sub(r"<function_calls>.*?</function_calls>", "", text,
+ flags=re.DOTALL | re.IGNORECASE)``: each block runs from the leftmost
+ opener to the first closer after it. That lazy regex rescanned the rest of
+ the text from every unclosed opener, which is quadratic on long LLM output
+ (CodeQL py/polynomial-redos), so the tags are walked once instead. The two
+ tags cannot overlap each other, so a single left-to-right token pass sees
+ exactly the tags the regex would.
+ """
+ pieces: list[str] = []
+ kept_from = 0
+ block_start = -1
+ for tag in _FUNCTION_CALLS_TAG_RE.finditer(text):
+ closing = tag.group().startswith("</")
+ if block_start < 0 and not closing:
+ block_start = tag.start()
+ elif block_start >= 0 and closing:
+ pieces.append(text[kept_from:block_start])
+ kept_from = tag.end()
+ block_start = -1
+ pieces.append(text[kept_from:])
+ return "".join(pieces)
+
+
+_UNICODE_DASH_RE = re.compile(r"[—–]")
+_DOUBLE_HYPHEN_RE = re.compile(r"-{2,}")
+
+
+def _collapse_unicode_dashes(text: str) -> str:
+ """Replace each em/en dash and the blanks around it with ", ".
+
+ Same result as ``re.sub(r"\\s*[—–]\\s*", ", ", text)``, in linear time:
+ that pattern restarted ``\\s*`` at every position of a long blank run and
+ rescanned the run each time (CodeQL py/polynomial-redos). Splitting at the
+ dashes and trimming the blanks next to each cut is the same edit.
+ """
+ parts = _UNICODE_DASH_RE.split(text)
+ if len(parts) == 1:
+ return text
+ last = len(parts) - 1
+ return ", ".join(
+ part.rstrip() if i == 0 else part.lstrip() if i == last else part.strip()
+ for i, part in enumerate(parts)
+ )
+
+
+def _collapse_double_hyphens(text: str) -> str:
+ """Replace each blank-framed ``--`` aside (and its blanks) with ", ".
+
+ Same result as ``re.sub(r"\\s+-{2,}\\s+", ", ", text)``, in linear time
+ (that pattern had the same restart problem as the dash rewrite above). A
+ hyphen run counts only when blanks frame it on both sides; blanks already
+ swallowed by the previous replacement cannot frame the next one.
+ """
+ pieces: list[str] = []
+ kept_from = 0
+ size = len(text)
+ for run in _DOUBLE_HYPHEN_RE.finditer(text):
+ start, end = run.span()
+ left = start
+ while left > kept_from and text[left - 1].isspace():
+ left -= 1
+ if left == start or end >= size or not text[end].isspace():
+ continue
+ right = end
+ while right < size and text[right].isspace():
+ right += 1
+ pieces.append(text[kept_from:left])
+ pieces.append(", ")
+ kept_from = right
+ pieces.append(text[kept_from:])
+ return "".join(pieces)
+
+
ANTHROPIC_INVOKE_RE = re.compile(
r"<invoke\b[^>]*>.*?</invoke>",
re.DOTALL | re.IGNORECASE,
@@ -671,12 +746,12 @@ def scrub_for_voice(
out = new
# 3. Tool-Call-JSON / -KW / -XML / YAML-Args / Anthropic-Tags / Base64 —
- # alle Tool-Use-/Internal-Leaks rausschneiden.
- # Reihenfolge: zuerst die groessten Wrapper-Bloecke (function_calls,
- # generic_tool_wrappers, base64_data_uri), dann verbleibende kleinere
- # Patterns. Sonst koennten innere Token-Patterns Teile des Wrapper-
- # Inhalts matchen und Whitespace-Reste hinterlassen.
- new = ANTHROPIC_FUNCTION_CALLS_RE.sub("", out)
+ # cut out every tool-use / internal leak.
+ # Order: the largest wrapper blocks first (function_calls,
+ # generic_tool_wrappers, base64_data_uri), then the remaining smaller
+ # patterns. Otherwise inner token patterns could match parts of the
+ # wrapper content and leave whitespace behind.
+ new = _strip_function_call_blocks(out)
new = ANTHROPIC_INVOKE_RE.sub("", new)
new = GENERIC_TOOL_WRAPPER_RE.sub("", new)
new = BASE64_DATA_URI_RE.sub("", new)
@@ -803,13 +878,13 @@ def scrub_for_voice(
# comma. Hyphen compounds ("Browser-Provider", "Sub-Agent") use a plain
# ASCII '-' with no surrounding whitespace and are NOT in the class below,
# so they survive untouched.
- new = re.sub(r"\s*[—–]\s*", ", ", out)
+ new = _collapse_unicode_dashes(out)
# ASCII double hyphen used as a dash-aside (" -- ") reads as the same hard
# TTS pause; collapse it too (2026-06-30: the Unicode-only scrub missed it,
# and several canned phrases / LLM outputs use " -- "). Require surrounding
# whitespace so hyphen compounds ("T-Shirt") and numeric ranges ("20-30") —
# which have no spaces — survive untouched.
- new = re.sub(r"\s+-{2,}\s+", ", ", new)
+ new = _collapse_double_hyphens(new)
if new != out:
actions.append("removed_em_dash")
out = new
@@ -826,7 +901,8 @@ def scrub_for_voice(
actions.append("spelled_out_numbers")
out = new
- # 8. Whitespace normalisieren
+ # 8. Normalise whitespace. After the first line every blank run is a
+ # single character, so the ``\s+`` patterns below cannot backtrack.
out = re.sub(r"\s{2,}", " ", out).strip()
out = re.sub(r"\s+([,.!?;:])", r"\1", out)
# A dash->comma swap can leave a doubled or dangling comma; tidy it.
diff --git a/jarvis/contacts/store.py b/jarvis/contacts/store.py
index 95003a2a83..0b1d232c2a 100644
--- a/jarvis/contacts/store.py
+++ b/jarvis/contacts/store.py
@@ -40,6 +40,7 @@ Frontmatter layout::
<the ~300-word Markdown README is the body>
"""
+
from __future__ import annotations
import os
@@ -50,6 +51,7 @@ from datetime import UTC, date, datetime
from pathlib import Path
from typing import Any
+from jarvis.core.path_safety import UnsafePathError, contained_path
from jarvis.core.paths import user_data_dir
from jarvis.memory.frontmatter import parse_frontmatter, write_frontmatter
from jarvis.memory.workspace import person_slug
@@ -60,7 +62,12 @@ from .schema import normalize_relationship
# A pragmatic, dependency-free e-mail check (cloud-first base install stays light —
# no `email-validator`/`libphonenumber`). Good enough to reject obvious garbage
# before it lands in a file; the UI is the authority for what the user wants.
-_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+#
+# Same language as ``^[^@\s]+@[^@\s]+\.[^@\s]+$`` (a dot somewhere inside the
+# domain, neither first nor last), written so the domain has exactly one way
+# to split at its first inner dot: the ambiguous split was quadratic on long
+# dotted input (CodeQL py/polynomial-redos), and vCard files are untrusted.
+_EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s][^@\s.]*\.[^@\s]+$")
_NON_DIGIT_RE = re.compile(r"\D")
#: The only address sub-keys we persist (anything else is dropped).
@@ -87,9 +94,7 @@ def _validate_birthday(raw: str | None) -> str | None:
try:
return date.fromisoformat(s).isoformat()
except ValueError as exc:
- raise ValueError(
- f"Invalid birthday {raw!r} — expected ISO format YYYY-MM-DD."
- ) from exc
+ raise ValueError(f"Invalid birthday {raw!r} — expected ISO format YYYY-MM-DD.") from exc
def _clean_str_list(values: list[str] | None) -> list[str]:
@@ -272,7 +277,18 @@ class ContactStore:
# Paths / IO
# ------------------------------------------------------------------
def _path(self, slug: str) -> Path:
- return self.base_dir / f"{slug}.md"
+ """The contact file for *slug*, contained in ``base_dir``.
+
+ The slug arrives from HTTP routes, so a value such as ``../x`` or a
+ drive-relative ``C:x`` must never address a file outside the contacts
+ folder. Raises :class:`UnsafePathError` (a ``ValueError``) for those.
+ """
+ if not slug or any(sep in slug for sep in ("/", "\\", ":", "\x00")):
+ raise UnsafePathError(f"not a contact slug: {slug!r}")
+ path = contained_path(self.base_dir, f"{slug}.md")
+ if path.parent != contained_path(self.base_dir, "."):
+ raise UnsafePathError(f"not a contact slug: {slug!r}")
+ return path
def _iter_paths(self) -> list[Path]:
if not self.base_dir.exists():
@@ -318,7 +334,10 @@ class ContactStore:
return contacts
def get(self, slug: str) -> Contact | None:
- path = self._path(slug)
+ try:
+ path = self._path(slug)
+ except UnsafePathError: # an escaping slug is no stored contact: None = not found
+ return None
if not path.exists():
return None
return Contact.load(path)
@@ -513,14 +532,15 @@ class ContactStore:
# ------------------------------------------------------------------
def delete(self, slug: str) -> bool:
existing = self.get(slug)
- path = self._path(slug)
+ try:
+ path = self._path(slug)
+ except UnsafePathError: # an escaping slug is no stored contact: nothing to delete
+ return False
try:
path.unlink()
except FileNotFoundError:
return False
- notify_contact_changed(
- "deleted", slug, existing.name if existing is not None else slug
- )
+ notify_contact_changed("deleted", slug, existing.name if existing is not None else slug)
return True
def render_for_prompt(self, *, max_chars: int = 800) -> str:
diff --git a/jarvis/contacts/vcard.py b/jarvis/contacts/vcard.py
index 8de68eedd4..2e9834e6a4 100644
--- a/jarvis/contacts/vcard.py
+++ b/jarvis/contacts/vcard.py
@@ -318,5 +318,8 @@ def import_records(store: ContactStore, records: list[dict[str, Any]]) -> dict[s
skipped += 1
if len(errors) < _MAX_ERRORS_REPORTED:
errors.append(f"{name}: {exc}")
- log.warning("vcard import: skipped %r: %s", name, exc)
+ # The contact name and the store's reason (which may quote an email
+ # or phone number) go back to the caller in ``errors`` only; the
+ # app log gets no personal data.
+ log.warning("vcard import: skipped a record (%s)", type(exc).__name__)
return {"created": created, "updated": updated, "skipped": skipped, "errors": errors}
diff --git a/jarvis/core/admin_password.py b/jarvis/core/admin_password.py
new file mode 100644
index 0000000000..9ff3b61f25
--- /dev/null
+++ b/jarvis/core/admin_password.py
@@ -0,0 +1,140 @@
+"""Admin password hashing and verification for ``security.admin_password_hash``.
+
+The admin password gates sensitive UI actions (built-in skill edits, self-mod
+backup restore). It is stored as a salted scrypt digest -- a memory-hard KDF
+from the standard library, so no extra dependency and identical behaviour on
+every OS.
+
+Stored format (one string, ``$``-separated)::
+
+ scrypt$<n>$<r>$<p>$<salt_hex>$<digest_hex>
+
+Create one with::
+
+ python -m jarvis.core.admin_password
+
+A bare 64-character SHA-256 hex digest (the pre-2026-09 format) is still
+accepted so an existing config keeps working, but it is deprecated: it has no
+salt and no work factor, so a leaked config makes the password cheap to
+brute-force. Re-hash with the command above.
+"""
+
+from __future__ import annotations
+
+import getpass
+import hashlib
+import hmac
+import logging
+import re
+import secrets
+import sys
+
+log = logging.getLogger(__name__)
+
+SCHEME = "scrypt"
+# Interactive-login strength (~16 MiB, well under OpenSSL's default maxmem).
+_N = 2**14
+_R = 8
+_P = 1
+_SALT_BYTES = 16
+_DKLEN = 32
+# Upper bounds applied to a stored hash so a hand-edited config cannot make a
+# single check allocate gigabytes.
+_MAX_N = 2**20
+_MAX_R = 32
+_MAX_P = 16
+
+_LEGACY_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
+
+
+def _scrypt(password: str, salt: bytes, n: int, r: int, p: int, dklen: int) -> bytes:
+ # maxmem must cover 128 * n * r (plus slack); the bounds above cap it.
+ return hashlib.scrypt(
+ password.encode("utf-8"),
+ salt=salt,
+ n=n,
+ r=r,
+ p=p,
+ dklen=dklen,
+ maxmem=256 * n * r + 1024 * 1024,
+ )
+
+
+def hash_admin_password(password: str) -> str:
+ """Return the storable scrypt hash string for *password*."""
+ if not password:
+ raise ValueError("admin password must not be empty")
+ salt = secrets.token_bytes(_SALT_BYTES)
+ digest = _scrypt(password, salt, _N, _R, _P, _DKLEN)
+ return f"{SCHEME}${_N}${_R}${_P}${salt.hex()}${digest.hex()}"
+
+
+def is_legacy_hash(stored: str) -> bool:
+ """True when *stored* is the deprecated unsalted SHA-256 hex format."""
+ return bool(_LEGACY_SHA256_RE.match(stored or ""))
+
+
+def _verify_legacy_sha256(provided: str, stored: str) -> bool:
+ # Deprecated format, kept only so existing configs do not lock their
+ # owner out. New hashes are always scrypt (see hash_admin_password).
+ log.warning(
+ "security.admin_password_hash uses the deprecated unsalted SHA-256 "
+ "format; re-hash it with `python -m jarvis.core.admin_password`."
+ )
+ computed = hashlib.sha256(provided.encode("utf-8")).hexdigest()
+ return hmac.compare_digest(computed, stored.lower())
+
+
+def verify_admin_password(provided: str | None, stored: str | None) -> bool:
+ """Constant-time check of *provided* against the stored hash string.
+
+ Empty stored hash or empty password -> False (admin mode locked). A
+ malformed stored hash also returns False and logs why, never raises.
+ """
+ if not stored or not provided:
+ return False
+ if is_legacy_hash(stored):
+ return _verify_legacy_sha256(provided, stored)
+ parts = stored.split("$")
+ if len(parts) != 6 or parts[0] != SCHEME:
+ log.warning("security.admin_password_hash has an unrecognised format; admin mode locked.")
+ return False
+ try:
+ n, r, p = int(parts[1]), int(parts[2]), int(parts[3])
+ salt = bytes.fromhex(parts[4])
+ expected = bytes.fromhex(parts[5])
+ except ValueError:
+ log.warning("security.admin_password_hash is malformed; admin mode locked.")
+ return False
+ if not (1 < n <= _MAX_N and n & (n - 1) == 0 and 0 < r <= _MAX_R and 0 < p <= _MAX_P):
+ log.warning(
+ "security.admin_password_hash has out-of-range scrypt parameters; admin mode locked."
+ )
+ return False
+ if not salt or not expected:
+ log.warning("security.admin_password_hash has an empty salt or digest; admin mode locked.")
+ return False
+ computed = _scrypt(provided, salt, n, r, p, len(expected))
+ return hmac.compare_digest(computed, expected)
+
+
+def check_admin_pass(provided: str | None, security_cfg: object) -> bool:
+ """Check *provided* against ``security_cfg.admin_password_hash``."""
+ if security_cfg is None:
+ return False
+ return verify_admin_password(provided, getattr(security_cfg, "admin_password_hash", ""))
+
+
+def main() -> int:
+ """Prompt for a password and print the value for ``admin_password_hash``."""
+ first = getpass.getpass("New admin password: ")
+ second = getpass.getpass("Repeat: ")
+ if not first or first != second:
+ print("Passwords are empty or do not match.", file=sys.stderr)
+ return 1
+ print(hash_admin_password(first))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index b3bc4822fb..d3bb8fbed2 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -2314,8 +2314,9 @@ class SecurityConfig(BaseModel):
"""Gate for sensitive UI actions (e.g. built-in skill editing).
Empty hash = no admin mode set — built-in edits are locked.
- To set: write the SHA-256 hex of the password into ``admin_password_hash``,
- e.g. via ``python -c "import hashlib; print(hashlib.sha256(b'<pass>').hexdigest())"``.
+ To set: run ``python -m jarvis.core.admin_password`` and paste the printed
+ salted scrypt hash into ``admin_password_hash``. A bare SHA-256 hex digest
+ (the old format) is still accepted but deprecated.
"""
admin_password_hash: str = ""
diff --git a/jarvis/core/http_guard.py b/jarvis/core/http_guard.py
index bb49250004..70d1c758bc 100644
--- a/jarvis/core/http_guard.py
+++ b/jarvis/core/http_guard.py
@@ -27,11 +27,20 @@ handles as "the download failed".
from __future__ import annotations
+import asyncio
+import ipaddress
+import socket
from typing import Any
import httpx
-__all__ = ["InsecureRedirect", "https_only", "https_only_async"]
+__all__ = [
+ "BlockedDestination",
+ "InsecureRedirect",
+ "https_only",
+ "https_only_async",
+ "public_only_async",
+]
class InsecureRedirect(httpx.HTTPError):
@@ -68,3 +77,70 @@ def https_only() -> dict[str, Any]:
def https_only_async() -> dict[str, Any]:
"""The same, for ``httpx.AsyncClient`` — its hooks must be awaitable."""
return {"event_hooks": {"response": [_check_async]}}
+
+
+# ---------------------------------------------------------------------------
+# Public-destination guard: for a URL the USER pasted (not a registry entry),
+# plain http is fine, but the fetch runs server-side, so it must never reach
+# the loopback API, the LAN, or a cloud metadata endpoint. It runs as a
+# REQUEST hook, so every redirect hop is checked before it is sent.
+# ---------------------------------------------------------------------------
+
+
+class BlockedDestination(httpx.HTTPError):
+ """The request targeted a non-public address or a disallowed scheme.
+
+ An ``httpx.HTTPError`` for the same reason as :class:`InsecureRedirect`:
+ call sites already report that as "the download failed".
+ """
+
+
+def _is_public_ip(value: str) -> bool:
+ ip = ipaddress.ip_address(value.split("%", 1)[0]) # drop an IPv6 zone id
+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:
+ ip = ip.ipv4_mapped
+ return ip.is_global and not ip.is_multicast
+
+
+async def _check_public_request(request: httpx.Request, schemes: frozenset[str]) -> None:
+ url = request.url
+ if url.scheme not in schemes:
+ raise BlockedDestination(f"refusing a {url.scheme!r} URL")
+ host = url.host
+ if not host:
+ raise BlockedDestination("refusing a URL without a host")
+ try:
+ # A literal address needs no lookup.
+ literal_ok = _is_public_ip(host)
+ except ValueError: # not an IP literal, so it is a hostname and DNS resolution below decides
+ literal_ok = None
+ if literal_ok is not None:
+ if not literal_ok:
+ raise BlockedDestination(f"refusing non-public address {host}")
+ return
+ port = url.port or (443 if url.scheme == "https" else 80)
+ try:
+ infos = await asyncio.get_running_loop().getaddrinfo(host, port, type=socket.SOCK_STREAM)
+ except OSError as exc:
+ raise BlockedDestination(f"cannot resolve {host}") from exc
+ addresses = {info[4][0] for info in infos}
+ # Every address must be public: a name that resolves to both a public and a
+ # private address could otherwise be connected to on the private one.
+ if not addresses or not all(_is_public_ip(str(a)) for a in addresses):
+ raise BlockedDestination(f"refusing {host}: it resolves to a non-public address")
+
+
+def public_only_async(*, schemes: tuple[str, ...] = ("https",)) -> dict[str, Any]:
+ """``httpx.AsyncClient`` kwargs that refuse non-public destinations.
+
+ Every request — the first and each redirect hop — must use one of
+ ``schemes`` and resolve only to globally routable addresses. The lookup
+ happens just before httpx connects; this narrows but does not fully close a
+ DNS-rebinding window, which is acceptable for a user-initiated download.
+ """
+ allowed = frozenset(s.lower() for s in schemes)
+
+ async def _hook(request: httpx.Request) -> None:
+ await _check_public_request(request, allowed)
+
+ return {"event_hooks": {"request": [_hook]}}
diff --git a/jarvis/core/path_safety.py b/jarvis/core/path_safety.py
new file mode 100644
index 0000000000..e891f84885
--- /dev/null
+++ b/jarvis/core/path_safety.py
@@ -0,0 +1,62 @@
+"""Containment helpers for paths built from caller-supplied names.
+
+Routes and stores often join a name that came from a request (an id, a slug,
+a file name) onto a directory they own. A name like ``..``, ``..\\x``, an
+absolute path or a Windows drive-relative name (``C:x``) would otherwise make
+that join land outside the directory. These helpers resolve the joined path
+and refuse it unless it stays inside the root.
+
+The check is written as ``os.path.realpath`` followed by a ``startswith`` on
+the resolved root so static analysers recognise it as a path sanitiser.
+Stdlib only; identical behaviour on Windows, macOS and Linux.
+"""
+
+from __future__ import annotations
+
+import os
+import re
+from pathlib import Path
+
+__all__ = ["UnsafePathError", "contained_path", "is_safe_name", "safe_child"]
+
+#: One path component: letters, digits, dot, dash, underscore, space. It must
+#: start with a letter or digit, so ``.``, ``..`` and hidden names never pass.
+_SAFE_NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9._\- ]{0,254}")
+
+
+class UnsafePathError(ValueError):
+ """A caller-supplied path would leave the directory it must stay in."""
+
+
+def is_safe_name(name: str) -> bool:
+ """True when *name* is a single, plain path component."""
+ return isinstance(name, str) and _SAFE_NAME.fullmatch(name) is not None
+
+
+def contained_path(root: str | os.PathLike[str], candidate: str | os.PathLike[str]) -> Path:
+ """Resolve *candidate* (relative to *root* unless absolute) inside *root*.
+
+ Returns the fully resolved path. Raises :class:`UnsafePathError` when the
+ result is not *root* itself or a descendant of it, symlinks included.
+ """
+ real_root = os.path.realpath(os.fspath(root))
+ real_target = os.path.realpath(os.path.join(real_root, os.fspath(candidate)))
+ prefix = real_root if real_root.endswith(os.sep) else real_root + os.sep
+ if real_target != real_root and not real_target.startswith(prefix):
+ raise UnsafePathError(f"path escapes its directory: {os.fspath(candidate)!r}")
+ return Path(real_target)
+
+
+def safe_child(root: str | os.PathLike[str], name: str) -> Path:
+ """``root / name`` for a single plain component *name*, contained in *root*.
+
+ Raises :class:`UnsafePathError` when *name* is not a plain component
+ (separators, ``..``, drive letters, leading dot) or resolves outside
+ *root* (for instance through a symlink).
+ """
+ if not is_safe_name(name):
+ raise UnsafePathError(f"not a plain file name: {name!r}")
+ target = contained_path(root, name)
+ if target == Path(os.path.realpath(os.fspath(root))):
+ raise UnsafePathError(f"not a plain file name: {name!r}")
+ return target
diff --git a/jarvis/dictation/stats.py b/jarvis/dictation/stats.py
index 46e44d13ef..d8bec25430 100644
--- a/jarvis/dictation/stats.py
+++ b/jarvis/dictation/stats.py
@@ -39,6 +39,7 @@ import json
import logging
import os
import tempfile
+import time
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from datetime import date as _date
@@ -48,6 +49,25 @@ from typing import Any
from jarvis.dictation._locks import store_lock
+# Windows antivirus and indexers briefly hold a freshly written file open, so
+# os.replace onto it can fail with WinError 5/32 even under our own lock. A
+# short bounded retry rides that out; any other error still fails at once.
+_REPLACE_RETRY_DELAYS_S: tuple[float, ...] = (0.0, 0.02, 0.05, 0.1, 0.2, 0.4)
+
+
+def _replace_with_retry(src: str, dst: Path) -> None:
+ last_error: PermissionError | None = None
+ for delay_s in _REPLACE_RETRY_DELAYS_S:
+ if delay_s:
+ time.sleep(delay_s)
+ try:
+ os.replace(src, dst)
+ return
+ except PermissionError as exc: # transient share lock: retried, re-raised at the end
+ last_error = exc
+ if last_error is not None:
+ raise last_error
+
log = logging.getLogger(__name__)
#: How many days the API hands to the UI. Enough for a year-ish of sparkline
@@ -349,7 +369,7 @@ class DictationStats:
try:
with os.fdopen(fd, "w", encoding="utf-8") as fh:
json.dump(payload, fh, ensure_ascii=False, indent=2)
- os.replace(tmp_name, self._path)
+ _replace_with_retry(tmp_name, self._path)
except Exception:
try:
os.unlink(tmp_name)
diff --git a/jarvis/mcp/agents/export.py b/jarvis/mcp/agents/export.py
index cc42a9a67f..6000ea2734 100644
--- a/jarvis/mcp/agents/export.py
+++ b/jarvis/mcp/agents/export.py
@@ -241,8 +241,19 @@ def install(
if path.exists():
try:
existing = json.loads(path.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, OSError) as exc:
- return {"ok": False, "error": f"{path} is not readable JSON: {exc}"}
+ except json.JSONDecodeError as exc:
+ # Line and column let the user repair their own file; the parser's
+ # message itself is not echoed.
+ return {
+ "ok": False,
+ "error": (f"{path} is not readable JSON (line {exc.lineno}, column {exc.colno})."),
+ }
+ except OSError:
+ log.warning("MCP client config %s could not be read", path, exc_info=True)
+ return {
+ "ok": False,
+ "error": f"{path} is not readable JSON: the file could not be opened.",
+ }
if not isinstance(existing, dict):
return {"ok": False, "error": f"{path} does not hold a JSON object."}
servers = existing.setdefault("mcpServers", {})
diff --git a/jarvis/mcp/state.py b/jarvis/mcp/state.py
index f9bd6ad470..4ac0f7ee87 100644
--- a/jarvis/mcp/state.py
+++ b/jarvis/mcp/state.py
@@ -271,8 +271,12 @@ def import_claude_desktop() -> tuple[int, list[str], str]:
try:
raw = json.loads(src.read_text(encoding="utf-8"))
- except (json.JSONDecodeError, OSError) as exc:
- return (0, [], f"Config not readable: {exc}")
+ except json.JSONDecodeError as exc:
+ # Line and column let the user fix their own file.
+ return (0, [], f"Config is not valid JSON (line {exc.lineno}, column {exc.colno}).")
+ except OSError:
+ log.warning("Claude Desktop config not readable: %s", src, exc_info=True)
+ return (0, [], "Config not readable. Details are in the Jarvis log.")
claude_servers = raw.get("mcpServers", {})
if not isinstance(claude_servers, dict) or not claude_servers:
diff --git a/jarvis/missions/stream_evidence.py b/jarvis/missions/stream_evidence.py
index e9516af519..3e1815560e 100644
--- a/jarvis/missions/stream_evidence.py
+++ b/jarvis/missions/stream_evidence.py
@@ -597,9 +597,18 @@ def _command_from_tool_input(tool_name: str, tool_input: dict) -> str:
# NON-option word, so ``git log --grep=push`` does NOT match (``log`` is not a
# mutating subcommand and the ``push`` inside the flag value is never in
# subcommand position).
+# Every option token has exactly ONE parse (CodeQL py/redos): a value that is
+# itself a dash-word (``-c -x``) or an ``--git-dir=…`` form is read only by the
+# plain-flag arm ``-\S+`` (which also covers ``--x``); two readings per token
+# made a failing match exponential in the number of options. A value therefore
+# starts with a non-dash, or is a lone "-" (which no flag can be) — spelled as
+# character classes, not a lookahead, so the static analysis sees the one
+# parse too. The set of matched commands is unchanged.
+_GIT_OPTION_VALUE = r"(?:[^\s-]\S*|-)"
_MUTATING_CMD_RE = re.compile(
- r"\bgit\b(?:\s+(?:-[cC]\s+\S+|--(?:git-dir|work-tree|namespace)(?:=|\s+)\S+"
- r"|--?\S+))*\s+(?:push|commit|merge|tag|cherry-pick|revert|am)\b"
+ rf"\bgit\b(?:\s+(?:-[cC]\s+{_GIT_OPTION_VALUE}"
+ rf"|--(?:git-dir|work-tree|namespace)\s+{_GIT_OPTION_VALUE}"
+ r"|-\S+))*\s+(?:push|commit|merge|tag|cherry-pick|revert|am)\b"
r"|\bgh\s+(?:pr|issue|release|repo|gist)\s+"
r"(?:create|merge|close|edit|comment|review|delete|reopen)\b",
re.IGNORECASE,
diff --git a/jarvis/platform/open_path.py b/jarvis/platform/open_path.py
index 934a5f52f7..7b17062087 100644
--- a/jarvis/platform/open_path.py
+++ b/jarvis/platform/open_path.py
@@ -131,8 +131,17 @@ def open_file_with(file: Path, launch_kind: str, launch_value: str) -> bool:
return True
if launch_kind == "startfile":
# Windows .lnk/app launched with the file as an argument via `start`.
+ # cmd.exe re-parses its own command line, and list2cmdline only
+ # quotes arguments that contain spaces, so a file named
+ # "a&calc.md" would have run a second command. Both paths are
+ # double-quoted by hand (a Windows path cannot contain '"'; one
+ # that does is refused) and the string reaches CreateProcess as is.
+ file_str = str(file)
+ if '"' in launch_value or '"' in file_str:
+ log.warning("open_file_with: refusing a path containing a quote: %r", file_str)
+ return False
subprocess.Popen( # noqa: S603
- ["cmd", "/c", "start", "", launch_value, str(file)],
+ f'cmd /c start "" "{launch_value}" "{file_str}"',
creationflags=NO_WINDOW_CREATIONFLAGS,
close_fds=True,
)
diff --git a/jarvis/plugins/tool/youtube_music_rest.py b/jarvis/plugins/tool/youtube_music_rest.py
index 575f42692d..2b65fa719b 100644
--- a/jarvis/plugins/tool/youtube_music_rest.py
+++ b/jarvis/plugins/tool/youtube_music_rest.py
@@ -40,11 +40,32 @@ import logging
import time
from collections.abc import Awaitable, Callable
from typing import Any
+from urllib.parse import urlsplit
from jarvis.core.protocols import ExecutionContext, ToolResult
from ._playlist_match import is_liked_name, match_playlist
+
+def _is_google_console_url(url: str) -> bool:
+ """True for an https link on a ``console.*.google.com`` host.
+
+ Parsed, not substring-matched: ``https://console.evil.example/google.com/``
+ or ``https://console.google.com.evil.example/`` must not pass as Google's
+ API-activation page, since the link is shown to the user to click.
+ """
+ try:
+ parts = urlsplit(url)
+ except ValueError: # an unparsable URL is by definition not the trusted Google console link
+ return False
+ host = (parts.hostname or "").lower()
+ return (
+ parts.scheme == "https"
+ and parts.username is None
+ and host.startswith("console.")
+ and host.endswith(".google.com")
+ )
+
log = logging.getLogger(__name__)
_API = "https://www.googleapis.com/youtube/v3"
@@ -709,7 +730,7 @@ class YouTubeMusicRestTool:
if isinstance(link, dict):
candidates.append(str(link.get("url") or ""))
for url in candidates:
- if url.startswith("https://console.") and "google.com/" in url:
+ if _is_google_console_url(url):
return url
return ""
diff --git a/jarvis/screen_context/redaction.py b/jarvis/screen_context/redaction.py
index edcd564a06..ceb0026632 100644
--- a/jarvis/screen_context/redaction.py
+++ b/jarvis/screen_context/redaction.py
@@ -44,11 +44,24 @@ from jarvis.screen_context.ports import Rect
log = logging.getLogger(__name__)
+# Detector for custom patterns that could backtrack catastrophically: a
+# backreference, a quantified group that already holds a quantifier, or a
+# quantified alternation. It must not be catastrophic itself (CodeQL py/redos):
+# a group body reads a backslash ONLY as the start of an escape pair, so every
+# body has exactly one parse, the scan up to the first inner quantifier (or
+# "|") excludes that token, and every run is possessive. An escaped paren is
+# therefore always group content — the old form could also read "\)" as a
+# backslash followed by the group's end and flag safe patterns such as
+# ``(x+\)+y)``; otherwise the verdicts are unchanged.
+_RX_ESCAPE = r"\\[\s\S]"
+_RX_QUANT = r"(?:[+*]|\{\d*+,?+\d*+\})"
+_RX_BODY = rf"(?:{_RX_ESCAPE}|[^()\\])"
+_RX_BODY_BEFORE_QUANT = rf"(?:{_RX_ESCAPE}|[^()\\+*{{]|\{{(?!\d*+,?+\d*+\}}))"
+_RX_BODY_BEFORE_BAR = rf"(?:{_RX_ESCAPE}|[^()\\|])"
_UNSAFE_CUSTOM_REGEX_RE = re.compile(
r"\\[1-9]|\(\?P=|"
- r"\((?:\\.|[^()])*(?:[+*]|\{\d*,?\d*\})(?:\\.|[^()])*\)"
- r"(?:[+*]|\{\d*,?\d*\})|"
- r"\((?:\\.|[^()])*\|(?:\\.|[^()])*\)(?:[+*]|\{\d*,?\d*\})"
+ rf"\({_RX_BODY_BEFORE_QUANT}*+{_RX_QUANT}{_RX_BODY}*+\){_RX_QUANT}|"
+ rf"\({_RX_BODY_BEFORE_BAR}*+\|{_RX_BODY}*+\){_RX_QUANT}"
)
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 8fca8f90d3..1287b32c90 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -86,6 +86,7 @@ from jarvis.core.events import (
WakeWordDetected,
)
from jarvis.core.protocols import AudioChunk, Transcript
+from jarvis.core.redact import safe_preview
from jarvis.core.turn_language import (
DEFAULT_LOCALE,
normalize_language_tag,
@@ -9575,12 +9576,15 @@ class SpeechPipeline:
# Filler-only surface text. The residue guard turned it
# into the generic error phrase; re-rendering that would
# announce a failure the user does not have.
+ # Only the scrub actions and the length: the filler text
+ # itself stems from the provider message and carries no
+ # diagnostic value worth logging.
log.info(
"Realtime surface fallback carried no substance (%s) "
- "— dropping it instead of speaking the error phrase: "
- "%r",
+ "— dropping it instead of speaking the error phrase "
+ "(%d chars)",
scrubbed.actions,
- text[:80],
+ len(text),
)
return
cleaned = scrubbed.cleaned.strip()
@@ -9763,7 +9767,13 @@ class SpeechPipeline:
else TurnTakingState.LISTENING
)
elif kind == "provider_error":
- log.warning("Realtime desktop status: %s", message)
+ # Only the redacted, capped error text -- never the raw
+ # message dict, whose provider detail may echo a credential
+ # or a provider error body (AP-34).
+ log.warning(
+ "Realtime desktop status: provider_error: %s",
+ safe_preview(message.get("error"), max_chars=300),
+ )
elif kind == "provider_fallback":
# The call is crossing to a DIFFERENT provider family, which can
# mean a different billing path (AP-22). The user-facing notice
diff --git a/jarvis/telephony/outbound.py b/jarvis/telephony/outbound.py
index ee075bb936..808dff826c 100644
--- a/jarvis/telephony/outbound.py
+++ b/jarvis/telephony/outbound.py
@@ -31,7 +31,7 @@ from __future__ import annotations
import re
from urllib.parse import urlencode
-from .provisioning import TelephonyProvisionError
+from .provisioning import TelephonyProvisionError, sdk_failure
from .security import public_url_for
# Raw E.164: a leading '+' then 7..15 digits (first digit non-zero).
@@ -124,7 +124,7 @@ def place_call(
except TelephonyProvisionError:
raise
except Exception as exc: # noqa: BLE001 - twilio raises a wide error tree
- raise TelephonyProvisionError(f"Outbound call failed: {exc}") from exc
+ raise sdk_failure("Outbound call failed", exc) from exc
return getattr(call, "sid", "") or ""
diff --git a/jarvis/telephony/provisioning.py b/jarvis/telephony/provisioning.py
index a3bb1d3082..76d586edbb 100644
--- a/jarvis/telephony/provisioning.py
+++ b/jarvis/telephony/provisioning.py
@@ -17,11 +17,48 @@ with a clean English message on failure; the caller turns that into JSON.
from __future__ import annotations
+import logging
from dataclasses import dataclass
+_log = logging.getLogger(__name__)
+
+# Client-facing wording per provider-test status. The Twilio SDK's own message
+# can carry the raw REST response body, so it is classified, never surfaced.
+_STATUS_HINTS: dict[str, str] = {
+ "bad_key": "Twilio rejected the account SID or auth token",
+ "no_credits": "the Twilio account is out of funds or suspended",
+ "rate_limited": "Twilio is rate-limiting requests, try again shortly",
+ "model_unavailable": "Twilio could not find or allow the requested resource",
+ "unreachable": "Twilio could not be reached",
+}
+
class TelephonyProvisionError(RuntimeError):
- """Raised when a Twilio REST operation cannot complete."""
+ """Raised when a Twilio REST operation cannot complete.
+
+ ``str(exc)`` is always a clean English sentence safe to show in the UI;
+ ``status`` is a ``PROVIDER_TEST_STATUSES`` value (``"error"`` when the
+ failure was not a classified Twilio REST error).
+ """
+
+ def __init__(self, message: str, *, status: str = "error") -> None:
+ super().__init__(message)
+ self.status = status
+
+
+def sdk_failure(action: str, exc: BaseException) -> TelephonyProvisionError:
+ """Turn a Twilio SDK exception into a client-safe ``TelephonyProvisionError``.
+
+ Only the exception type and the classified status are logged: the SDK
+ message embeds Twilio's response body, which never reaches logs or the UI
+ (AP-34).
+ """
+ from jarvis.brain.provider_test import classify_provider_error
+
+ status = classify_provider_error(str(exc))
+ _log.warning("%s: Twilio SDK error %s (%s)", action, type(exc).__name__, status)
+ hint = _STATUS_HINTS.get(status, "see the Jarvis log for details")
+ return TelephonyProvisionError(f"{action}: {hint}.", status=status)
@dataclass(frozen=True, slots=True)
@@ -64,7 +101,7 @@ def verify_credentials(account_sid: str, auth_token: str) -> dict[str, str]:
try:
account = client.api.accounts(account_sid).fetch()
except Exception as exc: # noqa: BLE001 - twilio raises a wide tree
- raise TelephonyProvisionError(f"Twilio credential check failed: {exc}") from exc
+ raise sdk_failure("Twilio credential check failed", exc) from exc
return {
"account_status": getattr(account, "status", "") or "",
"friendly_name": getattr(account, "friendly_name", "") or "",
@@ -87,7 +124,7 @@ def list_available_numbers(
kwargs["area_code"] = area_code
results = client.available_phone_numbers(country).local.list(**kwargs)
except Exception as exc: # noqa: BLE001
- raise TelephonyProvisionError(f"Number search failed: {exc}") from exc
+ raise sdk_failure("Number search failed", exc) from exc
return [
AvailableNumber(
phone_number=getattr(n, "phone_number", "") or "",
@@ -116,7 +153,7 @@ def buy_number(
voice_method="POST",
)
except Exception as exc: # noqa: BLE001
- raise TelephonyProvisionError(f"Number purchase failed: {exc}") from exc
+ raise sdk_failure("Number purchase failed", exc) from exc
return OwnedNumber(
sid=getattr(bought, "sid", "") or "",
phone_number=getattr(bought, "phone_number", "") or phone_number,
@@ -142,7 +179,7 @@ def set_voice_webhook(
except TelephonyProvisionError:
raise
except Exception as exc: # noqa: BLE001
- raise TelephonyProvisionError(f"Webhook update failed: {exc}") from exc
+ raise sdk_failure("Webhook update failed", exc) from exc
return OwnedNumber(
sid=getattr(updated, "sid", "") or "",
phone_number=getattr(updated, "phone_number", "") or phone_number,
@@ -157,7 +194,7 @@ def inspect_number(account_sid: str, auth_token: str, *, phone_number: str) -> O
try:
owned = client.incoming_phone_numbers.list(phone_number=phone_number, limit=1)
except Exception as exc: # noqa: BLE001
- raise TelephonyProvisionError(f"Number inspect failed: {exc}") from exc
+ raise sdk_failure("Number inspect failed", exc) from exc
if not owned:
return None
n = owned[0]
@@ -173,6 +210,7 @@ __all__ = [
"AvailableNumber",
"OwnedNumber",
"TelephonyProvisionError",
+ "sdk_failure",
"buy_number",
"inspect_number",
"list_available_numbers",
diff --git a/jarvis/ui/web/deck_routes.py b/jarvis/ui/web/deck_routes.py
index e31f0ec606..f7299a6c43 100644
--- a/jarvis/ui/web/deck_routes.py
+++ b/jarvis/ui/web/deck_routes.py
@@ -100,7 +100,7 @@ def cu_frame(sha: str) -> Response:
404 covers both "never recorded" and "already pruned by the retention
sweep" — the deck treats them the same (show nothing, keep going).
"""
- if not _SHA256_RE.match(sha):
+ if not _SHA256_RE.fullmatch(sha):
# A hash is the ONLY accepted key. Anything else — a filename, a
# path, a shorter digest — is refused before it touches the filesystem.
raise HTTPException(status_code=400, detail="invalid_hash")
diff --git a/jarvis/ui/web/desktop_routes.py b/jarvis/ui/web/desktop_routes.py
index 45fefa676a..87560855d7 100644
--- a/jarvis/ui/web/desktop_routes.py
+++ b/jarvis/ui/web/desktop_routes.py
@@ -102,12 +102,12 @@ async def window_detach(body: DetachBody, request: Request) -> dict[str, Any]:
try:
return await asyncio.to_thread(fn, body.view)
except Exception as exc: # noqa: BLE001
- # Not swallowed: the reason travels back to the caller, mirroring the
- # /api/window/focus contract.
- log.warning("window detach failed: %s: %s", type(exc).__name__, exc)
+ # Not swallowed: the traceback goes to the log and a machine-readable
+ # reason travels back to the caller (exception text stays server-side).
+ log.warning("window detach failed: %s", exc, exc_info=True)
return {
"ok": False,
- "reason": f"{type(exc).__name__}: {exc}",
+ "reason": "detach_failed",
"fallback_url": _solo_url_path(body.view),
}
@@ -143,8 +143,8 @@ async def window_reattach(body: DetachBody, request: Request) -> dict[str, Any]:
try:
return await asyncio.to_thread(fn, body.view)
except Exception as exc: # noqa: BLE001
- log.warning("window reattach failed: %s: %s", type(exc).__name__, exc)
- return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}
+ log.warning("window reattach failed: %s", exc, exc_info=True)
+ return {"ok": False, "reason": "reattach_failed"}
class FullscreenBody(BaseModel):
@@ -189,8 +189,8 @@ async def window_command(body: WindowCommandBody, request: Request) -> dict[str,
try:
return await asyncio.to_thread(fn, body.action, body.view or None)
except Exception as exc: # noqa: BLE001
- log.warning("window command failed: %s: %s", type(exc).__name__, exc)
- return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}
+ log.warning("window command failed: %s", exc, exc_info=True)
+ return {"ok": False, "reason": "command_failed"}
@router.post("/fullscreen", operation_id="fullscreen")
diff --git a/jarvis/ui/web/diagnostics_routes.py b/jarvis/ui/web/diagnostics_routes.py
index 4d8d1d673d..0f1189f83a 100644
--- a/jarvis/ui/web/diagnostics_routes.py
+++ b/jarvis/ui/web/diagnostics_routes.py
@@ -120,7 +120,8 @@ async def cancel_scopes() -> dict[str, Any]:
try:
from anyio._backends._asyncio import CancelScope # type: ignore[import-not-found]
except Exception as exc: # noqa: BLE001 — anyio absent or reshaped
- return {"error": f"anyio backend CancelScope unavailable: {exc}"}
+ log.opt(exception=exc).warning("anyio backend CancelScope unavailable")
+ return {"error": "anyio backend CancelScope unavailable"}
def _task_brief(task: Any) -> str:
try:
diff --git a/jarvis/ui/web/error_text.py b/jarvis/ui/web/error_text.py
new file mode 100644
index 0000000000..4f1f4af136
--- /dev/null
+++ b/jarvis/ui/web/error_text.py
@@ -0,0 +1,55 @@
+"""Client-safe error text for web routes.
+
+A caught exception's ``str()`` can carry internal paths, library reprs or a
+provider's raw response body. Routes that answer a local UI with an error
+string use :func:`internal_error` instead: the full exception (with its
+traceback) goes to the server log, and the client gets a short, stable
+sentence it can show next to the button that failed.
+
+Messages the UI must act on (a validation error we raise ourselves, a clear
+"package not installed" hint) keep their own text; this helper is for the
+unexpected ``except Exception`` branches.
+"""
+
+from __future__ import annotations
+
+import logging
+
+_log = logging.getLogger(__name__)
+
+LOG_HINT = "Details are in the Jarvis log."
+
+
+def internal_error(
+ action: str,
+ exc: BaseException,
+ *,
+ logger: logging.Logger | None = None,
+) -> str:
+ """Log *exc* with its traceback and return a generic client message.
+
+ ``action`` is a short lowercase phrase ("config write", "memory read") that
+ names what failed; it must not contain exception data.
+ """
+ (logger or _log).warning("%s failed", action, exc_info=(type(exc), exc, exc.__traceback__))
+ return f"{action} failed. {LOG_HINT}"
+
+
+def diagnostic_text(exc: BaseException, *, max_chars: int = 300) -> str:
+ """One-line ``Type: message`` for a failure the user must diagnose themselves.
+
+ For user-configured local processes (an MCP server command, say) the reason
+ is the whole point of the reply. It never includes a traceback: only the
+ first line of the message, credential shapes masked, length capped.
+ """
+ from jarvis.core.redact import redact_secrets
+
+ first_line = (str(exc).strip().splitlines() or [""])[0]
+ text = f"{type(exc).__name__}: {first_line}" if first_line else type(exc).__name__
+ text = redact_secrets(text)
+ if len(text) > max_chars:
+ text = text[:max_chars] + "…"
+ return text
+
+
+__all__ = ["LOG_HINT", "diagnostic_text", "internal_error"]
diff --git a/jarvis/ui/web/frontend/package-lock.json b/jarvis/ui/web/frontend/package-lock.json
index 52257a78e7..fa55380db9 100644
--- a/jarvis/ui/web/frontend/package-lock.json
+++ b/jarvis/ui/web/frontend/package-lock.json
@@ -71,7 +71,7 @@
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.6.2",
"vite": "^6.4.3",
- "vitest": "^3.2.6"
+ "vitest": "^4.1.11"
}
},
"node_modules/@alloc/quick-lru": {
@@ -2879,39 +2879,40 @@
}
},
"node_modules/@vitest/expect": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-3.2.6.tgz",
- "integrity": "sha512-1+7q9BtaKzEmO+fmNT3kYvoNn5Y71XWAx2Q5HRim4tTVRQVRv4uJFAQ5FbK0OPUeNP/WmVCpxYxoJdvuHVjzBQ==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
+ "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
"dev": true,
"license": "MIT",
"dependencies": {
+ "@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
- "@vitest/spy": "3.2.6",
- "@vitest/utils": "3.2.6",
- "chai": "^5.2.0",
- "tinyrainbow": "^2.0.0"
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "chai": "^6.2.2",
+ "tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/mocker": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-3.2.6.tgz",
- "integrity": "sha512-EZOrpDbkKotFAP7wPAQV1UIyoGOk4oX7ynWhBhLB7v+meMHbQhU16oPpIYGTTe4oFlhpryGpgpcZP/sin3hYuw==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
+ "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/spy": "3.2.6",
+ "@vitest/spy": "4.1.11",
"estree-walker": "^3.0.3",
- "magic-string": "^0.30.17"
+ "magic-string": "^0.30.21"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
@@ -2923,42 +2924,42 @@
}
},
"node_modules/@vitest/pretty-format": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-3.2.6.tgz",
- "integrity": "sha512-lb7XXXzmm2h2ASzFnRvQpDo6onT1NmMJA3tkGTWiBFtRJ9lxGY3d3mm/Apt36gej2bkkOVLL/yTOtufDaFa/jA==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
+ "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "tinyrainbow": "^2.0.0"
+ "tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/runner": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-3.2.6.tgz",
- "integrity": "sha512-HYcoSj1w5tcgUnzoF0HcyaAQjpA1gj9ftUJ7iSJSuipc02jW9gKkigwZbjFldAfYHA1fa8UZVRftdMY5msWM9Q==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
+ "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/utils": "3.2.6",
- "pathe": "^2.0.3",
- "strip-literal": "^3.0.0"
+ "@vitest/utils": "4.1.11",
+ "pathe": "^2.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/snapshot": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-3.2.6.tgz",
- "integrity": "sha512-H+ZjNTWGpObenh0YnlBctAPnJSI20P81PL8BPzWpx54YXLLTm8hEsWawtcYLMrwvpK48hGxLLbCS+1KRXhsKhw==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
+ "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "3.2.6",
- "magic-string": "^0.30.17",
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "magic-string": "^0.30.21",
"pathe": "^2.0.3"
},
"funding": {
@@ -2966,28 +2967,25 @@
}
},
"node_modules/@vitest/spy": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-3.2.6.tgz",
- "integrity": "sha512-oq6BbH68WzcWmwtBrU9nqLeaXTR4XwJF7FSLkKEZo4i6eoXcrxjcwSuTvWBIRUTC6VC72nXYunzqgZA+IKdtxg==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
+ "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "tinyspy": "^4.0.3"
- },
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-3.2.6.tgz",
- "integrity": "sha512-lI23nIs4bnT3T8NIoh+vFaz5s2/DdP0Jgt2jxwgWljvwn82cLJtyi/If+fjFyoLMGIOz0U/fKvWE0d4jsNQEfg==",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
+ "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
- "@vitest/pretty-format": "3.2.6",
- "loupe": "^3.1.4",
- "tinyrainbow": "^2.0.0"
+ "@vitest/pretty-format": "4.1.11",
+ "convert-source-map": "^2.0.0",
+ "tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
@@ -3292,9 +3290,9 @@
"license": "MIT"
},
"node_modules/baseline-browser-mapping": {
- "version": "2.10.20",
- "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.20.tgz",
- "integrity": "sha512-1AaXxEPfXT+GvTBJFuy4yXVHWJBXa4OdbIebGN/wX5DlsIkU0+wzGnd2lOzokSk51d5LUmqjgBLRLlypLUqInQ==",
+ "version": "2.11.26",
+ "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.26.tgz",
+ "integrity": "sha512-GLQdD3y6UF8iVuMJl5fHgE4jdn/ua7n+toKfLgNlg3BqQtOZjpy68T8Tup8/wGWZCDlm7KMg7tPb4MPn7oN0TQ==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -3350,9 +3348,9 @@
}
},
"node_modules/browserslist": {
- "version": "4.28.2",
- "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz",
- "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==",
+ "version": "4.29.2",
+ "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.2.tgz",
+ "integrity": "sha512-/u9r8k8ue4ZhHCw9ovDtltpWdXeXzjhdxCGj6vm1RGLPXb8lu33EMdoCHF5Sx8oYBS+Q/FYYNmAqlHncxR3RmA==",
"dev": true,
"funding": [
{
@@ -3371,11 +3369,11 @@
"license": "MIT",
"peer": true,
"dependencies": {
- "baseline-browser-mapping": "^2.10.12",
- "caniuse-lite": "^1.0.30001782",
- "electron-to-chromium": "^1.5.328",
- "node-releases": "^2.0.36",
- "update-browserslist-db": "^1.2.3"
+ "baseline-browser-mapping": "^2.11.26",
+ "caniuse-lite": "^1.0.30001812",
+ "electron-to-chromium": "^1.5.439",
+ "node-releases": "^2.0.57",
+ "update-browserslist-db": "^1.3.3"
},
"bin": {
"browserslist": "cli.js"
@@ -3408,16 +3406,6 @@
"ieee754": "^1.2.1"
}
},
- "node_modules/cac": {
- "version": "6.7.14",
- "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
- "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=8"
- }
- },
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
@@ -3452,9 +3440,9 @@
}
},
"node_modules/caniuse-lite": {
- "version": "1.0.30001788",
- "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001788.tgz",
- "integrity": "sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==",
+ "version": "1.0.30001813",
+ "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001813.tgz",
+ "integrity": "sha512-zfjJo4rM0+fUomGDBW/xcDjhIwz/210DGvip2MAMDZ8KHcRPnOHmEgHPZP0UHlZoxr8fYKVJOqcORhYQcG4FKQ==",
"dev": true,
"funding": [
{
@@ -3495,18 +3483,11 @@
}
},
"node_modules/chai": {
- "version": "5.3.3",
- "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
- "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
+ "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
"dev": true,
"license": "MIT",
- "dependencies": {
- "assertion-error": "^2.0.1",
- "check-error": "^2.1.1",
- "deep-eql": "^5.0.1",
- "loupe": "^3.1.0",
- "pathval": "^2.0.0"
- },
"engines": {
"node": ">=18"
}
@@ -3551,16 +3532,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/check-error": {
- "version": "2.1.3",
- "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
- "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 16"
- }
- },
"node_modules/chokidar": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
@@ -4067,16 +4038,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/deep-eql": {
- "version": "5.0.2",
- "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
- "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -4187,9 +4148,9 @@
}
},
"node_modules/electron-to-chromium": {
- "version": "1.5.340",
- "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.340.tgz",
- "integrity": "sha512-908qahOGocRMinT2nM3ajCEM99H4iPdv84eagPP3FfZy/1ZGeOy2CZYzjhms81ckOPCXPlW7LkY4XpxD8r1DrA==",
+ "version": "1.5.439",
+ "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.439.tgz",
+ "integrity": "sha512-qu6QIPXhsb+CRcAiTMNjR4A1y/7tCYKkKjr5CZXRVih6qkDf79peZ2BpEU3qoDBNCRrcy3Mra3X9nG5oruuA7Q==",
"dev": true,
"license": "ISC"
},
@@ -4233,9 +4194,9 @@
}
},
"node_modules/es-module-lexer": {
- "version": "1.7.0",
- "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
- "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
"dev": true,
"license": "MIT"
},
@@ -5316,13 +5277,6 @@
"loose-envify": "cli.js"
}
},
- "node_modules/loupe": {
- "version": "3.2.1",
- "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
- "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -6434,11 +6388,14 @@
"license": "BSD-3-Clause"
},
"node_modules/node-releases": {
- "version": "2.0.37",
- "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.37.tgz",
- "integrity": "sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==",
+ "version": "2.0.57",
+ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.57.tgz",
+ "integrity": "sha512-kQK9LGGFiHtrWiNhZtA7Qbw17AQz+dmsEKODRIVTXA9+e5MS/2gZEBhYJt13GrAz5/IOZKddH/0Z3TP/Zgo+yw==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
},
"node_modules/normalize-path": {
"version": "3.0.0",
@@ -6476,6 +6433,20 @@
"node": ">= 6"
}
},
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
"node_modules/oniguruma-to-es": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-2.3.0.tgz",
@@ -6548,16 +6519,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/pathval": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
- "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">= 14.16"
- }
- },
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -6754,9 +6715,9 @@
}
},
"node_modules/postcss-selector-parser": {
- "version": "6.1.2",
- "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.2.tgz",
- "integrity": "sha512-Q8qQfPiZ+THO/3ZrOrO0cJJKfpYCagtMUkXbnEfmgUjwXg6z/WBeOyS9APBBPCTSiDV+s4SwQGu8yFsiMRIudg==",
+ "version": "6.1.4",
+ "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.4.tgz",
+ "integrity": "sha512-bIoJLOmjCO1S9XdY/DcnR5hJxvrDir1PbGChrzXG3vw0/FOliy/fA3dmdhQ441kah4gKv+TwckGzex6wNS5cnQ==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -7698,9 +7659,9 @@
"license": "MIT"
},
"node_modules/std-env": {
- "version": "3.10.0",
- "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
- "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
+ "integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
"dev": true,
"license": "MIT"
},
@@ -7718,26 +7679,6 @@
"url": "https://github.com/sponsors/wooorm"
}
},
- "node_modules/strip-literal": {
- "version": "3.1.0",
- "resolved": "https://registry.npmjs.org/strip-literal/-/strip-literal-3.1.0.tgz",
- "integrity": "sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "js-tokens": "^9.0.1"
- },
- "funding": {
- "url": "https://github.com/sponsors/antfu"
- }
- },
- "node_modules/strip-literal/node_modules/js-tokens": {
- "version": "9.0.1",
- "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-9.0.1.tgz",
- "integrity": "sha512-mxa9E9ITFOt0ban3j6L5MpjwegGz6lBQmM1IJkWeBZGcMxto50+eWdjC/52xDbS2vy0k7vIMK0Fe2wfL9OQSpQ==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/style-to-js": {
"version": "1.1.21",
"resolved": "https://registry.npmjs.org/style-to-js/-/style-to-js-1.1.21.tgz",
@@ -8005,11 +7946,14 @@
"license": "MIT"
},
"node_modules/tinyexec": {
- "version": "0.3.2",
- "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
- "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
"dev": true,
- "license": "MIT"
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
},
"node_modules/tinyglobby": {
"version": "0.2.16",
@@ -8060,30 +8004,10 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
- "node_modules/tinypool": {
- "version": "1.1.1",
- "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
- "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": "^18.0.0 || >=20.0.0"
- }
- },
"node_modules/tinyrainbow": {
- "version": "2.0.0",
- "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-2.0.0.tgz",
- "integrity": "sha512-op4nsTR47R6p0vMUUoYl/a+ljLFVtlfaXkLQmqfLR1qHma1h/ysYk4hEXZ880bf2CYgTskvTa/e196Vd5dDQXw==",
- "dev": true,
- "license": "MIT",
- "engines": {
- "node": ">=14.0.0"
- }
- },
- "node_modules/tinyspy": {
- "version": "4.0.4",
- "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-4.0.4.tgz",
- "integrity": "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q==",
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
+ "integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -8358,9 +8282,9 @@
}
},
"node_modules/update-browserslist-db": {
- "version": "1.2.3",
- "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
- "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==",
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.3.tgz",
+ "integrity": "sha512-pJ2sYawQS0R/WI928Gj5GlPhTGzbMelq0+4INtSYNDV9ErKJcX6xjGWkoG/VnB3dpUm00zALaqkrUD77pO5TDQ==",
"dev": true,
"funding": [
{
@@ -8582,29 +8506,6 @@
}
}
},
- "node_modules/vite-node": {
- "version": "3.2.4",
- "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-3.2.4.tgz",
- "integrity": "sha512-EbKSKh+bh1E1IFxeO0pg1n4dvoOTt0UDiXMd/qn++r98+jPO1xtJilvXldeuQ8giIB5IkpjCgMleHMNEsGH6pg==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "cac": "^6.7.14",
- "debug": "^4.4.1",
- "es-module-lexer": "^1.7.0",
- "pathe": "^2.0.3",
- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
- },
- "bin": {
- "vite-node": "vite-node.mjs"
- },
- "engines": {
- "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
- },
- "funding": {
- "url": "https://opencollective.com/vitest"
- }
- },
"node_modules/vite/node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -8638,65 +8539,79 @@
}
},
"node_modules/vitest": {
- "version": "3.2.6",
- "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.6.tgz",
- "integrity": "sha512-xejya+bT/j/+R/AGa1XOfRxLmNUlLtlwjRsFUILF+xHfzElmGcmFydy2gqqIrd62ptIEfwVMofd19uNWD9L7Nw==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/chai": "^5.2.2",
- "@vitest/expect": "3.2.6",
- "@vitest/mocker": "3.2.6",
- "@vitest/pretty-format": "^3.2.6",
- "@vitest/runner": "3.2.6",
- "@vitest/snapshot": "3.2.6",
- "@vitest/spy": "3.2.6",
- "@vitest/utils": "3.2.6",
- "chai": "^5.2.0",
- "debug": "^4.4.1",
- "expect-type": "^1.2.1",
- "magic-string": "^0.30.17",
+ "version": "4.1.11",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
+ "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "4.1.11",
+ "@vitest/mocker": "4.1.11",
+ "@vitest/pretty-format": "4.1.11",
+ "@vitest/runner": "4.1.11",
+ "@vitest/snapshot": "4.1.11",
+ "@vitest/spy": "4.1.11",
+ "@vitest/utils": "4.1.11",
+ "es-module-lexer": "^2.0.0",
+ "expect-type": "^1.3.0",
+ "magic-string": "^0.30.21",
+ "obug": "^2.1.1",
"pathe": "^2.0.3",
- "picomatch": "^4.0.2",
- "std-env": "^3.9.0",
+ "picomatch": "^4.0.3",
+ "std-env": "^4.0.0-rc.1",
"tinybench": "^2.9.0",
- "tinyexec": "^0.3.2",
- "tinyglobby": "^0.2.14",
- "tinypool": "^1.1.1",
- "tinyrainbow": "^2.0.0",
- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0",
- "vite-node": "3.2.4",
+ "tinyexec": "^1.0.2",
+ "tinyglobby": "^0.2.15",
+ "tinyrainbow": "^3.1.0",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
- "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
+ "node": "^20.0.0 || ^22.0.0 || >=24.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
- "@types/debug": "^4.1.12",
- "@types/node": "^18.0.0 || ^20.0.0 || >=22.0.0",
- "@vitest/browser": "3.2.6",
- "@vitest/ui": "3.2.6",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "4.1.11",
+ "@vitest/browser-preview": "4.1.11",
+ "@vitest/browser-webdriverio": "4.1.11",
+ "@vitest/coverage-istanbul": "4.1.11",
+ "@vitest/coverage-v8": "4.1.11",
+ "@vitest/ui": "4.1.11",
"happy-dom": "*",
- "jsdom": "*"
+ "jsdom": "*",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
- "@types/debug": {
+ "@opentelemetry/api": {
"optional": true
},
"@types/node": {
"optional": true
},
- "@vitest/browser": {
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
"optional": true
},
"@vitest/ui": {
@@ -8707,6 +8622,9 @@
},
"jsdom": {
"optional": true
+ },
+ "vite": {
+ "optional": false
}
}
},
diff --git a/jarvis/ui/web/frontend/package.json b/jarvis/ui/web/frontend/package.json
index a7508ebbd1..ad03562949 100644
--- a/jarvis/ui/web/frontend/package.json
+++ b/jarvis/ui/web/frontend/package.json
@@ -73,6 +73,6 @@
"tailwindcss-animate": "^1.0.7",
"typescript": "^5.6.2",
"vite": "^6.4.3",
- "vitest": "^3.2.6"
+ "vitest": "^4.1.11"
}
}
diff --git a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx
index d28d278336..dba2fbcad1 100644
--- a/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/RealtimeOptionsControl.test.tsx
@@ -52,6 +52,8 @@ beforeEach(() => {
afterEach(() => {
cleanup();
+ // Vitest 4's restoreAllMocks no longer resets plain vi.fn() mocks.
+ vi.resetAllMocks();
vi.restoreAllMocks();
});
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
index 1cdfcd9899..dc8cc3015e 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.test.ts
@@ -18,6 +18,9 @@ describe("chat file links", () => {
it.each([
"https://example.test/clip.mp4",
"javascript:alert(1)",
+ " JavaScript:alert(1)",
+ "VBScript:msgbox(1)",
+ "data:text/html,<script>alert(1)</script>",
"file://server/share/clip.mp4",
"/api/outputs/run/files/clip.mp4/download",
])("does not treat %s as a local file", raw => {
diff --git a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
index 9f345a29d6..a08f2a3fd6 100644
--- a/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
+++ b/jarvis/ui/web/frontend/src/components/agentchat/chatLinks.ts
@@ -63,6 +63,7 @@ export function nativePathFromMarkdownUrl(raw: string): string | null {
lower.startsWith("http://") ||
lower.startsWith("https://") ||
lower.startsWith("javascript:") ||
+ lower.startsWith("vbscript:") ||
lower.startsWith("data:") ||
lower.startsWith("mailto:")
) {
diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx
index 2bb87d5e8f..bbbb6e4ded 100644
--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentModelPicker.test.tsx
@@ -1,7 +1,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import * as Dialog from "@radix-ui/react-dialog";
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
-import { afterEach, beforeEach, expect, test, vi } from "vitest";
+import { afterEach, beforeEach, expect, test, vi, type Mock } from "vitest";
import { loadLocaleChunk } from "@/i18n";
import type { AgentChatProvider, AgentConnectionRow } from "@/lib/agentChatApi";
import { SAMPLE_ROSTER } from "../mockRoster";
@@ -26,7 +26,7 @@ let extraProviders: AgentChatProvider[];
let liveModels: Record<string, { id: string; label: string }[]>;
let providerRows: unknown[];
let catalogCalls: number;
-let saving: ReturnType<typeof vi.fn>;
+let saving: Mock<(saving: boolean) => void>;
let catalogGate: Promise<void> | undefined;
let connectionsGate: Promise<void> | undefined;
let accountsGate: Promise<void> | undefined;
@@ -39,7 +39,7 @@ beforeEach(async () => {
tier: "specialist", state: "active", provider: "openai", model: "openai-large", effort: "high", account_id: "saved-seat",
avatar: {}, grants: [], focus: [], denies: [], approval_rules: {}, stats: { runs: 3, total_cost_usd: 1, last_active_ms: null },
} as unknown as SocietyAgentRow;
- posts = []; failSave = false; saving = vi.fn();
+ posts = []; failSave = false; saving = vi.fn<(saving: boolean) => void>();
extraProviders = []; liveModels = {}; providerRows = []; catalogCalls = 0;
catalogGate = undefined; connectionsGate = undefined; accountsGate = undefined;
vi.stubGlobal("fetch", vi.fn(async (url: string, init?: RequestInit) => {
diff --git a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
index 2e93b6c45e..40f8366366 100644
--- a/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
+++ b/jarvis/ui/web/frontend/src/components/wiki/PageRenderer.tsx
@@ -198,8 +198,9 @@ export function preprocessWikilinks(body: string): string {
return body.replace(WIKILINK_RE, (_match, target: string, label?: string) => {
const slug = lastSegment(target.trim());
const text = label ? label.trim() : slug;
- // Escape only `]` to avoid breaking the surrounding markdown.
- const safeText = text.replace(/]/g, "\\]");
+ // Escape backslashes first, then `]`, so a label cannot break out of the
+ // surrounding markdown link (a trailing `\` would otherwise escape the `]`).
+ const safeText = text.replace(/\\/g, "\\\\").replace(/]/g, "\\]");
return `[${safeText}](${WIKILINK_PREFIX}${slug})`;
});
}
diff --git a/jarvis/ui/web/frontend/src/hooks/useGraphAwake.test.ts b/jarvis/ui/web/frontend/src/hooks/useGraphAwake.test.ts
index cbba0b0a80..356bb9f477 100644
--- a/jarvis/ui/web/frontend/src/hooks/useGraphAwake.test.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useGraphAwake.test.ts
@@ -1,5 +1,5 @@
import { renderHook, act } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, describe, expect, it, vi, type Mock } from "vitest";
import { useGraphAwake, type GraphEngineApi } from "./useGraphAwake";
@@ -18,10 +18,13 @@ function pretend(state: { hidden?: boolean; focused?: boolean }): void {
}
function engine(): GraphEngineApi & {
- pauseAnimation: ReturnType<typeof vi.fn>;
- resumeAnimation: ReturnType<typeof vi.fn>;
+ pauseAnimation: Mock<() => unknown>;
+ resumeAnimation: Mock<() => unknown>;
} {
- return { pauseAnimation: vi.fn(), resumeAnimation: vi.fn() };
+ return {
+ pauseAnimation: vi.fn<() => unknown>(),
+ resumeAnimation: vi.fn<() => unknown>(),
+ };
}
afterEach(() => {
diff --git a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts
index 86902a92b6..f4064787d0 100644
--- a/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts
+++ b/jarvis/ui/web/frontend/src/hooks/useVisualArtifacts.ts
@@ -141,14 +141,17 @@ export function pageTitleFromPreview(preview: string | null | undefined): string
return title.length > 0 ? decodeEntities(title) : null;
}
-/** The handful of entities a `<title>` realistically carries. */
+/**
+ * The handful of entities a `<title>` realistically carries. `&amp;` is
+ * decoded last so `&amp;lt;` stays the literal text `&lt;` (no double decode).
+ */
function decodeEntities(text: string): string {
return text
- .replace(/&amp;/g, "&")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&quot;/g, '"')
- .replace(/&#39;|&apos;/g, "'");
+ .replace(/&#39;|&apos;/g, "'")
+ .replace(/&amp;/g, "&");
}
/** The visuals among a run's files, carrying the run they belong to. */
diff --git a/jarvis/ui/web/frontend/src/lib/sound.test.ts b/jarvis/ui/web/frontend/src/lib/sound.test.ts
index f92bdff717..0641e2a839 100644
--- a/jarvis/ui/web/frontend/src/lib/sound.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/sound.test.ts
@@ -33,7 +33,10 @@ function installFakeAudio() {
createGain = vi.fn(() => new FakeGain());
createOscillator = vi.fn(() => new FakeOsc());
}
- const ctorSpy = vi.fn(() => new FakeCtx());
+ // A `function` (not an arrow) so Vitest 4 lets the page `new` the mock.
+ const ctorSpy = vi.fn(function () {
+ return new FakeCtx();
+ });
(window as unknown as { AudioContext: unknown }).AudioContext = ctorSpy;
return { ctorSpy, oscillators, started, stopped };
}
diff --git a/jarvis/ui/web/frontend/src/store/newPaneChat.test.ts b/jarvis/ui/web/frontend/src/store/newPaneChat.test.ts
index 4788e0b311..37bb745b18 100644
--- a/jarvis/ui/web/frontend/src/store/newPaneChat.test.ts
+++ b/jarvis/ui/web/frontend/src/store/newPaneChat.test.ts
@@ -77,7 +77,10 @@ const MISSING: SplitAgentChoice = {
kind: "cli",
};
-function store(agents: SplitAgentChoice[], open = vi.fn(async () => undefined)) {
+function store(
+ agents: SplitAgentChoice[],
+ open = vi.fn(async (_: NewPaneRequest) => undefined),
+) {
return {
hook: createNewPaneChatStore({ folder: "C:/work/app", agents, open }),
open,
diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
index 214ab8dd5b..def2084f98 100644
--- a/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/PluginsView.test.tsx
@@ -427,9 +427,11 @@ describe("PkceConnectDialog own-client + production hint", () => {
await waitFor(() =>
expect(
calls.some(
- (c) =>
- c.url === "/api/settings/open-external" &&
- c.body.includes("https://api.slack.com/apps"),
+ (c) => {
+ if (c.url !== "/api/settings/open-external") return false;
+ const opened = new URL(JSON.parse(c.body).url as string);
+ return opened.hostname === "api.slack.com" && opened.pathname === "/apps";
+ },
),
).toBe(true),
);
diff --git a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx
index 7fa8a09623..6a3fc9fb82 100644
--- a/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/VisualizationView.test.tsx
@@ -166,6 +166,7 @@ describe("pageTitleFromPreview", () => {
it("reads a page's own title and decodes the common entities", () => {
expect(pageTitleFromPreview(DASH_HTML)).toBe("Umsatz-Dashboard");
expect(pageTitleFromPreview("<title> A &amp; B\n </title>")).toBe("A & B");
+ expect(pageTitleFromPreview("<title>&amp;lt;tag&amp;gt;</title>")).toBe("&lt;tag&gt;");
expect(pageTitleFromPreview("<html><body>no title</body></html>")).toBeNull();
expect(pageTitleFromPreview(null)).toBeNull();
});
diff --git a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
index 040143f4ed..1e63aa667e 100644
--- a/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/WikiView.test.tsx
@@ -538,6 +538,15 @@ describe("PageRenderer — wikilink behaviour", () => {
);
});
+ it("preprocessWikilinks escapes backslashes in labels", () => {
+ expect(preprocessWikilinks("[[example-user|a\\b]]")).toBe(
+ "[a\\\\b](#wiki:example-user)",
+ );
+ expect(preprocessWikilinks("[[example-user|trail\\]]")).toBe(
+ "[trail\\\\](#wiki:example-user)",
+ );
+ });
+
it("clicking a wikilink fires onWikilinkClick with the target slug", async () => {
installFetchMock({
"/api/wiki/tree": () => POPULATED_TREE,
diff --git a/jarvis/ui/web/frontend/vite.config.ts b/jarvis/ui/web/frontend/vite.config.ts
index b0d5b4f333..a568eaa7e4 100644
--- a/jarvis/ui/web/frontend/vite.config.ts
+++ b/jarvis/ui/web/frontend/vite.config.ts
@@ -1,4 +1,4 @@
-/// <reference types="vitest" />
+/// <reference types="vitest/config" />
import fs from "node:fs";
import { defineConfig } from "vite";
import type { Plugin } from "vite";
diff --git a/jarvis/ui/web/marketplace_publish_routes.py b/jarvis/ui/web/marketplace_publish_routes.py
index 0250a56072..6a3e9cb7ba 100644
--- a/jarvis/ui/web/marketplace_publish_routes.py
+++ b/jarvis/ui/web/marketplace_publish_routes.py
@@ -24,6 +24,7 @@ from fastapi import APIRouter, HTTPException, Response
from pydantic import BaseModel
from jarvis.marketplace.token_store import TokenStore
+from jarvis.ui.web.error_text import internal_error
log = logging.getLogger(__name__)
@@ -88,7 +89,8 @@ async def publish_identity(response: Response) -> dict[str, Any]:
"enabled": enabled,
"wallpapers_enabled": wallpapers_enabled,
"signed_in": False,
- "unreachable": str(exc),
+ # A flag with a fixed sentence; the network error itself is logged.
+ "unreachable": "GitHub is unreachable.",
}
return {"enabled": enabled, "wallpapers_enabled": wallpapers_enabled, **state}
@@ -132,7 +134,7 @@ async def signin_poll(flow_id: str, response: Response) -> dict[str, Any]:
try:
return task.result()
except Exception as exc: # noqa: BLE001 - surface, never crash the poll
- return {"status": "error", "error": str(exc)}
+ return {"status": "error", "error": internal_error("sign-in", exc, logger=log)}
@router.delete("/signin/{flow_id}")
diff --git a/jarvis/ui/web/mcp_routes.py b/jarvis/ui/web/mcp_routes.py
index 6fa44e6f39..45e4bf9700 100644
--- a/jarvis/ui/web/mcp_routes.py
+++ b/jarvis/ui/web/mcp_routes.py
@@ -25,6 +25,7 @@ from jarvis.core.config import get_secret, set_secret
from jarvis.core.events import BrainToolsChanged
from jarvis.mcp import state as mcp_state
from jarvis.mcp.registry import BOOTSTRAP_SERVERS, MCPRegistry, MCPServerSpec
+from jarvis.ui.web.error_text import diagnostic_text
log = logging.getLogger(__name__)
@@ -382,7 +383,8 @@ async def check_mcp(name: str, request: Request) -> dict[str, Any]:
"note": "already connected",
}
except Exception as exc: # noqa: BLE001
- msg = f"{type(exc).__name__}: {exc}"
+ log.warning("MCP probe of %s failed", name, exc_info=True)
+ msg = diagnostic_text(exc)
registry._errors[name] = msg # noqa: SLF001
return {"ok": False, "tools_count": 0, "error": msg}
@@ -399,7 +401,8 @@ async def check_mcp(name: str, request: Request) -> dict[str, Any]:
registry.clear_error(name)
return {"ok": True, "tools_count": len(tools), "error": None}
except Exception as exc: # noqa: BLE001
- msg = f"{type(exc).__name__}: {exc}"
+ log.warning("MCP probe of %s failed", name, exc_info=True)
+ msg = diagnostic_text(exc)
registry._errors[name] = msg # noqa: SLF001
return {"ok": False, "tools_count": 0, "error": msg}
finally:
diff --git a/jarvis/ui/web/self_mod_routes.py b/jarvis/ui/web/self_mod_routes.py
index a545396bfd..a38464add8 100644
--- a/jarvis/ui/web/self_mod_routes.py
+++ b/jarvis/ui/web/self_mod_routes.py
@@ -16,8 +16,6 @@ because the log can grow over months (Plan §AD-6, no rotation).
from __future__ import annotations
import base64
-import hashlib
-import hmac
import json
import logging
from datetime import datetime
@@ -27,6 +25,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException, Query, Request
from pydantic import BaseModel, Field
+from jarvis.core.admin_password import check_admin_pass
from jarvis.core.self_mod import (
AtomicConfigWriter,
BackupRef,
@@ -106,13 +105,7 @@ def _security_cfg(request: Request) -> Any:
def _check_admin_pass(provided: str | None, security_cfg: Any) -> bool:
"""Identical to skills_routes._check_admin_pass — reused here."""
- if security_cfg is None:
- return False
- expected = getattr(security_cfg, "admin_password_hash", "")
- if not expected or not provided:
- return False
- computed = hashlib.sha256(provided.encode("utf-8")).hexdigest()
- return hmac.compare_digest(computed, expected)
+ return check_admin_pass(provided, security_cfg)
# ----------------------------------------------------------------------
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 28cd01bd7a..44cd5cf831 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -1518,12 +1518,14 @@ class WebServer:
from jarvis.core.config import DATA_DIR
from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
+ from .error_text import LOG_HINT
+
try:
mem = CoreMemory.load(DATA_DIR / CORE_MEMORY_FILENAME)
return {"ok": True, "data": mem.all()}
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("Memory read error")
- return {"ok": False, "error": str(exc), "data": {}}
+ return {"ok": False, "error": "memory read failed. " + LOG_HINT, "data": {}}
@app.post("/api/memory/facts")
async def add_memory_fact(payload: dict[str, Any]) -> dict[str, Any]:
@@ -1531,6 +1533,8 @@ class WebServer:
from jarvis.core.config import DATA_DIR
from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
+ from .error_text import LOG_HINT
+
fact = (payload.get("fact") or "").strip()
category = (payload.get("category") or "general").strip()
if not fact:
@@ -1541,7 +1545,7 @@ class WebServer:
return {"ok": True, "data": mem.all()}
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("Memory write error")
- return {"ok": False, "error": str(exc)}
+ return {"ok": False, "error": "memory write failed. " + LOG_HINT}
@app.delete("/api/memory/facts")
async def delete_memory_fact(payload: dict[str, Any]) -> dict[str, Any]:
@@ -1549,6 +1553,8 @@ class WebServer:
from jarvis.core.config import DATA_DIR
from jarvis.memory import CORE_MEMORY_FILENAME, CoreMemory
+ from .error_text import LOG_HINT
+
fact = (payload.get("fact") or "").strip()
category = (payload.get("category") or "general").strip()
if not fact:
@@ -1559,7 +1565,7 @@ class WebServer:
return {"ok": ok, "data": mem.all()}
except Exception as exc: # noqa: BLE001
logger.opt(exception=exc).warning("Memory delete error")
- return {"ok": False, "error": str(exc)}
+ return {"ok": False, "error": "memory delete failed. " + LOG_HINT}
@app.get("/api/terminal/shells")
async def terminal_shells() -> dict[str, Any]:
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 30268b192e..b45cac226c 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -42,6 +42,7 @@ from jarvis.memory.wiki.integration import get_running_curator
from jarvis.speech.local_models import FASTER_WHISPER_PACKAGE
from jarvis.ui.overlay_styles import OVERLAY_STYLES, normalize_overlay_style
+from .error_text import LOG_HINT
from .lifecycle_guard import require_interactive_desktop_action
if TYPE_CHECKING:
@@ -1499,15 +1500,14 @@ def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str,
# The failure is REPORTED, never swallowed: `persisted` and `message` carry
# it so the UI can say the setting will not survive a restart.
persisted = False
- persist_error = ""
try:
from jarvis.core import config_writer
config_writer.set_wake_word_enabled(bool(body.enabled))
persisted = True
- except Exception as exc: # noqa: BLE001 — best-effort, reported not raised
- persist_error = str(exc)
- log.warning("wake activation persist failed: %s", exc)
+ except Exception: # noqa: BLE001 — best-effort, reported not raised
+ # The traceback stays in the log; the client gets a stable sentence.
+ log.warning("wake activation persist failed", exc_info=True)
# Best-effort in-memory update so a later cfg read agrees pre-restart.
cfg = _config(request)
if cfg is not None and getattr(cfg, "trigger", None) is not None:
@@ -1534,7 +1534,7 @@ def set_wake_activation(body: WakeActivationBody, request: Request) -> dict[str,
"message": (
""
if persisted
- else f"The setting could not be saved to jarvis.toml: {persist_error}"
+ else f"The setting could not be saved to jarvis.toml. {LOG_HINT}"
),
}
@@ -2229,8 +2229,12 @@ async def put_overlay_style(body: OverlayStyleBody, request: Request) -> dict[st
bool(result.get("applied_live")) if isinstance(result, dict) else bool(result)
)
except Exception as exc: # noqa: BLE001 — never fail the toggle on an apply hiccup
- log.warning("overlay-style live-apply failed (persisted; applies on restart): %s", exc)
- detail = str(exc)
+ log.warning(
+ "overlay-style live-apply failed (persisted; applies on restart): %s",
+ exc,
+ exc_info=True,
+ )
+ detail = f"The live switch failed; the style applies on restart. {LOG_HINT}"
return {
"ok": True,
diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.py
index 181f4d685f..5c12f37b96 100644
--- a/jarvis/ui/web/skills_routes.py
+++ b/jarvis/ui/web/skills_routes.py
@@ -16,8 +16,6 @@ set by the ``WebServer`` at startup (after ``ensure_user_skills_dir()``).
from __future__ import annotations
import asyncio
-import hashlib
-import hmac
import importlib.util
import re
from dataclasses import replace
@@ -28,6 +26,7 @@ from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import PlainTextResponse
from pydantic import BaseModel, Field
+from jarvis.core.admin_password import check_admin_pass
from jarvis.core.paths import user_skills_dir
from jarvis.core.uploads import UploadRejected, stage_upload
from jarvis.skills.builtin import BUILTIN_SKILL_NAMES
@@ -35,6 +34,7 @@ from jarvis.skills.finder import SearchFilters, SkillFinder
from jarvis.skills.loader import parse_skill
from jarvis.skills.origin import read_origin
from jarvis.skills.schema import RESOURCE_KINDS, Skill, SkillLifecycleState
+from jarvis.ui.web.error_text import internal_error
from jarvis.ui.web.upload_intake import (
read_upload_entries,
upload_http_error,
@@ -209,15 +209,10 @@ def _check_admin_pass(provided: str | None, security_cfg: Any) -> bool:
- No hash set (empty string) -> always False (built-in edits locked).
- No password provided -> False.
- - Otherwise: compare SHA-256, constant-time via ``hmac.compare_digest``.
+ - Otherwise: salted scrypt check (legacy SHA-256 hex still accepted),
+ constant-time -- see ``jarvis.core.admin_password``.
"""
- if security_cfg is None:
- return False
- expected = getattr(security_cfg, "admin_password_hash", "")
- if not expected or not provided:
- return False
- computed = hashlib.sha256(provided.encode("utf-8")).hexdigest()
- return hmac.compare_digest(computed, expected)
+ return check_admin_pass(provided, security_cfg)
# ----------------------------------------------------------------------
@@ -690,12 +685,17 @@ async def import_skill(body: SkillImportBody, request: Request) -> dict[str, Any
import httpx
+ from jarvis.core.http_guard import public_only_async
+
reg = _require_registry(request)
raw_url = _extract_import_url(body.input)
+ # The download runs server-side, so the pasted link (and every redirect it
+ # takes) must not reach the loopback API, the LAN or a metadata endpoint.
async with httpx.AsyncClient(
follow_redirects=True,
timeout=httpx.Timeout(20.0),
+ **public_only_async(schemes=("http", "https")),
) as client:
try:
resp = await client.get(raw_url)
@@ -1871,7 +1871,7 @@ async def install_from_catalog(
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # noqa: BLE001
raise HTTPException(
- status_code=500, detail=f"Installation failed: {exc}"
+ status_code=500, detail=internal_error("Installation", exc)
) from exc
# Registry refresh — the new skill should appear in the sidebar immediately
@@ -1883,7 +1883,7 @@ async def install_from_catalog(
"ok": True,
"name": body.name,
"path": str(target_path),
- "reload_warning": str(exc),
+ "reload_warning": internal_error("Skill registry reload", exc),
}
try:
diff --git a/jarvis/ui/web/society_figure_routes.py b/jarvis/ui/web/society_figure_routes.py
index b52caf7006..59751546c2 100644
--- a/jarvis/ui/web/society_figure_routes.py
+++ b/jarvis/ui/web/society_figure_routes.py
@@ -27,6 +27,7 @@ from fastapi.concurrency import run_in_threadpool
from fastapi.responses import FileResponse
from jarvis.core.config import DATA_DIR
+from jarvis.core.path_safety import UnsafePathError, safe_child
log = logging.getLogger(__name__)
@@ -45,6 +46,21 @@ def figures_dir() -> Path:
return DATA_DIR / "society" / "figures"
+def _figure_path(file_name: str) -> Path | None:
+ """The stored figure called *file_name*, or None when the name is not one.
+
+ Only a plain ``*.glb`` component inside :func:`figures_dir` qualifies, so a
+ request can never read or delete a file elsewhere (``..``, separators, or a
+ Windows drive-relative name such as ``C:x.glb``).
+ """
+ if not file_name.endswith(".glb"):
+ return None
+ try:
+ return safe_child(figures_dir(), file_name)
+ except UnsafePathError: # an escaping name is simply not a figure; the route answers 404
+ return None
+
+
def _load_gate():
if "check_society_figures" in sys.modules:
return sys.modules["check_society_figures"]
@@ -136,13 +152,8 @@ async def import_figure(request: Request, name: str = Query("figure")) -> dict[s
@router.get("/{file_name}")
def get_figure(file_name: str) -> FileResponse:
- path = figures_dir() / file_name
- if (
- not file_name.endswith(".glb")
- or "/" in file_name
- or "\\" in file_name
- or not path.is_file()
- ):
+ path = _figure_path(file_name)
+ if path is None or not path.is_file():
raise HTTPException(404, "no such figure")
return FileResponse(
path, media_type="model/gltf-binary", headers={"Cache-Control": "public, max-age=31536000"}
@@ -151,14 +162,8 @@ def get_figure(file_name: str) -> FileResponse:
@router.delete("/{file_name}", openapi_extra={"x-jarvis-dangerous": True})
async def delete_figure(file_name: str) -> dict[str, Any]:
- path = figures_dir() / file_name
- if (
- not file_name.endswith(".glb")
- or "/" in file_name
- or "\\" in file_name
- or not path.is_file()
- ):
+ path = _figure_path(file_name)
+ if path is None or not path.is_file():
raise HTTPException(404, "no such figure")
await run_in_threadpool(path.unlink)
return {"deleted": file_name}
-
diff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.py
index 72730d475a..c9756e3c8e 100644
--- a/jarvis/ui/web/telephony_routes.py
+++ b/jarvis/ui/web/telephony_routes.py
@@ -55,6 +55,7 @@ from jarvis.telephony.security import (
)
from jarvis.telephony.status import CallRecord, TelephonyManager
from jarvis.telephony.twiml import build_connect_stream_twiml, build_reject_twiml
+from jarvis.ui.web.error_text import internal_error
log = logging.getLogger("jarvis.telephony.routes")
@@ -254,8 +255,9 @@ async def post_config(request: Request, body: ConfigUpdate) -> JSONResponse:
status_code=409,
)
except Exception as exc: # noqa: BLE001
- log.warning("telephony config write failed: %s", exc)
- return JSONResponse({"error": f"config write failed: {exc}"}, status_code=409)
+ return JSONResponse(
+ {"error": internal_error("config write", exc, logger=log)}, status_code=409
+ )
# The disk write succeeded — mirror it onto the live shared config so
# the webhook / media-socket handlers see it immediately (Bug: config
# split-brain, see _apply_live_twilio_updates).
@@ -312,7 +314,7 @@ async def post_credentials(request: Request, body: CredentialsUpdate) -> JSONRes
except Exception as exc: # noqa: BLE001
return JSONResponse(
{
- "error": f"config write failed: {exc}",
+ "error": internal_error("config write", exc, logger=log),
"token_saved": token_saved,
"sid_saved": False,
},
@@ -360,36 +362,61 @@ async def post_test(request: Request) -> JSONResponse:
except Exception: # noqa: BLE001 — no/empty body → fall back to persisted
body = {}
twilio = _twilio_cfg(request)
- account_sid = (str(body.get("account_sid") or "").strip()
- or (getattr(twilio, "account_sid", "") or ""))
+ account_sid = str(body.get("account_sid") or "").strip() or (
+ getattr(twilio, "account_sid", "") or ""
+ )
token = str(body.get("auth_token") or "").strip() or _auth_token()
mgr = _manager(request)
# M4: honest five-layer status (PROVIDER_TEST_STATUSES) instead of a binary
# ok/failed — bad SID, unfunded/suspended account, and an outage are different.
- from jarvis.brain.provider_test import classify_provider_error
-
+ # The status is classified inside provisioning (TelephonyProvisionError.status)
+ # so Twilio's raw response text never reaches this payload.
if not account_sid or not token:
mgr.set_reachable(False, "account_sid or auth_token missing")
- return JSONResponse({
- "ok": False, "reachable": False, "status": "not_configured",
- "error": "account_sid or auth_token missing",
- })
+ return JSONResponse(
+ {
+ "ok": False,
+ "reachable": False,
+ "status": "not_configured",
+ "error": "account_sid or auth_token missing",
+ }
+ )
try:
from jarvis.telephony.provisioning import verify_credentials
info = verify_credentials(account_sid, token)
mgr.set_reachable(True, None)
- return JSONResponse({
- "ok": True, "reachable": True, "status": "ok",
- "account_status": info.get("account_status", ""),
- })
+ return JSONResponse(
+ {
+ "ok": True,
+ "reachable": True,
+ "status": "ok",
+ "account_status": info.get("account_status", ""),
+ }
+ )
+ except TelephonyProvisionError as exc:
+ # str(exc) is a clean sentence built by provisioning.sdk_failure / _client.
+ message = str(exc)
+ mgr.set_reachable(False, message)
+ return JSONResponse(
+ {
+ "ok": False,
+ "reachable": False,
+ "status": exc.status,
+ "error": message,
+ }
+ )
except Exception as exc: # noqa: BLE001
- mgr.set_reachable(False, str(exc))
- return JSONResponse({
- "ok": False, "reachable": False,
- "status": classify_provider_error(str(exc)),
- "error": str(exc),
- })
+ message = internal_error("Twilio credential check", exc, logger=log)
+ mgr.set_reachable(False, message)
+ return JSONResponse(
+ {
+ "ok": False,
+ "reachable": False,
+ "status": "error",
+ "error": message,
+ }
+ )
# ---------------------------------------------------------------------------
@@ -429,7 +456,7 @@ async def post_selftest(request: Request) -> JSONResponse:
chunks.append(chunk)
response_text = "".join(chunks).strip()
except Exception as exc: # noqa: BLE001
- error = f"brain: {exc}"
+ error = f"brain: {internal_error('selftest brain call', exc, logger=log)}"
if not response_text:
response_text = "Ja, das Telefon funktioniert. Ich höre dich klar und deutlich." # i18n-allow: canned voice-output fallback, synthesized via TTS below
@@ -451,8 +478,9 @@ async def post_selftest(request: Request) -> JSONResponse:
if pcm:
audio_bytes += len(tts_pcm_to_twilio_ulaw(pcm, source_rate=rate))
except Exception as exc: # noqa: BLE001
+ message = internal_error("selftest speech synthesis", exc, logger=log)
if error is None:
- error = f"tts: {exc}"
+ error = f"tts: {message}"
return JSONResponse(
{
@@ -612,10 +640,14 @@ async def post_outbound(request: Request, body: OutboundCall) -> JSONResponse:
public_base_url=public_base_url,
)
except TelephonyProvisionError as exc:
+ # A clean English sentence: our own validation text, or the classified
+ # summary from provisioning.sdk_failure — never Twilio's raw response.
return JSONResponse({"ok": False, "error": str(exc)}, status_code=409)
except Exception as exc: # noqa: BLE001 - never 500 a UI button
- log.warning("telephony outbound call failed: %s", exc)
- return JSONResponse({"ok": False, "error": f"outbound call failed: {exc}"}, status_code=409)
+ return JSONResponse(
+ {"ok": False, "error": internal_error("outbound call", exc, logger=log)},
+ status_code=409,
+ )
return JSONResponse({"ok": True, "call_sid": call_sid})
diff --git a/jarvis/ui/web/wallpapers.py b/jarvis/ui/web/wallpapers.py
index 4fb7b28283..4ebdecc197 100644
--- a/jarvis/ui/web/wallpapers.py
+++ b/jarvis/ui/web/wallpapers.py
@@ -441,7 +441,7 @@ class WallpaperUploads:
return []
items: list[UploadedWallpaper] = []
for image in self._root.glob("u*.webp"):
- if not _UPLOAD_ID_PATTERN.match(image.stem):
+ if not _UPLOAD_ID_PATTERN.fullmatch(image.stem):
continue
item = self._read(image.stem)
if item is not None:
@@ -449,7 +449,7 @@ class WallpaperUploads:
return sorted(items, key=lambda item: (-item.created_at, item.id))
def get(self, upload_id: str) -> UploadedWallpaper | None:
- if not _UPLOAD_ID_PATTERN.match(upload_id):
+ if not _UPLOAD_ID_PATTERN.fullmatch(upload_id):
return None
return self._read(upload_id)
@@ -573,7 +573,7 @@ class WallpaperUploads:
def remove(self, upload_id: str) -> bool:
"""Delete one upload, picture and sidecar and thumbnail."""
- if not _UPLOAD_ID_PATTERN.match(upload_id):
+ if not _UPLOAD_ID_PATTERN.fullmatch(upload_id):
return False
with self._lock:
image = self._image_path(upload_id)
diff --git a/jarvis/workspace/custom_clis.py b/jarvis/workspace/custom_clis.py
index bb337b5f41..b1ecbd9129 100644
--- a/jarvis/workspace/custom_clis.py
+++ b/jarvis/workspace/custom_clis.py
@@ -40,6 +40,7 @@ Cross-platform: the command is stored verbatim and started through this host's
own shell (``jarvis.terminal.shells``), so a Windows entry may be a ``.cmd`` and
a Linux one a shell function without either needing to know about the other.
"""
+
from __future__ import annotations
import json
@@ -53,6 +54,7 @@ from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Literal
+from jarvis.core.path_safety import UnsafePathError, safe_child
from jarvis.core.paths import workspace_clis_dir, workspace_clis_path
log = logging.getLogger(__name__)
@@ -307,9 +309,7 @@ def _write(entries: Iterable[CustomCli]) -> None:
"entries": [entry.to_dict() for entry in entries],
}
tmp = path.with_name(path.name + ".tmp")
- tmp.write_text(
- json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
- )
+ tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
os.replace(tmp, path)
_bump()
@@ -429,9 +429,7 @@ def update_custom_cli(
if description is not None:
entry = replace(entry, description=_clean_description(description))
if file_reference is not None:
- entry = replace(
- entry, file_reference="at" if file_reference == "at" else "quoted"
- )
+ entry = replace(entry, file_reference="at" if file_reference == "at" else "quoted")
entries[index] = entry
_write(entries)
return entry
@@ -458,9 +456,25 @@ def delete_custom_cli(entry_id: str) -> CustomCli:
# --------------------------------------------------------------------------
+def _logo_path(entry_id: str, suffix: str) -> Path | None:
+ """The logo file for this id, or None when the id is not a plain name.
+
+ Ids normally come from :func:`_slug`, but the store is a JSON file a person
+ can edit by hand, so the name is still checked to stay inside
+ :func:`logo_dir` before anything reads, writes or deletes it.
+ """
+ try:
+ return safe_child(logo_dir(), f"{entry_id}{suffix}")
+ except UnsafePathError:
+ log.warning("workspace-clis: refusing logo path for id %r", entry_id)
+ return None
+
+
def _remove_logo_files(entry_id: str) -> None:
for suffix in LOGO_TYPES:
- candidate = logo_dir() / f"{entry_id}{suffix}"
+ candidate = _logo_path(entry_id, suffix)
+ if candidate is None:
+ continue
try:
candidate.unlink(missing_ok=True)
except OSError as exc: # noqa: PERF203 - one failure must not stop the rest
@@ -497,16 +511,16 @@ def set_logo(entry_id: str, data: bytes, filename: str) -> CustomCli:
if not data:
raise CustomCliError("That file is empty.")
if len(data) > MAX_LOGO_BYTES:
- raise CustomCliError(
- f"Keep the logo under {MAX_LOGO_BYTES // 1024} KB."
- )
+ raise CustomCliError(f"Keep the logo under {MAX_LOGO_BYTES // 1024} KB.")
if not _looks_like(suffix, data):
raise CustomCliError(f"That file is not really a {suffix.lstrip('.').upper()}.")
# One logo per entry: the old file goes first, so a switch from PNG to SVG
# does not leave a stale sibling that a later lookup could pick up.
+ target = _logo_path(entry_id, suffix)
+ if target is None:
+ raise CustomCliError("That CLI's id cannot name a logo file.")
_remove_logo_files(entry_id)
- target = logo_dir() / f"{entry_id}{suffix}"
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(data)
@@ -541,7 +555,9 @@ def logo_file(entry_id: str) -> tuple[Path, str] | None:
media = LOGO_TYPES.get(suffix)
if media is None:
return None
- path = logo_dir() / f"{entry_id}{suffix}"
+ path = _logo_path(entry_id, suffix)
+ if path is None:
+ return None
return (path, media) if path.is_file() else None
diff --git a/scripts/ci/privacy_gate/scripts/strip_and_scan.py b/scripts/ci/privacy_gate/scripts/strip_and_scan.py
index 4ec7d4fefb..1f6b9634cd 100644
--- a/scripts/ci/privacy_gate/scripts/strip_and_scan.py
+++ b/scripts/ci/privacy_gate/scripts/strip_and_scan.py
@@ -406,21 +406,22 @@ def cmd_scan(args: argparse.Namespace) -> int:
text, _ = _decode(data)
exempt = _matches_any(rel, scrub_exempt)
- # high-confidence secret shapes
+ # high-confidence secret shapes -- the matched credential itself is
+ # never copied into the report or the terminal (see _secret_location).
for name, rx in secret_rx.items():
for m in rx.finditer(text):
value = m.group(0)
+ where = _secret_location(text, m)
if (value, rel) in allow:
- suppressed.append({"path": rel, "pattern": name, "value": value})
+ suppressed.append({"path": rel, "pattern": name, **where})
elif exempt:
warnings.append(
{"kind": "secret_in_exempt", "path": rel,
- "pattern": name, "value": value}
+ "pattern": name, **where}
)
else:
blocking.append(
- {"kind": "secret", "path": rel, "pattern": name,
- "value": value}
+ {"kind": "secret", "path": rel, "pattern": name, **where}
)
# residual PII (scrub + block-only rows must be 0 in non-exempt files)
@@ -485,7 +486,8 @@ def cmd_scan(args: argparse.Namespace) -> int:
f"{len(suppressed)} allowlisted-suppressed."
)
for b in blocking[:50]:
- _eprint(f" BLOCK [{b['kind']}] {b['path']}: {b.get('value', b.get('detail',''))}")
+ where = f"{b['path']}:{b['line']}" if b.get("line") else b["path"]
+ _eprint(f" BLOCK [{b['kind']}] {where}: {b.get('value', b.get('detail', ''))}")
# fail-closed: any blocking finding => non-zero exit
return 2 if blocking else 0
@@ -717,6 +719,19 @@ def cmd_set_version(args: argparse.Namespace) -> int:
return 0
+def _secret_location(text: str, match: re.Match[str]) -> dict:
+ """Where a secret-shape match sits, WITHOUT the matched value.
+
+ Scan reports and stderr end up in CI logs and review transcripts, so a
+ secret finding carries only its line and length; the maintainer opens the
+ file at that line to see (and allowlist) the exact value.
+ """
+ return {
+ "line": text.count("\n", 0, match.start()) + 1,
+ "value": f"<hidden, {len(match.group(0))} chars>",
+ }
+
+
def _write_report(report_path: str | None, payload: dict) -> None:
if report_path:
Path(report_path).write_text(json.dumps(payload, indent=2), "utf-8")
diff --git a/scripts/ci/privacy_pre_push.py b/scripts/ci/privacy_pre_push.py
index 395b5e84d2..2c8e75ebfb 100644
--- a/scripts/ci/privacy_pre_push.py
+++ b/scripts/ci/privacy_pre_push.py
@@ -199,7 +199,9 @@ def scan_text_for_secrets(
unless the exact (value, rel) pair is in the allowlist (the ship skill's
secret-allowlist, loaded as a set of (value, path) tuples).
- Returns: list of {"path": rel, "pattern": <name>, "value": <matched>}.
+ Returns: list of {"path": rel, "pattern": <name>, "value": <matched>,
+ "line": <1-based line number>}. ``value`` is for allowlist matching only --
+ print a finding with :func:`describe_secret_finding`, never the raw value.
"""
findings: list[dict] = []
for name, rx in compiled_patterns.items():
@@ -207,10 +209,25 @@ def scan_text_for_secrets(
value = m.group(0)
if (value, rel) in allowlist:
continue
- findings.append({"path": rel, "pattern": name, "value": value})
+ line = text.count("\n", 0, m.start()) + 1
+ findings.append({"path": rel, "pattern": name, "value": value, "line": line})
return findings
+def describe_secret_finding(finding: dict) -> str:
+ """Human-readable location of a secret finding WITHOUT the secret itself.
+
+ Terminal output of a git hook ends up in CI logs, agent transcripts and
+ screen shares, so only the pattern name, the file:line and the match
+ length are shown; the author opens the file to see the value.
+ """
+ where = finding["path"]
+ if finding.get("line"):
+ where = f"{where}:{finding['line']}"
+ length = len(finding.get("value") or "")
+ return f"secret ({finding['pattern']}) in {where} [{length} chars, value hidden]"
+
+
# --------------------------------------------------------------------------- #
# Thin git / IO wrappers (NOT unit-tested — side-effecting)
# --------------------------------------------------------------------------- #
@@ -513,8 +530,7 @@ def main(argv: list[str], stdin) -> int:
blocked = True
for s in secrets:
print(
- f"\nPUSH BLOCKED: secret ({s['pattern']}) in "
- f"{s['path']}: {s['value']}",
+ f"\nPUSH BLOCKED: {describe_secret_finding(s)}",
file=sys.stderr,
)
diff --git a/scripts/smoke_groq_stt.py b/scripts/smoke_groq_stt.py
index 0956173b5e..49c48d2fc7 100644
--- a/scripts/smoke_groq_stt.py
+++ b/scripts/smoke_groq_stt.py
@@ -54,7 +54,7 @@ async def main() -> int:
if not key:
print("ERROR: set GROQ_API_KEY before invoking this script.", file=sys.stderr)
return 2
- print(f"[smoke] GROQ_API_KEY present (len={len(key)}, prefix={key[:4]}...)")
+ print("[smoke] GROQ_API_KEY is set.") # never echo any part of the key
pcm = _synthetic_speech_like_pcm()
chunk = _Chunk(pcm=pcm)
diff --git a/tests/e2e/test_self_mod_e2e.py b/tests/e2e/test_self_mod_e2e.py
index 8822160aed..66d40304c1 100644
--- a/tests/e2e/test_self_mod_e2e.py
+++ b/tests/e2e/test_self_mod_e2e.py
@@ -614,10 +614,10 @@ def api_app(
app.include_router(self_mod_router)
app.state.self_mod_audit = audit
app.state.self_mod_writer = writer
- # Admin-PW: SHA-256 von "secret"
- import hashlib
+ # Admin password "secret", stored as a salted scrypt hash.
+ from jarvis.core.admin_password import hash_admin_password
- expected_hash = hashlib.sha256(b"secret").hexdigest()
+ expected_hash = hash_admin_password("secret")
app.state.config = type(
"C",
(),
diff --git a/tests/missions/test_mutating_cmd_regex_linear_time.py b/tests/missions/test_mutating_cmd_regex_linear_time.py
new file mode 100644
index 0000000000..42fc493409
--- /dev/null
+++ b/tests/missions/test_mutating_cmd_regex_linear_time.py
@@ -0,0 +1,64 @@
+"""The mutating git/gh command detector never backtracks exponentially.
+
+CodeQL py/redos: an option such as ``-c -x`` or ``--git-dir=x`` had two
+readings, so a long option list that ends without a mutating subcommand
+doubled the work per option. Each token now has one parse.
+"""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+from jarvis.missions.stream_evidence import _MUTATING_CMD_RE
+
+
+ ("command", "expected"),
+ [
+ ("git push origin main", True),
+ ("git -C /tmp/repo commit -m x", True),
+ ("git -c user.name=x push", True),
+ ("git -c -x push", True),
+ ("git -c - push", True),
+ ("git --no-pager commit", True),
+ ("git --git-dir=/r/.git push", True),
+ ("git --git-dir /r/.git --work-tree /r tag v1", True),
+ ("git --git-dir -x push", True),
+ ("git log --grep=push", False),
+ ("git status", False),
+ ("echo gitpush", False),
+ ("gh pr create --fill", True),
+ ("gh pr list", False),
+ ],
+)
+def test_mutating_cmd_normal(command: str, expected: bool) -> None:
+ assert bool(_MUTATING_CMD_RE.search(command)) is expected
+
+
+ "tail",
+ [
+ " -c -!" * 40,
+ " -c -! " * 40,
+ " -! -" * 40,
+ " --x" * 40,
+ " --git-dir=x" * 40,
+ " --git-dir -" * 40,
+ " -c x" * 5000,
+ ],
+ ids=[
+ "value-is-flag",
+ "value-is-flag-spaced",
+ "flag-pairs",
+ "double-dash",
+ "git-dir-eq",
+ "git-dir-lone-dash",
+ "many-pairs",
+ ],
+)
+def test_mutating_cmd_pathological(tail: str) -> None:
+ start = time.perf_counter()
+ assert _MUTATING_CMD_RE.search("git" + tail + " status") is None
+ assert time.perf_counter() - start < 1.0
diff --git a/tests/unit/agentic_ide/test_library.py b/tests/unit/agentic_ide/test_library.py
index 3f297e51e0..8b11ed199c 100644
--- a/tests/unit/agentic_ide/test_library.py
+++ b/tests/unit/agentic_ide/test_library.py
@@ -218,3 +218,10 @@ def test_title_from_prompt_takes_the_first_line_and_stays_short() -> None:
def test_title_from_prompt_survives_an_empty_prompt() -> None:
"""Whitespace in, empty out — never an exception on the prompt path."""
assert library.title_from_prompt(" \n\n ") == ""
+
+
+def test_a_hostile_project_id_never_names_a_file_outside() -> None:
+ """A project id from a request cannot read or write beside the threads folder."""
+ for hostile in ("../projects", "..", "a/b", "C:evil"):
+ assert library._threads_path(hostile) is None
+ assert library.list_threads(hostile) == []
diff --git a/tests/unit/agentic_ide/test_regex_linear_time.py b/tests/unit/agentic_ide/test_regex_linear_time.py
new file mode 100644
index 0000000000..95e58cf4e2
--- /dev/null
+++ b/tests/unit/agentic_ide/test_regex_linear_time.py
@@ -0,0 +1,153 @@
+"""The agentic-IDE parsers stay linear on long, hostile input.
+
+CodeQL flagged these patterns as polynomial ReDoS (py/polynomial-redos): typed
+or pasted text reaches them unbounded, and the old forms rescanned long blank
+runs from every start position. Each test pins the normal behaviour AND a
+pathological input of ~50k characters that must finish well under a second.
+""" # i18n-allow: quoted spoken input in the cases below
+
+from __future__ import annotations
+
+import time
+from collections.abc import Callable
+
+import pytest
+
+from jarvis.agentic_ide import clarify, intent
+
+_BUDGET_S = 1.0
+_N = 50_000
+
+
+def _fast(fn: Callable[[], object]) -> None:
+ start = time.perf_counter()
+ fn()
+ assert time.perf_counter() - start < _BUDGET_S
+
+
+ ("prefix", "expected"),
+ [
+ ("", True),
+ ("Hallo.", True),
+ ("Hallo. ", True),
+ ("erste Zeile\n", True),
+ ("erste Zeile\n ", True),
+ (" ", False),
+ ("sag", False),
+ ("x. y", False),
+ ],
+)
+def test_opens_sentence_normal(prefix: str, expected: bool) -> None:
+ assert clarify._opens_sentence(prefix) is expected
+
+
+def test_opens_sentence_pathological() -> None:
+ _fast(lambda: clarify._opens_sentence("\n" * _N + "x"))
+
+
+ ("gap", "expected"),
+ [(", ", True), (" und ", True), (" as well as ", True), ("", True), (" oder ", False)],
+)
+def test_enumeration_gap_normal(gap: str, expected: bool) -> None:
+ assert bool(clarify._ENUMERATION_GAP_RE.match(gap)) is expected
+
+
+def test_enumeration_gap_pathological() -> None:
+ _fast(lambda: clarify._ENUMERATION_GAP_RE.match("\t" * _N + "x"))
+
+
+ ("gap", "expected"),
+ [(", ", True), (" und ", True), (" & ", True), (" oder ", False), (" sagt ", False)],
+)
+def test_coordination_normal(gap: str, expected: bool) -> None:
+ assert bool(intent._COORDINATION_RE.match(gap)) is expected
+
+
+def test_coordination_pathological() -> None:
+ _fast(lambda: intent._COORDINATION_RE.match("\t" * _N + "x"))
+
+
+ ("suffix", "expected"),
+ [("nicht", True), (", aber nicht.", True), ("not !", True), ("no way", False)],
+)
+def test_trailing_negation_normal(suffix: str, expected: bool) -> None:
+ assert bool(intent._TRAILING_NEGATION_RE.fullmatch(suffix)) is expected
+
+
+def test_trailing_negation_pathological() -> None:
+ _fast(lambda: intent._TRAILING_NEGATION_RE.fullmatch("no" + " " * _N + "x"))
+
+
+ ("text", "expected"),
+ [
+ ("Und was passiert dann?", "was passiert dann?"),
+ ("¿ y qué pasa?", "qué pasa?"),
+ ("and, and — why?", "why?"),
+ ("Was passiert?", "Was passiert?"),
+ ],
+)
+def test_question_discourse_prefix_normal(text: str, expected: str) -> None:
+ assert intent._QUESTION_DISCOURSE_PREFIX_RE.sub("", text) == expected
+
+
+def test_question_discourse_prefix_pathological() -> None:
+ _fast(lambda: intent._QUESTION_DISCOURSE_PREFIX_RE.sub("", " " * _N + "x"))
+
+
+ ("task", "expected"),
+ [
+ ("die Tests fixen und der ", "die Tests fixen"),
+ ("den Bug fixen, and the", "den Bug fixen"),
+ ("den Hund", "den Hund"),
+ ("docs lesen. ", "docs lesen"),
+ ],
+)
+def test_group_task_trim_normal(task: str, expected: str) -> None:
+ assert intent._GROUP_TASK_TRIM_RE.sub("", task) == expected
+
+
[email protected]("blank", ["\t", " ", " ."], ids=["tab", "space", "dot"])
+def test_group_task_trim_pathological(blank: str) -> None:
+ _fast(lambda: intent._GROUP_TASK_TRIM_RE.sub("", blank * _N + "x"))
+
+
+ ("text", "span"),
+ [
+ ("mach zwei Terminals und prompt sie", (24, 30)),
+ ("zwei Terminals, gib ihnen die Aufgabe, Tests zu fixen", (16, 37)),
+ ("gib mir zwei Terminals\ndie Aufgabe kommt später", None),
+ ("gib jedem eine Aufgabe und tell them", (0, 22)),
+ ("zwei Terminals auf", None),
+ ],
+)
+def test_fleet_brief_search_normal(text: str, span: tuple[int, int] | None) -> None:
+ match = intent._fleet_brief_search(text)
+ assert (match.span() if match else None) == span
+
+
+def test_fleet_brief_search_honours_bounds() -> None:
+ text = "tell them, gib ihnen die Aufgabe"
+ match = intent._fleet_brief_search(text, 5)
+ assert match is not None and match.start() == 11
+ assert intent._fleet_brief_search(text, 5, 20) is None
+
+
+ "build",
+ [
+ lambda: "gib" + " " * _N + "x",
+ lambda: "gib " * (_N // 4),
+ lambda: "gib\n" * (_N // 4) + "aufgabe",
+ ],
+ ids=["one-long-gap", "many-leads", "many-lines"],
+)
+def test_fleet_brief_search_pathological(build: Callable[[], str]) -> None:
+ text = build()
+ _fast(lambda: intent._fleet_brief_search(text))
diff --git a/tests/unit/brain/test_regex_linear_time.py b/tests/unit/brain/test_regex_linear_time.py
new file mode 100644
index 0000000000..17020e6a68
--- /dev/null
+++ b/tests/unit/brain/test_regex_linear_time.py
@@ -0,0 +1,238 @@
+"""Brain-side matchers stay linear on long, hostile input.
+
+CodeQL flagged these patterns as polynomial ReDoS (py/polynomial-redos): user
+utterances and LLM output reach them unbounded. Each test pins the normal
+behaviour AND a pathological input of ~50k characters that must finish well
+under a second.
+""" # i18n-allow: quoted spoken input in the cases below
+
+from __future__ import annotations
+
+import re
+import time
+from collections.abc import Callable
+
+import pytest
+
+from jarvis.brain import ack_generator, local_outcome_gate, mission_command_gate, output_filter
+
+_BUDGET_S = 1.0
+_N = 50_000
+
+
+def _fast(fn: Callable[[], object]) -> None:
+ start = time.perf_counter()
+ fn()
+ assert time.perf_counter() - start < _BUDGET_S
+
+
+# --- ack_generator ----------------------------------------------------------
+
+
+ ("utterance", "expected"),
+ [
+ ("halt", True),
+ ("Stop please!", True),
+ ("leiser bitte .", True),
+ ("please stop talking now", True),
+ ("stop the music", False),
+ ("halt die Klappe", True),
+ ("lauter Applaus war zu hoeren", False),
+ ],
+)
+def test_voice_control_normal(utterance: str, expected: bool) -> None:
+ assert ack_generator.is_voice_control_utterance(utterance) is expected
+
+
+def test_voice_control_pathological() -> None:
+ _fast(lambda: ack_generator.is_voice_control_utterance("halt" + " " * _N + "x"))
+
+
+# --- mission_command_gate ---------------------------------------------------
+
+
+ ("text", "intent"),
+ [
+ ("brich die mission ab", "cancel"),
+ ("brich das jetzt ab", "cancel"),
+ ("status?", "status"),
+ ("jarvis, wie weit?", "status"),
+ ("wie weit ist berlin", None),
+ ("what's the status", "status"),
+ ],
+)
+def test_mission_command_normal(text: str, intent: str | None) -> None:
+ match = mission_command_gate.match_mission_command(text)
+ assert (match.intent if match else None) == intent
+
+
+def test_status_en_keeps_final_line_break_quirk() -> None:
+ # The EN arm ends in \b, which only holds at the '$' in front of a final
+ # line break — the rewrite must keep that exact behaviour.
+ pattern = mission_command_gate._STATUS_PATTERN_EN
+ assert pattern.search("status\n") is not None
+ assert pattern.search("status") is not None
+ assert pattern.search("status now") is None
+
+
+ "build",
+ [
+ lambda: "brich das" + " " * _N + "x",
+ lambda: "status" + " " * _N + "x",
+ lambda: "wie weit" + " " * _N + "x",
+ ],
+ ids=["cancel", "status", "how-far"],
+)
+def test_mission_command_pathological(build: Callable[[], str]) -> None:
+ text = build()
+ for pattern in (
+ mission_command_gate._CANCEL_PATTERN_DE,
+ mission_command_gate._STATUS_PATTERN_DE,
+ mission_command_gate._STATUS_PATTERN_EN,
+ ):
+ _fast(lambda pattern=pattern: pattern.search(text))
+
+
+# --- output_filter ----------------------------------------------------------
+
+# The original patterns, kept here as the reference the linear rewrites must
+# reproduce on short inputs.
+_FUNCTION_CALLS_REFERENCE = re.compile(
+ r"<function_calls>.*?</function_calls>", re.DOTALL | re.IGNORECASE
+)
+_UNICODE_DASH_REFERENCE = re.compile(r"\s*[—–]\s*")
+_DOUBLE_HYPHEN_REFERENCE = re.compile(r"\s+-{2,}\s+")
+_QUOTED_LITERAL_REFERENCE = re.compile(
+ r"""(?<!\w)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`[^`]*`)"""
+)
+
+
+ "text",
+ [
+ "a <function_calls>x</function_calls> b",
+ "<function_calls>1</FUNCTION_CALLS> mid <function_calls>2</function_calls> end",
+ "<function_calls> unclosed",
+ "no tags at all",
+ "</function_calls> then <function_calls> open",
+ ],
+)
+def test_strip_function_call_blocks_matches_pattern(text: str) -> None:
+ expected = _FUNCTION_CALLS_REFERENCE.sub("", text)
+ assert output_filter._strip_function_call_blocks(text) == expected
+
+
+ "build",
+ [
+ lambda: "x</function_calls>" + "<function_calls>" * (_N // 16),
+ lambda: "<function_calls>" + "<" * _N,
+ lambda: ("<function_calls>" + "<" * 100 + "</function_calls>") * 400,
+ ],
+ ids=["unclosed-openers", "opener-then-brackets", "many-blocks"],
+)
+def test_strip_function_call_blocks_pathological(build: Callable[[], str]) -> None:
+ text = build()
+ _fast(lambda: output_filter._strip_function_call_blocks(text))
+
+
+ "text",
+ [
+ "Fine — thanks",
+ "a — — b",
+ " –x— ",
+ "a\n — \tb",
+ "none",
+ "That is -- as I said -- fine",
+ "a -- -- b",
+ "a ---x -- y",
+ " -- ",
+ "x --\n-- y",
+ "-- a --",
+ ],
+)
+def test_dash_helpers_match_patterns(text: str) -> None:
+ unicode_expected = _UNICODE_DASH_REFERENCE.sub(", ", text)
+ hyphen_expected = _DOUBLE_HYPHEN_REFERENCE.sub(", ", text)
+ assert output_filter._collapse_unicode_dashes(text) == unicode_expected
+ assert output_filter._collapse_double_hyphens(text) == hyphen_expected
+
+
+ "build",
+ [lambda: "a" + " " * _N + "x", lambda: "a" + " -- " * (_N // 4), lambda: "—" * _N],
+ ids=["blank-run", "many-asides", "many-dashes"],
+)
+def test_dash_helpers_pathological(build: Callable[[], str]) -> None:
+ text = build()
+ _fast(lambda: output_filter._collapse_unicode_dashes(text))
+ _fast(lambda: output_filter._collapse_double_hyphens(text))
+
+
+ ("text", "expected"),
+ [
+ ("Fine — thanks", "Fine, thanks"),
+ ("A – B — C", "A, B, C"),
+ ("That is -- as I said -- fine", "That is, as I said, fine"),
+ ("A T-Shirt and an E-Mail", "A T-Shirt and an E-Mail"),
+ ],
+)
+def test_dash_scrub_normal(text: str, expected: str) -> None:
+ assert output_filter.scrub_for_voice(text, language="en").cleaned == expected
+
+
+ "build",
+ [lambda: "a" + " " * _N + "x", lambda: "a -" + " " * _N + "x"],
+ ids=["blank-run", "blank-run-after-hyphen"],
+)
+def test_dash_scrub_pathological(build: Callable[[], str]) -> None:
+ text = build()
+ _fast(lambda: output_filter.scrub_for_voice(text, language="en"))
+
+
+# --- local_outcome_gate -----------------------------------------------------
+
+
+def _mark(match: re.Match[str]) -> str:
+ return f"<{match.start()}:{match.group()}>"
+
+
+def _mark_literal(start: int, literal: str) -> str:
+ return f"<{start}:{literal}>"
+
+
+ "text",
+ [
+ 'create "my file.txt" now',
+ "don't touch 'a b' or `c d`",
+ 'escaped \\"x\\" and "y"',
+ '"unclosed \\" and "closed"',
+ "it's 'odd",
+ "a\\\n'x' `y",
+ ],
+)
+def test_sub_quoted_literals_matches_pattern(text: str) -> None:
+ expected = _QUOTED_LITERAL_REFERENCE.sub(_mark, text)
+ assert local_outcome_gate._sub_quoted_literals(_mark_literal, text) == expected
+
+
+ "build",
+ [lambda: '"' + '\\"' * (_N // 2), lambda: "'" + "\\'" * (_N // 2), lambda: "`" * _N + "a"],
+ ids=["double", "single", "backtick"],
+)
+def test_sub_quoted_literals_pathological(build: Callable[[], str]) -> None:
+ text = build()
+ _fast(lambda: local_outcome_gate._sub_quoted_literals(_mark_literal, text))
+
+
+def test_local_outcome_mandate_escaped_quote_run() -> None:
+ text = "create a folder " + '"' + '\\"' * (_N // 2)
+ _fast(lambda: local_outcome_gate.resolve_local_outcome_mandate(text))
diff --git a/tests/unit/ci/test_privacy_pre_push.py b/tests/unit/ci/test_privacy_pre_push.py
index c96f107b70..2ae21aa812 100644
--- a/tests/unit/ci/test_privacy_pre_push.py
+++ b/tests/unit/ci/test_privacy_pre_push.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import importlib.util
import io
+import json
import re
import sys
from pathlib import Path
@@ -238,6 +239,20 @@ class TestScanTextForSecrets:
text = f"OPENAI_API_KEY = '{_REAL_OPENAI}'\n"
assert gate.scan_text_for_secrets("config.py", text, {}, set()) == []
+ def test_finding_carries_its_line_number(self):
+ text = f"# header\n\nOPENAI_API_KEY = '{_REAL_OPENAI}'\n"
+ findings = gate.scan_text_for_secrets("config.py", text, _COMPILED, set())
+ assert findings[0]["line"] == 3
+
+ def test_description_never_contains_the_secret(self):
+ text = f"# header\nOPENAI_API_KEY = '{_REAL_OPENAI}'\n"
+ finding = gate.scan_text_for_secrets("config.py", text, _COMPILED, set())[0]
+ described = gate.describe_secret_finding(finding)
+ assert _REAL_OPENAI not in described
+ assert _REAL_OPENAI[:8] not in described
+ assert "config.py:2" in described
+ assert "openai_legacy" in described
+
# --------------------------------------------------------------------------- #
# main() orchestration — git/IO monkeypatched so the suite stays hermetic
@@ -333,3 +348,39 @@ class TestMain:
)
rc = gate.main(["prog", "origin", "url"], stdin)
assert rc == 1
+
+
+# --------------------------------------------------------------------------- #
+# strip_and_scan scan report never carries the secret itself
+# --------------------------------------------------------------------------- #
+class TestScanReportHidesSecrets:
+ def test_report_and_stderr_carry_location_not_value(self, tmp_path, capsys):
+ tree = tmp_path / "tree"
+ tree.mkdir()
+ (tree / "config.py").write_text(
+ f"# header\nOPENAI_API_KEY = '{_REAL_OPENAI}'\n", encoding="utf-8"
+ )
+ skill_dir = tmp_path / "skill"
+ skill_dir.mkdir()
+ report = tmp_path / "report.json"
+
+ rc = _SAS.main(
+ [
+ "scan",
+ "--tree",
+ str(tree),
+ "--skill-dir",
+ str(skill_dir),
+ "--report",
+ str(report),
+ ]
+ )
+
+ assert rc == 2
+ body = report.read_text(encoding="utf-8")
+ assert _REAL_OPENAI not in body
+ assert _REAL_OPENAI not in capsys.readouterr().err
+ finding = next(b for b in json.loads(body)["blocking"] if b["kind"] == "secret")
+ assert finding["path"] == "config.py"
+ assert finding["line"] == 2
+ assert finding["pattern"] == "openai_legacy"
diff --git a/tests/unit/contacts/test_email_regex_linear_time.py b/tests/unit/contacts/test_email_regex_linear_time.py
new file mode 100644
index 0000000000..70cbbe1190
--- /dev/null
+++ b/tests/unit/contacts/test_email_regex_linear_time.py
@@ -0,0 +1,39 @@
+"""The contact e-mail check stays linear on long, hostile input.
+
+CodeQL py/polynomial-redos: ``[^@\\s]+\\.[^@\\s]+`` could split a long dotted
+domain at every dot before failing, and vCard files are untrusted input.
+"""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+from jarvis.contacts.store import _EMAIL_RE
+
+
+ ("value", "expected"),
+ [
+ ("[email protected]", True),
+ ("[email protected]", True),
+ ("[email protected]", True),
+ ("[email protected]", True),
+ ("[email protected]", False),
+ ("a@bc.", False),
+ ("a@bc", False),
+ ("a [email protected]", False),
+ ("a@[email protected]", False),
+ ("@b.c", False),
+ ],
+)
+def test_email_normal(value: str, expected: bool) -> None:
+ assert bool(_EMAIL_RE.match(value)) is expected
+
+
+def test_email_pathological() -> None:
+ value = "!@!." + "!." * 25_000 + "@"
+ start = time.perf_counter()
+ assert _EMAIL_RE.match(value) is None
+ assert time.perf_counter() - start < 1.0
diff --git a/tests/unit/contacts/test_store.py b/tests/unit/contacts/test_store.py
index 68816320b9..62a27246b2 100644
--- a/tests/unit/contacts/test_store.py
+++ b/tests/unit/contacts/test_store.py
@@ -313,3 +313,15 @@ def test_primary_helpers_none_when_empty(store: ContactStore) -> None:
c = store.upsert(name="NoContactInfo")
assert c.primary_email is None
assert c.primary_phone is None
+
+
[email protected]("slug", ["../escape", "a/b", "C:escape", "sub\\..\\..\\escape", ""])
+def test_hostile_slug_never_leaves_contacts_dir(tmp_path: Path, slug: str) -> None:
+ base = tmp_path / "contacts"
+ base.mkdir()
+ outside = tmp_path / "escape.md"
+ outside.write_text("---\nidentity:\n name: Outside\n---\n", encoding="utf-8")
+ store = ContactStore(base_dir=base)
+ assert store.get(slug) is None
+ assert store.delete(slug) is False
+ assert outside.exists()
diff --git a/tests/unit/contacts/test_vcard.py b/tests/unit/contacts/test_vcard.py
index a946bba2ac..da636d4e67 100644
--- a/tests/unit/contacts/test_vcard.py
+++ b/tests/unit/contacts/test_vcard.py
@@ -188,3 +188,18 @@ def test_import_drops_invalid_values_but_keeps_the_record(store: ContactStore) -
assert c is not None
assert c.emails == ["[email protected]"]
assert c.phones == ["+491511"]
+
+
+def test_skipped_record_keeps_personal_data_out_of_the_log(
+ store: ContactStore, caplog: pytest.LogCaptureFixture
+) -> None:
+ records = [{"name": "Private Person", "birthday": "1990-99-99"}]
+ with caplog.at_level("WARNING", logger="jarvis.contacts.vcard"):
+ stats = import_records(store, records)
+ assert stats["skipped"] == 1
+ # The caller still learns which card failed and why ...
+ assert stats["errors"] and "Private Person" in stats["errors"][0]
+ # ... but the app log carries no name and no field value.
+ assert "skipped a record" in caplog.text
+ assert "Private Person" not in caplog.text
+ assert "1990-99-99" not in caplog.text
diff --git a/tests/unit/core/test_admin_password.py b/tests/unit/core/test_admin_password.py
new file mode 100644
index 0000000000..71861a3116
--- /dev/null
+++ b/tests/unit/core/test_admin_password.py
@@ -0,0 +1,59 @@
+"""Admin password hashing: salted scrypt, legacy SHA-256 still accepted."""
+
+from __future__ import annotations
+
+from jarvis.core.admin_password import (
+ check_admin_pass,
+ hash_admin_password,
+ is_legacy_hash,
+ verify_admin_password,
+)
+from jarvis.core.config import SecurityConfig
+
+# SHA-256 hex of "legacy-pass" -- the pre-scrypt stored format.
+_LEGACY = "c4ebc632c03529cf9f121d07055ee260606f7907540be42424cd2af15a0bf342"
+
+
+def test_new_hash_is_salted_scrypt() -> None:
+ first = hash_admin_password("hunter2")
+ second = hash_admin_password("hunter2")
+ assert first.startswith("scrypt$")
+ assert first != second # random salt
+ assert "hunter2" not in first
+ assert not is_legacy_hash(first)
+
+
+def test_verify_accepts_right_and_rejects_wrong_password() -> None:
+ stored = hash_admin_password("hunter2")
+ assert verify_admin_password("hunter2", stored)
+ assert not verify_admin_password("hunter3", stored)
+
+
+def test_empty_inputs_lock_admin_mode() -> None:
+ stored = hash_admin_password("x")
+ assert not verify_admin_password("", stored)
+ assert not verify_admin_password(None, stored)
+ assert not verify_admin_password("x", "")
+ assert not check_admin_pass("x", None)
+
+
+def test_legacy_sha256_hash_still_verifies() -> None:
+ assert is_legacy_hash(_LEGACY)
+ assert verify_admin_password("legacy-pass", _LEGACY)
+ assert verify_admin_password("legacy-pass", _LEGACY.upper())
+ assert not verify_admin_password("other", _LEGACY)
+
+
+def test_malformed_or_hostile_hash_is_rejected() -> None:
+ assert not verify_admin_password("x", "scrypt$abc$8$1$00$00")
+ assert not verify_admin_password("x", "bcrypt$whatever")
+ # Work factor far above the cap must not be computed.
+ assert not verify_admin_password("x", "scrypt$1073741824$8$1$00ff$00ff")
+ assert not verify_admin_password("x", "scrypt$16384$8$1$$")
+
+
+def test_check_admin_pass_reads_security_config() -> None:
+ cfg = SecurityConfig(admin_password_hash=hash_admin_password("pw"))
+ assert check_admin_pass("pw", cfg)
+ assert not check_admin_pass("nope", cfg)
+ assert not check_admin_pass("pw", SecurityConfig())
diff --git a/tests/unit/core/test_http_guard.py b/tests/unit/core/test_http_guard.py
index 2672c3df54..17f40e997a 100644
--- a/tests/unit/core/test_http_guard.py
+++ b/tests/unit/core/test_http_guard.py
@@ -11,7 +11,13 @@ from __future__ import annotations
import httpx
import pytest
-from jarvis.core.http_guard import InsecureRedirect, https_only, https_only_async
+from jarvis.core.http_guard import (
+ BlockedDestination,
+ InsecureRedirect,
+ https_only,
+ https_only_async,
+ public_only_async,
+)
def _redirecting(target: str) -> httpx.MockTransport:
@@ -75,3 +81,71 @@ def test_sync_client_guard_refuses_too() -> None:
) as client:
with pytest.raises(InsecureRedirect):
client.get("https://start.example/skill.md")
+
+
+# --------------------------------------------------------------------------
+# public_only_async — a user-pasted URL may be http, but never non-public
+# --------------------------------------------------------------------------
+
+
+def _public_redirecting(target: str) -> httpx.MockTransport:
+ """http://8.8.8.8 (a literal public address, no DNS) redirects to target."""
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ if request.url.host == "8.8.8.8":
+ return httpx.Response(302, headers={"location": target})
+ return httpx.Response(200, text="landed")
+
+ return httpx.MockTransport(handler)
+
+
+ "url",
+ [
+ "http://127.0.0.1:8765/api/anything",
+ "http://localhost:8765/api/anything",
+ "http://169.254.169.254/latest/meta-data/",
+ "http://192.168.1.1/admin",
+ "http://[::1]/",
+ "http://[::ffff:127.0.0.1]/",
+ ],
+)
+async def test_public_only_refuses_non_public_first_hop(url: str) -> None:
+ async with httpx.AsyncClient(
+ transport=_public_redirecting("https://1.1.1.1/x"),
+ **public_only_async(schemes=("http", "https")),
+ ) as client:
+ with pytest.raises(BlockedDestination):
+ await client.get(url)
+
+
+async def test_public_only_refuses_a_redirect_into_the_lan() -> None:
+ async with httpx.AsyncClient(
+ transport=_public_redirecting("http://10.0.0.5/secret"),
+ follow_redirects=True,
+ **public_only_async(schemes=("http", "https")),
+ ) as client:
+ with pytest.raises(httpx.HTTPError):
+ await client.get("http://8.8.8.8/skill.md")
+
+
+async def test_public_only_follows_a_public_redirect() -> None:
+ async with httpx.AsyncClient(
+ transport=_public_redirecting("https://1.1.1.1/skill.md"),
+ follow_redirects=True,
+ **public_only_async(schemes=("http", "https")),
+ ) as client:
+ resp = await client.get("http://8.8.8.8/skill.md")
+ assert resp.text == "landed"
+
+
+async def test_public_only_default_is_https_only() -> None:
+ async with httpx.AsyncClient(
+ transport=_public_redirecting("https://1.1.1.1/x"), **public_only_async()
+ ) as client:
+ with pytest.raises(BlockedDestination):
+ await client.get("http://8.8.8.8/skill.md")
diff --git a/tests/unit/core/test_path_safety.py b/tests/unit/core/test_path_safety.py
new file mode 100644
index 0000000000..e1e42d911f
--- /dev/null
+++ b/tests/unit/core/test_path_safety.py
@@ -0,0 +1,51 @@
+"""Tests for jarvis.core.path_safety containment helpers."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from jarvis.core.path_safety import UnsafePathError, contained_path, is_safe_name, safe_child
+
+
[email protected]("name", ["a.md", "u0123abcd.webp", "My File-1_x.json", "figure-ab12.glb"])
+def test_plain_names_pass(name: str) -> None:
+ assert is_safe_name(name)
+
+
+ "name",
+ ["", ".", "..", ".hidden", "../x", "..\\x", "a/b", "a\\b", "C:x", "/etc/passwd", "a\nb"],
+)
+def test_unsafe_names_rejected(tmp_path: Path, name: str) -> None:
+ assert not is_safe_name(name)
+ with pytest.raises(UnsafePathError):
+ safe_child(tmp_path, name)
+
+
+def test_safe_child_stays_inside(tmp_path: Path) -> None:
+ target = safe_child(tmp_path, "note.md")
+ assert target.parent == tmp_path.resolve()
+
+
+def test_contained_path_allows_nested(tmp_path: Path) -> None:
+ assert contained_path(tmp_path, "a/b/c.txt") == (tmp_path / "a" / "b" / "c.txt").resolve()
+
+
[email protected]("rel", ["../escape.txt", "a/../../escape.txt"])
+def test_contained_path_rejects_traversal(tmp_path: Path, rel: str) -> None:
+ with pytest.raises(UnsafePathError):
+ contained_path(tmp_path / "root", rel)
+
+
+def test_contained_path_rejects_absolute_elsewhere(tmp_path: Path) -> None:
+ (tmp_path / "root").mkdir()
+ with pytest.raises(UnsafePathError):
+ contained_path(tmp_path / "root", str(tmp_path / "other.txt"))
+
+
+def test_contained_path_rejects_sibling_prefix(tmp_path: Path) -> None:
+ (tmp_path / "root").mkdir()
+ with pytest.raises(UnsafePathError):
+ contained_path(tmp_path / "root", str(tmp_path / "root-evil" / "x"))
diff --git a/tests/unit/dictation/test_polish_timeout_ramp.py b/tests/unit/dictation/test_polish_timeout_ramp.py
index 7e4d124bc0..9abd886b4d 100644
--- a/tests/unit/dictation/test_polish_timeout_ramp.py
+++ b/tests/unit/dictation/test_polish_timeout_ramp.py
@@ -36,6 +36,10 @@ from jarvis.dictation import polish
from jarvis.dictation.polish import polish_transcript
from jarvis.dictation.polish_client import POLISH_FAMILIES, PolishFamily
+# The deadline is a difference of monotonic clock readings, so an exact budget
+# can come back a few ULPs above its ceiling (1.2000000000007 <= 1.2 fails).
+_FLOAT_SLACK = 1e-9
+
pytestmark = pytest.mark.asyncio
GROQ: PolishFamily = POLISH_FAMILIES[0]
@@ -119,7 +123,7 @@ async def test_a_short_dictation_keeps_the_configured_ceiling(
# The walk hands the client the time REMAINING, so a few milliseconds of
# our own work are legitimately missing; what must not happen is the
# budget growing.
- assert 1.0 < deadline <= 1.2
+ assert 1.0 < deadline <= 1.2 + _FLOAT_SLACK
async def test_a_long_dictation_is_given_more_time_than_a_short_one(
@@ -138,7 +142,7 @@ async def test_a_long_dictation_is_given_more_time_than_a_short_one(
# 60 words = 35 over the free allowance, 15 ms each on top of 1200 ms, and
# still short of the 2000 ms cap — so this asserts the RAMP rather than
# the ceiling the next test owns.
- assert 1.5 < long <= 1.725
+ assert 1.5 < long <= 1.725 + _FLOAT_SLACK
async def test_the_extra_time_stops_at_the_configured_maximum(
@@ -153,7 +157,7 @@ async def test_the_extra_time_stops_at_the_configured_maximum(
monkeypatch, 5000, _Cfg(polish_timeout_ms=1200, polish_timeout_max_ms=2500)
)
- assert 2.3 < deadline <= 2.5
+ assert 2.3 < deadline <= 2.5 + _FLOAT_SLACK
async def test_a_maximum_at_the_base_switches_the_ramp_off(
@@ -169,7 +173,7 @@ async def test_a_maximum_at_the_base_switches_the_ramp_off(
monkeypatch, 800, _Cfg(polish_timeout_ms=900, polish_timeout_max_ms=900)
)
- assert 0.7 < deadline <= 0.9
+ assert 0.7 < deadline <= 0.9 + _FLOAT_SLACK
async def test_a_maximum_below_the_base_never_shortens_the_base(
@@ -186,7 +190,7 @@ async def test_a_maximum_below_the_base_never_shortens_the_base(
monkeypatch, 800, _Cfg(polish_timeout_ms=1500, polish_timeout_max_ms=400)
)
- assert 1.3 < deadline <= 1.5
+ assert 1.3 < deadline <= 1.5 + _FLOAT_SLACK
async def test_an_explicit_override_is_never_ramped(
@@ -202,7 +206,7 @@ async def test_an_explicit_override_is_never_ramped(
await polish_transcript(_words(900), language="en", cfg=_Cfg(), timeout_s=0.5)
- assert client.calls and 0 < client.calls[0] <= 0.5
+ assert client.calls and 0 < client.calls[0] <= 0.5 + _FLOAT_SLACK
async def test_a_config_that_never_heard_of_the_maximum_still_ramps(
diff --git a/tests/unit/platform/test_open_path.py b/tests/unit/platform/test_open_path.py
index 3ba378271a..b853d8b51b 100644
--- a/tests/unit/platform/test_open_path.py
+++ b/tests/unit/platform/test_open_path.py
@@ -129,6 +129,29 @@ def test_open_file_with_xdg_open_linux_opens_file():
assert argv[0] == "xdg-open" and argv[1] == "/out/report.md"
+def test_open_file_with_startfile_quotes_cmd_metacharacters(monkeypatch):
+ """A '&' in a file name must stay inside quotes, never start a second command."""
+ launched: list[object] = []
+ monkeypatch.setattr(op, "detect_capabilities", lambda: _caps())
+ monkeypatch.setattr(op.subprocess, "Popen", lambda cmd, **kw: launched.append(cmd))
+
+ ok = op.open_file_with(
+ Path(r"C:\out\a&calc.md"), "startfile", r"C:\links\Editor.lnk"
+ )
+
+ assert ok is True
+ assert launched == [r'cmd /c start "" "C:\links\Editor.lnk" "C:\out\a&calc.md"']
+
+
+def test_open_file_with_startfile_refuses_a_quote(monkeypatch):
+ launched: list[object] = []
+ monkeypatch.setattr(op, "detect_capabilities", lambda: _caps())
+ monkeypatch.setattr(op.subprocess, "Popen", lambda cmd, **kw: launched.append(cmd))
+
+ assert op.open_file_with(Path('/x/a" & calc "b.md'), "startfile", "app") is False
+ assert launched == []
+
+
def test_open_file_with_headless_is_noop():
with patch.object(op, "detect_capabilities", return_value=_caps(display=False)), \
patch.object(op.subprocess, "Popen") as popen:
diff --git a/tests/unit/plugins/tool/test_youtube_music_rest.py b/tests/unit/plugins/tool/test_youtube_music_rest.py
index 55d8b697c8..2e3697762f 100644
--- a/tests/unit/plugins/tool/test_youtube_music_rest.py
+++ b/tests/unit/plugins/tool/test_youtube_music_rest.py
@@ -879,3 +879,17 @@ async def test_execute_routes_and_validates():
assert not res.success and "unknown action" in res.error
res = await tool.execute({"action": "now_playing"}, ctx=None) # type: ignore[arg-type]
assert res.success and res.output["track"] == "Karma Police"
+
+
+def test_activation_link_must_be_a_google_console_host() -> None:
+ """The link is shown to the user to click, so its host is parsed, not grepped."""
+ from jarvis.plugins.tool.youtube_music_rest import _is_google_console_url
+
+ assert _is_google_console_url(
+ "https://console.developers.google.com/apis/api/youtube.googleapis.com/overview"
+ )
+ assert _is_google_console_url("https://console.cloud.google.com/apis/library")
+ assert not _is_google_console_url("https://console.evil.example/google.com/")
+ assert not _is_google_console_url("https://console.google.com.evil.example/x")
+ assert not _is_google_console_url("https://[email protected]/")
+ assert not _is_google_console_url("http://console.cloud.google.com/")
diff --git a/tests/unit/screen_context/test_unsafe_regex_detector_linear_time.py b/tests/unit/screen_context/test_unsafe_regex_detector_linear_time.py
new file mode 100644
index 0000000000..82e04b96b8
--- /dev/null
+++ b/tests/unit/screen_context/test_unsafe_regex_detector_linear_time.py
@@ -0,0 +1,49 @@
+"""The custom-pattern safety detector is not catastrophic itself.
+
+CodeQL py/redos: a group body read a backslash either as an escape or as a
+plain character, so ``(\\'\\'\\'…`` had exponentially many parses. The body now
+reads a backslash only as the start of an escape pair.
+"""
+
+from __future__ import annotations
+
+import time
+
+import pytest
+
+from jarvis.screen_context.redaction import _UNSAFE_CUSTOM_REGEX_RE, validate_pattern_source
+
+
+ ("source", "unsafe"),
+ [
+ (r"(a+)+", True),
+ (r"(a*b)*", True),
+ (r"(ab{2,})+", True),
+ (r"(a|b)+", True),
+ (r"(a|b){3}", True),
+ (r"(\d+)\1", True),
+ (r"(?P<x>a)(?P=x)", True),
+ (r"(\)+)+", True),
+ (r"CUST-[0-9]+", False),
+ (r"(ab)+", False),
+ (r"(a{b)+", False),
+ (r"(x+\)+y)", False),
+ (r"\(a+\)+", False),
+ ],
+)
+def test_unsafe_detector_normal(source: str, unsafe: bool) -> None:
+ assert bool(_UNSAFE_CUSTOM_REGEX_RE.search(source)) is unsafe
+
+
+ "prefix",
+ ["(", "(*", "(|", "(a+"],
+ ids=["open", "open-star", "open-bar", "open-quant"],
+)
+def test_unsafe_detector_pathological(prefix: str) -> None:
+ source = prefix + "\\'" * 248
+ start = time.perf_counter()
+ _UNSAFE_CUSTOM_REGEX_RE.search(source)
+ validate_pattern_source(source)
+ assert time.perf_counter() - start < 1.0
diff --git a/tests/unit/telephony/test_outbound.py b/tests/unit/telephony/test_outbound.py
index 9099c68203..c0c79b31e3 100644
--- a/tests/unit/telephony/test_outbound.py
+++ b/tests/unit/telephony/test_outbound.py
@@ -65,6 +65,34 @@ _VALID = {
}
+def test_place_call_sdk_error_is_classified_not_echoed(monkeypatch):
+ """Twilio's raw REST error body never reaches the exception text (AP-34)."""
+ from jarvis.telephony.outbound import place_call
+
+ class _RejectingCalls:
+ def create(self, **kwargs): # noqa: ANN003, ANN201
+ raise RuntimeError("HTTP 401 error: Unable to create record: body-with-details")
+
+ class _RejectingClient:
+ def __init__(self, account_sid: str, auth_token: str) -> None:
+ self.calls = _RejectingCalls()
+
+ # A stand-in ``twilio.rest`` module, so this runs without the telephony extra.
+ import types # noqa: PLC0415
+
+ fake_rest = types.ModuleType("twilio.rest")
+ fake_rest.Client = _RejectingClient # type: ignore[attr-defined]
+ fake_pkg = types.ModuleType("twilio")
+ fake_pkg.rest = fake_rest # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "twilio", fake_pkg)
+ monkeypatch.setitem(sys.modules, "twilio.rest", fake_rest)
+ with pytest.raises(TelephonyProvisionError) as exc:
+ place_call(to="+4915112345678", opening="Hi", **_VALID)
+ assert exc.value.status == "bad_key"
+ assert "body-with-details" not in str(exc.value)
+ assert str(exc.value).startswith("Outbound call failed")
+
+
# --------------------------------------------------------------------------- #
# place_call — Contract 2
# --------------------------------------------------------------------------- #
diff --git a/tests/unit/telephony/test_routes.py b/tests/unit/telephony/test_routes.py
index 538c311ada..cdcccc5ab0 100644
--- a/tests/unit/telephony/test_routes.py
+++ b/tests/unit/telephony/test_routes.py
@@ -199,9 +199,7 @@ def test_config_post_updates_live_shared_config_without_reload(
assert app.state.config.integrations.twilio.max_call_seconds == 120
-def test_credentials_post_updates_live_shared_config_sid(
- app, secret_store, fake_cfg, monkeypatch
-):
+def test_credentials_post_updates_live_shared_config_sid(app, secret_store, fake_cfg, monkeypatch):
monkeypatch.setattr(
"jarvis.core.config_writer.set_telephony_config",
lambda values, **kw: setattr(
@@ -239,10 +237,25 @@ def test_credentials_reports_partial_commit_when_sid_write_fails(
body = r.json()
assert body["token_saved"] is True
assert body["sid_saved"] is False
+ # The raw exception text stays in the server log, never in the response.
+ assert "disk full" not in body["error"]
+ assert body["error"].startswith("config write failed")
# The token really did land in the credential store despite the SID error.
assert secret_store["twilio_auth_token"] == "freshtoken"
+def test_outbound_route_hides_unexpected_exception_text(app, secret_store, monkeypatch):
+ def boom(**kwargs):
+ raise RuntimeError("C:/internal/path secret-ish detail")
+
+ monkeypatch.setattr("jarvis.telephony.outbound.place_call", boom)
+ with TestClient(app) as client:
+ r = client.post("/api/telephony/outbound", json={"to": "+4915112345678", "opening": "Hi"})
+ assert r.status_code == 409
+ assert "internal/path" not in r.json()["error"]
+ assert r.json()["error"].startswith("outbound call failed")
+
+
def test_calls_endpoint_returns_ring_buffer(app, secret_store):
from jarvis.telephony.status import CallRecord
diff --git a/tests/unit/ui/test_desktop_detached_windows.py b/tests/unit/ui/test_desktop_detached_windows.py
index d450ce1650..b7bd1cae24 100644
--- a/tests/unit/ui/test_desktop_detached_windows.py
+++ b/tests/unit/ui/test_desktop_detached_windows.py
@@ -527,7 +527,8 @@ def test_detach_route_surfaces_handler_failure_with_fallback() -> None:
body = response.json()
assert body["ok"] is False
- assert "RuntimeError" in body["reason"]
+ assert body["reason"] == "detach_failed"
+ assert "boom" not in str(body)
assert body["fallback_url"] == "/?view=chats&solo=1"
diff --git a/tests/unit/ui/test_error_text.py b/tests/unit/ui/test_error_text.py
new file mode 100644
index 0000000000..92620c5bd9
--- /dev/null
+++ b/tests/unit/ui/test_error_text.py
@@ -0,0 +1,45 @@
+"""Client-safe error text helpers (jarvis/ui/web/error_text.py)."""
+
+from __future__ import annotations
+
+import logging
+
+import pytest
+
+from jarvis.ui.web.error_text import LOG_HINT, diagnostic_text, internal_error
+
+
+def test_internal_error_hides_exception_and_logs_traceback(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ error = RuntimeError("C:/secret/internal/path")
+ try:
+ raise error
+ except RuntimeError as exc:
+ with caplog.at_level(logging.WARNING, logger="jarvis.ui.web.error_text"):
+ message = internal_error("config write", exc)
+
+ assert message == f"config write failed. {LOG_HINT}"
+ assert "internal/path" not in message
+ record = caplog.records[-1]
+ assert record.exc_info is not None
+ assert record.exc_info[1] is error
+
+
+def test_diagnostic_text_is_one_line_redacted_and_capped() -> None:
+ exc = FileNotFoundError(
+ "npx not found api_key=sk-ant-abcdefghijklmnopqrstuvwxyz0123\n"
+ "Traceback (most recent call last)"
+ )
+ text = diagnostic_text(exc)
+ assert text.startswith("FileNotFoundError: npx not found")
+ assert "Traceback" not in text
+ assert "sk-ant-abcdefghijklmnopqrstuvwxyz0123" not in text
+
+ long_text = diagnostic_text(RuntimeError("no such file " * 100), max_chars=50)
+ assert len(long_text) == 51
+ assert long_text.endswith("…")
+
+
+def test_diagnostic_text_without_message_is_the_type_name() -> None:
+ assert diagnostic_text(TimeoutError()) == "TimeoutError"
diff --git a/tests/unit/ui/test_wake_word_route.py b/tests/unit/ui/test_wake_word_route.py
index 45f2d8b631..562834aa55 100644
--- a/tests/unit/ui/test_wake_word_route.py
+++ b/tests/unit/ui/test_wake_word_route.py
@@ -282,6 +282,8 @@ def test_activation_reports_a_failed_persist_instead_of_500(monkeypatch) -> None
assert body["ok"] is True
assert body["persisted"] is False
assert "could not be saved" in body["message"]
+ # The raw exception text stays in the server log, never in the response.
+ assert "invalid continuation" not in body["message"]
# The switch still reached the running pipeline — it just will not survive
# a restart, which is exactly what `persisted` tells the caller.
assert pipe.activation is True
diff --git a/tests/unit/ui/test_wallpaper_routes.py b/tests/unit/ui/test_wallpaper_routes.py
index 09d7e4e765..4c93bc6959 100644
--- a/tests/unit/ui/test_wallpaper_routes.py
+++ b/tests/unit/ui/test_wallpaper_routes.py
@@ -352,7 +352,13 @@ def test_deleting_something_that_is_not_there_is_a_404(client: TestClient) -> No
@pytest.mark.parametrize(
"upload_id",
- ["../../../etc/passwd", "01-cinematic-photoreal-01", "u00", "uZZZZZZZZZZZZZZZZ"],
+ [
+ "../../../etc/passwd",
+ "01-cinematic-photoreal-01",
+ "u00",
+ "uZZZZZZZZZZZZZZZZ",
+ "u0123456789abcdef%0A",
+ ],
)
def test_malformed_upload_ids_are_refused(client: TestClient, upload_id: str) -> None:
assert client.get(f"/api/wallpapers/uploads/{upload_id}/full").status_code == 404
diff --git a/tests/unit/ui/web/test_society_figure_routes.py b/tests/unit/ui/web/test_society_figure_routes.py
index 8e4eb80695..63531a8b89 100644
--- a/tests/unit/ui/web/test_society_figure_routes.py
+++ b/tests/unit/ui/web/test_society_figure_routes.py
@@ -98,3 +98,12 @@ def test_a_figure_facing_the_wrong_way_is_refused_with_the_reason(
def test_serving_never_leaves_the_figures_folder(client: TestClient):
assert client.get("/api/society/figures/..%2F..%2Fjarvis.toml").status_code == 404
assert client.get("/api/society/figures/nope.glb").status_code == 404
+
+
+def test_hostile_names_never_reach_a_file_outside(client: TestClient, tmp_path: Path):
+ outside = tmp_path / "outside.glb"
+ outside.write_bytes(b"glTF-outside")
+ for name in ("..%5Coutside.glb", "C%3Aoutside.glb", ".hidden.glb", "..glb"):
+ assert client.get(f"/api/society/figures/{name}").status_code == 404
+ assert client.delete(f"/api/society/figures/{name}").status_code == 404
+ assert outside.exists()
diff --git a/tests/unit/workspace/test_custom_clis.py b/tests/unit/workspace/test_custom_clis.py
index 3457b2909b..c0bcaeadf5 100644
--- a/tests/unit/workspace/test_custom_clis.py
+++ b/tests/unit/workspace/test_custom_clis.py
@@ -3,6 +3,7 @@
Every test runs against a temporary app-data directory, so nothing here can see
or damage the maintainer's own stored CLIs.
"""
+
from __future__ import annotations
import json
@@ -153,11 +154,7 @@ def test_a_hand_written_entry_cannot_shadow_a_built_in(isolated_store: Path) ->
isolated_store.mkdir(parents=True, exist_ok=True)
(isolated_store / "custom.json").write_text(
json.dumps(
- {
- "entries": [
- {"id": "codex", "display_name": "Impostor", "command": "impostor"}
- ]
- }
+ {"entries": [{"id": "codex", "display_name": "Impostor", "command": "impostor"}]}
),
encoding="utf-8",
)
@@ -190,9 +187,7 @@ def test_a_windows_path_survives_the_split() -> None:
("agy --model $MODEL", True),
],
)
-def test_shell_source_is_told_apart_from_an_argv(
- command: str, through_shell: bool
-) -> None:
+def test_shell_source_is_told_apart_from_an_argv(command: str, through_shell: bool) -> None:
assert custom_clis.needs_shell(command) is through_shell
@@ -357,6 +352,32 @@ def test_a_hand_edited_logo_path_cannot_escape_the_logo_directory(
assert custom_clis.logo_file("evil") is None
+def test_a_hand_edited_id_cannot_write_or_read_outside_the_logo_directory(
+ isolated_store: Path,
+) -> None:
+ """An id that is not a plain name never becomes a logo path."""
+ isolated_store.mkdir(parents=True, exist_ok=True)
+ (isolated_store / "custom.json").write_text(
+ json.dumps(
+ {
+ "entries": [
+ {
+ "id": "../escape",
+ "display_name": "Escape",
+ "command": "escape",
+ "logo": "escape.svg",
+ }
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+ with pytest.raises(custom_clis.CustomCliError):
+ custom_clis.set_logo("../escape", SVG, "mark.svg")
+ assert custom_clis.logo_file("../escape") is None
+ assert not (isolated_store / "escape.svg").exists()
+
+
def test_deleting_an_entry_takes_its_logo_with_it() -> None:
entry = custom_clis.create_custom_cli("Antigravity", "agy")
custom_clis.set_logo(entry.id, SVG, "mark.svg")