Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(email,auth): escape TOML credentials, surface login errors, kill orphaned CLI children
trohitg1e348b8fdd93
diff --git a/.env.template b/.env.templateindex 46c33bf0..d57324ce 100644--- a/.env.template+++ b/.env.template@@ -36,8 +36,19 @@ JWT_SECRET_KEY=dev-jwt-secret-key-12345678901234567890JWT_EXPIRE_MINUTES=10080JWT_COOKIE_NAME=opencompany_tokenJWT_COOKIE_SECURE=false+# JWT_COOKIE_SAMESITE: "lax" | "strict" | "none". "none" REQUIRES+# JWT_COOKIE_SECURE=true (browsers reject an insecure SameSite=None cookie,+# which silently breaks login) — the combination is rejected at startup.JWT_COOKIE_SAMESITE=lax+# Login/registration throttling. Deliberately tighter than RATE_LIMIT_* below,+# which is a generic API budget and far too loose for a password endpoint.+# Counters are per-process: exact under `company serve` (one uvicorn worker),+# best-effort under the legacy multi-worker gunicorn path.+AUTH_RATE_LIMIT_ENABLED=true+AUTH_RATE_LIMIT_ATTEMPTS=10+AUTH_RATE_LIMIT_WINDOW=300+# CORS Configuration - the app port, the Vite dev client, and Vite's# bare default (5173) for ad-hoc runsCORS_ORIGINS=["http://localhost:5678","http://localhost:5679","http://127.0.0.1:5678","http://127.0.0.1:5679","http://localhost:5173"]diff --git a/CLAUDE.md b/CLAUDE.mdindex 863cfa7a..340d748e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -16,7 +16,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (toggled by Dashboard's `visibilitychange` listener; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 SVGs across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. || **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), and 12-theme docs (`guidelines/THEMES.md`, `reference/themes/`). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). || **[Schema Source of Truth RFC](./docs-internal/schema_source_of_truth_rfc.md)** | Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Live invariant total via `pytest --collect-only`. |-| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — 27 at time of writing, do not hand-maintain. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. |+| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — 30 at time of writing, do not hand-maintain. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live count via `glob server/nodes/**/__init__.py`); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — up to six generic registries (`ws_handler_registry`, `register_router`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`) so rich plugins like telegram own their entire surface area without core-services edits. || **[Nodes Cookbook](./server/nodes/README.md)** | 5-minute recipe + folder map + shared helpers (`_base.py` / `_inline.py` per domain) + shared credentials + **canonical folder-per-plugin shape (telegram is the reference implementation)** + contract invariants + common pitfalls. Lives next to the plugin files. || **[Node Creation Guide](./docs-internal/node_creation.md)** | Canonical plugin recipe — one self-contained folder per plugin under `server/nodes/<group>/<plugin>/`, rooted at `__init__.py`. Multi-file split (`_service.py` / `_handlers.py` / etc.) when the plugin owns long-lived state. Zero frontend edits, zero core-services edits. Auto-registers via `BaseNode.__init_subclass__` + the six `register_*` hooks. Covers tool nodes, dual-purpose nodes (workflow + AI tool), and specialized agents as variations of the same recipe. || **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute through the provider-neutral `run_native_agent_loop` |@@ -803,7 +803,7 @@ See **[Scripts Reference](./docs-internal/SCRIPTS.md)** for full documentation.✅ **UI State Persistence**: localStorage persistence for sidebar visibility, component palette visibility, dev mode, and collapsed sections✅ **Normal/Dev Mode**: Toggle in toolbar to filter Component Palette - Normal mode shows only AI Agents, Models, and Skills; Dev mode shows all categories✅ **Production Deployment**: Docker Compose deployment (4 containers: Redis, Backend, Frontend, WhatsApp), nginx reverse proxy, and Let's Encrypt SSL-✅ **Authentication System**: n8n-style JWT authentication with HttpOnly cookies, single-owner and multi-user modes+✅ **Authentication System**: n8n-style JWT authentication with HttpOnly cookies, single-owner and multi-user modes, rate-limited login. Note `AUTH_MODE=multi` authenticates but does NOT isolate data — see Known Limitations in [authentication.md](./docs-internal/authentication.md)✅ **Cache System**: n8n-pattern cache with Redis (production) / SQLite (local dev) / Memory fallback hierarchy✅ **AI Thinking/Reasoning**: Extended thinking for Claude, Gemini 2.5/3, OpenAI GPT-5/o-series, Groq Qwen3 with output available in Input Data & Variables for downstream nodes✅ **Onboarding Service**: 5-step welcome wizard with shadcn UI, database persistence, skip/resume/replay support@@ -1231,7 +1231,11 @@ The historical Docker Compose topology (4-container stack: redis / backend / fro## Authentication System-n8n-style JWT auth in HttpOnly cookies. `VITE_AUTH_ENABLED=false` bypasses login (anonymous owner, dev); when enabled, `AUTH_MODE=single` (first user = owner, registration then closed) or `multi` (open registration). Backend: `User` (bcrypt) + `UserAuthService` + `/api/auth/*` router + `AuthMiddleware` (public-path allowlist + `/webhook/` prefix). Frontend: `AuthContext` (TanStack-Query bootstrap with full-jitter backoff) + `ProtectedRoute` + `LoginPage`; all API calls send `credentials: 'include'`, and the WebSocket refuses to connect without the cookie.+n8n-style JWT auth in HttpOnly cookies. `VITE_AUTH_ENABLED=false` bypasses login (anonymous owner, dev); when enabled, `AUTH_MODE=single` (first user = owner, registration then closed) or `multi` (open registration). Backend: `User` (bcrypt) + `UserAuthService` + `/api/auth/*` router + `AuthMiddleware` (public-path allowlist + `/webhook/` prefix). `/login` and `/register` are throttled by the in-process `core/rate_limit.py` sliding window (`AUTH_RATE_LIMIT_*`; no `slowapi` dependency — the primary runtime is a single uvicorn worker). Frontend: `AuthContext` (TanStack-Query bootstrap with full-jitter backoff, plus `useMutation` for login/register/logout) + `ProtectedRoute` + `LoginPage` (RHF + zod via the shadcn `Form` primitives); all API calls send `credentials: 'include'`, and the WebSocket refuses to connect without the cookie.++**Two context distinctions that are load-bearing, not stylistic:** `isLoading` is the bootstrap query (gates the whole app in `ProtectedRoute`) while `isSubmitting` is per-request — using the former to disable the login form disables nothing, since it has already settled by the time that form renders. And `error` means "cannot reach the server" while `submitError` is the server's own rejection text; a `setQueryData` write is a *success* value, so routing a login failure through the status cache surfaces no error at all and additionally collapses `can_register`.++**Read the Known Limitations section of [authentication.md](./docs-internal/authentication.md) before building on this.** `AUTH_MODE=multi` provides authentication but no data isolation — `request.state.user_id` is written by the middleware and read by nothing, so all users share one workflow store and one credential store. There is also no CSRF token and no token revocation (`User.is_active` is the only lever).**Load-bearing rule:** JWT handling uses **PyJWT** (`import jwt`, HS256 with `Settings.jwt_secret_key`). Do NOT reintroduce `python-jose` — it drags in pure-Python `ecdsa` with the unpatchable Minerva timing-attack advisory (GHSA-wj6h-64fc-37mp). Full reference (models, router, middleware, config, startup retry, key files, deps) in **[Authentication](./docs-internal/authentication.md)**.diff --git a/client/src/components/auth/LoginPage.tsx b/client/src/components/auth/LoginPage.tsxindex c8850bd6..0f314146 100644--- a/client/src/components/auth/LoginPage.tsx+++ b/client/src/components/auth/LoginPage.tsx@@ -1,122 +1,180 @@/*** Login/Register Page.- * Shows login form, or register form if registration is available.+ *+ * Built on react-hook-form + zod through the shadcn `Form` primitives, the+ * same composition `EmailPanel` uses. That is not cosmetic: `FormControl`+ * emits `aria-invalid` and wires `aria-describedby` to the matching+ * `FormMessage`, which the previous hand-rolled markup did not do.+ *+ * Two failure signals are displayed, and they are not the same thing:+ * `submitError` is the server's rejection ("Invalid email or password"),+ * `error` is a connectivity failure from the bootstrap query. Before, only+ * the latter existed on the context, so a wrong password produced no+ * feedback whatsoever.*/-import React, { useState } from 'react';+import React, { useMemo, useState } from 'react';+import { useForm } from 'react-hook-form';+import { zodResolver } from '@hookform/resolvers/zod';+import { useAuth } from '../../contexts/AuthContext';import { Card, CardContent, CardHeader, CardTitle, CardDescription, CardFooter } from '@/components/ui/card';import { Input } from '@/components/ui/input';-import { Label } from '@/components/ui/label';import { Button } from '@/components/ui/button';import { Alert, AlertDescription } from '@/components/ui/alert';+import {+ Form,+ FormControl,+ FormField,+ FormItem,+ FormLabel,+ FormMessage,+} from '@/components/ui/form';+import { createAuthFormSchema, type AuthFormValues } from './schemas/login';const LoginPage: React.FC = () => {- const { login, register, canRegister, error, isLoading } = useAuth();+ const {+ login,+ register,+ canRegister,+ error,+ submitError,+ isSubmitting,+ resetAuthErrors,+ } = useAuth();const [isRegistering, setIsRegistering] = useState(false);- const [email, setEmail] = useState('');- const [password, setPassword] = useState('');- const [displayName, setDisplayName] = useState('');- const [localError, setLocalError] = useState<string | null>(null);-- const handleSubmit = async (e: React.FormEvent) => {- e.preventDefault();- setLocalError(null);-- if (!email || !password) {- setLocalError('Email and password are required');- return;- }+ const schema = useMemo(() => createAuthFormSchema(isRegistering), [isRegistering]);++ const form = useForm<AuthFormValues>({+ resolver: zodResolver(schema),+ defaultValues: { email: '', password: '', displayName: '' },+ mode: 'onSubmit',+ });++ const onSubmit = async (values: AuthFormValues) => {+ resetAuthErrors();if (isRegistering) {- if (!displayName) {- setLocalError('Display name is required');- return;- }- if (password.length < 8) {- setLocalError('Password must be at least 8 characters');- return;- }- await register(email, password, displayName);+ await register(values.email, values.password, values.displayName ?? '');} else {- await login(email, password);+ await login(values.email, values.password);}+ // Failure text lives on `submitError`; nothing to do here. The mutation+ // never rejects out of these wrappers.};const toggleMode = () => {- setIsRegistering(!isRegistering);- setLocalError(null);+ setIsRegistering((prev) => !prev);+ resetAuthErrors();+ form.clearErrors();};- const displayError = localError || error;-return (<div className="flex min-h-screen items-center justify-center bg-background p-5"><Card className="w-full max-w-md"><CardHeader className="text-center">- <CardTitle className="text-3xl font-bold text-node-agent">OpenCompany</CardTitle>+ {/* A real <h1>: the page previously had no heading landmark at all. */}+ <CardTitle className="text-3xl font-bold text-node-agent">+ <h1>OpenCompany</h1>+ </CardTitle><CardDescription>{isRegistering ? 'Create your account' : 'Sign in to continue'}</CardDescription></CardHeader><CardContent className="space-y-4">- {displayError && (- <Alert variant="destructive">- <AlertDescription>{displayError}</AlertDescription>+ {/* Server rejection: wrong password, duplicate email, rate limit. */}+ {submitError && (+ <Alert variant="destructive" aria-live="assertive">+ <AlertDescription>{submitError}</AlertDescription></Alert>)}- <form onSubmit={handleSubmit} className="space-y-4">- {isRegistering && (- <div className="space-y-1.5">- <Label htmlFor="displayName">Display Name</Label>- <Input- id="displayName"- type="text"- value={displayName}- onChange={(e) => setDisplayName(e.target.value)}- placeholder="Your name"- disabled={isLoading}+ {/* Connectivity failure, distinct from a rejected credential. */}+ {error && !submitError && (+ <Alert variant="destructive" aria-live="polite">+ <AlertDescription>{error}</AlertDescription>+ </Alert>+ )}++ <Form {...form}>+ {/* noValidate: zod owns validation. Otherwise the browser's own+ constraint check on type="email" silently blocks submit and+ shows a native bubble, which neither matches FormMessage+ styling nor respects the schema's rules. */}+ <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" noValidate>+ {isRegistering && (+ <FormField+ control={form.control}+ name="displayName"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Display Name</FormLabel>+ <FormControl>+ <Input+ placeholder="Your name"+ autoComplete="name"+ disabled={isSubmitting}+ {...field}+ value={field.value ?? ''}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}/>- </div>- )}-- <div className="space-y-1.5">- <Label htmlFor="email">Email</Label>- <Input- id="email"- type="email"- value={email}- onChange={(e) => setEmail(e.target.value)}- placeholder="[email protected]"- disabled={isLoading}- autoComplete="email"+ )}++ <FormField+ control={form.control}+ name="email"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Email</FormLabel>+ <FormControl>+ <Input+ type="email"+ placeholder="[email protected]"+ autoComplete="email"+ disabled={isSubmitting}+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}/>- </div>-- <div className="space-y-1.5">- <Label htmlFor="password">Password</Label>- <Input- id="password"- type="password"- value={password}- onChange={(e) => setPassword(e.target.value)}- placeholder={isRegistering ? 'At least 8 characters' : 'Your password'}- disabled={isLoading}- autoComplete={isRegistering ? 'new-password' : 'current-password'}++ <FormField+ control={form.control}+ name="password"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Password</FormLabel>+ <FormControl>+ <Input+ type="password"+ placeholder={isRegistering ? 'At least 8 characters' : 'Your password'}+ autoComplete={isRegistering ? 'new-password' : 'current-password'}+ disabled={isSubmitting}+ {...field}+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}/>- </div>-- <Button type="submit" className="w-full" disabled={isLoading}>- {isLoading- ? 'Please wait...'- : isRegistering- ? 'Create Account'- : 'Sign In'}- </Button>- </form>++ <Button type="submit" className="w-full" disabled={isSubmitting}>+ {isSubmitting+ ? 'Please wait...'+ : isRegistering+ ? 'Create Account'+ : 'Sign In'}+ </Button>+ </form>+ </Form></CardContent>{canRegister && (@@ -125,9 +183,10 @@ const LoginPage: React.FC = () => {{isRegistering ? 'Already have an account?' : "Don't have an account?"}</span><Button+ type="button"variant="link"onClick={toggleMode}- disabled={isLoading}+ disabled={isSubmitting}className="h-auto p-0">{isRegistering ? 'Sign In' : 'Register'}diff --git a/client/src/components/auth/__tests__/LoginPage.test.tsx b/client/src/components/auth/__tests__/LoginPage.test.tsxnew file mode 100644index 00000000..ede6e703--- /dev/null+++ b/client/src/components/auth/__tests__/LoginPage.test.tsx@@ -0,0 +1,208 @@+/**+ * Tests for LoginPage.+ *+ * The page previously had no tests at all, and three user-visible defects+ * lived here: server rejections were never displayed, the Register link+ * disappeared after one failed login, and the submit button never disabled+ * (so the form accepted unlimited concurrent requests). Each of those has a+ * case below.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++import LoginPage from '../LoginPage';++const authState = {+ login: vi.fn(),+ register: vi.fn(),+ canRegister: true,+ error: null as string | null,+ submitError: null as string | null,+ isSubmitting: false,+ resetAuthErrors: vi.fn(),+};++vi.mock('../../../contexts/AuthContext', () => ({+ useAuth: () => authState,+}));++beforeEach(() => {+ vi.clearAllMocks();+ authState.login = vi.fn().mockResolvedValue(true);+ authState.register = vi.fn().mockResolvedValue(true);+ authState.canRegister = true;+ authState.error = null;+ authState.submitError = null;+ authState.isSubmitting = false;+ authState.resetAuthErrors = vi.fn();+});++const fillCredentials = async (user: ReturnType<typeof userEvent.setup>) => {+ await user.type(screen.getByLabelText(/email/i), '[email protected]');+ await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');+};++describe('LoginPage', () => {+ it('renders a heading and the sign-in form', () => {+ render(<LoginPage />);+ expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('OpenCompany');+ expect(screen.getByRole('button', { name: /sign in/i })).toBeInTheDocument();+ });++ it('submits credentials to login', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);+ await fillCredentials(user);+ await user.click(screen.getByRole('button', { name: /sign in/i }));++ await waitFor(() => {+ expect(authState.login).toHaveBeenCalledWith('[email protected]', 'hunter2hunter2');+ });+ });++ it('displays the server rejection in an alert', async () => {+ authState.submitError = 'Invalid email or password';+ render(<LoginPage />);++ const alert = screen.getByRole('alert');+ expect(alert).toHaveTextContent('Invalid email or password');+ });++ it('keeps the Register link visible when a login has failed', async () => {+ authState.submitError = 'Invalid email or password';+ authState.canRegister = true;+ render(<LoginPage />);++ expect(screen.getByRole('button', { name: /^register$/i })).toBeInTheDocument();+ });++ it('hides the Register link when registration is closed', () => {+ authState.canRegister = false;+ render(<LoginPage />);+ expect(screen.queryByRole('button', { name: /^register$/i })).not.toBeInTheDocument();+ });++ it('rejects a malformed email without calling login', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);++ await user.type(screen.getByLabelText(/email/i), 'not-an-email');+ await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');+ await user.click(screen.getByRole('button', { name: /sign in/i }));++ await waitFor(() => {+ expect(screen.getByText(/valid email address/i)).toBeInTheDocument();+ });+ expect(authState.login).not.toHaveBeenCalled();+ });++ it('requires a password', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);++ await user.type(screen.getByLabelText(/email/i), '[email protected]');+ await user.click(screen.getByRole('button', { name: /sign in/i }));++ await waitFor(() => {+ expect(screen.getByText(/password is required/i)).toBeInTheDocument();+ });+ expect(authState.login).not.toHaveBeenCalled();+ });++ it('disables inputs and the button while submitting', () => {+ authState.isSubmitting = true;+ render(<LoginPage />);++ expect(screen.getByLabelText(/email/i)).toBeDisabled();+ expect(screen.getByLabelText(/password/i)).toBeDisabled();+ const button = screen.getByRole('button', { name: /please wait/i });+ expect(button).toBeDisabled();+ });++ it('does not fire a second request while one is in flight', async () => {+ const user = userEvent.setup();+ // A slow login keeps the mutation pending; the component is driven by+ // `isSubmitting`, so assert the disabled attribute blocks the second click.+ const { rerender } = render(<LoginPage />);+ await fillCredentials(user);++ authState.isSubmitting = true;+ rerender(<LoginPage />);++ const button = screen.getByRole('button', { name: /please wait/i });+ await user.click(button).catch(() => undefined);+ expect(authState.login).not.toHaveBeenCalled();+ });++ it('switches to register mode and requires a display name', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);++ await user.click(screen.getByRole('button', { name: /^register$/i }));+ expect(screen.getByRole('button', { name: /create account/i })).toBeInTheDocument();++ await user.type(screen.getByLabelText(/email/i), '[email protected]');+ await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');+ await user.click(screen.getByRole('button', { name: /create account/i }));++ await waitFor(() => {+ expect(screen.getByText(/display name is required/i)).toBeInTheDocument();+ });+ expect(authState.register).not.toHaveBeenCalled();+ });++ it('enforces the 8-character minimum only when registering', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);++ await user.click(screen.getByRole('button', { name: /^register$/i }));+ await user.type(screen.getByLabelText(/display name/i), 'A');+ await user.type(screen.getByLabelText(/email/i), '[email protected]');+ await user.type(screen.getByLabelText(/password/i), 'short');+ await user.click(screen.getByRole('button', { name: /create account/i }));++ await waitFor(() => {+ expect(screen.getByText(/at least 8 characters/i)).toBeInTheDocument();+ });+ });++ it('registers with a display name', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);++ await user.click(screen.getByRole('button', { name: /^register$/i }));+ await user.type(screen.getByLabelText(/display name/i), 'Alice');+ await user.type(screen.getByLabelText(/email/i), '[email protected]');+ await user.type(screen.getByLabelText(/password/i), 'hunter2hunter2');+ await user.click(screen.getByRole('button', { name: /create account/i }));++ await waitFor(() => {+ expect(authState.register).toHaveBeenCalledWith('[email protected]', 'hunter2hunter2', 'Alice');+ });+ });++ it('clears stale errors when toggling mode', async () => {+ const user = userEvent.setup();+ render(<LoginPage />);+ await user.click(screen.getByRole('button', { name: /^register$/i }));+ expect(authState.resetAuthErrors).toHaveBeenCalled();+ });++ it('shows a connectivity error when there is no submit error', () => {+ authState.error = 'Failed to connect to server';+ render(<LoginPage />);+ expect(screen.getByRole('alert')).toHaveTextContent('Failed to connect to server');+ });++ it('prefers the submit error over the connectivity error', () => {+ authState.error = 'Failed to connect to server';+ authState.submitError = 'Invalid email or password';+ render(<LoginPage />);++ const alerts = screen.getAllByRole('alert');+ expect(alerts).toHaveLength(1);+ expect(alerts[0]).toHaveTextContent('Invalid email or password');+ });+});diff --git a/client/src/components/auth/schemas/login.ts b/client/src/components/auth/schemas/login.tsnew file mode 100644index 00000000..328fd0d5--- /dev/null+++ b/client/src/components/auth/schemas/login.ts@@ -0,0 +1,31 @@+import { z } from 'zod';++/**+ * Validation schema for the login / register form.+ *+ * Mirrors the shape of `credentials/panels/schemas/email.ts` so both forms+ * are validated the same way. Previously this was hand-rolled inside+ * `LoginPage`, which meant email format was never checked client-side --+ * the server uses `EmailStr`, so a malformed address came back as a 422+ * whose `detail` is a list of objects rather than a string.+ */+export function createAuthFormSchema(isRegistering: boolean) {+ return z.object({+ email: z+ .string()+ .min(1, 'Email is required')+ .pipe(z.email('Enter a valid email address')),+ password: isRegistering+ ? z.string().min(8, 'Password must be at least 8 characters')+ : z.string().min(1, 'Password is required'),+ // Required only when registering. The 100-character ceiling mirrors the+ // `max_length=100` column on `User.display_name`; SQLite truncates+ // silently rather than raising, so an over-long name would be accepted+ // and then quietly altered.+ displayName: isRegistering+ ? z.string().trim().min(1, 'Display name is required').max(100, 'Display name must be 100 characters or fewer')+ : z.string().optional(),+ });+}++export type AuthFormValues = z.infer<ReturnType<typeof createAuthFormSchema>>;diff --git a/client/src/components/credentials/panels/EmailPanel.tsx b/client/src/components/credentials/panels/EmailPanel.tsxindex 23c69e08..a1a35407 100644--- a/client/src/components/credentials/panels/EmailPanel.tsx+++ b/client/src/components/credentials/panels/EmailPanel.tsx@@ -43,6 +43,7 @@ import { NodeIcon } from '../../../assets/icons';import { StatusCard } from '../primitives';import {AUTH_NOTES,+ ENCRYPTION_OPTIONS,PROVIDER_OPTIONS,createEmailFormSchema,type EmailFormValues,@@ -53,12 +54,37 @@ const DEFAULT_VALUES: EmailFormValues = {provider: 'gmail',address: '',password: '',+ displayName: '',imapHost: '',imapPort: 993,+ imapEncryption: 'tls',smtpHost: '',smtpPort: 465,+ smtpEncryption: 'tls',};+/** Server-specific keys, written only for the `custom` provider and cleared+ * when switching away from it. */+const CUSTOM_SERVER_KEYS = [+ 'email_imap_host',+ 'email_imap_port',+ 'email_imap_encryption',+ 'email_smtp_host',+ 'email_smtp_port',+ 'email_smtp_encryption',+] as const;++/** Every key this panel owns. `resolve_credentials` in+ * `server/nodes/email/_service.py` reads exactly these — keep the two in+ * sync, or a key becomes unsettable (or un-removable) from the UI. */+const ALL_EMAIL_KEYS = [+ 'email_provider',+ 'email_address',+ 'email_password',+ 'email_display_name',+ ...CUSTOM_SERVER_KEYS,+] as const;+const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {const { saveApiKey, getStoredApiKey, hasStoredKey, removeApiKey, isConnected } = useApiKeys();@@ -85,24 +111,41 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ colet cancelled = false;(async () => {try {- const [providerKey, addr, hasPassword, imapHost, imapPort, smtpHost, smtpPort] = await Promise.all([+ const [+ providerKey,+ addr,+ hasPassword,+ displayName,+ imapHost,+ imapPort,+ imapEncryption,+ smtpHost,+ smtpPort,+ smtpEncryption,+ ] = await Promise.all([getStoredApiKey('email_provider'),getStoredApiKey('email_address'),hasStoredKey('email_password'),+ getStoredApiKey('email_display_name'),getStoredApiKey('email_imap_host'),getStoredApiKey('email_imap_port'),+ getStoredApiKey('email_imap_encryption'),getStoredApiKey('email_smtp_host'),getStoredApiKey('email_smtp_port'),+ getStoredApiKey('email_smtp_encryption'),]);if (cancelled) return;form.reset({provider: providerKey || 'gmail',address: addr || '',password: '',+ displayName: displayName || '',imapHost: imapHost || '',imapPort: imapPort ? parseInt(imapPort, 10) : 993,+ imapEncryption: (imapEncryption as EmailFormValues['imapEncryption']) || 'tls',smtpHost: smtpHost || '',smtpPort: smtpPort ? parseInt(smtpPort, 10) : 465,+ smtpEncryption: (smtpEncryption as EmailFormValues['smtpEncryption']) || 'tls',});setAddress(addr || '');setStored(hasPassword);@@ -120,11 +163,21 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ coawait saveApiKey('email_provider', values.provider);await saveApiKey('email_address', values.address.trim());if (values.password?.trim()) await saveApiKey('email_password', values.password.trim());+ await saveApiKey('email_display_name', values.displayName?.trim() || '');if (values.provider === 'custom') {+ // The `custom` preset is blank server-side, so these stored keys are+ // the only source for host/port/encryption — all six must be written.if (values.imapHost) await saveApiKey('email_imap_host', values.imapHost.trim());if (values.imapPort != null) await saveApiKey('email_imap_port', String(values.imapPort));+ if (values.imapEncryption) await saveApiKey('email_imap_encryption', values.imapEncryption);if (values.smtpHost) await saveApiKey('email_smtp_host', values.smtpHost.trim());if (values.smtpPort != null) await saveApiKey('email_smtp_port', String(values.smtpPort));+ if (values.smtpEncryption) await saveApiKey('email_smtp_encryption', values.smtpEncryption);+ } else {+ // Switching away from `custom` must clear the server-specific keys.+ // Leaving them behind stranded a stale host in the store, which then+ // silently won the `or` chain for any preset field left blank.+ await Promise.all(CUSTOM_SERVER_KEYS.map((key) => removeApiKey(key).catch(() => undefined)));}setStored(true);setAddress(values.address.trim());@@ -140,15 +193,7 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ cosetLoading('remove');setError(null);try {- await Promise.all([- removeApiKey('email_password'),- removeApiKey('email_address'),- removeApiKey('email_provider'),- removeApiKey('email_imap_host'),- removeApiKey('email_imap_port'),- removeApiKey('email_smtp_host'),- removeApiKey('email_smtp_port'),- ]);+ await Promise.all(ALL_EMAIL_KEYS.map((key) => removeApiKey(key)));setStored(false);setAddress('');form.reset(DEFAULT_VALUES);@@ -251,6 +296,24 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ co)}/>+ <FormField+ control={form.control}+ name="displayName"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ Display Name+ <span className="ml-2 text-xs font-normal text-muted-foreground">(optional)</span>+ </FormLabel>+ <FormControl>+ <Input placeholder="Alice Example" {...field} value={field.value ?? ''} />+ </FormControl>+ <FormDescription>Shown as the sender name on outgoing mail.</FormDescription>+ <FormMessage />+ </FormItem>+ )}+ />+{provider === 'custom' && (<div className="rounded-md border border-border bg-muted p-3"><div className="mb-3 text-sm font-medium">Custom IMAP / SMTP</div>@@ -288,6 +351,30 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ co</FormItem>)}/>+ <FormField+ control={form.control}+ name="imapEncryption"+ render={({ field }) => (+ <FormItem className="flex-1">+ <FormLabel>IMAP Security</FormLabel>+ <Select onValueChange={field.onChange} value={field.value ?? 'tls'}>+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {ENCRYPTION_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ /></div><div className="mt-3 flex gap-3"><FormField@@ -323,6 +410,30 @@ const EmailPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ co</FormItem>)}/>+ <FormField+ control={form.control}+ name="smtpEncryption"+ render={({ field }) => (+ <FormItem className="flex-1">+ <FormLabel>SMTP Security</FormLabel>+ <Select onValueChange={field.onChange} value={field.value ?? 'tls'}>+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {ENCRYPTION_OPTIONS.map((opt) => (+ <SelectItem key={opt.value} value={opt.value}>+ {opt.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FormMessage />+ </FormItem>+ )}+ /></div></div>)}diff --git a/client/src/components/credentials/panels/schemas/email.ts b/client/src/components/credentials/panels/schemas/email.tsindex cdd65268..926094e3 100644--- a/client/src/components/credentials/panels/schemas/email.ts+++ b/client/src/components/credentials/panels/schemas/email.ts@@ -22,6 +22,17 @@ export const AUTH_NOTES: Record<string, string> = {const PROVIDER_VALUES = PROVIDER_OPTIONS.map((p) => p.value) as [string, ...string[]];+/** Transport security modes himalaya accepts. Mirrors `_ENCRYPTIONS` in+ * `server/nodes/email/_himalaya.py` — anything else is rejected at+ * config-parse time. */+export const ENCRYPTION_OPTIONS = [+ { label: 'TLS / SSL', value: 'tls' },+ { label: 'STARTTLS', value: 'start-tls' },+ { label: 'None (plaintext)', value: 'none' },+] as const;++const ENCRYPTION_VALUES = ENCRYPTION_OPTIONS.map((e) => e.value) as [string, ...string[]];+/*** Build a zod schema for the email form. Password is required only when no* credential is stored yet (toggle via the `passwordRequired` flag).@@ -37,10 +48,13 @@ export function createEmailFormSchema(passwordRequired: boolean) {password: passwordRequired? z.string().min(1, 'Password is required'): z.string().optional(),+ displayName: z.string().max(200).optional(),imapHost: z.string().optional(),imapPort: z.number().int().min(1).max(65535).optional(),+ imapEncryption: z.enum(ENCRYPTION_VALUES).optional(),smtpHost: z.string().optional(),smtpPort: z.number().int().min(1).max(65535).optional(),+ smtpEncryption: z.enum(ENCRYPTION_VALUES).optional(),}).superRefine((data, ctx) => {if (data.provider !== 'custom') return;@@ -58,6 +72,22 @@ export function createEmailFormSchema(passwordRequired: boolean) {message: 'SMTP host is required for custom provider',});}+ // The `custom` preset is blank server-side so these stored keys are+ // reachable; if the form omits them there is no fallback left.+ if (data.imapPort == null) {+ ctx.addIssue({+ code: 'custom',+ path: ['imapPort'],+ message: 'IMAP port is required for custom provider',+ });+ }+ if (data.smtpPort == null) {+ ctx.addIssue({+ code: 'custom',+ path: ['smtpPort'],+ message: 'SMTP port is required for custom provider',+ });+ }});}diff --git a/client/src/contexts/AuthContext.tsx b/client/src/contexts/AuthContext.tsxindex a2dddff1..e2a1d4cd 100644--- a/client/src/contexts/AuthContext.tsx+++ b/client/src/contexts/AuthContext.tsx@@ -7,20 +7,31 @@* cleanup, Strict-Mode safety, and 401/403 fast-fail are all delegated* to the library — see https://tanstack.com/query/v5/docs/framework/react/guides/query-retries.*- * The context's public surface (user, isAuthenticated, isLoading,- * authMode, canRegister, error, login, register, logout, checkAuth) is- * unchanged so consumer code does not move.- *- * Login / register / logout mutate the auth state by invalidating the- * `['auth', 'status']` query rather than calling a private setter — the+ * Login / register / logout are `useMutation`s that settle by invalidating+ * the `['auth', 'status']` query rather than calling a private setter — the* single source of truth stays the query cache, which TanStack Query* dedupes by reference equality, eliminating the spurious* `isAuthenticated` flips that closed the WS prematurely under React* Strict Mode.+ *+ * Two distinctions the surface makes deliberately, because collapsing+ * either one produced a user-visible bug:+ *+ * `isLoading` vs `isSubmitting` — the former is the bootstrap query and+ * gates the entire app in `ProtectedRoute`; the latter is per-request.+ * Using `isLoading` to disable the login form disabled nothing, since+ * the bootstrap query has long since settled by the time that form+ * renders, so the form accepted unlimited concurrent submits.+ *+ * `error` vs `submitError` — the former means "cannot reach the server",+ * the latter is the server's own rejection text. Login failures used to+ * be written into the status cache as `null`, which is a *success* value:+ * `isError` stayed false so nothing was ever displayed, and+ * `can_register` fell back to false, hiding the Register link entirely.*/import React, { createContext, useContext, useCallback, useMemo } from 'react';-import { useQuery, useQueryClient } from '@tanstack/react-query';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';import { API_CONFIG } from '../config/api';import { AUTH_RETRY } from '../lib/connectionConfig';@@ -42,14 +53,25 @@ export interface AuthStatus {interface AuthContextType {user: User | null;isAuthenticated: boolean;+ /** Bootstrap-query pending state. Gates the whole app in+ * `ProtectedRoute`; NOT a per-submit signal — use `isSubmitting`. */isLoading: boolean;+ /** True while a login/register request is in flight. */+ isSubmitting: boolean;authMode: 'single' | 'multi';canRegister: boolean;+ /** Connectivity error from the bootstrap query only. */error: string | null;+ /** Server-rejection message from the last login/register attempt. */+ submitError: string | null;+ /** Message shown when logout could not be confirmed server-side. */+ logoutError: string | null;login: (email: string, password: string) => Promise<boolean>;register: (email: string, password: string, displayName: string) => Promise<boolean>;logout: () => Promise<void>;checkAuth: () => Promise<void>;+ /** Clear stale submit errors (mode toggle, field edit). */+ resetAuthErrors: () => void;}const AuthContext = createContext<AuthContextType | undefined>(undefined);@@ -85,9 +107,68 @@ const authShouldRetry = (failureCount: number, error: unknown): boolean => {if (failureCount >= AUTH_RETRY.MAX_ATTEMPTS) return false;const msg = error instanceof Error ? error.message : String(error);if (msg.includes('HTTP 401') || msg.includes('HTTP 403')) return false;+ if (msg.includes(NON_RETRYABLE)) return false;return true;};+/** Marks an error as pointless to retry (see `authShouldRetry`). */+const NON_RETRYABLE = 'auth.non-retryable';++const isJsonResponse = (response: Response): boolean =>+ (response.headers.get('content-type') ?? '').toLowerCase().includes('application/json');++/**+ * Turn a FastAPI error body into one displayable string.+ *+ * Three shapes reach us and only the first was ever handled:+ * - `{"detail": "Invalid email or password"}` — HTTPException+ * - `{"detail": [{"msg": ..., "loc": [...]}]}` — 422 request validation+ * - anything non-JSON — proxy/SPA-fallback HTML+ */+const extractErrorMessage = (body: unknown, fallback: string): string => {+ if (typeof body === 'string' && body.trim()) return body;+ if (body && typeof body === 'object') {+ const detail = (body as { detail?: unknown }).detail;+ if (typeof detail === 'string' && detail.trim()) return detail;+ if (Array.isArray(detail)) {+ const messages = detail+ .map((item) => (item && typeof item === 'object' ? (item as { msg?: unknown }).msg : null))+ .filter((msg): msg is string => typeof msg === 'string' && msg.trim().length > 0);+ if (messages.length) return messages.join('; ');+ }+ }+ return fallback;+};++/** POST to an auth endpoint, throwing an Error whose message is display-ready. */+const postAuth = async (path: string, payload: unknown): Promise<{ user: User }> => {+ const response = await fetch(`${getApiBase()}${path}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify(payload),+ });++ let body: unknown = null;+ if (isJsonResponse(response)) {+ try {+ body = await response.json();+ } catch {+ body = null;+ }+ }++ if (!response.ok) {+ throw new Error(extractErrorMessage(body, `Request failed (HTTP ${response.status})`));+ }++ const parsed = body as { success?: boolean; user?: User } | null;+ if (!parsed?.success || !parsed.user) {+ throw new Error(extractErrorMessage(body, 'Unexpected response from server'));+ }+ return { user: parsed.user };+};+const fetchAuthStatus = async ({ signal }: { signal: AbortSignal }): Promise<AuthStatus> => {const response = await fetch(`${getApiBase()}/status`, {credentials: 'include',@@ -98,6 +179,13 @@ const fetchAuthStatus = async ({ signal }: { signal: AbortSignal }): Promise<Aut// 401/403 without parsing the original Response.throw new Error(`auth.status: HTTP ${response.status}`);}+ // A 200 carrying HTML means the SPA fallback swallowed /api/auth/status --+ // usually a proxy misroute. Retrying cannot turn HTML into JSON, and the+ // raw SyntaxError message matches none of the fast-fail checks, so it used+ // to burn the entire retry budget on an unrecoverable condition.+ if (!isJsonResponse(response)) {+ throw new Error(`auth.status: ${NON_RETRYABLE} (non-JSON response)`);+ }return response.json() as Promise<AuthStatus>;};@@ -139,40 +227,70 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children[queryClient],);- const login = useCallback(async (email: string, password: string): Promise<boolean> => {- try {- const response = await fetch(`${getApiBase()}/login`, {+ // Optimistically write the authenticated user so the UI updates this+ // render, then invalidate so the refetch supplies the server-derived+ // fields (auth_mode, can_register). `invalidateQueries` still refetches+ // despite `staleTime: Infinity` — it marks stale AND refetches actives.+ const applyAuthenticatedUser = useCallback((nextUser: User) => {+ queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, (prev) => ({+ auth_enabled: true,+ auth_mode: prev?.auth_mode ?? 'single',+ authenticated: true,+ user: nextUser,+ can_register: prev?.can_register ?? false,+ }));+ return invalidateAuth();+ }, [queryClient, invalidateAuth]);++ const loginMutation = useMutation({+ mutationFn: ({ email, password }: { email: string; password: string }) =>+ postAuth('/login', { email, password }),+ onSuccess: ({ user: nextUser }) => applyAuthenticatedUser(nextUser),+ });++ const registerMutation = useMutation({+ mutationFn: ({ email, password, displayName }: {+ email: string; password: string; displayName: string;+ }) => postAuth('/register', { email, password, display_name: displayName }),+ onSuccess: ({ user: nextUser }) => applyAuthenticatedUser(nextUser),+ });++ const logoutMutation = useMutation({+ mutationFn: async () => {+ const response = await fetch(`${getApiBase()}/logout`, {method: 'POST',- headers: { 'Content-Type': 'application/json' },credentials: 'include',- body: JSON.stringify({ email, password }),});- const body = await response.json();-- if (!response.ok || !body.success || !body.user) {- // Surface the server's error via the query cache so `error` flips- // through the same path as a normal `isError` would.- queryClient.setQueryData<AuthStatus | null>(AUTH_STATUS_QUERY_KEY, null);- return false;+ // Do NOT swallow this. The cookie is HttpOnly, so if the server did+ // not clear it the client cannot either — the user looks logged out+ // until a reload silently restores the session.+ if (!response.ok) {+ throw new Error(`Logout may not have completed (HTTP ${response.status}). Reload to confirm.`);}-- // Optimistically write the new user into the cache so the UI- // updates this render; then invalidate so the next refetch- // picks up server-derived fields (auth_mode, can_register).- queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, {- auth_enabled: true,- auth_mode: authMode,- authenticated: true,- user: body.user,- can_register: false,- });+ },+ // onSettled, not onSuccess: consumers (notably the WebSocket teardown+ // effect) must see `authenticated: false` on this render regardless of+ // whether the server confirmed.+ onSettled: async () => {+ queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, (prev) => ({+ ...(prev ?? { auth_enabled: true, auth_mode: 'single' as const, can_register: false }),+ authenticated: false,+ user: null,+ }));await invalidateAuth();+ },+ });++ const login = useCallback(async (email: string, password: string): Promise<boolean> => {+ try {+ await loginMutation.mutateAsync({ email, password });return true;- } catch (err) {- console.error('Login error:', err);+ } catch {+ // The message is on `loginMutation.error`; swallow so the caller is+ // not forced into a try/catch for an expected outcome.return false;}- }, [queryClient, invalidateAuth, authMode]);+ }, [loginMutation]);const register = useCallback(async (email: string,@@ -180,71 +298,57 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ childrendisplayName: string,): Promise<boolean> => {try {- const response = await fetch(`${getApiBase()}/register`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- credentials: 'include',- body: JSON.stringify({ email, password, display_name: displayName }),- });- const body = await response.json();-- if (!response.ok || !body.success || !body.user) {- return false;- }-- queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, {- auth_enabled: true,- auth_mode: authMode,- authenticated: true,- user: body.user,- can_register: false,- });- await invalidateAuth();+ await registerMutation.mutateAsync({ email, password, displayName });return true;- } catch (err) {- console.error('Register error:', err);+ } catch {return false;}- }, [queryClient, invalidateAuth, authMode]);+ }, [registerMutation]);const logout = useCallback(async () => {try {- await fetch(`${getApiBase()}/logout`, {- method: 'POST',- credentials: 'include',- });- } catch (err) {- console.error('Logout error:', err);- } finally {- // Force `authenticated: false` immediately so consumers (esp. the- // WebSocket logout effect) react this render; then refetch so- // `can_register` and `auth_mode` come back fresh.- queryClient.setQueryData<AuthStatus>(AUTH_STATUS_QUERY_KEY, (prev) => ({- ...(prev ?? { auth_enabled: true, auth_mode: 'single' as const, can_register: false }),- authenticated: false,- user: null,- }));- await invalidateAuth();+ await logoutMutation.mutateAsync();+ } catch {+ // Surfaced via `logoutError`.}- }, [queryClient, invalidateAuth]);+ }, [logoutMutation]);+ // Deliberately NOT `authQuery.refetch()`: `authQuery`'s identity changes on+ // essentially every render, which churned `checkAuth`, which broke the+ // context `useMemo` below and re-rendered every `useAuth()` consumer on+ // every provider render.const checkAuth = useCallback(async () => {- await authQuery.refetch();- }, [authQuery]);+ await queryClient.refetchQueries({ queryKey: AUTH_STATUS_QUERY_KEY });+ }, [queryClient]);++ const resetAuthErrors = useCallback(() => {+ loginMutation.reset();+ registerMutation.reset();+ }, [loginMutation, registerMutation]);++ const isSubmitting = loginMutation.isPending || registerMutation.isPending;+ const submitError =+ (loginMutation.error instanceof Error ? loginMutation.error.message : null) ??+ (registerMutation.error instanceof Error ? registerMutation.error.message : null);+ const logoutError = logoutMutation.error instanceof Error ? logoutMutation.error.message : null;const value: AuthContextType = useMemo(() => ({user,isAuthenticated,isLoading,+ isSubmitting,authMode,canRegister,error,+ submitError,+ logoutError,login,register,logout,checkAuth,- }), [user, isAuthenticated, isLoading, authMode, canRegister, error,- login, register, logout, checkAuth]);+ resetAuthErrors,+ }), [user, isAuthenticated, isLoading, isSubmitting, authMode, canRegister, error,+ submitError, logoutError, login, register, logout, checkAuth, resetAuthErrors]);return (<AuthContext.Provider value={value}>diff --git a/client/src/contexts/__tests__/AuthContext.test.tsx b/client/src/contexts/__tests__/AuthContext.test.tsxindex 7d2a3fb4..d8c39a27 100644--- a/client/src/contexts/__tests__/AuthContext.test.tsx+++ b/client/src/contexts/__tests__/AuthContext.test.tsx@@ -219,3 +219,269 @@ describe('AuthContext (TanStack Query)', () => {});});});++// ---------------------------------------------------------------------------+// login / register+//+// These had NO coverage, which is precisely where the bugs were: server+// rejections were parsed and then thrown away, a failed login poisoned the+// status cache with `null` (hiding the Register link), and `isLoading` was+// wired to the bootstrap query so the form never disabled.+// ---------------------------------------------------------------------------++const STATUS_BODY = {+ auth_enabled: true,+ auth_mode: 'single' as const,+ authenticated: false,+ user: null,+ can_register: true,+};++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ });++/** Mock /status plus one scripted response for /login or /register. */+function mockAuthEndpoints(handler: (url: string) => Response | undefined) {+ return vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {+ const url = typeof input === 'string' ? input : (input as Request).url;+ const scripted = handler(url);+ if (scripted) return scripted;+ return json(STATUS_BODY);+ });+}++async function mountProbe(client: QueryClient) {+ const { states, Probe } = makeProbe();+ render(+ <Wrapper client={client}>+ <Probe />+ </Wrapper>,+ );+ await waitFor(() => expect(states[states.length - 1].isLoading).toBe(false));+ return {+ states,+ latest: () => states[states.length - 1],+ };+}++describe('AuthContext login/register', () => {+ it('surfaces the server detail string on a failed login', async () => {+ mockAuthEndpoints((url) =>+ url.endsWith('/login')+ ? json({ detail: 'Invalid email or password' }, 401)+ : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());++ let returned: boolean | undefined;+ await act(async () => {+ returned = await latest().login('[email protected]', 'wrong');+ });++ expect(returned).toBe(false);+ await waitFor(() => {+ expect(latest().submitError).toBe('Invalid email or password');+ });+ });++ it('keeps canRegister true after a failed login', async () => {+ // The regression: login failure wrote `null` into the status cache, so+ // `can_register` fell back to false and the Register link vanished until+ // a full page reload.+ mockAuthEndpoints((url) =>+ url.endsWith('/login') ? json({ detail: 'Invalid email or password' }, 401) : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());+ expect(latest().canRegister).toBe(true);++ await act(async () => {+ await latest().login('[email protected]', 'wrong');+ });++ await waitFor(() => expect(latest().submitError).not.toBeNull());+ expect(latest().canRegister).toBe(true);+ });++ it('renders a 422 validation array as a readable string', async () => {+ mockAuthEndpoints((url) =>+ url.endsWith('/register')+ ? json(+ {+ detail: [+ { msg: 'value is not a valid email address', loc: ['body', 'email'] },+ { msg: 'String should have at least 1 character', loc: ['body', 'display_name'] },+ ],+ },+ 422,+ )+ : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());++ await act(async () => {+ await latest().register('nope', 'hunter2hunter2', '');+ });++ await waitFor(() => {+ const message = latest().submitError;+ expect(message).toContain('valid email address');+ // Never the raw "[object Object]" the old path would have produced.+ expect(message).not.toContain('object');+ });+ });++ it('surfaces a rate-limit 429 detail verbatim', async () => {+ mockAuthEndpoints((url) =>+ url.endsWith('/login')+ ? json({ detail: 'Too many attempts. Please wait and try again.' }, 429)+ : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());+ await act(async () => {+ await latest().login('[email protected]', 'whatever');+ });++ await waitFor(() => {+ expect(latest().submitError).toContain('Too many attempts');+ });+ });++ it('falls back to a generic message when the error body is not JSON', async () => {+ mockAuthEndpoints((url) =>+ url.endsWith('/login')+ ? new Response('<html>502 Bad Gateway</html>', {+ status: 502,+ headers: { 'Content-Type': 'text/html' },+ })+ : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());+ await act(async () => {+ await latest().login('[email protected]', 'pw');+ });++ await waitFor(() => {+ expect(latest().submitError).toContain('502');+ });+ });++ it('sets the user and clears submitError on a successful login', async () => {+ // Stateful on purpose: `onSuccess` writes the user optimistically and then+ // invalidates, so /status refetches and is authoritative. A mock that kept+ // reporting `authenticated: false` would (correctly) undo the login.+ const user = { id: 7, email: '[email protected]', display_name: 'A', is_owner: true };+ let loggedIn = false;++ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {+ const url = typeof input === 'string' ? input : (input as Request).url;+ if (url.endsWith('/login')) {+ loggedIn = true;+ return json({ success: true, user });+ }+ return json({+ ...STATUS_BODY,+ authenticated: loggedIn,+ user: loggedIn ? user : null,+ });+ });++ const { latest } = await mountProbe(makeQueryClient());++ let returned: boolean | undefined;+ await act(async () => {+ returned = await latest().login('[email protected]', 'correct-horse');+ });++ expect(returned).toBe(true);+ await waitFor(() => {+ expect(latest().user?.email).toBe('[email protected]');+ expect(latest().submitError).toBeNull();+ });+ });++ it('resetAuthErrors clears a stale submit error', async () => {+ mockAuthEndpoints((url) =>+ url.endsWith('/login') ? json({ detail: 'Invalid email or password' }, 401) : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());+ await act(async () => {+ await latest().login('[email protected]', 'wrong');+ });+ await waitFor(() => expect(latest().submitError).not.toBeNull());++ await act(async () => {+ latest().resetAuthErrors();+ });+ await waitFor(() => expect(latest().submitError).toBeNull());+ });++ it('does not retry a non-JSON 200 from /status', async () => {+ // A 200 carrying HTML means the SPA fallback swallowed the API route.+ // Retrying cannot turn HTML into JSON, and the raw SyntaxError matched+ // none of the fast-fail checks, so this burned the whole retry budget.+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response('<!doctype html><html></html>', {+ status: 200,+ headers: { 'Content-Type': 'text/html' },+ }),+ );++ const client = makeQueryClient({ retry: 5 });+ const { states, Probe } = makeProbe();+ render(+ <Wrapper client={client}>+ <Probe />+ </Wrapper>,+ );++ await waitFor(() => {+ expect(states[states.length - 1].isLoading).toBe(false);+ });+ expect(fetchSpy).toHaveBeenCalledTimes(1);+ });++ it('reports a logout that the server did not confirm', async () => {+ mockAuthEndpoints((url) =>+ url.endsWith('/logout') ? new Response('', { status: 500 }) : undefined,+ );++ const { latest } = await mountProbe(makeQueryClient());+ await act(async () => {+ await latest().logout();+ });++ await waitFor(() => {+ // Local state still flips (the WS teardown depends on it) ...+ expect(latest().isAuthenticated).toBe(false);+ // ... but the failure is no longer silent.+ expect(latest().logoutError).not.toBeNull();+ });+ });++ it('keeps the context value referentially stable across re-renders', async () => {+ // `checkAuth` used to depend on `authQuery`, whose identity changes on+ // essentially every render, breaking the context useMemo and re-rendering+ // every useAuth() consumer in the app.+ mockAuthEndpoints(() => undefined);++ const client = makeQueryClient();+ const { states } = await mountProbe(client);++ const before = states[states.length - 1];+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve, 10));+ });+ const after = states[states.length - 1];++ expect(after).toBe(before);+ });+});diff --git a/docs-internal/authentication.md b/docs-internal/authentication.mdindex 451c1c51..64d58bf6 100644--- a/docs-internal/authentication.md+++ b/docs-internal/authentication.md@@ -53,17 +53,32 @@ class User(SQLModel, table=True):```### Auth Service (`server/services/user_auth.py`)-- `register_user()` - Creates new user, sets as owner if first user in single mode-- `authenticate_user()` - Validates credentials, returns user-- `create_token()` - Generates JWT token+- `register()` - Creates a new user; sets `is_owner` if first user in single mode.+ Eligibility checks and the INSERT share ONE session (they used to span four,+ so two concurrent first-registrations could both be granted ownership), and a+ `IntegrityError` on the email UNIQUE index returns a 400-shaped error rather+ than surfacing as a 500.+- `login()` - Validates credentials, returns `(user, error)`. Every rejection+ returns the same `"Invalid email or password"`, and the unknown-email path+ still runs a bcrypt comparison against a dummy hash — distinct messages and+ an early return were both account-enumeration oracles on a public endpoint.+- `create_access_token()` - Mints the JWT (HS256, `sub`/`email`/`display_name`/+ `is_owner`/`exp`/`iat`/`nbf`/`jti`). No `iss`/`aud`: enforcing them would+ invalidate every token already held by a browser for negligible benefit in a+ single-audience app with a per-deployment secret.- `verify_token()` - Validates JWT token-- `get_auth_status()` - Returns mode, registration availability, user count--`UserAuthService` is also the integration point for the encrypted-credentials-system: `login()` calls `_initialize_encryption(password)` (derives the Fernet-key via PBKDF2 from the user's password + the credentials DB salt) and-`logout()` calls `self.encryption.clear()` to wipe the key from memory. See-[Credentials Encryption](./credentials_encryption.md) for the full pipeline.+- `get_current_user()` - Resolves the token's subject to a `User`, rejecting a+ non-numeric `sub` and any account with `is_active = False`+- `get_auth_status()` - Returns `auth_mode` and `registration_enabled`+- `logout()` - A no-op log line. See Known Limitations.++**`UserAuthService` does not touch the encryption service.** Earlier revisions+of this document described `login()` calling `_initialize_encryption(password)`+and `logout()` calling `self.encryption.clear()`. Neither method has ever+existed. The Fernet key is **server-scoped**: initialised once during startup+in `main.py` from `API_KEY_ENCRYPTION_KEY`, never derived from a user password+and never cleared on logout. See+[Credentials Encryption](./credentials_encryption.md) for the real pipeline.### Auth Router (`server/routers/auth.py`)| Endpoint | Method | Description |@@ -129,9 +144,19 @@ const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) =```### Login Page (`client/src/components/auth/LoginPage.tsx`)-- Dracula-themed login/register form-- Switches between login and register based on `canRegister`-- Displays errors from auth context+- shadcn `Form` composition (react-hook-form + zod), matching `EmailPanel` —+ schema in `components/auth/schemas/login.ts`. `FormControl` supplies+ `aria-invalid` + `aria-describedby` per field; the form is `noValidate` so+ zod is the single validation authority rather than native browser bubbles.+- `canRegister` gates the footer link only; the mode itself is local state.+- **Two error channels, deliberately distinct.** `submitError` is the server's+ own rejection text (wrong password, duplicate email, 429) and takes+ precedence; `error` is a bootstrap-query connectivity failure. Both render in+ a `role="alert"` region.+- Inputs and the submit button gate on `isSubmitting` (per-request), **not**+ `isLoading` (bootstrap query). The latter has always settled by the time this+ page renders, so using it disabled nothing and the form accepted unlimited+ concurrent submits.## ConfigurationEnvironment variables in `.env`:@@ -145,9 +170,53 @@ JWT_SECRET_KEY=your-secret-key-32 # Min 32 charsJWT_EXPIRE_MINUTES=10080 # 7 daysJWT_COOKIE_NAME=opencompany_tokenJWT_COOKIE_SECURE=false # true for HTTPS-JWT_COOKIE_SAMESITE=lax+JWT_COOKIE_SAMESITE=lax # 'none' REQUIRES SECURE=true (enforced)++# Login/registration throttling (core/rate_limit.py)+AUTH_RATE_LIMIT_ENABLED=true+AUTH_RATE_LIMIT_ATTEMPTS=10 # per window, per (client IP, email)+AUTH_RATE_LIMIT_WINDOW=300 # seconds```+`cookie_posture_warnings(settings)` (in `core/config.py`, beside+`dev_secret_offenders`) logs a non-fatal banner at startup for an insecure+cookie outside `DEPLOYMENT_MODE=local`, and for `"*"` in `CORS_ORIGINS` while+credentialed CORS is on. Warnings rather than failures on purpose: `company+deploy` intentionally sets `JWT_COOKIE_SECURE=false` because the VM is reached+over plain HTTP on its IP, so raising would break every LAN/IP deployment with+the worst possible symptom — login appearing to succeed, then immediately+logging out. The one combination that *does* hard-fail is+`JWT_COOKIE_SAMESITE=none` with `JWT_COOKIE_SECURE=false`, which no browser+accepts.++## Known Limitations++Recorded explicitly because each of these is easy to assume is handled.++- **`AUTH_MODE=multi` provides authentication, not isolation.**+ `middleware/auth.py` writes `request.state.user_id` / `user_email` /+ `is_owner`, and **no file in `server/` reads them** — the only `user_id` in+ the data layer is the literal `"default"`. Every registered user therefore+ shares one workflow store and one credential store, and `is_owner` is+ decorative. Real per-user scoping touches the whole data layer and needs its+ own design pass; until then treat `multi` as "several people who fully trust+ each other".+- **No CSRF token.** The API is cookie-authenticated and `SameSite` is the only+ defence. Mitigated by every mutating endpoint being `POST` under `/api/` and+ by `SameSite=none` + insecure being rejected at startup. A real double-submit+ scheme would touch every `fetch` and the WebSocket handshake.+- **No token revocation.** `logout` clears the cookie; there is no `jti`+ denylist, so a token captured beforehand stays valid until `exp` (default 7+ days). The practical lever is `User.is_active`, enforced in+ `get_current_user`.+- **Rate-limit counters are per-process** — see `core/rate_limit.py`.+- **`/docs`, `/redoc`, `/openapi.json` are served only when auth is disabled or+ `DEPLOYMENT_MODE=local`.** They were previously public on every deployment+ because `AuthMiddleware` gates by exclusion: any GET/HEAD outside `/api/` and+ `/ws/` is unauthenticated so the SPA shell can load pre-login. That rule is+ safe only while every router lives under `/api/`; the invariant test in+ `tests/auth/test_auth_middleware.py` fails if a new router breaks it.+`core/config.py` carries the `vite_auth_enabled` field (required becausePydantic Settings uses `extra="forbid"`). It also exposes `DEV_SECRET_LITERALS`and `dev_secret_offenders()`: server startup (lifespan) logs a non-fatal errordiff --git a/docs-internal/email_service.md b/docs-internal/email_service.mdindex 041fda08..3c40fb68 100644--- a/docs-internal/email_service.md+++ b/docs-internal/email_service.md@@ -9,7 +9,7 @@ IMAP/SMTP email integration via the [Himalaya CLI](https://github.com/pimalaya/h│ EmailService (singleton) ││ │plugin ──────────► resolve_credentials(params) -> dict │- execute_op │ params > preset (email_providers.json) │+ @Operation │ preset (email_providers.json) > stored │(nodes/email/...) │ > stored API keys (AuthService) ││ ││ send(params) -> dict │@@ -41,14 +41,13 @@ via its `himalaya` property (lazy import).emailSend node│▼-EmailSendNode.execute_op (server/nodes/email/email_send/__init__.py)+EmailSendNode @Operation("send") (server/nodes/email/email_send/__init__.py)│▼EmailService.send(params)│├── resolve_credentials(params)- │ node params > email_providers.json preset- │ > stored "email_*" API keys+ │ email_providers.json preset > stored "email_*" API keys│▼HimalayaService.send_email(creds, to, subject, body, ...)@@ -69,11 +68,27 @@ For every field in the returned credentials dict:| Priority | Source | Example ||---|---|---|-| 1 (highest) | **Node parameter** (per-node override) | `params["imap_host"]` |-| 2 | **Provider preset** from `email_providers.json` | `providers.gmail.imap_host = "imap.gmail.com"` |-| 3 (lowest) | **Stored API key** via `AuthService.get_api_key()` | `email_imap_host` |--Custom/self-hosted providers rely on stored custom keys because their presets are empty. Gmail and other named presets skip the custom-key lookup because the preset always wins first.+| 1 (highest) | **Provider preset** from `email_providers.json` | `providers.gmail.imap_host = "imap.gmail.com"` |+| 2 (lowest) | **Stored API key** via `AuthService.get_api_key()` | `email_imap_host` |++`provider` itself is the one field still read from node parameters, because it+*is* declared on all three Params models.++**Credentials are not readable from node parameters, by design.** There used to+be a documented third tier above these two (`params["imap_host"]`,+`params["password"]`, …). It never worked: the keys were not declared on any+Params model and all three set `extra="ignore"`, so Pydantic stripped them+before `model_dump()` and every `params.get(...)` returned `None`. Declaring+them to revive the tier is not an option either — `ToolNode.as_tool_schema`+dumps `Params.model_json_schema()` wholesale with no field-exclusion hook, so a+declared `password` becomes an argument the LLM can pass to a callable tool.++The `custom` provider's preset is **entirely blank**, which is what makes the+stored keys reachable for a self-hosted server. Do not put default ports or+encryption values back into it: `resolve_credentials` falls through an `or`+chain, so a non-empty preset value shadows the stored key and makes it+unsettable. That is exactly what pinned self-hosted servers to 993/465/tls.+Defaults live in `_himalaya._toml_port` / `_toml_encryption` instead.## Key Files@@ -92,7 +107,7 @@ Self-contained plugin folder (Wave 11.I) — everything email-specific lives und| `server/nodes/email/email_{send,read,receive}/icon.svg` + `meta.json` | Per-plugin icon (served at `/api/schemas/nodes/<type>/icon`) + color metadata. || `server/config/email_providers.json` | Provider presets (IMAP/SMTP host/port/encryption per provider) + defaults + polling config. Cached on first load. || `server/constants.py` | `EMAIL_TYPES`, `EMAIL_TOOL_TYPES`, plus `emailReceive` in `POLLING_TRIGGER_TYPES` and `WORKFLOW_TRIGGER_TYPES`. |-| `client/src/components/CredentialsModal.tsx` | Email credentials panel (provider dropdown, email/password inputs, conditional custom IMAP/SMTP section). |+| `client/src/components/credentials/panels/EmailPanel.tsx` + `panels/schemas/email.ts` | Email credentials panel (provider dropdown, email/password/display-name inputs, conditional custom IMAP/SMTP + encryption section). |**AI tool schema** is derived automatically from each plugin's `Params` Pydantic model — there is no hand-written `EmailSendSchema` / `EmailReadSchema`. Dual-purpose dispatch goes through the generic plugin fast-path in `server/services/handlers/tools.py` (`instance.execute_as_tool(...)`), not a per-email `_execute_email_tool` branch.@@ -102,20 +117,28 @@ Self-contained plugin folder (Wave 11.I) — everything email-specific lives und### `async resolve_credentials(params: Dict) -> Dict`-Async. Builds the credentials dict consumed by `HimalayaService` (reads stored keys via `AuthService.get_api_key`). Required before every operation. Raises `ValueError` if the email address or password is not set (neither in params nor stored).+Async. Builds the credentials dict consumed by `HimalayaService` (reads stored keys via `AuthService.get_api_key`). Required before every operation. Raises `ValueError` if the stored email address or password is missing.Returned keys:- `email` (str, required) — account address, used as IMAP/SMTP login- `password` (str, required) — raw password or app password-- `display_name` (str) — optional display name (only written to TOML if non-empty)+- `display_name` (str) — from the stored `email_display_name` key; written to TOML only when non-empty- `imap_host`, `imap_port`, `imap_encryption` — resolved via precedence chain- `smtp_host`, `smtp_port`, `smtp_encryption` — resolved via precedence chain-Ports come from any level of precedence as `int` (the internal `_coerce_port` helper converts stored string values safely).+Stored port values arrive as strings and go through `_coerce_port`, which+returns `None` rather than raising on garbage. **Every port and encryption key+is always present in the returned dict, sometimes valued `None`** — which is+why `_generate_config` must use `_toml_port(creds.get("imap_port"), 993)` and+not `creds.get("imap_port", 993)`: the key *is* present, so `dict.get`'s+default never fires and `backend.port = None` renders as unparseable TOML.++`display_name` resolves from the stored `email_display_name` key (written by the+credentials panel), not from node parameters.### `send(params: Dict) -> Dict`-Resolves credentials, calls `HimalayaService.send_email()`, and returns the result merged with `{"from": creds["email"]}`. Validates `to` and `subject` are non-empty.+Resolves credentials, calls `HimalayaService.send_email()`, and returns the result merged with `{"from": creds["email"]}`.### `read(params: Dict) -> Dict`@@ -137,6 +160,17 @@ Return shape: `{"operation": ..., "folder": ..., ...data}` where `data` is mergeReads polling config from `email_providers.json` (`polling.interval`, `polling.min_interval`, `polling.max_interval`) and clamps the user-provided `poll_interval` into range. Returns `{"interval", "folder", "mark_as_read"}`.+Every field is **coerced, not trusted**: `emailReceive` overrides `execute()`+and passes raw parameters, so the Pydantic `ge=30, le=3600` guard never runs on+that path and `poll_interval` can arrive as `None` or a string.+`dict.get(key, default)` only substitutes when the key is *absent*, so an+explicit `None` used to reach `min()` and raise `TypeError`. Mirrors+`PollingTriggerNode._clamp_interval`.++Note this clamp applies only to the interactive Run path. The deployment path+re-clamps through `PollingTriggerNode._clamp_interval`, so the JSON+`polling.interval` is not consulted there.+### Polling helpers- `poll_ids(creds, folder) -> Set[str]` — Calls `list_envelopes` with `baseline_page_size` (from JSON config), extracts envelope IDs as strings for baseline/diff.@@ -150,12 +184,12 @@ Reads polling config from `email_providers.json` (`polling.interval`, `polling.mEvery operation follows the same pattern inside `execute()`:-1. `ensure_binary()` — locate `himalaya` on `PATH` via `shutil.which`. Caches the path on the singleton. Raises `RuntimeError` with install instructions if missing.+1. `ensure_binary()` — locate `himalaya` on `PATH` via `shutil.which`. Caches the path on the singleton. Raises `RuntimeError` with install instructions if missing. Despite the name it installs nothing; see "Installation Requirement" below.2. `_generate_config(account_name, credentials)` — build TOML config as a single string (no template file; uses Python f-strings).3. `tempfile.NamedTemporaryFile(suffix=".toml", delete=False)` — write config to a temp file.4. `asyncio.create_subprocess_exec(binary, -c <tmp>, -a <account>, --output json, <args>)`5. Pipe `stdin_data` if provided (used by `send_email` to deliver the MIME message).-6. `asyncio.wait_for(proc.communicate(...), timeout=60)` — enforces a 60s budget.+6. Delegates to `services.events.cli.run_cli_command`, which enforces the `cli.timeout_seconds` budget from `email_providers.json` AND tree-kills the child on timeout. `asyncio.wait_for` cancels only the wrapper, so the old inline call left an orphaned process holding the temp config open -- and the `finally` unlink then raised PermissionError on Windows, masking the timeout.7. Parse JSON stdout (`json.loads`). Fall back to `{"raw_output": stdout_str}` on JSON decode error.8. `finally`: delete the temp config file with `Path.unlink(missing_ok=True)`.@@ -218,7 +252,7 @@ Read/search/manage emails via IMAP. Group: `['email', 'tool']`. Two outputs (`ma| `flag` | flag | Seen / Answered / Flagged / Draft / Deleted || `flag_action` | flag | add / remove || `page` | list | default 1 |-| `page_size` | list | default 20, max 100 |+| `page_size` | list | default 20, max 500 |**AI tool schema:** derived from `EmailReadParams`, exposing every operation and all operation-specific fields. The LLM picks an `operation` and fills the relevant subset.@@ -232,13 +266,13 @@ Group: `['email', 'trigger']`. No inputs. Single output `main` with the new emai| `provider` | gmail | Provider preset || `folder` | INBOX | Mailbox to monitor || `poll_interval` | 60 | seconds (clamped 30..3600) |-| `filter_query` | `""` | Server-side filter (currently applied client-side in `build_email_filter`) |+| `filter_query` | `""` | Case-insensitive substring match over subject / from / to / body, applied in `_filters.build_filter` || `mark_as_read` | false | If true, adds `Seen` flag to new messages after fetch |**Baseline detection:** On first execution the handler calls `poll_ids(creds, folder)` to capture the set of currently-existing envelope IDs. The poll loop then diffs against this baseline -- only newly appearing IDs trigger the workflow. This avoids firing on existing historical mail.**Standalone event dispatch:** When a new message arrives during an interactive-Run, `EmailReceiveNode.execute_op`:+Run, `EmailReceiveNode.execute()` (a plain override, not an @Operation):1. Fetches full detail via `fetch_detail`2. Optionally flags it as read3. Calls `dispatch_email_received(email_data)` (in `_events.py`), which builds a `WorkflowEvent` (`type="com.opencompany.email.message.received"`) and routes it through `dispatch.emit`@@ -264,7 +298,7 @@ The poll loop:2. Establishes the baseline via `svc.poll_ids(creds, folder)`3. On each iteration (clamped interval from `resolve_poll_params`):- Polls for current IDs and computes `new_ids = current - seen`- - For each new ID: fetches detail, optionally marks read, dispatches the event+ - For each new ID, oldest UID first: fetches detail, optionally marks read, dispatches the event. The envelope returned to the canvas is the FIRST message; earlier revisions dispatched only one and dropped the rest.- Handles `asyncio.CancelledError` cleanly on teardownAll credential resolution and IMAP access still delegate to `EmailService` —@@ -299,7 +333,7 @@ These custom keys are **only used when the preset for the selected provider has### Credentials Modal UI-**File:** `client/src/components/CredentialsModal.tsx`+**File:** `client/src/components/credentials/panels/EmailPanel.tsx`The Email category appears between Productivity and Android in the sidebar. The panel provides:@@ -311,7 +345,7 @@ The Email category appears between Productivity and Android in the sidebar. The- IMAP host (text) + IMAP port (number, default 993)- SMTP host (text) + SMTP port (number, default 465)- **Save** button — writes `email_provider`, `email_address`, and conditionally `email_password` (only if user typed a new one) + the four custom IMAP/SMTP keys when applicable.-- **Remove** button — clears all seven `email_*` keys.+- **Remove** button — clears all ten `email_*` keys. Switching away from the `custom` provider also clears the six server-specific keys, which otherwise stranded a stale host that then won the `or` chain.Status is shown via `getSpecialStatus(item)` returning `{ connected: !!emailStored, label: emailAddress || 'Not configured' }`. No WebSocket connection is needed because email credentials are pure API keys (no live session like Telegram or WhatsApp).@@ -366,7 +400,7 @@ Status is shown via `getSpecialStatus(item)` returning `{ connected: !!emailStorLoaded lazily by the module-level `_load_config()` in `_service.py` and cached in a module-level `_CONFIG` variable (surfaced through `EmailService.config` / `.defaults` / `.polling` properties). To add a new provider, edit only this JSON — no code changes required.-**Zero magic numbers:** every default, clamp, and preset lives in this file. `resolve_poll_params` reads the polling defaults; `EmailService.read()` reads `defaults.page_size`, `defaults.flag`, etc.; the provider dropdown options in `CredentialsModal.tsx` mirror the `providers` keys.+**Config-driven, with named exceptions.** `resolve_poll_params` reads the polling defaults, `EmailService.read()` reads `defaults.page_size` / `defaults.flag`, and `HimalayaService.execute` reads `cli.timeout_seconds`. Three values deliberately live in code rather than here: the port and encryption fallbacks in `_himalaya._toml_port` / `_toml_encryption` (they must NOT be in the `custom` preset, which would shadow the stored keys), and `EmailReceiveNode.poll_interval_clamp`, which the deployment path uses instead of the JSON clamp. The provider dropdown options and auth notes are duplicated in `panels/schemas/email.ts` with no test asserting they stay in sync with the `providers` keys.## Installation Requirement@@ -410,3 +444,35 @@ cargo install himalaya- [Event Waiter System](./event_waiter_system.md) — trigger registration for `emailReceive`- [New Service Integration](./new_service_integration.md) — end-to-end integration pattern (use Google Workspace as a richer OAuth example)- [Credentials Encryption](./credentials_encryption.md) — how `email_*` keys are encrypted on disk++## Security notes++**TOML generation escapes everything.** `_generate_config` routes every+interpolated credential through `_toml_str` / `_toml_port` /+`_toml_encryption`. Do not add a raw f-string interpolation: an unescaped `"`+in a password breaks the config, and `"` plus a newline injects arbitrary+himalaya keys — including a `backend.host` pointing at someone else's server.+App passwords are user-chosen, so that path needs no prior compromise.+`tests/nodes/test_email_service.py` parses the generated config with `tomllib`+and asserts the key set, which is the actual regression guard.++**CLI errors are scrubbed before they leave `execute`.** himalaya echoes the+config path — and on a parse failure, config content — into stderr, and that+string becomes the `RuntimeError` message, the node error envelope, a persisted+node output, and a WebSocket broadcast. `_scrub` runs before both the log call+and the raise.++**The password still touches disk.** Each invocation writes a `0600` ++`O_EXCL` temp TOML and unlinks it in a `finally` (now actually effective on the+timeout path, since the child is killed first). Removing that entirely means+switching to himalaya's `backend.auth.cmd`:++```toml+backend.auth.type = "password"+backend.auth.cmd = "<command that prints the password>"+```++Not adopted yet: `cmd` delegates to pimalaya's process crate, which is `sh -c`+on POSIX and `cmd /C` on Windows, and getting a value to round-trip without+trailing-newline corruption on both shells needs verification against a real+binary. Recorded here so the next person does not re-derive it.diff --git a/server/config/email_providers.json b/server/config/email_providers.jsonindex 8df76a4f..bea8b98b 100644--- a/server/config/email_providers.json+++ b/server/config/email_providers.json@@ -26,28 +26,6 @@"baseline_page_size": 50},- "config_template": [- "[accounts.{account}]",- "email = \"{email}\"",- "display-name = \"{display_name}\"",- "",- "backend.type = \"imap\"",- "backend.host = \"{imap_host}\"",- "backend.port = {imap_port}",- "backend.encryption = \"{imap_encryption}\"",- "backend.login = \"{email}\"",- "backend.auth.type = \"password\"",- "backend.auth.raw = \"{password}\"",- "",- "message.send.backend.type = \"smtp\"",- "message.send.backend.host = \"{smtp_host}\"",- "message.send.backend.port = {smtp_port}",- "message.send.backend.encryption = \"{smtp_encryption}\"",- "message.send.backend.login = \"{email}\"",- "message.send.backend.auth.type = \"password\"",- "message.send.backend.auth.raw = \"{password}\""- ],-"providers": {"gmail": {"name": "Gmail",@@ -111,12 +89,13 @@},"custom": {"name": "Custom / Self-hosted",+ "_comment": "Every field is blank on purpose. resolve_credentials falls through an `or` chain, so a non-empty preset value here shadows the stored email_* key and makes it unreachable — which is exactly what kept self-hosted servers pinned to 993/465/tls. Defaults live in _himalaya._toml_port / _toml_encryption instead.","imap_host": "",- "imap_port": 993,- "imap_encryption": "tls",+ "imap_port": "",+ "imap_encryption": "","smtp_host": "",- "smtp_port": 465,- "smtp_encryption": "tls",+ "smtp_port": "",+ "smtp_encryption": "","auth_note": "Enter your mail server details"}}diff --git a/server/config/llm_defaults.json b/server/config/llm_defaults.jsonindex 70024dc5..8db389e0 100644--- a/server/config/llm_defaults.json+++ b/server/config/llm_defaults.json@@ -1,7 +1,7 @@{"version": "2026.07.25","last_updated": "2026-07-25",- "_description": "LLM provider defaults. popular_models drives the ordered global selector and offline fallback independently of token constraints. POLICY (2026-07-23): popular_models lists only models with >= 1M-token context windows — providers whose models are all below 1M carry an empty list and contribute nothing to the global selector (their models stay reachable via the live per-provider fetch_models dropdown). base_url directly configures the eight OpenAI-compatible native providers; dedicated OpenAI, Anthropic, and Gemini providers use SDK defaults, while OpenRouter has its own gateway default. Runtime proxy credentials can override supported endpoints. Model specs are enriched by model_registry.json (OpenRouter cache).",+ "_description": "LLM provider defaults. popular_models drives the ordered global selector and offline fallback independently of token constraints. POLICY (2026-07-23): popular_models lists only models with >= 1M-token context windows — providers whose models are all below 1M carry an empty list and contribute nothing to the global selector (their models stay reachable via the live per-provider fetch_models dropdown). base_url directly configures the nine OpenAI-compatible native providers; dedicated OpenAI, Anthropic, and Gemini providers use SDK defaults, while OpenRouter has its own gateway default. Runtime proxy credentials can override supported endpoints. Model specs are enriched by model_registry.json (OpenRouter cache).","agent": {"_description": "Agent execution defaults. recursion_limit and compaction.ratio are sourced from the environment (AGENT_RECURSION_LIMIT, COMPACTION_RATIO via core.config.Settings) — these JSON values are last-resort fallbacks when the env vars aren't loaded (e.g. one-off CLI scripts that bypass Settings). default_temperature stays JSON-resident since it has no env override yet.",diff --git a/server/core/config.py b/server/core/config.pyindex 90cc3e56..87314a6d 100644--- a/server/core/config.py+++ b/server/core/config.py@@ -2,7 +2,7 @@from typing import List, Literal, Optionalfrom pathlib import Path-from pydantic import Field, field_validator+from pydantic import Field, field_validator, model_validatorfrom pydantic_settings import BaseSettings@@ -41,6 +41,35 @@ def dev_secret_offenders(settings) -> list[str]:return offenders+def cookie_posture_warnings(settings) -> list[str]:+ """Human-readable warnings about a risky session-cookie configuration.++ Warnings, not failures. The defaults are deliberately permissive because+ `company deploy` reaches the VM over plain HTTP on its IP and explicitly+ sets ``JWT_COOKIE_SECURE=false``; flipping the default would break every+ LAN/IP deployment with the worst possible symptom -- login appearing to+ succeed and then immediately logging out.++ Duck-typed like ``dev_secret_offenders`` so tests can pass a stub.+ """+ warnings: list[str] = []++ if not getattr(settings, "jwt_cookie_secure", False) and getattr(settings, "deployment_mode", "local") != "local":+ warnings.append(+ "JWT_COOKIE_SECURE=false outside local deployment: the session cookie "+ "will travel over plaintext HTTP."+ )++ origins = getattr(settings, "cors_origins", []) or []+ if "*" in origins:+ warnings.append(+ "CORS_ORIGINS contains '*' while credentialed CORS is enabled: any "+ "origin can make authenticated requests."+ )++ return warnings++class Settings(BaseSettings):"""Application settings driven entirely by environment variables."""@@ -63,6 +92,13 @@ class Settings(BaseSettings):jwt_cookie_secure: bool = Field(default=False, env="JWT_COOKIE_SECURE") # True in productionjwt_cookie_samesite: Literal["lax", "strict", "none"] = Field(default="lax", env="JWT_COOKIE_SAMESITE")+ # Login/registration throttling. Defaults are deliberately tighter than+ # the generic `rate_limit_*` fields below (100/60s), which are far too+ # loose for a password endpoint.+ auth_rate_limit_enabled: bool = Field(default=True, env="AUTH_RATE_LIMIT_ENABLED")+ auth_rate_limit_attempts: int = Field(default=10, env="AUTH_RATE_LIMIT_ATTEMPTS", ge=1)+ auth_rate_limit_window: int = Field(default=300, env="AUTH_RATE_LIMIT_WINDOW", ge=1)+# Securitysecret_key: str = Field(env="SECRET_KEY", min_length=32)cors_origins: List[str] = Field(env="CORS_ORIGINS")@@ -451,6 +487,23 @@ class Settings(BaseSettings):def _expanduser_path(cls, v: Optional[str]) -> Optional[str]:return str(Path(v).expanduser()) if v else v+ @model_validator(mode="after")+ def _reject_unusable_cookie_combination(self):+ """Fail fast on `SameSite=None` without `Secure`.++ Every current browser rejects that cookie outright, so the app would+ boot fine and then silently refuse to keep anyone logged in. This is+ the one cookie misconfiguration worth failing on rather than warning+ about -- see `cookie_posture_warnings` for the rest.+ """+ if self.jwt_cookie_samesite == "none" and not self.jwt_cookie_secure:+ raise ValueError(+ "JWT_COOKIE_SAMESITE=none requires JWT_COOKIE_SECURE=true; "+ "browsers reject a SameSite=None cookie that is not Secure, "+ "which silently breaks login."+ )+ return self+@propertydef database_url(self) -> str:"""Compose the SQLAlchemy URL from ``DATA_DIR`` + ``WORKFLOW_DB_FILENAME``.diff --git a/server/core/rate_limit.py b/server/core/rate_limit.pynew file mode 100644index 00000000..75773eea--- /dev/null+++ b/server/core/rate_limit.py@@ -0,0 +1,93 @@+"""In-process sliding-window rate limiter.++Exists because `POST /api/auth/login` is public, unauthenticated, and was+completely unthrottled -- an unlimited online brute-force surface.++Deliberately dependency-free rather than pulling in `slowapi`: the primary+runtime (`cli/commands/serve.py`) is a single uvicorn process, so a per-process+counter is exact. Under the legacy gunicorn path (`server/gunicorn.conf.py`)+each worker keeps its own counter, making the effective limit+`workers * max_events` -- still a hard ceiling, just a looser one. If this ever+needs to be exact across processes, back it with the existing `CacheService`+rather than adding a dependency.+"""++from __future__ import annotations++import time+from collections import deque+from typing import Callable, Deque, Dict++# Upper bound on tracked keys. An attacker rotating source addresses would+# otherwise grow the dict without limit; at the cap the coldest keys are+# dropped, which fails open for those keys rather than exhausting memory.+_MAX_TRACKED_KEYS = 10_000+++class SlidingWindowLimiter:+ """Allow at most ``max_events`` hits per ``window_seconds`` per key."""++ def __init__(+ self,+ *,+ max_events: int,+ window_seconds: float,+ clock: Callable[[], float] = time.monotonic,+ ) -> None:+ if max_events < 1:+ raise ValueError("max_events must be >= 1")+ if window_seconds <= 0:+ raise ValueError("window_seconds must be > 0")+ self._max_events = max_events+ self._window = float(window_seconds)+ self._clock = clock+ self._events: Dict[str, Deque[float]] = {}++ def hit(self, key: str) -> bool:+ """Record an attempt. Returns True if allowed, False if over the limit.++ A rejected attempt is NOT recorded -- otherwise a client that keeps+ retrying while blocked would extend its own lockout indefinitely,+ which turns a rate limit into a denial of service against the+ legitimate owner of that key.+ """+ now = self._clock()+ cutoff = now - self._window++ bucket = self._events.get(key)+ if bucket is None:+ if len(self._events) >= _MAX_TRACKED_KEYS:+ self._evict_stale(cutoff)+ bucket = self._events.setdefault(key, deque())++ while bucket and bucket[0] <= cutoff:+ bucket.popleft()++ if len(bucket) >= self._max_events:+ return False++ bucket.append(now)+ return True++ def reset(self, key: str) -> None:+ """Forget a key. Called after a successful login so a user who+ finally gets their password right is not still throttled."""+ self._events.pop(key, None)++ def retry_after(self, key: str) -> int:+ """Whole seconds until the oldest recorded hit for ``key`` expires."""+ bucket = self._events.get(key)+ if not bucket:+ return 0+ remaining = (bucket[0] + self._window) - self._clock()+ return max(0, int(remaining) + 1)++ def _evict_stale(self, cutoff: float) -> None:+ """Drop keys whose events have all aged out; if that frees nothing,+ drop the single oldest key so insertion can always proceed."""+ stale = [k for k, v in self._events.items() if not v or v[-1] <= cutoff]+ for key in stale:+ self._events.pop(key, None)+ if not stale and self._events:+ oldest = min(self._events, key=lambda k: self._events[k][-1])+ self._events.pop(oldest, None)diff --git a/server/main.py b/server/main.pyindex 7c7eb967..cac1b3bc 100644--- a/server/main.py+++ b/server/main.py@@ -46,7 +46,7 @@ from fastapi.middleware.cors import CORSMiddleware# [debug] ...``) because the supervisor already prepends# ``[HH:MM:SS.fff]`` to every aggregated line._startup_log("Importing settings + logging...")-from core.config import Settings, dev_secret_offenders+from core.config import Settings, cookie_posture_warnings, dev_secret_offendersfrom core.logging import configure_logging, get_logger, setup_websocket_logging, shutdown_websocket_loggingfrom core.tracing import init_tracing@@ -94,6 +94,13 @@ async def lifespan(app: FastAPI):", ".join(offenders),)+ # Same posture-warning pattern for the session cookie. Warnings only:+ # `company deploy` intentionally ships JWT_COOKIE_SECURE=false because+ # the VM is reached over plain HTTP on its IP, so raising here would+ # brick every LAN/IP deployment.+ for warning in cookie_posture_warnings(settings):+ logger.warning("SECURITY: %s", warning)+# Wave 10.C: discover node plugins so their register_node() calls# populate the four registries before any router serves NodeSpec.# Side-effect import; the package __init__ walks its submodules.@@ -455,12 +462,25 @@ async def lifespan(app: FastAPI):logger.info("Services shutdown complete")+# Interactive docs and the raw OpenAPI schema are in the middleware's public+# allowlist, so they were reachable unauthenticated on every deployment. Keep+# them for local development, where they are genuinely useful, and switch them+# off wherever auth is actually enforced.+_docs_settings = Settings()+_expose_docs = (+ (_docs_settings.vite_auth_enabled or "").lower() == "false"+ or _docs_settings.deployment_mode == "local"+)+# Create FastAPI appapp = FastAPI(title="OpenCompany API",version="3.0.0",description="OpenCompany workflow automation backend",lifespan=lifespan,+ docs_url="/docs" if _expose_docs else None,+ redoc_url="/redoc" if _expose_docs else None,+ openapi_url="/openapi.json" if _expose_docs else None,)# Add exception handler middleware BEFORE CORS to catch all errorsdiff --git a/server/nodes/email/_filters.py b/server/nodes/email/_filters.pyindex 98fa9c9a..2232a5de 100644--- a/server/nodes/email/_filters.py+++ b/server/nodes/email/_filters.py@@ -1,21 +1,41 @@"""Email event-trigger filter builder (Wave 11.I, milestone K).-Moved verbatim from ``services/event_waiter.build_email_filter``.+Moved from ``services/event_waiter.build_email_filter``, then extended to+honour ``filter_query`` -- which was declared on ``EmailReceiveParams`` and+rendered in the node panel, but read by nothing."""from __future__ import annotationsfrom typing import Callable, Dict+# Fields a free-text filter searches, in the shape `_format_message` emits.+_SEARCHABLE_FIELDS = ("subject", "from", "to", "body")+def build_filter(params: Dict) -> Callable[[Dict], bool]:- """Build filter for email events (Himalaya IMAP polling)."""- folder_filter = params.get("folder", "INBOX")+ """Build filter for email events (Himalaya IMAP polling).++ ``folder`` matches exactly, with ``"all"`` as a wildcard. ``filter_query``+ is a case-insensitive substring match across subject / from / to / body --+ deliberately not IMAP search syntax, which belongs server-side in the+ ``search`` operation rather than in a post-fetch predicate.+ """+ folder_filter = params.get("folder") or "INBOX"+ query = (params.get("filter_query") or "").strip().lower()def matches(data: Dict) -> bool:if folder_filter and folder_filter != "all":if data.get("folder", "") != folder_filter:return False++ if query:+ haystack = " ".join(+ str(data.get(field) or "") for field in _SEARCHABLE_FIELDS+ ).lower()+ if query not in haystack:+ return False+return Truereturn matchesdiff --git a/server/nodes/email/_himalaya.py b/server/nodes/email/_himalaya.pyindex 8c2db956..7e5fab73 100644--- a/server/nodes/email/_himalaya.py+++ b/server/nodes/email/_himalaya.py@@ -5,19 +5,91 @@ email send/receive/manage capabilities via any IMAP/SMTP provider."""import asyncio-import json+import reimport shutilimport tempfilefrom email.mime.text import MIMETextfrom email.mime.multipart import MIMEMultipartfrom pathlib import Path-from typing import List, Optional+from typing import Any, List, Optionalfrom core.logging import get_loggerfrom services.plugin.singleton import ServiceSingletonlogger = get_logger(__name__)+# Himalaya accepts these three transport-security values; anything else is+# rejected at config-parse time with an error that names the config path.+_ENCRYPTIONS = ("tls", "start-tls", "none")++# TOML basic-string escapes, per the spec. Order matters: the backslash+# substitution must run first or it would double-escape the ones below it.+_TOML_ESCAPES = (+ ("\\", "\\\\"),+ ('"', '\\"'),+ ("\b", "\\b"),+ ("\t", "\\t"),+ ("\n", "\\n"),+ ("\f", "\\f"),+ ("\r", "\\r"),+)++_TOML_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0e-\x1f\x7f]")+++def _toml_str(value: Any) -> str:+ """Render ``value`` as a quoted TOML basic string.++ Returns the value *including* its surrounding quotes so call sites read+ ``f"backend.host = {_toml_str(host)}"`` and cannot forget them.++ Without this, any credential containing a ``"`` breaks the config, and a+ ``"`` followed by a newline injects arbitrary himalaya keys -- e.g. a+ ``backend.host`` pointing at someone else's server. App passwords are+ user-chosen, so that is reachable without any prior compromise.+ """+ text = "" if value is None else str(value)+ for raw, escaped in _TOML_ESCAPES:+ text = text.replace(raw, escaped)+ # Remaining C0 controls (and DEL) have no shorthand escape.+ text = _TOML_CONTROL_RE.sub(lambda m: f"\\u{ord(m.group()):04X}", text)+ return f'"{text}"'+++def _toml_port(value: Any, default: int) -> int:+ """Coerce ``value`` to a valid TCP port, falling back to ``default``.++ ``resolve_credentials`` always emits the port keys, sometimes valued+ ``None`` -- so ``credentials.get("imap_port", 993)`` finds the key present+ and never applies its default, rendering ``backend.port = None``. Ports are+ interpolated unquoted, so that is unparseable TOML rather than a bad value.+ """+ try:+ port = int(value)+ except (TypeError, ValueError):+ return default+ return port if 1 <= port <= 65535 else default+++def _toml_encryption(value: Any, default: str = "tls") -> str:+ """Return an allowlisted encryption mode as a quoted TOML string."""+ text = "" if value is None else str(value).strip().lower()+ return _toml_str(text if text in _ENCRYPTIONS else default)+++def _scrub(text: str, *secrets: str) -> str:+ """Redact ``secrets`` from ``text``.++ The himalaya error string is not log-only: it becomes the ``RuntimeError``+ message, which becomes the node error envelope, which is persisted and+ broadcast over the WebSocket. Scrubbing only the log would leave the secret+ in the payload the frontend renders.+ """+ for secret in secrets:+ if secret:+ text = text.replace(secret, "[REDACTED]")+ return text+class HimalayaService(ServiceSingleton):"""Manages Himalaya CLI configuration and execution.@@ -45,38 +117,57 @@ class HimalayaService(ServiceSingleton):"or download from https://github.com/pimalaya/himalaya/releases")+ def _timeout_seconds(self) -> float:+ """Per-invocation CLI timeout, from ``cli.timeout_seconds``.++ Imported lazily: ``_service`` reaches back into this module for the+ singleton, so a module-level import would be circular.+ """+ from ._service import _load_config++ raw = _load_config().get("cli", {}).get("timeout_seconds", 60)+ try:+ return float(raw)+ except (TypeError, ValueError):+ return 60.0+def _generate_config(self, account_name: str, credentials: dict) -> str:- """Generate TOML config content for a himalaya account."""+ """Generate TOML config content for a himalaya account.++ Every interpolated value goes through ``_toml_str`` / ``_toml_port`` /+ ``_toml_encryption``. Do not add a raw f-string interpolation here --+ see the note on ``_toml_str`` for what that costs.+ """email = credentials.get("email", "")display_name = credentials.get("display_name", "")password = credentials.get("password", "")imap_host = credentials.get("imap_host", "")- imap_port = credentials.get("imap_port", 993)- imap_encryption = credentials.get("imap_encryption", "tls")+ imap_port = _toml_port(credentials.get("imap_port"), 993)+ imap_encryption = _toml_encryption(credentials.get("imap_encryption"))smtp_host = credentials.get("smtp_host", "")- smtp_port = credentials.get("smtp_port", 465)- smtp_encryption = credentials.get("smtp_encryption", "tls")+ smtp_port = _toml_port(credentials.get("smtp_port"), 465)+ smtp_encryption = _toml_encryption(credentials.get("smtp_encryption"))lines = [f"[accounts.{account_name}]",- f'email = "{email}"',+ f"email = {_toml_str(email)}",]if display_name:- lines.append(f'display-name = "{display_name}"')+ lines.append(f"display-name = {_toml_str(display_name)}")# IMAP backendlines.extend(["",'backend.type = "imap"',- f'backend.host = "{imap_host}"',+ f"backend.host = {_toml_str(imap_host)}",f"backend.port = {imap_port}",- f'backend.encryption = "{imap_encryption}"',- f'backend.login = "{email}"',+ f"backend.encryption = {imap_encryption}",+ f"backend.login = {_toml_str(email)}",'backend.auth.type = "password"',- f'backend.auth.raw = "{password}"',+ f"backend.auth.raw = {_toml_str(password)}",])@@ -85,12 +176,12 @@ class HimalayaService(ServiceSingleton):["",'message.send.backend.type = "smtp"',- f'message.send.backend.host = "{smtp_host}"',+ f"message.send.backend.host = {_toml_str(smtp_host)}",f"message.send.backend.port = {smtp_port}",- f'message.send.backend.encryption = "{smtp_encryption}"',- f'message.send.backend.login = "{email}"',+ f"message.send.backend.encryption = {smtp_encryption}",+ f"message.send.backend.login = {_toml_str(email)}",'message.send.backend.auth.type = "password"',- f'message.send.backend.auth.raw = "{password}"',+ f"message.send.backend.auth.raw = {_toml_str(password)}",])@@ -103,58 +194,68 @@ class HimalayaService(ServiceSingleton):args: List[str],stdin_data: Optional[str] = None,) -> dict:- """Execute himalaya CLI command and return parsed JSON output."""+ """Execute himalaya CLI command and return parsed JSON output.++ Delegates the subprocess lifecycle to the shared ``run_cli_command``+ so the kill-on-timeout guarantee is the same one every other CLI+ plugin gets, then adapts the envelope back to this method's+ raise-on-failure contract.+ """+ from services.events.cli import run_cli_command+binary = await self.ensure_binary()config_content = self._generate_config(account_name, credentials)+ timeout = self._timeout_seconds()+ # NamedTemporaryFile is 0600 + O_EXCL, so the window is narrow --+ # but it is still a plaintext password on disk for the life of the+ # call. See docs-internal/email_service.md for the backend.auth.cmd+ # follow-up that would remove it entirely.tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".toml", prefix="himalaya_", delete=False)try:tmp.write(config_content)tmp.flush()tmp.close()- cmd = [- binary,- "-c",- tmp.name,- "-a",- account_name,- "--output",- "json",- ] + args-logger.debug(f"[Himalaya] Executing: himalaya {' '.join(args)}")- proc = await asyncio.create_subprocess_exec(- *cmd,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- stdin=asyncio.subprocess.PIPE if stdin_data else None,- )-stdin_bytes = stdin_data.encode("utf-8") if stdin_data else None- stdout, stderr = await asyncio.wait_for(- proc.communicate(input=stdin_bytes),- timeout=60,+ envelope = await run_cli_command(+ binary=binary,+ argv=["-c", tmp.name, "-a", account_name, "--output", "json", *args],+ timeout=timeout,+ stdin=asyncio.subprocess.PIPE if stdin_bytes else None,+ input=stdin_bytes,)- stdout_str = stdout.decode("utf-8", errors="replace").strip()- stderr_str = stderr.decode("utf-8", errors="replace").strip()-- if proc.returncode != 0:- error_msg = stderr_str or stdout_str or f"Exit code {proc.returncode}"- logger.error(f"[Himalaya] Command failed: {error_msg}")+ if not envelope.get("success"):+ error_msg = (+ envelope.get("error")+ or envelope.get("stderr")+ or envelope.get("stdout")+ or "unknown failure"+ )+ # himalaya echoes the config path -- and on a parse failure,+ # config content -- into stderr. This string becomes the+ # RuntimeError message, the node error envelope, a persisted+ # node output, and a WebSocket broadcast, so scrub before it+ # leaves this function rather than only before the log call.+ error_msg = _scrub(error_msg, credentials.get("password", ""))+ logger.warning(f"[Himalaya] Command failed: {error_msg}")raise RuntimeError(f"himalaya error: {error_msg}")+ stdout_str = envelope.get("stdout") or ""if not stdout_str:return {}- try:- return json.loads(stdout_str)- except json.JSONDecodeError:+ parsed = envelope.get("result")+ if parsed is None:return {"raw_output": stdout_str}+ return parsedfinally:+ # Now actually effective on the timeout path: run_cli_command+ # tree-kills the child first, so the handle is released.Path(tmp.name).unlink(missing_ok=True)# =========================================================================@@ -299,9 +400,19 @@ class HimalayaService(ServiceSingleton):return await self.execute(account, credentials, ["folder", "list"])def _account_name(self, credentials: dict) -> str:- """Generate a consistent account name from credentials."""- email = credentials.get("email", "default")- return email.split("@")[0].replace(".", "_").replace("+", "_")+ """Generate a consistent account name from credentials.++ The result lands in two places with different rules: the TOML table+ header ``[accounts.X]``, where only bare-key characters are legal, and+ argv as ``-a X``, where a leading ``-`` is parsed as a flag. Email+ local-parts legally contain ``!#$%&'*/=?^`{|}~``, none of which are+ valid bare-key characters -- ``o'[email protected]`` used to produce+ ``[accounts.o'brien]`` and a config parse error.+ """+ email = credentials.get("email") or "default"+ local_part = str(email).split("@")[0]+ name = re.sub(r"[^A-Za-z0-9_-]", "_", local_part).lstrip("-")+ return name or "default"def get_himalaya_service() -> HimalayaService:diff --git a/server/nodes/email/_service.py b/server/nodes/email/_service.pyindex 811055e1..6243067a 100644--- a/server/nodes/email/_service.py+++ b/server/nodes/email/_service.py@@ -52,11 +52,20 @@ class EmailService(ServiceSingleton):# -- credentials --async def resolve_credentials(self, params: Dict[str, Any]) -> Dict[str, Any]:- """Merge stored creds + provider presets + param overrides.-- Precedence (per field): node params > provider preset > stored custom keys.- Stored custom keys (email_imap_host, email_smtp_port, etc.) are used when- the provider is 'custom' or when a preset field is empty.+ """Merge provider presets with stored credential keys.++ Precedence (per field): provider preset > stored key. Stored keys+ (``email_imap_host``, ``email_smtp_port``, ...) apply when the preset+ leaves the field blank, which is how the ``custom`` provider works.++ Credentials are deliberately NOT readable from node parameters. They+ used to be the documented top tier, but the fields were never declared+ on any Params model and all three set ``extra="ignore"``, so every+ ``params.get("password")`` silently returned None. Declaring them to+ revive the tier is not an option either: ``ToolNode.as_tool_schema``+ dumps ``Params.model_json_schema()`` wholesale with no field-exclusion+ hook, so a declared ``password`` becomes an argument the LLM can pass+ to a callable tool. ``provider`` stays because it IS declared."""from services.plugin.deps import get_auth_service@@ -65,8 +74,8 @@ class EmailService(ServiceSingleton):provider = params.get("provider") or await auth.get_api_key("email_provider") or self.defaults.get("provider")preset = self._provider_preset(provider)- email = params.get("email") or await auth.get_api_key("email_address") or ""- password = params.get("password") or await auth.get_api_key("email_password") or ""+ email = await auth.get_api_key("email_address") or ""+ password = await auth.get_api_key("email_password") or ""if not email:raise ValueError("Email address not configured")@@ -81,17 +90,17 @@ class EmailService(ServiceSingleton):except (TypeError, ValueError):return None- imap_host = params.get("imap_host") or preset.get("imap_host") or await auth.get_api_key("email_imap_host") or ""- imap_port = params.get("imap_port") or preset.get("imap_port") or _coerce_port(await auth.get_api_key("email_imap_port"))- imap_encryption = params.get("imap_encryption") or preset.get("imap_encryption") or await auth.get_api_key("email_imap_encryption")- smtp_host = params.get("smtp_host") or preset.get("smtp_host") or await auth.get_api_key("email_smtp_host") or ""- smtp_port = params.get("smtp_port") or preset.get("smtp_port") or _coerce_port(await auth.get_api_key("email_smtp_port"))- smtp_encryption = params.get("smtp_encryption") or preset.get("smtp_encryption") or await auth.get_api_key("email_smtp_encryption")+ imap_host = preset.get("imap_host") or await auth.get_api_key("email_imap_host") or ""+ imap_port = preset.get("imap_port") or _coerce_port(await auth.get_api_key("email_imap_port"))+ imap_encryption = preset.get("imap_encryption") or await auth.get_api_key("email_imap_encryption")+ smtp_host = preset.get("smtp_host") or await auth.get_api_key("email_smtp_host") or ""+ smtp_port = preset.get("smtp_port") or _coerce_port(await auth.get_api_key("email_smtp_port"))+ smtp_encryption = preset.get("smtp_encryption") or await auth.get_api_key("email_smtp_encryption")return {"email": email,"password": password,- "display_name": params.get("display_name", ""),+ "display_name": await auth.get_api_key("email_display_name") or "","imap_host": imap_host,"imap_port": imap_port,"imap_encryption": imap_encryption,@@ -101,14 +110,25 @@ class EmailService(ServiceSingleton):}def resolve_poll_params(self, params: Dict[str, Any]) -> Dict[str, Any]:- """Resolve polling parameters from node params + JSON polling config."""+ """Resolve polling parameters from node params + JSON polling config.++ Every read coerces rather than trusting the value: ``emailReceive``+ overrides ``execute()`` and passes raw parameters, so the Pydantic+ ``ge=30, le=3600`` guard never runs on this path and ``poll_interval``+ can arrive as ``None`` or a string. ``dict.get(key, default)`` only+ substitutes when the key is *absent*, so an explicit None reached+ ``min()`` and raised TypeError. Mirrors ``PollingTriggerNode._clamp_interval``.+ """p = self.polling- interval = params.get("poll_interval", p.get("interval"))- interval = max(p.get("min_interval"), min(p.get("max_interval"), interval))+ try:+ interval = int(params.get("poll_interval") or p.get("interval"))+ except (TypeError, ValueError):+ interval = int(p.get("interval"))+ interval = max(int(p.get("min_interval")), min(int(p.get("max_interval")), interval))return {"interval": interval,- "folder": params.get("folder", self.defaults.get("folder")),- "mark_as_read": params.get("mark_as_read", False),+ "folder": params.get("folder") or self.defaults.get("folder"),+ "mark_as_read": bool(params.get("mark_as_read")),}# -- operations --diff --git a/server/nodes/email/email_read/__init__.py b/server/nodes/email/email_read/__init__.pyindex 636bbafb..9e7bfa24 100644--- a/server/nodes/email/email_read/__init__.py+++ b/server/nodes/email/email_read/__init__.py@@ -24,12 +24,16 @@ class EmailReadParams(BaseModel):description="IMAP action. folders lists all mailbox folders (no other params needed).",)- # folder (used by list/search and move source; optional for others)+ # folder — every operation forwards it (see EmailService.read), so the UI+ # must offer it for all six. Gating it to list/search left move/delete/flag+ # silently pinned to INBOX with no way to change the source folder.folder: str = Field(default="INBOX",description="Mailbox folder to query.",json_schema_extra={- "displayOptions": {"show": {"operation": ["list", "search"]}},+ "displayOptions": {+ "show": {"operation": ["list", "search", "read", "move", "delete", "flag"]},+ },},)query: str = Field(@@ -60,16 +64,9 @@ class EmailReadParams(BaseModel):json_schema_extra={"displayOptions": {"show": {"operation": ["flag"]}}},)- # Pagination (list / search)- limit: int = Field(- default=20,- ge=1,- le=500,- description="Max envelopes per page.",- json_schema_extra={- "displayOptions": {"show": {"operation": ["list", "search"]}},- },- )+ # Pagination (list / search). `limit` and `offset` used to live here too;+ # neither was read by EmailService.read, and because Params feeds the AI+ # tool schema verbatim, an agent could set limit=100 and silently get 20.page: int = Field(default=1,ge=1,@@ -82,15 +79,7 @@ class EmailReadParams(BaseModel):default=20,ge=1,le=500,- description="Items per page (overrides limit when paginating).",- json_schema_extra={- "displayOptions": {"show": {"operation": ["list", "search"]}},- },- )- offset: int = Field(- default=0,- ge=0,- description="Alternative to page-based pagination — skip this many messages.",+ description="Messages per page.",json_schema_extra={"displayOptions": {"show": {"operation": ["list", "search"]}},},diff --git a/server/nodes/email/email_receive/__init__.py b/server/nodes/email/email_receive/__init__.pyindex 3426d1fe..fee6c225 100644--- a/server/nodes/email/email_receive/__init__.py+++ b/server/nodes/email/email_receive/__init__.py@@ -149,38 +149,69 @@ class EmailReceiveNode(PollingTriggerNode):f"[EmailReceive] Baseline: {len(seen)} emails in {poll['folder']}",)+ # Wave 12 B4 + canary opt-in: route through plugin _events.py+ # wrapper. Dual-dispatch via event_waiter (legacy collector) ++ # dispatch.emit (Temporal-durable TriggerListenerWorkflow consumers).+ from nodes.email import dispatch_email_received++ logger = get_logger(__name__)+while True:await asyncio.sleep(poll["interval"])- new_ids = await svc.poll_ids(creds, poll["folder"]) - seen++ # Per-cycle isolation, matching gmail_receive. Without it a+ # single transient IMAP error ends the whole interactive Run+ # instead of being retried on the next tick.+ try:+ new_ids = await svc.poll_ids(creds, poll["folder"]) - seen+ except asyncio.CancelledError:+ raise+ except Exception as poll_err:+ logger.error(f"[EmailReceive] Poll cycle failed: {poll_err}")+ continue+if not new_ids:continue- msg_id = next(iter(new_ids))+ # Dispatch EVERY new message, oldest first. Taking one and+ # marking the rest seen dropped N-1 events per cycle -- and+ # since new_ids is a set, *which* one survived was arbitrary.+ # IMAP UIDs are numeric; the tuple key keeps non-numeric ids+ # sorting last instead of raising.+ ordered = sorted(new_ids, key=lambda i: (0, int(i)) if str(i).isdigit() else (1, str(i)))seen.update(new_ids)- email_data = await svc.fetch_detail(creds, msg_id, poll["folder"])-- if poll["mark_as_read"]:- d = svc.defaults- await svc.himalaya.flag_message(- creds,- msg_id,- d.get("flag"),- d.get("flag_action"),- poll["folder"],- )-- # Wave 12 B4 + canary opt-in: route through plugin- # _events.py wrapper. Dual-dispatch via event_waiter- # (legacy collector) + dispatch.emit (Temporal-durable- # TriggerListenerWorkflow consumers).- from nodes.email import dispatch_email_received-- await dispatch_email_received(email_data)++ first_email = None+ for msg_id in ordered:+ try:+ email_data = await svc.fetch_detail(creds, msg_id, poll["folder"])++ if poll["mark_as_read"]:+ d = svc.defaults+ await svc.himalaya.flag_message(+ creds,+ msg_id,+ d.get("flag"),+ d.get("flag_action"),+ poll["folder"],+ )++ await dispatch_email_received(email_data)+ if first_email is None:+ first_email = email_data+ except asyncio.CancelledError:+ raise+ except Exception as msg_err:+ logger.error(f"[EmailReceive] Failed to handle message {msg_id}: {msg_err}")++ if first_email is None:+ continue+return {"success": True,"node_id": node_id,"node_type": self.type,- "result": email_data,+ "result": first_email,"execution_time": time.time() - start_time,"timestamp": datetime.now().isoformat(),}diff --git a/server/routers/auth.py b/server/routers/auth.pyindex 6855b40a..5df7d941 100644--- a/server/routers/auth.py+++ b/server/routers/auth.py@@ -1,23 +1,60 @@"""Authentication routes for user login, registration, and session management."""+from typing import Optional+from fastapi import APIRouter, Depends, HTTPException, Response, Request-from pydantic import BaseModel, EmailStr+from pydantic import BaseModel, EmailStr, Fieldfrom core.auth_cookies import get_session_token, session_cookie_namesfrom core.container import containerfrom core.config import Settingsfrom core.logging import get_logger+from core.rate_limit import SlidingWindowLimiterfrom services.user_auth import UserAuthServicefrom services.auth import AuthServicelogger = get_logger(__name__)router = APIRouter(prefix="/api/auth", tags=["auth"])+# Module-level so the window survives across requests. Built lazily from+# settings on first use -- `container.settings()` is not resolvable at import.+_login_limiter: Optional[SlidingWindowLimiter] = None+_register_limiter: Optional[SlidingWindowLimiter] = None+++def _client_key(request: Request) -> str:+ return request.client.host if request.client else "unknown"+++def _limiters(settings: Settings) -> tuple[SlidingWindowLimiter, SlidingWindowLimiter]:+ global _login_limiter, _register_limiter+ if _login_limiter is None or _register_limiter is None:+ attempts = settings.auth_rate_limit_attempts+ window = settings.auth_rate_limit_window+ _login_limiter = SlidingWindowLimiter(max_events=attempts, window_seconds=window)+ _register_limiter = SlidingWindowLimiter(max_events=attempts, window_seconds=window)+ return _login_limiter, _register_limiter+++def _enforce_limit(limiter: SlidingWindowLimiter, key: str, settings: Settings) -> None:+ if not settings.auth_rate_limit_enabled:+ return+ if not limiter.hit(key):+ retry_after = limiter.retry_after(key)+ logger.warning("Auth rate limit tripped for key=%s", key)+ raise HTTPException(+ status_code=429,+ detail="Too many attempts. Please wait and try again.",+ headers={"Retry-After": str(retry_after)},+ )+class RegisterRequest(BaseModel):email: EmailStrpassword: str- display_name: str+ # Mirrors the max_length=100 column on User.display_name so the rejection+ # is a 422 at the edge rather than a silent SQLite truncation.+ display_name: str = Field(min_length=1, max_length=100)class LoginRequest(BaseModel):@@ -84,6 +121,7 @@ async def get_auth_status(async def register(request: RegisterRequest,response: Response,+ http_request: Request,user_auth: UserAuthService = Depends(get_user_auth_service),settings: Settings = Depends(get_settings),):@@ -92,6 +130,9 @@ async def register(In single-owner mode, only the first user can register.In multi-user mode, anyone can register."""+ _, register_limiter = _limiters(settings)+ _enforce_limit(register_limiter, _client_key(http_request), settings)+user, error = await user_auth.register(email=request.email, password=request.password, display_name=request.display_name)if error:@@ -115,6 +156,7 @@ async def register(async def login(request: LoginRequest,response: Response,+ http_request: Request,user_auth: UserAuthService = Depends(get_user_auth_service),settings: Settings = Depends(get_settings),):@@ -122,11 +164,22 @@ async def login(Login with email and password.Sets HttpOnly cookie with JWT token."""+ # Keyed on (source address, email) so one attacker cannot lock out an+ # unrelated account from a shared NAT, and a password-spray against many+ # accounts from one address is still bounded per account.+ login_limiter, _ = _limiters(settings)+ limit_key = f"{_client_key(http_request)}|{request.email.lower()}"+ _enforce_limit(login_limiter, limit_key, settings)+user, error = await user_auth.login(email=request.email, password=request.password)if error:raise HTTPException(status_code=401, detail=error)+ # Clear the counter so a user who eventually gets it right is not still+ # throttled by their own earlier typos.+ login_limiter.reset(limit_key)+# Create token and set cookietoken = user_auth.create_access_token(user)response.set_cookie(@@ -149,14 +202,21 @@ async def logout(settings: Settings = Depends(get_settings),):"""- Logout by clearing the auth cookie, encryption key, and memory caches.-- Clears:- - Auth cookie- - Encryption service key (prevents credential decryption)- - API key memory cache (removes decrypted keys from memory)+ Logout by clearing the session cookie and the API-key memory cache.++ What this actually does:+ - Deletes the session cookie (canonical + legacy names)+ - Clears the decrypted API-key cache++ What it does NOT do, despite what this docstring used to claim:+ - It does not clear any encryption key. `user_auth.logout()` is a no-op+ log line, and the encryption key is server-scoped -- initialised once+ in `main.py` from `API_KEY_ENCRYPTION_KEY`, never per session.+ - It does not invalidate the JWT. There is no denylist, so a token+ captured before logout stays valid until `exp`. The only revocation+ lever is `User.is_active`, enforced in `get_current_user`.+ See the Known Limitations section of docs-internal/authentication.md."""- # Clear encryption key from memoryuser_auth.logout()# Clear API key memory cachediff --git a/server/services/events/cli.py b/server/services/events/cli.pyindex ff10f68b..9cca4e78 100644--- a/server/services/events/cli.py+++ b/server/services/events/cli.py@@ -11,9 +11,12 @@ from __future__ import annotationsimport asyncioimport json+import osimport shutilfrom typing import Any, Dict, List, Optional, Type+from services._supervisor.util import kill_tree+async def run_cli_command(*,@@ -25,6 +28,7 @@ async def run_cli_command(env: Optional[Dict[str, str]] = None,stdin: Optional[int] = None,cwd: Optional[str] = None,+ input: Optional[bytes] = None,) -> Dict[str, Any]:"""Run ``<binary> <argv> [api_key_arg <key>]`` once, return parsed JSON.@@ -50,6 +54,11 @@ async def run_cli_command(the read block forever, keeping the callback server alive untilthe CLI naturally exits after rendering its response.+ ``input``: optional bytes written to the child's stdin and then closed.+ Requires ``stdin=asyncio.subprocess.PIPE``. Used by CLIs that take their+ payload on stdin rather than argv (himalaya reads an RFC 2822 message+ that way, which also keeps the message body out of the process table).+Returns a uniform envelope:{"success": bool, "result": parsed-JSON-or-None,"stdout": str, "stderr": str, "error": str or None}@@ -64,7 +73,16 @@ async def run_cli_command(if not api_key:return {"success": False, "error": f"{binary}: credential required"}+ # shutil.which stays the primary path: on Windows it honours PATHEXT and+ # turns a bare "npm" into the absolute "npm.cmd" that CreateProcessW needs.+ # But a caller that already resolved its binary (himalaya's ensure_binary,+ # which caches the which() result) hands us an absolute path, and+ # re-resolving it buys nothing while making the call fail whenever which()+ # is stricter than the eventual spawn. Trust an absolute path as-is and let+ # the spawn be the judge.resolved = shutil.which(binary)+ if resolved is None and os.path.isabs(binary):+ resolved = binaryif resolved is None:return {"success": False, "error": f"{binary!r} not on PATH"}@@ -81,9 +99,28 @@ async def run_cli_command(env=env,cwd=cwd,)- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=timeout)+ stdout, stderr = await asyncio.wait_for(proc.communicate(input=input), timeout=timeout)except asyncio.TimeoutError:+ # wait_for cancels the communicate() task but does NOT touch the+ # child, so without this the process keeps running, orphaned, still+ # holding whatever handles it opened. Callers that hand it a temp+ # config then unlink that file in a finally block -- which on Windows+ # raises PermissionError against the live process and masks the+ # timeout entirely.+ kill_tree(proc.pid)+ try:+ await proc.wait()+ except Exception: # pragma: no cover - reaping is best-effort+ passreturn {"success": False, "error": f"{binary} timed out ({timeout}s)"}+ except OSError as exc:+ # MUST stay below the TimeoutError clause: since 3.11 asyncio.TimeoutError+ # is the builtin TimeoutError, which subclasses OSError -- catching OSError+ # first silently swallows every timeout and skips the kill above.+ # An absolute path is no longer pre-validated by which(), so a missing or+ # non-executable binary lands here; keep the envelope uniform rather than+ # raising through every caller.+ return {"success": False, "error": f"{binary}: {exc or type(exc).__name__}"}out = stdout.decode(errors="replace").strip()err = stderr.decode(errors="replace").strip()diff --git a/server/services/llm/providers/__init__.py b/server/services/llm/providers/__init__.pyindex 94c1cd63..ab2b39f8 100644--- a/server/services/llm/providers/__init__.py+++ b/server/services/llm/providers/__init__.py@@ -23,4 +23,4 @@ from services.llm.providers import anthropic # noqa: F401from services.llm.providers import openai # noqa: F401from services.llm.providers import gemini # noqa: F401from services.llm.providers import openrouter # noqa: F401-from services.llm.providers import _compat # noqa: F401 (registers 8 OpenAI-compat providers)+from services.llm.providers import _compat # noqa: F401 (registers 9 OpenAI-compat providers)diff --git a/server/services/user_auth.py b/server/services/user_auth.pyindex a148f5dd..cf6755ff 100644--- a/server/services/user_auth.py+++ b/server/services/user_auth.py@@ -1,12 +1,15 @@"""User authentication service with JWT handling and encryption initialization."""import logging+import uuidfrom datetime import datetime, timezone, timedeltafrom typing import Optional, Dict, Any+import bcryptimport jwtfrom jwt import PyJWTError-from sqlmodel import select+from sqlalchemy.exc import IntegrityError+from sqlmodel import func, selectfrom core.config import Settingsfrom core.database import Database@@ -16,6 +19,20 @@ from models.auth import Userlogger = logging.getLogger(__name__)+# One generic message for every credential rejection. Distinct messages+# ("Account is disabled") confirm an address exists, which is an account+# enumeration oracle on a public, unauthenticated endpoint.+_INVALID_CREDENTIALS = "Invalid email or password"++# Compared against when no user matches, so the unknown-email path costs the+# same ~50-300ms of bcrypt as the known-email path. Without it, response time+# alone reveals which addresses are registered.+#+# Generated out-of-band from a discarded random string; deliberately NOT+# computed at import via bcrypt.gensalt(), which would add a full KDF round+# to every process start (startup timing is instrumented -- see _startup_log).+_DUMMY_PASSWORD_HASH = b"$2b$12$C6UzMDM.H6dfI/f/IKcEe.6Vc/qGgQEHOQKMxLbLQ3vRhBnGYDbXK"+class UserAuthService:"""Handles user authentication, registration, and JWT token management."""@@ -34,10 +51,14 @@ class UserAuthService:self._algorithm = "HS256"async def get_user_count(self) -> int:- """Get total number of users."""+ """Get total number of users.++ COUNT(*) rather than materialising every row -- `can_register` calls+ this on every `/api/auth/status` poll in single-owner mode.+ """async with self.database.get_session() as session:- result = await session.execute(select(User))- return len(result.scalars().all())+ result = await session.execute(select(func.count()).select_from(User))+ return int(result.scalar_one())async def get_user_by_email(self, email: str) -> Optional[User]:"""Get user by email address."""@@ -63,39 +84,65 @@ class UserAuthService:"""Register a new user.Returns (user, None) on success, (None, error_message) on failure.- """- # Check if registration is allowed- if not await self.can_register():- if self.settings.auth_mode == "single":- return None, "Registration disabled - owner account already exists"- return None, "Registration is currently disabled"-- # Check if email already exists- existing = await self.get_user_by_email(email)- if existing:- return None, "Email already registered"- # Validate password strength+ The eligibility checks and the INSERT share ONE session. They used to+ span four, so two concurrent first-registrations could both observe+ "no users exist" and both be granted ``is_owner``. The UNIQUE index on+ email is still the final arbiter, but a loser now gets a clean error+ instead of an unhandled IntegrityError surfacing as a 500.+ """+ # Validate before touching the DB.if len(password) < 8:return None, "Password must be at least 8 characters"- # Determine if this is the owner (first user in single-owner mode)- is_owner = self.settings.auth_mode == "single" and await self.get_user_count() == 0+ display_name = (display_name or "").strip()+ if not display_name:+ return None, "Display name is required"+ # The column is max_length=100 and SQLite truncates silently rather+ # than raising, so an over-long name would be stored altered.+ if len(display_name) > 100:+ return None, "Display name must be 100 characters or fewer"- # Create user- user = User.create(- email=email,- password=password,- display_name=display_name,- is_owner=is_owner,- )+ normalized_email = (email or "").lower().strip()+ if not normalized_email:+ return None, "Email is required"async with self.database.get_session() as session:+ # Inline the lookups rather than calling get_user_by_email /+ # get_user_count: those open their own sessions, which would+ # reintroduce the very race this block exists to close.+ existing = (+ await session.execute(select(User).where(User.email == normalized_email))+ ).scalars().first()+ if existing:+ return None, "Email already registered"++ user_count = int(+ (await session.execute(select(func.count()).select_from(User))).scalar_one()+ )++ if self.settings.auth_mode != "multi" and user_count > 0:+ return None, "Registration disabled - owner account already exists"++ is_owner = self.settings.auth_mode == "single" and user_count == 0++ user = User.create(+ email=normalized_email,+ password=password,+ display_name=display_name,+ is_owner=is_owner,+ )+session.add(user)- await session.commit()+ try:+ await session.commit()+ except IntegrityError:+ await session.rollback()+ logger.info("Registration lost a race on email uniqueness: %s", normalized_email)+ return None, "Email already registered"await session.refresh(user)- logger.info(f"User registered: {email} (owner={is_owner})")+ logger.info(f"User registered: {normalized_email} (owner={is_owner})")return user, None@@ -105,40 +152,74 @@ class UserAuthService:Returns (user, None) on success, (None, error_message) on failure."""user = await self.get_user_by_email(email)- if not user:- return None, "Invalid email or password"- if not user.is_active:- return None, "Account is disabled"+ if user is None:+ # Burn an equivalent bcrypt round so an unregistered address is+ # not distinguishable by response time. The result is discarded.+ bcrypt.checkpw(password.encode("utf-8"), _DUMMY_PASSWORD_HASH)+ logger.info("Login rejected: no such account")+ return None, _INVALID_CREDENTIALS- if not user.verify_password(password):- return None, "Invalid email or password"+ password_ok = user.verify_password(password)- # Update last login- async with self.database.get_session() as session:- result = await session.execute(select(User).where(User.id == user.id))- db_user = result.scalars().first()- if db_user:- db_user.last_login = datetime.now(timezone.utc)- await session.commit()+ if not password_ok:+ logger.info("Login rejected: bad password for user id=%s", user.id)+ return None, _INVALID_CREDENTIALS++ if not user.is_active:+ # Same message as a bad password on purpose -- a distinct one+ # confirms the account exists. The reason is logged instead so+ # operators can still tell the two apart.+ logger.info("Login rejected: account disabled, user id=%s", user.id)+ return None, _INVALID_CREDENTIALS++ # Update last login. A failure here must not turn a valid login into+ # a 500 -- the timestamp is bookkeeping, not part of authentication.+ try:+ async with self.database.get_session() as session:+ result = await session.execute(select(User).where(User.id == user.id))+ db_user = result.scalars().first()+ if db_user:+ db_user.last_login = datetime.now(timezone.utc)+ await session.commit()+ except Exception:+ logger.warning("Could not record last_login for user id=%s", user.id, exc_info=True)logger.info(f"User logged in: {email}")return user, Nonedef logout(self) -> None:- """Log out user. Encryption key persists (server-scoped, not session-scoped)."""+ """No-op hook kept for symmetry with login.++ There is nothing to tear down here: the encryption key is+ server-scoped (initialised once in ``main.py`` from+ ``API_KEY_ENCRYPTION_KEY``), not derived per session, and there is no+ token denylist. The router clears the session cookie; that is the+ entire logout. See the Known Limitations section of+ ``docs-internal/authentication.md``.+ """logger.debug("User logged out")def create_access_token(self, user: User) -> str:- """Create JWT access token for user."""- expire = datetime.now(timezone.utc) + timedelta(minutes=self.settings.jwt_expire_minutes)+ """Create JWT access token for user.++ ``jti`` / ``nbf`` are additive -- unknown claims are ignored on+ decode, so tokens minted before this change keep verifying. ``iss``+ and ``aud`` are deliberately absent: enforcing them would invalidate+ every token currently held by a browser, for negligible benefit in a+ single-audience app with a per-deployment secret.+ """+ now = datetime.now(timezone.utc)+ expire = now + timedelta(minutes=self.settings.jwt_expire_minutes)payload = {"sub": str(user.id),"email": user.email,"display_name": user.display_name,"is_owner": user.is_owner,"exp": expire,- "iat": datetime.now(timezone.utc),+ "iat": now,+ "nbf": now,+ "jti": uuid.uuid4().hex,}return jwt.encode(payload, self.settings.jwt_secret_key, algorithm=self._algorithm)@@ -155,7 +236,12 @@ class UserAuthService:return Noneasync def get_current_user(self, token: str) -> Optional[User]:- """Get current user from token."""+ """Get current user from token.++ Rejects a deactivated account. There is no token denylist, so+ ``is_active`` is the only revocation lever available to an operator+ before the token's own expiry.+ """payload = self.verify_token(token)if not payload:return None@@ -164,7 +250,18 @@ class UserAuthService:if not user_id:return None- return await self.get_user_by_id(int(user_id))+ try:+ numeric_id = int(user_id)+ except (TypeError, ValueError):+ # A non-numeric `sub` means a malformed or foreign token; a bare+ # int() here raised ValueError and surfaced as a 500.+ logger.debug("Token carried a non-numeric subject")+ return None++ user = await self.get_user_by_id(numeric_id)+ if user is None or not user.is_active:+ return None+ return userdef get_auth_status(self) -> Dict[str, Any]:"""Get authentication status and mode info."""diff --git a/server/tests/auth/conftest.py b/server/tests/auth/conftest.pynew file mode 100644index 00000000..12889a75--- /dev/null+++ b/server/tests/auth/conftest.py@@ -0,0 +1,112 @@+"""Fixtures for the user-authentication test suite.++`server/tests/conftest.py` stubs `core` and `core.*` with MagicMocks for the+LLM provider tests. This suite needs the real modules -- `core.config`,+`core.database`, `core.rate_limit` -- so it wipes those entries the same way+`tests/credentials/conftest.py` does.+"""++import sys+from pathlib import Path+from types import SimpleNamespace+from typing import AsyncIterator++import pytest+import pytest_asyncio++SERVER_DIR = Path(__file__).resolve().parents[2]+if str(SERVER_DIR) not in sys.path:+ sys.path.insert(0, str(SERVER_DIR))++# `core.credentials_database` declares SQLModel tables at import time, and+# SQLModel's metadata is process-global and NOT wiped here -- so re-importing+# it raises "Table 'credentials_metadata' is already defined". Preserve it;+# nothing in this suite needs a fresh copy (UserAuthService only holds the+# reference and never calls it on any path under test).+_PRESERVE = {"core.credentials_database"}++for mod_name in [+ name+ for name in list(sys.modules)+ if (name == "core" or name.startswith("core.")) and name not in _PRESERVE+]:+ del sys.modules[mod_name]++from core.database import Database # noqa: E402++# Must be imported before `Database.startup()` runs `SQLModel.metadata.create_all`+# -- the metadata only knows about model classes that have been imported, so+# without this the `users` table is created only if some other import happens+# to pull it in first, making the suite order-dependent.+from models.auth import User # noqa: E402,F401++pytestmark = pytest.mark.unit+++def make_settings(**overrides) -> SimpleNamespace:+ """Minimal Settings stand-in for UserAuthService.++ A SimpleNamespace rather than a real `Settings()`, which would demand the+ full env surface (ports, CORS origins, secrets) for tests that only touch+ five fields.+ """+ base = dict(+ auth_mode="single",+ jwt_secret_key="test-jwt-secret-key-at-least-32-characters-long",+ jwt_expire_minutes=60,+ jwt_cookie_name="opencompany_token",+ jwt_cookie_secure=False,+ jwt_cookie_samesite="lax",+ auth_rate_limit_enabled=False,+ auth_rate_limit_attempts=10,+ auth_rate_limit_window=300,+ vite_auth_enabled="true",+ deployment_mode="local",+ cors_origins=["http://localhost"],+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++@pytest_asyncio.fixture+async def database(tmp_path) -> AsyncIterator[Database]:+ """Real SQLite Database on a temp file, migrated and ready.++ `Database` reads its URL off a settings object, so this passes the four+ attributes `startup()` actually touches rather than a full `Settings()`.+ """+ db_settings = SimpleNamespace(+ database_url=f"sqlite+aiosqlite:///{tmp_path / 'workflow.db'}",+ database_echo=False,+ database_pool_size=5,+ database_max_overflow=10,+ )+ db = Database(db_settings)+ await db.startup()+ try:+ yield db+ finally:+ await db.shutdown()+++def settings() -> SimpleNamespace:+ return make_settings()+++@pytest_asyncio.fixture+async def user_auth(database: Database, settings: SimpleNamespace):+ """UserAuthService backed by a real database.++ Encryption and the credentials DB are stubs: `UserAuthService` stores the+ references but never touches them on any path under test (its `logout()`+ is a no-op, and the encryption key is server-scoped).+ """+ from services.user_auth import UserAuthService++ return UserAuthService(+ database=database,+ settings=settings,+ encryption=SimpleNamespace(is_initialized=lambda: True),+ credentials_db=SimpleNamespace(),+ )diff --git a/server/tests/auth/test_auth_middleware.py b/server/tests/auth/test_auth_middleware.pynew file mode 100644index 00000000..7c7dee78--- /dev/null+++ b/server/tests/auth/test_auth_middleware.py@@ -0,0 +1,207 @@+"""Tests for AuthMiddleware, including an invariant that pins its riskiest rule.++The middleware gates by exclusion: any GET/HEAD outside `/api/` and `/ws/` is+served without authentication, because the SPA shell must load before login.+That is correct today only because every router in the app is mounted under+`/api/` (or is already deliberately public). Nothing enforced that, so a future+router mounted at, say, `/admin/` would become world-readable with no code+review signal. `TestPublicSurfaceInvariant` is that signal.+"""++from __future__ import annotations++import httpx+import pytest+from fastapi import FastAPI, Request++from middleware.auth import PUBLIC_PATHS, PUBLIC_PREFIXES, AuthMiddleware+from tests.auth.conftest import make_settings++pytestmark = pytest.mark.unit++# Prefixes the middleware actually gates. Anything outside these is public for+# GET/HEAD by the exclusion rule at middleware/auth.py:49.+GATED_PREFIXES = ("/api/", "/ws/")+++def overridden_container():+ """Override the DI providers the middleware resolves, then restore.++ Two traps here, both of which made every gating assertion pass vacuously+ by leaving auth disabled (the real `.env` ships VITE_AUTH_ENABLED=false):++ 1. It must use dependency_injector's `override()` API. A plain+ `monkeypatch.setattr` on the container does not take.+ 2. It must override the container object `middleware.auth` itself+ holds. That module does `from core.container import container` at+ import time, and this suite's conftest wipes `core.*` from+ sys.modules -- so `core.container` may be a *different* module+ object than the one the middleware closed over, depending on+ whether the middleware was imported before or after the wipe.+ """+ import middleware.auth as middleware_module++ container = middleware_module.container++ applied = []++ def _apply(*, settings, user_auth):+ container.settings.override(settings)+ container.user_auth_service.override(user_auth)+ applied.extend([container.settings, container.user_auth_service])++ yield _apply++ for provider in applied:+ provider.reset_override()+++def _build_app(user_auth, settings, overridden_container):+ """App with AuthMiddleware plus a couple of probe routes."""+ overridden_container(settings=settings, user_auth=user_auth)++ app = FastAPI()+ app.add_middleware(AuthMiddleware)++ # `request` MUST be annotated: an untyped parameter is treated as a+ # required query parameter, and the resulting 422 masks the status the+ # middleware actually produced.+ @app.get("/api/protected")+ async def protected(request: Request): # pragma: no cover - exercised via HTTP+ return {+ "user_id": getattr(request.state, "user_id", None),+ "is_owner": getattr(request.state, "is_owner", None),+ }++ @app.get("/")+ async def spa_shell(): # pragma: no cover - exercised via HTTP+ return {"shell": True}++ @app.post("/webhook/incoming")+ async def webhook(): # pragma: no cover - exercised via HTTP+ return {"ok": True}++ transport = httpx.ASGITransport(app=app)+ return httpx.AsyncClient(transport=transport, base_url="http://test")+++class TestGating:+ async def test_api_route_without_cookie_is_401(self, user_auth, settings, overridden_container):+ client = _build_app(user_auth, settings, overridden_container)+ async with client as http:+ response = await http.get("/api/protected")+ assert response.status_code == 401++ async def test_valid_cookie_populates_request_state(self, user_auth, settings, overridden_container):+ user, _ = await user_auth.register(+ email="[email protected]", password="hunter2hunter2", display_name="Owner"+ )+ token = user_auth.create_access_token(user)++ client = _build_app(user_auth, settings, overridden_container)+ async with client as http:+ response = await http.get(+ "/api/protected", cookies={settings.jwt_cookie_name: token}+ )++ assert response.status_code == 200+ assert response.json()["user_id"] == str(user.id)++ async def test_garbage_cookie_is_401(self, user_auth, settings, overridden_container):+ client = _build_app(user_auth, settings, overridden_container)+ async with client as http:+ response = await http.get(+ "/api/protected", cookies={settings.jwt_cookie_name: "not-a-jwt"}+ )+ assert response.status_code == 401++ async def test_auth_disabled_passes_through_anonymously(self, user_auth, overridden_container):+ settings = make_settings(vite_auth_enabled="false")+ client = _build_app(user_auth, settings, overridden_container)+ async with client as http:+ response = await http.get("/api/protected")++ assert response.status_code == 200+ assert response.json()["is_owner"] is True++ async def test_spa_shell_is_public(self, user_auth, settings, overridden_container):+ client = _build_app(user_auth, settings, overridden_container)+ async with client as http:+ response = await http.get("/")+ assert response.status_code == 200++ async def test_webhook_prefix_bypasses_the_cookie_gate(self, user_auth, settings, overridden_container):+ client = _build_app(user_auth, settings, overridden_container)+ async with client as http:+ response = await http.post("/webhook/incoming")+ assert response.status_code == 200+++class TestPublicSurfaceInvariant:+ """Every mounted router must sit under a gated prefix, or be explicitly+ public. Without this, the GET-exclusion rule turns any new non-`/api`+ router into an unauthenticated endpoint."""++ @staticmethod+ def _all_routers():+ """Every APIRouter the app mounts: the `routers` package plus the+ plugin routers registered on `import nodes`."""+ import importlib+ import pkgutil++ from fastapi import APIRouter++ import routers as routers_pkg++ found: list[tuple[str, APIRouter]] = []++ for info in pkgutil.iter_modules(routers_pkg.__path__):+ module = importlib.import_module(f"routers.{info.name}")+ for attr in vars(module).values():+ if isinstance(attr, APIRouter):+ found.append((f"routers.{info.name}", attr))++ import nodes # noqa: F401 -- registers plugin routers as a side effect+ from services.ws_handler_registry import get_routers++ for entry in get_routers():+ router = entry[0] if isinstance(entry, tuple) else entry+ if isinstance(router, APIRouter):+ found.append(("plugin", router))++ return found++ def test_every_router_is_gated_or_explicitly_public(self):+ offenders = []+ for source, router in self._all_routers():+ prefix = router.prefix or ""+ if prefix.startswith(GATED_PREFIXES):+ continue+ if prefix and prefix.rstrip("/") + "/" in PUBLIC_PREFIXES:+ continue+ for route in router.routes:+ path = getattr(route, "path", "")+ full = f"{prefix}{path}"+ if full.startswith(GATED_PREFIXES):+ continue+ if full in PUBLIC_PATHS:+ continue+ if full.startswith(PUBLIC_PREFIXES):+ continue+ offenders.append(f"{source}: {full}")++ assert not offenders, (+ "These routes sit outside the gated prefixes and are not in the public "+ "allowlist, so AuthMiddleware's GET/HEAD exclusion rule serves them "+ "unauthenticated:\n " + "\n ".join(sorted(offenders))+ )++ def test_gated_prefixes_match_the_middleware_source(self):+ """If the middleware's exclusion tuple changes, this test's notion of+ 'gated' must change with it -- otherwise the invariant above silently+ checks the wrong thing."""+ import inspect++ source = inspect.getsource(AuthMiddleware.dispatch)+ assert 'path.startswith(("/api/", "/ws/"))' in sourcediff --git a/server/tests/auth/test_auth_router.py b/server/tests/auth/test_auth_router.pynew file mode 100644index 00000000..47c35484--- /dev/null+++ b/server/tests/auth/test_auth_router.py@@ -0,0 +1,241 @@+"""Contract tests for /api/auth/*.++Pins the exact wire shapes the frontend depends on. In particular the 401+body must be `{"detail": "..."}` with a string -- `AuthContext.postAuth`+renders that string directly, and a shape change would silently take the+login page back to showing no error at all.+"""++from __future__ import annotations++from types import SimpleNamespace++import httpx+import pytest+from fastapi import FastAPI++from tests.auth.conftest import make_settings++pytestmark = pytest.mark.unit+++def _build_client(user_auth, settings):+ """Bare app with only the auth router, per tests/routers/test_workspace.py."""+ from routers import auth as auth_router++ # The limiters are module-level so a window survives across requests;+ # reset them per client so tests do not inherit each other's counters.+ auth_router._login_limiter = None+ auth_router._register_limiter = None++ app = FastAPI()+ app.include_router(auth_router.router)+ app.dependency_overrides[auth_router.get_user_auth_service] = lambda: user_auth+ app.dependency_overrides[auth_router.get_settings] = lambda: settings+ app.dependency_overrides[auth_router.get_auth_service] = lambda: SimpleNamespace(+ clear_cache=lambda: None+ )++ transport = httpx.ASGITransport(app=app)+ return httpx.AsyncClient(transport=transport, base_url="http://test")+++def client(user_auth, settings):+ return _build_client(user_auth, settings)+++REGISTER = {"email": "[email protected]", "password": "hunter2hunter2", "display_name": "Owner"}+LOGIN = {"email": "[email protected]", "password": "hunter2hunter2"}+++class TestRegisterEndpoint:+ async def test_success_sets_httponly_cookie(self, client, settings):+ async with client as http:+ response = await http.post("/api/auth/register", json=REGISTER)++ assert response.status_code == 200+ assert response.json()["success"] is True+ cookie = response.headers.get("set-cookie", "")+ assert settings.jwt_cookie_name in cookie+ assert "HttpOnly" in cookie++ async def test_duplicate_email_is_400_with_string_detail(self, client):+ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ response = await http.post("/api/auth/register", json=REGISTER)++ assert response.status_code == 400+ assert isinstance(response.json()["detail"], str)++ async def test_overlong_display_name_is_422(self, client):+ async with client as http:+ response = await http.post(+ "/api/auth/register", json={**REGISTER, "display_name": "x" * 101}+ )+ assert response.status_code == 422++ async def test_malformed_email_is_422_with_list_detail(self, client):+ """The shape the UI could not render: `detail` is a list of objects,+ not a string. `extractErrorMessage` joins the `msg` fields."""+ async with client as http:+ response = await http.post("/api/auth/register", json={**REGISTER, "email": "nope"})++ assert response.status_code == 422+ detail = response.json()["detail"]+ assert isinstance(detail, list)+ assert all("msg" in item for item in detail)+++class TestLoginEndpoint:+ async def test_success(self, client, settings):+ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ response = await http.post("/api/auth/login", json=LOGIN)++ assert response.status_code == 200+ body = response.json()+ assert body["success"] is True+ assert body["user"]["email"] == "[email protected]"+ assert "HttpOnly" in response.headers.get("set-cookie", "")++ async def test_bad_password_401_body_is_the_frontend_contract(self, client):+ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ response = await http.post(+ "/api/auth/login", json={**LOGIN, "password": "wrong-password"}+ )++ assert response.status_code == 401+ # Exact shape AND exact text: AuthContext renders `detail` verbatim.+ assert response.json() == {"detail": "Invalid email or password"}++ async def test_unknown_user_401_is_identical(self, client):+ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ unknown = await http.post(+ "/api/auth/login", json={"email": "[email protected]", "password": "hunter2hunter2"}+ )+ wrong = await http.post("/api/auth/login", json={**LOGIN, "password": "nope-nope-nope"})++ assert unknown.status_code == wrong.status_code == 401+ assert unknown.json() == wrong.json()+++class TestRateLimit:+ async def test_login_trips_after_the_configured_attempts(self, user_auth):+ settings = make_settings(auth_rate_limit_enabled=True, auth_rate_limit_attempts=3)+ client = _build_client(user_auth, settings)++ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ statuses = [+ (await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})).status_code+ for _ in range(4)+ ]++ assert statuses[:3] == [401, 401, 401]+ assert statuses[3] == 429++ async def test_429_carries_retry_after_and_string_detail(self, user_auth):+ settings = make_settings(auth_rate_limit_enabled=True, auth_rate_limit_attempts=1)+ client = _build_client(user_auth, settings)++ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})+ response = await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})++ assert response.status_code == 429+ assert isinstance(response.json()["detail"], str)+ assert int(response.headers["retry-after"]) > 0++ async def test_successful_login_clears_the_counter(self, user_auth):+ """A user who eventually types the right password must not stay+ throttled by their own earlier typos."""+ settings = make_settings(auth_rate_limit_enabled=True, auth_rate_limit_attempts=3)+ client = _build_client(user_auth, settings)++ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})+ await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})+ good = await http.post("/api/auth/login", json=LOGIN)+ # Counter reset, so three more failures are available.+ after = [+ (await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})).status_code+ for _ in range(3)+ ]++ assert good.status_code == 200+ assert after == [401, 401, 401]++ async def test_disabled_by_config(self, user_auth):+ settings = make_settings(auth_rate_limit_enabled=False, auth_rate_limit_attempts=1)+ client = _build_client(user_auth, settings)++ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ statuses = [+ (await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})).status_code+ for _ in range(3)+ ]++ assert statuses == [401, 401, 401]++ async def test_limit_is_per_email(self, user_auth):+ """Keyed on (address, email) so spraying one account does not lock out+ an unrelated one behind the same NAT."""+ settings = make_settings(+ auth_mode="multi", auth_rate_limit_enabled=True, auth_rate_limit_attempts=2+ )+ client = _build_client(user_auth, settings)++ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ for _ in range(2):+ await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})+ blocked = await http.post("/api/auth/login", json={**LOGIN, "password": "wrong"})+ other = await http.post(+ "/api/auth/login", json={"email": "[email protected]", "password": "wrong-pass"}+ )++ assert blocked.status_code == 429+ assert other.status_code == 401+++class TestLogoutEndpoint:+ async def test_clears_canonical_and_legacy_cookies(self, client, settings):+ from core.auth_cookies import session_cookie_names++ async with client as http:+ response = await http.post("/api/auth/logout")++ assert response.status_code == 200+ header = response.headers.get_list("set-cookie")+ cleared = " ".join(header)+ for name in session_cookie_names(settings):+ assert name in cleared+++class TestStatusEndpoint:+ async def test_reports_registration_open_before_first_user(self, client):+ async with client as http:+ response = await http.get("/api/auth/status")++ assert response.status_code == 200+ assert response.json()["can_register"] is True++ async def test_registration_closes_in_single_mode(self, client):+ async with client as http:+ await http.post("/api/auth/register", json=REGISTER)+ response = await http.get("/api/auth/status")++ assert response.json()["can_register"] is False++ async def test_response_is_json(self, client):+ """AuthContext treats a non-JSON 200 as non-retryable; this pins that+ the real endpoint does return JSON."""+ async with client as http:+ response = await http.get("/api/auth/status")+ assert "application/json" in response.headers["content-type"]diff --git a/server/tests/auth/test_rate_limit.py b/server/tests/auth/test_rate_limit.pynew file mode 100644index 00000000..70022aa4--- /dev/null+++ b/server/tests/auth/test_rate_limit.py@@ -0,0 +1,138 @@+"""Unit tests for SlidingWindowLimiter, driven by an injected clock."""++from __future__ import annotations++import pytest++from core.rate_limit import _MAX_TRACKED_KEYS, SlidingWindowLimiter++pytestmark = pytest.mark.unit+++class _Clock:+ def __init__(self) -> None:+ self.now = 1000.0++ def __call__(self) -> float:+ return self.now++ def advance(self, seconds: float) -> None:+ self.now += seconds+++def clock() -> _Clock:+ return _Clock()+++def _limiter(clock, *, max_events=3, window_seconds=60.0):+ return SlidingWindowLimiter(max_events=max_events, window_seconds=window_seconds, clock=clock)+++class TestConstruction:+ @pytest.mark.parametrize("max_events", [0, -1])+ def test_rejects_non_positive_max_events(self, clock, max_events):+ with pytest.raises(ValueError):+ _limiter(clock, max_events=max_events)++ @pytest.mark.parametrize("window", [0, -5])+ def test_rejects_non_positive_window(self, clock, window):+ with pytest.raises(ValueError):+ _limiter(clock, window_seconds=window)+++class TestHit:+ def test_allows_up_to_the_limit(self, clock):+ limiter = _limiter(clock)+ assert [limiter.hit("k") for _ in range(3)] == [True, True, True]++ def test_blocks_past_the_limit(self, clock):+ limiter = _limiter(clock)+ for _ in range(3):+ limiter.hit("k")+ assert limiter.hit("k") is False++ def test_keys_are_independent(self, clock):+ limiter = _limiter(clock, max_events=1)+ assert limiter.hit("a") is True+ assert limiter.hit("b") is True+ assert limiter.hit("a") is False++ def test_recovers_after_the_window(self, clock):+ limiter = _limiter(clock, max_events=1, window_seconds=60.0)+ assert limiter.hit("k") is True+ assert limiter.hit("k") is False+ clock.advance(61)+ assert limiter.hit("k") is True++ def test_window_slides_rather_than_resetting(self, clock):+ limiter = _limiter(clock, max_events=2, window_seconds=60.0)+ limiter.hit("k") # t=0+ clock.advance(30)+ limiter.hit("k") # t=30+ assert limiter.hit("k") is False+ clock.advance(31) # t=61 -- the t=0 hit has aged out+ assert limiter.hit("k") is True+ assert limiter.hit("k") is False++ def test_blocked_attempts_are_not_recorded(self, clock):+ """Otherwise a client retrying while blocked extends its own lockout+ forever, turning the limit into a self-inflicted denial of service."""+ limiter = _limiter(clock, max_events=1, window_seconds=60.0)+ limiter.hit("k") # t=0, recorded+ clock.advance(30)+ assert limiter.hit("k") is False # must NOT record at t=30+ clock.advance(31) # t=61, the only real hit has expired+ assert limiter.hit("k") is True+++class TestReset:+ def test_reset_clears_a_key(self, clock):+ limiter = _limiter(clock, max_events=1)+ limiter.hit("k")+ assert limiter.hit("k") is False+ limiter.reset("k")+ assert limiter.hit("k") is True++ def test_reset_of_unknown_key_is_safe(self, clock):+ _limiter(clock).reset("never-seen")+++class TestRetryAfter:+ def test_zero_when_untracked(self, clock):+ assert _limiter(clock).retry_after("k") == 0++ def test_counts_down(self, clock):+ limiter = _limiter(clock, max_events=1, window_seconds=60.0)+ limiter.hit("k")+ first = limiter.retry_after("k")+ clock.advance(30)+ assert limiter.retry_after("k") < first++ def test_always_positive_while_blocked(self, clock):+ limiter = _limiter(clock, max_events=1, window_seconds=60.0)+ limiter.hit("k")+ assert limiter.retry_after("k") > 0+++class TestEviction:+ def test_key_count_stays_bounded(self, clock):+ """An attacker rotating source addresses must not grow the dict+ without limit."""+ limiter = _limiter(clock, max_events=1, window_seconds=1.0)+ for i in range(_MAX_TRACKED_KEYS + 50):+ limiter.hit(f"key-{i}")+ # Age keys out as we go so the stale sweep has work to do.+ if i % 100 == 0:+ clock.advance(2)+ assert len(limiter._events) <= _MAX_TRACKED_KEYS++ def test_insertion_still_succeeds_when_nothing_is_stale(self, clock):+ """With every key fresh the stale sweep frees nothing, so the oldest+ key is dropped instead -- a new key must never be refused outright."""+ limiter = _limiter(clock, max_events=5, window_seconds=10_000.0)+ for i in range(_MAX_TRACKED_KEYS):+ limiter.hit(f"key-{i}")+ clock.advance(0.001)+ assert limiter.hit("brand-new") is True+ assert len(limiter._events) <= _MAX_TRACKED_KEYSdiff --git a/server/tests/auth/test_user_auth_service.py b/server/tests/auth/test_user_auth_service.pynew file mode 100644index 00000000..e39cdc65--- /dev/null+++ b/server/tests/auth/test_user_auth_service.py@@ -0,0 +1,308 @@+"""Tests for UserAuthService.++This surface previously had zero coverage: bcrypt hashing, JWT minting and+verification, owner bootstrap, and the single-vs-multi registration gate were+all untested, which is how a user-enumeration timing oracle and a TOCTOU on+the owner account both went unnoticed.+"""++from __future__ import annotations++import asyncio+from datetime import datetime, timedelta, timezone++import jwt+import pytest++from tests.auth.conftest import make_settings++pytestmark = pytest.mark.unit+++async def _register(user_auth, email="[email protected]", password="hunter2hunter2", name="Owner"):+ return await user_auth.register(email=email, password=password, display_name=name)+++class TestRegister:+ async def test_first_user_becomes_owner(self, user_auth):+ user, error = await _register(user_auth)+ assert error is None+ assert user.is_owner is True+ assert user.email == "[email protected]"++ async def test_single_mode_closes_after_first_user(self, user_auth):+ await _register(user_auth)+ user, error = await _register(user_auth, email="[email protected]")+ assert user is None+ assert "already exists" in error++ async def test_multi_mode_allows_more_users(self, database):+ from services.user_auth import UserAuthService++ from types import SimpleNamespace++ svc = UserAuthService(+ database=database,+ settings=make_settings(auth_mode="multi"),+ encryption=SimpleNamespace(is_initialized=lambda: True),+ credentials_db=SimpleNamespace(),+ )+ first, _ = await _register(svc)+ second, error = await _register(svc, email="[email protected]")+ assert error is None+ assert second is not None+ # Only single-owner mode confers ownership.+ assert first.is_owner is False++ async def test_duplicate_email_rejected(self, user_auth):+ await _register(user_auth)+ user, error = await _register(user_auth, name="Impostor")+ assert user is None+ assert error == "Email already registered"++ async def test_email_is_normalized(self, user_auth):+ await _register(user_auth, email=" [email protected] ")+ found = await user_auth.get_user_by_email("[email protected]")+ assert found is not None++ async def test_concurrent_first_registration_yields_one_owner(self, database):+ """The four-session TOCTOU: both callers could observe an empty table+ and both be granted is_owner. The UNIQUE index is the final arbiter,+ but a loser must get a clean error rather than a 500."""+ from types import SimpleNamespace++ from services.user_auth import UserAuthService++ svc = UserAuthService(+ database=database,+ settings=make_settings(),+ encryption=SimpleNamespace(is_initialized=lambda: True),+ credentials_db=SimpleNamespace(),+ )++ results = await asyncio.gather(+ svc.register(email="[email protected]", password="hunter2hunter2", display_name="A"),+ svc.register(email="[email protected]", password="hunter2hunter2", display_name="B"),+ )++ created = [u for u, e in results if u is not None]+ errors = [e for u, e in results if u is None]+ assert len(created) == 1, "exactly one registration may win"+ assert all(isinstance(e, str) for e in errors), "the loser must get a message, not an exception"+ assert await svc.get_user_count() == 1++ @pytest.mark.parametrize("password", ["", "short", "1234567"])+ async def test_short_password_rejected(self, user_auth, password):+ user, error = await _register(user_auth, password=password)+ assert user is None+ assert "at least 8" in error++ async def test_blank_display_name_rejected(self, user_auth):+ user, error = await _register(user_auth, name=" ")+ assert user is None+ assert "Display name" in error++ async def test_overlong_display_name_rejected(self, user_auth):+ """The column is max_length=100 and SQLite truncates silently, so an+ over-long name would be stored altered rather than rejected."""+ user, error = await _register(user_auth, name="x" * 101)+ assert user is None+ assert "100 characters" in error++ async def test_display_name_at_limit_accepted(self, user_auth):+ user, error = await _register(user_auth, name="x" * 100)+ assert error is None+ assert user is not None+++class TestLogin:+ async def test_happy_path(self, user_auth):+ await _register(user_auth)+ user, error = await user_auth.login("[email protected]", "hunter2hunter2")+ assert error is None+ assert user.email == "[email protected]"++ async def test_wrong_password_rejected(self, user_auth):+ await _register(user_auth)+ user, error = await user_auth.login("[email protected]", "wrong-password")+ assert user is None+ assert error == "Invalid email or password"++ async def test_unknown_user_and_wrong_password_are_indistinguishable(self, user_auth):+ """Distinct messages are an account-enumeration oracle on a public,+ unauthenticated endpoint."""+ await _register(user_auth)+ _, unknown_error = await user_auth.login("[email protected]", "hunter2hunter2")+ _, wrong_error = await user_auth.login("[email protected]", "wrong-password")+ assert unknown_error == wrong_error == "Invalid email or password"++ async def test_disabled_account_uses_the_same_message(self, user_auth, database):+ """"Account is disabled" confirmed the address existed."""+ from sqlmodel import select++ from models.auth import User++ await _register(user_auth)+ async with database.get_session() as session:+ row = (await session.execute(select(User))).scalars().first()+ row.is_active = False+ await session.commit()++ user, error = await user_auth.login("[email protected]", "hunter2hunter2")+ assert user is None+ assert error == "Invalid email or password"++ async def test_unknown_user_still_runs_a_bcrypt_comparison(self, user_auth, monkeypatch):+ """Returning before bcrypt made an unregistered address measurably+ faster to reject -- a timing oracle. Assert the work happens rather+ than timing it, which would be flaky under CI load."""+ import services.user_auth as module++ calls = []+ original = module.bcrypt.checkpw++ def _spy(password, hashed):+ calls.append(hashed)+ return original(password, hashed)++ monkeypatch.setattr(module.bcrypt, "checkpw", _spy)++ await user_auth.login("[email protected]", "some-password")+ assert calls, "unknown-user path must still pay for a bcrypt comparison"+ assert calls[0] == module._DUMMY_PASSWORD_HASH++ async def test_dummy_hash_never_matches(self, user_auth):+ """A dummy hash of a guessable password would let anyone authenticate+ as a non-existent user if the branch were ever restructured."""+ import bcrypt++ import services.user_auth as module++ for guess in (b"", b"password", b"123456", b"dummy", b"changeme"):+ assert not bcrypt.checkpw(guess, module._DUMMY_PASSWORD_HASH)++ async def test_last_login_failure_does_not_break_login(self, user_auth, monkeypatch):+ """The timestamp is bookkeeping; a DB hiccup must not turn a valid+ login into a 500."""+ await _register(user_auth)++ real_get_session = user_auth.database.get_session+ state = {"calls": 0}++ def _flaky():+ state["calls"] += 1+ if state["calls"] > 1:+ raise RuntimeError("transient DB failure")+ return real_get_session()++ monkeypatch.setattr(user_auth.database, "get_session", _flaky)+ user, error = await user_auth.login("[email protected]", "hunter2hunter2")+ assert error is None+ assert user is not None+++class TestTokens:+ async def test_token_round_trip(self, user_auth):+ user, _ = await _register(user_auth)+ token = user_auth.create_access_token(user)+ payload = user_auth.verify_token(token)+ assert payload["sub"] == str(user.id)+ assert payload["email"] == user.email++ async def test_token_carries_jti_and_nbf(self, user_auth):+ user, _ = await _register(user_auth)+ payload = user_auth.verify_token(user_auth.create_access_token(user))+ assert payload["jti"]+ assert payload["nbf"]++ async def test_jti_is_unique_per_token(self, user_auth):+ user, _ = await _register(user_auth)+ first = user_auth.verify_token(user_auth.create_access_token(user))["jti"]+ second = user_auth.verify_token(user_auth.create_access_token(user))["jti"]+ assert first != second++ async def test_expired_token_rejected(self, user_auth):+ user, _ = await _register(user_auth)+ expired = jwt.encode(+ {+ "sub": str(user.id),+ "exp": datetime.now(timezone.utc) - timedelta(minutes=1),+ },+ user_auth.settings.jwt_secret_key,+ algorithm="HS256",+ )+ assert user_auth.verify_token(expired) is None++ async def test_token_signed_with_another_key_rejected(self, user_auth):+ user, _ = await _register(user_auth)+ forged = jwt.encode(+ {"sub": str(user.id), "exp": datetime.now(timezone.utc) + timedelta(minutes=5)},+ "a-different-secret-key-that-is-long-enough",+ algorithm="HS256",+ )+ assert user_auth.verify_token(forged) is None+++class TestGetCurrentUser:+ async def test_happy_path(self, user_auth):+ user, _ = await _register(user_auth)+ token = user_auth.create_access_token(user)+ assert (await user_auth.get_current_user(token)).id == user.id++ async def test_non_numeric_subject_returns_none(self, user_auth):+ """A bare int() here raised ValueError and surfaced as a 500."""+ token = jwt.encode(+ {+ "sub": "not-a-number",+ "exp": datetime.now(timezone.utc) + timedelta(minutes=5),+ },+ user_auth.settings.jwt_secret_key,+ algorithm="HS256",+ )+ assert await user_auth.get_current_user(token) is None++ async def test_deactivated_user_is_rejected(self, user_auth, database):+ """is_active is the only revocation lever, since there is no denylist+ and logout only clears the cookie."""+ from sqlmodel import select++ from models.auth import User++ user, _ = await _register(user_auth)+ token = user_auth.create_access_token(user)+ assert await user_auth.get_current_user(token) is not None++ async with database.get_session() as session:+ row = (await session.execute(select(User))).scalars().first()+ row.is_active = False+ await session.commit()++ assert await user_auth.get_current_user(token) is None++ async def test_unknown_user_id_returns_none(self, user_auth):+ token = jwt.encode(+ {"sub": "99999", "exp": datetime.now(timezone.utc) + timedelta(minutes=5)},+ user_auth.settings.jwt_secret_key,+ algorithm="HS256",+ )+ assert await user_auth.get_current_user(token) is None+++class TestUserCount:+ async def test_empty(self, user_auth):+ assert await user_auth.get_user_count() == 0++ async def test_counts_rows(self, database):+ from types import SimpleNamespace++ from services.user_auth import UserAuthService++ svc = UserAuthService(+ database=database,+ settings=make_settings(auth_mode="multi"),+ encryption=SimpleNamespace(is_initialized=lambda: True),+ credentials_db=SimpleNamespace(),+ )+ for i in range(3):+ await _register(svc, email=f"user{i}@example.com")+ assert await svc.get_user_count() == 3diff --git a/server/tests/core_config/test_cookie_posture.py b/server/tests/core_config/test_cookie_posture.pynew file mode 100644index 00000000..383be1b2--- /dev/null+++ b/server/tests/core_config/test_cookie_posture.py@@ -0,0 +1,151 @@+"""Tests for the session-cookie posture guard (core.config).++Locks two contracts:+ 1. ``cookie_posture_warnings`` warns -- never raises -- about a risky but+ working configuration. It must stay a warning: ``company deploy``+ intentionally ships ``JWT_COOKIE_SECURE=false`` because the VM is+ reached over plain HTTP on its IP, so failing here would brick every+ LAN/IP deployment with the worst possible symptom (login appears to+ succeed, then immediately logs out).+ 2. ``SameSite=None`` without ``Secure`` DOES hard-fail, because no browser+ accepts that cookie -- the app would boot fine and then silently refuse+ to keep anyone signed in.+"""++from types import SimpleNamespace++import pytest++from core.config import cookie_posture_warnings+++def _settings(**overrides) -> SimpleNamespace:+ base = dict(+ jwt_cookie_secure=True,+ jwt_cookie_samesite="lax",+ deployment_mode="cloud",+ cors_origins=["https://app.example.com"],+ )+ base.update(overrides)+ return SimpleNamespace(**base)+++class TestInsecureCookieWarning:+ def test_warns_when_insecure_outside_local(self):+ warnings = cookie_posture_warnings(_settings(jwt_cookie_secure=False))+ assert any("JWT_COOKIE_SECURE" in w for w in warnings)++ def test_silent_when_insecure_but_local(self):+ """The documented local-dev posture; nagging here would train+ operators to ignore the banner."""+ warnings = cookie_posture_warnings(+ _settings(jwt_cookie_secure=False, deployment_mode="local")+ )+ assert not any("JWT_COOKIE_SECURE" in w for w in warnings)++ def test_silent_when_secure(self):+ assert cookie_posture_warnings(_settings(jwt_cookie_secure=True)) == []++ @pytest.mark.parametrize("mode", ["cloud", "self_hosted"])+ def test_warns_for_every_non_local_mode(self, mode):+ warnings = cookie_posture_warnings(_settings(jwt_cookie_secure=False, deployment_mode=mode))+ assert warnings+++class TestWildcardCorsWarning:+ def test_warns_on_wildcard_origin(self):+ warnings = cookie_posture_warnings(_settings(cors_origins=["*"]))+ assert any("CORS_ORIGINS" in w for w in warnings)++ def test_silent_on_explicit_origins(self):+ assert cookie_posture_warnings(_settings(cors_origins=["https://a", "https://b"])) == []++ def test_handles_empty_and_missing_origins(self):+ assert cookie_posture_warnings(_settings(cors_origins=[])) == []+ assert cookie_posture_warnings(_settings(cors_origins=None)) == []+++class TestNeverRaises:+ def test_tolerates_a_sparse_settings_object(self):+ """Duck-typed like `dev_secret_offenders`; a missing attribute must+ not explode during startup."""+ assert cookie_posture_warnings(SimpleNamespace()) == []++ def test_returns_both_warnings_together(self):+ warnings = cookie_posture_warnings(+ _settings(jwt_cookie_secure=False, cors_origins=["*"])+ )+ assert len(warnings) == 2+++class TestSameSiteNoneValidator:+ """The one cookie misconfiguration worth failing on.++ Constructed with explicit kwargs and ``_env_file=None``, matching+ ``test_dev_secret_guard.py`` -- `Settings()` has many env-required fields,+ so a bare call picks up the developer's own `.env` and tests nothing.+ """++ @staticmethod+ def _kwargs(**overrides):+ base = {+ "host": "127.0.0.1",+ "port": 3010,+ "jwt_secret_key": "x" * 32,+ "secret_key": "y" * 32,+ "cors_origins": ["http://localhost:3001"],+ "workflow_db_filename": "workflow.db",+ "temporal_enabled": False,+ "temporal_server_address": "localhost:5681",+ "temporal_namespace": "default",+ "temporal_task_queue": "machina-tasks",+ "temporal_per_type_dispatch": True,+ "temporal_agent_workflow_enabled": True,+ "temporal_graceful_shutdown_seconds": 30,+ "temporal_frontend_grpc_port": 7233,+ "temporal_ui_port": 8233,+ "temporal_sqlite_path": "temporal.db",+ "temporal_terminate_running_on_startup": True,+ "api_key_encryption_key": "z" * 32,+ }+ base.update(overrides)+ return base++ def test_samesite_none_without_secure_is_rejected(self):+ from core.config import Settings++ with pytest.raises(Exception) as exc_info:+ Settings(+ _env_file=None,+ **self._kwargs(jwt_cookie_samesite="none", jwt_cookie_secure=False),+ )+ assert "JWT_COOKIE_SAMESITE" in str(exc_info.value)++ def test_samesite_none_with_secure_is_accepted(self):+ from core.config import Settings++ settings = Settings(+ _env_file=None,+ **self._kwargs(jwt_cookie_samesite="none", jwt_cookie_secure=True),+ )+ assert settings.jwt_cookie_samesite == "none"+ assert settings.jwt_cookie_secure is True++ def test_lax_without_secure_is_accepted(self):+ """The shipped default, and what `company deploy` relies on."""+ from core.config import Settings++ settings = Settings(+ _env_file=None,+ **self._kwargs(jwt_cookie_samesite="lax", jwt_cookie_secure=False),+ )+ assert settings.jwt_cookie_samesite == "lax"++ def test_auth_rate_limit_defaults(self):+ """Tighter than the generic rate_limit_* fields on purpose."""+ from core.config import Settings++ settings = Settings(_env_file=None, **self._kwargs())+ assert settings.auth_rate_limit_enabled is True+ assert settings.auth_rate_limit_attempts == 10+ assert settings.auth_rate_limit_window == 300diff --git a/server/tests/nodes/test_email.py b/server/tests/nodes/test_email.pyindex 1dcad893..eaa72d7e 100644--- a/server/tests/nodes/test_email.py+++ b/server/tests/nodes/test_email.py@@ -34,13 +34,25 @@ def _reset_singletons():himalaya_service.HimalayaService._instance = None+# Credentials come from the stored-key store only -- never from node params.+# See TestResolveCredentials in test_email_service.py for why declaring them+# on Params is not an option.+STORED_CREDS = {+ "email_provider": "gmail",+ "email_address": "[email protected]",+ "email_password": "sekret",+}++def _base_creds_params(**overrides):- """Minimal params that satisfy resolve_credentials without stored keys."""- params = {- "provider": "gmail",- "email": "[email protected]",- "password": "sekret",- }+ """Node params for an email node.++ Deliberately carries NO credential keys. The previous version injected+ `email`/`password` here *and* every call site also stored them, so the+ tests passed whichever tier the code actually read -- which is how an+ entire dead credential tier survived unnoticed. Keep this params-only.+ """+ params = {"provider": "gmail"}params.update(overrides)return params@@ -72,7 +84,7 @@ class TestEmailSend:with (_patch_ensure_binary(),patched_subprocess(stdout=stdout, returncode=0) as proc,- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),):result = await harness.execute(@@ -97,7 +109,7 @@ class TestEmailSend:with (_patch_ensure_binary(),patched_subprocess(stdout=b"{}", returncode=0),- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),patch("nodes.email._himalaya.HimalayaService.execute", new=AsyncMock(return_value={})) as mock_exec,):@@ -134,7 +146,7 @@ class TestEmailSend:with (_patch_ensure_binary(),patched_subprocess(stdout=b"", stderr=b"auth failed", returncode=1),- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),):result = await harness.execute(@@ -161,7 +173,7 @@ class TestEmailRead:with (_patch_ensure_binary(),patch("nodes.email._himalaya.HimalayaService.execute", new=AsyncMock(return_value=envelopes)),- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),):result = await harness.execute(@@ -180,7 +192,7 @@ class TestEmailRead:with (_patch_ensure_binary(),patch("nodes.email._himalaya.HimalayaService.execute", new=AsyncMock(return_value=message)),- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),):result = await harness.execute(@@ -194,12 +206,54 @@ class TestEmailRead:assert payload["subject"] == "hello"assert payload["body"] == "world"+ @pytest.mark.parametrize(+ "params,expected_argv",+ [+ (+ {"operation": "search", "query": "from:alice", "folder": "Archive"},+ ["envelope", "list", "-f", "Archive", "--query", "from:alice"],+ ),+ ({"operation": "folders"}, ["folder", "list"]),+ (+ {"operation": "move", "message_id": "42", "target_folder": "Done", "folder": "Archive"},+ ["message", "move", "42", "Done", "-f", "Archive"],+ ),+ (+ {"operation": "delete", "message_id": "42", "folder": "Archive"},+ ["message", "delete", "42", "-f", "Archive"],+ ),+ (+ {"operation": "flag", "message_id": "42", "flag": "Flagged", "flag_action": "remove", "folder": "Archive"},+ ["flag", "remove", "42", "--flag", "Flagged", "-f", "Archive"],+ ),+ ],+ ids=["search", "folders", "move", "delete", "flag"],+ )+ async def test_operation_argv(self, harness, params, expected_argv):+ """The five operations that had no coverage at all.++ Asserting exact argv also pins the non-INBOX `folder` forwarding --+ the UI used to gate `folder` to list/search only, so move/delete/flag+ were silently stuck on INBOX with no way to change the source.+ """+ exec_mock = AsyncMock(return_value={})+ with (+ _patch_ensure_binary(),+ patch("nodes.email._himalaya.HimalayaService.execute", exec_mock),+ patched_container(auth_api_keys=STORED_CREDS),+ patched_pricing(),+ ):+ result = await harness.execute("emailRead", _base_creds_params(**params))++ harness.assert_envelope(result, success=True)+ assert exec_mock.await_args.args[2] == expected_argv+async def test_unknown_operation_returns_error(self, harness):# No subprocess should be spawned; router raises ValueErrorwith (_patch_ensure_binary(),patched_subprocess(),- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),):result = await harness.execute(@@ -214,7 +268,7 @@ class TestEmailRead:with (_patch_ensure_binary(),patched_subprocess(stdout=b"", stderr=b"folder not found", returncode=1),- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),):result = await harness.execute(@@ -249,7 +303,7 @@ class TestEmailReceive:)with (- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),patch.object(EmailService, "poll_ids", poll_ids_mock),patch.object(EmailService, "fetch_detail", fetch_detail_mock),@@ -289,7 +343,7 @@ class TestEmailReceive:flag_mock = AsyncMock(return_value={})with (- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),patch.object(EmailService, "poll_ids", poll_ids_mock),patch.object(EmailService, "fetch_detail", fetch_detail_mock),@@ -331,7 +385,7 @@ class TestEmailReceive:poll_ids_mock = AsyncMock(side_effect=RuntimeError("himalaya error: connection refused"))with (- patched_container(auth_api_keys={"email_address": "[email protected]", "email_password": "sekret", "email_provider": "gmail"}),+ patched_container(auth_api_keys=STORED_CREDS),patched_pricing(),patch.object(EmailService, "poll_ids", poll_ids_mock),patch("asyncio.sleep", new=AsyncMock(return_value=None)),@@ -347,3 +401,85 @@ class TestEmailReceive:harness.assert_envelope(result, success=False)assert "himalaya" in result["error"].lower() or "connection refused" in result["error"].lower()++ async def test_every_new_message_is_dispatched(self, harness):+ """Two messages arriving in one poll window must produce two events.++ The loop used to take `next(iter(new_ids))` and mark the whole set+ seen, so N-1 events were dropped -- and since `new_ids` is a set,+ *which* one survived was arbitrary. The returned envelope is still+ the first message, by UID order.+ """+ from nodes.email._service import EmailService++ poll_ids_mock = AsyncMock(side_effect=[{"1"}, {"1", "2", "3"}])+ fetch_detail_mock = AsyncMock(+ side_effect=lambda creds, msg_id, folder: {+ "message_id": msg_id,+ "folder": folder,+ "subject": f"msg-{msg_id}",+ }+ )++ with (+ patched_container(auth_api_keys=STORED_CREDS),+ patched_pricing(),+ patch.object(EmailService, "poll_ids", poll_ids_mock),+ patch.object(EmailService, "fetch_detail", fetch_detail_mock),+ patch("asyncio.sleep", new=AsyncMock(return_value=None)),+ patch("services.status_broadcaster.get_status_broadcaster") as bcast,+ patch("services.events.dispatch.emit") as emit_mock,+ ):+ bcast.return_value.update_node_status = AsyncMock(return_value=None)+ emit_mock.return_value = None++ result = await harness.execute(+ "emailReceive",+ _base_creds_params(folder="INBOX", poll_interval=30),+ )++ harness.assert_envelope(result, success=True)+ assert emit_mock.call_count == 2, "both new messages must be dispatched"+ dispatched = {c.args[0].subject for c in emit_mock.call_args_list}+ assert dispatched == {"2", "3"}+ # Lowest UID first, so the envelope is deterministic.+ assert result["result"]["message_id"] == "2"++ async def test_transient_poll_error_does_not_end_the_run(self, harness):+ """One failing cycle must be retried on the next tick.++ Previously any exception inside the loop propagated to the outer+ handler and ended the interactive Run entirely.+ """+ from nodes.email._service import EmailService++ poll_ids_mock = AsyncMock(+ side_effect=[+ {"1"}, # baseline+ RuntimeError("temporary IMAP failure"), # cycle 1 blows up+ {"1", "2"}, # cycle 2 recovers+ ]+ )+ fetch_detail_mock = AsyncMock(+ return_value={"message_id": "2", "folder": "INBOX", "subject": "after recovery"}+ )++ with (+ patched_container(auth_api_keys=STORED_CREDS),+ patched_pricing(),+ patch.object(EmailService, "poll_ids", poll_ids_mock),+ patch.object(EmailService, "fetch_detail", fetch_detail_mock),+ patch("asyncio.sleep", new=AsyncMock(return_value=None)),+ patch("services.status_broadcaster.get_status_broadcaster") as bcast,+ patch("services.events.dispatch.emit"),+ ):+ bcast.return_value.update_node_status = AsyncMock(return_value=None)++ result = await harness.execute(+ "emailReceive",+ _base_creds_params(folder="INBOX"),+ )++ harness.assert_envelope(result, success=True)+ assert result["result"]["subject"] == "after recovery"+ assert poll_ids_mock.await_count == 3diff --git a/server/tests/nodes/test_email_service.py b/server/tests/nodes/test_email_service.pynew file mode 100644index 00000000..d0674af7--- /dev/null+++ b/server/tests/nodes/test_email_service.py@@ -0,0 +1,513 @@+"""Unit tests for the email plugin's service layer.++These exercise `EmailService` / `HimalayaService` directly, with no+NodeExecutor in the loop -- hence `unit` rather than the `node_contract`+marker carried by `test_email.py`.++Most of this file exists because of a specific class of bug: the email code+had a documented credential-precedence tier that was dead, a `custom` provider+whose ports could not be configured, and a config generator that interpolated+passwords into TOML unescaped -- and not one of those produced a failing test,+because every existing test supplied node params *and* stored keys together+and never inspected the generated config. The assertions below are written to+fail if any of those regress.+"""++from __future__ import annotations++import asyncio+import tomllib+from unittest.mock import AsyncMock, patch++import pytest++from tests.nodes._mocks import patched_container++pytestmark = pytest.mark.unit+++def _reset_singletons():+ from nodes.email import _himalaya as himalaya_service+ from nodes.email import _service as email_service++ email_service.EmailService._instance = None+ himalaya_service.HimalayaService._instance = None++[email protected](autouse=True)+def _clean_singletons():+ _reset_singletons()+ yield+ _reset_singletons()+++def _service():+ from nodes.email._service import get_email_service++ return get_email_service()+++def _himalaya():+ from nodes.email._himalaya import get_himalaya_service++ return get_himalaya_service()+++# The full set of keys `_generate_config` is allowed to emit. An injection+# that smuggles in an extra key shows up here as a set difference, which is+# the real guard -- a substring assertion would miss `backend.host` being+# overridden by a second occurrence.+_EXPECTED_CONFIG_KEYS = {+ "email",+ "display-name",+ "backend.type",+ "backend.host",+ "backend.port",+ "backend.encryption",+ "backend.login",+ "backend.auth.type",+ "backend.auth.raw",+ "message.send.backend.type",+ "message.send.backend.host",+ "message.send.backend.port",+ "message.send.backend.encryption",+ "message.send.backend.login",+ "message.send.backend.auth.type",+ "message.send.backend.auth.raw",+}+++def _flatten(data: dict, prefix: str = "") -> dict:+ """Flatten nested TOML tables back into dotted keys."""+ flat = {}+ for key, value in data.items():+ path = f"{prefix}{key}"+ if isinstance(value, dict):+ flat.update(_flatten(value, f"{path}."))+ else:+ flat[path] = value+ return flat+++def _render(**creds):+ """Render a config and return (parsed_account_table, raw_text)."""+ base = {+ "email": "[email protected]",+ "password": "sekret",+ "imap_host": "imap.example.com",+ "imap_port": 993,+ "imap_encryption": "tls",+ "smtp_host": "smtp.example.com",+ "smtp_port": 465,+ "smtp_encryption": "tls",+ }+ base.update(creds)+ svc = _himalaya()+ raw = svc._generate_config(svc._account_name(base), base)+ parsed = tomllib.loads(raw)+ account = next(iter(parsed["accounts"].values()))+ return _flatten(account), raw+++class TestGenerateConfigEscaping:+ """A `"` in any credential used to break the TOML; a `"` plus a newline+ injected arbitrary himalaya keys -- including a `backend.host` pointing+ somewhere else entirely."""++ @pytest.mark.parametrize(+ "password",+ [+ 'has"quote',+ "has\\backslash",+ 'quote"and\nnewline',+ 'evil"\nbackend.host = "attacker.example.com',+ "tab\there",+ "null\x00byte",+ ],+ )+ def test_password_survives_round_trip(self, password):+ flat, _ = _render(password=password)+ assert flat["backend.auth.raw"] == password+ assert flat["message.send.backend.auth.raw"] == password++ def test_injection_cannot_add_keys(self):+ flat, _ = _render(password='x"\nbackend.host = "attacker.example.com')+ assert set(flat) <= _EXPECTED_CONFIG_KEYS+ # The real host must survive unchanged.+ assert flat["backend.host"] == "imap.example.com"++ def test_host_injection_cannot_add_keys(self):+ flat, _ = _render(imap_host='imap.example.com"\nbackend.auth.raw = "leaked')+ assert set(flat) <= _EXPECTED_CONFIG_KEYS+ assert flat["backend.auth.raw"] == "sekret"++ def test_display_name_escaped(self):+ flat, _ = _render(display_name='Alice "The Boss"')+ assert flat["display-name"] == 'Alice "The Boss"'++ def test_display_name_omitted_when_blank(self):+ flat, _ = _render(display_name="")+ assert "display-name" not in flat+++class TestGenerateConfigPorts:+ """`resolve_credentials` always emits the port keys, sometimes as None.+ `dict.get(key, default)` finds the key present and returns None, which+ rendered `backend.port = None` -- unparseable, since ports are unquoted.++ This was masked only by the `custom` preset hardcoding 993/465. Blanking+ those (so self-hosted servers can set their own) removes the mask, which+ is why these cases matter.+ """++ @pytest.mark.parametrize(+ "value,expected",+ [+ (None, 993),+ ("", 993),+ ("993", 993),+ (1143, 1143),+ ("1143", 1143),+ (0, 993),+ (70000, 993),+ (-1, 993),+ ("abc", 993),+ (True, 1), # bool is an int subclass; 1 is a legal port+ ],+ )+ def test_imap_port_coercion(self, value, expected):+ flat, _ = _render(imap_port=value)+ assert flat["backend.port"] == expected+ assert isinstance(flat["backend.port"], int)++ def test_smtp_port_defaults_independently(self):+ flat, _ = _render(smtp_port=None)+ assert flat["message.send.backend.port"] == 465++ def test_none_port_still_parses(self):+ """The regression in one line: this raised a TOMLDecodeError before."""+ _, raw = _render(imap_port=None, smtp_port=None)+ tomllib.loads(raw)+++class TestGenerateConfigEncryption:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (None, "tls"),+ ("", "tls"),+ ("tls", "tls"),+ ("start-tls", "start-tls"),+ ("none", "none"),+ ("TLS", "tls"),+ (" StartTLS ".replace("StartTLS", "start-tls"), "start-tls"),+ ("garbage", "tls"),+ ('injected"\nx = "y', "tls"),+ ],+ )+ def test_encryption_allowlist(self, value, expected):+ flat, _ = _render(imap_encryption=value)+ assert flat["backend.encryption"] == expected+++class TestAccountName:+ @pytest.mark.parametrize(+ "email,expected",+ [+ ("[email protected]", "jane_doe_bot"),+ ("[email protected]", "alice"),+ ("o'[email protected]", "o_brien"),+ ("a!#$%&'*@example.com", "a_______"),+ ("[email protected]", "dash"),+ ("@example.com", "default"),+ ("", "default"),+ ],+ )+ def test_account_name_is_a_valid_bare_key(self, email, expected):+ svc = _himalaya()+ name = svc._account_name({"email": email})+ assert name == expected+ # Must be usable as a TOML bare key AND as an argv value that clap+ # will not read as a flag.+ assert not name.startswith("-")+ tomllib.loads(f"[accounts.{name}]\nemail = \"[email protected]\"")++ def test_missing_email_key(self):+ assert _himalaya()._account_name({}) == "default"+++class TestScrub:+ def test_password_redacted(self):+ from nodes.email._himalaya import _scrub++ text = "config error at /tmp/x.toml: backend.auth.raw = \"sekret\""+ assert "sekret" not in _scrub(text, "sekret")+ assert "[REDACTED]" in _scrub(text, "sekret")++ def test_empty_secret_is_noop(self):+ from nodes.email._himalaya import _scrub++ assert _scrub("unchanged", "") == "unchanged"+++class TestExecuteTimeout:+ """`asyncio.wait_for` cancels the wrapper, not the child. The subprocess+ stayed alive holding the temp config open, and the `finally` unlink then+ raised PermissionError on Windows -- masking the timeout entirely."""++ async def test_timeout_kills_child_and_removes_config(self, tmp_path):+ from pathlib import Path++ captured = {}++ class _HangingProc:+ pid = 4242+ returncode = None++ async def communicate(self, input=None):+ await asyncio.sleep(3600)++ async def wait(self):+ captured["waited"] = True+ return -9++ async def _fake_exec(*args, **kwargs):+ captured["config_path"] = Path(args[2])+ captured["config_existed"] = captured["config_path"].exists()+ return _HangingProc()++ svc = _himalaya()+ with (+ patch.object(+ type(svc), "ensure_binary", new=AsyncMock(return_value="/usr/bin/himalaya")+ ),+ patch.object(type(svc), "_timeout_seconds", return_value=0.05),+ patch("asyncio.create_subprocess_exec", new=_fake_exec),+ patch("services.events.cli.kill_tree") as kill_tree,+ ):+ with pytest.raises(RuntimeError, match="timed out"):+ await svc.execute("alice", {"email": "[email protected]", "password": "p"}, ["folder", "list"])++ assert captured["config_existed"] is True+ assert kill_tree.called, "the orphaned child must be tree-killed"+ assert kill_tree.call_args[0][0] == 4242+ assert captured.get("waited") is True, "the killed child must be reaped"+ assert not captured["config_path"].exists(), "temp config must be unlinked"+++class TestResolveCredentials:+ """The precedence tests that did not exist -- which is exactly why a whole+ documented tier could be dead code without a red test."""++ async def test_stored_keys_only(self):+ with patched_container(+ auth_api_keys={+ "email_provider": "gmail",+ "email_address": "[email protected]",+ "email_password": "sekret",+ }+ ):+ creds = await _service().resolve_credentials({})++ assert creds["email"] == "[email protected]"+ assert creds["password"] == "sekret"+ assert creds["imap_host"] == "imap.gmail.com"+ assert creds["smtp_host"] == "smtp.gmail.com"++ async def test_credential_params_are_ignored(self):+ """Node parameters must never carry credentials.++ They cannot be declared on Params without also handing the LLM a+ `password` argument, since `as_tool_schema` dumps the model schema+ wholesale with no field-exclusion hook.+ """+ with patched_container(+ auth_api_keys={+ "email_provider": "gmail",+ "email_address": "[email protected]",+ "email_password": "stored-pass",+ }+ ):+ creds = await _service().resolve_credentials(+ {+ "email": "[email protected]",+ "password": "attacker-pass",+ "imap_host": "imap.evil.com",+ "smtp_host": "smtp.evil.com",+ }+ )++ assert creds["email"] == "[email protected]"+ assert creds["password"] == "stored-pass"+ assert creds["imap_host"] == "imap.gmail.com"+ assert creds["smtp_host"] == "smtp.gmail.com"++ async def test_custom_provider_uses_stored_server_settings(self):+ """The whole point of blanking the `custom` preset: a self-hosted+ server on a non-standard port used to be unconfigurable, because the+ preset's 993/465/tls won the `or` chain."""+ with patched_container(+ auth_api_keys={+ "email_provider": "custom",+ "email_address": "[email protected]",+ "email_password": "sekret",+ "email_imap_host": "mail.self.host",+ "email_imap_port": "1143",+ "email_imap_encryption": "start-tls",+ "email_smtp_host": "mail.self.host",+ "email_smtp_port": "1587",+ "email_smtp_encryption": "start-tls",+ }+ ):+ creds = await _service().resolve_credentials({})++ assert creds["imap_host"] == "mail.self.host"+ assert creds["imap_port"] == 1143+ assert creds["imap_encryption"] == "start-tls"+ assert creds["smtp_port"] == 1587+ assert creds["smtp_encryption"] == "start-tls"++ async def test_custom_ports_reach_the_generated_config(self):+ """End-to-end for the A1/A5 ordering hazard."""+ with patched_container(+ auth_api_keys={+ "email_provider": "custom",+ "email_address": "[email protected]",+ "email_password": "sekret",+ "email_imap_host": "mail.self.host",+ "email_imap_port": "1143",+ "email_smtp_host": "mail.self.host",+ "email_smtp_port": "1587",+ }+ ):+ creds = await _service().resolve_credentials({})++ svc = _himalaya()+ flat = _flatten(+ tomllib.loads(svc._generate_config("alice", creds))["accounts"]["alice"]+ )+ assert flat["backend.port"] == 1143+ assert flat["message.send.backend.port"] == 1587+ # Encryption was never written by the panel; the code default applies.+ assert flat["backend.encryption"] == "tls"++ async def test_display_name_from_stored_key(self):+ with patched_container(+ auth_api_keys={+ "email_provider": "gmail",+ "email_address": "[email protected]",+ "email_password": "sekret",+ "email_display_name": "Alice Example",+ }+ ):+ creds = await _service().resolve_credentials({})+ assert creds["display_name"] == "Alice Example"++ async def test_missing_email_raises(self):+ with patched_container(auth_api_keys={"email_password": "sekret"}):+ with pytest.raises(ValueError, match="Email address not configured"):+ await _service().resolve_credentials({})++ async def test_missing_password_raises(self):+ with patched_container(auth_api_keys={"email_address": "[email protected]"}):+ with pytest.raises(ValueError, match="Email password not configured"):+ await _service().resolve_credentials({})++ @pytest.mark.parametrize(+ "provider", ["gmail", "outlook", "yahoo", "icloud", "protonmail", "fastmail"]+ )+ async def test_every_preset_resolves(self, provider):+ """Six of seven providers had no coverage at all."""+ import json+ from pathlib import Path++ from nodes.email._service import _CONFIG_PATH++ expected = json.loads(Path(_CONFIG_PATH).read_text())["providers"][provider]++ with patched_container(+ auth_api_keys={+ "email_provider": provider,+ "email_address": "[email protected]",+ "email_password": "sekret",+ }+ ):+ creds = await _service().resolve_credentials({})++ assert creds["imap_host"] == expected["imap_host"]+ assert creds["imap_port"] == expected["imap_port"]+ assert creds["smtp_host"] == expected["smtp_host"]+ assert creds["smtp_port"] == expected["smtp_port"]+++class TestResolvePollParams:+ """`emailReceive.execute()` passes raw params, so the Pydantic+ `ge=30, le=3600` guard never runs here."""++ @pytest.mark.parametrize(+ "value,expected",+ [+ (None, 60),+ ("", 60),+ ("abc", 60),+ (5, 30),+ (30, 30),+ (120, 120),+ ("120", 120),+ (99999, 3600),+ (-10, 30),+ ],+ )+ def test_interval_clamped(self, value, expected):+ assert _service().resolve_poll_params({"poll_interval": value})["interval"] == expected++ def test_absent_interval_uses_config_default(self):+ assert _service().resolve_poll_params({})["interval"] == 60++ def test_explicit_none_does_not_raise(self):+ """This raised `TypeError: '<' not supported between NoneType and int`."""+ assert _service().resolve_poll_params({"poll_interval": None, "folder": None})++ def test_folder_falls_back_when_none(self):+ assert _service().resolve_poll_params({"folder": None})["folder"] == "INBOX"++ def test_mark_as_read_coerced_to_bool(self):+ assert _service().resolve_poll_params({"mark_as_read": None})["mark_as_read"] is False+ assert _service().resolve_poll_params({"mark_as_read": "yes"})["mark_as_read"] is True+++class TestBuildFilter:+ def _filter(self, **params):+ from nodes.email._filters import build_filter++ return build_filter(params)++ def test_folder_match(self):+ assert self._filter(folder="INBOX")({"folder": "INBOX"}) is True+ assert self._filter(folder="INBOX")({"folder": "Archive"}) is False++ def test_all_is_a_wildcard(self):+ assert self._filter(folder="all")({"folder": "Whatever"}) is True++ def test_default_folder_when_absent(self):+ assert self._filter()({"folder": "INBOX"}) is True+ assert self._filter()({"folder": "Spam"}) is False++ def test_filter_query_matches_subject(self):+ f = self._filter(folder="INBOX", filter_query="invoice")+ assert f({"folder": "INBOX", "subject": "Your Invoice is ready"}) is True+ assert f({"folder": "INBOX", "subject": "Lunch?"}) is False++ def test_filter_query_is_case_insensitive_across_fields(self):+ f = self._filter(folder="INBOX", filter_query="ALICE")+ assert f({"folder": "INBOX", "from": "[email protected]"}) is True+ assert f({"folder": "INBOX", "body": "regards, Alice"}) is True++ def test_filter_query_tolerates_missing_fields(self):+ f = self._filter(folder="INBOX", filter_query="x")+ assert f({"folder": "INBOX"}) is False+ assert f({"folder": "INBOX", "subject": None, "body": "box"}) is True++ def test_blank_filter_query_is_inert(self):+ f = self._filter(folder="INBOX", filter_query=" ")+ assert f({"folder": "INBOX", "subject": "anything"}) is True