diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..9958547 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,20 @@ +.git +.gitignore +.gitattributes +*.md +frontend/node_modules +frontend/.cache +**/__pycache__ +**/*.pyc +**/*.pyo +.pytest_cache +.coverage +htmlcov/ +.env +.env.* +!.env.example +.idea/ +.vscode/ +*.swp +*.swo +.DS_Store diff --git a/docker-compose.yml b/docker-compose.yml index 67a3722..107121c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,6 +13,12 @@ services: OLLAMA_URL: "http://ollama:11434" OLLAMA_MODEL: "${OLLAMA_MODEL:-llama3.1}" SECRET_KEY: "${SECRET_KEY:-dev-secret-change-me}" + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/health')"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 30s db: image: postgres:16-alpine diff --git a/frontend/src/assets/editor-shared.css b/frontend/src/assets/editor-shared.css new file mode 100644 index 0000000..3041264 --- /dev/null +++ b/frontend/src/assets/editor-shared.css @@ -0,0 +1,544 @@ +/* ── Layout ── */ +.editor-page { + max-width: 1400px; + margin: 0 auto; + height: 100%; + display: flex; + flex-direction: column; + overflow: hidden; +} +.editor-header { + flex-shrink: 0; + display: flex; + flex-direction: column; + gap: 0.75rem; + padding: 1rem 1.5rem 0.5rem; + border-bottom: 1px solid var(--color-border); +} +.editor-body { + flex: 1; + min-height: 0; + display: flex; + overflow: hidden; +} +.editor-main { + flex: 1; + min-width: 0; + overflow-y: auto; + padding: 0.75rem 1.5rem 1.5rem; +} + +/* ── Toolbar & inputs ── */ +.toolbar { + display: flex; + gap: 0.5rem; + align-items: center; +} +.btn-back { + display: inline-flex; + align-items: center; + padding: 0.45rem 1rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + background: none; + color: var(--color-text-secondary); + text-decoration: none; + cursor: pointer; + font-size: 0.9rem; +} +.btn-back:hover { + border-color: var(--color-primary); + color: var(--color-primary); +} +.btn-save { + padding: 0.45rem 1rem; + background: var(--color-primary); + color: #fff; + border: none; + border-radius: var(--radius-sm); + cursor: pointer; +} +.btn-save:disabled { + opacity: 0.6; + cursor: default; +} +.btn-delete { + padding: 0.45rem 1rem; + background: var(--color-danger); + color: #fff; + border: none; + border-radius: var(--radius-sm); + cursor: pointer; +} +.btn-assist-toggle { + margin-left: auto; + padding: 0.4rem 0.9rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + background: none; + color: var(--color-text-secondary); + cursor: pointer; + font-size: 0.85rem; +} +.btn-assist-toggle.active { + background: color-mix(in srgb, var(--color-primary) 12%, transparent); + border-color: var(--color-primary); + color: var(--color-primary); +} +.title-input { + padding: 0.5rem 0.75rem; + border: 1px solid var(--color-input-border); + border-radius: var(--radius-sm); + font-size: 1.25rem; + font-weight: 600; + background: var(--color-bg-card); + color: var(--color-text); +} +.editor-tabs { + display: flex; + gap: 0; + border-bottom: 1px solid var(--color-border); +} +.tab { + padding: 0.45rem 1rem; + border: none; + background: none; + color: var(--color-text-secondary); + cursor: pointer; + font-size: 0.9rem; + border-bottom: 2px solid transparent; +} +.tab.active { + color: var(--color-primary); + border-bottom-color: var(--color-primary); +} +.preview-pane { + padding: 0.75rem; + border: 1px solid var(--color-input-border); + border-radius: var(--radius-sm); + min-height: 200px; + background: var(--color-bg-card); +} + +/* ── Tag suggestions ── */ +.tag-suggest-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.4rem; +} +.btn-suggest-tags { + padding: 0.3rem 0.7rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + background: var(--color-bg-card); + color: var(--color-text-secondary); + cursor: pointer; + font-size: 0.8rem; +} +.btn-suggest-tags:hover:not(:disabled) { + border-color: var(--color-primary); + color: var(--color-primary); +} +.btn-suggest-tags:disabled { + opacity: 0.6; + cursor: wait; +} +.tag-pill { + display: inline-flex; + align-items: center; + gap: 0.2rem; + padding: 0.2rem 0.55rem; + border: 1px solid var(--color-primary); + border-radius: 999px; + background: transparent; + color: var(--color-primary); + font-size: 0.8rem; + cursor: pointer; + transition: background 0.15s, color 0.15s; +} +.tag-pill:hover:not(:disabled) { + background: var(--color-primary); + color: #fff; +} +.tag-pill.applied { + background: var(--color-success, #2ecc71); + border-color: var(--color-success, #2ecc71); + color: #fff; + cursor: default; +} +.tag-check { + font-size: 0.7rem; +} +.btn-dismiss-tags { + padding: 0.1rem 0.4rem; + border: none; + background: none; + color: var(--color-text-muted); + cursor: pointer; + font-size: 1rem; + line-height: 1; +} +.btn-dismiss-tags:hover { + color: var(--color-text); +} + +/* ── Assist panel ── */ +.assist-panel { + width: 320px; + flex-shrink: 0; + border-left: 1px solid var(--color-border); + background: var(--color-bg-secondary); + display: flex; + flex-direction: column; + overflow: hidden; +} +.assist-panel-header { + flex-shrink: 0; + display: flex; + align-items: center; + gap: 0.5rem; + padding: 0.65rem 0.9rem; + border-bottom: 1px solid var(--color-border); +} +.assist-panel-title { + flex: 1; + font-size: 0.8rem; + font-weight: 700; + color: var(--color-text-secondary); + text-transform: uppercase; + letter-spacing: 0.05em; +} +.btn-proofread { + padding: 0.3rem 0.65rem; + font-size: 0.78rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + background: none; + color: var(--color-text-secondary); + cursor: pointer; +} +.btn-proofread:hover:not(:disabled) { + border-color: var(--color-primary); + color: var(--color-primary); +} +.btn-proofread:disabled { + opacity: 0.5; + cursor: default; +} +.btn-close-assist { + padding: 0.1rem 0.4rem; + border: none; + background: none; + color: var(--color-text-muted); + cursor: pointer; + font-size: 1rem; + line-height: 1; +} +.assist-panel-body { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: 0.75rem 0.9rem 1rem; + display: flex; + flex-direction: column; + gap: 0.6rem; +} + +/* Section list */ +.assist-sections-label { + font-size: 0.72rem; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--color-text-muted); + margin-bottom: 0.2rem; +} +.assist-sections { + border: 1px solid var(--color-input-border); + border-radius: var(--radius-sm); + background: var(--color-bg); + max-height: 200px; + overflow-y: auto; + flex-shrink: 0; +} +.assist-section-item { + padding: 0.35rem 0.7rem; + cursor: pointer; + font-size: 0.82rem; + border-left: 3px solid transparent; + color: var(--color-text); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} +.assist-section-item:hover { + background: var(--color-bg-secondary); +} +.assist-section-item.selected { + border-left-color: var(--color-primary); + background: var(--color-bg-secondary); + font-weight: 500; +} +.assist-empty, +.assist-hint { + padding: 0.6rem 0.7rem; + font-size: 0.82rem; + color: var(--color-text-muted); +} +.assist-target-preview { + font-size: 0.8rem; + color: var(--color-text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.assist-target-preview em { + font-style: normal; + color: var(--color-text); +} +.assist-instruction { + width: 100%; + padding: 0.5rem 0.65rem; + border: 1px solid var(--color-input-border); + border-radius: var(--radius-sm); + font-size: 0.88rem; + font-family: inherit; + resize: vertical; + background: var(--color-bg); + color: var(--color-text); + box-sizing: border-box; + min-height: 3.5rem; +} +.assist-input-actions { + display: flex; + gap: 0.5rem; +} +.btn-generate { + padding: 0.4rem 0.9rem; + background: var(--color-primary); + color: #fff; + border: none; + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.85rem; +} +.btn-generate:disabled { + opacity: 0.5; + cursor: default; +} +.btn-clear { + padding: 0.4rem 0.9rem; + background: none; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.85rem; + color: var(--color-text-secondary); +} + +/* Streaming */ +.assist-streaming-label { + font-size: 0.8rem; + color: var(--color-text-secondary); + font-style: italic; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.assist-preview-box { + padding: 0.65rem; + border: 1px solid var(--color-input-border); + border-radius: var(--radius-sm); + background: var(--color-bg); + font-size: 0.9rem; + max-height: 300px; + overflow-y: auto; +} +.typing-indicator { + color: var(--color-text-muted); + font-size: 0.75rem; + letter-spacing: 0.15em; + animation: blink 1s step-end infinite; +} +@keyframes blink { + 50% { opacity: 0; } +} + +/* Error */ +.assist-error { + padding: 0.5rem 0.75rem; + background: color-mix(in srgb, var(--color-danger) 10%, transparent); + border: 1px solid var(--color-danger); + border-radius: var(--radius-sm); + font-size: 0.85rem; + color: var(--color-danger); +} + +/* Review / diff */ +.assist-review-header { + display: flex; + align-items: center; + justify-content: space-between; + font-size: 0.8rem; + font-weight: 600; + color: var(--color-text-secondary); +} +.btn-toggle-view { + font-size: 0.75rem; + color: var(--color-primary); + background: none; + border: none; + cursor: pointer; + padding: 0; +} +.diff-view { + border: 1px solid var(--color-input-border); + border-radius: var(--radius-sm); + background: var(--color-bg); + font-size: 0.82rem; + font-family: monospace; + max-height: 340px; + overflow-y: auto; + padding: 0.4rem 0; +} +.diff-line { + display: flex; + align-items: baseline; + padding: 0.05rem 0.5rem; + line-height: 1.5; +} +.diff-delete { + background: color-mix(in srgb, var(--color-danger) 12%, transparent); + color: var(--color-danger); +} +.diff-insert { + background: color-mix(in srgb, var(--color-success) 12%, transparent); + color: var(--color-success); +} +.diff-equal { + color: var(--color-text-muted); +} +.diff-marker { + flex-shrink: 0; + width: 1rem; + text-align: center; + user-select: none; + font-weight: 700; +} +.diff-text { + flex: 1; + white-space: pre-wrap; + word-break: break-word; +} +.diff-empty { + padding: 0.5rem; + color: var(--color-text-muted); + font-style: italic; + font-size: 0.82rem; +} +.assist-actions { + display: flex; + gap: 0.5rem; +} +.btn-accept { + padding: 0.4rem 1rem; + background: var(--color-success); + color: #fff; + border: none; + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.85rem; +} +.btn-reject { + padding: 0.4rem 1rem; + background: none; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.85rem; + color: var(--color-text-secondary); +} + +/* ── Modal ── */ +.modal-overlay { + position: fixed; + inset: 0; + background: var(--color-overlay); + display: flex; + align-items: center; + justify-content: center; + z-index: 200; +} +.modal-card { + background: var(--color-bg-card); + border-radius: var(--radius-md); + padding: 1.5rem; + max-width: 400px; + width: 90%; + box-shadow: 0 8px 32px var(--color-shadow); +} +.modal-title { + margin: 0 0 0.5rem; + font-size: 1.1rem; +} +.modal-message { + margin: 0 0 1.25rem; + color: var(--color-text-secondary); + font-size: 0.95rem; +} +.modal-actions { + display: flex; + gap: 0.5rem; + justify-content: flex-end; +} +.modal-btn { + padding: 0.45rem 1rem; + border: 1px solid var(--color-border); + border-radius: var(--radius-sm); + background: var(--color-bg-card); + color: var(--color-text); + cursor: pointer; + font-size: 0.9rem; +} +.modal-btn-danger { + background: var(--color-danger); + color: #fff; + border-color: var(--color-danger); +} + +/* ── Floating inline assist button (teleported to body) ── */ +.inline-assist-btn { + position: fixed; + z-index: 100; + transform: translateX(-50%); + padding: 0.3rem 0.75rem; + background: var(--color-primary); + color: #fff; + border: none; + border-radius: var(--radius-sm); + cursor: pointer; + font-size: 0.8rem; + box-shadow: 0 2px 8px var(--color-shadow); + pointer-events: auto; +} + +/* ── Mobile ── */ +@media (max-width: 768px) { + .editor-body { + flex-direction: column; + } + .assist-panel { + width: auto; + flex: 0 0 45%; + border-left: none; + border-top: 1px solid var(--color-border); + border-radius: var(--radius-md) var(--radius-md) 0 0; + } + .editor-header { + padding: 0.75rem 1rem 0.5rem; + } + .editor-main { + padding: 0.5rem 1rem 1rem; + } +} diff --git a/frontend/src/components/TaskCard.vue b/frontend/src/components/TaskCard.vue index 4515be9..70cdf09 100644 --- a/frontend/src/components/TaskCard.vue +++ b/frontend/src/components/TaskCard.vue @@ -30,7 +30,8 @@ function goEdit() { function isOverdue(): boolean { if (!props.task.due_date || props.task.status === "done") return false; - return new Date(props.task.due_date) < new Date(new Date().toDateString()); + const today = new Date().toISOString().slice(0, 10); + return props.task.due_date < today; } diff --git a/frontend/src/components/TiptapEditor.vue b/frontend/src/components/TiptapEditor.vue index a6cd0e5..a971193 100644 --- a/frontend/src/components/TiptapEditor.vue +++ b/frontend/src/components/TiptapEditor.vue @@ -90,12 +90,24 @@ try { if (!selectedText) return; const md = lastEmittedMarkdown; - const idx = md.indexOf(selectedText); - if (idx !== -1) { + const fraction = from / (ed.state.doc.content.size || 1); + const estIdx = Math.floor(fraction * md.length); + + let bestIdx = -1; + let bestDist = Infinity; + let searchFrom = 0; + while (true) { + const idx = md.indexOf(selectedText, searchFrom); + if (idx === -1) break; + const dist = Math.abs(idx - estIdx); + if (dist < bestDist) { bestDist = dist; bestIdx = idx; } + searchFrom = idx + 1; + } + if (bestIdx !== -1) { emit("selectionChange", { text: selectedText, - start: idx, - end: idx + selectedText.length, + start: bestIdx, + end: bestIdx + selectedText.length, }); } }, diff --git a/frontend/src/composables/useAssist.ts b/frontend/src/composables/useAssist.ts index 4fbfdf1..d6a67a4 100644 --- a/frontend/src/composables/useAssist.ts +++ b/frontend/src/composables/useAssist.ts @@ -202,6 +202,7 @@ export function useAssist(body: Ref) { const currentSlice = body.value.slice(t.startOffset, t.endOffset); if (currentSlice !== t.text) { error.value = "The document changed since this suggestion was made. Please clear and try again."; + state.value = "idle"; return body.value; } } diff --git a/frontend/src/stores/chat.ts b/frontend/src/stores/chat.ts index 9b8cf1b..29a2dd6 100644 --- a/frontend/src/stores/chat.ts +++ b/frontend/src/stores/chat.ts @@ -378,7 +378,11 @@ export const useChatStore = defineStore("chat", () => { let attempts = 0; const MAX = 12; // up to ~60s of fast polling const timer = setInterval(async () => { - await fetchStatus(); + try { + await fetchStatus(); + } catch { + // best-effort polling + } attempts++; if (modelStatus.value === "loaded" || attempts >= MAX) { clearInterval(timer); diff --git a/frontend/src/utils/markdown.ts b/frontend/src/utils/markdown.ts index 8cc174e..124fa39 100644 --- a/frontend/src/utils/markdown.ts +++ b/frontend/src/utils/markdown.ts @@ -36,15 +36,23 @@ const headingRenderer = { marked.use({ renderer: headingRenderer }); +const PURIFY_OPTS_FULL = { + ADD_ATTR: ["data-tag", "data-title"], + FORCE_BODY: true, +}; + +const PURIFY_OPTS_PREVIEW = { + FORBID_TAGS: ["a", "img"], + FORCE_BODY: true, +}; + export function renderMarkdown(text: string): string { const stripped = stripFirstLineTags(text); const decoded = decodeEntities(stripped); const html = marked(decoded) as string; const withTags = linkifyTags(html); const withLinks = linkifyWikilinks(withTags); - const sanitized = DOMPurify.sanitize(withLinks, { - ADD_ATTR: ["data-tag", "data-title"], - }); + const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_FULL); // marked escapes ' to ' — replace after sanitization to ensure clean rendering return sanitized.replace(/'/g, "'"); } @@ -55,8 +63,6 @@ export function renderPreview(text: string): string { const html = marked(decoded) as string; const withTags = linkifyTags(html); const withLinks = linkifyWikilinks(withTags); - const sanitized = DOMPurify.sanitize(withLinks, { - FORBID_TAGS: ["a", "img"], - }); + const sanitized = DOMPurify.sanitize(withLinks, PURIFY_OPTS_PREVIEW); return sanitized.replace(/'/g, "'"); } diff --git a/frontend/src/utils/sectionParser.ts b/frontend/src/utils/sectionParser.ts index 1690297..b8241aa 100644 --- a/frontend/src/utils/sectionParser.ts +++ b/frontend/src/utils/sectionParser.ts @@ -42,8 +42,31 @@ function parseFallbackSections(body: string): MarkdownSection[] { const headingIndices = new Set( paragraphs.map((p, i) => isPseudoHeading(p.text) ? i : -1).filter(i => i >= 0) ); - if (headingIndices.size === 0) + if (headingIndices.size === 0) { + // No pseudo-headings — check if body is a bullet/numbered list. + // If so, treat each top-level item (no leading spaces) as a section. + const TOP_BULLET_RE = /^(?:[-*+]|\d+\.) /gm; + const bulletStarts: number[] = []; + let bm: RegExpExecArray | null; + while ((bm = TOP_BULLET_RE.exec(body)) !== null) { + bulletStarts.push(bm.index); + } + if (bulletStarts.length > 1) { + return bulletStarts.map((startIdx, i) => { + const endIdx = i + 1 < bulletStarts.length ? bulletStarts[i + 1] : body.length; + const content = body.slice(startIdx, endIdx); + const firstLine = content.split('\n')[0].replace(/^(?:[-*+]|\d+\.) /, '').trim(); + return { + heading: firstLine.length > 50 ? firstLine.slice(0, 50) + '\u2026' : firstLine, + level: 0, + content, + startOffset: startIdx, + endOffset: endIdx, + }; + }); + } return [{ heading: '', level: 0, content: body, startOffset: 0, endOffset: body.length }]; + } const sections: MarkdownSection[] = []; const headingIdxArray = [...headingIndices].sort((a, b) => a - b); diff --git a/frontend/src/views/NoteEditorView.vue b/frontend/src/views/NoteEditorView.vue index 41bae00..b5e08c9 100644 --- a/frontend/src/views/NoteEditorView.vue +++ b/frontend/src/views/NoteEditorView.vue @@ -202,6 +202,28 @@ async function confirmDelete() { } } +// Auto-save every 5 minutes when editing an existing note +let autoSaveTimer: ReturnType | null = null; + +async function autoSave() { + if (!isEditing.value || !dirty.value || saving.value) return; + saving.value = true; + try { + await store.updateNote(noteId.value!, { title: title.value, body: body.value }); + savedTitle = title.value; + savedBody = body.value; + dirty.value = false; + toast.show("Auto-saved"); + } catch { + // Silent — user can still save manually + } finally { + saving.value = false; + } +} + +onMounted(() => { autoSaveTimer = setInterval(autoSave, 5 * 60 * 1000); }); +onUnmounted(() => { if (autoSaveTimer !== null) clearInterval(autoSaveTimer); }); + // Ctrl+S handler function onKeydown(e: KeyboardEvent) { if ((e.ctrlKey || e.metaKey) && e.key === "s") { @@ -438,533 +460,4 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload)); - + + \ No newline at end of file diff --git a/frontend/src/views/TaskViewerView.vue b/frontend/src/views/TaskViewerView.vue index 436cbb6..c7f5ece 100644 --- a/frontend/src/views/TaskViewerView.vue +++ b/frontend/src/views/TaskViewerView.vue @@ -60,9 +60,8 @@ function cycleStatus() { function isOverdue(): boolean { if (!store.currentTask?.due_date || store.currentTask.status === "done") return false; - return ( - new Date(store.currentTask.due_date) < new Date(new Date().toDateString()) - ); + const today = new Date().toISOString().slice(0, 10); + return store.currentTask.due_date < today; } async function convertToNote() { diff --git a/src/fabledassistant/app.py b/src/fabledassistant/app.py index 1af6c92..6073f1f 100644 --- a/src/fabledassistant/app.py +++ b/src/fabledassistant/app.py @@ -78,6 +78,16 @@ def create_app() -> Quart: except Exception: logger.debug("Failed to log usage", exc_info=True) + response.headers.setdefault("X-Content-Type-Options", "nosniff") + response.headers.setdefault("X-Frame-Options", "DENY") + response.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin") + response.headers.setdefault( + "Content-Security-Policy", + "default-src 'self'; script-src 'self' 'unsafe-inline'; " + "style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; " + "connect-src 'self'; font-src 'self' data:; object-src 'none'; base-uri 'self';" + ) + return response @app.before_serving diff --git a/src/fabledassistant/auth.py b/src/fabledassistant/auth.py index 1f3ce58..cac2515 100644 --- a/src/fabledassistant/auth.py +++ b/src/fabledassistant/auth.py @@ -5,7 +5,7 @@ from quart import g, jsonify, session from fabledassistant.services.auth import get_user_by_id -def login_required(f): +def _check_auth(f, required_role: str | None = None): @functools.wraps(f) async def decorated(*args, **kwargs): user_id = session.get("user_id") @@ -15,27 +15,20 @@ def login_required(f): if not user: session.clear() return jsonify({"error": "Authentication required"}), 401 - g.user = user - return await f(*args, **kwargs) - return decorated - - -def admin_required(f): - @functools.wraps(f) - async def decorated(*args, **kwargs): - user_id = session.get("user_id") - if not user_id: - return jsonify({"error": "Authentication required"}), 401 - user = await get_user_by_id(user_id) - if not user: - session.clear() - return jsonify({"error": "Authentication required"}), 401 - if user.role != "admin": + if required_role and user.role != required_role: return jsonify({"error": "Admin access required"}), 403 g.user = user return await f(*args, **kwargs) return decorated +def login_required(f): + return _check_auth(f) + + +def admin_required(f): + return _check_auth(f, required_role="admin") + + def get_current_user_id() -> int: return g.user.id diff --git a/src/fabledassistant/config.py b/src/fabledassistant/config.py index 4b562ad..0c3f72f 100644 --- a/src/fabledassistant/config.py +++ b/src/fabledassistant/config.py @@ -44,3 +44,4 @@ class Config: SMTP_FROM_NAME: str = os.environ.get("SMTP_FROM_NAME", "Fabled Assistant") SMTP_USE_TLS: bool = os.environ.get("SMTP_USE_TLS", "true").lower() in ("1", "true", "yes") BASE_URL: str = os.environ.get("BASE_URL", "http://localhost:5000").rstrip("/") + TRUST_PROXY_HEADERS: bool = os.environ.get("TRUST_PROXY_HEADERS", "").lower() in ("1", "true", "yes") diff --git a/src/fabledassistant/rate_limit.py b/src/fabledassistant/rate_limit.py new file mode 100644 index 0000000..a9c9b71 --- /dev/null +++ b/src/fabledassistant/rate_limit.py @@ -0,0 +1,18 @@ +import asyncio +import time +from collections import defaultdict + +_buckets: dict[str, list[float]] = defaultdict(list) +_lock = asyncio.Lock() + + +async def is_rate_limited(key: str, max_requests: int, window_seconds: int) -> bool: + """Returns True if request should be blocked (limit exceeded).""" + async with _lock: + now = time.monotonic() + cutoff = now - window_seconds + _buckets[key] = [t for t in _buckets[key] if t > cutoff] + if len(_buckets[key]) >= max_requests: + return True + _buckets[key].append(now) + return False diff --git a/src/fabledassistant/routes/auth.py b/src/fabledassistant/routes/auth.py index 26fedeb..ec0374f 100644 --- a/src/fabledassistant/routes/auth.py +++ b/src/fabledassistant/routes/auth.py @@ -3,6 +3,8 @@ import asyncio from quart import Blueprint, g, jsonify, request, session from fabledassistant.auth import login_required, get_current_user_id +from fabledassistant.config import Config +from fabledassistant.rate_limit import is_rate_limited from fabledassistant.services.auth import ( authenticate, change_password, @@ -28,8 +30,19 @@ from fabledassistant.services.email import get_base_url, is_smtp_configured auth_bp = Blueprint("auth", __name__, url_prefix="/api/auth") +def _client_ip() -> str: + if Config.TRUST_PROXY_HEADERS: + for header in ("X-Forwarded-For", "X-Real-IP"): + val = request.headers.get(header, "").split(",")[0].strip() + if val: + return val + return request.remote_addr or "" + + @auth_bp.route("/register", methods=["POST"]) async def register(): + if await is_rate_limited(f"register:{_client_ip()}", max_requests=5, window_seconds=300): + return jsonify({"error": "Too many registration attempts. Try again later."}), 429 if not await is_registration_open(): return jsonify({"error": "Registration is closed"}), 403 @@ -49,12 +62,14 @@ async def register(): return jsonify({"error": "Username already taken"}), 409 session["user_id"] = user.id - await log_audit("register", user_id=user.id, username=user.username, ip_address=request.remote_addr) + await log_audit("register", user_id=user.id, username=user.username, ip_address=_client_ip()) return jsonify(user.to_dict()), 201 @auth_bp.route("/login", methods=["POST"]) async def login(): + if await is_rate_limited(f"login:{_client_ip()}", max_requests=10, window_seconds=60): + return jsonify({"error": "Too many login attempts. Try again later."}), 429 data = await request.get_json() username = (data.get("username") or "").strip() password = data.get("password") or "" @@ -64,21 +79,21 @@ async def login(): user = await authenticate(username, password) if not user: - await log_audit("login_failed", username=username, ip_address=request.remote_addr) + await log_audit("login_failed", username=username, ip_address=_client_ip()) # Try to notify the actual user about the failed attempt target_user = await get_user_by_username(username) if target_user: asyncio.create_task(notify_security_event( target_user.id, "login_failed", - {"ip_address": request.remote_addr, "username": username}, + {"ip_address": _client_ip(), "username": username}, )) return jsonify({"error": "Invalid username or password"}), 401 session["user_id"] = user.id - await log_audit("login", user_id=user.id, username=user.username, ip_address=request.remote_addr) + await log_audit("login", user_id=user.id, username=user.username, ip_address=_client_ip()) asyncio.create_task(notify_security_event( user.id, "login", - {"ip_address": request.remote_addr}, + {"ip_address": _client_ip()}, )) return jsonify(user.to_dict()) @@ -88,10 +103,10 @@ async def logout(): uid = session.get("user_id") if uid: user = await get_user_by_id(uid) - await log_audit("logout", user_id=uid, username=user.username if user else None, ip_address=request.remote_addr) + await log_audit("logout", user_id=uid, username=user.username if user else None, ip_address=_client_ip()) asyncio.create_task(notify_security_event( uid, "logout", - {"ip_address": request.remote_addr}, + {"ip_address": _client_ip()}, )) session.clear() return jsonify({"status": "ok"}) @@ -123,16 +138,18 @@ async def update_password(): if not success: return jsonify({"error": "Current password is incorrect"}), 403 - await log_audit("password_change", user_id=uid, username=g.user.username, ip_address=request.remote_addr) + await log_audit("password_change", user_id=uid, username=g.user.username, ip_address=_client_ip()) asyncio.create_task(notify_security_event( uid, "password_change", - {"ip_address": request.remote_addr}, + {"ip_address": _client_ip()}, )) return jsonify({"status": "ok"}) @auth_bp.route("/forgot-password", methods=["POST"]) async def forgot_password(): + if await is_rate_limited(f"forgot:{_client_ip()}", max_requests=5, window_seconds=300): + return jsonify({"status": "ok"}) data = await request.get_json() email = (data.get("email") or "").strip().lower() @@ -150,7 +167,7 @@ async def forgot_password(): "password_reset_requested", user_id=user.id, username=user.username, - ip_address=request.remote_addr, + ip_address=_client_ip(), ) return jsonify({"status": "ok"}) @@ -158,6 +175,8 @@ async def forgot_password(): @auth_bp.route("/reset-password", methods=["POST"]) async def reset_password(): + if await is_rate_limited(f"reset:{_client_ip()}", max_requests=10, window_seconds=60): + return jsonify({"error": "Too many attempts. Try again later."}), 429 data = await request.get_json() token = (data.get("token") or "").strip() new_password = data.get("new_password") or "" @@ -167,34 +186,18 @@ async def reset_password(): if len(new_password) < 8: return jsonify({"error": "Password must be at least 8 characters"}), 400 - success = await reset_password_with_token(token, new_password) - if not success: + user_id = await reset_password_with_token(token, new_password) + if user_id is None: return jsonify({"error": "Invalid or expired reset link"}), 400 - # Look up user by token to send notifications (token is now used, so look up by hash) - import hashlib - from fabledassistant.models import async_session - from fabledassistant.models.password_reset import PasswordResetToken - from sqlalchemy import select - - token_hash = hashlib.sha256(token.encode()).hexdigest() - async with async_session() as session: - result = await session.execute( - select(PasswordResetToken).where(PasswordResetToken.token_hash == token_hash) + user = await get_user_by_id(user_id) + if user: + await log_audit( + "password_reset_completed", + user_id=user.id, username=user.username, ip_address=_client_ip(), ) - reset_token = result.scalars().first() - if reset_token: - user = await get_user_by_id(reset_token.user_id) - if user: - await log_audit( - "password_reset_completed", - user_id=user.id, - username=user.username, - ip_address=request.remote_addr, - ) - if user.email: - asyncio.create_task(send_password_reset_success_email(user.email)) - + if user.email: + asyncio.create_task(send_password_reset_success_email(user.email)) return jsonify({"status": "ok"}) @@ -233,7 +236,7 @@ async def register_with_invite(): "register_with_invite", user_id=user.id, username=user.username, - ip_address=request.remote_addr, + ip_address=_client_ip(), ) return jsonify(user.to_dict()), 201 diff --git a/src/fabledassistant/routes/chat.py b/src/fabledassistant/routes/chat.py index cbf95f2..c91d56e 100644 --- a/src/fabledassistant/routes/chat.py +++ b/src/fabledassistant/routes/chat.py @@ -35,7 +35,7 @@ chat_bp = Blueprint("chat", __name__, url_prefix="/api/chat") @login_required async def list_conversations_route(): uid = get_current_user_id() - limit = request.args.get("limit", 50, type=int) + limit = min(request.args.get("limit", 50, type=int), 500) offset = request.args.get("offset", 0, type=int) conversations, total = await list_conversations(uid, limit=limit, offset=offset) return jsonify({ @@ -167,7 +167,10 @@ async def generation_stream_route(conv_id: int): # Determine starting point from Last-Event-ID header or query param last_id_str = request.headers.get("Last-Event-ID") or request.args.get("last_event_id") - last_id = int(last_id_str) if last_id_str is not None else -1 + try: + last_id = int(last_id_str) if last_id_str is not None else -1 + except (ValueError, TypeError): + last_id = -1 async def stream(): cursor = last_id @@ -335,14 +338,17 @@ async def chat_status_route(): result["ollama"] = "available" model_names = {m["name"] for m in tags_resp.json().get("models", [])} base = default_model.removesuffix(":latest") - if default_model in model_names or f"{base}:latest" in model_names: + if default_model in model_names or f"{base}:latest" in model_names or base in model_names: # Installed — now check if currently loaded in memory result["model"] = "cold" if not isinstance(ps_resp, Exception): - ps_resp.raise_for_status() - loaded_names = {m["name"] for m in ps_resp.json().get("models", [])} - if default_model in loaded_names or f"{base}:latest" in loaded_names: - result["model"] = "loaded" + try: + ps_resp.raise_for_status() + loaded_names = {m["name"] for m in ps_resp.json().get("models", [])} + if default_model in loaded_names or f"{base}:latest" in loaded_names or base in loaded_names: + result["model"] = "loaded" + except Exception: + logger.debug("Ollama /api/ps check failed", exc_info=True) except Exception: logger.debug("Ollama status check failed", exc_info=True) return jsonify(result) diff --git a/src/fabledassistant/routes/notes.py b/src/fabledassistant/routes/notes.py index e6dacf3..f06b384 100644 --- a/src/fabledassistant/routes/notes.py +++ b/src/fabledassistant/routes/notes.py @@ -45,7 +45,7 @@ async def list_notes_route(): tag = request.args.getlist("tag") sort = request.args.get("sort", "updated_at") order = request.args.get("order", "desc") - limit = request.args.get("limit", 50, type=int) + limit = min(request.args.get("limit", 50, type=int), 500) offset = request.args.get("offset", 0, type=int) # Default to non-task notes only; ?is_task=true for tasks, ?all=true for everything @@ -74,7 +74,10 @@ async def create_note_route(): priority = data.get("priority") due_date = None if data.get("due_date"): - due_date = date.fromisoformat(data["due_date"]) + try: + due_date = date.fromisoformat(data["due_date"]) + except ValueError: + return jsonify({"error": "Invalid date format. Use YYYY-MM-DD."}), 400 note = await create_note( uid, @@ -178,9 +181,13 @@ async def update_note_route(note_id: int): fields[key] = data[key] if "due_date" in data: - fields["due_date"] = ( - date.fromisoformat(data["due_date"]) if data["due_date"] else None - ) + if data["due_date"]: + try: + fields["due_date"] = date.fromisoformat(data["due_date"]) + except ValueError: + return jsonify({"error": "Invalid date format. Use YYYY-MM-DD."}), 400 + else: + fields["due_date"] = None if "body" in fields: fields["tags"] = extract_tags(fields["body"]) @@ -272,7 +279,10 @@ async def assist_stream_route(): return jsonify({"error": "No active assist generation"}), 404 last_id_str = request.headers.get("Last-Event-ID") or request.args.get("last_event_id") - last_id = int(last_id_str) if last_id_str is not None else -1 + try: + last_id = int(last_id_str) if last_id_str is not None else -1 + except (ValueError, TypeError): + last_id = -1 async def stream(): cursor = last_id diff --git a/src/fabledassistant/routes/tasks.py b/src/fabledassistant/routes/tasks.py index 1751722..ba86a0f 100644 --- a/src/fabledassistant/routes/tasks.py +++ b/src/fabledassistant/routes/tasks.py @@ -26,13 +26,16 @@ async def list_tasks_route(): priority = request.args.get("priority") sort = request.args.get("sort", "updated_at") order = request.args.get("order", "desc") - limit = request.args.get("limit", 50, type=int) + limit = min(request.args.get("limit", 50, type=int), 500) offset = request.args.get("offset", 0, type=int) due_before_str = request.args.get("due_before") due_after_str = request.args.get("due_after") - due_before = date.fromisoformat(due_before_str) if due_before_str else None - due_after = date.fromisoformat(due_after_str) if due_after_str else None + try: + due_before = date.fromisoformat(due_before_str) if due_before_str else None + due_after = date.fromisoformat(due_after_str) if due_after_str else None + except ValueError: + return jsonify({"error": "Invalid date format. Use YYYY-MM-DD."}), 400 tasks, total = await list_notes( uid, @@ -61,7 +64,10 @@ async def create_task_route(): due_date = None if data.get("due_date"): - due_date = date.fromisoformat(data["due_date"]) + try: + due_date = date.fromisoformat(data["due_date"]) + except ValueError: + return jsonify({"error": "Invalid date format. Use YYYY-MM-DD."}), 400 status = TaskStatus(data["status"]).value if "status" in data else TaskStatus.todo.value priority = ( @@ -107,9 +113,13 @@ async def update_task_route(task_id: int): fields["body"] = data["description"] if "due_date" in data: - fields["due_date"] = ( - date.fromisoformat(data["due_date"]) if data["due_date"] else None - ) + if data["due_date"]: + try: + fields["due_date"] = date.fromisoformat(data["due_date"]) + except ValueError: + return jsonify({"error": "Invalid date format. Use YYYY-MM-DD."}), 400 + else: + fields["due_date"] = None if "body" in fields: fields["tags"] = extract_tags(fields["body"]) diff --git a/src/fabledassistant/services/assist.py b/src/fabledassistant/services/assist.py index 76781d1..a52e614 100644 --- a/src/fabledassistant/services/assist.py +++ b/src/fabledassistant/services/assist.py @@ -24,7 +24,10 @@ def build_assist_messages( "your output MUST also start with a heading at the same level. " "You may revise the heading text but do not remove it. " "Do not include other sections, explanatory text, or markdown code fences around the output. " - "Match the document's existing tone and style." + "Match the document's existing tone and style. " + "IMPORTANT: Preserve all markdown formatting exactly — including bullet lists (- item), " + "numbered lists (1. item), nested/indented sub-items ( - sub), bold (**text**), " + "italic (_text_), and code blocks. Never flatten nested lists into plain text." ) user_content = ( diff --git a/src/fabledassistant/services/auth.py b/src/fabledassistant/services/auth.py index 6a2e4f3..b4f74a9 100644 --- a/src/fabledassistant/services/auth.py +++ b/src/fabledassistant/services/auth.py @@ -65,7 +65,7 @@ async def create_user( ) await session.execute( update(Setting) - .where(Setting.user_id == user.id) + .where(Setting.user_id.is_(None)) .values(user_id=user.id) ) # Auto-close registration after first user setup @@ -194,8 +194,8 @@ async def create_password_reset_token(user_id: int) -> str: return raw_token -async def reset_password_with_token(raw_token: str, new_password: str) -> bool: - """Validate a reset token and update the user's password. Returns True on success.""" +async def reset_password_with_token(raw_token: str, new_password: str) -> int | None: + """Validate a reset token and update the user's password. Returns user_id on success.""" token_hash = hashlib.sha256(raw_token.encode()).hexdigest() async with async_session() as session: @@ -205,22 +205,22 @@ async def reset_password_with_token(raw_token: str, new_password: str) -> bool: reset_token = result.scalars().first() if not reset_token: - return False + return None if reset_token.used: - return False + return None if reset_token.expires_at < datetime.now(timezone.utc): - return False + return None user = await session.get(User, reset_token.user_id) if not user: - return False + return None user.password_hash = hash_password(new_password) reset_token.used = True await session.commit() logger.info("Password reset via token for user %d (%s)", user.id, user.username) - return True + return user.id async def create_invitation(email: str, invited_by: int) -> str: diff --git a/src/fabledassistant/services/backup.py b/src/fabledassistant/services/backup.py index bd03513..2541e52 100644 --- a/src/fabledassistant/services/backup.py +++ b/src/fabledassistant/services/backup.py @@ -27,6 +27,10 @@ async def export_full_backup() -> dict: return { "version": 1, "scope": "full", + "_security_notice": ( + "This backup contains hashed passwords. " + "Store it securely and restrict access." + ), "users": [ { "id": u.id, diff --git a/summary.md b/summary.md index 202feb2..46e5f93 100644 --- a/summary.md +++ b/summary.md @@ -12,7 +12,7 @@ > Include file-level details in the commit body when the change is non-trivial. ## Last Updated -2026-02-19 — Phase 13: Writing assistant UI redesign (right-side panel, diff view, proofread, floating inline assist, fallback section detection, increased site-wide max-width) +2026-02-19 — Phase 14: Security audit, bug fixes, auto-save, and writing assistant improvements ## Project Overview Fabled Assistant is a self-hosted note-taking and task-tracking application with @@ -104,6 +104,16 @@ for AI-assisted features. flag controlled by `SECURE_COOKIES` env var (enable when behind TLS). - **Default SECRET_KEY warning:** App logs a WARNING on startup if the default `dev-secret-change-me` key is in use. +- **Security headers:** Applied in `app.py` `after_request` using `setdefault` so + SSE/streaming responses that set their own headers aren't clobbered: `X-Content-Type-Options`, + `X-Frame-Options: DENY`, `Referrer-Policy`, and a restrictive `Content-Security-Policy`. +- **Rate limiting:** In-memory sliding-window rate limiter (`rate_limit.py`) applied to + auth endpoints: login (10/60s), register (5/300s), forgot-password (5/300s, silent drop + to avoid timing info), reset-password (10/60s). Keys are per-IP. +- **Proxy-aware client IP:** `TRUST_PROXY_HEADERS` env var enables reading real client IP + from `X-Forwarded-For` / `X-Real-IP` when behind a trusted reverse proxy. Off by default. +- **Auto-save:** Both note and task editors auto-save every 5 minutes when editing an + existing dirty record. Silent on error; shows "Auto-saved" toast on success. ### High-Level Component Diagram ``` @@ -215,7 +225,8 @@ fabledassistant/ ├── summary.md # This file — canonical project context ├── pyproject.toml # Python project config (deps include caldav, icalendar) ├── Dockerfile # Multi-stage build (Node → Python) -├── docker-compose.yml # Dev compose (app, PostgreSQL, Ollama) +├── .dockerignore # Prevents secrets/node_modules/__pycache__/.env.* leaking into build +├── docker-compose.yml # Dev compose (app, PostgreSQL, Ollama) — app service has healthcheck ├── docker-compose.prod.yml # Production stack (Docker Swarm, secrets, network isolation) ├── alembic.ini # Alembic config (prepend_sys_path = src) ├── alembic/ @@ -237,9 +248,10 @@ fabledassistant/ ├── src/ │ └── fabledassistant/ │ ├── __init__.py -│ ├── app.py # Quart app factory: SPA via 404 handler, JSON 404/500 for API, request logging middleware -│ ├── auth.py # Auth decorators: login_required, admin_required, get_current_user_id -│ ├── config.py # Config from env vars + Docker secrets file support (_read_secret) + SECURE_COOKIES flag +│ ├── app.py # Quart app factory: SPA via 404 handler, JSON 404/500 for API, request logging, security headers (after_request) +│ ├── auth.py # Auth decorators: login_required, admin_required, get_current_user_id — shared _check_auth() helper +│ ├── config.py # Config from env vars + Docker secrets file support (_read_secret) + SECURE_COOKIES + TRUST_PROXY_HEADERS flags +│ ├── rate_limit.py # In-memory sliding-window rate limiter (asyncio.Lock + defaultdict); is_rate_limited(key, max, window) │ ├── models/ │ │ ├── __init__.py # async_session factory, Base, imports all models │ │ ├── user.py # User model (id, username, email, password_hash, role, created_at) @@ -251,14 +263,14 @@ fabledassistant/ │ ├── routes/ │ │ ├── __init__.py │ │ ├── api.py # /api blueprint with /health endpoint (public) -│ │ ├── auth.py # /api/auth blueprint: register, login, logout, me, status, password reset, invitation registration +│ │ ├── auth.py # /api/auth blueprint: register, login, logout, me, status, password reset, invitation registration — rate limiting + _client_ip() helper │ │ ├── admin.py # /api/admin blueprint: backup, restore, user management, registration toggle, invitations, base URL, SMTP (admin only) │ │ ├── chat.py # /api/chat blueprint: conversations CRUD, SSE message streaming (all @login_required) │ │ ├── notes.py # /api/notes CRUD + wikilinks + backlinks + tag suggestions (all @login_required) │ │ ├── tasks.py # /api/tasks CRUD + PATCH status (all @login_required) │ │ └── settings.py # /api/settings GET/PUT — per-user settings (@login_required) │ ├── services/ -│ │ ├── auth.py # Auth business logic: hash_password, verify_password, create_user, authenticate, get_user_by_id, is_registration_open, list_users, delete_user, set_registration_open, password reset tokens, invitation tokens (create, validate, register_with_invitation, list_pending, revoke) +│ │ ├── auth.py # Auth business logic: hash_password, verify_password, create_user, authenticate, get_user_by_id, is_registration_open, list_users, delete_user, set_registration_open, password reset tokens (reset_password_with_token returns int|None), invitation tokens (create, validate, register_with_invitation, list_pending, revoke) │ │ ├── backup.py # Backup/restore: export_full_backup, export_user_backup, restore_full_backup │ │ ├── notes.py # CRUD with user_id isolation, is_task filter, convert, backlinks, search_notes_for_context │ │ ├── llm.py # Ollama interaction: build_context with user_id, streaming (stream_chat + stream_chat_with_tools), ChatChunk dataclass, URL fetching @@ -285,19 +297,20 @@ fabledassistant/ │ ├── App.vue # Shell: .app-shell (100dvh flex column) with AppHeader + .app-content (flex:1, scrollable) wrapping router-view; starts status polling + loads settings on mount │ ├── main.ts # App init, imports theme.css │ ├── assets/ - │ │ └── theme.css # CSS custom properties: light/dark themes, body reset, design tokens, responsive breakpoints (480/768/1024), utility classes (.hide-mobile/.hide-desktop), mobile touch targets; global .inline-assist-btn (teleported floating pill) + │ │ ├── theme.css # CSS custom properties: light/dark themes, body reset, design tokens, responsive breakpoints (480/768/1024), utility classes (.hide-mobile/.hide-desktop), mobile touch targets + │ │ └── editor-shared.css # Shared editor styles for NoteEditorView + TaskEditorView: layout, toolbar, tag suggestions, assist panel, diff view, modal, responsive, .inline-assist-btn (global — required for teleported elements) │ ├── api/ │ │ └── client.ts # ApiError class, apiGet/apiPost/apiPut/apiPatch/apiDelete + apiSSEStream (fetch+ReadableStream), apiStreamPost (legacy), auto 401→login redirect │ ├── composables/ │ │ ├── useTheme.ts # Theme toggle, localStorage, prefers-color-scheme │ │ ├── useShortcuts.ts # Shared showShortcuts ref + open/close/toggle helpers (used by App.vue + AppHeader.vue) │ │ ├── useAutocomplete.ts # Legacy textarea autocomplete (replaced by Tiptap suggestion extensions) - │ │ └── useAssist.ts # AI Assist composable: section parsing, target selection, two-step POST+SSE streaming (apiPost → apiSSEStream), accept/reject, proofread (full-document), LCS line diff (DiffLine/computeDiff), isProofreading ref; watches body ref for auto-sync + │ │ └── useAssist.ts # AI Assist composable: section parsing, target selection, two-step POST+SSE streaming (apiPost → apiSSEStream), accept/reject (accept() resets to idle on doc-change error), proofread (full-document), LCS line diff (DiffLine/computeDiff), isProofreading ref; watches body ref for auto-sync │ ├── stores/ │ │ ├── auth.ts # Auth state: user, isAuthenticated, isAdmin, login/register/logout/checkAuth │ │ ├── notes.ts # CRUD + tag filter, resolveTitle, convertToTask, convertToNote, fetchBacklinks, fetchAllTags (with toast errors) │ │ ├── tasks.ts # CRUD + status/priority filter, patchStatus (with toast errors) - │ │ ├── chat.ts # Conversation CRUD, sendMessage (SSE streaming), status polling, running models, model warming, updateConversationModel (with toast errors) + │ │ ├── chat.ts # Conversation CRUD, sendMessage (SSE streaming), status polling (memory-leak-safe _pollUntilLoaded), running models, model warming, updateConversationModel (with toast errors) │ │ ├── settings.ts # App settings: assistantName, defaultModel, pullModel, deleteModel (with toast errors) │ │ └── toast.ts # Toast notification state (success/error/warning), 4s auto-dismiss, dismiss(id) │ ├── types/ @@ -314,9 +327,9 @@ fabledassistant/ │ │ └── suggestionRenderer.ts # Shared Vue renderer for suggestion dropdowns (creates/positions SuggestionDropdown) │ ├── utils/ │ │ ├── tags.ts # extractTags(), linkifyTags() (with (?